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

@POST(path = "/backend/jvm/heap-dump", permission = "agent:jvm:heapDump")
String heapDump(@BindAgentId String agentId, @BindRequest HeapDumpRequest request) throws Exception {
    checkNotNull(liveJvmService);//from  w  ww. j a va2 s. c o m
    HeapDumpFileInfo heapDumpFileInfo;
    try {
        heapDumpFileInfo = liveJvmService.heapDump(agentId, request.directory());
    } catch (DirectoryDoesNotExistException e) {
        logger.debug(e.getMessage(), e);
        return "{\"directoryDoesNotExist\": true}";
    }
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    try {
        jg.writeStartObject();
        jg.writeStringField("filePath", heapDumpFileInfo.getFilePath());
        jg.writeNumberField("fileSizeBytes", heapDumpFileInfo.getFileSizeBytes());
        jg.writeEndObject();
    } finally {
        jg.close();
    }
    return sb.toString();
}

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

@GET("/backend/jvm/process-info")
String getProcess() throws Exception {
    String command = System.getProperty("sun.java.command");
    String mainClass = null;/*w ww .j  a v  a 2  s  .  c o  m*/
    List<String> arguments = ImmutableList.of();
    if (command != null) {
        int index = command.indexOf(' ');
        if (index > 0) {
            mainClass = command.substring(0, index);
            arguments = Lists.newArrayList(Splitter.on(' ').split(command.substring(index + 1)));
        }
    }
    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    String jvm = StandardSystemProperty.JAVA_VM_NAME.value() + " ("
            + StandardSystemProperty.JAVA_VM_VERSION.value() + ", " + System.getProperty("java.vm.info") + ")";
    String java = "version " + StandardSystemProperty.JAVA_VERSION.value() + ", vendor "
            + StandardSystemProperty.JAVA_VM_VENDOR.value();
    String javaHome = StandardSystemProperty.JAVA_HOME.value();

    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    jg.writeStartObject();
    jg.writeNumberField("startTime", runtimeMXBean.getStartTime());
    jg.writeNumberField("uptime", runtimeMXBean.getUptime());
    jg.writeStringField("pid", MoreObjects.firstNonNull(processId, "<unknown>"));
    jg.writeStringField("mainClass", mainClass);
    jg.writeFieldName("mainClassArguments");
    mapper.writeValue(jg, arguments);
    jg.writeStringField("jvm", jvm);
    jg.writeStringField("java", java);
    jg.writeStringField("javaHome", javaHome);
    jg.writeFieldName("jvmArguments");
    mapper.writeValue(jg, runtimeMXBean.getInputArguments());
    jg.writeEndObject();
    jg.close();
    return sb.toString();
}

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

@VisibleForTesting
static @Nullable String queriesToJson(List<Aggregate.Query> queries) throws IOException {
    if (queries.isEmpty()) {
        return null;
    }/*from   w w  w. jav  a2 s . c  o  m*/
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = jsonFactory.createGenerator(CharStreams.asWriter(sb));
    try {
        writeQueries(jg, queries);
    } finally {
        jg.close();
    }
    return sb.toString();
}

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

@GET(path = "/backend/transaction/full-query-text", permission = "agent:transaction:queries")
String getQueryText(@BindAgentRollupId String agentRollupId, @BindRequest FullQueryTextRequest request)
        throws Exception {
    String fullQueryText = transactionCommonService.readFullQueryText(agentRollupId, request.fullTextSha1());
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    try {//from   w  w  w.  java 2 s .  c  o  m
        jg.writeStartObject();
        if (fullQueryText == null) {
            jg.writeBooleanField("expired", true);
        } else {
            jg.writeStringField("fullText", fullQueryText);
        }
        jg.writeEndObject();
    } finally {
        jg.close();
    }
    return sb.toString();
}

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

