Java Examples for javax.xml.transform.dom.DOMResult

The following java examples will help you to understand the usage of javax.xml.transform.dom.DOMResult. These source code samples are taken from different open source projects.

Example 1
Project: SOCIETIES-Platform-master  File: W3CDomHandler.java View source code
public Element getElement(DOMResult r) {
    // JAXP spec is ambiguous about what really happens in this case,
    // so work defensively
    Node n = r.getNode();
    if (n instanceof Document) {
        return ((Document) n).getDocumentElement();
    }
    if (n instanceof Element)
        return (Element) n;
    if (n instanceof DocumentFragment)
        return (Element) n.getChildNodes().item(0);
    // That's why we throw a runtime exception.
    throw new IllegalStateException(n.toString());
}
Example 2
Project: aetheria-master  File: DOMUtils.java View source code
public static Node stringToNode(String s) {
    StreamSource ss = new StreamSource(new StringReader(s));
    DOMResult dr = new DOMResult();
    try {
        Transformer t = TransformerFactory.newInstance().newTransformer();
        t.transform(ss, dr);
    } catch (TransformerException te) {
        te.printStackTrace();
        return null;
    }
    return dr.getNode().getFirstChild();
}
Example 3
Project: ManagedRuntimeInitiative-master  File: W3CDomHandler.java View source code
public Element getElement(DOMResult r) {
    // JAXP spec is ambiguous about what really happens in this case,
    // so work defensively
    Node n = r.getNode();
    if (n instanceof Document) {
        return ((Document) n).getDocumentElement();
    }
    if (n instanceof Element)
        return (Element) n;
    if (n instanceof DocumentFragment)
        return (Element) n.getChildNodes().item(0);
    // That's why we throw a runtime exception.
    throw new IllegalStateException(n.toString());
}
Example 4
Project: classlib6-master  File: StreamHeader.java View source code
public void writeTo(SOAPMessage saaj) throws SOAPException {
    try {
        // TODO what about in-scope namespaces
        // Not very efficient consider implementing a stream buffer
        // processor that produces a DOM node from the buffer.
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer();
        XMLStreamBufferSource source = new XMLStreamBufferSource(_mark);
        DOMResult result = new DOMResult();
        t.transform(source, result);
        Node d = result.getNode();
        if (d.getNodeType() == Node.DOCUMENT_NODE)
            d = d.getFirstChild();
        SOAPHeader header = saaj.getSOAPHeader();
        Node node = header.getOwnerDocument().importNode(d, true);
        header.appendChild(node);
    } catch (Exception e) {
        throw new SOAPException(e);
    }
}
Example 5
Project: ikvm-openjdk-master  File: W3CDomHandler.java View source code
public Element getElement(DOMResult r) {
    // JAXP spec is ambiguous about what really happens in this case,
    // so work defensively
    Node n = r.getNode();
    if (n instanceof Document) {
        return ((Document) n).getDocumentElement();
    }
    if (n instanceof Element)
        return (Element) n;
    if (n instanceof DocumentFragment)
        return (Element) n.getChildNodes().item(0);
    // That's why we throw a runtime exception.
    throw new IllegalStateException(n.toString());
}
Example 6
Project: openjdk-master  File: SourceReaderFactory.java View source code
public static XMLStreamReader createSourceReader(Source source, boolean rejectDTDs, String charsetName) {
    try {
        if (source instanceof StreamSource) {
            StreamSource streamSource = (StreamSource) source;
            InputStream is = streamSource.getInputStream();
            if (is != null) {
                // Wrap input stream in Reader if charset is specified
                if (charsetName != null) {
                    return XMLStreamReaderFactory.create(source.getSystemId(), new InputStreamReader(is, charsetName), rejectDTDs);
                } else {
                    return XMLStreamReaderFactory.create(source.getSystemId(), is, rejectDTDs);
                }
            } else {
                Reader reader = streamSource.getReader();
                if (reader != null) {
                    return XMLStreamReaderFactory.create(source.getSystemId(), reader, rejectDTDs);
                } else {
                    return XMLStreamReaderFactory.create(source.getSystemId(), new URL(source.getSystemId()).openStream(), rejectDTDs);
                }
            }
        } else if (source.getClass() == fastInfosetSourceClass) {
            return FastInfosetUtil.createFIStreamReader((InputStream) fastInfosetSource_getInputStream.invoke(source));
        } else if (source instanceof DOMSource) {
            DOMStreamReader dsr = new DOMStreamReader();
            dsr.setCurrentNode(((DOMSource) source).getNode());
            return dsr;
        } else if (source instanceof SAXSource) {
            // TODO: need SAX to StAX adapter here -- Use transformer for now
            Transformer tx = XmlUtil.newTransformer();
            DOMResult domResult = new DOMResult();
            tx.transform(source, domResult);
            return createSourceReader(new DOMSource(domResult.getNode()), rejectDTDs);
        } else {
            throw new XMLReaderException("sourceReader.invalidSource", source.getClass().getName());
        }
    } catch (Exception e) {
        throw new XMLReaderException(e);
    }
}
Example 7
Project: ArchStudio5-master  File: SchematronTester.java View source code
public void runTest() throws SchematronInitializationException, SchematronTestException {
    DOMSource metastylesheetSource = SchematronUtils.getSchematronMetastylesheet();
    Transformer transformer1 = SchematronUtils.getTransformer(metastylesheetSource);
    DOMSource rulesFileSource = null;
    Document doc = testFile.getDocument();
    rulesFileSource = new DOMSource(doc);
    DOMResult tempStylesheetResult = SchematronUtils.getEmptyDOMResult();
    try {
        transformer1.transform(rulesFileSource, tempStylesheetResult);
    } catch (TransformerException te) {
        throw new SchematronTestException(te);
    }
    DOMSource tempStylesheetSource = new DOMSource(tempStylesheetResult.getNode());
    Transformer transformer2 = SchematronUtils.getTransformer(tempStylesheetSource);
    DOMSource documentToTestSource = null;
    try {
        StringReader r = new StringReader(xmlDocumentToTest);
        Document docToTest = SchematronUtils.parseToDocument(r);
        r.close();
        documentToTestSource = new DOMSource(docToTest);
    } catch (ParserConfigurationException pce) {
        throw new SchematronTestException(pce);
    } catch (SAXException se) {
        throw new SchematronTestException(se);
    } catch (IOException ioe) {
        throw new SchematronTestException(ioe);
    }
    DOMResult finalResult = SchematronUtils.getEmptyDOMResult();
    try {
        transformer2.transform(documentToTestSource, finalResult);
        this.result = (Document) finalResult.getNode();
    } catch (TransformerException te) {
        throw new SchematronTestException(te);
    }
}
Example 8
Project: eclipselink.runtime-master  File: DocumentPreservationFragmentTestCases.java View source code
public void testMarshalFragmentToDOMResult() throws Exception {
    InputStream inputStream = ClassLoader.getSystemResourceAsStream("org/eclipse/persistence/testing/oxm/documentpreservation/missing_element_result_no_header.xml");
    byte[] bytes = new byte[inputStream.available()];
    inputStream.read(bytes);
    Document sourceDocument = parse("org/eclipse/persistence/testing/oxm/documentpreservation/missing_element_source.xml");
    Employee emp = (Employee) unmarshaller.unmarshal(sourceDocument);
    emp.setAddress(getNewAddress());
    Document document = parser.newDocument();
    DOMResult result = new DOMResult(document);
    marshaller.marshal(emp, result);
    String controlStringNoWS = removeWhiteSpaceFromString(new String(bytes));
    String writerStringNoWS = removeWhiteSpaceFromString("");
    log("\nWRITERSTRING:" + writerStringNoWS);
    log("CONTROLSTRING:" + controlStringNoWS);
    assertXMLIdentical(sourceDocument, document);
}
Example 9
Project: geoserver-2.0.x-master  File: XmlObjectEncodingResponseTest.java View source code
public void testEncode() throws Exception {
    Ows10Factory f = Ows10Factory.eINSTANCE;
    GetCapabilitiesType caps = f.createGetCapabilitiesType();
    AcceptVersionsType versions = f.createAcceptVersionsType();
    caps.setAcceptVersions(versions);
    versions.getVersion().add("1.0.0");
    versions.getVersion().add("1.1.0");
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    response.write(caps, output, null);
    Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    TransformerFactory.newInstance().newTransformer().transform(new StreamSource(new ByteArrayInputStream(output.toByteArray())), new DOMResult(d));
    assertEquals("ows:GetCapabilities", d.getDocumentElement().getNodeName());
    assertEquals(2, d.getElementsByTagName("ows:Version").getLength());
}
Example 10
Project: geoserver-master  File: XmlObjectEncodingResponseTest.java View source code
public void testEncode() throws Exception {
    Ows10Factory f = Ows10Factory.eINSTANCE;
    GetCapabilitiesType caps = f.createGetCapabilitiesType();
    AcceptVersionsType versions = f.createAcceptVersionsType();
    caps.setAcceptVersions(versions);
    versions.getVersion().add("1.0.0");
    versions.getVersion().add("1.1.0");
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    response.write(caps, output, null);
    Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    TransformerFactory.newInstance().newTransformer().transform(new StreamSource(new ByteArrayInputStream(output.toByteArray())), new DOMResult(d));
    assertEquals("ows:GetCapabilities", d.getDocumentElement().getNodeName());
    assertEquals(2, d.getElementsByTagName("ows:Version").getLength());
}
Example 11
Project: geoserver-old-master  File: XmlObjectEncodingResponseTest.java View source code
public void testEncode() throws Exception {
    Ows10Factory f = Ows10Factory.eINSTANCE;
    GetCapabilitiesType caps = f.createGetCapabilitiesType();
    AcceptVersionsType versions = f.createAcceptVersionsType();
    caps.setAcceptVersions(versions);
    versions.getVersion().add("1.0.0");
    versions.getVersion().add("1.1.0");
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    response.write(caps, output, null);
    Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    TransformerFactory.newInstance().newTransformer().transform(new StreamSource(new ByteArrayInputStream(output.toByteArray())), new DOMResult(d));
    assertEquals("ows:GetCapabilities", d.getDocumentElement().getNodeName());
    assertEquals(2, d.getElementsByTagName("ows:Version").getLength());
}
Example 12
Project: geoserver_trunk-master  File: XmlObjectEncodingResponseTest.java View source code
public void testEncode() throws Exception {
    Ows10Factory f = Ows10Factory.eINSTANCE;
    GetCapabilitiesType caps = f.createGetCapabilitiesType();
    AcceptVersionsType versions = f.createAcceptVersionsType();
    caps.setAcceptVersions(versions);
    versions.getVersion().add("1.0.0");
    versions.getVersion().add("1.1.0");
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    response.write(caps, output, null);
    Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    TransformerFactory.newInstance().newTransformer().transform(new StreamSource(new ByteArrayInputStream(output.toByteArray())), new DOMResult(d));
    assertEquals("ows:GetCapabilities", d.getDocumentElement().getNodeName());
    assertEquals(2, d.getElementsByTagName("ows:Version").getLength());
}
Example 13
Project: j-road-master  File: StandardXRoadConsumerCallback.java View source code
@Override
public void doWithMessage(WebServiceMessage request) throws IOException, TransformerException {
    SaajSoapMessage message = (SaajSoapMessage) request;
    SOAPMessage mes = message.getSaajMessage();
    try {
        mes.getSOAPPart().getEnvelope().addNamespaceDeclaration(StandardXRoadConsumer.ROOT_NS, metadata.getRequestElementNs());
        getMarshaller().marshal(object, new DOMResult(mes.getSOAPBody()));
    } catch (SOAPException e) {
        throw new RuntimeException("Invalid SOAP message");
    }
    callback.doWithMessage(request);
}
Example 14
Project: liferay-portal-master  File: SampleHandler.java View source code
@Override
public boolean handleMessage(LogicalMessageContext logicalMessageContext) {
    try {
        boolean outboundMessage = (boolean) logicalMessageContext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
        if (!outboundMessage) {
            return true;
        }
        LogicalMessage logicalMessage = logicalMessageContext.getMessage();
        Transformer transformer = _transformerFactory.newTransformer(new StreamSource(_url.openStream()));
        DOMResult domResult = new DOMResult();
        transformer.transform(logicalMessage.getPayload(), domResult);
        logicalMessage.setPayload(new DOMSource(domResult.getNode()));
        return true;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 15
Project: OG-Platform-master  File: SchemaGenerator.java View source code
public static void main(String[] args) throws JAXBException, IOException {
    JAXBContext ctx = JAXBContext.newInstance(PortfolioDocumentV1_0.class);
    DOMResult result = extractSchemaResult(ctx);
    Document document = (Document) result.getNode();
    OutputFormat format = new OutputFormat(document);
    format.setIndenting(true);
    XMLSerializer serializer = new XMLSerializer(System.out, format);
    serializer.serialize(document);
}
Example 16
Project: service-prefetching-master  File: JaxbAdapter.java View source code
public Object marshal(Object o) throws Exception {
    if (o == null) {
        return null;
    }
    if (o instanceof SOAPEnvelope) {
        return WSClient.toElement(WSClient.toString((SOAPEnvelope) o));
    }
    Class<?> clazz = o.getClass();
    if (!contexts.containsKey(clazz)) {
        JAXBContext c = JAXBContext.newInstance(clazz);
        contexts.put(clazz, c);
    }
    JAXBContext c = contexts.get(clazz);
    DOMResult res = new DOMResult();
    c.createMarshaller().marshal(o, res);
    Element e = ((Document) res.getNode()).getDocumentElement();
    e.setAttribute("class", clazz.getCanonicalName());
    return e;
}
Example 17
Project: spring-ws-master  File: CommonsXsdSchemaCollectionTest.java View source code
@Test
public void testInlineComplex() throws Exception {
    Resource a = new ClassPathResource("A.xsd", AbstractXsdSchemaTestCase.class);
    collection.setXsds(a);
    collection.setInline(true);
    collection.afterPropertiesSet();
    XsdSchema[] schemas = collection.getXsdSchemas();
    Assert.assertEquals("Invalid amount of XSDs loaded", 2, schemas.length);
    Assert.assertEquals("Invalid target namespace", "urn:1", schemas[0].getTargetNamespace());
    Resource abc = new ClassPathResource("ABC.xsd", AbstractXsdSchemaTestCase.class);
    Document expected = documentBuilder.parse(SaxUtils.createInputSource(abc));
    DOMResult domResult = new DOMResult();
    transformer.transform(schemas[0].getSource(), domResult);
    assertXMLEqual("Invalid XSD generated", expected, (Document) domResult.getNode());
    Assert.assertEquals("Invalid target namespace", "urn:2", schemas[1].getTargetNamespace());
    Resource cd = new ClassPathResource("CD.xsd", AbstractXsdSchemaTestCase.class);
    expected = documentBuilder.parse(SaxUtils.createInputSource(cd));
    domResult = new DOMResult();
    transformer.transform(schemas[1].getSource(), domResult);
    assertXMLEqual("Invalid XSD generated", expected, (Document) domResult.getNode());
}
Example 18
Project: jaxb-master  File: ResultFactory.java View source code
/**
     * Factory method for producing {@link XmlSerializer} from {@link javax.xml.transform.Result}.
     *
     * This method supports {@link javax.xml.transform.sax.SAXResult},
     * {@link javax.xml.transform.stream.StreamResult}, and {@link javax.xml.transform.dom.DOMResult}.
     *
     * @param result the Result that will receive output from the XmlSerializer 
     * @return an implementation of XmlSerializer that will produce output on the supplied Result
     */
public static XmlSerializer createSerializer(Result result) {
    if (result instanceof SAXResult)
        return new SaxSerializer((SAXResult) result);
    if (result instanceof DOMResult)
        return new DomSerializer((DOMResult) result);
    if (result instanceof StreamResult)
        return new StreamSerializer((StreamResult) result);
    if (result instanceof TXWResult)
        return new TXWSerializer(((TXWResult) result).getWriter());
    throw new UnsupportedOperationException("Unsupported Result type: " + result.getClass().getName());
}
Example 19
Project: GeoBI-master  File: CustomXPathTest.java View source code
public void testXslt() throws TransformerException, IOException {
    final StringReader xsltStream = new StringReader("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n" + "                xmlns:xalan=\"http://xml.apache.org/xalan\"\n" + "                xmlns:custom=\"Custom\"\n" + "                version=\"1.0\">\n" + "  <xalan:component prefix=\"custom\" functions=\"factorArray\">\n" + "    <xalan:script lang=\"javaclass\" src=\"org.mapfish.print.CustomXPath\"/>\n" + "  </xalan:component>\n" + "  <xsl:template match=\"/*\">\n" + "    <tutu b=\"{custom:factorArray(@a,3)}\"/>\n" + "  </xsl:template>\n" + "</xsl:stylesheet>");
    final StringReader xmlStream = new StringReader("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<toto a=\"1,2,3\"/>");
    DOMResult transformedSvg = new DOMResult();
    final TransformerFactory factory = TransformerFactory.newInstance();
    javax.xml.transform.Transformer xslt = factory.newTransformer(new StreamSource(xsltStream));
    xslt.transform(new StreamSource(xmlStream), transformedSvg);
    Document doc = (Document) transformedSvg.getNode();
    Node main = doc.getFirstChild();
    assertEquals("tutu", main.getNodeName());
    final Node attrB = main.getAttributes().getNamedItem("b");
    assertNotNull(attrB);
    assertEquals("3,6,9", attrB.getNodeValue());
    xmlStream.close();
    xsltStream.close();
}
Example 20
Project: geronimo-specs-master  File: W3CDomHandler.java View source code
public Element getElement(DOMResult rt) {
    Node n = rt.getNode();
    if (n instanceof Document) {
        return ((Document) n).getDocumentElement();
    }
    if (n instanceof Element) {
        return (Element) n;
    }
    if (n instanceof DocumentFragment) {
        return (Element) n.getChildNodes().item(0);
    } else {
        throw new IllegalStateException(n.toString());
    }
}
Example 21
Project: hale-master  File: SchematronUtils.java View source code
/**
	 * Writes the content of the given {@link Result} into a
	 * {@link StringWriter}
	 * 
	 * @param result {@link Result} from {@link SchematronValidator} validation
	 * @param writer {@link StringWriter} to write report to
	 */
public static void convertValidatorResult(Result result, StringWriter writer) {
    if (result instanceof DOMResult) {
        convertResult((DOMResult) result, writer);
    } else if (result instanceof StreamResult) {
        convertResult((StreamResult) result, writer);
    } else {
        throw new RuntimeException(String.format("Could not evaluate Schematron validation result of type '%s'", result.getClass().getCanonicalName()));
    }
}
Example 22
Project: jboss-jaxb-api_spec-master  File: W3CDomHandler.java View source code
public Element getElement(DOMResult r) {
    // JAXP spec is ambiguous about what really happens in this case,
    // so work defensively
    Node n = r.getNode();
    if (n instanceof Document) {
        return ((Document) n).getDocumentElement();
    }
    if (n instanceof Element)
        return (Element) n;
    if (n instanceof DocumentFragment)
        return (Element) n.getChildNodes().item(0);
    // That's why we throw a runtime exception.
    throw new IllegalStateException(n.toString());
}
Example 23
Project: JDK-master  File: W3CDomHandler.java View source code
public Element getElement(DOMResult r) {
    // JAXP spec is ambiguous about what really happens in this case,
    // so work defensively
    Node n = r.getNode();
    if (n instanceof Document) {
        return ((Document) n).getDocumentElement();
    }
    if (n instanceof Element)
        return (Element) n;
    if (n instanceof DocumentFragment)
        return (Element) n.getChildNodes().item(0);
    // That's why we throw a runtime exception.
    throw new IllegalStateException(n.toString());
}
Example 24
Project: jlibs-master  File: ParseDOM.java View source code
@Override
protected void parsingCompleted(Exchange exchange, Message msg, AsyncXMLReader xmlReader) {
    TransformerHandler handler = (TransformerHandler) xmlReader.getContentHandler();
    DOMResult result = (DOMResult) handler.getTransformer().getParameter(DOMResult.class.getName());
    MediaType mt = msg.getPayload().getMediaType();
    String contentType = mt.withCharset(IOUtil.UTF_8.name()).toString();
    try {
        msg.setPayload(new DOMPayload(contentType, result.getNode(), false, -1));
    } catch (Throwable thr) {
        exchange.resume(thr);
        return;
    }
    super.parsingCompleted(exchange, msg, xmlReader);
}
Example 25
Project: picketlink-master  File: DOMTransformerTestCase.java View source code
@Test
public void testDOMTransformer() throws Exception {
    ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes());
    XMLEventReader xmlEventReader = StaxParserUtil.getXMLEventReader(bis);
    StartElement a = StaxParserUtil.getNextStartElement(xmlEventReader);
    StaxParserUtil.validate(a, "a");
    Document resultDocument = DocumentUtil.createDocument();
    DOMResult domResult = new DOMResult(resultDocument);
    // Let us parse <b><c><d> using transformer
    StAXSource source = new StAXSource(xmlEventReader);
    Transformer transformer = TransformerUtil.getStaxSourceToDomResultTransformer();
    transformer.transform(source, domResult);
    Document doc = (Document) domResult.getNode();
    Element elem = doc.getDocumentElement();
    assertEquals("b", elem.getLocalName());
    XMLEvent xmlEvent = xmlEventReader.nextEvent();
    assertTrue(xmlEvent instanceof EndElement);
    StaxParserUtil.validate((EndElement) xmlEvent, "a");
}
Example 26
Project: sd-dss-master  File: XsltConverter.java View source code
/**
     * @param xmlDom the xmlDom representing the report
     * @return a DOM XHTML standalone document.
     */
public Document renderAsHtml(XmlDom xmlDom) {
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    try {
        final InputStream xslStream = getXsltFileClasspathResource();
        Transformer transformer = transformerFactory.newTransformer(new StreamSource(xslStream));
        final DOMResult domResult = new DOMResult();
        final DOMSource xmlSource = new DOMSource(xmlDom.getRootElement().getOwnerDocument());
        transformer.transform(xmlSource, domResult);
        return (Document) domResult.getNode();
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    }
}
Example 27
Project: servicemix4-specs-master  File: W3CDomHandler.java View source code
public Element getElement(DOMResult rt) {
    Node n = rt.getNode();
    if (n instanceof Document) {
        return ((Document) n).getDocumentElement();
    }
    if (n instanceof Element) {
        return (Element) n;
    }
    if (n instanceof DocumentFragment) {
        return (Element) n.getChildNodes().item(0);
    } else {
        throw new IllegalStateException(n.toString());
    }
}
Example 28
Project: Smooks-for-Mule-master  File: TransformerTest.java View source code
public void testResultClass() {
    transformer.setConfigFile(smooksConfigFile);
    transformer.setResultType("RESULT");
    transformer.setResultClass("javax.xml.transform.dom.DOMResult");
    try {
        transformer.initialise();
    } catch (InitialisationException e) {
        logger.error("Initialisation Exception", e);
        fail("Should not have thrown A InitializationException");
    }
}
Example 29
Project: spring-integration-master  File: MarshallingTransformerParserTests.java View source code
@Test
public void testDefault() throws Exception {
    MessageChannel input = (MessageChannel) appContext.getBean("marshallingTransformerNoResultFactory");
    GenericMessage<Object> message = new GenericMessage<Object>("hello");
    input.send(message);
    Message<?> result = output.receive(0);
    assertTrue("Wrong payload type", result.getPayload() instanceof DOMResult);
    Document doc = (Document) ((DOMResult) result.getPayload()).getNode();
    assertEquals("Wrong payload", "hello", doc.getDocumentElement().getTextContent());
}
Example 30
Project: tesb-rt-se-master  File: SimpleEndpoint.java View source code
private EndpointReferenceType createEndpointReference(PropertiesTransformer transformer) {
    AttributedURIType endpoint = new AttributedURIType();
    endpoint.setValue(addr);
    EndpointReferenceType epr = new EndpointReferenceType();
    epr.setAddress(endpoint);
    if (props != null) {
        DOMResult result = new DOMResult();
        transformer.writePropertiesTo(props, result);
        Document docResult = (Document) result.getNode();
        MetadataType metadata = new MetadataType();
        epr.setMetadata(metadata);
        metadata.getAny().add(docResult.getDocumentElement());
    }
    return epr;
}
Example 31
Project: tuscany-sca-2.x-master  File: DataObject2Node.java View source code
public Node transform(DataObject source, TransformationContext context) {
    if (source == null) {
        return null;
    }
    try {
        HelperContext helperContext = SDOContextHelper.getHelperContext(context, true);
        XMLHelper xmlHelper = helperContext.getXMLHelper();
        QName elementName = SDOContextHelper.getElement(context);
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        DOMResult result = new DOMResult(doc);
        XMLDocument xmlDoc = xmlHelper.createDocument(source, elementName.getNamespaceURI(), elementName.getLocalPart());
        xmlHelper.save(xmlDoc, result, null);
        return doc.getDocumentElement();
    } catch (Exception e) {
        throw new TransformationException(e);
    }
}
Example 32
Project: xdocreport-master  File: Struts2ODTFile2XSLFOTest.java View source code
public static void doGenerate() {
    long startTime = System.currentTimeMillis();
    ODTXSLFOConverter converter = ODTXSLFOConverter.getInstance();
    InputStream inputStream = Struts2ODTFile2XSLFOTest.class.getResourceAsStream("org.appache.struts2.ide.odt");
    // OutputStream outputStream = new StringBuilderOutputStream();
    DOMResult result = new DOMResult();
    try {
        converter.convert2FO(inputStream, result, null);
        System.err.println(XMLUtils.toString(result.getNode()));
    } catch (XDocConverterException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println(System.currentTimeMillis() - startTime + "(ms)");
// startTime = System.currentTimeMillis() ;
// inputStream = ODTXSLFOConverterTest.class
// .getResourceAsStream("HelloWorld.content.xml");
// // OutputStream outputStream = new StringBuilderOutputStream();
// result = new DOMResult();
// try {
// converter.convert2FO(new StreamSource(inputStream), result);
// System.err.println(XMLUtils.toString(result.getNode()));
// } catch (XDocConverterException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// System.out.println(System.currentTimeMillis() - startTime + "(ms)");
}
Example 33
Project: zarathustra-master  File: WebdriverHelper.java View source code
/**
   * Returns the DOM representation of a page given its full HTML
   * representation.
   * 
   * @param page full dump of the HTML of the page.
   * @return the DOM corresponding to the provided page.
   */
public static Document getDom(String page) {
    try {
        DOMResult result = new DOMResult();
        XMLReader reader = new Parser();
        reader.setFeature(Parser.namespacesFeature, true);
        reader.setFeature(Parser.namespacePrefixesFeature, true);
        // See: http://ccil.org/~cowan/XML/tagsoup/#properties
        reader.setFeature("http://www.ccil.org/~cowan/tagsoup/features/root-bogons", true);
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.transform(new SAXSource(reader, new InputSource(new StringReader(page))), result);
        return (Document) result.getNode();
    } catch (SAXNotRecognizedException e) {
        throw new AssertionError(e);
    } catch (SAXNotSupportedException e) {
        throw new AssertionError(e);
    } catch (TransformerException e) {
        throw new AssertionError(e);
    }
}
Example 34
Project: aorra-master  File: XmlUtils.java View source code
public static Document xslt(InputStream stylesheet, Document input) throws FileNotFoundException, TransformerException, ParserConfigurationException {
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer(new StreamSource(stylesheet));
    Document result = newDocument();
    DOMResult domResult = new DOMResult(result);
    transformer.transform(new DOMSource(input), domResult);
    return result;
}
Example 35
Project: camel-master  File: TidyMarkupDataFormat.java View source code
/**
     * Return the HTML Markup as an {@link org.w3c.dom.Node}
     * 
     * @param inputStream
     *            The input Stream to convert
     * @return org.w3c.dom.Node The HTML Markup as a DOM Node
     * @throws CamelException
     */
public Node asNodeTidyMarkup(InputStream inputStream) throws CamelException {
    XMLReader parser = createTagSoupParser();
    StringWriter w = new StringWriter();
    parser.setContentHandler(createContentHandler(w));
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        DOMResult result = new DOMResult();
        transformer.transform(new SAXSource(parser, new InputSource(inputStream)), result);
        return result.getNode();
    } catch (Exception e) {
        throw new CamelException("Failed to convert the HTML to tidy Markup", e);
    }
}
Example 36
Project: cxf-master  File: FastInfosetExperiment.java View source code
private void readWithWoodstox() throws SAXException, TransformerConfigurationException, TransformerException, IOException {
    InputStream is = getClass().getResourceAsStream("/META-INF/cxf/cxf.xml");
    WstxSAXParserFactory woodstoxParserFactory;
    woodstoxParserFactory = new WstxSAXParserFactory();
    woodstoxParserFactory.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
    SAXParser parser = woodstoxParserFactory.newSAXParser();
    XMLReader reader = parser.getXMLReader();
    SAXSource saxSource = new SAXSource(reader, new InputSource(is));
    Document document;
    document = documentBuilder.newDocument();
    DOMResult domResult = new DOMResult(document);
    transformerFactory.newTransformer().transform(saxSource, domResult);
    is.close();
}
Example 37
Project: dbeaver-master  File: DBDDocumentXML.java View source code
@Override
public void updateDocument(@NotNull DBRProgressMonitor monitor, @NotNull InputStream stream, String encoding) throws DBException {
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        DOMResult output = new DOMResult();
        transformer.transform(new StreamSource(new InputStreamReader(stream, encoding)), output);
        document = (Document) output.getNode();
        modified = true;
    } catch (Exception e) {
        throw new DBException("Error transforming XML document", e);
    }
}
Example 38
Project: External-Projects-master  File: XMLDocumentContainer.java View source code
/**
     * Reads XML, caches it internally and returns the Document.
     * @return Object value
     */
