Example usage for com.google.common.io CharStreams asWriter

List of usage examples for com.google.common.io CharStreams asWriter

Introduction

In this page you can find the example usage for com.google.common.io CharStreams asWriter.

Prototype

public static Writer asWriter(Appendable target) 

Source Link

Document

Returns a Writer that sends all output to the given Appendable target.

Usage

From source file:io.takari.maven.plugins.util.PropertiesWriter.java

public static void write(Properties properties, String comment, OutputStream out) throws IOException {
    StringBuilder sb = new StringBuilder();
    properties.store(CharStreams.asWriter(sb), comment);
    write(CharSource.wrap(sb.toString()), comment, out);
}

From source file:org.glowroot.agent.config.PluginDescriptor.java

public static String writeValue(List<PluginDescriptor> pluginDescriptors) throws IOException {
    ObjectMapper mapper = ObjectMappers.create();
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    try {//from w  ww.ja v  a 2s .co m
        jg.setPrettyPrinter(ObjectMappers.getPrettyPrinter());
        jg.writeStartArray();
        for (PluginDescriptor pluginDescriptor : pluginDescriptors) {
            ObjectNode objectNode = mapper.valueToTree(pluginDescriptor);
            ObjectMappers.stripEmptyContainerNodes(objectNode);
            jg.writeTree(objectNode);
        }
        jg.writeEndArray();
    } finally {
        jg.close();
    }
    // newline is not required, just a personal preference
    sb.append(ObjectMappers.NEWLINE);
    return sb.toString();
}

From source file:org.openqa.selenium.json.Json.java

