Example usage for java.io PrintStream print

List of usage examples for java.io PrintStream print

Introduction

In this page you can find the example usage for java.io PrintStream print.

Prototype

public void print(Object obj) 

Source Link

Document

Prints an object.

Usage

From source file:hu.bme.mit.sette.run.Run.java

private static String readScenario(String[] args, BufferedReader in, PrintStream out) throws IOException {
    String scenario = null;/*w  ww  .  j av  a  2 s.c om*/

    if (args.length > 1) {
        out.println("Usage: java -jar SETTE.jar [scenario]");
        out.println("Available scenarios:");
        for (int i = 0; i < Run.scenarios.length; i++) {
            out.println(String.format("  [%d] %s", i, Run.scenarios[i]));
        }
    } else if (args.length == 1) {
        scenario = Run.parseScenario(args[0]);
        if (scenario == null) {
            out.println("Invalid scenario: " + args[0].trim());
            out.println("Available scenarios:");
            for (int i = 0; i < Run.scenarios.length; i++) {
                out.println(String.format("  [%d] %s", i, Run.scenarios[i]));
            }
        }
    } else {
        while (scenario == null) {
            out.println("Available scenarios:");
            for (int i = 0; i < Run.scenarios.length; i++) {
                out.println(String.format("  [%d] %s", i, Run.scenarios[i]));
            }

            out.print("Select scenario: ");

            String line = in.readLine();

            if (line == null) {
                out.println("EOF detected, exiting");
                return null;
            } else if (StringUtils.isBlank(line)) {
                out.println("Exiting");
                return null;
            }

            scenario = Run.parseScenario(line);
            if (scenario == null) {
                out.println("Invalid scenario: " + line.trim());
            }
        }
    }

    out.println("Selected scenario: " + scenario);
    return scenario;
}

From source file:com.recomdata.export.HeatMapTable.java

public void writeToFile(String delimiter, PrintStream ps, Boolean addMeans) {
    // outputs a data table, suitable for export to genepattern

    ps.println("#1.2");

    if (addMeans) {
        ps.println(rows.size() + delimiter + columns.size());
    } else {/*  w ww  . ja v  a2  s  . c  o  m*/
        ps.println(rows.size() + delimiter + (columns.size() - 1));
    }

    ps.print("NAME" + delimiter + "Description");

    // to assure that columns are returned in the right order,
    // build a list of subject ids, then sort the list
    ArrayList<String> ids = new ArrayList<String>();
    for (String id : ids1.values()) {
        ids.add(id);
    }
    for (String id : ids2.values()) {
        ids.add(id);
    }

    // ids should be numerically sorted already...

    java.util.Collections.sort(ids, new subjectComparator());

    for (String id : ids) {
        ps.print(delimiter + id);
    }

    if (addMeans) {
        ps.print(delimiter + "Mean");
    }

    ps.print("\n");

    HeatMapRow row;
    Double sumOfValues = 0.0;
    Double countOfValues = 0.0;
    for (String gene : rows.keySet()) {
        ps.print(gene + delimiter + descriptions.get(gene));
        row = rows.get(gene);
        for (String id : ids) {
            String value = row.get(id);
            if (value == "null" || value == "") {
                // causes problems in genepattern
                value = "";
            } else if (addMeans) {
                // System.out.println(gene + ", " + id + ": " + value);
                sumOfValues = sumOfValues + Double.valueOf(value);
                countOfValues = countOfValues + 1;
            }
            ps.print(delimiter + value);
        }
        if (addMeans) {
            Double mean = 0.0;
            if (countOfValues > 0) {
                mean = sumOfValues / countOfValues;
            }
            ps.print(delimiter + mean);
        }
        ps.print("\n");
    }
}

From source file:com.google.feedserver.tools.FeedServerClientTool.java

protected void printIndentation(PrintStream out) {
    for (int i = 0; i < indentation.get(); i++) {
        out.print(' ');
    }//w  w  w  .  jav  a  2s  .  co m
}

From source file:org.apache.hadoop.util.Crc32PerformanceTest.java