public Object getValue() {
    if (document == null) {
        try {
            if (source != null) {
                DOMResult result = new DOMResult();
                Transformer trans = TransformerFactory.newInstance().newTransformer();
                trans.transform(source, result);
                document = (Document) result.getNode();
            } else {
                document = delegate.getValue();
            }
        } catch (Exception ex) {
            throw new JXPathException("Cannot read XML from: " + (xmlURL != null ? xmlURL.toString() : (source != null ? source.getSystemId() : "<<undefined source>>")), ex);
        }
    }
    return document;
}
Example 39
Project: extreme-fishbowl-master  File: TestBaseConfigurationXMLReader.java View source code
private void checkDocument(BaseConfigurationXMLReader creader, String rootName) throws Exception {
    SAXSource source = new SAXSource(creader, new InputSource());
    DOMResult result = new DOMResult();
    Transformer trans = TransformerFactory.newInstance().newTransformer();
    try {
        //When executed on a JDK 1.3 this line throws a NoSuchMethodError
        //somewhere deep in Xalan. We simply ignore this.
        trans.transform(source, result);
    } catch (NoSuchMethodError ex) {
        return;
    }
    Node root = ((Document) result.getNode()).getDocumentElement();
    JXPathContext ctx = JXPathContext.newContext(root);
    assertEquals("Wrong root name", rootName, root.getNodeName());
    assertEquals("Wrong number of children", 3, ctx.selectNodes("/*").size());
    check(ctx, "world/continents/continent", CONTINENTS);
    check(ctx, "world/greeting", new String[] { "Hello", "Salute" });
    check(ctx, "world/wish", "Peace");
    check(ctx, "application/mail/smtp", "smtp.mymail.org");
    check(ctx, "application/mail/timeout", "42");
    check(ctx, "application/mail/account/type", "pop3");
    check(ctx, "application/mail/account/user", "postmaster");
    check(ctx, "test", "true");
}
Example 40
Project: federation-master  File: DOMTransformerTestCase.java View source code
@Test
public void testDOMTransformer() throws Exception {
    ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes());
    XMLEventReader xmlEventReader = StaxParserUtil.getXMLEventReader(bis);
    StartElement a = StaxParserUtil.getNextStartElement(xmlEventReader);
    StaxParserUtil.validate(a, "a");
    Document resultDocument = DocumentUtil.createDocument();
    DOMResult domResult = new DOMResult(resultDocument);
    // Let us parse <b><c><d> using transformer
    StAXSource source = new StAXSource(xmlEventReader);
    Transformer transformer = TransformerUtil.getStaxSourceToDomResultTransformer();
    transformer.transform(source, domResult);
    Document doc = (Document) domResult.getNode();
    Element elem = doc.getDocumentElement();
    assertEquals("b", elem.getLocalName());
    XMLEvent xmlEvent = xmlEventReader.nextEvent();
    assertTrue(xmlEvent instanceof EndElement);
    StaxParserUtil.validate((EndElement) xmlEvent, "a");
}
Example 41
Project: fop-master  File: IFMimickingTestCase.java View source code
private void doTestMimicking(String mime) throws FOPException, IFException, TransformerException {
    //Set up XMLRenderer to render to a DOM
    DOMResult domResult = new DOMResult();
    FOUserAgent userAgent = fopFactory.newFOUserAgent();
    userAgent.getEventBroadcaster().addEventListener(new EventListener() {

        public void processEvent(Event event) {
            if (event.getEventGroupID().equals(FontEventProducer.class.getName())) {
                fail("There must be no font-related event! Got: " + EventFormatter.format(event));
            }
        }
    });
    //Create an instance of the target renderer so the XMLRenderer can use its font setup
    IFDocumentHandler targetHandler = userAgent.getRendererFactory().createDocumentHandler(userAgent, mime);
    //Setup painter
    IFSerializer serializer = new IFSerializer(new IFContext(userAgent));
    serializer.mimicDocumentHandler(targetHandler);
    serializer.setResult(domResult);
    userAgent.setDocumentHandlerOverride(serializer);
    Fop fop = fopFactory.newFop(userAgent);
    //minimal-pdf-a.fo uses the Gladiator font so is an ideal FO file for this test:
    StreamSource src = new StreamSource(new File("test/xml/pdf-a/minimal-pdf-a.fo"));
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer();
    setErrorListener(transformer);
    transformer.transform(src, new SAXResult(fop.getDefaultHandler()));
}
Example 42
Project: geotools-master  File: GMLWriterTest.java View source code
protected Document encode(GeometryEncoder encoder, Geometry geometry) throws Exception {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    // create the document serializer
    SAXTransformerFactory txFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    TransformerHandler xmls;
    try {
        xmls = txFactory.newTransformerHandler();
    } catch (TransformerConfigurationException e) {
        throw new IOException(e);
    }
    Properties outputProps = new Properties();
    outputProps.setProperty(INDENT_AMOUNT_KEY, "2");
    xmls.getTransformer().setOutputProperties(outputProps);
    xmls.getTransformer().setOutputProperty(OutputKeys.METHOD, "XML");
    xmls.setResult(new StreamResult(out));
    GMLWriter handler = new GMLWriter(xmls, gtEncoder.getNamespaces(), 6, false, "gml");
    handler.startDocument();
    handler.startPrefixMapping("gml", GML.NAMESPACE);
    handler.endPrefixMapping("gml");
    encoder.encode(geometry, new AttributesImpl(), handler);
    handler.endDocument();
    ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
    DOMResult result = new DOMResult();
    Transformer tx = TransformerFactory.newInstance().newTransformer();
    tx.transform(new StreamSource(in), result);
    Document d = (Document) result.getNode();
    return d;
}
Example 43
Project: hudson_plugins-master  File: NativePageCountsParserTest.java View source code
@Test
public void transformRawResultsShouldProduceSomethingUsable() throws Exception {
    DOMResult domResult = new DOMResult();
    fitnesseParser.transformRawResults(toInputStream(RESULTS), domResult);
    Assert.assertNotNull(domResult.getNode());
    Assert.assertNotNull(domResult.getNode().getFirstChild());
    Assert.assertEquals("hudson-fitnesse-plugin-report", domResult.getNode().getFirstChild().getNodeName());
}
Example 44
Project: izpack-with-ips-master  File: LineNumberFilter.java View source code
/**
     * Apply line numbers stored by a parse using this object on the xml elements.
     *
     * @param result The result of the parse.
     */
