Example usage for java.io StringWriter write

List of usage examples for java.io StringWriter write

Introduction

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

Prototype

public void write(String str) 

Source Link

Document

Write a string.

Usage

From source file:net.sourceforge.doddle_owl.ui.InputDocumentSelectionPanel.java

public String getTargetTextLines(String word) {
    StringWriter writer = new StringWriter();
    ListModel listModel = inputDocList.getModel();
    for (int i = 0; i < listModel.getSize(); i++) {
        Document doc = (Document) listModel.getElementAt(i);
        String text = doc.getText();
        if (text != null) {
            writer.write("[ " + doc.getFile().getAbsolutePath() + " ]\n");
            String[] lines = text.split("\n");
            for (int j = 0; j < lines.length; j++) {
                String line = lines[j];
                if (line.indexOf(word) != -1) {
                    writer.write((j + 1) + ": " + line + "\n");
                }//from  w  w  w.  j  ava2  s .  c o m
            }
            writer.write("\n");
        }
    }
    return writer.toString();
}

From source file:com.gdo.servlet.RpcWrapper.java

private void facet(StclContext stclContext, RpcArgs args) throws IOException {
    HttpServletResponse response = stclContext.getResponse();

    try {//from www  .jav  a 2 s.  c  om

        // gets facet type and mode
        String type = args.getStringParameter(stclContext, FACETS_PARAM);
        String mode = args.getStringParameter(stclContext, MODES_PARAM);
        if (StringUtils.isBlank(type)) {

            // the type is undefined
            String msg = String.format("no facet defined (param %s)", FACETS_PARAM);
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
            return;
        }

        // gets stencil
        PStcl stcl = args.getStencilFromPath(stclContext);
        if (StencilUtils.isNull(stcl)) {

            // null stencil may be accepted
            if (args.acceptNoStencil()) {
                StudioGdoServlet.writeHTMLResponse(stclContext.getResponse(), "",
                        args.getCharacterEncoding(stclContext));
                return;
            }

            // stencil may not be null
            String reason = StencilUtils.getNullReason(stcl);
            String msg = String.format("facet service : cannot found stencil at path %s : %s", args.getPath(),
                    reason);
            response.sendError(HttpServletResponse.SC_NO_CONTENT, msg);
            return;
        }

        // searches facet from stencil
        RenderContext<StclContext, PStcl> renderCtxt = new RenderContext<StclContext, PStcl>(stclContext, stcl,
                type, mode);
        FacetResult facetResult = stcl.getFacet(renderCtxt);
        if (facetResult.isNotSuccess()) {

            // error in facet
            response.sendError(HttpServletResponse.SC_NOT_FOUND, facetResult.getMessage());
            return;
        }

        // HTML facet
        if (FacetType.HTML.equals(type)) {
            StringWriter writer = new StringWriter();
            writer.write("<html>\n");
            writer.write(" <META HTTP-EQUIV=\"Pragma\" CONTENT=\"no-cache\">\n");
            writer.write(" <META HTTP-EQUIV=\"Expires\" CONTENT=\"-1\">\n");
            writer.write(" <META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=utf-8\">\n");
            writer.write("<body>\n");
            IOUtils.copy(facetResult.getInputStream(), writer);
            facetResult.closeInputStream();
            writer.write("</body>\n</html>\n");
            String content = stcl.format(stclContext, writer.getBuffer().toString());
            StudioGdoServlet.writeHTMLResponse(response, content, args.getCharacterEncoding(stclContext));
            return;
        }

        // HTML 5 facet or JSON facet
        if (FacetType.HTML5.equals(type) || FacetType.DOM5.equals(type) || FacetType.TRANS.equals(type)
                || FacetType.JSON.equals(type) || FacetType.JSKEL.equals(type) || FacetType.PYTHON.equals(type)
                || FacetType.REST.equals(type)) {
            String mime = facetResult.getMimeType();
            InputStream in = facetResult.getInputStream();
            StudioGdoServlet.writeResponse(stclContext.getResponse(), HttpServletResponse.SC_OK, mime, in,
                    StclContext.getCharacterEncoding());
            return;
        }

        // file facet
        if (FacetType.FILE.equals(type)) {
            if (FacetType.E4X.equals(mode)) {
                InputStream in = facetResult.getInputStream();
                String enc = StclContext.getCharacterEncoding();
                StudioGdoServlet.writeXMLResponse(stclContext.getResponse(), in, enc);
                facetResult.closeInputStream();
                return;
            }
            CatalinaUtils.writeFileResponse(stclContext, facetResult);
            return;
        }

        // write result
        Reader reader = new InputStreamReader(facetResult.getInputStream());
        XmlStringWriter writer = new XmlStringWriter(args.getCharacterEncoding(stclContext));
        writer.startElement("result");
        args.writeAttributes(stclContext, stcl, false, writer);
        addStatus(writer, Result.success());

        // not escaped as XML may be used in data
        writer.writeCDATAElement("data", StringHelper.read(reader));
        writer.endElement("result");

        // trace and response
        String xml = writer.getString();
        logTrace(stclContext, xml);
        StudioGdoServlet.writeXMLResponse(stclContext.getResponse(), xml,
                args.getCharacterEncoding(stclContext));
        facetResult.closeInputStream();
    } catch (Exception e) {
        String msg = logError(stclContext, e.toString());
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        return;
    }
}

