Example usage for java.io File exists

List of usage examples for java.io File exists

Introduction

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

Prototype

public boolean exists() 

Source Link

Document

Tests whether the file or directory denoted by this abstract pathname exists.

Usage

From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step6HITPreparator.java

public static void main(String[] args) throws Exception {
    // input dir - list of xml query containers
    // step5-linguistic-annotation/
    System.err.println("Starting step 6 HIT Preparation");

    File inputDir = new File(args[0]);

    // output dir
    File outputDir = new File(args[1]);
    if (outputDir.exists()) {
        outputDir.delete();//w  w w  .j  a v a  2 s  .  com
    }
    outputDir.mkdir();

    List<String> queries = new ArrayList<>();

    // iterate over query containers
    int countClueWeb = 0;
    int countSentence = 0;
    for (File f : FileUtils.listFiles(inputDir, new String[] { "xml" }, false)) {
        QueryResultContainer queryResultContainer = QueryResultContainer
                .fromXML(FileUtils.readFileToString(f, "utf-8"));
        if (queries.contains(f.getName()) || queries.size() == 0) {
            // groups contain only non-empty documents
            Map<Integer, List<QueryResultContainer.SingleRankedResult>> groups = new HashMap<>();

            // split to groups according to number of sentences
            for (QueryResultContainer.SingleRankedResult rankedResult : queryResultContainer.rankedResults) {
                if (rankedResult.originalXmi != null) {
                    byte[] bytes = new BASE64Decoder()
                            .decodeBuffer(new ByteArrayInputStream(rankedResult.originalXmi.getBytes()));
                    JCas jCas = JCasFactory.createJCas();
                    XmiCasDeserializer.deserialize(new ByteArrayInputStream(bytes), jCas.getCas());

                    Collection<Sentence> sentences = JCasUtil.select(jCas, Sentence.class);

                    int groupId = sentences.size() / 40;
                    if (rankedResult.originalXmi == null) {
                        System.err.println("Empty document: " + rankedResult.clueWebID);
                    } else {
                        if (!groups.containsKey(groupId)) {
                            groups.put(groupId, new ArrayList<>());

                        }
                    }
                    //handle it
                    groups.get(groupId).add(rankedResult);
                    countClueWeb++;
                }
            }

            for (Map.Entry<Integer, List<QueryResultContainer.SingleRankedResult>> entry : groups.entrySet()) {
                Integer groupId = entry.getKey();
                List<QueryResultContainer.SingleRankedResult> rankedResults = entry.getValue();

                // make sure the results are sorted
                // DEBUG
                //                for (QueryResultContainer.SingleRankedResult r : rankedResults) {
                //                    System.out.print(r.rank + "\t");
                //                }

                Collections.sort(rankedResults, (o1, o2) -> o1.rank.compareTo(o2.rank));

                // iterate over results for one query and group
                for (int i = 0; i < rankedResults.size() && i < TOP_RESULTS_PER_GROUP; i++) {
                    QueryResultContainer.SingleRankedResult rankedResult = rankedResults.get(i);

                    QueryResultContainer.SingleRankedResult r = rankedResults.get(i);
                    int rank = r.rank;
                    MustacheFactory mf = new DefaultMustacheFactory();
                    Mustache mustache = mf.compile("template/template.html");
                    String queryId = queryResultContainer.qID;
                    String query = queryResultContainer.query;
                    // make the first letter uppercase
                    query = query.substring(0, 1).toUpperCase() + query.substring(1);

                    List<String> relevantInformationExamples = queryResultContainer.relevantInformationExamples;
                    List<String> irrelevantInformationExamples = queryResultContainer.irrelevantInformationExamples;
                    byte[] bytes = new BASE64Decoder()
                            .decodeBuffer(new ByteArrayInputStream(rankedResult.originalXmi.getBytes()));

                    JCas jCas = JCasFactory.createJCas();
                    XmiCasDeserializer.deserialize(new ByteArrayInputStream(bytes), jCas.getCas());

                    List<generators.Sentence> sentences = new ArrayList<>();
                    List<Integer> paragraphs = new ArrayList<>();
                    paragraphs.add(0);

                    for (WebParagraph webParagraph : JCasUtil.select(jCas, WebParagraph.class)) {
                        for (Sentence s : JCasUtil.selectCovered(Sentence.class, webParagraph)) {

                            String sentenceBegin = String.valueOf(s.getBegin());
                            generators.Sentence sentence = new generators.Sentence(s.getCoveredText(),
                                    sentenceBegin);
                            sentences.add(sentence);
                            countSentence++;
                        }
                        int SentenceID = paragraphs.get(paragraphs.size() - 1);
                        if (sentences.size() > 120)
                            while (SentenceID < sentences.size()) {
                                if (!paragraphs.contains(SentenceID))
                                    paragraphs.add(SentenceID);
                                SentenceID = SentenceID + 120;
                            }
                        paragraphs.add(sentences.size());

                    }
                    System.err.println("Output dir: " + outputDir);
                    int startID = 0;
                    int endID;

                    for (int j = 0; j < paragraphs.size(); j++) {

                        endID = paragraphs.get(j);
                        int sentLength = endID - startID;
                        if (sentLength > 120 || j == paragraphs.size() - 1) {
                            if (sentLength > 120) {

                                endID = paragraphs.get(j - 1);
                                j--;
                            }
                            sentLength = endID - startID;
                            if (sentLength <= 40)
                                groupId = 40;
                            else if (sentLength <= 80 && sentLength > 40)
                                groupId = 80;
                            else if (sentLength > 80)
                                groupId = 120;

                            File folder = new File(outputDir + "/" + groupId);
                            if (!folder.exists()) {
                                System.err.println("creating directory: " + outputDir + "/" + groupId);
                                boolean result = false;

                                try {
                                    folder.mkdir();
                                    result = true;
                                } catch (SecurityException se) {
                                    //handle it
                                }
                                if (result) {
                                    System.out.println("DIR created");
                                }
                            }

                            String newHtmlFile = folder.getAbsolutePath() + "/" + f.getName() + "_"
                                    + rankedResult.clueWebID + "_" + sentLength + ".html";
                            System.err.println("Printing a file: " + newHtmlFile);
                            File newHTML = new File(newHtmlFile);
                            int t = 0;
                            while (newHTML.exists()) {
                                newHTML = new File(folder.getAbsolutePath() + "/" + f.getName() + "_"
                                        + rankedResult.clueWebID + "_" + sentLength + "." + t + ".html");
                                t++;
                            }
                            mustache.execute(new PrintWriter(new FileWriter(newHTML)),
                                    new generators(query, relevantInformationExamples,
                                            irrelevantInformationExamples, sentences.subList(startID, endID),
                                            queryId, rank))
                                    .flush();
                            startID = endID;
                        }
                    }
                }
            }

        }
    }
    System.out.println("Printed " + countClueWeb + " documents with " + countSentence + " sentences");
}

