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

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

Introduction

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

Prototype

DefaultParser

Source Link

Usage

From source file:ch.ethz.topobench.graph.utility.CmdAssistant.java

/**
 * Parse the options. Fails if it does not adhere to requirements.
 *
 * @param options   Options set for the command line
 * @param args      Input from command line
 * @param allowUnknownOptsAtEnd     Whether to allow unknown commands at end
 *
 * @return  Parsed command line arguments
 *///w  w  w.  ja va 2s.c  o  m
public static CommandLine parseOptions(Options options, String[] args, boolean allowUnknownOptsAtEnd) {

    // Parse the arguments
    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd;

    try {
        cmd = parser.parse(options, args, allowUnknownOptsAtEnd);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        formatter.printHelp("ProduceLP", options);
        throw new RuntimeException("Failed to generated graph due to missing options.");
    }

    return cmd;

}

From source file:edu.usf.cutr.onebusaway.nav.utils.CommandLineUtils.java

public static String getInputFilePath(String args[]) throws Exception {
    Options options = new Options();
    options.addOption("i", true, "Input io path");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);
    return getInputPath(cmd);
}

From source file:com.act.lcms.db.analysis.PathwayProductAnalysis.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());//from   ww  w  .  jav  a2s  .  c  o  m
    }

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

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

    File lcmsDir = new File(cl.getOptionValue(OPTION_DIRECTORY));
    if (!lcmsDir.isDirectory()) {
        System.err.format("File at %s is not a directory\n", lcmsDir.getAbsolutePath());
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        System.exit(1);
    }

    Double fontScale = null;
    if (cl.hasOption("font-scale")) {
        try {
            fontScale = Double.parseDouble(cl.getOptionValue("font-scale"));
        } catch (IllegalArgumentException e) {
            System.err.format("Argument for font-scale must be a floating point number.\n");
            System.exit(1);
        }
    }

    try (DB db = DB.openDBFromCLI(cl)) {
        Set<Integer> takeSamplesFromPlateIds = null;
        if (cl.hasOption(OPTION_FILTER_BY_PLATE_BARCODE)) {
            String[] plateBarcodes = cl.getOptionValues(OPTION_FILTER_BY_PLATE_BARCODE);
            System.out.format("Considering only sample wells in plates: %s\n",
                    StringUtils.join(plateBarcodes, ", "));
            takeSamplesFromPlateIds = new HashSet<>(plateBarcodes.length);
            for (String plateBarcode : plateBarcodes) {
                Plate p = Plate.getPlateByBarcode(db, plateBarcode);
                if (p == null) {
                    System.err.format("WARNING: unable to find plate in DB with barcode %s\n", plateBarcode);
                } else {
                    takeSamplesFromPlateIds.add(p.getId());
                }
            }
            // Allow filtering on barcode even if we couldn't find any in the DB.
        }

        System.out.format("Loading/updating LCMS scan files into DB\n");
        ScanFile.insertOrUpdateScanFilesInDirectory(db, lcmsDir);

        System.out.format("Processing LCMS scans\n");
        Pair<List<LCMSWell>, Set<Integer>> positiveWellsAndPlateIds = Utils.extractWellsAndPlateIds(db,
                cl.getOptionValues(OPTION_STRAINS), cl.getOptionValues(OPTION_CONSTRUCT),
                takeSamplesFromPlateIds, false);
        List<LCMSWell> positiveWells = positiveWellsAndPlateIds.getLeft();
        if (positiveWells.size() == 0) {
            throw new RuntimeException("Found no LCMS wells for specified strains/constructs");
        }
        // Only take negative samples from the plates where we found the positive samples.
        Pair<List<LCMSWell>, Set<Integer>> negativeWellsAndPlateIds = Utils.extractWellsAndPlateIds(db,
                cl.getOptionValues(OPTION_NEGATIVE_STRAINS), cl.getOptionValues(OPTION_NEGATIVE_CONSTRUCTS),
                positiveWellsAndPlateIds.getRight(), true);
        List<LCMSWell> negativeWells = negativeWellsAndPlateIds.getLeft();
        if (negativeWells == null || negativeWells.size() == 0) {
            System.err.format("WARNING: no valid negative samples found in same plates as positive samples\n");
        }

        // Extract the chemicals in the pathway and their product masses, then look up info on those chemicals
        List<Pair<ChemicalAssociatedWithPathway, Double>> productMasses = Utils
                .extractMassesForChemicalsAssociatedWithConstruct(db, cl.getOptionValue(OPTION_CONSTRUCT));
        List<Pair<String, Double>> searchMZs = new ArrayList<>(productMasses.size());
        List<ChemicalAssociatedWithPathway> pathwayChems = new ArrayList<>(productMasses.size());
        for (Pair<ChemicalAssociatedWithPathway, Double> productMass : productMasses) {
            String chemName = productMass.getLeft().getChemical();
            searchMZs.add(Pair.of(chemName, productMass.getRight()));
            pathwayChems.add(productMass.getLeft());
        }
        System.out.format("Searching for intermediate/side-reaction products:\n");
        for (Pair<String, Double> searchMZ : searchMZs) {
            System.out.format("  %s: %.3f\n", searchMZ.getLeft(), searchMZ.getRight());
        }

        // Look up the standard by name.
        List<StandardWell> standardWells = new ArrayList<>();
        if (cl.hasOption(OPTION_STANDARD_WELLS)) {
            Plate standardPlate = Plate.getPlateByBarcode(db, cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE));
            Map<Integer, StandardWell> pathwayIdToStandardWell = extractStandardWellsFromOptionsList(db,
                    pathwayChems, cl.getOptionValues(OPTION_STANDARD_WELLS), standardPlate);
            for (ChemicalAssociatedWithPathway c : pathwayChems) { // TODO: we can avoid this loop.
                StandardWell well = pathwayIdToStandardWell.get(c.getId());
                if (well != null) {
                    standardWells.add(well);
                }
            }
        } else {
            for (ChemicalAssociatedWithPathway c : pathwayChems) {
                String standardName = c.getChemical();
                System.out.format("Searching for well containing standard %s\n", standardName);
                List<StandardWell> wells = StandardIonAnalysis.getStandardWellsForChemical(db, c.getChemical());
                if (wells != null) {
                    standardWells.addAll(wells);
                }
            }
        }

        boolean useFineGrainedMZ = cl.hasOption("fine-grained-mz");
        boolean useSNR = cl.hasOption(OPTION_USE_SNR);

        /* Process the standard, positive, and negative wells, producing ScanData containers that will allow them to be
         * iterated over for graph writing. We do not need to specify granular includeIons and excludeIons since
         * this would not take advantage of our caching strategy which uses a list of metlin ions as an index. */
        HashMap<Integer, Plate> plateCache = new HashMap<>();
        Pair<List<ScanData<StandardWell>>, Double> allStandardScans = AnalysisHelper.processScans(db, lcmsDir,
                searchMZs, ScanData.KIND.STANDARD, plateCache, standardWells, useFineGrainedMZ, EMPTY_SET,
                EMPTY_SET, useSNR);
        Pair<List<ScanData<LCMSWell>>, Double> allPositiveScans = AnalysisHelper.processScans(db, lcmsDir,
                searchMZs, ScanData.KIND.POS_SAMPLE, plateCache, positiveWells, useFineGrainedMZ, EMPTY_SET,
                EMPTY_SET, useSNR);
        Pair<List<ScanData<LCMSWell>>, Double> allNegativeScans = AnalysisHelper.processScans(db, lcmsDir,
                searchMZs, ScanData.KIND.NEG_CONTROL, plateCache, negativeWells, useFineGrainedMZ, EMPTY_SET,
                EMPTY_SET, useSNR);

        String fmt = "pdf";
        String outImg = cl.getOptionValue(OPTION_OUTPUT_PREFIX) + "." + fmt;
        String outData = cl.getOptionValue(OPTION_OUTPUT_PREFIX) + ".data";
        String outAnalysis = cl.getOptionValue(OPTION_OUTPUT_PREFIX) + ".tsv";

        System.err.format("Writing combined scan data to %s and graphs to %s\n", outData, outImg);
        String plottingDirectory = cl.getOptionValue(OPTION_PLOTTING_DIR);

        List<ScanData<LCMSWell>> posNegWells = new ArrayList<>();
        posNegWells.addAll(allPositiveScans.getLeft());
        posNegWells.addAll(allNegativeScans.getLeft());

        Map<Integer, String> searchIons;
        if (cl.hasOption(OPTION_PATHWAY_SEARCH_IONS)) {
            searchIons = extractPathwayStepIons(pathwayChems, cl.getOptionValues(OPTION_PATHWAY_SEARCH_IONS),
                    cl.getOptionValue(OPTION_SEARCH_ION, "M+H"));
            /* This is pretty lazy, but works with the existing API.  Extract all selected ions for all search masses when
             * performing the scan, then filter down to the desired ions for the plot at the end.
             * TODO: specify the masses and scans per sample rather than batching everything together.  It might be slower,
             * but it'll be clearer to read. */
        } else {
            // We need to make sure that the standard metlin ion we choose is consistent with the ion modes of
            // the given positive, negative and standard scan files. For example, we should not pick a negative
            // metlin ion if all our available positive control scan files are in the positive ion mode.
            Map<Integer, Pair<Boolean, Boolean>> ionModes = new HashMap<>();
            for (ChemicalAssociatedWithPathway chemical : pathwayChems) {
                boolean isPositiveScanPresent = false;
                boolean isNegativeScanPresent = false;

                for (ScanData<StandardWell> scan : allStandardScans.getLeft()) {
                    if (chemical.getChemical().equals(scan.getWell().getChemical())
                            && chemical.getChemical().equals(scan.getTargetChemicalName())) {
                        if (MS1.IonMode.valueOf(
                                scan.getScanFile().getMode().toString().toUpperCase()) == MS1.IonMode.POS) {
                            isPositiveScanPresent = true;
                        }

                        if (MS1.IonMode.valueOf(
                                scan.getScanFile().getMode().toString().toUpperCase()) == MS1.IonMode.NEG) {
                            isNegativeScanPresent = true;
                        }
                    }
                }

                for (ScanData<LCMSWell> scan : posNegWells) {
                    if (chemical.getChemical().equals(scan.getWell().getChemical())
                            && chemical.getChemical().equals(scan.getTargetChemicalName())) {
                        if (MS1.IonMode.valueOf(
                                scan.getScanFile().getMode().toString().toUpperCase()) == MS1.IonMode.POS) {
                            isPositiveScanPresent = true;
                        }

                        if (MS1.IonMode.valueOf(
                                scan.getScanFile().getMode().toString().toUpperCase()) == MS1.IonMode.NEG) {
                            isNegativeScanPresent = true;
                        }
                    }
                }

                ionModes.put(chemical.getId(), Pair.of(isPositiveScanPresent, isNegativeScanPresent));
            }

            // Sort in descending order of media where MeOH and Water related media are promoted to the top and
            // anything derived from yeast media are demoted. We do this because we want to first process the water
            // and meoh media before processing the yeast media since the yeast media depends on the analysis of the former.
            Collections.sort(standardWells, new Comparator<StandardWell>() {
                @Override
                public int compare(StandardWell o1, StandardWell o2) {
                    if (StandardWell.doesMediaContainYeastExtract(o1.getMedia())
                            && !StandardWell.doesMediaContainYeastExtract(o2.getMedia())) {
                        return 1;
                    } else {
                        return 0;
                    }
                }
            });

            searchIons = extractPathwayStepIonsFromStandardIonAnalysis(pathwayChems, lcmsDir, db, standardWells,
                    plottingDirectory, ionModes);
        }

        produceLCMSPathwayHeatmaps(lcmsDir, outData, outImg, outAnalysis, pathwayChems, allStandardScans,
                allPositiveScans, allNegativeScans, fontScale, cl.hasOption(OPTION_USE_HEATMAP), searchIons);
    }
}