From source file:org.eclipse.virgo.ide.bundlor.internal.core.BundlorProjectBuilder.java

private InputStream formatManifest(IFile file, InputStream manifestInput) throws IOException {
    StringWriter writer = new StringWriter();
    SpringBundleModel model = new SpringBundleModel("", true);
    SpringBundleModelFactory factory = new SpringBundleModelFactory(model);
    try {/*from  www.  j a  v a  2s .c  om*/
        Map headers = ManifestElement.parseBundleManifest(manifestInput, null);
        for (Object obj : headers.keySet()) {
            String key = (String) obj;
            String value = (String) headers.get(key);
            ManifestHeader header = (ManifestHeader) factory.createHeader(key, value);
            header.update(false);
            String result = header.write();
            writer.write(result);
        }
    } catch (BundleException e) {
    }
    String manifestOutput = writer.toString();
    writer.close();
    manifestInput.close();
    model.dispose();
    return new ByteArrayInputStream(manifestOutput.getBytes());
}

From source file:com.gdo.servlet.RpcWrapper.java

private void facets(StclContext stclContext, RpcArgs args) throws IOException {
    HttpServletResponse response = stclContext.getResponse();
    try {/*www  .  jav  a  2s. c om*/

        // gets facet type and mode
        String type = args.getStringParameter(stclContext, FACETS_PARAM);
        String mode = args.getStringParameter(stclContext, MODES_PARAM);
        if (StringUtils.isBlank(type)) {

            // the type is undefined
            String msg = String.format("no facet defined (param %s)", FACETS_PARAM);
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
            return;
        }

        // HTML 5 facet or JSON facet
        if (FacetType.HTML5.equals(type) || FacetType.DOM5.equals(type) || FacetType.JSON.equals(type)
                || FacetType.JSKEL.equals(type) || FacetType.PYTHON.equals(type)) {
            String mime = null;
            StringWriter str = new StringWriter();

            if (FacetType.JSON.equals(type) || FacetType.JSKEL.equals(type))
                str.write("[");

            for (PStcl stcl : args.getStencilsFromPath(stclContext)) {

                // on first stencil, mime variable is nor defined
                if (mime != null && (FacetType.JSON.equals(type) || FacetType.JSKEL.equals(type)))
                    str.write(",");

                // searches facet from stencil
                RenderContext<StclContext, PStcl> renderCtxt = new RenderContext<StclContext, PStcl>(
                        stclContext, stcl, type, mode);
                FacetResult facetResult = stcl.getFacet(renderCtxt);
                if (facetResult.isNotSuccess()) {

                    // error in facet
                    response.sendError(HttpServletResponse.SC_NOT_FOUND, facetResult.getMessage());
                    return;
                }

                InputStream in = facetResult.getInputStream();
                IOUtils.copy(in, str);
                facetResult.closeInputStream();

                if (mime == null)
                    mime = facetResult.getMimeType();
            }

            if (FacetType.JSON.equals(type) || FacetType.JSKEL.equals(type))
                str.write("]");

            InputStream in = new ByteArrayInputStream(
                    str.toString().getBytes(StclContext.getCharacterEncoding()));
            StudioGdoServlet.writeResponse(stclContext.getResponse(), HttpServletResponse.SC_OK, mime, in,
                    StclContext.getCharacterEncoding());
            return;
        }

        // the mode is undefined
        String msg = String.format("cannot call facets on mode %s", mode);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        return;
    } catch (Exception e) {
        String msg = logError(stclContext, e.toString());
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        return;
    }
}