From source file:com.act.lcms.v2.fullindex.Searcher.java

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

    File indexDir = new File(cl.getOptionValue(OPTION_INDEX_PATH));
    if (!indexDir.exists() || !indexDir.isDirectory()) {
        cliUtil.failWithMessage("Unable to read index directory at %s", indexDir.getAbsolutePath());
    }/*from w  ww .  jav a 2 s. co m*/

    if (!cl.hasOption(OPTION_MZ_RANGE) && !cl.hasOption(OPTION_TIME_RANGE)) {
        cliUtil.failWithMessage(
                "Extracting all readings is not currently supported; specify an m/z or time range");
    }

    Pair<Double, Double> mzRange = extractRange(cl.getOptionValue(OPTION_MZ_RANGE));
    Pair<Double, Double> timeRange = extractRange(cl.getOptionValue(OPTION_TIME_RANGE));

    Searcher searcher = Factory.makeSearcher(indexDir);
    List<TMzI> results = searcher.searchIndexInRange(mzRange, timeRange);

    if (cl.hasOption(OPTION_OUTPUT_FILE)) {
        try (PrintWriter writer = new PrintWriter(new FileWriter(cl.getOptionValue(OPTION_OUTPUT_FILE)))) {
            Searcher.writeOutput(writer, results);
        }
    } else {
        // Don't close the print writer if we're writing to stdout.
        Searcher.writeOutput(new PrintWriter(new OutputStreamWriter(System.out)), results);
    }

    LOGGER.info("Done");
}

From source file:com.sangupta.keepwalking.MergeRepo.java

/**
 * @param args/*w w  w  . j av  a  2s. c o m*/
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {
    if (args.length != 3) {
        usage();
        return;
    }

    final String previousRepo = args[0];
    final String newerRepo = args[1];
    final String mergedRepo = args[2];

    final File previous = new File(previousRepo);
    final File newer = new File(newerRepo);
    final File merged = new File(mergedRepo);

    if (!(previous.exists() && previous.isDirectory())) {
        System.out.println("The previous version does not exists or is not a directory.");
        return;
    }

    if (!(newer.exists() && newer.isDirectory())) {
        System.out.println("The newer version does not exists or is not a directory.");
        return;
    }

    final IOFileFilter directoryFilter = FileFilterUtils.makeCVSAware(FileFilterUtils.makeSVNAware(null));

    final Collection<File> olderFiles = FileUtils.listFiles(previous, TrueFileFilter.TRUE, directoryFilter);
    final Collection<File> newerFiles = FileUtils.listFiles(newer, TrueFileFilter.TRUE, directoryFilter);

    // build a list of unique paths
    System.out.println("Reading files from older version...");
    List<String> olderPaths = new ArrayList<String>();
    for (File oldFile : olderFiles) {
        olderPaths.add(getRelativePath(oldFile, previous));
    }

    System.out.println("Reading files from newer version...");
    List<String> newerPaths = new ArrayList<String>();
    for (File newerFile : newerFiles) {
        newerPaths.add(getRelativePath(newerFile, newer));
    }

    // find which files have been removed from Perforce depot
    List<String> filesRemoved = new ArrayList<String>(olderPaths);
    filesRemoved.removeAll(newerPaths);
    System.out.println("Files removed in newer version: " + filesRemoved.size());
    for (String removed : filesRemoved) {
        System.out.print("    ");
        System.out.println(removed);
    }

    // find which files have been added in Perforce depot
    List<String> filesAdded = new ArrayList<String>(newerPaths);
    filesAdded.removeAll(olderPaths);
    System.out.println("Files added in newer version: " + filesAdded.size());
    for (String added : filesAdded) {
        System.out.print("    ");
        System.out.println(added);
    }

    // find which files are common 
    // now check if they have modified or not
    newerPaths.retainAll(olderPaths);
    List<String> modified = checkModifiedFiles(newerPaths, previous, newer);
    System.out.println("Files modified in newer version: " + modified.size());
    for (String modify : modified) {
        System.out.print("    ");
        System.out.println(modify);
    }

    // clean any previous existence of merged repo
    System.out.println("Cleaning any previous merged repositories...");
    if (merged.exists() && merged.isDirectory()) {
        FileUtils.deleteDirectory(merged);
    }

    System.out.println("Merging from newer to older repository...");
    // copy the original SVN repo to merged
    FileUtils.copyDirectory(previous, merged);

    // now remove all files that need to be
    for (String removed : filesRemoved) {
        File toRemove = new File(merged, removed);
        toRemove.delete();
    }

    // now add all files that are new in perforce
    for (String added : filesAdded) {
        File toAdd = new File(newer, added);
        File destination = new File(merged, added);
        FileUtils.copyFile(toAdd, destination);
    }

    // now over-write modified files
    for (String changed : modified) {
        File change = new File(newer, changed);
        File destination = new File(merged, changed);
        destination.delete();
        FileUtils.copyFile(change, destination);
    }

    System.out.println("Done merging.");
}

