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:net.sourceforge.jaulp.xsl.transform.XsltTransformerUtilsTest.java

@Test(enabled = true)
public void testTransformSourceSourceOutputStream() throws TransformerException, IOException {
    final File resDestDir = PathFinder.getSrcTestResourcesDir();
    String[] dirsAndFilename = { "net", "sourceforge", "jaulp", "xsl", "transform", "birthdates.xml" };
    File xmlFile = PathFinder.getRelativePath(resDestDir, dirsAndFilename);
    File xsltFile = PathFinder.getRelativePathTo(resDestDir, "\\.", "net.sourceforge.jaulp.xsl.transform",
            "functions.xsl");
    InputStream is = StreamUtils.getInputStream(xsltFile);
    Source xsltSource = new StreamSource(is);

    InputStream xmlIs = StreamUtils.getInputStream(xmlFile);
    File outputFile = PathFinder.getRelativePathTo(resDestDir, "\\.", "net.sourceforge.jaulp.xsl.transform",
            "data_02_output.xml");
    OutputStream output = StreamUtils.getOutputStream(outputFile, true);
    Source xmlSource = new StreamSource(xmlIs);
    XsltTransformerUtils.transform(xmlSource, xsltSource, output);
    String actual = ReadFileUtils.readFromFile(outputFile);
    actual = StringUtils.remove(actual, '\r');
    actual = StringUtils.remove(actual, '\n');
    expected = StringUtils.remove(expected, '\r');
    expected = StringUtils.remove(expected, '\n');
    AssertJUnit.assertTrue("", expected.equals(actual));
}

From source file:de.mpg.mpdl.inge.transformation.transformations.LocalUriResolver.java

/**
 * {@inheritDoc}//from   www .ja  v  a  2 s . co m
 */
public final Source resolve(String href, String altBase) throws TransformerException {

    String path = null;

    if (altBase == null) {
        altBase = "";
    }

    try {

        if ("ves-mapping.xml".equals(href) || "vocabulary-mappings.xsl".equals(href)) {
            path = TRANS_PATH + href;
        } else if (href != null && href.matches("^https?://.*")) {
            HttpClient client = new HttpClient();
            GetMethod getMethod = new GetMethod(href);
            ProxyHelper.executeMethod(client, getMethod);
            return new StreamSource(getMethod.getResponseBodyAsStream());
        } else {
            path = this.base + altBase + "/" + href;
        }

        return new StreamSource(
                ResourceUtil.getResourceAsStream(path, LocalUriResolver.class.getClassLoader()));
    } catch (FileNotFoundException e) {
        // throw new TransformerException("Cannot resolve URI: " + href);
        throw new TransformerException("Cannot resolve URI: " + path, e);
    } catch (HttpException e) {
        throw new TransformerException("Cannot connect to URI: " + path, e);
    } catch (IOException e) {
        throw new TransformerException("Cannot get content from URI: " + path, e);
    }
}

From source file:gov.nih.nci.cabig.caaers.api.BlankFormGenerator.java

public synchronized void generatePdf(String xml, String pdfOutFileName) throws Exception {
    FopFactory fopFactory = FopFactory.newInstance();

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

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

    try {/*from  w  w  w. j  a v a2s .  c  om*/
        // Construct fop with desired output format
        Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);

        // Setup XSLT
        TransformerFactory factory = TransformerFactory.newInstance();
        //            System.out.println(factory == null);

        Transformer transformer = factory.newTransformer(
                new StreamSource(BlankFormGenerator.class.getClassLoader().getResourceAsStream(XSLFile)));
        //            Transformer transformer = factory.newTransformer(new StreamSource(XSLFile));

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

        // Setup XML String as input for XSLT transformation
        Source src = new StreamSource(new ByteArrayInputStream(xml.getBytes("UTF-8")));

        // 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 {
        out.close();
    }
}

From source file:edu.lternet.pasta.client.EmlUtility.java

