Example usage for java.io StringWriter getBuffer

List of usage examples for java.io StringWriter getBuffer

Introduction

In this page you can find the example usage for java.io StringWriter getBuffer.

Prototype

public StringBuffer getBuffer() 

Source Link

Document

Return the string buffer itself.

Usage

From source file:org.alfresco.filesys.FTPServerTest.java

/**
 * Test quality utility to read an input stream into a string.
 * @param is/*from  www.  j a  va  2 s .  c o  m*/
 * @return the content of the stream in a string.
 * @throws IOException
 */
private String inputStreamToString(InputStream is) throws IOException {
    if (is != null) {
        StringWriter 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();
        }
        is.close();

        return writer.getBuffer().toString();

    }
    return "";
}

From source file:com.gdo.stencils.plug.PStcl.java

public String getStringFacet(StclContext stclContext, String facet, String mode) {
    try {//from  w  w  w .  ja va 2  s.c om
        FacetResult facetResult = getFacet(stclContext, facet, mode);
        StringWriter sw = new StringWriter();
        InputStream input = facetResult.getInputStream();
        IOUtils.copy(input, sw);
        facetResult.closeInputStream();
        return sw.getBuffer().toString();
    } catch (Exception e) {
        return e.toString();
    }
}

From source file:com.gdo.stencils.plug.PStcl.java

public String getDOM5Facet(StclContext stclContext, String html) {
    try {/*  ww  w .  j a va2 s . c o m*/
        FacetResult facetResult = getFacet(stclContext, FacetType.DOM5, html);
        StringWriter sw = new StringWriter();
        InputStream input = facetResult.getInputStream();
        IOUtils.copy(input, sw);
        facetResult.closeInputStream();
        return sw.getBuffer().toString();
    } catch (Exception e) {
        return e.toString();
    }
}

From source file:com.gdo.stencils.plug.PStcl.java

public String getHTML5TextFacet(StclContext stclContext, String skeleton) {
    try {/*from ww w .j  a  v  a2  s.  c  o  m*/
        FacetResult facetResult = getFacet(stclContext, FacetType.HTML5_TEXT, skeleton);
        StringWriter sw = new StringWriter();
        InputStream input = facetResult.getInputStream();
        IOUtils.copy(input, sw);
        facetResult.closeInputStream();
        return sw.getBuffer().toString();
    } catch (Exception e) {
        return e.toString();
    }
}

From source file:com.gdo.stencils.plug.PStcl.java

public String getDOM5TextFacet(StclContext stclContext, String html) {
    try {/*from  w  ww.j a  v  a2s.  c  o m*/
        FacetResult facetResult = getFacet(stclContext, FacetType.DOM5_TEXT, html);
        StringWriter sw = new StringWriter();
        InputStream input = facetResult.getInputStream();
        IOUtils.copy(input, sw);
        facetResult.closeInputStream();
        return sw.getBuffer().toString();
    } catch (Exception e) {
        return e.toString();
    }
}

From source file:org.apache.jackrabbit.core.config.RepositoryConfig.java

/**
 * Creates a new workspace configuration with the specified name and the
 * specified workspace <code>template</.
 * <p/>/*from w w w  .  j  av  a 2 s  .c  o m*/
 * This method creates a workspace configuration subdirectory,
 * copies the workspace configuration template into it, and finally
 * adds the created workspace configuration to the repository.
 * The initialized workspace configuration object is returned to
 * the caller.
 *
 * @param name workspace name
 * @param template the workspace template
 * @param configContent optional stringbuffer that will have the content
 *        of workspace configuration file written in
 * @return created workspace configuration
 * @throws ConfigurationException if creating the workspace configuration
 *                                failed
 */
