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:org.codice.ddf.spatial.ogc.csw.catalog.transformer.AbstractGmdTransformer.java

@Override
public BinaryContent transform(Metacard metacard, Map<String, Serializable> arguments)
        throws CatalogTransformerException {
    StringWriter stringWriter = new StringWriter();
    Boolean omitXmlDec = null;//ww  w  .  j a  v  a 2s .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);

    converterSupplier.get().marshal(metacard, writer, context);

    ByteArrayInputStream bais = new ByteArrayInputStream(
            stringWriter.toString().getBytes(StandardCharsets.UTF_8));

    return new BinaryContentImpl(bais, CswRecordConverter.XML_MIME_TYPE);
}

From source file:jetbrains.exodus.entitystore.Explainer.java

@SuppressWarnings({ "ObjectAllocationInLoop" })
public void log(Object origin) {
    if (origin == null) {
        return;/*from w w  w .ja v a  2s  .  c  om*/
    }
    Map<String, Object> query = queries.get(origin);
    if (query == null || query.get(ITERABLE_ADVANCES) == null) {
        return;
    }
    Object cursorAdvances = query.get(CURSOR_ADVANCES);
    Object cursorAdvancesForFirst = query.get(CURSOR_ADVANCES_FOR_FIRST);
    if (cursorAdvances != null && cursorAdvancesForFirst != null) {
        // not ITERABLE_ADVANCES - 1 because of some advances for the last unsuccessful hasNext
        query.put(AVERAGE_CURSOR_ADVANCES, ((Integer) cursorAdvances - (Integer) cursorAdvancesForFirst) * 1.0
                / (Integer) query.get(ITERABLE_ADVANCES));
    }

    List<Pair<Integer, String>> byType = new ArrayList<>();
    List<Pair<Integer, String>> byHandle = new ArrayList<>();
    Collection<String> toRemove = new HashSet<>();
    for (String parameter : query.keySet()) {
        if (parameter.startsWith(_CURSOR_ADVANCES_BY_TYPE)) {
            toRemove.add(parameter);
            byType.add(new Pair<>((Integer) query.get(parameter), EntityIterableType
                    .valueOf(parameter.substring(_CURSOR_ADVANCES_BY_TYPE.length() + 1)).toString()));
        }
        if (parameter.startsWith(_CURSOR_ADVANCES_BY_HANDLE)) {
            toRemove.add(parameter);
            byHandle.add(new Pair<>((Integer) query.get(parameter),
                    parameter.substring(_CURSOR_ADVANCES_BY_HANDLE.length() + 1)));
        }
    }
    for (String parameter : toRemove) {
        query.remove(parameter);
    }
    Comparator<Pair<Integer, String>> pairComparator = new Comparator<Pair<Integer, String>>() {
        @Override
        public int compare(Pair<Integer, String> p1, Pair<Integer, String> p2) {
            return p2.getFirst().compareTo(p1.getFirst());
        }
    };
    Collections.sort(byType, pairComparator);
    Collections.sort(byHandle, pairComparator);
    StringBuilder advancesByType = new StringBuilder();
    for (Pair<Integer, String> pair : byType) {
        advancesByType.append('\n').append(pair.getSecond()).append(": ").append(pair.getFirst());
    }
    StringBuilder advancesByHandle = new StringBuilder();
    for (Pair<Integer, String> pair : byHandle) {
        advancesByHandle.append('\n').append(pair.getFirst()).append(": ").append(pair.getSecond());
    }
    query.put(CURSOR_ADVANCES_BY_TYPE, advancesByType.toString());
    query.put(CURSOR_ADVANCES_BY_HANDLE, advancesByHandle.toString());

    boolean show = false;
    for (String parameter : PERFORMANCE_PARAMETERS) {
        if (query.get(parameter) == null) {
            continue;
        }
        double value = ((Number) query.get(parameter)).doubleValue();
        Double worst = WORST_VALUES.get(parameter);
        if (worst <= value * 2) {
            show = true;
            WORST_VALUES.put(parameter, Math.max(value, worst));
        }
    }

    if (show) {
        StringWriter stringWriter = new StringWriter();
        stringWriter.append("Explain\n");
        for (Map.Entry<String, Object> entry : query.entrySet()) {
            stringWriter.append(entry.getKey());
            stringWriter.append(": ");
            stringWriter.append(entry.getValue().toString());
            stringWriter.append('\n');
        }
        log.info(stringWriter);
    }

    if (!isExplainForcedForThread()) {
        clean(origin);
    }
}

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