private String emlReferenceExpander(String xslPath) throws ParseException {

    String xml = null;//from w  ww .  j a  v  a  2 s.  c o  m

    File styleSheet = new File(xslPath);

    StringReader stringReader = new StringReader(this.eml);
    StringWriter stringWriter = new StringWriter();
    StreamSource styleSource = new StreamSource(styleSheet);
    Result result = new StreamResult(stringWriter);
    Source source = new StreamSource(stringReader);

    try {
        Transformer t = TransformerFactory.newInstance().newTransformer(styleSource);
        t.transform(source, result);
        xml = stringWriter.toString();
    } catch (TransformerConfigurationException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } catch (TransformerFactoryConfigurationError e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } catch (TransformerException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
        throw new ParseException("EML Parse Error: " + e.getMessage(), 0);
    }

    return xml;

}

From source file:de.mpg.escidoc.services.transformation.transformations.LocalUriResolver.java

/**
 * {@inheritDoc}//from ww  w .j  a v a  2  s. c  o m
 */
public final Source resolve(String href, String altBase) throws TransformerException {

    String path = null;

    if (altBase == null) {
        altBase = "";
    }

    try {

        if ("ves-mapping.xml".equals(href) || "vocabulary-mappings.xsl".equals(href)) {
            path = TRANS_PATH + href;
        } else if (href != null && href.matches("^https?://.*")) {
            HttpClient client = new HttpClient();
            GetMethod getMethod = new GetMethod(href);
            ProxyHelper.executeMethod(client, getMethod);
            return new StreamSource(getMethod.getResponseBodyAsStream());
        } else {
            path = this.base + altBase + "/" + href;
        }

        return new StreamSource(
                ResourceUtil.getResourceAsStream(path, LocalUriResolver.class.getClassLoader()));
    } catch (FileNotFoundException e) {
        //throw new TransformerException("Cannot resolve URI: " + href);
        throw new TransformerException("Cannot resolve URI: " + path, e);
    } catch (HttpException e) {
        throw new TransformerException("Cannot connect to URI: " + path, e);
    } catch (IOException e) {
        throw new TransformerException("Cannot get content from URI: " + path, e);
    }
}

From source file:com.consol.citrus.admin.service.spring.SpringBeanService.java

@PostConstruct
protected void init() {
    transformerFactory.setURIResolver(new URIResolver() {
        @Override// w ww.j  a v a2  s .  c  om
        public Source resolve(String href, String base) throws TransformerException {
            try {
                return new StreamSource(new ClassPathResource("transform/" + href).getInputStream());
            } catch (IOException e) {
                throw new TransformerException("Failed to resolve uri: " + href, e);
            }
        }
    });
}

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