private static @Nullable String sharedQueryTextsToJson(List<Trace.SharedQueryText> sharedQueryTexts)
        throws IOException {
    if (sharedQueryTexts.isEmpty()) {
        return null;
    }//from w w  w .jav a2 s. co  m
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = jsonFactory.createGenerator(CharStreams.asWriter(sb));
    try {
        writeSharedQueryTexts(jg, sharedQueryTexts);
    } finally {
        jg.close();
    }
    return sb.toString();
}

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

@POST(path = "/backend/jvm/heap-histogram", permission = "agent:jvm:heapHistogram")
String heapHistogram(@BindAgentId String agentId) throws Exception {
    checkNotNull(liveJvmService);/*  ww w.  ja v  a 2  s .c  o  m*/
    HeapHistogram heapHistogram;
    try {
        heapHistogram = liveJvmService.heapHistogram(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 (UnavailableDueToDockerAlpinePidOneException e) {
        logger.debug(e.getMessage(), e);
        return "{\"unavailableDueToDockerAlpinePidOne\":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.writeArrayFieldStart("items");
        long totalBytes = 0;
        long totalCount = 0;
        for (HeapHistogram.ClassInfo classInfo : heapHistogram.getClassInfoList()) {
            jg.writeStartObject();
            jg.writeStringField("className", classInfo.getClassName());
            jg.writeNumberField("bytes", classInfo.getBytes());
            jg.writeNumberField("count", classInfo.getCount());
            jg.writeEndObject();
            totalBytes += classInfo.getBytes();
            totalCount += classInfo.getCount();
        }
        jg.writeEndArray();
        jg.writeNumberField("totalBytes", totalBytes);
        jg.writeNumberField("totalCount", totalCount);
        jg.writeEndObject();
    } finally {
        jg.close();
    }
    return sb.toString();
}

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

@POST(path = "/backend/admin/web", permission = "admin:edit:web")
Object updateWebConfig(@BindRequest String content) throws Exception {
    if (central) {
        CentralWebConfigDto configDto = mapper.readValue(content, ImmutableCentralWebConfigDto.class);
        CentralWebConfig config = configDto.convert();
        try {//from  w w  w.  j a  v a  2  s.c om
            configRepository.updateCentralWebConfig(config, configDto.version());
        } catch (OptimisticLockException e) {
            throw new JsonServiceException(PRECONDITION_FAILED, e);
        }
        return getCentralWebConfig();
    } else {
        checkNotNull(httpServer);
        EmbeddedWebConfigDto configDto = mapper.readValue(content, ImmutableEmbeddedWebConfigDto.class);
        EmbeddedWebConfig config = configDto.convert();
        if (config.https() && !httpServer.getHttps()) {
            // validate certificate and private key exist and are valid
            File certificateFile = getConfFile("ui-cert.pem");
            if (certificateFile == null) {
                return "{\"httpsRequiredFilesDoNotExist\":true}";
            }
            File privateKeyFile = getConfFile("ui-key.pem");
            if (privateKeyFile == null) {
                return "{\"httpsRequiredFilesDoNotExist\":true}";
            }
            try {
                SslContextBuilder.forServer(certificateFile, privateKeyFile);
            } catch (Exception e) {
                logger.debug(e.getMessage(), e);
                StringBuilder sb = new StringBuilder();
                JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
                try {
                    jg.writeStartObject();
                    jg.writeStringField("httpsValidationError", e.getMessage());
                    jg.writeEndObject();
                } finally {
                    jg.close();
                }
                return sb.toString();
            }
        }
        if (webPortReadOnly && config.port() != checkNotNull(httpServer.getPort())) {
            throw new JsonServiceException(BAD_REQUEST, "cannot change port when using -Dglowroot.agent.port");
        }
        try {
            configRepository.updateEmbeddedWebConfig(config, configDto.version());
        } catch (OptimisticLockException e) {
            throw new JsonServiceException(PRECONDITION_FAILED, e);
        }
        return onSuccessfulEmbeddedWebUpdate(config);
    }
}

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

@GET("/backend/jvm/system-properties")
String getSystemProperties() throws IOException {
    Properties properties = System.getProperties();
    // can't use Maps.newTreeMap() because of OpenJDK6 type inference bug
    // see https://code.google.com/p/guava-libraries/issues/detail?id=635
    Map<String, String> sortedProperties = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
    for (Enumeration<?> e = properties.propertyNames(); e.hasMoreElements();) {
        Object obj = e.nextElement();
        if (obj instanceof String) {
            String propertyName = (String) obj;
            String propertyValue = properties.getProperty(propertyName);
            if (propertyValue != null) {
                sortedProperties.put(propertyName, propertyValue);
            }//from w w w  . j  av  a 2s .c  om
        }
    }
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    jg.writeStartArray();
    for (Entry<String, String> entry : sortedProperties.entrySet()) {
        jg.writeStartObject();
        jg.writeStringField("name", entry.getKey());
        jg.writeStringField("value", entry.getValue());
        jg.writeEndObject();
    }
    jg.writeEndArray();
    jg.close();
    return sb.toString();
}

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

@GET("/backend/jvm/capabilities")
String getCapabilities() throws IOException {
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    jg.writeStartObject();/*from  w  ww  .j ava 2 s  .  c o  m*/
    jg.writeFieldName("threadCpuTime");
    mapper.writeValue(jg, getThreadCpuTimeAvailability());
    jg.writeFieldName("threadContentionTime");
    mapper.writeValue(jg, getThreadContentionAvailability());
    jg.writeFieldName("threadAllocatedBytes");
    mapper.writeValue(jg, threadAllocatedBytes.getAvailability());
    jg.writeFieldName("heapDump");
    mapper.writeValue(jg, heapDumps.getAvailability());
    jg.writeEndObject();
    jg.close();
    return sb.toString();
}

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

@GET(path = "/backend/transaction/service-calls", permission = "agent:transaction:serviceCalls")
String getServiceCalls(@BindAgentRollupId String agentRollupId, @BindRequest TransactionDataRequest request)
        throws Exception {
    AggregateQuery query = toQuery(request, DataKind.SERVICE_CALL);
    ServiceCallCollector serviceCallCollector = transactionCommonService.getMergedServiceCalls(agentRollupId,
            query);/* www .  j  a  va2 s .c o m*/
    List<MutableServiceCall> serviceCalls = serviceCallCollector.getSortedAndTruncatedServiceCalls();
    if (serviceCalls.isEmpty() && fallBackToLargestAggregates(query)) {
        // fall back to largest aggregates in case expiration settings have recently changed
        query = withLargestRollupLevel(query);
        serviceCallCollector = transactionCommonService.getMergedServiceCalls(agentRollupId, query);
        serviceCalls = serviceCallCollector.getSortedAndTruncatedServiceCalls();
        if (ignoreFallBackData(query, serviceCallCollector.getLastCaptureTime())) {
            // this is probably data from before the requested time period
            serviceCalls = ImmutableList.of();
        }
    }
    List<ServiceCall> serviceCallList = Lists.newArrayList();
    for (MutableServiceCall loopServiceCall : serviceCalls) {
        serviceCallList.add(ImmutableServiceCall.builder().type(loopServiceCall.getType())
                .text(loopServiceCall.getText()).totalDurationNanos(loopServiceCall.getTotalDurationNanos())
                .executionCount(loopServiceCall.getExecutionCount()).build());
    }
    Collections.sort(serviceCallList, new Comparator<ServiceCall>() {
        @Override
        public int compare(ServiceCall left, ServiceCall right) {
            // sort descending
            return Doubles.compare(right.totalDurationNanos(), left.totalDurationNanos());
        }
    });
    if (serviceCallList.isEmpty() && aggregateRepository.shouldHaveServiceCalls(agentRollupId, query)) {
        return "{\"overwritten\":true}";
    }
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    try {
        jg.writeObject(serviceCallList);
    } finally {
        jg.close();
    }
    return sb.toString();
}