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

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

Introduction

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

Prototype

public Writer getWriter() 

Source Link

Document

Get the character stream that was set with setWriter.

Usage

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 a va 2  s.  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 {//from   w  ww  .ja  va  2s. 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.displaytag.export.FopExportView.java

/**
 * log it./* w  w w  .  j a  v a  2s  .c  o  m*/
 * @param xmlResults raw
 * @param transformer the transformer
 * @param e the optional exception
 * @throws JspException wrapping an existing error
 */
protected void logXsl(String xmlResults, Transformer transformer, Exception e) throws JspException {
    StreamResult debugRes = new StreamResult(new StringWriter());
    StreamSource src = new StreamSource(new StringReader(xmlResults));
    try {
        transformer.transform(src, debugRes);
        if (e != null) {
            log.error("xslt-fo error " + e.getMessage(), e); //$NON-NLS-1$
            log.error("xslt-fo result of " + debugRes.getWriter()); //$NON-NLS-1$
            throw new JspException("Stylesheet produced invalid xsl-fo result", e); //$NON-NLS-1$
        } else {
            log.info("xslt-fo result of " + debugRes.getWriter()); //$NON-NLS-1$
        }
    } catch (TransformerException ee) {
        throw new JspException("error creating pdf output " + ee.getMessage(), ee); //$NON-NLS-1$
    }
}

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();//from  ww  w . j  a  v a2s .  c om
        } else {
            final Writer w = r.getWriter();
            if (w != null) {
                w.close();
            }
        }
    }
}

From source file:org.eclipse.smila.integration.solr.SolrIndexPipelet.java

