Example usage for javax.xml.transform.stream StreamSource StreamSource

List of usage examples for javax.xml.transform.stream StreamSource StreamSource

Introduction

In this page you can find the example usage for javax.xml.transform.stream StreamSource StreamSource.

Prototype

public StreamSource(File f) 

Source Link

Document

Construct a StreamSource from a File.

Usage

From source file:Main.java

private static Transformer getThreadedTransformer(final boolean omitXmlDeclaration, final boolean standalone,
        final Map<Thread, Transformer> threadMap, final String xslURL)
        throws TransformerConfigurationException {
    final Thread currentThread = Thread.currentThread();
    Transformer transformer = null;
    if (threadMap != null) {
        transformer = threadMap.get(currentThread);
    }//from  www .j  av a  2  s . com
    if (transformer == null) {
        if (xslURL == null) {
            transformer = tFactory.newTransformer(); // "never null"
        } else {
            transformer = tFactory.newTransformer(new StreamSource(xslURL));
        }
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        if (threadMap != null) {
            threadMap.put(currentThread, transformer);
        }
    }
    transformer.setOutputProperty(OutputKeys.STANDALONE, standalone ? "yes" : "no");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, omitXmlDeclaration ? "yes" : "no");
    return transformer;
}

From source file:org.apache.servicemix.camel.JbiInOnlyWithErrorHandledTrueSpringDSLTest.java

public void testErrorHandledByExceptionClause() throws Exception {
    ServiceMixClient smxClient = getServicemixClient();
    MessageExchange[] exchanges = new MessageExchange[] { smxClient.createInOnlyExchange(),
            smxClient.createRobustInOnlyExchange() };
    for (MessageExchange exchange : exchanges) {
        exchange.setService(TEST_SERVICE);
        Source content = new StreamSource(new ByteArrayInputStream(MESSAGE.getBytes()));
        exchange.getMessage("in").setContent(content);

        smxClient.send(exchange);/*w  ww  .  ja va 2s.  c o  m*/

        exchange = smxClient.receive();
        assertEquals(ExchangeStatus.DONE, exchange.getStatus());
        assertNotNull(exchange.getProperty(Exchange.EXCEPTION_CAUGHT));
    }

    receiver.getMessageList().assertMessagesReceived(2);
    deadLetter.getMessageList().assertMessagesReceived(0);
}

From source file:org.web4thejob.orm.TypeSerailizationTest.java

@Test
public void simpleMarshallingTest() throws XmlMappingException, IOException {
    final Marshaller marshaller = ContextUtil.getBean(Marshaller.class);
    Assert.assertNotNull(marshaller);//w w w .j  a  v a  2 s  .c  o  m

    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final Result result = new StreamResult(out);
    final Master1 master1 = ContextUtil.getDRS().getOne(Master1.class);
    marshaller.marshal(master1, result);

    final Unmarshaller unmarshaller = ContextUtil.getBean(Unmarshaller.class);
    final Master1 master2 = (Master1) unmarshaller
            .unmarshal(new StreamSource(new ByteArrayInputStream(out.toByteArray())));

    Assert.assertEquals(master1, master2);
}

From source file:at.tfr.securefs.module.validation.SchemaValidationModule.java

