rendered paste body/** * <p> * File XMLUtil.java * </p> * <p> * Package fr.interfacesi.gpm.util * </p> * <p> * Created on May 8, 2006 * </p> * <p> * @author AdrianS * </p> */package fr.interfacesi.gpm.util;import java.util.List;import java.util.Map;import java.util.HashMap;import java.io.ByteArrayInputStream;import java.io.File;import java.io.FileInputStream;import java.io.StringWriter;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.xml.serialize.OutputFormat;import org.apache.xml.serialize.XMLSerializer;import org.apache.xpath.XPathAPI;import org.w3c.dom.Attr;import org.w3c.dom.Document;import org.w3c.dom.NamedNodeMap;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import org.xml.sax.InputSource;import org.iso_relax.verifier.*;/** * <p> * This class implements xml files tasks * </p> * <p> * Created on May 8, 2006 * </p> * <p> * @author AdrianS * </p> * <p> * @version $Revision: 1.1 $ * </p> */public class XMLUtil { /** * logger object */ static Log logger = LogFactory.getLog(XMLUtil.class); /** * Initializes a DOM xml tree from a path * @param xmlPath * @return an instance to a DOM Document */ public static org.w3c.dom.Document initXMLDoc(String xmlPath) { Document doc = null; GPMUtil.writeLog("XMLUtil.initXMLDoc",Messages.getString("templatesGui.log.message63"),null); try { File file = new File(xmlPath); if (!file.exists()) return null; FileInputStream fileInputStream = new FileInputStream(file); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource inputSource = new InputSource(fileInputStream); doc = builder.parse(inputSource); } catch(Exception ex) { GPMUtil.writeLog("XMLUtil.initXMLDoc","",ex); logger.error("initXMLDoc: ", ex); } return doc; } /** * Initializes a DOM xml tree from a buffer * @param xmlBuff * @return an instance to a DOM Document */ public static org.w3c.dom.Document initXMLDoc(byte[] xmlBuff) { Document doc = null; GPMUtil.writeLog("XMLUtil.initXMLDoc",Messages.getString("templatesGui.log.message64"),null); try { ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(xmlBuff); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource inputSource = new InputSource(byteArrayInputStream); doc = builder.parse(inputSource); } catch(Exception ex) { GPMUtil.writeLog("XMLUtil.initXMLDoc","",ex); logger.error("initXMLDoc: ", ex); } return doc; } /** * Verify a DOM document with a RelaxNG type schema * @param doc * @param rngFile * @return xml file has been validated or not */ public static boolean validateXmlWithNG(Document doc, String rngFile) { boolean ret = true; GPMUtil.writeLog("XMLUtil.validateXmlWithNG",Messages.getString("templatesGui.log.message65"),null); //no .rng file, assume xml file is valid if (!GPMUtil.existsFile(rngFile)) return ret; try { // setup JARV and compile a schema. VerifierFactory factory = new com.sun.msv.verifier.jarv.TheFactoryImpl(); Verifier verifier = factory.compileSchema(rngFile).newVerifier(); ret = verifier.verify(doc); } catch(Exception ex) { GPMUtil.writeLog("XMLUtil.validateXmlWithNG","",ex); ret = false; logger.info(ex); } return ret; } /** * XPATH-based function to search an xml node inside an xml tree * @param xpathFilter * XPATH based query string * @return Node */ public static Node findNode(Node node, String xpathFilter) { Node nodeRet = null; try { nodeRet = XPathAPI.selectSingleNode(node,xpathFilter); } catch (Exception ex) { logger.error("initXMLDoc: ", ex); } return nodeRet; } /** * XPATH-based function to search xml nodes inside an xml tree * @param xpathFilter * XPATH based query string * @return NodeList */ public static NodeList findNodes(Node node, String xpathFilter) { NodeList list = null; try { list = XPathAPI.selectNodeList(node,xpathFilter); } catch (Exception ex) { logger.error("findNodes: ", ex); } return list; } /** * * @param doc * @param node * @param param */ public static void editNode(Document doc,Node node,List param) { String nodeType = (String)param.get(0); String nodeText = (String)param.get(1); Attr attr = null; String attrName = null; String attrValue = null; try { for (int i = 2;i<param.size();i++) { attrName = (String)param.get(i); attrValue = (String)param.get(i+1); i++; attr = doc.createAttribute(attrName); attr.setValue(attrValue); node.getAttributes().setNamedItem(attr); } if (nodeText.length()>0) { Node newTextNode = doc.createTextNode(nodeText); Node oldTextNode = null; NodeList list = node.getChildNodes(); for (int j=0;j<list.getLength();j++) { oldTextNode = list.item(j); if (oldTextNode.getNodeType()==Node.TEXT_NODE) break; } node.replaceChild(newTextNode,oldTextNode); } } catch(Exception ex) { logger.error("editNode : ", ex); } } /** * * @param doc * @param node * @param param */ public static void addNode(Document doc,Node node,List param) { String nodeType = (String)param.get(0); String nodeText = (String)param.get(1); Node child = null; //function addNode also acts as a nodes edition function //the condition is that nodeType be 0-lengthed //so nodeType is 0-lenghted, addNode make editions, not additions if (nodeType.length()>0) child = doc.createElement(nodeType); else child = node; Attr attr = null; String attrName = null; String attrValue = null; boolean found = false; try { for (int i = 2;i<param.size();i++) { attrName = (String)param.get(i); attrValue = (String)param.get(i+1); i++; attr = doc.createAttribute(attrName); attr.setValue(attrValue); child.getAttributes().setNamedItem(attr); } if (nodeType.length()>0) { if (nodeText.length()>0) { Node textNode = doc.createTextNode(nodeText); child.appendChild(textNode); } node.appendChild(child); } else { if (nodeText.length()>0) { Node newTextNode = doc.createTextNode(nodeText); Node oldTextNode = null; NodeList list = node.getChildNodes(); for (int j=0;j<list.getLength();j++) { oldTextNode = list.item(j); if (oldTextNode.getNodeType()==Node.TEXT_NODE) { found = true; break; } } if (found) node.replaceChild(newTextNode,oldTextNode); else node.appendChild(newTextNode); } } } catch(Exception ex) { logger.error("addNode : ", ex); } } /** * * @param doc * @param filePath * @param encoding */ public static void flushXMLDoc(Document doc, String filePath, String encoding) { try { //use specific Xerces class to write DOM-data to a file: OutputFormat format = new OutputFormat(doc); format.setEncoding(encoding); java.io.FileWriter fw = new java.io.FileWriter(filePath); XMLSerializer serializer = new XMLSerializer(fw,format); //serializer.setOutputCharStream(fw); serializer.serialize(doc); fw.close(); } catch(Exception ex) { logger.error("flushXMLDoc : ", ex); } } public static void flushXMLDoc(Document doc, String filePath) { XMLUtil.flushXMLDoc(doc,filePath,GPMUtil.XML_ENCODING_ISO_8859_1); } /** * * @param doc * @return treated document */ public static Document treatSpecialChars(Document doc) { Node parent = doc.getDocumentElement(); parent = treatSpecialChars(parent); return doc; } /** * * @param node * @return treated node */ public static Node treatSpecialChars(Node node) { Node child = null; NamedNodeMap map = null; Node attr = null; String value = null; NodeList list = node.getChildNodes(); for (int i=0;i<list.getLength();i++) { child = list.item(i); map = child.getAttributes(); if (map!=null) { for (int j=0;j<map.getLength();j++) { attr = map.item(j); value = attr.getNodeValue(); value = checkForBookmarkInvalidChars(value); attr.setNodeValue(value); } } if (child.hasAttributes()) treatSpecialChars(child); } return node; } /** * * @param s * @return treated string */ public static String checkForBookmarkInvalidChars(String s) { char[] carr = s.toCharArray(); char c; for (int i=0;i<carr.length;i++) { c = carr[i]; if (!Character.isDigit(c) && !Character.isLetter(c)) carr[i] = '_'; } return new String(carr); } /** * * @param path * @param names * @param id * @param attrName * @return dom document interface of a template control xml */ public static Document findXmlFilesByAttr(String path,List names,String id,String nodeType, String attrName) { String name = null; Document doc = null; Node n = null; Node attr = null; NamedNodeMap map = null; String nodeId = null; for (int i=0;i<names.size();i++) { name = (String)names.get(i); doc = XMLUtil.initXMLDoc(path + File.separator + name); n = XMLUtil.findNode(doc,nodeType); map = n.getAttributes(); attr = map.getNamedItem(attrName); if (attr!=null) { nodeId = attr.getNodeValue(); if (nodeId.equals(id)) break; } } return doc; } /** * Find an xml file (template control) whose file name starts with a specified id * @param path * @param names * @param identif * @return dom document interface of a template control xml */ public static Document findXmlFileStartingWithId(String path,List names,String identif) { String name = null; Document doc = null; for (int i=0;i<names.size();i++) { name = (String)names.get(i); if (name.indexOf(identif)>-1) { doc = XMLUtil.initXMLDoc(path + File.separator + name); break; } } return doc; } /** * * @param doc * @return map with template control info */ public static Map getTemplateControlInfo(Document doc) { Node n = null; Node child = null; Node child1 = null; String name = null; String value = null; Map tplMap = new HashMap(); n = XMLUtil.findNode(doc,GPMUtil.XPATH_TEMPLATE); if(null == n) { return null; } //first its attributes, then the child nodes for (int j=0;j<n.getAttributes().getLength();j++) { name = n.getAttributes().item(j).getNodeName(); value = n.getAttributes().item(j).getNodeValue(); tplMap.put((String)name,(String)value); } for (int j=0;j<n.getChildNodes().getLength();j++) { child = n.getChildNodes().item(j); if (child.getNodeType()==Node.ELEMENT_NODE) { name = child.getNodeName(); child1 = child.getFirstChild(); value = (child1!=null) ? child1.getNodeValue() : ""; tplMap.put((String)name,(String)value); } } return tplMap; } /** * Returns the value of attribute name of "bookmarks" type node from * a Bookmarks.xml * @param doc * @return value of "name" attribute */ public static String getBookmarksNameById(Document doc) { String name = null; String value = null; Node node = XMLUtil.findNode(doc,GPMUtil.XPATH_BOOKMARKS); for (int j=0;j<node.getAttributes().getLength();j++) { name = node.getAttributes().item(j).getNodeName(); value = node.getAttributes().item(j).getNodeValue(); if (name.equalsIgnoreCase(GPMUtil.XML_NAME)) break; } return value; } /** * Converts a DOM interface document to an array of bytes * @param doc * @return */ public static byte[] convertDOMToBytes(Document doc) { try { OutputFormat format = new OutputFormat(doc, "ISO-8859-1", true); format.setStandalone(true); format.setIndenting(true); StringWriter stringOut = new StringWriter(); XMLSerializer serial = new XMLSerializer(stringOut,format); serial.asDOMSerializer(); serial.serialize(doc); return stringOut.getBuffer().toString().getBytes(); } catch(Exception ex) { logger.error("convertDOMToBytes: ", ex); } return null; }}