Example usage for org.apache.commons.cli Options addOption

List of usage examples for org.apache.commons.cli Options addOption

Introduction

In this page you can find the example usage for org.apache.commons.cli Options addOption.

Prototype

public Options addOption(Option opt) 

Source Link

Document

Adds an option instance

Usage

From source file:edu.umd.ujjwalgoel.AnalyzePMI.java

@SuppressWarnings({ "static-access" })
public static void main(String[] args) {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT));

    CommandLine cmdline = null;/* w  ww . j a  v  a 2 s .co  m*/
    CommandLineParser parser = new GnuParser();

    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(INPUT)) {
        System.out.println("args: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(120);
        formatter.printHelp(AnalyzePMI.class.getName(), options);
        ToolRunner.printGenericCommandUsage(System.out);
        System.exit(-1);
    }

    String inputPath = cmdline.getOptionValue(INPUT);
    System.out.println("input path: " + inputPath);

    BufferedReader br = null;
    int countPairs = 0;

    List<PairOfWritables<PairOfStrings, FloatWritable>> pmis = new ArrayList<PairOfWritables<PairOfStrings, FloatWritable>>();
    List<PairOfWritables<PairOfStrings, FloatWritable>> cloudPmis = new ArrayList<PairOfWritables<PairOfStrings, FloatWritable>>();
    List<PairOfWritables<PairOfStrings, FloatWritable>> lovePmis = new ArrayList<PairOfWritables<PairOfStrings, FloatWritable>>();

    PairOfWritables<PairOfStrings, FloatWritable> highestPMI = null;
    PairOfWritables<PairOfStrings, FloatWritable> highestCloudPMI = null;
    PairOfWritables<PairOfStrings, FloatWritable> highestCloudPMI2 = null;
    PairOfWritables<PairOfStrings, FloatWritable> highestCloudPMI3 = null;

    PairOfWritables<PairOfStrings, FloatWritable> highestLovePMI = null;
    PairOfWritables<PairOfStrings, FloatWritable> highestLovePMI2 = null;
    PairOfWritables<PairOfStrings, FloatWritable> highestLovePMI3 = null;

    try {
        FileSystem fs = FileSystem.get(new Configuration());
        FileStatus[] status = fs.listStatus(new Path(inputPath));
        //PairOfStrings pair = new PairOfStrings();
        for (int i = 0; i < status.length; i++) {
            br = new BufferedReader(new InputStreamReader(fs.open(status[i].getPath())));
            String line = br.readLine();
            while (line != null) {
                String[] words = line.split("\\t");
                float value = Float.parseFloat(words[1].trim());
                String[] wordPair = words[0].replaceAll("\\(", "").replaceAll("\\)", "").split(",");
                PairOfStrings pair = new PairOfStrings();
                pair.set(wordPair[0].trim(), wordPair[1].trim());
                if (wordPair[0].trim().equals("cloud")) {
                    PairOfWritables<PairOfStrings, FloatWritable> cloudPmi = new PairOfWritables<PairOfStrings, FloatWritable>();
                    cloudPmi.set(pair, new FloatWritable(value));
                    cloudPmis.add(cloudPmi);
                    if ((highestCloudPMI == null)
                            || (highestCloudPMI.getRightElement().compareTo(cloudPmi.getRightElement()) < 0)) {
                        highestCloudPMI = cloudPmi;
                    } else if ((highestCloudPMI2 == null)
                            || (highestCloudPMI2.getRightElement().compareTo(cloudPmi.getRightElement()) < 0)) {
                        highestCloudPMI2 = cloudPmi;
                    } else if ((highestCloudPMI3 == null)
                            || (highestCloudPMI3.getRightElement().compareTo(cloudPmi.getRightElement()) < 0)) {
                        highestCloudPMI3 = cloudPmi;
                    }
                }
                if (wordPair[0].trim().equals("love")) {
                    PairOfWritables<PairOfStrings, FloatWritable> lovePmi = new PairOfWritables<PairOfStrings, FloatWritable>();
                    lovePmi.set(pair, new FloatWritable(value));
                    lovePmis.add(lovePmi);
                    if ((highestLovePMI == null)
                            || (highestLovePMI.getRightElement().compareTo(lovePmi.getRightElement()) < 0)) {
                        highestLovePMI = lovePmi;
                    } else if ((highestLovePMI2 == null)
                            || (highestLovePMI2.getRightElement().compareTo(lovePmi.getRightElement()) < 0)) {
                        highestLovePMI2 = lovePmi;
                    } else if ((highestLovePMI3 == null)
                            || (highestLovePMI3.getRightElement().compareTo(lovePmi.getRightElement()) < 0)) {
                        highestLovePMI3 = lovePmi;
                    }
                }
                PairOfWritables<PairOfStrings, FloatWritable> pmi = new PairOfWritables<PairOfStrings, FloatWritable>();
                pmi.set(pair, new FloatWritable(value));
                pmis.add(pmi);
                if (highestPMI == null) {
                    highestPMI = pmi;
                } else if (highestPMI.getRightElement().compareTo(pmi.getRightElement()) < 0) {
                    highestPMI = pmi;
                }
                countPairs++;
                line = br.readLine();
            }
        }
    } catch (Exception ex) {
        System.out.println("ERROR" + ex.getMessage());
    }

    /*Collections.sort(pmis, new Comparator<PairOfWritables<PairOfStrings, FloatWritable>>() {
      public int compare(PairOfWritables<PairOfStrings, FloatWritable> e1,
          PairOfWritables<PairOfStrings, FloatWritable> e2) {
        /*if (e2.getRightElement().compareTo(e1.getRightElement()) == 0) {
          return e1.getLeftElement().getLeftElement().compareTo(e2.getLeftElement().getLeftElement());
        }
            
        return e2.getRightElement().compareTo(e1.getRightElement());
      }
    });
            
            
    Collections.sort(cloudPmis, new Comparator<PairOfWritables<PairOfStrings, FloatWritable>>() {
      public int compare(PairOfWritables<PairOfStrings, FloatWritable> e1,
          PairOfWritables<PairOfStrings, FloatWritable> e2) {
        if (e2.getRightElement().compareTo(e1.getRightElement()) == 0) {
    return e1.getLeftElement().getLeftElement().compareTo(e2.getLeftElement().getLeftElement());
            }
            
        return e2.getRightElement().compareTo(e1.getRightElement());
      }
    });
            
            
    Collections.sort(lovePmis, new Comparator<PairOfWritables<PairOfStrings, FloatWritable>>() {
      public int compare(PairOfWritables<PairOfStrings, FloatWritable> e1,
          PairOfWritables<PairOfStrings, FloatWritable> e2) {
        if (e2.getRightElement().compareTo(e1.getRightElement()) == 0) {
    return e1.getLeftElement().getLeftElement().compareTo(e2.getLeftElement().getLeftElement());
           }
            
        return e2.getRightElement().compareTo(e1.getRightElement());
      }
    });
            
     PairOfWritables<PairOfStrings, FloatWritable> highestPMI = pmis.get(0);
     PairOfWritables<PairOfStrings, FloatWritable> highestCloudPMI = cloudPmis.get(0);      PairOfWritables<PairOfStrings, FloatWritable> highestCloudPMI2 = cloudPmis.get(1);
     PairOfWritables<PairOfStrings, FloatWritable> highestCloudPMI3 = cloudPmis.get(2);
             
     PairOfWritables<PairOfStrings, FloatWritable> highestLovePMI = lovePmis.get(0);       PairOfWritables<PairOfStrings, FloatWritable> highestLovePMI2 = lovePmis.get(1);
     PairOfWritables<PairOfStrings, FloatWritable> highestLovePMI3 = lovePmis.get(2);*/

    System.out.println("Total Distinct Pairs : " + countPairs);
    System.out.println("Pair with highest PMI : (" + highestPMI.getLeftElement().getLeftElement() + ", "
            + highestPMI.getLeftElement().getRightElement());

    System.out
            .println("Word with highest PMI with Cloud : " + highestCloudPMI.getLeftElement().getRightElement()
                    + " with value : " + highestCloudPMI.getRightElement().get());
    System.out.println(
            "Word with second highest PMI with Cloud : " + highestCloudPMI2.getLeftElement().getRightElement()
                    + " with value : " + highestCloudPMI2.getRightElement().get());
    System.out.println(
            "Word with third highest PMI with Cloud : " + highestCloudPMI3.getLeftElement().getRightElement()
                    + " with value : " + highestCloudPMI3.getRightElement().get());

    System.out.println("Word with highest PMI with Love : " + highestLovePMI.getLeftElement().getRightElement()
            + " with value : " + highestLovePMI.getRightElement().get());
    System.out.println(
            "Word with second highest PMI with Love : " + highestLovePMI2.getLeftElement().getRightElement()
                    + " with value : " + highestLovePMI2.getRightElement().get());
    System.out.println(
            "Word with third highest PMI with Love : " + highestLovePMI3.getLeftElement().getRightElement()
                    + " with value : " + highestLovePMI3.getRightElement().get());

}