public void applyLN(DOMResult result) {
    Element elt = getFirstChild(result.getNode());
    boolean end = false;
    Stack<Element> stack = new Stack<Element>();
    while (!end) {
        if (hasChildElements(elt)) {
            // not a leaf
            stack.push(elt);
            applyLN(elt);
            // go down
            elt = getFirstChild(elt);
        } else {
            // a leaf
            applyLN(elt);
            Element sibling = getNextSibling(elt);
            if (sibling != null) {
                // has a sibling
                elt = sibling;
            } else {
                // no sibling
                do {
                    if (stack.isEmpty()) {
                        end = true;
                    } else {
                        elt = stack.pop();
                        elt = getNextSibling(elt);
                    }
                } while (!end && elt == null);
            }
        }
    }
}
Example 45
Project: JBossAS51-master  File: XalanCheck.java View source code
/**
    * Throws an exception when run using xalan 2.5.2
    * Borrowed from here: http://issues.apache.org/bugzilla/show_bug.cgi?id=15140
    */
public void testXalan25Bug15140() throws Exception {
    String testString = "<doc xmlns:a=\"http://www.test.com\"/>";
    SAXParserFactory parserFactory = SAXParserFactory.newInstance();
    SAXParser parser = parserFactory.newSAXParser();
    XMLReader reader = parser.getXMLReader();
    reader.setFeature("http://xml.org/sax/features/namespaces", true);
    reader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
    DOMResult domResult = new DOMResult();
    SAXTransformerFactory transformerFactory = (SAXTransformerFactory) TransformerFactory.newInstance();
    TransformerHandler handler = transformerFactory.newTransformerHandler();
    handler.setResult(domResult);
    reader.setContentHandler(handler);
    InputSource input = new InputSource(new StringReader(testString));
    reader.parse(input);
}
Example 46
Project: JBossAS_5_1_EDG-master  File: XalanCheck.java View source code
/**
    * Throws an exception when run using xalan 2.5.2
    * Borrowed from here: http://issues.apache.org/bugzilla/show_bug.cgi?id=15140
    */