private synchronized WorkspaceConfig internalCreateWorkspaceConfig(String name, Element template,
        StringBuffer configContent) throws ConfigurationException {

    // The physical workspace home directory on disk (TODO encode name?)
    File directory = new File(workspaceDirectory, name);

    // Create the physical workspace directory, fail if it exists
    // or cannot be created
    if (!directory.mkdir()) {
        if (directory.exists()) {
            throw new ConfigurationException("Workspace directory already exists: " + name);
        } else {
            throw new ConfigurationException("Failed to create workspace directory: " + name);
        }
    }

    FileSystem virtualFS;
    if (workspaceConfigDirectory != null) {
        // a configuration directoy had been specified;
        // workspace configurations are maintained in
        // virtual repository file system
        try {
            virtualFS = fsf.getFileSystem();
        } catch (RepositoryException e) {
            throw new ConfigurationException("File system configuration error", e);
        }
    } else {
        // workspace configurations are maintained on disk
        virtualFS = null;
    }
    try {
        Writer configWriter;

        // get a writer for the workspace configuration file
        if (virtualFS != null) {
            // a configuration directoy had been specified; create workspace
            // configuration in virtual repository file system rather than
            // on disk
            String configDir = workspaceConfigDirectory + FileSystem.SEPARATOR + name;
            String configFile = configDir + FileSystem.SEPARATOR + WORKSPACE_XML;
            try {
                // Create the directory
                virtualFS.createFolder(configDir);

                configWriter = new OutputStreamWriter(virtualFS.getOutputStream(configFile));
            } catch (FileSystemException e) {
                throw new ConfigurationException(
                        "failed to create workspace configuration at path " + configFile, e);
            }
        } else {
            File file = new File(directory, WORKSPACE_XML);
            try {
                configWriter = new FileWriter(file);
            } catch (IOException e) {
                throw new ConfigurationException(
                        "failed to create workspace configuration at path " + file.getPath(), e);
            }
        }

        // Create the workspace.xml file using the configuration template and
        // the configuration writer.
        try {
            template.setAttribute("name", name);

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

            if (configContent == null) {
                transformer.transform(new DOMSource(template), new StreamResult(configWriter));
            } else {
                StringWriter writer = new StringWriter();
                transformer.transform(new DOMSource(template), new StreamResult(writer));

                String s = writer.getBuffer().toString();
                configWriter.write(s);
                configContent.append(s);
            }
        } catch (IOException e) {
            throw new ConfigurationException("Cannot create a workspace configuration file", e);
        } catch (TransformerConfigurationException e) {
            throw new ConfigurationException("Cannot create a workspace configuration writer", e);
        } catch (TransformerException e) {
            throw new ConfigurationException("Cannot create a workspace configuration file", e);
        } finally {
            IOUtils.closeQuietly(configWriter);
        }

        // Load the created workspace configuration.
        WorkspaceConfig wc;
        if (virtualFS != null) {
            String configDir = workspaceConfigDirectory + FileSystem.SEPARATOR + name;
            wc = loadWorkspaceConfig(virtualFS, configDir);
        } else {
            wc = loadWorkspaceConfig(directory);
        }
        if (wc != null) {
            addWorkspaceConfig(wc);
            return wc;
        } else {
            throw new ConfigurationException(
                    "Failed to load the created configuration for workspace " + name + ".");
        }
    } finally {
        try {
            if (virtualFS != null) {
                virtualFS.close();
            }
        } catch (FileSystemException ignore) {
        }
    }
}

From source file:edu.cornell.med.icb.goby.stats.TestAnnotationAveragingWriter.java

@Test
public void testCase2() {
    String[] samples = new String[] { "sample1" };
    int[] positions = new int[] { 6, 8, 14, 16 };
    int[][] C = { { 5, 3, 9, 8 } };
    int[][] Cm = { { 9, 7, 1, 5 } };

    testSupport = new MethylCountProviderTestSupport(samples, positions, "Case2", C, Cm);
    final StringWriter stringWriter = new StringWriter();
    AnnotationAveragingWriter testWriter = new AnnotationAveragingWriter(stringWriter, genome, testSupport);
    testWriter.setAnnotationFilename("test-data/vcf-averaging/annotations-1.tsv");
    testWriter.setWriteNumSites(false);/* w  w  w  .ja  v a2  s.  c o  m*/
    testWriter.setContexts(DEFAULT_TEST_CONTEXTS);
    testWriter.writeRecord();
    testWriter.writeRecord();
    testWriter.writeRecord();
    testWriter.writeRecord();
    testWriter.close();
    assertEquals("Test Case 2 result: ",
            "Chromosome\tStart\tEnd\tFeature\tMR[sample1][CpG]\tMR[sample1][CpA]\tMR[sample1][CpC]\tMR[sample1][CpT]\tMR[sample1][CpN]\n"
                    + "Case2\t5\t9\tannotation1\t66.67\t\t\t\t\n"
                    + "Case2\t13\t17\tannotation2\t26.09\t\t\t\t\n",
            stringWriter.getBuffer().toString());
}

