Example usage for java.io PrintWriter close

List of usage examples for java.io PrintWriter close

Introduction

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

Prototype

public void close() 

Source Link

Document

Closes the stream and releases any system resources associated with it.

Usage

From source file:org.jfree.chart.demo.ImageMapDemo1.java

/**
 * Starting point for the demo.//from   w ww  . j  a v  a 2 s  .c o m
 *
 * @param args  ignored.
 */
public static void main(final String[] args) {

    // create a chart
    final double[][] data = new double[][] { { 56.0, -12.0, 34.0, 76.0, 56.0, 100.0, 67.0, 45.0 },
            { 37.0, 45.0, 67.0, 25.0, 34.0, 34.0, 100.0, 53.0 },
            { 43.0, 54.0, 34.0, 34.0, 87.0, 64.0, 73.0, 12.0 } };
    final CategoryDataset dataset = DatasetUtilities.createCategoryDataset("Series ", "Type ", data);

    JFreeChart chart = null;
    final boolean drilldown = true;

    if (drilldown) {
        final CategoryAxis categoryAxis = new CategoryAxis("Category");
        final ValueAxis valueAxis = new NumberAxis("Value");
        final BarRenderer renderer = new BarRenderer();
        renderer.setToolTipGenerator(new StandardCategoryToolTipGenerator());
        renderer.setItemURLGenerator(new StandardCategoryURLGenerator("bar_chart_detail.jsp"));
        final CategoryPlot plot = new CategoryPlot(dataset, categoryAxis, valueAxis, renderer);
        plot.setOrientation(PlotOrientation.VERTICAL);
        chart = new JFreeChart("Bar Chart", JFreeChart.DEFAULT_TITLE_FONT, plot, true);
    } else {
        chart = ChartFactory.createBarChart("Vertical Bar Chart", // chart title
                "Category", // domain axis label
                "Value", // range axis label
                dataset, // data
                PlotOrientation.VERTICAL, true, // include legend
                true, false);
    }
    chart.setBackgroundPaint(java.awt.Color.white);

    // ****************************************************************************
    // * JFREECHART DEVELOPER GUIDE                                               *
    // * The JFreeChart Developer Guide, written by David Gilbert, is available   *
    // * to purchase from Object Refinery Limited:                                *
    // *                                                                          *
    // * http://www.object-refinery.com/jfreechart/guide.html                     *
    // *                                                                          *
    // * Sales are used to provide funding for the JFreeChart project - please    * 
    // * support us so that we can continue developing free software.             *
    // ****************************************************************************

    // save it to an image
    try {
        final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        final File file1 = new File("barchart100.png");
        ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);

        // write an HTML page incorporating the image with an image map
        final File file2 = new File("barchart100.html");
        final OutputStream out = new BufferedOutputStream(new FileOutputStream(file2));
        final PrintWriter writer = new PrintWriter(out);
        writer.println("<HTML>");
        writer.println("<HEAD><TITLE>JFreeChart Image Map Demo</TITLE></HEAD>");
        writer.println("<BODY>");
        //            ChartUtilities.writeImageMap(writer, "chart", info);
        writer.println("<IMG SRC=\"barchart100.png\" "
                + "WIDTH=\"600\" HEIGHT=\"400\" BORDER=\"0\" USEMAP=\"#chart\">");
        writer.println("</BODY>");
        writer.println("</HTML>");
        writer.close();

    } catch (IOException e) {
        System.out.println(e.toString());
    }

}

From source file:org.jfree.chart.demo.ImageMapDemo3.java

/**
 * Starting point for the demo.//from www.  j  ava 2 s .co  m
 *
 * @param args  ignored.
 *
 * @throws ParseException if there is a problem parsing dates.
 */
