List of usage examples for org.w3c.dom Document adoptNode
public Node adoptNode(Node source) throws DOMException;
From source file:org.apache.camel.component.xmlsecurity.api.XAdESSignatureProperties.java
protected Element createChildFromXmlFragmentOrText(Document doc, Input input, String localElementName, String errorMessage, String elementOrText) throws IOException, ParserConfigurationException, XmlSignatureException { String ending = localElementName + ">"; Element child;// w w w . ja v a2 s .c o m if (elementOrText.startsWith("<") && elementOrText.endsWith(ending)) { try { // assume xml InputSource source = new InputSource(new StringReader(elementOrText)); source.setEncoding("UTF-8"); Document parsedDoc = XmlSignatureHelper.newDocumentBuilder(Boolean.TRUE).parse(source); replacePrefixes(parsedDoc, input); child = (Element) doc.adoptNode(parsedDoc.getDocumentElement()); // check for correct namespace String ns = findNamespace(input.getMessage()); if (!ns.equals(child.getNamespaceURI())) { throw new XmlSignatureException(String.format( "The XAdES confguration is invalid. The root element '%s' of the provided XML fragment '%s' has the invalid namespace '%s'. The correct namespace is '%s'.", child.getLocalName(), elementOrText, child.getNamespaceURI(), ns)); } } catch (SAXException e) { throw new XmlSignatureException( String.format(errorMessage, elementOrText, localElementName, namespace), e); } } else { child = createElement(localElementName, doc, input); child.setTextContent(elementOrText); } return child; }
From source file:org.apache.padaf.xmpbox.SaveMetadataHelper.java
/** * Serialize a schema into an Output stream * /* w w w . ja v a2 s.c o m*/ * @param schema * Schema concerned by the serialization processing * @param os * Stream to save serialized schema * @throws TransformException * When couldn't parse data to XML/RDF */ public static void serialize(XMPSchema schema, OutputStream os) throws TransformException { try { Document doc = XMLUtil.newDocument(); Element rdf = doc.createElementNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf:RDF"); Node schemContent = schema.getElement().cloneNode(true); doc.adoptNode(schemContent); rdf.appendChild(schemContent); XMLUtil.save(rdf, os, "UTF-8"); } catch (TransformerException e) { throw new TransformException("Failed to parse defined XMP", e); } catch (IOException e) { throw new TransformException("Failed to create Document to contain Schema representation ", e); } }
From source file:org.apache.shindig.gadgets.servlet.CajaContentRewriter.java
public void rewrite(Gadget gadget, MutableContent mc) { if (!cajaEnabled(gadget)) return;//from w w w . j av a2 s . co m GadgetContext gadgetContext = gadget.getContext(); boolean debug = gadgetContext.getDebug(); Document doc = mc.getDocument(); // Serialize outside of MutableContent, to prevent a re-parse. String docContent = HtmlSerialization.serialize(doc); String cacheKey = HashUtil.checksum(docContent.getBytes()); Node root = doc.createDocumentFragment(); root.appendChild(doc.getDocumentElement()); Node cajoledData = null; if (cajoledCache != null && !debug) { Element cajoledOutput = cajoledCache.getElement(cacheKey); if (cajoledOutput != null) { cajoledData = doc.adoptNode(cajoledOutput); createContainerFor(doc, cajoledData); mc.documentChanged(); } } if (cajoledData == null) { UriFetcher fetcher = makeFetcher(gadget); UriPolicy policy = makePolicy(gadget); URI javaGadgetUri = gadgetContext.getUrl().toJavaUri(); MessageQueue mq = new SimpleMessageQueue(); MessageContext context = new MessageContext(); PluginMeta meta = new PluginMeta(fetcher, policy); PluginCompiler compiler = makePluginCompiler(meta, mq); compiler.setMessageContext(context); if (debug) { // This will load cajita-debugmode.js gadget.addFeature("caja-debug"); compiler.setGoals(compiler.getGoals().without(PipelineMaker.ONE_CAJOLED_MODULE) .with(PipelineMaker.ONE_CAJOLED_MODULE_DEBUG)); } InputSource is = new InputSource(javaGadgetUri); boolean safe = false; compiler.addInput(new Dom(root), javaGadgetUri); try { if (!compiler.run()) { throw new GadgetRewriteException("Gadget has compile errors"); } StringBuilder scriptBody = new StringBuilder(); CajoledModule cajoled = compiler.getJavascript(); TokenConsumer tc = debug ? new JsPrettyPrinter(new Concatenator(scriptBody)) : new JsMinimalPrinter(new Concatenator(scriptBody)); cajoled.render(new RenderContext(tc).withAsciiOnly(true).withEmbeddable(true)); tc.noMoreTokens(); Node html = compiler.getStaticHtml(); Element script = doc.createElementNS(Namespaces.HTML_NAMESPACE_URI, "script"); script.setAttributeNS(Namespaces.HTML_NAMESPACE_URI, "type", "text/javascript"); script.appendChild(doc.createTextNode(scriptBody.toString())); Element cajoledOutput = doc.createElement("div"); cajoledOutput.setAttribute("id", "cajoled-output"); cajoledOutput.setAttribute("classes", "g___"); cajoledOutput.setAttribute("style", "position: relative;"); cajoledOutput.appendChild(doc.adoptNode(html)); cajoledOutput.appendChild(tameCajaClientApi(doc)); cajoledOutput.appendChild(doc.adoptNode(script)); Element messagesNode = formatErrors(doc, is, docContent, mq, /* is invisible */ false); cajoledOutput.appendChild(messagesNode); if (cajoledCache != null && !debug) { cajoledCache.addElement(cacheKey, cajoledOutput); } cajoledData = cajoledOutput; createContainerFor(doc, cajoledData); mc.documentChanged(); safe = true; HtmlSerialization.attach(doc, htmlSerializer, null); } catch (GadgetRewriteException e) { // There were cajoling errors // Content is only used to produce useful snippets with error messages createContainerFor(doc, formatErrors(doc, is, docContent, mq, true /* visible */)); logException(e, mq); safe = true; } finally { if (!safe) { // Fail safe mc.setContent(""); } } } }
From source file:org.cauldron.einstein.ri.core.model.data.xml.dom.DOMUtil.java
@Post @Pre//from w w w. j a v a 2s . c o m static DocumentFragment createDOMFromObject(List<DataObject> objects) { log.debug("Creating XMLDOM DataList."); DocumentBuilder docBuilder = null; try { docBuilder = docBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new DataConversionRuntimeException(e); } DocumentFragment fragment; Document doc = docBuilder.newDocument(); fragment = doc.createDocumentFragment(); for (DataObject dataObject : objects) { final XMLDOMDataObject object = (XMLDOMDataObject) EinsteinRIRuntimeFactory.getInstance().getRuntime() .getRosettaStone().convert(XMLDOMDataModel.class, dataObject); final Node node = object.getNode(); doc.adoptNode(node); fragment.appendChild(node); } return fragment; }
From source file:org.cauldron.einstein.ri.core.model.data.xml.dom.DOMUtil.java
@Post @Pre/*from ww w . j ava 2s .co m*/ public static DocumentFragment buildFragmentFromNodeList(DocumentBuilder docBuilder, NodeList nodeList) throws IOException, TransformerException, SAXException { Document doc; DocumentFragment fragment; /* I know this is convoluted but it's very difficult to actually add a bunch of random nodes to a document fragment without getting errors. This works by normalizing the nodes. */ ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byteArrayOutputStream.write("<dummy>".getBytes()); Transformer xformer = transformerFactory.newTransformer(); xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); for (int i = 0; i < nodeList.getLength(); i++) { Source source = new DOMSource(nodeList.item(i)); Result result = new StreamResult(byteArrayOutputStream); xformer.transform(source, result); } byteArrayOutputStream.write("</dummy>".getBytes()); log.debug("Dumy node {0}.", byteArrayOutputStream); doc = docBuilder.parse(new ByteArrayInputStream(byteArrayOutputStream.toByteArray())); fragment = doc.createDocumentFragment(); nodeList = doc.getDocumentElement().getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { log.debug("Moving temporary node."); final Node node = nodeList.item(i); doc.adoptNode(node); fragment.appendChild(node); } log.debug("Fragment is now {0}.", fragment); return fragment; }
From source file:org.cauldron.einstein.ri.core.model.data.xml.dom.DOMUtil.java
@Post @Pre//from w ww. jav a 2 s . co m public static DocumentFragment buildFragmentFromNode(DocumentBuilder docBuilder, Node node) throws IOException, TransformerException, SAXException { Document doc; DocumentFragment fragment; /* I know this is convoluted but it's very difficult to actually add a bunch of random nodes to a document fragment without getting errors. XML DOM APIs are bloomin sketchy so this guarantees that the node can be added. Need to throw this rubbish away and use a better XML API really. */ ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byteArrayOutputStream.write("<dummy>".getBytes()); Transformer xformer = transformerFactory.newTransformer(); xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); Source source = new DOMSource(node); Result result = new StreamResult(byteArrayOutputStream); xformer.transform(source, result); byteArrayOutputStream.write("</dummy>".getBytes()); log.debug("Dumy node {0}.", byteArrayOutputStream); doc = docBuilder.parse(new ByteArrayInputStream(byteArrayOutputStream.toByteArray())); fragment = doc.createDocumentFragment(); final Element element = doc.getDocumentElement(); if (element.hasChildNodes()) { //has child nodes, not text. NodeList nodeList = element.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { log.debug("Moving temporary node."); final Node newNode = nodeList.item(i); doc.adoptNode(newNode); fragment.appendChild(newNode); } } log.debug("Fragment is now {0}.", ReflectionToStringBuilder.reflectionToString(fragment)); return fragment; }
From source file:org.eclipse.packagedrone.repo.aspect.common.p2.internal.P2Unzipper.java
private void processMetaData(final Context context, final InputStream in, final String filename, final String xpath) throws Exception { // parse input final Document doc = this.xml.newDocumentBuilder().parse(new CloseShieldInputStream(in)); final XPathExpression path = this.xml.newXPathFactory().newXPath().compile(xpath); // filter/*from ww w .ja v a 2 s .c o m*/ final NodeList result = XmlHelper.executePath(doc, path); // write filtered output final Document fragmentDoc = this.xml.newDocumentBuilder().newDocument(); Node node = result.item(0); node = fragmentDoc.adoptNode(node); fragmentDoc.appendChild(node); // create artifact context.createVirtualArtifact(filename, out -> { try { XmlHelper.write(this.xml.newTransformerFactory(), fragmentDoc, new StreamResult(out)); } catch (final Exception e) { throw new IOException(e); } }, null); }
From source file:org.ojbc.intermediaries.sn.testutil.TestFaultMessageBuilderUtil.java
private void validateFaultResponse(String fault) throws Exception { Node faultResponse = XmlUtils.xPathNodeSearch(OJBUtils.loadXMLFromString(fault), "//subfltrsp-exch:SubscriptionFaultResponseMessage"); Assert.assertNotNull(faultResponse); DocumentBuilderFactory docBuilderFact = DocumentBuilderFactory.newInstance(); docBuilderFact.setNamespaceAware(true); DocumentBuilder docBuilder = docBuilderFact.newDocumentBuilder(); Document document = docBuilder.newDocument(); document.adoptNode(faultResponse); String iepdRootPath = "ssp/Subscription_Notification/information_model/Subscription_Response-IEPD/xsd"; XmlUtils.validateInstance(iepdRootPath, "Subscription_Fault_Response.xsd", document, new ResourceResolver(iepdRootPath)); }
From source file:org.unitedinternet.cosmo.dav.caldav.report.FreeBusyReport.java
@Override public Element toXml(Document document) { try {//from w w w . ja va 2s .co m if (getStream() == null) { runQuery(); } Document doc = DomUtil.parseDocument(getStream()); document.adoptNode(doc); return doc.getDocumentElement(); } catch (IOException | CosmoDavException | ParserConfigurationException | SAXException e) { throw new RuntimeException(e); } }
From source file:se.unlogic.hierarchy.core.servlets.CoreServlet.java
protected void processRequest(HttpServletRequest req, HttpServletResponse res, User user, URIParser uriParser) throws TransformerException, IOException { ForegroundModuleResponse moduleResponse = null; RequestException exception = null;// w w w . j a va2 s. c o m try { try { moduleResponse = this.rootSection.processRequest(req, res, user, uriParser, rootSection.getSectionDescriptor().getRequiredProtocol()); } catch (AccessDeniedException e) { if (user == null) { loginHandler.processLoginRequest(req, res, uriParser, true); } if (!res.isCommitted()) { throw e; } } } catch (RequestException e) { log.log(e.getPriority(), e.toString() + " Requested by user " + user + " accessing from " + req.getRemoteAddr(), e.getThrowable()); exception = e; } // Check if the response has been committed if (!res.isCommitted()) { // Set request attribute to tell the URLFilter to ignore this response req.setAttribute("processed", true); // Response has not been committed create xml document Document doc = XMLUtils.createDomDocument(); // Create root element Element document = doc.createElement("document"); doc.appendChild(document); if (exception != null) { // Append exception Element errors = doc.createElement("errors"); doc.getDocumentElement().appendChild(errors); errors.appendChild(exception.toXML(doc)); if (exception.getStatusCode() != null) { res.setStatus(exception.getStatusCode()); } this.appendLinks(doc, exception.getBackgroundModuleResponses()); this.appendScripts(doc, exception.getBackgroundModuleResponses()); this.addBackgroundModuleResponses(exception.getBackgroundModuleResponses(), doc, user, req); } else { // Check if the user has changed if (moduleResponse.isUserChanged()) { try { HttpSession session = req.getSession(false); if (session != null) { user = (User) session.getAttribute("user"); } } catch (IllegalStateException e) { user = null; } } if (moduleResponse.isExcludeSystemTransformation()) { doc = moduleResponse.getDocument(); document = doc.getDocumentElement(); } this.appendLinks(doc, moduleResponse); this.appendScripts(doc, moduleResponse); if (isValidResponse(moduleResponse)) { if (moduleResponse.getResponseType() == ResponseType.HTML) { // Append module html response Element moduleres = doc.createElement("moduleHTMLResponse"); document.appendChild(moduleres); moduleres.appendChild(doc.createCDATASection(moduleResponse.getHtml())); } else if (moduleResponse.getResponseType() == ResponseType.XML_FOR_CORE_TRANSFORMATION) { // Append module response Element moduleres = doc.createElement("moduleXMLResponse"); document.appendChild(moduleres); moduleres.appendChild(doc.adoptNode(moduleResponse.getElement())); } else if (moduleResponse.getResponseType() == ResponseType.XML_FOR_SEPARATE_TRANSFORMATION) { if (moduleResponse.getTransformer() != null) { // Write xml to debug file if xml debug output is enabled if (moduleXMLDebug && !StringUtils.isEmpty(moduleXMLDebugFile)) { this.log.debug("XML debug mode enabled, writing module XML to " + moduleXMLDebugFile + " for module " + moduleResponse.getModuleDescriptor()); try { XMLUtils.writeXMLFile(moduleResponse.getDocument(), this.applicationFileSystemPath + "WEB-INF/" + moduleXMLDebugFile, true, encoding); this.log.debug("Finished writing module XML to " + this.applicationFileSystemPath + "WEB-INF/" + moduleXMLDebugFile); } catch (Exception e) { this.log.error("Error writing module XML to " + this.applicationFileSystemPath + "WEB-INF/" + moduleXMLDebugFile, e); } } // Transform output try { this.log.debug("Module XML transformation starting"); if (moduleResponse.isExcludeSystemTransformation()) { // Set response parameters res.setContentType("text/html"); // Set standard HTTP/1.1 no-cache headers. res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, proxy-revalidate"); XMLTransformer.transformToWriter(moduleResponse.getTransformer(), doc, res.getWriter(), encoding); return; } else { StringWriter stringWriter = new StringWriter(); XMLTransformer.transformToWriter(moduleResponse.getTransformer(), moduleResponse.getDocument(), stringWriter, encoding); // Append module response Element moduleres = doc.createElement("moduleTransformedResponse"); document.appendChild(moduleres); this.log.debug("Module XML transformation finished, appending result..."); moduleres.appendChild(doc.createCDATASection(stringWriter.toString())); this.log.debug("Result appended"); } } catch (Exception e) { this.log.error("Tranformation of module response from module" + moduleResponse.getModuleDescriptor() + " failed, requested by user " + user + " accesing from " + req.getRemoteAddr(), e); Element errors = doc.createElement("errors"); document.appendChild(errors); Element separateTransformationFailedElement = doc .createElement("separateTransformationFailed"); errors.appendChild(separateTransformationFailedElement); separateTransformationFailedElement .appendChild(XMLUtils.createCDATAElement("exception", e.toString(), doc)); separateTransformationFailedElement .appendChild(moduleResponse.getModuleDescriptor().toXML(doc)); } } else { this.log.error( "Module response for separate transformation without attached stylesheet returned by module " + moduleResponse.getModuleDescriptor() + " requested by user " + user + " accesing from " + req.getRemoteAddr()); Element errors = doc.createElement("errors"); document.appendChild(errors); Element separateTransformationWithoutStylesheetElement = doc .createElement("separateTransformationWithoutStylesheet"); errors.appendChild(separateTransformationWithoutStylesheetElement); separateTransformationWithoutStylesheetElement .appendChild(moduleResponse.getModuleDescriptor().toXML(doc)); } } } else { // No response, append error this.log.error("Invalid module response from module" + moduleResponse.getModuleDescriptor() + ", requested by user " + user + " accesing from " + req.getRemoteAddr()); Element errors = doc.createElement("errors"); document.appendChild(errors); Element invalidModuleResonseElement = doc.createElement("invalidModuleResonse"); errors.appendChild(invalidModuleResonseElement); invalidModuleResonseElement.appendChild(moduleResponse.getModuleDescriptor().toXML(doc)); } this.addBackgroundModuleResponses(moduleResponse.getBackgroundModuleResponses(), doc, user, req); } XMLUtils.appendNewCDATAElement(doc, document, "version", VERSION); document.appendChild(RequestUtils.getRequestInfoAsXML(doc, req, uriParser, false, true)); // Append root section document.appendChild(this.rootSection.getSectionDescriptor().toXML(doc)); // Append userinfo and menuitems if (user != null) { document.appendChild(user.toXML(doc)); } //Get style sheet so that the correct menu type can be added CachedXSLTDescriptor xslDescriptor; if (this.xsltCacheHandler.getXslDescriptorCount() == 1) { //Only default stylesheet loaded, skip i18n support. xslDescriptor = this.xsltCacheHandler.getDefaultXsltDescriptor(); } else { Language language = this.getLanguage(req, user); String preferedDesign = this.getPreferedDesign(req, user); xslDescriptor = this.xsltCacheHandler.getBestMatchingXSLTDescriptor(language, preferedDesign); } Element menus = doc.createElement("menus"); document.appendChild(menus); if (moduleResponse != null) { if (moduleResponse.getTitle() != null) { document.appendChild(XMLUtils.createCDATAElement("title", moduleResponse.getTitle(), doc)); } if (xslDescriptor.usesFullMenu()) { menus.appendChild(rootSection.getFullMenu(user, uriParser).toXML(doc)); } else { if (moduleResponse.getMenu() != null) { menus.appendChild(moduleResponse.getMenu().toXML(doc)); } } if (!moduleResponse.getBreadcrumbs().isEmpty()) { Element breadcrumbsElement = doc.createElement("breadcrumbs"); document.appendChild(breadcrumbsElement); for (Breadcrumb breadcrumb : moduleResponse.getBreadcrumbs()) { if (breadcrumb != null) { breadcrumbsElement.appendChild(breadcrumb.toXML(doc)); } } } } else if (exception != null) { if (xslDescriptor.usesFullMenu()) { menus.appendChild(rootSection.getFullMenu(user, uriParser).toXML(doc)); } else { if (exception.getMenu() != null) { menus.appendChild(exception.getMenu().toXML(doc)); } } //TODO add breadcrumbs to exceptions } // Write xml to debug file if xml debug output is enabled if (systemXMLDebug && !StringUtils.isEmpty(systemXMLDebugFile)) { this.log.debug("XML debug mode enabled, writing system XML to " + systemXMLDebugFile); try { FileWriter xmldebugstream = new FileWriter( new File(this.applicationFileSystemPath + "WEB-INF/" + systemXMLDebugFile)); XMLUtils.toString(doc, encoding, xmldebugstream, false); xmldebugstream.close(); this.log.debug("Finished writing system XML to " + this.applicationFileSystemPath + "WEB-INF/" + systemXMLDebugFile); } catch (Exception e) { this.log.error("Error writing system XML to " + this.applicationFileSystemPath + "WEB-INF/" + systemXMLDebugFile, e); } } // Set encoding res.setCharacterEncoding(encoding); // Set response parameters res.setContentType("text/html"); // Set standard HTTP/1.1 no-cache headers. res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, proxy-revalidate"); // Transform output try { this.log.debug("System XML transformation starting"); XMLTransformer.transformToWriter(xslDescriptor.getTransformer(), doc, res.getWriter(), encoding); this.log.debug("System XML transformation finished, response transformed and committed"); } catch (TransformerException e) { this.log.error("System XML transformation failed, " + e); throw e; } catch (IOException e) { if (!res.isCommitted()) { log.error("Error writing response", e); throw e; } else { this.log.debug("Response already committed"); } } catch (IllegalStateException e) { this.log.debug("Response already committed"); } } else { if (exception != null) { this.log.warn("Error " + exception + " after response has been committed"); } else { this.log.debug("Response already committed"); } } }