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:org.glowroot.local.ui.ErrorJsonService.java

@GET("/backend/error/messages")
String getData(String queryString) throws Exception {
    ErrorMessageRequest request = QueryStrings.decode(queryString, ErrorMessageRequest.class);

    ErrorMessageQuery query = ErrorMessageQuery.builder().transactionType(request.transactionType())
            .transactionName(request.transactionName()).from(request.from()).to(request.to())
            .addAllIncludes(request.includes()).addAllExcludes(request.excludes())
            .limit(request.errorMessageLimit()).build();
    QueryResult<ErrorMessageCount> queryResult = traceDao.readErrorMessageCounts(query);
    List<ErrorPoint> unfilteredErrorPoints = errorCommonService.readErrorPoints(query.transactionType(),
            query.transactionName(), query.from(), query.to());
    DataSeries dataSeries = new DataSeries(null);
    Map<Long, Long[]> dataSeriesExtra = Maps.newHashMap();
    if (query.includes().isEmpty() && query.excludes().isEmpty()) {
        populateDataSeries(query, unfilteredErrorPoints, dataSeries, dataSeriesExtra);
    } else {/*from  ww  w.ja  va2 s .  co  m*/
        Map<Long, Long> transactionCountMap = Maps.newHashMap();
        for (ErrorPoint unfilteredErrorPoint : unfilteredErrorPoints) {
            transactionCountMap.put(unfilteredErrorPoint.captureTime(),
                    unfilteredErrorPoint.transactionCount());
        }
        ImmutableList<TraceErrorPoint> traceErrorPoints = traceDao.readErrorPoints(query,
                getDataPointIntervalMillis(query));
        List<ErrorPoint> errorPoints = Lists.newArrayList();
        for (TraceErrorPoint traceErrorPoint : traceErrorPoints) {
            Long transactionCount = transactionCountMap.get(traceErrorPoint.captureTime());
            if (transactionCount != null) {
                errorPoints.add(ErrorPoint.of(traceErrorPoint.captureTime(), traceErrorPoint.errorCount(),
                        transactionCount));
            }
        }
        populateDataSeries(query, errorPoints, dataSeries, dataSeriesExtra);
    }

    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    jg.writeStartObject();
    jg.writeObjectField("dataSeries", dataSeries);
    jg.writeObjectField("dataSeriesExtra", dataSeriesExtra);
    jg.writeFieldName("errorMessages");
    jg.writeObject(queryResult.records());
    jg.writeBooleanField("moreErrorMessagesAvailable", queryResult.moreAvailable());
    jg.writeEndObject();
    jg.close();
    return sb.toString();
}

From source file:org.glowroot.ui.GaugeValueJsonService.java

@GET(path = "/backend/jvm/gauges", permission = "agent:jvm:gauges")
String getGaugeValues(@BindAgentRollupId String agentRollupId, @BindRequest GaugeValueRequest request)
        throws Exception {
    int rollupLevel = rollupLevelService.getGaugeRollupLevelForView(request.from(), request.to(),
            agentRollupId.endsWith("::"));
    long dataPointIntervalMillis;
    if (rollupLevel == 0) {
        dataPointIntervalMillis = configRepository.getGaugeCollectionIntervalMillis();
    } else {/*  ww w.  ja  v  a 2s .  c om*/
        dataPointIntervalMillis = configRepository.getRollupConfigs().get(rollupLevel - 1).intervalMillis();
    }
    Map<String, List<GaugeValue>> origGaugeValues = getGaugeValues(agentRollupId, request, rollupLevel,
            dataPointIntervalMillis);
    Map<String, List<GaugeValue>> gaugeValues = origGaugeValues;
    if (isEmpty(gaugeValues) && noHarmFallingBackToLargestAggregate(agentRollupId, rollupLevel, request)) {
        // fall back to largest aggregates in case expiration settings have recently changed
        rollupLevel = getLargestRollupLevel();
        dataPointIntervalMillis = configRepository.getRollupConfigs().get(rollupLevel - 1).intervalMillis();
        gaugeValues = getGaugeValues(agentRollupId, request, rollupLevel, dataPointIntervalMillis);
        long lastCaptureTime = 0;
        for (List<GaugeValue> list : gaugeValues.values()) {
            if (!list.isEmpty()) {
                lastCaptureTime = Math.max(lastCaptureTime, Iterables.getLast(list).getCaptureTime());
            }
        }
        if (lastCaptureTime != 0 && ignoreFallBackData(request, lastCaptureTime)) {
            // this is probably data from before the requested time period
            // (go back to empty gauge values)
            gaugeValues = origGaugeValues;
        }
    }
    if (rollupLevel != 0) {
        syncManualRollupCaptureTimes(gaugeValues, rollupLevel);
    }
    double gapMillis = dataPointIntervalMillis * 1.5;
    List<DataSeries> dataSeriesList = Lists.newArrayList();
    for (Map.Entry<String, List<GaugeValue>> entry : gaugeValues.entrySet()) {
        dataSeriesList.add(convertToDataSeriesWithGaps(entry.getKey(), entry.getValue(), gapMillis));
    }
    List<Gauge> gauges = gaugeValueRepository.getGauges(agentRollupId, request.from(), request.to());
    List<Gauge> sortedGauges = new GaugeOrdering().immutableSortedCopy(gauges);
    sortedGauges = addCounterSuffixesIfAndWhereNeeded(sortedGauges);
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    try {
        jg.writeStartObject();
        jg.writeObjectField("dataSeries", dataSeriesList);
        jg.writeNumberField("dataPointIntervalMillis", dataPointIntervalMillis);
        jg.writeObjectField("allGauges", sortedGauges);
        jg.writeEndObject();
    } finally {
        jg.close();
    }
    return sb.toString();
}

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

