List of usage examples for org.w3c.dom Element appendChild
public Node appendChild(Node newChild) throws DOMException;
newChild
to the end of the list of children of this node. From source file:org.openmrs.module.atomfeed.AtomFeedUtil.java
/** * Updates content of atom feed header file by re-creating new xml header block and writing it * into given file. Actually, if given atom feed header file does not exists, it creates it. * Otherwise, it changes values of "updated", "versionId" and "entriesSize" elements within * header xml tree./*from ww w . j ava 2 s . c om*/ * * @param atomfeedheader the file target to be updated * @param entriesSize the size in bytes of entries payload, which is related to given feed * header */ private static void updateFeedFileHeader(File atomfeedheader, long entriesSize) { try { // We need a Document DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); Document doc = docBuilder.newDocument(); // ////////////////////// // Creating the XML tree // create the root element and add it to the document Element root = doc.createElement("feed"); root.setAttribute("xmlns", "http://www.w3.org/2005/Atom"); doc.appendChild(root); // create title element, add its text, and add to root Element title = doc.createElement("title"); Text titleText = doc.createTextNode(AtomFeedConstants.ATOM_FEED_TITLE); title.appendChild(titleText); root.appendChild(title); // create title element, add its attrs, and add to root Element selflink = doc.createElement("link"); selflink.setAttribute("href", AtomFeedUtil.getFeedUrl()); selflink.setAttribute("rel", "self"); root.appendChild(selflink); Element serverlink = doc.createElement("link"); serverlink.setAttribute("href", getWebServiceUrl()); root.appendChild(serverlink); // create title element, add its text, and add to root Element id = doc.createElement("id"); Text idText = doc.createTextNode(AtomFeedConstants.ATOM_FEED_ID); id.appendChild(idText); root.appendChild(id); // create updated element, add its text, and add to root Element updated = doc.createElement("updated"); Date lastModified = new Date(); Text updatedText = doc.createTextNode(dateToRFC3339(lastModified)); updated.appendChild(updatedText); root.appendChild(updated); // create versionId element, add its text, and add to root Element versionId = doc.createElement("versionId"); Text versionIdText = doc.createTextNode(String.valueOf(lastModified.getTime())); versionId.appendChild(versionIdText); root.appendChild(versionId); // create versionId element, add its text, and add to root Element entriesSizeElement = doc.createElement("entriesSize"); Text entriesSizeText = doc.createTextNode(String.valueOf(entriesSize)); entriesSizeElement.appendChild(entriesSizeText); root.appendChild(entriesSizeElement); /* * Print the xml to the file */ // set up a transformer TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); trans.setOutputProperty(OutputKeys.INDENT, "no"); // create string from xml tree FileWriter fw = new FileWriter(atomfeedheader); StreamResult result = new StreamResult(fw); DOMSource source = new DOMSource(doc); trans.transform(source, result); // print xml for debugging purposes if (log.isTraceEnabled()) { StringWriter sw = new StringWriter(); result = new StreamResult(sw); trans.transform(source, result); log.trace("Here's the initial xml:\n\n" + sw.toString()); } } catch (Exception e) { log.error("unable to initialize feed at: " + atomfeedheader.getAbsolutePath(), e); } }
From source file:com.netspective.sparx.form.DialogContext.java
static public void exportParamToXml(Element parent, String name, String[] values) { Document doc = parent.getOwnerDocument(); Element fieldElem = doc.createElement("request-param"); fieldElem.setAttribute("name", name); if (values != null && values.length > 1) { fieldElem.setAttribute("value-type", "strings"); Element valuesElem = doc.createElement("values"); for (int i = 0; i < values.length; i++) { Element valueElem = doc.createElement("value"); valueElem.appendChild(doc.createTextNode(values[i])); valuesElem.appendChild(valueElem); }//from w w w .j a va 2s . c o m fieldElem.appendChild(valuesElem); parent.appendChild(fieldElem); } else if (values != null) { fieldElem.setAttribute("value-type", "string"); Element valueElem = doc.createElement("value"); valueElem.appendChild(doc.createTextNode(values[0])); fieldElem.appendChild(valueElem); parent.appendChild(fieldElem); } }
From source file:com.meltmedia.cadmium.core.util.WarUtils.java
/** * Adds vHost and context-root mappings to a jboss-web.xml file contained withing a zip/war file. * @param inZip The zip file that the original jboss-web.xml file is in. * @param outZip The zip output stream to write the updated jboss-web.xml file to. * @param jbossWeb The zip element that represents the jboss-web.xml file. * @param domain The domain to add a vHost for. * @param context The context to add a context-root for. * @throws Exception//from w ww . j a va 2 s . co m */ public static void updateDomain(ZipFile inZip, ZipOutputStream outZip, ZipEntry jbossWeb, String domain, String context) throws Exception { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(inZip.getInputStream(jbossWeb)); Element rootNode = null; NodeList nodes = doc.getElementsByTagName("jboss-web"); if (nodes.getLength() == 1) { rootNode = (Element) nodes.item(0); } if (domain != null && domain.length() > 0) { Element vHost = doc.createElement("virtual-host"); removeNodesByTagName(rootNode, "virtual-host"); vHost.appendChild(doc.createTextNode(domain)); rootNode.appendChild(vHost); } if (context != null && context.length() > 0) { Element cRoot = doc.createElement("context-root"); removeNodesByTagName(rootNode, "context-root"); cRoot.appendChild(doc.createTextNode(context)); rootNode.appendChild(cRoot); } storeXmlDocument(outZip, jbossWeb, doc); }
From source file:com.granule.json.utils.XML.java
private static void convertJSONObject(Document doc, Element parent, JSONObject jObject, String tagName) { Set attributes = jObject.keySet(); Iterator attrsItr = attributes.iterator(); Element element = doc.createElement(removeProblemCharacters(tagName)); if (parent != null) { parent.appendChild(element); } else {/*w w w. j a va2s . co m*/ doc.appendChild(element); } while (attrsItr.hasNext()) { String attr = (String) attrsItr.next(); Object obj = jObject.opt(attr); if (obj instanceof Number) { element.setAttribute(attr, obj.toString()); } else if (obj instanceof Boolean) { element.setAttribute(attr, obj.toString()); } else if (obj instanceof String) { element.setAttribute(attr, escapeEntityCharacters(obj.toString())); } else if (obj == null) { element.setAttribute(attr, ""); } else if (obj instanceof JSONObject) { convertJSONObject(doc, element, (JSONObject) obj, attr); } else if (obj instanceof JSONArray) { convertJSONArray(doc, element, (JSONArray) obj, attr); } } }
From source file:org.openmrs.module.atomfeed.AtomFeedUtil.java
/** * Converts the given object to an xml entry * /*from w w w . j av a 2s. c o m*/ * @param action what is happenening * @param object the object being changed * @return atom feed xml entry string * @should return valid entry xml data */ protected static String getEntry(String action, OpenmrsObject object) { try { // We need a Document DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); Document doc = docBuilder.newDocument(); // ////////////////////// // Creating the XML tree // create the root element and add it to the document Element root = doc.createElement("entry"); doc.appendChild(root); // the title element is REQUIRED // create title element, add object class, and add to root Element title = doc.createElement("title"); Text titleText = doc.createTextNode(action + ":" + object.getClass().getName()); title.appendChild(titleText); root.appendChild(title); // create link to view object details Element link = doc.createElement("link"); link.setAttribute("href", AtomFeedUtil.getViewUrl(object)); root.appendChild(link); // the id element is REQUIRED // create id element Element id = doc.createElement("id"); Text idText = doc.createTextNode("urn:uuid:" + object.getUuid()); id.appendChild(idText); root.appendChild(id); // the updated element is REQUIRED // create updated element, set current date Element updated = doc.createElement("updated"); // TODO: try to discover dateChanged/dateCreated from object -- ATOM-2 // instead? Text updatedText = doc.createTextNode(dateToRFC3339(getUpdatedValue(object))); updated.appendChild(updatedText); root.appendChild(updated); // the author element is REQUIRED // add author element, find creator Element author = doc.createElement("author"); Element name = doc.createElement("name"); Text nameText = doc.createTextNode(getAuthor(object)); name.appendChild(nameText); author.appendChild(name); root.appendChild(author); // the summary element is REQUIRED // add a summary Element summary = doc.createElement("summary"); Text summaryText = doc.createTextNode(object.getClass().getSimpleName() + " -- " + action); summary.appendChild(summaryText); root.appendChild(summary); Element classname = doc.createElement("classname"); Text classnameText = doc.createTextNode(object.getClass().getName()); classname.appendChild(classnameText); root.appendChild(classname); Element actionElement = doc.createElement("action"); Text actionText = doc.createTextNode(action); actionElement.appendChild(actionText); root.appendChild(actionElement); /* * Print the xml to the string */ // set up a transformer TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans.setOutputProperty(OutputKeys.INDENT, "no"); StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); DOMSource source = new DOMSource(doc); trans.transform(source, result); return sw.toString(); } catch (Exception e) { log.error("unable to create entry string for: " + object); return ""; } }
From source file:com.msopentech.odatajclient.engine.data.json.DOMTreeUtils.java
/** * Recursively builds DOM content out of JSON subtree rooted at given node. * * @param document root of the DOM document being built * @param parent parent of the nodes being generated during this step * @param node JSON node to be used as source for DOM elements */// ww w . ja v a 2s. com public static void buildSubtree(final Element parent, final JsonNode node) { final Iterator<String> fieldNameItor = node.fieldNames(); final Iterator<JsonNode> nodeItor = node.elements(); while (nodeItor.hasNext()) { final JsonNode child = nodeItor.next(); final String name = fieldNameItor.hasNext() ? fieldNameItor.next() : ""; // no name? array item if (name.isEmpty()) { final Element element = parent.getOwnerDocument().createElementNS(ODataConstants.NS_DATASERVICES, ODataConstants.PREFIX_DATASERVICES + ODataConstants.ELEM_ELEMENT); parent.appendChild(element); if (child.isValueNode()) { if (child.isNull()) { element.setAttributeNS(ODataConstants.NS_METADATA, ODataConstants.ATTR_NULL, Boolean.toString(true)); } else { element.appendChild(parent.getOwnerDocument().createTextNode(child.asText())); } } if (child.isContainerNode()) { buildSubtree(element, child); } } else if (!name.contains("@") && !ODataConstants.JSON_TYPE.equals(name)) { final Element property = parent.getOwnerDocument().createElementNS(ODataConstants.NS_DATASERVICES, ODataConstants.PREFIX_DATASERVICES + name); parent.appendChild(property); boolean typeSet = false; if (node.hasNonNull(name + "@" + ODataConstants.JSON_TYPE)) { property.setAttributeNS(ODataConstants.NS_METADATA, ODataConstants.ATTR_M_TYPE, node.get(name + "@" + ODataConstants.JSON_TYPE).textValue()); typeSet = true; } if (child.isNull()) { property.setAttributeNS(ODataConstants.NS_METADATA, ODataConstants.ATTR_NULL, Boolean.toString(true)); } else if (child.isValueNode()) { if (!typeSet) { if (child.isInt()) { property.setAttributeNS(ODataConstants.NS_METADATA, ODataConstants.ATTR_M_TYPE, EdmSimpleType.Int32.toString()); } if (child.isLong()) { property.setAttributeNS(ODataConstants.NS_METADATA, ODataConstants.ATTR_M_TYPE, EdmSimpleType.Int64.toString()); } if (child.isBigDecimal()) { property.setAttributeNS(ODataConstants.NS_METADATA, ODataConstants.ATTR_M_TYPE, EdmSimpleType.Decimal.toString()); } if (child.isDouble()) { property.setAttributeNS(ODataConstants.NS_METADATA, ODataConstants.ATTR_M_TYPE, EdmSimpleType.Double.toString()); } if (child.isBoolean()) { property.setAttributeNS(ODataConstants.NS_METADATA, ODataConstants.ATTR_M_TYPE, EdmSimpleType.Boolean.toString()); } if (child.isTextual()) { property.setAttributeNS(ODataConstants.NS_METADATA, ODataConstants.ATTR_M_TYPE, EdmSimpleType.String.toString()); } } property.appendChild(parent.getOwnerDocument().createTextNode(child.asText())); } else if (child.isContainerNode()) { if (!typeSet && child.hasNonNull(ODataConstants.JSON_TYPE)) { property.setAttributeNS(ODataConstants.NS_METADATA, ODataConstants.ATTR_M_TYPE, child.get(ODataConstants.JSON_TYPE).textValue()); } final String type = property.getAttribute(ODataConstants.ATTR_M_TYPE); if (StringUtils.isNotBlank(type) && EdmSimpleType.isGeospatial(type)) { if (EdmSimpleType.Geography.toString().equals(type) || EdmSimpleType.Geometry.toString().equals(type)) { final String geoType = child.get(ODataConstants.ATTR_TYPE).textValue(); property.setAttributeNS(ODataConstants.NS_METADATA, ODataConstants.ATTR_M_TYPE, geoType.startsWith("Geo") ? EdmSimpleType.namespace() + "." + geoType : type + geoType); } if (child.has(ODataConstants.JSON_COORDINATES) || child.has(ODataConstants.JSON_GEOMETRIES)) { GeospatialJSONHandler.deserialize(child, property, property.getAttribute(ODataConstants.ATTR_M_TYPE)); } } else { buildSubtree(property, child); } } } } }
From source file:com.git.original.common.config.XMLFileConfigDocument.java
/** * ??XML//w w w . ja va 2s .co m * * @param cn * ? * @return XML */ @SuppressWarnings("unchecked") static Element convertConfigNode(Document doc, ConfigNode cn) { Element elem = doc.createElement(cn.getName()); Map<String, String> attrMap = cn.attributes(); if (attrMap != null) { for (Entry<String, String> entry : attrMap.entrySet()) { elem.setAttribute(entry.getKey(), entry.getValue()); } } if (cn.hasChildren()) { for (Object child : cn.getAllChildren()) { if (child instanceof List) { List<ConfigNode> cnList = (List<ConfigNode>) child; for (ConfigNode node : cnList) { elem.appendChild(convertConfigNode(doc, node)); } } else { elem.appendChild(convertConfigNode(doc, (ConfigNode) child)); } } } else if (cn.value != null) { elem.setTextContent(cn.value.toString()); } return elem; }
From source file:com.msopentech.odatajclient.engine.data.ODataBinder.java
private static Element toCollectionPropertyElement(final ODataProperty prop, final Document doc, final boolean setType) { if (!prop.hasCollectionValue()) { throw new IllegalArgumentException( "Invalid property value type " + prop.getValue().getClass().getSimpleName()); }//from w w w .j a v a 2 s. c o m final ODataCollectionValue value = prop.getCollectionValue(); final Element element = doc.createElement(ODataConstants.PREFIX_DATASERVICES + prop.getName()); if (value.getTypeName() != null && setType) { element.setAttribute(ODataConstants.ATTR_M_TYPE, value.getTypeName()); } for (ODataValue el : value) { if (el.isPrimitive()) { element.appendChild( toPrimitivePropertyElement(ODataConstants.ELEM_ELEMENT, el.asPrimitive(), doc, setType)); } else { element.appendChild( toComplexPropertyElement(ODataConstants.ELEM_ELEMENT, el.asComplex(), doc, setType)); } } return element; }
From source file:Main.java
public static Element overrideXml(Element target, Element parent) { if (parent != null) { NamedNodeMap namedNodeMap = parent.getAttributes(); for (int i = 0; i < namedNodeMap.getLength(); i++) { Node attributeNode = namedNodeMap.item(i); String parentAttributeName = attributeNode.getNodeName(); String parentAttributeValue = attributeNode.getNodeValue(); // attribute override if (!target.hasAttribute(parentAttributeName)) { target.setAttribute(parentAttributeName, parentAttributeValue); }//from ww w . ja v a 2 s .co m // children override if (parent.getChildNodes().getLength() > 0) { if (target.getChildNodes().getLength() == 0) { for (int j = 0; j < target.getChildNodes().getLength(); j++) { target.appendChild(target.getChildNodes().item(j)); } } } } } return target; }
From source file:ConfigFiles.java
public static void saveXML(boolean blank, String filename) { boolean saved = true; try {//from ww w. ja v a 2 s.c o m DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); DOMSource source = new DOMSource(document); Comment simpleComment = document.createComment( "\n Master config file for TSC.\n \n Logs" + " Path: Where CE and PE write their getLogs()." + " Reports Path: Where all reports are saved.\n " + "Test Suite Config: All info about the current " + "Test Suite (Test Plan).\n"); document.appendChild(simpleComment); Element root = document.createElement("Root"); document.appendChild(root); Element rootElement = document.createElement("FileType"); root.appendChild(rootElement); rootElement.appendChild(document.createTextNode("config")); try { addTag("CentralEnginePort", tceport.getText(), root, blank, document); } catch (Exception e) { addTag("CentralEnginePort", "", root, blank, document); } // try{addTag("ResourceAllocatorPort",traPort.getText(),root,blank,document);} // catch(Exception e){addTag("ResourceAllocatorPort","",root,blank,document);} // try{addTag("HttpServerPort",thttpPort.getText(),root,blank,document);} // catch(Exception e){addTag("HttpServerPort","",root,blank,document);} try { addTag("TestCaseSourcePath", ttcpath.getText(), root, blank, document); } catch (Exception e) { addTag("TestCaseSourcePath", "", root, blank, document); } try { addTag("LibsPath", libpath.getText(), root, blank, document); } catch (Exception e) { addTag("LibsPath", "", root, blank, document); } try { addTag("UsersPath", tUsers.getText(), root, blank, document); } catch (Exception e) { addTag("UsersPath", "", root, blank, document); } try { addTag("PredefinedSuitesPath", tSuites.getText(), root, blank, document); } catch (Exception e) { addTag("PredefinedSuitesPath", "", root, blank, document); } try { addTag("ArchiveLogsPath", tsecondarylog.getText(), root, blank, document); } catch (Exception e) { addTag("ArchiveLogsPath", "", root, blank, document); } try { addTag("ArchiveLogsPathActive", logsenabled.isSelected() + "", root, blank, document); } catch (Exception e) { addTag("ArchiveLogsPath", "", root, blank, document); } try { addTag("LogsPath", tlog.getText(), root, blank, document); } catch (Exception e) { addTag("LogsPath", "", root, blank, document); } rootElement = document.createElement("LogFiles"); root.appendChild(rootElement); try { addTag("logRunning", trunning.getText(), rootElement, blank, document); } catch (Exception e) { addTag("logRunning", "", rootElement, blank, document); } try { addTag("logDebug", tdebug.getText(), rootElement, blank, document); } catch (Exception e) { addTag("logDebug", "", rootElement, blank, document); } try { addTag("logSummary", tsummary.getText(), rootElement, blank, document); } catch (Exception e) { addTag("logSummary", "", rootElement, blank, document); } try { addTag("logTest", tinfo.getText(), rootElement, blank, document); } catch (Exception e) { addTag("logTest", "", rootElement, blank, document); } try { addTag("logCli", tcli.getText(), rootElement, blank, document); } catch (Exception e) { addTag("logCli", "", rootElement, blank, document); } try { addTag("DbConfigFile", tdbfile.getText(), root, blank, document); } catch (Exception e) { addTag("DbConfigFile", "", root, blank, document); } try { addTag("EpNames", tepid.getText(), root, blank, document); } catch (Exception e) { addTag("EpNames", "", root, blank, document); } try { addTag("EmailConfigFile", temailfile.getText(), root, blank, document); } catch (Exception e) { addTag("EmailConfigFile", "", root, blank, document); } try { addTag("GlobalParams", tglobalsfile.getText(), root, blank, document); } catch (Exception e) { addTag("GlobalParams", "", root, blank, document); } try { addTag("TestConfigPath", testconfigpath.getText(), root, blank, document); } catch (Exception e) { addTag("TestConfigPath", "", root, blank, document); } String temp; if (blank) temp = "fwmconfig"; else temp = filename; File file = new File(RunnerRepository.temp + RunnerRepository.getBar() + "Twister" + RunnerRepository.getBar() + temp + ".xml"); Result result = new StreamResult(file); transformer.transform(source, result); System.out.println("Saving to: " + RunnerRepository.USERHOME + "/twister/config/"); FileInputStream in = new FileInputStream(file); RunnerRepository.uploadRemoteFile(RunnerRepository.USERHOME + "/twister/config/", in, file.getName()); } catch (ParserConfigurationException e) { System.out .println("DocumentBuilder cannot be created which" + " satisfies the configuration requested"); saved = false; } catch (TransformerConfigurationException e) { System.out.println("Could not create transformer"); saved = false; } catch (Exception e) { e.printStackTrace(); saved = false; } if (saved) { CustomDialog.showInfo(JOptionPane.INFORMATION_MESSAGE, RunnerRepository.window, "Successful", "File successfully saved"); } else { CustomDialog.showInfo(JOptionPane.WARNING_MESSAGE, RunnerRepository.window.mainpanel.p4.getConfig(), "Warning", "File could not be saved "); } }