From source file:com.khubla.jvmbasic.jvmbasicc.JVMBasic.java

/**
 * start here//from  w  w w . j  av  a 2  s . c om
 * <p>
 * -file src\test\resources\bas\easy\print.bas -verbose true
 * </p>
 */
public static void main(String[] args) {
    try {
        System.out.println("khubla.com jvmBASIC Compiler");
        /*
         * options
         */
        final Options options = new Options();
        Option oo = Option.builder().argName(OUTPUT_OPTION).longOpt(OUTPUT_OPTION).type(String.class).hasArg()
                .required(false).desc("target directory to output to").build();
        options.addOption(oo);
        oo = Option.builder().argName(FILE_OPTION).longOpt(FILE_OPTION).type(String.class).hasArg()
                .required(true).desc("file to compile").build();
        options.addOption(oo);
        oo = Option.builder().argName(VERBOSE_OPTION).longOpt(VERBOSE_OPTION).type(String.class).hasArg()
                .required(false).desc("verbose output").build();
        options.addOption(oo);
        /*
         * parse
         */
        final CommandLineParser parser = new DefaultParser();
        CommandLine cmd = null;
        try {
            cmd = parser.parse(options, args);
        } catch (final Exception e) {
            e.printStackTrace();
            final HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("posix", options);
            System.exit(0);
        }
        /*
         * verbose output?
         */
        final Boolean verbose = Boolean.parseBoolean(cmd.getOptionValue(VERBOSE_OPTION));
        /*
         * get the file
         */
        final String filename = cmd.getOptionValue(FILE_OPTION);
        final String outputDirectory = cmd.getOptionValue(OUTPUT_OPTION);
        if (null != filename) {
            /*
             * filename
             */
            final String basFileName = System.getProperty("user.dir") + "/" + filename;
            final File fl = new File(basFileName);
            if (true == fl.exists()) {
                /*
                 * show the filename
                 */
                System.out.println("Compiling: " + fl.getCanonicalFile());
                /*
                 * compiler
                 */
                final JVMBasicCompiler jvmBasicCompiler = new JVMBasicCompiler();
                /*
                 * compile
                 */
                jvmBasicCompiler.compileToClassfile(basFileName, null, outputDirectory, verbose, true, true);
            } else {
                throw new Exception("Unable to find: '" + basFileName + "'");
            }
        } else {
            throw new Exception("File was not supplied");
        }
    } catch (final Exception e) {
        e.printStackTrace();
    }
}

