Example usage for java.io StringWriter getBuffer

List of usage examples for java.io StringWriter getBuffer

Introduction

In this page you can find the example usage for java.io StringWriter getBuffer.

Prototype

public StringBuffer getBuffer() 

Source Link

Document

Return the string buffer itself.

Usage

From source file:com.flipkart.phantom.runtime.impl.spring.web.HystrixMetricsSnapshotController.java

/**
 * Controller for providing the last 10*N seconds metrics snapshot
 * @throws java.io.IOException/*from w  w w .j a v a  2  s. c  o m*/
 * @return json response
 */
@RequestMapping(value = { "/hystrix.snapshot.global" }, method = RequestMethod.GET)
public @ResponseBody String handleRequest(ModelMap model, HttpServletRequest request) throws IOException {
    final JsonFactory jsonFactory = new JsonFactory();
    StringWriter responseJsonString = new StringWriter();
    JsonGenerator responseJson = jsonFactory.createJsonGenerator(responseJsonString);
    responseJson.writeStartObject();

    /* Get the metrics of last duration from Aggregator */
    Map<String, Map<String, Map<String, Long>>> lastOneMinuteMetrics = hystrixMetricsAggregator
            .getMetricsSnapshotReporter().getMetricsLastDuration();
    /* HystrixCommand value is an array of multiple objects; an object for each command */
    responseJson.writeObjectFieldStart("HystrixCommand");

    if (lastOneMinuteMetrics != null && lastOneMinuteMetrics.get("HystrixCommand") != null) {
        for (String commandName : lastOneMinuteMetrics.get("HystrixCommand").keySet()) {
            Map<String, Long> commandMetrics = lastOneMinuteMetrics.get("HystrixCommand").get(commandName);

            String a[] = commandName.split("\\.");
            responseJson.writeObjectFieldStart(commandName);

            responseJson.writeStringField("name", a[1]);
            responseJson.writeStringField("group", a[0]);

            responseJson.writeNumberField("errorCount", commandMetrics.get("errorCount"));
            responseJson.writeNumberField("requestCount", commandMetrics.get("requestCount"));
            if (commandMetrics.get("requestCount") > 0)
                responseJson.writeNumberField("errorPercent",
                        100.0 * commandMetrics.get("errorCount") / commandMetrics.get("requestCount"));
            else
                responseJson.writeNumberField("errorPercent", 0.);

            responseJson.writeNumberField("rollingCountFailure", commandMetrics.get("rollingCountFailure"));
            responseJson.writeNumberField("rollingCountSemaphoreRejected",
                    commandMetrics.get("rollingCountSemaphoreRejected"));
            responseJson.writeNumberField("rollingCountShortCircuited",
                    commandMetrics.get("rollingCountShortCircuited"));
            responseJson.writeNumberField("rollingCountThreadPoolRejected",
                    commandMetrics.get("rollingCountThreadPoolRejected"));
            responseJson.writeNumberField("rollingCountSuccess", commandMetrics.get("rollingCountSuccess"));
            responseJson.writeNumberField("rollingCountTimeout", commandMetrics.get("rollingCountTimeout"));

            responseJson.writeNumberField("latencyTotal_mean", commandMetrics.get("latencyTotal_mean"));
            responseJson.writeObjectFieldStart("latencyTotal");
            responseJson.writeNumberField("0", commandMetrics.get("0"));
            responseJson.writeNumberField("25", commandMetrics.get("25"));
            responseJson.writeNumberField("50", commandMetrics.get("50"));
            responseJson.writeNumberField("75", commandMetrics.get("75"));
            responseJson.writeNumberField("90", commandMetrics.get("90"));
            responseJson.writeNumberField("95", commandMetrics.get("95"));
            responseJson.writeNumberField("99", commandMetrics.get("99"));
            responseJson.writeNumberField("99.5", commandMetrics.get("99.5"));
            responseJson.writeNumberField("100", commandMetrics.get("100"));
            responseJson.writeEndObject();

            responseJson.writeEndObject();
        }
    }
    responseJson.writeEndObject();

    responseJson.writeObjectFieldStart("HystrixThreadPool");
    /* thread pool metrics: an array of multiple objects; an object for each method */

    if (lastOneMinuteMetrics != null && lastOneMinuteMetrics.get("HystrixThreadPool") != null) {
        for (String commandName : lastOneMinuteMetrics.get("HystrixThreadPool").keySet()) {
            responseJson.writeObjectFieldStart(commandName);

            responseJson.writeStringField("name", commandName);

            responseJson.writeNumberField("currentActiveCount",
                    lastOneMinuteMetrics.get("HystrixThreadPool").get(commandName).get("currentActiveCount"));
            responseJson.writeNumberField("currentQueueSize",
                    lastOneMinuteMetrics.get("HystrixThreadPool").get(commandName).get("currentQueueSize"));
            responseJson.writeEndObject();
        }
    }
    responseJson.writeEndObject();

    responseJson.writeEndObject();
    responseJson.close();

    return responseJsonString.getBuffer().toString() + "\n";
}