From source file:com.jbrisbin.groovy.mqdsl.RabbitMQDsl.java

public static void main(String[] argv) {

    // Parse command line arguments
    CommandLine args = null;/*from  www .  j  a  v  a2s  .  c o  m*/
    try {
        Parser p = new BasicParser();
        args = p.parse(cliOpts, argv);
    } catch (ParseException e) {
        log.error(e.getMessage(), e);
    }

    // Check for help
    if (args.hasOption('?')) {
        printUsage();
        return;
    }

    // Runtime properties
    Properties props = System.getProperties();

    // Check for ~/.rabbitmqrc
    File userSettings = new File(System.getProperty("user.home"), ".rabbitmqrc");
    if (userSettings.exists()) {
        try {
            props.load(new FileInputStream(userSettings));
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    // Load Groovy builder file
    StringBuffer script = new StringBuffer();
    BufferedInputStream in = null;
    String filename = "<STDIN>";
    if (args.hasOption("f")) {
        filename = args.getOptionValue("f");
        try {
            in = new BufferedInputStream(new FileInputStream(filename));
        } catch (FileNotFoundException e) {
            log.error(e.getMessage(), e);
        }
    } else {
        in = new BufferedInputStream(System.in);
    }

    // Read script
    if (null != in) {
        byte[] buff = new byte[4096];
        try {
            for (int read = in.read(buff); read > -1;) {
                script.append(new String(buff, 0, read));
                read = in.read(buff);
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    } else {
        System.err.println("No script file to evaluate...");
    }

    PrintStream stdout = System.out;
    PrintStream out = null;
    if (args.hasOption("o")) {
        try {
            out = new PrintStream(new FileOutputStream(args.getOptionValue("o")), true);
            System.setOut(out);
        } catch (FileNotFoundException e) {
            log.error(e.getMessage(), e);
        }
    }

    String[] includes = (System.getenv().containsKey("MQDSL_INCLUDE")
            ? System.getenv("MQDSL_INCLUDE").split(String.valueOf(File.pathSeparatorChar))
            : new String[] { System.getenv("HOME") + File.separator + ".mqdsl.d" });

    try {
        // Setup RabbitMQ
        String username = (args.hasOption("U") ? args.getOptionValue("U")
                : props.getProperty("mq.user", "guest"));
        String password = (args.hasOption("P") ? args.getOptionValue("P")
                : props.getProperty("mq.password", "guest"));
        String virtualHost = (args.hasOption("v") ? args.getOptionValue("v")
                : props.getProperty("mq.virtualhost", "/"));
        String host = (args.hasOption("h") ? args.getOptionValue("h")
                : props.getProperty("mq.host", "localhost"));
        int port = Integer.parseInt(
                args.hasOption("p") ? args.getOptionValue("p") : props.getProperty("mq.port", "5672"));

        CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host);
        connectionFactory.setPort(port);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        if (null != virtualHost) {
            connectionFactory.setVirtualHost(virtualHost);
        }

        // The DSL builder
        RabbitMQBuilder builder = new RabbitMQBuilder();
        builder.setConnectionFactory(connectionFactory);
        // Our execution environment
        Binding binding = new Binding(args.getArgs());
        binding.setVariable("mq", builder);
        String fileBaseName = filename.replaceAll("\\.groovy$", "");
        binding.setVariable("log",
                LoggerFactory.getLogger(fileBaseName.substring(fileBaseName.lastIndexOf("/") + 1)));
        if (null != out) {
            binding.setVariable("out", out);
        }

        // Include helper files
        GroovyShell shell = new GroovyShell(binding);
        for (String inc : includes) {
            File f = new File(inc);
            if (f.isDirectory()) {
                File[] files = f.listFiles(new FilenameFilter() {
                    @Override
                    public boolean accept(File file, String s) {
                        return s.endsWith(".groovy");
                    }
                });
                for (File incFile : files) {
                    run(incFile, shell, binding);
                }
            } else {
                run(f, shell, binding);
            }
        }

        run(script.toString(), shell, binding);

        while (builder.isActive()) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                log.error(e.getMessage(), e);
            }
        }

        if (null != out) {
            out.close();
            System.setOut(stdout);
        }

    } finally {
        System.exit(0);
    }
}

From source file:eu.ensure.aging.AgingSimulator.java

public static void main(String[] args) {

    Options options = new Options();
    options.addOption("n", "flip-bit-in-name", true, "Flip bit in first byte of name of first file");
    options.addOption("u", "flip-bit-in-uname", true, "Flip bit in first byte of username of first file");
    options.addOption("c", "update-checksum", true, "Update header checksum (after prior bit flips)");

    Properties properties = new Properties();
    CommandLineParser parser = new PosixParser();
    try {/* w  w w. java  2 s .  com*/
        CommandLine line = parser.parse(options, args);

        //
        if (line.hasOption("flip-bit-in-name")) {
            properties.put("flip-bit-in-name", line.getOptionValue("flip-bit-in-name"));
        } else {
            // On by default (if not explicitly de-activated above)
            properties.put("flip-bit-in-name", "true");
        }

        //
        if (line.hasOption("flip-bit-in-uname")) {
            properties.put("flip-bit-in-uname", line.getOptionValue("flip-bit-in-uname"));
        } else {
            properties.put("flip-bit-in-uname", "false");
        }

        //
        if (line.hasOption("update-checksum")) {
            properties.put("update-checksum", line.getOptionValue("update-checksum"));
        } else {
            properties.put("update-checksum", "false");
        }

        String[] fileArgs = line.getArgs();

        if (fileArgs.length < 1) {
            printHelp(options, System.err);
            System.exit(1);
        }

        String srcPath = fileArgs[0];

        File srcAIP = new File(srcPath);
        if (!srcAIP.exists()) {
            String info = "The source path does not locate a file: " + srcPath;
            System.err.println(info);
            System.exit(1);
        }

        if (srcAIP.isDirectory()) {
            String info = "The source path locates a directory, not a file: " + srcPath;
            System.err.println(info);
            System.exit(1);
        }

        if (!srcAIP.canRead()) {
            String info = "Cannot read source file: " + srcPath;
            System.err.println(info);
            System.exit(1);
        }

        boolean doReplace = false;
        File destAIP = null;

        if (fileArgs.length > 1) {
            String destPath = fileArgs[1];
            destAIP = new File(destPath);

            if (destAIP.exists()) {
                String info = "The destination path locates an existing file: " + destPath;
                System.err.println(info);
                System.exit(1);
            }
        } else {
            doReplace = true;
            try {
                destAIP = File.createTempFile("tmp-aged-aip-", ".tar");
            } catch (IOException ioe) {
                String info = "Failed to create temporary file: ";
                info += ioe.getMessage();
                System.err.println(info);
                System.exit(1);
            }
        }

        String info = "Age simulation\n";
        info += "  Reading from " + srcAIP.getName() + "\n";
        if (doReplace) {
            info += "  and replacing it's content";
        } else {
            info += "  Writing to " + destAIP.getName();
        }
        System.out.println(info);

        //
        InputStream is = null;
        OutputStream os = null;
        try {
            is = new BufferedInputStream(new FileInputStream(srcAIP));
            os = new BufferedOutputStream(new FileOutputStream(destAIP));

            simulateAging(srcAIP.getName(), is, os, properties);

        } catch (FileNotFoundException fnfe) {
            info = "Could not locate file: " + fnfe.getMessage();
            System.err.println(info);
        } finally {
            try {
                if (null != os)
                    os.close();
                if (null != is)
                    is.close();
            } catch (IOException ignore) {
            }
        }

        //
        if (doReplace) {
            File renamedOriginal = new File(srcAIP.getName() + "-backup");
            srcAIP.renameTo(renamedOriginal);

            ReadableByteChannel rbc = null;
            WritableByteChannel wbc = null;
            try {
                rbc = Channels.newChannel(new FileInputStream(destAIP));
                wbc = Channels.newChannel(new FileOutputStream(srcAIP));
                FileIO.fastChannelCopy(rbc, wbc);
            } catch (FileNotFoundException fnfe) {
                info = "Could not locate temporary output file: " + fnfe.getMessage();
                System.err.println(info);
            } catch (IOException ioe) {
                info = "Could not copy temporary output file over original AIP: " + ioe.getMessage();
                System.err.println(info);
            } finally {
                try {
                    if (null != wbc)
                        wbc.close();
                    if (null != rbc)
                        rbc.close();

                    destAIP.delete();
                } catch (IOException ignore) {
                }
            }
        }
    } catch (ParseException pe) {
        String info = "Failed to parse command line: " + pe.getMessage();
        System.err.println(info);
        printHelp(options, System.err);
        System.exit(1);
    }
}

From source file:com.act.analysis.surfactant.AnalysisDriver.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());/*from  w  w  w  . j  a  va2  s  .  c  om*/
    }

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        System.err.format("Argument parsing failed: %s\n", e.getMessage());
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        return;
    }

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

    TSVWriter<String, String> tsvWriter = null;
    if (cl.hasOption(OPTION_OUTPUT_FILE)) {
        File outputFile = new File(cl.getOptionValue(OPTION_OUTPUT_FILE));
        List<Map<String, String>> oldResults = null;
        if (outputFile.exists()) {
            System.err.format(
                    "Output file already exists, reading old results and skipping processed molecules.\n");
            TSVParser outputParser = new TSVParser();
            outputParser.parse(outputFile);
            oldResults = outputParser.getResults();
            for (Map<String, String> row : oldResults) {
                // TODO: verify that the last row was written cleanly/completely.
                seenOutputIds.add(row.get("id"));
            }
        }

        List<String> header = new ArrayList<>();
        header.add("name");
        header.add("id");
        header.add("inchi");
        header.add("label");
        for (SurfactantAnalysis.FEATURES f : SurfactantAnalysis.FEATURES.values()) {
            header.add(f.toString());
        }
        // TODO: make this API more auto-closable friendly.
        tsvWriter = new TSVWriter<>(header);
        tsvWriter.open(outputFile);
        if (oldResults != null) {
            System.out.format("Re-writing %d existing result rows\n", oldResults.size());
            tsvWriter.append(oldResults);
        }
    }

    try {
        Map<SurfactantAnalysis.FEATURES, Double> analysisFeatures;

        LicenseManager.setLicenseFile(cl.getOptionValue(OPTION_LICENSE_FILE));
        if (cl.hasOption(OPTION_INCHI)) {
            analysisFeatures = SurfactantAnalysis.performAnalysis(cl.getOptionValue(OPTION_INCHI),
                    cl.hasOption(OPTION_DISPLAY));
            Map<String, String> tsvFeatures = new HashMap<>();
            // Convert features to strings to avoid some weird formatting issues.  It's ugly, but it works.
            for (Map.Entry<SurfactantAnalysis.FEATURES, Double> entry : analysisFeatures.entrySet()) {
                tsvFeatures.put(entry.getKey().toString(), String.format("%.6f", entry.getValue()));
            }
            tsvFeatures.put("name", "direct-inchi-input");
            if (tsvWriter != null) {
                tsvWriter.append(tsvFeatures);
            }
        } else if (cl.hasOption(OPTION_INPUT_FILE)) {
            TSVParser parser = new TSVParser();
            parser.parse(new File(cl.getOptionValue(OPTION_INPUT_FILE)));
            int i = 0;
            List<Map<String, String>> inputRows = parser.getResults();

            for (Map<String, String> row : inputRows) {
                i++; // Just for warning messages.
                if (!row.containsKey("name") || !row.containsKey("id") || !row.containsKey("inchi")) {
                    System.err.format(
                            "WARNING: TSV rows must contain at least name, id, and inchi, skipping row %d\n",
                            i);
                    continue;
                }
                if (seenOutputIds.contains(row.get("id"))) {
                    System.out.format("Skipping input row with id already in output: %s\n", row.get("id"));
                    continue;
                }

                System.out.format("Analysis for chemical %s\n", row.get("name"));
                try {
                    analysisFeatures = SurfactantAnalysis.performAnalysis(row.get("inchi"), false);
                } catch (Exception e) {
                    // Ignore exceptions for now.  Sometimes the regression analysis or Chemaxon processing chokes unexpectedly.
                    System.err.format("ERROR caught exception while processing '%s':\n", row.get("name"));
                    System.err.format("%s\n", e.getMessage());
                    e.printStackTrace(System.err);
                    System.err.println("Skipping...");
                    continue;
                }
                System.out.format("--- Done analysis for chemical %s\n", row.get("name"));

                // This is a duplicate of the OPTION_INCHI block code, but it's inside of a tight loop, so...
                Map<String, String> tsvFeatures = new HashMap<>();
                for (Map.Entry<SurfactantAnalysis.FEATURES, Double> entry : analysisFeatures.entrySet()) {
                    tsvFeatures.put(entry.getKey().toString(), String.format("%.6f", entry.getValue()));
                }
                tsvFeatures.put("name", row.get("name"));
                tsvFeatures.put("id", row.get("id"));
                tsvFeatures.put("inchi", row.get("inchi"));
                tsvFeatures.put("label", row.containsKey("label") ? row.get("label") : "?");
                if (tsvWriter != null) {
                    tsvWriter.append(tsvFeatures);
                    // Flush every time in case we crash or get interrupted.  The features must flow!
                    tsvWriter.flush();
                }
            }
        } else {
            throw new RuntimeException("Must specify inchi or input file");
        }
    } finally {
        if (tsvWriter != null) {
            tsvWriter.close();
        }
    }
}

