List of usage examples for org.w3c.dom Document appendChild
public Node appendChild(Node newChild) throws DOMException;
newChild
to the end of the list of children of this node. From source file:org.bigtester.ate.model.data.TestDatabaseInitializer.java
/** * Combine init xml files./*from w w w.j av a 2s.c o m*/ * * @return the input stream */ private InputStream combineInitXmlFiles() { if (getInitXmlFiles().isEmpty()) { throw GlobalUtils.createNotInitializedException("xml data files are not populated"); } else { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); DocumentBuilder dbuilder; try { dbuilder = dbf.newDocumentBuilder(); Document retDoc = dbuilder.newDocument(); Document doc0; doc0 = dbuilder.parse(getInitXmlFiles().get(0)); Node firstDataset = retDoc.importNode(doc0.getFirstChild(), true); retDoc.appendChild(firstDataset); for (int i = 1; i < getInitXmlFiles().size(); i++) { Document doc2 = dbuilder.parse(getInitXmlFiles().get(i)); Node root = doc2.getFirstChild(); NodeList list = root.getChildNodes(); for (int index = 0; index < list.getLength(); index++) { Node copiedNode = retDoc.importNode(list.item(index), true); retDoc.getDocumentElement().appendChild(copiedNode); } } DOMSource source = new DOMSource(retDoc); StringWriter xmlAsWriter = new StringWriter(); StreamResult result = new StreamResult(xmlAsWriter); TransformerFactory.newInstance().newTransformer().transform(source, result); // write changes return new ByteArrayInputStream(xmlAsWriter.toString().getBytes("UTF-8")); } catch (SAXException | IOException | ParserConfigurationException e) { throw GlobalUtils.createNotInitializedException("xml data files are not correctly populated", e); } catch (TransformerException | TransformerFactoryConfigurationError transE) { throw GlobalUtils.createInternalError("xml transformer error!", transE); } } }
From source file:be.fedict.eid.applet.service.signer.odf.AbstractODFSignatureService.java
@Override protected final Document getEnvelopingDocument() throws ParserConfigurationException, IOException, SAXException { Document document = getODFSignatureDocument(); if (null != document) { return document; }//from w ww . j a va2 s . co m document = ODFUtil.getNewDocument(); Element rootElement = document.createElementNS(ODFUtil.SIGNATURE_NS, ODFUtil.SIGNATURE_ELEMENT); rootElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", ODFUtil.SIGNATURE_NS); document.appendChild(rootElement); return document; }
From source file:me.uni.sushilkumar.geodine.util.YummlyLookup.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request//from ww w . j a v a2 s. c o m * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ParseException { response.setContentType("text/xml"); PrintWriter out = response.getWriter(); DBConnection con = null; try { String cuisine = request.getParameter("cuisine"); con = new DBConnection(); CuisineObject obj = con.getCuisineData(cuisine); int id = obj.getId(); String cuisineId = obj.getCuisineId(); String country = obj.getCountry(); String ytid = obj.getYtid(); ArrayList<String> directions = obj.getDirections(); ArrayList<String> ingredients = obj.getIngredients(); HttpSession session = request.getSession(true); String email = (String) session.getAttribute("userName"); boolean isFav = con.isFavourite(cuisineId, email); String fav = ""; if (isFav) fav = "true"; else fav = "false"; DocumentBuilderFactory docFactory = null; DocumentBuilder docBuilder = null; Document xmlDoc = null; Element root = null; docFactory = DocumentBuilderFactory.newInstance(); docBuilder = docFactory.newDocumentBuilder(); xmlDoc = docBuilder.newDocument(); root = xmlDoc.createElement("item"); xmlDoc.appendChild(root); Element eid = xmlDoc.createElement("id"); eid.appendChild(xmlDoc.createTextNode(Integer.toString(id))); root.appendChild(eid); Element eisfav = xmlDoc.createElement("favourite"); eisfav.appendChild(xmlDoc.createTextNode(fav)); root.appendChild(eisfav); Element ecuisineId = xmlDoc.createElement("cuisine-id"); ecuisineId.appendChild(xmlDoc.createTextNode(cuisineId)); root.appendChild(ecuisineId); Element ecountry = xmlDoc.createElement("country"); ecountry.appendChild(xmlDoc.createTextNode(country)); root.appendChild(ecountry); Element eytid = xmlDoc.createElement("ytid"); eytid.appendChild(xmlDoc.createTextNode(ytid)); root.appendChild(eytid); Element edirections = xmlDoc.createElement("steps"); for (int i = 0; i < directions.size(); i++) { Element temp = xmlDoc.createElement("step"); temp.appendChild(xmlDoc.createTextNode(directions.get(i))); edirections.appendChild(temp); } root.appendChild(edirections); Element eingredients = xmlDoc.createElement("ingredients"); for (int i = 0; i < ingredients.size(); i++) { Element temp = xmlDoc.createElement("ingredient"); temp.appendChild(xmlDoc.createTextNode(ingredients.get(i))); eingredients.appendChild(temp); } root.appendChild(eingredients); StringWriter sw = new StringWriter(); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); //transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(xmlDoc); StreamResult result = new StreamResult(sw); transformer.transform(source, result); out.println(sw.toString()); if (email != null) { con.addRecentCuisine(cuisineId, email, new Date().toString()); } } catch (TransformerException ex) { Logger.getLogger(YummlyLookup.class.getName()).log(Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { Logger.getLogger(YummlyLookup.class.getName()).log(Level.SEVERE, null, ex); } finally { out.close(); if (con != null) { con.close(); } } }
From source file:com.centeractive.ws.builder.soap.XmlUtils.java
public static Document createDocument(QName element) { ensureDocumentBuilder();/* w w w .j a va2 s .co m*/ Document document = documentBuilder.newDocument(); document.appendChild(document.createElementNS(element.getNamespaceURI(), element.getLocalPart())); return document; }
From source file:act.installer.HMDBParser.java
/** * Convert an HMDB XML document into a Chemical object. Expects one chemical per document. * @param doc A parsed HMDB XML doc./* w w w . j a v a 2 s. com*/ * @return The corresponding chemical to store in the DB. * @throws JaxenException * @throws JSONException */ protected Chemical extractChemicalFromXMLDocument(Document doc) throws JaxenException, JSONException { String hmdbId = getText(HMDB_XPATH.HMDB_ID_TEXT, doc); String primaryName = getText(HMDB_XPATH.PRIMARY_NAME_TEXT, doc); String iupacName = getText(HMDB_XPATH.IUPAC_NAME_TEXT, doc); List<String> synonyms = getTextFromNodes(HMDB_XPATH.SYNONYMS_NODES, doc); String inchi = getText(HMDB_XPATH.INCHI_TEXT, doc); String smiles = getText(HMDB_XPATH.SMILES_TEXT, doc); // Require an InChI if we're going to consume this molecule. if (inchi == null || inchi.isEmpty()) { LOGGER.warn("No InChI found for HMDB chemical %s, aborting", hmdbId); return null; } String ontologyStatus = getText(HMDB_XPATH.ONTOLOGY_STATUS_TEXT, doc); List<String> ontologyOrigins = getTextFromNodes(HMDB_XPATH.ONTOLOGY_ORIGINS_NODES, doc); List<String> ontologyFunctions = getTextFromNodes(HMDB_XPATH.ONTOLOGY_FUNCTIONS_NODES, doc); List<String> ontologyApplications = getTextFromNodes(HMDB_XPATH.ONTOLOGY_APPLICATIONS_NODES, doc); List<String> ontologyLocations = getTextFromNodes(HMDB_XPATH.ONTOLOGY_LOCATIONS_NODES, doc); List<String> locationFluids = getTextFromNodes(HMDB_XPATH.LOCATIONS_FLUID_NODES, doc); List<String> locationTissues = getTextFromNodes(HMDB_XPATH.LOCATIONS_TISSUE_NODES, doc); List<String> pathwayNames = getTextFromNodes(HMDB_XPATH.PATHWAY_NAME_NODES, doc); List<String> diseaseNames = getTextFromNodes(HMDB_XPATH.DISEASE_NAME_NODES, doc); String metlinId = getText(HMDB_XPATH.METLIN_ID_TEXT, doc); String pubchemId = getText(HMDB_XPATH.PUBCHEM_ID_TEXT, doc); String chebiId = getText(HMDB_XPATH.CHEBI_ID_TEXT, doc); List<Node> proteins = getNodes(HMDB_XPATH.PROTEIN_L1_NODES, doc); // Simple triples of name, uniprot id, gene name. List<Triple<String, String, String>> proteinAttributes = new ArrayList<>(proteins.size()); for (Node n : proteins) { /* In order to run XPath on a sub-document, we have to Extract the relevant nodes into their own document object. * If we try to run evaluate on `n` instead of this new document, we'll get matching paths for the original * document `d` but not for the nodes we're looking at right now. Very weird. */ Document proteinDoc = documentBuilder.newDocument(); proteinDoc.adoptNode(n); proteinDoc.appendChild(n); String name = getText(HMDB_XPATH.PROTEIN_L2_NAME_TEXT, proteinDoc); String uniprotId = getText(HMDB_XPATH.PROTEIN_L2_UNIPROT_ID_TEXT, proteinDoc); String geneName = getText(HMDB_XPATH.PROTEIN_L2_GENE_NAME_TEXT, proteinDoc); proteinAttributes.add(Triple.of(name, uniprotId, geneName)); } // Assumption: when we reach this point there will always be an InChI. Chemical chem = new Chemical(inchi); chem.setSmiles(smiles); chem.setCanon(primaryName); if (pubchemId != null && !pubchemId.isEmpty()) { chem.setPubchem(Long.valueOf(pubchemId)); } synonyms.forEach(chem::addSynonym); chem.addSynonym(iupacName); // TODO: is there a better place for this? JSONObject meta = new JSONObject().put("hmdb_id", hmdbId).put("ontology", new JSONObject().put("status", ontologyStatus).put("origins", new JSONArray(ontologyOrigins)) .put("functions", new JSONArray(ontologyFunctions)) .put("applications", new JSONArray(ontologyApplications)) .put("locations", new JSONArray(ontologyLocations))) .put("location", new JSONObject().put("fluid", new JSONArray(locationFluids)).put("tissue", new JSONArray(locationTissues))) .put("pathway_names", new JSONArray(pathwayNames)).put("disease_names", new JSONArray(diseaseNames)) .put("metlin_id", metlinId).put("chebi_id", chebiId).put("proteins", new JSONArray(proteinAttributes .stream().map(t -> new JSONObject().put("name", t.getLeft()) .put("uniprot_id", t.getMiddle()).put("gene_name", t.getRight())) .collect(Collectors.toList()))); chem.putRef(Chemical.REFS.HMDB, meta); return chem; }
From source file:erwins.util.repack.xml.XMLBuilder.java
/** * Construct a builder for new XML document with a default namespace. * The document will be created with the given root element, and the builder * returned by this method will serve as the starting-point for any further * document additions./*from ww w . j a v a2s.com*/ * * @param name * the name of the document's root element. * @param namespaceURI * default namespace URI for document, ignored if null or empty. * @return * a builder node that can be used to add more nodes to the XML document. * * @throws FactoryConfigurationError * @throws ParserConfigurationException */ public static XMLBuilder create(String name, String namespaceURI) throws ParserConfigurationException, FactoryConfigurationError { // Init DOM builder and Document. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(isNamespaceAware); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.newDocument(); Element rootElement = null; if (namespaceURI != null && namespaceURI.length() > 0) { rootElement = document.createElementNS(namespaceURI, name); } else { rootElement = document.createElement(name); } document.appendChild(rootElement); return new XMLBuilder(document); }
From source file:io.wcm.tooling.commons.contentpackagebuilder.XmlContentBuilder.java
private Element createJcrRoot(Document doc, String primaryType) { Element jcrRoot = doc.createElementNS(NS_JCR, "jcr:root"); for (Map.Entry<String, String> namespace : xmlNamespaces.entrySet()) { jcrRoot.setAttribute("xmlns:" + namespace.getKey(), namespace.getValue()); }/*from ww w . j a v a2s.c o m*/ setAttributeNamespaceAware(jcrRoot, PN_PRIMARY_TYPE, primaryType); doc.appendChild(jcrRoot); return jcrRoot; }
From source file:com.bluexml.xforms.controller.FluxFacade.java
public org.w3c.dom.Element setRepeatIndex(String id, String position, String sessionKey) throws FluxException { try {//from w w w .j a va 2 s . c om UIEvent event = new DefaultUIEventImpl(); event.initEvent("SETINDEX", id, position); return handleUIEvent(event, sessionKey); } catch (Exception e) { LOGGER.fatal("XFormsSession not found - stopping"); Document newDocument = DOMUtil.newDocument(false, false); Element root = newDocument.createElement("root"); newDocument.appendChild(root); return root; } }
From source file:com.krawler.esp.utils.ConfigReader.java
/** Writes non-default properties in this configuration. */ public void write(OutputStream out) throws IOException { Properties properties = getProps(); try {//from w w w .j ava 2 s . co m Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element conf = doc.createElement("krawler-conf"); doc.appendChild(conf); conf.appendChild(doc.createTextNode("\n")); for (Enumeration e = properties.keys(); e.hasMoreElements();) { String name = (String) e.nextElement(); String value = (String) properties.get(name); Element propNode = doc.createElement("property"); conf.appendChild(propNode); Element nameNode = doc.createElement("name"); nameNode.appendChild(doc.createTextNode(name)); propNode.appendChild(nameNode); Element valueNode = doc.createElement("value"); valueNode.appendChild(doc.createTextNode(value)); propNode.appendChild(valueNode); conf.appendChild(doc.createTextNode("\n")); } DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(out); TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); transformer.transform(source, result); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:act.installer.pubchem.PubchemParser.java
/** * Extracts compound features from a sub-document/sub-tree containing one PC-Compound element. Nodes that contain * interesting features are found and their text extracted using XPath. * * @param d The document from which to extract features. * @return A PubchemEntry object corresponding to features from one PC-Compound document. * @throws XPathExpressionException//w ww . jav a 2s . c o m */ private PubchemEntry extractPCCompoundFeatures(Document d) throws JaxenException { Long id = Long.valueOf(xpaths.get(PC_XPATHS.PC_ID_L1_TEXT).stringValueOf(d)); PubchemEntry entry = new PubchemEntry(id); // Jaxen's API is from a pre-generics age! List<Node> nodes = (List<Node>) xpaths.get(PC_XPATHS.IUPAC_NAME_L1_NODES).selectNodes(d); if (nodes.size() == 0) { LOGGER.warn("No names available for compound %d", id); } for (Node n : nodes) { /* In order to run XPath on a sub-document, we have to Extract the relevant nodes into their own document object. * If we try to run evaluate on `n` instead of this new document, we'll get matching paths for the original * document `d` but not for the nodes we're looking at right now. Very weird. * TODO: remember this way of running XPath on documents the next time we need to write an XML parser. */ Document iupacNameDoc = documentBuilder.newDocument(); iupacNameDoc.adoptNode(n); iupacNameDoc.appendChild(n); String type = xpaths.get(PC_XPATHS.IUPAC_NAME_L2_TYPE_TEXT).stringValueOf(iupacNameDoc); String value = xpaths.get(PC_XPATHS.IUPAC_NAME_L2_VALUE_TEXT).stringValueOf(iupacNameDoc); entry.setNameByType(type, value); } // We really need an InChI for a chemical to make sense, so log errors if we can't find one. boolean hasInChI = false; nodes = xpaths.get(PC_XPATHS.INCHI_L1_NODES).selectNodes(d); if (nodes.size() == 0) { LOGGER.warn("Found chemical (%d) with no InChIs, hoping for SMILES instead", id); } else if (nodes.size() > 1) { LOGGER.error("Assumption violation: found chemical with multiple InChIs (%d), skipping", id); return null; } else { hasInChI = true; Node n = nodes.get(0); Document inchiDoc = documentBuilder.newDocument(); inchiDoc.adoptNode(n); inchiDoc.appendChild(n); String value = xpaths.get(PC_XPATHS.INCHI_L2_TEXT).stringValueOf(inchiDoc); entry.setInchi(value); } nodes = xpaths.get(PC_XPATHS.SMILES_L1_NODES).selectNodes(d); if (nodes.size() == 0) { if (hasInChI) { LOGGER.warn("Found chemical (%d) with no SMILES, using only InChI"); } else { LOGGER.warn("Found chemical (%d) with no InChI or SMILES, skipping"); return null; } } else { for (Node n : nodes) { Document smilesDoc = documentBuilder.newDocument(); smilesDoc.adoptNode(n); smilesDoc.appendChild(n); String smiles = xpaths.get(PC_XPATHS.SMILES_L2_TEXT).stringValueOf(smilesDoc); entry.appendSmiles(smiles); } } return entry; }