@Override
public ModuleResult apply(InputStream input, ModuleConfiguration moduleConfiguration)
        throws ModuleException, IOException {
    SchemaResolver errorHandler = null;//from  w ww .ja va2  s .  co  m
    moduleStatistics.getCalls().incrementAndGet();

    try {
        // parse an XML document into a DOM tree
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setValidating(true);
        dbf.setCoalescing(true);
        dbf.setCoalescing(true);

        if (schema == null) {
            loadSchema(moduleConfiguration);
        }

        DOMImplementationLS domImpl = (DOMImplementationLS) dbf.newDocumentBuilder().getDOMImplementation();
        errorHandler = new SchemaResolver(configuration.getSchemaPath(), domImpl);

        Validator validator = schema.newValidator();
        validator.setErrorHandler(errorHandler);
        validator.setResourceResolver(errorHandler);

        validator.validate(new StreamSource(input));

    } catch (SAXParseException e) {
        moduleStatistics.getFailures().incrementAndGet();
        String message = "error validating: " + getCurrent() + " err: " + e;
        log.debug(message, e);
        log.info(message);
        if (moduleConfiguration.isMandatory()) {
            throw new ModuleException(message, e);
        } else {
            return new ModuleResult(false, e);
        }
    } catch (Exception e) {
        moduleStatistics.getErrors().incrementAndGet();
        String message = "error validating: " + getCurrent() + " err: " + e;
        log.info(message, e);
        log.warn(message);
        if (moduleConfiguration.isMandatory()) {
            throw new IOException(message, e);
        } else {
            return new ModuleResult(false, e);
        }
    }

    if (errorHandler != null && errorHandler.getErrors().size() > 0) {

        moduleStatistics.getFailures().incrementAndGet();

        String message = "Validation errors for File: " + getCurrent() + " errors: " + errorHandler.getErrors();
        if (log.isDebugEnabled()) {
            log.debug(message);
            if (log.isTraceEnabled()) {
                log.trace("Validation warnings for File: " + getCurrent() + " errors: "
                        + errorHandler.getWarnings());
            }
        }
        if (moduleConfiguration.isMandatory()) {
            throw new ModuleException(message);
        } else {
            log.info("accepted errors - " + message);
        }
        return new ModuleResult(false, errorHandler.getErrors().get(0));
    }

    moduleStatistics.getSuccesses().incrementAndGet();
    return new ModuleResult(true);
}

From source file:ee.ria.xroad.common.Request.java

/**
 * Converts the given SOAP message string to a pretty-printed format.
 * @param soap the SOAP XML to convert/*ww  w  .j av  a 2 s  .c o  m*/
 * @return pretty-printed String of the SOAP XML
 */
