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.google.code.docbook4j.renderer.FORenderer.java

@Override
protected FileObject postProcess(final FileObject xmlSource, final FileObject xslSource,
        final FileObject xsltResult, final FileObject userConfigXml) throws Docbook4JException {

    FileObject target = null;/*  ww w .j a v a 2s .  c o m*/
    try {

        final FopFactory fopFactory = FopFactory.newInstance();

        final FOUserAgent userAgent = fopFactory.newFOUserAgent();
        userAgent.setBaseURL(xmlSource.getParent().getURL().toExternalForm());
        userAgent.setURIResolver(new VfsURIResolver());

        enhanceFOUserAgent(userAgent);

        String tmpPdf = "tmp://" + UUID.randomUUID().toString();
        target = FileObjectUtils.resolveFile(tmpPdf);
        target.createFile();

        Configuration configuration = createFOPConfig(userConfigXml);
        if (configuration != null) {
            fopFactory.setUserConfig(configuration);
            fopFactory.setBaseURL(userConfigXml.getParent().getURL().toExternalForm());
            fopFactory.setFontBaseURL(userConfigXml.getParent().getURL().toExternalForm());
        }

        Fop fop = fopFactory.newFop(getMimeType(), userAgent, target.getContent().getOutputStream());

        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer(); // identity
        // transformer
        transformer.setParameter("use.extensions", "1");
        transformer.setParameter("fop.extensions", "0");
        transformer.setParameter("fop1.extensions", "1");

        Source src = new StreamSource(xsltResult.getContent().getInputStream());
        Result res = new SAXResult(fop.getDefaultHandler());
        transformer.transform(src, res);
        return target;

    } catch (FileSystemException e) {
        throw new Docbook4JException("Error create filesystem manager!", e);
    } catch (TransformerException e) {
        throw new Docbook4JException("Error transforming fo to pdf!", e);
    } catch (FOPException e) {
        throw new Docbook4JException("Error transforming fo to pdf!", e);
    } catch (ConfigurationException e) {
        throw new Docbook4JException("Error loading user configuration!", e);
    } catch (SAXException e) {
        throw new Docbook4JException("Error loading user configuration!", e);
    } catch (IOException e) {
        throw new Docbook4JException("Error loading user configuration!", e);
    } finally {
        FileObjectUtils.closeFileObjectQuietly(target);
    }

}

From source file:io.konik.zugferd.RandomInvoiceTest.java

@Test
public void validateRandomInvoiceAgainstSchema() throws SAXException, IOException {
    //validate// w ww  .  j a  va  2 s .  c o m
    StringReader reader = new StringReader(randomInvoiceAsXml);
    getSchemaValidator().validate(new StreamSource(reader));
}

From source file:gov.nih.cadsr.transform.FilesTransformation.java

public static String transformFormToCSV(String xmlFile) {

    StringBuffer sb = null;//from   www.j  a  v a  2  s .  c o m

    try {

        File tf = new File("/local/content/cadsrapi/transform/xslt/", "formbuilder.xslt"); // template file
        String path = "/local/content/cadsrapi/transform/data/";
        String ext = "txt";
        File dir = new File(path);
        String name = String.format("%s.%s", RandomStringUtils.randomAlphanumeric(8), ext);
        File rf = new File(dir, name);

        if (tf == null || !tf.exists() || !tf.canRead()) {
            System.out.println("File path incorrect");
            return "";
        }

        long startTime = System.currentTimeMillis();

        //Obtain a new instance of a TransformerFactory. 
        TransformerFactory f = TransformerFactory.newInstance();
        // Process the Source into a Transformer Object...Construct a StreamSource from a File.
        Transformer t = f.newTransformer(new StreamSource(tf));

        //Construct a StreamSource from input and output
        Source s;
        try {
            s = new StreamSource((new ByteArrayInputStream(xmlFile.getBytes("utf-8"))));
            Result r = new StreamResult(rf);

            //Transform the XML Source to a Result.
            t.transform(s, r);
            System.out.println("Tranformation completed ...");
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            System.out.println(e1.toString());
        }

        //convert output file to string                                       
        try {
            BufferedReader bf = new BufferedReader(new FileReader(rf));
            sb = new StringBuffer();
            try {
                String currentLine;
                while ((currentLine = bf.readLine()) != null) {
                    sb.append(currentLine).append("\n");
                    //System.out.println(bf.readLine());

                }
            } catch (IOException e) {

                e.printStackTrace();
            }

        } catch (FileNotFoundException e) {

            e.printStackTrace();
        }

        long endTime = System.currentTimeMillis();
        System.out.println("Transformation took " + (endTime - startTime) + " milliseconds");
        System.out.println("Transformation took " + (endTime - startTime) / 1000 + " seconds");
    }

    catch (TransformerConfigurationException e) {
        System.out.println(e.toString());

    } catch (TransformerException e) {
        System.out.println(e.toString());

    }

    return sb.toString();
}

From source file:com.predic8.membrane.core.interceptor.schemavalidation.SchematronValidator.java

