Example usage for java.io StringWriter append

List of usage examples for java.io StringWriter append

Introduction

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

Prototype

public StringWriter append(char c) 

Source Link

Document

Appends the specified character to this writer.

Usage

From source file:com.espertech.esper.epl.expression.core.ExprNodeUtility.java

private static ExprValidationException getNamedValidationException(String parameterName, Class[] expected) {
    String expectedType;//from   w  w w .  jav  a  2 s.c  o m
    if (expected.length == 1) {
        expectedType = "a " + JavaClassHelper.getSimpleNameForClass(expected[0]) + "-typed value";
    } else {
        StringWriter buf = new StringWriter();
        buf.append("any of the following types: ");
        String delimiter = "";
        for (Class clazz : expected) {
            buf.append(delimiter);
            buf.append(JavaClassHelper.getSimpleNameForClass(clazz));
            delimiter = ",";
        }
        expectedType = buf.toString();
    }
    String message = "Failed to validate named parameter '" + parameterName
            + "', expected a single expression returning " + expectedType;
    return new ExprValidationException(message);
}

From source file:gate.crowdsource.rest.CrowdFlowerClient.java

/**
 * Create a named entity annotation job on CrowdFlower.
 * // w  w w . j av  a  2  s.  c  o  m
 * @param title the job title
 * @param instructions the instructions
 * @param caption a caption for the answer form, which should include
 *          the entity type to be annotated.
 * @param noEntitiesCaption a caption for the "there are no entities"
 *          checkbox.
 * @return the newly created job ID.
 * @throws IOException
 */
public long createAnnotationJob(String title, String instructions, String caption, String noEntitiesCaption)
        throws IOException {
    log.debug("Creating annotation job");
    log.debug("title: " + title);
    log.debug("instructions: " + instructions);
    log.debug("caption: " + caption);

    // load the CSS that makes highlighting work
    InputStream cssStream = CrowdFlowerClient.class.getResourceAsStream("gate-crowdflower.css");
    String css = null;
    try {
        css = IOUtils.toString(cssStream, "UTF-8");
    } finally {
        cssStream.close();
    }

    // load the JavaScript that toggles the colour of tokens when
    // clicked
    InputStream jsStream = CrowdFlowerClient.class.getResourceAsStream("gate-crowdflower.js");
    String js = null;
    try {
        js = IOUtils.toString(jsStream, "UTF-8");
    } finally {
        jsStream.close();
    }

    // construct the CML
    StringWriter cml = new StringWriter();
    cml.append("<div class=\"gate-snippet\">\n" + "  <cml:checkboxes validates=\"required\" label=\"");
    StringEscapeUtils.escapeXml(cml, caption);
    cml.append("\" name=\"answer\">\n" + "    {% for tok in tokens %}\n"
            + "      <cml:checkbox label=\"{{ tok }}\" value=\"{{ forloop.index0 }}\" />\n"
            + "    {% endfor %}\n" + "  </cml:checkboxes>\n" + "</div>\n" + "{% if detail %}\n"
            + "  <div class=\"well\">{{detail}}</div>\n" + "{% endif %}\n"
            + "<div class=\"gate-no-entities\">\n"
            // TODO work out how to customize the validation error
            // message
            + "  <cml:checkbox name=\"noentities\" label=\"");
    StringEscapeUtils.escapeXml(cml, noEntitiesCaption);
    cml.append(
            "\" value=\"1\"\n" + "      only-if=\"!answer:required\" validates=\"required\"/>\n" + "</div>\n");
    log.debug("cml: " + cml.toString());

    log.debug("POSTing to CrowdFlower");
    JsonElement json = post("/jobs", "job[title]", title, "job[instructions]", instructions, "job[cml]",
            cml.toString(), "job[css]", css, "job[js]", js);
    log.debug("CrowdFlower returned " + json);
    try {
        return json.getAsJsonObject().get("id").getAsLong();
    } catch (Exception e) {
        throw new GateRuntimeException("Failed to create CF job");
    }
}

From source file:nl.knaw.dans.dccd.rest.AbstractProjectResource.java

/**
 * Append location XML/* w ww  .j  a va 2s.c o m*/
 * 
 * @param sw
 *            writer to append to
 * @param dccdSB
 *            search result
 */
protected void appendProjectLocationAsXml(java.io.StringWriter sw, DccdSB dccdSB) {
    if (dccdSB.hasLatLng()) {
        // just append it, no WGS84 or EPSG indications, it's implicit
        sw.append("<location>");
        sw.append(getXMLElementString("lat", dccdSB.getLat().toString()));
        sw.append(getXMLElementString("lng", dccdSB.getLng().toString()));
        sw.append("</location>");
    }
}

