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

/**
 * Main bean entry point//w  ww  .  jav  a2s. c o  m
 */
public String transform(String document, String transletName) {

    // Initialise the output stream
    final StringWriter sout = new StringWriter();
    final PrintWriter out = new PrintWriter(sout);

    try {
        if ((document == null) || (transletName == null)) {
            out.println(nullErrorMsg);
        } else {
            TransformerFactory tf = TransformerFactory.newInstance();
            try {
                tf.setAttribute("use-classpath", Boolean.TRUE);
            } catch (IllegalArgumentException iae) {
                System.err.println("Could not set XSLTC-specific TransformerFactory "
                        + "attributes.  Transformation failed.");
            }

            Transformer t = tf.newTransformer(new StreamSource(transletName));

            // Do the actual transformation
            final long start = System.currentTimeMillis();
            t.transform(new StreamSource(document), new StreamResult(out));
            final long done = System.currentTimeMillis() - start;
            out.println("<!-- transformed by XSLTC in " + done + "msecs -->");
        }
    }

    catch (Exception e) {
        errorMsg(out, e, "Impossible state reached.");
    }

    // Now close up the sink, and return the HTML output in the
    // StringWrite object as a string.
    out.close();
    return sout.toString();
}

From source file:com.predic8.membrane.core.interceptor.xslt.XSLTTransformer.java

private void createOneTransformer(ResolverMap rr, String baseLocation)
        throws TransformerConfigurationException, InterruptedException, ResourceRetrievalException {
    Transformer t;/*from  w  w w  .j  a va2 s .c om*/
    if (isNullOrEmpty(styleSheet))
        t = fac.newTransformer();
    else {
        StreamSource source = new StreamSource(rr.resolve(ResolverMap.combine(baseLocation, styleSheet)));
        source.setSystemId(styleSheet);
        t = fac.newTransformer(source);
    }
    transformers.put(t);
}

From source file:org.socialhistoryservices.pid.database.dao.HandleDaoImpl.java

public HandleDaoImpl() {
    try {/*from w  w  w . j a va 2s. c o  m*/
        templates = TransformerFactory.newInstance().newTemplates(
                new StreamSource(this.getClass().getResourceAsStream("/locations.remove.ns.xsl")));
    } catch (TransformerConfigurationException e) {
        e.printStackTrace();
    }
}

From source file:no.digipost.signature.client.asice.signature.CreateSignatureTest.java

@Test
public void test_generated_signatures() {
    Signature signature = createSignature.createSignature(files, noekkelpar);
    XAdESSignatures xAdESSignatures = (XAdESSignatures) marshaller
            .unmarshal(new StreamSource(new ByteArrayInputStream(signature.getBytes())));

    assertThat(xAdESSignatures.getSignatures(), hasSize(1));
    no.digipost.signature.api.xml.thirdparty.xmldsig.Signature dSignature = xAdESSignatures.getSignatures()
            .get(0);/*  w w w. j  a v a 2s .  co m*/
    verify_signed_info(dSignature.getSignedInfo());
    assertThat(dSignature.getSignatureValue(), is(notNullValue()));
    assertThat(dSignature.getKeyInfo(), is(notNullValue()));
}

From source file:org.fcrepo.syndication.RSSPublisher.java

/**
 * Get the RSS feed//www. j a v a 2 s. c  om
 *
 * @return
 * @throws FeedException
 */
@GET
@Produces("application/rss+xml")
public StreamSource getFeed() throws FeedException {
    feed.setLink(uriInfo.getBaseUri().toString());
    feed.setEntries(transform(copyOf(feedQueue).reverse(), event2entry));
    // TODO ought to make this stream, not go through a string
    return new StreamSource(new ByteArrayInputStream(new SyndFeedOutput().outputString(feed).getBytes(UTF_8)));
}

From source file:ca.uhn.fhir.validation.schematron.SchematronBaseValidator.java

@Override
public void validateResource(IValidationContext<IBaseResource> theCtx) {

    ISchematronResource sch = getSchematron(theCtx);
    String resourceAsString;/* www  .ja  v  a  2  s . co m*/
    if (theCtx.getResourceAsStringEncoding() == EncodingEnum.XML) {
        resourceAsString = theCtx.getResourceAsString();
    } else {
        resourceAsString = theCtx.getFhirContext().newXmlParser().encodeResourceToString(theCtx.getResource());
    }
    StreamSource source = new StreamSource(new StringReader(resourceAsString));

    SchematronOutputType results = SchematronHelper.applySchematron(sch, source);
    if (results == null) {
        return;
    }

    IResourceErrorGroup errors = SchematronHelper.convertToResourceErrorGroup(results,
            theCtx.getFhirContext().getResourceDefinition(theCtx.getResource()).getBaseDefinition().getName());

    if (errors.getAllErrors().containsOnlySuccess()) {
        return;
    }

    for (IResourceError next : errors.getAllErrors().getAllResourceErrors()) {
        ResultSeverityEnum severity;
        switch (next.getErrorLevel()) {
        case ERROR:
            severity = ResultSeverityEnum.ERROR;
            break;
        case FATAL_ERROR:
            severity = ResultSeverityEnum.FATAL;
            break;
        case WARN:
            severity = ResultSeverityEnum.WARNING;
            break;
        case INFO:
        case SUCCESS:
        default:
            continue;
        }

        String details = next.getAsString(Locale.getDefault());

        SingleValidationMessage message = new SingleValidationMessage();
        message.setMessage(details);
        message.setLocationLine(next.getLocation().getLineNumber());
        message.setLocationCol(next.getLocation().getColumnNumber());
        message.setLocationString(next.getLocation().getAsString());
        message.setSeverity(severity);
        theCtx.addValidationMessage(message);
    }

}