public static void main(final String[] args) throws ParseException {

    //  Create a sample dataset
    final SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
    final XYSeries dataSeries = new XYSeries("Curve data");
    final ArrayList toolTips = new ArrayList();
    dataSeries.add(sdf.parse("01-Jul-2002").getTime(), 5.22);
    toolTips.add("1D - 5.22");
    dataSeries.add(sdf.parse("02-Jul-2002").getTime(), 5.18);
    toolTips.add("2D - 5.18");
    dataSeries.add(sdf.parse("03-Jul-2002").getTime(), 5.23);
    toolTips.add("3D - 5.23");
    dataSeries.add(sdf.parse("04-Jul-2002").getTime(), 5.15);
    toolTips.add("4D - 5.15");
    dataSeries.add(sdf.parse("05-Jul-2002").getTime(), 5.22);
    toolTips.add("5D - 5.22");
    dataSeries.add(sdf.parse("06-Jul-2002").getTime(), 5.25);
    toolTips.add("6D - 5.25");
    dataSeries.add(sdf.parse("07-Jul-2002").getTime(), 5.31);
    toolTips.add("7D - 5.31");
    dataSeries.add(sdf.parse("08-Jul-2002").getTime(), 5.36);
    toolTips.add("8D - 5.36");
    final XYSeriesCollection xyDataset = new XYSeriesCollection(dataSeries);
    final CustomXYToolTipGenerator ttg = new CustomXYToolTipGenerator();
    ttg.addToolTipSeries(toolTips);

    //  Create the chart
    final StandardXYURLGenerator urlg = new StandardXYURLGenerator("xy_details.jsp");
    final ValueAxis timeAxis = new DateAxis("");
    final NumberAxis valueAxis = new NumberAxis("");
    valueAxis.setAutoRangeIncludesZero(false); // override default
    final XYPlot plot = new XYPlot(xyDataset, timeAxis, valueAxis, null);
    final StandardXYItemRenderer sxyir = new StandardXYItemRenderer(
            StandardXYItemRenderer.LINES + StandardXYItemRenderer.SHAPES, ttg, urlg);
    sxyir.setShapesFilled(true);
    plot.setRenderer(sxyir);
    final JFreeChart chart = new JFreeChart("", JFreeChart.DEFAULT_TITLE_FONT, plot, false);
    chart.setBackgroundPaint(java.awt.Color.white);

    // ****************************************************************************
    // * JFREECHART DEVELOPER GUIDE                                               *
    // * The JFreeChart Developer Guide, written by David Gilbert, is available   *
    // * to purchase from Object Refinery Limited:                                *
    // *                                                                          *
    // * http://www.object-refinery.com/jfreechart/guide.html                     *
    // *                                                                          *
    // * Sales are used to provide funding for the JFreeChart project - please    * 
    // * support us so that we can continue developing free software.             *
    // ****************************************************************************

    // save it to an image
    try {
        final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        final File file1 = new File("xychart100.png");
        ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);

        // write an HTML page incorporating the image with an image map
        final File file2 = new File("xychart100.html");
        final OutputStream out = new BufferedOutputStream(new FileOutputStream(file2));
        final PrintWriter writer = new PrintWriter(out);
        writer.println("<HTML>");
        writer.println("<HEAD><TITLE>JFreeChart Image Map Demo</TITLE></HEAD>");
        writer.println("<BODY>");
        //            ChartUtilities.writeImageMap(writer, "chart", info);
        writer.println("<IMG SRC=\"xychart100.png\" "
                + "WIDTH=\"600\" HEIGHT=\"400\" BORDER=\"0\" USEMAP=\"#chart\">");
        writer.println("</BODY>");
        writer.println("</HTML>");
        writer.close();

    } catch (IOException e) {
        System.out.println(e.toString());
    }
    return;
}

From source file:com.act.biointerpretation.ProductExtractor.java

public static void main(String[] args) throws Exception {
    CLIUtil cliUtil = new CLIUtil(ProductExtractor.class, HELP_MESSAGE, OPTION_BUILDERS);
    CommandLine cl = cliUtil.parseCommandLine(args);

    String orgPrefix = cl.getOptionValue(OPTION_ORGANISM_PREFIX);
    LOGGER.info("Using organism prefix %s", orgPrefix);

    MongoDB db = new MongoDB(DEFAULT_DB_HOST, DEFAULT_DB_PORT, cl.getOptionValue(OPTION_DB_NAME));

    Map<Long, String> validOrganisms = new TreeMap<>();
    DBIterator orgIter = db.getDbIteratorOverOrgs();
    Organism o = null;/*from w ww. j  a va 2  s . co  m*/
    while ((o = db.getNextOrganism(orgIter)) != null) {
        if (!o.getName().isEmpty() && o.getName().startsWith(orgPrefix)) {
            validOrganisms.put(o.getUUID(), o.getName());
        }
    }

    LOGGER.info("Found %d valid organisms", validOrganisms.size());

    Set<Long> productIds = new TreeSet<>(); // Use something with implicit ordering we can traverse in order.
    DBIterator reactionIterator = db.getIteratorOverReactions();
    Reaction r;
    while ((r = db.getNextReaction(reactionIterator)) != null) {
        Set<JSONObject> proteins = r.getProteinData();
        boolean valid = false;
        for (JSONObject j : proteins) {
            if (j.has("organism") && validOrganisms.containsKey(j.getLong("organism"))) {
                valid = true;
                break;
            } else if (j.has("organisms")) {
                JSONArray organisms = j.getJSONArray("organisms");
                for (int i = 0; i < organisms.length(); i++) {
                    if (validOrganisms.containsKey(organisms.getLong(i))) {
                        valid = true;
                        break;
                    }
                }
            }
        }

        if (valid) {
            for (Long id : r.getProducts()) {
                productIds.add(id);
            }
            for (Long id : r.getProductCofactors()) {
                productIds.add(id);
            }
        }
    }

    LOGGER.info("Found %d valid product ids for '%s'", productIds.size(), orgPrefix);
    PrintWriter writer = cl.hasOption(OPTION_OUTPUT_FILE)
            ? new PrintWriter(new FileWriter(cl.getOptionValue(OPTION_OUTPUT_FILE)))
            : new PrintWriter(System.out);

    for (Long id : productIds) {
        Chemical c = db.getChemicalFromChemicalUUID(id);
        String inchi = c.getInChI();
        if (inchi.startsWith("InChI=") && !inchi.startsWith("InChI=/FAKE")) {
            writer.println(inchi);
        }
    }

    if (cl.hasOption(OPTION_OUTPUT_FILE)) {
        writer.close();
    }
    LOGGER.info("Done.");
}

