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.ui.TransactionJsonService.java

@GET(path = "/backend/transaction/average", permission = "agent:transaction:overview")
String getOverview(@BindAgentRollupId String agentRollupId, @BindRequest TransactionDataRequest request,
        @BindAutoRefresh boolean autoRefresh) throws Exception {
    AggregateQuery query = toChartQuery(request, DataKind.GENERAL);
    long liveCaptureTime = clock.currentTimeMillis();
    List<OverviewAggregate> overviewAggregates = transactionCommonService.getOverviewAggregates(agentRollupId,
            query, autoRefresh);/* w  ww .  j  av a2  s  . co m*/
    if (overviewAggregates.isEmpty() && fallBackToLargestAggregates(query)) {
        // fall back to largest aggregates in case expiration settings have recently changed
        query = withLargestRollupLevel(query);
        overviewAggregates = transactionCommonService.getOverviewAggregates(agentRollupId, query, autoRefresh);
        if (!overviewAggregates.isEmpty()
                && ignoreFallBackData(query, Iterables.getLast(overviewAggregates).captureTime())) {
            // this is probably data from before the requested time period
            overviewAggregates = ImmutableList.of();
        }
    }
    long dataPointIntervalMillis = configRepository.getRollupConfigs().get(query.rollupLevel())
            .intervalMillis();
    List<DataSeries> dataSeriesList = getDataSeriesForTimerChart(request, overviewAggregates,
            dataPointIntervalMillis, liveCaptureTime);
    Map<Long, Long> transactionCounts = getTransactionCounts(overviewAggregates);
    // TODO more precise aggregate when from/to not on rollup grid
    List<OverviewAggregate> overviewAggregatesForMerging = Lists.newArrayList();
    for (OverviewAggregate overviewAggregate : overviewAggregates) {
        long captureTime = overviewAggregate.captureTime();
        if (captureTime > request.from() && captureTime <= request.to()) {
            overviewAggregatesForMerging.add(overviewAggregate);
        }
    }
    MergedAggregate mergedAggregate = AggregateMerging.getMergedAggregate(overviewAggregatesForMerging);

    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("transactionCounts", transactionCounts);
        jg.writeObjectField("mergedAggregate", mergedAggregate);
        jg.writeEndObject();
    } finally {
        jg.close();
    }
    return sb.toString();
}

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

private static String buildCompilationErrorResponse(List<String> compilationErrors) throws IOException {
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    try {//from  ww  w.j av a  2  s . c  o  m
        jg.writeStartObject();
        jg.writeArrayFieldStart("javaSourceCompilationErrors");
        for (String compilationError : compilationErrors) {
            jg.writeString(compilationError);
        }
        jg.writeEndArray();
        jg.writeEndObject();
    } finally {
        jg.close();
    }
    return sb.toString();
}

From source file:org.glowroot.config.ConfigFile.java

private static String writeValueAsString(Config config) throws IOException {
    CustomPrettyPrinter prettyPrinter = new CustomPrettyPrinter();
    prettyPrinter.indentArraysWith(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE);
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb))
            .setPrettyPrinter(prettyPrinter);
    jg.writeObject(config);//from w  w w . j  a va  2s. c om
    jg.close();
    // newline is not required, just a personal preference
    return sb.toString() + NEWLINE;
}

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

@GET("/backend/transaction/profile")
String getProfile(String queryString) throws Exception {
    TransactionProfileRequest request = QueryStrings.decode(queryString, TransactionProfileRequest.class);
    ProfileNode profile = transactionCommonService.getProfile(request.transactionType(),
            request.transactionName(), request.from(), request.to(), request.truncateLeafPercentage());
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    jg.writeObject(profile);// ww w  .  j a  v  a 2  s . com
    jg.close();
    return sb.toString();
}

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

@GET("/backend/error/tab-bar-data")
String getTabBarData(String queryString) throws Exception {
    TabBarDataRequest request = QueryStrings.decode(queryString, TabBarDataRequest.class);

    String transactionName = request.transactionName();
    long traceCount;
    if (transactionName == null) {
        traceCount = traceDao.readOverallErrorCount(request.transactionType(), request.from(), request.to());
    } else {// w ww.j  a v  a 2s.  co  m
        traceCount = traceDao.readTransactionErrorCount(request.transactionType(), transactionName,
                request.from(), request.to());
    }
    boolean tracesExpired = false;
    if (traceCount == 0) {
        tracesExpired = transactionCommonService.shouldHaveErrorTraces(request.transactionType(),
                transactionName, request.from(), request.to());
    }

    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    jg.writeStartObject();
    jg.writeNumberField("traceCount", traceCount);
    jg.writeBooleanField("tracesExpired", tracesExpired);
    jg.writeEndObject();
    jg.close();
    return sb.toString();
}

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