private static @Nullable String writeExceptionAsString(@Nullable ThrowableInfo exception) throws IOException {
    if (exception == null) {
        return null;
    }/*from www.  j a v  a  2s.co  m*/
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = jsonFactory.createGenerator(CharStreams.asWriter(sb));
    EntriesCharSourceCreator.writeThrowable(exception, jg);
    jg.close();
    return sb.toString();
}

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

/**
 * Converts XML object into a String./*w  w  w  . j  a va 2  s.  co  m*/
 *
 * @param xml Object (e.g., DOM {@link Node})
 * @return String representation of {@code xml} or empty on error.
 */
@Beta
public static String toString(Object xml) {
    TransformerFactory tf = TransformerFactory.newInstance();
    try {
        Transformer t = tf.newTransformer();
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        Source xmlSource = null;
        if (xml instanceof Node) {
            xmlSource = new DOMSource((Node) xml);
        } else if (xml instanceof XMLEventReader) {
            xmlSource = new StAXSource((XMLEventReader) xml);
        } else if (xml instanceof XMLStreamReader) {
            xmlSource = new StAXSource((XMLStreamReader) xml);
        } else {
            log.warn("Unknown XML object type: {}, {}", xml.getClass(), xml);
            return "";
        }

        StringBuilder sb = new StringBuilder();
        t.transform(xmlSource, new StreamResult(CharStreams.asWriter(sb)));
        return sb.toString();
    } catch (TransformerException | XMLStreamException e) {
        log.error("Exception thrown", e);
        return "";
    }
}

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

private static @Nullable String writeTimersAsString(TimerImpl rootTimer) throws IOException {
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = jsonFactory.createGenerator(CharStreams.asWriter(sb));
    rootTimer.writeValue(jg);/*  ww w  .  j  a va2 s.  c o  m*/
    jg.close();
    return sb.toString();
}

From source file:org.glowroot.ui.JvmJsonService.java

