xmlutil.java.svn-base

来自「j2me mobile application for upload file 」· SVN-BASE 代码 · 共 416 行

SVN-BASE
416
字号
/**
 * 
 */
package org.celllife.clforms.xml;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Random;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.OutputConnection;
import javax.microedition.io.file.FileConnection;

import org.celllife.clforms.Constants;
import org.celllife.clforms.api.Binding;
import org.celllife.clforms.api.XFElement;
import org.celllife.clforms.api.XForm;
import org.kxml2.io.KXmlParser;
import org.kxml2.io.KXmlSerializer;
import org.kxml2.kdom.Document;
import org.kxml2.kdom.Element;
import org.kxml2.kdom.Node;
import org.xmlpull.v1.XmlPullParser;

import de.enough.polish.util.HashMap;
import de.enough.polish.util.Locale;
import de.enough.polish.util.StringTokenizer;

/**
 * @author Simon
 * 
 */
public class XMLUtil {

	/**
	 * Method to parse an XForm from and input stream.
	 * 
	 * @param inputStreamReader
	 * @return XForm
	 */
	public static XForm parseForm(InputStreamReader isr) {
		XForm xform = new XForm();
		// xform.setName(getRandomName());

		try {
			KXmlParser parser = new KXmlParser();
			parser.setInput(isr);
			parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
			Document doc = new Document();
			doc.parse(parser);

			Element html = doc.getRootElement();
			parseElement(xform, html, null);

		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return xform;
	}


	/**
	 * Recursive method to process XML.
	 * 
	 * @param xform
	 * @param element
	 * @param xelem
	 * @return
	 */
	private static XFElement parseElement(XForm xform, Element element,
			XFElement xelem) {
		String label = ""; //$NON-NLS-1$
		String value = ""; //$NON-NLS-1$

		int numOfEntries = element.getChildCount();
		for (int i = 0; i < numOfEntries; i++) {
			if (element.isText(i)) {
				// Text here are all insignificant white spaces.
				// We are only interested in children elements
			} else {
				Element child = element.getElement(i);
				String tagname = child.getName();
				if (tagname.equalsIgnoreCase("head")) { //$NON-NLS-1$
					parseElement(xform, child, null);
				} else if (tagname.equalsIgnoreCase("body")) { //$NON-NLS-1$
					parseElement(xform, child, null);
				} else if (tagname.equalsIgnoreCase("title")) { //$NON-NLS-1$
					xform.setName(child.getText(0).trim());
				} else if (tagname.equalsIgnoreCase("model")) { //$NON-NLS-1$
					parseElement(xform, child, null);
				} else if (tagname.equalsIgnoreCase("instance")) { //$NON-NLS-1$

					Document model = new Document();
					model.addChild(Node.ELEMENT, child.getElement(1));
					xform.setXmlModel(model);

				} else if (tagname.equalsIgnoreCase("bind")) { //$NON-NLS-1$

					Binding b = new Binding();
					b.setId(child.getAttributeValue("", "id")); //$NON-NLS-1$ //$NON-NLS-2$
					b.setNodeset(child.getAttributeValue("", "nodeset")); //$NON-NLS-1$ //$NON-NLS-2$
					b.setRelevancy(child.getAttributeValue("", "relevant")); //$NON-NLS-1$ //$NON-NLS-2$
					String type = child.getAttributeValue("", "type"); //$NON-NLS-1$ //$NON-NLS-2$
					if (type.indexOf(':') > 0)
						type = type.substring(type.indexOf(':') + 1);
					b.setType(type);
					xform.addBinding(b);

				} else if (tagname.equalsIgnoreCase("input")) { //$NON-NLS-1$

					XFElement xf = new XFElement();
					String ref = child.getAttributeValue(null, "ref"); //$NON-NLS-1$
					String bind = child.getAttributeValue(null, "bind"); //$NON-NLS-1$
					if (ref != null) {
						xf.setXpathBinding(ref);
						xf.setId(getLastToken(ref, '/'));
					} else if (bind != null) {
						Binding b = (Binding) xform.getBindings().get(bind);
						if (b != null) {
							xf.setXpathBinding(b.getNodeset());
							xf.setType(getTypeFromString(b.getType()));
							xf.setId(b.getId());
						}
					}

					xf = parseElement(xform, child, xf);
					xform.addElement(xf);

				} else if (tagname.equalsIgnoreCase("select1")) { //$NON-NLS-1$

					XFElement xf = new XFElement();
					String ref = child.getAttributeValue(null, "ref"); //$NON-NLS-1$
					String bind = child.getAttributeValue(null, "bind"); //$NON-NLS-1$
					if (ref != null) {
						xf.setXpathBinding(ref);
						xf.setId(getLastToken(ref, '/'));
					} else if (bind != null) {
						Binding b = (Binding) xform.getBindings().get(bind);
						if (b != null) {
							xf.setXpathBinding(b.getNodeset());
							xf.setId(b.getId());
						}
					}
					xf.setType(Constants.SELECT1);
					xf.setSelect(new HashMap());
					xf = parseElement(xform, child, xf);
					xform.addElement(xf);

				} else if (tagname.equalsIgnoreCase("select")) { //$NON-NLS-1$

					XFElement xf = new XFElement();
					String ref = child.getAttributeValue(null, "ref"); //$NON-NLS-1$
					String bind = child.getAttributeValue(null, "bind"); //$NON-NLS-1$
					if (ref != null) {
						xf.setXpathBinding(ref);
						xf.setId(getLastToken(ref, '/'));
					} else if (bind != null) {
						Binding b = (Binding) xform.getBindings().get(bind);
						if (b != null) {
							xf.setXpathBinding(b.getNodeset());
							xf.setId(b.getId());
						}
					}
					xf.setType(Constants.SELECT);
					xf.setSelect(new HashMap());
					xf = parseElement(xform, child, xf);
					xform.addElement(xf);

				} else if (tagname.equalsIgnoreCase("label")) { //$NON-NLS-1$
					label = child.getText(0).trim();
				} else if (tagname.equalsIgnoreCase("hint")) { //$NON-NLS-1$
					xelem.setHintText(child.getText(0).trim());
				} else if (tagname.equalsIgnoreCase("item")) { //$NON-NLS-1$
					parseElement(xform, child, xelem);
				} else if (tagname.equalsIgnoreCase("value")) { //$NON-NLS-1$
					value = child.getText(0).trim();
				}
			}
		}

		if (!label.equals("") && !value.equals("")) { //$NON-NLS-1$ //$NON-NLS-2$
			if (xelem.getSelect() != null) {
				xelem.getSelect().put(label, value);
			}
		} else if (!label.equals("")) { //$NON-NLS-1$
			xelem.setLabel(label);
		}
		return xelem;
	}

	private static String getLastToken(String ref, char c) {
		StringTokenizer tok = new StringTokenizer(ref, c);
		String last = ""; //$NON-NLS-1$
		while (tok.hasMoreTokens())
			last = tok.nextToken();
		return last;
	}

	/**
	 * @param type
	 * @return
	 */
	private static int getTypeFromString(String type) {
		int index = type.indexOf(':');
		if (index > 0)
			type = type.substring(index + 1);

		if (type.equalsIgnoreCase("int")) //$NON-NLS-1$
			return Constants.INT;
		else if (type.equalsIgnoreCase("date")) //$NON-NLS-1$
			return Constants.DATE;
		else if (type.equalsIgnoreCase("boolean")) //$NON-NLS-1$
			return Constants.BOOLEAN;
		else
			return Constants.STRING;
	}

	/**
	 * Opens a file and returns an InputStreamReader to it
	 * 
	 * @param file
	 * @return
	 */
	public static InputStreamReader getReader(String file) {

		InputStreamReader isr = null;
		try {
			FileConnection fc = (FileConnection) Connector.open(file);

			if (!fc.exists()) {
				throw new IOException(Locale.get("error.file"));
			} else {
				InputStream fis = fc.openInputStream();

				isr = new InputStreamReader(fis);
				/*
				 * fis.close(); fc.close();
				 */

			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return isr;
	}

	/**
	 * Writes string parameter to a file
	 * 
	 * @param file
	 * @param writableString
	 */
	public static void writeStringToFile(String file, String writableString) {

		try {
			// "file://c:/myfile.txt;append=true"
			OutputConnection connection = (OutputConnection) Connector.open(
					file, Connector.WRITE);
			// TODO do something appropriate if the file does not exist
			OutputStream os = connection.openOutputStream();
			os.write(writableString.getBytes());
			os.flush();
			os.close();
		} catch (IOException e) {
			// TODO handle exception appropriately
			System.out.println(Locale.get("error.file.write")); //$NON-NLS-1$
			e.printStackTrace();
		}
	}

	/**
	 * Writes XML Document parameter to a file
	 * 
	 * @param file
	 * @param xml
	 */
	public static void writeXMLToFile(String file, Document xml)
			throws IOException {
		KXmlSerializer serializer = new KXmlSerializer();

		OutputConnection connection = (OutputConnection) Connector.open(file,
				Connector.WRITE);
		// TODO do something appropriate if the file does not exist
		OutputStream os = connection.openOutputStream();

		serializer.setOutput(os, null);
		xml.write(serializer);
		serializer.flush();

		os.close();
		connection.close();
	}

	public static String readTextFile(String url) throws IOException {
		FileConnection fc = (FileConnection) Connector.open(url);

		if (!fc.exists()) {
			throw new IOException("File does not exists");
		}

		InputStream fis = fc.openInputStream();
		StringBuffer content = new StringBuffer();
		int ch;
		while ((ch = fis.read()) != -1) {
			
			content.append((char) ch);
		}


		fis.close();
		fc.close();

		return content.toString();
	}

	public static void printModel(Document doc) throws IOException {
		KXmlSerializer serializer = new KXmlSerializer();
		serializer.setOutput(System.out, null);
		doc.write(serializer);
		serializer.flush();
	}
	
	public static String sendHttpGet(String url) {
		HttpConnection hcon = null;
		DataInputStream dis = null;
		StringBuffer responseMessage = new StringBuffer();

		try {
			// a standard HttpConnection with READ access
			hcon = (HttpConnection) Connector.open(url);

			// obtain a DataInputStream from the HttpConnection
			dis = new DataInputStream(hcon.openInputStream());

			// retrieve the response from the server
			int ch;
			while ((ch = dis.read()) != -1) {
				responseMessage.append((char) ch);
			}
		} catch (Exception e) {
			e.printStackTrace();
			responseMessage.append("ERROR");
		} finally {
			try {
				if (hcon != null)
					hcon.close();
				if (dis != null)
					dis.close();
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
		}
		return responseMessage.toString();
	}

	public static String sendHttpPost(String url) {
		HttpConnection hcon = null;
		DataInputStream dis = null;
		DataOutputStream dos = null;
		StringBuffer responseMessage = new StringBuffer();
		// the request body
		String requeststring = "uname=simon" +
				"&pw=123abc" +
				"&redirect=%2FOPENMRSDTHF" +
				"&refererURL=http%3A%2F%2Ftambo.cell-life.org%3A8180%2FOPENMRSDTHF%2Flogin.htm";

		try {
			// an HttpConnection with both read and write access
			hcon = (HttpConnection) Connector.open(url, Connector.READ_WRITE);

			// set the request method to POST
			hcon.setRequestMethod(HttpConnection.POST);
			
			// obtain DataOutputStream for sending the request string
			dos = hcon.openDataOutputStream();
			byte[] request_body = requeststring.getBytes();

			// send request string to server
			for (int i = 0; i < request_body.length; i++) {
				dos.writeByte(request_body[i]);
			}// end for( int i = 0; i < request_body.length; i++ )

			// obtain DataInputStream for receiving server response
			dis = new DataInputStream(hcon.openInputStream());

			// retrieve the response from server
			int ch;
			while ((ch = dis.read()) != -1) {
				responseMessage.append((char) ch);
			}// end while( ( ch = dis.read() ) != -1 ) {
		} catch (Exception e) {
			e.printStackTrace();
			responseMessage.append("ERROR");
		} finally {
			// free up i/o streams and http connection
			try {
				if (hcon != null)
					hcon.close();
				if (dis != null)
					dis.close();
				if (dos != null)
					dos.close();
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}// end try/catch
		}// end try/catch/finally
		return responseMessage.toString();
	}// end sendHttpPost( String )
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?