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.dnastack.bob.rest.BasicTest.java

public static Object readObject(Class c, String url) throws JAXBException, MalformedURLException {
    JAXBContext jc = JAXBContext.newInstance(c);

    Unmarshaller unmarshaller = jc.createUnmarshaller();
    unmarshaller.setProperty(JAXBContextProperties.MEDIA_TYPE, "application/json");
    unmarshaller.setProperty(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
    StreamSource source = new StreamSource(url);
    JAXBElement jaxbElement = unmarshaller.unmarshal(source, c);

    return jaxbElement.getValue();
}

From source file:com.lohika.alp.reporter.fe.controller.TestInstanceController.java

@RequestMapping(method = RequestMethod.POST, value = "/{testInstanceId}/test-methods")
String addTestMethod(Model model, @RequestBody String body, @PathVariable("suiteId") long suiteId,
        @PathVariable("testId") long testId) {
    // TODO implement XML controller

    Source source = new StreamSource(new StringReader(body));
    TestMethod testMethod = (TestMethod) jaxb2Mashaller.unmarshal(source);

    // Save to database

    // Set database id
    testMethod.setId(1L);//from w  ww.  j  av a 2  s . c om

    model.addAttribute(testMethod);
    return view;
}

From source file:edu.mayo.xsltserver.Transformer.java

/**
 * Transform.//from w w  w . ja  v a  2s  . c o m
 *
 * @param xmlInputStream the xml input stream
 * @param xsltInputStream the xslt input stream
 * @param outputStream the output stream
 * @param parameters the parameters
 */
public void transform(InputStream xmlInputStream, InputStream xsltInputStream, OutputStream outputStream,
        Map<String, String> parameters) {
    try {
        // Source XML File
        StreamSource xmlFile = new StreamSource(xmlInputStream);

        // Source XSLT Stylesheet
        StreamSource xsltFile = new StreamSource(xsltInputStream);
        TransformerFactory xsltFactory = TransformerFactory.newInstance();

        final URIResolver decoratedResolver = xsltFactory.getURIResolver();

        xsltFactory.setURIResolver(new URIResolver() {

            @Override
            public Source resolve(String href, String base) throws TransformerException {
                Source source = decoratedResolver.resolve(href,
                        fileService.getStorageDirectory() + File.separator);

                return source;
            }

        });

        javax.xml.transform.Transformer transformer = xsltFactory.newTransformer(xsltFile);

        if (parameters != null) {
            for (Entry<String, String> entry : parameters.entrySet()) {
                transformer.setParameter(entry.getKey(), entry.getValue());
            }
        }

        // Send transformed output to the console
        StreamResult resultStream = new StreamResult(outputStream);

        // Apply the transformation
        transformer.transform(xmlFile, resultStream);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.adaptris.util.text.XmlTransformerTest.java

@Test
public void testTransform() throws Exception {
    XmlTransformerFactory factory = new XsltTransformerFactory();
    XmlTransformer transform = factory.configure(new XmlTransformer());
    transform.registerBuilder(DocumentBuilderFactoryBuilder.newInstance());
    String xsl = backslashToSlash(PROPERTIES.getProperty(KEY_XML_TEST_TRANSFORM_URL));
    AdaptrisMessage m1 = MessageHelper.createMessage(PROPERTIES.getProperty(KEY_XML_TEST_INPUT));
    try (InputStream in = m1.getInputStream(); OutputStream out = m1.getOutputStream()) {
        StreamResult output = new StreamResult(out);
        StreamSource input = new StreamSource(in);
        transform.transform(factory.createTransformer(xsl), input, output, xsl,
                new HashMap<>(System.getProperties()));
    }//www.  ja v  a2 s  . co m
    AdaptrisMessage m2 = MessageHelper.createMessage(PROPERTIES.getProperty(KEY_XML_TEST_INPUT));

    try (InputStream in = m2.getInputStream(); OutputStream out = m2.getOutputStream()) {
        StreamResult output = new StreamResult(out);
        StreamSource input = new StreamSource(in);
        transform.transform(factory.createTransformer(xsl), input, output, xsl);
    }
}

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

public synchronized void generatePdf(String xml, String pdfOutFileName, String XSLFile) 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 {/*ww  w  .  jav  a2 s . c om*/
        // Construct fop with desired output format
        Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);

        // Setup XSLT
        TransformerFactory factory = TransformerFactory.newInstance();

        Transformer transformer = null;

        transformer = factory.newTransformer(
                new StreamSource(BasePDFGenerator.class.getClassLoader().getResourceAsStream(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:org.esigate.xml.XsltRenderer.java

private static Transformer createTransformer(InputStream templateStream) throws IOException {
    try {/*from  w ww  .j  a va 2  s  .c om*/
        return TRANSFORMER_FACTORY.newTransformer(new StreamSource(templateStream));
    } catch (TransformerConfigurationException e) {
        throw new ProcessingFailedException("Failed to create XSLT template", e);
    } finally {
        templateStream.close();
    }
}

From source file:edu.wisc.hrs.dao.url.SoapHrsUrlDaoTest.java

@Test
@Override//from www . j  a va 2s .c o m
public void testGetUrls() throws Exception {
    final WebServiceMessage webServiceMessage = setupWebServiceMessageSender();

    when(webServiceMessage.getPayloadSource())
            .thenReturn(new StreamSource(this.getClass().getResourceAsStream("/hrs/url.xml")));

    super.testGetUrls();
}

From source file:com.wantez.eregparser.Parser.java

public String parse(final String document) throws TransformerException, UnsupportedEncodingException {
    Source streamSource = new StreamSource(IOUtils.toInputStream(document));
    String result;/*from w  w  w. j a  v  a2s. c  o  m*/
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Result streamResult = new StreamResult(baos);
    this.transformer.transform(streamSource, streamResult);
    result = baos.toString("ISO-8859-1");
    return result;
}

From source file:com.seajas.search.profiler.validator.ArchiveValidator.java

/**
 * Validate the given command object.// ww w . j a v  a 2  s. c  o m
 * 
 * @param command
 * @param errors
 */
@Override
public void validate(final Object command, final Errors errors) {
    ArchiveCommand archive = (ArchiveCommand) command;

    if (archive.getAction().equals("add") || archive.getAction().equals("edit")) {
        if (StringUtils.isEmpty(archive.getName()))
            errors.rejectValue("name", "archives.error.no.name");
        if (StringUtils.isEmpty(archive.getDescription()))
            errors.rejectValue("description", "archives.error.no.description");

        if (!StringUtils.isEmpty(archive.getTransformerContent())) {
            StreamSource source = new StreamSource(new StringReader(archive.getTransformerContent()));

            try {
                TransformerFactory.newInstance().newTransformer(source);
            } catch (Exception e) {
                errors.rejectValue("transformerContent", "archives.error.invalid.transformation");
            }
        } else
            errors.rejectValue("transformerContent", "archives.error.invalid.transformation");

        if (StringUtils.isEmpty(archive.getInternalLink()))
            errors.rejectValue("internalLink", "archives.error.no.internal.link");

        if (!StringUtils.isEmpty(archive.getDeletionExpression()))
            try {
                Pattern.compile(archive.getDeletionExpression());
            } catch (PatternSyntaxException e) {
                errors.rejectValue("deletionExpression", "archives.error.invalid.expression");
            }
        if (!StringUtils.isEmpty(archive.getExclusionExpression()))
            try {
                Pattern.compile(archive.getExclusionExpression());
            } catch (PatternSyntaxException e) {
                errors.rejectValue("exclusionExpression", "archives.error.invalid.expression");
            }

        for (String archiveUrl : archive.getArchiveUrls())
            try {
                new URL(archiveUrl);
            } catch (MalformedURLException e) {
                errors.rejectValue("archiveUrls", "archives.error.invalid.urls");

                break;
            }
    }
}

From source file:org.yamj.filescanner.tools.XmlTools.java

/**
 * Read a file from disk/* w  w  w.j  ava  2s  .  co  m*/
 *
 * @param <T>
 * @param filename
 * @param clazz
 * @return
 */
public <T> T read(String filename, Class<T> clazz) {
    LOG.debug("Reading filename '{}' of type {}", filename, clazz.getSimpleName());

    // http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/oxm.html
    FileInputStream is = null;
    try {
        is = new FileInputStream(filename);
        return (T) unmarshaller.unmarshal(new StreamSource(is));
    } catch (FileNotFoundException ex) {
        LOG.warn("File not found '{}'", filename);
    } catch (IOException ex) {
        LOG.warn("IO exception for '{}', Error: {}", filename, ex.getMessage());
    } catch (XmlMappingException ex) {
        LOG.warn("XML Mapping error for '{}', Error: {}", filename, ex.getMessage());
    } catch (StreamException ex) {
        LOG.warn("Stream exception for '{}', Error {}", filename, ex.getMessage());
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ex) {
                LOG.warn("Failed to close library file '{}', Error: {}", filename, ex.getMessage());
            }
        }
    }
    return null;
}