Example usage for java.io PrintWriter printf

List of usage examples for java.io PrintWriter printf

Introduction

In this page you can find the example usage for java.io PrintWriter printf.

Prototype

public PrintWriter printf(String format, Object... args) 

Source Link

Document

A convenience method to write a formatted string to this writer using the specified format string and arguments.

Usage

From source file:org.jenkins_ci.update_center.Main.java

/**
 * Identify the latest core, populates the htaccess redirect file, optionally download the core wars and build the
 * index.html/*from   w  w  w  .j  a  v a  2  s .c om*/
 *
 * @return the JSON for the core Jenkins
 */
protected JSONObject buildCore(MavenRepository repository, PrintWriter redirect) throws Exception {
    TreeMap<VersionNumber, HudsonWar> wars = repository.getHudsonWar();
    if (wars.isEmpty()) {
        return null;
    }

    HudsonWar latest = wars.get(wars.firstKey());
    latest.file = repository.resolve(latest.artifact);
    JSONObject core = latest.toJSON("core");
    System.out.println("core\n=> " + core);

    redirect.printf("Redirect 302 /latest/jenkins.war %s\n", latest.getURL().getPath());
    redirect.printf(
            "Redirect 302 /latest/debian/jenkins.deb http://pkg.jenkins-ci.org/debian/binary/jenkins_%s_all.deb\n",
            latest.getVersion());
    redirect.printf(
            "Redirect 302 /latest/redhat/jenkins.rpm http://pkg.jenkins-ci.org/redhat/RPMS/noarch/jenkins-%s-1.1.noarch.rpm\n",
            latest.getVersion());
    redirect.printf(
            "Redirect 302 /latest/opensuse/jenkins.rpm http://pkg.jenkins-ci.org/opensuse/RPMS/noarch/jenkins-%s-1.1.noarch.rpm\n",
            latest.getVersion());

    if (latestCoreTxt != null) {
        writeToFile(latest.getVersion().toString(), latestCoreTxt);
    }

    if (download != null) {
        // build the download server layout
        for (HudsonWar w : wars.values()) {
            stage(w, new File(download, "war/" + w.version + "/" + w.getFileName()));
        }
    }

    if (www != null) {
        buildIndex(new File(www, "download/war/"), "jenkins.war", wars.values(), "/latest/jenkins.war");
    }

    return core;
}

From source file:com.adobe.acs.commons.errorpagehandler.impl.ErrorPageHandlerImpl.java

