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:siia.booking.domain.trip.LegQuoteMarshallingTest.java

@Test
public void testUnmarshallingLeg() throws Exception {
    StreamSource source = new StreamSource(new StringReader(this.exampleQuoteXml));
    Object unmarshalled = marshaller.unmarshal(source);
    assertEquals("Wrong class returned by unmrshalling", LegQuoteCommand.class, unmarshalled.getClass());
    LegQuoteCommand legQuoteReq = (LegQuoteCommand) unmarshalled;
    assertEquals("Wrong leg location", exampleLegQuote.getLeg(), legQuoteReq.getLeg());
}

From source file:com.vmware.o11n.plugin.powershell.config.impl.HostConfigPersister.java

private byte[] convertOldFormat(byte[] bytes) {
    String XSLT = "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">"
            + "  <xsl:template match=\"/\">" + "    <xsl:apply-templates select=\"*\"/>" + "  </xsl:template>"
            + "  <xsl:template match=\"node()\">"
            + "    <xsl:copy><xsl:apply-templates select=\"node()\"/></xsl:copy>" + "  </xsl:template>"
            + "  <xsl:template match=\"autorizationMode\">"
            + "    <authorizationMode><xsl:apply-templates select=\"node()\"/></authorizationMode>"
            + "  </xsl:template> " + "</xsl:stylesheet>";
    try {/*from w  w  w  . j a  v a2  s  . c om*/
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        Transformer transformer = TransformerFactory.newInstance()
                .newTransformer(new StreamSource(new StringReader(XSLT)));
        Source xmlSource = new StreamSource(bais);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        StreamResult out = new StreamResult(baos);
        transformer.transform(xmlSource, out);
        return baos.toByteArray();
    } catch (TransformerException e) {
        throw new RuntimeException("Unable to convert configuration.", e);
    }
}

From source file:org.n52.youngs.harvest.PoxCswSource.java

@Override
public Collection<SourceRecord> getRecords(long startPosition, long maxRecords, Report report) {
    log.debug("Requesting {} records from catalog starting at {}", maxRecords, startPosition);
    Collection<SourceRecord> records = Lists.newArrayList();

    HttpEntity entity = createRequest(startPosition, maxRecords);

    try {//from  www  .j av a  2s.  c o  m
        log.debug("GetRecords request: {}", EntityUtils.toString(entity));

        String response = Request.Post(getEndpoint().toString()).body(entity)
                .addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_XML.getMimeType())
                .addHeader(HttpHeaders.ACCEPT_CHARSET, Charsets.UTF_8.name()).execute().returnContent()
                .asString(Charsets.UTF_8);
        log.trace("Response: {}", response);
        JAXBElement<GetRecordsResponseType> jaxb_response = unmarshaller
                .unmarshal(new StreamSource(new StringReader(response)), GetRecordsResponseType.class);
        BigInteger numberOfRecordsReturned = jaxb_response.getValue().getSearchResults()
                .getNumberOfRecordsReturned();
        log.debug("Got response with {} records", numberOfRecordsReturned);

        List<Object> nodes = jaxb_response.getValue().getSearchResults().getAny();
        if (!nodes.isEmpty()) {
            log.debug("Found {} \"any\" nodes.", nodes.size());
            nodes.stream().filter(n -> n instanceof Node).map(n -> (Node) n).map(n -> new NodeSourceRecord(n))
                    .forEach(records::add);
        }

        List<JAXBElement<? extends AbstractRecordType>> jaxb_records = jaxb_response.getValue()
                .getSearchResults().getAbstractRecord();
        if (!jaxb_records.isEmpty()) {
            log.debug("Found {} \"AbstractRecordType\" records.", jaxb_records.size());
            DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            jaxb_records.stream().map(type -> {
                return getNode(type, context, db);
            }).filter(Objects::nonNull).map(n -> new NodeSourceRecord(n)).forEach(records::add);
        }
    } catch (IOException | JAXBException | ParserConfigurationException e) {
        log.error("Could not retrieve records from endpoint {}", getEndpoint(), e);
        report.addMessage(String.format("Error retrieving record from endpoint %s: %s", this, e));
    }

    log.debug("Decoded {} records", records.size());
    return records;
}

From source file:javancss.XmlFormatterTest.java

private String getXML(String xmlContent, File xsltFile) throws IOException, TransformerException {
    String xsltContent = FileUtils.readFileToString(xsltFile, "ISO-8859-1");

    StreamSource xmlSource = new StreamSource(new StringReader(xmlContent));
    StreamSource styleSource = new StreamSource(new StringReader(xsltContent));

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer(styleSource);

    ByteArrayOutputStream output = new ByteArrayOutputStream(1024);
    StreamResult result = new StreamResult(output);
    transformer.transform(xmlSource, result);

    return output.toString();
}

From source file:org.mage.server.rest.GameService.java

@RequestMapping(method = RequestMethod.POST, value = "/game/{id}/state")
public ModelAndView newGameState(@RequestBody String body, @PathVariable String id)
        throws XmlMappingException, IOException, JAXBException {
    Source source = new StreamSource(new StringReader(body));
    GameState state = (GameState) jaxb2Unmarshaller.unmarshal(source);

    gameStateDao.save(state);//www.  j ava 2s. com

    GameStateCreateResponse response = new GameStateCreateResponse();
    response.setValue(true);
    Response responseOuter = new Response();
    responseOuter.setStateCreated(response);

    return new ModelAndView(STATE_VIEW_NAME, "object", responseOuter);
}

From source file:org.cruk.genologics.api.GenologicsAPIPaginatedBatchTest.java

