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:dk.statsbiblioteket.util.Logs.java

protected static void expand(StringWriter writer, List list, int maxLength, int maxDepth, int listLength) {
    writer.append(Integer.toString(listLength));
    if (maxDepth == 0) {
        writer.append("(...)");
        return;/*from   ww w  . jav  a  2  s.  c o  m*/
    }
    int num = listLength <= maxLength + 1 ? list.size() : Math.max(1, maxLength);
    writer.append("(");
    int counter = 0;
    for (Object object : list) {
        expand(writer, object, maxLength, maxDepth - 1);
        if (counter++ < num - 1) {
            writer.append(", ");
        } else {
            break;
        }
    }
    if (num < listLength) {
        writer.append(", ...");
    }
    writer.append(")");
}

From source file:com.espertech.esper.core.deploy.EPLModuleUtil.java

public static Module readInternal(InputStream stream, String resourceName) throws IOException, ParseException {
    BufferedReader br = new BufferedReader(new InputStreamReader(stream));
    StringWriter buffer = new StringWriter();
    String strLine;//  w  ww  .ja  v a 2  s  .c o  m
    while ((strLine = br.readLine()) != null) {
        buffer.append(strLine);
        buffer.append(newline);
    }
    stream.close();

    return parseInternal(buffer.toString(), resourceName);
}

From source file:org.jaggeryjs2.xhr.XMLHttpRequest.java

private static String serializeObjectArray(Object[] obj) {
    StringWriter json = new StringWriter();
    json.append("[");
    boolean first = true;
    for (Object value : obj) {
        if (!first) {
            json.append(", ");
        } else {/*w ww.j a  va 2  s  .c  o  m*/
            first = false;
        }
        json.append(serializeJSON(value));
    }
    json.append("]");
    return json.toString();
}

From source file:org.opf_labs.utils.ProcessRunnerImpl.java

/**
 * Utility Method for reading a stream into a string, for returning
 * /*  w  w w .j  av  a 2s.  c o  m*/
 * @param stream
 *            the string to read.
 * @return A string with the contents of the stream.
 */
private static String getStringContent(final InputStream stream) {
    if (stream == null) {
        return null;
    }
    BufferedInputStream in = new BufferedInputStream(stream, 1000);
    StringWriter sw = new StringWriter(1000);
    int c;
    try {
        while ((c = in.read()) != -1) {
            sw.append((char) c);
        }
        return sw.toString();
    } catch (IOException e) {
        return "Could not transform content of stream to String";
    }

}

From source file:Main.java

public static String nodeListToString(NodeList nodeList) throws TransformerException {
    StringWriter stringWriter = new StringWriter();
    for (int i = 0; i < nodeList.getLength(); ++i) {
        Node node = nodeList.item(i);
        if (node instanceof Element) {
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.transform(new DOMSource(node), new StreamResult(stringWriter));
        } else {/*from  ww  w  .j  av  a  2  s.c o  m*/
            stringWriter.append(node.getTextContent());
        }
    }
    return stringWriter.toString();
}

From source file:org.epics.archiverappliance.utils.ui.GetUrlContent.java

/**
 * Post a list of strings to the remove server as a CSV and return the results as a array of JSONObjects
 * @param url URL//from   w ww .  java  2 s  .  c  o  m
 * @param paramName  &emsp; 
 * @param params a list of strings 
 * @return JSONArray  &emsp; 
 * @throws IOException  &emsp; 
 */