@SuppressWarnings("squid:S1149")
private void configure(ComponentContext componentContext) {
    Dictionary<?, ?> config = componentContext.getProperties();
    final String legacyPrefix = "prop.";

    this.enabled = PropertiesUtil.toBoolean(config.get(PROP_ENABLED),
            PropertiesUtil.toBoolean(config.get(legacyPrefix + PROP_ENABLED), DEFAULT_ENABLED));

    this.vanityDispatchCheckEnabled = PropertiesUtil.toBoolean(config.get(PROP_VANITY_DISPATCH_ENABLED),
            PropertiesUtil.toBoolean(config.get(legacyPrefix + PROP_VANITY_DISPATCH_ENABLED),
                    DEFAULT_VANITY_DISPATCH_ENABLED));

    /** Error Pages **/

    this.systemErrorPagePath = PropertiesUtil.toString(config.get(PROP_ERROR_PAGE_PATH), PropertiesUtil
            .toString(config.get(legacyPrefix + PROP_ERROR_PAGE_PATH), DEFAULT_SYSTEM_ERROR_PAGE_PATH_DEFAULT));

    this.errorPageExtension = PropertiesUtil.toString(config.get(PROP_ERROR_PAGE_EXTENSION), PropertiesUtil
            .toString(config.get(legacyPrefix + PROP_ERROR_PAGE_EXTENSION), DEFAULT_ERROR_PAGE_EXTENSION));

    this.fallbackErrorName = PropertiesUtil.toString(config.get(PROP_FALLBACK_ERROR_NAME), PropertiesUtil
            .toString(config.get(legacyPrefix + PROP_FALLBACK_ERROR_NAME), DEFAULT_FALLBACK_ERROR_NAME));

    this.pathMap = configurePathMap(PropertiesUtil.toStringArray(config.get(PROP_SEARCH_PATHS),
            PropertiesUtil.toStringArray(config.get(legacyPrefix + PROP_SEARCH_PATHS), DEFAULT_SEARCH_PATHS)));

    /** Not Found Handling **/
    this.notFoundBehavior = PropertiesUtil.toString(config.get(PROP_NOT_FOUND_DEFAULT_BEHAVIOR),
            DEFAULT_NOT_FOUND_DEFAULT_BEHAVIOR);

    String[] tmpNotFoundExclusionPatterns = PropertiesUtil.toStringArray(
            config.get(PROP_NOT_FOUND_EXCLUSION_PATH_PATTERNS), DEFAULT_NOT_FOUND_EXCLUSION_PATH_PATTERNS);

    this.notFoundExclusionPatterns = new ArrayList<Pattern>();
    for (final String tmpPattern : tmpNotFoundExclusionPatterns) {
        this.notFoundExclusionPatterns.add(Pattern.compile(tmpPattern));
    }/*  w w  w.  j a v a  2 s.  c  o  m*/

    /** Error Page Cache **/

    int ttl = PropertiesUtil.toInteger(config.get(PROP_TTL),
            PropertiesUtil.toInteger(LEGACY_PROP_TTL, DEFAULT_TTL));

    boolean serveAuthenticatedFromCache = PropertiesUtil
            .toBoolean(config.get(PROP_SERVE_AUTHENTICATED_FROM_CACHE), PropertiesUtil.toBoolean(
                    LEGACY_PROP_SERVE_AUTHENTICATED_FROM_CACHE, DEFAULT_SERVE_AUTHENTICATED_FROM_CACHE));
    try {
        cache = new ErrorPageCacheImpl(ttl, serveAuthenticatedFromCache);

        Dictionary<String, Object> serviceProps = new Hashtable<String, Object>();
        serviceProps.put("jmx.objectname", "com.adobe.acs.commons:type=ErrorPageHandlerCache");

        cacheRegistration = componentContext.getBundleContext().registerService(DynamicMBean.class.getName(),
                cache, serviceProps);
    } catch (NotCompliantMBeanException e) {
        log.error("Unable to create cache", e);
    }

    /** Error Images **/

    this.errorImagesEnabled = PropertiesUtil.toBoolean(config.get(PROP_ERROR_IMAGES_ENABLED),
            DEFAULT_ERROR_IMAGES_ENABLED);

    this.errorImagePath = PropertiesUtil.toString(config.get(PROP_ERROR_IMAGE_PATH), DEFAULT_ERROR_IMAGE_PATH);

    // Absolute path
    if (StringUtils.startsWith(this.errorImagePath, "/")) {
        ResourceResolver serviceResourceResolver = null;
        try {
            Map<String, Object> authInfo = Collections.singletonMap(ResourceResolverFactory.SUBSERVICE,
                    (Object) SERVICE_NAME);
            serviceResourceResolver = resourceResolverFactory.getServiceResourceResolver(authInfo);
            final Resource resource = serviceResourceResolver.resolve(this.errorImagePath);

            if (resource != null && resource.isResourceType(JcrConstants.NT_FILE)) {
                final PathInfo pathInfo = new PathInfo(this.errorImagePath);

                if (!StringUtils.equals("img", pathInfo.getSelectorString())
                        || StringUtils.isBlank(pathInfo.getExtension())) {

                    log.warn("Absolute Error Image Path paths to nt:files should have '.img.XXX' "
                            + "selector.extension");
                }
            }
        } catch (LoginException e) {
            log.error("Could not get admin resource resolver to inspect validity of absolute errorImagePath");
        } finally {
            if (serviceResourceResolver != null) {
                serviceResourceResolver.close();
            }
        }
    }

    this.errorImageExtensions = PropertiesUtil.toStringArray(config.get(PROP_ERROR_IMAGE_EXTENSIONS),
            DEFAULT_ERROR_IMAGE_EXTENSIONS);

    for (int i = 0; i < errorImageExtensions.length; i++) {
        this.errorImageExtensions[i] = StringUtils.lowerCase(errorImageExtensions[i], Locale.ENGLISH);
    }

    final StringWriter sw = new StringWriter();
    final PrintWriter pw = new PrintWriter(sw);

    pw.println();
    pw.printf("Enabled: %s", this.enabled).println();
    pw.printf("System Error Page Path: %s", this.systemErrorPagePath).println();
    pw.printf("Error Page Extension: %s", this.errorPageExtension).println();
    pw.printf("Fallback Error Page Name: %s", this.fallbackErrorName).println();

    pw.printf("Resource Not Found - Behavior: %s", this.notFoundBehavior).println();
    pw.printf("Resource Not Found - Exclusion Path Patterns %s", Arrays.toString(tmpNotFoundExclusionPatterns))
            .println();

    pw.printf("Cache - TTL: %s", ttl).println();
    pw.printf("Cache - Serve Authenticated: %s", serveAuthenticatedFromCache).println();

    pw.printf("Error Images - Enabled: %s", this.errorImagesEnabled).println();
    pw.printf("Error Images - Path: %s", this.errorImagePath).println();
    pw.printf("Error Images - Extensions: %s", Arrays.toString(this.errorImageExtensions)).println();

    log.debug(sw.toString());
}

