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:ClassFile.java

/**
 * Write out a text version of this class.
 *//*ww  w. jav a2s . c  o  m*/
public void display(PrintStream ps) throws Exception {
    int i;
    String myClassName;
    String mySuperClassName;
    String packageName = null;

    if (!isValidClass) {
        ps.println("Not a valid class");
    }

    myClassName = printClassName(thisClass.arg1.strValue);
    mySuperClassName = printClassName(superClass.arg1.strValue);
    if (myClassName.indexOf('.') > 0) {
        packageName = myClassName.substring(0, myClassName.lastIndexOf('.'));
        myClassName = myClassName.substring(myClassName.lastIndexOf('.') + 1);
        ps.println("package " + packageName + "\n");
    }

    for (i = 1; i < constantPool.length; i++) {
        if (constantPool[i] == null)
            continue;
        if ((constantPool[i] == thisClass) || (constantPool[i] == superClass))
            continue;
        if (constantPool[i].type == ConstantPoolInfo.CLASS) {
            String s = constantPool[i].arg1.strValue;
            if (s.charAt(0) == '[')
                continue;
            s = printClassName(constantPool[i].arg1.strValue);
            if ((packageName != null) && (s.startsWith(packageName)))
                continue;
            ps.println("import " + printClassName(s) + ";");
        }
    }
    ps.println();
    ps.println("/*");
    DataInputStream dis;
    ConstantPoolInfo cpi;

    if (attributes != null) {
        ps.println(" * This class has " + attributes.length + " optional class attributes.");
        ps.println(" * These attributes are: ");
        for (i = 0; i < attributes.length; i++) {
            String attrName = attributes[i].name.strValue;
            dis = new DataInputStream(new ByteArrayInputStream(attributes[i].data));

            ps.println(" * Attribute " + (i + 1) + " is of type " + attributes[i].name);
            if (attrName.compareTo("SourceFile") == 0) {
                cpi = null;
                try {
                    cpi = constantPool[dis.readShort()];
                } catch (IOException e) {
                }
                ps.println(" *  SourceFile : " + cpi);
            } else {
                ps.println(" *  TYPE (" + attrName + ")");
            }
        }
    } else {
        ps.println(" * This class has NO optional class attributes.");
    }
    ps.println(" */\n");
    ps.print(accessString(accessFlags) + "class " + myClassName + " extends " + mySuperClassName);
    if (interfaces != null) {
        ps.print(" implements ");
        for (i = 0; i < interfaces.length - 1; i++) {
            ps.print(interfaces[i].arg1.strValue + ", ");
        }
        ps.print(interfaces[interfaces.length - 1].arg1.strValue);
    }
    ps.println(" {\n");
    if (fields != null) {
        ps.println("/* Instance Variables */");
        for (i = 0; i < fields.length; i++) {
            ps.println("    " + fields[i].toString(constantPool) + ";");
        }
    }

    if (methods != null) {
        ps.println("\n/* Methods */");
        for (i = 0; i < methods.length; i++) {
            ps.println("    " + methods[i].toString(myClassName));
        }
    }
    ps.println("\n}");
}

From source file:com.opengamma.analytics.financial.model.volatility.local.LocalVolatilityPDEGreekCalculator.java

/**
 * bumped each input volatility by 1bs and record the effect on the representative point by following the chain
 * of refitting the implied volatility surface, the local volatility surface and running the backwards PDE solver
 * @param ps Print Stream//  www  .jav  a  2 s. c om
 * @param option test option
 */
public void bucketedVegaBackwardsPDE(final PrintStream ps, final EuropeanVanillaOption option) {

    final int n = _marketData.getNumExpiries();
    final double[][] strikes = _marketData.getStrikes();
    final double forward = _marketData.getForwardCurve().getForward(option.getTimeToExpiry());
    final double maxFwd = 3.5 * Math.max(option.getStrike(), forward);
    final PDEResults1D pdeRes = runBackwardsPDESolver(option.getStrike(), _localVolatilityStrike,
            option.isCall(), _theta, option.getTimeToExpiry(), maxFwd, _timeSteps, _spaceSteps,
            _timeGridBunching, _spaceGridBunching, option.getStrike());

    final double exampleVol;
    final double[] fwdNodes = pdeRes.getGrid().getSpaceNodes();
    int index = getLowerBoundIndex(fwdNodes, forward);
    if (index >= 1) {
        index--;
    }
    if (index >= _spaceSteps - 1) {
        index--;
        if (index >= _spaceSteps - 1) {
            index--;
        }
    }
    final double[] vols = new double[4];
    final double[] fwds = new double[4];
    System.arraycopy(fwdNodes, index, fwds, 0, 4);
    for (int i = 0; i < 4; i++) {
        vols[i] = BlackFormulaRepository.impliedVolatility(pdeRes.getFunctionValue(index + i), fwds[i],
                option.getStrike(), option.getTimeToExpiry(), option.isCall());
    }
    Interpolator1DDoubleQuadraticDataBundle db = INTERPOLATOR_1D.getDataBundle(fwds, vols);
    exampleVol = INTERPOLATOR_1D.interpolate(db, forward);

    final double shiftAmount = 1e-4; //1bps

    final double[][] res = new double[n][];

    for (int i = 0; i < n; i++) {
        final int m = strikes[i].length;
        res[i] = new double[m];
        for (int j = 0; j < m; j++) {
            final BlackVolatilitySurfaceMoneyness bumpedSurface = _surfaceFitter
                    .getBumpedVolatilitySurface(_marketData, i, j, shiftAmount);
            final LocalVolatilitySurfaceStrike bumpedLV = LocalVolatilitySurfaceConverter
                    .toStrikeSurface(DUPIRE.getLocalVolatility(bumpedSurface));
            final PDEResults1D pdeResBumped = runBackwardsPDESolver(option.getStrike(), bumpedLV,
                    option.isCall(), _theta, option.getTimeToExpiry(), maxFwd, _timeSteps, _spaceSteps,
                    _timeGridBunching, _spaceGridBunching, option.getStrike());
            for (int k = 0; k < 4; k++) {
                vols[k] = BlackFormulaRepository.impliedVolatility(pdeResBumped.getFunctionValue(index + k),
                        fwds[k], option.getStrike(), option.getTimeToExpiry(), option.isCall());
            }
            db = INTERPOLATOR_1D.getDataBundle(fwds, vols);
            final double vol = INTERPOLATOR_1D.interpolate(db, forward);
            res[i][j] = (vol - exampleVol) / shiftAmount;
        }
    }

    for (int i = 0; i < n; i++) {
        //     System.out.print(TENORS[i] + "\t");
        final int m = strikes[i].length;
        for (int j = 0; j < m; j++) {
            ps.print(res[i][j] + "\t");
        }
        ps.print("\n");
    }
    ps.print("\n");
}

