Example usage for org.apache.commons.cli Option Option

List of usage examples for org.apache.commons.cli Option Option

Introduction

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

Prototype

public Option(String opt, String longOpt, boolean hasArg, String description) throws IllegalArgumentException 

Source Link

Document

Creates an Option using the specified parameters.

Usage

From source file:LNISmokeTest.java

/**
 * Execute command line. See Usage string for options and arguments.
 * /*from w w w . jav  a 2 s.  co m*/
 * @param argv the argv
 * 
 * @throws Exception the exception
 */
public static void main(String[] argv) throws Exception {
    Options options = new Options();

    OptionGroup func = new OptionGroup();
    func.addOption(new Option("c", "copy", true, "copy <Item> to -C <Collection>"));
    func.addOption(new Option("s", "submit", true, "submit <collection> -P <packager> -i <file>"));
    func.addOption(new Option("d", "disseminate", true, "disseminate <item> -P <packager> -o <file>"));
    func.addOption(new Option("f", "propfind", true, "propfind of all properties or -N <propname>"));
    func.addOption(new Option("r", "rpropfind", true, "recursive propfind, only collections"));
    func.addOption(new Option("n", "names", true, "list all property names on resource"));
    func.addOption(new Option("p", "proppatch", true, "set property: <handle> -N <property> -V <newvalue>"));
    func.setRequired(true);
    options.addOptionGroup(func);

    options.addOption("h", "help", false, "show help message");
    options.addOption("e", "endpoint", true, "SOAP endpoint URL (REQUIRED)");
    options.addOption("P", "packager", true, "Packager to use to import/export a package.");
    options.addOption("C", "collection", true, "Target collection of -c copy");
    options.addOption("o", "output", true, "file to create for new package");
    options.addOption("i", "input", true, "file containing package to submit");
    options.addOption("N", "name", true, "name of property to query/set");
    options.addOption("V", "value", true, "new value for property being set");

    try {
        CommandLine line = (new PosixParser()).parse(options, argv);
        if (line.hasOption("h")) {
            usage(options, 0, null);
        }

        // get SOAP client connection, using the endpoint URL
        String endpoint = line.getOptionValue("e");
        if (endpoint == null) {
            usage(options, 2, "Missing the required -e endpoint argument");
        }
        LNISoapServletServiceLocator loc = new LNISoapServletServiceLocator();
        LNISoapServlet lni = loc.getDSpaceLNI(new URL(endpoint));

        // propfind - with optional single-property Name
        if (line.hasOption("f")) {
            String pfXml = (line.hasOption("N"))
                    ? specificPropPrefix + line.getOptionValue("N") + specificPropSuffix
                    : allProp;
            doPropfind(lni, line.getOptionValue("f"), pfXml, 0, null);
        }

        // recursive propfind limited to collection, community objects
        else if (line.hasOption("r")) {
            doPropfind(lni, line.getOptionValue("r"), someProp, -1, "collection,community");
        } else if (line.hasOption("n")) {
            doPropfind(lni, line.getOptionValue("n"), nameProp, 0, null);
        } else if (line.hasOption("p")) {
            if (line.hasOption("N") && line.hasOption("V")) {
                doProppatch(lni, line.getOptionValue("p"), line.getOptionValue("N"), line.getOptionValue("V"));
            } else {
                usage(options, 13, "Missing required args: -N <name> -V <value>n");
            }
        }

        // submit a package
        else if (line.hasOption("s")) {
            if (line.hasOption("P") && line.hasOption("i")) {
                doPut(lni, line.getOptionValue("s"), line.getOptionValue("P"), line.getOptionValue("i"),
                        endpoint);
            } else {
                usage(options, 13, "Missing required args after -s: -P <packager> -i <file>");
            }
        }

        // Disseminate (GET) item as package
        else if (line.hasOption("d")) {
            if (line.hasOption("P") && line.hasOption("o")) {
                doGet(lni, line.getOptionValue("d"), line.getOptionValue("P"), line.getOptionValue("o"),
                        endpoint);
            } else {
                usage(options, 13, "Missing required args after -d: -P <packager> -o <file>");
            }
        }

        // copy from src to dst
        else if (line.hasOption("c")) {
            if (line.hasOption("C")) {
                doCopy(lni, line.getOptionValue("c"), line.getOptionValue("C"));
            } else {
                usage(options, 13, "Missing required args after -c: -C <collection>\n");
            }
        } else {
            usage(options, 14, "Missing command option.\n");
        }

    } catch (ParseException pe) {
        usage(options, 1, "Error in arguments: " + pe.toString());

    } catch (java.rmi.RemoteException de) {
        System.out.println("ERROR, got RemoteException, message=" + de.getMessage());

        de.printStackTrace();

        die(1, "  Exception class=" + de.getClass().getName());
    }
}

From source file:com.basistech.ninja.Train.java

/**
 * Command line interface to train a model.
 *
 * <pre>/*from   w  w  w.java  2s  .  c o m*/
 *  usage: Train [options]
 *  --batch-size <arg>      batch size (default = 10)
 *  --epochs <arg>          epochs (default = 5)
 *  --examples <arg>        input examples file (required)
 *  --layer-sizes <arg>     layer sizes, including input/output, e.g. 3 4 2 (required)
 *  --learning-rate <arg>   learning-rate (default = 0.7)
 *  --model <arg>           output model file (required)
 * </pre>
 *
 * @param args command line arguments
 * @throws IOException
 */
public static void main(String[] args) throws IOException {
    String defaultBatchSize = "10";
    String deafaultEpochs = "5";
    String defaultLearningRate = "0.7";

    Options options = new Options();
    Option option;
    option = new Option(null, "examples", true, "input examples file (required)");
    option.setRequired(true);
    options.addOption(option);
    option = new Option(null, "model", true, "output model file (required)");
    option.setRequired(true);
    options.addOption(option);
    option = new Option(null, "layer-sizes", true,
            "layer sizes, including input/output, e.g. 3 4 2 (required)");
    option.setRequired(true);
    option.setArgs(Option.UNLIMITED_VALUES);
    options.addOption(option);
    option = new Option(null, "batch-size", true, String.format("batch size (default = %s)", defaultBatchSize));
    options.addOption(option);
    option = new Option(null, "epochs", true, String.format("epochs (default = %s)", deafaultEpochs));
    options.addOption(option);
    option = new Option(null, "learning-rate", true,
            String.format("learning-rate (default = %s)", defaultLearningRate));
    options.addOption(option);

    CommandLineParser parser = new GnuParser();
    CommandLine cmdline = null;
    try {
        cmdline = parser.parse(options, args);
    } catch (org.apache.commons.cli.ParseException e) {
        System.err.println(e.getMessage());
        usage(options);
        System.exit(1);
    }
    String[] remaining = cmdline.getArgs();
    if (remaining == null) {
        usage(options);
        System.exit(1);
    }

    List<Integer> layerSizes = Lists.newArrayList();
    for (String s : cmdline.getOptionValues("layer-sizes")) {
        layerSizes.add(Integer.parseInt(s));
    }

    File examplesFile = new File(cmdline.getOptionValue("examples"));
    Train that = new Train(layerSizes, examplesFile);
    int batchSize = Integer.parseInt(cmdline.getOptionValue("batch-size", defaultBatchSize));
    int epochs = Integer.parseInt(cmdline.getOptionValue("epochs", deafaultEpochs));
    double learningRate = Double.parseDouble(cmdline.getOptionValue("learning-rate", defaultLearningRate));
    File modelFile = new File(cmdline.getOptionValue("model"));

    that.train(batchSize, epochs, learningRate, modelFile);
}

From source file:edu.ksu.cis.indus.staticanalyses.flow.instances.ofa.OFAXMLizerCLI.java

/**
 * The entry point to the program via command line.
 * /*from  www . ja v  a 2s  .  com*/
 * @param args is the command line arguments.
 * @throws RuntimeException when object flow analysis fails.
 */