From source file:fNIRs.FNIRsStats.java

public static void writeANOVAs(File outFile, GroupedChannels data, List<String> groupNames,
        List<Integer> conditions, int numChunks, int precision) {
    // open file for writing with a nice print stream object:
    PrintWriter ostream = makePWriter(outFile); // OKAY VAR NAME?
    // get all condition-group sequences:
    ArrayList<GroupedChannels.TaggedDataSequence> allTDSs = data.getAllSelectedTDSs(groupNames, conditions);

    // chunkData(allTDSs, numChunks); // COMMENT THIS LATER

    int idFieldWidth = getIdFieldWidth(groupNames, conditions, precision);
    String idFieldFormat = "%-" + idFieldWidth + "s"; // format string
    String separator = " , "; // what goes between columns of output

    // output the first row, containing identifying information for each
    // group-condition combination:
    // first, output spaces to take the place of the identifier column:
    ostream.printf("%" + idFieldWidth + "s" + separator, ""); // TOO HACKY??
    // then, output all tds identifiers:
    for (GroupedChannels.TaggedDataSequence tds : allTDSs) {
        ostream.printf(idFieldFormat + separator, tds.getGroupName() + " c" + tds.getCondition());
    }//from  ww  w  .jav a  2  s. c o m
    ostream.println(); // print newline
    // output ANOVA values line by line:
    OneWayAnova myANOVA = new OneWayAnova(); // this object will do the
    // ANOVAs
    for (GroupedChannels.TaggedDataSequence first : allTDSs) {
        // output tds identifier in first column:
        ostream.printf(idFieldFormat + separator, first.getGroupName() + " c" + first.getCondition());
        // create Collection to send to the ANOVA object:
        LinkedList<double[]> dataSets = new LinkedList<double[]>();
        // convert first's data sequence to an array, then add it to
        // dataSets
        dataSets.add(toPrimitiveDoubleArray(first.getData()));
        dataSets.add(null); // placeholder for second's data sequence
        for (GroupedChannels.TaggedDataSequence second : allTDSs) {
            // convert and add second's data sequence to position one in
            // dataSets:
            dataSets.set(1, toPrimitiveDoubleArray(second.getData()));
            double result = -1; // not a valid ANOVA value so we know if
            // something went wrong
            try {
                result = myANOVA.anovaPValue(dataSets);
                // if (first == second) { // if the two TDSs are the same
                // TDS,
                // result = 1; // then the ANOVA value should be 1, even
                // though a divide-by-zero
                // }
            } catch (Exception ex) {
                ostream.println();
                System.out.println("foo");
                localError("unknown problem calculating ANOVA: " + ex.getMessage());
                System.out.println(
                        "---------------------------------------------------------------------------------------------------------------------------------------");
                for (double[] set : dataSets) {
                    printDoubleAry(set);
                    System.out.println("---------------------------------------");
                }
            }
            if (result != result) { // if result is NaN
                System.out.println("NaN on " + first.getGroupName() + " c" + first.getCondition() + " and "
                        + second.getGroupName() + " c" + second.getCondition());
            }
            // AGAIN, SEE IF "PRECISON" == "NUMBER OF DECIMAL PLACES"
            ostream.printf("%-" + idFieldWidth + "." + precision + "f" + separator, result);
        }
        ostream.println(); // print newline
    }
    ostream.close();
}

From source file:org.apache.sling.adapter.internal.AdapterWebConsolePlugin.java

