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:com.net2plan.utils.HTMLUtils.java

/**
 * Converts an XML file to a formatted HTML output via an XSLT definition.
 * //  w  w w  .  ja  v  a2 s.co  m
 * @param xml String containing an XML file
 * @param xsl URL containing an XSLT definition
 * @return Formatted HTML output
 */
public static String getHTMLFromXML(String xml, URL xsl) {
    try {
        Source xmlDoc = new StreamSource(new StringReader(xml));
        Source xslDoc = new StreamSource(xsl.openStream());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer(xslDoc);
        transformer.transform(xmlDoc, new StreamResult(baos));
        String html = baos.toString(StandardCharsets.UTF_8.name());
        html = prepareImagePath(html, xsl);
        return html;
    } catch (IOException | TransformerFactoryConfigurationError | TransformerException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.feedzai.fos.impl.r.RandomForestPMMLProducerConsumerTest.java

@Test
public void testCompressed() throws Exception {
    ModelConfig modelConfig = setupConfig();
    RManager rManager = setupManager();//from w w w  .  j a  v a2 s  . co m

    UUID uuid = rManager.trainAndAdd(modelConfig, RIntegrationTest.getTrainingInstances());

    File targetFile = Files.createTempFile("targetPMML", ".xml").toFile();

    // Save the model as PMML and load it.
    rManager.saveAsPMML(uuid, targetFile.getAbsolutePath(), true);

    try (FileInputStream fis = new FileInputStream(targetFile);
            GZIPInputStream gis = new GZIPInputStream(fis)) {

        JAXBUtil.unmarshalPMML(new StreamSource(gis));
    }

    targetFile.delete();
}

From source file:de.drv.dsrv.extra.marshaller.impl.ExtraUnmarschaller.java

@Override
public <X> X unmarshal(final InputStream inputStream, final Class<X> extraTransportClass,
        final boolean validation) throws XmlMappingException, IOException {
    Assert.notNull(inputStream, "InputStream is null");
    Assert.notNull(extraTransportClass, "ExtraTransportClass is null");
    final StreamSource inputStreamSource = new StreamSource(inputStream);
    return unmarshal(inputStreamSource, extraTransportClass, validation);
}

From source file:org.trpr.platform.integration.impl.xml.XMLTranscoderImpl.java

/**
 * Interface method implementation. Note that the package name specified should contain JAXB compatible generated classes/artifacts.
 * @see XMLTranscoder#unmarshal(String, Class)
 *//*from  w w  w . j  av  a2 s  .c  o  m*/
@SuppressWarnings("unchecked")
public <T> T unmarshal(String xml, Class<T> clazz) throws XMLDataException {
    StringReader stringReader = new StringReader(xml);
    try {
        if (this.getUnmarshaller() == this.defaultUnmarshaller) {
            // the default unmarshaller is not initialized with the context path. Initialize it by calling suitable methods
            this.defaultUnmarshaller.setContextPath(clazz.getPackage().getName());
            this.defaultUnmarshaller.afterPropertiesSet();
        }
        return (T) this.getUnmarshaller().unmarshal(new StreamSource(stringReader));
    } catch (Exception e) {
        throw new XMLDataException(
                "Error unmarshalling XML. XML:packageName is " + xml + ":" + clazz.getPackage().getName(), e);
    } finally {
        stringReader.close();
    }
}

From source file:de.extra.client.plugins.outputplugin.ws.WsOutputPlugin.java

/**
 * @see de.extrastandard.api.plugin.IOutputPlugin#outputData(java.io.InputStream)
 *//*from  w  w  w.j av  a2s.c  o  m*/
@Override
public ResponseTransport outputData(final RequestTransport requestTransport) {
    // 1. RequestTransport as Stream umwandeln. Prfen, ob es auch einfacher
    // geht.
    try {

        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        final StreamResult streamResult = new StreamResult(outputStream);
        marshaller.marshal(requestTransport, streamResult, outgoingXmlValidation);
        final ByteArrayInputStream requestAsStream = new ByteArrayInputStream(outputStream.toByteArray());

        logger.debug("sending request");
        operation_logger.info("Webservice Aufruf von: {}", endpointUrl);

        final ByteArrayOutputStream temp = new ByteArrayOutputStream();
        final StreamSource source = new StreamSource(requestAsStream);
        final StreamResult result = new StreamResult(temp);
        webServiceTemplate.sendSourceAndReceiveToResult(endpointUrl, source, result);
        // ResponseTransport aus Stream erzeugen
        final ResponseTransport extraResponse = extraUnmarschaller
                .unmarshal(new ByteArrayInputStream(temp.toByteArray()), ResponseTransport.class);
        return extraResponse;
    } catch (final SoapFaultClientException soapFaultClientException) {
        // Faengt eine vom Server gemeldete SoapFaultClientException ab
        operation_logger.error("Server meldet SOAP-Fehler: {}",
                soapFaultClientException.getFaultStringOrReason());
        final ExtraOutputPluginRuntimeException extraOutputPluginRuntimeException = extractSoapFaultClientException(
                soapFaultClientException);
        throw (extraOutputPluginRuntimeException);
    } catch (final XmlMappingException xmlMappingException) {
        final ExtraOutputPluginRuntimeException extraOutputPluginRuntimeException = new ExtraOutputPluginRuntimeException(
                xmlMappingException);
        throw (extraOutputPluginRuntimeException);
    } catch (final IOException ioException) {
        final ExtraOutputPluginRuntimeException extraOutputPluginRuntimeException = new ExtraOutputPluginRuntimeException(
                ioException);
        throw (extraOutputPluginRuntimeException);
    }

}

From source file:org.apache.taverna.scufl2.translator.t2flow.defaultactivities.AbstractActivityParser.java

public <ConfigType> ConfigType unmarshallXml(T2FlowParser t2FlowParser, String xml,
        Class<ConfigType> configType) throws ReaderException {
    Unmarshaller unmarshaller2 = t2FlowParser.getUnmarshaller();
    unmarshaller2.setSchema(null);/*w  ww . ja v a 2s.  co  m*/

    Source source = new StreamSource(new StringReader(xml));
    try {
        JAXBElement<ConfigType> configElemElem = unmarshaller2.unmarshal(source, configType);
        return configElemElem.getValue();
    } catch (JAXBException | ClassCastException e) {
        throw new ReaderException("Can't parse xml " + xml, e);
    }
}

From source file:no.difi.sdp.client.asice.signature.CreateSignatureTest.java

@Test
public void test_generated_signatures() {
    Signature signature = sut.createSignature(noekkelpar, files);
    XAdESSignatures xAdESSignatures = (XAdESSignatures) marshaller
            .unmarshal(new StreamSource(new ByteArrayInputStream(signature.getBytes())));

    assertThat(xAdESSignatures.getSignatures()).hasSize(1);
    org.w3.xmldsig.Signature dSignature = xAdESSignatures.getSignatures().get(0);
    verify_signed_info(dSignature.getSignedInfo());
    assertThat(dSignature.getSignatureValue()).isNotNull();
    assertThat(dSignature.getKeyInfo()).isNotNull();
}

From source file:ca.uhn.fhir.validation.SchemaBaseValidator.java

private void doValidate(IValidationContext<?> theContext, String schemaName) {
    Schema schema = loadSchema("dstu", schemaName);

    try {/*  w  ww.j  a  v a  2 s.c  o  m*/
        Validator validator = schema.newValidator();
        MyErrorHandler handler = new MyErrorHandler(theContext);
        validator.setErrorHandler(handler);
        String encodedResource;
        if (theContext.getResourceAsStringEncoding() == EncodingEnum.XML) {
            encodedResource = theContext.getResourceAsString();
        } else {
            encodedResource = theContext.getFhirContext().newXmlParser()
                    .encodeResourceToString((IBaseResource) theContext.getResource());
        }

        try {
            /*
             * See https://github.com/jamesagnew/hapi-fhir/issues/339
             * https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing
             */
            validator.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
            validator.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
        } catch (SAXNotRecognizedException ex) {
            ourLog.warn("Jaxp 1.5 Support not found.", ex);
        }

        validator.validate(new StreamSource(new StringReader(encodedResource)));
    } catch (SAXParseException e) {
        SingleValidationMessage message = new SingleValidationMessage();
        message.setLocationLine(e.getLineNumber());
        message.setLocationCol(e.getColumnNumber());
        message.setMessage(e.getLocalizedMessage());
        message.setSeverity(ResultSeverityEnum.FATAL);
        theContext.addValidationMessage(message);
    } catch (SAXException e) {
        // Catch all
        throw new ConfigurationException("Could not load/parse schema file", e);
    } catch (IOException e) {
        // Catch all
        throw new ConfigurationException("Could not load/parse schema file", e);
    }
}

From source file:com.quangphuong.crawler.util.XMLUtil.java

public void convertToFO(String xmlPath, String xsltInputPath, String foOutputPath)
        throws IOException, FOPException, TransformerException {
    File xsltFile = new File(rootPath, xsltInputPath);
    StreamSource xmlSource = new StreamSource(new File(rootPath, xmlPath));
    OutputStream out;//  w w w .ja v a 2 s.c om
    out = new java.io.FileOutputStream(new File(rootPath, foOutputPath));
    try {
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer(new StreamSource(xsltFile));
        Result res = new StreamResult(out);
        transformer.transform(xmlSource, res);
    } finally {
        out.close();
    }
}

From source file:fr.paris.lutece.plugins.document.web.DocumentMetaPageInclude.java

/**
 * Load the XSL stylesheet used to convert document metadata into meta tags
 * @return The source stream/*from   w  w w  .  j  a va 2s.  c om*/
 */
private Source loadXsl() {
    FileInputStream fis = AppPathService.getResourceAsStream(PATH_XSL, FILE_XSL);
    Source sourceXsl = new StreamSource(fis);

    return sourceXsl;
}