Example usage for java.io Writer toString

List of usage examples for java.io Writer toString

Introduction

In this page you can find the example usage for java.io Writer toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:bridge.toolkit.commands.S1000DConverter.java

/** 
 * The unit of processing work to be performed for the S1000DConverter module.
 * @see org.apache.commons.chain.Command#execute(org.apache.commons.chain.Context)
 *///from  w  w w  .jav  a 2s  .  co  m
public boolean execute(Context ctx) {
    System.out.println("Executing S1000D Converter");
    if ((ctx.get(Keys.SCPM_FILE) != null) && (ctx.get(Keys.RESOURCE_PACKAGE) != null)) {
        /*
         * check the output directory in the context if it does not exist make it
         */
        if (!(ctx.containsKey(Keys.OUTPUT_DIRECTORY))) {
            ctx.put(Keys.OUTPUT_DIRECTORY, "");
        }

        resourcepack = ctx.get(Keys.RESOURCE_PACKAGE).toString();
        /*
         * if SCPM is 4.1 then Move the original file to the temp directory
         * in this file it will perform the downgrade to 4.0 version If
         * /scormContentPackage/content/scoEntry/scoEntryItem exists is a
         * 4.1 SCPM
         */
        org.w3c.dom.Document new40 = null;
        File tempSCPM = null;
        try {
            new40 = getDoc(new File(ctx.get(Keys.SCPM_FILE).toString()));
            if (processXPathSingleNode("/scormContentPackage/content/scoEntry/scoEntryItem", new40) == null) {
                System.out.println("S1000D Converter Complete");
                return CONTINUE_PROCESSING;
            }
            tempSCPM = File.createTempFile(new File(ctx.get(Keys.SCPM_FILE).toString()).getName(), ".xml");
            copy(ctx.get(Keys.SCPM_FILE).toString(), tempSCPM.toString());
            ctx.put(Keys.SCPM_FILE, tempSCPM.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
            return PROCESSING_COMPLETE;
        }

        List<File> src_files = new ArrayList<File>();
        try {
            src_files = getSourceFiles((String) ctx.get(Keys.RESOURCE_PACKAGE));
        } catch (Exception npe) {
            System.out.println("The 'Resource Package' is empty.");
            return PROCESSING_COMPLETE;
        }

        /*
         * For each scoEntry adding sconEntryAddress and scoEntryStatus
         */
        try {
            // getting the modelic and issuer from status SCPM
            modelic = processXPathSingleNode(
                    "/scormContentPackage/identAndStatusSection/scormContentPackageAddress/scormContentPackageIdent/scormContentPackageCode/@modelIdentCode",
                    new40).getNodeValue();
            PackageIssuer = processXPathSingleNode(
                    "/scormContentPackage/identAndStatusSection/scormContentPackageAddress/scormContentPackageIdent/scormContentPackageCode/@scormContentPackageIssuer",
                    new40).getNodeValue();
            PackageNumber = processXPathSingleNode(
                    "/scormContentPackage/identAndStatusSection/scormContentPackageAddress/scormContentPackageIdent/scormContentPackageCode/@scormContentPackageNumber",
                    new40).getNodeValue();
            PackageVolume = processXPathSingleNode(
                    "/scormContentPackage/identAndStatusSection/scormContentPackageAddress/scormContentPackageIdent/scormContentPackageCode/@scormContentPackageVolume",
                    new40).getNodeValue();

            securityClassification = processXPathSingleNode(
                    "/scormContentPackage/identAndStatusSection/scormContentPackageStatus/security/@securityClassification",
                    new40).getNodeValue();
            ;
            qualityAssurance = processXPathSingleNode(
                    "/scormContentPackage/identAndStatusSection/scormContentPackageStatus/qualityAssurance",
                    new40);

            // getting the content node
            Node content = processXPathSingleNode("//content", new40);

            if (content != null) {
                // delete content..
                Node contentclone = content.cloneNode(true);
                removeNode(content);
                // add the content Node..
                org.w3c.dom.Element newcontent = new40.createElement("content");
                // navigate through the tree seeking for scoEntry
                for (int i = 0; i < contentclone.getChildNodes().getLength(); i++) {
                    Node node = contentclone.getChildNodes().item(i);
                    if (node.getNodeName().equals("scoEntry")) {
                        Node scoE = node.cloneNode(true);
                        walkingthrough(scoE, new40);
                        newcontent.appendChild(scoE);
                    }
                }

                // add the content modified
                Node pm = processXPathSingleNode("//scormContentPackage", new40);
                pm.appendChild(newcontent);

                // re write on temp file the new XML..
                writeOnDisk(tempSCPM, getXMLString(new40));
            }

        } catch (Exception npe) {
            Writer writer = new StringWriter();
            PrintWriter printWriter = new PrintWriter(writer);
            npe.printStackTrace(printWriter);
            writer.toString();
            System.out.println("Error " + npe + " " + writer.toString());
            return PROCESSING_COMPLETE;
        }

        System.out.println("Conversion of SCPM 4.1 to SCPM 4.0 was successful");
    } else {
        System.out.println("One of the required Context entries for the " + this.getClass().getSimpleName()
                + " command to be executed was null");
        return PROCESSING_COMPLETE;
    }
    return CONTINUE_PROCESSING;
}

From source file:com.netspective.commons.xml.ParseContext.java

public void doExternalTransformations() throws TransformerConfigurationException, TransformerException,
        ParserConfigurationException, SAXException, IOException {
    // re-create the input source because the original stream is already closed
    InputSource inputSource = recreateInputSource();

    Source activeSource = inputSource.getByteStream() != null ? new StreamSource(inputSource.getByteStream())
            : new StreamSource(inputSource.getCharacterStream());
    activeSource.setSystemId(inputSource.getSystemId());

    Writer activeResultBuffer = new StringWriter();
    Result activeResult = new StreamResult(activeResultBuffer);
    activeResult.setSystemId(activeResultBuffer.getClass().getName());

    TransformerFactory factory = TransformerFactory.newInstance();
    int lastTransformer = transformSources.length - 1;
    for (int i = 0; i <= lastTransformer; i++) {
        Transformer transformer = factory.newTransformer(transformSources[i]);
        transformer.transform(activeSource, activeResult);

        if (i < lastTransformer) {
            activeSource = new StreamSource(new StringReader(activeResultBuffer.toString()));
            activeResultBuffer = new StringWriter();
            activeResult = new StreamResult(activeResultBuffer);
        }/* w w w  .  j  a va2s .  c o m*/
    }

    // now that all the transformations have been performed, we want to reset our input source to the final
    // transformation
    init(createInputSource(activeResultBuffer.toString()));
}

From source file:com.adobe.cq.wcm.core.components.extension.contentfragment.internal.models.v1.ContentFragmentImplTest.java

@Test
public void testJSONExport() throws IOException {
    ContentFragmentImpl fragment = (ContentFragmentImpl) getTestContentFragment(CF_TEXT_ONLY);
    Writer writer = new StringWriter();
    ObjectMapper mapper = new ObjectMapper();
    mapper.writerWithView(ContentFragmentImpl.class).writeValue(writer, fragment);
    JsonReader jsonReaderOutput = Json.createReader(IOUtils.toInputStream(writer.toString()));
    JsonReader jsonReaderExpected = Json.createReader(Thread.currentThread().getContextClassLoader().getClass()
            .getResourceAsStream("/contentfragment/test-expected-content-export.json"));
    assertEquals(jsonReaderExpected.read(), jsonReaderOutput.read());
}

From source file:com.xebialabs.overthere.cifs.winrm.WinRmClient.java

/**
 * Handle the httpResponse and return the SOAP XML String.
 *//*from w  w  w.  ja v  a  2s .  c o m*/
protected String handleResponse(final HttpResponse response, final HttpContext context) throws IOException {
    final HttpEntity entity = response.getEntity();
    if (null == entity.getContentType()
            || !entity.getContentType().getValue().startsWith("application/soap+xml")) {
        throw new WinRmRuntimeIOException("Error when sending request to " + targetURL
                + "; Unexpected content-type: " + entity.getContentType());
    }

    final InputStream is = entity.getContent();
    final Writer writer = new StringWriter();
    final Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
    try {
        int n;
        final char[] buffer = new char[1024];
        while ((n = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, n);
        }
    } finally {
        closeQuietly(reader);
        closeQuietly(is);
        consume(response.getEntity());
    }

    return writer.toString();
}

From source file:net.sourceforge.fenixedu.domain.accounting.report.events.EventReportQueueJob.java

private StringBuilder getExceptionLine(Throwable e) {
    StringBuilder exceptionLine = new StringBuilder();
    final Writer result = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(result);
    e.printStackTrace(printWriter);//from w  w w .j av a2  s.  c o m
    String[] exceptionLines = result.toString().split(LINE_BREAK);
    exceptionLine.append(exceptionLines[0]).append(" - ")
            .append(exceptionLines[1].replace(FIELD_SEPARATOR, ""));
    return exceptionLine;
}

From source file:nl.sogeti.android.gpstracker.actions.ShareTrack.java

public String convertStreamToString(InputStream is) throws IOException {
    /*//from   w w w .  java 2s .co  m
     * To convert the InputStream to String we use the Reader.read(char[] buffer) method. We iterate until the Reader return -1 which means there's no more data to read. We use the StringWriter
     * class to produce the string.
     */
    if (is != null) {
        Writer writer = new StringWriter();

        char[] buffer = new char[1024];
        try {
            Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            is.close();
        }
        return writer.toString();
    } else {
        return "";
    }
}

From source file:org.apache.camel.converter.jaxb.FallbackTypeConverter.java

protected <T> T marshall(Class<T> type, Exchange exchange, Object value)
        throws JAXBException, XMLStreamException, FactoryConfigurationError {
    T answer = null;/*from w w w.j a v  a 2  s .com*/
    if (parentTypeConverter != null) {
        // lets convert the object to a JAXB source and try convert that to
        // the required source
        JAXBContext context = createContext(value.getClass());
        // must create a new instance of marshaller as its not thread safe
        Marshaller marshaller = context.createMarshaller();
        Writer buffer = new StringWriter();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
                isPrettyPrint() ? Boolean.TRUE : Boolean.FALSE);
        if (exchange != null && exchange.getProperty(Exchange.CHARSET_NAME, String.class) != null) {
            marshaller.setProperty(Marshaller.JAXB_ENCODING,
                    exchange.getProperty(Exchange.CHARSET_NAME, String.class));
        }
        if (needFiltering(exchange)) {
            XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(buffer);
            FilteringXmlStreamWriter filteringWriter = new FilteringXmlStreamWriter(writer);
            marshaller.marshal(value, filteringWriter);
        } else {
            marshaller.marshal(value, buffer);
        }
        answer = parentTypeConverter.convertTo(type, buffer.toString());
    }

    return answer;
}

