Example usage for java.nio.file Files newBufferedWriter

List of usage examples for java.nio.file Files newBufferedWriter

Introduction

In this page you can find the example usage for java.nio.file Files newBufferedWriter.

Prototype

public static BufferedWriter newBufferedWriter(Path path, OpenOption... options) throws IOException 

Source Link

Document

Opens or creates a file for writing, returning a BufferedWriter to write text to the file in an efficient manner.

Usage

From source file:Test.java

public static void main(String[] args) {
    try (BufferedReader inputReader = Files.newBufferedReader(Paths.get(new URI("file:///C:/users.txt")),
            Charset.defaultCharset());
            BufferedWriter outputWriter = Files.newBufferedWriter(Paths.get(new URI("file:///C:/users.bak")),
                    Charset.defaultCharset())) {

        String inputLine;//  w  w w .j  a  v a  2 s . co  m
        while ((inputLine = inputReader.readLine()) != null) {
            outputWriter.write(inputLine);
            outputWriter.newLine();
        }
        System.out.println("Copy complete!");
    } catch (URISyntaxException | IOException ex) {
        ex.printStackTrace();
    }

}

From source file:Test.java

public static void main(String[] args) {
    try (BufferedReader inputReader = Files.newBufferedReader(Paths.get(new URI("file:///C:/users.txt")),
            Charset.defaultCharset());

            BufferedWriter outputWriter = Files.newBufferedWriter(Paths.get(new URI("file:///C:/users.bak")),
                    Charset.defaultCharset())) {

        String inputLine;/*from   w  w  w .j a v  a 2  s .  c  o  m*/
        while ((inputLine = inputReader.readLine()) != null) {
            outputWriter.write(inputLine);
            outputWriter.newLine();
        }
        System.out.println("Copy complete!");
    } catch (URISyntaxException | IOException ex) {
        ex.printStackTrace();
    }

}

From source file:io.druid.query.aggregation.datasketches.quantiles.GenerateTestData.java

public static void main(String[] args) throws Exception {
    Path buildPath = FileSystems.getDefault().getPath("doubles_build_data.tsv");
    Path sketchPath = FileSystems.getDefault().getPath("doubles_sketch_data.tsv");
    BufferedWriter buildData = Files.newBufferedWriter(buildPath, StandardCharsets.UTF_8);
    BufferedWriter sketchData = Files.newBufferedWriter(sketchPath, StandardCharsets.UTF_8);
    Random rand = new Random();
    int sequenceNumber = 0;
    for (int i = 0; i < 20; i++) {
        int product = rand.nextInt(10);
        UpdateDoublesSketch sketch = UpdateDoublesSketch.builder().build();
        for (int j = 0; j < 20; j++) {
            double value = rand.nextDouble();
            buildData.write("2016010101");
            buildData.write('\t');
            buildData.write(Integer.toString(sequenceNumber)); // dimension with unique numbers for ingesting raw data
            buildData.write('\t');
            buildData.write(Integer.toString(product)); // product dimension
            buildData.write('\t');
            buildData.write(Double.toString(value));
            buildData.newLine();/*from w ww. j av  a2 s .c o  m*/
            sketch.update(value);
            sequenceNumber++;
        }
        sketchData.write("2016010101");
        sketchData.write('\t');
        sketchData.write(Integer.toString(product)); // product dimension
        sketchData.write('\t');
        sketchData.write(Base64.encodeBase64String(sketch.toByteArray(true)));
        sketchData.newLine();
    }
    buildData.close();
    sketchData.close();
}

From source file:org.apache.druid.query.aggregation.datasketches.quantiles.GenerateTestData.java