From source file:com.github.lxyscls.jvmjava.Cmd.java

static Cmd parseCmd(String[] args) throws ParseException {
    Cmd cmd = new Cmd();

    Options options = new Options();
    options.addOption("help", false, "print help message");
    options.addOption("?", false, "print help message");
    options.addOption("version", false, "print version and exit");
    options.addOption("classpath", true, "classpath");
    options.addOption("cp", true, "classpath");
    options.addOption("Xjre", true, "path to jre");

    CommandLineParser parser = new DefaultParser();

    CommandLine cl = parser.parse(options, args);
    cmd.helpFlag = cl.hasOption("help") || cl.hasOption("?");
    cmd.versionFlag = cl.hasOption("version");

    if (cl.hasOption("classpath")) {
        cmd.cpOption = cl.getOptionValue("classpath");
    } else if (cl.hasOption("cp")) {
        cmd.cpOption = cl.getOptionValue("cp");
    }// w w w.j  a  v  a 2 s .  c  om
    if (cl.hasOption("Xjre")) {
        cmd.XjreOption = cl.getOptionValue("Xjre");
    }

    String[] leftOverArgs = cl.getArgs();
    if (leftOverArgs.length > 0) {
        cmd.runClass = leftOverArgs[0];
        cmd.runClassArgs = Arrays.copyOfRange(leftOverArgs, 1, leftOverArgs.length);
    }

    return cmd;
}