public void testXalan25Bug15140() throws Exception {
    String testString = "<doc xmlns:a=\"http://www.test.com\"/>";
    SAXParserFactory parserFactory = SAXParserFactory.newInstance();
    SAXParser parser = parserFactory.newSAXParser();
    XMLReader reader = parser.getXMLReader();
    reader.setFeature("http://xml.org/sax/features/namespaces", true);
    reader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
    DOMResult domResult = new DOMResult();
    SAXTransformerFactory transformerFactory = (SAXTransformerFactory) TransformerFactory.newInstance();
    TransformerHandler handler = transformerFactory.newTransformerHandler();
    handler.setResult(domResult);
    reader.setContentHandler(handler);
    InputSource input = new InputSource(new StringReader(testString));
    reader.parse(input);
}
Example 47
Project: killbill-commons-master  File: XMLSchemaGenerator.java View source code
public static void pojoToXSD(final JAXBContext context, final OutputStream out) throws IOException, TransformerException {
    final List<DOMResult> results = new ArrayList<DOMResult>();
    context.generateSchema(new SchemaOutputResolver() {

        @Override
        public Result createOutput(final String ns, final String file) throws IOException {
            final DOMResult result = new DOMResult();
            result.setSystemId(file);
            results.add(result);
            return result;
        }
    });
    final DOMResult domResult = results.get(0);
    final Document doc = (Document) domResult.getNode();
    // Use a Transformer for output
    final TransformerFactory tFactory = TransformerFactory.newInstance();
    final Transformer transformer = tFactory.newTransformer();
    final DOMSource source = new DOMSource(doc);
    final StreamResult result = new StreamResult(out);
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.transform(source, result);
}
Example 48
Project: mapsforge-platform-master  File: SchemaGenertator.java View source code
/**
     * Generates xml schemas for the provided class instance as a list of
     * Strings.
     *
     * @return A list of xml schema Strings.
     * @throws JAXBException
     * @throws IOException
     */
public List<String> generatateSchemas() throws JAXBException, IOException {
    ArrayList<String> schemas = new ArrayList<String>();
    // grab the context
    JAXBContext context = JAXBContext.newInstance(clazz);
    final List<Result> results = new ArrayList<Result>();
    // generate the schema
    context.generateSchema(new SchemaOutputResolverImpl(results));
    // output schema via System.out
    for (Object domr : results) {
        if (domr instanceof DOMResult) {
            DOMResult domResult = (DOMResult) domr;
            Document doc = (Document) domResult.getNode();
            OutputFormat format = new OutputFormat(doc);
            format.setIndenting(true);
            StringWriter stringWriter = new StringWriter();
            XMLSerializer serializer = new XMLSerializer(stringWriter, format);
            serializer.serialize(doc);
            schemas.add(stringWriter.toString());
        }
    }
    return schemas;
}
Example 49
Project: marytts-master  File: SSMLParser.java View source code
public MaryData process(MaryData d) throws Exception {
    DOMSource domSource = new DOMSource(d.getDocument());
    Transformer transformer = stylesheet.newTransformer();
    // Log transformation errors to client:
    if (doWarnClient) {
        // Use custom error handler:
        transformer.setErrorListener(new LoggingErrorHandler(Thread.currentThread().getName() + " client.SSML transformer"));
    }
    // Transform DOMSource into a DOMResult
    Document maryxmlDocument = docBuilder.newDocument();
    DOMResult domResult = new DOMResult(maryxmlDocument);
    transformer.transform(domSource, domResult);
    MaryData result = new MaryData(outputType(), d.getLocale());
    result.setDocument(maryxmlDocument);
    return result;
}
Example 50
Project: netty-xmpp-master  File: XMLUtil.java View source code
/**
	 * Parses a String into a new Element.
	 * 
	 * @param element the String to parse
	 * @return the parsed Element
	 */
public static final Element fromString(final String element) {
    try {
        final Document doc = newDocument();
        transformer.transform(new StreamSource(new StringReader(element)), new DOMResult(doc));
        return doc.getDocumentElement();
    } catch (final TransformerException e) {
        throw new InternalError("Transformer error");
    }
}
Example 51
Project: openpipe-master  File: MultiXmlDocumentReader.java View source code
private Document readAndBuildDocument() throws Exception {
    assert currStartEle != null;
    DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
    DOMResult domResult = new DOMResult(docBuilder.newDocument());
    XMLEventWriter eventWriter = xmlOutputFactory.createXMLEventWriter(domResult);
    int depth = 1;
    eventWriter.add(currStartEle);
    while (eventReader.hasNext() && depth > 0) {
        XMLEvent evt = eventReader.nextEvent();
        eventWriter.add(evt);
        if (evt.isStartElement()) {
            depth++;
        } else if (evt.isEndElement()) {
            depth--;
        }
    }
    return new Document(new DomRawData(null, domResult.getNode()));
}
Example 52
Project: resin-master  File: XMLOutputFactoryImpl.java View source code
/**
   *  This method is optional.
   */
public XMLStreamWriter createXMLStreamWriter(Result result) throws XMLStreamException {
    if (result instanceof DOMResult) {
        return new DOMResultXMLStreamWriterImpl((DOMResult) result, _repair);
    } else if (result instanceof SAXResult) {
        return new SAXResultXMLStreamWriterImpl((SAXResult) result);
    } else if (result instanceof StreamResult) {
        Writer writer = ((StreamResult) result).getWriter();
        if (writer != null)
            return createXMLStreamWriter(writer);
        OutputStream os = ((StreamResult) result).getOutputStream();
        if (os != null)
            return createXMLStreamWriter(os);
        throw new XMLStreamException("StreamResult has no output stream or writer");
    }
    throw new UnsupportedOperationException(L.l("Results of type {0} are not supported", result.getClass().getName()));
}
Example 53
Project: sikker-digital-post-klient-java-master  File: CreateXAdESProperties.java View source code
public Document createPropertiesToSign(List<AsicEAttachable> files, Sertifikat sertifikat) {
    X509Certificate certificate = sertifikat.getX509Certificate();
    byte[] certificateDigestValue = sha1(sertifikat.getEncoded());
    DigestAlgAndValueType certificateDigest = new DigestAlgAndValueType(sha1DigestMethod, certificateDigestValue);
    X509IssuerSerialType certificateIssuer = new X509IssuerSerialType(certificate.getIssuerDN().getName(), certificate.getSerialNumber());
    SigningCertificate signingCertificate = new SigningCertificate(singletonList(new CertIDType(certificateDigest, certificateIssuer, null)));
    ZonedDateTime now = ZonedDateTime.now(clock);
    SignedSignatureProperties signedSignatureProperties = new SignedSignatureProperties(now, signingCertificate, null, null, null, null);
    SignedDataObjectProperties signedDataObjectProperties = new SignedDataObjectProperties(dataObjectFormats(files), null, null, null, null);
    SignedProperties signedProperties = new SignedProperties(signedSignatureProperties, signedDataObjectProperties, "SignedProperties");
    QualifyingProperties qualifyingProperties = new QualifyingProperties(signedProperties, null, "#Signature", null);
    DOMResult domResult = new DOMResult();
    marshaller.marshal(qualifyingProperties, domResult);
    Document document = (Document) domResult.getNode();
    // Explicitly mark the SignedProperties Id as an Document ID attribute, so that it will be eligble as a reference for signature.
    // If not, it will not be treated as something to sign.
    markAsIdProperty(document, "SignedProperties", "Id");
    return document;
}
Example 54
Project: siu-master  File: TransformSerializer.java View source code
/**
   * @param ctx
   * @param source
   * @return the Node resulting from the parse of the source
   * @throws XMLEncryptionException
   */
private Node deserialize(Node ctx, Source source) throws XMLEncryptionException {
    try {
        Document contextDocument = null;
        if (Node.DOCUMENT_NODE == ctx.getNodeType()) {
            contextDocument = (Document) ctx;
        } else {
            contextDocument = ctx.getOwnerDocument();
        }
        if (transformerFactory == null) {
            transformerFactory = TransformerFactory.newInstance();
            transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
        }
        Transformer transformer = transformerFactory.newTransformer();
        DOMResult res = new DOMResult();
        Node placeholder = contextDocument.createDocumentFragment();
        res.setNode(placeholder);
        transformer.transform(source, res);
        // Skip dummy element
        Node dummyChild = placeholder.getFirstChild();
        Node child = dummyChild.getFirstChild();
        if (child != null && child.getNextSibling() == null) {
            return child;
        }
        DocumentFragment docfrag = contextDocument.createDocumentFragment();
        while (child != null) {
            dummyChild.removeChild(child);
            docfrag.appendChild(child);
            child = dummyChild.getFirstChild();
        }
        return docfrag;
    } catch (Exception e) {
        throw new XMLEncryptionException("empty", e);
    }
}
Example 55
Project: smock-master  File: VanillaTest.java View source code
@Test
public void testGetFlightsXml() throws AirlineException, DatatypeConfigurationException, TransformerException {
    GetFlightsRequest request = JAXB.unmarshal(getStream("request1.xml"), GetFlightsRequest.class);
    GetFlightsResponse response = endpoint.getFlights(request);
    DOMResult domResponse = new DOMResult();
    JAXB.marshal(response, domResponse);
    XMLUnit.setIgnoreWhitespace(true);
    XMLAssert.assertXMLEqual(getDocument("response1.xml"), (Document) domResponse.getNode());
}
Example 56
Project: spring-framework-master  File: AbstractStaxHandlerTestCase.java View source code
@Test
public void noNamespacePrefixesDom() throws Exception {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document expected = documentBuilder.parse(new InputSource(new StringReader(SIMPLE_XML)));
    Document result = documentBuilder.newDocument();
    AbstractStaxHandler handler = createStaxHandler(new DOMResult(result));
    xmlReader.setContentHandler(handler);
    xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", handler);
    xmlReader.setFeature("http://xml.org/sax/features/namespaces", true);
    xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", false);
    xmlReader.parse(new InputSource(new StringReader(SIMPLE_XML)));
    assertThat(result, isSimilarTo(expected).withNodeFilter(nodeFilter));
}
Example 57
Project: traitocws-master  File: MetadataODM.java View source code
/**
	 * Transform ODM metadata into a template for ODM data loading
	 * @return the resulting template DOM Document
	 * @throws ODMException 
	 */
public ClinicalODM getClinicalTemplate() throws ODMException {
    InputStream xslt = getClass().getResourceAsStream(ODM_XSLT);
    Document result = documentBuilder.newDocument();
    try {
        Transformer transformer = transformerFactory.newTransformer(new StreamSource(xslt));
        transformer.transform(new DOMSource(this.odm), new DOMResult(result));
        return new ClinicalODM(result, false);
    } catch (Exception e) {
        throw new ODMException(e);
    }
}
Example 58
Project: TTT-master  File: FontLoader.java View source code
public static List<FontSpecification> fromStream(InputStream is, String sourceBase) throws IOException {
    try {
        SAXSource source = new SAXSource(new InputSource(is));
        DOMResult result = new DOMResult();
        TransformerFactory.newInstance().newTransformer().transform(source, result);
        Document d = (Document) result.getNode();
        return FontSpecification.fromDocument(d, sourceBase);
    } catch (TransformerFactoryConfigurationError e) {
        return noFontSpecifications;
    } catch (TransformerException e) {
        return noFontSpecifications;
    }
}
Example 59
Project: WSS-Client-for-Android-master  File: TransformSerializer.java View source code
/**
     * @param ctx
     * @param source
     * @return the Node resulting from the parse of the source
     * @throws XMLEncryptionException
     */