From source file:org.atricore.idbus.capabilities.sso.support.core.util.XmlUtils.java

public static String marshalSamlR2(Object msg, String msgQName, String msgLocalName) throws Exception {

    //JAXBContext jaxbContext = createJAXBContext(userPackages);
    JAXBContext jaxbContext = JAXBUtils.getJAXBContext(samlContextPackages, constructionType,
            samlContextPackages.toString(), XmlUtils.class.getClassLoader(), new HashMap<String, Object>());
    Marshaller m = JAXBUtils.getJAXBMarshaller(jaxbContext);

    JAXBElement jaxbRequest = new JAXBElement(new QName(msgQName, msgLocalName), msg.getClass(), msg);

    Writer writer = new StringWriter();
    XMLStreamWriter xmlStreamWriter = new NamespaceFilterXMLStreamWriter(writer);

    // Support XMLDsig

    // TODO : What about non-sun XML Bind stacks!
    m.setProperty("com.sun.xml.bind.namespacePrefixMapper", new NamespacePrefixMapper() {

        @Override//from w ww. j  a va 2 s .c o  m
        public String[] getPreDeclaredNamespaceUris() {
            return new String[] { SAMLR2Constants.SAML_PROTOCOL_NS, SAMLR2Constants.SAML_ASSERTION_NS,
                    "http://www.w3.org/2000/09/xmldsig#", "http://www.w3.org/2001/04/xmlenc#",
                    "http://www.w3.org/2001/XMLSchema" };
        }

        @Override
        public String getPreferredPrefix(String nsUri, String suggestion, boolean requirePrefix) {

            if (nsUri.equals(SAMLR2Constants.SAML_PROTOCOL_NS))
                return "samlp";
            else if (nsUri.equals(SAMLR2Constants.SAML_ASSERTION_NS))
                return "saml";
            else if (nsUri.equals("http://www.w3.org/2000/09/xmldsig#"))
                return "ds";
            else if (nsUri.equals("http://www.w3.org/2001/04/xmlenc#"))
                return "enc";
            else if (nsUri.equals("http://www.w3.org/2001/XMLSchema"))
                return "xsd";

            return suggestion;
        }
    });

    m.marshal(jaxbRequest, xmlStreamWriter);
    xmlStreamWriter.flush();
    JAXBUtils.releaseJAXBMarshaller(jaxbContext, m);

    return writer.toString();
}