From source file:net.adamjak.thomas.graph.application.cli.CliManager.java

/**
 * Manage CLI/*from www  .  jav  a2  s  .c  o  m*/
 *
 * @param arguments input arguments from user
 */
public static void manage(String[] arguments) {
    CliManager.arguments = arguments;

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(CliManager.getOptions(), arguments);
    } catch (ParseException e) {
        CliManager.printError("Error in parse cli arguments!\n" + "Message: " + e.getMessage());
        System.exit(-1);
    }

    if (cmd.hasOption("author")) {
        System.out.println(Utils.getAuthorInfo(false));
    } else if (cmd.hasOption("license")) {
        System.out.println(Utils.getLicenseInfo(false));
    } else if (cmd.hasOption("gui")) {
        AppMainWindow appMainWindow = new AppMainWindow();
        appMainWindow.setVisible(true);
    } else if (cmd.hasOption("i") && cmd.hasOption("t")) {
        RunnerBuilder builder = new RunnerBuilder();
        builder.setInputFile(new File(cmd.getOptionValue("i")));
        builder.setTestType(SnarkTestTypes.getSnarkTestTypeByName(cmd.getOptionValue("t")));

        if (cmd.hasOption("a")) {
            builder.setAlgorithmTest(Utils.getTestClassByName(cmd.getOptionValue("a")));
        }

        if (cmd.hasOption("o")) {
            builder.setOutputFile(new File(cmd.getOptionValue("o")));
        }

        if (cmd.hasOption("l")) {
            try {
                builder.setLoops(Integer.valueOf(cmd.getOptionValue("l")));
            } catch (NumberFormatException e) {
                CliManager.printError("Error in parse loops count.");
                System.exit(-1);
            }
        }

        try {
            if (cmd.hasOption("r")) {
                builder.build().runAndSaveResultsWithRawData();
            } else {
                builder.build().runAndSaveResults();
            }
        } catch (RunnerException e) {
            CliManager.printError(e.getMessage());
            System.exit(-1);
        }

    } else {
        CliManager.printHelp();
    }
}