@Override
public String[] process(final Blackboard blackboard, final String[] recordIds) throws ProcessingException {
    final String updateURL = HTTP_LOCALHOST + SOLR_WEBAPP + UPDATE;
    String updateXMLMessage = null;
    URL url = null;//from  w  ww .  j  a v a2 s.c  om
    HttpURLConnection conn = null;
    String logId = null;
    try {
        url = new URL(updateURL);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod(POST);
        conn.setRequestProperty(CONTENT_TYPE, TEXT_XML_CHARSET + UTF8);
        conn.setUseCaches(false);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setReadTimeout(10000);
    } catch (final Exception e) {
        final String msg = "Error while opening Solr connection: '" + e.getMessage() + "'";
        _log.error(msg, e);
        throw new ProcessingException(msg, e);
    }
    try {
        final DOMImplementation impl = DOMImplementationImpl.getDOMImplementation();
        final Document document = impl.createDocument(null, SolrResponseHandler.SOLR, null);
        Element add = null;
        if (_mode == ExecutionMode.ADD) {
            add = document.createElement(ADD);
        } else {
            add = document.createElement(DELETE);
        }
        if (_allowDoublets) {
            add.setAttribute(OVERWRITE, "false");
        } else {
            add.setAttribute(OVERWRITE, "true");
        }
        add.setAttribute(COMMIT_WITHIN, String.valueOf(_commitWithin));

        for (final String id : recordIds) {
            logId = id;
            final Element doc = document.createElement(SolrResponseHandler.DOC);
            add.appendChild(doc);

            // Create id attribute
            Element field = document.createElement(FIELD);
            field.setAttribute(SolrResponseHandler.NAME, SolrResponseHandler.ID);
            final String idEncoded = URLEncoder.encode(id, UTF8);
            Text text = document.createTextNode(idEncoded);
            field.appendChild(text);
            doc.appendChild(field);

            // Create all other attributes
            final AnyMap record = blackboard.getMetadata(id);
            for (final String attrName : record.keySet()) {
                if (!attrName.startsWith(META_DATA) && !attrName.startsWith(RESPONSE_HEADER)) {
                    final Any attributeValue = record.get(attrName);
                    for (final Any any : attributeValue) {
                        if (any.isValue()) {
                            final Value value = (Value) any;
                            String stringValue = null;
                            if (value.isDate()) {
                                final SimpleDateFormat df = new SimpleDateFormat(
                                        SolrResponseHandler.DATE_FORMAT_PATTERN);
                                stringValue = df.format(value.asDate());
                            } else if (value.isDateTime()) {
                                final SimpleDateFormat df = new SimpleDateFormat(
                                        SolrResponseHandler.DATE_FORMAT_PATTERN);
                                stringValue = df.format(value.asDateTime());
                            } else {
                                stringValue = replaceNonXMLChars(value.asString());
                            }
                            field = document.createElement(FIELD);
                            field.setAttribute(SolrResponseHandler.NAME, attrName);
                            text = document.createTextNode(stringValue);
                            field.appendChild(text);
                            doc.appendChild(field);
                        }
                    }
                }
            }
        }
        final Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
        if (_log.isDebugEnabled()) {
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        }
        final DOMSource source = new DOMSource(add);
        final Writer w = new StringWriter();
        final StreamResult streamResult = new StreamResult(w);
        transformer.transform(source, streamResult);
        updateXMLMessage = streamResult.getWriter().toString();
        conn.setRequestProperty(CONTENT_LENGTH, Integer.toString(updateXMLMessage.length()));
        final DataOutputStream os = new DataOutputStream(conn.getOutputStream());
        os.write(updateXMLMessage.getBytes(UTF8));
        os.flush();
        os.close();

        final BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        final StringBuffer response = new StringBuffer();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();
        // System.out.println("Response:\n" + response.toString());
    } catch (final Exception e) {
        final String msg = "Error while processing record '" + logId + "' for index '" + _indexName + "': "
                + e.getMessage() + "'.";
        _log.error(msg, e);
        if (_log.isDebugEnabled()) {
            try {
                final FileOutputStream fos = new FileOutputStream(DigestHelper.calculateDigest(logId) + ".xml");
                fos.write(updateXMLMessage.getBytes(UTF8));
                fos.flush();
                fos.close();
            } catch (final Exception ee) {
                throw new ProcessingException(msg, ee);
            }
        }
        throw new ProcessingException(msg, e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    return recordIds;
}

From source file:org.eclipse.smila.integration.solr.SolrPipelet.java

public Id[] process(Blackboard blackboard, Id[] recordIds) throws ProcessingException {
    String updateURL = HTTP_LOCALHOST + SOLR_WEBAPP + UPDATE;
    String updateXMLMessage = null;
    URL url = null;/*from   w w w.ja v  a2 s  . c  o m*/
    HttpURLConnection conn = null;
    Id _id = null;
    try {
        url = new URL(updateURL);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod(POST);
        conn.setRequestProperty(CONTENT_TYPE, TEXT_XML_CHARSET + UTF8);
        conn.setUseCaches(false);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setReadTimeout(10000);
    } catch (Exception e) {
        String msg = "Error while opening Solr connection: '" + e.getMessage() + "'";
        _log.error(msg, e);
        throw new ProcessingException(msg, e);
    }
    try {
        DOMImplementation impl = DOMImplementationImpl.getDOMImplementation();
        Document document = impl.createDocument(null, SolrResponseHandler.SOLR, null);
        Element add = null;
        if (_mode == ExecutionMode.ADD) {
            add = document.createElement(ADD);
        } else {
            add = document.createElement(DELETE);
        }
        if (_allowDoublets) {
            add.setAttribute(OVERWRITE, "false");
        } else {
            add.setAttribute(OVERWRITE, "true");
        }
        add.setAttribute(COMMIT_WITHIN, String.valueOf(_commitWithin));

        for (Id id : recordIds) {
            _id = id;
            Element doc = document.createElement(SolrResponseHandler.DOC);
            add.appendChild(doc);

            // Create id attribute
            Element field = document.createElement(FIELD);
            field.setAttribute(SolrResponseHandler.NAME, SolrResponseHandler.ID);
            IdBuilder idBuilder = new IdBuilder();
            String idXML = idBuilder.idToString(id);
            String idEncoded = URLEncoder.encode(idXML, UTF8);
            Text text = document.createTextNode(idEncoded);
            field.appendChild(text);
            doc.appendChild(field);

            // Create all other attributes
            Iterator<String> i = blackboard.getAttributeNames(id);
            while (i.hasNext()) {
                String attrName = i.next();
                if (!attrName.startsWith(META_DATA) && !attrName.startsWith(RESPONSE_HEADER)) {
                    Path path = new Path(attrName);
                    Iterator<Literal> literals = blackboard.getLiterals(id, path).iterator();
                    while (literals.hasNext()) {
                        Literal value = literals.next();
                        String stringValue = null;
                        if (Literal.DataType.DATE.equals(value.getDataType())) {
                            SimpleDateFormat df = new SimpleDateFormat(SolrResponseHandler.DATE_FORMAT_PATTERN);
                            stringValue = df.format(value.getDateValue());
                        } else if (Literal.DataType.DATETIME.equals(value.getDataType())) {
                            SimpleDateFormat df = new SimpleDateFormat(SolrResponseHandler.DATE_FORMAT_PATTERN);
                            stringValue = df.format(value.getDateTimeValue());
                        } else {
                            stringValue = replaceNonXMLChars(value.getStringValue());
                        }
                        field = document.createElement(FIELD);
                        field.setAttribute(SolrResponseHandler.NAME, attrName);
                        text = document.createTextNode(stringValue);
                        field.appendChild(text);
                        doc.appendChild(field);
                    }
                }
            }
        }
        Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
        if (_log.isDebugEnabled()) {
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        }
        DOMSource source = new DOMSource(add);
        Writer w = new StringWriter();
        StreamResult streamResult = new StreamResult(w);
        transformer.transform(source, streamResult);
        updateXMLMessage = streamResult.getWriter().toString();
        conn.setRequestProperty(CONTENT_LENGTH, Integer.toString(updateXMLMessage.length()));
        DataOutputStream os = new DataOutputStream(conn.getOutputStream());
        os.write(updateXMLMessage.getBytes(UTF8));
        os.flush();
        os.close();
        System.out.println(updateXMLMessage);

        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        StringBuffer response = new StringBuffer();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();
        System.out.println("Response:\n" + response.toString());
    } catch (Exception e) {
        String msg = "Error while processing record '" + _id + "' for index '" + _indexName + "': "
                + e.getMessage() + "'.";
        _log.error(msg, e);
        if (_log.isDebugEnabled()) {
            try {
                FileOutputStream fos = new FileOutputStream(_id.getIdHash() + ".xml");
                fos.write(updateXMLMessage.getBytes(UTF8));
                fos.flush();
                fos.close();
            } catch (Exception ee) {
                throw new ProcessingException(msg, ee);
            }
        }
        throw new ProcessingException(msg, e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    return recordIds;
}

From source file:org.efaps.eclipse.wizards.CopyCIWizardPage.java

@Override
protected InputStream getInitialContents() {
    InputStream ret = null;/*w w w  . ja v  a  2s . com*/
    if (this.fileResource != null && this.fileResource.isAccessible()) {
        final URI uri = this.fileResource.getLocationURI();
        final File file = new File(uri);
        try {
            ret = new FileInputStream(file);

            final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            final DocumentBuilder docBuilder = factory.newDocumentBuilder();
            final Document doc = docBuilder.parse(file);
            // create the root element
            final Element root = doc.getDocumentElement();
            final NodeList children = root.getChildNodes();
            boolean def = false;
            boolean uuid = false;
            for (int i = 0; i < children.getLength(); i++) {
                if (children.item(i) instanceof Element) {
                    final Element child = (Element) children.item(i);
                    if ("uuid".equals(child.getNodeName())) {
                        child.setTextContent(UUID.randomUUID().toString());
                        uuid = true;
                    }
                    if ("definition".equals(child.getNodeName())) {
                        final NodeList defChildren = child.getChildNodes();
                        for (int j = 0; j < defChildren.getLength(); j++) {
                            if (defChildren.item(j) instanceof Element) {
                                final Element defChild = (Element) defChildren.item(j);
                                if ("name".equals(defChild.getNodeName())) {
                                    defChild.setTextContent(
                                            getFileName().replace("." + getFileExtension(), ""));
                                    break;
                                }
                            }
                        }
                        def = true;
                    }
                    if (def && uuid) {
                        break;
                    }
                }
            }

            final TransformerFactory transfac = TransformerFactory.newInstance();
            final Transformer trans = transfac.newTransformer();
            final Source source = new DOMSource(doc);
            final StreamResult result = new StreamResult(new StringWriter());
            trans.transform(source, result);
            ret = IOUtils.toInputStream(result.getWriter().toString());

        } catch (final FileNotFoundException e) {
            EfapsPlugin.getDefault().logError(getClass(), "FileNotFoundException", e);
        } catch (final ParserConfigurationException e) {
            EfapsPlugin.getDefault().logError(getClass(), "ParserConfigurationException", e);
        } catch (final SAXException e) {
            EfapsPlugin.getDefault().logError(getClass(), "SAXException", e);
        } catch (final IOException e) {
            EfapsPlugin.getDefault().logError(getClass(), "IOException", e);
        } catch (final TransformerConfigurationException e) {
            EfapsPlugin.getDefault().logError(getClass(), "TransformerConfigurationException", e);
        } catch (final TransformerException e) {
            EfapsPlugin.getDefault().logError(getClass(), "TransformerException", e);
        }
    }
    return ret;
}

From source file:org.ehealth_connector.communication.mpi.impl.V3PixAdapter.java

/**
 * Logs a debug message./*  w  w  w  .ja va  2  s  .c  o m*/
 * 
 * @param test
 *          will be prefixed to the log message
 * @param element
 *          the xml element serialized to be logged
 */
private void printMessage(String test, Element element) {

    try {
        // use a transformer to improve the output of the xml
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        // initialize StreamResult with File object to save to file
        StreamResult result = new StreamResult(new StringWriter());
        DOMSource source = new DOMSource(element);
        transformer.transform(source, result);

        String xmlString = result.getWriter().toString();

        log.debug(test + "\r" + xmlString);
    } catch (Exception e) {
        log.debug(test + " problem encountered in printMessage");
    }
}

From source file:org.erdc.cobie.shared.spreadsheetml.transformation.cobietab.COBieSpreadSheet.java

License:asdf

public String getXMLText() throws TransformerFactoryConfigurationError, TransformerException {
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    // initialize StreamResult with File object to save to file
    String xml = "";
    try {/*  w w w.  j  av a  2 s .  c om*/
        spreadsheetMLDocument = xlWorkbook.createDocument();

    } catch (ParserConfigurationException e) {
        LOGGER.error("", e);
    }
    StreamResult result = new StreamResult(new StringWriter());
    DOMSource source = new DOMSource(spreadsheetMLDocument);
    transformer.transform(source, result);
    xml = result.getWriter().toString();
    return xml;
}

From source file:org.expath.exist.ftclient.GetResourceMetadataFunction.java

@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {

    Sequence result = new ValueSequence();

    StreamResult resultAsStreamResult = null;

    try {//w w  w . j  a v  a 2  s  .  com
        resultAsStreamResult = ro.kuberam.libs.java.ftclient.GetResourceMetadata
                .getResourceMetadata(ExistExpathFTClientModule.retrieveRemoteConnection(context,
                        ((IntegerValue) args[0].itemAt(0)).getLong()), args[1].getStringValue());
    } catch (Exception ex) {
        throw new XPathException(ex.getMessage());
    }

    ByteArrayInputStream resultDocAsInputStream = null;
    try {
        resultDocAsInputStream = new ByteArrayInputStream(
                resultAsStreamResult.getWriter().toString().getBytes("UTF-8"));
    } catch (UnsupportedEncodingException ex) {
        throw new XPathException(ex.getMessage());
    }

    XMLReader reader = null;

    context.pushDocumentContext();
    try {
        InputSource src = new InputSource(new CloseShieldInputStream(resultDocAsInputStream));

        reader = context.getBroker().getBrokerPool().getParserPool().borrowXMLReader();
        MemTreeBuilder builder = context.getDocumentBuilder();
        DocumentBuilderReceiver receiver = new DocumentBuilderReceiver(builder, true);
        reader.setContentHandler(receiver);
        reader.parse(src);
        Document doc = receiver.getDocument();

        result = (NodeValue) doc;
    } catch (SAXException saxe) {
        // do nothing, we will default to trying to return a string below
    } catch (IOException ioe) {
        // do nothing, we will default to trying to return a string below
    } finally {
        context.popDocumentContext();

        if (reader != null) {
            context.getBroker().getBrokerPool().getParserPool().returnXMLReader(reader);
        }
    }

    return result;
}