From source file:com.datatorrent.stram.cli.ApexCli.java

private void printHelp(String command, CommandSpec commandSpec, PrintStream os) {
    if (consolePresent) {
        os.print(getHighlightColor());
        os.print(command);/*from ww  w.  ja v  a 2 s.co m*/
        os.print(COLOR_RESET);
    } else {
        os.print(command);
    }
    if (commandSpec instanceof OptionsCommandSpec) {
        OptionsCommandSpec ocs = (OptionsCommandSpec) commandSpec;
        if (ocs.options != null) {
            os.print(" [options]");
        }
    }
    if (commandSpec.requiredArgs != null) {
        for (Arg arg : commandSpec.requiredArgs) {
            if (consolePresent) {
                os.print(" " + ITALICS + arg + COLOR_RESET);
            } else {
                os.print(" <" + arg + ">");
            }
        }
    }
    if (commandSpec.optionalArgs != null) {
        for (Arg arg : commandSpec.optionalArgs) {
            if (consolePresent) {
                os.print(" [" + ITALICS + arg + COLOR_RESET);
            } else {
                os.print(" [<" + arg + ">");
            }
            if (arg instanceof VarArg) {
                os.print(" ...");
            }
            os.print("]");
        }
    }
    os.println("\n\t" + commandSpec.description);
    if (commandSpec instanceof OptionsCommandSpec) {
        OptionsCommandSpec ocs = (OptionsCommandSpec) commandSpec;
        if (ocs.options != null) {
            os.println("\tOptions:");
            HelpFormatter formatter = new HelpFormatter();
            PrintWriter pw = new PrintWriter(os);
            formatter.printOptions(pw, 80, ocs.options, 12, 4);
            pw.flush();
        }
    }
}

From source file:org.cesecore.util.CertTools.java

/**
 * Reads certificates in PEM-format from an InputStream. 
 * The stream may contain other things between the different certificates.
 * /*from   w w w  .j  a  v a2 s .  com*/
 * @param certstream the input stream containing the certificates in PEM-format
 * @return Ordered List of Certificates, first certificate first, or empty List
 * @exception CertificateParsingException if the stream contains an incorrect certificate.
 */
public static List<Certificate> getCertsFromPEM(InputStream certstream) throws CertificateParsingException {
    if (log.isTraceEnabled()) {
        log.trace(">getCertfromPEM");
    }
    ArrayList<Certificate> ret = new ArrayList<Certificate>();
    String beginKeyTrust = "-----BEGIN TRUSTED CERTIFICATE-----";
    String endKeyTrust = "-----END TRUSTED CERTIFICATE-----";
    BufferedReader bufRdr = null;
    ByteArrayOutputStream ostr = null;
    PrintStream opstr = null;
    try {
        try {
            bufRdr = new BufferedReader(new InputStreamReader(certstream));
            while (bufRdr.ready()) {
                ostr = new ByteArrayOutputStream();
                opstr = new PrintStream(ostr);
                String temp;
                while ((temp = bufRdr.readLine()) != null
                        && !(temp.equals(CertTools.BEGIN_CERTIFICATE) || temp.equals(beginKeyTrust))) {
                    continue;
                }
                if (temp == null) {
                    if (ret.isEmpty()) {
                        // There was no certificate in the file
                        throw new CertificateParsingException("Error in " + certstream.toString() + ", missing "
                                + CertTools.BEGIN_CERTIFICATE + " boundary");
                    } else {
                        // There were certificates, but some blank lines or something in the end
                        // anyhow, the file has ended so we can break here.
                        break;
                    }
                }
                while ((temp = bufRdr.readLine()) != null
                        && !(temp.equals(CertTools.END_CERTIFICATE) || temp.equals(endKeyTrust))) {
                    opstr.print(temp);
                }
                if (temp == null) {
                    throw new IllegalArgumentException("Error in " + certstream.toString() + ", missing "
                            + CertTools.END_CERTIFICATE + " boundary");
                }
                opstr.close();

                byte[] certbuf = Base64.decode(ostr.toByteArray());
                ostr.close();
                // Phweeew, were done, now decode the cert from file back to Certificate object
                Certificate cert = getCertfromByteArray(certbuf);
                ret.add(cert);
            }

        } finally {
            if (bufRdr != null) {
                bufRdr.close();
            }
            if (opstr != null) {
                opstr.close();
            }
            if (ostr != null) {
                ostr.close();
            }
        }
    } catch (IOException e) {
        throw new IllegalStateException(
                "Exception caught when attempting to read stream, see underlying IOException", e);
    }
    if (log.isTraceEnabled()) {
        log.trace("<getcertfromPEM:" + ret.size());
    }
    return ret;
}