From source file:com.hortonworks.registries.schemaregistry.examples.avro.KafkaAvroSerDesApp.java

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

    Option sendMessages = Option.builder("sm").longOpt("send-messages").desc("Send Messages to Kafka")
            .type(Boolean.class).build();
    Option consumeMessages = Option.builder("cm").longOpt("consume-messages")
            .desc("Consume Messages from Kafka").type(Boolean.class).build();

    Option dataFileOption = Option.builder("d").longOpt("data-file").hasArg().desc("Provide a data file")
            .type(String.class).build();
    Option producerFileOption = Option.builder("p").longOpt("producer-config").hasArg()
            .desc("Provide a Kafka producer config file").type(String.class).build();
    Option schemaOption = Option.builder("s").longOpt("schema-file").hasArg().desc("Provide a schema file")
            .type(String.class).build();

    Option consumerFileOption = Option.builder("c").longOpt("consumer-config").hasArg()
            .desc("Provide a Kafka Consumer config file").type(String.class).build();

    OptionGroup groupOpt = new OptionGroup();
    groupOpt.addOption(sendMessages);/*w  w w .  ja v a2 s .c  o m*/
    groupOpt.addOption(consumeMessages);
    groupOpt.setRequired(true);

    Options options = new Options();
    options.addOptionGroup(groupOpt);
    options.addOption(dataFileOption);
    options.addOption(producerFileOption);
    options.addOption(schemaOption);
    options.addOption(consumerFileOption);

    //showHelpMessage(args, options);

    CommandLineParser parser = new DefaultParser();
    CommandLine commandLine;

    try {
        commandLine = parser.parse(options, args);
        if (commandLine.hasOption("sm")) {
            if (commandLine.hasOption("p") && commandLine.hasOption("d") && commandLine.hasOption("s")) {
                KafkaAvroSerDesApp kafkaAvroSerDesApp = new KafkaAvroSerDesApp(commandLine.getOptionValue("p"),
                        commandLine.getOptionValue("s"));
                kafkaAvroSerDesApp.sendMessages(commandLine.getOptionValue("d"));
            } else {
                LOG.error("please provide following options for sending messages to Kafka");
                LOG.error("-d or --data-file");
                LOG.error("-s or --schema-file");
                LOG.error("-p or --producer-config");
            }
        } else if (commandLine.hasOption("cm")) {
            if (commandLine.hasOption("c")) {
                KafkaAvroSerDesApp kafkaAvroSerDesApp = new KafkaAvroSerDesApp(commandLine.getOptionValue("c"));
                kafkaAvroSerDesApp.consumeMessages();
            } else {
                LOG.error("please provide following options for consuming messages from Kafka");
                LOG.error("-c or --consumer-config");
            }
        }
    } catch (ParseException e) {
        LOG.error("Please provide all the options ", e);
    } catch (Exception e) {
        LOG.error("Failed to send/receive messages ", e);
    }

}

