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.common.model.MutableProfile.java

public String toJson() throws IOException {
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    writeJson(jg);//w  w w. java2  s .c o m
    jg.close();
    return sb.toString();
}

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

@GET(path = "/backend/jvm/thread-dump", permission = "agent:jvm:threadDump")
String getThreadDump(@BindAgentId String agentId) throws Exception {
    checkNotNull(liveJvmService);/*from w  ww .ja  v  a 2 s. c  o  m*/
    ThreadDump threadDump;
    try {
        threadDump = liveJvmService.getThreadDump(agentId);
    } catch (AgentNotConnectedException e) {
        logger.debug(e.getMessage(), e);
        return "{\"agentNotConnected\":true}";
    }
    List<ThreadDump.Thread> allThreads = Lists.newArrayList();
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    try {
        jg.writeStartObject();
        jg.writeArrayFieldStart("transactions");
        List<Transaction> transactions = new TransactionOrderingByTotalTimeDesc()
                .sortedCopy(threadDump.getTransactionList());
        for (ThreadDump.Transaction transaction : transactions) {
            writeTransactionThread(transaction, jg);
            allThreads.addAll(transaction.getThreadList());
        }
        jg.writeEndArray();

        List<ThreadDump.Thread> unmatchedThreads = new ThreadOrderingByStackTraceSizeDesc()
                .sortedCopy(threadDump.getUnmatchedThreadList());
        Multimap<ThreadDump.Thread, ThreadDump.Thread> unmatchedThreadsGroupedByStackTrace = LinkedListMultimap
                .create();
        List<ThreadDump.Thread> glowrootThreads = Lists.newArrayList();
        for (ThreadDump.Thread thread : unmatchedThreads) {
            if (thread.getName().startsWith("Glowroot-")) {
                glowrootThreads.add(thread);
            } else {
                unmatchedThreadsGroupedByStackTrace.put(getGrouping(thread), thread);
            }
            allThreads.add(thread);
        }
        jg.writeArrayFieldStart("unmatchedThreadsByStackTrace");
        for (Map.Entry<ThreadDump.Thread, Collection<ThreadDump.Thread>> entry : unmatchedThreadsGroupedByStackTrace
                .asMap().entrySet()) {
            jg.writeStartArray();
            for (ThreadDump.Thread thread : entry.getValue()) {
                writeThread(thread, jg);
            }
            jg.writeEndArray();
        }
        jg.writeStartArray();
        for (ThreadDump.Thread thread : glowrootThreads) {
            writeThread(thread, jg);
        }
        jg.writeEndArray();
        jg.writeEndArray();

        jg.writeFieldName("threadDumpingThread");
        writeThread(threadDump.getThreadDumpingThread(), jg);
        allThreads.add(threadDump.getThreadDumpingThread());
        writeDeadlockedCycles(allThreads, jg);
        jg.writeEndObject();
    } finally {
        jg.close();
    }
    return sb.toString();
}

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