private void getHtml(final HttpServletResponse resp) throws IOException {
    final PrintWriter writer = resp.getWriter();
    writer.println("<p class=\"statline ui-state-highlight\">${Introduction}</p>");
    writer.println("<p>${intro}</p>");
    writer.println("<p class=\"statline ui-state-highlight\">${How to Use This Information}</p>");
    writer.println("<p>${usage}</p>");
    writer.println("<table class=\"adapters nicetable\">");
    writer.println(//from w ww .  j a  va2 s  . c o m
            "<thead><tr><th class=\"header\">${Adaptable Class}</th><th class=\"header\">${Adapter Class}</th><th class=\"header\">${Condition}</th><th class=\"header\">${Deprecated}</th><th class=\"header\">${Providing Bundle}</th></tr></thead>");
    String rowClass = "odd";
    for (final AdaptableDescription desc : allAdaptables) {
        writer.printf("<tr class=\"%s ui-state-default\"><td>", rowClass);
        boolean packageExported = AdapterManagerImpl.checkPackage(packageAdmin, desc.adaptable);
        if (!packageExported) {
            writer.print("<span class='error'>");
        }
        writer.print(desc.adaptable);
        if (!packageExported) {
            writer.print("</span>");
        }
        writer.print("</td>");
        writer.print("<td>");
        for (final String adapter : desc.adapters) {
            packageExported = AdapterManagerImpl.checkPackage(packageAdmin, adapter);
            if (!packageExported) {
                writer.print("<span class='error'>");
            }
            writer.print(adapter);
            if (!packageExported) {
                writer.print("</span>");
            }
            writer.print("<br/>");
        }
        writer.print("</td>");
        if (desc.condition == null) {
            writer.print("<td>&nbsp;</td>");
        } else {
            writer.printf("<td>%s</td>", desc.condition);
        }
        if (desc.deprecated) {
            writer.print("<td>${Deprecated}</td>");
        } else {
            writer.print("<td></td>");
        }
        writer.printf("<td><a href=\"${pluginRoot}/../bundles/%s\">%s (%s)</a></td>", desc.bundle.getBundleId(),
                desc.bundle.getSymbolicName(), desc.bundle.getBundleId());
        writer.println("</tr>");

        if (rowClass.equals("odd")) {
            rowClass = "even";
        } else {
            rowClass = "odd";
        }
    }
    writer.println("</table>");
}

From source file:com.nridge.core.base.io.console.DataTableConsole.java

/**
 * Writes the contents of the data table to the console.
 *
 * @param aPW Printer writer instance./*from  w  ww. java2 s  .  co m*/
 * @param aTitle An optional presentation title.
 * @param aMaxWidth Maximum width of any column (zero means unlimited).
 * @param aColSpace Number of spaces between columns.
 */