From source file:org.executequery.gui.resultset.TableCellData.java

private String readClob() {

    if (StringUtils.isNotBlank(valueAsString) || value == null) {

        return valueAsString;
    }/*w  ww .ja v  a 2s .c  om*/

    Clob clob = (Clob) value;

    Writer writer = new StringWriter();
    Reader reader;
    try {

        reader = clob.getCharacterStream();

    } catch (SQLException e) {

        if (Log.isDebugEnabled()) {

            Log.debug("Error reading CLOB data", e);
        }

        return e.getMessage();
    }

    char[] buffer = new char[DEFAULT_BUFFER_SIZE];

    try {

        while (true) {

            int amountRead;
            amountRead = reader.read(buffer);

            if (amountRead == -1) {

                break;
            }

            writer.write(buffer);
        }

        writer.flush();

    } catch (IOException e) {

        if (Log.isDebugEnabled()) {

            Log.debug("Error reading CLOB data", e);
        }

        return e.getMessage();
    }

    valueAsString = writer.toString();
    return valueAsString;
}

From source file:org.apache.cocoon.xml.dom.DOMUtil.java

/**
 * Get a document fragment from a <code>Reader</code>.
 * The reader must provide valid XML, but it is allowed that the XML
 * has more than one root node. This xml is parsed by the
 * specified parser instance and a DOM DocumentFragment is created.
 *///from   w w  w  .  ja  v a  2  s  .c  o m