From source file:hudson.plugins.project_inheritance.projects.InheritanceProject.java

public String renderSVGRelationGraph(int width, int height) {
    SVGTreeRenderer tree = new SVGTreeRenderer(this.getSVGRelationGraph(), width, height);
    Document doc = tree.render();
    try {//from  w  ww.j  a v  a 2s.co  m
        DOMSource source = new DOMSource(doc);
        StringWriter stringWriter = new StringWriter();
        StreamResult result = new StreamResult(stringWriter);
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
        transformer.transform(source, result);
        return stringWriter.getBuffer().toString();
    } catch (TransformerConfigurationException e) {
        e.printStackTrace();
    } catch (TransformerException e) {
        e.printStackTrace();
    }
    return "";
}

From source file:com.silverpeas.form.form.XmlSearchForm.java

/**
 * Prints the HTML layout of the dataRecord using the RecordTemplate to extract labels and extra
 * informations. The value formats may be adapted to a local language. Never throws an Exception
 * but log a silvertrace and writes an empty string when :
 * <UL>// ww  w. j  a  va 2s. c om
 * <LI>a field is unknown by the template.
 * <LI>a field has not the required type.
 * </UL>
 * @param pagesContext
 * @param record
 * @return
 */
@Override
public String toString(PagesContext pagesContext, DataRecord record) {
    SilverTrace.info("form", "XmlSearchForm.toString", "root.MSG_GEN_ENTER_METHOD");
    StringWriter sw = new StringWriter();
    String language = pagesContext.getLanguage();
    PrintWriter out = new PrintWriter(sw, true);

    if (pagesContext.getPrintTitle() && title != null && title.length() > 0) {
        out.println("<table CELLPADDING=0 CELLSPACING=2 BORDER=0 WIDTH=\"98%\" CLASS=intfdcolor>");
        out.println("<tr>");
        out.println("<td CLASS=intfdcolor4 NOWRAP>");
        out.println("<table CELLPADDING=0 CELLSPACING=0 BORDER=0 WIDTH=\"100%\">");
        out.println("<tr>");
        out.println("<td class=\"intfdcolor\" nowrap width=\"100%\">");
        out.println("<img border=\"0\" src=\"" + Util.getIcon("px") + "\" width=5><span class=txtNav>" + title
                + "</span>");
        out.println("</td>");
        out.println("</tr>");
        out.println("</table>");
        out.println("</td>");
        out.println("</tr>");
        out.println("</table>");
    }
    if (fieldTemplates != null && !fieldTemplates.isEmpty()) {
        Iterator<FieldTemplate> itFields = this.fieldTemplates.iterator();
        if (pagesContext.isBorderPrinted()) {
            out.println(
                    "<table width=\"98%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=intfdcolor4>");
            out.println("<tr>");
            out.println("<td nowrap>");
            out.println(
                    "<table border=\"0\" cellspacing=\"0\" cellpadding=\"5\" class=\"contourintfdcolor\" width=\"100%\">");
        } else {
            out.println("<table width=\"98%\" border=\"0\" cellspacing=\"0\" cellpadding=\"5\">");
        }
        out.print("<input TYPE=\"hidden\" NAME=id VALUE=\"");
        out.print(record.getId());
        out.println("\">");
        PagesContext pc = new PagesContext(pagesContext);
        pc.setNbFields(fieldTemplates.size());
        pc.incCurrentFieldIndex(1);

        // calcul lastFieldIndex
        int lastFieldIndex = -1;
        lastFieldIndex += Integer.parseInt(pc.getCurrentFieldIndex());
        FieldDisplayer fieldDisplayer = null;

        while (itFields.hasNext()) {
            FieldTemplate fieldTemplate = itFields.next();
            if (fieldTemplate != null) {
                String fieldType = fieldTemplate.getTypeName();
                String fieldDisplayerName = fieldTemplate.getDisplayerName();
                try {
                    if (!StringUtil.isDefined(fieldDisplayerName)) {
                        fieldDisplayerName = getTypeManager().getDisplayerName(fieldType);
                    }

                    fieldDisplayer = getTypeManager().getDisplayer(fieldType, fieldDisplayerName);
                    if (fieldDisplayer != null) {
                        lastFieldIndex += fieldDisplayer.getNbHtmlObjectsDisplayed(fieldTemplate, pc);
                    }
                } catch (FormException fe) {
                    SilverTrace.error("form", "XmlSearchForm.toString", "form.EXP_UNKNOWN_DISPLAYER", null, fe);
                }
            }
        }
        pc.setLastFieldIndex(lastFieldIndex);

        itFields = this.fieldTemplates.iterator();
        while (itFields.hasNext()) {
            FieldTemplate fieldTemplate = itFields.next();
            if (fieldTemplate != null) {
                String fieldName = fieldTemplate.getFieldName();
                String fieldLabel = fieldTemplate.getLabel(language);
                String fieldType = fieldTemplate.getTypeName();
                String fieldDisplayerName = fieldTemplate.getDisplayerName();
                try {
                    if (!StringUtil.isDefined(fieldDisplayerName)) {
                        fieldDisplayerName = getTypeManager().getDisplayerName(fieldType);
                    }

                    fieldDisplayer = getTypeManager().getDisplayer(fieldType, fieldDisplayerName);
                } catch (FormException fe) {
                    SilverTrace.error("form", "XmlSearchForm.toString", "form.EXP_UNKNOWN_DISPLAYER", null, fe);
                }
                if (fieldDisplayer != null) {
                    out.println("<tr align=center>");
                    if (StringUtil.isDefined(fieldLabel)) {
                        out.println("<td class=\"txtlibform\" align=left width=\"200\">");
                        out.println(fieldLabel);
                        out.println("</td>");
                    }
                    out.println("<td valign=\"baseline\" align=left>");
                    try {
                        fieldDisplayer.display(out, record.getField(fieldName), fieldTemplate, pc);
                    } catch (FormException fe) {
                        SilverTrace.error("form", "XmlSearchForm.toString", "form.EX_CANT_GET_FORM", null, fe);
                    }
                    out.println("</td>");
                    out.println("</tr>");
                    ;
                    pc.incCurrentFieldIndex(fieldDisplayer.getNbHtmlObjectsDisplayed(fieldTemplate, pc));
                }
            }
        }
        if (pagesContext.isBorderPrinted()) {
            out.println("</TABLE>");
            out.println("</TD>");
            out.println("</TR>");
        }
        out.println("</TABLE>");
    }
    return sw.getBuffer().toString();
}

