Example usage for java.io PrintWriter PrintWriter

List of usage examples for java.io PrintWriter PrintWriter

Introduction

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

Prototype

public PrintWriter(File file) throws FileNotFoundException 

Source Link

Document

Creates a new PrintWriter, without automatic line flushing, with the specified file.

Usage

From source file:ekb.elastic.ingest.TaxiQuery.java

public static void main(String... args) {

    Options options = new Options();
    HelpFormatter help = new HelpFormatter();

    try {// www.  j a v a 2 s  .c  o m
        Option hostOpt = new Option("h", "host", true, "ElasticSearch URL");
        hostOpt.setArgs(1);
        hostOpt.setRequired(true);
        Option portOpt = new Option("p", "port", true, "ElasticSearch URL");
        portOpt.setArgs(1);
        portOpt.setRequired(true);
        Option clusterOpt = new Option("c", "cluster", true, "Cluster");
        clusterOpt.setArgs(1);
        clusterOpt.setRequired(true);
        Option indexOpt = new Option("i", "index", true, "The index");
        indexOpt.setArgs(1);
        indexOpt.setRequired(true);

        Option pickupTimeOpt = new Option("u", "pickup", true, "The pickup time");
        pickupTimeOpt.setArgs(1);
        pickupTimeOpt.setRequired(true);
        Option dropTimeOpt = new Option("d", "dropoff", true, "The dropoff time");
        dropTimeOpt.setArgs(1);
        dropTimeOpt.setRequired(true);

        options.addOption(hostOpt);
        options.addOption(portOpt);
        options.addOption(clusterOpt);
        options.addOption(indexOpt);
        options.addOption(pickupTimeOpt);
        options.addOption(dropTimeOpt);

        GnuParser parser = new GnuParser();
        CommandLine cmd = parser.parse(options, args);

        Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", cmd.getOptionValue('c'))
                .build();
        Client client = new TransportClient(settings).addTransportAddress(new InetSocketTransportAddress(
                cmd.getOptionValue('h'), Integer.parseInt(cmd.getOptionValue('p'))));

        TaxiQuery tq = new TaxiQuery();

        TaxiStats stats = tq.getTaxiStats(client, cmd.getOptionValues("i"));

        log.info("Results:\n" + stats.toDateString());

        sdf.parse(cmd.getOptionValue("u"));
        sdf.parse(cmd.getOptionValue("d"));

        // 2013-01-01T10:10:00

        ArrayList<TaxiBucket> list = tq.getInterval(client, cmd.getOptionValues("index"),
                cmd.getOptionValue("u"), cmd.getOptionValue("d"), 60);

        log.info("List size is: " + list.size());

        client.close();

    } catch (ParseException pe) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);

        help.printUsage(pw, 80, TaxiQuery.class.getName(), options);

        log.error(sw.toString());

    } catch (TaxiQueryException e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        log.error(sw.toString());
    } catch (java.text.ParseException e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        log.error(sw.toString());
    }
}

From source file:edu.msu.cme.rdp.readseq.utils.SequenceTrimmer.java

