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.healthcit.cacure.web.controller.FormExportController.java

@RequestMapping(method = RequestMethod.GET)
public void exportForm(@RequestParam(value = "id", required = true) Long formId,
        @RequestParam(value = "format", required = true) String format, HttpServletResponse response) {

    try {//from w ww  .j a  v a2s  . c  o m
        OutputStream oStream = response.getOutputStream();
        Cure cureXml = dataExporter.constructFormXML(formId);
        JAXBContext jc = JAXBContext.newInstance("com.healthcit.cacure.export.model");

        if (ExportFormat.XML.name().endsWith(format)) {
            String fileNameHeader = String.format("attachment; filename=form-%d.xml;", formId);
            response.setHeader("Content-Disposition", fileNameHeader);
            response.setContentType("application/xml");

            Marshaller m = jc.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            m.marshal(cureXml, oStream);
            oStream.flush();
        } else if (ExportFormat.EXCEL.name().equals(format)) {
            String fileNameHeader = String.format("attachment; filename=form-%d.xlxml;", formId);
            response.setHeader("Content-Disposition", fileNameHeader);
            response.setContentType("application/xml");
            StreamSource xslSource = new StreamSource(this.getClass().getClassLoader()
                    .getResourceAsStream(AppConfig.getString(Constants.EXPORT_EXCEL_XSLT_FILE)));
            JAXBSource xmlSource = new JAXBSource(jc, cureXml);
            Transformer transformer = TransformerFactory.newInstance().newTransformer(xslSource);
            transformer.transform(xmlSource, new StreamResult(oStream));
        }
    } catch (IOException e) {
        log.error("Unable to obtain output stream from the response");
        log.error(e.getMessage(), e);
    } catch (JAXBException e) {
        log.error("Unable to marshal the object");
        log.error(e.getMessage(), e);
    } catch (TransformerException e) {
        log.error("XSLT transformation failed");
        log.error(e.getMessage(), e);
    }
}

From source file:org.n52.youngs.harvest.KvpCswSource.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();

    String recordsRequest = createRequest(startPosition, maxRecords);
    log.trace("GetRecords request: {}", recordsRequest);

    try {//from ww w. j  av a 2  s.  c  o  m
        InputStream response = Request.Get(recordsRequest).execute().returnContent().asStream();

        JAXBElement<GetRecordsResponseType> jaxb_response = unmarshaller.unmarshal(new StreamSource(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.trace("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.trace("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 using url {}", recordsRequest, e);
        report.addMessage(String.format("Error retrieving record from endpoint %s: %s", this, e));
    }

    return records;
}

From source file:de.tudarmstadt.ukp.dkpro.core.io.xml.InlineXmlWriter.java

@Override
public void initialize(UimaContext aContext) throws ResourceInitializationException {
    super.initialize(aContext);

    if (xslt != null) {
        TransformerFactory tf = TransformerFactory.newInstance();
        try {/*  w  w w.  j a v a 2  s .  co  m*/
            URL url = ResourceUtils.resolveLocation(xslt, this, getContext());
            transformer = tf.newTransformer(new StreamSource(url.openStream()));
        } catch (Exception e) {
            throw new ResourceInitializationException(e);
        }
    }

    cas2xml = new CasToInlineXml();
}

From source file:com.agimatec.validation.jsr303.xml.ValidationParser.java

private ValidationConfigType parseXmlConfig() {
    try {/*from   w w w .j a v a  2s  . com*/
        InputStream inputStream = getInputStream(validationXmlFile);
        if (inputStream == null) {
            if (log.isDebugEnabled())
                log.debug("No " + validationXmlFile + " found. Using annotation based configuration only.");
            return null;
        }

        if (log.isDebugEnabled())
            log.debug(validationXmlFile + " found.");

        Schema schema = getSchema();
        JAXBContext jc = JAXBContext.newInstance(ValidationConfigType.class);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        unmarshaller.setSchema(schema);
        StreamSource stream = new StreamSource(inputStream);
        JAXBElement<ValidationConfigType> root = unmarshaller.unmarshal(stream, ValidationConfigType.class);
        return root.getValue();
    } catch (JAXBException e) {
        throw new ValidationException("Unable to parse " + validationXmlFile, e);
    } catch (IOException e) {
        throw new ValidationException("Unable to parse " + validationXmlFile, e);
    }
}

From source file:embedding.MultipleFO2PDF.java

/**
 * Converts an FO file to a PDF file using FOP
 * @param fo the FO file/*from w w  w. j a  v  a 2s  .co m*/
 * @param pdf the target PDF file
 * @throws TransformerException in case of a transformation problem
 * @throws IOException in case of an I/O problem
 * @throws FOPException in case of a FOP problem
 * @return the formatting results of the run
 */
public FormattingResults convertFO2PDF(File fo, File pdf)
        throws TransformerException, IOException, FOPException {

    OutputStream out = null;
    Fop fop;

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

        // Setup output stream.  Note: Using BufferedOutputStream
        // for performance reasons (helpful with FileOutputStreams).
        out = new FileOutputStream(pdf);
        out = new BufferedOutputStream(out);

        // Construct fop with desired output format and output stream
        fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);

        // Setup JAXP using identity transformer
        Transformer transformer = factory.newTransformer(); // identity transformer

        // Setup input stream
        Source src = new StreamSource(fo);

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

    return fop.getResults();
}

From source file:com.bluecloud.ioc.parse.KernelXMLParser.java

/**
 * <h3>XML?</h3> ?XML???Shcema?XMLXML
 * /*from www  . ja va 2s .  c o  m*/
 * @param xmlPath
 *            XML?URL
 * @throws KernelXMLParserException
 */
private void load(URL[] xmlPath) throws KernelXMLParserException {
    Set<URL> urls = new LinkedHashSet<URL>();
    for (URL url : xmlPath) {
        try {
            InputStream is = url.openStream();
            validator.validate(new StreamSource(is));
            urls.add(url);
            is.close();
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error(url.toString() + "?");
            }
        }
    }
    this.validatedXML = urls.toArray(new URL[urls.size()]);
}

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

