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:com.blackducksoftware.tools.nrt.generator.NRTReportGenerator.java

private void writeOutLicenseText(String componentName, PrintStream outputTextFile) {
    try {/*from  ww  w . j a va2 s  .c o m*/
        outputTextFile.println();
        outputTextFile.println("License texts (" + (componentMap.get(componentName).getLicenses() != null
                ? componentMap.get(componentName).getLicenses().size()
                : "0") + ")");

        int licenseCounter = 0;
        if (componentMap.get(componentName).getLicenses() != null) {

            for (LicenseModel license : componentMap.get(componentName).getLicenseModels()) {

                String licenseName = license.getName() != null
                        ? license.getName() + "(Taken from KnowledgeBase)"
                        : "license_" + licenseCounter + "(Taken from scanned file)";

                if (nrtConfig.isTextFileOutput()) {
                    outputTextFile.println();
                    outputTextFile.println(
                            "==========================================================================");
                    outputTextFile.println(licenseName);
                    outputTextFile.print(StringEscapeUtils.unescapeHtml(Jsoup.clean(license.getText(), "",
                            Whitelist.none(), new Document.OutputSettings().prettyPrint(false))));
                }
                licenseCounter++;
            } // for all licenses
        } // if licenses exist

    } catch (Exception e) {
        log.error("Error writing out licenses", e);
    }
}

From source file:org.artifactory.cli.common.StreamMasker.java

/**
 * Constructor/* w  ww  . j a v a2  s . co m*/
 *
 * @param out    A given output stream
 * @param prompt The prompt to display on the given output
 * @throws IllegalArgumentException Might occur when given null or illegal inputs and utils
 */
public StreamMasker(PrintStream out, String prompt) throws IllegalArgumentException {
    if (out == null) {
        throw new IllegalArgumentException("Output stream cannot be nul.");
    }
    if (prompt == null) {
        throw new IllegalArgumentException("Prompt to display on output cannot be null");
    }
    if (prompt.contains("\n")) {
        throw new IllegalArgumentException("Prompt cannot contain the new line ('\\n') char");
    }
    if (prompt.contains("\r")) {
        throw new IllegalArgumentException("prompt cannot contain the carriage return ('\\r') char");
    }
    this.out = out;
    setCursorToStart = "\r";
    promptOverwrite =
            // sets cursor back to beginning of line:
            setCursorToStart +
            // writes prompt
                    prompt +
                    // writes 10 blanks beyond the prompt to mask out any input
                    TEN_BLANKS +
                    // sets cursor back to beginning of line
                    setCursorToStart +
                    //writes prompt again; the cursor will now be positioned immediately after prompt
                    prompt;

    // ensure that is written at least once
    out.print(promptOverwrite);
}

From source file:com.analog.lyric.dimple.solvers.core.parameterizedMessages.MultivariateNormalParameters.java

@Override
public void print(PrintStream out, int verbosity) {
    if (verbosity < 0) {
        return;/* w  ww .ja  v  a  2  s  .com*/
    }

    String vectorLabel = "mean";
    double[] vector = _mean;
    if (vector.length == 0) {
        vector = _infoVector;
        vectorLabel = "info";
    }

    out.print("Normal(");

    if (verbosity > 1) {
        out.println();
        out.print("    ");
    }
    out.format("%s=[", vectorLabel);
    for (int i = 0, end = vector.length; i < end; ++i) {
        if (i > 0) {
            out.print(',');
            if (verbosity > 0) {
                out.print(' ');
            }
        }
        if (verbosity > 0) {
            out.format("%d=", i);
        }
        out.format(verbosity > 1 ? "%.12g" : "%g", vector[i]);
    }
    out.print(']');
    if (verbosity > 1) {
        out.println();
    } else {
        out.print(", ");
    }

    out.print(_isInInformationForm ? "precision=[" : "covariance=[");

    if (isDiagonal()) {
        double[] diagonal = _isInInformationForm ? _precision : _variance;

        for (int i = 0, end = diagonal.length; i < end; ++i) {
            if (i > 0) {
                out.print(',');
                if (verbosity > 0) {
                    out.print(' ');
                }
            }
            if (verbosity > 0) {
                out.format("%d=", i);
            }
            out.format("%g", diagonal[i]);
        }
    } else {
        final int n = _matrix.length;
        for (int row = 0; row < n; ++row) {
            if (row > 0) {
                out.print(";");
            }
            out.print("\n        ");
            for (int col = 0; col < n; ++col) {
                if (col > 0) {
                    out.print(',');
                }
                out.format("%g", _matrix[row][col]);
            }
        }
    }

    out.print(']');

    if (verbosity > 1) {
        out.println();
    }
    out.print(')');
}