public static JSONArray postStringListAndGetContentAsJSONArray(String url, String paramName,
        LinkedList<String> params) throws IOException {
    StringWriter buf = new StringWriter();
    buf.append(paramName);
    buf.append("=");
    boolean isFirst = true;
    for (String param : params) {
        if (isFirst) {
            isFirst = false;
        } else {
            buf.append(",");
        }
        buf.append(param);
    }

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost postMethod = new HttpPost(url);
    postMethod.addHeader("Content-Type", MimeTypeConstants.APPLICATION_FORM_URLENCODED);
    postMethod.addHeader("Connection", "close"); // https://www.nuxeo.com/blog/using-httpclient-properly-avoid-closewait-tcp-connections/
    StringEntity archiverValues = new StringEntity(buf.toString(), ContentType.APPLICATION_FORM_URLENCODED);
    postMethod.setEntity(archiverValues);
    if (logger.isDebugEnabled()) {
        logger.debug("About to make a POST with " + url);
    }
    HttpResponse response = httpclient.execute(postMethod);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        logger.debug("Obtained a HTTP entity of length " + entity.getContentLength());
        // ArchiverValuesHandler takes over the burden of closing the input stream.
        try (InputStream is = entity.getContent()) {
            JSONArray retval = (JSONArray) JSONValue.parse(new InputStreamReader(is));
            return retval;
        }
    } else {
        throw new IOException("HTTP response did not have an entity associated with it");
    }
}

From source file:com.espertech.esper.event.property.PropertyParser.java

private synchronized static String escapeKeywords(CommonTokenStream tokens) {

    if (keywordCache == null) {
        keywordCache = new HashSet<String>();
        Set<String> keywords = new EsperEPL2GrammarParser(tokens).getKeywords();
        for (String keyword : keywords) {
            if (keyword.charAt(0) == '\'' && keyword.charAt(keyword.length() - 1) == '\'') {
                keywordCache.add(keyword.substring(1, keyword.length() - 1));
            }/*  w  w  w .  ja  v a2  s  .  c  o m*/
        }
    }

    StringWriter writer = new StringWriter();
    for (Object token : tokens.getTokens()) // Call getTokens first before invoking tokens.size! ANTLR problem
    {
        Token t = (Token) token;
        boolean isKeyword = keywordCache.contains(t.getText().toLowerCase());
        if (isKeyword) {
            writer.append('`');
            writer.append(t.getText());
            writer.append('`');
        } else {
            writer.append(t.getText());
        }
    }
    return writer.toString();
}

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

/**
 * Compress a list of js files into one combined string
 * @param a list of js files//from   w  ww. ja  v  a2  s.com
 * @return a string that contains all the compressed data
 * @throws EvaluatorException
 * @throws IOException
 */
private static String compressJS(Collection<IDiagramPlugin> plugins, ServletContext context) {
    StringWriter sw = new StringWriter();
    for (IDiagramPlugin plugin : plugins) {
        sw.append("/* ").append(plugin.getName()).append(" */\n");
        InputStream input = plugin.getContents();
        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");
    }
    return sw.toString();
}

From source file:nl.knaw.dans.dccd.web.search.SearchResultDataConverter.java

private static String getElementXML(final DccdSB dccdSB, final ProjectPermissionLevel effectivelevel) {
    java.io.StringWriter sw = new StringWriter();

    if (ProjectPermissionLevel.ELEMENT.isPermittedBy(effectivelevel)) {
        // element.title, type, taxon
        sw.append(getXMLElementString(NAME_ELEMENT_TITLE, getElementTitleString(dccdSB)));
        sw.append(getXMLElementString(NAME_ELEMENT_TYPE, getElementTypeString(dccdSB)));
        sw.append(getXMLElementString(NAME_ELEMENT_TAXON, getElementTaxonString(dccdSB)));
    } else {/*from   w ww .j a  va 2s.  c o m*/
        // not permitted
        sw.append(getXMLElementString(NAME_ELEMENT_TITLE, VALUE_NOT_PERMITTED));
        sw.append(getXMLElementString(NAME_ELEMENT_TYPE, VALUE_NOT_PERMITTED));
        sw.append(getXMLElementString(NAME_ELEMENT_TAXON, VALUE_NOT_PERMITTED));
    }

    return sw.toString();
}

From source file:com.kenai.redminenb.issue.JournalDisplay.java