From source file:edu.harvard.med.screensaver.io.Spammer.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {

    CommandLineApplication app = new CommandLineApplication(args);
    String[] option = MAIL_RECIPIENT_LIST_OPTION;
    app.addCommandLineOption(OptionBuilder.withType(Integer.class).hasArg().isRequired()
            .withArgName(option[SHORT_OPTION_INDEX]).withDescription(option[DESCRIPTION_INDEX])
            .withLongOpt(option[LONG_OPTION_INDEX]).create(option[SHORT_OPTION_INDEX]));

    option = MAIL_CC_LIST_OPTION;//from  ww  w.  ja  v  a2 s  . c o m
    app.addCommandLineOption(OptionBuilder.hasArg().withArgName(option[SHORT_OPTION_INDEX])
            .withDescription(option[DESCRIPTION_INDEX]).withLongOpt(option[LONG_OPTION_INDEX])
            .create(option[SHORT_OPTION_INDEX]));

    option = MAIL_REPLYTO_LIST_OPTION;
    app.addCommandLineOption(OptionBuilder.hasArg().withArgName(option[SHORT_OPTION_INDEX])
            .withDescription(option[DESCRIPTION_INDEX]).withLongOpt(option[LONG_OPTION_INDEX])
            .create(option[SHORT_OPTION_INDEX]));

    option = MAIL_MESSAGE_OPTION;
    app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName(option[SHORT_OPTION_INDEX])
            .withDescription(option[DESCRIPTION_INDEX]).withLongOpt(option[LONG_OPTION_INDEX])
            .create(option[SHORT_OPTION_INDEX]));

    option = MAIL_FILE_ATTACHMENT;
    app.addCommandLineOption(OptionBuilder.hasArg().withArgName(option[SHORT_OPTION_INDEX])
            .withDescription(option[DESCRIPTION_INDEX]).withLongOpt(option[LONG_OPTION_INDEX])
            .create(option[SHORT_OPTION_INDEX]));

    option = MAIL_SUBJECT_OPTION;
    app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName(option[SHORT_OPTION_INDEX])
            .withDescription(option[DESCRIPTION_INDEX]).withLongOpt(option[LONG_OPTION_INDEX])
            .create(option[SHORT_OPTION_INDEX]));

    option = MAIL_SERVER_OPTION;
    app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName(option[SHORT_OPTION_INDEX])
            .withDescription(option[DESCRIPTION_INDEX]).withLongOpt(option[LONG_OPTION_INDEX])
            .create(option[SHORT_OPTION_INDEX]));

    option = MAIL_USERNAME_OPTION;
    app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName(option[SHORT_OPTION_INDEX])
            .withDescription(option[DESCRIPTION_INDEX]).withLongOpt(option[LONG_OPTION_INDEX])
            .create(option[SHORT_OPTION_INDEX]));

    option = MAIL_USER_PASSWORD_OPTION;
    app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName(option[SHORT_OPTION_INDEX])
            .withDescription(option[DESCRIPTION_INDEX]).withLongOpt(option[LONG_OPTION_INDEX])
            .create(option[SHORT_OPTION_INDEX]));

    option = MAIL_FROM_OPTION;
    app.addCommandLineOption(OptionBuilder.hasArg().withArgName(option[SHORT_OPTION_INDEX])
            .withDescription(option[DESCRIPTION_INDEX]).withLongOpt(option[LONG_OPTION_INDEX])
            .create(option[SHORT_OPTION_INDEX]));

    option = MAIL_USE_SMTPS;
    app.addCommandLineOption(
            OptionBuilder.withArgName(option[SHORT_OPTION_INDEX]).withDescription(option[DESCRIPTION_INDEX])
                    .withLongOpt(option[LONG_OPTION_INDEX]).create(option[SHORT_OPTION_INDEX]));

    app.processOptions(true, true);

    String message = app.getCommandLineOptionValue(MAIL_MESSAGE_OPTION[SHORT_OPTION_INDEX]);

    File attachedFile = null;
    if (app.isCommandLineFlagSet(MAIL_FILE_ATTACHMENT[SHORT_OPTION_INDEX])) {
        attachedFile = new File(app.getCommandLineOptionValue(MAIL_FILE_ATTACHMENT[SHORT_OPTION_INDEX]));
        if (!attachedFile.exists()) {
            log.error("Specified file does not exist: " + attachedFile.getCanonicalPath());
            System.exit(1);
        }
    }

    String subject = app.getCommandLineOptionValue(MAIL_SUBJECT_OPTION[SHORT_OPTION_INDEX]);
    String recipientlist = app.getCommandLineOptionValue(MAIL_RECIPIENT_LIST_OPTION[SHORT_OPTION_INDEX]);
    String[] recipients = recipientlist.split(DELIMITER);

    String[] ccrecipients = null;
    if (app.isCommandLineFlagSet(MAIL_CC_LIST_OPTION[SHORT_OPTION_INDEX])) {
        String cclist = app.getCommandLineOptionValue(MAIL_CC_LIST_OPTION[SHORT_OPTION_INDEX]);
        ccrecipients = cclist.split(DELIMITER);
    }

    String replytos = null;
    if (app.isCommandLineFlagSet(MAIL_REPLYTO_LIST_OPTION[SHORT_OPTION_INDEX])) {
        replytos = app.getCommandLineOptionValue(MAIL_CC_LIST_OPTION[SHORT_OPTION_INDEX]);
    }

    String mailHost = app.getCommandLineOptionValue(MAIL_SERVER_OPTION[SHORT_OPTION_INDEX]);
    String username = app.getCommandLineOptionValue(MAIL_USERNAME_OPTION[SHORT_OPTION_INDEX]);
    String password = app.getCommandLineOptionValue(MAIL_USER_PASSWORD_OPTION[SHORT_OPTION_INDEX]);
    boolean useSmtps = app.isCommandLineFlagSet(MAIL_USE_SMTPS[SHORT_OPTION_INDEX]);

    String mailFrom = username;
    if (app.isCommandLineFlagSet(MAIL_FROM_OPTION[SHORT_OPTION_INDEX])) {
        mailFrom = app.getCommandLineOptionValue(MAIL_FROM_OPTION[SHORT_OPTION_INDEX]);
    }

    SmtpEmailService service = new SmtpEmailService(mailHost, username, replytos, password, useSmtps);
    service.send(subject, message, mailFrom, recipients, ccrecipients, attachedFile);
}