public static DocumentFragment getDocumentFragment(SAXParser parser, Reader stream) throws ProcessingException {
    DocumentFragment frag = null;

    Writer writer;
    Reader reader;
    boolean removeRoot = true;

    try {
        // create a writer,
        // write the root element, then the input from the
        // reader
        writer = new StringWriter();

        writer.write(XML_ROOT_DEFINITION);
        char[] cbuf = new char[16384];
        int len;
        do {
            len = stream.read(cbuf, 0, 16384);
            if (len != -1) {
                writer.write(cbuf, 0, len);
            }
        } while (len != -1);
        writer.write("</root>");

        // now test if xml input start with <?xml
        String xml = writer.toString();
        String searchString = XML_ROOT_DEFINITION + "<?xml ";
        if (xml.startsWith(searchString) == true) {
            // now remove the surrounding root element
            xml = xml.substring(XML_ROOT_DEFINITION.length(), xml.length() - 7);
            removeRoot = false;
        }

        reader = new StringReader(xml);

        InputSource input = new InputSource(reader);

        DOMBuilder builder = new DOMBuilder();
        builder.startDocument();
        builder.startElement("", "root", "root", XMLUtils.EMPTY_ATTRIBUTES);

        IncludeXMLConsumer filter = new IncludeXMLConsumer(builder, builder);
        parser.parse(input, filter);

        builder.endElement("", "root", "root");
        builder.endDocument();

        // Create Document Fragment, remove <root>
        final Document doc = builder.getDocument();
        frag = doc.createDocumentFragment();
        final Node root = doc.getDocumentElement().getFirstChild();
        root.normalize();
        if (removeRoot == false) {
            root.getParentNode().removeChild(root);
            frag.appendChild(root);
        } else {
            Node child;
            while (root.hasChildNodes() == true) {
                child = root.getFirstChild();
                root.removeChild(child);
                frag.appendChild(child);
            }
        }
    } catch (SAXException sax) {
        throw new ProcessingException("SAXException: " + sax, sax);
    } catch (IOException ioe) {
        throw new ProcessingException("IOException: " + ioe, ioe);
    }
    return frag;
}