private void doBench(final List<Class<? extends Crc32>> crcs, final ByteBuffer[] dataBufs, final int bytePerCrc,
        final PrintStream out) throws Exception {
    final ByteBuffer[] crcBufs = new ByteBuffer[dataBufs.length];
    for (int i = 0; i < crcBufs.length; i++) {
        crcBufs[i] = computeCrc(dataBufs[i], bytePerCrc);
    }// w w  w .jav  a 2 s . c o m

    final String numBytesStr = " bpc ";
    final String numThreadsStr = "#T";
    final String diffStr = "% diff";

    out.print('|');
    printCell(numBytesStr, 0, out);
    printCell(numThreadsStr, 0, out);
    for (int i = 0; i < crcs.size(); i++) {
        final Class<? extends Crc32> c = crcs.get(i);
        out.print('|');
        printCell(c.getSimpleName(), 8, out);
        for (int j = 0; j < i; j++) {
            printCell(diffStr, diffStr.length(), out);
        }
    }
    out.printf("\n");

    for (int numThreads = 1; numThreads <= dataBufs.length; numThreads <<= 1) {
        out.printf("|");
        printCell(String.valueOf(bytePerCrc), numBytesStr.length(), out);
        printCell(String.valueOf(numThreads), numThreadsStr.length(), out);

        final List<BenchResult> previous = new ArrayList<BenchResult>();
        for (Class<? extends Crc32> c : crcs) {
            System.gc();

            final BenchResult result = doBench(c, numThreads, dataBufs, crcBufs, bytePerCrc);
            printCell(String.format("%9.1f", result.mbps), c.getSimpleName().length() + 1, out);

            //compare result with previous
            for (BenchResult p : previous) {
                final double diff = (result.mbps - p.mbps) / p.mbps * 100;
                printCell(String.format("%5.1f%%", diff), diffStr.length(), out);
            }
            previous.add(result);
        }
        out.printf("\n");
    }
}

From source file:org.apache.hadoop.hdfs.util.LightWeightHashSet.java

/**
 * Print detailed information of this object.
 *///from  www .  j  a  v a  2s. c o m
public void printDetails(final PrintStream out) {
    out.print(this + ", entries = [");
    for (int i = 0; i < entries.length; i++) {
        if (entries[i] != null) {
            LinkedElement<T> e = entries[i];
            out.print("\n  " + i + ": " + e);
            for (e = e.next; e != null; e = e.next) {
                out.print(" -> " + e);
            }
        }
    }
    out.println("\n]");
}

From source file:com.adaptris.core.AdaptrisMessageCase.java

@Test
public void testOutputStream() throws Exception {
    AdaptrisMessage msg1 = createMessage();

    PrintStream out = new PrintStream(msg1.getOutputStream());
    out.print(PAYLOAD2);
    // w/o closing the output stream, it's not going to be equal
    assertNotSame(PAYLOAD2, msg1.getContent());
    out.close();//from www. j  a va2  s  .  c o  m
    assertEquals(PAYLOAD2, msg1.getContent());
}

From source file:io.snappydata.test.dunit.standalone.ProcessManager.java

private void linkStreams(final int vmNum, final ProcessHolder holder, final InputStream in,
        final PrintStream out) {
    Thread ioTransport = new Thread() {
        public void run() {
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String vmName = (vmNum == -2) ? "[locator]" : "[vm_" + vmNum + "]";
            try {
                String line = reader.readLine();
                while (line != null) {
                    out.print(vmName);
                    out.println(line);//from  ww  w.j  av  a  2s .com
                    line = reader.readLine();
                }
            } catch (Exception e) {
                if (!holder.isKilled()) {
                    out.println("Error transporting IO from child process");
                    e.printStackTrace(out);
                }
            }
        }
    };

    ioTransport.setDaemon(true);
    ioTransport.start();
}

From source file:com.intel.ssg.dcst.panthera.cli.PantheraCliDriver.java

/**
 * If enabled and applicable to this command, print the field headers
 * for the output./*from   w w w.j  ava  2  s.  c o m*/
 *
 * @param qp Driver that executed the command
 * @param out Printstream which to send output to
 */
private void printHeader(Driver qp, PrintStream out) {
    List<FieldSchema> fieldSchemas = qp.getSchema().getFieldSchemas();
    if (HiveConf.getBoolVar(conf, HiveConf.ConfVars.HIVE_CLI_PRINT_HEADER) && fieldSchemas != null) {
        // Print the column names
        boolean first_col = true;
        for (FieldSchema fs : fieldSchemas) {
            if (!first_col) {
                out.print('\t');
            }
            out.print(fs.getName());
            first_col = false;
        }
        out.println();
    }
}

From source file:com.sangupta.jerry.print.ConsoleTable.java

/**
 * Display one row of information//from  w  w w. ja v a  2s.  c  om
 *  
 * @param out
 * @param row
 */