From source file:com.portfolio.data.provider.MysqlAdminProvider.java

@Override
public String getGroupUserList() {
    PreparedStatement st;/* w ww.j a v a 2  s  .c  o m*/
    String sql;
    ResultSet res;
    String retVal = "";

    try {
        sql = "SELECT * FROM group_user";
        st = connection.prepareStatement(sql);
        res = st.executeQuery();

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.newDocument();

        Element groups = document.createElement("group_user");
        document.appendChild(groups);

        while (res.next()) {
            Integer gid = res.getInt(1);
            Integer uid = res.getInt(2);
            Element group = document.createElement("gu");
            group.setAttribute("gid", gid.toString());
            group.setAttribute("uid", uid.toString());

            groups.appendChild(group);
        }

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        StringWriter writer = new StringWriter();
        transformer.transform(new DOMSource(document), new StreamResult(writer));

        retVal = writer.getBuffer().toString().replaceAll("\n|\r", "");
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return retVal;
}

From source file:com.portfolio.data.provider.MysqlAdminProvider.java

@Override
public String getGroupList() {
    PreparedStatement st;/*from  w w  w  .  java 2s  .co m*/
    String sql;
    ResultSet res;
    String retVal = "";

    try {
        sql = "SELECT * FROM group_info";
        st = connection.prepareStatement(sql);
        res = st.executeQuery();

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.newDocument();

        Element groups = document.createElement("groups");
        document.appendChild(groups);

        while (res.next()) {
            Integer gid = res.getInt(1);
            Integer grid = res.getInt(2);
            Integer owner = res.getInt(3);
            String label = res.getString(4);
            Element group = document.createElement("group");
            group.setAttribute("gid", gid.toString());
            group.setAttribute("grid", grid.toString());
            group.setAttribute("owner", owner.toString());
            group.appendChild(document.createTextNode(label));

            groups.appendChild(group);
        }

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        StringWriter writer = new StringWriter();
        transformer.transform(new DOMSource(document), new StreamResult(writer));

        retVal = writer.getBuffer().toString().replaceAll("\n|\r", "");
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return retVal;
}

From source file:com.portfolio.data.provider.MysqlAdminProvider.java

@Override
public String getGroupRightList() {
    PreparedStatement st;/*from w ww. j a  v  a  2s. c o  m*/
    String sql;
    ResultSet res;
    String retVal = "";

    try {
        sql = "SELECT grid, owner, label, change_rights, bin2uuid(portfolio_id) "
                + "FROM group_right_info ORDER BY portfolio_id";
        st = connection.prepareStatement(sql);
        res = st.executeQuery();

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.newDocument();

        Element groups = document.createElement("group_rights");
        document.appendChild(groups);

        String prevPort = "DUMMY";
        Element portNode = null;
        while (res.next()) {
            Integer grid = res.getInt(1);
            Integer owner = res.getInt(2);
            String label = res.getString(3);
            Integer change = res.getInt(4);
            String portfolio = res.getString(5);
            if (portfolio == null)
                portfolio = "";

            if (!prevPort.equals(portfolio)) {
                portNode = document.createElement("portfolio");
                portNode.setAttribute("id", portfolio);
                groups.appendChild(portNode);

                prevPort = portfolio;
            }

            Element group = document.createElement("group");
            group.setAttribute("grid", grid.toString());
            group.setAttribute("owner", owner.toString());
            group.setAttribute("change_rights", change.toString());
            //          group.setAttribute("portfolio", portfolio);
            group.setNodeValue(label);

            portNode.appendChild(group);
        }

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        StringWriter writer = new StringWriter();
        transformer.transform(new DOMSource(document), new StreamResult(writer));

        retVal = writer.getBuffer().toString().replaceAll("\n|\r", "");
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return retVal;
}

From source file:com.portfolio.data.provider.MysqlAdminProvider.java

@Override
public String getRolePortfolio(MimeType mimeType, String portfolioId, int userId) {
    PreparedStatement st;//w ww.jav a2 s  . c o m
    String sql;
    ResultSet res;

    String retVal = "";

    try {
        sql = "SELECT gri.grid, gri.owner, gri.change_rights, bin2uuid(gr.id) AS uuid, gr.RD, gr.WR, gr.DL, gr.SB, gr.AD, gr.types_id, gr.rules_id, gr.notify_roles "
                + "FROM group_right_info gri " + "LEFT JOIN group_rights gr ON gri.grid=gr.grid "
                + "WHERE gri.portfolio_id=uuid2bin(?) " + "ORDER BY gri.grid";
        st = connection.prepareStatement(sql);
        st.setString(1, portfolioId);

        res = st.executeQuery();

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.newDocument();

        Element root = document.createElement("portfolio");
        root.setAttribute("id", portfolioId);
        document.appendChild(root);

        int prevgrid = 0;

        while (res.next()) {
            int grid = res.getInt("grid");
            int owner = res.getInt("owner");
            int change = res.getInt("change_rights");
            Element rights = null;
            if (prevgrid != grid) {
                rights = document.createElement("rights");
                rights.setAttribute("id", Integer.toString(grid));
                rights.setAttribute("owner", Integer.toString(owner));
                rights.setAttribute("change_rights", Integer.toString(change));
                root.appendChild(rights);
                prevgrid = grid;
            }

            String uuid = res.getString("uuid");
            int rd = res.getInt("RD");
            int wr = res.getInt("WR");
            int dl = res.getInt("DL");
            int sb = res.getInt("SB");
            int ad = res.getInt("AD");
            String types_id = res.getString("types_id");
            if (types_id == null)
                types_id = "";
            String rules_id = res.getString("rules_id");
            if (rules_id == null)
                rules_id = "";
            String notify = res.getString("notify_roles");
            if (notify == null)
                notify = "";

            Element right = document.createElement("right");
            right.setAttribute("id", uuid);
            right.setAttribute("RD", Integer.toString(rd));
            right.setAttribute("WR", Integer.toString(wr));
            right.setAttribute("DL", Integer.toString(dl));
            right.setAttribute("SB", Integer.toString(sb));
            right.setAttribute("AD", Integer.toString(ad));
            right.setAttribute("types_id", types_id);
            right.setAttribute("rules_id", rules_id);
            right.setAttribute("notify", notify);

            rights.appendChild(right);

        }

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        StringWriter writer = new StringWriter();
        transformer.transform(new DOMSource(document), new StreamResult(writer));

        retVal = writer.getBuffer().toString().replaceAll("\n|\r", "");

    } catch (Exception e) {

    }

    return retVal;
}

From source file:org.springframework.cloud.netflix.hystrix.amqp.HystrixStreamTask.java

@Scheduled(fixedRateString = "${hystrix.stream.amqp.gatherRate:500}")
public void gatherMetrics() {
    try {/*  ww  w.j  ava2 s . co  m*/
        // command metrics
        Collection<HystrixCommandMetrics> instances = HystrixCommandMetrics.getInstances();
        if (!instances.isEmpty()) {
            log.trace("gathering metrics size: " + instances.size());
        }

        ServiceInstance localService = this.discoveryClient.getLocalServiceInstance();

        for (HystrixCommandMetrics commandMetrics : instances) {
            HystrixCommandKey key = commandMetrics.getCommandKey();
            HystrixCircuitBreaker circuitBreaker = HystrixCircuitBreaker.Factory.getInstance(key);

            StringWriter jsonString = new StringWriter();
            JsonGenerator json = this.jsonFactory.createGenerator(jsonString);

            json.writeStartObject();

            addServiceData(json, localService);
            json.writeObjectFieldStart("data");
            json.writeStringField("type", "HystrixCommand");
            String name = key.name();

            if (this.properties.isPrefixMetricName()) {
                name = localService.getServiceId() + "." + name;
            }

            json.writeStringField("name", name);
            json.writeStringField("group", commandMetrics.getCommandGroup().name());
            json.writeNumberField("currentTime", System.currentTimeMillis());

            // circuit breaker
            if (circuitBreaker == null) {
                // circuit breaker is disabled and thus never open
                json.writeBooleanField("isCircuitBreakerOpen", false);
            } else {
                json.writeBooleanField("isCircuitBreakerOpen", circuitBreaker.isOpen());
            }
            HystrixCommandMetrics.HealthCounts healthCounts = commandMetrics.getHealthCounts();
            json.writeNumberField("errorPercentage", healthCounts.getErrorPercentage());
            json.writeNumberField("errorCount", healthCounts.getErrorCount());
            json.writeNumberField("requestCount", healthCounts.getTotalRequests());

            // rolling counters
            json.writeNumberField("rollingCountCollapsedRequests",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.COLLAPSED));
            json.writeNumberField("rollingCountExceptionsThrown",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN));
            json.writeNumberField("rollingCountFailure",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.FAILURE));
            json.writeNumberField("rollingCountFallbackFailure",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE));
            json.writeNumberField("rollingCountFallbackRejection",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION));
            json.writeNumberField("rollingCountFallbackSuccess",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS));
            json.writeNumberField("rollingCountResponsesFromCache",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE));
            json.writeNumberField("rollingCountSemaphoreRejected",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED));
            json.writeNumberField("rollingCountShortCircuited",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED));
            json.writeNumberField("rollingCountSuccess",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS));
            json.writeNumberField("rollingCountThreadPoolRejected",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED));
            json.writeNumberField("rollingCountTimeout",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT));

            json.writeNumberField("currentConcurrentExecutionCount",
                    commandMetrics.getCurrentConcurrentExecutionCount());

            // latency percentiles
            json.writeNumberField("latencyExecute_mean", commandMetrics.getExecutionTimeMean());
            json.writeObjectFieldStart("latencyExecute");
            json.writeNumberField("0", commandMetrics.getExecutionTimePercentile(0));
            json.writeNumberField("25", commandMetrics.getExecutionTimePercentile(25));
            json.writeNumberField("50", commandMetrics.getExecutionTimePercentile(50));
            json.writeNumberField("75", commandMetrics.getExecutionTimePercentile(75));
            json.writeNumberField("90", commandMetrics.getExecutionTimePercentile(90));
            json.writeNumberField("95", commandMetrics.getExecutionTimePercentile(95));
            json.writeNumberField("99", commandMetrics.getExecutionTimePercentile(99));
            json.writeNumberField("99.5", commandMetrics.getExecutionTimePercentile(99.5));
            json.writeNumberField("100", commandMetrics.getExecutionTimePercentile(100));
            json.writeEndObject();
            //
            json.writeNumberField("latencyTotal_mean", commandMetrics.getTotalTimeMean());
            json.writeObjectFieldStart("latencyTotal");
            json.writeNumberField("0", commandMetrics.getTotalTimePercentile(0));
            json.writeNumberField("25", commandMetrics.getTotalTimePercentile(25));
            json.writeNumberField("50", commandMetrics.getTotalTimePercentile(50));
            json.writeNumberField("75", commandMetrics.getTotalTimePercentile(75));
            json.writeNumberField("90", commandMetrics.getTotalTimePercentile(90));
            json.writeNumberField("95", commandMetrics.getTotalTimePercentile(95));
            json.writeNumberField("99", commandMetrics.getTotalTimePercentile(99));
            json.writeNumberField("99.5", commandMetrics.getTotalTimePercentile(99.5));
            json.writeNumberField("100", commandMetrics.getTotalTimePercentile(100));
            json.writeEndObject();

            // property values for reporting what is actually seen by the command
            // rather than what was set somewhere
            HystrixCommandProperties commandProperties = commandMetrics.getProperties();

            json.writeNumberField("propertyValue_circuitBreakerRequestVolumeThreshold",
                    commandProperties.circuitBreakerRequestVolumeThreshold().get());
            json.writeNumberField("propertyValue_circuitBreakerSleepWindowInMilliseconds",
                    commandProperties.circuitBreakerSleepWindowInMilliseconds().get());
            json.writeNumberField("propertyValue_circuitBreakerErrorThresholdPercentage",
                    commandProperties.circuitBreakerErrorThresholdPercentage().get());
            json.writeBooleanField("propertyValue_circuitBreakerForceOpen",
                    commandProperties.circuitBreakerForceOpen().get());
            json.writeBooleanField("propertyValue_circuitBreakerForceClosed",
                    commandProperties.circuitBreakerForceClosed().get());
            json.writeBooleanField("propertyValue_circuitBreakerEnabled",
                    commandProperties.circuitBreakerEnabled().get());

            json.writeStringField("propertyValue_executionIsolationStrategy",
                    commandProperties.executionIsolationStrategy().get().name());
            json.writeNumberField("propertyValue_executionIsolationThreadTimeoutInMilliseconds",
                    commandProperties.executionIsolationThreadTimeoutInMilliseconds().get());
            json.writeBooleanField("propertyValue_executionIsolationThreadInterruptOnTimeout",
                    commandProperties.executionIsolationThreadInterruptOnTimeout().get());
            json.writeStringField("propertyValue_executionIsolationThreadPoolKeyOverride",
                    commandProperties.executionIsolationThreadPoolKeyOverride().get());
            json.writeNumberField("propertyValue_executionIsolationSemaphoreMaxConcurrentRequests",
                    commandProperties.executionIsolationSemaphoreMaxConcurrentRequests().get());
            json.writeNumberField("propertyValue_fallbackIsolationSemaphoreMaxConcurrentRequests",
                    commandProperties.fallbackIsolationSemaphoreMaxConcurrentRequests().get());

            // TODO
            /*
             * The following are commented out as these rarely change and are verbose
             * for streaming for something people don't change. We could perhaps allow
             * a property or request argument to include these.
             */

            // json.put("propertyValue_metricsRollingPercentileEnabled",
            // commandProperties.metricsRollingPercentileEnabled().get());
            // json.put("propertyValue_metricsRollingPercentileBucketSize",
            // commandProperties.metricsRollingPercentileBucketSize().get());
            // json.put("propertyValue_metricsRollingPercentileWindow",
            // commandProperties.metricsRollingPercentileWindowInMilliseconds().get());
            // json.put("propertyValue_metricsRollingPercentileWindowBuckets",
            // commandProperties.metricsRollingPercentileWindowBuckets().get());
            // json.put("propertyValue_metricsRollingStatisticalWindowBuckets",
            // commandProperties.metricsRollingStatisticalWindowBuckets().get());
            json.writeNumberField("propertyValue_metricsRollingStatisticalWindowInMilliseconds",
                    commandProperties.metricsRollingStatisticalWindowInMilliseconds().get());

            json.writeBooleanField("propertyValue_requestCacheEnabled",
                    commandProperties.requestCacheEnabled().get());
            json.writeBooleanField("propertyValue_requestLogEnabled",
                    commandProperties.requestLogEnabled().get());

            json.writeNumberField("reportingHosts", 1); // this will get summed across
            // all instances in a cluster

            json.writeEndObject(); // end data attribute
            json.writeEndObject();
            json.close();

            // output
            this.jsonMetrics.add(jsonString.getBuffer().toString());
        }

        // thread pool metrics
        for (HystrixThreadPoolMetrics threadPoolMetrics : HystrixThreadPoolMetrics.getInstances()) {
            HystrixThreadPoolKey key = threadPoolMetrics.getThreadPoolKey();

            StringWriter jsonString = new StringWriter();
            JsonGenerator json = this.jsonFactory.createGenerator(jsonString);
            json.writeStartObject();

            addServiceData(json, localService);
            json.writeObjectFieldStart("data");

            json.writeStringField("type", "HystrixThreadPool");
            json.writeStringField("name", key.name());
            json.writeNumberField("currentTime", System.currentTimeMillis());

            json.writeNumberField("currentActiveCount", threadPoolMetrics.getCurrentActiveCount().intValue());
            json.writeNumberField("currentCompletedTaskCount",
                    threadPoolMetrics.getCurrentCompletedTaskCount().longValue());
            json.writeNumberField("currentCorePoolSize", threadPoolMetrics.getCurrentCorePoolSize().intValue());
            json.writeNumberField("currentLargestPoolSize",
                    threadPoolMetrics.getCurrentLargestPoolSize().intValue());
            json.writeNumberField("currentMaximumPoolSize",
                    threadPoolMetrics.getCurrentMaximumPoolSize().intValue());
            json.writeNumberField("currentPoolSize", threadPoolMetrics.getCurrentPoolSize().intValue());
            json.writeNumberField("currentQueueSize", threadPoolMetrics.getCurrentQueueSize().intValue());
            json.writeNumberField("currentTaskCount", threadPoolMetrics.getCurrentTaskCount().longValue());
            json.writeNumberField("rollingCountThreadsExecuted",
                    threadPoolMetrics.getRollingCountThreadsExecuted());
            json.writeNumberField("rollingMaxActiveThreads", threadPoolMetrics.getRollingMaxActiveThreads());

            json.writeNumberField("propertyValue_queueSizeRejectionThreshold",
                    threadPoolMetrics.getProperties().queueSizeRejectionThreshold().get());
            json.writeNumberField("propertyValue_metricsRollingStatisticalWindowInMilliseconds",
                    threadPoolMetrics.getProperties().metricsRollingStatisticalWindowInMilliseconds().get());

            json.writeNumberField("reportingHosts", 1); // this will get summed across
            // all instances in a cluster

            json.writeEndObject(); // end of data object
            json.writeEndObject();
            json.close();
            // output to stream
            this.jsonMetrics.add(jsonString.getBuffer().toString());
        }
    } catch (Exception ex) {
        log.error("Error adding metrics to queue", ex);
    }
}