public static void main(final String[] args) {
    final Options _options = new Options();
    Option _option = new Option("c", "cumulative", false, "Consider all root methods in the same execution.");
    _options.addOption(_option);
    _option = new Option("o", "output", true, "Directory into which xml files will be written into.");
    _option.setArgs(1);
    _options.addOption(_option);
    _option = new Option("j", "jimple", false, "Dump xmlized jimple.");
    _options.addOption(_option);
    _option = new Option("h", "help", false, "Display message.");
    _options.addOption(_option);
    _option = new Option("p", "soot-classpath", false, "Prepend this to soot class path.");
    _option.setArgs(1);
    _option.setArgName("classpath");
    _option.setOptionalArg(false);
    _options.addOption(_option);
    _option = new Option("t", "ofa-type", false, "Type of analysis : fioi, fsoi, fios, fsos, fioirt, fsoirt.");
    _option.setArgs(1);
    _option.setArgName("type");
    _option.setOptionalArg(false);
    _option.setRequired(true);
    _options.addOption(_option);
    _option = new Option("S", "scope", true, "The scope that should be analyzed.");
    _option.setArgs(1);
    _option.setArgName("scope");
    _option.setRequired(false);
    _options.addOption(_option);

    final PosixParser _parser = new PosixParser();

    try {
        final CommandLine _cl = _parser.parse(_options, args);

        if (_cl.hasOption("h")) {
            printUsage(_options);
            System.exit(1);
        }

        String _outputDir = _cl.getOptionValue('o');

        if (_outputDir == null) {
            if (LOGGER.isWarnEnabled()) {
                LOGGER.warn("Defaulting to current directory for output.");
            }
            _outputDir = ".";
        }

        if (_cl.getArgList().isEmpty()) {
            throw new MissingArgumentException("Please specify atleast one class.");
        }

        final OFAXMLizerCLI _cli = new OFAXMLizerCLI();
        _cli.xmlizer.setXmlOutputDir(_outputDir);
        _cli.xmlizer.setGenerator(new UniqueJimpleIDGenerator());
        _cli.setCumulative(_cl.hasOption('c'));
        _cli.setClassNames(_cl.getArgList());
        _cli.type = _cl.getOptionValue('t');

        if (_cl.hasOption('p')) {
            _cli.addToSootClassPath(_cl.getOptionValue('p'));
        }

        if (_cl.hasOption('S')) {
            _cli.setScopeSpecFile(_cl.getOptionValue('S'));
        }

        _cli.initialize();

        _cli.<ITokens>execute(_cl.hasOption('j'));
    } catch (final ParseException _e) {
        LOGGER.error("Error while parsing command line.", _e);
        System.out.println("Error while parsing command line. \n" + _e);
        printUsage(_options);
    } catch (final Throwable _e) {
        LOGGER.error("Beyond our control. May day! May day!", _e);
        throw new RuntimeException(_e);
    }
}

From source file:ar.edu.taco.TacoMain.java

/**
 * @param args/*from   w ww.  j  av a2s.  c  om*/
 */
@SuppressWarnings({ "static-access" })
public static void main(String[] args) {
    @SuppressWarnings("unused")
    int loopUnrolling = 3;

    String tacoVersion = getManifestAttribute(Attributes.Name.IMPLEMENTATION_VERSION);
    String tacoCreatedBy = getManifestAttribute(new Name("Created-By"));

    System.out.println("TACO: Taco static analysis tool.");
    System.out.println("Created By: " + tacoCreatedBy);
    System.out.println("Version: " + tacoVersion);
    System.out.println("");
    System.out.println("");

    Option helpOption = new Option("h", "help", false, "print this message");
    Option versionOption = new Option("v", "version", false, "shows version");

    Option configFileOption = OptionBuilder.withArgName("path").withLongOpt("configFile").hasArg()
            .withDescription("set the configuration file").create("cf");
    Option classToCheckOption = OptionBuilder.withArgName("classname").withLongOpt("classToCheck").hasArg()
            .withDescription("set the class to be checked").create('c');
    Option methodToCheckOption = OptionBuilder.withArgName("methodname").withLongOpt("methodToCheck").hasArg()
            .withDescription("set the method to be checked").create('m');
    Option dependenciesOption = OptionBuilder.withArgName("classname").withLongOpt("dependencies").hasArgs()
            .withDescription("additional sources to be parsed").create('d');
    Option relevantClassesOption = OptionBuilder.withArgName("classname").withLongOpt("relevantClasses")
            .hasArgs().withDescription("Set the relevant classes to be used").create("rd");
    Option loopsOptions = OptionBuilder.withArgName("integer").withLongOpt("unroll").hasArg()
            .withDescription("set number of loop unrollings").create('u');
    Option bitOptions = OptionBuilder.withArgName("integer").withLongOpt("width").hasArg()
            .withDescription("set bit width").create('w');
    Option instOptions = OptionBuilder.withArgName("integer").withLongOpt("bound").hasArg()
            .withDescription("set class bound").create('b');
    Option skolemizeOption = OptionBuilder.withLongOpt("skolemize")
            .withDescription("set whether or not skolemize").create("sk");
    Option simulateOption = OptionBuilder.withLongOpt("simulate")
            .withDescription("run method instead of checking").create("r");
    Option modularReasoningOption = OptionBuilder.withLongOpt("modularReasoning")
            .withDescription("check method using modular reasoning").create("mr");
    Option relevancyAnalysisOption = OptionBuilder.withLongOpt("relevancyAnalysis")
            .withDescription("calculate the needed relevantClasses").create("ra");
    Option scopeRestrictionOption = OptionBuilder.withLongOpt("scopeRestriction")
            .withDescription("restrict signature scope to value set in -b option").create("sr");
    /*
     * Option noVerifyOption = OptionBuilder.withLongOpt(
     * "noVerify").withDescription(
     * "builds output but does not invoke verification engine").create(
     * "nv");
     */
    Options options = new Options();
    options.addOption(helpOption);
    options.addOption(versionOption);
    options.addOption(configFileOption);
    options.addOption(classToCheckOption);
    options.addOption(methodToCheckOption);
    options.addOption(dependenciesOption);
    options.addOption(relevantClassesOption);
    options.addOption(loopsOptions);
    options.addOption(bitOptions);
    options.addOption(instOptions);
    options.addOption(skolemizeOption);
    options.addOption(simulateOption);
    options.addOption(modularReasoningOption);
    options.addOption(relevancyAnalysisOption);
    options.addOption(scopeRestrictionOption);
    // options.addOption(noVerifyOption)

    String configFileArgument = null;
    Properties overridingProperties = new Properties();
    TacoCustomScope tacoScope = new TacoCustomScope();

    // create the parser
    CommandLineParser parser = new PosixParser();

    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        // help
        if (line.hasOption(helpOption.getOpt())) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(120, CMD, HEADER, options, FOOTER, true);
            return;
        }

        // version
        if (line.hasOption(versionOption.getOpt())) {
            System.out.println(FOOTER);
            System.out.println("");
            return;
        }

        // Configuration file
        if (line.hasOption(configFileOption.getOpt())) {
            configFileArgument = line.getOptionValue(configFileOption.getOpt());
        }

        // class to check
        if (line.hasOption(classToCheckOption.getOpt())) {
            overridingProperties.put(TacoConfigurator.CLASS_TO_CHECK_FIELD,
                    line.getOptionValue(classToCheckOption.getOpt()));
        }

        // method to check
        if (line.hasOption(methodToCheckOption.getOpt())) {
            String methodtoCheck = line.getOptionValue(methodToCheckOption.getOpt());

            if (!methodtoCheck.matches("^[A-Za-z0-9_-]+_[0-9]")) {
                methodtoCheck = methodtoCheck + "_0";
            }
            overridingProperties.put(TacoConfigurator.METHOD_TO_CHECK_FIELD, methodtoCheck);
        }

        // Dependencies classes
        if (line.hasOption(dependenciesOption.getOpt())) {
            String dependenciesClasses = "";
            for (String aDependencyClass : line.getOptionValues(dependenciesOption.getOpt())) {
                dependenciesClasses += aDependencyClass;
            }
            overridingProperties.put(TacoConfigurator.CLASSES_FIELD, dependenciesClasses);
        }

        // Relevant classes
        if (line.hasOption(relevantClassesOption.getOpt())) {
            String relevantClasses = "";
            for (String aRelevantClass : line.getOptionValues(relevantClassesOption.getOpt())) {
                relevantClasses += aRelevantClass;
            }
            overridingProperties.put(TacoConfigurator.RELEVANT_CLASSES, relevantClasses);
        }

        // Loop unrolling
        if (line.hasOption(loopsOptions.getOpt())) {
            loopUnrolling = Integer.parseInt(line.getOptionValue(loopsOptions.getOpt()));
        }

        // Int bitwidth
        if (line.hasOption(bitOptions.getOpt())) {
            String alloy_bitwidth_str = line.getOptionValue(bitOptions.getOpt());
            overridingProperties.put(TacoConfigurator.BITWIDTH, alloy_bitwidth_str);
            int alloy_bitwidth = new Integer(alloy_bitwidth_str);
            tacoScope.setAlloyBitwidth(alloy_bitwidth);
        }

        // instances scope
        if (line.hasOption(instOptions.getOpt())) {
            String assertionsArguments = "for " + line.getOptionValue(instOptions.getOpt());
            overridingProperties.put(TacoConfigurator.ASSERTION_ARGUMENTS, assertionsArguments);
        }

        // Skolemize
        if (line.hasOption(skolemizeOption.getOpt())) {
            overridingProperties.put(TacoConfigurator.SKOLEMIZE_INSTANCE_INVARIANT, false);
            overridingProperties.put(TacoConfigurator.SKOLEMIZE_INSTANCE_ABSTRACTION, false);
        }

        // Simulation
        if (line.hasOption(simulateOption.getOpt())) {
            overridingProperties.put(TacoConfigurator.INCLUDE_SIMULATION_PROGRAM_DECLARATION, true);
            overridingProperties.put(TacoConfigurator.GENERATE_CHECK, false);
            overridingProperties.put(TacoConfigurator.GENERATE_RUN, false);
        }

        // Modular Reasoning
        if (line.hasOption(modularReasoningOption.getOpt())) {
            overridingProperties.put(TacoConfigurator.MODULAR_REASONING, true);
        }

        // Relevancy Analysis
        if (line.hasOption(relevancyAnalysisOption.getOpt())) {
            overridingProperties.put(TacoConfigurator.RELEVANCY_ANALYSIS, true);
        }

    } catch (ParseException e) {
        System.err.println("Command line parsing failed: " + e.getMessage());
    }

    try {

        System.out.println("****** Starting Taco (version. " + tacoVersion + ") ****** ");
        System.out.println("");

        File file = new File("config/log4j.xml");
        if (file.exists()) {
            DOMConfigurator.configure("config/log4j.xml");
        } else {
            System.err.println("log4j:WARN File config/log4j.xml not found");
        }

        TacoMain main = new TacoMain();

        // BUILD TacoScope 

        //
        main.run(configFileArgument, overridingProperties);

    } catch (IllegalArgumentException e) {
        System.err.println("Error found:");
        System.err.println(e.getMessage());
    } catch (MethodToCheckNotFoundException e) {
        System.err.println("Error found:");
        System.err.println("Method to check was not found. Please verify config file, or add -m option");
    } catch (TacoException e) {
        System.err.println("Error found:");
        System.err.println(e.getMessage());
    }
}