public JsonOutput newOutput(Appendable to) throws UncheckedIOException {
    try {//  ww w . jav  a  2 s. c om
        return new JsonOutput(toJson, GSON.newJsonWriter(CharStreams.asWriter(to)));
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:io.datakernel.cube.api.HttpResultProcessor.java

private String constructResult(List results, Class resultClass, TotalsPlaceholder totals, int count,
        Set<DrillDown> drillDowns, Set<List<String>> chains, List<String> dimensions, List<String> attributes,
        List<String> measures, List<String> sortedBy, Object filterAttributesPlaceholder,
        List<String> filterAttributes, Set<String> fields, Set<String> metadataFields) throws IOException {
    Field[] dimensionFields = new Field[dimensions.size()];
    KeyType[] keyTypes = new KeyType[dimensions.size()];
    for (int i = 0; i < dimensions.size(); ++i) {
        String key = dimensions.get(i);
        dimensionFields[i] = getField(key, resultClass);
        keyTypes[i] = structure.getKeyType(key);
    }/*from  ww  w . j a v  a 2  s .  c  o  m*/

    Field[] attributeFields = new Field[attributes.size()];
    for (int i = 0; i < attributes.size(); ++i) {
        String attribute = attributes.get(i);
        attributeFields[i] = getField(attribute, resultClass);
    }

    Field[] measureFields = new Field[measures.size()];
    FieldType[] fieldTypes = new FieldType[measures.size()];
    for (int i = 0; i < measures.size(); ++i) {
        String field = measures.get(i);
        measureFields[i] = getField(field, resultClass);
        fieldTypes[i] = structure.getFieldType(field);
    }

    StringBuilder sb = new StringBuilder();
    JsonWriter writer = new JsonWriter(CharStreams.asWriter(sb));

    writer.beginObject();
    writeRecords(writer, results, fields, dimensions, attributes, measures, dimensionFields, keyTypes,
            measureFields, fieldTypes, attributeFields, reportingConfiguration);
    writeTotals(writer, totals, measures, structure);

    if (metadataFields == null || !metadataFields.isEmpty()) {
        writeMetadata(writer, metadataFields, dimensions, attributes, measures, filterAttributes,
                filterAttributesPlaceholder, drillDowns, chains, sortedBy);
    }

    writer.name(COUNT_FIELD).value(count);
    writer.endObject();

    return sb.toString();
}

From source file:org.glowroot.agent.config.ConfigFileUtil.java

private static String writeConfigAsString(ObjectNode rootObjectNode, List<String> keyOrder) throws IOException {
    ObjectNode orderedRootObjectNode = getOrderedObjectNode(rootObjectNode, keyOrder);
    ObjectMappers.stripEmptyContainerNodes(orderedRootObjectNode);
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    try {/*w  w  w. j a  va2 s.  co  m*/
        jg.setPrettyPrinter(ObjectMappers.getPrettyPrinter());
        jg.writeTree(orderedRootObjectNode);
    } finally {
        jg.close();
    }
    // newline is not required, just a personal preference
    return sb.toString() + ObjectMappers.NEWLINE;
}

From source file:org.onosproject.netconf.NetconfRpcParserUtil.java

private static NetconfRpcReply parseRpcReplyBody(NetconfRpcReply.Builder builder, XMLStreamReader xsr) {

    try {//from   w  w w  .  j  a  v  a 2s.  co m
        for (; xsr.hasNext(); xsr.next()) {
            if (xsr.isStartElement()) {
                switch (xsr.getName().getLocalPart()) {
                case "ok":
                    try {
                        // skip to end of tag event
                        xsr.getElementText();
                    } catch (XMLStreamException e) {
                        log.warn("Failed parsing ok", e);
                    }
                    // ok should be the only element
                    return builder.buildOk();

                case "rpc-error":
                    try {
                        JAXBContext context = JAXBContext.newInstance(RpcErrorType.class);
                        Unmarshaller unmarshaller = context.createUnmarshaller();
                        JAXBElement<RpcErrorType> error = unmarshaller.unmarshal(xsr, RpcErrorType.class);
                        builder.addError(NetconfRpcError.wrap(error.getValue()));
                    } catch (JAXBException e) {
                        log.warn("Failed parsing rpc-error", e);
                    }
                    break;

                default: // =rpc-response
                    QName qName = xsr.getName();
                    try {
                        TransformerFactory tf = TransformerFactory.newInstance();
                        Transformer t = tf.newTransformer();

                        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                        StringBuilder sb = new StringBuilder();
                        t.transform(new StAXSource(xsr), new StreamResult(CharStreams.asWriter(sb)));
                        builder.addResponses(sb.toString());
                    } catch (TransformerException e) {
                        log.warn("Failed parsing {}", qName, e);
                    }
                    break;
                }
            }
        }
    } catch (XMLStreamException e) {
        log.error("Exception thrown parsing rpc-reply body", e);
    }

    return builder.build();

}

From source file:org.glowroot.local.ui.LayoutService.java

String getNeedsAuthenticationLayout() throws IOException {
    UserInterfaceConfig userInterfaceConfig = configService.getUserInterfaceConfig();
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = jsonFactory.createGenerator(CharStreams.asWriter(sb));
    jg.writeStartObject();/*from   www .j av a2s  . c om*/
    jg.writeBooleanField("needsAuthentication", true);
    jg.writeBooleanField("readOnlyPasswordEnabled", userInterfaceConfig.readOnlyPasswordEnabled());
    jg.writeStringField("footerMessage", "version " + version);
    jg.writeEndObject();
    jg.close();
    return sb.toString();
}

From source file:org.glowroot.collector.TraceCreator.java

private static @Nullable String writeCustomAttributesAsString(ImmutableSetMultimap<String, String> attributes)
        throws IOException {
    if (attributes.isEmpty()) {
        return null;
    }//from   www  .j  av  a 2 s .  c  om
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = jsonFactory.createGenerator(CharStreams.asWriter(sb));
    jg.writeStartObject();
    for (Entry<String, Collection<String>> entry : attributes.asMap().entrySet()) {
        jg.writeArrayFieldStart(entry.getKey());
        for (String value : entry.getValue()) {
            jg.writeString(value);
        }
        jg.writeEndArray();
    }
    jg.writeEndObject();
    jg.close();
    return sb.toString();
}

From source file:org.glowroot.local.ui.TransactionJsonService.java

@GET("/backend/transaction/overview")
String getOverview(String queryString) throws Exception {
    TransactionDataRequest request = QueryStrings.decode(queryString, TransactionDataRequest.class);

    List<Aggregate> aggregates = transactionCommonService.getAggregates(request.transactionType(),
            request.transactionName(), request.from(), request.to());
    List<DataSeries> dataSeriesList = getDataSeriesForOverviewChart(request, aggregates);
    Map<Long, Long> transactionCounts = getTransactionCounts(aggregates);
    if (!aggregates.isEmpty() && aggregates.get(0).captureTime() == request.from()) {
        // the left most aggregate is not really in the requested interval since it is for
        // prior capture times
        aggregates = aggregates.subList(1, aggregates.size());
    }//from  www  .  j  a  va 2 s . c o m
    HistogramMergedAggregate histogramMergedAggregate = AggregateMerging
            .getHistogramMergedAggregate(aggregates);

    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    jg.writeStartObject();
    jg.writeObjectField("dataSeries", dataSeriesList);
    jg.writeObjectField("transactionCounts", transactionCounts);
    jg.writeObjectField("mergedAggregate", histogramMergedAggregate);
    jg.writeEndObject();
    jg.close();
    return sb.toString();
}

From source file:org.glowroot.collector.TraceCreator.java

private static @Nullable String writeCustomDetailAsString(Map<String, ? extends /*@Nullable*/Object> detail)
        throws IOException {
    if (detail == null) {
        return null;
    }//from  ww w. j  av  a  2s  .c  o m
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = jsonFactory.createGenerator(CharStreams.asWriter(sb));
    new DetailMapWriter(jg).write(detail);
    jg.close();
    return sb.toString();
}