@GET(path = "/backend/error/messages", permission = "agent:error:overview")
String getData(@BindAgentRollupId String agentRollupId, @BindRequest ErrorMessageRequest request,
        @BindAutoRefresh boolean autoRefresh) throws Exception {
    TraceQuery query = ImmutableTraceQuery.builder().transactionType(request.transactionType())
            .transactionName(request.transactionName()).from(request.from()).to(request.to()).build();
    AggregateQuery aggregateQuery = ImmutableAggregateQuery.builder().transactionType(request.transactionType())
            .transactionName(request.transactionName()).from(request.from()).to(request.to())
            .rollupLevel(/*from  w  w w .  j  a  v  a  2  s  .  c  om*/
                    rollupLevelService.getRollupLevelForView(request.from(), request.to(), DataKind.GENERAL))
            .build();
    ErrorMessageFilter filter = ImmutableErrorMessageFilter.builder().addAllIncludes(request.include())
            .addAllExcludes(request.exclude()).build();
    long liveCaptureTime = clock.currentTimeMillis();
    List<ThroughputAggregate> throughputAggregates = transactionCommonService
            .getThroughputAggregates(agentRollupId, aggregateQuery, autoRefresh);
    if (throughputAggregates.isEmpty() && fallBackToLargestAggregates(aggregateQuery)) {
        // fall back to largest aggregates in case expiration settings have recently changed
        aggregateQuery = withLargestRollupLevel(aggregateQuery);
        throughputAggregates = transactionCommonService.getThroughputAggregates(agentRollupId, aggregateQuery,
                autoRefresh);
        if (!throughputAggregates.isEmpty()
                && ignoreFallBackData(aggregateQuery, Iterables.getLast(throughputAggregates).captureTime())) {
            // this is probably data from before the requested time period
            throughputAggregates = ImmutableList.of();
        }
    }
    long dataPointIntervalMillis = configRepository.getRollupConfigs().get(aggregateQuery.rollupLevel())
            .intervalMillis();
    DataSeries dataSeries = new DataSeries(null);
    Map<Long, Long[]> dataSeriesExtra = Maps.newHashMap();
    Map<Long, Long> transactionCountMap = Maps.newHashMap();
    for (ThroughputAggregate unfilteredErrorPoint : throughputAggregates) {
        transactionCountMap.put(unfilteredErrorPoint.captureTime(), unfilteredErrorPoint.transactionCount());
    }
    List<ErrorMessageCount> records = Lists.newArrayList();
    boolean moreAvailable = false;
    if (!throughputAggregates.isEmpty()) {
        long maxCaptureTime = Iterables.getLast(throughputAggregates).captureTime();
        ErrorMessageResult result = traceRepository.readErrorMessages(agentRollupId,
                ImmutableTraceQuery.builder().copyFrom(query).to(maxCaptureTime).build(), filter,
                dataPointIntervalMillis, request.errorMessageLimit());
        List<ErrorPoint> errorPoints = Lists.newArrayList();
        for (ErrorMessagePoint traceErrorPoint : result.points()) {
            long captureTime = traceErrorPoint.captureTime();
            if (captureTime > maxCaptureTime) {
                // traceRepository.readErrorMessages() returns capture time on resolutionMillis,
                // while throughputAggregates may return last capture time at a finer rollup
                // level
                captureTime = maxCaptureTime;
            }
            Long transactionCount = transactionCountMap.get(captureTime);
            if (transactionCount != null) {
                errorPoints.add(
                        ImmutableErrorPoint.of(captureTime, traceErrorPoint.errorCount(), transactionCount));
            }
        }
        populateDataSeries(query, errorPoints, dataSeries, dataSeriesExtra, dataPointIntervalMillis,
                liveCaptureTime);
        records = result.counts().records();
        moreAvailable = result.counts().moreAvailable();
    }
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    try {
        jg.writeStartObject();
        jg.writeObjectField("dataSeries", dataSeries);
        jg.writeNumberField("dataPointIntervalMillis", dataPointIntervalMillis);
        jg.writeObjectField("dataSeriesExtra", dataSeriesExtra);
        jg.writeObjectField("errorMessages", records);
        jg.writeBooleanField("moreErrorMessagesAvailable", moreAvailable);
        jg.writeEndObject();
    } finally {
        jg.close();
    }
    return sb.toString();
}

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

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

    TransactionSummary overallSummary = transactionCommonService.readOverallSummary(request.transactionType(),
            request.from() + 1, request.to());

    TransactionSummaryQuery query = TransactionSummaryQuery.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  a2  s  .  com*/
    QueryResult<TransactionSummary> queryResult = transactionCommonService.readTransactionSummaries(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:com.facebook.buck.android.MergeAndroidResourcesStep.java

public static String generateJavaCodeForPackageAndResources(String packageName, SortedSet<Resource> resources) {
    StringBuilder b = new StringBuilder();

    try (PrintWriter writer = new PrintWriter(CharStreams.asWriter(b))) {
        writeJavaCodeForPackageAndResources(writer, packageName, resources);
    } catch (IOException e) {
        // Impossible.
        throw new RuntimeException(e);
    }//from w  w  w  .  ja  v  a  2 s. c  o  m
    return b.toString();
}

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

@GET(path = "/backend/config/json", permission = "agent:config:view")
String getAllConfig(@BindAgentId String agentId) throws Exception {
    AgentConfig config = configRepository.getAllConfig(agentId);
    ObjectNode configRootNode = mapper.valueToTree(AllConfigDto.create(config));
    ObjectMappers.stripEmptyContainerNodes(configRootNode);
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    try {/*  w  w w.  j  ava 2 s  .  c om*/
        jg.setPrettyPrinter(ObjectMappers.getPrettyPrinter());
        jg.writeObject(configRootNode);
    } finally {
        jg.close();
    }
    // newline is not required, just a personal preference
    sb.append(ObjectMappers.NEWLINE);
    return sb.toString();
}

From source file:com.facebook.buck.rules.MergeAndroidResourcesStep.java

public static String generateJavaCodeForPackageAndResources(String packageName, SortedSet<Resource> resources) {
    StringBuilder b = new StringBuilder();
    Closer closer = Closer.create();/*from www .  java  2  s .c  om*/
    PrintWriter writer = closer.register(new PrintWriter(CharStreams.asWriter(b)));
    try {
        writeJavaCodeForPackageAndResources(writer, packageName, resources);
    } catch (IOException e) {
        // Impossible.
        throw new RuntimeException(e);
    } finally {
        try {
            closer.close();
        } catch (IOException e) {
            Throwables.propagate(e);
        }
    }
    return b.toString();
}