From source file:com.zimbra.doc.soap.changelog.SoapApiChangeLog.java

/**
 * Main/*from   w  w  w.  j  av  a  2s.  c o m*/
 */
public static void main(String[] args) throws Exception {
    CommandLineParser parser = new PosixParser();
    Options options = new Options();

    Option opt;
    opt = new Option("d", ARG_OUTPUT_DIR, true, "Output directory for changelog information");
    opt.setRequired(true);
    options.addOption(opt);
    opt = new Option("t", ARG_TEMPLATES_DIR, true, "Directory containing Freemarker templates");
    opt.setRequired(true);
    options.addOption(opt);
    opt = new Option("b", ARG_APIDESC_BASELINE_JSON, true, "JSON file - description of baseline SOAP API");
    opt.setRequired(true);
    options.addOption(opt);
    opt = new Option("c", ARG_APIDESC_CURRENT_JSON, true, "JSON file - description of current SOAP API");
    opt.setRequired(true);
    options.addOption(opt);

    CommandLine cl = null;
    try {
        cl = parser.parse(options, args, true);
    } catch (ParseException pe) {
        System.err.println("error: " + pe.getMessage());
        System.exit(2);
    }

    String baselineApiDescriptionJson = cl.getOptionValue('b');
    String currentApiDescriptionJson = cl.getOptionValue('c');
    SoapApiChangeLog clog = new SoapApiChangeLog(cl.getOptionValue('d'), cl.getOptionValue('t'));
    clog.setBaselineDesc(SoapApiDescription.deserializeFromJson(new File(baselineApiDescriptionJson)));
    clog.setCurrentDesc(SoapApiDescription.deserializeFromJson(new File(currentApiDescriptionJson)));
    clog.makeChangeLogDataModel();
    clog.writeChangelog();
}

From source file:com.cyberway.issue.io.Arc2Warc.java

/**
 * Command-line interface to Arc2Warc./* ww w.j ava 2 s .  c om*/
 *
 * @param args Command-line arguments.
 * @throws ParseException Failed parse of the command line.
 * @throws IOException
 * @throws java.text.ParseException
 */
public static void main(String[] args) throws ParseException, IOException, java.text.ParseException {
    Options options = new Options();
    options.addOption(new Option("h", "help", false, "Prints this message and exits."));
    options.addOption(new Option("f", "force", false, "Force overwrite of target file."));
    PosixParser parser = new PosixParser();
    CommandLine cmdline = parser.parse(options, args, false);
    List cmdlineArgs = cmdline.getArgList();
    Option[] cmdlineOptions = cmdline.getOptions();
    HelpFormatter formatter = new HelpFormatter();

    // If no args, print help.
    if (cmdlineArgs.size() <= 0) {
        usage(formatter, options, 0);
    }

    // Now look at options passed.
    boolean force = false;
    for (int i = 0; i < cmdlineOptions.length; i++) {
        switch (cmdlineOptions[i].getId()) {
        case 'h':
            usage(formatter, options, 0);
            break;

        case 'f':
            force = true;
            break;

        default:
            throw new RuntimeException("Unexpected option: " + +cmdlineOptions[i].getId());
        }
    }

    // If no args, print help.
    if (cmdlineArgs.size() != 2) {
        usage(formatter, options, 0);
    }
    (new Arc2Warc()).transform(new File(cmdlineArgs.get(0).toString()), new File(cmdlineArgs.get(1).toString()),
            force);
}