@Test
public void test_xades_signed_properties() {
    Signature signature = createSignature.createSignature(files, noekkelpar);

    XAdESSignatures xAdESSignatures = (XAdESSignatures) marshaller
            .unmarshal(new StreamSource(new ByteArrayInputStream(signature.getBytes())));
    no.digipost.signature.api.xml.thirdparty.xmldsig.Object object = xAdESSignatures.getSignatures().get(0)
            .getObjects().get(0);/*  w w w.  j ava 2s .  co  m*/

    QualifyingProperties xadesProperties = (QualifyingProperties) object.getContent().get(0);
    SigningCertificate signingCertificate = xadesProperties.getSignedProperties().getSignedSignatureProperties()
            .getSigningCertificate();
    verify_signing_certificate(signingCertificate);

    SignedDataObjectProperties signedDataObjectProperties = xadesProperties.getSignedProperties()
            .getSignedDataObjectProperties();
    verify_signed_data_object_properties(signedDataObjectProperties);
}

From source file:eu.seaclouds.platform.dashboard.util.ObjectMapperHelpers.java

/**
 * Transforms a XML string to an List<Object> using javax.xml.bind.Unmarshaller.
 * If you want to parse a single Object please @see {#link XmlToObject}
 *
 * @param xml  string representing a collection of objects
 * @param type Class of the contained objects within the list
 * @param <T>  target class/*from ww  w. j a v  a 2  s  .co  m*/
 * @return a List of T
 * @throws IOException if is not possible to parse the object
 **/
public static <T> List<T> XmlToObjectCollection(String xml, Class<T> type) throws JAXBException {
    JAXBContext ctx = JAXBContext.newInstance(ObjectMapperHelpers.JAXBCollection.class, type);
    Unmarshaller u = ctx.createUnmarshaller();

    Source src = new StreamSource(IOUtils.toInputStream(xml));
    ObjectMapperHelpers.JAXBCollection<T> collection = u
            .unmarshal(src, ObjectMapperHelpers.JAXBCollection.class).getValue();
    return collection.getItems();
}

From source file:se.inera.intyg.intygstjanst.web.service.converter.SendMessageToCareConverterTest.java

private SendMessageToCareType getSendMessageToCareTypeFromFile(String fileName) throws Exception {
    JAXBContext jaxbContext = JAXBContext.newInstance(SendMessageToCareType.class);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    return unmarshaller.unmarshal(new StreamSource(new ClassPathResource(fileName).getInputStream()),
            SendMessageToCareType.class).getValue();
}

From source file:com.agilejava.docbkx.maven.AbstractPdfMojo.java

public void postProcessResult(File result) throws MojoExecutionException {
    super.postProcessResult(result);

    final FopFactory fopFactory = FopFactory.newInstance();
    final FOUserAgent userAgent = fopFactory.newFOUserAgent();
    userAgent.setBaseURL(baseUrl);/*from w ww .  ja  v a 2s . c o  m*/
    // FOUserAgent can be used to set PDF metadata

    Configuration configuration = loadFOPConfig();
    InputStream in = null;
    OutputStream out = null;

    try {
        in = openFileForInput(result);
        out = openFileForOutput(getOutputFile(result));
        fopFactory.setUserConfig(configuration);
        Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, userAgent, out);

        // Setup JAXP using identity transformer
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer(); // identity transformer

        // Setup input stream
        Source src = new StreamSource(in);

        // 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);
    } catch (FOPException e) {
        throw new MojoExecutionException("Failed to convert to PDF", e);
    } catch (TransformerConfigurationException e) {
        throw new MojoExecutionException("Failed to load JAXP configuration", e);
    } catch (TransformerException e) {
        throw new MojoExecutionException("Failed to transform to PDF", e);
    } finally {
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(in);
    }
}