Example usage for java.io File getAbsolutePath

List of usage examples for java.io File getAbsolutePath

Introduction

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

Prototype

public String getAbsolutePath() 

Source Link

Document

Returns the absolute pathname string of this abstract pathname.

Usage

From source file:fr.inria.edelweiss.kgdqp.core.FedInferrencingCLI.java

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

    List<String> endpoints = new ArrayList<String>();
    String queryPath = null;// w w  w . j av a  2  s .  c  o  m
    boolean rulesSelection = false;
    File rulesDir = null;
    File ontDir = null;

    Options options = new Options();
    Option helpOpt = new Option("h", "help", false, "print this message");
    Option queryOpt = new Option("q", "query", true, "specify the sparql query file");
    Option endpointOpt = new Option("e", "endpoint", true, "a federated sparql endpoint URL");
    Option versionOpt = new Option("v", "version", false, "print the version information and exit");
    Option rulesOpt = new Option("r", "rulesDir", true, "directory containing the inference rules");
    Option ontOpt = new Option("o", "ontologiesDir", true,
            "directory containing the ontologies for rules selection");
    //        Option selOpt = new Option("s", "rulesSelection", false, "if set to true, only the applicable rules are run");
    options.addOption(queryOpt);
    options.addOption(endpointOpt);
    options.addOption(helpOpt);
    options.addOption(versionOpt);
    options.addOption(rulesOpt);
    options.addOption(ontOpt);
    //        options.addOption(selOpt);

    String header = "Corese/KGRAM distributed rule engine command line interface";
    String footer = "\nPlease report any issue to alban.gaignard@cnrs.fr, olivier.corby@inria.fr";

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("kgdqp", header, options, footer, true);
        System.exit(0);
    }
    if (!cmd.hasOption("e")) {
        logger.info("You must specify at least the URL of one sparql endpoint !");
        System.exit(0);
    } else {
        endpoints = new ArrayList<String>(Arrays.asList(cmd.getOptionValues("e")));
    }
    if (cmd.hasOption("o")) {
        rulesSelection = true;
        String ontDirPath = cmd.getOptionValue("o");
        ontDir = new File(ontDirPath);
        if (!ontDir.isDirectory()) {
            logger.warn(ontDirPath + " is not a valid directory path.");
            System.exit(0);
        }
    }
    if (!cmd.hasOption("r")) {
        logger.info("You must specify a path for inference rules directory !");
        System.exit(0);
    } else if (rulesSelection) {

    }

    if (cmd.hasOption("v")) {
        logger.info("version 3.0.4-SNAPSHOT");
        System.exit(0);
    }

    String rulesDirPath = cmd.getOptionValue("r");
    rulesDir = new File(rulesDirPath);
    if (!rulesDir.isDirectory()) {
        logger.warn(rulesDirPath + " is not a valid directory path.");
        System.exit(0);
    }

    /////////////////
    Graph graph = Graph.create();
    QueryProcessDQP execDQP = QueryProcessDQP.create(graph);
    for (String url : endpoints) {
        try {
            execDQP.addRemote(new URL(url), WSImplem.REST);
        } catch (MalformedURLException ex) {
            logger.error(url + " is not a well-formed URL");
            System.exit(1);
        }
    }

    // Local rules graph initialization
    Graph rulesG = Graph.create();
    Load ld = Load.create(rulesG);

    if (rulesSelection) {
        // Ontology loading
        if (ontDir.isDirectory()) {
            for (File o : ontDir.listFiles()) {
                logger.info("Loading " + o.getAbsolutePath());
                ld.load(o.getAbsolutePath());
            }
        }
    }

    // Rules loading
    if (rulesDir.isDirectory()) {
        for (File r : rulesDir.listFiles()) {
            logger.info("Loading " + r.getAbsolutePath());
            ld.load(r.getAbsolutePath());
        }
    }

    // Rule engine initialization
    RuleEngine ruleEngine = RuleEngine.create(graph);
    ruleEngine.set(execDQP);

    StopWatch sw = new StopWatch();
    logger.info("Federated graph size : " + graph.size());
    logger.info("Rules graph size : " + rulesG.size());

    // Rule selection
    logger.info("Rules selection");
    QueryProcess localKgram = QueryProcess.create(rulesG);
    ArrayList<String> applicableRules = new ArrayList<String>();
    sw.start();
    String rulesSelQuery = "";
    if (rulesSelection) {
        rulesSelQuery = pertinentRulesQuery;
    } else {
        rulesSelQuery = allRulesQuery;
    }
    Mappings maps = localKgram.query(rulesSelQuery);
    logger.info("Rules selected in " + sw.getTime() + " ms");
    logger.info("Applicable rules : " + maps.size());

    // Selected rule loading
    for (Mapping map : maps) {
        IDatatype dt = (IDatatype) map.getValue("?res");
        String rule = dt.getLabel();
        //loading rule in the rule engine
        //            logger.info("Adding rule : " + rule);
        applicableRules.add(rule);
        ruleEngine.addRule(rule);
    }

    // Rules application on distributed sparql endpoints
    logger.info("Rules application (" + applicableRules.size() + " rules)");
    ExecutorService threadPool = Executors.newCachedThreadPool();
    RuleEngineThread ruleThread = new RuleEngineThread(ruleEngine);
    sw.reset();
    sw.start();

    //        ruleEngine.process();
    threadPool.execute(ruleThread);
    threadPool.shutdown();

    //monitoring loop
    while (!threadPool.isTerminated()) {
        System.out.println("******************************");
        System.out.println(Util.jsonDqpCost(QueryProcessDQP.queryCounter, QueryProcessDQP.queryVolumeCounter,
                QueryProcessDQP.sourceCounter, QueryProcessDQP.sourceVolumeCounter));
        System.out.println("Rule engine running for " + sw.getTime() + " ms");
        System.out.println("Federated graph size : " + graph.size());
        Thread.sleep(10000);
    }

    logger.info("Federated graph size : " + graph.size());
    logger.info(Util.jsonDqpCost(QueryProcessDQP.queryCounter, QueryProcessDQP.queryVolumeCounter,
            QueryProcessDQP.sourceCounter, QueryProcessDQP.sourceVolumeCounter));

    ///////////// Query file processing
    //        StringBuffer fileData = new StringBuffer(1000);
    //        BufferedReader reader = null;
    //        try {
    //            reader = new BufferedReader(new FileReader(queryPath));
    //        } catch (FileNotFoundException ex) {
    //             logger.error("Query file "+queryPath+" not found !");
    //             System.exit(1);
    //        }
    //        char[] buf = new char[1024];
    //        int numRead = 0;
    //        try {
    //            while ((numRead = reader.read(buf)) != -1) {
    //                String readData = String.valueOf(buf, 0, numRead);
    //                fileData.append(readData);
    //                buf = new char[1024];
    //            }
    //            reader.close();
    //        } catch (IOException ex) {
    //           logger.error("Error while reading query file "+queryPath);
    //           System.exit(1);
    //        }
    //
    //        String sparqlQuery = fileData.toString();
    //
    //        Query q = exec.compile(sparqlQuery,null);
    //        System.out.println(q);
    //        
    //        StopWatch sw = new StopWatch();
    //        sw.start();
    //        Mappings map = exec.query(sparqlQuery);
    //        int dqpSize = map.size();
    //        System.out.println("--------");
    //        long time = sw.getTime();
    //        System.out.println(time + " " + dqpSize);
}