public static void main(String[] args) throws IOException {
    Options options = new Options();
    options.addOption("r", "ref-seq", true,
            "Trim points are given as positions in a reference sequence from this file");
    options.addOption("i", "inclusive", false, "Trim points are inclusive");
    options.addOption("l", "length", true, "Minimum length of sequence after trimming");
    options.addOption("f", "filled-ratio", true,
            "Minimum ratio of filled model positions of sequence after trimming");
    options.addOption("o", "out", true, "Write sequences to directory (default=cwd)");
    options.addOption("s", "stats", true, "Write stats to file");

    PrintWriter statsOut = new PrintWriter(new NullWriter());
    boolean inclusive = false;
    int minLength = 0;
    int minTrimmedLength = 0;
    int maxNs = 0;
    int maxTrimNs = 0;

    int trimStart = 0;
    int trimStop = 0;
    Sequence refSeq = null;//from  w  w  w  . j  a va2s  .c o m
    float minFilledRatio = 0;

    int expectedModelPos = -1;
    String[] inputFiles = null;
    File outdir = new File(".");
    try {
        CommandLine line = new PosixParser().parse(options, args);

        if (line.hasOption("ref-seq")) {
            refSeq = readRefSeq(new File(line.getOptionValue("ref-seq")));
        }

        if (line.hasOption("inclusive")) {
            inclusive = true;
        }

        if (line.hasOption("length")) {
            minLength = Integer.valueOf(line.getOptionValue("length"));
        }

        if (line.hasOption("filled-ratio")) {
            minFilledRatio = Float.valueOf(line.getOptionValue("filled-ratio"));
        }

        if (line.hasOption("out")) {
            outdir = new File(line.getOptionValue("out"));
            if (!outdir.isDirectory()) {
                outdir = outdir.getParentFile();
                System.err.println("Output option is not a directory, using " + outdir + " instead");
            }
        }

        if (line.hasOption("stats")) {
            statsOut = new PrintWriter(line.getOptionValue("stats"));
        }

        args = line.getArgs();

        if (args.length < 3) {
            throw new Exception("Unexpected number of arguments");
        }

        trimStart = Integer.parseInt(args[0]);
        trimStop = Integer.parseInt(args[1]);
        inputFiles = Arrays.copyOfRange(args, 2, args.length);

        if (refSeq != null) {
            expectedModelPos = SeqUtils.getMaskedBySeqString(refSeq.getSeqString()).length();
            trimStart = translateCoord(trimStart, refSeq, CoordType.seq, CoordType.model);
            trimStop = translateCoord(trimStop, refSeq, CoordType.seq, CoordType.model);
        }

    } catch (Exception e) {
        new HelpFormatter().printHelp("SequenceTrimmer <trim start> <trim stop> <aligned file> ...", options);
        System.err.println("Error: " + e.getMessage());
    }

    System.err.println("Starting sequence trimmer");
    System.err.println("*  Input files:           " + Arrays.asList(inputFiles));
    System.err.println("*  Minimum Length:        " + minLength);
    System.err.println("*  Trim point inclusive?: " + inclusive);
    System.err.println("*  Trim points:           " + trimStart + "-" + trimStop);
    System.err.println("*  Min filled ratio:      " + minFilledRatio);
    System.err.println("*  refSeq:                "
            + ((refSeq == null) ? "model" : refSeq.getSeqName() + " " + refSeq.getDesc()));

    Sequence seq;
    SeqReader reader;
    TrimStats stats;

    writeStatsHeader(statsOut);

    FastaWriter seqWriter;
    File in;
    for (String infile : inputFiles) {
        in = new File(infile);
        reader = new SequenceReader(in);
        seqWriter = new FastaWriter(new File(outdir, "trimmed_" + in.getName()));

        while ((seq = reader.readNextSequence()) != null) {
            if (seq.getSeqName().startsWith("#")) {
                seqWriter.writeSeq(seq.getSeqName(), "", trimMetaSeq(seq.getSeqString(), trimStart, trimStop));
                continue;
            }

            stats = getStats(seq, trimStart, trimStop);
            boolean passed = didSeqPass(stats, minLength, minTrimmedLength, maxNs, maxTrimNs, minFilledRatio);
            writeStats(statsOut, seq.getSeqName(), stats, passed);
            if (passed) {
                seqWriter.writeSeq(seq.getSeqName(), seq.getDesc(), new String(stats.trimmedBases));
            }
        }

        reader.close();
        seqWriter.close();
    }

    statsOut.close();
}

From source file:microbiosima.SelectiveMicrobiosima.java

/**
 * @param args/*from  www.j  av a2s  .  c  o m*/
 *            the command line arguments
 * @throws java.io.FileNotFoundException
 * @throws java.io.UnsupportedEncodingException
 */