From source file:examples.tftp.java

public final static void main(String[] args) {
    boolean receiveFile = true, closed;
    int transferMode = TFTP.BINARY_MODE, argc;
    String arg, hostname, localFilename, remoteFilename;
    TFTPClient tftp;//from   www .  j  a  va2s. c  o  m

    // Parse options
    for (argc = 0; argc < args.length; argc++) {
        arg = args[argc];
        if (arg.startsWith("-")) {
            if (arg.equals("-r"))
                receiveFile = true;
            else if (arg.equals("-s"))
                receiveFile = false;
            else if (arg.equals("-a"))
                transferMode = TFTP.ASCII_MODE;
            else if (arg.equals("-b"))
                transferMode = TFTP.BINARY_MODE;
            else {
                System.err.println("Error: unrecognized option.");
                System.err.print(USAGE);
                System.exit(1);
            }
        } else
            break;
    }

    // Make sure there are enough arguments
    if (args.length - argc != 3) {
        System.err.println("Error: invalid number of arguments.");
        System.err.print(USAGE);
        System.exit(1);
    }

    // Get host and file arguments
    hostname = args[argc];
    localFilename = args[argc + 1];
    remoteFilename = args[argc + 2];

    // Create our TFTP instance to handle the file transfer.
    tftp = new TFTPClient();

    // We want to timeout if a response takes longer than 60 seconds
    tftp.setDefaultTimeout(60000);

    // Open local socket
    try {
        tftp.open();
    } catch (SocketException e) {
        System.err.println("Error: could not open local UDP socket.");
        System.err.println(e.getMessage());
        System.exit(1);
    }

    // We haven't closed the local file yet.
    closed = false;

    // If we're receiving a file, receive, otherwise send.
    if (receiveFile) {
        FileOutputStream output = null;
        File file;

        file = new File(localFilename);

        // If file exists, don't overwrite it.
        if (file.exists()) {
            System.err.println("Error: " + localFilename + " already exists.");
            System.exit(1);
        }

        // Try to open local file for writing
        try {
            output = new FileOutputStream(file);
        } catch (IOException e) {
            tftp.close();
            System.err.println("Error: could not open local file for writing.");
            System.err.println(e.getMessage());
            System.exit(1);
        }

        // Try to receive remote file via TFTP
        try {
            tftp.receiveFile(remoteFilename, transferMode, output, hostname);
        } catch (UnknownHostException e) {
            System.err.println("Error: could not resolve hostname.");
            System.err.println(e.getMessage());
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Error: I/O exception occurred while receiving file.");
            System.err.println(e.getMessage());
            System.exit(1);
        } finally {
            // Close local socket and output file
            tftp.close();
            try {
                output.close();
                closed = true;
            } catch (IOException e) {
                closed = false;
                System.err.println("Error: error closing file.");
                System.err.println(e.getMessage());
            }
        }

        if (!closed)
            System.exit(1);

    } else {
        // We're sending a file
        FileInputStream input = null;

        // Try to open local file for reading
        try {
            input = new FileInputStream(localFilename);
        } catch (IOException e) {
            tftp.close();
            System.err.println("Error: could not open local file for reading.");
            System.err.println(e.getMessage());
            System.exit(1);
        }

        // Try to send local file via TFTP
        try {
            tftp.sendFile(remoteFilename, transferMode, input, hostname);
        } catch (UnknownHostException e) {
            System.err.println("Error: could not resolve hostname.");
            System.err.println(e.getMessage());
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Error: I/O exception occurred while sending file.");
            System.err.println(e.getMessage());
            System.exit(1);
        } finally {
            // Close local socket and input file
            tftp.close();
            try {
                input.close();
                closed = true;
            } catch (IOException e) {
                closed = false;
                System.err.println("Error: error closing file.");
                System.err.println(e.getMessage());
            }
        }

        if (!closed)
            System.exit(1);

    }

}