From source file:org.apache.solr.SolrTestCaseJ4.java

/**
 * Generates an &lt;add&gt;&lt;doc&gt;... XML String with options
 * on the add./*from   w  w  w.  j a v  a  2 s. com*/
 *
 * @param doc the Document to add
 * @param args 0th and Even numbered args are param names, Odds are param values.
 * @see #add
 * @see #doc
 */
public static String add(XmlDoc doc, String... args) {
    try {
        StringWriter r = new StringWriter();

        // this is annoying
        if (null == args || 0 == args.length) {
            r.write("<add>");
            r.write(doc.xml);
            r.write("</add>");
        } else {
            XML.writeUnescapedXML(r, "add", doc.xml, (Object[]) args);
        }

        return r.getBuffer().toString();
    } catch (IOException e) {
        throw new RuntimeException("this should never happen with a StringWriter", e);
    }
}

From source file:org.exist.http.SOAPServer.java

/**
 * @param query/*from w ww .java 2  s .  co m*/
 * @param e
 */
private String formatXPathException(String query, String path, XPathException e) {
    final StringWriter writer = new StringWriter();
    writer.write(QUERY_ERROR_HEAD);
    writer.write("<p class=\"path\"><span class=\"high\">Path</span>: ");
    writer.write("<a href=\"");
    writer.write(path);
    writer.write("\">");
    writer.write(path);
    writer.write("</a></p>");

    writer.write("<p class=\"errmsg\">");
    writer.write(e.getMessage());
    writer.write("</p>");
    if (query != null) {
        writer.write("<p><span class=\"high\">Query</span>:</p><pre>");
        writer.write(query);
        writer.write("</pre>");
    }
    writer.write("</body></html>");
    return writer.toString();
}

From source file:com.vmware.identity.samlservice.impl.SamlServiceImpl.java

@Override
public String buildPostResponseForm(Response response, String relayState, String where) {
    log.debug("Building HTTP POST response form for relayState :" + relayState + ", destination: " + where
            + ", response:" + response.toString());
    Validate.notNull(where);//  w  ww.  j  av a2  s.c o  m
    Validate.notNull(response);

    StringWriter sw = new StringWriter();
    // We must build our representation to put into the html form
    Marshaller marshaller = org.opensaml.Configuration.getMarshallerFactory().getMarshaller(response);
    org.w3c.dom.Element authDOM;
    try {
        authDOM = marshaller.marshall(response);
    } catch (MarshallingException e) {
        log.debug("Caught exception " + e.toString());
        return null;
    }
    StringWriter rspWrt = new StringWriter();
    XMLHelper.writeNode(authDOM, rspWrt);
    String messageXML = rspWrt.toString();

    try {
        String samlResponseParameter = Shared.encodeBytes(messageXML.getBytes("UTF-8"));
        sw.write("<form method=\"post\" action=\"" + StringEscapeUtils.escapeHtml(where)
                + "\" id=\"SamlPostForm\"> <input type=\"hidden\" name=\"SAMLResponse\" value=\""
                + StringEscapeUtils.escapeHtml(samlResponseParameter) + "\" />");
    } catch (UnsupportedEncodingException e) {
        log.debug("Caught exception " + e.toString());

        return null;
    }

    if (relayState != null) {
        sw.write("<input type=\"hidden\" name=\"RelayState\" value=\""
                + StringEscapeUtils.escapeHtml(relayState) + "\" />");
    }
    sw.write("<input type=\"submit\" value=\"Submit\" style=\"display:none;\" /> </form>");
    String resultForm = sw.toString();

    StringWriter sw2 = new StringWriter();
    sw2.write(
            "<html> <head> <script language=\"JavaScript\" type=\"text/javascript\">function load(){ document.getElementById('SamlPostForm').submit(); }</script> </head> <body onload=\"load()\">");
    sw2.write(resultForm);
    sw2.write("</body></html>");
    String result = sw2.toString();

    return result;
}