public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
    int populationSize = 500;//Integer.parseInt(parameters[1]);
    int microSize = 1000;//Integer.parseInt(parameters[2]);
    int numberOfSpecies = 150;//Integer.parseInt(parameters[3]);
    int numberOfGeneration = 10000;
    int Ngene = 10;
    int numberOfObservation = 100;
    int numberOfReplication = 10;
    double Ngenepm = 5;
    double pctEnv = 0;
    double pctPool = 0;
    double msCoeff = 1;
    double hsCoeff = 1;
    boolean HMS_or_TMS = true;

    Options options = new Options();

    Option help = new Option("h", "help", false, "print this message");
    Option version = new Option("v", "version", false, "print the version information and exit");
    options.addOption(help);
    options.addOption(version);

    options.addOption(Option.builder("o").longOpt("obs").hasArg().argName("OBS")
            .desc("Number generation for observation [default: 100]").build());
    options.addOption(Option.builder("r").longOpt("rep").hasArg().argName("REP")
            .desc("Number of replication [default: 1]").build());

    Builder C = Option.builder("c").longOpt("config").numberOfArgs(6).argName("Pop Micro Spec Gen")
            .desc("Four Parameters in the following orders: "
                    + "(1) population size, (2) microbe size, (3) number of species, (4) number of generation, (5) number of total traits, (6)number of traits per microbe"
                    + " [default: 500 1000 150 10000 10 5]");
    options.addOption(C.build());

    HelpFormatter formatter = new HelpFormatter();
    String syntax = "microbiosima pctEnv pctPool";
    String header = "\nSimulates the evolutionary and ecological dynamics of microbiomes within a population of hosts.\n\n"
            + "required arguments:\n" + "  pctEnv             Percentage of environmental acquisition\n"
            + "  pctPool            Percentage of pooled environmental component\n"
            + "  msCoeff            Parameter related to microbe selection strength\n"
            + "  hsCoeff            Parameter related to host selection strength\n"
            + "  HMS_or_TMS         String HMS or TMS to specify host-mediated or trait-mediated microbe selection\n"
            + "\noptional arguments:\n";
    String footer = "\n";

    formatter.setWidth(80);

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;

    try {
        cmd = parser.parse(options, args);
        String[] pct_config = cmd.getArgs();

        if (cmd.hasOption("h") || args.length == 0) {
            formatter.printHelp(syntax, header, options, footer, true);
            System.exit(0);
        }
        if (cmd.hasOption("v")) {
            System.out.println("Microbiosima " + VERSION);
            System.exit(0);
        }
        if (pct_config.length != 5) {
            System.out.println(
                    "ERROR! Required exactly five argumennts for pct_env, pct_pool, msCoeff, hsCoeff and HMS_or_TMS. It got "
                            + pct_config.length + ": " + Arrays.toString(pct_config));
            formatter.printHelp(syntax, header, options, footer, true);
            System.exit(3);
        } else {
            pctEnv = Double.parseDouble(pct_config[0]);
            pctPool = Double.parseDouble(pct_config[1]);
            msCoeff = Double.parseDouble(pct_config[2]);
            hsCoeff = Double.parseDouble(pct_config[3]);
            if (pct_config[4].equals("HMS"))
                HMS_or_TMS = true;
            if (pct_config[4].equals("TMS"))
                HMS_or_TMS = false;
            if (pctEnv < 0 || pctEnv > 1) {
                System.out.println(
                        "ERROR: pctEnv (Percentage of environmental acquisition) must be between 0 and 1 (pctEnv="
                                + pctEnv + ")! EXIT");
                System.exit(3);
            }
            if (pctPool < 0 || pctPool > 1) {
                System.out.println(
                        "ERROR: pctPool (Percentage of pooled environmental component must) must be between 0 and 1 (pctPool="
                                + pctPool + ")! EXIT");
                System.exit(3);
            }
            if (msCoeff < 1) {
                System.out.println(
                        "ERROR: msCoeff (parameter related to microbe selection strength) must be not less than 1 (msCoeff="
                                + msCoeff + ")! EXIT");
                System.exit(3);
            }
            if (hsCoeff < 1) {
                System.out.println(
                        "ERROR: hsCoeff (parameter related to host selection strength) must be not less than 1 (hsCoeff="
                                + hsCoeff + ")! EXIT");
                System.exit(3);
            }
            if (!(pct_config[4].equals("HMS") || pct_config[4].equals("TMS"))) {
                System.out.println(
                        "ERROR: HMS_or_TMS (parameter specifying host-mediated or trait-mediated selection) must be either 'HMS' or 'TMS' (HMS_or_TMS="
                                + pct_config[4] + ")! EXIT");
                System.exit(3);
            }

        }
        if (cmd.hasOption("config")) {
            String[] configs = cmd.getOptionValues("config");
            populationSize = Integer.parseInt(configs[0]);
            microSize = Integer.parseInt(configs[1]);
            numberOfSpecies = Integer.parseInt(configs[2]);
            numberOfGeneration = Integer.parseInt(configs[3]);
            Ngene = Integer.parseInt(configs[4]);
            Ngenepm = Double.parseDouble(configs[5]);
            if (Ngenepm > Ngene) {
                System.out.println(
                        "ERROR: number of traits per microbe must not be greater than number of total traits! EXIT");
                System.exit(3);
            }
        }
        if (cmd.hasOption("obs")) {
            numberOfObservation = Integer.parseInt(cmd.getOptionValue("obs"));
        }
        if (cmd.hasOption("rep")) {
            numberOfReplication = Integer.parseInt(cmd.getOptionValue("rep"));
        }

    } catch (ParseException e) {
        e.printStackTrace();
        System.exit(3);
    }

    StringBuilder sb = new StringBuilder();
    sb.append("Configuration Summary:").append("\n\tPopulation size: ").append(populationSize)
            .append("\n\tMicrobe size: ").append(microSize).append("\n\tNumber of species: ")
            .append(numberOfSpecies).append("\n\tNumber of generation: ").append(numberOfGeneration)
            .append("\n\tNumber generation for observation: ").append(numberOfObservation)
            .append("\n\tNumber of replication: ").append(numberOfReplication)
            .append("\n\tNumber of total traits: ").append(Ngene).append("\n\tNumber of traits per microbe: ")
            .append(Ngenepm).append("\n");
    System.out.println(sb.toString());

    double[] environment = new double[numberOfSpecies];
    for (int i = 0; i < numberOfSpecies; i++) {
        environment[i] = 1 / (double) numberOfSpecies;
    }
    int[] fitnessToHost = new int[Ngene];
    int[] fitnessToMicrobe = new int[Ngene];

    for (int rep = 0; rep < numberOfReplication; rep++) {
        String prefix = "" + (rep + 1) + "_";
        String sufix;
        if (HMS_or_TMS)
            sufix = "_E" + pctEnv + "_P" + pctPool + "_HS" + hsCoeff + "_HMS" + msCoeff + ".txt";
        else
            sufix = "_E" + pctEnv + "_P" + pctPool + "_HS" + hsCoeff + "_TMS" + msCoeff + ".txt";
        System.out.println("Output 5 result files in the format of: " + prefix + "[****]" + sufix);
        try {
            PrintWriter file1 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "gamma_diversity" + sufix)));
            PrintWriter file2 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "alpha_diversity" + sufix)));
            PrintWriter file3 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "beta_diversity" + sufix)));
            PrintWriter file4 = new PrintWriter(new BufferedWriter(new FileWriter(prefix + "sum" + sufix)));
            PrintWriter file5 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "inter_generation_distance" + sufix)));
            PrintWriter file6 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "environment_population_distance" + sufix)));
            PrintWriter file7 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "host_fitness" + sufix)));
            PrintWriter file8 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "cos_theta" + sufix)));
            PrintWriter file9 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "host_fitness_distribution" + sufix)));
            PrintWriter file10 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "microbiome_fitness_distribution" + sufix)));
            PrintWriter file11 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "bacteria_contents" + sufix)));
            PrintWriter file12 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "individual_bacteria_contents" + sufix)));
            for (int i = 0; i < Ngene; i++) {
                fitnessToMicrobe[i] = MathUtil.getNextInt(2) - 1;
                fitnessToHost[i] = MathUtil.getNextInt(2) - 1;
            }
            MathUtil.setSeed(rep % numberOfReplication);
            SelectiveSpeciesRegistry ssr = new SelectiveSpeciesRegistry(numberOfSpecies, Ngene, Ngenepm,
                    msCoeff, fitnessToHost, fitnessToMicrobe);
            MathUtil.setSeed();
            SelectivePopulation population = new SelectivePopulation(microSize, environment, populationSize,
                    pctEnv, pctPool, 0, 0, ssr, hsCoeff, HMS_or_TMS);

            while (population.getNumberOfGeneration() < numberOfGeneration) {
                population.sumSpecies();
                if (population.getNumberOfGeneration() % numberOfObservation == 0) {
                    //file1.print(population.gammaDiversity(false));
                    //file2.print(population.alphaDiversity(false));
                    //file1.print("\t");
                    //file2.print("\t");
                    file1.println(population.gammaDiversity(true));
                    file2.println(population.alphaDiversity(true));
                    //file3.print(population.betaDiversity(true));
                    //file3.print("\t");
                    file3.println(population.BrayCurtis(true));
                    file4.println(population.printOut());
                    file5.println(population.interGenerationDistance());
                    file6.println(population.environmentPopulationDistance());
                    file7.print(population.averageHostFitness());
                    file7.print("\t");
                    file7.println(population.varianceHostFitness());
                    file8.println(population.cosOfMH());
                    file9.println(population.printOutHFitness());
                    file10.println(population.printOutMFitness());
                    file11.println(population.printBacteriaContents());
                }
                population.getNextGen();
            }
            for (SelectiveIndividual host : population.getIndividuals()) {
                file12.println(host.printBacteriaContents());
            }
            file1.close();
            file2.close();
            file3.close();
            file4.close();
            file5.close();
            file6.close();
            file7.close();
            file8.close();
            file9.close();
            file10.close();
            file11.close();
            file12.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:PrintWriterDemo.java