From source file:com.redhat.rhn.frontend.taglibs.ListDisplayTagBase.java

protected void renderPanelHeading(JspWriter out) throws IOException {

    StringWriter headFilterContent = new StringWriter();
    StringWriter titleContent = new StringWriter();
    StringWriter headAddons = new StringWriter();

    renderTitle(titleContent);/*from   ww  w  . j  ava  2s  .co  m*/
    if (getPageList().hasFilter()) {
        headFilterContent.append("<div class=\"spacewalk-list-filter\">");
        renderFilterBox(headFilterContent);
        headFilterContent.append("</div>");
    }
    renderHeadExtraAddons(headAddons);

    int headContentLength = headFilterContent.getBuffer().length() + titleContent.getBuffer().length()
            + headAddons.getBuffer().length();

    if (headContentLength > 0) {
        out.println("<div class=\"panel-heading\">");
        out.println(titleContent.toString());
        out.println("<div class=\"spacewalk-list-head-addons\">");
        out.println(headFilterContent.toString());
        out.println("<div class=\"spacewalk-list-head-addons-extra\">");
        out.println(headAddons.toString());
        out.println("</div>");
        out.println("</div>");
        out.println("</div>");
    }
}

From source file:org.maximachess.jdrone.HipChatNotifier.java

public void sendNotification(String text) {

    /* no config? */
    if (roomUrl == null) {
        /* return silently hipchat is not configured */
        return;//from ww  w . j av a  2  s  .co m
    }

    /* generate message */
    StringWriter sw = new StringWriter();
    try (JsonGenerator generator = jsonFactory.createGenerator(sw)) {
        generator.writeStartObject();
        generator.writeStringField("color", "red");
        generator.writeStringField("message", text);
        generator.writeBooleanField("notify", false);
        generator.writeStringField("message_format", "text");
        generator.writeEndObject();
    } catch (IOException e) {
        sw.append(e.getMessage());
    }
    LOGGER.trace("HipChat API Message {}", sw.toString());

    try {
        HttpPost httppost = new HttpPost(roomUrl);
        httppost.setHeader("Content-Type", "application/json");
        httppost.setEntity(new StringEntity(sw.toString()));

        try (CloseableHttpResponse response = httpclient.execute(httppost)) {
            LOGGER.trace("Http POST reponse {}", response.getStatusLine());
        }
    } catch (IOException ex) {
        LOGGER.error(ex);
    }
}

From source file:org.wapama.web.EditorHandler.java

/**
 * Initiate the compression of the environment.
 * @param context//  w ww .j  a  v  a  2s. c om
 * @throws IOException
 */
private void initEnvFiles(ServletContext context) throws IOException {
    // only do it the first time the servlet starts
    try {
        JSONObject obj = new JSONObject(readEnvFiles(context));

        JSONArray array = obj.getJSONArray("files");
        for (int i = 0; i < array.length(); i++) {
            _envFiles.add(array.getString(i));
        }
    } catch (JSONException e) {
        _logger.error("invalid js_files.json");
        _logger.error(e.getMessage(), e);
        throw new RuntimeException("Error initializing the " + "environment of the editor");
    }

    // generate script to setup the languages
    //_envFiles.add("i18n/translation_ja.js");
    if (System.getProperty(DEV) == null) {
        StringWriter sw = new StringWriter();
        for (String file : _envFiles) {
            sw.append("/* ").append(file).append(" */\n");
            InputStream input = new FileInputStream(new File(getServletContext().getRealPath(file)));
            try {
                JavaScriptCompressor compressor = new JavaScriptCompressor(new InputStreamReader(input), null);
                compressor.compress(sw, -1, false, false, false, false);
            } catch (EvaluatorException e) {
                _logger.error(e.getMessage(), e);
            } catch (IOException e) {
                _logger.error(e.getMessage(), e);
            } finally {
                try {
                    input.close();
                } catch (IOException e) {
                }
            }

            sw.append("\n");
        }
        try {
            FileWriter w = new FileWriter(context.getRealPath("jsc/env_combined.js"));
            w.write(sw.toString());
            w.close();
        } catch (IOException e) {
            _logger.error(e.getMessage(), e);
        }
    } else {
        if (_logger.isInfoEnabled()) {
            _logger.info("The diagram editor is running in development mode. "
                    + "Javascript will be served uncompressed");
        }
    }
}

From source file:nl.knaw.dans.dccd.rest.AbstractProjectResource.java

/**
 * Append information anyone is allowed to see
 * The most important project data but not identical to TRiDaS!
 * /*from www. j  av a2  s .co  m*/
 * @param sw
 *            writer to append to
 * @param dccdSB
 *            search result
 */