From source file:de.prozesskraft.pkraft.Clone.java

public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException {

    /*----------------------------
      get options from ini-file/*from   w  ww.ja  v a2 s . c  o  m*/
    ----------------------------*/
    java.io.File inifile = new java.io.File(
            WhereAmI.getInstallDirectoryAbsolutePath(Clone.class) + "/" + "../etc/pkraft-clone.ini");

    if (inifile.exists()) {
        try {
            ini = new Ini(inifile);
        } catch (InvalidFileFormatException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } else {
        System.err.println("ini file does not exist: " + inifile.getAbsolutePath());
        System.exit(1);
    }

    /*----------------------------
      create boolean options
    ----------------------------*/
    Option ohelp = new Option("help", "print this message");
    Option ov = new Option("v", "prints version and build-date");

    /*----------------------------
      create argument options
    ----------------------------*/
    Option oinstance = OptionBuilder.withArgName("File").hasArg()
            .withDescription("[mandatory] process you want to clone.")
            //            .isRequired()
            .create("instance");

    Option obasedir = OptionBuilder.withArgName("DIR").hasArg().withDescription(
            "[optional, default: <basedirOfInstance>] base directory you want to place the root directory of the clone. this directory must exist at call time.")
            //            .isRequired()
            .create("basedir");

    /*----------------------------
      create options object
    ----------------------------*/
    Options options = new Options();

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(oinstance);
    options.addOption(obasedir);

    /*----------------------------
      create the parser
    ----------------------------*/
    CommandLineParser parser = new GnuParser();
    // parse the command line arguments
    commandline = parser.parse(options, args);

    /*----------------------------
      usage/help
    ----------------------------*/
    if (commandline.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("clone", options);
        System.exit(0);
    }

    if (commandline.hasOption("v")) {
        System.out.println("author:  alexander.vogel@prozesskraft.de");
        System.out.println("version: [% version %]");
        System.out.println("date:    [% date %]");
        System.exit(0);
    }
    /*----------------------------
      ueberpruefen ob eine schlechte kombination von parametern angegeben wurde
    ----------------------------*/
    if (!(commandline.hasOption("instance"))) {
        System.err.println("option -instance is mandatory");
        exiter();
    }

    /*----------------------------
      die lizenz ueberpruefen und ggf abbrechen
    ----------------------------*/

    // check for valid license
    ArrayList<String> allPortAtHost = new ArrayList<String>();
    allPortAtHost.add(ini.get("license-server", "license-server-1"));
    allPortAtHost.add(ini.get("license-server", "license-server-2"));
    allPortAtHost.add(ini.get("license-server", "license-server-3"));

    MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1");

    // lizenz-logging ausgeben
    for (String actLine : (ArrayList<String>) lic.getLog()) {
        System.err.println(actLine);
    }

    // abbruch, wenn lizenz nicht valide
    if (!lic.isValid()) {
        System.exit(1);
    }

    /*----------------------------
      die eigentliche business logic
    ----------------------------*/
    String pathToInstance = commandline.getOptionValue("instance");
    java.io.File fileInstance = new java.io.File(pathToInstance);
    java.io.File fileBaseDir = null;

    // wenn es nicht vorhanden ist, dann mit fehlermeldung abbrechen
    if (!fileInstance.exists()) {
        System.err.println("instance file does not exist.");
        exiter();
    }

    // testen ob eventuell vorhandene angaben basedir
    if (commandline.hasOption("basedir")) {
        fileBaseDir = new java.io.File(commandline.getOptionValue("basedir"));
        if (!fileBaseDir.exists()) {
            System.err.println("error: -basedir: directory does not exist");
            exiter();
        }
        if (!fileBaseDir.isDirectory()) {
            System.err.println("error: -basedir: is not a directory");
            exiter();
        }
    }

    // den main-prozess trotzdem nochmal einlesen um subprozesse extrahieren zu koennen
    Process p1 = new Process();
    p1.setInfilebinary(pathToInstance);
    Process process = p1.readBinary();

    // directories setzen, falls angegeben
    if (fileBaseDir != null) {
        process.setBaseDir(fileBaseDir.getCanonicalPath());
    }

    // den main-prozess ueber die static function klonen
    Process clonedProcess = cloneProcess(process, null);

    // alle steps durchgehen und falls subprocesses existieren auch fuer diese ein cloning durchfuehren
    for (Step actStep : process.getStep()) {
        if (actStep.getSubprocess() != null) {
            Process pDummy = new Process();
            pDummy.setInfilebinary(actStep.getAbsdir() + "/process.pmb");
            Process processInSubprocess = pDummy.readBinary();
            //            System.err.println("info: reading process freshly from file: " + actStep.getAbsdir() + "/process.pmb");
            if (processInSubprocess != null) {
                cloneProcess(processInSubprocess, clonedProcess);
            }
        }
    }
}

From source file:com.act.reachables.CladeTraversal.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  ww .j  a v a2s  .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(CladeTraversal.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

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

    String targetInchi = cl.getOptionValue(OPTION_TARGET_INCHI, PABA_INCHI);
    String inchiFileName = cl.getOptionValue(OPTION_OUTPUT_INCHI_FILE_NAME, DEFAULT_INCHI_FILE);
    String reactionsFileName = cl.getOptionValue(OPTION_OUTPUT_REACTION_FILE_NAME, DEFAULT_REACTIONS_FILE);
    String reactionDirectory = cl.getOptionValue(OPTION_OUTPUT_FAILED_REACTIONS_DIR_NAME, "/");
    String actDataFile = cl.getOptionValue(OPTION_ACT_DATA_FILE, DEFAULT_ACTDATA_FILE);

    runCladeExpansion(actDataFile, targetInchi, inchiFileName, reactionsFileName, reactionDirectory);
}

From source file:com.genentech.chemistry.openEye.apps.SDFMDLSSSMatcher.java

public static void main(String... args) throws IOException, InterruptedException {
    oechem.OEUseJavaHeap(false);//from   w  ww  . ja  va  2 s.c  o m

    // create command line Options object
    Options options = new Options();
    Option opt = new Option("in", true, "input file [.sdf,...]");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option("out", true, "output file oe-supported");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("ref", true, "refrence file with MDL query molecules");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option("anyMatch", false, "if set all matches are reported not just the first.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("printAll", false, "if set even compounds that do not macht are outputted.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("nCpu", true, "number of CPU's used in parallel, dafault 1");
    opt.setRequired(false);
    options.addOption(opt);

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp(options);
    }

    args = cmd.getArgs();
    if (args.length > 0) {
        exitWithHelp("Unknown param: " + args[0], options);
    }

    if (cmd.hasOption("d")) {
        System.err.println("Start debugger and press return:");
        new BufferedReader(new InputStreamReader(System.in)).readLine();
    }

    int nCpu = 1;
    boolean firstMatch = !cmd.hasOption("anyMatch");
    boolean printAll = cmd.hasOption("printAll");

    String d = cmd.getOptionValue("nCpu");
    if (d != null)
        nCpu = Integer.parseInt(d);

    String inFile = cmd.getOptionValue("in");
    String outFile = cmd.getOptionValue("out");
    String refFile = cmd.getOptionValue("ref");

    SDFMDLSSSMatcher matcher = new SDFMDLSSSMatcher(refFile, outFile, firstMatch, printAll, nCpu);
    matcher.run(inFile);
    matcher.close();
}

From source file:fr.tpt.s3.mcdag.scheduling.Main.java

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

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

    Option input = new Option("i", "input", true, "MC-DAG XML Models");
    input.setRequired(true);//  w  w  w .  j a  v a  2 s .c o m
    input.setArgs(Option.UNLIMITED_VALUES); // Sets maximum number of threads to be launched
    options.addOption(input);

    Option outSched = new Option("os", "out-scheduler", false, "Write the scheduling tables into a file.");
    outSched.setRequired(false);
    options.addOption(outSched);

    Option outPrism = new Option("op", "out-prism", false, "Write PRISM model into a file.");
    outPrism.setRequired(false);
    options.addOption(outPrism);

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

    Option debugOpt = new Option("d", "debug", false, "Enabling debug.");
    debugOpt.setRequired(false);
    options.addOption(debugOpt);

    Option preemptOpt = new Option("p", "preempt", false, "Count for preemptions.");
    preemptOpt.setRequired(false);
    options.addOption(preemptOpt);

    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd;

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        formatter.printHelp("MC-DAG framework", options);

        System.exit(1);
        return;
    }

    String inputFilePath[] = cmd.getOptionValues("input");
    boolean bOutSched = cmd.hasOption("out-scheduler");
    boolean bOutPrism = cmd.hasOption("out-prism");
    boolean debug = cmd.hasOption("debug");
    boolean preempt = cmd.hasOption("preempt");
    boolean levels = cmd.hasOption("n-levels");
    int nbFiles = inputFilePath.length;

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

    if (debug)
        System.out.println("[DEBUG] Launching " + inputFilePath.length + " thread(s).");

    int i_files = 0;
    ExecutorService executor = Executors.newFixedThreadPool(nbJobs);

    /* Launch threads to solve allocation */
    while (i_files != nbFiles) {
        SchedulingThread ft = new SchedulingThread(inputFilePath[i_files], bOutSched, bOutPrism, debug,
                preempt);

        ft.setLevels(levels);
        executor.execute(ft);
        i_files++;
    }

    executor.shutdown();
    executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
    System.out.println("[FRAMEWORK Main] DONE");
}

