package org.javarosa.services.transport;

import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;

import org.javarosa.core.log.FatalException;
import org.kxml2.io.KXmlParser;
import org.kxml2.kdom.Document;
import org.xmlpull.v1.XmlPullParser;

/**
 * utility class for extracting an xml document out of a string or bytestream, typically used for
 * processing xml payloads sent in response to server requests
 * 
 * @author Drew Roos
 *
 */
public class CommUtil {

	public static Document getXMLResponse (byte[] response) {
		try {
			return getXMLResponse(new InputStreamReader(new ByteArrayInputStream(response), "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			throw new FatalException("can't happen; utf8 must be supported", e);
		}
	}

	public static Document getXMLResponse (Reader reader) {
    	Document doc = new Document();
		
    	try{
    		KXmlParser parser = new KXmlParser();
    		parser.setInput(reader);
    		parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
		                       
    		doc.parse(parser);
    	} catch (Exception e) {
    		System.err.println("couldn't process response payload from server!!");
    		doc = null;
    	}
			
		try {
			doc.getRootElement();
		} catch (RuntimeException re) {
			doc = null; //work around kxml bug where it should have failed to parse xml (doc == null)
						//but instead returned an empty doc that throws an exception when you try to
						//get its root element
		}
    	
    	return doc;
    }
	
}

@@ -563,18 +563,19 @@
 Util %7B%0D%0A
+%09
 %0D%0A
-
 %09public 
@@ -626,26 +626,16 @@
 nse) %7B%0D%0A
-%09%09try %7B%0D%0A%09
 %09%09return
@@ -654,200 +654,29 @@
 nse(
-new InputStreamReader(new ByteArrayInputStream(response), %22UTF-8%22));%0D%0A%09%09%7D catch (UnsupportedEncodingException e) %7B%0D%0A%09%09%09throw new FatalException(%22can't happen; utf8 must be supported%22, e);%0D%0A%09%09%7D
+getReader(response));
 %0D%0A%09%7D
@@ -1451,11 +1451,501 @@
   %7D%0D%0A%09%0D%0A
+%09public static String getString (byte%5B%5D data) %7B%0D%0A%09%09try %7B%0D%0A%09%09%09return new String(data, %22UTF-8%22);%0D%0A%09%09%7D catch (UnsupportedEncodingException e) %7B%0D%0A%09%09%09throw new FatalException(%22can't happen; utf8 must be supported%22, e);%0D%0A%09%09%7D%0D%0A%09%7D%0D%0A%0D%0A%09public static Reader getReader (byte%5B%5D data) %7B%0D%0A%09%09try %7B%0D%0A%09%09%09return new InputStreamReader(new ByteArrayInputStream(data), %22UTF-8%22);%0D%0A%09%09%7D catch (UnsupportedEncodingException e) %7B%0D%0A%09%09%09throw new FatalException(%22can't happen; utf8 must be supported%22, e);%0D%0A%09%09%7D%0D%0A%09%7D%0D%0A%09%0D%0A
 %7D%0D%0A

add helper functions for reading bytestreams