private Node deserialize(Node ctx, Source source) throws XMLEncryptionException {
    try {
        Document contextDocument = null;
        if (Node.DOCUMENT_NODE == ctx.getNodeType()) {
            contextDocument = (Document) ctx;
        } else {
            contextDocument = ctx.getOwnerDocument();
        }
        if (transformerFactory == null) {
            transformerFactory = TransformerFactory.newInstance();
            transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
        }
        Transformer transformer = transformerFactory.newTransformer();
        DOMResult res = new DOMResult();
        Node placeholder = contextDocument.createDocumentFragment();
        res.setNode(placeholder);
        transformer.transform(source, res);
        // Skip dummy element
        Node dummyChild = placeholder.getFirstChild();
        Node child = dummyChild.getFirstChild();
        if (child != null && child.getNextSibling() == null) {
            return child;
        }
        DocumentFragment docfrag = contextDocument.createDocumentFragment();
        while (child != null) {
            dummyChild.removeChild(child);
            docfrag.appendChild(child);
            child = dummyChild.getFirstChild();
        }
        return docfrag;
    } catch (Exception e) {
        throw new XMLEncryptionException("empty", e);
    }
}
Example 60
Project: anno4j-master  File: DocumentFragmentMarshall.java View source code
public DocumentFragment deserialize(Literal literal) {
    try {
        String wrapper = START_TAG + literal.getLabel() + END_TAG;
        Source source = new StreamSource(new StringReader(wrapper));
        Document doc = builder.newDocumentBuilder().newDocument();
        DOMResult result = new DOMResult(doc);
        Transformer transformer = factory.newTransformer();
        ErrorCatcher listener = new ErrorCatcher();
        transformer.setErrorListener(listener);
        transformer.transform(source, result);
        if (listener.isFatal())
            throw listener.getFatalError();
        DocumentFragment frag = doc.createDocumentFragment();
        Element element = doc.getDocumentElement();
        NodeList nodes = element.getChildNodes();
        int size = nodes.getLength();
        List<Node> list = new ArrayList<Node>(size);
        for (int i = 0, n = size; i < n; i++) {
            list.add(nodes.item(i));
        }
        for (Node node : list) {
            frag.appendChild(node);
        }
        return frag;
    } catch (TransformerConfigurationException e) {
        throw new ObjectConversionException(e);
    } catch (TransformerException e) {
        throw new ObjectConversionException(e);
    } catch (ParserConfigurationException e) {
        throw new ObjectConversionException(e);
    }
}
Example 61
Project: axis2-java-master  File: ProcessorTest.java View source code
@Test
public void testServiceClient() throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document response = db.newDocument();
    InputStream in = ProcessorTest.class.getResourceAsStream("request.xml");
    try {
        OMElement request = OMXMLBuilderFactory.createOMBuilder(in).getDocumentElement();
        ServiceClient client = new ServiceClient(UtilServer.getConfigurationContext(), null);
        Options options = client.getOptions();
        options.setTo(new EndpointReference(ENDPOINT));
        try {
            OMElement omResponse = client.sendReceive(request);
            TransformerFactory.newInstance().newTransformer().transform(omResponse.getSAXSource(false), new DOMResult(response));
        } finally {
            client.cleanupTransport();
            client.cleanup();
        }
    } finally {
        in.close();
    }
    in = ProcessorTest.class.getResourceAsStream("response.xml");
    Document expectedResponse;
    try {
        expectedResponse = db.parse(in);
    } finally {
        in.close();
    }
    XMLAssert.assertXMLEqual(expectedResponse, response);
}
Example 62
Project: choreos_middleware-master  File: SchemaGenerator.java View source code
// based on
// http://arthur.gonigberg.com/2010/04/26/jaxb-generating-schema-from-object-model/
// and
// http://stackoverflow.com/questions/2325388/java-shortest-way-to-pretty-print-to-stdout-a-org-w3c-dom-document
private void printSchema(Class<?> clazz) throws JAXBException, IOException, TransformerException {
    // grab the context
    JAXBContext context = JAXBContext.newInstance(clazz);
    final List<DOMResult> results = new ArrayList<DOMResult>();
    // generate the schema
    context.generateSchema(// need to define a SchemaOutputResolver to store to
    new SchemaOutputResolver() {

        @Override
        public Result createOutput(String ns, String file) throws IOException {
            // save the schema to the list
            DOMResult result = new DOMResult();
            result.setSystemId(file);
            results.add(result);
            return result;
        }
    });
    // output schema via System.out
    DOMResult domResult = results.get(0);
    Document doc = (Document) domResult.getNode();
    printDocument(doc, System.out);
//        OutputFormat format = new OutputFormat(doc);
//        format.setIndenting(true);
//        StringWriter writer = new StringWriter();
//        XMLSerializer serializer = new XMLSerializer(writer, format);
//        serializer.serialize(doc);
//        return writer.toString();
}
Example 63
Project: cocoon-master  File: DOMBuilder.java View source code
/**
     * Setup this instance transformer and result objects.
     */
private void setup() {
    try {
        TransformerHandler handler = this.factory.newTransformerHandler();
        setContentHandler(handler);
        setLexicalHandler(handler);
        if (this.parentNode != null) {
            this.result = new DOMResult(this.parentNode);
        } else {
            this.result = new DOMResult();
        }
        handler.setResult(this.result);
    } catch (javax.xml.transform.TransformerException local) {
        throw new CascadingRuntimeException("Fatal-Error: Unable to get transformer handler", local);
    }
}
Example 64
Project: delcyon-capo-master  File: TransformElement.java View source code
@Override
public Object processServerSideElement() throws Exception {
    String ref = getAttributeValue(Attributes.ref);
    String stylesheet = getAttributeValue(Attributes.stylesheet);
    String src = null;
    //see if we are making a specific reference to something, and if so ues it, as opposed to the module system.
    if (ResourceURI.getScheme(stylesheet) != null) {
        src = stylesheet;
    }
    Node refNode = XPath.selectSingleNode(getControlElementDeclaration(), ref);
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = null;
    if (src != null) {
        ResourceDescriptor resourceDescriptor = getParentGroup().getResourceDescriptor(this, src);
        resourceDescriptor.addResourceParameters(getParentGroup(), new ResourceParameter(FileResourceType.Parameters.PARENT_PROVIDED_DIRECTORY, PREFERENCE.MODULE_DIR, Source.CALL));
        resourceDescriptor.addResourceParameters(getParentGroup(), new ResourceParameter(RefResourceType.Parameters.XMLNS, "xsl=http://www.w3.org/1999/XSL/Transform"));
        if (resourceDescriptor.isSupportedStreamFormat(StreamType.INPUT, StreamFormat.XML_BLOCK)) {
            Element styleSheetElement = resourceDescriptor.readXML(getParentGroup(), ResourceParameterBuilder.getResourceParameters(getControlElementDeclaration()));
            Document transformDocument = CapoApplication.getDocumentBuilder().newDocument();
            Element transformStyleSheetElement = (Element) transformDocument.adoptNode(styleSheetElement);
            transformDocument.appendChild(transformStyleSheetElement);
            //for some reason, we always strip out the parent name space if it's declared in the child, which it has to be, so we add it back in.
            String parentNameSpace = getControlElementDeclaration().getNamespaceURI();
            String parentPrefix = getControlElementDeclaration().getPrefix();
            transformStyleSheetElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + parentPrefix, parentNameSpace);
            transformer = tFactory.newTransformer(new DOMSource(transformDocument));
        } else {
            transformer = tFactory.newTransformer(new StreamSource(resourceDescriptor.getInputStream(getParentGroup(), ResourceParameterBuilder.getResourceParameters(getControlElementDeclaration()))));
        }
        //cleanup and parameters we added when calling this.
        resourceDescriptor.close(getParentGroup(), ResourceParameterBuilder.getResourceParameters(getControlElementDeclaration()));
    } else if (stylesheet.isEmpty() == false) {
        Element moduleElement = ModuleProvider.getModuleElement(stylesheet);
        if (moduleElement == null) {
            throw new Exception("Couldn't locate a style sheet named " + stylesheet + " in any of the module directories");
        }
        Document transformDocument = CapoApplication.getDocumentBuilder().newDocument();
        Element transformStyleSheetElement = (Element) transformDocument.adoptNode(moduleElement);
        transformDocument.appendChild(transformStyleSheetElement);
        //for some reason, we always strip out the parent name space if it's declared in the child, which it has to be, so we add it back in.
        String parentNameSpace = getControlElementDeclaration().getNamespaceURI();
        String parentPrefix = getControlElementDeclaration().getPrefix();
        transformStyleSheetElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + parentPrefix, parentNameSpace);
        transformer = tFactory.newTransformer(new DOMSource(transformDocument));
    }
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.transform(new DOMSource(refNode), new DOMResult(getControlElementDeclaration()));
    if (getControlElementDeclaration().hasAttribute(Attributes.name.toString())) {
        getParentGroup().set(getAttributeValue(Attributes.name), XPath.getXPath(getControlElementDeclaration()));
    }
    return null;
}
Example 65
Project: dlibrary-master  File: XMLUtil.java View source code
/**
     * Applies a stylesheet (that receives parameters) to a given xml document.
     * 
     * @param xmlDocument
     *            the xml document to be transformed
     * @param parameters
     *            the hashtable with the parameters to be passed to the
     *            stylesheet
     * @param xsltFilename
     *            the filename of the stylesheet
     * @return the transformed xml document
     * @throws Exception
     */
public static Document transformDocument(Document xmlDocument, Map<String, String> parameters, String xsltFilename) throws Exception {
    // Generate a Transformer.
    Transformer transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(xsltFilename));
    // set transformation parameters
    if (parameters != null) {
        for (Map.Entry<String, String> param : parameters.entrySet()) {
            transformer.setParameter(param.getKey(), param.getValue());
        }
    }
    // Create an empty DOMResult object for the output.
    DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
    dFactory.setNamespaceAware(true);
    DocumentBuilder dBuilder = dFactory.newDocumentBuilder();
    Document dstDocument = dBuilder.newDocument();
    DOMResult domResult = new DOMResult(dstDocument);
    // Perform the transformation.
    transformer.transform(new DOMSource(xmlDocument), domResult);
    // Now you can get the output Node from the DOMResult.
    return dstDocument;
}
Example 66
Project: docx4j-master  File: OpenDoPEIntegrity.java View source code
private void process(JaxbXmlPart part) throws Docx4JException {
    log.info("/n Processing " + part.getPartName().getName());
    org.docx4j.openpackaging.packages.OpcPackage pkg = part.getPackage();
    // Binding is a concept which applies more broadly
    // than just Word documents.
    org.w3c.dom.Document doc = XmlUtils.marshaltoW3CDomDocument(part.getJaxbElement());
    JAXBContext jc = Context.jc;
    try {
        // Use constructor which takes Unmarshaller, rather than JAXBContext,
        // so we can set JaxbValidationEventHandler
        Unmarshaller u = jc.createUnmarshaller();
        JaxbValidationEventHandler eventHandler = new org.docx4j.jaxb.JaxbValidationEventHandler();
        //eventHandler.setContinue(true);				
        u.setEventHandler(eventHandler);
        Map<String, Object> transformParameters = new HashMap<String, Object>();
        transformParameters.put("OpenDoPEIntegrity", this);
        try {
            javax.xml.bind.util.JAXBResult result = new javax.xml.bind.util.JAXBResult(u);
            org.docx4j.XmlUtils.transform(doc, xslt, transformParameters, result);
            part.setJaxbElement(result);
        // this will fail if there is unexpected content, 
        // since JaxbValidationEventHandler fails by default
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            log.error("Input in question:" + XmlUtils.w3CDomNodeToString(doc));
            log.error("Now trying DOMResult..");
            DOMResult result = new DOMResult();
            org.docx4j.XmlUtils.transform(doc, xslt, transformParameters, result);
            if (log.isDebugEnabled()) {
                org.w3c.dom.Document docResult = ((org.w3c.dom.Document) result.getNode());
                Object o = XmlUtils.unmarshal(((org.w3c.dom.Document) result.getNode()));
                part.setJaxbElement(o);
            } else {
                Object o = XmlUtils.unmarshal(((org.w3c.dom.Document) result.getNode()));
                part.setJaxbElement(o);
            }
        }
    } catch (Exception e) {
        throw new Docx4JException("Problems ensuring integrity", e);
    }
}
Example 67
Project: DSpace-SVN-Deprecated-master  File: XMLUtil.java View source code
/**
     * Applies a stylesheet (that receives parameters) to a given xml document.
     * 
     * @param xmlDocument
     *            the xml document to be transformed
     * @param parameters
     *            the hashtable with the parameters to be passed to the
     *            stylesheet
     * @param xsltFilename
     *            the filename of the stylesheet
     * @return the transformed xml document
     * @throws Exception
     */
