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:dbseer.comp.process.transaction.TransactionLogWriter.java

public void writeLog(long timestamp, Collection<Transaction> transactions) throws Exception {
    if (!this.isInitialized) {
        throw new Exception("TransactionLogWriter not initialized.");
    }/*  ww  w . j  a va  2s .  c o  m*/

    double totalCount = 0;
    double[][] count = new double[numServer][DBSeerConstants.MAX_NUM_TABLE];
    double[][] latencySum = new double[numServer][DBSeerConstants.MAX_NUM_TABLE];
    String gap = "   ";

    if (!dbscan.isInitialized() && !dbscan.isInitializing()) {
        initialTransactions.addAll(transactions);

        if (initialTransactions.size() > dbscan.getInitPts() && !dbscan.isInitializing()) {
            dbscanInitializer = Executors.newSingleThreadExecutor();
            dbscanInitializer.submit(new Runnable() {
                @Override
                public void run() {
                    dbscan.initialDBSCAN(initialTransactions);
                }
            });
        }
    }

    for (Transaction t : transactions) {
        if (dbscan != null && dbscan.isInitialized()) {
            if (liveLogProcessor.getTxStartTime() == 0) {
                liveLogProcessor.setTxStartTime(timestamp);
            }
            dbscan.train(t);
        }

        int type;
        if (t.getCluster() == null) {
            type = 0;
        } else {
            type = t.getCluster().getId();
        }

        if (type > maxType) {
            maxType = type;
        }

        // if not outlier;
        if (type >= 0) {
            String server = t.getServerName();
            int index = serverIndex.get(server);
            latencySum[index][type] += t.getLatency();
            count[index][type]++;
            totalCount++;

            ArrayList<Double> latencyList = writers.get(server).getLatencyMap().get(type);
            if (latencyList == null) {
                latencyList = new ArrayList<Double>();
                writers.get(server).getLatencyMap().put(type, latencyList);
            }
            latencyList.add((double) t.getLatency());

            // write sample
            HashMap<Integer, Integer> countMap = writers.get(server).getTransactionSampleCountMap();
            Integer sampleCount = countMap.get(type);
            if (sampleCount == null) {
                countMap.put(type, 1);
            } else {
                int countVal = sampleCount.intValue();
                if (countVal < DBSeerConstants.MAX_TRANSACTION_SAMPLE) {
                    HashMap<Integer, PrintWriter> sampleWriters = writers.get(server)
                            .getTransactionSampleWriter();
                    PrintWriter sampleWriter = sampleWriters.get(type);
                    if (sampleWriter == null) {
                        sampleWriter = new PrintWriter(new FileOutputStream(String.format("%s%d",
                                this.dir + File.separator + server + File.separator + "tx_sample_", type),
                                false));
                        sampleWriters.put(type, sampleWriter);
                    }
                    sampleWriter.print(t.getEntireStatement());
                    sampleWriter.println("---");
                    sampleWriter.flush();
                    countVal++;
                    countMap.put(type, countVal);
                }
            }
        }
    }

    // update live monitor
    if (monitor != null) {
        monitor.setCurrentTimestamp(timestamp);
        monitor.setNumTransactionTypes(maxType + 1);
        monitor.setGlobalTransactionCount(totalCount);

        for (int i = 0; i <= maxType; ++i) {
            double countSum = 0;
            double latencySumSum = 0;
            for (int j = 0; j < numServer; ++j) {
                countSum += count[j][i];
                latencySumSum += latencySum[j][i];
            }
            monitor.setCurrentTPS(i, countSum);
            if (countSum == 0) {
                monitor.setCurrentAverageLatency(i, 0.0);
            } else {
                monitor.setCurrentAverageLatency(i, latencySumSum / countSum);
            }
        }
    }

    if (timestamp < liveLogProcessor.getSysStartTime() || liveLogProcessor.getSysStartTime() == 0) {
        return;
    }

    for (String server : servers) {
        TransactionWriter writer = writers.get(server);
        PrintWriter tpsWriter = writer.getTpsWriter();
        PrintWriter latencyWriter = writer.getLatencyWriter();

        HashMap<Integer, PrintWriter> prctileLatencyWriter = writer.getPrctileLatencyWriter();
        HashMap<Integer, ArrayList<Double>> latencyMap = writer.getLatencyMap();

        tpsWriter.print(gap);
        latencyWriter.print(gap);

        tpsWriter.printf("%.16e", (double) timestamp);
        latencyWriter.printf("%.16e", (double) timestamp);

        int index = serverIndex.get(server);

        for (int i = 0; i <= maxType; ++i) {
            tpsWriter.print(gap);
            tpsWriter.printf("%.16e", count[index][i]);

            latencyWriter.print(gap);
            if (count[index][i] == 0.0) {
                latencyWriter.printf("%.16e", 0.0);
            } else {
                latencyWriter.printf("%.16e", (latencySum[index][i] / count[index][i]) / 1000.0);
            }

            // write percentile
            PrintWriter prctileWriter = prctileLatencyWriter.get(i);
            ArrayList<Double> latencyList = latencyMap.get(i);
            if (latencyList == null) {
                latencyList = new ArrayList<Double>();
                latencyMap.put(i, latencyList);
            }
            if (prctileWriter == null) {
                prctileWriter = new PrintWriter(new FileOutputStream(
                        String.format("%s%03d",
                                this.dir + File.separator + server + File.separator + "prctile_latency_", i),
                        false));
                prctileLatencyWriter.put(i, prctileWriter);
            }
            double[] latencies = Doubles.toArray(latencyList);
            prctileWriter.printf("%d,", timestamp);
            for (double p : percentiles) {
                Percentile percentile = new Percentile(p);
                percentile.setData(latencies);
                double val = percentile.evaluate();
                if (Double.isNaN(val))
                    val = 0.0;
                prctileWriter.printf("%f,", val / 1000.0);
            }
            prctileWriter.println();
            prctileWriter.flush();
            latencyList.clear();
        }

        tpsWriter.println();
        latencyWriter.println();
        tpsWriter.flush();
        latencyWriter.flush();
        isWritingStarted = true;
    }
}

