Example usage for javax.xml.transform.stream StreamResult getOutputStream

List of usage examples for javax.xml.transform.stream StreamResult getOutputStream

Introduction

In this page you can find the example usage for javax.xml.transform.stream StreamResult getOutputStream.

Prototype

public OutputStream getOutputStream() 

Source Link

Document

Get the byte stream that was set with setOutputStream.

Usage

From source file:org.dataconservancy.packaging.tool.ser.AbstractJenaTest.java

protected StreamSource fromResult(StreamResult result) {
    return new StreamSource(
            new ByteArrayInputStream(((ByteArrayOutputStream) result.getOutputStream()).toByteArray()));
}

From source file:org.dhatim.delivery.AbstractParser.java

protected Writer getWriter(Result result, ExecutionContext executionContext) {
    if (!(result instanceof StreamResult)) {
        return new NullWriter();
    }/*from ww  w  .  jav  a 2 s .  c  o m*/

    StreamResult streamResult = (StreamResult) result;
    if (streamResult.getWriter() != null) {
        return streamResult.getWriter();
    } else if (streamResult.getOutputStream() != null) {
        try {
            if (executionContext != null) {
                return new OutputStreamWriter(streamResult.getOutputStream(),
                        executionContext.getContentEncoding());
            } else {
                return new OutputStreamWriter(streamResult.getOutputStream(), "UTF-8");
            }
        } catch (UnsupportedEncodingException e) {
            throw new SmooksException("Unable to encode output stream.", e);
        }
    } else {
        throw new SmooksException(
                "Invalid " + StreamResult.class.getName() + ".  No OutputStream or Writer instance.");
    }
}

From source file:org.dhatim.delivery.Filter.java

protected Writer getWriter(Result result, ExecutionContext executionContext) {
    if (!(result instanceof StreamResult)) {
        return new NullWriter();
    }//from w  w w .  j av  a 2s  .c o  m

    StreamResult streamResult = (StreamResult) result;
    if (streamResult.getWriter() != null) {
        return streamResult.getWriter();
    } else if (streamResult.getOutputStream() != null) {
        try {
            if (executionContext instanceof ExecutionContext) {
                return new OutputStreamWriter(streamResult.getOutputStream(),
                        executionContext.getContentEncoding());
            } else {
                return new OutputStreamWriter(streamResult.getOutputStream(), "UTF-8");
            }
        } catch (UnsupportedEncodingException e) {
            throw new SmooksException("Unable to encode output stream.", e);
        }
    } else {
        throw new SmooksException(
                "Invalid " + StreamResult.class.getName() + ".  No OutputStream or Writer instance.");
    }
}

From source file:org.dhatim.delivery.Filter.java

protected void close(Result result) {
    if (result instanceof StreamResult) {
        StreamResult streamResult = ((StreamResult) result);

        try {//ww  w .  j ava 2 s.  co m
            if (streamResult.getWriter() != null) {
                Writer writer = streamResult.getWriter();
                try {
                    writer.flush();
                } finally {
                    writer.close();
                }
            } else if (streamResult.getOutputStream() != null) {
                OutputStream stream = streamResult.getOutputStream();
                try {
                    stream.flush();
                } finally {
                    // Close the stream as long as it's not sysout or syserr...
                    if (stream != System.out && stream != System.err) {
                        stream.close();
                    }
                }
            }
        } catch (Throwable throwable) {
            logger.debug("Failed to close output stream/writer.  May already be closed.", throwable);
        }
    }
}

From source file:org.dita.dost.util.XMLUtils.java

/** Close result. */
public static void close(final Result result) throws IOException {
    if (result != null && result instanceof StreamResult) {
        final StreamResult r = (StreamResult) result;
        final OutputStream o = r.getOutputStream();
        if (o != null) {
            o.close();/* ww w.  j a  va 2s . c  o  m*/
        } else {
            final Writer w = r.getWriter();
            if (w != null) {
                w.close();
            }
        }
    }
}

From source file:org.jetbrains.jet.grammar.GrammarGenerator.java

public static void main(String[] args) throws IOException, TransformerException {

    System.out.println("Checking cmd line arguments.");
    if (args.length < 2)
        throw new IllegalArgumentException("Usage: grammar-parser <path to grm files> <output file name>");

    File grammarDir = new File(args[0]);
    File outputFile = new File(args[1]);

    if (!outputFile.exists()) {
        if (!outputFile.createNewFile())
            throw new IOException("Cannot create output file.");
    }//ww  w . j a  va2s.c  o  m

    Set<File> used = new HashSet<File>();
    List<Token> tokens = getJoinedTokensFromAllFiles(grammarDir, used);
    assertAllFilesAreUsed(grammarDir, used);
    System.out.println("Preparing resources.");
    ClassLoader loader = ClassLoader.getSystemClassLoader();

    StreamSource xml = new StreamSource(new StringReader(generate(tokens)));
    StreamSource xsl = new StreamSource(loader.getResourceAsStream("convert.xsl"));

    System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
    StreamResult result = new StreamResult(outputFile);

    System.out.println("Processing.");
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer(xsl);

    transformer.transform(xml, result);
    result.getOutputStream().close();
    System.out.println("Done.");
}