From source file:de.juwimm.cms.model.EditionHbmDaoImpl.java

@SuppressWarnings("unchecked")
@Override//  w w  w .  j av  a  2  s  .  com
protected void handleDocumentsToXmlRecursive(Integer unitId, Integer siteId, PrintStream out,
        boolean includeUnused, EditionHbm edition) throws Exception {
    // TODO: if searchIndex is reliable only linked documents should be included in edition
    includeUnused = true;
    out.println("\t<documents>");
    try {
        if (unitId == null) {
            Collection<UnitHbm> units = getUnitHbmDao().findAll(siteId);
            for (UnitHbm unit : units) {
                Collection<DocumentHbm> docs = getDocumentHbmDao().findAllPerUnit(unit.getUnitId());
                for (DocumentHbm doc : docs) {
                    if (!includeUnused && doc.getUseCountPublishVersion() == 0)
                        continue;
                    out.print(getDocumentHbmDao().toXml(doc.getDocumentId(), 2, true));
                }
            }
        } else {
            if (unitId == -1)
                unitId = getSiteHbmDao().load(siteId).getRootUnit().getUnitId();
            Collection<DocumentHbm> docs = getDocumentHbmDao().findAllPerUnit(unitId);
            for (DocumentHbm doc : docs) {
                if (!includeUnused && doc.getUseCountPublishVersion() == 0)
                    continue;
                out.print(getDocumentHbmDao().toXml(doc.getDocumentId(), 2, true));
            }
        }
    } catch (Exception exe) {
        log.error("Error occured", exe);
    }
    out.println("\t</documents>");
}

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

/**
 * Perform the split transcripts mode./*from  w  w w. j a va  2 s  .  com*/
 *
 * @throws IOException error reading / writing
 */
