
nyla.solutions.global.xml.DOM4J Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of nyla.solutions.global Show documentation
Show all versions of nyla.solutions.global Show documentation
Nyla Solutions Global Java API provides support for basic application
utilities (application configuration, data encryption, debugger and text
processing).
The newest version!
package nyla.solutions.global.xml;
/**
* XML is XML utility class. This class can be used to convert any
* complex or JavaBean object to an XML string, see XML.toXML(object) and
* XML.populate(...) method.
*
* @author Gregory Green
* @version 2.0
*/
import nyla.solutions.global.exception.RequiredException;
import nyla.solutions.global.exception.SystemException;
import nyla.solutions.global.io.IO;
import nyla.solutions.global.util.*;
import nyla.solutions.global.xml.xstream.XStreamInterpreter;
import org.xml.sax.*;
import org.dom4j.*;
import org.dom4j.io.*;
import nyla.solutions.global.util.Text;
import java.lang.reflect.Array;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.*;
import org.apache.commons.beanutils.PropertyUtils;
public class DOM4J extends XML
{
/**
* Construct from w3c document
* @param document
*/
public DOM4J(org.w3c.dom.Document document)
throws Exception
{
this(DOM4J.toXML(document));
}// --------------------------------------------
/**
*
* @param aXml
* input XML
* @throws Exception
*/
public DOM4J(String aXml) throws Exception
{
if (aXml == null || aXml.length() == 0)
throw new RequiredException("xml");
this.xml = aXml;
try
{
// Set an ErrorHandler before parsing
//xmlReader.setErrorHandler(new CommandErrorHandler(System.err));
// Tell the XMLReader to parse the XML document
InputSource is = new InputSource(new StringReader(aXml));
org.dom4j.io.SAXReader reader = new SAXReader();
document = reader.read(is);
}
catch (Exception e)
{
throw new SystemException(" XML="+aXml+" ERROR:"+Debugger.stackTrace(e));
}
}//-------------------------------------
public static String getText(org.w3c.dom.Node node)
{
String value = node.getNodeValue();
if(value != null && value.length() > 0)
return value;
org.w3c.dom.Node firstChild = node.getFirstChild();
value = firstChild.getNodeValue();
if(value != null && value.length() > 0)
return value;
return ""; //no value found
}// --------------------------------------------
/**
*
* @param xml the xml to convert
* @return the created InputSource
*/
public static InputSource toInputSource(URL url)
{
try
{
return new InputSource(url.openStream());
}
catch (Exception e)
{
throw new SystemException(Debugger.stackTrace(e));
}
}// --------------------------------------------
public static InputSource toInputSource(InputStream inputStream)
{
try
{
return new InputSource(inputStream);
}
catch (Exception e)
{
throw new SystemException(Debugger.stackTrace(e));
}
}// --------------------------------------------
/**
*
* @return XStreamInterpreter
*/
public static XMLInterpreter getInterpreter()
{
return new XStreamInterpreter();
}// --------------------------------------------
public static String toElementText(String aElementName, String aText)
{
aElementName = DOM4J.escapeElementEntities(aElementName);
StringBuffer element = new StringBuffer("<").append(aElementName).append(">");
element.append(aText);
element.append("").append(aElementName).append(">");
return element.toString();
}// --------------------------------------------
/**
*
* @param xml
* @return the striped the XML heade
*/
public static String stripHeader(String xml)
{
if (xml == null)
throw new RequiredException("xml");
//remove header
int start = xml.indexOf("
int end = xml.indexOf("?>", start);
if(end < start) //does not contain end
return xml;
return xml.substring(end+"?>".length()).trim();
}//--------------------------------------------
/***
* Return XML version of a result set
* @param aResultSet the result set
* @return the XML version
* @throws java.sql.SQLException
* @throws Exception
*/
public static String toXML(ResultSet aResultSet)
throws java.sql.SQLException, Exception
{
ResultSetMetaData metaData = aResultSet.getMetaData();
Map columnNames = new Hashtable();
Map columnClassNames = new Hashtable();
Map columnTypeNames = new Hashtable();
Integer columnNumber = null;
for(int i=1;i <=metaData.getColumnCount();i++)
{
columnNumber = Integer.valueOf(i);
columnNames.put(columnNumber,metaData.getColumnLabel(i));
columnClassNames.put(columnNumber,metaData.getColumnClassName(i));
columnTypeNames.put(columnNumber,metaData.getColumnTypeName(i));
//columnDisplaySizes.put(columnNumber,new Integer(metaData.getColumnDisplaySize(i)));
}
org.dom4j.DocumentFactory factory = org.dom4j.DocumentFactory.getInstance();
org.dom4j.Element root = factory.createElement("ResultSet");
org.dom4j.Element child = null;
String value =null;
org.dom4j.Element rowElement = null;
while(aResultSet.next())
{
rowElement = factory.createElement("Row");
for(Map.Entry entry : columnNames.entrySet())
{
columnNumber = entry.getKey();
value = String.valueOf(aResultSet.getObject(columnNumber.intValue()));
child = factory.createElement(entry.getValue());
child.add(factory.createAttribute(child,"type",
(String)columnTypeNames.get(columnNumber)));
child.addText(value);
rowElement.add(child);
}
root.add(rowElement);
}
return convertToXML(root);
}//--------------------------------------
/**
* Escape all special characters in the input string
*
* @param str
* string to escape
* @return String with all special characters encoded
*/
public static String escapeAttributeEntities(String str) {
if (str == null) {
return "";
}
StringBuffer buffer = null;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
String entity;
switch (ch) {
case 60: // '<'
entity = "<";
break;
case 62: // '>'
entity = ">";
break;
case 34: // '"'
entity = """;
break;
case 38: // '&'
entity = "&";
break;
default:
entity = null;
break;
}
if (buffer == null) {
if (entity != null) {
buffer = new StringBuffer(str.length() + 20);
buffer.append(str.substring(0, i));
buffer.append(entity);
}
} else if (entity == null)
buffer.append(ch);
else
buffer.append(entity);
}
return buffer != null ? buffer.toString() : str;
}//--------------------------------------------------------
public static String escapeElementEntities(String str) {
if (str == null) {
return "";
}
StringBuffer buffer = null;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
String entity;
switch (ch) {
case 60: // '<'
entity = "<";
break;
case 62: // '>'
entity = ">";
break;
case 38: // '&'
entity = "&";
break;
default:
entity = null;
break;
}
if (buffer == null) {
if (entity != null) {
buffer = new StringBuffer(str.length() + 20);
buffer.append(str.substring(0, i));
buffer.append(entity);
}
} else if (entity == null)
buffer.append(ch);
else
buffer.append(entity);
}
return buffer != null ? buffer.toString() : str;
}//-------------------------------------------------------
/**
*
* @param aXpath
* the XPATH element i.e. "/root/element@attribName"
* @return the node that matches the XPATH
* @throws Exception
* when an internal errors
*/
public org.dom4j.Node retrieveNode(String aXpath) throws Exception {
return this.document.selectSingleNode(aXpath);
}//--------------------------------------
/**
* The root name should exist in the Map with key "class"
*
* @param map
* return root class name from the map
* @return
*/
private static String getRootName(Map map) {
String root = String.valueOf(map.get("class"));
int lastIndex = root.lastIndexOf(".");
if (lastIndex < 0)
return root;
else
return root.substring(lastIndex + 1, root.length());
}
//-----------------------------------------------------------
/**
* lightweight XML parse method for retrieving XML elements
*
* @param aXml
* the XML document
* @param aXpath
* the full XPATH expression (attribs not supported)
* @return the element from the aXml document
*/
public String retrieveElementValue(String aXpath) throws Exception {
//treeWalk(document);
Object object = document.selectObject(aXpath);
if (object instanceof Node) {
Node n = (Node) object;
return n.getStringValue().trim();
}
if (object == null)
return "";
else
return object.toString();
}//-------------------------------------------------------------
/**
* Print XML content to standard out
*
*/
public void dump() {
DOM4J.treeWalk(this.document);
}//------------------------------------------------
/**
* Print XML content to standard out
*
*/
public static void treeWalk(org.dom4j.Document document) {
treeWalk(document.getRootElement());
}//-------------------------------------------------------
/**
* Print XML content to standard out
*
*/
@SuppressWarnings("unchecked")
public static void treeWalk(org.dom4j.Element element) {
System.out.println(element.getPath());
//Print attributes
org.dom4j.Attribute attribute = null;
for (Iterator i = element.attributeIterator(); i.hasNext();) {
attribute = (org.dom4j.Attribute) i.next();
System.out.print(attribute.getPath());
}
// Print others
for (int i = 0, size = element.nodeCount(); i < size; i++) {
org.dom4j.Node node = element.node(i);
if (node instanceof org.dom4j.Element) {
treeWalk((org.dom4j.Element) node);
} else {
//System.out.print(node.getPath());
}
}
}//-------------------------------------------------------
/**
* validation the XML against a MAP of XPATH elements/Regular expressions
* pairs
*
* @throws Exception
* when an XML parsing XML occurs
*/
public void validate(Map
© 2015 - 2025 Weber Informatics LLC | Privacy Policy