From source file:com.bluexml.side.integration.buildHudson.utils.Utils.java

/**
 * Mthode qui retourne le contenu du fichier pass en paramtre
 * //w w  w  . jav  a  2s.c  o m
 * @param f
 *            Le fichier a retourner
 * @return Le contenu du fichier
 */
private static String loadFile(File f) {
    StringWriter out = null;
    try {
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(f));
        out = new StringWriter();
        int b;
        while ((b = in.read()) != -1)
            out.write(b);
        out.flush();
        out.close();
        in.close();
        return out.toString();
    } catch (IOException ie) {
        ie.printStackTrace();
    }
    return out.toString();
}

From source file:edu.harvard.med.iccbl.screensaver.soaputils.PubchemChembankQueryUtility.java

private void query(final Library library, final boolean queryPubchem, final boolean queryChembank,
        final GenericEntityDAO dao, int intervalMs, int numberOfTries, PrintWriter writer,
        PrintWriter errorWriter) throws InterruptedException, FindBySimilarity1Fault1 {
    Set<Well> wells = library.getWells();
    log.info("begin: " + wells.size() + " compounds to look up.");

    StringWriter buf = new StringWriter();
    boolean fail = false;
    String errMsgPC = "";
    String errMsgCB = "";
    long startTime = System.currentTimeMillis();
    int smilesCount = 1;
    int failCount = 0;
    for (Well well : wells) {
        if (hasWellBeenReadAlready(well.getWellId())) {
            log.info("This well has already been read: " + well.getWellId());
            continue;
        } else {//from  w  ww.j a  v  a2 s  . c o m
            if (well.getLibraryWellType().equals(LibraryWellType.EXPERIMENTAL)) {
                long loopTime = System.currentTimeMillis();
                well = dao.reloadEntity(well, true, Well.reagents);
                SmallMoleculeReagent reagent = (SmallMoleculeReagent) well.getReagents()
                        .get(library.getLatestContentsVersion());
                if (reagent == null) {
                    log.warn("Null reagent for well: " + well.getWellId());
                } else {
                    String smiles = reagent.getSmiles();

                    buf.write(well.getWellId());
                    buf.write(DELIMITER);

                    buf.write("" + well.getLibraryWellType());
                    buf.write(DELIMITER);

                    buf.write(smiles);
                    buf.write(DELIMITER);

                    buf.write(Joiner.on(LIST_DELIMITER).join(reagent.getPubchemCids()));
                    buf.write(DELIMITER);

                    if (StringUtils.isEmpty(smiles)) {
                        errMsgPC = "Smiles string is empty";
                        errMsgCB = errMsgPC;
                        fail = true;
                    }

                    if (!fail && queryPubchem) {
                        try {
                            Pair<String, int[]> result = PugSoapUtil.standardizeAndIdentitySearch(smiles,
                                    intervalMs, numberOfTries);
                            buf.write(result.getFirst());
                            buf.write(DELIMITER);

                            List<Integer> cids = Lists.newLinkedList();
                            for (int cid : result.getSecond())
                                cids.add(cid);
                            if (!cids.isEmpty())
                                buf.write(Joiner.on(LIST_DELIMITER).join(cids));
                            buf.write(DELIMITER);

                            smilesCount++;
                        } catch (NonSuccessStatus e) {
                            errMsgPC = e.getMessage();
                            String errMsg = "Non successful lookup: " + "\twell: " + well.getWellId()
                                    + ", SMILES: " + smiles;
                            log.error(errMsg, e);
                            fail = true;
                        } catch (RemoteException e) {
                            errMsgPC = "Lookup Failed: " + e.getClass().getName() + ", msg: "
                                    + e.getLocalizedMessage();
                            String errMsg = "Lookup Failed: _" + "\twell: " + well.getWellId() + ", SMILES: "
                                    + smiles;
                            log.error(errMsg, e);
                            fail = true;
                        }
                    } else {
                        buf.write(DELIMITER);
                        buf.write(DELIMITER);
                    }

                    if (!fail && queryChembank) {
                        try {
                            List<String> chembankIDs = getChembankIdsForSmiles(smiles);
                            if (!chembankIDs.isEmpty())
                                buf.write(Joiner.on(LIST_DELIMITER).join(chembankIDs));
                        } catch (RemoteException e) {
                            errMsgCB = "Lookup Failed: " + e.getClass().getName() + ", msg: "
                                    + e.getLocalizedMessage();
                            String errMsg = "Lookup Failed:" + "\twell: " + well.getWellId() + ", SMILES: "
                                    + smiles;
                            log.error(errMsg, e);
                            fail = true;
                        }
                    } else {
                        // last element does not need a delimiter
                    }

                    if (!fail) {
                        writer.write(buf.toString());
                        writer.println();
                        writer.flush();
                        long currentTime = System.currentTimeMillis();
                        log.info("Well: " + well.getWellId() + ", SMILES: " + smiles + ", Loop time: "
                                + (currentTime - loopTime) + ", avg: " + (currentTime - startTime) / smilesCount
                                + ", cumulative: "
                                + (float) (((double) (currentTime - startTime)) / (double) 60000) + " min");
                    } else {
                        log.warn("Line not written due to errors");
                        errorWriter.write(buf.toString());

                        if (!errMsgPC.isEmpty()) {
                            errorWriter.write(DELIMITER);
                            errorWriter.write(errMsgPC);
                            errMsgPC = "";
                        }
                        if (!errMsgCB.isEmpty()) {
                            errorWriter.write(DELIMITER);
                            errorWriter.write(errMsgCB);
                            errMsgCB = "";
                        }
                        errorWriter.println();
                        errorWriter.flush();
                        if (fail)
                            failCount++;
                        fail = false;
                    }
                    buf = new StringWriter();
                }
            } // experimental
            else {
                log.info("not experimental: " + well.getWellId() + ", " + well.getLibraryWellType());
            }
        }
    } // for wells
    log.info("Finished: Library: " + library.getShortName() + ", failCount: " + failCount);
}