From source file:com.hortonworks.registries.schemaregistry.examples.avro.TruckEventsKafkaAvroSerDesApp.java

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

    Option sendMessages = Option.builder("sm").longOpt("send-messages").desc("Send Messages to Kafka")
            .type(Boolean.class).build();
    Option consumeMessages = Option.builder("cm").longOpt("consume-messages")
            .desc("Consume Messages from Kafka").type(Boolean.class).build();

    Option dataFileOption = Option.builder("d").longOpt("data-file").hasArg().desc("Provide a data file")
            .type(String.class).build();
    Option producerFileOption = Option.builder("p").longOpt("producer-config").hasArg()
            .desc("Provide a Kafka producer config file").type(String.class).build();
    Option schemaOption = Option.builder("s").longOpt("schema-file").hasArg().desc("Provide a schema file")
            .type(String.class).build();

    Option consumerFileOption = Option.builder("c").longOpt("consumer-config").hasArg()
            .desc("Provide a Kafka Consumer config file").type(String.class).build();

    OptionGroup groupOpt = new OptionGroup();
    groupOpt.addOption(sendMessages);/*from  w w  w  .ja v a2s.co m*/
    groupOpt.addOption(consumeMessages);
    groupOpt.setRequired(true);

    Options options = new Options();
    options.addOptionGroup(groupOpt);
    options.addOption(dataFileOption);
    options.addOption(producerFileOption);
    options.addOption(schemaOption);
    options.addOption(consumerFileOption);

    //showHelpMessage(args, options);

    CommandLineParser parser = new DefaultParser();
    CommandLine commandLine;

    try {
        commandLine = parser.parse(options, args);
        if (commandLine.hasOption("sm")) {
            if (commandLine.hasOption("p") && commandLine.hasOption("d") && commandLine.hasOption("s")) {
                TruckEventsKafkaAvroSerDesApp truckEventsKafkaAvroSerDesApp = new TruckEventsKafkaAvroSerDesApp(
                        commandLine.getOptionValue("p"), commandLine.getOptionValue("s"));
                truckEventsKafkaAvroSerDesApp.sendMessages(commandLine.getOptionValue("d"));
            } else {
                LOG.error("please provide following options for sending messages to Kafka");
                LOG.error("-d or --data-file");
                LOG.error("-s or --schema-file");
                LOG.error("-p or --producer-config");
            }
        } else if (commandLine.hasOption("cm")) {
            if (commandLine.hasOption("c")) {
                TruckEventsKafkaAvroSerDesApp truckEventsKafkaAvroSerDesApp = new TruckEventsKafkaAvroSerDesApp(
                        commandLine.getOptionValue("c"));
                truckEventsKafkaAvroSerDesApp.consumeMessages();
            } else {
                LOG.error("please provide following options for consuming messages from Kafka");
                LOG.error("-c or --consumer-config");
            }
        }
    } catch (ParseException e) {
        LOG.error("Please provide all the options ", e);
    } catch (Exception e) {
        LOG.error("Failed to send/receive messages ", e);
    }

}