@Override
public void execute() throws IOException {
    // Load the gene to transcripts file
    if (!config.validate()) {
        throw new IOException("Invalid SplitTranscripts configuration");
    }
    final GeneTranscriptRelationships gtr = new GeneTranscriptRelationships();
    final IndexedIdentifier transcriptIdents = new IndexedIdentifier();
    final Int2ObjectMap<MutableString> transcriptIndexToIdMap = new Int2ObjectOpenHashMap<MutableString>();
    final List<FastXEntry> fastxEntries = new LinkedList<FastXEntry>();
    //
    // Pass through the file once to collect the transcript - gene relationships
    //
    int entryCount = 0;
    try {
        for (final FastXEntry entry : new FastXReader(config.getInputFile())) {
            entryCount++;
            parseHeader(entry.getEntryHeader());
            final MutableString transcriptId = transcriptHeader.get("transcriptId");
            final MutableString geneId = transcriptHeader.get("geneId");

            final int transcriptIndex = transcriptIdents.registerIdentifier(transcriptId);
            gtr.addRelationship(geneId, transcriptIndex);

            transcriptIndexToIdMap.put(transcriptIndex, transcriptId);

            fastxEntries.add(entry.clone());
        }
    } catch (CloneNotSupportedException e) {
        LOG.error("Couldn't clone for some reason", e);
        throw new GobyRuntimeException("Couldn't clone for some reason", e);
    }

    LOG.info("Loading map of genes-transcripts complete.");

    //
    // Scan through the transcript-gene relationships to determine which
    // transcript id goes into which file
    //
    final Int2IntMap transcriptIndex2FileIndex = new Int2IntOpenHashMap();
    final String configOutputFilename = config.getOutputBase() + ".config";
    final String configOutputPath = FilenameUtils.getFullPath(configOutputFilename);
    if (StringUtils.isNotBlank(configOutputPath)) {
        LOG.info("Creating output directory: " + configOutputPath);
        FileUtils.forceMkdir(new File(configOutputPath));
    }

    PrintWriter configOutput = null;
    try {
        configOutput = new PrintWriter(configOutputFilename);
        configOutput.println("Ensembl Gene ID\tEnsembl Transcript ID");

        final Int2IntMap fileIndex2NumberOfEntries = new Int2IntOpenHashMap();
        fileIndex2NumberOfEntries.defaultReturnValue(0);
        transcriptIndex2FileIndex.defaultReturnValue(-1);

        final int initialNumberOfFiles = getNumberOfFiles(gtr, transcriptIndex2FileIndex);

        for (int geneIndex = 0; geneIndex < gtr.getNumberOfGenes(); geneIndex++) {
            final MutableString geneId = gtr.getGeneId(geneIndex);
            final IntSet transcriptIndices = gtr.getTranscriptSet(geneIndex);
            int fileNum = 0;

            for (final int transcriptIndex : transcriptIndices) {
                if (transcriptIndex2FileIndex.get(transcriptIndex) != -1) {
                    LOG.warn("Skipping repeated transcriptIndex: " + transcriptIndex);
                    continue;
                }
                final int maxEntriesPerFile = config.getMaxEntriesPerFile();
                final int numberOfEntriesInOriginalBucket = fileIndex2NumberOfEntries.get(fileNum);
                final int adjustedFileIndex = fileNum
                        + initialNumberOfFiles * (numberOfEntriesInOriginalBucket / maxEntriesPerFile);

                transcriptIndex2FileIndex.put(transcriptIndex, adjustedFileIndex);
                fileIndex2NumberOfEntries.put(fileNum, fileIndex2NumberOfEntries.get(fileNum) + 1);
                final MutableString transcriptId = transcriptIndexToIdMap.get(transcriptIndex);
                configOutput.printf("%s\t%s%n", geneId, transcriptId);

                fileNum++;
            }
        }
    } finally {
        IOUtils.closeQuietly(configOutput);
    }

    final int numFiles = getFileIndices(transcriptIndex2FileIndex).size();
    if (LOG.isInfoEnabled()) {
        LOG.info(NumberFormat.getInstance().format(entryCount) + " entries will be written to " + numFiles
                + " files");
        final int maxEntriesPerFile = config.getMaxEntriesPerFile();
        if (maxEntriesPerFile < Integer.MAX_VALUE) {
            LOG.info("Each file will contain at most " + maxEntriesPerFile + " entries");
        }
    }

    // formatter for uniquely numbering files each with the same number of digits
    final NumberFormat fileNumberFormatter = getNumberFormatter(numFiles - 1);

    final ProgressLogger progressLogger = new ProgressLogger();
    progressLogger.expectedUpdates = entryCount;
    progressLogger.itemsName = "entries";
    progressLogger.start();

    // Write each file one at a time rather than in the order they appear in the input file
    // to avoid the issue of having too many streams open at the same or continually opening
    // and closing streams which is quite costly.  We could store the gene/transcripts in
    // memory and then just write the files at the end but that could be worse.
    for (final int fileIndex : getFileIndices(transcriptIndex2FileIndex)) {
        final String filename = config.getOutputBase() + "." + fileNumberFormatter.format(fileIndex) + ".fa.gz";
        PrintStream printStream = null;
        try {
            // each file is compressed
            printStream = new PrintStream(new GZIPOutputStream(new FileOutputStream(filename)));

            //
            // Read through the input file get the actual sequence information
            //
            final Iterator<FastXEntry> entries = fastxEntries.iterator();
            while (entries.hasNext()) {
                final FastXEntry entry = entries.next();
                parseHeader(entry.getEntryHeader());
                final MutableString transcriptId = transcriptHeader.get("transcriptId");
                final MutableString geneId = transcriptHeader.get("geneId");
                final int transcriptIndex = transcriptIdents.getInt(transcriptId);
                final int transcriptFileIndex = transcriptIndex2FileIndex.get(transcriptIndex);
                if (transcriptFileIndex == fileIndex) {
                    printStream.print(entry.getHeaderSymbol());
                    printStream.print(transcriptId);
                    printStream.print(" gene:");
                    printStream.println(geneId);
                    printStream.println(entry.getEntrySansHeader());
                    entries.remove();
                    progressLogger.lightUpdate();
                }
            }
        } finally {
            IOUtils.closeQuietly(printStream);
        }
    }

    assert progressLogger.count == entryCount : "Some entries were not processed!";
    progressLogger.done();
}

