Example usage for java.io PrintStream PrintStream

List of usage examples for java.io PrintStream PrintStream

Introduction

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

Prototype

public PrintStream(File file) throws FileNotFoundException 

Source Link

Document

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

Usage

From source file:ie.aib.nbp.zosresttest.RunTest.java

/**
 * @param args the command line arguments
 *///ww  w. j a va  2s . c om
public static void main(String[] args) {
    PrintStream printer = null;

    if (args.length < 2) {
        System.out.println("***************************************************************************");
        System.out.println("*                   Z/OS REST SERVICES PERFORMANCE TESTER                 *");
        System.out.println("*                                                                         *");
        System.out.println("* At least 2 run parameters are required:                                 *");
        System.out.println("*  1 username: your mainframe username                                    *");
        System.out.println("*  2 password: your mainframe passeord                                    *");
        System.out.println("*  3 runtime behaviour switch: 1 - active, everything else - inactive     *");
        System.out.println("*    this parameter is optional and causes the app to run the test or not *");
        System.out.println("*    lack of it assings default value: 0                                  *");
        System.out.println("*    which triggers the service discovery feature                         *");
        System.out.println("*    and displays all currently available services                        *");
        System.out.println("*  4 output type:                                                         *");
        System.out.println("*     F - output to file (then fifth parameter hold the file location)    *");
        System.out.println("*     Everything else (including no parameter at all) outputs to console  *");
        System.out.println("***************************************************************************");
        return;
    }

    readConfig(CONFIG_FILE_PATH);
    String username = args[0];
    String password = args[1];

    String runPerformanceTest;
    try {
        runPerformanceTest = args[2];
    } catch (ArrayIndexOutOfBoundsException ex) {
        runPerformanceTest = "0";
    }

    String outputType;
    String outputFileLocation;
    try {
        outputType = args[3]; // F saves to file, everything else output to console            
    } catch (ArrayIndexOutOfBoundsException ex) {
        outputType = "C";
    }

    if (outputType.equalsIgnoreCase("F")) { // write to file
        String outputFile;
        try {
            outputFile = args[4]; // if prev param is F then this one may contain the file name (default name instead)
        } catch (ArrayIndexOutOfBoundsException ex) {
            SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy-HHmmssZ");
            outputFile = "ZosPerformanceTest".concat("-".concat(sdf.format(new Date()))).concat(".txt");
        }
        try {
            String filePath = config.getProperty("OUT_FILE_PATH").concat(outputFile);
            printer = new PrintStream(new FileOutputStream(filePath, true));
        } catch (FileNotFoundException ex) {
            Logger.getLogger(RunTest.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else { // othewise write to java console
        printer = new PrintStream(System.out);
    }

    if (runPerformanceTest.equals("1"))
        runPerformanceTest(username, password, printer, true, false);
    else
        runServiceDiscovery(username, password, printer);
}

From source file:it.units.malelab.ege.MappingPropertiesExperimenter.java

public static void main(String[] args) throws IOException, InterruptedException, ExecutionException {
    final int n = 10000;
    final int nDist = 10000;
    //prepare problems and methods
    List<String> problems = Lists.newArrayList("bool-parity5", "bool-mopm3", "sr-keijzer6", "sr-nguyen7",
            "sr-pagie1", "sr-vladislavleva4", "other-klandscapes3", "other-klandscapes7", "other-text");
    List<String> mappers = new ArrayList<>();
    for (int gs : new int[] { 64, 128, 256, 512, 1024 }) {
        mappers.add("ge-" + gs + "-2");
        mappers.add("ge-" + gs + "-4");
        mappers.add("ge-" + gs + "-8");
        mappers.add("ge-" + gs + "-12");
        mappers.add("pige-" + gs + "-4");
        mappers.add("pige-" + gs + "-8");
        mappers.add("pige-" + gs + "-16");
        mappers.add("pige-" + gs + "-24");
        mappers.add("hge-" + gs + "-0");
        mappers.add("whge-" + gs + "-2");
        mappers.add("whge-" + gs + "-3");
        mappers.add("whge-" + gs + "-5");
    }//from  w  w w.  j  av a  2 s.  c  om
    mappers.add("sge-0-5");
    mappers.add("sge-0-6");
    mappers.add("sge-0-7");
    mappers.add("sge-0-8");
    mappers.clear();
    mappers.addAll(Lists.newArrayList("ge-1024-8", "pige-1024-16", "hge-1024-0", "whge-1024-3", "sge-0-6"));
    PrintStream filePrintStream = null;
    if (args.length > 0) {
        filePrintStream = new PrintStream(args[0]);
    } else {
        filePrintStream = System.out;
    }
    filePrintStream.printf("problem;mapper;genotypeSize;param;property;value%n");
    //prepare distances
    Distance<Node<String>> phenotypeDistance = new CachedDistance<>(new LeavesEdit<String>());
    Distance<Sequence> genotypeDistance = new CachedDistance<>(new Hamming());
    //iterate
    for (String problemName : problems) {
        for (String mapperName : mappers) {
            System.out.printf("%20.20s, %20.20s", problemName, mapperName);
            //build problem
            Problem<String, NumericFitness> problem = null;
            if (problemName.equals("bool-parity5")) {
                problem = new Parity(5);
            } else if (problemName.equals("bool-mopm3")) {
                problem = new MultipleOutputParallelMultiplier(3);
            } else if (problemName.equals("sr-keijzer6")) {
                problem = new HarmonicCurve();
            } else if (problemName.equals("sr-nguyen7")) {
                problem = new Nguyen7(1);
            } else if (problemName.equals("sr-pagie1")) {
                problem = new Pagie1();
            } else if (problemName.equals("sr-vladislavleva4")) {
                problem = new Vladislavleva4(1);
            } else if (problemName.equals("other-klandscapes3")) {
                problem = new KLandscapes(3);
            } else if (problemName.equals("other-klandscapes7")) {
                problem = new KLandscapes(7);
            } else if (problemName.equals("other-text")) {
                problem = new Text();
            }
            //build configuration and evolver
            Mapper mapper = null;
            int genotypeSize = Integer.parseInt(mapperName.split("-")[1]);
            int mapperMainParam = Integer.parseInt(mapperName.split("-")[2]);
            if (mapperName.split("-")[0].equals("ge")) {
                mapper = new StandardGEMapper<>(mapperMainParam, 1, problem.getGrammar());
            } else if (mapperName.split("-")[0].equals("pige")) {
                mapper = new PiGEMapper<>(mapperMainParam, 1, problem.getGrammar());
            } else if (mapperName.split("-")[0].equals("sge")) {
                mapper = new SGEMapper<>(mapperMainParam, problem.getGrammar());
            } else if (mapperName.split("-")[0].equals("hge")) {
                mapper = new HierarchicalMapper<>(problem.getGrammar());
            } else if (mapperName.split("-")[0].equals("whge")) {
                mapper = new WeightedHierarchicalMapper<>(mapperMainParam, false, true, problem.getGrammar());
            }
            //prepare things
            Random random = new Random(1);
            Set<Sequence> genotypes = new LinkedHashSet<>(n);
            //build genotypes
            if (mapperName.split("-")[0].equals("sge")) {
                SGEGenotypeFactory<String> factory = new SGEGenotypeFactory<>((SGEMapper) mapper);
                while (genotypes.size() < n) {
                    genotypes.add(factory.build(random));
                }
                genotypeSize = factory.getBitSize();
            } else {
                BitsGenotypeFactory factory = new BitsGenotypeFactory(genotypeSize);
                while (genotypes.size() < n) {
                    genotypes.add(factory.build(random));
                }
            }
            //build and fill map
            Multimap<Node<String>, Sequence> multimap = HashMultimap.create();
            int progress = 0;
            for (Sequence genotype : genotypes) {
                Node<String> phenotype;
                try {
                    if (mapperName.split("-")[0].equals("sge")) {
                        phenotype = mapper.map((SGEGenotype<String>) genotype, new HashMap<>());
                    } else {
                        phenotype = mapper.map((BitsGenotype) genotype, new HashMap<>());
                    }
                } catch (MappingException e) {
                    phenotype = Node.EMPTY_TREE;
                }
                multimap.put(phenotype, genotype);
                progress = progress + 1;
                if (progress % Math.round(n / 10) == 0) {
                    System.out.print(".");
                }
            }
            System.out.println();
            //compute distances
            List<Pair<Double, Double>> allDistances = new ArrayList<>();
            List<Pair<Double, Double>> allValidDistances = new ArrayList<>();
            Multimap<Node<String>, Double> genotypeDistances = ArrayListMultimap.create();
            for (Node<String> phenotype : multimap.keySet()) {
                for (Sequence genotype1 : multimap.get(phenotype)) {
                    for (Sequence genotype2 : multimap.get(phenotype)) {
                        double gDistance = genotypeDistance.d(genotype1, genotype2);
                        genotypeDistances.put(phenotype, gDistance);
                        if (genotypeDistances.get(phenotype).size() > nDist) {
                            break;
                        }
                    }
                    if (genotypeDistances.get(phenotype).size() > nDist) {
                        break;
                    }
                }
            }
            List<Map.Entry<Node<String>, Sequence>> entries = new ArrayList<>(multimap.entries());
            Collections.shuffle(entries, random);
            for (Map.Entry<Node<String>, Sequence> entry1 : entries) {
                for (Map.Entry<Node<String>, Sequence> entry2 : entries) {
                    double gDistance = genotypeDistance.d(entry1.getValue(), entry2.getValue());
                    double pDistance = phenotypeDistance.d(entry1.getKey(), entry2.getKey());
                    allDistances.add(new Pair<>(gDistance, pDistance));
                    if (!Node.EMPTY_TREE.equals(entry1.getKey()) && !Node.EMPTY_TREE.equals(entry2.getKey())) {
                        allValidDistances.add(new Pair<>(gDistance, pDistance));
                    }
                    if (allDistances.size() > nDist) {
                        break;
                    }
                }
                if (allDistances.size() > nDist) {
                    break;
                }
            }
            //compute properties
            double invalidity = (double) multimap.get(Node.EMPTY_TREE).size() / (double) genotypes.size();
            double redundancy = 1 - (double) multimap.keySet().size() / (double) genotypes.size();
            double validRedundancy = redundancy;
            if (multimap.keySet().contains(Node.EMPTY_TREE)) {
                validRedundancy = 1 - ((double) multimap.keySet().size() - 1d)
                        / (double) (genotypes.size() - multimap.get(Node.EMPTY_TREE).size());
            }
            double locality = Utils.pearsonCorrelation(allDistances);
            double validLocality = Utils.pearsonCorrelation(allValidDistances);
            double[] sizes = new double[multimap.keySet().size()];
            double[] meanGenotypeDistances = new double[multimap.keySet().size()];
            int invalidIndex = -1;
            int c = 0;
            for (Node<String> phenotype : multimap.keySet()) {
                if (Node.EMPTY_TREE.equals(phenotype)) {
                    invalidIndex = c;
                }
                sizes[c] = multimap.get(phenotype).size();
                double[] distances = new double[genotypeDistances.get(phenotype).size()];
                int k = 0;
                for (Double distance : genotypeDistances.get(phenotype)) {
                    distances[k] = distance;
                    k = k + 1;
                }
                meanGenotypeDistances[c] = StatUtils.mean(distances);
                c = c + 1;
            }
            double nonUniformity = Math.sqrt(StatUtils.variance(sizes)) / StatUtils.mean(sizes);
            double nonSynonymousity = StatUtils.mean(meanGenotypeDistances)
                    / StatUtils.mean(firsts(allDistances));
            double validNonUniformity = nonUniformity;
            double validNonSynonymousity = nonSynonymousity;
            if (invalidIndex != -1) {
                double[] validSizes = new double[multimap.keySet().size() - 1];
                double[] validMeanGenotypeDistances = new double[multimap.keySet().size() - 1];
                if (invalidIndex > 0) {
                    System.arraycopy(sizes, 0, validSizes, 0, invalidIndex);
                    System.arraycopy(meanGenotypeDistances, 0, validMeanGenotypeDistances, 0, invalidIndex);
                }
                System.arraycopy(sizes, invalidIndex + 1, validSizes, invalidIndex,
                        sizes.length - invalidIndex - 1);
                System.arraycopy(meanGenotypeDistances, invalidIndex + 1, validMeanGenotypeDistances,
                        invalidIndex, meanGenotypeDistances.length - invalidIndex - 1);
                validNonUniformity = Math.sqrt(StatUtils.variance(validSizes)) / StatUtils.mean(validSizes);
                validNonSynonymousity = StatUtils.mean(validMeanGenotypeDistances)
                        / StatUtils.mean(firsts(allValidDistances));
            }
            //compute locality
            filePrintStream.printf("%s;%s;%d;%d;invalidity;%f %n", problemName, mapperName.split("-")[0],
                    genotypeSize, mapperMainParam, invalidity);
            filePrintStream.printf("%s;%s;%d;%d;redundancy;%f %n", problemName, mapperName.split("-")[0],
                    genotypeSize, mapperMainParam, redundancy);
            filePrintStream.printf("%s;%s;%d;%d;validRedundancy;%f %n", problemName, mapperName.split("-")[0],
                    genotypeSize, mapperMainParam, validRedundancy);
            filePrintStream.printf("%s;%s;%d;%d;locality;%f %n", problemName, mapperName.split("-")[0],
                    genotypeSize, mapperMainParam, locality);
            filePrintStream.printf("%s;%s;%d;%d;validLLocality;%f %n", problemName, mapperName.split("-")[0],
                    genotypeSize, mapperMainParam, validLocality);
            filePrintStream.printf("%s;%s;%d;%d;nonUniformity;%f %n", problemName, mapperName.split("-")[0],
                    genotypeSize, mapperMainParam, nonUniformity);
            filePrintStream.printf("%s;%s;%d;%d;validNonUniformity;%f %n", problemName,
                    mapperName.split("-")[0], genotypeSize, mapperMainParam, validNonUniformity);
            filePrintStream.printf("%s;%s;%d;%d;nonSynonymousity;%f %n", problemName, mapperName.split("-")[0],
                    genotypeSize, mapperMainParam, nonSynonymousity);
            filePrintStream.printf("%s;%s;%d;%d;validNonSynonymousity;%f %n", problemName,
                    mapperName.split("-")[0], genotypeSize, mapperMainParam, validNonSynonymousity);
        }
    }
    if (filePrintStream != null) {
        filePrintStream.close();
    }
}

From source file:edu.msu.cme.rdp.multicompare.Reprocess.java

/**
 * This class reprocesses the classification results (allrank output) and print out hierarchy output file, based on the confidence cutoff;
 * and print out only the detail classification results with assignment at certain rank with confidence above the cutoff or/and matching a given taxon.
 * @param args/*from   ww  w . j  av  a  2s . c o m*/
 * @throws Exception 
 */
public static void main(String[] args) throws Exception {

    PrintWriter assign_out = new PrintWriter(new NullWriter());
    float conf = 0.8f;
    PrintStream heir_out = null;
    String hier_out_filename = null;
    ClassificationResultFormatter.FORMAT format = ClassificationResultFormatter.FORMAT.allRank;
    String rank = null;
    String taxonFilterFile = null;
    String train_propfile = null;
    String gene = null;
    List<MCSample> samples = new ArrayList();

    try {
        CommandLine line = new PosixParser().parse(options, args);
        if (line.hasOption(CmdOptions.HIER_OUTFILE_SHORT_OPT)) {
            hier_out_filename = line.getOptionValue(CmdOptions.HIER_OUTFILE_SHORT_OPT);
            heir_out = new PrintStream(hier_out_filename);
        } else {
            throw new Exception(
                    "It make sense to provide output filename for " + CmdOptions.HIER_OUTFILE_LONG_OPT);
        }
        if (line.hasOption(CmdOptions.OUTFILE_SHORT_OPT)) {
            assign_out = new PrintWriter(line.getOptionValue(CmdOptions.OUTFILE_SHORT_OPT));
        }

        if (line.hasOption(CmdOptions.RANK_SHORT_OPT)) {
            rank = line.getOptionValue(CmdOptions.RANK_SHORT_OPT);
        }
        if (line.hasOption(CmdOptions.TAXON_SHORT_OPT)) {
            taxonFilterFile = line.getOptionValue(CmdOptions.TAXON_SHORT_OPT);
        }

        if (line.hasOption(CmdOptions.BOOTSTRAP_SHORT_OPT)) {
            conf = Float.parseFloat(line.getOptionValue(CmdOptions.BOOTSTRAP_SHORT_OPT));
            if (conf < 0 || conf > 1) {
                throw new IllegalArgumentException("Confidence must be in the range [0,1]");
            }
        }
        if (line.hasOption(CmdOptions.FORMAT_SHORT_OPT)) {
            String f = line.getOptionValue(CmdOptions.FORMAT_SHORT_OPT);
            if (f.equalsIgnoreCase("allrank")) {
                format = ClassificationResultFormatter.FORMAT.allRank;
            } else if (f.equalsIgnoreCase("fixrank")) {
                format = ClassificationResultFormatter.FORMAT.fixRank;
            } else if (f.equalsIgnoreCase("db")) {
                format = ClassificationResultFormatter.FORMAT.dbformat;
            } else if (f.equalsIgnoreCase("filterbyconf")) {
                format = ClassificationResultFormatter.FORMAT.filterbyconf;
            } else {
                throw new IllegalArgumentException(
                        "Not valid output format, only allrank, fixrank, filterbyconf and db allowed");
            }
        }
        if (line.hasOption(CmdOptions.TRAINPROPFILE_SHORT_OPT)) {
            if (gene != null) {
                throw new IllegalArgumentException(
                        "Already specified the gene from the default location. Can not specify train_propfile");
            } else {
                train_propfile = line.getOptionValue(CmdOptions.TRAINPROPFILE_SHORT_OPT);
            }
        }
        if (line.hasOption(CmdOptions.GENE_SHORT_OPT)) {
            if (train_propfile != null) {
                throw new IllegalArgumentException(
                        "Already specified train_propfile. Can not specify gene any more");
            }
            gene = line.getOptionValue(CmdOptions.GENE_SHORT_OPT).toLowerCase();

            if (!gene.equals(ClassifierFactory.RRNA_16S_GENE) && !gene.equals(ClassifierFactory.FUNGALLSU_GENE)
                    && !gene.equals(ClassifierFactory.FUNGALITS_warcup_GENE)
                    && !gene.equals(ClassifierFactory.FUNGALITS_unite_GENE)) {
                throw new IllegalArgumentException(gene + " is NOT valid, only allows "
                        + ClassifierFactory.RRNA_16S_GENE + ", " + ClassifierFactory.FUNGALLSU_GENE + ", "
                        + ClassifierFactory.FUNGALITS_warcup_GENE + " and "
                        + ClassifierFactory.FUNGALITS_unite_GENE);
            }
        }
        args = line.getArgs();
        if (args.length < 1) {
            throw new Exception("Incorrect number of command line arguments");
        }

        for (String arg : args) {
            String[] inFileNames = arg.split(",");
            String inputFile = inFileNames[0];
            File idmappingFile = null;

            if (inFileNames.length == 2) {
                idmappingFile = new File(inFileNames[1]);
                if (!idmappingFile.exists()) {
                    System.err.println("Failed to find input file \"" + inFileNames[1] + "\"");
                    return;
                }
            }

            MCSample nextSample = new MCSampleResult(inputFile, idmappingFile);
            samples.add(nextSample);

        }
    } catch (Exception e) {
        System.out.println("Command Error: " + e.getMessage());
        new HelpFormatter().printHelp(120,
                "Reprocess [options] <Classification_allrank_result>[,idmappingfile] ...", "", options, "");
        return;
    }

    if (train_propfile == null && gene == null) {
        gene = ClassifierFactory.RRNA_16S_GENE;
    }

    HashSet<String> taxonFilter = null;
    if (taxonFilterFile != null) {
        taxonFilter = readTaxonFilterFile(taxonFilterFile);
    }

    MultiClassifier multiClassifier = new MultiClassifier(train_propfile, gene);
    DefaultPrintVisitor printVisitor = new DefaultPrintVisitor(heir_out, samples);
    MultiClassifierResult result = multiClassifier.multiClassificationParser(samples, conf, assign_out, format,
            rank, taxonFilter);

    result.getRoot().topDownVisit(printVisitor);

    assign_out.close();
    heir_out.close();
    if (multiClassifier.hasCopyNumber()) {
        // print copy number corrected counts
        File cn_corrected_s = new File(new File(hier_out_filename).getParentFile(),
                "cncorrected_" + hier_out_filename);
        PrintStream cn_corrected_hier_out = new PrintStream(cn_corrected_s);
        printVisitor = new DefaultPrintVisitor(cn_corrected_hier_out, samples, true);
        result.getRoot().topDownVisit(printVisitor);
        cn_corrected_hier_out.close();
    }

}

From source file:it.cnr.isti.labsedc.glimpse.MainMonitoring.java

/**
 * Read the properties and init the connections to the enterprise service bus
 * //www. jav a2 s  . c  o  m
 * @param is the systemSettings file
 */
public static void main(String[] args) {
    try {
        FileOutputStream fos = new FileOutputStream("glimpseLog.log");
        PrintStream ps = new PrintStream(fos);
        System.setErr(ps);

        Logger log = Logger.getLogger(MainMonitoring.class.getName());

        log.debug("Hello this is an debug message");
        log.info("Hello this is an info message");

        if (MainMonitoring.initProps(args[0]) && MainMonitoring.init()) {

            SplashScreen.Show();
            System.out.println("Please wait until setup is done...");

            //the buffer where the events are stored to be analyzed, in this version
            //the buffer object is not used because Drools has it's own eventStream object
            EventsBuffer<GlimpseBaseEvent<?>> buffer = new EventsBufferImpl<GlimpseBaseEvent<?>>();

            //The complex event engine that will be used (in this case drools)
            ComplexEventProcessor engineOne = new ComplexEventProcessorImpl(Manager.Read(MANAGERPARAMETERFILE),
                    buffer, connFact, initConn);
            engineOne.start();

            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            RuleTemplateManager templateManager = new RuleTemplateManager(DROOLSRULEREQUESTTEMPLATE1,
                    DROOLSRULEREQUESTTEMPLATE2, DROOLSRULEREQUESTTEMPLATE3_1, DROOLSRULEREQUESTTEMPLATE3_2);

            //the component in charge to locate services and load specific rules.
            ServiceLocatorFactory.getServiceLocatorParseViolationReceivedFromBSM(engineOne, templateManager,
                    REGEXPATTERNFILEPATH).start();

            //start MailNotifier component
            MailNotification mailer = new MailNotification(Manager.Read(MAILNOTIFICATIONSETTINGSFILEPATH));
            mailer.start();

            //the manager of all the architecture
            GlimpseManager manager = new GlimpseManager(Manager.Read(MANAGERPARAMETERFILE), connFact, initConn,
                    engineOne.getRuleManager());
            manager.start();
        }
    } catch (Exception e) {
        System.out.println("USAGE: java -jar MainMonitoring.jar \"systemSettings\"");
    }
}

From source file:com.mapr.synth.Synth.java

public static void main(String[] args)
        throws IOException, CmdLineException, InterruptedException, ExecutionException {
    final Options opts = new Options();
    CmdLineParser parser = new CmdLineParser(opts);
    try {//w  w  w.  ja v a 2 s.  c o m
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println("Usage: " + "[ -count <number>G|M|K ] " + "-schema schema-file "
                + "[-quote DOUBLE_QUOTE|BACK_SLASH|OPTIMISTIC] " + "[-format JSON|TSV|CSV|XML ] "
                + "[-threads n] " + "[-output output-directory-name] ");
        throw e;
    }
    Preconditions.checkArgument(opts.threads > 0 && opts.threads <= 2000,
            "Must have at least one thread and no more than 2000");

    if (opts.threads > 1) {
        Preconditions.checkArgument(!"-".equals(opts.output),
                "If more than on thread is used, you have to use -output to set the output directory");
    }

    File outputDir = new File(opts.output);
    if (!"-".equals(opts.output)) {
        if (!outputDir.exists()) {
            Preconditions.checkState(outputDir.mkdirs(),
                    String.format("Couldn't create output directory %s", opts.output));
        }
        Preconditions.checkArgument(outputDir.exists() && outputDir.isDirectory(),
                String.format("Couldn't create directory %s", opts.output));
    }

    if (opts.schema == null) {
        throw new IllegalArgumentException("Must specify schema file using [-schema filename] option");
    }
    final SchemaSampler sampler = new SchemaSampler(opts.schema);
    final AtomicLong rowCount = new AtomicLong();

    final List<ReportingWorker> tasks = Lists.newArrayList();
    int limit = (opts.count + opts.threads - 1) / opts.threads;
    int remaining = opts.count;
    for (int i = 0; i < opts.threads; i++) {

        final int count = Math.min(limit, remaining);
        remaining -= count;

        tasks.add(new ReportingWorker(opts, sampler, rowCount, count, i));
    }

    final double t0 = System.nanoTime() * 1e-9;
    ExecutorService pool = Executors.newFixedThreadPool(opts.threads);
    ScheduledExecutorService blinker = Executors.newScheduledThreadPool(1);
    final AtomicBoolean finalRun = new AtomicBoolean(false);

    final PrintStream sideLog = new PrintStream(new FileOutputStream("side-log"));
    Runnable blink = new Runnable() {
        public double oldT;
        private long oldN;

        @Override
        public void run() {
            double t = System.nanoTime() * 1e-9;
            long n = rowCount.get();
            System.err.printf("%s\t%d\t%.1f\t%d\t%.1f\t%.3f\n", finalRun.get() ? "F" : "R", opts.threads,
                    t - t0, n, n / (t - t0), (n - oldN) / (t - oldT));
            for (ReportingWorker task : tasks) {
                ReportingWorker.ThreadReport r = task.report();
                sideLog.printf("\t%d\t%.2f\t%.2f\t%.2f\t%.1f\t%.1f\n", r.fileNumber, r.threadTime, r.userTime,
                        r.wallTime, r.rows / r.threadTime, r.rows / r.wallTime);
            }
            oldN = n;
            oldT = t;
        }
    };
    if (!"-".equals(opts.output)) {
        blinker.scheduleAtFixedRate(blink, 0, 10, TimeUnit.SECONDS);
    }
    List<Future<Integer>> results = pool.invokeAll(tasks);

    int total = 0;
    for (Future<Integer> result : results) {
        total += result.get();
    }
    Preconditions.checkState(total == opts.count, String
            .format("Expected to generate %d lines of output, but actually generated %d", opts.count, total));
    pool.shutdownNow();
    blinker.shutdownNow();
    finalRun.set(true);
    sideLog.close();
    blink.run();
}

From source file:fr.cs.examples.frames.Frames3.java

public static void main(String[] args) {
    try {//w w w .  jav a  2  s . c om

        // configure Orekit and printing format
        Autoconfiguration.configureOrekit();

        // Initial state definition :
        // ==========================

        // Date
        // ****
        AbsoluteDate initialDate = new AbsoluteDate(new DateComponents(1970, 04, 07), TimeComponents.H00,
                TimeScalesFactory.getUTC());

        // Orbit
        // *****
        // The Sun is in the orbital plane for raan ~ 202
        double mu = 3.986004415e+14; // gravitation coefficient
        Frame eme2000 = FramesFactory.getEME2000(); // inertial frame
        Orbit orbit = new CircularOrbit(7178000.0, 0.5e-4, -0.5e-4, FastMath.toRadians(50.),
                FastMath.toRadians(220.), FastMath.toRadians(5.300), PositionAngle.MEAN, eme2000, initialDate,
                mu);

        // Attitude laws
        // *************

        // Earth
        Frame earthFrame = FramesFactory.getITRF(IERSConventions.IERS_2010, true);
        BodyShape earth = new OneAxisEllipsoid(Constants.WGS84_EARTH_EQUATORIAL_RADIUS,
                Constants.WGS84_EARTH_FLATTENING, earthFrame);

        // Target pointing attitude provider over satellite nadir at date, without yaw compensation
        NadirPointing nadirLaw = new NadirPointing(eme2000, earth);

        // Target pointing attitude provider with yaw compensation
        final PVCoordinatesProvider sun = CelestialBodyFactory.getSun();
        YawSteering yawSteeringLaw = new YawSteering(eme2000, nadirLaw, sun, Vector3D.MINUS_I);

        // Propagator : Eckstein-Hechler analytic propagator
        Propagator propagator = new EcksteinHechlerPropagator(orbit, yawSteeringLaw,
                Constants.EIGEN5C_EARTH_EQUATORIAL_RADIUS, Constants.EIGEN5C_EARTH_MU,
                Constants.EIGEN5C_EARTH_C20, Constants.EIGEN5C_EARTH_C30, Constants.EIGEN5C_EARTH_C40,
                Constants.EIGEN5C_EARTH_C50, Constants.EIGEN5C_EARTH_C60);

        // Let's write the results in a file in order to draw some plots.
        propagator.setMasterMode(10, new OrekitFixedStepHandler() {

            PrintStream out = null;

            public void init(SpacecraftState s0, AbsoluteDate t) throws PropagationException {
                try {
                    File file = new File(System.getProperty("user.home"), "XYZ.dat");
                    System.out.println("Results written to file: " + file.getAbsolutePath());
                    out = new PrintStream(file);
                    out.println("#time X Y Z Wx Wy Wz");
                } catch (IOException ioe) {
                    throw new PropagationException(ioe, LocalizedFormats.SIMPLE_MESSAGE,
                            ioe.getLocalizedMessage());
                }
            }

            public void handleStep(SpacecraftState currentState, boolean isLast) throws PropagationException {
                try {

                    // get the transform from orbit/attitude reference frame to spacecraft frame
                    Transform inertToSpacecraft = currentState.toTransform();

                    // get the position of the Sun in orbit/attitude reference frame
                    Vector3D sunInert = sun.getPVCoordinates(currentState.getDate(), currentState.getFrame())
                            .getPosition();

                    // convert Sun position to spacecraft frame
                    Vector3D sunSat = inertToSpacecraft.transformPosition(sunInert);

                    // and the spacecraft rotational rate also
                    Vector3D spin = inertToSpacecraft.getRotationRate();

                    // Lets calculate the reduced coordinates
                    double sunX = sunSat.getX() / sunSat.getNorm();
                    double sunY = sunSat.getY() / sunSat.getNorm();
                    double sunZ = sunSat.getZ() / sunSat.getNorm();

                    out.format(Locale.US, "%s %12.3f %12.3f %12.3f %12.7f %12.7f %12.7f%n",
                            currentState.getDate(), sunX, sunY, sunZ, spin.getX(), spin.getY(), spin.getZ());

                    if (isLast) {
                        out.close();
                    }
                } catch (OrekitException oe) {
                    throw new PropagationException(oe);
                }
            }

        });

        System.out.println("Running...");
        propagator.propagate(initialDate.shiftedBy(6000));

    } catch (OrekitException oe) {
        System.err.println(oe.getMessage());
    }
}

From source file:net.cliftonsnyder.svgchart.Main.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption("c", "stylesheet", true, "CSS stylesheet (default: " + SVGChart.DEFAULT_STYLESHEET + ")");
    options.addOption("h", "height", true, "chart height");
    options.addOption("i", "input-file", true, "input file [default: stdin]");
    options.addOption("o", "output-file", true, "output file [default: stdout]");
    options.addOption("w", "width", true, "chart width");
    options.addOption("?", "help", false, "print a brief help message");

    Option type = new Option("t", "type", true, "chart type " + Arrays.toString(SVGChart.TYPES));
    type.setRequired(true);// w w  w  .  ja v a2 s . c  om
    options.addOption(type);

    CommandLineParser parser = new GnuParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine line = null;
    try {
        // parse the command line arguments
        line = parser.parse(options, args);
        if (line.hasOption("help")) {
            formatter.printHelp(USAGE, options);
            System.exit(0);
        }
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("unable to parse command line: " + exp.getMessage());
        formatter.printHelp(USAGE, options);
        System.exit(1);
    }

    SVGChart chart = null;
    String tmp = line.getOptionValue("type");
    Matcher m = null;
    for (Pattern p : SVGChart.TYPE_PATTERNS) {
        if ((m = p.matcher(tmp)).matches()) {
            switch (m.group().charAt(0)) {
            case 'l':
                // DEBUG
                System.err.println("line");
                break;
            case 'b':
                System.err.println("bar");
                chart = new BarChart();
                break;
            case 'p':
                System.err.println("pie");
                break;
            default:
                System.err.println("unknown or unimplemented chart type: '" + tmp + "'");
                System.exit(1);
            }
        }
    }

    try {
        chart.setWidth(Double.parseDouble(line.getOptionValue("width", "" + SVGChart.DEFAULT_WIDTH)));
    } catch (NumberFormatException e) {
        System.err.println(
                "unable to parse command line: invalid width value '" + line.getOptionValue("width") + "'");
        System.exit(1);
    }

    try {
        chart.setHeight(Double.parseDouble(line.getOptionValue("height", "" + SVGChart.DEFAULT_HEIGHT)));
    } catch (NumberFormatException e) {
        System.err.println(
                "unable to parse command line: invalid height value '" + line.getOptionValue("height") + "'");
        System.exit(1);
    }

    InputStream in = System.in;
    tmp = line.getOptionValue("input-file", "-");
    if ("-".equals(tmp)) {
        in = System.in;
    } else {
        try {
            in = new FileInputStream(tmp);
        } catch (FileNotFoundException e) {
            System.err.println("input file not found: '" + tmp + "'");
            System.exit(1);
        }
    }

    PrintStream out = System.out;
    tmp = line.getOptionValue("output-file", "-");
    if ("-".equals(tmp)) {
        out = System.out;
    } else {
        try {
            out = new PrintStream(new FileOutputStream(tmp));
        } catch (FileNotFoundException e) {
            System.err.println("output file not found: '" + tmp + "'");
            System.exit(1);
        }
    }

    tmp = line.getOptionValue("stylesheet", SVGChart.DEFAULT_STYLESHEET);
    chart.setStyleSheet(tmp);

    try {
        chart.parseInput(in);
    } catch (IOException e) {
        System.err.println("I/O error while reading input");
        System.exit(1);
    } catch (net.cliftonsnyder.svgchart.parse.ParseException e) {
        System.err.println("error parsing input: " + e.getMessage());
    }

    chart.createChart();

    try {
        chart.printChart(out, true);
    } catch (IOException e) {
        System.err.println("error serializing output");
        System.exit(1);
    }
}

From source file:friendsandfollowers.FilesThreaderFriendsIDs.java

public static void main(String[] args) throws InterruptedException {

    // Check how many arguments were passed in
    if ((args == null) || (args.length < 4)) {
        System.err.println("4 Parameters are required plus one optional " + "parameter to launch a Job.");
        System.err.println("First: String 'INPUT: /path/to/files/'");
        System.err.println("Second: String 'OUTPUT: /output/path/'");
        System.err.println("Third: (int) Total Number Of Jobs");
        System.err.println("Fourth: (int) Number of seconds to pause");
        System.err/* w w  w.  java  2  s .  c om*/
                .println("Fifth: (int) Number of ids to fetch. " + "Provide number which increment by 5000 eg "
                        + "(5000, 10000, 15000 etc) " + "or -1 to fetch all ids.");
        System.err.println("Example: fileToRun /input/path/ " + "/output/path/ 10 2 75000");
        System.exit(-1);
    }

    // to write output in a file
    ThreadPrintStream.replaceSystemOut();
    try {
        INPUT = StringEscapeUtils.escapeJava(args[0]);
    } catch (Exception e) {
        System.err.println("Argument" + args[0] + " must be an String.");
        System.exit(-1);
    }

    try {
        OUTPUT = StringEscapeUtils.escapeJava(args[1]);
    } catch (Exception e) {
        System.err.println("Argument" + args[1] + " must be an String.");
        System.exit(-1);
    }

    try {
        TOTAL_JOBS_STR = StringEscapeUtils.escapeJava(args[2]);
    } catch (Exception e) {
        System.err.println("Argument" + args[2] + " must be an integer.");
        System.exit(-1);
    }

    try {
        PAUSE_STR = StringEscapeUtils.escapeJava(args[3]);
    } catch (Exception e) {
        System.err.println("Argument" + args[3] + " must be an integer.");
        System.exit(-1);
    }

    if (args.length == 5) {
        try {
            IDS_TO_FETCH = StringEscapeUtils.escapeJava(args[4]);
        } catch (Exception e) {
            System.err.println("Argument" + args[4] + " must be an integer.");
            System.exit(-1);
        }
    }

    try {
        PAUSE = Integer.parseInt(args[3]);
    } catch (NumberFormatException e) {
        System.err.println("Argument" + args[3] + " must be an integer.");
        System.exit(-1);
    }

    try {
        TOTAL_JOBS = Integer.parseInt(TOTAL_JOBS_STR);
    } catch (NumberFormatException e) {
        System.err.println("Argument" + TOTAL_JOBS_STR + " must be an integer.");
        System.exit(-1);
    }

    System.out.println("Going to launch jobs. " + "Please see logs files to track jobs.");

    ExecutorService threadPool = Executors.newFixedThreadPool(TOTAL_JOBS);

    for (int i = 0; i < TOTAL_JOBS; i++) {

        final String JOB_NO = Integer.toString(i);

        threadPool.submit(new Runnable() {

            public void run() {

                try {

                    // Creating a text file where System.out.println()
                    // will send its output for this thread.
                    String name = Thread.currentThread().getName();
                    FileOutputStream fos = null;
                    try {
                        fos = new FileOutputStream(name + "-logs.txt");
                    } catch (Exception e) {
                        System.err.println(e.getMessage());
                        System.exit(0);
                    }

                    // Create a PrintStream that will write to the new file.
                    PrintStream stream = new PrintStream(new BufferedOutputStream(fos));
                    // Install the PrintStream to be used as 
                    // System.out for this thread.
                    ((ThreadPrintStream) System.out).setThreadOut(stream);
                    // Output three messages to System.out.
                    System.out.println(name);
                    System.out.println();
                    System.out.println();

                    FilesThreaderFriendsIDs.execTask(INPUT, OUTPUT, TOTAL_JOBS_STR, JOB_NO, PAUSE_STR,
                            IDS_TO_FETCH);

                } catch (IOException | ClassNotFoundException | SQLException | JSONException e) {

                    // e.printStackTrace();
                    System.out.println(e.getMessage());
                }
            }
        });

        helpers.pause(PAUSE);
    }
    threadPool.shutdown();
}

From source file:friendsandfollowers.FilesThreaderFollowersIDs.java

public static void main(String[] args) throws InterruptedException {

    // Check how many arguments were passed in
    if ((args == null) || (args.length < 4)) {
        System.err.println("4 Parameters are required plus one optional " + "parameter to launch a Job.");
        System.err.println("First: String 'INPUT: /path/to/files/'");
        System.err.println("Second: String 'OUTPUT: /output/path/'");
        System.err.println("Third: (int) Total Number Of Jobs");
        System.err.println("Fourth: (int) Number of seconds to pause");
        System.err/*w ww .  j av  a  2 s .  co m*/
                .println("Fifth: (int) Number of ids to fetch. " + "Provide number which increment by 5000 eg "
                        + "(5000, 10000, 15000 etc) " + "or -1 to fetch all ids.");
        System.err.println("Example: fileToRun /input/path/ " + "/output/path/ 10 2 75000");
        System.exit(-1);
    }

    // to write output in a file
    ThreadPrintStream.replaceSystemOut();
    try {
        INPUT = StringEscapeUtils.escapeJava(args[0]);
    } catch (Exception e) {
        System.err.println("Argument" + args[0] + " must be an String.");
        System.exit(-1);
    }

    try {
        OUTPUT = StringEscapeUtils.escapeJava(args[1]);
    } catch (Exception e) {
        System.err.println("Argument" + args[1] + " must be an String.");
        System.exit(-1);
    }

    try {
        TOTAL_JOBS_STR = StringEscapeUtils.escapeJava(args[2]);
    } catch (Exception e) {
        System.err.println("Argument" + args[2] + " must be an integer.");
        System.exit(-1);
    }

    try {
        PAUSE_STR = StringEscapeUtils.escapeJava(args[3]);
    } catch (Exception e) {
        System.err.println("Argument" + args[3] + " must be an integer.");
        System.exit(-1);
    }

    if (args.length == 5) {
        try {
            IDS_TO_FETCH = StringEscapeUtils.escapeJava(args[4]);
        } catch (Exception e) {
            System.err.println("Argument" + args[4] + " must be an integer.");
            System.exit(-1);
        }
    }

    try {
        PAUSE = Integer.parseInt(args[3]);
    } catch (NumberFormatException e) {
        System.err.println("Argument" + args[3] + " must be an integer.");
        System.exit(-1);
    }

    try {
        TOTAL_JOBS = Integer.parseInt(TOTAL_JOBS_STR);
    } catch (NumberFormatException e) {
        System.err.println("Argument" + TOTAL_JOBS_STR + " must be an integer.");
        System.exit(-1);
    }

    System.out.println("Going to launch jobs. " + "Please see logs files to track jobs.");

    ExecutorService threadPool = Executors.newFixedThreadPool(TOTAL_JOBS);

    for (int i = 0; i < TOTAL_JOBS; i++) {

        final String JOB_NO = Integer.toString(i);

        threadPool.submit(new Runnable() {

            public void run() {

                try {

                    // Creating a text file where System.out.println()
                    // will send its output for this thread.
                    String name = Thread.currentThread().getName();
                    FileOutputStream fos = null;
                    try {
                        fos = new FileOutputStream(name + "-logs.txt");
                    } catch (Exception e) {
                        System.err.println(e.getMessage());
                        System.exit(0);
                    }

                    // Create a PrintStream that will write to the new file.
                    PrintStream stream = new PrintStream(new BufferedOutputStream(fos));

                    //                         Install the PrintStream to be used as 
                    //                         System.out for this thread.
                    ((ThreadPrintStream) System.out).setThreadOut(stream);

                    // Output three messages to System.out.
                    System.out.println(name);
                    System.out.println();
                    System.out.println();

                    FilesThreaderFollowersIDs.execTask(INPUT, OUTPUT, TOTAL_JOBS_STR, JOB_NO, PAUSE_STR,
                            IDS_TO_FETCH);

                } catch (IOException | ClassNotFoundException | SQLException | JSONException e) {

                    // e.printStackTrace();
                    System.out.println(e.getMessage());
                }
            }
        });

        helpers.pause(PAUSE);
    }
    threadPool.shutdown();
}

From source file:com.act.lcms.ExtractFromNetCDFAroundMass.java

public static void main(String[] args) throws Exception {
    if (args.length != 4 || !args[0].endsWith(".nc")) {
        throw new RuntimeException(
                "Needs (1) NetCDF .nc file, " + "(2) mass value, e.g., 132.0772 for debugging, "
                        + "(3) how many timepoints to process (-1 for all), "
                        + "(4) prefix for .data and rendered .pdf, '-' for stdout");
    }/*ww w  .j a  va  2 s  . com*/

    String netCDF = args[0];
    Double mz = Double.parseDouble(args[1]);
    Integer numSpectraToProcess = Integer.parseInt(args[2]);
    String outPrefix = args[3];
    String outPDF = outPrefix.equals("-") ? null : outPrefix + ".pdf";
    String outDATA = outPrefix.equals("-") ? null : outPrefix + ".data";

    ExtractFromNetCDFAroundMass e = new ExtractFromNetCDFAroundMass();
    List<Triple<Double, Double, Double>> window = e.get2DWindow(netCDF, mz, numSpectraToProcess);

    // Write data output to outfile
    PrintStream whereTo = outDATA == null ? System.out : new PrintStream(new FileOutputStream(outDATA));
    for (Triple<Double, Double, Double> xyz : window) {
        whereTo.format("%.4f\t%.4f\t%.4f\n", xyz.getLeft(), xyz.getMiddle(), xyz.getRight());
        whereTo.flush();
    }

    if (outDATA != null) {
        // if outDATA is != null, then we have written to .data file
        // now render the .data to the corresponding .pdf file

        // first close the .data
        whereTo.close();

        // render outDATA to outPDF using gnuplo
        Gnuplotter plotter = new Gnuplotter();
        plotter.plot3D(outDATA, outPDF, netCDF, mz);
    }
}