From source file:de.uniwue.info2.main.CommandLineInterpreter.java

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

    /*-------------------------------------------------------- */
    /*---------------SETTING TARGET LANGUAGE------------------ */
    /*-------------------------------------------------------- */
    LanguageFactory languageFactory = new LanguageFactory();

    CommandLine line = null;/*from  ww w  .  j  a  va 2s  .  c  o m*/
    CommandLineParser parser = new BasicParser();
    Options options = new Options();
    // options to display in the help page
    Options options_short = new Options();

    // add help option
    Option help_option = new Option(HELP_OPTION_SHORT, HELP_OPTION, false, HELP_DESCRIPTION);
    options.addOption(help_option);
    options_short.addOption(help_option);
    // add extended help option
    Option help2_option = new Option(HELP2_OPTION_SHORT, HELP2_OPTION, false, HELP2_DESCRIPTION);
    options.addOption(help2_option);
    options_short.addOption(help2_option);
    // add optional operations option
    options.addOption(new Option(OPTIONAL_OPTION_SHORT, OPTIONAL_OPTION, false, OPTIONAL_DESCRIPTION));
    options.addOption(new Option(BIG_ENDIAN_OPTION_SHORT, BIG_ENDIAN_OPTION, false, BIG_ENDIAN_DESCRIPTION));
    options.addOption(
            new Option(LITTLE_ENDIAN_OPTION_SHORT, LITTLE_ENDIAN_OPTION, false, LITTLE_ENDIAN_DESCRIPTION));
    // add optional operations config option
    options.addOption(OptionBuilder.withLongOpt(OPTIONAL_FUNCTIONS_CONFIG_OPTION)
            .withArgName(OPTIONAL_FUNCTIONS_CONFIG_ARGUMENT)
            .withDescription(OPTIONAL_FUNCTIONS_CONFIG_DESCRIPTION).hasArg()
            .create(OPTIONAL_FUNCTIONS_CONFIG_SHORT));
    // add dsl option
    Option dsl_option = OptionBuilder.withLongOpt(DSL_OPTION).withArgName(DSL_ARGUMENT)
            .withDescription(DSL_DESCRIPTION).hasArg().isRequired().create(DSL_OPTION_SHORT);
    options.addOption(dsl_option);
    options_short.addOption(dsl_option);
    // add output-folder option
    Option output_option = OptionBuilder.withLongOpt(OUTPUT_OPTION).isRequired().withArgName(OUTPUT_ARGUMENT)
            .withDescription(OUTPUT_DESCRIPTION).hasArg().create(OUTPUT_OPTION_SHORT);
    options.addOption(output_option);
    options_short.addOption(output_option);

    // count possible language-specifications
    short optionCounter = 1;

    // get all possible language-specifications from language-factory and iterate through them
    List<LanguageSpecification> lSpecs = languageFactory.getAvailableLanguageSpecifications_();

    for (LanguageSpecification lSpec : lSpecs) {
        // get all possible unit-specifications for current language and iterate through them
        List<UnitTestLibrarySpecification> uSpecs = languageFactory
                .getAvailableUnitTestLibraries_(lSpec.getOptionName());
        String languageDescriptionAll = LANGUAGE_SPECIFICATION + lSpec.getLanguageName();
        String languageCounter = "s" + INDEX.format(optionCounter++);

        for (UnitTestLibrarySpecification uSpec : uSpecs) {
            // get all possible arithmetic-library-specifications for current language and iterate through
            // them
            List<ArithmeticLibrarySpecification> aSpecs = languageFactory
                    .getAvailableArithmeticLibraries_(lSpec.getOptionName());
            for (ArithmeticLibrarySpecification aSpec : aSpecs) {
                String languageDescription = "Generate unit-test for " + lSpec.getLanguageName() + "\n*["
                        + uSpec.getLibraryName() + " - " + uSpec.getVersion() + "]\n*[" + aSpec.getLibraryName()
                        + " - " + aSpec.getVersion() + "]";

                // if there is more than one option, generate suitable option-names and add them all to
                // commandline options
                if (uSpecs.size() > 1 || aSpecs.size() > 1) {
                    options.addOption(OptionBuilder
                            .withLongOpt(lSpec.getOptionName() + "_" + uSpec.getOptionName() + "_"
                                    + aSpec.getOptionName())
                            .withDescription(languageDescription).hasArg(false)
                            .create("s" + INDEX.format(optionCounter++)));
                } else {
                    // if there is only one option, use language-name as option-name
                    languageDescriptionAll = languageDescription;
                }
            }
            // add specifications to options
            options.addOption(OptionBuilder.withLongOpt(lSpec.getOptionName())
                    .withDescription(languageDescriptionAll).hasArg(false).create(languageCounter));
        }
    }

    /*-------------------------------------------------------- */
    /*-------------------PARSE USER INPUT--------------------- */
    /*-------------------------------------------------------- */
    try {
        // manual search for help-arguments
        for (String arg : args) {
            arg = arg.trim().replace("-", "");
            if (arg.equals(HELP_OPTION_SHORT) || arg.equals(HELP_OPTION)) {
                printHelp(options_short);
                return;
            }
            if (arg.equals(HELP2_OPTION_SHORT) || arg.equals(HELP2_OPTION)) {
                printExtendedHelp(options);
                return;
            }
        }

        // parse arguments   
        line = parser.parse(options, args);

        File dsl_file = null;
        File output_folder = null;
        File optional_config = null;
        Properties optional_operations = null;
        Boolean optional = false;
        Boolean little_endian = null;
        ArrayList<String> optional_exceptions = new ArrayList<String>();

        // if help-option found print help
        if (line.hasOption(HELP2_OPTION_SHORT) || args.length == 0) {
            printExtendedHelp(options);
            return;
        }

        // if help-option found print help
        if (line.hasOption(HELP_OPTION_SHORT) || args.length == 0) {
            System.out.println("\n");
            printHelp(options_short);
            return;
        }

        if (line.hasOption(OPTIONAL_OPTION_SHORT)) {
            optional = true;
        }

        if (line.hasOption(LITTLE_ENDIAN_OPTION)) {
            little_endian = true;
        }

        if (line.hasOption(BIG_ENDIAN_OPTION)) {
            little_endian = false;
        }

        // if dsl-option found, check if file exists and is readable
        // print help if error occurs
        if (line.hasOption(DSL_OPTION_SHORT)) {
            dsl_file = new File(line.getOptionValue(DSL_OPTION_SHORT));
            if (!dsl_file.exists()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - DSL-file doesn't exist:\n" + dsl_file
                        + "\n" + SEPERATOR + "\n");
                printHelp(options_short);
                return;
            } else if (dsl_file.isDirectory()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - DSL-file is a directory:\n" + dsl_file
                        + "\n" + SEPERATOR + "\n");
                printHelp(options_short);
                return;
            } else if (!dsl_file.canRead()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - Need read-permission for DSL-file:\n"
                        + dsl_file + "\n" + SEPERATOR + "\n");
                printHelp(options_short);
                return;
            }
        }

        // if output-option found, check if folder exists and if write-permission was granted
        // print help if error occurs
        if (line.hasOption(OUTPUT_OPTION_SHORT)) {
            output_folder = new File(line.getOptionValue(OUTPUT_OPTION_SHORT));
            if (!output_folder.exists()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - Output-folder doesn't exist:\n"
                        + output_folder + "\n" + SEPERATOR + "\n");
                printHelp(options_short);
                return;
            } else if (!output_folder.isDirectory()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - Output-folder is not a directory:\n"
                        + output_folder + "\n" + SEPERATOR + "\n");
                printHelp(options_short);
                return;
            } else if (!output_folder.canWrite() || !output_folder.canRead()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - Missing permissions for output-folder:\n"
                        + output_folder + "\n" + SEPERATOR + "\n");
                printHelp(options_short);
                return;
            }
        }

        if (line.hasOption(OPTIONAL_FUNCTIONS_CONFIG_SHORT)) {
            optional_config = new File(line.getOptionValue(OPTIONAL_FUNCTIONS_CONFIG_OPTION));
            if (!dsl_file.exists()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - config-file doesn't exist:\n" + dsl_file
                        + "\n" + SEPERATOR + "\n");
                printExtendedHelp(options);
                return;
            } else if (dsl_file.isDirectory()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - config-file is a directory:\n" + dsl_file
                        + "\n" + SEPERATOR + "\n");
                printExtendedHelp(options);
                return;
            } else if (!dsl_file.canRead()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - Need read-permission for config-file:\n"
                        + dsl_file + "\n" + SEPERATOR + "\n");
                printExtendedHelp(options);
                return;
            }
        }

        if (optional_config != null) {
            optional_operations = new Properties();
            BufferedInputStream stream = new BufferedInputStream(new FileInputStream(optional_config));
            optional_operations.load(stream);
            stream.close();
            String optional_prop = optional_operations.getProperty("GENERATE_OPTIONAL");
            if (optional_prop != null) {
                if (optional_prop.trim().toLowerCase().equals("true")) {
                    optional = true;
                } else if (optional_prop.trim().toLowerCase().equals("false")) {
                    optional = false;
                } else if (!optional_prop.trim().isEmpty()) {
                    System.err.println("\n" + SEPERATOR + "\n"
                            + "ERROR - Syntax incorrect in config-file:\nUse \"true\" or \"false\" for \"GENERATE_OPTIONAL\"\n"
                            + SEPERATOR + "\n");
                    printExtendedHelp(options);
                    return;
                }
            }
            String exceptions = optional_operations.getProperty("EXCLUSIONS");
            if (exceptions != null) {
                for (String exc : optional_operations.getProperty("EXCLUSIONS").split(";")) {
                    optional_exceptions.add(exc.trim());
                }
            }
        }

        /*-------------------------------------------------------- */
        /*-------------------START GENERATING--------------------- */
        /*-------------------------------------------------------- */

        // instantiate generator for unit-tests
        TestcaseGenerator mainGenerator = new TestcaseGenerator(dsl_file, output_folder);

        boolean overrideDefaultSpecs = false;

        // check if user input contains a language-specifications
        // if user specified language, set overrideDefaultSpecs to true, so that only given specifications
        // are used
        for (int i = 1; i <= optionCounter; i++) {
            String opt = "s" + INDEX.format(i);
            if (line.hasOption(opt)) {
                LanguageSpecification targetSpecification = languageFactory
                        .getLanguageSpecification(options.getOption(opt).getLongOpt());
                String output = (GENERATING_DIALOG + targetSpecification.getLanguageName());

                // finally generate unit-test for current language-specification
                boolean successful = mainGenerator.generateUnitTest(targetSpecification, optional,
                        optional_exceptions, little_endian);

                if (successful) {
                    System.out.println(output + "\n--> Successfully generated.");
                } else {
                    System.err.println(output + "\n--> ERROR - see logfile");
                }
                overrideDefaultSpecs = true;
            }
        }

        // skip, if user already defined one language-specification
        // if user did not define language-specification, generate unit-tests for all
        // possible language-specifications (default)
        if (!overrideDefaultSpecs) {
            for (int i = 0; i < lSpecs.size(); i++) {
                LanguageSpecification specification = languageFactory
                        .getLanguageSpecification(lSpecs.get(i).getOptionName());

                String output = INDEX.format(i + 1) + " - " + GENERATING_DIALOG
                        + specification.getLanguageName();

                // finally generate unit-test for current language-specification
                boolean successful = mainGenerator.generateUnitTest(specification, optional,
                        optional_exceptions, little_endian);

                if (successful) {
                    System.out.println(output + "\n--> Successfully generated.");
                } else {
                    System.err.println(output + "\n--> ERROR - see logfile");
                }
            }
        }

    } catch (ParseException | IOException p) {
        System.err.println("\n" + SEPERATOR + "\n" + "ERROR - WRONG ARGUMENTS:\n" + p.getMessage() + "\n"
                + SEPERATOR + "\n");
        printHelp(options_short);
        System.out.println("\n");
    }
}