From source file:org.apache.jackrabbit.core.ItemManager.java

/**
 * {@inheritDoc}//from w w  w .j  a va2 s  .c o m
 */
public synchronized void dump(PrintStream ps) {
    ps.println("ItemManager (" + this + ")");
    ps.println();
    ps.println("Items in cache:");
    ps.println();
    synchronized (itemCache) {
        for (ItemId id : itemCache.keySet()) {
            ItemData item = itemCache.get(id);
            if (item.isNode()) {
                ps.print("Node: ");
            } else {
                ps.print("Property: ");
            }
            if (item.getState().isTransient()) {
                ps.print("transient ");
            } else {
                ps.print("          ");
            }
            ps.println(id + "\t" + safeGetJCRPath(id) + " (" + item + ")");
        }
    }
}

From source file:com.appeligo.search.actions.ResponseReportAction.java

public String execute() throws Exception {
    long timestamp = new Date().getTime();
    String day = Utils.getDatePath(timestamp);
    String hostname = null;/*from   w w w. j a  v  a2s. c  om*/
    try {
        hostname = InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
        hostname = "UnknownHost";
    }
    String dirname = documentRoot + "/stats/" + day + "/" + hostname;
    String responseFileName = dirname + "/response-" + reporter + ".html";
    try {
        File dir = new File(dirname);
        if ((!dir.exists()) && (!dir.mkdirs())) {
            throw new IOException("Error creating directory " + dirname);
        }
        File file = new File(responseFileName);
        PrintStream responseFile = null;
        if (file.exists()) {
            responseFile = new PrintStream(new FileOutputStream(responseFileName, true));
        } else {
            responseFile = new PrintStream(new FileOutputStream(responseFileName));
            String title = "Response Times for " + getServletRequest().getServerName() + " to " + reporter;
            responseFile.println("<html><head><title>" + title + "</title></head>");
            responseFile.println("<body><h1>" + title + "</h1>");
            responseFile.println("<table border='1'>");
            responseFile.println("<tr>");
            responseFile.println("<th>Time (UTC)</th>");
            responseFile.println("<th>Response (Millis)</th>");
            responseFile.println("<th>Status</th>");
            responseFile.println("<th>Bytes Read</th>");
            responseFile.println("<th>Timed Out</th>");
            responseFile.println("<th>Exception</th>");
            responseFile.println("</tr>");
        }
        Calendar cal = Calendar.getInstance();
        cal.setTimeZone(TimeZone.getTimeZone("GMT"));
        cal.setTimeInMillis(timestamp);
        String time = String.format("%1$tH:%1$tM:%1$tS", cal);
        responseFile.print("<tr>");
        responseFile.print("<td>" + time + "</td>");
        responseFile.format("<td>%,d</td>", responseMillis);
        responseFile.print("<td>" + status + "</td>");
        responseFile.format("<td>%,d</td>", bytesRead);
        responseFile.print("<td>" + timedOut + "</td>");
        responseFile.print("<td>" + exception + "</td>");
        responseFile.println("</tr>");
    } catch (IOException e) {
        log.error("Error opening or writing to " + responseFileName, e);
    }

    return SUCCESS;
}