From source file:com.github.lindenb.jvarkit.tools.backlocate.BackLocate.java

private void backLocate(PrintStream out, KnownGene gene, String geneName, char aa1, char aa2, int peptidePos1)
        throws IOException {

    final GeneticCode geneticCode = getGeneticCodeByChromosome(gene.getChromosome());
    RNASequence wildRNA = null;/*from   www .j a  v a  2s  .  c  om*/
    ProteinCharSequence wildProt = null;

    if (genomicSeq == null || !gene.getChromosome().equals(genomicSeq.getChrom())) {
        LOG.info("fetch genome");
        this.genomicSeq = new GenomicSequence(this.indexedFastaSequenceFile, gene.getContig());
    }

    if (gene.isPositiveStrand()) {
        int exon_index = 0;
        while (exon_index < gene.getExonCount()) {
            for (int i = gene.getExonStart(exon_index); i < gene.getExonEnd(exon_index); ++i) {
                if (i < gene.getCdsStart())
                    continue;
                if (i >= gene.getCdsEnd())
                    break;

                if (wildRNA == null) {
                    wildRNA = new RNASequence(genomicSeq, '+');
                }

                wildRNA.genomicPositions.add(i);

                if (wildRNA.length() % 3 == 0 && wildRNA.length() > 0 && wildProt == null) {
                    wildProt = new ProteinCharSequence(geneticCode, wildRNA);
                }
            }
            ++exon_index;
        }

    } else // reverse orientation
    {
        int exon_index = gene.getExonCount() - 1;
        while (exon_index >= 0) {
            for (int i = gene.getExonEnd(exon_index) - 1; i >= gene.getExonStart(exon_index); --i) {
                if (i >= gene.getCdsEnd())
                    continue;
                if (i < gene.getCdsStart())
                    break;

                if (wildRNA == null) {
                    wildRNA = new RNASequence(genomicSeq, '-');
                }

                wildRNA.genomicPositions.add(i);
                if (wildRNA.length() % 3 == 0 && wildRNA.length() > 0 && wildProt == null) {
                    wildProt = new ProteinCharSequence(geneticCode, wildRNA);
                }

            }
            --exon_index;
        }

    } //end of if reverse

    if (wildProt == null) {
        stderr().println("#no protein found for transcript:" + gene.getName());
        return;
    }
    int peptideIndex0 = peptidePos1 - 1;
    if (peptideIndex0 >= wildProt.length()) {
        out.println("#index out of range for :" + gene.getName() + " petide length=" + wildProt.length());
        return;
    }

    if (wildProt.charAt(peptideIndex0) != aa1) {
        out.println("##Warning ref aminod acid for " + gene.getName() + "  [" + peptidePos1
                + "] is not the same (" + wildProt.charAt(peptideIndex0) + "/" + aa1 + ")");
    } else {
        out.println("##" + gene.getName());
    }
    int indexesInRNA[] = new int[] { 0 + peptideIndex0 * 3, 1 + peptideIndex0 * 3, 2 + peptideIndex0 * 3 };
    final String wildCodon = "" + wildRNA.charAt(indexesInRNA[0]) + wildRNA.charAt(indexesInRNA[1])
            + wildRNA.charAt(indexesInRNA[2]);
    /* 2015 : adding possible mut codons */
    final Set<String> possibleAltCodons = new HashSet<>();
    final char bases[] = new char[] { 'A', 'C', 'G', 'T' };
    for (int codon_pos = 0; codon_pos < 3; ++codon_pos) {
        StringBuilder sb = new StringBuilder(wildCodon);
        for (char mutBase : bases) {
            sb.setCharAt(codon_pos, mutBase);
            if (geneticCode.translate(sb.charAt(0), sb.charAt(1), sb.charAt(2)) == Character.toUpperCase(aa2)) {
                possibleAltCodons.add(sb.toString());
            }
        }
    }

    for (int indexInRna : indexesInRNA) {
        out.print(geneName);
        out.print('\t');
        out.print(aa1);
        out.print('\t');
        out.print(peptidePos1);
        out.print('\t');
        out.print(aa2);
        out.print('\t');
        out.print(gene.getName());
        out.print('\t');
        out.print(gene.getStrand() == Strand.NEGATIVE ? "-" : "+");
        out.print('\t');
        out.print(wildProt.charAt(peptideIndex0));
        out.print('\t');
        out.print(indexInRna);
        out.print('\t');
        out.print(wildCodon);
        out.print('\t');
        if (possibleAltCodons.isEmpty()) {
            out.print('.');
        } else {
            boolean first = true;
            for (String mutCodon : possibleAltCodons) {
                if (!first)
                    out.print('|');
                first = false;
                out.print(mutCodon);
            }
        }
        out.print('\t');
        out.print(wildRNA.charAt(indexInRna));
        out.print('\t');
        out.print(gene.getChromosome());
        out.print('\t');
        out.print(wildRNA.genomicPositions.get(indexInRna));
        out.print('\t');
        String exonName = null;
        for (KnownGene.Exon exon : gene.getExons()) {
            int genome = wildRNA.genomicPositions.get(indexInRna);
            if (exon.getStart() <= genome && genome < exon.getEnd()) {
                exonName = exon.getName();
                break;
            }
        }
        out.print(exonName);
        if (this.printSequences) {
            String s = wildRNA.toString();
            out.print('\t');
            out.print(s.substring(0, indexInRna) + "[" + s.charAt(indexInRna) + "]"
                    + (indexInRna + 1 < s.length() ? s.substring(indexInRna + 1) : ""));
            s = wildProt.toString();
            out.print('\t');
            out.print(
                    s.substring(0, peptideIndex0) + "[" + aa1 + "/" + aa2 + "/" + wildProt.charAt(peptideIndex0)
                            + "]" + (peptideIndex0 + 1 < s.length() ? s.substring(peptideIndex0 + 1) : ""));
        }
        out.println();
    }
}

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