public Source resolve(String href, String base) throws TransformerException {
    Source source = null;/*from w ww .j  av  a  2s  . co  m*/
    URL url;
    try {
        url = new URL(href);
    } catch (MalformedURLException e) {
        // the XSLT processor should try to resolve the URI itself, 
        // here it may be a location path, which it can resolve
        if (logger.isDebugEnabled())
            logger.debug("resolve back to XSLT processor MalformedURLException href=" + href + " base=" + base
                    + " exception=" + e);
        return null;
    }
    String reposName = config.getRepositoryNameFromUrl(url);
    if (reposName == null || reposName.length() == 0) {
        // here other resolve mechanism may be coded, or
        // the XSLT processor should try to resolve the URI itself,
        // e.g. it can resolve the file protocol
        if (logger.isDebugEnabled())
            logger.debug("resolve back to XSLT processor no reposName href=" + href + " base=" + base + " url="
                    + url.toString());
        return null;
    }
    if (logger.isDebugEnabled())
        logger.debug("resolve get from repository href=" + href + " base=" + base + " url=" + url.toString()
                + " reposName=" + reposName);
    System.setProperty("javax.net.ssl.trustStore", config.getTrustStorePath(reposName));
    System.setProperty("javax.net.ssl.trustStorePassword", config.getTrustStorePass(reposName));
    WebClient client = new WebClient();
    try {
        if (logger.isDebugEnabled())
            logger.debug("resolve get from reposName=" + reposName + " source=\n"
                    + client.getResponseAsString(href, false, new UsernamePasswordCredentials(
                            config.getFedoraUser(reposName), config.getFedoraPass(reposName))));
        source = new StreamSource(
                client.get(href, false, config.getFedoraUser(reposName), config.getFedoraPass(reposName)));
    } catch (Exception e) {
        throw new TransformerException(
                "resolve get from reposName=" + reposName + " href=" + href + " base=" + base + " exception=\n",
                e);
    }
    return source;
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.jena.JenaXMLFileUpload.java

public void init() throws ServletException {
    super.init();
    File baseDir = new File(getServletContext().getRealPath("/xmlFileUpload"));

    if (baseDir.exists() && baseDir.isDirectory()) {
        System.out.println("JenaXMLFileUpload, found upload directory of " + baseDir.getAbsolutePath());
    } else {//www .j  a  va2  s  .  c  o m
        System.out.println(
                "Attemping to setup JenaXMLFileUpload with temp directory of " + baseDir.getAbsolutePath());
        baseDir.mkdir();
        if (baseDir.exists() && baseDir.isDirectory()) {
            System.out.println("Created directory " + baseDir.getAbsolutePath());
        } else {
            System.out.println("Could not create directory " + baseDir.getAbsolutePath());
        }
    }
    baseDirectoryForFiles = baseDir.getAbsolutePath();

    File xslt = new File(getServletContext().getRealPath("/xslt/xml2rdf.xsl"));
    System.out.println("JenaXMLFileUpload, attempting to load xslt " + xslt.getAbsolutePath());
    processor = new Processor(false);
    XsltCompiler compiler = processor.newXsltCompiler();
    try {
        xsltExec = compiler.compile(new StreamSource(xslt));
        System.out.println("JenaXMLFileUpload, loaded " + xslt.getAbsolutePath());
    } catch (SaxonApiException e) {
        System.out.println("could not compile xslt/xml2rdf.xsl");
        System.out.println(e.getMessage());
    }
}

From source file:om.edu.squ.squportal.portlet.dps.role.service.RoleServiceImpl.java

/**
 * /*  w  w  w  .j a v  a  2  s. c o  m*/
 * method name  : getRuleXmlToRoleObject
 * @param xmlFile
 * @return
 * @throws IOException
 * RoleServiceImpl
 * return type  : Object
 * 
 * purpose      : Convert XML to Object (Unmarshalling)
 *
 * Date          :   Feb 8, 2017 2:17:51 PM
 */
public Object getXmlToRoleObject(String xmlFile) throws IOException {
    Resource resource = new ClassPathResource(xmlFile);

    InputStream inputStream = resource.getInputStream();

    return unmarshaller.unmarshal(new StreamSource(inputStream));
}

From source file:it.intecs.pisa.toolbox.util.URLReader.java

public static Object getFullURLContent(String urlString) throws Exception {

    String returnString = "";

    URL url = null;/*  www  .  j ava2s  .  c  o m*/
    URLConnection connection = null;

    // Open Connection
    try {
        url = new URL(urlString);
    } catch (MalformedURLException ex) {
        ex.printStackTrace();
    }

    try {
        connection = url.openConnection();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    HttpURLConnection httpConn = (HttpURLConnection) connection;
    try {

        StreamSource source = new StreamSource(httpConn.getInputStream());

        TransformerFactory fac = TransformerFactory.newInstance();
        Transformer trans = null;
        StreamResult res = new StreamResult(new StringWriter());
        try {
            trans = fac.newTransformer();
        } catch (TransformerConfigurationException ex) {
            ex.printStackTrace();
        }
        try {

            trans.transform(source, res);
        } catch (TransformerException ex) {
            ex.printStackTrace();
        }
        StringWriter w = (StringWriter) res.getWriter();

        returnString = w.toString();

    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return returnString;
}