public static Document transformDocument(Document xmlDocument, Map<String, String> parameters, String xsltFilename) throws Exception {
    // Generate a Transformer.
    Transformer transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(xsltFilename));
    // set transformation parameters
    if (parameters != null) {
        for (Map.Entry<String, String> param : parameters.entrySet()) {
            transformer.setParameter(param.getKey(), param.getValue());
        }
    }
    // Create an empy DOMResult object for the output.
    DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
    dFactory.setNamespaceAware(true);
    DocumentBuilder dBuilder = dFactory.newDocumentBuilder();
    Document dstDocument = dBuilder.newDocument();
    DOMResult domResult = new DOMResult(dstDocument);
    // Perform the transformation.
    transformer.transform(new DOMSource(xmlDocument), domResult);
    // Now you can get the output Node from the DOMResult.
    return dstDocument;
}
Example 68
Project: edireader-master  File: DocumentUtil.java View source code
public synchronized Document buildDocumentFromEdi(InputSource inputSource, PluginControllerFactoryInterface factory) throws Exception {
    EDIReader ediReader = new EDIReader();
    if (factory != null) {
        ediReader.setPluginControllerFactory(factory);
    }
    XMLReader xmlReader = ediReader;
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    DOMResult domResult = new DOMResult();
    transformer.transform(new SAXSource(xmlReader, inputSource), domResult);
    Document document = (Document) domResult.getNode();
    if (document == null)
        throw new RuntimeException("transform produced null document");
    return document;
}
Example 69
Project: esigate-master  File: XsltRenderer.java View source code
/** {@inheritDoc} */
@Override
public void render(DriverRequest httpRequest, String src, Writer out) throws IOException {
    try {
        HtmlDocumentBuilder htmlDocumentBuilder = new HtmlDocumentBuilder();
        htmlDocumentBuilder.setDoctypeExpectation(DoctypeExpectation.NO_DOCTYPE_ERRORS);
        Document document = htmlDocumentBuilder.parse(new InputSource(new StringReader(src)));
        Source source = new DOMSource(document);
        DOMResult result = new DOMResult();
        transformer.transform(source, result);
        XhtmlSerializer serializer = new XhtmlSerializer(out);
        Dom2Sax dom2Sax = new Dom2Sax(serializer, serializer);
        dom2Sax.parse(result.getNode());
    } catch (TransformerException e) {
        throw new ProcessingFailedException("Failed to transform source", e);
    } catch (SAXException e) {
        throw new ProcessingFailedException("Failed serialize transformation result", e);
    }
}
Example 70
Project: FireflowEngine20-master  File: WebServiceCallerImpl.java View source code
/*
	public List<Document> callWebService(List<Document> messagePlayload) throws ServiceInvocationException {
		Definition wsdlDef = ws.getWsdlDefinition();
		String targetNsUri = wsdlDef.getTargetNamespace();
		QName serviceQName = new QName(targetNsUri,ws.getName());
		QName portQName = new QName(targetNsUri,ws.getPortName());
		
		String urlStr = ws.getWsdlURL();
		URL url = null;
		if (urlStr.toLowerCase().startsWith(WebService.CLASSPATH_URL_PREFIX)) {
			url = WebServiceCallerImpl.class.getResource(urlStr
					.substring(WebService.CLASSPATH_URL_PREFIX.length()));
		}else{
			try {
				url = new URL(urlStr);
			} catch (MalformedURLException e) {
				throw new ServiceInvocationException(e);
			}
		}
		
		if (url==null){
			throw new ServiceInvocationException("Invalid wsdl url '"+urlStr+"'");
		}
		
		javax.xml.ws.Service jawsService = javax.xml.ws.Service.create(url, serviceQName);
		Dispatch<DOMSource> dispatch = jawsService.createDispatch(portQName, DOMSource.class, javax.xml.ws.Service.Mode.PAYLOAD);
		
		Document thePayLoad = messagePlayload.get(0);//TODO 待处�
		
		DOMSource request = new DOMSource(thePayLoad);
		DOMSource response = dispatch.invoke(request);

		Document theResponsePayload = (Document)response.getNode();
		
		List<Document> result = new ArrayList<Document>();
		result.add(theResponsePayload);
		return result;
	}
	*/
public Document callWebService(Document messagePlayload) throws ServiceInvocationException {
    Definition wsdlDef = ws.getWsdlDefinition();
    String targetNsUri = wsdlDef.getTargetNamespace();
    QName serviceQName = new QName(targetNsUri, ws.getName());
    QName portQName = new QName(targetNsUri, ws.getPortName());
    String urlStr = ws.getWsdlURL();
    URL url = null;
    if (urlStr.toLowerCase().startsWith(WebServiceDef.CLASSPATH_URL_PREFIX)) {
        url = WebServiceCallerImpl.class.getResource(urlStr.substring(WebServiceDef.CLASSPATH_URL_PREFIX.length()));
    } else {
        try {
            url = new URL(urlStr);
        } catch (MalformedURLException e) {
            throw new ServiceInvocationException(e);
        }
    }
    if (url == null) {
        throw new ServiceInvocationException("Invalid wsdl url '" + urlStr + "'");
    }
    javax.xml.ws.Service jawsService = javax.xml.ws.Service.create(url, serviceQName);
    Dispatch<Source> dispatch = jawsService.createDispatch(portQName, Source.class, javax.xml.ws.Service.Mode.PAYLOAD);
    DOMSource domSource = new DOMSource(messagePlayload);
    log.debug("Call web service , servicename=" + serviceQName + ", portname=" + portQName + ", the soap message is: \n");
    log.debug(DOMInitializer.dom2String(messagePlayload));
    Source response = dispatch.invoke(domSource);
    DOMResult domResult = new DOMResult();
    Transformer transformer = null;
    try {
        transformer = transformerFactory.newTransformer();
        transformer.transform(response, domResult);
    } catch (TransformerConfigurationException e) {
        throw new RuntimeException("Couldn't parse response stream.", e);
    } catch (TransformerException e) {
        throw new RuntimeException("Couldn't parse response stream.", e);
    }
    Document theResponsePayload = (Document) domResult.getNode();
    log.debug("The response of the web service is :");
    log.debug(DOMInitializer.dom2String(theResponsePayload));
    return theResponsePayload;
}
Example 71
Project: geotoolkit-master  File: StaxStreamWriterTest.java View source code
@Test
public void testWritingToDom() throws Exception {
    //this test requiere and advanced Stax library, here we use WoodStox stream reader.
    final DocumentBuilderFactory fabrique = DocumentBuilderFactory.newInstance();
    final DocumentBuilder constructeur = fabrique.newDocumentBuilder();
    final Document document = constructeur.newDocument();
    final File file = new File("src/test/resources/org/geotoolkit/xml/sampleOutput.xml");
    if (file.exists())
        file.delete();
    final Result res = new DOMResult(document);
    final MockWriter instance = new MockWriter();
    instance.setOutput(res);
    instance.write();
    instance.dispose();
    //check by reading it back
    final Source src = new DOMSource(document);
    final XMLInputFactory XMLfactory = new WstxInputFactory();
    final XMLStreamReader reader = XMLfactory.createXMLStreamReader(src);
    final MockReader mr = new MockReader();
    mr.setInput(reader);
    StaxStreamReaderTest.validate(mr.read());
    mr.dispose();
}
Example 72
Project: hsn2-framework-master  File: HWLParser.java View source code
private void createSchema() throws IOException, SAXException {
    final DOMResult result = new DOMResult();
    SchemaOutputResolver outputResolver = new HwlSchemaOutputResolver(result);
    ctx.generateSchema(outputResolver);
    this.schemaNode = result.getNode();
    this.schemaSystemId = result.getSystemId();
    Source source = new DOMSource(schemaNode, schemaSystemId);
    this.schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(source);
}
Example 73
Project: incubator-falcon-master  File: OozieUtils.java View source code
public static void marshalHiveAction(org.apache.falcon.oozie.workflow.ACTION wfAction, JAXBElement<org.apache.falcon.oozie.hive.ACTION> actionjaxbElement) {
    try {
        DOMResult hiveActionDOM = new DOMResult();
        Marshaller marshaller = HIVE_ACTION_JAXB_CONTEXT.createMarshaller();
        marshaller.marshal(actionjaxbElement, hiveActionDOM);
        wfAction.setAny(((Document) hiveActionDOM.getNode()).getDocumentElement());
    } catch (JAXBException e) {
        throw new RuntimeException("Unable to marshall hive action.", e);
    }
}
Example 74
Project: isis-master  File: XmlSnapshotServiceAbstract.java View source code
@Override
public Document asDocument(String xmlStr) {
    try {
        final StringReader reader = new StringReader(xmlStr);
        final StreamSource streamSource = new StreamSource(reader);
        final DOMResult result = new DOMResult();
        final TransformerFactory tf = TransformerFactory.newInstance();
        final Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.transform(streamSource, result);
        final Node node = result.getNode();
        return (Document) node;
    } catch (TransformerException e) {
        throw new XmlSnapshotService.Exception(e);
    }
}
Example 75
Project: ISJ-master  File: PreloaderPlan.java View source code
private Document getDocument(InputStream in) throws TransformerException {
    TransformerFactory tFactory = TransformerFactory.newInstance();
    //Custom error listener to minimize output to console
    ErrorListener errorListener = new DefaultErrorListener(log);
    tFactory.setErrorListener(errorListener);
    Transformer transformer = tFactory.newTransformer();
    transformer.setErrorListener(errorListener);
    Source source = new StreamSource(in);
    DOMResult res = new DOMResult();
    transformer.transform(source, res);
    Document doc = (Document) res.getNode();
    return doc;
}
Example 76
Project: jaxws-master  File: TestHandler.java View source code
private Source incrementArgument(Source source) throws TransformerException {
    Transformer xFormer = TransformerFactory.newInstance().newTransformer();
    xFormer.setOutputProperty("omit-xml-declaration", "yes");
    DOMResult dResult = new DOMResult();
    xFormer.transform(source, dResult);
    Node documentNode = dResult.getNode();
    Node envelopeNode = documentNode.getFirstChild();
    Node requestResponseNode = envelopeNode.getLastChild().getFirstChild();
    Node textNode = requestResponseNode.getFirstChild().getFirstChild();
    int orig = Integer.parseInt(textNode.getNodeValue());
    // check for error tests
    if (orig == THROW_HTTP_EXCEPTION) {
        throw new HTTPException(500);
    } else if (orig == THROW_RUNTIME_EXCEPTION) {
        throw new RuntimeException("EXPECTED EXCEPTION");
    } else if (orig == THROW_PROTOCOL_EXCEPTION) {
        throw new ProtocolException("TEST EXCEPTION FROM HANDLER");
    }
    textNode.setNodeValue(String.valueOf(++orig));
    return new DOMSource(documentNode);
}
Example 77
Project: jboss-deployers-master  File: XSLDeployer.java View source code
@Override
protected T parse(VFSDeploymentUnit unit, VirtualFile file, T root) throws Exception {
    if (file == null)
        throw new IllegalArgumentException("Null file");
    Document document = doParse(unit, file);
    Transformer trans = getTemplates().newTransformer();
    trans.setErrorListener(new JBossErrorHandler(file.getPathName(), null));
    Source s = new DOMSource(document);
    s.setSystemId(file.toURI().toString());
    DOMResult r = new DOMResult();
    setParameters(trans);
    trans.transform(s, r);
    document = (Document) r.getNode();
    String docStr = DOMWriter.printNode(document, true);
    log.debug("Transformed " + file.getPathName() + " into " + docStr);
    return parse(unit, file, document);
}
Example 78
Project: juxy-master  File: RunnerImpl.java View source code
private void checkEnvironment() {
    if (!trFactory.getFeature(SAXSource.FEATURE))
        throw new JuxyRuntimeException("The specified transformer factory does not support SAXSource");
    if (!trFactory.getFeature(DOMResult.FEATURE))
        throw new JuxyRuntimeException("The specified transformer factory does not support DOMResult");
}
Example 79
Project: mdrill-master  File: XsltXMLLoader.java View source code
@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;
    XMLStreamReader parser = null;
    // 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();
    }
}
Example 80
Project: olca-modules-master  File: GeoKmzImport.java View source code
private byte[] getKmz(XMLStreamReader reader) {
    try {
        DOMResult dom = new DOMResult();
        transformer.transform(new StAXSource(reader), dom);
        Document doc = (Document) dom.getNode();
        NodeList list = doc.getElementsByTagName("*");
        String ns = "http://earth.google.com/kml/2.1";
        for (int i = 0; i < list.getLength(); i++) {
            Node n = list.item(i);
            doc.renameNode(n, ns, n.getLocalName());
        }
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        transformer.transform(new DOMSource(doc), new StreamResult(bout));
        byte[] bytes = bout.toByteArray();
        return BinUtils.zip(bytes);
    } catch (Exception e) {
        log.error("failed to parse KML", e);
        return null;
    }
}
Example 81
Project: openengsb-master  File: XmlMethodCallMarshalOutgoingFilter.java View source code
private Document serializeRequest(MethodCallMessage result) {
    DOMResult domResult = new DOMResult();
    try {
        @SuppressWarnings("unchecked") List<Class<?>> classes = ClassUtils.convertClassNamesToClasses(result.getMethodCall().getClasses());
        if (classes.contains(null)) {
            throw new FilterException("Could not load all required classes. Require: " + result.getMethodCall().getClasses() + " got: " + classes);
        }
        classes.add(MethodCallMessage.class);
        JAXBContext jaxbContext = JAXBContext.newInstance(classes.toArray(new Class<?>[classes.size()]));
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.marshal(new JAXBElement<MethodCallMessage>(new QName(MethodCallMessage.class.getSimpleName()), MethodCallMessage.class, result), domResult);
    } catch (JAXBException e) {
        throw new FilterException(e);
    }
    return (Document) domResult.getNode();
}
Example 82
Project: orbeon-forms-master  File: ResourceManagerBase.java View source code
public Node getContentAsDOM(String key) {
    try {
        final TransformerXMLReceiver identity = TransformerUtils.getIdentityTransformerHandler();
        final DOMResult domResult = new DOMResult(XMLParsing.createDocument());
        identity.setResult(domResult);
        getContentAsSAX(key, identity);
        return domResult.getNode();
    } catch (IllegalArgumentException e) {
        throw new OXFException(e);
    }
}
Example 83
Project: pegadi-master  File: FOPPublisher.java View source code
public Document generateFO(Article article) {
    Document doc = null;
    TransformerFactory tFactory = TransformerFactory.newInstance();
    try {
        Transformer transformer = tFactory.newTransformer(new StreamSource(getXmlPath() + "/" + getStylesheet(article, PublishingMediaEnum.PDF).getStylesheetURL()));
        setParameters(transformer, article);
        if (transformerProperties != null) {
            for (Map.Entry e : transformerProperties.entrySet()) {
                transformer.setParameter((String) e.getKey(), e.getValue());
            }
        } else {
            transformer.setParameter("printarticle", "true");
        }
        transformer.setOutputProperties(getOutputProperties());
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        doc = builder.newDocument();
        transformer.transform(new DOMSource(article.getDocument()), new DOMResult(doc));
    } catch (Exception e) {
        log.error("Exception when generating FO document", e);
    }
    return doc;
}
Example 84
Project: quercus-master  File: XMLOutputFactoryImpl.java View source code
/**
   *  This method is optional.
   */