public SchematronValidator(ResolverMap resourceResolver, String schematron,
        ValidatorInterceptor.FailureHandler failureHandler, Router router, BeanFactory beanFactory)
        throws Exception {
    this.failureHandler = failureHandler;

    //works as standalone "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl"
    TransformerFactory fac;//from  ww  w  .  ja va 2 s.  co m
    try {
        fac = beanFactory.getBean("transformerFactory", TransformerFactory.class);
    } catch (NoSuchBeanDefinitionException e) {
        throw new RuntimeException(
                "Please define a bean called 'transformerFactory' in monitor-beans.xml, e.g. with "
                        + "<spring:bean id=\"transformerFactory\" class=\"com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl\" />",
                e);
    }
    fac.setURIResolver(new URIResolver() {
        @Override
        public Source resolve(String href, String base) throws TransformerException {
            return new StreamSource(SchematronValidator.class.getResourceAsStream(href));
        }
    });
    Transformer t = fac.newTransformer(
            new StreamSource(SchematronValidator.class.getResourceAsStream("conformance1-5.xsl")));

    // transform schematron-XML into XSLT
    DOMResult r = new DOMResult();
    t.transform(new StreamSource(router.getResolverMap().resolve(schematron)), r);

    // build XSLT transformers
    fac.setURIResolver(null);
    int concurrency = Runtime.getRuntime().availableProcessors() * 2;
    transformers = new ArrayBlockingQueue<Transformer>(concurrency);
    for (int i = 0; i < concurrency; i++) {
        Transformer transformer = fac.newTransformer(new DOMSource(r.getNode()));
        transformer.setErrorListener(new NullErrorListener()); // silence console logging
        transformers.put(transformer);
    }

    xmlInputFactory = XMLInputFactory.newInstance();
    xmlInputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false);
    xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
}

From source file:gov.nih.nci.integration.transformer.XSLTTransformer.java

/**
 * Performs xsl transformation on source XML
 * // w  w w . j  av  a2 s. c om
 * @param params the set of parameters to pass to the transformation, may be null
 * @param in XML input stream
 * @param out XML output stream
 * @throws IntegrationException exception
 */
public void transform(Map<String, String> params, InputStream in, OutputStream out)
        throws IntegrationException {
    if (params != null) { //NOPMD
        for (Entry<String, String> entry : params.entrySet()) {
            transformer.setParameter(entry.getKey(), entry.getValue());
        }
    }

    try {
        transformer.transform(new StreamSource(in), new StreamResult(out));
    } catch (TransformerException e) {
        LOG.error("XSLTTransformer..TransformerException while transforming the XML ", e);
        throw new IntegrationException(IntegrationError._1027, e);
    }
}

From source file:at.gv.egiz.slbinding.SLUnmarshaller.java

private static Schema createSchema(Collection<String> schemaUrls) throws SAXException, IOException {
    Logger log = LoggerFactory.getLogger(SLUnmarshaller.class);
    Source[] sources = new Source[schemaUrls.size()];
    Iterator<String> urls = schemaUrls.iterator();
    StringBuilder sb = null;//  w  w w  . ja va 2s  .co m
    if (log.isDebugEnabled()) {
        sb = new StringBuilder();
        sb.append("Created schema using URLs: ");
    }
    for (int i = 0; i < sources.length && urls.hasNext(); i++) {
        String url = urls.next();
        if (url != null && url.startsWith("classpath:")) {
            URL schemaUrl = new URL(null, url, new ClasspathURLStreamHandler());
            sources[i] = new StreamSource(schemaUrl.openStream());
        } else {
            sources[i] = new StreamSource(url);
        }
        if (sb != null) {
            sb.append(url);
            if (urls.hasNext()) {
                sb.append(", ");
            }
        }
    }
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = schemaFactory.newSchema(sources);
    if (sb != null) {
        log.debug(sb.toString());
    }
    return schema;
}

From source file:embedding.events.ExampleEvents.java

/**
 * Converts an FO file to a PDF file using FOP
 * @param fo the FO file/*from   ww w .  ja va2s . co  m*/
 * @param pdf the target PDF file
 * @throws IOException In case of an I/O problem
 * @throws FOPException In case of a FOP problem
 * @throws TransformerException In case of a problem with XSLT
 */