private void displayRow(final ConsoleTableLayout layout, final PrintStream out, final ConsoleTableRow row) {
    final ConsoleTableRow multiLineSplitRow = new ConsoleTableRow();

    boolean lineWasSplit = false;
    for (int index = 0; index < row.getColumns().size(); index++) {
        out.print(this.columnSeparator); // prepend every table cell with a space as a separator

        final String column = row.column(index);
        final int colSize = getMaxColSize(index);
        final int size = column.length();
        final int delta = colSize - size;

        switch (layout) {
        case FULL_WIDTH:
            out.print(column);
            ;
            if (delta > 0) {
                out.print(StringUtils.repeat(' ', delta));
            }

            break;

        case MULTI_LINE:
            if (delta < 0) {
                // now break this line into two and push suffix-split to multiLineRows
                // we will output them at the end again
                // check for new line before colSize
                int splitPosition = colSize;

                // check for new line before
                int search = StringUtils.lastIndexBefore(column, "\n", colSize);
                if (search > 0 && search < colSize) {
                    splitPosition = search;
                } else {
                    search = StringUtils.lastIndexBefore(column, " ", colSize);
                    if (search > 0) {
                        splitPosition = search;
                    }
                }

                String split = column.substring(0, splitPosition);
                multiLineSplitRow.addColumn(column.substring(splitPosition));
                lineWasSplit = true;

                // output the split prefix
                out.print(split);
            } else {
                multiLineSplitRow.addColumn("");
                out.print(column);
                ;

                if (delta > 0) {
                    out.print(StringUtils.repeat(' ', delta));
                }
            }
            break;

        case STRIPPED:
            if (delta == 0) {
                out.print(column);
            } else {
                if (delta < 0) {
                    out.print(column.substring(0, colSize));
                } else {
                    out.print(column);
                    ;
                    out.print(StringUtils.repeat(' ', delta));
                }
            }
            break;

        default:
            throw new IllegalStateException("Layout has not yet been implemented");
        }
    }
    out.println();

    // any additional rows to be written again
    if (lineWasSplit) {
        displayRow(layout, out, multiLineSplitRow);
    }
}

From source file:org.intermine.web.struts.TemplateAction.java