private URI makeSearchURI(String[] words) throws URISyntaxException, UnsupportedEncodingException {
    StringWriter w = new StringWriter();
    for (int i = 1; i < words.length; i++) {
        w.append(words[i]);
        if (i < words.length - 1)
            w.append(" ");
    }/*  w  w  w  .ja v a 2  s  . c  o  m*/
    String encoded = URLEncoder.encode(w.toString(), "UTF-8");
    return new URI("http", "localhost:" + getPort() + "/Search?searchFor=" + encoded, null);
}

From source file:ubc.pavlab.aspiredb.server.util.JSONUtil.java

/**
 * Converts a collection of objects to a json string
 * /*from   w  ww. j a  va  2 s .c  o  m*/
 * @param collection
 * @return
 * @throws JSONException
 */
public String collectionToJson(Collection<?> collection) throws JSONException {
    StringWriter jsonText = new StringWriter();
    jsonText.write("[");

    try {
        Iterator<?> it = collection.iterator();
        while (it.hasNext()) {
            Object obj = it.next();
            String delim = it.hasNext() ? "," : "";
            jsonText.append(new JSONObject(obj).toString() + delim);
        }
        jsonText.append("]");
        jsonText.flush();
    } catch (Exception e) {
        log.error(e.getLocalizedMessage(), e);
        JSONObject json = new JSONObject();
        json.put("success", false);
        json.put("message", e.getLocalizedMessage());
        jsonText.write(json.toString());
        log.info(jsonText);
    }

    try {
        jsonText.close();
    } catch (Exception e) {
        log.error(e.getLocalizedMessage(), e);
        JSONObject json = new JSONObject();
        json.put("success", false);
        json.put("message", e.getLocalizedMessage());
        jsonText.write(json.toString());
        log.info(jsonText);
    }

    return jsonText.toString();
}

From source file:org.dataconservancy.dcs.access.server.BagUploadServlet.java

public void getSIPfile(String bagitEp, String filename, HttpServletResponse resp)
        throws IOException, InvalidXmlException {
    Client client = Client.create();//from   w  w w  .j a v  a2 s  .c  o  m
    System.out.println(bagitEp);
    WebResource webResource = client.resource(bagitEp);

    File file = new File(filename);
    FileDataBodyPart fdp = new FileDataBodyPart("file", file, MediaType.APPLICATION_OCTET_STREAM_TYPE);

    FormDataMultiPart formDataMultiPart = new FormDataMultiPart();

    formDataMultiPart.bodyPart(fdp);

    ClientResponse response = webResource.path("sip").type(MediaType.MULTIPART_FORM_DATA)
            .post(ClientResponse.class, formDataMultiPart);

    if (response.getStatus() == 500) {
        StringWriter writer = new StringWriter();
        IOUtils.copy(response.getEntityInputStream(), writer);
        resp.getWriter().write(writer.toString());
        resp.setStatus(500);
        resp.flushBuffer();
        return;
    }
    String sipPath = System.getProperty("java.io.tmpdir") + "/" + UUID.randomUUID().toString() + "_sip_0.xml";// significance of 0 is limiting

    IOUtils.copy(response.getEntityInputStream(), new FileOutputStream(sipPath));
    ResearchObject sip = new SeadXstreamStaxModelBuilder().buildSip(new FileInputStream(sipPath));

    StringWriter tempWriter = new StringWriter();
    siptoJsonConverter().toXML(toQueryResult(sip), tempWriter);
    tempWriter.append(";" + sipPath);
    resp.getWriter().write(tempWriter.toString());
    //  resp.setHeader("localSipPath", sipPath);
    resp.setStatus(200);
    resp.setContentType("application/json");
    resp.flushBuffer();
}