public void convertFO2PDF(URL fo, File pdf) throws IOException, FOPException, TransformerException {

    OutputStream out = null;

    try {
        //Create the user agent for this processing run
        FOUserAgent foUserAgent = fopFactory.newFOUserAgent();

        //Adding a simple logging listener that writes to stdout and stderr
        foUserAgent.getEventBroadcaster().addEventListener(new SysOutEventListener());

        // Add your own event listener
        foUserAgent.getEventBroadcaster().addEventListener(new MyEventListener());

        // configure foUserAgent further as desired

        // Setup output stream.  Note: Using BufferedOutputStream
        // for performance reasons (helpful with FileOutputStreams).
        out = new FileOutputStream(pdf);
        out = new BufferedOutputStream(out);

        // Construct fop with desired output format
        Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);

        // Setup JAXP using identity transformer
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer(); // identity transformer

        // Setup input stream
        Source src = new StreamSource(fo.toExternalForm());

        // Resulting SAX events (the generated FO) must be piped through to FOP
        Result res = new SAXResult(fop.getDefaultHandler());

        // Start XSLT transformation and FOP processing
        transformer.transform(src, res);

    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:gov.nih.nci.cabig.caaers.utils.XsltTransformer.java

/**
 * //w ww .  j a  v a 2s.c  om
 * @param inXml
 * @param outPdfFile
 * @param xsltFile
 * @throws Exception
 */
public void toPdf(String inXml, String outPdfFile, String xsltFile) throws Exception {

    String fo = getFO(inXml, xsltFile);
    // System.out.println(fo);

    FopFactory fopFactory = FopFactory.newInstance();

    OutputStream out = null;

    try {
        FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
        // configure foUserAgent as desired

        // Setup output stream. Note: Using BufferedOutputStream
        // for performance reasons (helpful with FileOutputStreams).
        out = new FileOutputStream(outPdfFile);
        out = new BufferedOutputStream(out);

        // Construct fop with desired output format
        Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);

        // Setup JAXP using identity transformer
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer(); // identity transformer
        // Setup input stream
        Source src = new StreamSource(new ByteArrayInputStream(fo.getBytes()));

        // Resulting SAX events (the generated FO) must be piped through to FOP
        Result res = new SAXResult(fop.getDefaultHandler());

        // Start XSLT transformation and FOP processing
        transformer.transform(src, res);

        // Result processing
        FormattingResults foResults = fop.getResults();
        java.util.List pageSequences = foResults.getPageSequences();
        for (java.util.Iterator it = pageSequences.iterator(); it.hasNext();) {
            PageSequenceResults pageSequenceResults = (PageSequenceResults) it.next();

            if (log.isInfoEnabled())
                log.info(
                        "PageSequence "
                                + (String.valueOf(pageSequenceResults.getID()).length() > 0
                                        ? pageSequenceResults.getID()
                                        : "<no id>")
                                + " generated " + pageSequenceResults.getPageCount() + " pages.");
        }
        if (log.isInfoEnabled())
            log.info("Generated " + foResults.getPageCount() + " pages in total.");

    } catch (Exception e) {
        throw new Exception(e);
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:com.github.lindenb.jvarkit.tools.blast.BlastFilterJS.java

@Override
protected Collection<Throwable> call(String inputName) throws Exception {

    final CompiledScript compiledScript;
    Unmarshaller unmarshaller;//from ww w. ja va  2s .  com
    Marshaller marshaller;
    try {
        compiledScript = super.compileJavascript();

        JAXBContext jc = JAXBContext.newInstance("gov.nih.nlm.ncbi.blast");

        unmarshaller = jc.createUnmarshaller();
        marshaller = jc.createMarshaller();

        XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
        xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
        xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
        xmlInputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE);
        xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        PrintWriter pw = openFileOrStdoutAsPrintWriter();
        XMLOutputFactory xof = XMLOutputFactory.newFactory();
        xof.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.FALSE);
        XMLEventWriter w = xof.createXMLEventWriter(pw);

        StreamSource src = null;
        if (inputName == null) {
            LOG.info("Reading stdin");
            src = new StreamSource(stdin());
        } else {
            LOG.info("Reading file " + inputName);
            src = new StreamSource(new File(inputName));
        }

        XMLEventReader r = xmlInputFactory.createXMLEventReader(src);

        XMLEventFactory eventFactory = XMLEventFactory.newFactory();

        SimpleBindings bindings = new SimpleBindings();
        while (r.hasNext()) {
            XMLEvent evt = r.peek();
            switch (evt.getEventType()) {
            case XMLEvent.START_ELEMENT: {
                StartElement sE = evt.asStartElement();
                Hit hit = null;
                JAXBElement<Hit> jaxbElement = null;
                if (sE.getName().getLocalPart().equals("Hit")) {
                    jaxbElement = unmarshaller.unmarshal(r, Hit.class);
                    hit = jaxbElement.getValue();
                } else {
                    w.add(r.nextEvent());
                    break;
                }

                if (hit != null) {

                    bindings.put("hit", hit);

                    boolean accept = super.evalJavaScriptBoolean(compiledScript, bindings);

                    if (accept) {
                        marshaller.marshal(jaxbElement, w);
                        w.add(eventFactory.createCharacters("\n"));
                    }
                }

                break;
            }
            case XMLEvent.SPACE:
                break;
            default: {
                w.add(r.nextEvent());
                break;
            }
            }
            r.close();
        }
        w.flush();
        w.close();
        pw.flush();
        pw.close();
        return RETURN_OK;
    } catch (Exception err) {
        return wrapException(err);
    } finally {

    }
}

From source file:nl.iwelcome.connector.google.GoogleAppsService.java

private GoogleAtom getCustomerId() {
    String token = googleAppsTemplate.getToken();
    byte[] bytes = googleAppsTemplate.getCustomerId(token);

    Reader reader = new InputStreamReader(new ByteArrayInputStream(bytes));

    Source source = new StreamSource(reader);
    GoogleAtom googleAtom = (GoogleAtom) marshaller.unmarshal(source);
    return googleAtom;
}