public static void main(String[] args) throws Exception {
    Path buildPath = FileSystems.getDefault().getPath("doubles_build_data.tsv");
    Path sketchPath = FileSystems.getDefault().getPath("doubles_sketch_data.tsv");
    BufferedWriter buildData = Files.newBufferedWriter(buildPath, StandardCharsets.UTF_8);
    BufferedWriter sketchData = Files.newBufferedWriter(sketchPath, StandardCharsets.UTF_8);
    Random rand = ThreadLocalRandom.current();
    int sequenceNumber = 0;
    for (int i = 0; i < 20; i++) {
        int product = rand.nextInt(10);
        UpdateDoublesSketch sketch = UpdateDoublesSketch.builder().build();
        for (int j = 0; j < 20; j++) {
            double value = rand.nextDouble();
            buildData.write("2016010101");
            buildData.write('\t');
            buildData.write(Integer.toString(sequenceNumber)); // dimension with unique numbers for ingesting raw data
            buildData.write('\t');
            buildData.write(Integer.toString(product)); // product dimension
            buildData.write('\t');
            buildData.write(Double.toString(value));
            buildData.newLine();/*from ww  w .j av  a 2s  .c  o m*/
            sketch.update(value);
            sequenceNumber++;
        }
        sketchData.write("2016010101");
        sketchData.write('\t');
        sketchData.write(Integer.toString(product)); // product dimension
        sketchData.write('\t');
        sketchData.write(Base64.encodeBase64String(sketch.toByteArray(true)));
        sketchData.newLine();
    }
    buildData.close();
    sketchData.close();
}

From source file:com.mapr.PurchaseLog.java

public static void main(String[] args) throws IOException {
    Options opts = new Options();
    CmdLineParser parser = new CmdLineParser(opts);
    try {//from w  w w .  j  a  v  a  2s  . co m
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println("Usage: -count <number>G|M|K [ -users number ]  log-file user-profiles");
        return;
    }

    Joiner withTab = Joiner.on("\t");

    // first generate lots of user definitions
    SchemaSampler users = new SchemaSampler(
            Resources.asCharSource(Resources.getResource("user-schema.txt"), Charsets.UTF_8).read());
    File userFile = File.createTempFile("user", "tsv");
    BufferedWriter out = Files.newBufferedWriter(userFile.toPath(), Charsets.UTF_8);
    for (int i = 0; i < opts.users; i++) {
        out.write(withTab.join(users.sample()));
        out.newLine();
    }
    out.close();

    // now generate a session for each user
    Splitter onTabs = Splitter.on("\t");
    Splitter onComma = Splitter.on(",");

    Random gen = new Random();
    SchemaSampler intermediate = new SchemaSampler(
            Resources.asCharSource(Resources.getResource("hit_step.txt"), Charsets.UTF_8).read());

    final int COUNTRY = users.getFieldNames().indexOf("country");
    final int CAMPAIGN = intermediate.getFieldNames().indexOf("campaign_list");
    final int SEARCH_TERMS = intermediate.getFieldNames().indexOf("search_keywords");
    Preconditions.checkState(COUNTRY >= 0, "Need country field in user schema");
    Preconditions.checkState(CAMPAIGN >= 0, "Need campaign_list field in step schema");
    Preconditions.checkState(SEARCH_TERMS >= 0, "Need search_keywords field in step schema");

    out = Files.newBufferedWriter(new File(opts.out).toPath(), Charsets.UTF_8);

    for (String line : Files.readAllLines(userFile.toPath(), Charsets.UTF_8)) {
        long t = (long) (TimeUnit.MILLISECONDS.convert(30, TimeUnit.DAYS) * gen.nextDouble());
        List<String> user = Lists.newArrayList(onTabs.split(line));

        // pick session length
        int n = (int) Math.floor(-30 * Math.log(gen.nextDouble()));

        for (int i = 0; i < n; i++) {
            // time on page
            int dt = (int) Math.floor(-20000 * Math.log(gen.nextDouble()));
            t += dt;

            // hit specific values
            JsonNode step = intermediate.sample();

            // check for purchase
            double p = 0.01;
            List<String> campaigns = Lists.newArrayList(onComma.split(step.get("campaign_list").asText()));
            List<String> keywords = Lists.newArrayList(onComma.split(step.get("search_keywords").asText()));
            if ((user.get(COUNTRY).equals("us") && campaigns.contains("5"))
                    || (user.get(COUNTRY).equals("jp") && campaigns.contains("7")) || keywords.contains("homer")
                    || keywords.contains("simpson")) {
                p = 0.5;
            }

            String events = gen.nextDouble() < p ? "1" : "-";

            out.write(Long.toString(t));
            out.write("\t");
            out.write(line);
            out.write("\t");
            out.write(withTab.join(step));
            out.write("\t");
            out.write(events);
            out.write("\n");
        }
    }
    out.close();
}