From source file:com.betfair.cougar.test.socket.app.SocketCompatibilityTestingApp.java

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

    Parser parser = new PosixParser();
    Options options = new Options();
    options.addOption("r", "repo", true, "Repository type to search: local|central");
    options.addOption("c", "client-concurrency", true,
            "Max threads to allow each client tester to run tests, defaults to 10");
    options.addOption("t", "test-concurrency", true, "Max client testers to run concurrently, defaults to 5");
    options.addOption("m", "max-time", true,
            "Max time (in minutes) to allow tests to complete, defaults to 10");
    options.addOption("v", "version", false, "Print version and exit");
    options.addOption("h", "help", false, "This help text");
    CommandLine commandLine = parser.parse(options, args);
    if (commandLine.hasOption("h")) {
        System.out.println(options);
        System.exit(0);//from ww  w .ja v a 2s. c o  m
    }
    if (commandLine.hasOption("v")) {
        System.out.println("How the hell should I know?");
        System.exit(0);
    }
    // 1. Find all testers in given repos
    List<RepoSearcher> repoSearchers = new ArrayList<>();
    for (String repo : commandLine.getOptionValues("r")) {
        if ("local".equals(repo.toLowerCase())) {
            repoSearchers.add(new LocalRepoSearcher());
        } else if ("central".equals(repo.toLowerCase())) {
            repoSearchers.add(new CentralRepoSearcher());
        } else {
            System.err.println("Unrecognized repo: " + repo);
            System.err.println(options);
            System.exit(1);
        }
    }
    int clientConcurrency = 10;
    if (commandLine.hasOption("c")) {
        try {
            clientConcurrency = Integer.parseInt(commandLine.getOptionValue("c"));
        } catch (NumberFormatException nfe) {
            System.err.println(
                    "client-concurrency is not a valid integer: '" + commandLine.getOptionValue("c") + "'");
            System.exit(1);
        }
    }
    int testConcurrency = 5;
    if (commandLine.hasOption("t")) {
        try {
            testConcurrency = Integer.parseInt(commandLine.getOptionValue("t"));
        } catch (NumberFormatException nfe) {
            System.err.println(
                    "test-concurrency is not a valid integer: '" + commandLine.getOptionValue("t") + "'");
            System.exit(1);
        }
    }
    int maxMinutes = 10;
    if (commandLine.hasOption("m")) {
        try {
            maxMinutes = Integer.parseInt(commandLine.getOptionValue("m"));
        } catch (NumberFormatException nfe) {
            System.err.println("max-time is not a valid integer: '" + commandLine.getOptionValue("m") + "'");
            System.exit(1);
        }
    }

    Properties clientProps = new Properties();
    clientProps.setProperty("client.concurrency", String.valueOf(clientConcurrency));

    File baseRunDir = new File(System.getProperty("user.dir") + "/run");
    baseRunDir.mkdirs();

    File tmpDir = new File(baseRunDir, "jars");
    tmpDir.mkdirs();

    List<ServerRunner> serverRunners = new ArrayList<>();
    List<ClientRunner> clientRunners = new ArrayList<>();
    for (RepoSearcher searcher : repoSearchers) {
        List<File> jars = searcher.findAndCache(tmpDir);
        for (File f : jars) {
            ServerRunner serverRunner = new ServerRunner(f, baseRunDir);
            System.out.println("Found tester: " + serverRunner.getVersion());
            serverRunners.add(serverRunner);
            clientRunners.add(new ClientRunner(f, baseRunDir, clientProps));
        }
    }

    // 2. Start servers and collect ports
    System.out.println();
    System.out.println("Starting " + serverRunners.size() + " servers...");
    for (ServerRunner server : serverRunners) {
        server.startServer();
    }
    System.out.println();

    List<TestCombo> tests = new ArrayList<>(serverRunners.size() * clientRunners.size());
    for (ServerRunner server : serverRunners) {
        for (ClientRunner client : clientRunners) {
            tests.add(new TestCombo(server, client));
        }
    }

    System.out.println("Enqueued " + tests.size() + " test combos to run...");

    long startTime = System.currentTimeMillis();
    // 3. Run every client against every server, collecting results
    BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue(serverRunners.size() * clientRunners.size());
    ThreadPoolExecutor service = new ThreadPoolExecutor(testConcurrency, testConcurrency, 5000,
            TimeUnit.MILLISECONDS, workQueue);
    service.prestartAllCoreThreads();
    workQueue.addAll(tests);
    while (!workQueue.isEmpty()) {
        Thread.sleep(1000);
    }
    service.shutdown();
    service.awaitTermination(maxMinutes, TimeUnit.MINUTES);
    long endTime = System.currentTimeMillis();
    long totalTimeSecs = Math.round((endTime - startTime) / 1000.0);
    for (ServerRunner server : serverRunners) {
        server.shutdownServer();
    }

    System.out.println();
    System.out.println("=======");
    System.out.println("Results");
    System.out.println("-------");
    // print a summary
    int totalTests = 0;
    int totalSuccess = 0;
    for (TestCombo combo : tests) {
        String clientVer = combo.getClientVersion();
        String serverVer = combo.getServerVersion();
        String results = combo.getClientResults();
        ObjectMapper mapper = new ObjectMapper(new JsonFactory());
        JsonNode node = mapper.reader().readTree(results);
        JsonNode resultsArray = node.get("results");
        int numTests = resultsArray.size();
        int numSuccess = 0;
        for (int i = 0; i < numTests; i++) {
            if ("success".equals(resultsArray.get(i).get("result").asText())) {
                numSuccess++;
            }
        }
        totalSuccess += numSuccess;
        totalTests += numTests;
        System.out.println(clientVer + "/" + serverVer + ": " + numSuccess + "/" + numTests
                + " succeeded - took " + String.format("%2f", combo.getRunningTime()) + " seconds");
    }
    System.out.println("-------");
    System.out.println(
            "Overall: " + totalSuccess + "/" + totalTests + " succeeded - took " + totalTimeSecs + " seconds");

    FileWriter out = new FileWriter("results.json");
    PrintWriter pw = new PrintWriter(out);

    // 4. Output full results
    pw.println("{\n  \"results\": [");
    for (TestCombo combo : tests) {
        combo.emitResults(pw, "    ");
    }
    pw.println("  ],");
    pw.println("  \"servers\": [");
    for (ServerRunner server : serverRunners) {
        server.emitInfo(pw, "    ");
    }
    pw.println("  ],");
    pw.close();
}