From source file:org.jvnet.hudson.update_center.Main.java

/**
 * Identify the latest core, populates the htaccess redirect file, optionally download the core wars and build the index.html
 * @return the JSON for the core Jenkins
 */// w  w w .  j  a v a 2 s .  c  o  m
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());
    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.telefonica.iot.perseo.EventsServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from w w  w .j ava 2s .  c o  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Utils.putCorrelatorAndTrans(request);
    logger.debug("events doPost");
    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        StringBuilder sb = new StringBuilder();
        String eventText = Utils.getBodyAsString(request);
        logger.info("incoming event:" + eventText);
        org.json.JSONObject jo = new JSONObject(eventText);
        logger.debug("event as JSONObject: " + jo);
        Map<String, Object> eventMap = Utils.JSONObject2Map(jo);
        logger.debug("event as map: " + eventMap);
        epService.getEPRuntime().sendEvent(eventMap, Constants.IOT_EVENT);
        logger.debug("event was sent: " + eventMap);
    } catch (JSONException je) {
        logger.error("error: " + je);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        out.printf("{\"error\":\"%s\"}\n", je.getMessage());

    } finally {
        out.close();
    }
}

From source file:org.ow2.mind.doc.adl.HTMLDocumentGenerator.java

private String copySourceToHTML(final File sourceDirectory, String sourceFileName, final String destFileName) {
    String dest = null;//from   w  w  w .  j a v  a2s.c o  m
    if (sourceFileName.startsWith("/")) {
        sourceFileName = sourceFileName.substring(1);
    }

    final File sourceFile = new File(sourceDirectory, sourceFileName);
    if (!sourceFile.canRead()) {
        Launcher.logger.warning("Cannot read implementation file '" + sourceFileName.toString() + "'.");
    } else {
        try {
            final File destinationFile = new File(outputFile.getParentFile(), destFileName);
            final FileWriter out = new FileWriter(destinationFile);
            final PrintWriter writer = new PrintWriter(out);
            final InputStream in = new FileInputStream(sourceFile);

            writer.print("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
                    + "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n"
                    + "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" + "<head>\n"
                    + "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n");
            writer.printf("<title>%s</title>\n", sourceFileName);
            writer.println("</head>");
            writer.println("<body>");
            writer.println("<pre>");
            IOUtils.copy(in, out);
            writer.println("</pre>");
            writer.println("</body>");
            writer.println("</html>");
            writer.close();
            in.close();
            dest = destinationFile.getName();
        } catch (final IOException e) {
            Launcher.logger.warning("Cannot copy implementation file '" + sourceFileName.toString()
                    + "'. Reason: " + e.getLocalizedMessage());
        }
    }
    return dest;
}