From source file:de.fuberlin.wiwiss.marbles.MarblesServlet.java

/**
 * Discovers an URI and renders a given view for it (<code>view</code>).
 *
 * @param request//from w  w  w .j a v  a 2s .  c  om
 * @param response
 * @throws IOException
 */
public void fresnelView(HttpServletRequest request, HttpServletResponse response) throws IOException {
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));
    String errorString = null;
    Selection selected = null;
    List<org.apache.commons.httpclient.URI> retrievedURLs = null;
    Resource focalResource = null;
    Configuration conf = null;
    String redirectLocation = null;

    try {
        /* Reload the Fresnel configuration using the provided language */
        String langPref = (request.getParameter("lang") != null ? request.getParameter("lang") : "en");
        loadFresnelConfig(langPref);

        conf = new Configuration(confRepository, ontoRepository);

        /* Create the focal resource */
        if (request.getParameter("uri") != null) {
            String uriString = request.getParameter("uri");
            if (uriString.startsWith("_:")) /* blank node */
                focalResource = valueFactory.createBNode(uriString.substring(2));
            else
                focalResource = valueFactory.createURI(uriString);

            /* Collect data about the focal resource */
            if (request.getParameter("skipload") == null) {
                retrievedURLs = semwebClient.discoverResource(focalResource, true /* wait */);
            } /* skip */

            /* Initiate manual owl:sameAs inference */
            if (request.getParameter("skipInference") == null) {
                sameAsInferencer.addInferredForResource(focalResource);
            }

            if (conf.hasWarnings())
                writer.println(conf.getWarningsString());

            Purpose purpose = null;

            /* Look up the requested lens purpose */
            if (request.getParameter("purpose") != null
                    && (!request.getParameter("purpose").equals("defaultPurpose")))
                purpose = new Purpose(new URIImpl(Constants.nsFresnelExt + request.getParameter("purpose")));
            else
                purpose = new Purpose(new URIImpl(
                        "http://www.w3.org/2004/09/fresnel#defaultLens")); /* this must be provided, or a random lens is chosen */

            try {
                /* Perform Fresnel selection using the requested display purpose and language */
                selected = conf.select(dataRepository, focalResource, purpose, langPref);

                /* Perform Fresnel formatting */
                selected = conf.format(dataRepository, selected);
            } catch (NoResultsException e) {

                /* 
                 * If no results are found, redirect the user to the resource
                 * if it is not an RDF document.
                 * This code is not reached when there already is some data about the resource.
                 */
                RepositoryConnection metaDataConn = null;
                try {
                    metaDataConn = metaDataRepository.getConnection();

                    /* Manual support for one level of redirects */
                    String resourceRedirect = cacheController.getCachedHeaderDataValue(metaDataConn,
                            focalResource, "location");
                    Resource resourceURI = (resourceRedirect == null ? focalResource
                            : new URIImpl(resourceRedirect));

                    /* Get target content type */
                    String contentType = cacheController.getCachedHeaderDataValue(metaDataConn, resourceURI,
                            "content-type");
                    if (contentType != null && !ContentTypes.isRDF(contentType)) {
                        redirectLocation = focalResource.toString();
                    }
                } catch (RepositoryException re) {
                    re.printStackTrace();
                } catch (IllegalArgumentException ie) {
                    ie.printStackTrace();
                } finally {
                    try {
                        if (metaDataConn != null)
                            metaDataConn.close();
                    } catch (RepositoryException re) {
                        re.printStackTrace();
                    }
                }
            }
        } /* uri != null */
    } catch (Exception e) {
        e.printStackTrace();
        errorString = e.getMessage();
    }

    /* Output */
    try {
        /* Handle redirection to non-RDF data */
        if (redirectLocation != null) {
            response.setHeader("Location", redirectLocation);
            response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
        } else { /* Perform XSL output */

            /*
             * When there are no results, we still need a selection object in 
             * order to render the fresnel tree
             */
            if (selected == null)
                selected = new Selection(conf);

            Document fresnelTree = selected.render();
            addSources(fresnelTree, retrievedURLs);

            /* Prepare XSLT */
            StreamSource styleSource = new StreamSource(
                    new File(dataRoot + "/" + xslDirectory + "/" + xslTransformation));
            net.sf.saxon.TransformerFactoryImpl tf = new net.sf.saxon.TransformerFactoryImpl();
            Transformer styleTransformer = tf.newTransformer(styleSource);

            /* Debug output */
            if (request.getParameter("debug") != null) {
                /* debug output: fresnel tree */
                StringWriter stringWriter = new StringWriter();
                Transformer treeTransformer = tf.newTransformer();
                treeTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
                treeTransformer.transform(new DOMSource(fresnelTree), new StreamResult(stringWriter));
                styleTransformer.setParameter("fresnelTree", stringWriter.getBuffer().toString());
            }

            /* Apply parameters */
            styleTransformer.setParameter("assetsURL", assetsURL != null ? assetsURL.toString() : "");
            styleTransformer.setParameter("serviceURL", serviceURL != null ? serviceURL.toString() : "");
            styleTransformer.setParameter("errorString", errorString);
            styleTransformer.setParameter("mainResource",
                    focalResource != null ? focalResource.toString() : "");
            if (request.getParameter("purpose") != null)
                styleTransformer.setParameter("purpose", request.getParameter("purpose"));
            else
                styleTransformer.setParameter("purpose", "defaultPurpose");

            if (request.getParameter("mobile") != null)
                styleTransformer.setParameter("isMobile", request.getParameter("mobile"));

            HashMap<String, String[]> newParameters = new HashMap<String, String[]>(request.getParameterMap());

            if (!newParameters.containsKey("lang"))
                newParameters.put("lang", new String[] { "en" });

            for (Object key : new String[] { "purpose", "uri" }) {
                newParameters.remove(key);
            }

            String parameterString = "";

            /* Serialize parameters for use in HTML links and forms */
            for (Object key : newParameters.keySet()) {
                parameterString += (parameterString.equals("") ? "" : "&") + key + "="
                        + ((String[]) newParameters.get(key))[0];
            }

            styleTransformer.setParameter("sessionParams", parameterString);

            /* Perform rendering */
            StreamResult res = new StreamResult(writer);
            styleTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
            styleTransformer.transform(new DOMSource(fresnelTree), res);
        }
    } catch (Exception e) {
        e.printStackTrace();
        writer.print(e.getMessage());
    } finally {
    }
}

