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

@GET("/backend/transaction/flame-graph")
String getFlameGraph(String queryString) throws Exception {
    FlameGraphRequest request = QueryStrings.decode(queryString, FlameGraphRequest.class);
    ProfileNode profile = transactionCommonService.getProfile(request.transactionType(),
            request.transactionName(), request.from(), request.to(), request.truncateLeafPercentage());
    ProfileNode interestingNode = profile;
    while (interestingNode.getChildNodes().size() == 1) {
        interestingNode = interestingNode.getChildNodes().get(0);
    }/*ww w  . j a  va2s  . com*/
    if (interestingNode.getChildNodes().isEmpty()) {
        // only a single branch through entire tree
        interestingNode = profile;
    }
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    jg.writeStartObject();
    jg.writeObjectFieldStart("");
    jg.writeNumberField("svUnique", 0);
    jg.writeNumberField("svTotal", interestingNode.getSampleCount());
    jg.writeObjectFieldStart("svChildren");
    writeFlameGraphNode(interestingNode, jg);
    jg.writeEndObject();
    jg.writeEndObject();
    jg.close();
    return sb.toString();
}

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

@GET(path = "/backend/jvm/jstack", permission = "agent:jvm:threadDump")
String getJstack(@BindAgentId String agentId) throws Exception {
    checkNotNull(liveJvmService);/*from  ww w.j  a  v  a 2 s .  co  m*/
    String jstack;
    try {
        jstack = liveJvmService.getJstack(agentId);
    } catch (AgentNotConnectedException e) {
        logger.debug(e.getMessage(), e);
        return "{\"agentNotConnected\":true}";
    } catch (UnavailableDueToRunningInJreException e) {
        logger.debug(e.getMessage(), e);
        return "{\"unavailableDueToRunningInJre\":true}";
    } catch (UnavailableDueToRunningInJ9JvmException e) {
        logger.debug(e.getMessage(), e);
        return "{\"unavailableDueToRunningInJ9Jvm\":true}";
    } catch (AgentUnsupportedOperationException e) {
        // this operation introduced in 0.9.2
        logger.debug(e.getMessage(), e);
        return getAgentUnsupportedOperationResponse(agentId);
    }
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    try {
        jg.writeStartObject();
        jg.writeStringField("jstack", jstack);
        jg.writeEndObject();
    } finally {
        jg.close();
    }
    return sb.toString();
}

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