From source file:com.epimorphics.lda.renderers.common.PropertyPath.java

/**
 * @return A string denoting this path in a form suitable for HTML presentation
 *//*from w w w . j  av  a  2 s  .c  o  m*/
public String toHTMLString() {
    StringWriter buf = new StringWriter();
    boolean first = true;

    for (String segment : segments) {
        buf.append(first ? "" : " &raquo; ");
        buf.append("<code class='rdf-path-segment'>");
        buf.append(tokeniseWords(segment));
        buf.append("</code>");
        first = false;
    }

    return buf.toString();
}

From source file:com.sangupta.shire.tools.ShireBlogImporter.java

/**
 * Append a line with the given prefix and the list of string values that need to be separated
 * by the given character.//from  w  ww. j  ava 2 s.c  om
 * 
 * @param writer to which the text is appended
 * 
 * @param prefix the prefix to append
 * 
 * @param values the list of values that need to be added
 * 
 * @param separator the separator to be used between values
 * 
 */
protected void appendLine(StringWriter writer, String prefix, List<String> values, char separator) {
    writer.append(prefix);
    for (int index = 0; index < values.size(); index++) {
        String value = values.get(index);

        if (index > 0) {
            writer.write(separator);
        }
        writer.write(value);
    }

    writer.append(NEW_LINE);
}

From source file:com.sangupta.shire.tools.ShireBlogImporter.java

/**
 * Append a new line with all the given items
 * /*from  w  w w .  ja  va2s  .  co  m*/
 * @param writer to which the text is appended
 * 
 * @param items all the items that need to be added
 * 
 */
protected void appendLine(StringWriter writer, String... items) {
    for (int index = 0; index < items.length; index++) {
        writer.append(items[index]);
    }
    writer.append(NEW_LINE);
}

From source file:de.rkl.tools.tzconv.TimezoneConverter.java

private void fillFromTemplate(final StringWriter mainAreaWriter, final ZonedDateTime dateTime) {
    final File templateFileObject = applicationModel.templateFile.getValue();
    if (templateFileObject == null) {
        mainAreaWriter.append(formatConvertedDateTimes(dateTime));
    } else {/*from  ww w.  j  a v  a2 s  .  com*/
        try {
            velocityEngine.evaluate(initVelocityContext(dateTime), mainAreaWriter, templateFileObject.getName(),
                    new FileReader(templateFileObject));
        } catch (FileNotFoundException e) {
            final Alert fileNotFoundAlert = new Alert(Alert.AlertType.ERROR);
            fileNotFoundAlert.setHeaderText("Template file not found");
            fileNotFoundAlert.setContentText(String.valueOf(e));
            fileNotFoundAlert.showAndWait();
        }
    }
}

From source file:org.openhab.binding.samsungtv.internal.protocol.RemoteController.java

private String createRegistrationPayload(String ip) throws IOException {
    /*/*from  w  w w .  j av  a 2s  .  com*/
     * Payload starts with 2 bytes: 0x64 and 0x00, then comes 3 strings
     * encoded with base64 algorithm. Every string is preceded by 2-bytes
     * field containing encoded string length.
     * 
     * These three strings are as follow:
     * 
     * remote control device IP, unique ID  value to distinguish
     * controllers, name  it will be displayed as controller name.
     */

    StringWriter w = new StringWriter();
    w.append((char) 0x64);
    w.append((char) 0x00);
    writeBase64String(w, ip);
    writeBase64String(w, uniqueId);
    writeBase64String(w, appName);
    w.flush();
    return w.toString();
}