From source file:edu.umn.cs.spatialHadoop.visualization.HadoopvizServer.java

/**
 * This method will handle the output result.
 * //  ww w  . ja v  a  2 s .  c  o  m
 * @param request
 * @param response
 */
private void handleOutputInfo(HttpServletRequest request, HttpServletResponse response) {
    try {
        FileSystem fs = outputPath.getFileSystem(commonParams);
        Path infoPath = new Path(outputPath.toString() + "/" + request.getParameter("path") + "/info.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(fs.open(infoPath)));
        JobID jobID = JobID.forName(br.readLine());
        br.close();

        JobClient jobClient = new JobClient(new JobConf(commonParams));
        RunningJob runningJob = jobClient.getJob(jobID);
        Counters counters = runningJob.getCounters();

        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print("{\"inputSize\":\"" + humanReadable(
                runningJob.getCounters().findCounter("FileSystemCounters", "HDFS_BYTES_READ").getCounter())
                + "\",");
        writer.print("\"intermediateSize\":\""
                + humanReadable(counters.getCounter(Task.Counter.MAP_OUTPUT_BYTES)) + "\",");
        writer.printf("\"jobID\":\"%s\",\n", jobID);
        writer.printf("\"jobURL\":\"%s\",\n", runningJob.getTrackingURL());
        writer.print("\"intermediateGroup\":" + "\"" + counters.getCounter(Task.Counter.REDUCE_INPUT_GROUPS)
                + "\"}");
        writer.close();
        response.setStatus(HttpServletResponse.SC_OK);
    } catch (Exception e) {
        System.out.println("error happened");
        e.printStackTrace();
        response.setContentType("text/plain;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:edu.cornell.med.icb.goby.modes.FilesToAttributesMode.java

@Override
public void execute() throws IOException {
    final PrintWriter out = outputFilename == null ? new PrintWriter(System.out)
            : new PrintWriter(outputFilename);
    try {/*from  w  w  w  .j  a va 2s .c o  m*/
        int index = 0;
        out.print("trackName\t");
        for (String attributeName : attributeNames) {
            if (!"ignore".equals(attributeName)) {
                out.print(attributeName);

                if (index != attributeNames.length) {
                    out.print('\t');
                }
            }
            index++;
        }
        out.println();
        for (String file : filenames) {
            final String file1 = file;
            String name = FilenameUtils.getName(file1);
            String filename = FilenameUtils.getBaseName(name);
            String[] tokens = filename.split(delimiter);
            out.printf("%s\t", adjustSuffix(name));
            for (int i = 0; i < attributeNames.length; i++) {
                if (!"ignore".equals(attributeNames[i])) {
                    if (tokens.length <= i) {
                        continue;
                    }
                    out.print(tokens[i]);
                    if (i != attributeNames.length) {
                        out.print('\t');
                    }
                }

            }
            out.println();
        }
        out.flush();
    } finally {
        out.close();

    }
}

From source file:es.tid.cep.esperanza.Rules.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*  w  w w . ja va  2s.  co m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    response.setContentType("application/json;charset=UTF-8");
    try {
        ServletInputStream sis = request.getInputStream();
        byte[] b = new byte[request.getContentLength()];
        sis.read(b, 0, b.length);
        String expression = new String(b);
        logger.debug("rule text: ", expression);
        EPStatement statement = epService.getEPAdministrator().createEPL(expression);
        logger.debug("statement json: " + Utils.Statement2JSONObject(statement));
        statement.addListener(new GenericListener());
        out.println(Utils.Statement2JSONObject(statement));
    } catch (EPException epe) {
        logger.error("creating statement", epe);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        out.printf("{\"error\":%s}\n", JSONObject.valueToString(epe.getMessage()));
    } finally {
        out.close();
    }
}

From source file:es.tid.cep.esperanza.Events.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/* w w  w.j av  a 2  s  .  c o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("events doPost");
    PrintWriter out = response.getWriter();
    try {
        response.setContentType("application/json;charset=UTF-8");
        ServletInputStream sis = request.getInputStream();
        byte[] b = new byte[request.getContentLength()];
        sis.read(b, 0, b.length);
        sis.close();
        String eventText = new String(b);
        logger.debug("event as text:" + eventText);
        org.json.JSONObject jo = new JSONObject(eventText);
        logger.debug("event as JSONObject: " + jo);
        Map<String, Object> otro = Utils.JSONObject2Map(jo);
        logger.debug("event as map: " + otro);
        epService.getEPRuntime().sendEvent(otro, "iotEvent");
        logger.debug("event was sent: " + otro);
    } catch (JSONException je) {
        logger.debug("error: " + je.getMessage());
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        out.printf("{\"error\":\"%s\"}\n", je.getMessage());

    } finally {
        out.close();
    }
}

From source file:de.qucosa.webapi.v1.DocumentResource.java

private void writeHtAccessFile(String qid, Document qucosaDocument)
        throws XPathExpressionException, FileNotFoundException {

    NodeList restrictedFiles = (NodeList) xPath.evaluate("//File[PathName!='' and FrontdoorVisible!='1']",
            qucosaDocument, XPathConstants.NODESET);

    File htaccess;//from w  w w  .  j  a v  a2  s.c  o  m
    try {
        htaccess = fileHandlingService.newFile(qid, ".htaccess");
    } catch (IOException e) {
        log.error("Cannot create .htaccess file: " + e.getMessage());

        if (log.isDebugEnabled()) {
            log.debug("Cause: ", e.getCause());
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            log.debug("Stacktrace: ", sw);
        }

        return;
    }

    if (htaccess == null || !htaccess.exists() || !htaccess.canWrite()) {
        log.error("No write access to .htaccess file");
        return;
    }

    if (restrictedFiles.getLength() == 0) {
        if (htaccess.exists())
            htaccess.delete();
        return;
    }

    List<String> filenames = new LinkedList<>();
    for (int i = 0; i < restrictedFiles.getLength(); i++) {
        filenames.add(
                ((Element) restrictedFiles.item(i)).getElementsByTagName("PathName").item(0).getTextContent());
    }

    PrintWriter printWriter = new PrintWriter(htaccess);
    for (String filename : filenames) {
        printWriter.printf("<Files \"%s\">\n\tOrder Deny,Allow\n\tDeny From All\n</Files>\n", filename);
    }
    printWriter.close();
}

From source file:com.nridge.core.base.io.xml.DataFieldXML.java

public void saveValue(PrintWriter aPW, DataField aDataField, int anIndentAmount) throws IOException {
    if (aDataField.isRangeAssigned()) {
        String singleValue;/*w  w w.  j  a  va2  s .c  o  m*/
        mRangeXML.saveNode(aPW, anIndentAmount + 1);
        mRangeXML.saveAttr(aPW, aDataField.getRange());
        mRangeXML.saveValue(aPW, aDataField.getRange());
        if (aDataField.isMultiValue()) {
            String mvDelimiter = aDataField.getFeature(Field.FEATURE_MV_DELIMITER);
            if (StringUtils.isNotEmpty(mvDelimiter))
                singleValue = aDataField.collapse(mvDelimiter.charAt(0));
            else
                singleValue = aDataField.collapse();
        } else
            singleValue = aDataField.getValue();

        IOXML.writeNodeNameValue(aPW, anIndentAmount + 1, "Value", singleValue);
        IOXML.indentLine(aPW, anIndentAmount);
        aPW.printf("</%s>%n", IO.XML_FIELD_NODE_NAME);
    } else {
        if (aDataField.isMultiValue()) {
            String mvDelimiter = aDataField.getFeature(Field.FEATURE_MV_DELIMITER);
            if (StringUtils.isNotEmpty(mvDelimiter))
                aPW.printf(">%s</%s>%n",
                        StringEscapeUtils.escapeXml10(aDataField.collapse(mvDelimiter.charAt(0))),
                        IO.XML_FIELD_NODE_NAME);
            else
                aPW.printf(">%s</%s>%n", StringEscapeUtils.escapeXml10(aDataField.collapse()),
                        IO.XML_FIELD_NODE_NAME);
        } else {
            if (aDataField.isFeatureTrue(Field.FEATURE_IS_CONTENT))
                aPW.printf(">%s</%s>%n", XMLUtl.escapeElemStrValue(aDataField.getValue()),
                        IO.XML_FIELD_NODE_NAME);
            else
                aPW.printf(">%s</%s>%n", StringEscapeUtils.escapeXml10(aDataField.getValue()),
                        IO.XML_FIELD_NODE_NAME);
        }
    }
}