From source file:examples.tftp.java

public final static void main(String[] args) {
    boolean receiveFile = true, closed;
    int transferMode = TFTP.BINARY_MODE, argc;
    String arg, hostname, localFilename, remoteFilename;
    TFTPClient tftp;/*from   ww  w . j a va 2s.co m*/

    // Parse options
    for (argc = 0; argc < args.length; argc++) {
        arg = args[argc];
        if (arg.startsWith("-")) {
            if (arg.equals("-r"))
                receiveFile = true;
            else if (arg.equals("-s"))
                receiveFile = false;
            else if (arg.equals("-a"))
                transferMode = TFTP.ASCII_MODE;
            else if (arg.equals("-b"))
                transferMode = TFTP.BINARY_MODE;
            else {
                System.err.println("Error: unrecognized option.");
                System.err.print(USAGE);
                System.exit(1);
            }
        } else
            break;
    }

    // Make sure there are enough arguments
    if (args.length - argc != 3) {
        System.err.println("Error: invalid number of arguments.");
        System.err.print(USAGE);
        System.exit(1);
    }

    // Get host and file arguments
    hostname = args[argc];
    localFilename = args[argc + 1];
    remoteFilename = args[argc + 2];

    // Create our TFTP instance to handle the file transfer.
    tftp = new TFTPClient();

    // We want to timeout if a response takes longer than 60 seconds
    tftp.setDefaultTimeout(60000);

    // Open local socket
    try {
        tftp.open();
    } catch (SocketException e) {
        System.err.println("Error: could not open local UDP socket.");
        System.err.println(e.getMessage());
        System.exit(1);
    }

    // We haven't closed the local file yet.
    closed = false;

    // If we're receiving a file, receive, otherwise send.
    if (receiveFile) {
        FileOutputStream output = null;
        File file;

        file = new File(localFilename);

        // If file exists, don't overwrite it.
        if (file.exists()) {
            System.err.println("Error: " + localFilename + " already exists.");
            System.exit(1);
        }

        // Try to open local file for writing
        try {
            output = new FileOutputStream(file);
        } catch (IOException e) {
            tftp.close();
            System.err.println("Error: could not open local file for writing.");
            System.err.println(e.getMessage());
            System.exit(1);
        }

        // Try to receive remote file via TFTP
        try {
            tftp.receiveFile(remoteFilename, transferMode, output, hostname);
        } catch (UnknownHostException e) {
            System.err.println("Error: could not resolve hostname.");
            System.err.println(e.getMessage());
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Error: I/O exception occurred while receiving file.");
            System.err.println(e.getMessage());
            System.exit(1);
        } finally {
            // Close local socket and output file
            tftp.close();
            try {
                output.close();
                closed = true;
            } catch (IOException e) {
                closed = false;
                System.err.println("Error: error closing file.");
                System.err.println(e.getMessage());
            }
        }

        if (!closed)
            System.exit(1);

    } else {
        // We're sending a file
        FileInputStream input = null;

        // Try to open local file for reading
        try {
            input = new FileInputStream(localFilename);
        } catch (IOException e) {
            tftp.close();
            System.err.println("Error: could not open local file for reading.");
            System.err.println(e.getMessage());
            System.exit(1);
        }

        // Try to send local file via TFTP
        try {
            tftp.sendFile(remoteFilename, transferMode, input, hostname);
        } catch (UnknownHostException e) {
            System.err.println("Error: could not resolve hostname.");
            System.err.println(e.getMessage());
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Error: I/O exception occurred while sending file.");
            System.err.println(e.getMessage());
            System.exit(1);
        } finally {
            // Close local socket and input file
            tftp.close();
            try {
                input.close();
                closed = true;
            } catch (IOException e) {
                closed = false;
                System.err.println("Error: error closing file.");
                System.err.println(e.getMessage());
            }
        }

        if (!closed)
            System.exit(1);

    }

}