public static String prettyFormat(String soap) {
    try {
        Source xmlInput = new StreamSource(new StringReader(soap));
        StringWriter stringWriter = new StringWriter();
        StreamResult xmlOutput = new StreamResult(stringWriter);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();

        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        transformer.transform(xmlInput, xmlOutput);
        return xmlOutput.getWriter().toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:fr.xebia.springframework.jms.support.converter.JaxbMessageConverter.java

/**
 * <p>//from w  ww  .  ja  v a 2 s .  c om
 * Unmarshal given <code>message</code> into an <code>object</code>.
 * </p>
 * 
 * <p>
 * Should we raise an exception if the XML message encoding is not in sync with the underlying TextMessage encoding when the JMS
 * Provider supports MOM message's encoding ?
 * </p>
 * 
 * @param message
 *            message to unmarshal, MUST be an instance of {@link TextMessage} or of {@link BytesMessage}.
 * @see org.springframework.jms.support.converter.MessageConverter#fromMessage(javax.jms.Message)
 * @see org.springframework.oxm.Unmarshaller#unmarshal(Source)
 */
public Object fromMessage(Message message) throws JMSException, MessageConversionException {

    Source source;
    if (message instanceof TextMessage) {
        TextMessage textMessage = (TextMessage) message;
        source = new StringSource(textMessage.getText());

    } else if (message instanceof BytesMessage) {
        BytesMessage bytesMessage = (BytesMessage) message;
        byte[] bytes = new byte[(int) bytesMessage.getBodyLength()];
        bytesMessage.readBytes(bytes);
        source = new StreamSource(new ByteArrayInputStream(bytes));

    } else {
        throw new MessageConversionException("Unsupported JMS Message type " + message.getClass()
                + ", expected instance of TextMessage or BytesMessage for " + message);
    }
    Object result = jaxb2Marshaller.unmarshal(source);

    return result;
}

From source file:fi.mystes.synapse.mediator.util.XslTransformer.java

/**
 * Creates XSL transformer./*w w w .  ja v  a2 s  .  c om*/
 * 
 * @param xsl XSL style sheet to initialize transformer with
 * 
 * @return Initiated XSL transformer
 * 
 * @throws TransformerConfigurationException If transformer initialization fails
 */
private Transformer createTransformerFor(String xsl) throws TransformerConfigurationException {
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    return transformerFactory.newTransformer(new StreamSource(IOUtils.toInputStream(xsl)));
}

From source file:org.apache.servicemix.camel.JbiInOnlyWithFaultHandledTrueSpringDSLTest.java

public void testInOnlyWithFaultHandledByExceptionClause() throws Exception {
    ServiceMixClient smxClient = getServicemixClient();
    InOnly exchange = smxClient.createInOnlyExchange();
    exchange.setEndpoint(jbiContainer.getRegistry().getEndpointsForService(TEST_SERVICE)[0]);
    Source content = new StreamSource(new ByteArrayInputStream(MESSAGE.getBytes()));
    exchange.getMessage("in").setContent(content);

    smxClient.send(exchange);// w  w w  . java2s  .  c  o m

    exchange = (InOnly) smxClient.receive();
    assertEquals(ExchangeStatus.DONE, exchange.getStatus());
    assertNotNull(exchange.getProperty(Exchange.EXCEPTION_CAUGHT));

    deadLetter.getMessageList().assertMessagesReceived(0);
    receiver.getMessageList().assertMessagesReceived(1);
}

From source file:com.marklogic.client.functionaltest.TestBulkWriteWithTransformations.java

@Test
public void testBulkLoadWithXSLTClientSideTransform() throws Exception {
    String docId[] = { "/transform/emp.xml", "/transform/food1.xml", "/transform/food2.xml" };
    Source s[] = new Source[3];
    s[0] = new StreamSource("src/test/java/com/marklogic/client/functionaltest/data/employee.xml");
    s[1] = new StreamSource("src/test/java/com/marklogic/client/functionaltest/data/xml-original.xml");
    s[2] = new StreamSource("src/test/java/com/marklogic/client/functionaltest/data/xml-original-test.xml");
    // get the xslt
    Source xsl = new StreamSource(
            "src/test/java/com/marklogic/client/functionaltest/data/employee-stylesheet.xsl");

    // create transformer
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer(xsl);
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    XMLDocumentManager docMgr = client.newXMLDocumentManager();
    DocumentWriteSet writeset = docMgr.newWriteSet();
    for (int i = 0; i < 3; i++) {
        SourceHandle handle = new SourceHandle();
        handle.set(s[i]);//from w  w w  . ja  v a 2s .  c o  m
        // set the transformer
        handle.setTransformer(transformer);
        writeset.add(docId[i], handle);
        //Close handle.
        handle.close();
    }
    docMgr.write(writeset);
    FileHandle dh = new FileHandle();
    //       DOMHandle dh = new DOMHandle();
    docMgr.read(docId[0], dh);
    Scanner scanner = new Scanner(dh.get()).useDelimiter("\\Z");
    String readContent = scanner.next();
    assertTrue("xml document contains firstname", readContent.contains("firstname"));
    docMgr.read(docId[1], dh);
    Scanner sc1 = new Scanner(dh.get()).useDelimiter("\\Z");
    readContent = sc1.next();
    assertTrue("xml document contains firstname", readContent.contains("firstname"));
    docMgr.read(docId[2], dh);
    Scanner sc2 = new Scanner(dh.get()).useDelimiter("\\Z");
    readContent = sc2.next();
    assertTrue("xml document contains firstname", readContent.contains("firstname"));

}

From source file:mx.bigdata.sat.cfdi.TFDv11c33.java

public void validar(ErrorHandler handler) throws Exception {
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Source[] schemas = new Source[XSD.length];
    for (int i = 0; i < XSD.length; i++) {
        schemas[i] = new StreamSource(getClass().getResourceAsStream(XSD[i]));
    }// w ww  .ja v  a  2 s . c om
    Schema schema = sf.newSchema(schemas);
    Validator validator = schema.newValidator();
    if (handler != null) {
        validator.setErrorHandler(handler);
    }
    validator.validate(new JAXBSource(CONTEXT, tfd));
}