From source file:org.eclipse.mylyn.docs.examples.GenerateEPUB.java

public static void main(String[] args) {

    // clean up from last run
    try {//  w  ww . jav  a2  s .c  o m
        Files.delete(Paths.get("loremipsum.html"));
        Files.delete(Paths.get("loremipsum.epub"));
    } catch (IOException e1) {
        /* no worries */ }

    try ( // read MarkDown
            FileReader fr = new FileReader("loremipsum.md");
            // and output HTML
            Writer fw = Files.newBufferedWriter(Paths.get("loremipsum.html"), StandardOpenOption.CREATE)) {

        // generate HTML from markdown
        MarkupParser parser = new MarkupParser();
        parser.setMarkupLanguage(new MarkdownLanguage());
        HtmlDocumentBuilder builder = new HtmlDocumentBuilder(fw);
        parser.setBuilder(builder);
        parser.parse(fr, true);

        // convert any inline equations in the HTML into MathML
        String html = new String(Files.readAllBytes(Paths.get("loremipsum.html")));
        StringBuffer sb = new StringBuffer();
        Matcher m = EQUATION.matcher(html);

        // for each equation
        while (m.find()) {
            // replace the LaTeX code with MathML
            m.appendReplacement(sb, laTeX2MathMl(m.group()));
        }
        m.appendTail(sb);

        // EPUB 2.0 can only handle embedded SVG so we find all referenced
        // SVG files and replace the reference with the actual SVG code
        Document parse = Jsoup.parse(sb.toString(), "UTF-8", Parser.xmlParser());

        Elements select = parse.select("img");
        for (Element element : select) {
            String attr = element.attr("src");
            if (attr.endsWith(".svg")) {
                byte[] svg = Files.readAllBytes(Paths.get(attr));
                element.html(new String(svg));
            }
        }

        // write back the modified HTML-file
        Files.write(Paths.get("loremipsum.html"), sb.toString().getBytes(), StandardOpenOption.WRITE);

        // instantiate a new EPUB version 2 publication
        Publication pub = Publication.getVersion2Instance();

        // include referenced resources (default is false)
        pub.setIncludeReferencedResources(true);

        // title and subject is required
        pub.addTitle("EclipseCon Demo");
        pub.addSubject("EclipseCon Demo");

        // generate table of contents (default is true)
        pub.setGenerateToc(true);
        epub.add(pub);

        // add one chapter
        pub.addItem(Paths.get("loremipsum.html").toFile());

        // create the EPUB
        epub.pack(new File("loremipsum.epub"));

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

}

From source file:org.niord.core.ChartConverter.java

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

    String csvPath = "/Users/carolus/Downloads/charts.csv";
    String resultPath = "/Users/carolus/Downloads/charts.json";

    List<SystemChartVo> charts = new ArrayList<>();

    Files.readAllLines(Paths.get(csvPath), Charset.forName("UTF-8")).forEach(line -> {
        String[] fields = line.split(";");

        SystemChartVo chart = new SystemChartVo();
        chart.setChartNumber(fields[0].split(" ")[1].trim());
        if (StringUtils.isNotBlank(fields[1]) && StringUtils.isNumeric(fields[1])) {
            chart.setInternationalNumber(Integer.valueOf(fields[1]));
        }/*w ww . jav  a2s  . c om*/

        chart.setName(StringUtils.defaultIfBlank(fields[3], ""));

        if (StringUtils.isNotBlank(fields[4]) && StringUtils.isNumeric(fields[4])) {
            chart.setScale(Integer.valueOf(fields[4]));
        }

        if (!"Ukendt / Unknown".equals(fields[5])) {
            chart.setHorizontalDatum(StringUtils.defaultIfBlank(fields[5], ""));
        }

        Double south = parsePos(fields[6]);
        Double west = -parsePos(fields[7]);
        Double north = parsePos(fields[8]);
        Double east = -parsePos(fields[9]);

        double[][] coords = new double[][] { { east, north }, { east, south }, { west, south }, { west, north },
                { east, north }, };
        PolygonVo geometry = new PolygonVo();
        geometry.setCoordinates(new double[][][] { coords });
        GeoJsonUtils.roundCoordinates(geometry, 8);
        chart.setGeometry(geometry);

        charts.add(chart);
    });

    ObjectMapper mapper = new ObjectMapper();

    System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(charts));

    try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(resultPath), StandardCharsets.UTF_8)) {
        //writer.write("\uFEFF");
        writer.write(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(charts));
    }
}