public static void main() throws Exception {
    PrintWriter pw = new PrintWriter(new FileWriter("dice.txt"));
    for (int i = 1; i <= 1000; i++) {
        int die = (int) (1 + 6 * Math.random());
        pw.print(die);//from  w  w w . j av  a  2 s . co m
        pw.print(' ');
        if (i % 20 == 0)
            pw.println();
    }
    pw.println();
    pw.close(); // Without this, the output file may be empty
}

From source file:Counter.java

/** Main program entry point. */
public static void main(String argv[]) {

    // is there anything to do?
    if (argv.length == 0) {
        printUsage();//from   w ww  . j  a va 2  s . c o  m
        System.exit(1);
    }

    // variables
    Counter counter = new Counter();
    PrintWriter out = new PrintWriter(System.out);
    ParserWrapper parser = null;
    int repetition = DEFAULT_REPETITION;
    boolean namespaces = DEFAULT_NAMESPACES;
    boolean validation = DEFAULT_VALIDATION;
    boolean schemaValidation = DEFAULT_SCHEMA_VALIDATION;
    boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING;
    boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS;
    boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS;
    boolean dynamicValidation = DEFAULT_DYNAMIC_VALIDATION;
    boolean xincludeProcessing = DEFAULT_XINCLUDE;
    boolean xincludeFixupBaseURIs = DEFAULT_XINCLUDE_FIXUP_BASE_URIS;
    boolean xincludeFixupLanguage = DEFAULT_XINCLUDE_FIXUP_LANGUAGE;

    // process arguments
    for (int i = 0; i < argv.length; i++) {
        String arg = argv[i];
        if (arg.startsWith("-")) {
            String option = arg.substring(1);
            if (option.equals("p")) {
                // get parser name
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -p option.");
                }
                String parserName = argv[i];

                // create parser
                try {
                    parser = (ParserWrapper) Class.forName(parserName).newInstance();
                } catch (Exception e) {
                    parser = null;
                    System.err.println("error: Unable to instantiate parser (" + parserName + ")");
                }
                continue;
            }
            if (option.equals("x")) {
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -x option.");
                    continue;
                }
                String number = argv[i];
                try {
                    int value = Integer.parseInt(number);
                    if (value < 1) {
                        System.err.println("error: Repetition must be at least 1.");
                        continue;
                    }
                    repetition = value;
                } catch (NumberFormatException e) {
                    System.err.println("error: invalid number (" + number + ").");
                }
                continue;
            }
            if (option.equalsIgnoreCase("n")) {
                namespaces = option.equals("n");
                continue;
            }
            if (option.equalsIgnoreCase("v")) {
                validation = option.equals("v");
                continue;
            }
            if (option.equalsIgnoreCase("s")) {
                schemaValidation = option.equals("s");
                continue;
            }
            if (option.equalsIgnoreCase("f")) {
                schemaFullChecking = option.equals("f");
                continue;
            }
            if (option.equalsIgnoreCase("hs")) {
                honourAllSchemaLocations = option.equals("hs");
                continue;
            }
            if (option.equalsIgnoreCase("va")) {
                validateAnnotations = option.equals("va");
                continue;
            }
            if (option.equalsIgnoreCase("dv")) {
                dynamicValidation = option.equals("dv");
                continue;
            }
            if (option.equalsIgnoreCase("xi")) {
                xincludeProcessing = option.equals("xi");
                continue;
            }
            if (option.equalsIgnoreCase("xb")) {
                xincludeFixupBaseURIs = option.equals("xb");
                continue;
            }
            if (option.equalsIgnoreCase("xl")) {
                xincludeFixupLanguage = option.equals("xl");
                continue;
            }
            if (option.equals("h")) {
                printUsage();
                continue;
            }
        }

        // use default parser?
        if (parser == null) {

            // create parser
            try {
                parser = (ParserWrapper) Class.forName(DEFAULT_PARSER_NAME).newInstance();
            } catch (Exception e) {
                System.err.println("error: Unable to instantiate parser (" + DEFAULT_PARSER_NAME + ")");
                continue;
            }
        }

        // set parser features
        try {
            parser.setFeature(NAMESPACES_FEATURE_ID, namespaces);
        } catch (SAXException e) {
            System.err.println("warning: Parser does not support feature (" + NAMESPACES_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(VALIDATION_FEATURE_ID, validation);
        } catch (SAXException e) {
            System.err.println("warning: Parser does not support feature (" + VALIDATION_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schemaValidation);
        } catch (SAXException e) {
            System.err
                    .println("warning: Parser does not support feature (" + SCHEMA_VALIDATION_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
        } catch (SAXException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
        } catch (SAXException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        }
        try {
            parser.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
        } catch (SAXException e) {
            System.err.println("warning: Parser does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        }
        try {
            parser.setFeature(DYNAMIC_VALIDATION_FEATURE_ID, dynamicValidation);
        } catch (SAXException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + DYNAMIC_VALIDATION_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(XINCLUDE_FEATURE_ID, xincludeProcessing);
        } catch (SAXException e) {
            System.err.println("warning: Parser does not support feature (" + XINCLUDE_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID, xincludeFixupBaseURIs);
        } catch (SAXException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID, xincludeFixupLanguage);
        } catch (SAXException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID + ")");
        }

        // parse file
        try {
            long beforeParse = System.currentTimeMillis();
            Document document = null;
            for (int j = 0; j < repetition; j++) {
                document = parser.parse(arg);
            }
            long afterParse = System.currentTimeMillis();
            long parse = afterParse - beforeParse;

            ParserWrapper.DocumentInfo documentInfo = parser.getDocumentInfo();
            counter.setDocumentInfo(documentInfo);

            long beforeTraverse1 = System.currentTimeMillis();
            counter.count(document);
            long afterTraverse1 = System.currentTimeMillis();
            long traverse1 = afterTraverse1 - beforeTraverse1;

            long beforeTraverse2 = System.currentTimeMillis();
            counter.count(document);
            long afterTraverse2 = System.currentTimeMillis();
            long traverse2 = afterTraverse2 - beforeTraverse2;
            counter.printResults(out, arg, parse, traverse1, traverse2, repetition);
        } catch (SAXParseException e) {
            // ignore
        } catch (Exception e) {
            System.err.println("error: Parse error occurred - " + e.getMessage());
            Exception se = e;
            if (e instanceof SAXException) {
                se = ((SAXException) e).getException();
            }
            if (se != null)
                se.printStackTrace(System.err);
            else
                e.printStackTrace(System.err);
        }
    }

}