From source file:com.evolveum.midpoint.util.DOMUtil.java

public static StringBuffer printDom(Node node, boolean indent, boolean omitXmlDeclaration) {
    StringWriter writer = new StringWriter();
    TransformerFactory transfac = TransformerFactory.newInstance();
    Transformer trans;/*  w w  w.  java 2 s. co m*/
    try {
        trans = transfac.newTransformer();
    } catch (TransformerConfigurationException e) {
        throw new SystemException("Error in XML configuration: " + e.getMessage(), e);
    }
    trans.setOutputProperty(OutputKeys.INDENT, (indent ? "yes" : "no"));
    trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); // XALAN-specific
    trans.setParameter(OutputKeys.ENCODING, "utf-8");
    // Note: serialized XML does not contain xml declaration
    trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, (omitXmlDeclaration ? "yes" : "no"));

    DOMSource source = new DOMSource(node);
    try {
        trans.transform(source, new StreamResult(writer));
    } catch (TransformerException e) {
        throw new SystemException("Error in XML transformation: " + e.getMessage(), e);
    }

    return writer.getBuffer();
}

From source file:com.photon.phresco.framework.rest.api.RepositoryService.java

private static String convertDocumentToString(Document doc) throws PhrescoException {
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer;/*from  ww  w .j a  va  2 s . c  o  m*/
    try {
        transformer = tf.newTransformer();
        StringWriter writer = new StringWriter();
        transformer.transform(new DOMSource(doc), new StreamResult(writer));
        String output = writer.getBuffer().toString();
        return output;
    } catch (TransformerException e) {
        throw new PhrescoException(e);
    }
}