public void printHTML(Vector<Vector<Object>> result, PrintStream writer) {
    // variables for computing iterative harmonic means
    int expected = 0; // expected so far
    int foundVect[]; // found so far
    double symVect[]; // symmetric similarity
    double effVect[]; // effort-based similarity
    double precOrVect[]; // precision-oriented similarity
    double recOrVect[]; // recall-oriented similarity

    fsize = format.length();//from w w  w .  j a v a 2s  .  c  o  m
    try {
        Formatter formatter = new Formatter(writer);
        // Print the header
        writer.println("<html><head></head><body>");
        writer.println("<table border='2' frame='sides' rules='groups'>");
        writer.println("<colgroup align='center' />");
        // for each algo <td spancol='2'>name</td>
        for (String m : listAlgo) {
            writer.println("<colgroup align='center' span='" + 2 * fsize + "' />");
        }
        // For each file do a
        writer.println("<thead valign='top'><tr><th>algo</th>");
        // for each algo <td spancol='2'>name</td>
        for (String m : listAlgo) {
            writer.println("<th colspan='" + ((2 * fsize)) + "'>" + m + "</th>");
        }
        writer.println("</tr></thead><tbody><tr><td>test</td>");
        // for each algo <td>Prec.</td><td>Rec.</td>
        for (String m : listAlgo) {
            for (int i = 0; i < fsize; i++) {
                if (format.charAt(i) == 's') {
                    writer.println("<td colspan='2'><center>Symmetric</center></td>");
                } else if (format.charAt(i) == 'e') {
                    writer.println("<td colspan='2'><center>Effort</center></td>");
                } else if (format.charAt(i) == 'p') {
                    writer.println("<td colspan='2'><center>Prec. orient.</center></td>");
                } else if (format.charAt(i) == 'r') {
                    writer.println("<td colspan='2'><center>Rec. orient.</center></td>");
                }
            }
            //writer.println("<td>Prec.</td><td>Rec.</td>");
        }
        writer.println("</tr></tbody><tbody>");
        foundVect = new int[size];
        symVect = new double[size];
        effVect = new double[size];
        precOrVect = new double[size];
        recOrVect = new double[size];
        for (int k = size - 1; k >= 0; k--) {
            foundVect[k] = 0;
            symVect[k] = 0.;
            effVect[k] = 0.;
            precOrVect[k] = 0.;
            recOrVect[k] = 0.;
        }
        // </tr>
        // For each directory <tr>
        boolean colored = false;
        for (Vector<Object> test : result) {
            int nexpected = -1;
            if (colored == true && color != null) {
                colored = false;
                writer.println("<tr bgcolor=\"" + color + "\">");
            } else {
                colored = true;
                writer.println("<tr>");
            }
            ;
            // Print the directory <td>bla</td>
            writer.println("<td>" + (String) test.get(0) + "</td>");
            // For each record print the values <td>bla</td>
            Enumeration<Object> f = test.elements();
            f.nextElement();
            for (int k = 0; f.hasMoreElements(); k++) {
                ExtPREvaluator eval = (ExtPREvaluator) f.nextElement();
                if (eval != null) {
                    // iterative H-means computation
                    if (nexpected == -1) {
                        nexpected = eval.getExpected();
                        expected += nexpected;
                    }
                    // If foundVect is -1 then results are invalid
                    if (foundVect[k] != -1)
                        foundVect[k] += eval.getFound();
                    for (int i = 0; i < fsize; i++) {
                        writer.print("<td>");
                        if (format.charAt(i) == 's') {
                            formatter.format("%1.2f", eval.getSymPrecision());
                            writer.print("</td><td>");
                            formatter.format("%1.2f", eval.getSymRecall());
                            symVect[k] += eval.getSymSimilarity();
                        } else if (format.charAt(i) == 'e') {
                            formatter.format("%1.2f", eval.getEffPrecision());
                            writer.print("</td><td>");
                            formatter.format("%1.2f", eval.getEffRecall());
                            effVect[k] += eval.getEffSimilarity();
                        } else if (format.charAt(i) == 'p') {
                            formatter.format("%1.2f", eval.getPrecisionOrientedPrecision());
                            writer.print("</td><td>");
                            formatter.format("%1.2f", eval.getPrecisionOrientedRecall());
                            precOrVect[k] += eval.getPrecisionOrientedSimilarity();
                        } else if (format.charAt(i) == 'r') {
                            formatter.format("%1.2f", eval.getRecallOrientedPrecision());
                            writer.print("</td><td>");
                            formatter.format("%1.2f", eval.getRecallOrientedRecall());
                            recOrVect[k] += eval.getRecallOrientedSimilarity();
                        }
                        writer.print("</td>");
                    }
                } else {
                    for (int i = 0; i < fsize; i++)
                        writer.print("<td>n/a</td>");
                }
            }
            writer.println("</tr>");
        }
        writer.print("<tr bgcolor=\"yellow\"><td>H-mean</td>");
        int k = 0;
        for (String m : listAlgo) {
            if (foundVect[k] != -1) {
                for (int i = 0; i < fsize; i++) {
                    writer.print("<td>");
                    if (format.charAt(i) == 's') {
                        formatter.format("%1.2f", symVect[k] / foundVect[k]);
                        writer.print("</td><td>");
                        formatter.format("%1.2f", symVect[k] / expected);
                    } else if (format.charAt(i) == 'e') {
                        formatter.format("%1.2f", effVect[k] / foundVect[k]);
                        writer.print("</td><td>");
                        formatter.format("%1.2f", effVect[k] / expected);
                    } else if (format.charAt(i) == 'p') {
                        formatter.format("%1.2f", precOrVect[k] / foundVect[k]);
                        writer.print("</td><td>");
                        formatter.format("%1.2f", precOrVect[k] / expected);
                    } else if (format.charAt(i) == 'r') {
                        formatter.format("%1.2f", recOrVect[k] / foundVect[k]);
                        writer.print("</td><td>");
                        formatter.format("%1.2f", recOrVect[k] / expected);
                    }
                    writer.println("</td>");
                }
            } else {
                writer.println("<td colspan='2'><center>Error</center></td>");
            }
            //};
            k++;
        }
        writer.println("</tr>");
        writer.println("</tbody></table>");
        writer.println("<p><small>n/a: result alignment not provided or not readable<br />");
        writer.println("NaN: division per zero, likely due to empty alignent.</small></p>");
        writer.println("</body></html>");
    } catch (Exception ex) {
        logger.debug("IGNORED Exception", ex);
    } finally {
        writer.flush();
        writer.close();
    }
}