From source file:sadl.oneclassclassifier.TestOneClassSvm.java

/**
 * comparing weka LibSVM and normal libSVM result
 * //from  w ww. ja va2 s .  c  o m
 * @param args
 */
public static void main(final String[] args) {
    // feature should be at index 0
    final TestOneClassSvm tester = new TestOneClassSvm();
    // final WekaSvmClassifier wekaSvm = new WekaSvmClassifier(0, 0.2, 0.01, 1, 2, 0.001, 3, ScalingMethod.NORMALIZE);
    final LibSvmClassifier libSvm = new LibSvmClassifier(0, 0.2, 0.01, 2, 0.001, 3, ScalingMethod.NORMALIZE);
    tester.createData();
    // wekaSvm.train(train);
    libSvm.train(train);
    final Normalizer norm = new Normalizer(train.get(0).length);
    final List<double[]> normalizedTrain = norm.train(train);
    // List<double[]> normalizedTrain = train;

    final svm_model model = tester.svmTrain(normalizedTrain, 0, 0.2, 0.01, 2, 0.001, 3);
    System.out.println("testset");
    int libSvmRightAnswer = 0;
    int libSvmWrongAnswer = 0;
    // int wekaRightAnswer = 0;
    // int wekaWrongAnswer = 0;
    int wrongAnswer = 0;
    int rightAnswer = 0;
    // final boolean[] wekaTrainResult = wekaSvm.areAnomalies(train);
    // final boolean[] wekaTestResult = wekaSvm.areAnomalies(test);
    // final boolean[] libSvmTestResult = libSvm.areAnomalies(test);

    final List<double[]> normalizedTest = norm.scale(test);
    // List<double[]> normalizedTest = test;

    try (BufferedWriter bw = Files.newBufferedWriter(Paths.get("train_svm_normalized.csv"),
            StandardCharsets.UTF_8)) {
        for (final double[] ds : normalizedTrain) {
            for (int i = 0; i < ds.length; i++) {

                bw.append(Double.toString(ds[i]));
                if (i < ds.length - 1) {
                    bw.append(',');
                }
            }
            bw.append('\n');
        }
    } catch (final IOException e) {
        e.printStackTrace();
    }
    try (BufferedWriter bw = Files.newBufferedWriter(Paths.get("test_svm_normalized.csv"),
            StandardCharsets.UTF_8)) {
        for (final double[] ds : normalizedTest) {
            for (int i = 0; i < ds.length; i++) {

                bw.append(Double.toString(ds[i]));
                if (i < ds.length - 1) {
                    bw.append(',');
                }
            }
            bw.append('\n');
        }
    } catch (final IOException e) {
        e.printStackTrace();
    }

    for (int i = 0; i < test.size(); i++) {
        // all of the test data are outliers
        final boolean isAnomaly = libSvm.isOutlier(test.get(i));
        final double v = tester.evaluate(normalizedTest.get(i), model);
        if (-1 == v) {
            // libsvm says outlier
            rightAnswer++;
        } else {
            // libsvm says normal
            wrongAnswer++;
        }
        // if (wekaSvm.isOutlier(test.get(i))) {
        // weka says outlier
        // wekaRightAnswer++;
        // } else {
        // wekaWrongAnswer++;
        // }
        if (isAnomaly) {
            // libsvm says outlier
            libSvmRightAnswer++;
        } else {
            // libsvm says normal
            libSvmWrongAnswer++;
        }
    }
    System.out.println("Expected Result: 10/0");
    System.out.println("SvmResult: RightAnswers=" + rightAnswer + "; WrongAnswers=" + wrongAnswer);
    System.out
            .println("LibSvmResult: RightAnswers=" + libSvmRightAnswer + "; WrongAnswers=" + libSvmWrongAnswer);
    // System.out.println("WekaResult: RightAnswers=" + wekaRightAnswer + "; WrongAnswers=" + wekaWrongAnswer);

    libSvmRightAnswer = libSvmWrongAnswer = rightAnswer = wrongAnswer = 0;
    System.out.println("\ntrainset again");
    for (int i = 0; i < train.size(); i++) {
        // all the data should be normal!
        final boolean isAnomaly = libSvm.isOutlier(train.get(i));
        final double v = tester.evaluate(normalizedTrain.get(i), model);

        if (1 == v) {
            // libsvm says normal
            rightAnswer++;
        } else {
            // libsvm says outlier
            wrongAnswer++;
        }
        // if (wekaSvm.isOutlier(train.get(i))) {
        // // System.err.println("weka says something different");
        // wekaWrongAnswer++;
        // } else {
        // wekaRightAnswer++;
        // }
        if (!isAnomaly) {
            // libsvm says normal
            libSvmRightAnswer++;
        } else {
            // libsvm says outlier
            libSvmWrongAnswer++;
        }
    }
    System.out.println("Expected Result with this parameter setting: 600/400");
    System.out.println("SvmResult: RightAnswers=" + rightAnswer + "; WrongAnswers=" + wrongAnswer);
    System.out
            .println("LibSvmResult: RightAnswers=" + libSvmRightAnswer + "; WrongAnswers=" + libSvmWrongAnswer);
    // System.out.println("WekaResult: RightAnswers=" + wekaRightAnswer + "; WrongAnswers=" + wekaWrongAnswer);

    // will return 800/200 with this parameter setting

    // if (!Arrays.equals(libSvmTrainResult, wekaTrainResult) || !Arrays.equals(libSvmTestResult, wekaTestResult)) {
    // System.err.println("Weka and libsvm do not result in same output");
    // }
}