From source file:de.hasait.clap.CLAP.java

public void printHelp(final PrintStream pPrintStream) {
    final Map<CLAPHelpCategoryImpl, Set<CLAPHelpNode>> nodes = new TreeMap<CLAPHelpCategoryImpl, Set<CLAPHelpNode>>();
    _root.collectHelpNodes(nodes, null);

    int maxLength = 0;
    for (final Entry<CLAPHelpCategoryImpl, Set<CLAPHelpNode>> entry : nodes.entrySet()) {
        for (final CLAPHelpNode node : entry.getValue()) {
            final int length = node.getHelpID().length();
            if (length > maxLength) {
                maxLength = length;//ww w  . j  a v a2s .c  o  m
            }
        }
    }
    maxLength += 6; // space to description

    for (final Entry<CLAPHelpCategoryImpl, Set<CLAPHelpNode>> entry : nodes.entrySet()) {
        pPrintStream.println();
        pPrintStream.println(nls(entry.getKey().getTitleNLSKey()));
        for (final CLAPHelpNode node : entry.getValue()) {
            pPrintStream.println();
            pPrintStream.print("  "); //$NON-NLS-1$
            pPrintStream.print(StringUtils.rightPad(node.getHelpID(), maxLength - 2));
            final String descriptionNLSKey = node.getDescriptionNLSKey();
            if (descriptionNLSKey != null) {
                pPrintStream.println(nls(descriptionNLSKey));
            } else {
                pPrintStream.println();
            }
        }
    }
}

From source file:org.apache.jackrabbit.core.SessionImpl.java

/**
 * {@inheritDoc}/*from   ww w  . ja v a2s  . c o  m*/
 */
public void dump(PrintStream ps) {
    ps.print("Session: ");
    if (userId == null) {
        ps.print("unknown");
    } else {
        ps.print(userId);
    }
    ps.println(" (" + this + ")");
    ps.println();
    itemMgr.dump(ps);
    ps.println();
    itemStateMgr.dump(ps);
}

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

private void tallyPosition(final RandomAccessSequenceCache cache, final int referenceIndex, final int position,
        final double foldChange, final int windowSize, final int referenceSize, final String referenceId,
        final PrintStream out, final int countA, final int countB, final double sumA, final double sumB) {
    int minPosition = position - windowSize;
    int maxPosition = position + windowSize;
    if (minPosition < 0) {
        minPosition = 0;//w  w w.  j av  a  2  s .  c  o m
    }
    if (maxPosition >= referenceSize) {
        maxPosition = referenceSize - 2;
    }
    final MutableString buffer = new MutableString();
    buffer.append(position);
    buffer.append('\t');
    buffer.append(referenceId);
    buffer.append('\t');
    for (int i = position - windowSize; i < position + windowSize; i++) {
        final char base;
        if (i >= minPosition && i <= maxPosition) {
            base = cache.get(referenceIndex, i);
        } else {
            base = '-';
        }

        buffer.append(base);
        buffer.append('\t');

    }
    buffer.append(foldChange);
    buffer.append('\t');
    buffer.append(countA);
    buffer.append('\t');
    buffer.append(countB);
    buffer.append('\t');
    buffer.append(sumA);
    buffer.append('\t');
    buffer.append(sumB);
    buffer.append('\n');
    out.print(buffer);
}