From source file:MailHandlerDemo.java

/**
 * Used debug problems with the logging.properties. The system property
 * java.security.debug=access,stack can be used to trace access to the
 * LogManager reset./*from ww w  . j  av  a  2  s.c o  m*/
 *
 * @param prefix a string to prefix the output.
 * @param err any PrintStream or null for System.out.
 */
@SuppressWarnings("UseOfSystemOutOrSystemErr")
private static void checkConfig(String prefix, PrintStream err) {
    if (prefix == null || prefix.trim().length() == 0) {
        prefix = "DEBUG";
    }

    if (err == null) {
        err = System.out;
    }

    try {
        err.println(prefix + ": java.version=" + System.getProperty("java.version"));
        err.println(prefix + ": LOGGER=" + LOGGER.getLevel());
        err.println(prefix + ": JVM id " + ManagementFactory.getRuntimeMXBean().getName());
        err.println(prefix + ": java.security.debug=" + System.getProperty("java.security.debug"));
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            err.println(prefix + ": SecurityManager.class=" + sm.getClass().getName());
            err.println(prefix + ": SecurityManager classLoader=" + toString(sm.getClass().getClassLoader()));
            err.println(prefix + ": SecurityManager.toString=" + sm);
        } else {
            err.println(prefix + ": SecurityManager.class=null");
            err.println(prefix + ": SecurityManager.toString=null");
            err.println(prefix + ": SecurityManager classLoader=null");
        }

        String policy = System.getProperty("java.security.policy");
        if (policy != null) {
            File f = new File(policy);
            err.println(prefix + ": AbsolutePath=" + f.getAbsolutePath());
            err.println(prefix + ": CanonicalPath=" + f.getCanonicalPath());
            err.println(prefix + ": length=" + f.length());
            err.println(prefix + ": canRead=" + f.canRead());
            err.println(prefix + ": lastModified=" + new java.util.Date(f.lastModified()));
        }

        LogManager manager = LogManager.getLogManager();
        String key = "java.util.logging.config.file";
        String cfg = System.getProperty(key);
        if (cfg != null) {
            err.println(prefix + ": " + cfg);
            File f = new File(cfg);
            err.println(prefix + ": AbsolutePath=" + f.getAbsolutePath());
            err.println(prefix + ": CanonicalPath=" + f.getCanonicalPath());
            err.println(prefix + ": length=" + f.length());
            err.println(prefix + ": canRead=" + f.canRead());
            err.println(prefix + ": lastModified=" + new java.util.Date(f.lastModified()));
        } else {
            err.println(prefix + ": " + key + " is not set as a system property.");
        }
        err.println(prefix + ": LogManager.class=" + manager.getClass().getName());
        err.println(prefix + ": LogManager classLoader=" + toString(manager.getClass().getClassLoader()));
        err.println(prefix + ": LogManager.toString=" + manager);
        err.println(prefix + ": MailHandler classLoader=" + toString(MailHandler.class.getClassLoader()));
        err.println(
                prefix + ": Context ClassLoader=" + toString(Thread.currentThread().getContextClassLoader()));
        err.println(prefix + ": Session ClassLoader=" + toString(Session.class.getClassLoader()));
        err.println(prefix + ": DataHandler ClassLoader=" + toString(DataHandler.class.getClassLoader()));

        final String p = MailHandler.class.getName();
        key = p.concat(".mail.to");
        String to = manager.getProperty(key);
        err.println(prefix + ": TO=" + to);
        if (to != null) {
            err.println(prefix + ": TO=" + Arrays.toString(InternetAddress.parse(to, true)));
        }

        key = p.concat(".mail.from");
        String from = manager.getProperty(key);
        if (from == null || from.length() == 0) {
            Session session = Session.getInstance(new Properties());
            InternetAddress local = InternetAddress.getLocalAddress(session);
            err.println(prefix + ": FROM=" + local);
        } else {
            err.println(prefix + ": FROM=" + Arrays.asList(InternetAddress.parse(from, false)));
            err.println(prefix + ": FROM=" + Arrays.asList(InternetAddress.parse(from, true)));
        }

        synchronized (manager) {
            final Enumeration<String> e = manager.getLoggerNames();
            while (e.hasMoreElements()) {
                final Logger l = manager.getLogger(e.nextElement());
                if (l != null) {
                    final Handler[] handlers = l.getHandlers();
                    if (handlers.length > 0) {
                        err.println(prefix + ": " + l.getClass().getName() + ", " + l.getName());
                        for (Handler h : handlers) {
                            err.println(prefix + ":\t" + toString(prefix, err, h));
                        }
                    }
                }
            }
        }
    } catch (Throwable error) {
        err.print(prefix + ": ");
        error.printStackTrace(err);
    }
    err.flush();
}