From source file:org.energyos.espi.thirdparty.web.NotificationController.java

@RequestMapping(value = Routes.THIRD_PARTY_NOTIFICATION, method = RequestMethod.POST)
public void notification(HttpServletResponse response, InputStream inputStream) throws IOException {

    BatchList batchList = (BatchList) marshaller.unmarshal(new StreamSource(inputStream));

    batchListService.persist(batchList);

    for (String resourceUri : batchList.getResources()) {
        doImportAsynchronously(resourceUri);
    }// w  w  w  . j  a  va  2 s  .co  m

    response.setStatus(HttpServletResponse.SC_OK);
}

From source file:ValidateXMLInput.java

void validate() throws Exception {
    // Since we're going to use a SAX feature, the transformer must support 
    // input in the form of a SAXSource.
    TransformerFactory tfactory = TransformerFactory.newInstance();
    if (tfactory.getFeature(SAXSource.FEATURE)) {
        // Standard way of creating an XMLReader in JAXP 1.1.
        SAXParserFactory pfactory = SAXParserFactory.newInstance();
        pfactory.setNamespaceAware(true); // Very important!
        // Turn on validation.
        pfactory.setValidating(true);/*from w ww . jav  a 2 s  . c  o m*/
        // Get an XMLReader.
        XMLReader reader = pfactory.newSAXParser().getXMLReader();

        // Instantiate an error handler (see the Handler inner class below) that will report any
        // errors or warnings that occur as the XMLReader is parsing the XML input.
        Handler handler = new Handler();
        reader.setErrorHandler(handler);

        // Standard way of creating a transformer from a URL.
        Transformer t = tfactory.newTransformer(new StreamSource("birds.xsl"));

        // Specify a SAXSource that takes both an XMLReader and a URL.
        SAXSource source = new SAXSource(reader, new InputSource("birds.xml"));

        // Transform to a file.
        try {
            t.transform(source, new StreamResult("birds.out"));
        } catch (TransformerException te) {
            // The TransformerException wraps someting other than a SAXParseException
            // warning or error, either of which should be "caught" by the Handler.
            System.out.println("Not a SAXParseException warning or error: " + te.getMessage());
        }

        System.out.println("=====Done=====");
    } else
        System.out.println("tfactory does not support SAX features!");
}

From source file:no.digipost.api.handlers.ForsendelseSender.java

@Override
public void doWithMessage(final WebServiceMessage message) throws IOException, TransformerException {
    SoapMessage soapMessage = (SoapMessage) message;
    attachFile(soapMessage);// www  .j a  v a  2 s.  com
    Mpc mpc = new Mpc(forsendelse.prioritet, forsendelse.mpcId);
    if (forsendelse.sbdStream != null) {
        TransformerUtil.transform(new StreamSource(forsendelse.sbdStream),
                soapMessage.getEnvelope().getBody().getPayloadResult(), true);
    } else if (digitalPostformidling.getSignature() == null) {
        Document signedDoc = signer.sign(doc);
        Marshalling.marshal(signedDoc, soapMessage.getEnvelope().getBody().getPayloadResult());
    } else {
        Marshalling.marshal(marshaller, soapMessage.getEnvelope().getBody(), doc);
    }
    ebmsContext.addRequestStep(new AddUserMessageStep(mpc, forsendelse.messageId, forsendelse.action, null, doc,
            tekniskAvsender, tekniskMottaker, marshaller));
}

From source file:com.kurtraschke.wsf.gtfsrealtime.services.WSFVesselLocationService.java

public List<VesselLocationResponse> getAllVessels() throws URISyntaxException, IOException, JAXBException {
    ImmutableList.Builder<VesselLocationResponse> allVessels = ImmutableList.builder();

    URI endpoint = new URIBuilder("http://www.wsdot.wa.gov/ferries/api/vessels/rest/vessellocations")
            .addParameter("apiaccesscode", _apiAccessCode).build();
    CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(_connectionManager).build();
    HttpGet request = new HttpGet(endpoint);
    request.addHeader("Accept", "text/xml");

    try (CloseableHttpResponse response = httpclient.execute(request)) {
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            try (InputStream instream = entity.getContent()) {
                JAXBElement<ArrayOfVesselLocationResponse> responseArray;
                responseArray = _um.unmarshal(new StreamSource(instream), ArrayOfVesselLocationResponse.class);

                allVessels.addAll(responseArray.getValue().getVesselLocationResponse());
            }//from  w  w  w.  ja v  a 2s . c o m
        }
    }
    return allVessels.build();
}