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:JAXPTransletOneTransformation.java

public static void main(String argv[]) throws TransformerException, TransformerConfigurationException,
        IOException, SAXException, ParserConfigurationException, FileNotFoundException {
    // Set the TransformerFactory system property to generate and use a translet.
    // Note: To make this sample more flexible, load properties from a properties file.    
    // The setting for the Xalan Transformer is "org.apache.xalan.processor.TransformerFactoryImpl"
    String key = "javax.xml.transform.TransformerFactory";
    String value = "org.apache.xalan.xsltc.trax.TransformerFactoryImpl";
    Properties props = System.getProperties();
    props.put(key, value);/*w w  w .  j  av  a  2s.c  o  m*/
    System.setProperties(props);

    String xslInURI = "todo.xsl";
    String xmlInURI = "todo.xml";
    String htmlOutURI = "todo.html";
    try {
        // Instantiate the TransformerFactory, and use it along with a SteamSource
        // XSL stylesheet to create a Transformer.
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer(new StreamSource(xslInURI));
        // Perform the transformation from a StreamSource to a StreamResult;
        transformer.transform(new StreamSource(xmlInURI), new StreamResult(new FileOutputStream(htmlOutURI)));
        System.out.println("Produced todo.html");
    } catch (Exception e) {
        System.out.println(e.toString());
        e.printStackTrace();
    }
}

From source file:org.jasig.portlet.maps.tools.MapDataTransformer.java

/**
 * @param args//from ww w .  j  a  v a2  s. c  o m
 */
public static void main(String[] args) {

    // translate the KML file to the map portlet's native data format
    File kml = new File("map-data.xml");
    File xslt = new File("google-earth.xsl");

    try {
        TransformerFactory transFact = javax.xml.transform.TransformerFactory.newInstance();
        Transformer trans = transFact.newTransformer(new StreamSource(xslt));
        trans.transform(new StreamSource(kml), new StreamResult(System.out));
    } catch (TransformerConfigurationException e) {
        e.printStackTrace();
    } catch (TransformerException e) {
        e.printStackTrace();
    }

    // deserialize the map data from XML
    MapData data = null;
    try {
        JAXBContext jc = JAXBContext.newInstance(MapData.class);
        Unmarshaller u = jc.createUnmarshaller();
        data = (MapData) u.unmarshal(new FileInputStream(new File("map-data-transformed.xml")));
    } catch (JAXBException e1) {
        e1.printStackTrace();
        return;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return;
    }

    // ensure each location has a unique, non-null abbreviation
    setAbbreviations(data);

    // update each location with an address
    //        setAddresses(data);

    // sort locations by name
    Collections.sort(data.getLocations(), new ByNameLocationComparator());

    // serialize new map data out to a file into JSON format
    try {
        mapper.defaultPrettyPrintingWriter().writeValue(new File("map.json"), data);
    } catch (JsonGenerationException e) {
        System.out.println("Error generating JSON data for map");
        e.printStackTrace();
    } catch (JsonMappingException e) {
        System.out.println("Error generating JSON data for map");
        e.printStackTrace();
    } catch (IOException e) {
        System.out.println("Error writing JSON data to map file");
        e.printStackTrace();
    }

}

From source file:JAXPTransletMultipleTransformations.java

