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

public static void main(String[] args) throws Exception {
    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", "2");
    serializer.setOutputProperty("{http://xml.customer.org/xslt}indent-amount", "2");
    Source xmlSource = new SAXSource(new InputSource(
            new ByteArrayInputStream("<a><b><c/><d>text D</d><e value='0'/></b></a>".getBytes())));
    StreamResult res = new StreamResult(new ByteArrayOutputStream());
    serializer.transform(xmlSource, res);
    System.out.println(new String(((ByteArrayOutputStream) res.getOutputStream()).toByteArray()));
}

From source file:Main.java

public static String prettyPrintXML(String xml, int indentAmount)
        throws TransformerConfigurationException, TransformerException {

    Transformer serializer = SAXTransformerFactory.newInstance().newTransformer();

    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(indentAmount));
    Source xmlSource = new SAXSource(new InputSource(new ByteArrayInputStream(xml.getBytes())));
    StreamResult res = new StreamResult(new ByteArrayOutputStream());
    serializer.transform(xmlSource, res);

    return new String(((ByteArrayOutputStream) res.getOutputStream()).toByteArray());
}

From source file:Main.java

public static String formatXML(String xml) {
    try {//from w  ww.j a v a  2s  . com
        Transformer serializer = SAXTransformerFactory.newInstance().newTransformer();
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        Source xmlSource = new SAXSource(new InputSource(new ByteArrayInputStream(xml.getBytes())));
        StreamResult res = new StreamResult(new ByteArrayOutputStream());
        serializer.transform(xmlSource, res);
        return new String(((ByteArrayOutputStream) res.getOutputStream()).toByteArray());
    } catch (Exception e) {

        return xml;
    }
}

From source file:Main.java

public static String prettyFormat(String xml) {
    if (xml == null || xml.isEmpty() || !xml.contains("<")) {
        //          System.out.println("Why?"+xml.startsWith("<", 0));
        return xml;
    }/*from  www.j  a v  a  2s . c o  m*/
    try {
        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", "2");
        Source xmlSource = new SAXSource(new InputSource(new ByteArrayInputStream(xml.getBytes())));
        StreamResult res = new StreamResult(new ByteArrayOutputStream());
        serializer.transform(xmlSource, res);
        return new String(((ByteArrayOutputStream) res.getOutputStream()).toByteArray()).replace("><", ">\n<");
    } catch (Exception e) {
        System.out.println("prettyFormat: Error.." + e.getMessage());
        //TODO log error
        return xml.replace("<", "\n<");
        //            return xml.replace("><", ">\n<");
    }
}

From source file:Main.java

/** Convert an xml Document object to a String */
public static String convertDocumentToString(Document doc) {

    StreamResult sr = new StreamResult(new ByteArrayOutputStream());
    try {/*  ww  w  .  ja  v  a2 s .  c o m*/
        ourTransformer.transform(new DOMSource(doc), sr);
    } catch (TransformerException te) {
        System.out.println(te);
    }

    String docAsString = sr.getOutputStream().toString();
    return docAsString;
}

From source file:com.github.jjYBdx4IL.utils.fma.FMAConfig.java

public static String formatXml(String xml) {

    try {/*from   www  .  ja v  a  2 s.  co m*/
        Transformer serializer = SAXTransformerFactory.newInstance().newTransformer();

        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

        Source xmlSource = new SAXSource(new InputSource(new ByteArrayInputStream(xml.getBytes())));
        StreamResult res = new StreamResult(new ByteArrayOutputStream());

        serializer.transform(xmlSource, res);

        return new String(((ByteArrayOutputStream) res.getOutputStream()).toByteArray());

    } catch (IllegalArgumentException | TransformerException e) {
        LOG.error("", e);
        return xml;
    }
}

From source file:Main.java

/** Write a DOM to a file. */
public static void writeXML(Document document, File file) throws IOException {
    // save the DOM to file
    StreamResult result = new StreamResult(new BufferedOutputStream(new FileOutputStream(file)));
    TransformerFactory transFactory = TransformerFactory.newInstance();
    try {/* www .  j  a  va 2s .  co  m*/
        Transformer transformer = transFactory.newTransformer();
        transformer.setOutputProperty("indent", "yes");
        transformer.transform(new DOMSource(document), result);
    } catch (TransformerConfigurationException ex) {
        throw new IOException(ex.getMessage());
    } catch (TransformerException ex) {
        throw new IOException(ex.getMessage());
    }
    result.getOutputStream().close();
}

From source file:biz.c24.io.spring.oxm.C24Marshaller.java

/**
 * Returns a C24 {@link XMLSink} for the given {@link StreamResult}. Will prefer the result's {@link Writer} over its
 * {@link OutputStream}.//from w w  w. j  a  v a 2  s  .  co m
 * 
 * @param result
 * @return
 */
private XMLSink getXmlSinkFrom(StreamResult result) {

    Writer writer = result.getWriter();
    return writer != null ? new XMLSink(writer) : new XMLSink(result.getOutputStream());
}

From source file:com.ephesoft.dcma.webservice.EphesoftWebServiceAPI.java

/**
 * To get Batch Instance List.// w ww  .ja v a 2  s  . c  o  m
 * @param status {@link String}
 * @param resp {@link HttpServletResponse}
 * @param req {@link HttpServletRequest}
 */