From source file:appmain.AppMain.java

public static void main(String[] args) {

    try {/*from   w  w w  .  jav a2s .  c  o  m*/
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        UIManager.put("OptionPane.yesButtonText", "Igen");
        UIManager.put("OptionPane.noButtonText", "Nem");
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    try {

        AppMain app = new AppMain();
        app.init();

        File importFolder = new File(DEFAULT_IMPORT_FOLDER);
        if (!importFolder.isDirectory() || !importFolder.exists()) {
            JOptionPane.showMessageDialog(null,
                    "Az IMPORT mappa nem elrhet!\n"
                            + "Ellenrizze az elrsi utat s a jogosultsgokat!\n" + "Mappa: "
                            + importFolder.getAbsolutePath(),
                    "Informci", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        File exportFolder = new File(DEFAULT_EXPORT_FOLDER);
        if (!exportFolder.isDirectory() || !exportFolder.exists()) {
            JOptionPane.showMessageDialog(null,
                    "Az EXPORT mappa nem elrhet!\n"
                            + "Ellenrizze az elrsi utat s a jogosultsgokat!\n" + "Mappa: "
                            + exportFolder.getAbsolutePath(),
                    "Informci", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        List<File> xmlFiles = app.getXMLFiles(importFolder);
        if (xmlFiles == null || xmlFiles.isEmpty()) {
            JOptionPane.showMessageDialog(null,
                    "Nincs beolvasand XML fjl!\n" + "Mappa: " + importFolder.getAbsolutePath(),
                    "Informci", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        StringBuilder fileList = new StringBuilder();
        xmlFiles.stream().forEach(xml -> fileList.append("\n").append(xml.getName()));
        int ret = JOptionPane.showConfirmDialog(null,
                "Beolvassra elksztett fjlok:\n" + fileList + "\n\nIndulhat a feldolgozs?",
                "Megtallt XML fjlok", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);

        if (ret == JOptionPane.OK_OPTION) {
            String csvName = "tranzakcio_lista_" + df.format(new Date()) + "_" + System.currentTimeMillis()
                    + ".csv";
            File csv = new File(DEFAULT_EXPORT_FOLDER + "/" + csvName);
            app.writeCSV(csv, Arrays.asList(app.getHeaderLine()));
            xmlFiles.stream().forEach(xml -> {
                List<String> lines = app.readXMLData(xml);
                if (lines != null)
                    app.writeCSV(csv, lines);
            });
            if (csv.isFile() && csv.exists()) {
                JOptionPane.showMessageDialog(null,
                        "A CSV fjl sikeresen elllt!\n" + "Fjl: " + csv.getAbsolutePath(),
                        "Informci", JOptionPane.INFORMATION_MESSAGE);
                app.openFile(csv);
            }
        } else {
            JOptionPane.showMessageDialog(null, "Feldolgozs megszaktva!", "Informci",
                    JOptionPane.INFORMATION_MESSAGE);
        }

    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, "Nem kezelt kivtel!\n" + ExceptionUtils.getStackTrace(ex), "Hiba",
                JOptionPane.ERROR_MESSAGE);
    }

}