List of usage examples for javax.xml.transform.dom DOMResult getNode
public Node getNode()
From source file:org.apache.ode.utils.DOMUtils.java
/** * Parse an XML document located using an {@link InputSource} using the * pooled document builder.//w w w .j a v a2 s.c o m */ public static Document sourceToDOM(Source inputSource) throws IOException { try { /* // Requires JDK 1.6+ if (inputSource instanceof StAXSource) { StAXSource stax = (StAXSource) inputSource; //if (stax.getXMLEventReader() != null || sax.getXMLStreamReader() != null) { if (sax.getXMLStreamReader() != null) { return parse(stax.getXMLStreamReader()); } } */ if (inputSource instanceof SAXSource) { InputSource sax = ((SAXSource) inputSource).getInputSource(); if (sax.getCharacterStream() != null || sax.getByteStream() != null) { return parse(((SAXSource) inputSource).getInputSource()); } } if (inputSource instanceof DOMSource) { Node node = ((DOMSource) inputSource).getNode(); if (node != null) { return toDOMDocument(node); } } if (inputSource instanceof StreamSource) { StreamSource stream = (StreamSource) inputSource; if (stream.getReader() != null || stream.getInputStream() != null) { return toDocumentFromStream((StreamSource) inputSource); } } DOMResult domresult = new DOMResult(newDocument()); Transformer txer = getTransformer(); txer.transform(inputSource, domresult); return (Document) domresult.getNode(); } catch (SAXException e) { throwIOException(e); } catch (TransformerException e) { throwIOException(e); } throw new IllegalArgumentException("Cannot parse XML source: " + inputSource.getClass()); }
From source file:org.apache.ode.utils.xsl.XslTransformHandler.java
/** * Transforms a Source document to a result using the XSL stylesheet referenced * by the provided URI. The stylesheet MUST have been parsed previously. * @param uri referencing the stylesheet * @param source XML document//from w w w . j av a2 s.co m * @param parameters passed to the stylesheet * @param resolver used to resolve includes and imports * @return result of the transformation (XSL, HTML or text depending of the output method specified in stylesheet. */ public Object transform(QName processQName, URI uri, Source source, Map<QName, Object> parameters, URIResolver resolver) { Templates tm; synchronized (_templateCache) { tm = (Templates) _templateCache.get(processQName, uri); } if (tm == null) throw new XslTransformException("XSL sheet" + uri + " has not been parsed before transformation!"); try { Transformer tf = tm.newTransformer(); tf.setURIResolver(resolver); if (parameters != null) { for (Map.Entry<QName, Object> param : parameters.entrySet()) { tf.setParameter(param.getKey().getLocalPart(), param.getValue()); } } String method = tf.getOutputProperties().getProperty("method"); if (method == null || "xml".equals(method)) { DOMResult result = new DOMResult(); tf.transform(source, result); Node node = result.getNode(); if (node.getNodeType() == Node.DOCUMENT_NODE) node = ((Document) node).getDocumentElement(); if (__log.isDebugEnabled()) __log.debug("Returned node: type=" + node.getNodeType() + ", " + DOMUtils.domToString(node)); return node; } else { // text and html outputs are handled the same way StringWriter writerResult = new StringWriter(); StreamResult result = new StreamResult(writerResult); tf.transform(source, result); writerResult.flush(); String output = writerResult.toString(); if (__log.isDebugEnabled()) __log.debug("Returned string: " + output); return output; } } catch (TransformerConfigurationException e) { throw new XslTransformException(e); } catch (TransformerException e) { throw new XslTransformException("XSL Transformation failed!", e); } }
From source file:org.apache.solr.handler.loader.XMLLoader.java
@Override public void load(SolrQueryRequest req, SolrQueryResponse rsp, ContentStream stream, UpdateRequestProcessor processor) throws Exception { final String charset = ContentStreamBase.getCharsetFromContentType(stream.getContentType()); InputStream is = null;//from w w w . j a v a2 s . c o m XMLStreamReader parser = null; String tr = req.getParams().get(CommonParams.TR, null); if (tr != null) { final Transformer t = getTransformer(tr, req); final DOMResult result = new DOMResult(); // first step: read XML and build DOM using Transformer (this is no overhead, as XSL always produces // an internal result DOM tree, we just access it directly as input for StAX): try { is = stream.getStream(); final InputSource isrc = new InputSource(is); isrc.setEncoding(charset); final XMLReader xmlr = saxFactory.newSAXParser().getXMLReader(); xmlr.setErrorHandler(xmllog); xmlr.setEntityResolver(EmptyEntityResolver.SAX_INSTANCE); final SAXSource source = new SAXSource(xmlr, isrc); t.transform(source, result); } catch (TransformerException te) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, te.getMessage(), te); } finally { IOUtils.closeQuietly(is); } // second step: feed the intermediate DOM tree into StAX parser: try { parser = inputFactory.createXMLStreamReader(new DOMSource(result.getNode())); this.processUpdate(req, processor, parser); } catch (XMLStreamException e) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e.getMessage(), e); } finally { if (parser != null) parser.close(); } } // Normal XML Loader else { try { is = stream.getStream(); if (log.isTraceEnabled()) { final byte[] body = IOUtils.toByteArray(is); // TODO: The charset may be wrong, as the real charset is later // determined by the XML parser, the content-type is only used as a hint! log.trace("body", new String(body, (charset == null) ? ContentStreamBase.DEFAULT_CHARSET : charset)); IOUtils.closeQuietly(is); is = new ByteArrayInputStream(body); } parser = (charset == null) ? inputFactory.createXMLStreamReader(is) : inputFactory.createXMLStreamReader(is, charset); this.processUpdate(req, processor, parser); } catch (XMLStreamException e) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e.getMessage(), e); } finally { if (parser != null) parser.close(); IOUtils.closeQuietly(is); } } }
From source file:org.apache.solr.handler.XsltXMLLoader.java
@Override public void load(SolrQueryRequest req, SolrQueryResponse rsp, ContentStream stream) throws Exception { final DOMResult result = new DOMResult(); final Transformer t = getTransformer(req); InputStream is = null;//from w ww .j a v a2 s . c o m XMLStreamReader parser = null; // first step: read XML and build DOM using Transformer (this is no overhead, as XSL always produces // an internal result DOM tree, we just access it directly as input for StAX): try { is = stream.getStream(); final String charset = ContentStreamBase.getCharsetFromContentType(stream.getContentType()); final InputSource isrc = new InputSource(is); isrc.setEncoding(charset); final SAXSource source = new SAXSource(isrc); t.transform(source, result); } catch (TransformerException te) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, te.getMessage(), te); } finally { IOUtils.closeQuietly(is); } // second step feed the intermediate DOM tree into StAX parser: try { parser = inputFactory.createXMLStreamReader(new DOMSource(result.getNode())); this.processUpdate(processor, parser); } catch (XMLStreamException e) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e.getMessage(), e); } finally { if (parser != null) parser.close(); } }
From source file:org.apereo.portal.io.xml.JaxbPortalDataHandlerService.java
/** * Run the import/update process on the data *//*from w ww . j a va2s . c o m*/ protected final void importOrUpgradeData(String systemId, PortalDataKey portalDataKey, XMLEventReader xmlEventReader) { //See if there is a registered importer for the data, if so import final IDataImporter<Object> dataImporterExporter = this.portalDataImporters.get(portalDataKey); if (dataImporterExporter != null) { this.logger.debug("Importing: {}", getPartialSystemId(systemId)); final Object data = unmarshallData(xmlEventReader, dataImporterExporter); dataImporterExporter.importData(data); this.logger.info("Imported : {}", getPartialSystemId(systemId)); return; } //No importer, see if there is an upgrader, if so upgrade final IDataUpgrader dataUpgrader = this.portalDataUpgraders.get(portalDataKey); if (dataUpgrader != null) { this.logger.debug("Upgrading: {}", getPartialSystemId(systemId)); //Convert the StAX stream to a DOM node, due to poor JDK support for StAX with XSLT final Node sourceNode; try { sourceNode = xmlUtilities.convertToDom(xmlEventReader); } catch (XMLStreamException e) { throw new RuntimeException("Failed to create StAXSource from original XML reader", e); } final DOMSource source = new DOMSource(sourceNode); final DOMResult result = new DOMResult(); final boolean doImport = dataUpgrader.upgradeData(source, result); if (doImport) { //If the upgrader didn't handle the import as well wrap the result DOM in a new Source and start the import process over again final org.w3c.dom.Node node = result.getNode(); final PortalDataKey upgradedPortalDataKey = new PortalDataKey(node); if (this.logger.isTraceEnabled()) { this.logger.trace("Upgraded: " + getPartialSystemId(systemId) + " to " + upgradedPortalDataKey + "\n\nSource XML: \n" + XmlUtilitiesImpl.toString(source.getNode()) + "\n\nResult XML: \n" + XmlUtilitiesImpl.toString(node)); } else { this.logger.info("Upgraded: {} to {}", getPartialSystemId(systemId), upgradedPortalDataKey); } final DOMSource upgradedSource = new DOMSource(node, systemId); this.importData(upgradedSource, upgradedPortalDataKey); } else { this.logger.info("Upgraded and Imported: {}", getPartialSystemId(systemId)); } return; } //No importer or upgrader found, fail throw new IllegalArgumentException( "Provided data " + portalDataKey + " has no registered importer or upgrader support: " + systemId); }
From source file:org.codehaus.enunciate.modules.xfire.EnunciatedJAXWSOperationBinding.java
public void readMessage(InMessage message, MessageContext context) throws XFireFault { if (this.requestInfo == null) { throw new XFireFault("Unable to read message: no request info was found!", XFireFault.RECEIVER); }// w w w . j ava2 s .c o m Object bean; try { Unmarshaller unmarshaller = this.jaxbContext.createUnmarshaller(); XMLStreamReader streamReader = message.getXMLStreamReader(); if (this.requestInfo.isSchemaValidate()) { try { TransformerFactory xformFactory = TransformerFactory.newInstance(); DOMResult domResult = new DOMResult(); xformFactory.newTransformer().transform(new StAXSource(streamReader, true), domResult); unmarshaller.getSchema().newValidator().validate(new DOMSource(domResult.getNode())); streamReader = XMLInputFactory.newInstance() .createXMLStreamReader(new DOMSource(domResult.getNode())); } catch (Exception e) { throw new XFireRuntimeException("Unable to validate the request against the schema."); } } unmarshaller.setEventHandler(getValidationEventHandler()); unmarshaller.setAttachmentUnmarshaller(new AttachmentUnmarshaller(context)); bean = unmarshaller.unmarshal(streamReader, this.requestInfo.getBeanClass()).getValue(); } catch (JAXBException e) { throw new XFireRuntimeException("Unable to unmarshal type.", e); } List<Object> parameters = new ArrayList<Object>(); if (this.requestInfo.isBare()) { //bare method, doesn't need to be unwrapped. parameters.add(bean); } else { for (PropertyDescriptor descriptor : this.requestInfo.getPropertyOrder()) { try { parameters.add(descriptor.getReadMethod().invoke(bean)); } catch (IllegalAccessException e) { throw new XFireFault("Problem with property " + descriptor.getName() + " on " + this.requestInfo.getBeanClass().getName() + ".", e, XFireFault.RECEIVER); } catch (InvocationTargetException e) { throw new XFireFault("Problem with property " + descriptor.getName() + " on " + this.requestInfo.getBeanClass().getName() + ".", e, XFireFault.RECEIVER); } } } message.setBody(parameters); }
From source file:org.commonjava.maven.galley.maven.parse.XMLInfrastructure.java
private Document fallbackParseDocument(String xml, final Object docSource, final Exception e) throws GalleyMavenXMLException { logger.debug(/*from ww w . ja v a2s . co m*/ "Failed to parse: {}. DOM error: {}. Trying STaX parse with IS_REPLACING_ENTITY_REFERENCES == false...", e, docSource, e.getMessage()); try { Source source; if (safeInputFactory != null) { xml = repairXmlDeclaration(xml); final XMLEventReader eventReader = safeInputFactory.createXMLEventReader(new StringReader(xml)); source = new StAXSource(eventReader); } else { // Deal with ø and other undeclared entities... xml = escapeNonXMLEntityRefs(xml); final XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setFeature("http://xml.org/sax/features/validation", false); source = new SAXSource(reader, new InputSource(new StringReader(xml))); } final DOMResult result = new DOMResult(); final Transformer transformer = newTransformer(); transformer.transform(source, result); return (Document) result.getNode(); } catch (final TransformerException e1) { throw new GalleyMavenXMLException("Failed to parse: %s. Transformer error: %s.\nOriginal DOM error: %s", e1, docSource, e1.getMessage(), e.getMessage()); } catch (final SAXException e1) { throw new GalleyMavenXMLException("Failed to parse: %s. SAX error: %s.\nOriginal DOM error: %s", e1, docSource, e1.getMessage(), e.getMessage()); } catch (final XMLStreamException e1) { throw new GalleyMavenXMLException("Failed to parse: %s. STaX error: %s.\nOriginal DOM error: %s", e1, docSource, e1.getMessage(), e.getMessage()); } }
From source file:org.docx4j.convert.out.fo.renderers.FORendererApacheFOP.java
@Override public void render(String foDocument, FOSettings settings, boolean twoPass, List<SectionPageInformation> pageNumberInformation, OutputStream outputStream) throws Docx4JException { String apacheFopConfiguration = setupApacheFopConfiguration(settings); String apacheFopMime = setupApacheFopMime(settings); StreamSource foDocumentSrc = new StreamSource(new StringReader(foDocument)); FopPlaceholderLookup placeholderLookup = null; FormattingResults formattingResults = null; FopFactory fopFactory = null;//from w ww . ja v a2 s . c om try { fopFactory = getFopFactory(apacheFopConfiguration); } catch (FOPException e) { throw new Docx4JException("Exception creating fop factory for rendering: " + e.getMessage(), e); } if (twoPass) { //1st pass in 2 pass log.debug("1st pass in 2 pass"); StartEvent startEvent = new StartEvent(settings.getWmlPackage(), WellKnownProcessSteps.FOP_RENDER_PASS1); startEvent.publish(); placeholderLookup = new FopPlaceholderLookup(pageNumberInformation); formattingResults = calcResults(fopFactory, apacheFopMime, foDocumentSrc, placeholderLookup); placeholderLookup.setResults(formattingResults); foDocumentSrc = new StreamSource(new StringReader(foDocument)); new EventFinished(startEvent).publish(); } //1st pass in 1 pass or 2nd pass in 2 pass if (TEXTBOX_POSTPROCESSING_REQUIRED) { // System.out.println("\n\n performing TEXTBOX_POSTPROCESSING \n\n"); DOMResult result = new DOMResult(); org.docx4j.XmlUtils.transform(foDocumentSrc, xslt_POSTPROCESSING, null, result); org.w3c.dom.Document docResult = ((org.w3c.dom.Document) result.getNode()); String modifiedFO = XmlUtils.w3CDomNodeToString(docResult); log.debug("After moving! \n" + modifiedFO); foDocumentSrc = new StreamSource(new StringReader(modifiedFO)); } StartEvent startEvent = new StartEvent(settings.getWmlPackage(), WellKnownProcessSteps.FOP_RENDER_PASS1); startEvent.publish(); render(fopFactory, apacheFopMime, foDocumentSrc, placeholderLookup, outputStream); new EventFinished(startEvent).publish(); }
From source file:org.docx4j.openpackaging.parts.JaxbXmlPartXPathAware.java
/** * Unmarshal XML data from the specified InputStream and return the * resulting content tree. Validation event location information may * be incomplete when using this form of the unmarshal API. * * <p>// w w w. j a v a2 s. com * Implements <a href="#unmarshalGlobal">Unmarshal Global Root Element</a>. * * @param is the InputStream to unmarshal XML data from * @return the newly created root object of the java content tree * * @throws JAXBException * If any unexpected errors occur while unmarshalling */ @Override public E unmarshal(java.io.InputStream is) throws JAXBException { try { log.debug("For " + this.getClass().getName() + ", unmarshall via binder"); // InputStream to Document org.w3c.dom.Document doc = XmlUtils.getNewDocumentBuilder().parse(is); // binder = jc.createBinder(); log.debug("info: " + binder.getClass().getName()); JaxbValidationEventHandler eventHandler = new JaxbValidationEventHandler(); eventHandler.setContinue(false); binder.setEventHandler(eventHandler); try { unwrapUsually(binder, doc); // unlikely to need this in the code below } catch (Exception ue) { if (ue instanceof UnmarshalException) { // Usually.. } else { // eg java.lang.NumberFormatException log.warn(ue.getMessage(), ue); } if (is.markSupported()) { // When reading from zip, we use a ByteArrayInputStream, // which does support this. log.info("encountered unexpected content in " + this.getPartName() + "; pre-processing"); /* Always try our preprocessor, since if what is first encountered is * eg: * <w14:glow w14:rad="101600"> ... * * the error would be: * * unexpected element (uri:"http://schemas.microsoft.com/office/word/2010/wordml", local:"glow") * * but there could well be mc:AlternateContent somewhere * further down in the document. */ // mimic docx4j 2.7.0 and earlier behaviour; this will // drop w14:glow etc; the preprocessor doesn't need to // do that eventHandler.setContinue(true); // There is no JAXBResult(binder), // so use a DOMResult result = new DOMResult(); Templates mcPreprocessorXslt = JaxbValidationEventHandler.getMcPreprocessor(); XmlUtils.transform(doc, mcPreprocessorXslt, null, result); doc = (org.w3c.dom.Document) result.getNode(); try { jaxbElement = (E) XmlUtils.unwrap(binder.unmarshal(doc)); } catch (ClassCastException cce) { /* * Work around for issue with JAXB binder, in Java 1.6 * encountered with /src/test/resources/jaxb-binder-issue.docx * See http://old.nabble.com/BinderImpl.associativeUnmarshal-ClassCastException-casting-to-JAXBElement-td32456585.html * and http://java.net/jira/browse/JAXB-874 * * java.lang.ClassCastException: org.docx4j.wml.PPr cannot be cast to javax.xml.bind.JAXBElement at com.sun.xml.internal.bind.v2.runtime.ElementBeanInfoImpl$IntercepterLoader.intercept(Unknown Source) at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.endElement(Unknown Source) at com.sun.xml.internal.bind.v2.runtime.unmarshaller.InterningXmlVisitor.endElement(Unknown Source) at com.sun.xml.internal.bind.v2.runtime.unmarshaller.SAXConnector.endElement(Unknown Source) at com.sun.xml.internal.bind.unmarshaller.DOMScanner.visit(Unknown Source) at com.sun.xml.internal.bind.unmarshaller.DOMScanner.visit(Unknown Source) at com.sun.xml.internal.bind.unmarshaller.DOMScanner.visit(Unknown Source) at com.sun.xml.internal.bind.unmarshaller.DOMScanner.visit(Unknown Source) at com.sun.xml.internal.bind.unmarshaller.DOMScanner.visit(Unknown Source) at com.sun.xml.internal.bind.unmarshaller.DOMScanner.visit(Unknown Source) at com.sun.xml.internal.bind.unmarshaller.DOMScanner.visit(Unknown Source) at com.sun.xml.internal.bind.unmarshaller.DOMScanner.visit(Unknown Source) at com.sun.xml.internal.bind.unmarshaller.DOMScanner.visit(Unknown Source) at com.sun.xml.internal.bind.unmarshaller.DOMScanner.scan(Unknown Source) at com.sun.xml.internal.bind.unmarshaller.DOMScanner.scan(Unknown Source) at com.sun.xml.internal.bind.unmarshaller.DOMScanner.scan(Unknown Source) at com.sun.xml.internal.bind.v2.runtime.BinderImpl.associativeUnmarshal(Unknown Source) at com.sun.xml.internal.bind.v2.runtime.BinderImpl.unmarshal(Unknown Source) at org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart.unmarshal(MainDocumentPart.java:321) */ log.warn("Binder not available for this docx"); Unmarshaller u = jc.createUnmarshaller(); jaxbElement = (E) XmlUtils.unwrap(u.unmarshal(doc)); } } else { log.warn("problem in " + this.getPartName()); log.warn(ue.getMessage(), ue); log.warn(".. and mark not supported"); throw ue; } } return jaxbElement; } catch (Exception e) { // e.printStackTrace(); // return null; /* java.lang.NullPointerException at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDProcessor.startDTD(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDTDScannerImpl.scanDTDInternalSubset(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$DTDDriver.dispatch(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$DTDDriver.next(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(Unknown Source) */ for (int i = 0; i < e.getStackTrace().length; i++) { if (e.getStackTrace()[i].getClassName().contains("DTD") || e.getStackTrace()[i].getMethodName().contains("DTD")) { // Mimic Word 2010 message throw new JAXBException("DTD is prohibited", e); } } throw new JAXBException(e.getMessage(), e); } }
From source file:org.docx4j.openpackaging.parts.JaxbXmlPartXPathAware.java
/** * @since 2.7.1//from w w w .ja va2s.c o m */ @Override public E unmarshal(org.w3c.dom.Element el) throws JAXBException { try { log.debug("For " + this.getClass().getName() + ", unmarshall via binder"); binder = jc.createBinder(); JaxbValidationEventHandler eventHandler = new JaxbValidationEventHandler(); eventHandler.setContinue(false); binder.setEventHandler(eventHandler); try { // jaxbElement = (E) XmlUtils.unwrap(binder.unmarshal( el )); unwrapUsually(binder, el); // unlikely to need this in the code below } catch (Exception ue) { if (ue instanceof UnmarshalException) { // Usually.. } else { // eg java.lang.NumberFormatException log.warn(ue.getMessage(), ue); log.info(".. can recover if problem is w:tblW/@w:w"); } log.info("encountered unexpected content; pre-processing"); org.w3c.dom.Document doc = null; try { if (el instanceof org.w3c.dom.Document) { doc = (org.w3c.dom.Document) el; } else { // Hope for the best. Dodgy though; what if this is // being used on something deep in the tree? // TODO: revisit doc = el.getOwnerDocument(); } eventHandler.setContinue(true); DOMResult result = new DOMResult(); Templates mcPreprocessorXslt = JaxbValidationEventHandler.getMcPreprocessor(); XmlUtils.transform(doc, mcPreprocessorXslt, null, result); doc = (org.w3c.dom.Document) result.getNode(); jaxbElement = (E) XmlUtils.unwrap(binder.unmarshal(doc)); } catch (ClassCastException cce) { log.warn("Binder not available for this docx"); Unmarshaller u = jc.createUnmarshaller(); jaxbElement = (E) XmlUtils.unwrap(u.unmarshal(doc)); } catch (Exception e) { throw new JAXBException("Preprocessing exception", e); } } return jaxbElement; } catch (JAXBException e) { log.error(e.getMessage(), e); throw e; } }