From source file:eu.skqs.bertie.standalone.BertieStandalone.java

public static void main(String[] args) {

    // Options//from   www  .  j  av a  2 s  .com
    Option file = OptionBuilder.withArgName("file").withLongOpt("file").hasArg()
            .withDescription("File to annotate").create("f");

    Option directory = OptionBuilder.withArgName("directory").withLongOpt("directory").hasArg()
            .withDescription("Directory to annotate").create("d");

    Option owl = OptionBuilder.withArgName("owl").withLongOpt("owl").hasArg()
            .withDescription("OWL file to use in annotation").create("o");

    Option plain = OptionBuilder.withLongOpt("plain").withDescription("Plain text file format").create("p");

    Option tei = OptionBuilder.withLongOpt("tei").withDescription("TEI file format").create("t");

    Option mode = OptionBuilder.withArgName("extract|minimal|maximal|prosody").withLongOpt("mode").hasArg()
            .withDescription("Mode to operate in").create("m");

    Option clean = OptionBuilder.withArgName("T0,T1,T3").withLongOpt("clean").hasArg()
            .withDescription("Remove gives types, MUST START UPPERCASE").create("c");

    Options options = new Options();
    options.addOption(file);
    options.addOption(directory);
    options.addOption(owl);
    options.addOption(plain);
    options.addOption(tei);
    options.addOption(mode);
    options.addOption(clean);

    CommandLineParser parser = new GnuParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmdline = null;

    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException e) {
        e.printStackTrace();
        System.exit(-1);
    }

    BertieStandalone standalone = new BertieStandalone();
    String documentPath = null;

    // Check for custom OWL
    if (cmdline.hasOption("owl")) {
        owlPath = cmdline.getOptionValue("owl");
    }

    // Check for clean
    if (cmdline.hasOption("clean")) {
        typesToRemove = cmdline.getOptionValue("clean");
    }

    // Check for mode
    if (cmdline.hasOption("mode")) {
        String currentMode = cmdline.getOptionValue("mode");

        if (currentMode.equals("extract")) {
            extractMode = true;
        } else if (currentMode.equals("poetry")) {
            poetryMode = true;
        }

        analysisMode = currentMode;
    }

    // Check for directory option
    if (cmdline.hasOption("directory")) {
        // We support TEI directorys only
        if (!cmdline.hasOption("tei")) {
            logger.log(Level.WARNING, "TEI file format must be selected with directory argument");
            System.exit(-1);
        }

        String directoryPath = cmdline.getOptionValue("directory");

        if (extractMode) {
            try {
                standalone.extractWithCollectionReader(directoryPath);
            } catch (Exception e) {
            }

            System.exit(0);
        }

        try {
            standalone.processWithCollectionReader(directoryPath);
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }

        System.exit(0);
    }

    // Check for file option
    if (cmdline.hasOption("file")) {
        // TODO: clean this up
        documentPath = cmdline.getOptionValue("file");
        filePath = cmdline.getOptionValue("file");

        // TEI
        if (cmdline.hasOption("tei")) {
            try {
                processWithFile();
            } catch (Exception e) {
                e.printStackTrace();
                System.exit(-1);
            }
            System.exit(0);
        }

        // Check for plain option
        if (!cmdline.hasOption("plain")) {
            logger.log(Level.WARNING, "Plain text format must be selected with file argument");
            System.exit(-1);
        }
    } else {
        logger.log(Level.WARNING, "No file argument given. Quitting.");
        formatter.printHelp("bertie", options);
        System.exit(-1);
    }

    // Make sure we have a document path
    if (documentPath == null) {
        logger.log(Level.WARNING, "Document path is empty. Quitting.");
        System.exit(-1);
    }

    // Read the document
    try {
        String encodingType = "UTF-8";

        BufferedReader fileReader = new BufferedReader(
                new InputStreamReader(new FileInputStream(documentPath), encodingType));

        StringBuilder sb = new StringBuilder();
        String line = null;

        while ((line = fileReader.readLine()) != null) {
            sb.append(line + newLine);
        }

        String input = sb.toString();
        fileReader.close();

        String output = standalone.process(input);
        if (output == null) {
            logger.log(Level.WARNING, "Empty processing result.");
            System.exit(-1);
        }

        PrintWriter fileWriter = new PrintWriter(documentPath, encodingType);
        fileWriter.write(output);
        fileWriter.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.jkoolcloud.jesl.simulator.TNT4JSimulator.java

public static void main(String[] args) {
    boolean isTTY = (System.console() != null);
    long startTime = System.currentTimeMillis();

    try {/*from  ww w. j  a  v a  2 s  .com*/
        SAXParserFactory parserFactory = SAXParserFactory.newInstance();
        SAXParser theParser = parserFactory.newSAXParser();
        TNT4JSimulatorParserHandler xmlHandler = new TNT4JSimulatorParserHandler();

        processArgs(xmlHandler, args);

        TrackerConfig simConfig = DefaultConfigFactory.getInstance().getConfig(TNT4JSimulator.class.getName());
        logger = TrackingLogger.getInstance(simConfig.build());
        if (logger.isSet(OpLevel.TRACE))
            traceLevel = OpLevel.TRACE;
        else if (logger.isSet(OpLevel.DEBUG))
            traceLevel = OpLevel.DEBUG;

        if (runType == SimulatorRunType.RUN_SIM) {
            if (StringUtils.isEmpty(simFileName)) {
                simFileName = "tnt4j-sim.xml";
                String fileName = readFromConsole("Simulation file [" + simFileName + "]: ");

                if (!StringUtils.isEmpty(fileName))
                    simFileName = fileName;
            }

            StringBuffer simDef = new StringBuffer();
            BufferedReader simLoader = new BufferedReader(new FileReader(simFileName));
            String line;
            while ((line = simLoader.readLine()) != null)
                simDef.append(line).append("\n");
            simLoader.close();

            info("jKool Activity Simulator Run starting: file=" + simFileName + ", iterations=" + numIterations
                    + ", ttl.sec=" + ttl);
            startTime = System.currentTimeMillis();

            if (isTTY && numIterations > 1)
                System.out.print("Iteration: ");
            int itTrcWidth = 0;
            for (iteration = 1; iteration <= numIterations; iteration++) {
                itTrcWidth = printProgress("Executing Iteration", iteration, itTrcWidth);

                theParser.parse(new InputSource(new StringReader(simDef.toString())), xmlHandler);

                if (!Utils.isEmpty(jkFileName)) {
                    PrintWriter gwFile = new PrintWriter(new FileOutputStream(jkFileName, true));
                    gwFile.println("");
                    gwFile.close();
                }
            }
            if (numIterations > 1)
                System.out.println("");

            info("jKool Activity Simulator Run finished, elapsed time = "
                    + DurationFormatUtils.formatDurationHMS(System.currentTimeMillis() - startTime));
            printMetrics(xmlHandler.getSinkStats(), "Total Sink Statistics");
        } else if (runType == SimulatorRunType.REPLAY_SIM) {
            info("jKool Activity Simulator Replay starting: file=" + jkFileName + ", iterations="
                    + numIterations);
            connect();
            startTime = System.currentTimeMillis();

            // Determine number of lines in file
            BufferedReader gwFile = new BufferedReader(new java.io.FileReader(jkFileName));
            for (numIterations = 0; gwFile.readLine() != null; numIterations++)
                ;
            gwFile.close();

            // Reopen the file and
            gwFile = new BufferedReader(new java.io.FileReader(jkFileName));
            if (isTTY && numIterations > 1)
                System.out.print("Processing Line: ");
            int itTrcWidth = 0;
            String gwMsg;
            iteration = 0;
            while ((gwMsg = gwFile.readLine()) != null) {
                iteration++;
                if (isTTY)
                    itTrcWidth = printProgress("Processing Line", iteration, itTrcWidth);
                gwConn.write(gwMsg);
            }
            if (isTTY && numIterations > 1)
                System.out.println("");
            long endTime = System.currentTimeMillis();

            info("jKool Activity Simulator Replay finished, elasped.time = "
                    + DurationFormatUtils.formatDurationHMS(endTime - startTime));
        }
    } catch (Exception e) {
        if (e instanceof SAXParseException) {
            SAXParseException spe = (SAXParseException) e;
            error("Error at line: " + spe.getLineNumber() + ", column: " + spe.getColumnNumber(), e);
        } else {
            error("Error running simulator", e);
        }
    } finally {
        try {
            Thread.sleep(1000L);
        } catch (Exception e) {
        }
        TNT4JSimulator.disconnect();
    }

    System.exit(0);
}

From source file:fr.tpt.s3.mcdag.bench.MainBench.java

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

    // Command line options
    Options options = new Options();

    Option input = new Option("i", "input", true, "MC-DAG XML models");
    input.setRequired(true);//from   www  . jav a  2 s.co m
    input.setArgs(Option.UNLIMITED_VALUES);
    options.addOption(input);

    Option output = new Option("o", "output", true, "Folder where results have to be written.");
    output.setRequired(true);
    options.addOption(output);

    Option uUti = new Option("u", "utilization", true, "Utilization.");
    uUti.setRequired(true);
    options.addOption(uUti);

    Option output2 = new Option("ot", "output-total", true, "File where total results are being written");
    output2.setRequired(true);
    options.addOption(output2);

    Option oCores = new Option("c", "cores", true, "Cores given to the test");
    oCores.setRequired(true);
    options.addOption(oCores);

    Option oLvls = new Option("l", "levels", true, "Levels tested for the system");
    oLvls.setRequired(true);
    options.addOption(oLvls);

    Option jobs = new Option("j", "jobs", true, "Number of threads to be launched.");
    jobs.setRequired(false);
    options.addOption(jobs);

    Option debug = new Option("d", "debug", false, "Debug logs.");
    debug.setRequired(false);
    options.addOption(debug);

    /*
     * Parsing of the command line
     */
    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd;

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        formatter.printHelp("Benchmarks MultiDAG", options);
        System.exit(1);
        return;
    }

    String inputFilePath[] = cmd.getOptionValues("input");
    String outputFilePath = cmd.getOptionValue("output");
    String outputFilePathTotal = cmd.getOptionValue("output-total");
    double utilization = Double.parseDouble(cmd.getOptionValue("utilization"));
    boolean boolDebug = cmd.hasOption("debug");
    int nbLvls = Integer.parseInt(cmd.getOptionValue("levels"));
    int nbJobs = 1;
    int nbFiles = inputFilePath.length;

    if (cmd.hasOption("jobs"))
        nbJobs = Integer.parseInt(cmd.getOptionValue("jobs"));

    int nbCores = Integer.parseInt(cmd.getOptionValue("cores"));

    /*
     *  While files need to be allocated
     *  run the tests in the pool of threads
     */

    // For dual-criticality systems we call a specific thread
    if (nbLvls == 2) {

        System.out.println(">>>>>>>>>>>>>>>>>>>>> NB levels " + nbLvls);

        int i_files2 = 0;
        String outFile = outputFilePath.substring(0, outputFilePath.lastIndexOf('.'))
                .concat("-schedulability.csv");
        PrintWriter writer = new PrintWriter(outFile, "UTF-8");
        writer.println(
                "Thread; File; FSched (%); FPreempts; FAct; LSched (%); LPreempts; LAct; ESched (%); EPreempts; EAct; HSched(%); HPreempts; HAct; Utilization");
        writer.close();

        ExecutorService executor2 = Executors.newFixedThreadPool(nbJobs);
        while (i_files2 != nbFiles) {
            BenchThreadDualCriticality bt2 = new BenchThreadDualCriticality(inputFilePath[i_files2], outFile,
                    nbCores, boolDebug);

            executor2.execute(bt2);
            i_files2++;
        }

        executor2.shutdown();
        executor2.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);

        int fedTotal = 0;
        int laxTotal = 0;
        int edfTotal = 0;
        int hybridTotal = 0;
        int fedPreempts = 0;
        int laxPreempts = 0;
        int edfPreempts = 0;
        int hybridPreempts = 0;
        int fedActiv = 0;
        int laxActiv = 0;
        int edfActiv = 0;
        int hybridActiv = 0;
        // Read lines in file and do average
        int i = 0;
        File f = new File(outFile);
        @SuppressWarnings("resource")
        Scanner line = new Scanner(f);
        while (line.hasNextLine()) {
            String s = line.nextLine();
            if (i > 0) { // To skip the first line
                try (Scanner inLine = new Scanner(s).useDelimiter("; ")) {
                    int j = 0;

                    while (inLine.hasNext()) {
                        String val = inLine.next();
                        if (j == 2) {
                            fedTotal += Integer.parseInt(val);
                        } else if (j == 3) {
                            fedPreempts += Integer.parseInt(val);
                        } else if (j == 4) {
                            fedActiv += Integer.parseInt(val);
                        } else if (j == 5) {
                            laxTotal += Integer.parseInt(val);
                        } else if (j == 6) {
                            laxPreempts += Integer.parseInt(val);
                        } else if (j == 7) {
                            laxActiv += Integer.parseInt(val);
                        } else if (j == 8) {
                            edfTotal += Integer.parseInt(val);
                        } else if (j == 9) {
                            edfPreempts += Integer.parseInt(val);
                        } else if (j == 10) {
                            edfActiv += Integer.parseInt(val);
                        } else if (j == 11) {
                            hybridTotal += Integer.parseInt(val);
                        } else if (j == 12) {
                            hybridPreempts += Integer.parseInt(val);
                        } else if (j == 13) {
                            hybridActiv += Integer.parseInt(val);
                        }
                        j++;
                    }
                }
            }
            i++;
        }

        // Write percentage
        double fedPerc = (double) fedTotal / nbFiles;
        double laxPerc = (double) laxTotal / nbFiles;
        double edfPerc = (double) edfTotal / nbFiles;
        double hybridPerc = (double) hybridTotal / nbFiles;

        double fedPercPreempts = (double) fedPreempts / fedActiv;
        double laxPercPreempts = (double) laxPreempts / laxActiv;
        double edfPercPreempts = (double) edfPreempts / edfActiv;
        double hybridPercPreempts = (double) hybridPreempts / hybridActiv;

        Writer wOutput = new BufferedWriter(new FileWriter(outputFilePathTotal, true));
        wOutput.write(Thread.currentThread().getName() + "; " + utilization + "; " + fedPerc + "; "
                + fedPreempts + "; " + fedActiv + "; " + fedPercPreempts + "; " + laxPerc + "; " + laxPreempts
                + "; " + laxActiv + "; " + laxPercPreempts + "; " + edfPerc + "; " + edfPreempts + "; "
                + edfActiv + "; " + edfPercPreempts + "; " + hybridPerc + "; " + hybridPreempts + "; "
                + hybridActiv + "; " + hybridPercPreempts + "\n");
        wOutput.close();

    } else if (nbLvls > 2) {
        int i_files2 = 0;
        String outFile = outputFilePath.substring(0, outputFilePath.lastIndexOf('.'))
                .concat("-schedulability.csv");
        PrintWriter writer = new PrintWriter(outFile, "UTF-8");
        writer.println(
                "Thread; File; LSched (%); LPreempts; LAct; ESched (%); EPreempts; EAct; HSched(%); HPreempts; HAct; Utilization");
        writer.close();

        ExecutorService executor2 = Executors.newFixedThreadPool(nbJobs);
        while (i_files2 != nbFiles) {
            BenchThreadNLevels bt2 = new BenchThreadNLevels(inputFilePath[i_files2], outFile, nbCores,
                    boolDebug);

            executor2.execute(bt2);
            i_files2++;
        }

        executor2.shutdown();
        executor2.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);

        int laxTotal = 0;
        int edfTotal = 0;
        int hybridTotal = 0;
        int laxPreempts = 0;
        int edfPreempts = 0;
        int hybridPreempts = 0;
        int laxActiv = 0;
        int edfActiv = 0;
        int hybridActiv = 0;
        // Read lines in file and do average
        int i = 0;
        File f = new File(outFile);
        @SuppressWarnings("resource")
        Scanner line = new Scanner(f);
        while (line.hasNextLine()) {
            String s = line.nextLine();
            if (i > 0) { // To skip the first line
                try (Scanner inLine = new Scanner(s).useDelimiter("; ")) {
                    int j = 0;

                    while (inLine.hasNext()) {
                        String val = inLine.next();
                        if (j == 2) {
                            laxTotal += Integer.parseInt(val);
                        } else if (j == 3) {
                            laxPreempts += Integer.parseInt(val);
                        } else if (j == 4) {
                            laxActiv += Integer.parseInt(val);
                        } else if (j == 5) {
                            edfTotal += Integer.parseInt(val);
                        } else if (j == 6) {
                            edfPreempts += Integer.parseInt(val);
                        } else if (j == 7) {
                            edfActiv += Integer.parseInt(val);
                        } else if (j == 8) {
                            hybridTotal += Integer.parseInt(val);
                        } else if (j == 9) {
                            hybridPreempts += Integer.parseInt(val);
                        } else if (j == 10) {
                            hybridActiv += Integer.parseInt(val);
                        }
                        j++;
                    }
                }
            }
            i++;
        }

        // Write percentage
        double laxPerc = (double) laxTotal / nbFiles;
        double edfPerc = (double) edfTotal / nbFiles;
        double hybridPerc = (double) hybridTotal / nbFiles;

        double laxPercPreempts = (double) laxPreempts / laxActiv;
        double edfPercPreempts = (double) edfPreempts / edfActiv;
        double hybridPercPreempts = (double) hybridPreempts / hybridActiv;

        Writer wOutput = new BufferedWriter(new FileWriter(outputFilePathTotal, true));
        wOutput.write(Thread.currentThread().getName() + "; " + utilization + "; " + laxPerc + "; "
                + laxPreempts + "; " + laxActiv + "; " + laxPercPreempts + "; " + edfPerc + "; " + edfPreempts
                + "; " + edfActiv + "; " + edfPercPreempts + "; " + hybridPerc + "; " + hybridPreempts + "; "
                + hybridActiv + "; " + hybridPercPreempts + "\n");
        wOutput.close();

    } else {
        System.err.println("Wrong number of levels");
        System.exit(-1);
    }

    System.out.println("[BENCH Main] Done benchmarking U = " + utilization + " Levels " + nbLvls);
}