public static void main(String argv[]) {
    // Set the TransformerFactory system property to generate and use translets.
    // Note: To make this sample more flexible, load properties from a properties file.
    // The setting for the Xalan Transformer is "org.apache.xalan.processor.TransformerFactoryImpl"
    String key = "javax.xml.transform.TransformerFactory";
    String value = "org.apache.xalan.xsltc.trax.TransformerFactoryImpl";
    Properties props = System.getProperties();
    props.put(key, value);/*  w w  w  .ja  v a 2 s  .  c o m*/

    System.setProperties(props);

    String xslInURI = "todo.xsl";

    try {
        // Instantiate the TransformerFactory, and use it along with a SteamSource
        // XSL stylesheet to create a translet as a Templates object.
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Templates translet = tFactory.newTemplates(new StreamSource(xslInURI));

        // Perform each transformation
        doTransform(translet, "todo.xml", "todo.html");
        System.out.println("Produced todo.html");

        doTransform(translet, "todotoo.xml", "todotoo.html");
        System.out.println("Produced todotoo.html");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:net.fenyo.gnetwatch.Documentation.java

/**
 * General entry point./* w  w w  . j a va 2 s  .co m*/
 * @param args command line arguments.
 * @return void.
 * @throws IOException io exception.
 */
public static void main(String[] args) throws IOException, TransformerConfigurationException,
        TransformerException, FileNotFoundException, FOPException {
    final String docbook_stylesheets_path = args[0];

    // Get configuration properties.
    final Config config = new Config();

    // Read general logging rules.
    GenericTools.initLogEngine(config);
    log.info(config.getString("log_engine_initialized"));
    log.info(config.getString("begin"));

    Transformer docbookTransformerHTML = TransformerFactory.newInstance()
            .newTransformer(new StreamSource(new File(docbook_stylesheets_path + "/html/docbook.xsl")));
    //    docbookTransformerHTML.setParameter("draft.mode", "no");

    docbookTransformerHTML.transform(new StreamSource(new FileReader(new File("gnetwatch-documentation.xml"))),
            new StreamResult(new FileWriter(new File("c:/temp/gnetwatch-documentation.html"))));

    Transformer docbookTransformerFO = TransformerFactory.newInstance()
            .newTransformer(new StreamSource(new File(docbook_stylesheets_path + "/fo/docbook.xsl")));
    //    docbookTransformerFO.setParameter("draft.mode", "no");

    docbookTransformerFO.transform(new StreamSource(new FileReader(new File("gnetwatch-documentation.xml"))),
            new StreamResult(new FileWriter(new File("c:/temp/gnetwatch-documentation.fo"))));

    // for very old FOP version (0.20):
    //    Driver driver = new Driver();
    //    driver.setRenderer(Driver.RENDER_PDF);
    //    driver.setInputSource(new InputSource(new FileReader(new File("c:/temp/gnetwatch-documentation.fo"))));
    //    driver.setOutputStream(new FileOutputStream(new File("c:/temp/gnetwatch-documentation.pdf")));
    //    driver.run();
    // with new FOP version:
    OutputStream outStream = new BufferedOutputStream(
            new FileOutputStream("c:/temp/gnetwatch-documentation.pdf"));
    final FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI());
    Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, outStream);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    Source source = new StreamSource(new FileReader(new File("c:/temp/gnetwatch-documentation.fo")));
    Result result = new SAXResult(fop.getDefaultHandler());
    transformer.transform(source, result);
    outStream.close();
}

From source file:ExternalConnection.java

public static void main(String[] args)
        throws TransformerException, TransformerConfigurationException, FileNotFoundException, IOException {

    // Create a connection to the database server
    // Up the connection pool count for testing
    DefaultConnectionPool cp = new DefaultConnectionPool();
    cp.setDriver("org.apache.derby.jdbc.EmbeddedDriver");
    cp.setURL("jdbc:derby:sampleDB");
    //cp.setUser("sa");
    //cp.setPassword("");
    cp.setMinConnections(10);//from w w w  .j a v  a2  s. co  m
    cp.setPoolEnabled(true);

    // Now let's register our connection pool so we can use
    // in a stylesheet
    ConnectionPoolManager pm = new ConnectionPoolManager();
    pm.registerPool("extpool", cp);

    // Use the static TransformerFactory.newInstance() method to instantiate
    // a TransformerFactory. The javax.xml.transform.TransformerFactory
    // system property setting determines the actual class to instantiate --
    // org.apache.xalan.transformer.TransformerImpl.
    TransformerFactory tFactory = TransformerFactory.newInstance();

    // Grab the Name of the Stylesheet from the commad line
    if (args.length == 0) {
        System.out.println("You must provide the path and name to a stylesheet to process");
        System.exit(0);
    }

    String stylesheet = args[0];
    System.out.println("Transforming Stylesheet " + stylesheet);

    // Use the TransformerFactory to instantiate a Transformer that will work with
    // the stylesheet you specify. This method call also processes the stylesheet
    // into a compiled Templates object.
    Transformer transformer = tFactory.newTransformer(new StreamSource(stylesheet));

    // For this transformation, all the required information is in the stylesheet, so generate 
    // a minimal XML source document for the input.
    // Note: the command-line processor (org.apache.xalan.xslt.Process) uses this strategy when 
    // the user does not provide an -IN parameter.
    StringReader reader = new StringReader("<?xml version=\"1.0\"?> <doc/>");

    // Use the Transformer to apply the associated Templates object to an XML document
    // and write the output to a file.
    transformer.transform(new StreamSource(reader), new StreamResult(new FileOutputStream("dbtest-out.html")));

    System.out.println("************* The result is in dbtest-out.html *************");

    cp.setPoolEnabled(false);
}

From source file:bpgead2pdf.java

/**
 * Main method./*from  w  w  w  .  j  av a2 s  . co  m*/
 * @param args command-line arguments
 */