From source file:es.tid.fiware.fiwareconnectors.cygnus.nodes.CygnusApplication.java

/**
 * Main application to be run when this CygnusApplication is invoked. The only differences with the original one
 * are the CygnusApplication is used instead of the Application one, and the Management Interface port option in
 * the command line.//from   www  .j  a  va 2 s . c om
 * @param args
 */
public static void main(String[] args) {
    try {
        Options options = new Options();

        Option option = new Option("n", "name", true, "the name of this agent");
        option.setRequired(true);
        options.addOption(option);

        option = new Option("f", "conf-file", true, "specify a conf file");
        option.setRequired(true);
        options.addOption(option);

        option = new Option(null, "no-reload-conf", false, "do not reload " + "conf file if changed");
        options.addOption(option);

        option = new Option("h", "help", false, "display help text");
        options.addOption(option);

        option = new Option("p", "mgmt-if-port", true, "the management interface port");
        option.setRequired(false);
        options.addOption(option);

        CommandLineParser parser = new GnuParser();
        CommandLine commandLine = parser.parse(options, args);

        File configurationFile = new File(commandLine.getOptionValue('f'));
        String agentName = commandLine.getOptionValue('n');
        boolean reload = !commandLine.hasOption("no-reload-conf");

        if (commandLine.hasOption('h')) {
            new HelpFormatter().printHelp("flume-ng agent", options, true);
            return;
        } // if

        int mgmtIfPort = 8081; // default value

        if (commandLine.hasOption('p')) {
            mgmtIfPort = new Integer(commandLine.getOptionValue('p')).intValue();
        } // if

        // the following is to ensure that by default the agent will fail on startup if the file does not exist

        if (!configurationFile.exists()) {
            // if command line invocation, then need to fail fast
            if (System.getProperty(Constants.SYSPROP_CALLED_FROM_SERVICE) == null) {
                String path = configurationFile.getPath();

                try {
                    path = configurationFile.getCanonicalPath();
                } catch (IOException ex) {
                    logger.error("Failed to read canonical path for file: " + path, ex);
                } // try catch

                throw new ParseException("The specified configuration file does not exist: " + path);
            } // if
        } // if

        List<LifecycleAware> components = Lists.newArrayList();
        CygnusApplication application;

        if (reload) {
            EventBus eventBus = new EventBus(agentName + "-event-bus");
            PollingPropertiesFileConfigurationProvider configurationProvider = new PollingPropertiesFileConfigurationProvider(
                    agentName, configurationFile, eventBus, 30);
            components.add(configurationProvider);
            application = new CygnusApplication(components, mgmtIfPort);
            eventBus.register(application);
        } else {
            PropertiesFileConfigurationProvider configurationProvider = new PropertiesFileConfigurationProvider(
                    agentName, configurationFile);
            application = new CygnusApplication(mgmtIfPort);
            application.handleConfigurationEvent(configurationProvider.getConfiguration());
        } // if else

        application.start();

        final CygnusApplication appReference = application;
        Runtime.getRuntime().addShutdownHook(new Thread("agent-shutdown-hook") {
            @Override
            public void run() {
                appReference.stop();
            } // run
        });
    } catch (Exception e) {
        logger.error("A fatal error occurred while running. Exception follows.", e);
    } // try catch
}