/**
 * Build a query based on the template and the input from the user. There
 * are some request parameters that, if present, effect the behaviour of the
 * action. These are://from  ww  w. j a va2 s.c o  m
 *
 * <dl>
 * <dt>skipBuilder</dt>
 * <dd>If this attribute is specifed (with any value) then the action will
 * forward directly to the object details page if the results contain just
 * one object.</dd>
 * <dt>noSaveQuery</dt>
 * <dd>If this attribute is specifed (with any value) then the query is not
 * automatically saved in the user's query history.</dd>
 * </dl>
 *
 * @param mapping
 *            The ActionMapping used to select this instance
 * @param form
 *            The optional ActionForm bean for this request (if any)
 * @param request
 *            The HTTP request we are processing
 * @param response
 *            The HTTP response we are creating
 * @return an ActionForward object defining where control goes next
 *
 * @exception Exception
 *                if the application business logic throws an exception
 */
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    HttpSession session = request.getSession();
    final InterMineAPI im = SessionMethods.getInterMineAPI(session);

    TemplateForm tf = (TemplateForm) form;
    String templateName = tf.getName();
    boolean saveQuery = (request.getParameter("noSaveQuery") == null);
    boolean skipBuilder = (request.getParameter(SKIP_BUILDER_PARAMETER) != null);
    boolean editTemplate = (request.getParameter("editTemplate") != null);
    boolean editQuery = (request.getParameter("editQuery") != null);

    // Note this is a workaround and will fail if a user has a template with the same name as
    // a public template but has executed the public one.  TemplateManager always give
    // precedence to user templates when there is a naming clash.
    String scope = tf.getScope();
    if (StringUtils.isBlank(scope)) {
        scope = Scope.ALL;
    }

    SessionMethods.logTemplateQueryUse(session, scope, templateName);

    Profile profile = SessionMethods.getProfile(session);
    TemplateManager templateManager = im.getTemplateManager();

    TemplateQuery template = templateManager.getTemplate(profile, templateName, scope);
    //If I'm browsing from the history or from saved query the template is in the session
    //with the values edited by the user, from this template we retrieve the original name
    //that we use to call the TemplateManager
    if (template == null) {
        PathQuery query = SessionMethods.getQuery(session);
        if (query instanceof TemplateQuery) {
            TemplateQuery currentTemplate = (TemplateQuery) query;
            template = templateManager.getTemplate(profile, currentTemplate.getName(), scope);
        } else {
            //from the template click edit query and then back (in this case in the session
            //there is a pathquery)
            template = templateManager.getTemplate(profile, (String) session.getAttribute("templateName"),
                    scope);
        }
    }
    if (template == null) {
        throw new RuntimeException("Could not find a template called " + session.getAttribute("templateName"));
    }
    TemplateQuery populatedTemplate = TemplatePopulator.getPopulatedTemplate(template,
            templateFormToTemplateValues(tf, template));

    //displayconstraint list used to display  constraints edited by the user
    DisplayConstraintFactory factory = new DisplayConstraintFactory(im, null);
    DisplayConstraint displayConstraint = null;
    List<DisplayConstraint> displayConstraintList = new ArrayList<DisplayConstraint>();
    for (PathConstraint pathConstraint : populatedTemplate.getEditableConstraints()) {
        displayConstraint = factory.get(pathConstraint, profile, populatedTemplate);
        displayConstraintList.add(displayConstraint);
    }
    session.setAttribute("dcl", displayConstraintList);

    String url = new URLGenerator(request).getPermanentBaseURL();

    if (!populatedTemplate.isValid()) {
        recordError(new ActionMessage("errors.template.badtemplate",
                StringUtil.prettyList(populatedTemplate.verifyQuery())), request);
        return mapping.findForward("template");
    }

    if (!editQuery && !skipBuilder && !editTemplate && forwardToLinksPage(request)) {

        Properties webProperties = SessionMethods.getWebProperties(request.getSession().getServletContext());

        WebserviceCodeGenInfo info = new WebserviceCodeGenInfo(populatedTemplate, url,
                webProperties.getProperty("project.title"), webProperties.getProperty("perl.wsModuleVer"),
                WebserviceCodeGenAction.templateIsPublic(template, im, profile), profile.getUsername());
        WebserviceCodeGenerator codeGen = new WebserviceJavaScriptCodeGenerator();
        String code = codeGen.generate(info);
        session.setAttribute("realCode", code);
        String escapedCode = StringEscapeUtils.escapeHtml(code);
        session.setAttribute("jsCode", escapedCode);

        return mapping.findForward("serviceLink");
    }

    if (!editQuery && !skipBuilder && !editTemplate && wantsWebserviceURL(request)) {
        TemplateResultLinkGenerator gen = new TemplateResultLinkGenerator();
        String webserviceUrl = gen.getTabLink(url, populatedTemplate);

        response.setContentType("text/plain");

        PrintStream out;
        try {
            out = new PrintStream(response.getOutputStream());
            out.print(webserviceUrl);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    if (!editQuery && !skipBuilder && !editTemplate && exportTemplate(request)) {
        SessionMethods.loadQuery(populatedTemplate, request.getSession(), response);
        return mapping.findForward("export");
    }

    if (!editQuery && !skipBuilder && !editTemplate && codeGenTemplate(request)) {
        SessionMethods.loadQuery(populatedTemplate, request.getSession(), response);
        return new ForwardParameters(mapping.findForward("codeGen"))
                .addParameter("method", request.getParameter("actionType"))
                .addParameter("source", "templateQuery").forward();
    }

    // We're editing the query: load as a PathQuery
    if (!skipBuilder && !editTemplate) {
        SessionMethods.loadQuery(new PathQuery(populatedTemplate), request.getSession(), response);
        session.setAttribute("templateName", populatedTemplate.getName());
        session.removeAttribute(Constants.NEW_TEMPLATE);
        session.removeAttribute(Constants.EDITING_TEMPLATE);
        form.reset(mapping, request);
        return mapping.findForward("query");
    } else if (editTemplate) {
        // We want to edit the template: Load the query as a TemplateQuery
        // Don't care about the form
        // Reload the initial template
        session.removeAttribute(Constants.NEW_TEMPLATE);
        session.setAttribute(Constants.EDITING_TEMPLATE, Boolean.TRUE);
        if (template == null) {
            recordMessage(new ActionMessage("errors.edittemplate.empty"), request);
            return mapping.findForward("template");
        }
        SessionMethods.loadQuery(template, request.getSession(), response);
        if (!template.isValid()) {
            recordError(new ActionMessage("errors.template.badtemplate",
                    StringUtil.prettyList(template.verifyQuery())), request);
        }

        return mapping.findForward("query");
    }

    // Otherwise show the results: load the modified query from the template
    if (saveQuery) {
        SessionMethods.loadQuery(populatedTemplate, request.getSession(), response);
    }
    form.reset(mapping, request);

    String qid = SessionMethods.startQueryWithTimeout(request, saveQuery, populatedTemplate);
    Thread.sleep(200);

    //tracks the template execution
    im.getTrackerDelegate().trackTemplate(populatedTemplate.getName(), profile, session.getId());

    String trail = "";
    // only put query on the trail if we are saving the query
    // otherwise its a "super top secret" query, e.g. quick search
    // also, note we are not saving any previous trails. trail resets at
    // queries and bags
    if (saveQuery) {
        trail = "|query";
    } else {
        trail = "";
        // session.removeAttribute(Constants.QUERY);
    }

    return new ForwardParameters(mapping.findForward("waiting")).addParameter("qid", qid)
            .addParameter("trail", trail).forward();
}