public static JournalData buildJournalData(RedmineIssue ri, Journal jd, int index) {
    RedmineRepository repo = ri.getRepository();

    String noteText = jd.getNotes();
    StringWriter writer = new StringWriter();

    if (jd.getDetails() != null && jd.getDetails().size() > 0) {
        writer.append("<ul>");
        for (JournalDetail detail : jd.getDetails()) {
            writer.append("<li>");
            String fieldName = detail.getName();
            String translatedFieldName = fieldName;
            try {
                translatedFieldName = NbBundle.getMessage(JournalDisplay.class, "field." + fieldName);
            } catch (MissingResourceException ex) {
                // Ok, was not translated
            }//from   w  w w .j a va 2 s  . c o m

            String oldValue = detail.getOldValue();
            String newValue = detail.getNewValue();

            switch (fieldName) {
            case "category_id":
                oldValue = formatCategory(repo, ri, oldValue);
                newValue = formatCategory(repo, ri, newValue);
                break;
            case "fixed_version_id":
                oldValue = formatVersion(repo, ri, oldValue);
                newValue = formatVersion(repo, ri, newValue);
                break;
            case "priority_id":
                oldValue = formatPriority(repo, oldValue);
                newValue = formatPriority(repo, newValue);
                break;
            case "status_id":
                oldValue = formatStatus(repo, oldValue);
                newValue = formatStatus(repo, newValue);
                break;
            case "tracker_id":
                oldValue = formatTracker(repo, oldValue);
                newValue = formatTracker(repo, newValue);
                break;
            case "assigned_to_id":
                oldValue = formatUser(repo, ri, oldValue);
                newValue = formatUser(repo, ri, newValue);
                break;
            case "project_id":
                oldValue = formatProject(repo, ri, oldValue);
                newValue = formatProject(repo, ri, newValue);
                break;
            default:
                // Identity (silence findbugs)
                break;
            }

            if ("cf".equals(detail.getProperty())) {
                try {
                    int fieldId = Integer.parseInt(fieldName);
                    CustomFieldDefinition cfd = ri.getRepository().getCustomFieldDefinitionById(fieldId);
                    if (cfd != null) {
                        translatedFieldName = cfd.getName();
                        switch (cfd.getFieldFormat()) {
                        case "user":
                            oldValue = formatUser(repo, ri, oldValue);
                            newValue = formatUser(repo, ri, newValue);
                            break;
                        case "version":
                            oldValue = formatVersion(repo, ri, oldValue);
                            newValue = formatVersion(repo, ri, newValue);
                            break;
                        case "bool":
                            oldValue = formatBool(repo, ri, oldValue);
                            newValue = formatBool(repo, ri, newValue);
                            break;
                        default:
                            // Identity (silence findbugs)
                            break;
                        }
                    } else {
                        translatedFieldName = "Custom field ID " + fieldId;
                    }
                } catch (NumberFormatException ex) {
                }
            }

            Object[] formatParams = new Object[] { escapeHTML(fieldName), escapeHTML(translatedFieldName),
                    escapeHTML(oldValue), escapeHTML(newValue) };

            ResourceBundle rb = NbBundle.getBundle(JournalDisplay.class);

            String key;
            String alternativeKey;

            if ("description".equals(fieldName) || (oldValue == null && newValue == null)) {
                key = detail.getProperty() + ".baseChanged";
                alternativeKey = "attr.baseChanged";
            } else if (oldValue != null && newValue != null) {
                key = detail.getProperty() + ".changed";
                alternativeKey = "attr.changed";
            } else if (oldValue != null) {
                key = detail.getProperty() + ".deleted";
                alternativeKey = "attr.deleted";
            } else {
                key = detail.getProperty() + ".added";
                alternativeKey = "attr.added";
            }

            String info;
            if (!rb.containsKey(key)) {
                info = NbBundle.getMessage(JournalDisplay.class, alternativeKey, formatParams);
            } else {
                info = NbBundle.getMessage(JournalDisplay.class, key, formatParams);
            }

            writer.append(info);
            writer.append("</li>");
        }
        writer.append("</ul>");
    }

    if (StringUtils.isNotBlank(noteText)) {
        writer.append("<div class='note'>");
        TextileUtil.convertToHTML(noteText, writer);
        writer.append("</div>");
    }

    return new JournalData(jd.getId(), index + 1, jd.getUser().getFullName(), jd.getCreatedOn(),
            writer.toString());
}