@RequestMapping(value = "/getBatchInstanceList/{status}", method = RequestMethod.GET)
@ResponseBody
public void getBatchInstanceList(@PathVariable("status") final String status, final HttpServletResponse resp,
        final HttpServletRequest req) {
    LOGGER.info("Start processing get batch instance list from batch status web service");
    String respStr = WebServiceUtil.EMPTY_STRING;
    Set<String> batchInstancesId = new TreeSet<String>();
    if (!BatchInstanceStatus.valuesAsStringList().contains(status)) {
        respStr = "Invalid value for batch instance status. Please try again.";
    } else {
        final BatchInstanceStatus batchInstanceStatus = BatchInstanceStatus.valueOf(status);
        LOGGER.info("Batch instance status is " + status);
        LOGGER.info("Fetching batch instance list from the database");
        final List<BatchInstance> batchInstance = biService.getBatchInstByStatus(batchInstanceStatus);
        if (batchInstance != null && !batchInstance.isEmpty()) {
            Set<String> loggedInUserRole = getUserRoles(req);
            if (!isSuperAdmin(req)) {
                // fetch the batch instances from batch instance groups
                Set<String> batchInstancesIdentifiers = batchInstanceGroupsService
                        .getBatchInstanceIdentifierForUserRoles(loggedInUserRole);

                if (batchInstancesIdentifiers != null) {
                    batchInstancesId.addAll(batchInstancesIdentifiers);
                }

                // fetch the list of batch instances from the batch instance table for batch classes having the given role.
                List<BatchClass> batchClasses = bcService.getAllBatchClassesByUserRoles(loggedInUserRole);
                for (BatchClass batchClass : batchClasses) {
                    List<BatchInstance> eachBatchInstance = biService.getBatchInstByBatchClass(batchClass);
                    for (BatchInstance bi : eachBatchInstance) {
                        batchInstancesId.add(bi.getIdentifier());
                    }
                }
            } else {
                for (BatchInstance bi : batchInstance) {
                    batchInstancesId.add(bi.getIdentifier());
                }
            }

            LOGGER.info(
                    "Fetched list of batch instances from the batch instance table for batch classes having the given role:");
            for (String batchInstanceIdentifier : batchInstancesId) {
                LOGGER.info(batchInstanceIdentifier);
            }

            final BatchInstances batchInstances = new BatchInstances();

            final List<com.ephesoft.dcma.batch.schema.BatchInstances.BatchInstance> batchInstanceList = batchInstances
                    .getBatchInstance();

            for (final BatchInstance eachBatchInstance : batchInstance) {
                if (batchInstancesId.contains(eachBatchInstance.getIdentifier())) {
                    final com.ephesoft.dcma.batch.schema.BatchInstances.BatchInstance batchLocal = new com.ephesoft.dcma.batch.schema.BatchInstances.BatchInstance();
                    batchLocal.setIdentifier(eachBatchInstance.getIdentifier());
                    batchLocal.setBatchName(eachBatchInstance.getBatchName());
                    batchLocal.setCurrentUser(eachBatchInstance.getCurrentUser());
                    batchLocal.setExecutedModules(eachBatchInstance.getExecutedModules());
                    batchLocal.setLocalFolder(eachBatchInstance.getLocalFolder());
                    batchLocal.setRemoteBatchInstanceId(eachBatchInstance.getRemoteBatchInstance() != null
                            ? eachBatchInstance.getRemoteBatchInstance().getRemoteBatchInstanceIdentifier()
                            : null);
                    batchLocal.setReviewOperatorName(eachBatchInstance.getReviewUserName());
                    batchLocal.setServerIP(eachBatchInstance.getServerIP());
                    batchLocal.setUncSubFolder(eachBatchInstance.getUncSubfolder());
                    batchLocal.setValidateOperatorName(eachBatchInstance.getValidationUserName());
                    batchInstanceList.add(batchLocal);
                }
            }
            StreamResult result = null;
            try {
                result = new StreamResult(resp.getOutputStream());
                resp.setStatus(HttpServletResponse.SC_OK);
                batchSchemaDao.getJAXB2Template().getJaxb2Marshaller().marshal(batchInstances, result);
            } catch (final IOException e) {
                respStr = INTERNAL_SERVER_ERROR + e;
                LOGGER.error("Internal Server error.Exception occured:" + e.getMessage());
            } finally {
                if (result != null) {
                    IOUtils.closeQuietly(result.getOutputStream());
                }
            }
        } else {
            respStr = "No results found.";
        }
    }
    if (!respStr.isEmpty()) {
        try {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr);
            LOGGER.error(SERVER_ERROR_MSG + respStr);
        } catch (final IOException ioe) {
            LOGGER.info(ERROR_WHILE_SENDING_ERROR_RESPONSE_TO_CLIENT + ioe, ioe);
        }
    }
}

From source file:org.apache.fop.render.intermediate.AbstractBinaryWritingIFDocumentHandler.java

/** {@inheritDoc} */
public void setResult(Result result) throws IFException {
    if (result instanceof StreamResult) {
        StreamResult streamResult = (StreamResult) result;
        OutputStream out = streamResult.getOutputStream();
        if (out == null) {
            if (streamResult.getWriter() != null) {
                throw new IllegalArgumentException("FOP cannot use a Writer. Please supply an OutputStream!");
            }/*from  w  w  w . j  a  v  a 2s  .  c o m*/
            try {
                URL url = new URL(streamResult.getSystemId());
                File f = FileUtils.toFile(url);
                if (f != null) {
                    out = new java.io.FileOutputStream(f);
                } else {
                    out = url.openConnection().getOutputStream();
                }
            } catch (IOException ioe) {
                throw new IFException("I/O error while opening output stream", ioe);
            }
            out = new java.io.BufferedOutputStream(out);
            this.ownOutputStream = true;
        }
        if (out == null) {
            throw new IllegalArgumentException("Need a StreamResult with an OutputStream");
        }
        this.outputStream = out;
    } else {
        throw new UnsupportedOperationException("Unsupported Result subclass: " + result.getClass().getName());
    }
}