@GET(path = "/backend/report", permission = "")
String getReport(final @BindRequest ReportRequest request, @BindAuthentication Authentication authentication)
        throws Exception {
    String metric = request.metric();
    if (metric.startsWith("transaction:")) {
        checkPermissions(request.agentRollupIds(), "agent:transaction:overview", authentication);
    } else if (metric.startsWith("error:")) {
        checkPermissions(request.agentRollupIds(), "agent:error:overview", authentication);
    } else if (metric.startsWith("gauge:")) {
        checkPermissions(request.agentRollupIds(), "agent:jvm:gauges", authentication);
    } else {/*from   www.j a v a 2s .  c  o  m*/
        throw new IllegalStateException("Unexpected metric: " + metric);
    }
    final TimeZone timeZone = TimeZone.getTimeZone(request.timeZoneId());
    FromToPair fromToPair = parseDates(request.fromDate(), request.toDate(), timeZone);
    final Date from = fromToPair.from();
    final Date to = fromToPair.to();

    final RollupCaptureTimeFn rollupCaptureTimeFn = new RollupCaptureTimeFn(request.rollup(), timeZone,
            request.fromDate());

    final double gapMillis;
    switch (request.rollup()) {
    case HOURLY:
        gapMillis = HOURS.toMillis(1) * 1.5;
        break;
    case DAILY:
        gapMillis = DAYS.toMillis(1) * 1.5;
        break;
    case WEEKLY:
        gapMillis = DAYS.toMillis(1) * 7 * 1.5;
        break;
    case MONTHLY:
        gapMillis = DAYS.toMillis(1) * 30 * 1.5;
        break;
    default:
        throw new IllegalStateException("Unexpected rollup: " + request.rollup());
    }

    List<Future<DataSeries>> dataSeriesFutures;
    long dataPointIntervalMillis;
    if (metric.startsWith("transaction:") || metric.startsWith("error:")) {
        int rollupLevel = rollupLevelService.getRollupLevelForReport(from.getTime(), DataKind.GENERAL);
        // level 2 (30 min intervals) is the minimum level needed
        rollupLevel = Math.max(rollupLevel, 2);
        if (rollupLevel == 3) {
            verifyFourHourAggregateTimeZone(timeZone);
        }
        dataSeriesFutures = getTransactionReport(request, timeZone, from, to, rollupLevel, rollupCaptureTimeFn,
                gapMillis);
        dataPointIntervalMillis = configRepository.getRollupConfigs().get(rollupLevel).intervalMillis();
    } else if (metric.startsWith("gauge:")) {
        // level 3 (30 min intervals) is the minimum level needed
        final int rollupLevel = Math.max(rollupLevelService.getGaugeRollupLevelForReport(from.getTime()), 3);
        if (rollupLevel == 4) {
            verifyFourHourAggregateTimeZone(timeZone);
        }
        final String gaugeName = metric.substring("gauge:".length());
        dataSeriesFutures = Lists.newArrayList();
        for (final String agentRollupId : request.agentRollupIds()) {
            dataSeriesFutures.add(executor.submit(new Callable<DataSeries>() {
                @Override
                public DataSeries call() throws Exception {
                    return getDataSeriesForGauge(agentRollupId, gaugeName, from, to, rollupLevel,
                            rollupCaptureTimeFn, request.rollup(), timeZone, gapMillis);
                }
            }));
        }
        if (rollupLevel == 0) {
            dataPointIntervalMillis = configRepository.getGaugeCollectionIntervalMillis();
        } else {
            dataPointIntervalMillis = configRepository.getRollupConfigs().get(rollupLevel - 1).intervalMillis();
        }
    } else {
        throw new IllegalStateException("Unexpected metric: " + metric);
    }
    List<DataSeries> dataSeriesList = Lists.newArrayList();
    for (Future<DataSeries> dataSeriesFuture : dataSeriesFutures) {
        dataSeriesList.add(dataSeriesFuture.get());
    }
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    try {
        jg.writeStartObject();
        jg.writeObjectField("dataSeries", dataSeriesList);
        jg.writeNumberField("dataPointIntervalMillis", dataPointIntervalMillis);
        jg.writeEndObject();
    } finally {
        jg.close();
    }
    return sb.toString();
}

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

private static @Nullable String toJson(@Nullable Entries entries) throws IOException {
    if (entries == null) {
        return null;
    }//from  w w w . jav a  2  s .  com
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = jsonFactory.createGenerator(CharStreams.asWriter(sb));
    try {
        jg.writeStartObject();
        jg.writeFieldName("entries");
        writeEntries(jg, entries.entries());
        jg.writeFieldName("sharedQueryTexts");
        writeSharedQueryTexts(jg, entries.sharedQueryTexts());
        jg.writeEndObject();
    } finally {
        jg.close();
    }
    return sb.toString();
}

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

@GET(path = "/backend/admin/json", permission = "admin:view")
String getAllAdmin() throws Exception {
    Object config;/*from   w  w  w. j  av a2s. com*/
    if (central) {
        config = configRepository.getAllCentralAdminConfig();
    } else {
        config = configRepository.getAllEmbeddedAdminConfig();
    }
    ObjectNode rootNode = mapper.valueToTree(config);
    AllAdminConfigUtil.removePasswords(rootNode);
    ObjectMappers.stripEmptyContainerNodes(rootNode);
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    try {
        jg.setPrettyPrinter(ObjectMappers.getPrettyPrinter());
        jg.writeObject(rootNode);
    } finally {
        jg.close();
    }
    // newline is not required, just a personal preference
    sb.append(ObjectMappers.NEWLINE);
    return sb.toString();
}

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

@GET(path = "/backend/jvm/heap-dump-default-dir", permission = "agent:jvm:heapDump")
String getHeapDumpDefaultDir(@BindAgentId String agentId) throws Exception {
    checkNotNull(liveJvmService);//from  w w  w .  j a va 2  s .c om
    if (!liveJvmService.isAvailable(agentId)) {
        return "{\"agentNotConnected\":true}";
    }
    Environment environment = environmentRepository.read(agentId);
    checkNotNull(environment);
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    try {
        jg.writeStartObject();
        jg.writeStringField("directory", environment.getJavaInfo().getHeapDumpDefaultDir());
        jg.writeEndObject();
    } finally {
        jg.close();
    }
    return sb.toString();
}

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