public static void main(String[] args) {
    try {
        System.out.println("Preparing...");

        // Setup directories
        File baseDir = new File(".");
        File outDir = new File(baseDir, "out");
        outDir.mkdirs();

        // Setup input and output files
        File xmlfile = new File(args[0]);
        String xsltfile = new String("http://www.library.yale.edu/facc/xsl/fo/yul.ead2002.pdf.xsl");
        String pdffn = new String(FilenameUtils.getBaseName(args[0]) + ".pdf");
        File pdffile = new File(outDir, pdffn);

        System.out.println("Input: XML (" + xmlfile + ")");
        System.out.println("Stylesheet: " + xsltfile);
        System.out.println("Output: PDF (" + pdffile + ")");
        System.out.println();
        System.out.println("Transforming...");

        // configure fopFactory as desired
        FopFactory fopFactory = FopFactory.newInstance();

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

        // configure XSLT Processor
        Processor processor = new Processor(false);

        // Setup output
        OutputStream out = new java.io.FileOutputStream(pdffile);
        out = new java.io.BufferedOutputStream(out);

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

            // Setup XSLT
            XsltCompiler compiler = processor.newXsltCompiler();
            XsltExecutable transform = compiler.compile(new StreamSource(xsltfile));
            XsltTransformer transformer = transform.load();

            // Set the value of a <param> in the stylesheet
            // transformer.setParameter("versionParam", "2.0");

            // Setup input for XSLT transformation
            Source src = new StreamSource(xmlfile);

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

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

        } finally {
            out.close();
        }

        System.out.println("Success!");
    } catch (Exception e) {
        e.printStackTrace(System.err);
        System.exit(-1);
    }
}

From source file:com.arsdigita.util.parameter.ParameterPrinter.java

public static final void main(final String[] args) throws IOException {

    CommandLine line = null;//from  w  ww  .java  2 s.c o  m
    try {
        line = new PosixParser().parse(OPTIONS, args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }

    String[] outFile = line.getArgs();
    if (outFile.length != 1) {
        System.out.println("Usage: ParameterPrinter [--html] [--file config-list-file] output-file");
        System.exit(1);
    }
    if (line.hasOption("usage")) {
        System.out.println("Usage: ParameterPrinter [--html] [--file config-list-file] output-file");
        System.exit(0);
    }

    if (line.hasOption("file")) {
        String file = line.getOptionValue("file");
        try {
            BufferedReader reader = new BufferedReader(new FileReader(file));
            String configClass;
            while ((configClass = reader.readLine()) != null) {
                register(configClass);
            }
        } catch (IOException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    } else {
        register("com.arsdigita.runtime.RuntimeConfig");
        register("com.arsdigita.web.WebConfig");
        register("com.arsdigita.templating.TemplatingConfig");
        register("com.arsdigita.kernel.KernelConfig");
        register("com.arsdigita.kernel.security.SecurityConfig");
        register("com.arsdigita.mail.MailConfig");
        register("com.arsdigita.versioning.VersioningConfig");
        register("com.arsdigita.search.SearchConfig");
        register("com.arsdigita.search.lucene.LuceneConfig");
        register("com.arsdigita.kernel.security.SecurityConfig");
        register("com.arsdigita.bebop.BebopConfig");
        register("com.arsdigita.dispatcher.DispatcherConfig");
        register("com.arsdigita.workflow.simple.WorkflowConfig");
        register("com.arsdigita.cms.ContentSectionConfig");
    }

    if (line.hasOption("html")) {
        final StringWriter sout = new StringWriter();
        final PrintWriter out = new PrintWriter(sout);

        writeXML(out);

        final XSLTemplate template = new XSLTemplate(
                ParameterPrinter.class.getResource("ParameterPrinter_html.xsl"));

        final Source source = new StreamSource(new StringReader(sout.toString()));
        final Result result = new StreamResult(new File(outFile[0]));

        template.transform(source, result);
    } else {
        final PrintWriter out = new PrintWriter(new FileWriter(outFile[0]));

        writeXML(out);
    }
}

From source file:dk.defxws.fedoragsearch.server.GTransformer.java

public static void main(String[] args) {
    int argCount = 2;
    try {// w ww .  j a  v  a2  s.  c o m
        if (args.length == argCount) {
            File f = new File(args[1]);
            StreamSource ss = new StreamSource(new File(args[1]));
            GTransformer gt = new GTransformer();
            StreamResult destStream = new StreamResult(new StringWriter());
            gt.transform(args[0], ss, destStream);
            StringWriter sw = (StringWriter) destStream.getWriter();
            System.out.print(sw.getBuffer().toString());
        } else {
            throw new IOException("Must supply " + argCount + " arguments.");
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Usage: GTransformer xsltName xmlFileName");
    }
}

From source file:Main.java

public static Source getSource(String xml) {
    return new StreamSource(new StringReader(xml));
}

From source file:Main.java

public static String transform(String xmlString, String stylesheetPathname) throws TransformerException {
    try {/*w  ww . j ava2  s.  c  om*/
        TransformerFactory factory = TransformerFactory.newInstance();
        Source stylesheetSource = new StreamSource(new File(stylesheetPathname).getAbsoluteFile());
        Transformer transformer = factory.newTransformer(stylesheetSource);
        Source inputSource = new StreamSource(new StringReader(xmlString));
        Writer outputWriter = new StringWriter();
        Result outputResult = new StreamResult(outputWriter);
        transformer.transform(inputSource, outputResult);
        return outputWriter.toString();
    } catch (TransformerConfigurationException tce) {
        throw new TransformerException(tce.getMessageAndLocation());
    } catch (TransformerException te) {
        throw new TransformerException(te.getMessageAndLocation());
    }
}