From source file:com.github.lgi2p.obirs.utils.JSONConverter.java

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

    String annotdir = "/data/toxnuc/toxnuc_annots_5_11_14/annots";
    String annotsIndex = "/data/toxnuc/toxnuc_annots_5_11_14.json";

    File folder = new File(annotdir);
    File[] listOfFiles = folder.listFiles();

    PrintWriter printWriter = new PrintWriter(annotsIndex);

    int i = 0;/* w  w w  . j  a va  2 s. c  o m*/
    for (File file : listOfFiles) {
        if (file.isFile()) {
            System.out.println(file.getPath());
            String title = file.getName();
            String href = file.getPath();
            String json = toJSONindexFormat(i, title, Utils.readFileAsString(file), href);
            i++;

            printWriter.println(json);
        }
    }
    printWriter.close();
    System.out.println("consult: " + annotsIndex);
}

From source file:EchoClient.java

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

   ServerSocket serverSocket = null;
   try {//  w  w  w .j av a  2s  .  c  o m
      serverSocket = new ServerSocket(4444);
   } catch (IOException e) {
      System.err.println("Could not listen on port: 4444.");
      System.exit(1);
   }

   Socket clientSocket = null;
   try {
      clientSocket = serverSocket.accept();
   } catch (IOException e) {
      System.err.println("Accept failed.");
      System.exit(1);
   }

   PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
   BufferedReader in = new BufferedReader(new InputStreamReader(
         clientSocket.getInputStream()));
   String inputLine, outputLine;
   KnockKnockProtocol kkp = new KnockKnockProtocol();

   outputLine = kkp.processInput(null);
   out.println(outputLine);

   while ((inputLine = in.readLine()) != null) {
      outputLine = kkp.processInput(inputLine);
      out.println(outputLine);
      if (outputLine.equals("Bye."))
         break;
   }
   out.close();
   in.close();
   clientSocket.close();
   serverSocket.close();
}