public void write(PrintWriter aPW, String aTitle, int aMaxWidth, int aColSpace) {
    String rowString;
    DataField dataField;
    StringBuilder rowStrBuilder;
    int i, j, k, colCount, rowCount;
    String labelString, valueString;
    int strLength, colWidth, displayWidth, totalWidth;

    // Calculate our total output width.

    totalWidth = 0;
    colCount = mTable.columnCount();
    for (int col = 0; col < colCount; col++) {
        dataField = mTable.getFieldByColumn(col);

        if (dataField.isDisplayable())
            totalWidth += deriveRowColumnWidth(col, aMaxWidth);
    }
    totalWidth += (aColSpace * (colCount - 1));

    // Account for our title string.

    if (StringUtils.isNotEmpty(aTitle)) {
        totalWidth = Math.max(aTitle.length(), totalWidth);
        rowString = StrUtl.centerSpaces(aTitle, totalWidth);
        aPW.printf("%n%s%n%n", rowString);
    }

    // Display our column header information.

    rowStrBuilder = new StringBuilder();

    for (int col = 0; col < colCount; col++) {
        dataField = mTable.getFieldByColumn(col);

        if (dataField.isDisplayable()) {
            displayWidth = deriveRowColumnWidth(col, aMaxWidth);
            labelString = dataField.getTitle();
            strLength = labelString.length();
            colWidth = displayWidth + aColSpace;
            strLength = Math.min(displayWidth, strLength);
            rowStrBuilder.append(labelString.substring(0, strLength));
            for (k = strLength; k < colWidth; k++)
                rowStrBuilder.append(StrUtl.CHAR_SPACE);
        }
    }
    aPW.printf("%s%n", rowStrBuilder.toString());

    // Underline our column headers.

    rowStrBuilder.setLength(0);

    for (int col = 0; col < colCount; col++) {
        dataField = mTable.getFieldByColumn(col);

        if (dataField.isDisplayable()) {
            displayWidth = deriveRowColumnWidth(col, aMaxWidth);
            labelString = dataField.getTitle();
            strLength = labelString.length();
            colWidth = displayWidth + aColSpace;
            strLength = Math.min(displayWidth, strLength);
            for (j = 0; j < strLength; j++)
                rowStrBuilder.append(StrUtl.CHAR_HYPHEN);
            for (k = strLength; k < colWidth; k++)
                rowStrBuilder.append(StrUtl.CHAR_SPACE);
        }
    }
    aPW.printf("%s%n", rowStrBuilder.toString());

    // Display each row of cells.

    rowCount = mTable.rowCount();

    for (int row = 0; row < rowCount; row++) {
        rowStrBuilder.setLength(0);

        for (int col = 0; col < colCount; col++) {
            dataField = mTable.getFieldByRowCol(row, col);

            if (dataField.isDisplayable()) {
                displayWidth = deriveRowColumnWidth(col, aMaxWidth);
                if (dataField.isAssigned()) {
                    valueString = dataField.collapse(StrUtl.CHAR_COMMA);
                    if (StringUtils.isEmpty(valueString))
                        valueString = StringUtils.EMPTY;
                } else
                    valueString = StringUtils.EMPTY;

                strLength = valueString.length();
                colWidth = displayWidth + aColSpace;
                strLength = Math.min(displayWidth, strLength);
                rowStrBuilder.append(valueString.substring(0, strLength));
                for (k = strLength; k < colWidth; k++)
                    rowStrBuilder.append(StrUtl.CHAR_SPACE);
            }
        }
        aPW.printf("%s%n", rowStrBuilder.toString());
    }
    aPW.printf("%n");
}

From source file:org.apache.sling.commons.metrics.internal.MetricWebConsolePlugin.java

private void addGaugeDetails(PrintWriter pw, SortedMap<String, Gauge> gauges) {
    if (gauges.isEmpty()) {
        return;/*w  w w. j a  v a 2  s  . c  o m*/
    }

    pw.println("<br>");
    pw.println("<div class='table'>");
    pw.println("<div class='ui-widget-header ui-corner-top buttonGroup'>Gauges</div>");
    pw.println("<table class='nicetable' id='data-guages'>");
    pw.println("<thead>");
    pw.println("<tr>");
    pw.println("<th class='header'>Name</th>");
    pw.println("<th class='header'>Value</th>");
    pw.println("</tr>");
    pw.println("</thead>");
    pw.println("<tbody>");

    String rowClass = "odd";
    for (Map.Entry<String, Gauge> e : gauges.entrySet()) {
        Gauge g = e.getValue();
        String name = e.getKey();

        pw.printf("<tr class='%s ui-state-default'>%n", rowClass);

        pw.printf("<td>%s</td>", name);
        pw.printf("<td>%s</td>", g.getValue());

        pw.println("</tr>");
        rowClass = "odd".equals(rowClass) ? "even" : "odd";
    }

    pw.println("</tbody>");
    pw.println("</table>");
    pw.println("</div>");
}

From source file:org.apache.sling.commons.metrics.internal.MetricWebConsolePlugin.java

private void addCounterDetails(PrintWriter pw, SortedMap<String, Counter> counters) {
    if (counters.isEmpty()) {
        return;/*from  w  ww .  j av a 2  s.  co m*/
    }
    pw.println("<br>");
    pw.println("<div class='table'>");
    pw.println("<div class='ui-widget-header ui-corner-top buttonGroup'>Counters</div>");
    pw.println("<table class='nicetable' id='data-counters'>");
    pw.println("<thead>");
    pw.println("<tr>");
    pw.println("<th class='header'>Name</th>");
    pw.println("<th class='header'>Count</th>");
    pw.println("</tr>");
    pw.println("</thead>");
    pw.println("<tbody>");

    String rowClass = "odd";
    for (Map.Entry<String, Counter> e : counters.entrySet()) {
        Counter c = e.getValue();
        String name = e.getKey();

        pw.printf("<tr class='%s ui-state-default'>%n", rowClass);

        pw.printf("<td>%s</td>", name);
        pw.printf("<td>%d</td>", c.getCount());

        pw.println("</tr>");
        rowClass = "odd".equals(rowClass) ? "even" : "odd";
    }

    pw.println("</tbody>");
    pw.println("</table>");
    pw.println("</div>");
}