From source file:org.opencds.vmr.v1_0.mappings.out.MarshalVMR2VMRSchemaPayload.java

public synchronized String mappingOutbound(Map<String, List<?>> results, DSSRequestKMItem dssRequestKMItem)
        throws InvalidDriDataFormatExceptionFault, UnrecognizedLanguageExceptionFault,
        RequiredDataNotProvidedExceptionFault, UnsupportedLanguageExceptionFault,
        UnrecognizedScopedEntityExceptionFault, EvaluationExceptionFault, InvalidTimeZoneOffsetExceptionFault,
        DSSRuntimeExceptionFault {/*from   w  w w. jav a  2  s  . c o m*/
    String interactionId = dssRequestKMItem.getDssRequestDataItem().getInteractionId();
    String requestedKmId = dssRequestKMItem.getRequestedKmId();
    String streamResultString = "";

    log.debug("II: " + interactionId + " KMId: " + requestedKmId + " begin buildVMRSchemaResultSet");
    BuildVMRSchemaResultSet buildVMRSchemaResultSet = BuildVMRSchemaResultSet.getInstance();
    org.opencds.vmr.v1_0.schema.CDSOutput cdsXMLOutput = buildVMRSchemaResultSet.buildResultSet(results,
            dssRequestKMItem);

    log.debug("II: " + interactionId + " KMId: " + requestedKmId + " finish buildVMRSchemaResultSet");
    dssRequestKMItem.getKmTimingData().setFinishBuildOutputTime(new AtomicLong(System.nanoTime()));

    JAXBElement<org.opencds.vmr.v1_0.schema.CDSOutput> jaxbCDSOutput;

    try {
        log.debug("II: " + interactionId + " KMId: " + requestedKmId + " begin factory.createCdsOutput");

        org.opencds.vmr.v1_0.schema.ObjectFactory factory = new org.opencds.vmr.v1_0.schema.ObjectFactory();
        jaxbCDSOutput = factory.createCdsOutput(cdsXMLOutput);

        log.debug("II: " + interactionId + " KMId: " + requestedKmId + " finish factory.createCdsOutput");
    } catch (RuntimeException e) {
        e.printStackTrace();
        throw new DSSRuntimeExceptionFault("RuntimeException in mappingOutbound ObjectFactory cdsOutput: "
                + e.getMessage() + ", vmrOutput=" + cdsXMLOutput.getVmrOutput().toString(), e);
    }

    if ((null == cdsXMLOutput)
            || ((null == cdsXMLOutput.getSimpleOutput()) && (null == cdsXMLOutput.getVmrOutput()))) {
        // show the tags, but empty payload
        streamResultString = "";
        //FIXME          throw new DSSRuntimeExceptionFault("Marshalled Rules Engine results are empty.");

    } else {
        log.debug("II: " + interactionId + " KMId: " + requestedKmId
                + " begin marshalling results to external VMR: "
                + cdsXMLOutput.getVmrOutput().getTemplateId().toString());

        ByteArrayOutputStream output = new ByteArrayOutputStream();
        StreamResult streamResult = new StreamResult();
        streamResult.setOutputStream(output);

        try {
            JAXBContext jaxbContext = SimpleKnowledgeRepository
                    .getRequiredJAXBContextForMarshallerClassCache(this.getClass().getName());

            Marshaller marshaller = SimpleKnowledgeRepository
                    .getRequiredMarshallerInstanceForMarshallerClassCache(this.getClass().getName(),
                            jaxbContext);

            marshaller.marshal(jaxbCDSOutput, streamResult);

        } catch (JAXBException e) {
            e.printStackTrace();
            throw new EvaluationExceptionFault(
                    "JAXBException in mappingOutbound marshalling cdsOutput: " + e.getMessage(), e);
        } catch (RuntimeException e) {
            e.printStackTrace();
            throw new DSSRuntimeExceptionFault(
                    "RuntimeException in mappingOutbound marshalling cdsOutput: " + e.getMessage(), e);
        }

        log.debug("II: " + interactionId + " KMId: " + requestedKmId
                + " finished marshalling results to external VMR: "
                + cdsXMLOutput.getVmrOutput().getTemplateId().toString());

        OutputStream outputStream = streamResult.getOutputStream();
        streamResultString = outputStream.toString();

    }

    dssRequestKMItem.getKmTimingData().setFinishMarshalTime(new AtomicLong(System.nanoTime()));

    return streamResultString;
}