From source file:net.tirasa.ilgrosso.lngenerator.Main.java

public static void main(final String[] args) throws IOException, URISyntaxException {
    assert args.length > 0 : "No arguments provided";

    File source = new File(args[0]);
    if (!source.isDirectory()) {
        throw new IllegalArgumentException("Not a directory: " + args[0]);
    }/* ww w . j a  va 2  s  .  c om*/

    String destPath = args.length > 1 ? args[1] : System.getProperty("java.io.tmpdir");
    File dest = new File(destPath);
    if (!dest.isDirectory() || !dest.canWrite()) {
        throw new IllegalArgumentException("Not a directory, or not writable: " + destPath);
    }

    LOG.debug("Local Maven repo is {}", LOCAL_M2_REPO);
    LOG.debug("Source Path is {}", source.getAbsolutePath());
    LOG.debug("Destination Path is {}", dest.getAbsolutePath());
    LOG.warn("Existing LICENSE and NOTICE files in {} will be overwritten!", dest.getAbsolutePath());

    Set<String> keys = new HashSet<>();

    Files.walk(source.toPath()).filter(Files::isRegularFile)
            .map((final Path path) -> path.getFileName().toString())
            .filter((String path) -> path.endsWith(".jar")).sorted().forEach((filename) -> {
                try (Stream<Path> stream = Files.find(LOCAL_M2_REPO_PATH, 10,
                        (path, attr) -> String.valueOf(path.getFileName().toString()).equals(filename))) {

                    String fullPath = stream.sorted().map(String::valueOf).collect(Collectors.joining("; "));
                    if (fullPath.isEmpty()) {
                        LOG.warn("Could not find {} in the local Maven repo", filename);
                    } else {
                        String path = fullPath.substring(LOCAL_M2_REPO.length() + 1);
                        Gav gav = GAV_CALCULATOR.pathToGav(path);
                        if (gav == null) {
                            LOG.error("Invalid Maven path: {}", path);
                        } else if (!gav.getGroupId().startsWith("org.apache.")
                                && !gav.getGroupId().startsWith("commons-")
                                && !gav.getGroupId().equals("org.codehaus.groovy")
                                && !gav.getGroupId().equals("jakarta-regexp")
                                && !gav.getGroupId().equals("xml-apis") && !gav.getGroupId().equals("batik")) {

                            if (ArrayUtils.contains(CONSOLIDATING_GROUP_IDS, gav.getGroupId())) {
                                keys.add(gav.getGroupId());
                            } else if (gav.getGroupId().startsWith("com.fasterxml.jackson")) {
                                keys.add("com.fasterxml.jackson");
                            } else if (gav.getGroupId().equals("org.webjars.bower") && (gav.getArtifactId()
                                    .startsWith("angular-animate")
                                    || gav.getArtifactId().startsWith("angular-cookies")
                                    || gav.getArtifactId().startsWith("angular-resource")
                                    || gav.getArtifactId().startsWith("angular-sanitize")
                                    || gav.getArtifactId().startsWith("angular-treasure-overlay-spinner"))) {

                                keys.add("org.webjars.bower:angular");
                            } else if (gav.getGroupId().equals("org.webjars.bower")
                                    && gav.getArtifactId().startsWith("angular-translate")) {

                                keys.add("org.webjars.bower:angular-translate");
                            } else if (gav.getGroupId().startsWith("de.agilecoders")) {
                                keys.add("wicket-bootstrap");
                            } else if ("org.webjars".equals(gav.getGroupId())) {
                                if (gav.getArtifactId().startsWith("jquery-ui")) {
                                    keys.add("jquery-ui");
                                } else {
                                    keys.add(gav.getArtifactId());
                                }
                            } else {
                                keys.add(gav.getGroupId() + ":" + gav.getArtifactId());
                            }
                        }
                    }
                } catch (IOException e) {
                    LOG.error("While looking for Maven artifacts from the local Maven repo", e);
                }
            });

    final Properties licenses = new Properties();
    licenses.loadFromXML(Main.class.getResourceAsStream("/licenses.xml"));

    final Properties notices = new Properties();
    notices.loadFromXML(Main.class.getResourceAsStream("/notices.xml"));

    BufferedWriter licenseWriter = Files.newBufferedWriter(new File(dest, "LICENSE").toPath(),
            StandardOpenOption.CREATE);
    licenseWriter.write(
            new String(Files.readAllBytes(Paths.get(Main.class.getResource("/LICENSE.template").toURI()))));

    BufferedWriter noticeWriter = Files.newBufferedWriter(new File(dest, "NOTICE").toPath(),
            StandardOpenOption.CREATE);
    noticeWriter.write(
            new String(Files.readAllBytes(Paths.get(Main.class.getResource("/NOTICE.template").toURI()))));

    EnumSet<LICENSE> outputLicenses = EnumSet.noneOf(LICENSE.class);

    keys.stream().sorted().forEach((final String dependency) -> {
        if (licenses.getProperty(dependency) == null) {
            LOG.error("Could not find license information about {}", dependency);
        } else {
            try {
                licenseWriter.write("\n==\n\nFor " + licenses.getProperty(dependency) + ":\n");

                String depLicense = licenses.getProperty(dependency + ".license");
                if (depLicense == null) {
                    licenseWriter.write("This is licensed under the AL 2.0, see above.");
                } else {
                    LICENSE license = LICENSE.valueOf(depLicense);

                    if (license == LICENSE.PUBLIC_DOMAIN) {
                        licenseWriter.write("This is " + license.getLabel() + ".");
                    } else {
                        licenseWriter.write("This is licensed under the " + license.getLabel());

                        if (outputLicenses.contains(license)) {
                            licenseWriter.write(", see above.");
                        } else {
                            outputLicenses.add(license);

                            licenseWriter.write(":\n\n");
                            licenseWriter.write(new String(Files.readAllBytes(
                                    Paths.get(Main.class.getResource("/LICENSE." + license.name()).toURI()))));
                        }
                    }
                }
                licenseWriter.write('\n');

                if (notices.getProperty(dependency) != null) {
                    noticeWriter.write("\n==\n\n" + notices.getProperty(dependency) + "\n");
                }
            } catch (Exception e) {
                LOG.error("While dealing with {}", dependency, e);
            }
        }
    });

    licenseWriter.close();
    noticeWriter.close();

    LOG.debug("Execution completed successfully, look at {} for the generated LICENSE and NOTICE files",
            dest.getAbsolutePath());
}