From source file:net.sourceforge.pmd.benchmark.TextReport.java

@Override
public void generate(Map<String, BenchmarkResult> benchmarksByName, PrintStream stream) {

    List<BenchmarkResult> results = new ArrayList<>(benchmarksByName.values());

    long[] totalTime = new long[Benchmark.TotalPMD.index + 1];
    long[] totalCount = new long[Benchmark.TotalPMD.index + 1];

    for (BenchmarkResult benchmarkResult : results) {
        totalTime[benchmarkResult.type.index] += benchmarkResult.getTime();
        totalCount[benchmarkResult.type.index] += benchmarkResult.getCount();
        if (benchmarkResult.type.index < Benchmark.MeasuredTotal.index) {
            totalTime[Benchmark.MeasuredTotal.index] += benchmarkResult.getTime();
        }// www . j av  a2  s  . c  o m
    }
    results.add(new BenchmarkResult(Benchmark.RuleTotal, totalTime[Benchmark.RuleTotal.index], 0));
    results.add(new BenchmarkResult(Benchmark.RuleChainTotal, totalTime[Benchmark.RuleChainTotal.index], 0));
    results.add(new BenchmarkResult(Benchmark.MeasuredTotal, totalTime[Benchmark.MeasuredTotal.index], 0));
    results.add(new BenchmarkResult(Benchmark.NonMeasuredTotal,
            totalTime[Benchmark.TotalPMD.index] - totalTime[Benchmark.MeasuredTotal.index], 0));
    Collections.sort(results);

    StringBuilderCR buf = new StringBuilderCR(PMD.EOL);
    boolean writeRuleHeader = true;
    boolean writeRuleChainRuleHeader = true;
    long ruleCount = 0;
    long ruleChainCount = 0;

    for (BenchmarkResult benchmarkResult : results) {
        StringBuilder buf2 = new StringBuilder(benchmarkResult.name);
        buf2.append(':');
        while (buf2.length() <= NAME_COLUMN_WIDTH) {
            buf2.append(' ');
        }
        String result = MessageFormat.format("{0,number,0.000}",
                Double.valueOf(benchmarkResult.getTime() / 1000000000.0));
        buf2.append(StringUtils.leftPad(result, VALUE_COLUMN_WIDTH));
        if (benchmarkResult.type.index <= Benchmark.RuleChainRule.index) {
            buf2.append(StringUtils.leftPad(
                    MessageFormat.format("{0,number,###,###,###,###,###}", benchmarkResult.getCount()), 20));
        }
        switch (benchmarkResult.type) {
        case Rule:
            if (writeRuleHeader) {
                writeRuleHeader = false;
                buf.appendLn();
                buf.appendLn("---------------------------------<<< Rules >>>---------------------------------");
                buf.appendLn("Rule name                                       Time (secs)    # of Evaluations");
                buf.appendLn();
            }
            ruleCount++;
            break;
        case RuleChainRule:
            if (writeRuleChainRuleHeader) {
                writeRuleChainRuleHeader = false;
                buf.appendLn();
                buf.appendLn("----------------------------<<< RuleChain Rules >>>----------------------------");
                buf.appendLn("Rule name                                       Time (secs)         # of Visits");
                buf.appendLn();
            }
            ruleChainCount++;
            break;
        case CollectFiles:
            buf.appendLn();
            buf.appendLn("--------------------------------<<< Summary >>>--------------------------------");
            buf.appendLn("Segment                                         Time (secs)");
            buf.appendLn();
            break;
        case MeasuredTotal:
            String s = MessageFormat.format("{0,number,###,###,###,###,###}", ruleCount);
            String t = MessageFormat.format("{0,number,0.000}",
                    ruleCount == 0 ? 0 : total(totalTime, Benchmark.Rule, ruleCount));
            buf.appendLn("Rule Average (", s, " rules):", StringUtils.leftPad(t, 37 - s.length()));
            s = MessageFormat.format("{0,number,###,###,###,###,###}", ruleChainCount);
            t = MessageFormat.format("{0,number,0.000}",
                    ruleChainCount == 0 ? 0 : total(totalTime, Benchmark.RuleChainRule, ruleChainCount));
            buf.appendLn("RuleChain Average (", s, " rules):", StringUtils.leftPad(t, 32 - s.length()));

            buf.appendLn();
            buf.appendLn("-----------------------------<<< Final Summary >>>-----------------------------");
            buf.appendLn("Total                                           Time (secs)");
            buf.appendLn();
            break;
        default:
            // Do nothing
            break;
        }
        buf.appendLn(buf2.toString());
    }

    stream.print(buf.toString());
}

From source file:edu.cmu.tetrad.search.TestIndTestConditionalCorrelation.java