From source file:org.openmrs.module.casereport.CdaDocumentGenerator.java

/**
 * Generates and returns a CDA document for the specified report form
 * /*  w w  w. j av a  2 s. co m*/
 * @param reportForm
 * @return the generated CDA document
 * @should generate a CDA document
 */
public String generate(CaseReportForm reportForm) throws Exception {
    //cdaMessage = StringUtils.replace(cdaMessage, getPlaceHolder("triggerList"), triggerList);
    //cdaMessage = StringUtils.replace(cdaMessage, getPlaceHolder("dateSubmitted"), DATE_FORMATTER.format(new Date()));
    //String oid1 = "2.25." + new BigInteger(reportForm.getReportUuid().getBytes());
    //String oid2 = "2.25." + new BigInteger(UUID.randomUUID().toString().getBytes())
    ClinicalDocument cdaDocument = new ClinicalDocument();
    cdaDocument.setRealmCode(new SET<CS<BindingRealm>>(
            new CS<BindingRealm>(BindingRealm.UniversalRealmOrContextUsedInEveryInstance)));
    cdaDocument.setTypeId(TYPE_ID_ROOT, EXTENSION);
    cdaDocument.setTemplateId(Arrays.asList(new II(TEMPLATE_ID_ROOT)));
    cdaDocument.setId(reportForm.getReportUuid());
    cdaDocument.setCode(new CE<String>(DOCUMENT_CODE, CODE_SYSTEM_LOINC, CODE_SYSTEM_NAME_LOINC, null,
            LOINC_DOCUMENT_NAME, null));
    cdaDocument.setTitle(TITLE);
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(reportForm.getReportDate());
    cdaDocument.setEffectiveTime(calendar);
    cdaDocument.setConfidentialityCode(x_BasicConfidentialityKind.Normal);
    cdaDocument.setLanguageCode(LANGUAGE_CODE);
    cdaDocument.getRecordTarget().add(CdaUtil.createRecordTarget(reportForm));
    cdaDocument.getAuthor().add(CdaUtil.createAuthor(reportForm));
    cdaDocument.setComponent(CdaUtil.createComponent(reportForm));

    XmlIts1Formatter fmtr = new XmlIts1Formatter();
    //This instructs the XML ITS1 Formatter we want to use CDA datatypes
    fmtr.getGraphAides().add(new DatatypeFormatter(R1FormatterCompatibilityMode.ClinicalDocumentArchitecture));
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    fmtr.graph(out, cdaDocument);

    //Use a Transformer for output the cda in a pretty format
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputStream inputStream = new ByteArrayInputStream(out.toByteArray());
    Document doc = builder.parse(inputStream);

    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

    StreamResult result = new StreamResult(new ByteArrayOutputStream());
    transformer.transform(new DOMSource(doc), result);

    return result.getOutputStream().toString();
}

From source file:org.sonar.server.debt.DebtModelXMLExporter.java

private static String prettyFormatXml(String xml) {
    try {/*from w w  w  .j a  va 2s  . co m*/
        Transformer serializer = SAXTransformerFactory.newInstance().newTransformer();
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", DEFAULT_INDENT);
        Source xmlSource = new SAXSource(
                new InputSource(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8))));
        StreamResult res = new StreamResult(new ByteArrayOutputStream());
        serializer.transform(xmlSource, res);
        return new String(((ByteArrayOutputStream) res.getOutputStream()).toByteArray(),
                StandardCharsets.UTF_8);
    } catch (TransformerException ignored) {
        // Ignore, raw XML will be returned
    }
    return xml;
}

From source file:org.springframework.oxm.support.AbstractMarshaller.java

/**
 * Template method for handling {@code StreamResult}s.
 * <p>This implementation delegates to {@code marshalOutputStream} or {@code marshalWriter},
 * depending on what is contained in the {@code StreamResult}
 * @param graph the root of the object graph to marshal
 * @param streamResult the {@code StreamResult}
 * @throws IOException if an I/O Exception occurs
 * @throws XmlMappingException if the given object cannot be marshalled to the result
 * @throws IllegalArgumentException if {@code streamResult} does neither
 * contain an {@code OutputStream} nor a {@code Writer}
 *//*from ww w  .jav a 2 s.  c o m*/
protected void marshalStreamResult(Object graph, StreamResult streamResult)
        throws XmlMappingException, IOException {

    if (streamResult.getOutputStream() != null) {
        marshalOutputStream(graph, streamResult.getOutputStream());
    } else if (streamResult.getWriter() != null) {
        marshalWriter(graph, streamResult.getWriter());
    } else {
        throw new IllegalArgumentException("StreamResult contains neither OutputStream nor Writer");
    }
}