From source file:de.huberlin.wbi.cuneiform.cmdline.main.Main.java

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

    CommandLine cmd;//w ww .  ja  va2s  .co  m
    Options opt;
    BaseRepl repl;
    BaseCreActor cre;
    Path sandbox;
    ExecutorService executor;
    TicketSrcActor ticketSrc;
    JsonSummary summary;
    Path summaryPath;
    Log statLog;
    int nthread;
    Path workDir;

    statLog = LogFactory.getLog("statLogger");

    executor = Executors.newCachedThreadPool();
    try {

        opt = getOptions();
        cmd = parse(args, opt);
        config(cmd);

        if (cmd.hasOption('h')) {

            System.out.println("CUNEIFORM - A Functional Workflow Language\nversion " + BaseRepl.LABEL_VERSION
                    + " build " + BaseRepl.LABEL_BUILD);
            new HelpFormatter().printHelp("java -jar cuneiform.jar [OPTION]*", opt);

            return;
        }

        if (cmd.hasOption('r'))
            Invocation.putLibPath(ForeignLambdaExpr.LANGID_R, cmd.getOptionValue('r'));

        if (cmd.hasOption('y'))
            Invocation.putLibPath(ForeignLambdaExpr.LANGID_PYTHON, cmd.getOptionValue('y'));

        if (cmd.hasOption('l'))
            sandbox = Paths.get(cmd.getOptionValue("l"));
        else
            sandbox = Paths.get(System.getProperty("user.home")).resolve(".cuneiform");

        sandbox = sandbox.toAbsolutePath();

        if (cmd.hasOption('c'))
            LocalThread.deleteIfExists(sandbox);

        if (cmd.hasOption('t'))
            nthread = Integer.valueOf(cmd.getOptionValue('t'));
        else
            nthread = Runtime.getRuntime().availableProcessors();

        if (cmd.hasOption('w'))
            workDir = Paths.get(cmd.getOptionValue('w'));
        else
            workDir = Paths.get(System.getProperty("user.dir"));

        workDir = workDir.toAbsolutePath();

        switch (platform) {

        case PLATFORM_LOCAL:

            if (!Files.exists(sandbox))
                Files.createDirectories(sandbox);

            cre = new LocalCreActor(sandbox, workDir, nthread);
            break;

        case PLATFORM_HTCONDOR:

            if (!Files.exists(sandbox))
                Files.createDirectories(sandbox);

            if (cmd.hasOption('m')) { // MAX_TRANSFER SIZE
                String maxTransferSize = cmd.getOptionValue('m');
                try {
                    cre = new CondorCreActor(sandbox, maxTransferSize);
                } catch (Exception e) {
                    System.out.println("INVALID '-m' option value: " + maxTransferSize
                            + "\n\nCUNEIFORM - A Functional Workflow Language\nversion "
                            + BaseRepl.LABEL_VERSION + " build " + BaseRepl.LABEL_BUILD);
                    new HelpFormatter().printHelp("java -jar cuneiform.jar [OPTION]*", opt);

                    return;
                }
            } else {
                cre = new CondorCreActor(sandbox);
            }

            break;

        default:
            throw new RuntimeException("Platform not recognized.");
        }

        executor.submit(cre);
        ticketSrc = new TicketSrcActor(cre);
        executor.submit(ticketSrc);
        executor.shutdown();

        switch (format) {

        case FORMAT_CF:

            if (cmd.hasOption("i"))
                repl = new InteractiveRepl(ticketSrc, statLog);
            else
                repl = new CmdlineRepl(ticketSrc, statLog);
            break;

        case FORMAT_DAX:
            repl = new DaxRepl(ticketSrc, statLog);
            break;

        default:
            throw new RuntimeException("Format not recognized.");
        }

        if (cmd.hasOption("i")) {

            // run in interactive mode
            BaseRepl.run(repl);

            return;
        }

        // run in quiet mode

        if (inputFileVector.length > 0)

            for (Path f : inputFileVector)
                repl.interpret(readFile(f));

        else
            repl.interpret(readStdIn());

        Thread.sleep(3 * Actor.DELAY);
        while (repl.isBusy())
            Thread.sleep(Actor.DELAY);

        if (cmd.hasOption("s")) {

            summary = new JsonSummary(ticketSrc.getRunId(), sandbox, repl.getAns());
            summaryPath = Paths.get(cmd.getOptionValue("s"));
            summaryPath = summaryPath.toAbsolutePath();
            try (BufferedWriter writer = Files.newBufferedWriter(summaryPath, Charset.forName("UTF-8"))) {

                writer.write(summary.toString());
            }

        }

    } finally {
        executor.shutdownNow();
    }

}