From source file:fr.inrialpes.exmo.align.cli.GenPlot.java

/**
 * This does average plus generate the call for Google Chart API
 *
 * @param result the resulting plot/*from w w w  .  j a  va2  s .c  om*/
 * @param writer in which the output is sent
 */
public void printHTMLGGraph(Vector<Vector<Pair>> result, PrintWriter writer) {
    writer.print("<img src=\"http://chart.apis.google.com/chart?");
    writer.print("chs=600x500&cht=lxy&chg=10,10&chof=png");
    writer.print("&chxt=x,x,y,y&chxr=0,0.0,1.0,0.1|2,0.0,1.0,0.1&chxl=1:|" + xlabel + "|3:|" + ylabel
            + "&chma=b&chxp=1,50|3,50&chxs=0N*sz1*|2N*sz1*");
    writer.print("&chd=t:"); // data
    boolean firstalg = true;
    for (Vector<Pair> table : result) {
        if (!firstalg)
            writer.print("|");
        firstalg = false;
        boolean firstpoint = true;
        String Yval = "|";
        for (Pair p : table) {
            if (!firstpoint) {
                writer.print(",");
                Yval += ",";
            }
            firstpoint = false;
            Yval += String.format("%1.2f", p.getY() * 10);
            //logger.trace( " >> {} - {}", p.getX(), p.getY() );
            writer.printf("%1.2f", p.getX() * 10);
        }
        writer.print(Yval);
    }
    writer.print("&chdl="); // labels
    int i = 0;
    //String marktable[] = { "+", "*", "x", "-", "|", "o", "asterisk", "star", "oplus", "oplus*", "otimes", "otimes*", "square", "square*", "triangle", "triangle*", "diamond", "diamond*", "pentagon", "pentagon*"};
    //String colortable[] = { "black", "red", "green!50!black", "blue", "cyan", "magenta" };
    String colortable[] = { "000000", "ffff00", "ff00ff", "00ffff", "ff0000", "00ff00", "0000ff", "888888",
            "8888ff", "88ff88", "ff8888", "8800ff", "88ff00", "008800", "ff8800", "0088ff", "000088", "ff0088",
            "00ff88", "888800", "880088", "008888", "880000", "008800", "000088", "88ffff", "ff88ff",
            "ffff88" };
    String style = "";
    String color = "";
    for (String m : listAlgo) {
        if (i > 0) {
            writer.print("|");
            color += ",";
            style += "|";
        }
        writer.print(m);
        color += colortable[i % 28];
        if (!listEvaluators.get(i).isValid()) {
            style += "2,6,3";
        } else {
            style += "2";
        }
        i++;
    }
    //writer.print("&chdlp=b"); // legend position (but ugly)
    writer.print("&chco=" + color); // colors
    writer.print("&chls=" + style); // linestyle
    writer.println("&chds=0,10\"/>");
}

From source file:dbseer.comp.live.LiveTransactionProcessor.java