public XMLStreamWriter createXMLStreamWriter(Result result) throws XMLStreamException {
    if (result instanceof DOMResult) {
        return new DOMResultXMLStreamWriterImpl((DOMResult) result, _repair);
    } else if (result instanceof SAXResult) {
        return new SAXResultXMLStreamWriterImpl((SAXResult) result);
    } else if (result instanceof StreamResult) {
        Writer writer = ((StreamResult) result).getWriter();
        if (writer != null)
            return createXMLStreamWriter(writer);
        OutputStream os = ((StreamResult) result).getOutputStream();
        if (os != null)
            return createXMLStreamWriter(os);
        throw new XMLStreamException("StreamResult has no output stream or writer");
    }
    throw new UnsupportedOperationException(L.l("Results of type {0} are not supported", result.getClass().getName()));
}
Example 85
Project: richfaces-cdk-master  File: ElementsHandler.java View source code
@Override
public ModelElement getElement(DOMResult rt) {
    Element domElement = getDomElement(rt);
    AnyElement element = JAXB.unmarshal(new DOMSource(domElement), AnyElement.class);
    String prefix = domElement.getPrefix();
    QName name = new QName(domElement.getNamespaceURI(), domElement.getLocalName(), null != prefix ? prefix : XMLConstants.DEFAULT_NS_PREFIX);
    element.setName(name);
    return element;
}
Example 86
Project: smooks-editor-master  File: CSVDataParser.java View source code
public TagList parseCSV(InputStream stream, String fields, String rootName, String recordName, String separator, String quoteChar, String skiplines, String encoding) {
    Smooks smooks = new Smooks();
    // SmooksResourceConfiguration readerConfig = new
    // SmooksResourceConfiguration("org.xml.sax.driver",
    // CSVReader.class.getName());
    //		if ((quoteChar == null) || (encoding == null) || (fields == null)) {
    //			return null;
    //		}
    //		if (quoteChar == null)
    //			quoteChar = "\""; //$NON-NLS-1$
    //		if (skiplines == null)
    //			skiplines = "0"; //$NON-NLS-1$
    //		if (encoding == null)
    //			encoding = "UTF-8"; //$NON-NLS-1$
    CSVReaderConfigurator readerConfigurator = new CSVReaderConfigurator(fields);
    if (separator != null && separator.length() >= 1) {
        readerConfigurator.setSeparatorChar(separator.toCharArray()[0]);
    }
    if (quoteChar != null && quoteChar.length() >= 1) {
        readerConfigurator.setQuoteChar(quoteChar.toCharArray()[0]);
    }
    if (skiplines != null) {
        try {
            readerConfigurator.setSkipLineCount(Integer.parseInt(skiplines));
        } catch (Throwable t) {
        }
    }
    if (rootName != null) {
        readerConfigurator.setRootElementName(rootName);
    }
    if (recordName != null) {
        readerConfigurator.setRecordElementName(recordName);
    }
    readerConfigurator.setEncoding(Charset.forName(encoding));
    // readerConfigurator.setIndent(indent)
    smooks.setReaderConfig(readerConfigurator);
    DOMResult result = new DOMResult();
    smooks.filterSource(new StreamSource(stream), result);
    Document document = (Document) result.getNode();
    XMLObjectAnalyzer analyzer = new XMLObjectAnalyzer();
    TagList tagList = analyzer.analyze(document, null, null);
    try {
        if (smooks != null) {
            smooks.close();
            smooks = null;
        }
        if (stream != null) {
            stream.close();
            stream = null;
        }
        result = null;
    } catch (Throwable t) {
        t.printStackTrace();
    }
    return tagList;
}
Example 87
Project: spring-integration-samples-master  File: WeatherMarshaller.java View source code
public Object unmarshal(Source source) throws IOException, XmlMappingException {
    //this.writeXml(((DOMSource)source).getNode().getOwnerDocument());
    DOMResult result = null;
    try {
        Transformer transformer = transformerFactory.newTransformer();
        result = new DOMResult();
        transformer.transform(source, result);
    } catch (Exception e) {
        throw new MarshallingFailureException("Failed to unmarshal SOAP Response", e);
    }
    Weather weather = new Weather();
    String expression = xpathPrefix + "p:City";
    String city = XPathExpressionFactory.createXPathExpression(expression, namespacePrefixes).evaluateAsString(result.getNode());
    weather.setCity(city);
    expression = xpathPrefix + "p:State";
    String state = XPathExpressionFactory.createXPathExpression(expression, namespacePrefixes).evaluateAsString(result.getNode());
    weather.setState(state);
    expression = xpathPrefix + "p:Temperature";
    String temperature = XPathExpressionFactory.createXPathExpression(expression, namespacePrefixes).evaluateAsString(result.getNode());
    weather.setTemperature(temperature);
    expression = xpathPrefix + "p:Description";
    String description = XPathExpressionFactory.createXPathExpression(expression, namespacePrefixes).evaluateAsString(result.getNode());
    weather.setDescription(description);
    return weather;
}
Example 88
Project: teamengine-master  File: XSLTransformationParser.java View source code
public Document parse(URLConnection uc, Element instruction, PrintWriter logger) throws Exception {
    HashMap<String, String> properties = new HashMap<String, String>();
    properties.putAll(defaultProperties);
    HashMap<String, String> params = new HashMap<String, String>();
    params.putAll(defaultParams);
    Boolean ignoreErrors = defaultIgnoreErrors;
    Boolean ignoreWarnings = defaultIgnoreWarnings;
    Templates templates = parseInstruction(instruction, properties, params, ignoreErrors, ignoreWarnings);
    Transformer t = null;
    if (templates != null) {
        t = templates.newTransformer();
    } else if (defaultTemplates != null) {
        t = defaultTemplates.newTransformer();
    } else {
        t = tf.newTransformer();
    }
    for (Entry<String, String> prop : properties.entrySet()) {
        t.setOutputProperty(prop.getKey(), prop.getValue());
    }
    for (Entry<String, String> param : params.entrySet()) {
        // System.out.println(param.getKey() + ": " + param.getValue());
        t.setParameter(param.getKey(), param.getValue());
    }
    XSLTransformationErrorHandler el = new XSLTransformationErrorHandler(logger, ignoreErrors, ignoreWarnings);
    t.setErrorListener(el);
    Document doc = db.newDocument();
    InputStream is = null;
    try {
        if (LOGR.isLoggable(Level.FINER)) {
            String msg = String.format("Attempting to transform source from %s using instruction set:\n %s", uc.getURL(), DomUtils.serializeNode(instruction));
            LOGR.finer(msg);
        }
        // may return error stream
        is = URLConnectionUtils.getInputStream(uc);
        t.transform(new StreamSource(is), new DOMResult(doc));
    } catch (TransformerException e) {
        el.error(e);
    } finally {
        if (null != is)
            is.close();
    }
    if (el.getErrorCount() > 0 && !ignoreErrors) {
        return null;
    }
    if (el.getWarningCount() > 0 && !ignoreWarnings) {
        return null;
    }
    return doc;
}
Example 89
Project: testcases-master  File: MockPDPImpl.java View source code
private RequestType requestSourceToRequestType(Source requestSource) {
    try {
        Transformer trans = TransformerFactory.newInstance().newTransformer();
        DOMResult res = new DOMResult();
        trans.transform(requestSource, res);
        Node nd = res.getNode();
        if (nd instanceof Document) {
            nd = ((Document) nd).getDocumentElement();
        }
        return (RequestType) OpenSAMLUtil.fromDom((Element) nd);
    } catch (Exception e) {
        throw new RuntimeException("Error converting pdp response to ResponseType", e);
    }
}
Example 90
Project: uPortal-master  File: BaseXsltDataUpgraderTest.java View source code
protected void testXsltUpgrade(final Resource xslResource, final PortalDataKey dataKey, final Resource inputResource, final Resource expectedResultResource, final Resource xsdResource) throws Exception {
    final XmlUtilities xmlUtilities = new XmlUtilitiesImpl() {

        @Override
        public Templates getTemplates(Resource stylesheet) throws TransformerConfigurationException, IOException {
            final TransformerFactory transformerFactory = TransformerFactory.newInstance();
            return transformerFactory.newTemplates(new StreamSource(stylesheet.getInputStream()));
        }
    };
    final XsltDataUpgrader xsltDataUpgrader = new XsltDataUpgrader();
    xsltDataUpgrader.setPortalDataKey(dataKey);
    xsltDataUpgrader.setXslResource(xslResource);
    xsltDataUpgrader.setXmlUtilities(xmlUtilities);
    xsltDataUpgrader.afterPropertiesSet();
    //Create XmlEventReader (what the JaxbPortalDataHandlerService has)
    final XMLInputFactory xmlInputFactory = xmlUtilities.getXmlInputFactory();
    final XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(inputResource.getInputStream());
    final Node sourceNode = xmlUtilities.convertToDom(xmlEventReader);
    final DOMSource source = new DOMSource(sourceNode);
    final DOMResult result = new DOMResult();
    xsltDataUpgrader.upgradeData(source, result);
    //XSD Validation
    final String resultString = XmlUtilitiesImpl.toString(result.getNode());
    if (xsdResource != null) {
        final Schema schema = this.loadSchema(new Resource[] { xsdResource }, XMLConstants.W3C_XML_SCHEMA_NS_URI);
        final Validator validator = schema.newValidator();
        try {
            validator.validate(new StreamSource(new StringReader(resultString)));
        } catch (Exception e) {
            throw new XmlTestException("Failed to validate XSLT output against provided XSD", resultString, e);
        }
    }
    XMLUnit.setIgnoreWhitespace(true);
    XMLUnit.setNormalizeWhitespace(true);
    try {
        Diff d = new Diff(new InputStreamReader(expectedResultResource.getInputStream()), new StringReader(resultString));
        assertTrue("Upgraded data doesn't match expected data: " + d, d.similar());
    } catch (Exception e) {
        throw new XmlTestException("Failed to assert similar between XSLT output and expected XML", resultString, e);
    } catch (Error e) {
        throw new XmlTestException("Failed to assert similar between XSLT output and expected XML", resultString, e);
    }
}
Example 91
Project: vtechworks-master  File: XMLUtil.java View source code
/**
     * Applies a stylesheet (that receives parameters) to a given xml document.
     * 
     * @param xmlDocument
     *            the xml document to be transformed
     * @param parameters
     *            the hashtable with the parameters to be passed to the
     *            stylesheet
     * @param xsltFilename
     *            the filename of the stylesheet
     * @return the transformed xml document
     * @throws Exception
     */
