package com.nifty.cloud.ncs.service.parser;

import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.nifty.cloud.ncs.NiftyCloudClientException;
import com.nifty.cloud.ncs.NiftyCloudResponse;
import com.nifty.cloud.ncs.http.HttpResponse;
import com.nifty.cloud.ncs.service.CompleteMultipartUploadResult;

/**
 * CompleteMultipartUploadの応答XML解析用クラスです。
 *
 */
public class CompleteMultipartUploadParser extends AbstractStorageResponseParser<CompleteMultipartUploadResult>
{
	public CompleteMultipartUploadParser() throws NiftyCloudClientException
	{
		super();
	}

	@Override
	public NiftyCloudResponse<CompleteMultipartUploadResult> parse(HttpResponse response) throws Exception
	{
		NiftyCloudResponse<CompleteMultipartUploadResult> ncsResponse = super.parseMetaData(response);
		CompleteMultipartUploadUnmarshaller unmarshaller = new CompleteMultipartUploadUnmarshaller();
		parseXml(unmarshaller, response.getContent());
		CompleteMultipartUploadResult result = unmarshaller.getResult();

		ncsResponse.setResult(result);

		return (ncsResponse);
	}

	public class CompleteMultipartUploadUnmarshaller extends DefaultHandler
	{
		private CompleteMultipartUploadResult result;
		private StringBuffer text = null;

		public CompleteMultipartUploadUnmarshaller() {
			super();
			result = new CompleteMultipartUploadResult();
			text = new StringBuffer();
		}

		public CompleteMultipartUploadResult getResult() {
			return result;
		}

		@Override
		public void endElement(String uri, String localName, String qName)
				throws SAXException {
			if (localName.equals("Bucket"))
			{
				result.setBucketName(text.toString());
			} else if (localName.equals("Key"))
			{
				result.setObjectName(text.toString());
			} else if (localName.equals("Location"))
			{
				result.setLocation(text.toString());
			} else if (localName.equals("ETag"))
			{
				result.setETag(text.toString().replace("\"", ""));
			}
			text = new StringBuffer();
		}

		@Override
		public void characters(char[] ch, int start, int length)
				throws SAXException {
			text.append(ch, start, length);
		}
	}
}