From source file:edu.ku.brc.specify.dbsupport.cleanuptools.FirstLastVerifier.java

/**
 * @param args//from  w ww  .  jav a  2 s  .  c om
 */
public static void main(String[] args) {
    if (true) {
        testLastNames();
        return;
    }
    FirstLastVerifier flv = new FirstLastVerifier();
    System.out.println(flv.isFirstName("Bill"));
    System.out.println(flv.isLastName("Bill"));

    System.out.println(flv.isFirstName("Johnson"));
    System.out.println(flv.isLastName("Johnson"));

    try {
        if (false) {
            for (String nm : new String[] { "firstnames", "lastnames" }) {
                File file = new File("/Users/rods/Downloads/" + nm + ".txt");
                try {
                    PrintWriter pw = new PrintWriter("/Users/rods/Downloads/" + nm + ".list");
                    for (String line : (List<String>) FileUtils.readLines(file)) {
                        String[] toks = StringUtils.split(line, '\t');
                        if (toks != null && toks.length > 0)
                            pw.println(toks[0]);
                    }
                    pw.close();

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        Vector<String> lnames = new Vector<String>();
        File file = XMLHelper.getConfigDir("lastnames.list");
        if (false) {
            for (String name : (List<String>) FileUtils.readLines(file)) {
                if (flv.isFirstName(name)) {
                    System.out.println(name + " is first.");
                } else {
                    lnames.add(name);
                }
            }
            Collections.sort(lnames);
            FileUtils.writeLines(file, lnames);
        }

        lnames.clear();
        file = XMLHelper.getConfigDir("firstnames.list");
        for (String name : (List<String>) FileUtils.readLines(file)) {
            if (flv.isLastName(name)) {
                System.out.println(name + " is first.");
            } else {
                lnames.add(name);
            }
        }
        Collections.sort(lnames);
        //FileUtils.writeLines(file, lnames);

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}