public static Document transformDocument(Document xmlDocument, Map<String, String> parameters, String xsltFilename) throws Exception {
    // Generate a Transformer.
    Transformer transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(xsltFilename));
    // set transformation parameters
    if (parameters != null) {
        for (Map.Entry<String, String> param : parameters.entrySet()) {
            transformer.setParameter(param.getKey(), param.getValue());
        }
    }
    // Create an empty DOMResult object for the output.
    DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
    dFactory.setNamespaceAware(true);
    DocumentBuilder dBuilder = dFactory.newDocumentBuilder();
    Document dstDocument = dBuilder.newDocument();
    DOMResult domResult = new DOMResult(dstDocument);
    // Perform the transformation.
    transformer.transform(new DOMSource(xmlDocument), domResult);
    // Now you can get the output Node from the DOMResult.
    return dstDocument;
}
Example 92
Project: wicket-stuff-markup-validator-master  File: ValidatorImpl.java View source code
public void validate(Source source, Result result) throws SAXException, IOException {
    if (source == null)
        throw new NullPointerException();
    try {
        if (source instanceof SAXSource) {
            if (result != null && !(result instanceof SAXResult))
                throw new IllegalArgumentException();
            doValidate((SAXSource) source, result);
        } else if (source instanceof StreamSource) {
            if (result != null && !(result instanceof StreamResult))
                throw new IllegalArgumentException();
            doValidate(new SAXSource(SAXSource.sourceToInputSource(source)), result);
        } else if (source instanceof DOMSource) {
            if (result != null && !(result instanceof DOMResult))
                throw new IllegalArgumentException();
            doValidate((DOMSource) source, (DOMResult) result);
        } else
            throw new IllegalArgumentException("unsupported type of Source: " + source.getClass().getName());
    } catch (TransformerException e) {
        throw new SAXException(e);
    }
}
Example 93
Project: wikbook-master  File: AbstractSyntaxTestCase.java View source code
private void doTest(String testPath, Test... tests) throws Exception {
    File base = new File(System.getProperty("basedir"));
    File path = new File(base, "src/test/resources/wiki" + testPath);
    assertTrue(path.isDirectory());
    for (Test test : tests) {
        // We reinstantiate the context per test in order to reset the same initial state (matters for some unit
        // test like program listing with code citations
        SimpleXDOMDocbookBuilderContext context = new SimpleXDOMDocbookBuilderContext(path);
        context.setProperty("property_name", "propertyvalue");
        File file = new File(path, test.fileName + ".wiki");
        if (file.exists()) {
            DOMResult dom = new DOMResult();
            WikbookConverter converter = new WikbookConverter(context);
            converter.setEmitDoctype(false);
            converter.setSyntaxId(test.syntaxId);
            converter.setFormat(getFormat());
            converter.convert(test.fileName + ".wiki", dom);
            Document document = (Document) dom.getNode();
            //
            File f = new File(resultsDir, "test" + testPath.replace('/', '-') + "-" + test.fileName + ".xml");
            String result = XML.serialize(document);
            FileOutputStream out = new FileOutputStream(f);
            try {
                out.write(result.getBytes("UTF-8"));
            } finally {
                Utils.safeClose(out);
            }
            //
            File expected = new File(path, test.fileName + ".xml");
            if (!expected.exists() || !expected.isFile()) {
                expected = new File(path, "expected.xml");
            }
            if (expected.exists() && expected.isFile()) {
                Document expectedDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(expected);
                XMLUnit.setIgnoreAttributeOrder(true);
                XMLUnit.setIgnoreComments(true);
                XMLUnit.setIgnoreWhitespace(true);
                DetailedDiff diff = new DetailedDiff(new Diff(expectedDocument, document));
                List diffs = diff.getAllDifferences();
                if (diffs.size() > 0) {
                    String expectedXML = XML.serialize(expectedDocument);
                    String xml = XML.serialize(document);
                    String msg = "expected XML:\n" + expectedXML + "\n" + "effective XML:\n" + xml + "\n" + "Was expecting no difference between documents for path " + testPath + " : " + diff.toString();
                    fail(msg);
                }
            }
        }
    }
}
Example 94
Project: yangtools-master  File: DomUtils.java View source code
public static void serializeXmlValue(final Element element, final TypeDefinition<? extends TypeDefinition<?>> type, final XmlCodecProvider codecProvider, final Object value) {
    try {
        final XMLStreamWriter writer = XMLOutputFactory.newFactory().createXMLStreamWriter(new DOMResult(element));
        XmlStreamUtils.create(codecProvider).writeValue(writer, type, value);
    } catch (final XMLStreamException e) {
        throw new IllegalStateException("XML encoding failed", e);
    }
}
Example 95
Project: midpoint-master  File: TestSchemaRegistry.java View source code
/**
	 * Test whether the midpoint prism context was constructed OK and if it can validate
	 * ordinary user object.
	 */
@Test
public void testBasic() throws SAXException, IOException, SchemaException {
    MidPointPrismContextFactory factory = getContextFactory();
    PrismContext context = factory.createInitializedPrismContext();
    SchemaRegistry reg = context.getSchemaRegistry();
    Schema javaxSchema = reg.getJavaxSchema();
    assertNotNull(javaxSchema);
    // Try to use the schema to validate Jack
    //		PrismObject<UserType> user = context.parseObject(new File("src/test/resources/common/user-jack.xml"));
    //		Element document = context.serializeToDom(user);
    Document document = DOMUtil.parseFile("src/test/resources/common/user-jack.xml");
    Validator validator = javaxSchema.newValidator();
    DOMResult validationResult = new DOMResult();
    validator.validate(new DOMSource(document), validationResult);
//		System.out.println("Validation result:");
//		System.out.println(DOMUtil.serializeDOMToString(validationResult.getNode()));
}
Example 96
Project: archiv-editor-master  File: XSLTProcessor.java View source code
/**
	 * Processes the XSLT transformation of the XML input on which this 
	 * {@link XSLTProcessor} was instantiated. Since no output resource is
	 * passed, the result will be stored internally as a {@link DOMResult}
	 * which can be fetched from {@link #result()}, which for its part converts 
	 * the output to an {@link XMLContainer}.
	 * @return true if everything went right
	 */
public final boolean process() {
    if (_trans != null) {
        if (_result == null) {
            System.out.println("Setting up result object");
            _result = new DOMResult();
        }
        try {
            _trans.transform(_source, _result);
        } catch (TransformerException e) {
            System.out.println("Could not transform");
            e.printStackTrace();
            return false;
        }
        return true;
    } else {
        System.out.println("No Transformer instantiated. Was a XSL style sheet loaded?");
        return false;
    }
}
Example 97
Project: boilerpipe-android-master  File: DOMResultAugmentor.java View source code
public void setDOMResult(DOMResult result) {
    fIgnoreChars = false;
    if (result != null) {
        //MF - Renamed - Resourced
        final Node target = (Node) result.getNode();
        fDocument = (target.getNodeType() == Node.DOCUMENT_NODE) ? (Document) target : target.getOwnerDocument();
        fDocumentImpl = (fDocument instanceof CoreDocumentImpl) ? (CoreDocumentImpl) fDocument : null;
        fStorePSVI = (fDocument instanceof PSVIDocumentImpl);
        return;
    }
    fDocument = null;
    fDocumentImpl = null;
    fStorePSVI = false;
}
Example 98
Project: callingruby-master  File: XSLTEngine.java View source code
/**
     * Evaluate an expression. In this case, an expression is assumed
     * to be a stylesheet of the template style (see the XSLT spec).
     */
public Object eval(String source, int lineNo, int columnNo, Object oscript) throws BSFException {
    // get the style base URI (the place from where Xerces XSLT will
    // look for imported/included files and referenced docs): if a
    // bean named "xslt:styleBaseURI" is registered, then cvt it
    // to a string and use that. Otherwise use ".", which means the
    // base is the directory where the process is running from
    Object sbObj = mgr.lookupBean("xslt:styleBaseURI");
    String styleBaseURI = (sbObj == null) ? "." : sbObj.toString();
    // Locate the stylesheet.
    StreamSource styleSource;
    styleSource = new StreamSource(new StringReader(oscript.toString()));
    styleSource.setSystemId(styleBaseURI);
    try {
        transformer = tFactory.newTransformer(styleSource);
    } catch (Exception e) {
        logger.error("Exception from Xerces XSLT:", e);
        throw new BSFException(BSFException.REASON_EXECUTION_ERROR, "Exception from Xerces XSLT: " + e, e);
    }
    // get the src to work on: if a bean named "xslt:src" is registered
    // and its a Node, then use it as the source. If its not a Node, then
    // if its a URL parse it, if not treat it as a file and make a URL and
    // parse it and go. If no xslt:src is found, use an empty document
    // (stylesheet is treated as a literal result element stylesheet)
    Object srcObj = mgr.lookupBean("xslt:src");
    Object xis = null;
    if (srcObj != null) {
        if (srcObj instanceof Node) {
            xis = new DOMSource((Node) srcObj);
        } else {
            try {
                String mesg = "as anything";
                if (srcObj instanceof Reader) {
                    xis = new StreamSource((Reader) srcObj);
                    mesg = "as a Reader";
                } else if (srcObj instanceof File) {
                    xis = new StreamSource((File) srcObj);
                    mesg = "as a file";
                } else {
                    String srcObjstr = srcObj.toString();
                    xis = new StreamSource(new StringReader(srcObjstr));
                    if (srcObj instanceof URL) {
                        mesg = "as a URL";
                    } else {
                        ((StreamSource) xis).setPublicId(srcObjstr);
                        mesg = "as an XML string";
                    }
                }
                if (xis == null) {
                    throw new Exception("Unable to get input from '" + srcObj + "' " + mesg);
                }
            } catch (Exception e) {
                throw new BSFException(BSFException.REASON_EXECUTION_ERROR, "BSF:XSLTEngine: unable to get " + "input from '" + srcObj + "' as XML", e);
            }
        }
    } else {
        // create an empty document - real src must come into the 
        // stylesheet using "doc(...)" [see XSLT spec] or the stylesheet
        // must be of literal result element type
        xis = new StreamSource();
    }
    // set all declared beans as parameters.
    for (int i = 0; i < declaredBeans.size(); i++) {
        BSFDeclaredBean b = (BSFDeclaredBean) declaredBeans.elementAt(i);
        transformer.setParameter(b.name, new XObject(b.bean));
    }
    // declare a "bsf" parameter which is the BSF handle so that 
    // the script can do BSF stuff if it wants to
    transformer.setParameter("bsf", new XObject(new BSFFunctions(mgr, this)));
    // do it
    try {
        DOMResult result = new DOMResult();
        transformer.transform((StreamSource) xis, result);
        return new XSLTResultNode(result.getNode());
    } catch (Exception e) {
        throw new BSFException(BSFException.REASON_EXECUTION_ERROR, "exception while eval'ing XSLT script" + e, e);
    }
}
Example 99
Project: CORISCO2-master  File: XMLUtil.java View source code
/**
     * Applies a stylesheet (that receives parameters) to a given xml document.
     * 
     * @param xmlDocument
     *            the xml document to be transformed
     * @param parameters
     *            the hashtable with the parameters to be passed to the
     *            stylesheet
     * @param xsltFilename
     *            the filename of the stylesheet
     * @return the transformed xml document
     * @throws Exception
     */
public static Document transformDocument(Document xmlDocument, Hashtable parameters, String xsltFilename) throws Exception {
    // Generate a Transformer.
    Transformer transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(xsltFilename));
    // set transformation parameters
    if (parameters != null) {
        Enumeration keys = parameters.keys();
        while (keys.hasMoreElements()) {
            String key = (String) keys.nextElement();
            String value = (String) parameters.get(key);
            transformer.setParameter(key, value);
        }
    }
    // Create an empy DOMResult object for the output.
    DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
    dFactory.setNamespaceAware(true);
    DocumentBuilder dBuilder = dFactory.newDocumentBuilder();
    Document dstDocument = dBuilder.newDocument();
    DOMResult domResult = new DOMResult(dstDocument);
    // Perform the transformation.
    transformer.transform(new DOMSource(xmlDocument), domResult);
    // Now you can get the output Node from the DOMResult.
    return dstDocument;
}
Example 100
Project: droolsjbpm-integration-master  File: XMLResponseAggregator.java View source code
@Override
public String aggregate(List<String> data, String sortBy, boolean ascending, Integer page, Integer pageSize) {
    try {
        if (data == null || data.isEmpty()) {
            return null;
        }
        List<String> nodes = knownNames();
        Document document = data.stream().map( xml -> {
            return newDoc(xml);
        }).filter( d -> d != null).reduce(( source,  target) -> {
            deepMerge(source, target, nodes, target);
            return target;
        }).get();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Transformer transformer = null;
        String root = document.getDocumentElement().getNodeName();
        String sortNode = getElementLevel(root);
        if (sortBy != null && !sortBy.trim().isEmpty()) {
            transformer = sort(getRootNode(root), sortNode, sortBy, ascending, document);
            DOMResult toutput = new DOMResult();
            Source input = new DOMSource(document);
            transformer.transform(input, toutput);
            document = (Document) toutput.getNode();
        }
        transformer = page(getRootNode(root), sortNode, page, pageSize, document);
        Result output = new StreamResult(out);
        transformer.transform(new DOMSource(document), output);
        return new String(out.toByteArray());
    } catch (Exception e) {
        log.errorf("Failed to aggregate xml responses of %s", data, e);
        throw new RuntimeException(e);
    }
}
Example 101
Project: falcon-master  File: OozieUtils.java View source code
public static void marshalHiveAction(org.apache.falcon.oozie.workflow.ACTION wfAction, JAXBElement<org.apache.falcon.oozie.hive.ACTION> actionjaxbElement) {
    try {
        DOMResult hiveActionDOM = new DOMResult();
        Marshaller marshaller = HIVE_ACTION_JAXB_CONTEXT.createMarshaller();
        marshaller.marshal(actionjaxbElement, hiveActionDOM);
        wfAction.setAny(((Document) hiveActionDOM.getNode()).getDocumentElement());
    } catch (JAXBException e) {
        throw new RuntimeException("Unable to marshall hive action.", e);
    }
}