@GET(path = "/backend/jvm/environment", permission = "agent:jvm:environment")
String getEnvironment(@BindAgentId String agentId) throws Exception {
    Environment environment = environmentRepository.read(agentId);
    if (environment == null) {
        return "{}";
    }//from   w  w  w . j  a v a2s.co m
    HostInfo hostInfo = environment.getHostInfo();
    ProcessInfo processInfo = environment.getProcessInfo();
    JavaInfo javaInfo = environment.getJavaInfo();
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    try {
        jg.writeStartObject();
        Long hostCurrentTime = null;
        if (liveJvmService != null) {
            jg.writeBooleanField("agentNotConnected", !liveJvmService.isAvailable(agentId));
            try {
                hostCurrentTime = liveJvmService.getCurrentTime(agentId);
            } catch (AgentNotConnectedException e) {
                logger.debug(e.getMessage(), e);
            } catch (AgentUnsupportedOperationException e) {
                // this operation introduced in 0.13.0
                logger.debug(e.getMessage(), e);
            }
        }
        jg.writeObjectFieldStart("host");
        jg.writeStringField("hostname", hostInfo.getHostname());
        jg.writeNumberField("availableProcessors", hostInfo.getAvailableProcessors());
        if (hostInfo.hasTotalPhysicalMemoryBytes()) {
            jg.writeNumberField("totalPhysicalMemoryBytes", hostInfo.getTotalPhysicalMemoryBytes().getValue());
        }
        jg.writeStringField("osName", hostInfo.getOsName());
        jg.writeStringField("osVersion", hostInfo.getOsVersion());
        if (hostCurrentTime != null) {
            jg.writeNumberField("currentTime", hostCurrentTime);
        }
        jg.writeEndObject();
        jg.writeObjectFieldStart("process");
        if (processInfo.hasProcessId()) {
            jg.writeNumberField("processId", processInfo.getProcessId().getValue());
        }
        jg.writeNumberField("startTime", processInfo.getStartTime());
        jg.writeEndObject();
        jg.writeObjectFieldStart("java");
        jg.writeStringField("version", javaInfo.getVersion());
        jg.writeStringField("vm", javaInfo.getVm());
        jg.writeArrayFieldStart("args");
        // mask JVM args here in case maskSystemProperties was modified after the environment
        // data was captured JVM startup
        // (this also provides support in central for agent prior to 0.10.0)
        for (String arg : Masking.maskJvmArgs(javaInfo.getArgList(), getJvmMaskSystemProperties(agentId))) {
            jg.writeString(arg);
        }
        jg.writeEndArray();
        jg.writeStringField("glowrootAgentVersion", javaInfo.getGlowrootAgentVersion());
        jg.writeEndObject();
        jg.writeEndObject();
    } finally {
        jg.close();
    }
    return sb.toString();
}

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

private String getTimersJson() throws IOException {
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = jsonFactory.createGenerator(CharStreams.asWriter(sb));
    writeTimer(jg, syntheticRootTimer);//from w ww  . j av  a2 s.co  m
    jg.close();
    return sb.toString();
}

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

@GET("/backend/error/summaries")
String getSummaries(String queryString) throws Exception {
    ErrorSummaryRequest request = QueryStrings.decode(queryString, ErrorSummaryRequest.class);

    ErrorSummary overallSummary = errorCommonService.readOverallErrorSummary(request.transactionType(),
            request.from() + 1, request.to());

    ErrorSummaryQuery query = ErrorSummaryQuery.builder().transactionType(request.transactionType())
            .from(request.from() + 1).to(request.to()).sortOrder(request.sortOrder()).limit(request.limit())
            .build();//from w w w  .  j  a  v  a 2 s  .  c o  m
    QueryResult<ErrorSummary> queryResult = errorCommonService.readTransactionErrorSummaries(query);

    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    jg.writeStartObject();
    jg.writeFieldName("overall");
    jg.writeObject(overallSummary);
    jg.writeFieldName("transactions");
    jg.writeObject(queryResult.records());
    jg.writeBooleanField("moreAvailable", queryResult.moreAvailable());
    jg.writeEndObject();
    jg.close();
    return sb.toString();
}

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

@GET("/backend/transaction/metrics")
String getMetrics(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 = getDataSeriesForMetricsChart(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());
    }//ww  w. j a v a  2  s  . c  om
    TimerMergedAggregate timerMergedAggregate = AggregateMerging.getTimerMergedAggregate(aggregates);
    ThreadInfoAggregate threadInfoAggregate = AggregateMerging.getThreadInfoAggregate(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", timerMergedAggregate);
    if (!threadInfoAggregate.isEmpty()) {
        jg.writeObjectField("threadInfoAggregate", threadInfoAggregate);
    }
    jg.writeEndObject();
    jg.close();
    return sb.toString();
}

From source file:org.glowroot.ui.SyntheticResultJsonService.java