protected void appendProjectPublicDataAsXml(java.io.StringWriter sw, DccdSB dccdSB) {
    // Note the Fedora pid is our sid, but sometimes called pid anyway;
    // confusing I know
    sw.append(getXMLElementString("sid", dccdSB.getPid()));

    // modified timestamp
    // convert to UTC and format as ISO
    DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
    DateTime dUtc = dccdSB.getAdministrativeStateLastChange().toDateTime(DateTimeZone.UTC);
    //sw.append(getXMLElementString("stateChanged", dccdSB.getAdministrativeStateLastChange().toString()));
    sw.append(getXMLElementString("stateChanged", fmt.print(dUtc)));

    // Not at first only added title, so a client can show something in a
    // user interface,
    // but now we put in (almost) everything from the search results.

    // title
    sw.append(getXMLElementString("title", dccdSB.getTridasProjectTitle()));

    // identifier
    sw.append(getXMLElementString("identifier", dccdSB.getTridasProjectIdentifier()));

    // category, but not std, normal etc.
    sw.append(getXMLElementString("category", dccdSB.getTridasProjectCategory()));

    // investigator
    sw.append(getXMLElementString("investigator", dccdSB.getTridasProjectInvestigator()));

    // lab(s) (combined name, address, but not concatenated...)
    sw.append("<laboratories>");
    for (String lab : dccdSB.getTridasProjectLaboratoryCombined()) {
        sw.append(getXMLElementString("laboratory", lab));
    }
    sw.append("</laboratories>");

    // type(s)
    sw.append("<types>");
    for (String type : dccdSB.getTridasProjectType()) {
        sw.append(getXMLElementString("type", type));
    }
    sw.append("</types>");

    // Note that this goes to another service and is a Performance Penalty
    sw.append(getXMLElementString("ownerOrganizationId", getOwnerOrganizationId(dccdSB)));
    // And this one goes to the data archive... a penalty...
    sw.append(getXMLElementString("language", getProjectlanguage(dccdSB)));
}

From source file:org.apache.tika.gui.TikaGUI.java

private void handleError(String name, Throwable t) {
    StringWriter writer = new StringWriter();
    writer.append("Apache Tika was unable to parse the document\n");
    writer.append("at " + name + ".\n\n");
    writer.append("The full exception stack trace is included below:\n\n");
    t.printStackTrace(new PrintWriter(writer));

    JEditorPane editor = new JEditorPane("text/plain", writer.toString());
    editor.setEditable(false);//from  w w  w  .j  av  a 2s . c om
    editor.setBackground(Color.WHITE);
    editor.setCaretPosition(0);
    editor.setPreferredSize(new Dimension(600, 400));

    JDialog dialog = new JDialog(this, "Apache Tika error");
    dialog.add(new JScrollPane(editor));
    dialog.pack();
    dialog.setVisible(true);
}

From source file:org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.help.HelpManager.java

String reportApropos(String[] words, ScoreDoc[] hits) throws IOException {
    StringWriter w = new StringWriter();
    for (int i = 0; i < Math.min(hits.length, maxSearch); i++) {
        Document hitDoc = indexSearcher.doc(hits[i].doc);
        String name = hitDoc.get("name");
        String signature = getField(hitDoc, "signature");
        String synopsis = getField(hitDoc, "synopsis");
        w.append(name).append(":\n\t").append(synopsis);
        if (!signature.isEmpty()) {
            w.append("\n\t").append(signature);
        }/* ww w.  j  a  v a  2 s .  co m*/
        w.append("\n");
    }
    return w.toString();
}

From source file:org.codice.ddf.spatial.ogc.csw.catalog.transformer.GmdTransformer.java

@Override
public BinaryContent transform(Metacard metacard, Map<String, Serializable> arguments)
        throws CatalogTransformerException {
    StringWriter stringWriter = new StringWriter();
    Boolean omitXmlDec = null;//from   www  .j  av  a  2 s  . c  o m
    if (MapUtils.isNotEmpty(arguments)) {
        omitXmlDec = (Boolean) arguments.get(CswConstants.OMIT_XML_DECLARATION);
    }

    if (omitXmlDec == null || !omitXmlDec) {
        stringWriter.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n");
    }

    PrettyPrintWriter writer = new PrettyPrintWriter(stringWriter, new NoNameCoder());

    MarshallingContext context = new TreeMarshaller(writer, null, null);
    copyArgumentsToContext(context, arguments);

    new GmdConverter().marshal(metacard, writer, context);

    BinaryContent transformedContent;

    ByteArrayInputStream bais = new ByteArrayInputStream(
            stringWriter.toString().getBytes(StandardCharsets.UTF_8));
    transformedContent = new BinaryContentImpl(bais, new MimeType());
    return transformedContent;
}