@GET(path = "/backend/transaction/percentiles", permission = "agent:transaction:overview")
String getPercentiles(@BindAgentRollupId String agentRollupId,
        @BindRequest TransactionPercentileRequest request, @BindAutoRefresh boolean autoRefresh)
        throws Exception {
    AggregateQuery query = toChartQuery(request, DataKind.GENERAL);
    long liveCaptureTime = clock.currentTimeMillis();
    List<PercentileAggregate> percentileAggregates = transactionCommonService
            .getPercentileAggregates(agentRollupId, query, autoRefresh);
    if (percentileAggregates.isEmpty() && fallBackToLargestAggregates(query)) {
        // fall back to largest aggregates in case expiration settings have recently changed
        query = withLargestRollupLevel(query);
        percentileAggregates = transactionCommonService.getPercentileAggregates(agentRollupId, query,
                autoRefresh);//from  w  w w .jav a 2 s. c  o  m
        if (!percentileAggregates.isEmpty()
                && ignoreFallBackData(query, Iterables.getLast(percentileAggregates).captureTime())) {
            // this is probably data from before the requested time period
            percentileAggregates = ImmutableList.of();
        }
    }
    long dataPointIntervalMillis = configRepository.getRollupConfigs().get(query.rollupLevel())
            .intervalMillis();
    PercentileData percentileData = getDataSeriesForPercentileChart(request, percentileAggregates,
            request.percentile(), dataPointIntervalMillis, liveCaptureTime);
    Map<Long, Long> transactionCounts = getTransactionCounts2(percentileAggregates);

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

From source file:org.glowroot.common.model.MutableProfile.java

public String toFlameGraphJson() throws IOException {
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    try {//w w  w  .j a  v  a  2s  .c om
        jg.writeStartObject();
        jg.writeNumberField("totalSampleCount", getSampleCount());
        jg.writeArrayFieldStart("rootNodes");
        int height = 0;
        for (ProfileNode rootNode : rootNodes) {
            if (rootNode.sampleCount > rootNode.ellipsedSampleCount) {
                FlameGraphWriter flameGraphWriter = new FlameGraphWriter(rootNode, jg);
                flameGraphWriter.traverse();
                height = Math.max(height, flameGraphWriter.height);
            }
        }
        jg.writeEndArray();
        jg.writeNumberField("height", height);
        jg.writeEndObject();
    } finally {
        jg.close();
    }
    return sb.toString();
}

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

@GET("/backend/jvm/thread-dump")
String getThreadDump() throws IOException {
    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    ThreadInfo[] threadInfos = threadBean.getThreadInfo(threadBean.getAllThreadIds(), Integer.MAX_VALUE);
    List<ThreadInfo> sortedThreadInfos = threadInfoOrdering.immutableSortedCopy(Arrays.asList(threadInfos));
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    jg.writeStartArray();/*w w w  . j  av  a  2s .com*/
    long currentThreadId = Thread.currentThread().getId();
    for (ThreadInfo threadInfo : sortedThreadInfos) {
        jg.writeStartObject();
        jg.writeStringField("name", threadInfo.getThreadName());
        jg.writeStringField("state", threadInfo.getThreadState().name());
        jg.writeStringField("lockName", threadInfo.getLockName());
        jg.writeArrayFieldStart("stackTrace");
        boolean trimCurrentThreadStack = threadInfo.getThreadId() == currentThreadId;
        for (StackTraceElement stackTraceElement : threadInfo.getStackTrace()) {
            if (trimCurrentThreadStack
                    && !stackTraceElement.getClassName().equals(JvmJsonService.class.getName())) {
                // just cleaning current thread's stack trace a bit to make it more obvious
                // that it is just the current thread
                continue;
            }
            trimCurrentThreadStack = false;
            jg.writeString(stackTraceElement.toString());
        }
        jg.writeEndArray();
        jg.writeEndObject();
    }
    jg.writeEndArray();
    jg.close();
    return sb.toString();
}

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

@GET(path = "/backend/error/summaries", permission = "agent:error:overview")
String getSummaries(@BindAgentRollupId String agentRollupId, @BindRequest ErrorSummaryRequest request,
        @BindAutoRefresh boolean autoRefresh) throws Exception {
    SummaryQuery query = ImmutableSummaryQuery.builder().transactionType(request.transactionType())
            .from(request.from()).to(request.to())
            .rollupLevel(/*  w w  w . jav a  2  s . c o  m*/
                    rollupLevelService.getRollupLevelForView(request.from(), request.to(), DataKind.GENERAL))
            .build();
    OverallErrorSummaryCollector overallErrorSummaryCollector = errorCommonService
            .readOverallErrorSummary(agentRollupId, query, autoRefresh);
    OverallErrorSummary overallSummary = overallErrorSummaryCollector.getOverallErrorSummary();
    if (overallSummary.transactionCount() == 0 && fallBackToLargestAggregates(query)) {
        // fall back to largest aggregates in case expiration settings have recently changed
        query = withLargestRollupLevel(query);
        overallErrorSummaryCollector = errorCommonService.readOverallErrorSummary(agentRollupId, query,
                autoRefresh);
        overallSummary = overallErrorSummaryCollector.getOverallErrorSummary();
        if (ignoreFallBackData(query, overallErrorSummaryCollector.getLastCaptureTime())) {
            // this is probably data from before the requested time period
            overallSummary = ImmutableOverallErrorSummary.builder().errorCount(0).transactionCount(0).build();
        }
    }
    Result<TransactionNameErrorSummary> queryResult = errorCommonService.readTransactionNameErrorSummaries(
            agentRollupId, query, request.sortOrder(), request.limit(), autoRefresh);
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    try {
        jg.writeStartObject();
        jg.writeObjectField("overall", overallSummary);
        jg.writeObjectField("transactions", queryResult.records());
        jg.writeBooleanField("moreAvailable", queryResult.moreAvailable());
        jg.writeEndObject();
    } finally {
        jg.close();
    }
    return sb.toString();
}

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

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

    String transactionName = request.transactionName();
    long profileSampleCount = transactionCommonService.getProfileSampleCount(request.transactionType(),
            transactionName, request.from(), request.to());
    boolean profileExpired = false;
    if (profileSampleCount == 0) {
        profileExpired = transactionCommonService.shouldHaveProfiles(request.transactionType(), transactionName,
                request.from(), request.to());
    }/*from   w w w .j a  va2s.  co m*/
    long traceCount;
    if (transactionName == null) {
        traceCount = traceDao.readOverallCount(request.transactionType(), request.from(), request.to());
    } else {
        traceCount = traceDao.readTransactionCount(request.transactionType(), transactionName, request.from(),
                request.to());
    }
    boolean includeActiveTraces = shouldIncludeActiveTraces(request);
    if (includeActiveTraces) {
        // include active traces, this is mostly for the case where there is just a single very
        // long running active trace and it would be misleading to display Traces (0) on the tab
        for (Transaction transaction : transactionRegistry.getTransactions()) {
            // don't include partially stored traces since those are already counted above
            if (matchesActive(transaction, request) && !transaction.isPartiallyStored()) {
                traceCount++;
            }
        }
    }
    boolean tracesExpired = false;
    if (traceCount == 0) {
        tracesExpired = transactionCommonService.shouldHaveTraces(request.transactionType(), transactionName,
                request.from(), request.to());
    }

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

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

@GET("/backend/jvm/heap-dump-defaults")
String getHeapDumpDefaults() throws Exception {
    String heapDumpPath = getHeapDumpPathFromCommandLine();
    if (Strings.isNullOrEmpty(heapDumpPath)) {
        String javaTempDir = MoreObjects.firstNonNull(StandardSystemProperty.JAVA_IO_TMPDIR.value(), ".");
        heapDumpPath = new File(javaTempDir).getAbsolutePath();
    }//from  w  w  w  .  j a  v  a2  s .c o  m
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    jg.writeStartObject();
    jg.writeStringField("directory", heapDumpPath);
    jg.writeEndObject();
    jg.close();
    return sb.toString();
}

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

@POST(path = "/backend/config/plugins", permission = "agent:config:edit:plugins")
String updatePluginConfig(@BindAgentId String agentId, @BindRequest PluginUpdateRequest request)
        throws Exception {
    String pluginId = request.pluginId();
    if (pluginId.equals("jdbc")) {
        String firstInvalidRegularExpression = getFirstInvalidJdbcPluginRegularExpressions(
                request.properties());//from w  w w  .  ja v  a2s.  c  o m
        if (firstInvalidRegularExpression != null) {
            StringBuilder sb = new StringBuilder();
            JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
            try {
                jg.writeStartObject();
                jg.writeStringField("firstInvalidRegularExpression", firstInvalidRegularExpression);
                jg.writeEndObject();
            } finally {
                jg.close();
            }
            return sb.toString();
        }
    }
    PluginConfig.Builder builder = PluginConfig.newBuilder().setId(pluginId);
    for (PluginPropertyDto prop : request.properties()) {
        builder.addProperty(prop.convert());
    }
    try {
        configRepository.updatePluginConfig(agentId, builder.build(), request.version());
    } catch (OptimisticLockException e) {
        throw new JsonServiceException(PRECONDITION_FAILED, e);
    }
    return getPluginConfigInternal(agentId, pluginId);
}

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

@GET(path = "/backend/transaction/throughput", permission = "agent:transaction:overview")
String getThroughput(@BindAgentRollupId String agentRollupId, @BindRequest TransactionDataRequest request,
        @BindAutoRefresh boolean autoRefresh) throws Exception {
    AggregateQuery query = toChartQuery(request, DataKind.GENERAL);
    long liveCaptureTime = clock.currentTimeMillis();
    List<ThroughputAggregate> throughputAggregates = transactionCommonService
            .getThroughputAggregates(agentRollupId, query, autoRefresh);
    if (throughputAggregates.isEmpty() && fallBackToLargestAggregates(query)) {
        // fall back to largest aggregates in case expiration settings have recently changed
        query = withLargestRollupLevel(query);
        throughputAggregates = transactionCommonService.getThroughputAggregates(agentRollupId, query,
                autoRefresh);/* w  w  w. java2 s. c o m*/
        if (!throughputAggregates.isEmpty()
                && ignoreFallBackData(query, Iterables.getLast(throughputAggregates).captureTime())) {
            // this is probably data from before the requested time period
            throughputAggregates = ImmutableList.of();
        }
    }
    long dataPointIntervalMillis = configRepository.getRollupConfigs().get(query.rollupLevel())
            .intervalMillis();
    List<DataSeries> dataSeriesList = getDataSeriesForThroughputChart(request, throughputAggregates,
            dataPointIntervalMillis, liveCaptureTime);
    // TODO more precise aggregate when from/to not on rollup grid
    long transactionCount = 0;
    for (ThroughputAggregate throughputAggregate : throughputAggregates) {
        long captureTime = throughputAggregate.captureTime();
        if (captureTime > request.from() && captureTime <= request.to()) {
            transactionCount += throughputAggregate.transactionCount();
        }
    }

    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    try {
        jg.writeStartObject();
        jg.writeObjectField("dataSeries", dataSeriesList);
        jg.writeNumberField("dataPointIntervalMillis", dataPointIntervalMillis);
        jg.writeNumberField("transactionCount", transactionCount);
        jg.writeNumberField("transactionsPerMin", 60000.0 * transactionCount / (request.to() - request.from()));
        jg.writeEndObject();
    } finally {
        jg.close();
    }
    return sb.toString();
}