From source file:Main.java

public static String getStackTrace(Throwable t) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    t.printStackTrace(pw);//w  w  w . j  a va 2s .  c  om
    return sw.toString();
}

From source file:Main.java

public static String getExceptionStackTrace(Exception e) {
    StringWriter sw = new StringWriter();
    e.printStackTrace(new PrintWriter(sw));
    return sw.toString();
}

From source file:it.nibbles.javacoin.BlockTool.java

public static void main(String[] args) throws Exception {
    OptionParser parser = new OptionParser();
    parser.accepts("help");
    parser.accepts("import");
    parser.accepts("export");
    parser.accepts("testnet2");
    parser.accepts("testnet3");
    parser.accepts("prodnet");
    parser.accepts("first").withRequiredArg().ofType(Integer.class);
    parser.accepts("last").withRequiredArg().ofType(Integer.class);
    parser.accepts("hash").withRequiredArg();
    parser.accepts("port").withRequiredArg().ofType(Integer.class);
    optBdbPath = parser.accepts("bdbPath").withRequiredArg().defaultsTo("data");
    //optJdbcDriver = parser.accepts("driver").withRequiredArg().defaultsTo("com.mysql.jdbc.Driver");
    optJdbcUrl = parser.accepts("url").withRequiredArg().defaultsTo("jdbc:mysql://localhost/javacoin_testnet3");
    optJdbcUser = parser.accepts("dbuser").withRequiredArg().defaultsTo("javacoin");
    optJdbcPassword = parser.accepts("dbpass").withRequiredArg().defaultsTo("pw");
    inputfile = parser.accepts("inputfile").withRequiredArg();
    outputfile = parser.accepts("outputfile").withRequiredArg();
    //    String[] args = {
    //      "--inputfile", "blocks-0-100000.txt", "--prodnet", "--load", "--url", "jdbc:mysql://localhost/javacoin_test"
    //    };/* w w  w. ja v  a  2 s.co m*/
    OptionSet options = parser.parse(args);
    if (args.length == 0 || options.hasArgument("help") || options.nonOptionArguments().size() > 0
            || (options.has("export") && options.has("import"))
            || (options.has("export") && !options.has("outputfile"))
            || (options.has("import") && !options.has("inputfile"))
            || (options.has("testnet2") && options.has("testnet3"))
            || (options.has("testnet2") && options.has("prodnet"))
            || (options.has("testnet3") && options.has("prodnet"))) {
        println(HELP_TEXT);
        return;
    }
    if (options.hasArgument("port")) {
        //listenPort = ((Integer) options.valueOf("port")).intValue();
    }
    cmdExportBlockchain = options.has("export");
    cmdImportBlockchain = options.has("import");
    isProdnet = options.has("prodnet");
    isTestNet2 = options.has("testnet2");
    isTestNet3 = options.has("testnet3");
    if (!isProdnet && !isTestNet2 && !isTestNet3)
        isTestNet3 = true;
    if (options.hasArgument("first")) {
        firstBlock = ((Integer) options.valueOf("first")).intValue();
        if (!options.hasArgument("last"))
            lastBlock = firstBlock;
    }
    if (options.hasArgument("last")) {
        lastBlock = ((Integer) options.valueOf("last")).intValue();
        if (!options.hasArgument("first"))
            firstBlock = lastBlock;
    }
    if (options.hasArgument("hash"))
        blockHash = (String) options.valueOf("hash");
    if (cmdExportBlockchain && blockHash == null && firstBlock == 0 && lastBlock == 0) {
        println("To save blocks you have to specify a range or an hash");
        return;
    }

    //println("save: " + cmdSaveBlockchain + " load: " + cmdLoadBlockchain + " prodnet: " + isProdnet + " testnet2: " + isTestNet2 + " testnet3: " + isTestNet3);
    //println("FirstBlock: " + firstBlock + " lastBlock: " + lastBlock + " inputfile: " + inputfile.value(options) + " outputfile: " + outputfile.value(options));
    BlockTool app = new BlockTool();
    app.init(options);
    if (cmdImportBlockchain) {
        //System.out.println("Press return to start import blocks to blockchain");
        //System.in.read();
        BufferedReader reader;
        if ("-".equals(inputfile.value(options)))
            reader = new BufferedReader(new InputStreamReader(System.in));
        else
            reader = new BufferedReader(new FileReader(inputfile.value(options)));
        int numBlocks = 0;
        Block block = app.readBlock(reader, false);
        while (block != null) {
            numBlocks++;
            long startTime = System.currentTimeMillis();
            blockChain.addBlock(block);
            long insertTime = System.currentTimeMillis() - startTime;
            System.out.printf(
                    "%6d Block " + BtcUtil.hexOut(block.getHash()) + " #txs: %4d insertTime(ms): %d%n",
                    block.getTransactions().size(), insertTime);
            block = app.readBlock(reader, false);
        }
        System.out.println("Numero blocchi letti: " + numBlocks);
    } else if (cmdExportBlockchain) {
        BlockChainLink blockLink;
        try (PrintWriter writer = new PrintWriter(new File(outputfile.value(options)))) {
            if (blockHash != null) {
                blockLink = storage.getLink(BtcUtil.hexIn(blockHash));
                app.writeBlock(writer, blockLink.getBlock());
            } else {
                for (int i = firstBlock; i <= lastBlock; i++) {
                    blockLink = storage.getLinkAtHeight(i);
                    app.writeBlock(writer, blockLink.getBlock());
                }
            }
        }
    }
    app.close();
}

From source file:Main.java

public static String getExceptionStackTrace(Exception e) {
    Writer writer = new StringWriter();
    PrintWriter printWriter = new PrintWriter(writer);
    e.printStackTrace(printWriter);/*w ww  . ja v a  2  s .  com*/
    return writer.toString();
}

From source file:Main.java

public static void writeToFile(String fileName, String xml) throws IOException {
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileName, true), 1024));
    out.println(xml);/*www.j a  va 2  s .  c  o  m*/
    out.flush();
    out.close();
}