From source file:fr.tpt.s3.mcdag.generator.MainGenerator.java

/**
 * Main method for the generator: it launches a given number of threads with the parameters
 * given/*w ww. ja  v  a 2 s  . c o m*/
 * @param args
 */
public static void main(String[] args) {

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

    Option o_hi = new Option("mu", "max_utilization", true, "Upper bound utilization");
    o_hi.setRequired(true);
    options.addOption(o_hi);

    Option o_tasks = new Option("nt", "nb_tasks", true, "Number of tasks for the system");
    o_tasks.setRequired(true);
    options.addOption(o_tasks);

    Option o_eprob = new Option("e", "eprobability", true, "Probability of edges");
    o_eprob.setRequired(true);
    options.addOption(o_eprob);

    Option o_levels = new Option("l", "levels", true, "Number of criticality levels");
    o_levels.setRequired(true);
    options.addOption(o_levels);

    Option o_para = new Option("p", "parallelism", true, "Max parallelism for the DAGs");
    o_para.setRequired(true);
    options.addOption(o_para);

    Option o_nbdags = new Option("nd", "num_dags", true, "Number of DAGs");
    o_nbdags.setRequired(true);
    options.addOption(o_nbdags);

    Option o_nbfiles = new Option("nf", "num_files", true, "Number of files");
    o_nbfiles.setRequired(true);
    options.addOption(o_nbfiles);

    Option o_rfactor = new Option("rf", "reduc_factor", true, "Reduction factor for criticality modes");
    o_rfactor.setRequired(false);
    options.addOption(o_rfactor);

    Option o_out = new Option("o", "output", true, "Output file for the DAG");
    o_out.setRequired(true);
    options.addOption(o_out);

    Option graphOpt = new Option("g", "graphviz", false, "Generate a graphviz DOT file");
    graphOpt.setRequired(false);
    options.addOption(graphOpt);

    Option debugOpt = new Option("d", "debug", false, "Enabling debug");
    debugOpt.setRequired(false);
    options.addOption(debugOpt);

    Option jobsOpt = new Option("j", "jobs", true, "Number of jobs");
    jobsOpt.setRequired(false);
    options.addOption(jobsOpt);

    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd;

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        formatter.printHelp("DAG Generator", options);

        System.exit(1);
        return;
    }

    double maxU = Double.parseDouble(cmd.getOptionValue("max_utilization"));
    int edgeProb = Integer.parseInt(cmd.getOptionValue("eprobability"));
    int levels = Integer.parseInt(cmd.getOptionValue("levels"));
    int nbDags = Integer.parseInt(cmd.getOptionValue("num_dags"));
    int nbFiles = Integer.parseInt(cmd.getOptionValue("num_files"));
    int para = Integer.parseInt(cmd.getOptionValue("parallelism"));
    int nbTasks = Integer.parseInt(cmd.getOptionValue("nb_tasks"));
    boolean graph = cmd.hasOption("graphviz");
    boolean debug = cmd.hasOption("debug");
    String output = cmd.getOptionValue("output");
    int nbJobs = 1;
    if (cmd.hasOption("jobs"))
        nbJobs = Integer.parseInt(cmd.getOptionValue("jobs"));
    double rfactor = 2.0;
    if (cmd.hasOption("reduc_factor"))
        rfactor = Double.parseDouble(cmd.getOptionValue("reduc_factor"));
    /* ============================= Generator parameters ============================= */

    if (nbFiles < 0 || nbDags < 0 || nbJobs < 0) {
        System.err.println("[ERROR] Generator: Number of files & DAGs need to be positive.");
        formatter.printHelp("DAG Generator", options);
        System.exit(1);
        return;
    }

    Thread threads[] = new Thread[nbJobs];

    int nbFilesCreated = 0;
    int count = 0;

    while (nbFilesCreated != nbFiles) {
        int launched = 0;

        for (int i = 0; i < nbJobs && count < nbFiles; i++) {
            String outFile = output.substring(0, output.lastIndexOf('.')).concat("-" + count + ".xml");
            GeneratorThread gt = new GeneratorThread(maxU, nbTasks, edgeProb, levels, para, nbDags, rfactor,
                    outFile, graph, debug);
            threads[i] = new Thread(gt);
            threads[i].setName("GeneratorThread-" + i);
            launched++;
            count++;
            threads[i].start();
        }

        for (int i = 0; i < launched; i++) {
            try {
                threads[i].join();
                nbFilesCreated++;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.genentech.struchk.sdfNormalizer.java

public static void main(String[] args) {
    long start = System.currentTimeMillis();
    int nMessages = 0;
    int nErrors = 0;
    int nStruct = 0;

    // create command line Options object
    Options options = new Options();
    Option opt = new Option("in", true, "input file [.ism,.sdf,...]");
    opt.setRequired(true);/*from   w  ww.j  av a  2 s .  c  om*/
    options.addOption(opt);

    opt = new Option("out", true, "output file");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option("mol", true, "molFile used for output: ORIGINAL(def)|NORMALIZED|TAUTOMERIC");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("shortMessage", false,
            "Limit message to first 80 characters to conform with sdf file specs.");
    opt.setRequired(false);
    options.addOption(opt);

    CommandLineParser parser = new PosixParser();
    CommandLine cmd;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        exitWithHelp(options, e.getMessage());
        throw new Error(e); // avoid compiler errors
    }
    args = cmd.getArgs();

    if (args.length != 0) {
        System.err.print("Unknown options: " + args + "\n\n");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("sdfNormalizer", options);
        System.exit(1);
    }

    String molOpt = cmd.getOptionValue("mol");
    OUTMolFormat outMol = OUTMolFormat.ORIGINAL;
    if (molOpt == null || "original".equalsIgnoreCase(molOpt))
        outMol = OUTMolFormat.ORIGINAL;
    else if ("NORMALIZED".equalsIgnoreCase(molOpt))
        outMol = OUTMolFormat.NORMALIZED;
    else if ("TAUTOMERIC".equalsIgnoreCase(molOpt))
        outMol = OUTMolFormat.TAUTOMERIC;
    else {
        System.err.printf("Unkown option for -mol: %s\n", molOpt);
        System.exit(1);
    }

    String inFile = cmd.getOptionValue("in");
    String outFile = cmd.getOptionValue("out");
    boolean limitMessage = cmd.hasOption("shortMessage");

    try {
        oemolistream ifs = new oemolistream(inFile);
        oemolostream ofs = new oemolostream(outFile);

        URL cFile = OEStruchk.getResourceURL(OEStruchk.class, "Struchk.xml");

        // create OEStruchk from config file
        OEStruchk strchk = new OEStruchk(cFile, CHECKConfig.ASSIGNStructFlag, false);

        OEGraphMol mol = new OEGraphMol();
        StringBuilder sb = new StringBuilder(2000);
        while (oechem.OEReadMolecule(ifs, mol)) {
            if (!strchk.applyRules(mol, null))
                nErrors++;

            switch (outMol) {
            case NORMALIZED:
                mol.Clear();
                oechem.OEAddMols(mol, strchk.getTransformedMol("parent"));
                break;
            case TAUTOMERIC:
                mol.Clear();
                oechem.OEAddMols(mol, strchk.getTransformedMol(null));
                break;
            case ORIGINAL:
                break;
            }

            oechem.OESetSDData(mol, "CTISMILES", strchk.getTransformedIsoSmiles(null));
            oechem.OESetSDData(mol, "CTSMILES", strchk.getTransformedSmiles(null));
            oechem.OESetSDData(mol, "CISMILES", strchk.getTransformedIsoSmiles("parent"));
            oechem.OESetSDData(mol, "Strutct_Flag", strchk.getStructureFlag().getName());

            List<Message> msgs = strchk.getStructureMessages(null);
            nMessages += msgs.size();
            for (Message msg : msgs)
                sb.append(String.format("\t%s:%s", msg.getLevel(), msg.getText()));
            if (limitMessage)
                sb.setLength(Math.min(sb.length(), 80));

            oechem.OESetSDData(mol, "NORM_MESSAGE", sb.toString());

            oechem.OEWriteMolecule(ofs, mol);

            sb.setLength(0);
            nStruct++;
        }
        strchk.delete();
        mol.delete();
        ifs.close();
        ifs.delete();
        ofs.close();
        ofs.delete();

    } catch (Exception e) {
        throw new Error(e);
    } finally {
        System.err.printf("sdfNormalizer: Checked %d structures %d errors, %d messages in %dsec\n", nStruct,
                nErrors, nMessages, (System.currentTimeMillis() - start) / 1000);
    }
}

From source file:act.installer.pubchem.PubchemSynonymFinder.java

public static void main(String[] args) throws Exception {
    org.apache.commons.cli.Options opts = new org.apache.commons.cli.Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());
    }/*from  www. j  av a  2  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(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

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

    File rocksDBFile = new File(cl.getOptionValue(OPTION_INDEX_PATH));
    if (!rocksDBFile.isDirectory()) {
        System.err.format("Index directory does not exist or is not a directory at '%s'",
                rocksDBFile.getAbsolutePath());
        HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    List<String> compoundIds = null;
    if (cl.hasOption(OPTION_PUBCHEM_COMPOUND_ID)) {
        compoundIds = Collections.singletonList(cl.getOptionValue(OPTION_PUBCHEM_COMPOUND_ID));
    } else if (cl.hasOption(OPTION_IDS_FILE)) {
        File idsFile = new File(cl.getOptionValue(OPTION_IDS_FILE));
        if (!idsFile.exists()) {
            System.err.format("Cannot find Pubchem CIDs file at %s", idsFile.getAbsolutePath());
            HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                    true);
            System.exit(1);
        }

        compoundIds = getCIDsFromFile(idsFile);

        if (compoundIds.size() == 0) {
            System.err.format("Found zero Pubchem CIDs to process in file at '%s', exiting",
                    idsFile.getAbsolutePath());
            HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                    true);
            System.exit(1);
        }
    } else {
        System.err.format("Must specify one of '%s' or '%s'; index is too big to print all synonyms.",
                OPTION_PUBCHEM_COMPOUND_ID, OPTION_IDS_FILE);
        HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    // Run a quick check to warn users of malformed ids.
    compoundIds.forEach(x -> {
        if (!PC_CID_PATTERN.matcher(x).matches()) { // Use matches() for complete matching.
            LOGGER.warn("Specified compound id does not match expected format: %s", x);
        }
    });

    LOGGER.info("Opening DB and searching for %d Pubchem CIDs", compoundIds.size());
    Pair<RocksDB, Map<PubchemTTLMerger.COLUMN_FAMILIES, ColumnFamilyHandle>> dbAndHandles = null;
    Map<String, PubchemSynonyms> results = new LinkedHashMap<>(compoundIds.size());
    try {
        dbAndHandles = PubchemTTLMerger.openExistingRocksDB(rocksDBFile);
        RocksDB db = dbAndHandles.getLeft();
        ColumnFamilyHandle cidToSynonymsCfh = dbAndHandles.getRight()
                .get(PubchemTTLMerger.COLUMN_FAMILIES.CID_TO_SYNONYMS);

        for (String cid : compoundIds) {
            PubchemSynonyms synonyms = null;
            byte[] val = db.get(cidToSynonymsCfh, cid.getBytes(UTF8));
            if (val != null) {
                ObjectInputStream oi = new ObjectInputStream(new ByteArrayInputStream(val));
                // We're relying on our use of a one-value-type per index model here so we can skip the instanceof check.
                synonyms = (PubchemSynonyms) oi.readObject();
            } else {
                LOGGER.warn("No synonyms available for compound id '%s'", cid);
            }
            results.put(cid, synonyms);
        }
    } finally {
        if (dbAndHandles != null) {
            dbAndHandles.getLeft().close();
        }
    }

    try (OutputStream outputStream = cl.hasOption(OPTION_OUTPUT)
            ? new FileOutputStream(cl.getOptionValue(OPTION_OUTPUT))
            : System.out) {
        OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValue(outputStream, results);
        new OutputStreamWriter(outputStream).append('\n');
    }
    LOGGER.info("Done searching for Pubchem synonyms");
}