@Override
public void run() {
    try {//from  www.  j  av a  2 s . co  m
        this.transactionCountWriter = new PrintWriter(new FileWriter(this.transactionCountFile, true));
        this.avgLatencyWriter = new PrintWriter(new FileWriter(this.avgLatencyFile, true));
    } catch (IOException e) {
        e.printStackTrace();
    }

    long time;
    // wait for transactions to come in
    while (true) {
        time = map.getMinEndTime();
        if (time != Long.MAX_VALUE) {
            break;
        } else {
            try {
                Thread.sleep(250);
            } catch (InterruptedException e) {
                if (!terminate) {
                    e.printStackTrace();
                } else {
                    return;
                }
            }
        }
        if (terminate) {
            break;
        }
    }

    String gap = "   ";
    double totalCount = 0;
    double currentCount = 0;
    double[] count = new double[DBSeerConstants.MAX_NUM_TABLE];
    double[] latencySum = new double[DBSeerConstants.MAX_NUM_TABLE];
    int maxClusterId = 0;
    long transCount = 0;

    // start processing transactions
    while (true) {
        long maxTime, maxClusterEndTime;
        maxTime = map.getMaxEndTime();
        if (!StreamClustering.getDBSCAN().isInitialized() && transCount < DBSeerConstants.DBSCAN_INIT_PTS) {
            transCount = map.getCount();
            monitor.setGlobalTransactionCount(transCount);
            try {
                Thread.sleep(250);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //         synchronized (StreamClustering.LOCK)
        try {
            StreamClustering.LOCK.lockInterruptibly();
            {
                maxClusterEndTime = StreamClustering.getDBSCAN().getMaxEndTime();
            }
            StreamClustering.LOCK.unlock();
            while (time < maxTime && time < maxClusterEndTime) {
                currentCount = 0;
                Set<Transaction> transactions = map.pollTransactions(time);

                // if no transactions for the time, skip to the next timestamp.
                if (transactions.isEmpty()) {
                    ++time;
                    continue;
                }

                // if sys log not available for the time, also skip to the next timestamp;
                if (map.getMinSysLogTime() != Long.MAX_VALUE && map.getMinSysLogTime() > time) {
                    ++time;
                    continue;
                }

                boolean monitorLogFound = true;
                String monitorLog;
                while ((monitorLog = map.getSysLog(time)) == null) {
                    if (time < map.getLastSysLogTime()) {
                        monitorLogFound = false;
                        break;
                    }
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        if (!terminate) {
                            e.printStackTrace();
                        } else {
                            return;
                        }
                    }
                }

                if (!monitorLogFound) {
                    ++time;
                    continue;
                }

                monitorWriter.println(monitorLog);
                monitorWriter.flush();

                for (Transaction t : transactions) {
                    Cluster c = t.getCluster();
                    // if cluster is null, skip
                    if (c == null) {
                        continue;
                    }

                    int cId = c.getId();
                    long latency = t.getLatency();

                    // ignore outliers
                    if (cId >= 0) {
                        latencySum[cId] += latency;
                        ++count[cId];
                        ++totalCount;
                        ++currentCount;

                        ArrayList<Double> latencyList = latencyMap.get(cId);
                        if (latencyList == null) {
                            latencyList = new ArrayList<Double>();
                            latencyMap.put(cId, latencyList);
                        }
                        latencyList.add((double) latency / 1000.0);
                    }
                    if (cId > maxClusterId) {
                        maxClusterId = cId;
                    }
                }

                // update live monitor
                //               int numTrans = maxClusterId + 1;
                int numTrans = StreamClustering.getDBSCAN().getAllClusters().size();
                synchronized (LiveMonitorInfo.LOCK) {
                    monitor.setCurrentTimestamp(time);
                    monitor.setNumTransactionTypes(numTrans);
                    monitor.setGlobalTransactionCount(totalCount);
                    for (int i = 0; i < numTrans; ++i) {
                        monitor.setCurrentTPS(i, count[i]);
                        if (count[i] == 0) {
                            monitor.setCurrentAverageLatency(i, 0.0);
                        } else {
                            monitor.setCurrentAverageLatency(i, latencySum[i] / count[i]);
                        }
                    }
                }

                transactionCountWriter.print(gap);
                avgLatencyWriter.print(gap);

                transactionCountWriter.printf("%.16e", (double) time);
                avgLatencyWriter.printf("%.16e", (double) time);

                for (int i = 0; i < numTrans; ++i) {
                    transactionCountWriter.print(gap);
                    transactionCountWriter.printf("%.16e", count[i]);
                    avgLatencyWriter.print(gap);
                    if (count[i] == 0.0) {
                        avgLatencyWriter.printf("%.16e", 0.0);
                    } else {
                        avgLatencyWriter.printf("%.16e", (latencySum[i] / (double) count[i] / 1000.0));
                    }
                    count[i] = 0;
                    latencySum[i] = 0;

                    // write percentile
                    PrintWriter writer = percentileLatencyWriter.get(i);
                    ArrayList<Double> latencyList = latencyMap.get(i);
                    if (latencyList == null) {
                        latencyList = new ArrayList<Double>();
                        latencyMap.put(i, latencyList);
                    }
                    if (writer == null) {
                        try {
                            writer = new PrintWriter(new FileOutputStream(String.format("%s%03d",
                                    DBSeerGUI.userSettings.getDBSeerRootPath() + File.separator
                                            + DBSeerConstants.LIVE_DATASET_PATH + File.separator
                                            + "prctile_latency_",
                                    i), true));
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                        percentileLatencyWriter.put(i, writer);
                    }

                    double[] latencies = Doubles.toArray(latencyList);
                    writer.printf("%d,", time);
                    for (double p : percentiles) {
                        Percentile percentile = new Percentile(p);
                        percentile.setData(latencies);
                        double val = percentile.evaluate();
                        if (Double.isNaN(val))
                            val = 0.0;
                        writer.printf("%f,", val);
                    }
                    writer.println();
                    writer.flush();
                }

                transactionCountWriter.println();
                avgLatencyWriter.println();
                transactionCountWriter.flush();
                avgLatencyWriter.flush();

                //            System.out.print((maxClusterId + 1) + ": ");
                //            for (int i = 0; i <= maxClusterId; ++i)
                //            {
                //               System.out.print(count[i] + ", ");
                //               count[i] = 0;
                //            }
                //            System.out.println();
                //            ArrayList<Cluster> clusters = (ArrayList<Cluster>)StreamClustering.getDBSCAN().getCurrentClusters();
                //            for (int i = 0; i < clusters.size(); ++i)
                //            {
                //               Cluster c1 = clusters.get(i);
                //               for (int j = 0; j < clusters.size(); ++j)
                //               {
                //                  Cluster c2 = clusters.get(j);
                //                  System.out.print(c1.getClusterDistance(c2) + " ");
                //               }
                //               System.out.println();
                //            }
                //            System.out.println("----");
                // is it correct to set it here?
                DBSeerGUI.isLiveDataReady = true;

                ++time;
            }

            if (terminate) {
                break;
            }

            Thread.sleep(100);
        } catch (InterruptedException e) {
            if (!terminate) {
                e.printStackTrace();
            } else {
                return;
            }
        }
    }
}

From source file:org.apache.sling.commons.metrics.internal.MetricWebConsolePlugin.java

private void addMeterDetails(PrintWriter pw, SortedMap<String, Meter> meters) {
    if (meters.isEmpty()) {
        return;/*from ww w  .ja  v  a2 s .c  om*/
    }
    pw.println("<br>");
    pw.println("<div class='table'>");
    pw.println("<div class='ui-widget-header ui-corner-top buttonGroup'>Meters</div>");
    pw.println("<table class='nicetable' id='data-meters'>");
    pw.println("<thead>");
    pw.println("<tr>");
    pw.println("<th class='header'>Name</th>");
    pw.println("<th class='header'>Count</th>");
    pw.println("<th class='header'>Mean Rate</th>");
    pw.println("<th class='header'>OneMinuteRate</th>");
    pw.println("<th class='header'>FiveMinuteRate</th>");
    pw.println("<th class='header'>FifteenMinuteRate</ th>");
    pw.println("<th>RateUnit</th>");
    pw.println("</tr>");
    pw.println("</thead>");
    pw.println("<tbody>");

    String rowClass = "odd";
    for (Map.Entry<String, Meter> e : meters.entrySet()) {
        Meter m = e.getValue();
        String name = e.getKey();

        double rateFactor = timeUnit.rateFor(name).toSeconds(1);
        String rateUnit = "events/" + calculateRateUnit(timeUnit.rateFor(name));
        pw.printf("<tr class='%s ui-state-default'>%n", rowClass);

        pw.printf("<td>%s</td>", name);
        pw.printf("<td>%d</td>", m.getCount());
        pw.printf("<td>%f</td>", m.getMeanRate() * rateFactor);
        pw.printf("<td>%f</td>", m.getOneMinuteRate() * rateFactor);
        pw.printf("<td>%f</td>", m.getFiveMinuteRate() * rateFactor);
        pw.printf("<td>%f</td>", m.getFifteenMinuteRate() * rateFactor);
        pw.printf("<td>%s</td>", rateUnit);

        pw.println("</tr>");
        rowClass = "odd".equals(rowClass) ? "even" : "odd";
    }

    pw.println("</tbody>");
    pw.println("</table>");
    pw.println("</div>");
}