From source file:de.tu.darmstadt.lt.ner.preprocessing.GermaNERMain.java

public static void main(String[] arg) throws Exception {
    long startTime = System.currentTimeMillis();
    String usage = "USAGE: java -jar germanner.jar [-c config.properties] \n"
            + " [-f trainingFileName] -t testFileName -d ModelOutputDirectory-o outputFile";
    long start = System.currentTimeMillis();

    ChangeColon c = new ChangeColon();

    List<String> argList = Arrays.asList(arg);
    try {//w w  w.  j a  va  2s.co m

        if (argList.contains("-c") && argList.get(argList.indexOf("-c") + 1) != null) {
            if (!new File(argList.get(argList.indexOf("-c") + 1)).exists()) {
                LOG.error("Default configuration is read from the system\n");
            } else {
                configFile = new FileInputStream(argList.get(argList.indexOf("-c") + 1));
            }

        }

        if (argList.contains("-t") && argList.get(argList.indexOf("-t") + 1) != null) {
            if (!new File(argList.get(argList.indexOf("-t") + 1)).exists()) {
                LOG.error("There is no test file to tag");
                System.exit(1);
            }
            Configuration.testFileName = argList.get(argList.indexOf("-t") + 1);
        }

        if (argList.contains("-f") && argList.get(argList.indexOf("-f") + 1) != null) {
            if (!new File(argList.get(argList.indexOf("-f") + 1)).exists()) {
                LOG.error("The system is running in tagging mode. No training data provided");
            } else {
                Configuration.trainFileName = argList.get(argList.indexOf("-f") + 1);
            }
        }

        if (argList.contains("-d") && argList.get(argList.indexOf("-d") + 1) != null) {
            if (new File(argList.get(argList.indexOf("-d") + 1)).exists()) {
                Configuration.modelDir = argList.get(argList.indexOf("-d") + 1);
            } else {
                File dir = new File(argList.get(argList.indexOf("-d") + 1));
                dir.mkdirs();
                Configuration.modelDir = dir.getAbsolutePath();
            }
        }
        // load a properties file
        initNERModel();
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    try {
        setModelDir();

        File outputtmpFile = new File(modelDirectory, "result.tmp");
        File outputFile = null;
        if (argList.contains("-o") && argList.get(argList.indexOf("-o") + 1) != null) {
            outputFile = new File(argList.get(argList.indexOf("-o") + 1));
        } else {
            LOG.error("The directory for this output file does not exist. Output file "
                    + "will be found in the current directury under folder \"output\"");
            outputFile = new File(modelDirectory, "result.tsv");
        }

        if (Configuration.mode.equals("ft")
                && (Configuration.trainFileName == null || Configuration.testFileName == null)) {
            LOG.error(usage);
            System.exit(1);
        }
        if (Configuration.mode.equals("f") && Configuration.trainFileName == null) {
            LOG.error(usage);
            System.exit(1);
        }
        if (Configuration.mode.equals("t") && Configuration.testFileName == null) {
            LOG.error(usage);
            System.exit(1);
        }

        if (Configuration.mode.equals("f") && Configuration.trainFileName != null) {
            c.normalize(Configuration.trainFileName, Configuration.trainFileName + ".normalized");
            System.out.println("Start model generation");
            writeModel(new File(Configuration.trainFileName + ".normalized"), modelDirectory);
            System.out.println("Start model generation -- done");
            System.out.println("Start training");
            trainModel(modelDirectory);
            System.out.println("Start training ---done");
        } else if (Configuration.mode.equals("ft") && Configuration.trainFileName != null
                && Configuration.testFileName != null) {
            c.normalize(Configuration.trainFileName, Configuration.trainFileName + ".normalized");
            c.normalize(Configuration.testFileName, Configuration.testFileName + ".normalized");
            System.out.println("Start model generation");
            writeModel(new File(Configuration.trainFileName + ".normalized"), modelDirectory);
            System.out.println("Start model generation -- done");
            System.out.println("Start training");
            trainModel(modelDirectory);
            System.out.println("Start training ---done");
            System.out.println("Start tagging");
            classifyTestFile(modelDirectory, new File(Configuration.testFileName + ".normalized"),
                    outputtmpFile, null, null);
            System.out.println("Start tagging ---done");

            // re-normalized the colon changed text
            c.deNormalize(outputtmpFile.getAbsolutePath(), outputFile.getAbsolutePath());
        } else {
            c.normalize(Configuration.testFileName, Configuration.testFileName + ".normalized");
            System.out.println("Start tagging");
            classifyTestFile(modelDirectory, new File(Configuration.testFileName + ".normalized"),
                    outputtmpFile, null, null);
            // re-normalized the colon changed text
            c.deNormalize(outputtmpFile.getAbsolutePath(), outputFile.getAbsolutePath());

            System.out.println("Start tagging ---done");
        }
        long now = System.currentTimeMillis();
        UIMAFramework.getLogger().log(Level.INFO, "Time: " + (now - start) + "ms");
    } catch (Exception e) {
        LOG.error(usage);
        e.printStackTrace();
    }
    long endTime = System.currentTimeMillis();
    long totalTime = endTime - startTime;
    System.out.println("NER tarin/test done in " + totalTime / 1000 + " seconds");

}

From source file:org.objectrepository.MessageConsumerDaemon.java

/**
 * main//  w ww  . jav a  2  s.c  om
 * <p/>
 * Accepts one folder as argument:  -messageQueues
 * That folder ought to contain one or more folders ( or symbolic links ) to the files
 * The folder has the format: [foldername] or [foldername].[maxTasks]
 * MaxTasks is to indicate the total number of jobs being able to run.
 *
 * long
 *
 * @param argv
 */
public static void main(String[] argv) {

    if (instance == null) {
        final Properties properties = new Properties();

        if (argv.length > 0) {
            for (int i = 0; i < argv.length; i += 2) {
                try {
                    properties.put(argv[i], argv[i + 1]);
                } catch (ArrayIndexOutOfBoundsException arr) {
                    System.out.println("Missing value after parameter " + argv[i]);
                    System.exit(-1);
                }
            }
        } else {
            log.fatal("Usage: pmq-agent.jar -messageQueues [queues] -heartbeatInterval [interval in ms]\n"
                    + "The queues is a folder that contains symbolic links to the startup scripts.");
            System.exit(-1);
        }

        if (log.isInfoEnabled()) {
            log.info("Arguments set: ");
            for (String key : properties.stringPropertyNames()) {
                log.info("'" + key + "'='" + properties.getProperty(key) + "'");
            }
        }

        if (!properties.containsKey("-messageQueues")) {
            log.fatal("Expected case sensitive parameter: -messageQueues");
            System.exit(-1);
        }

        final File messageQueues = new File((String) properties.get("-messageQueues"));
        if (!messageQueues.exists()) {
            log.fatal("Cannot find folder for messageQueues: " + messageQueues.getAbsolutePath());
            System.exit(-1);
        }

        if (messageQueues.isFile()) {
            log.fatal(
                    "-messageQueues should point to a folder, not a file: " + messageQueues.getAbsolutePath());
            System.exit(-1);
        }

        long heartbeatInterval = 600000;
        if (properties.containsKey("-heartbeatInterval")) {
            heartbeatInterval = Long.parseLong((String) properties.get("heartbeatInterval"));
        }

        String identifier = null;
        if (properties.containsKey("-id")) {
            identifier = (String) properties.get("-id");
        } else if (properties.containsKey("-identifier")) {
            identifier = (String) properties.get("-identifier");
        }

        final File[] files = messageQueues.listFiles();
        final String[] scriptNames = (properties.containsKey("-startup"))
                ? new String[] { properties.getProperty("-startup") }
                : new String[] { "/startup.sh", "\\startup.bat" };
        final List<Queue> queues = new ArrayList<Queue>();
        for (File file : files) {
            final String name = file.getName();
            final String[] split = name.split("\\.", 2);
            final String queueName = split[0];
            for (String scriptName : scriptNames) {
                final String shellScript = file.getAbsolutePath() + scriptName;
                final int maxTask = (split.length == 1) ? 1 : Integer.parseInt(split[1]);
                log.info("Candidate mq client for " + queueName + " maxTasks " + maxTask);
                if (new File(shellScript).exists()) {
                    final Queue queue = new Queue(queueName, shellScript, false);
                    queue.setCorePoolSize(1);
                    queue.setMaxPoolSize(maxTask);
                    queue.setQueueCapacity(1);
                    queues.add(queue);
                    break;
                } else {
                    log.warn("... skipping, because no startup script found at " + shellScript);
                }
            }
        }

        if (queues.size() == 0) {
            log.fatal("No queue folders seen in " + messageQueues.getAbsolutePath());
            System.exit(-1);
        }

        // Add the system queue
        queues.add(new Queue("Connection", null, true));

        getInstance(queues, identifier, heartbeatInterval).run();
    }
    System.exit(0);
}

From source file:com.act.analysis.similarity.SubstructureSearch.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 v a 2s.  com
    }

    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(SubstructureSearch.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

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

    if (cl.hasOption(OPTION_LICENSE_FILE)) {
        LicenseManager.setLicenseFile(cl.getOptionValue(OPTION_LICENSE_FILE));
    }

    List<String> searchOpts = Collections.emptyList();
    if (cl.hasOption(OPTION_SEARCH_OPTIONS)) {
        searchOpts = Arrays.asList(cl.getOptionValues(OPTION_SEARCH_OPTIONS));
    }

    // Make sure we can initialize correctly before opening any file handles for writing.
    SubstructureSearch matcher = new SubstructureSearch();
    try {
        matcher.init(cl.getOptionValue(OPTION_QUERY), searchOpts);
    } catch (IllegalArgumentException e) {
        System.err.format("Unable to initialize substructure search.  %s\n", e.getMessage());
        HELP_FORMATTER.printHelp(SubstructureSearch.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    } catch (MolFormatException e) {
        System.err.format("Invalid SMILES structure query.  %s\n", e.getMessage());
        HELP_FORMATTER.printHelp(SubstructureSearch.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    Pair<List<String>, Iterator<Map<String, String>>> iterPair = null;
    if (cl.hasOption(OPTION_INPUT_FILE)) {
        File inFile = new File(cl.getOptionValue(OPTION_INPUT_FILE));
        if (!inFile.exists()) {
            System.err.format("File at %s does not exist", inFile.getAbsolutePath());
            HELP_FORMATTER.printHelp(SubstructureSearch.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                    true);
            System.exit(1);
        }
        iterPair = iterateOverTSV(inFile);
    } else if (cl.hasOption(OPTION_INPUT_DB)) {
        iterPair = iterateOverDB(cl.getOptionValue(OPTION_INPUT_DB_HOST, DEFAULT_HOST),
                Integer.parseInt(cl.getOptionValue(OPTION_INPUT_DB_HOST, DEFAULT_PORT)),
                cl.getOptionValue(OPTION_INPUT_DB));
    } else {
        System.err.format("Must specify either input TSV file or input DB from which to read.\n");
        HELP_FORMATTER.printHelp(SubstructureSearch.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    TSVWriter<String, String> writer = new TSVWriter<>(iterPair.getLeft());
    writer.open(new File(cl.getOptionValue(OPTION_OUTPUT_FILE)));

    LOGGER.info("Seaching for substructure '%s'", cl.getOptionValue(OPTION_QUERY));

    try {
        int rowNum = 0;
        while (iterPair.getRight().hasNext()) {
            Map<String, String> row = iterPair.getRight().next();
            rowNum++;
            try {
                String inchi = row.get(FIELD_INCHI);
                Molecule target = null;
                try {
                    target = MolImporter.importMol(inchi);
                } catch (Exception e) {
                    LOGGER.warn("Skipping molecule %d due to exception: %s\n", rowNum, e.getMessage());
                    continue;
                }
                if (matcher.matchSubstructure(target)) {
                    writer.append(row);
                    writer.flush();
                } else {
                    // Don't output if not a match.
                    LOGGER.debug("Found non-matching molecule: %s", inchi);
                }
            } catch (SearchException e) {
                LOGGER.error("Exception on input line %d: %s\n", rowNum, e.getMessage());
                throw e;
            }
        }
    } finally {
        writer.close();
    }
    LOGGER.info("Done with substructure search");
}

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  w w .j  a v a2 s.com*/

    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:mase.stat.MasterTournament.java

public static void main(String[] args) throws Exception {
    List<File> sampleFolders = new ArrayList<>();
    List<File> testFolders = new ArrayList<>();
    int freq = 0;
    String name = "";
    boolean self = false;
    String individuals = null;/*from   w  ww .jav  a  2 s  .  c om*/
    int elite = 0;

    for (int x = 0; x < args.length; x++) {
        if (args[x].equalsIgnoreCase(TEST_FOLDER)) {
            File folder = new File(args[1 + x++]);
            if (!folder.exists()) {
                throw new Exception("Folder does not exist: " + folder.getAbsolutePath());
            }
            testFolders.add(folder);
        } else if (args[x].equalsIgnoreCase(SAMPLE_FOLDER)) {
            File folder = new File(args[1 + x++]);
            if (!folder.exists()) {
                throw new Exception("Folder does not exist: " + folder.getAbsolutePath());
            }
            sampleFolders.add(folder);
        } else if (args[x].equalsIgnoreCase(BOTH_FOLDER)) {
            File folder = new File(args[1 + x++]);
            if (!folder.exists()) {
                throw new Exception("Folder does not exist: " + folder.getAbsolutePath());
            }
            sampleFolders.add(folder);
            testFolders.add(folder);
        } else if (args[x].equalsIgnoreCase(FREQUENCY)) {
            freq = Integer.parseInt(args[1 + x++]);
        } else if (args[x].equalsIgnoreCase(ELITE)) {
            elite = Integer.parseInt(args[1 + x++]);
        } else if (args[x].equalsIgnoreCase(OUTNAME)) {
            name = args[1 + x++];
        } else if (args[x].equalsIgnoreCase(SELF)) {
            self = true;
        } else if (args[x].equalsIgnoreCase(INDIVIDUALS)) {
            individuals = args[1 + x++];
        }
    }

    if (testFolders.isEmpty() || sampleFolders.isEmpty()) {
        System.out.println("Nothing to evaluate!");
        return;
    }

    MaseProblem sim = Reevaluate.createSimulator(args);
    MasterTournament mt = new MasterTournament(sampleFolders, testFolders, sim, name);

    if (individuals != null) {
        mt.makeIndsTournaments(individuals);
    } else if (self) {
        mt.makeSelfTournaments(freq);
    } else {
        mt.makeSampleTournaments(freq, elite);
    }

    mt.executor.shutdown();
}

From source file:com.hs.mail.deliver.Deliver.java

public static void main(String[] args) {
    CommandLine cli = null;// w w  w.  ja  v  a2 s  . c om
    try {
        cli = new PosixParser().parse(OPTS, args);
    } catch (ParseException e) {
        usage();
        System.exit(EX_USAGE);
    }

    // Configuration file path
    String config = cli.getOptionValue("c", DEFAULT_CONFIG_LOCATION);
    // Message file path
    File file = new File(cli.getOptionValue("p"));
    // Envelope sender address
    String from = cli.getOptionValue("f");
    // Destination mailboxes
    String[] rcpts = cli.getOptionValues("r");

    if (!file.exists()) {
        // Message file must exist
        logger.error("File not exist: " + file.getAbsolutePath());
        System.exit(EX_TEMPFAIL);
    }

    if (from == null || rcpts == null) {
        // If sender or recipients address was not specified, get the
        // addresses from the message header.
        InputStream is = null;
        try {
            is = new FileInputStream(file);
            MessageHeader header = new MessageHeader(is);
            if (from == null && header.getFrom() != null) {
                from = header.getFrom().getAddress();
            }
            if (rcpts == null) {
                rcpts = getRecipients(header);
            }
        } catch (IOException ex) {
            logger.error(ex.getMessage(), ex);
            System.exit(EX_TEMPFAIL);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }

    if (from == null || ArrayUtils.isEmpty(rcpts)) {
        usage();
        System.exit(EX_USAGE);
    }

    Deliver deliver = new Deliver();

    deliver.init(config);
    // Spool the incoming message
    deliver.deliver(from, rcpts, file);

    System.exit(EX_OK);
}

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

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

    File inputFile = new File(cl.getOptionValue(OPTION_SCAN_FILE));
    if (!inputFile.exists()) {
        cliUtil.failWithMessage("Cannot find input scan file at %s", inputFile.getAbsolutePath());
    }//ww  w .  j  av a2s .co  m

    File indexDir = new File(cl.getOptionValue(OPTION_INDEX_PATH));
    if (indexDir.exists()) {
        cliUtil.failWithMessage("Index file at %s already exists--remove and retry",
                indexDir.getAbsolutePath());
    }

    Builder indexBuilder = Factory.makeBuilder(indexDir);
    try {
        indexBuilder.processScan(indexBuilder.makeTargetMasses(), inputFile);
    } finally {
        if (indexBuilder != null) {
            indexBuilder.close();
        }
    }

    LOGGER.info("Done");
}

From source file:de.micromata.tpsb.doc.StaticTestDocGenerator.java

public static void main(String[] args) {

    ParserConfig.Builder bCfg = new ParserConfig.Builder();
    ParserConfig.Builder tCfg = new ParserConfig.Builder();
    tCfg.generateIndividualFiles(true);/*w  w w. j  ava  2 s  .  c  o m*/
    bCfg.generateIndividualFiles(true);
    List<String> la = Arrays.asList(args);
    Iterator<String> it = la.iterator();
    boolean baseDirSet = false;
    boolean ignoreLocalSettings = false;
    List<String> addRepos = new ArrayList<String>();
    StringResourceLoader.setRepository(StringResourceLoader.REPOSITORY_NAME_DEFAULT,
            new StringResourceRepositoryImpl());
    try {
        while (it.hasNext()) {
            String arg = it.next();
            String value = null;

            if ((value = getArgumentOption(it, arg, "--project-root", "-pr")) != null) {
                File f = new File(value);
                if (f.exists() == false) {
                    System.err.print("project root doesn't exists: " + f.getAbsolutePath());
                    continue;
                }
                TpsbEnvironment.get().addProjectRoots(f);
                File ts = new File(f, "src/test");
                if (ts.exists() == true) {
                    tCfg.addSourceFileRespository(new FileSystemSourceFileRepository(ts.getAbsolutePath()));
                    bCfg.addSourceFileRespository(new FileSystemSourceFileRepository(ts.getAbsolutePath()));
                }
                continue;
            }
            if ((value = getArgumentOption(it, arg, "--test-input", "-ti")) != null) {
                File f = new File(value);
                if (f.exists() == false) {
                    System.err.print("test-input doesn't exists: " + f.getAbsolutePath());
                }
                tCfg.addSourceFileRespository(new FileSystemSourceFileRepository(value));
                bCfg.addSourceFileRespository(new FileSystemSourceFileRepository(value));
                continue;
            }
            if ((value = getArgumentOption(it, arg, "--output-path", "-op")) != null) {
                if (baseDirSet == false) {
                    tCfg.outputDir(value);
                    bCfg.outputDir(value);
                    TpsbEnvironment.setBaseDir(value);
                    baseDirSet = true;
                } else {
                    addRepos.add(value);
                }
                continue;
            }
            if ((value = getArgumentOption(it, arg, "--index-vmtemplate", "-ivt")) != null) {
                try {
                    String content = FileUtils.readFileToString(new File(value), CharEncoding.UTF_8);
                    StringResourceRepository repo = StringResourceLoader.getRepository();
                    repo.putStringResource("customIndexTemplate", content, CharEncoding.UTF_8);
                    tCfg.indexTemplate("customIndexTemplate");
                } catch (IOException ex) {
                    throw new RuntimeException(
                            "Cannot load file " + new File(value).getAbsolutePath() + ": " + ex.getMessage(),
                            ex);
                }
                continue;
            }
            if ((value = getArgumentOption(it, arg, "--test-vmtemplate", "-tvt")) != null) {
                try {
                    String content = FileUtils.readFileToString(new File(value), CharEncoding.UTF_8);
                    StringResourceRepository repo = StringResourceLoader.getRepository();
                    repo.putStringResource("customTestTemplate", content, CharEncoding.UTF_8);
                    tCfg.testTemplate("customTestTemplate");
                } catch (IOException ex) {
                    throw new RuntimeException(
                            "Cannot load file " + new File(value).getAbsolutePath() + ": " + ex.getMessage(),
                            ex);
                }
                continue;
            }
            if (arg.equals("--singlexml") == true) {
                tCfg.generateIndividualFiles(false);
                bCfg.generateIndividualFiles(false);
            } else if (arg.equals("--ignore-local-settings") == true) {
                ignoreLocalSettings = true;
                continue;
            }
        }
    } catch (RuntimeException ex) {
        System.err.print(ex.getMessage());
        return;
    }
    if (ignoreLocalSettings == false) {
        readLocalSettings(bCfg, tCfg);
    }
    bCfg// .addSourceFileFilter(new MatcherSourceFileFilter("*Builder,*App,*builder")) //
            .addSourceFileFilter(new AnnotationSourceFileFilter(TpsbBuilder.class)) //
            .addSourceFileFilter(new AnnotationSourceFileFilter(TpsbApplication.class)) //
    ;
    tCfg// .addSourceFileFilter(new MatcherSourceFileFilter("*Test,*TestCase")) //
            .addSourceFileFilter(new AnnotationSourceFileFilter(TpsbTestSuite.class)) //
    ;

    StaticTestDocGenerator docGenerator = new StaticTestDocGenerator(bCfg.build(), tCfg.build());
    TpsbEnvironment env = TpsbEnvironment.get();
    if (addRepos.isEmpty() == false) {
        env.setIncludeRepos(addRepos);
    }
    docGenerator.parseTestBuilders();
    docGenerator.parseTestCases();
}

From source file:org.eclipse.swt.snippets.Snippet135.java

public static void main(String[] args) {
    final Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setText("SWT and Swing/AWT Example");

    Listener exitListener = e -> {/*from   ww  w.  j  a v  a2s.c  o m*/
        MessageBox dialog = new MessageBox(shell, SWT.OK | SWT.CANCEL | SWT.ICON_QUESTION);
        dialog.setText("Question");
        dialog.setMessage("Exit?");
        if (e.type == SWT.Close)
            e.doit = false;
        if (dialog.open() != SWT.OK)
            return;
        shell.dispose();
    };
    Listener aboutListener = e -> {
        final Shell s = new Shell(shell, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
        s.setText("About");
        GridLayout layout = new GridLayout(1, false);
        layout.verticalSpacing = 20;
        layout.marginHeight = layout.marginWidth = 10;
        s.setLayout(layout);
        Label label = new Label(s, SWT.NONE);
        label.setText("SWT and AWT Example.");
        Button button = new Button(s, SWT.PUSH);
        button.setText("OK");
        GridData data = new GridData();
        data.horizontalAlignment = GridData.CENTER;
        button.setLayoutData(data);
        button.addListener(SWT.Selection, event -> s.dispose());
        s.pack();
        Rectangle parentBounds = shell.getBounds();
        Rectangle bounds = s.getBounds();
        int x = parentBounds.x + (parentBounds.width - bounds.width) / 2;
        int y = parentBounds.y + (parentBounds.height - bounds.height) / 2;
        s.setLocation(x, y);
        s.open();
        while (!s.isDisposed()) {
            if (!display.readAndDispatch())
                display.sleep();
        }
    };
    shell.addListener(SWT.Close, exitListener);
    Menu mb = new Menu(shell, SWT.BAR);
    MenuItem fileItem = new MenuItem(mb, SWT.CASCADE);
    fileItem.setText("&File");
    Menu fileMenu = new Menu(shell, SWT.DROP_DOWN);
    fileItem.setMenu(fileMenu);
    MenuItem exitItem = new MenuItem(fileMenu, SWT.PUSH);
    exitItem.setText("&Exit\tCtrl+X");
    exitItem.setAccelerator(SWT.CONTROL + 'X');
    exitItem.addListener(SWT.Selection, exitListener);
    MenuItem aboutItem = new MenuItem(fileMenu, SWT.PUSH);
    aboutItem.setText("&About\tCtrl+A");
    aboutItem.setAccelerator(SWT.CONTROL + 'A');
    aboutItem.addListener(SWT.Selection, aboutListener);
    shell.setMenuBar(mb);

    RGB color = shell.getBackground().getRGB();
    Label separator1 = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL);
    Label locationLb = new Label(shell, SWT.NONE);
    locationLb.setText("Location:");
    Composite locationComp = new Composite(shell, SWT.EMBEDDED);
    ToolBar toolBar = new ToolBar(shell, SWT.FLAT);
    ToolItem exitToolItem = new ToolItem(toolBar, SWT.PUSH);
    exitToolItem.setText("&Exit");
    exitToolItem.addListener(SWT.Selection, exitListener);
    ToolItem aboutToolItem = new ToolItem(toolBar, SWT.PUSH);
    aboutToolItem.setText("&About");
    aboutToolItem.addListener(SWT.Selection, aboutListener);
    Label separator2 = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL);
    final Composite comp = new Composite(shell, SWT.NONE);
    final Tree fileTree = new Tree(comp, SWT.SINGLE | SWT.BORDER);
    Sash sash = new Sash(comp, SWT.VERTICAL);
    Composite tableComp = new Composite(comp, SWT.EMBEDDED);
    Label separator3 = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL);
    Composite statusComp = new Composite(shell, SWT.EMBEDDED);

    java.awt.Frame locationFrame = SWT_AWT.new_Frame(locationComp);
    final java.awt.TextField locationText = new java.awt.TextField();
    locationFrame.add(locationText);

    java.awt.Frame fileTableFrame = SWT_AWT.new_Frame(tableComp);
    java.awt.Panel panel = new java.awt.Panel(new java.awt.BorderLayout());
    fileTableFrame.add(panel);
    final JTable fileTable = new JTable(new FileTableModel(null));
    fileTable.setDoubleBuffered(true);
    fileTable.setShowGrid(false);
    fileTable.createDefaultColumnsFromModel();
    JScrollPane scrollPane = new JScrollPane(fileTable);
    panel.add(scrollPane);

    java.awt.Frame statusFrame = SWT_AWT.new_Frame(statusComp);
    statusFrame.setBackground(new java.awt.Color(color.red, color.green, color.blue));
    final java.awt.Label statusLabel = new java.awt.Label();
    statusFrame.add(statusLabel);
    statusLabel.setText("Select a file");

    sash.addListener(SWT.Selection, e -> {
        if (e.detail == SWT.DRAG)
            return;
        GridData data = (GridData) fileTree.getLayoutData();
        Rectangle trim = fileTree.computeTrim(0, 0, 0, 0);
        data.widthHint = e.x - trim.width;
        comp.layout();
    });

    File[] roots = File.listRoots();
    for (int i = 0; i < roots.length; i++) {
        File file = roots[i];
        TreeItem treeItem = new TreeItem(fileTree, SWT.NONE);
        treeItem.setText(file.getAbsolutePath());
        treeItem.setData(file);
        new TreeItem(treeItem, SWT.NONE);
    }
    fileTree.addListener(SWT.Expand, e -> {
        TreeItem item = (TreeItem) e.item;
        if (item == null)
            return;
        if (item.getItemCount() == 1) {
            TreeItem firstItem = item.getItems()[0];
            if (firstItem.getData() != null)
                return;
            firstItem.dispose();
        } else {
            return;
        }
        File root = (File) item.getData();
        File[] files = root.listFiles();
        if (files == null)
            return;
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            if (file.isDirectory()) {
                TreeItem treeItem = new TreeItem(item, SWT.NONE);
                treeItem.setText(file.getName());
                treeItem.setData(file);
                new TreeItem(treeItem, SWT.NONE);
            }
        }
    });
    fileTree.addListener(SWT.Selection, e -> {
        TreeItem item = (TreeItem) e.item;
        if (item == null)
            return;
        final File root = (File) item.getData();
        EventQueue.invokeLater(() -> {
            statusLabel.setText(root.getAbsolutePath());
            locationText.setText(root.getAbsolutePath());
            fileTable.setModel(new FileTableModel(root.listFiles()));
        });
    });

    GridLayout layout = new GridLayout(4, false);
    layout.marginWidth = layout.marginHeight = 0;
    layout.horizontalSpacing = layout.verticalSpacing = 1;
    shell.setLayout(layout);
    GridData data;
    data = new GridData(GridData.FILL_HORIZONTAL);
    data.horizontalSpan = 4;
    separator1.setLayoutData(data);
    data = new GridData();
    data.horizontalSpan = 1;
    data.horizontalIndent = 10;
    locationLb.setLayoutData(data);
    data = new GridData(GridData.FILL_HORIZONTAL);
    data.horizontalSpan = 2;
    data.heightHint = locationText.getPreferredSize().height;
    locationComp.setLayoutData(data);
    data = new GridData(GridData.FILL_HORIZONTAL);
    data.horizontalSpan = 1;
    toolBar.setLayoutData(data);
    data = new GridData(GridData.FILL_HORIZONTAL);
    data.horizontalSpan = 4;
    separator2.setLayoutData(data);
    data = new GridData(GridData.FILL_BOTH);
    data.horizontalSpan = 4;
    comp.setLayoutData(data);
    data = new GridData(GridData.FILL_HORIZONTAL);
    data.horizontalSpan = 4;
    separator3.setLayoutData(data);
    data = new GridData(GridData.FILL_HORIZONTAL);
    data.horizontalSpan = 4;
    data.heightHint = statusLabel.getPreferredSize().height;
    statusComp.setLayoutData(data);

    layout = new GridLayout(3, false);
    layout.marginWidth = layout.marginHeight = 0;
    layout.horizontalSpacing = layout.verticalSpacing = 1;
    comp.setLayout(layout);
    data = new GridData(GridData.FILL_VERTICAL);
    data.widthHint = 200;
    fileTree.setLayoutData(data);
    data = new GridData(GridData.FILL_VERTICAL);
    sash.setLayoutData(data);
    data = new GridData(GridData.FILL_BOTH);
    tableComp.setLayoutData(data);

    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}