From source file:hudson.plugins.sshslaves.SSHLauncher.java

/**
 * Given the output of "java -version" in <code>r</code>, determine if this
 * version of Java is supported. This method has default visiblity for testing.
 *
 * @param logger/* w w  w .ja v  a2  s . co  m*/
 *            where to log the output
 * @param javaCommand
 *            the command executed, used for logging
 * @param r
 *            the output of "java -version"
 * @param output
 *            copy the data from <code>r</code> into this output buffer
 */
@CheckForNull
protected String checkJavaVersion(final PrintStream logger, String javaCommand, final BufferedReader r,
        final StringWriter output) throws IOException {
    String line;
    while (null != (line = r.readLine())) {
        output.write(line);
        output.write("\n");
        line = line.toLowerCase(Locale.ENGLISH);
        if (line.startsWith("java version \"") || line.startsWith("openjdk version \"")) {
            final String versionStr = line.substring(line.indexOf('\"') + 1, line.lastIndexOf('\"'));
            logger.println(Messages.SSHLauncher_JavaVersionResult(getTimestamp(), javaCommand, versionStr));

            // parse as a number and we should be OK as all we care about is up through the first dot.
            try {
                final Number version = NumberFormat.getNumberInstance(Locale.US).parse(versionStr);
                if (version.doubleValue() < 1.5) {
                    throw new IOException(Messages.SSHLauncher_NoJavaFound(line));
                }
            } catch (final ParseException e) {
                throw new IOException(Messages.SSHLauncher_NoJavaFound(line));
            }
            return javaCommand;
        }
    }
    return null;
}