@GET(path = "/backend/synthetic-monitor/results", permission = "agent:syntheticMonitor")
String getSyntheticResults(@BindAgentRollupId String agentRollupId, @BindRequest SyntheticResultRequest request)
        throws Exception {
    int rollupLevel = rollupLevelService.getRollupLevelForView(request.from(), request.to(), DataKind.GENERAL);
    long dataPointIntervalMillis = configRepository.getRollupConfigs().get(rollupLevel).intervalMillis();
    double gapMillis = dataPointIntervalMillis * 1.5;
    long revisedFrom = request.from() - dataPointIntervalMillis;
    long revisedTo = request.to() + dataPointIntervalMillis;

    List<SyntheticMonitor> allSyntheticMonitors = getAllSyntheticMonitors(agentRollupId, request.from(),
            request.to());/*from w  ww  .  ja va  2 s. c  om*/
    List<String> syntheticMonitorIds;
    if (request.all()) {
        syntheticMonitorIds = Lists.newArrayList();
        for (SyntheticMonitor syntheticMonitor : allSyntheticMonitors) {
            syntheticMonitorIds.add(syntheticMonitor.id());
        }
    } else {
        syntheticMonitorIds = request.syntheticMonitorId();
    }
    Map<String, List<SyntheticResult>> map = Maps.newLinkedHashMap();
    for (String syntheticMonitorId : syntheticMonitorIds) {
        map.put(syntheticMonitorId,
                getSyntheticResults(agentRollupId, revisedFrom, revisedTo, syntheticMonitorId, rollupLevel));
    }
    if (rollupLevel != 0) {
        syncManualRollupCaptureTimes(map, rollupLevel);
    }
    List<DataSeries> dataSeriesList = Lists.newArrayList();
    List<Map<Long, Long>> executionCountsList = Lists.newArrayList();
    List<List<MultiErrorInterval>> multiErrorIntervalsList = Lists.newArrayList();
    for (Map.Entry<String, List<SyntheticResult>> entry : map.entrySet()) {
        String syntheticMonitorId = entry.getKey();
        List<SyntheticResult> syntheticResults = entry.getValue();
        dataSeriesList.add(convertToDataSeriesWithGaps(syntheticMonitorId, syntheticResults, gapMillis));
        Map<Long, Long> executionCounts = Maps.newHashMap();
        executionCountsList.add(executionCounts);
        for (SyntheticResult syntheticResult : syntheticResults) {
            executionCounts.put(syntheticResult.captureTime(), syntheticResult.executionCount());
        }
        ErrorIntervalCollector errorIntervalCollector = new ErrorIntervalCollector();
        for (SyntheticResult syntheticResult : syntheticResults) {
            List<ErrorInterval> errorIntervals = syntheticResult.errorIntervals();
            if (errorIntervals.isEmpty()) {
                errorIntervalCollector.addGap();
            } else {
                errorIntervalCollector.addErrorIntervals(errorIntervals);
            }
        }
        MultiErrorIntervalCollector multiErrorIntervalCollector = new MultiErrorIntervalCollector();
        multiErrorIntervalCollector.addErrorIntervals(errorIntervalCollector.getMergedErrorIntervals());
        multiErrorIntervalsList.add(multiErrorIntervalCollector.getMergedMultiErrorIntervals());
    }
    List<ChartMarking> markings = toChartMarkings(multiErrorIntervalsList, syntheticMonitorIds);
    boolean displayNoSyntheticMonitorsConfigured;
    if (allSyntheticMonitors.isEmpty()) {
        displayNoSyntheticMonitorsConfigured = configRepository.getSyntheticMonitorConfigs(agentRollupId)
                .isEmpty();
    } else {
        displayNoSyntheticMonitorsConfigured = false;
    }
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    try {
        jg.writeStartObject();
        jg.writeObjectField("dataSeries", dataSeriesList);
        jg.writeNumberField("dataPointIntervalMillis", dataPointIntervalMillis);
        jg.writeObjectField("executionCounts", executionCountsList);
        jg.writeObjectField("markings", markings);
        jg.writeObjectField("allSyntheticMonitors", allSyntheticMonitors);
        jg.writeBooleanField("displayNoSyntheticMonitorsConfigured", displayNoSyntheticMonitorsConfigured);
        jg.writeEndObject();
    } finally {
        jg.close();
    }
    return sb.toString();
}