From source file:esiptestbed.mudrod.main.MudrodEngine.java

/**
 * Main program invocation. Accepts one argument denoting location (on disk)
 * to a log file which is to be ingested. Help will be provided if invoked
 * with incorrect parameters./*from ww  w  . java2  s .co m*/
 * 
 * @param args
 *          {@link java.lang.String} array contaning correct parameters.
 */
public static void main(String[] args) {
    // boolean options
    Option helpOpt = new Option("h", "help", false, "show this help message");

    // preprocessing + processing
    Option fullIngestOpt = new Option("f", FULL_INGEST, false, "begin full ingest Mudrod workflow");
    // processing only, assuming that preprocessing results is in logDir
    Option processingOpt = new Option("p", PROCESSING, false, "begin processing with preprocessing results");

    // import raw web log into Elasticsearch
    Option logIngestOpt = new Option("l", LOG_INGEST, false, "begin log ingest without any processing only");
    // preprocessing web log, assuming web log has already been imported
    Option sessionReconOpt = new Option("s", SESSION_RECON, false, "begin session reconstruction");
    // calculate vocab similarity from session reconstrution results
    Option vocabSimFromOpt = new Option("v", VOCAB_SIM_FROM_LOG, false,
            "begin similarity calulation from web log Mudrod workflow");
    // add metadata and ontology preprocessing and processing results into web
    // log vocab similarity
    Option addMetaOntoOpt = new Option("a", ADD_META_ONTO, false, "begin adding metadata and ontology results");

    // argument options
    Option logDirOpt = Option.builder(LOG_DIR).required(true).numberOfArgs(1).hasArg(true)
            .desc("the log directory to be processed by Mudrod").argName(LOG_DIR).build();

    // create the options
    Options options = new Options();
    options.addOption(helpOpt);
    options.addOption(logIngestOpt);
    options.addOption(fullIngestOpt);
    options.addOption(processingOpt);
    options.addOption(sessionReconOpt);
    options.addOption(vocabSimFromOpt);
    options.addOption(addMetaOntoOpt);
    options.addOption(logDirOpt);

    CommandLineParser parser = new DefaultParser();
    try {
        CommandLine line = parser.parse(options, args);
        String processingType = null;

        if (line.hasOption(LOG_INGEST)) {
            processingType = LOG_INGEST;
        } else if (line.hasOption(FULL_INGEST)) {
            processingType = FULL_INGEST;
        } else if (line.hasOption(PROCESSING)) {
            processingType = PROCESSING;
        } else if (line.hasOption(SESSION_RECON)) {
            processingType = SESSION_RECON;
        } else if (line.hasOption(VOCAB_SIM_FROM_LOG)) {
            processingType = VOCAB_SIM_FROM_LOG;
        } else if (line.hasOption(ADD_META_ONTO)) {
            processingType = ADD_META_ONTO;
        }

        String dataDir = line.getOptionValue(LOG_DIR).replace("\\", "/");
        if (!dataDir.endsWith("/")) {
            dataDir += "/";
        }

        MudrodEngine me = new MudrodEngine();
        me.loadConfig();
        me.props.put(LOG_DIR, dataDir);
        me.es = new ESDriver(me.getConfig());
        me.spark = new SparkDriver();
        loadFullConfig(me, dataDir);
        if (processingType != null) {
            switch (processingType) {
            case LOG_INGEST:
                me.logIngest();
                break;
            case PROCESSING:
                me.startProcessing();
                break;
            case SESSION_RECON:
                me.sessionRestruction();
                break;
            case VOCAB_SIM_FROM_LOG:
                me.vocabSimFromLog();
                break;
            case ADD_META_ONTO:
                me.addMetaAndOntologySim();
                break;
            case FULL_INGEST:
                me.startFullIngest();
                break;
            default:
                break;
            }
        }
        me.end();
    } catch (Exception e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(
                "MudrodEngine: 'logDir' argument is mandatory. " + "User must also provide an ingest method.",
                options, true);
        LOG.error("Error inputting command line!", e);
        return;
    }
}