@POST("/backend/jvm/dump-heap")
String dumpHeap(String content) throws Exception {
    // this command is filtered out of the UI when service is null
    HeapDumps service = checkNotNull(heapDumps.getService(), "Heap dump service is not available: %s",
            heapDumps.getAvailability().getReason());
    RequestWithDirectory request = mapper.readValue(content, RequestWithDirectory.class);
    File dir = new File(request.directory());
    if (!dir.exists()) {
        return "{\"error\": \"Directory doesn't exist\"}";
    }//from www .j ava 2  s  .c o m
    if (!dir.isDirectory()) {
        return "{\"error\": \"Path is not a directory\"}";
    }
    String timestamp = new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date());
    File file = new File(dir, "heap-dump-" + timestamp + ".hprof");
    int i = 1;
    while (file.exists()) {
        // this seems unlikely now that timestamp is included in filename
        i++;
        file = new File(dir, "heap-dump-" + timestamp + "-" + i + ".hprof");
    }
    service.dumpHeap(file.getAbsolutePath());

    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    jg.writeStartObject();
    jg.writeStringField("filename", file.getAbsolutePath());
    jg.writeNumberField("size", file.length());
    jg.writeEndObject();
    jg.close();
    return sb.toString();
}

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

private static @Nullable String toJson(@Nullable Queries queries) throws IOException {
    if (queries == null) {
        return null;
    }//  w  ww .  j av a 2  s.c  om
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = jsonFactory.createGenerator(CharStreams.asWriter(sb));
    try {
        jg.writeStartObject();
        jg.writeFieldName("queries");
        writeQueries(jg, queries.queries());
        jg.writeFieldName("sharedQueryTexts");
        writeSharedQueryTexts(jg, queries.sharedQueryTexts());
        jg.writeEndObject();
    } finally {
        jg.close();
    }
    return sb.toString();
}

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

@VisibleForTesting
static @Nullable String entriesToJson(List<Trace.Entry> entries) throws IOException {
    if (entries.isEmpty()) {
        return null;
    }/*from  www .j a v  a  2  s .com*/
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = jsonFactory.createGenerator(CharStreams.asWriter(sb));
    try {
        writeEntries(jg, entries);
    } finally {
        jg.close();
    }
    return sb.toString();
}

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

@GET(path = "/backend/transaction/queries", permission = "agent:transaction:queries")
String getQueries(@BindAgentRollupId String agentRollupId, @BindRequest TransactionDataRequest request)
        throws Exception {
    AggregateQuery query = toQuery(request, DataKind.QUERY);
    QueryCollector queryCollector = transactionCommonService.getMergedQueries(agentRollupId, query);
    List<MutableQuery> queries = queryCollector.getSortedAndTruncatedQueries();
    if (queries.isEmpty() && fallBackToLargestAggregates(query)) {
        // fall back to largest aggregates in case expiration settings have recently changed
        query = withLargestRollupLevel(query);
        queryCollector = transactionCommonService.getMergedQueries(agentRollupId, query);
        queries = queryCollector.getSortedAndTruncatedQueries();
        if (ignoreFallBackData(query, queryCollector.getLastCaptureTime())) {
            // this is probably data from before the requested time period
            queries = ImmutableList.of();
        }//  ww w.ja va  2 s  .c o  m
    }
    List<Query> queryList = Lists.newArrayList();
    for (MutableQuery loopQuery : queries) {
        queryList.add(ImmutableQuery.builder().queryType(loopQuery.getType())
                .truncatedQueryText(loopQuery.getTruncatedText()).fullQueryTextSha1(loopQuery.getFullTextSha1())
                .totalDurationNanos(loopQuery.getTotalDurationNanos())
                .executionCount(loopQuery.getExecutionCount())
                .totalRows(loopQuery.hasTotalRows() ? loopQuery.getTotalRows() : null).build());
    }
    if (queryList.isEmpty() && aggregateRepository.shouldHaveQueries(agentRollupId, query)) {
        return "{\"overwritten\":true}";
    }
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    try {
        jg.writeObject(queryList);
    } finally {
        jg.close();
    }
    return sb.toString();
}