List of usage examples for org.w3c.dom Document adoptNode
public Node adoptNode(Node source) throws DOMException;
From source file:com.quest.keycloak.protocol.wsfed.builders.RequestSecurityTokenResponseBuilder.java
protected Document signAssertion(Document samlDocument) throws ProcessingException { Element originalAssertionElement = samlDocument.getDocumentElement(); //org.keycloak.saml.common.util.DocumentUtil.getChildElement(samlDocument.getDocumentElement(), new QName(JBossSAMLURIConstants.ASSERTION_NSURI.get(), JBossSAMLConstants.ASSERTION.get())); if (originalAssertionElement == null) return samlDocument; Node clonedAssertionElement = originalAssertionElement.cloneNode(true); Document temporaryDocument; try {// w ww . j a v a 2 s. c o m temporaryDocument = org.keycloak.saml.common.util.DocumentUtil.createDocument(); } catch (ConfigurationException e) { throw new ProcessingException(e); } temporaryDocument.adoptNode(clonedAssertionElement); temporaryDocument.appendChild(clonedAssertionElement); signDocument(temporaryDocument); return temporaryDocument; }
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 w w . j a v a 2 s. 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; }
From source file:cz.cas.lib.proarc.common.export.mets.MetsUtils.java
/** * * Returns a node from the xml document defined by the Xpath * * @param elements/* w w w. ja v a 2 s . com*/ * @param xPath * @return */ public static Node xPathEvaluateNode(List<Element> elements, String xPath) throws MetsExportException { Document document = null; try { document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); } catch (ParserConfigurationException e1) { throw new MetsExportException("Error while evaluating xPath " + xPath, false, e1); } for (Element element : elements) { Node newNode = element.cloneNode(true); document.adoptNode(newNode); document.appendChild(newNode); } XPath xpathObject = XPathFactory.newInstance().newXPath(); try { return (Node) xpathObject.compile(xPath).evaluate(document, XPathConstants.NODE); } catch (XPathExpressionException e) { throw new MetsExportException("Error while evaluating xPath " + xPath, false, e); } }
From source file:eu.europa.esig.dss.xades.signature.XAdESSignatureBuilder.java
static void createTransform(final Document document, final DSSTransform dssTransform, final Element transformDom) { transformDom.setAttribute(ALGORITHM, dssTransform.getAlgorithm()); final String elementName = dssTransform.getElementName(); final String textContent = dssTransform.getTextContent(); if (StringUtils.isNotBlank(elementName)) { final String namespace = dssTransform.getNamespace(); DSSXMLUtils.addTextElement(document, transformDom, namespace, elementName, textContent); } else if (StringUtils.isNotBlank(textContent)) { final Document transformContentDoc = DSSXMLUtils.buildDOM(textContent); final Element contextDocumentElement = transformContentDoc.getDocumentElement(); document.adoptNode(contextDocumentElement); transformDom.appendChild(contextDocumentElement); }/*w ww . ja v a 2s. c o m*/ }
From source file:com.twinsoft.convertigo.engine.util.XMLUtils.java
public static NodeList toNodeList(List<Node> nl) { Document doc = getDefaultDocumentBuilder().newDocument(); Element root = doc.createElement("root"); for (Node n : nl) { root.appendChild(doc.adoptNode(n)); }/* w w w . j a v a 2 s .c o m*/ return root.getChildNodes(); }
From source file:cz.cas.lib.proarc.common.export.mets.MetsUtils.java
/** * * Generates an XML document from list of elements * * @param elements//from w ww. j av a 2 s .co m * @return */ public static Document getDocumentFromList(List<Element> elements) throws MetsExportException { Document document = null; try { DocumentBuilderFactory builder = DocumentBuilderFactory.newInstance(); builder.setValidating(true); builder.setNamespaceAware(true); document = builder.newDocumentBuilder().newDocument(); } catch (ParserConfigurationException e1) { throw new MetsExportException("Error while getting document from list", false, e1); } for (Element element : elements) { Node newNode = element.cloneNode(true); document.adoptNode(newNode); document.appendChild(newNode); } return document; }
From source file:gov.nih.nci.cagrid.opensaml.SAMLObject.java
/** * Transforms the object into a DOM tree using an existing document context * * @param doc A Document object to use in manufacturing the tree * @param xmlns Include namespace(s) on root element? * @return Root element node of the DOM tree capturing the object * @exception SAMLException Raised if the object is incompletely defined */// w w w.ja va 2 s .c om public Node toDOM(Document doc, boolean xmlns) throws SAMLException { checkValidity(); if (root != null) { if (!dirty) { // If the DOM tree is already generated, compare the Documents. if (root.getOwnerDocument() != doc) { // We already built a tree. Just adopt it into the new document. return root = doc.adoptNode(root); } return root; } // Dirty, so we need a new root element. log.debug("toDOM() detected object changes, rebuilding tree"); } return root = buildRoot(doc, xmlns); }
From source file:de.ingrid.interfaces.csw.server.impl.GenericServer.java
@Override public Document process(GetRecordByIdRequest request) throws CSWException { try {/*from ww w . j av a 2 s . c om*/ CSWQuery query = request.getQuery(); CSWRecordResults result = this.searcher.search(query); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setNamespaceAware(true); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); DOMImplementation domImpl = docBuilder.getDOMImplementation(); Document doc = domImpl.createDocument(RESPONSE_NAMESPACE, "csw:GetRecordByIdResponse", null); if (result.getResults() != null) { Element rootElement = doc.getDocumentElement(); for (CSWRecord record : result.getResults()) { Node recordNode = record.getDocument().getFirstChild(); doc.adoptNode(recordNode); rootElement.appendChild(recordNode); } } return doc; } catch (CSWException ex) { log.error("An error occured processing GetRecordByIdRequest", ex); throw ex; } catch (Exception ex) { log.error("An error occured processing GetRecordByIdRequest", ex); throw new CSWException("An error occured processing GetRecordByIdRequest"); } }
From source file:cz.incad.kramerius.service.replication.ExternalReferencesFormat.java
private void changeDatastreamVersion(Document document, Element datastream, Element version, URL url) throws IOException { InputStream is = null;/*w ww .j a v a 2s.c o m*/ try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); URLConnection urlConnection = url.openConnection(); is = urlConnection.getInputStream(); IOUtils.copyStreams(is, bos); version.setAttribute("SIZE", "" + bos.size()); version.removeChild(XMLUtils.findElement(version, "contentLocation", version.getNamespaceURI())); Element binaryContent = document.createElementNS(version.getNamespaceURI(), "binaryContent"); document.adoptNode(binaryContent); binaryContent.setTextContent(new String(Base64.encodeBase64(bos.toByteArray()))); version.appendChild(binaryContent); datastream.setAttribute("CONTROL_GROUP", "M"); } finally { IOUtils.tryClose(is); } }
From source file:com.rest4j.generator.Generator.java
public void generate() throws Exception { ApiFactory fac = new ApiFactory(apiXml, null, null); for (String className : preprocessors) { Preprocessor p = (Preprocessor) Class.forName(className).newInstance(); fac.addPreprocessor(p);//ww w . ja va2s .c o m } Document xml = fac.getDocument(); preprocess(xml); URL url = getStylesheet(); String filename = "index.html"; for (TemplateParam param : params) { if (param.getName().equals("filename")) { filename = param.getValue(); } } Document doc = transform(xml, url); cleanupBeforePostprocess(doc.getDocumentElement()); if (postprocessingXSLT != null) { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document composed = documentBuilder.newDocument(); org.w3c.dom.Element top = composed.createElementNS("http://rest4j.com/api-description", "top"); composed.appendChild(top); top.appendChild(composed.adoptNode(xml.getDocumentElement())); top.appendChild(composed.adoptNode(doc.getDocumentElement())); xml = null; doc = null; // free some mem doc = transform(composed, postprocessingXSLT); } if ("files".equals(doc.getDocumentElement().getLocalName())) { // break the result into files for (Node child : Util.it(doc.getDocumentElement().getChildNodes())) { if ("file".equals(child.getLocalName())) { if (child.getAttributes().getNamedItem("name") == null) { throw new IllegalArgumentException("Attribute name not found in <file>"); } String name = child.getAttributes().getNamedItem("name").getTextContent(); File file = new File(outputDir, name); file.getParentFile().mkdirs(); System.out.println("Write " + file.getAbsolutePath()); Attr copyFromAttr = (Attr) child.getAttributes().getNamedItem("copy-from"); if (copyFromAttr == null) { cleanupFinal((Element) child); if (child.getAttributes().getNamedItem("text") != null) { // plain-text output FileOutputStream fos = new FileOutputStream(file); try { IOUtils.write(child.getTextContent(), fos, "UTF-8"); } finally { IOUtils.closeQuietly(fos); } } else { output(child, file); } } else { String copyFrom = copyFromAttr.getValue(); URL asset = getClass().getClassLoader().getResource(copyFrom); if (asset == null) { asset = getClass().getResource(copyFrom); } if (asset == null) { File assetFile = new File(copyFrom); if (!assetFile.canRead()) { if (postprocessingXSLT != null) { asset = new URL(postprocessingXSLT, copyFrom); try { asset.openStream().close(); } catch (FileNotFoundException fnfe) { asset = null; } } if (asset == null) { asset = new URL(getStylesheet(), copyFrom); try { asset.openStream().close(); } catch (FileNotFoundException fnfe) { asset = null; } } if (asset == null) throw new IllegalArgumentException("File '" + copyFrom + "' specified by @copy-from not found in the classpath or filesystem"); } else { asset = assetFile.toURI().toURL(); } } InputStream is = asset.openStream(); OutputStream fos = new FileOutputStream(file); try { IOUtils.copy(is, fos); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } } } else if (child.getNodeType() == Node.ELEMENT_NODE) { throw new IllegalArgumentException("Something but <file> found inside <files>"); } } } else { File file = new File(outputDir, filename); System.out.println("Write " + file.getAbsolutePath()); cleanupFinal(doc.getDocumentElement()); DOMSource source = new DOMSource(doc); FileOutputStream fos = new FileOutputStream(file); try { StreamResult result = new StreamResult(fos); Transformer trans = tFactory.newTransformer(); trans.transform(source, result); } finally { IOUtils.closeQuietly(fos); } } }