From source file:ArgumentParserTests.java

@BeforeClass
public static void ClassInit() {
    _options = OptionsProvider.Provide();
    _loggingService = new LoggingService();
    _parser = new DefaultParser();
}

From source file:com.javadeobfuscator.deobfuscator.DeobfuscatorMain.java

public static int run(String[] args) {
    Options options = new Options();
    options.addOption("transformer", true, "A transformer to use");
    options.addOption("path", true, "A JAR to be placed in the classpath");
    options.addOption("input", true, "The input file");
    options.addOption("output", true, "The output file");
    //TODO://from ww  w .  ja v  a 2  s.  c o m
    // * keepClass
    // * custom normalizer name

    CommandLineParser parser = new DefaultParser();
    try {
        Deobfuscator deobfuscator = new Deobfuscator();
        CommandLine cmd = parser.parse(options, args);

        if (!cmd.hasOption("input")) {
            System.out.println("No input jar specified");
            return 3;
        }

        if (!cmd.hasOption("output")) {
            System.out.println("No output jar specified");
            return 4;
        }

        File input = new File(cmd.getOptionValue("input"));
        if (!input.exists()) {
            System.out.println("Input file does not exist");
            return 5;
        }

        File output = new File(cmd.getOptionValue("output"));
        if (output.exists()) {
            System.out.println("Warning! Output file already exists");
        }

        deobfuscator.withInput(input).withOutput(output);

        String[] transformers = cmd.getOptionValues("transformer");
        if (transformers == null || transformers.length == 0) {
            System.out.println("No transformers specified");
            return 2;
        }
        for (String transformer : transformers) {
            Class<?> clazz = null;
            try {
                clazz = Class.forName("com.javadeobfuscator.deobfuscator.transformers." + transformer);
            } catch (ClassNotFoundException exception) {
                try {
                    clazz = Class.forName(transformer);
                } catch (ClassNotFoundException exception1) {
                    System.out.println("Could not locate transformer " + transformer);
                }
            }
            if (clazz != null) {
                if (Transformer.class.isAssignableFrom(clazz)) {
                    deobfuscator.withTransformer(clazz.asSubclass(Transformer.class));
                } else {
                    System.out.println(clazz.getCanonicalName()
                            + " does not extend com.javadeobfuscator.deobfuscator.transformers.Transformer");
                }
            }
        }

        String[] paths = cmd.getOptionValues("path");
        if (paths != null) {
            for (String path : paths) {
                File file = new File(path);
                if (file.exists()) {
                    deobfuscator.withClasspath(file);
                } else {
                    System.out.println("Could not find classpath file " + path);
                }
            }
        }

        try {
            deobfuscator.start();
            return 0;
        } catch (Deobfuscator.NoClassInPathException ex) {
            System.out.println("Could not locate a class file.");
            System.out.println("Have you added the necessary files to the -path argument?");
            System.out.println("The error was:");
            ex.printStackTrace(System.out);
            return -2;
        } catch (Throwable t) {
            System.out.println("Deobfuscation failed. Please open a ticket on GitHub");
            t.printStackTrace(System.out);
            return -1;
        }
    } catch (ParseException e) {
        return 1;
    }
}