private void writePatternAsMatrix(List<Node> nodes, Graph pattern, PrintStream out2) {
    GraphUtils.replaceNodes(pattern, nodes);

    for (int p = 0; p < 4; p++) {
        for (int q = 0; q < 4; q++) {

            Node n1 = nodes.get(p);
            Node n2 = nodes.get(q);

            Edge edge = pattern.getEdge(n1, n2);

            if (edge == null) {
                out2.print(0);
            } else if (Edges.isDirectedEdge(edge)) {
                if (edge.pointsTowards(n2)) {
                    out2.print(-1);/*from w w w . ja va 2  s . co  m*/
                } else {
                    out2.print(0);
                }
            } else if (Edges.isUndirectedEdge(edge)) {
                out2.print(1);
            } else if (Edges.isBidirectedEdge(edge)) {
                out2.print(1);
            } else {
                out2.print(0);
            }

            if (q < 4 - 1)
                out2.print(",");
        }

        out2.println();
    }
}

From source file:org.apache.hadoop.hive.ql.exec.ExplainTask.java

@VisibleForTesting
JSONObject outputPlan(Object work, PrintStream out, boolean extended, boolean jsonOutput, int indent,
        String appendToHeader) throws Exception {
    // Check if work has an explain annotation
    Annotation note = AnnotationUtils.getAnnotation(work.getClass(), Explain.class);

    String keyJSONObject = null;/*from  w  ww  .  j av  a2  s.  c  o  m*/

    if (note instanceof Explain) {
        Explain xpl_note = (Explain) note;
        boolean invokeFlag = false;
        if (this.work != null && this.work.isUserLevelExplain()) {
            invokeFlag = Level.USER.in(xpl_note.explainLevels());
        } else {
            if (extended) {
                invokeFlag = Level.EXTENDED.in(xpl_note.explainLevels());
            } else {
                invokeFlag = Level.DEFAULT.in(xpl_note.explainLevels());
            }
        }
        if (invokeFlag) {
            Vectorization vectorization = xpl_note.vectorization();
            if (this.work != null && this.work.isVectorization()) {

                // The EXPLAIN VECTORIZATION option was specified.
                final boolean desireOnly = this.work.isVectorizationOnly();
                final VectorizationDetailLevel desiredVecDetailLevel = this.work.isVectorizationDetailLevel();

                switch (vectorization) {
                case NON_VECTORIZED:
                    // Display all non-vectorized leaf objects unless ONLY.
                    if (desireOnly) {
                        invokeFlag = false;
                    }
                    break;
                case SUMMARY:
                case OPERATOR:
                case EXPRESSION:
                case DETAIL:
                    if (vectorization.rank < desiredVecDetailLevel.rank) {
                        // This detail not desired.
                        invokeFlag = false;
                    }
                    break;
                case SUMMARY_PATH:
                case OPERATOR_PATH:
                    if (desireOnly) {
                        if (vectorization.rank < desiredVecDetailLevel.rank) {
                            // Suppress headers and all objects below.
                            invokeFlag = false;
                        }
                    }
                    break;
                default:
                    throw new RuntimeException("Unknown EXPLAIN vectorization " + vectorization);
                }
            } else {
                // Do not display vectorization objects.
                switch (vectorization) {
                case SUMMARY:
                case OPERATOR:
                case EXPRESSION:
                case DETAIL:
                    invokeFlag = false;
                    break;
                case NON_VECTORIZED:
                    // No action.
                    break;
                case SUMMARY_PATH:
                case OPERATOR_PATH:
                    // Always include headers since they contain non-vectorized objects, too.
                    break;
                default:
                    throw new RuntimeException("Unknown EXPLAIN vectorization " + vectorization);
                }
            }
        }
        if (invokeFlag) {
            keyJSONObject = xpl_note.displayName();
            if (out != null) {
                out.print(indentString(indent));
                if (appendToHeader != null && !appendToHeader.isEmpty()) {
                    out.println(xpl_note.displayName() + appendToHeader);
                } else {
                    out.println(xpl_note.displayName());
                }
            }
        }
    }

    JSONObject json = jsonOutput ? new JSONObject(new LinkedHashMap<>()) : null;
    // If this is an operator then we need to call the plan generation on the
    // conf and then the children
    if (work instanceof Operator) {
        Operator<? extends OperatorDesc> operator = (Operator<? extends OperatorDesc>) work;
        if (operator.getConf() != null) {
            String appender = isLogical ? " (" + operator.getOperatorId() + ")" : "";
            JSONObject jsonOut = outputPlan(operator.getConf(), out, extended, jsonOutput,
                    jsonOutput ? 0 : indent, appender);
            if (this.work != null && (this.work.isUserLevelExplain() || this.work.isFormatted())) {
                if (jsonOut != null && jsonOut.length() > 0) {
                    ((JSONObject) jsonOut.get(JSONObject.getNames(jsonOut)[0])).put("OperatorId:",
                            operator.getOperatorId());
                }
                if (!this.work.isUserLevelExplain() && this.work.isFormatted()
                        && operator.getConf() instanceof ReduceSinkDesc) {
                    ((JSONObject) jsonOut.get(JSONObject.getNames(jsonOut)[0])).put("outputname:",
                            ((ReduceSinkDesc) operator.getConf()).getOutputName());
                }
            }
            if (jsonOutput) {
                json = jsonOut;
            }
        }

        if (!visitedOps.contains(operator) || !isLogical) {
            visitedOps.add(operator);
            if (operator.getChildOperators() != null) {
                int cindent = jsonOutput ? 0 : indent + 2;
                for (Operator<? extends OperatorDesc> op : operator.getChildOperators()) {
                    JSONObject jsonOut = outputPlan(op, out, extended, jsonOutput, cindent);
                    if (jsonOutput) {
                        ((JSONObject) json.get(JSONObject.getNames(json)[0])).accumulate("children", jsonOut);
                    }
                }
            }
        }

        if (jsonOutput) {
            return json;
        }
        return null;
    }

    // We look at all methods that generate values for explain
    Method[] methods = work.getClass().getMethods();
    Arrays.sort(methods, new MethodComparator());

    for (Method m : methods) {
        int prop_indents = jsonOutput ? 0 : indent + 2;
        note = AnnotationUtils.getAnnotation(m, Explain.class);

        if (note instanceof Explain) {
            Explain xpl_note = (Explain) note;
            boolean invokeFlag = false;
            if (this.work != null && this.work.isUserLevelExplain()) {
                invokeFlag = Level.USER.in(xpl_note.explainLevels());
            } else {
                if (extended) {
                    invokeFlag = Level.EXTENDED.in(xpl_note.explainLevels());
                } else {
                    invokeFlag = Level.DEFAULT.in(xpl_note.explainLevels());
                }
            }
            if (invokeFlag) {
                Vectorization vectorization = xpl_note.vectorization();
                if (this.work != null && this.work.isVectorization()) {

                    // The EXPLAIN VECTORIZATION option was specified.
                    final boolean desireOnly = this.work.isVectorizationOnly();
                    final VectorizationDetailLevel desiredVecDetailLevel = this.work
                            .isVectorizationDetailLevel();

                    switch (vectorization) {
                    case NON_VECTORIZED:
                        // Display all non-vectorized leaf objects unless ONLY.
                        if (desireOnly) {
                            invokeFlag = false;
                        }
                        break;
                    case SUMMARY:
                    case OPERATOR:
                    case EXPRESSION:
                    case DETAIL:
                        if (vectorization.rank < desiredVecDetailLevel.rank) {
                            // This detail not desired.
                            invokeFlag = false;
                        }
                        break;
                    case SUMMARY_PATH:
                    case OPERATOR_PATH:
                        if (desireOnly) {
                            if (vectorization.rank < desiredVecDetailLevel.rank) {
                                // Suppress headers and all objects below.
                                invokeFlag = false;
                            }
                        }
                        break;
                    default:
                        throw new RuntimeException("Unknown EXPLAIN vectorization " + vectorization);
                    }
                } else {
                    // Do not display vectorization objects.
                    switch (vectorization) {
                    case SUMMARY:
                    case OPERATOR:
                    case EXPRESSION:
                    case DETAIL:
                        invokeFlag = false;
                        break;
                    case NON_VECTORIZED:
                        // No action.
                        break;
                    case SUMMARY_PATH:
                    case OPERATOR_PATH:
                        // Always include headers since they contain non-vectorized objects, too.
                        break;
                    default:
                        throw new RuntimeException("Unknown EXPLAIN vectorization " + vectorization);
                    }
                }
            }
            if (invokeFlag) {

                Object val = null;
                try {
                    val = m.invoke(work);
                } catch (InvocationTargetException ex) {
                    // Ignore the exception, this may be caused by external jars
                    val = null;
                }

                if (val == null) {
                    continue;
                }

                String header = null;
                boolean skipHeader = xpl_note.skipHeader();
                boolean emptyHeader = false;

                if (!xpl_note.displayName().equals("")) {
                    header = indentString(prop_indents) + xpl_note.displayName() + ":";
                } else {
                    emptyHeader = true;
                    prop_indents = indent;
                    header = indentString(prop_indents);
                }

                // Try the output as a primitive object
                if (isPrintable(val)) {
                    if (out != null && shouldPrint(xpl_note, val)) {
                        if (!skipHeader) {
                            out.print(header);
                            out.print(" ");
                        }
                        out.println(val);
                    }
                    if (jsonOutput && shouldPrint(xpl_note, val)) {
                        json.put(header, val.toString());
                    }
                    continue;
                }

                int ind = 0;
                if (!jsonOutput) {
                    if (!skipHeader) {
                        ind = prop_indents + 2;
                    } else {
                        ind = indent;
                    }
                }

                // Try this as a map
                if (val instanceof Map) {
                    // Go through the map and print out the stuff
                    Map<?, ?> mp = (Map<?, ?>) val;

                    if (out != null && !skipHeader && mp != null && !mp.isEmpty()) {
                        out.print(header);
                    }

                    JSONObject jsonOut = outputMap(mp, !skipHeader && !emptyHeader, out, extended, jsonOutput,
                            ind);
                    if (jsonOutput && !mp.isEmpty()) {
                        json.put(header, jsonOut);
                    }
                    continue;
                }

                // Try this as a list
                if (val instanceof List || val instanceof Set) {
                    List l = val instanceof List ? (List) val : new ArrayList((Set) val);
                    if (out != null && !skipHeader && l != null && !l.isEmpty()) {
                        out.print(header);
                    }

                    JSONArray jsonOut = outputList(l, out, !skipHeader && !emptyHeader, extended, jsonOutput,
                            ind);

                    if (jsonOutput && !l.isEmpty()) {
                        json.put(header, jsonOut);
                    }

                    continue;
                }

                // Finally check if it is serializable
                try {
                    if (!skipHeader && out != null) {
                        out.println(header);
                    }
                    JSONObject jsonOut = outputPlan(val, out, extended, jsonOutput, ind);
                    if (jsonOutput && jsonOut != null && jsonOut.length() != 0) {
                        if (!skipHeader) {
                            json.put(header, jsonOut);
                        } else {
                            for (String k : JSONObject.getNames(jsonOut)) {
                                json.put(k, jsonOut.get(k));
                            }
                        }
                    }
                    continue;
                } catch (ClassCastException ce) {
                    // Ignore
                }
            }
        }
    }

    if (jsonOutput) {
        if (keyJSONObject != null) {
            JSONObject ret = new JSONObject(new LinkedHashMap<>());
            ret.put(keyJSONObject, json);
            return ret;
        }

        return json;
    }
    return null;
}