From source file:tuit.java

@SuppressWarnings("ConstantConditions")
public static void main(String[] args) {
    System.out.println(licence);//from ww  w.j a v  a2s.  c  om
    //Declare variables
    File inputFile;
    File outputFile;
    File tmpDir;
    File blastnExecutable;
    File properties;
    File blastOutputFile = null;
    //
    TUITPropertiesLoader tuitPropertiesLoader;
    TUITProperties tuitProperties;
    //
    String[] parameters = null;
    //
    Connection connection = null;
    MySQL_Connector mySQL_connector;
    //
    Map<Ranks, TUITCutoffSet> cutoffMap;
    //
    BLASTIdentifier blastIdentifier = null;
    //
    RamDb ramDb = null;

    CommandLineParser parser = new GnuParser();
    Options options = new Options();

    options.addOption(tuit.IN, "input<file>", true, "Input file (currently fasta-formatted only)");
    options.addOption(tuit.OUT, "output<file>", true, "Output file (in " + tuit.TUIT_EXT + " format)");
    options.addOption(tuit.P, "prop<file>", true, "Properties file (XML formatted)");
    options.addOption(tuit.V, "verbose", false, "Enable verbose output");
    options.addOption(tuit.B, "blast_output<file>", true, "Perform on a pre-BLASTed output");
    options.addOption(tuit.DEPLOY, "deploy", false, "Deploy the taxonomic databases");
    options.addOption(tuit.UPDATE, "update", false, "Update the taxonomic databases");
    options.addOption(tuit.USE_DB, "usedb", false, "Use RDBMS instead of RAM-based taxonomy");

    Option option = new Option(tuit.REDUCE, "reduce", true,
            "Pack identical (100% similar sequences) records in the given sample file");
    option.setArgs(Option.UNLIMITED_VALUES);
    options.addOption(option);
    option = new Option(tuit.COMBINE, "combine", true,
            "Combine a set of given reduction files into an HMP Tree-compatible taxonomy");
    option.setArgs(Option.UNLIMITED_VALUES);
    options.addOption(option);
    options.addOption(tuit.NORMALIZE, "normalize", false,
            "If used in combination with -combine ensures that the values are normalized by the root value");

    HelpFormatter formatter = new HelpFormatter();

    try {

        //Get TUIT directory
        final File tuitDir = new File(
                new File(tuit.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath())
                        .getParent());
        final File ramDbFile = new File(tuitDir, tuit.RAM_DB);

        //Setup logger
        Log.getInstance().setLogName("tuit.log");

        //Read command line
        final CommandLine commandLine = parser.parse(options, args, true);

        //Check if the REDUCE option is on
        if (commandLine.hasOption(tuit.REDUCE)) {

            final String[] fileList = commandLine.getOptionValues(tuit.REDUCE);
            for (String s : fileList) {
                final Path path = Paths.get(s);
                Log.getInstance().log(Level.INFO, "Processing " + path.toString() + "...");
                final NucleotideFastaSequenceReductor nucleotideFastaSequenceReductor = NucleotideFastaSequenceReductor
                        .fromPath(path);
                ReductorFileOperator.save(nucleotideFastaSequenceReductor,
                        path.resolveSibling(path.getFileName().toString() + ".rdc"));
            }

            Log.getInstance().log(Level.FINE, "Task done, exiting...");
            return;
        }

        //Check if COMBINE is on
        if (commandLine.hasOption(tuit.COMBINE)) {
            final boolean normalize = commandLine.hasOption(tuit.NORMALIZE);
            final String[] fileList = commandLine.getOptionValues(tuit.COMBINE);
            //TODO: implement a test for format here

            final List<TreeFormatter.TreeFormatterFormat.HMPTreesOutput> hmpTreesOutputs = new ArrayList<>();
            final TreeFormatter treeFormatter = TreeFormatter
                    .newInstance(new TreeFormatter.TuitLineTreeFormatterFormat());
            for (String s : fileList) {
                final Path path = Paths.get(s);
                Log.getInstance().log(Level.INFO, "Merging " + path.toString() + "...");
                treeFormatter.loadFromPath(path);
                final TreeFormatter.TreeFormatterFormat.HMPTreesOutput output = TreeFormatter.TreeFormatterFormat.HMPTreesOutput
                        .newInstance(treeFormatter.toHMPTree(normalize), s.substring(0, s.indexOf(".")));
                hmpTreesOutputs.add(output);
                treeFormatter.erase();
            }
            final Path destination;
            if (commandLine.hasOption(OUT)) {
                destination = Paths.get(commandLine.getOptionValue(tuit.OUT));
            } else {
                destination = Paths.get("merge.tcf");
            }
            CombinatorFileOperator.save(hmpTreesOutputs, treeFormatter, destination);
            Log.getInstance().log(Level.FINE, "Task done, exiting...");
            return;
        }

        if (!commandLine.hasOption(tuit.P)) {
            throw new ParseException("No properties file option found, exiting.");
        } else {
            properties = new File(commandLine.getOptionValue(tuit.P));
        }

        //Load properties
        tuitPropertiesLoader = TUITPropertiesLoader.newInstanceFromFile(properties);
        tuitProperties = tuitPropertiesLoader.getTuitProperties();

        //Create tmp directory and blastn executable
        tmpDir = new File(tuitProperties.getTMPDir().getPath());
        blastnExecutable = new File(tuitProperties.getBLASTNPath().getPath());

        //Check for deploy
        if (commandLine.hasOption(tuit.DEPLOY)) {
            if (commandLine.hasOption(tuit.USE_DB)) {
                NCBITablesDeployer.fastDeployNCBIDatabasesFromNCBI(connection, tmpDir);
            } else {
                NCBITablesDeployer.fastDeployNCBIRamDatabaseFromNCBI(tmpDir, ramDbFile);
            }

            Log.getInstance().log(Level.FINE, "Task done, exiting...");
            return;
        }
        //Check for update
        if (commandLine.hasOption(tuit.UPDATE)) {
            if (commandLine.hasOption(tuit.USE_DB)) {
                NCBITablesDeployer.updateDatabasesFromNCBI(connection, tmpDir);
            } else {
                //No need to specify a different way to update the database other than just deploy in case of the RAM database
                NCBITablesDeployer.fastDeployNCBIRamDatabaseFromNCBI(tmpDir, ramDbFile);
            }
            Log.getInstance().log(Level.FINE, "Task done, exiting...");
            return;
        }

        //Connect to the database
        if (commandLine.hasOption(tuit.USE_DB)) {
            mySQL_connector = MySQL_Connector.newDefaultInstance(
                    "jdbc:mysql://" + tuitProperties.getDBConnection().getUrl().trim() + "/",
                    tuitProperties.getDBConnection().getLogin().trim(),
                    tuitProperties.getDBConnection().getPassword().trim());
            mySQL_connector.connectToDatabase();
            connection = mySQL_connector.getConnection();
        } else {
            //Probe for ram database

            if (ramDbFile.exists() && ramDbFile.canRead()) {
                Log.getInstance().log(Level.INFO, "Loading RAM taxonomic map...");
                try {
                    ramDb = RamDb.loadSelfFromFile(ramDbFile);
                } catch (IOException ie) {
                    if (ie instanceof java.io.InvalidClassException)
                        throw new IOException("The RAM-based taxonomic database needs to be updated.");
                }

            } else {
                Log.getInstance().log(Level.SEVERE,
                        "The RAM database either has not been deployed, or is not accessible."
                                + "Please use the --deploy option and check permissions on the TUIT directory. "
                                + "If you were looking to use the RDBMS as a taxonomic reference, plese use the -usedb option.");
                return;
            }
        }

        if (commandLine.hasOption(tuit.B)) {
            blastOutputFile = new File(commandLine.getOptionValue(tuit.B));
            if (!blastOutputFile.exists() || !blastOutputFile.canRead()) {
                throw new Exception("BLAST output file either does not exist, or is not readable.");
            } else if (blastOutputFile.isDirectory()) {
                throw new Exception("BLAST output file points to a directory.");
            }
        }
        //Check vital parameters
        if (!commandLine.hasOption(tuit.IN)) {
            throw new ParseException("No input file option found, exiting.");
        } else {
            inputFile = new File(commandLine.getOptionValue(tuit.IN));
            Log.getInstance().setLogName(inputFile.getName().split("\\.")[0] + ".tuit.log");
        }
        //Correct the output file option if needed
        if (!commandLine.hasOption(tuit.OUT)) {
            outputFile = new File((inputFile.getPath()).split("\\.")[0] + tuit.TUIT_EXT);
        } else {
            outputFile = new File(commandLine.getOptionValue(tuit.OUT));
        }

        //Adjust the output level
        if (commandLine.hasOption(tuit.V)) {
            Log.getInstance().setLevel(Level.FINE);
            Log.getInstance().log(Level.INFO, "Using verbose output for the log");
        } else {
            Log.getInstance().setLevel(Level.INFO);
        }
        //Try all files
        if (inputFile != null) {
            if (!inputFile.exists() || !inputFile.canRead()) {
                throw new Exception("Input file either does not exist, or is not readable.");
            } else if (inputFile.isDirectory()) {
                throw new Exception("Input file points to a directory.");
            }
        }

        if (!properties.exists() || !properties.canRead()) {
            throw new Exception("Properties file either does not exist, or is not readable.");
        } else if (properties.isDirectory()) {
            throw new Exception("Properties file points to a directory.");
        }

        //Create blast parameters
        final StringBuilder stringBuilder = new StringBuilder();
        for (Database database : tuitProperties.getBLASTNParameters().getDatabase()) {
            stringBuilder.append(database.getUse());
            stringBuilder.append(" ");//Gonna insert an extra space for the last database
        }
        String remote;
        String entrez_query;
        if (tuitProperties.getBLASTNParameters().getRemote().getDelegate().equals("yes")) {
            remote = "-remote";
            entrez_query = "-entrez_query";
            parameters = new String[] { "-db", stringBuilder.toString(), remote, entrez_query,
                    tuitProperties.getBLASTNParameters().getEntrezQuery().getValue(), "-evalue",
                    tuitProperties.getBLASTNParameters().getExpect().getValue() };
        } else {
            if (!commandLine.hasOption(tuit.B)) {
                if (tuitProperties.getBLASTNParameters().getEntrezQuery().getValue().toUpperCase()
                        .startsWith("NOT")
                        || tuitProperties.getBLASTNParameters().getEntrezQuery().getValue().toUpperCase()
                                .startsWith("ALL")) {
                    parameters = new String[] { "-db", stringBuilder.toString(), "-evalue",
                            tuitProperties.getBLASTNParameters().getExpect().getValue(), "-negative_gilist",
                            TUITFileOperatorHelper.restrictToEntrez(tmpDir,
                                    tuitProperties.getBLASTNParameters().getEntrezQuery().getValue()
                                            .toUpperCase().replace("NOT", "OR"))
                                    .getAbsolutePath(),
                            "-num_threads", tuitProperties.getBLASTNParameters().getNumThreads().getValue() };
                } else if (tuitProperties.getBLASTNParameters().getEntrezQuery().getValue().toUpperCase()
                        .equals("")) {
                    parameters = new String[] { "-db", stringBuilder.toString(), "-evalue",
                            tuitProperties.getBLASTNParameters().getExpect().getValue(), "-num_threads",
                            tuitProperties.getBLASTNParameters().getNumThreads().getValue() };
                } else {
                    parameters = new String[] { "-db", stringBuilder.toString(), "-evalue",
                            tuitProperties.getBLASTNParameters().getExpect().getValue(),
                            /*"-gilist", TUITFileOperatorHelper.restrictToEntrez(
                            tmpDir, tuitProperties.getBLASTNParameters().getEntrezQuery().getValue()).getAbsolutePath(),*/ //TODO remove comment!!!!!
                            "-num_threads", tuitProperties.getBLASTNParameters().getNumThreads().getValue() };
                }
            }
        }
        //Prepare a cutoff Map
        if (tuitProperties.getSpecificationParameters() != null
                && tuitProperties.getSpecificationParameters().size() > 0) {
            cutoffMap = new HashMap<Ranks, TUITCutoffSet>(tuitProperties.getSpecificationParameters().size());
            for (SpecificationParameters specificationParameters : tuitProperties
                    .getSpecificationParameters()) {
                cutoffMap.put(Ranks.valueOf(specificationParameters.getCutoffSet().getRank()),
                        TUITCutoffSet.newDefaultInstance(
                                Double.parseDouble(
                                        specificationParameters.getCutoffSet().getPIdentCutoff().getValue()),
                                Double.parseDouble(specificationParameters.getCutoffSet()
                                        .getQueryCoverageCutoff().getValue()),
                                Double.parseDouble(
                                        specificationParameters.getCutoffSet().getAlpha().getValue())));
            }
        } else {
            cutoffMap = new HashMap<Ranks, TUITCutoffSet>();
        }
        final TUITFileOperatorHelper.OutputFormat format;
        if (tuitProperties.getBLASTNParameters().getOutputFormat().getFormat().equals("rdp")) {
            format = TUITFileOperatorHelper.OutputFormat.RDP_FIXRANK;
        } else {
            format = TUITFileOperatorHelper.OutputFormat.TUIT;
        }

        try (TUITFileOperator<NucleotideFasta> nucleotideFastaTUITFileOperator = NucleotideFastaTUITFileOperator
                .newInstance(format, cutoffMap);) {
            nucleotideFastaTUITFileOperator.setInputFile(inputFile);
            nucleotideFastaTUITFileOperator.setOutputFile(outputFile);
            final String cleanupString = tuitProperties.getBLASTNParameters().getKeepBLASTOuts().getKeep();
            final boolean cleanup;
            if (cleanupString.equals("no")) {
                Log.getInstance().log(Level.INFO, "Temporary BLAST files will be deleted.");
                cleanup = true;
            } else {
                Log.getInstance().log(Level.INFO, "Temporary BLAST files will be kept.");
                cleanup = false;
            }
            //Create blast identifier
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            if (commandLine.hasOption(tuit.USE_DB)) {

                if (blastOutputFile == null) {
                    blastIdentifier = TUITBLASTIdentifierDB.newInstanceFromFileOperator(tmpDir,
                            blastnExecutable, parameters, nucleotideFastaTUITFileOperator, connection,
                            cutoffMap,
                            Integer.parseInt(
                                    tuitProperties.getBLASTNParameters().getMaxFilesInBatch().getValue()),
                            cleanup);

                } else {
                    try {
                        blastIdentifier = TUITBLASTIdentifierDB.newInstanceFromBLASTOutput(
                                nucleotideFastaTUITFileOperator, connection, cutoffMap, blastOutputFile,
                                Integer.parseInt(
                                        tuitProperties.getBLASTNParameters().getMaxFilesInBatch().getValue()),
                                cleanup);

                    } catch (JAXBException e) {
                        Log.getInstance().log(Level.SEVERE, "Error reading " + blastOutputFile.getName()
                                + ", please check input. The file must be XML formatted.");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            } else {
                if (blastOutputFile == null) {
                    blastIdentifier = TUITBLASTIdentifierRAM.newInstanceFromFileOperator(tmpDir,
                            blastnExecutable, parameters, nucleotideFastaTUITFileOperator, cutoffMap,
                            Integer.parseInt(
                                    tuitProperties.getBLASTNParameters().getMaxFilesInBatch().getValue()),
                            cleanup, ramDb);

                } else {
                    try {
                        blastIdentifier = TUITBLASTIdentifierRAM.newInstanceFromBLASTOutput(
                                nucleotideFastaTUITFileOperator, cutoffMap, blastOutputFile,
                                Integer.parseInt(
                                        tuitProperties.getBLASTNParameters().getMaxFilesInBatch().getValue()),
                                cleanup, ramDb);

                    } catch (JAXBException e) {
                        Log.getInstance().log(Level.SEVERE, "Error reading " + blastOutputFile.getName()
                                + ", please check input. The file must be XML formatted.");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            Future<?> runnableFuture = executorService.submit(blastIdentifier);
            runnableFuture.get();
            executorService.shutdown();
        }
    } catch (ParseException pe) {
        Log.getInstance().log(Level.SEVERE, (pe.getMessage()));
        formatter.printHelp("tuit", options);
    } catch (SAXException saxe) {
        Log.getInstance().log(Level.SEVERE, saxe.getMessage());
    } catch (FileNotFoundException fnfe) {
        Log.getInstance().log(Level.SEVERE, fnfe.getMessage());
    } catch (TUITPropertyBadFormatException tpbfe) {
        Log.getInstance().log(Level.SEVERE, tpbfe.getMessage());
    } catch (ClassCastException cce) {
        Log.getInstance().log(Level.SEVERE, cce.getMessage());
    } catch (JAXBException jaxbee) {
        Log.getInstance().log(Level.SEVERE,
                "The properties file is not well formatted. Please ensure that the XML is consistent with the io.properties.dtd schema.");
    } catch (ClassNotFoundException cnfe) {
        //Probably won't happen unless the library deleted from the .jar
        Log.getInstance().log(Level.SEVERE, cnfe.getMessage());
        //cnfe.printStackTrace();
    } catch (SQLException sqle) {
        Log.getInstance().log(Level.SEVERE,
                "A database communication error occurred with the following message:\n" + sqle.getMessage());
        //sqle.printStackTrace();
        if (sqle.getMessage().contains("Access denied for user")) {
            Log.getInstance().log(Level.SEVERE, "Please use standard database login: "
                    + NCBITablesDeployer.login + " and password: " + NCBITablesDeployer.password);
        }
    } catch (Exception e) {
        Log.getInstance().log(Level.SEVERE, e.getMessage());
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException sqle) {
                Log.getInstance().log(Level.SEVERE, "Problem closing the database connection: " + sqle);
            }
        }
        Log.getInstance().log(Level.FINE, "Task done, exiting...");
    }
}

From source file:edu.ksu.cis.indus.staticanalyses.dependency.DependencyXMLizerCLI.java

/**
 * This is the entry point via command-line.
 * //w  w w .  j  a v  a 2 s.co m
 * @param args is the command line arguments.
 * @throws RuntimeException when an Throwable exception beyond our control occurs.
 * @pre args != null
 */
public static void main(final String[] args) {
    final Options _options = new Options();
    Option _option = new Option("o", "output", true,
            "Directory into which xml files will be written into.  Defaults to current directory if omitted");
    _option.setArgs(1);
    _option.setArgName("output-directory");
    _options.addOption(_option);
    _option = new Option("j", "jimple", false, "Dump xmlized jimple.");
    _options.addOption(_option);

    final DivergenceDA _fidda = DivergenceDA.getDivergenceDA(IDependencyAnalysis.Direction.FORWARD_DIRECTION);
    _fidda.setConsiderCallSites(true);

    final DivergenceDA _bidda = DivergenceDA.getDivergenceDA(IDependencyAnalysis.Direction.BACKWARD_DIRECTION);
    _bidda.setConsiderCallSites(true);

    final NonTerminationSensitiveEntryControlDA _ncda = new NonTerminationSensitiveEntryControlDA();
    final Object[][] _dasOptions = {
            { "ibdda1", "Identifier based data dependence (Soot)", new IdentifierBasedDataDA() },
            { "ibdda2", "Identifier based data dependence (Indus)", new IdentifierBasedDataDAv2() },
            { "ibdda3", "Identifier based data dependence (Indus Optimized)", new IdentifierBasedDataDAv3() },
            { "rbdda", "Reference based data dependence", new ReferenceBasedDataDA() },
            { "nscda", "Non-termination sensitive Entry control dependence", _ncda },
            { "nicda", "Non-termination insensitive Entry control dependence",
                    new NonTerminationInsensitiveEntryControlDA(), },
            { "xcda", "Exit control dependence", new ExitControlDA() },
            { "sda", "Synchronization dependence", new SynchronizationDA() },
            { "frda1", "Forward Ready dependence v1", ReadyDAv1.getForwardReadyDA() },
            { "brda1", "Backward Ready dependence v1", ReadyDAv1.getBackwardReadyDA() },
            { "frda2", "Forward Ready dependence v2", ReadyDAv2.getForwardReadyDA() },
            { "brda2", "Backward Ready dependence v2", ReadyDAv2.getBackwardReadyDA() },
            { "frda3", "Forward Ready dependence v3", ReadyDAv3.getForwardReadyDA() },
            { "brda3", "Backward Ready dependence v3", ReadyDAv3.getBackwardReadyDA() },
            { "ida1", "Interference dependence v1", new InterferenceDAv1() },
            { "ida2", "Interference dependence v2", new InterferenceDAv2() },
            { "ida3", "Interference dependence v3", new InterferenceDAv3() },
            { "fdda", "Forward Intraprocedural Divergence dependence",
                    DivergenceDA.getDivergenceDA(IDependencyAnalysis.Direction.FORWARD_DIRECTION), },
            { "bdda", "Backward Intraprocedural Divergence dependence",
                    DivergenceDA.getDivergenceDA(IDependencyAnalysis.Direction.BACKWARD_DIRECTION), },
            { "fidda", "Forward Intra+Interprocedural Divergence dependence", _fidda },
            { "bidda", "Backward Intra+Interprocedural Divergence dependence", _bidda },
            { "fpidda", "Forward Interprocedural Divergence dependence",
                    InterProceduralDivergenceDA
                            .getDivergenceDA(IDependencyAnalysis.Direction.FORWARD_DIRECTION), },
            { "bpidda", "Backward Interprocedural Divergence dependence", InterProceduralDivergenceDA
                    .getDivergenceDA(IDependencyAnalysis.Direction.BACKWARD_DIRECTION), }, };
    _option = new Option("h", "help", false, "Display message.");
    _option.setOptionalArg(false);
    _options.addOption(_option);
    _option = new Option("p", "soot-classpath", false, "Prepend this to soot class path.");
    _option.setArgs(1);
    _option.setArgName("classpath");
    _option.setOptionalArg(false);
    _options.addOption(_option);
    _option = new Option("aliasedusedefv1", false, "Use version 1 of aliased use-def info.");
    _options.addOption(_option);
    _option = new Option("safelockanalysis", false, "Use safe-lock-analysis for ready dependence.");
    _options.addOption(_option);
    _option = new Option("ofaforinterference", false, "Use OFA for interference dependence.");
    _options.addOption(_option);
    _option = new Option("ofaforready", false, "Use OFA for ready dependence.");
    _options.addOption(_option);
    _option = new Option("exceptionalexits", false, "Consider exceptional exits for control dependence.");
    _options.addOption(_option);
    _option = new Option("commonuncheckedexceptions", false, "Consider common unchecked exceptions.");
    _options.addOption(_option);
    _option = new Option("S", "scope", true, "The scope that should be analyzed.");
    _option.setArgs(1);
    _option.setArgName("scope");
    _option.setRequired(false);
    _options.addOption(_option);

    for (int _i = 0; _i < _dasOptions.length; _i++) {
        final String _shortOption = _dasOptions[_i][0].toString();
        final String _description = _dasOptions[_i][1].toString();
        _option = new Option(_shortOption, false, _description);
        _options.addOption(_option);
    }

    final CommandLineParser _parser = new GnuParser();

    try {
        final CommandLine _cl = _parser.parse(_options, args);

        if (_cl.hasOption("h")) {
            printUsage(_options);
            System.exit(1);
        }

        final DependencyXMLizerCLI _xmlizerCLI = new DependencyXMLizerCLI();
        String _outputDir = _cl.getOptionValue('o');

        if (_outputDir == null) {
            if (LOGGER.isWarnEnabled()) {
                LOGGER.warn("Defaulting to current directory for output.");
            }
            _outputDir = ".";
        }

        _xmlizerCLI.xmlizer.setXmlOutputDir(_outputDir);

        if (_cl.hasOption('p')) {
            _xmlizerCLI.addToSootClassPath(_cl.getOptionValue('p'));
        }

        if (_cl.hasOption('S')) {
            _xmlizerCLI.setScopeSpecFile(_cl.getOptionValue('S'));
        }

        _xmlizerCLI.dumpJimple = _cl.hasOption('j');
        _xmlizerCLI.useAliasedUseDefv1 = _cl.hasOption("aliasedusedefv1");
        _xmlizerCLI.useSafeLockAnalysis = _cl.hasOption("safelockanalysis");
        _xmlizerCLI.exceptionalExits = _cl.hasOption("exceptionalexits");
        _xmlizerCLI.commonUncheckedException = _cl.hasOption("commonuncheckedexceptions");

        final List<String> _classNames = _cl.getArgList();

        if (_classNames.isEmpty()) {
            throw new MissingArgumentException("Please specify atleast one class.");
        }
        _xmlizerCLI.setClassNames(_classNames);

        final int _exitControlDAIndex = 6;

        if (_cl.hasOption(_dasOptions[_exitControlDAIndex][0].toString())) {
            _xmlizerCLI.das.add(_ncda);

            for (final Iterator<DependenceSort> _i = _ncda.getIds().iterator(); _i.hasNext();) {
                final DependenceSort _id = _i.next();
                MapUtils.putIntoCollectionInMapUsingFactory(_xmlizerCLI.info, _id, _ncda,
                        SetUtils.getFactory());
            }
        }

        if (!parseForDependenceOptions(_dasOptions, _cl, _xmlizerCLI)) {
            throw new ParseException("Atleast one dependence analysis must be requested.");
        }

        _xmlizerCLI.<ITokens>execute();
    } catch (final ParseException _e) {
        LOGGER.error("Error while parsing command line.", _e);
        System.out.println("Error while parsing command line." + _e);
        printUsage(_options);
    } catch (final Throwable _e) {
        LOGGER.error("Beyond our control. May day! May day!", _e);
        throw new RuntimeException(_e);
    }
}

From source file:com.example.dlp.Redact.java

/** Command line application to redact strings, images using the Data Loss Prevention API. */
public static void main(String[] args) throws Exception {
    OptionGroup optionsGroup = new OptionGroup();
    optionsGroup.setRequired(true);// www . ja v  a  2s. co m
    Option stringOption = new Option("s", "string", true, "redact string");
    optionsGroup.addOption(stringOption);

    Option fileOption = new Option("f", "file path", true, "redact input file path");
    optionsGroup.addOption(fileOption);

    Options commandLineOptions = new Options();
    commandLineOptions.addOptionGroup(optionsGroup);

    Option minLikelihoodOption = Option.builder("minLikelihood").hasArg(true).required(false).build();

    commandLineOptions.addOption(minLikelihoodOption);

    Option replaceOption = Option.builder("r").longOpt("replace string").hasArg(true).required(false).build();
    commandLineOptions.addOption(replaceOption);

    Option infoTypesOption = Option.builder("infoTypes").hasArg(true).required(false).build();
    infoTypesOption.setArgs(Option.UNLIMITED_VALUES);
    commandLineOptions.addOption(infoTypesOption);

    Option outputFilePathOption = Option.builder("o").hasArg(true).longOpt("outputFilePath").required(false)
            .build();
    commandLineOptions.addOption(outputFilePathOption);

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

    try {
        cmd = parser.parse(commandLineOptions, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        formatter.printHelp(Redact.class.getName(), commandLineOptions);
        System.exit(1);
        return;
    }

    String replacement = cmd.getOptionValue(replaceOption.getOpt(), "_REDACTED_");

    List<InfoType> infoTypesList = new ArrayList<>();
    String[] infoTypes = cmd.getOptionValues(infoTypesOption.getOpt());
    if (infoTypes != null) {
        for (String infoType : infoTypes) {
            infoTypesList.add(InfoType.newBuilder().setName(infoType).build());
        }
    }
    Likelihood minLikelihood = Likelihood.valueOf(
            cmd.getOptionValue(minLikelihoodOption.getOpt(), Likelihood.LIKELIHOOD_UNSPECIFIED.name()));

    // string inspection
    if (cmd.hasOption("s")) {
        String source = cmd.getOptionValue(stringOption.getOpt());
        redactString(source, replacement, minLikelihood, infoTypesList);
    } else if (cmd.hasOption("f")) {
        String filePath = cmd.getOptionValue(fileOption.getOpt());
        String outputFilePath = cmd.getOptionValue(outputFilePathOption.getOpt());
        redactImage(filePath, minLikelihood, infoTypesList, outputFilePath);
    }
}