public GenologicsAPIPaginatedBatchTest() throws MalformedURLException {
    pageFiles = new File[] { new File("src/test/xml/multipagefetch-1.xml"),
            new File("src/test/xml/multipagefetch-2.xml"), new File("src/test/xml/multipagefetch-3.xml") };

    context = new ClassPathXmlApplicationContext("/org/cruk/genologics/api/genologics-client-context.xml");

    marshaller = context.getBean("genologicsJaxbMarshaller", Jaxb2Marshaller.class);

    Samples page1 = (Samples) marshaller.unmarshal(new StreamSource(pageFiles[0]));
    response1 = new ResponseEntity<Samples>(page1, HttpStatus.OK);
    Samples page2 = (Samples) marshaller.unmarshal(new StreamSource(pageFiles[1]));
    response2 = new ResponseEntity<Samples>(page2, HttpStatus.OK);
    Samples page3 = (Samples) marshaller.unmarshal(new StreamSource(pageFiles[2]));
    response3 = new ResponseEntity<Samples>(page3, HttpStatus.OK);
}

From source file:org.jboss.windup.decorator.xml.XSLTDecorator.java

@Override
public void afterPropertiesSet() {
    LOG.debug("Getting XSLT Location: " + xsltLocation);
    Source xsltSource = new StreamSource(
            Thread.currentThread().getContextClassLoader().getResourceAsStream(xsltLocation));
    try {//from w  w w .j  a  v a2  s .c  o m
        TransformerFactory tf = TransformerFactory.newInstance();
        tf.setURIResolver(new URIResolver() {
            @Override
            public Source resolve(String href, String base) throws TransformerException {
                // fetch local only, for speed reasons.
                if (StringUtils.contains(href, "http://")) {
                    LOG.warn("Trying to fetch remote URL for XSLT.  This is not possible; for speed reasons: "
                            + href + ": " + base);
                    return null;
                }
                return new StreamSource(
                        Thread.currentThread().getContextClassLoader().getResourceAsStream(href));
            }
        });

        xsltTransformer = tf.newTransformer(xsltSource);
        if (xsltParameters != null) {
            for (String key : xsltParameters.keySet()) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Setting property: " + key + " -> " + xsltParameters.get(key));
                }
                xsltTransformer.setParameter(key, xsltParameters.get(key));
            }
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Created XSLT successfully: " + xsltLocation);
        }
    } catch (Exception e) {
        LOG.error("Exception creating XSLT: " + xsltLocation, e);
    }
}

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

private List<Validator> getValidators() throws Exception {
    log.info("Get validators for WSDL: " + wsdl);
    WSDLParserContext ctx = new WSDLParserContext();
    ctx.setInput(wsdl);/*w w w.  j  a va 2 s  .co m*/
    SchemaFactory sf = SchemaFactory.newInstance(Constants.XSD_NS);
    sf.setResourceResolver(new SOAModelResourceResolver(wsdl));
    List<Validator> validators = new ArrayList<Validator>();
    for (Schema schema : getEmbeddedSchemas(ctx)) {
        log.info("Adding embedded schema: " + schema);
        Validator validator = sf
                .newSchema(new StreamSource(new ByteArrayInputStream(schema.getAsString().getBytes())))
                .newValidator();
        validator.setErrorHandler(new SchemaValidatorErrorHandler());
        validators.add(validator);
    }
    return validators;
}

From source file:org.toobsframework.transformpipeline.domain.XSLUriResolverImpl.java

public Source resolve(String xslFile, String base) throws TransformerException {
    if (log.isDebugEnabled()) {
        log.debug("ENTER XSLUriResolverImpl.resolve('" + xslFile + "', '" + base + "');");
    }/* ww  w.  jav a2s .c  o  m*/

    Source xslSource = null;
    URL xslUrl = sourceMap.get(xslFile);
    try {
        if (xslUrl == null || doReload) {
            if (applicationContext != null) {
                xslUrl = resolveContextResource(xslFile, "");
            }
            if (xslUrl == null) {
                xslUrl = resolveClasspathResource(xslFile, "");
            }
            if (xslUrl == null) {
                throw new TransformerException("xsl " + xslFile + " not found");
            }
            sourceMap.put(xslFile, xslUrl);
        }

        xslSource = new StreamSource(xslUrl.openStream());
        xslSource.setSystemId(xslUrl.getPath());
    } catch (IOException e) {
        log.error("XSL File " + xslFile + " had IOException " + e.getMessage(), e);
        throw new TransformerException("xsl " + xslFile + " cannot be loaded");
    }

    if (log.isDebugEnabled()) {
        log.debug("EXIT XSLUriResolverImpl.resolve('" + xslFile + "', '" + base + "');");
    }
    return xslSource;
}

From source file:com.premiumminds.billy.gin.services.impl.pdf.FOPPDFTransformer.java

protected void transformToStream(InputStream templateStream, ParamsTree<String, String> documentParams,
        OutputStream outStream) throws ExportServiceException {

    // the XML file from which we take the name
    Source source = this.mapParamsToSource(documentParams);
    // creation of transform source
    StreamSource transformSource = new StreamSource(templateStream);

    // create an instance of fop factory
    FopFactory fopFactory = FopFactory.newInstance();
    // a user agent is needed for transformation
    FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
    // to store output

    try {/*  ww w.ja v a  2s  . c om*/
        Transformer xslfoTransformer = this.getTransformer(transformSource);

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

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

        // Start XSLT transformation and FOP processing
        // everything will happen here..
        xslfoTransformer.transform(source, res);
    } catch (FOPException e) {
        FOPPDFTransformer.log.error(e.getMessage(), e);
        throw new ExportServiceException("Error using FOP to open the template", e);
    } catch (TransformerException e) {
        FOPPDFTransformer.log.error(e.getMessage(), e);
        throw new ExportServiceException("Error generating pdf from template and data source", e);
    }
}