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:edu.cmu.sv.modelinference.modeltool.handlers.STLog2ModelHandler.java

@Override
public Model<?> process(String logFile, String logType, String[] additionalCmdArgs)
        throws LogProcessingException {
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;/*from w ww . j  a  v  a  2 s  . co m*/
    try {
        cmd = parser.parse(cmdOpts, additionalCmdArgs, false);
    } catch (ParseException exp) {
        logger.error(exp.getMessage());
        System.err.println(exp.getMessage());
        Util.printHelpAndExit(STLog2ModelHandler.class, cmdOpts);
    }

    Model<?> model = null;
    ModelInferer<GridState> modelInferer = null;
    if (cmd.hasOption(GRID_DIM)) {
        String partStr = cmd.getOptionValue(GRID_DIM).trim();
        GridPartitions parts;
        try {
            parts = STConfig.extractGridPartitions(partStr);
        } catch (ParseException e) {
            throw new LogProcessingException(e);
        }
        modelInferer = new STModelInferer(parts.horiz, parts.vert);
    } else
        modelInferer = new STModelInferer(STModelInferer.DEF_PARTITIONS, STModelInferer.DEF_PARTITIONS);

    try {
        model = modelInferer.generateModel(logFile);
    } catch (IOException e) {
        throw new LogProcessingException(e);
    }
    return model;
}

From source file:alluxio.cli.LogLevel.java

/**
 * Implements log level setting and getting.
 *
 * @param args list of arguments contains target, logName and level
 * @exception ParseException if there is an error in parsing
 *//* w w  w .ja  v a  2s.com*/
public static void logLevel(String[] args) throws ParseException, IOException {
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(OPTIONS, args, true /* stopAtNonOption */);

    List<TargetInfo> targets = parseOptTarget(cmd);
    String logName = parseOptLogName(cmd);
    String level = parseOptLevel(cmd);

    for (TargetInfo targetInfo : targets) {
        setLogLevel(targetInfo, logName, level);
    }
}

From source file:io.mxnet.caffetranslator.Launcher.java

public void parseCommandLine(String[] args) {
    CommandLineParser clParser = new DefaultParser();

    Options options = new Options();

    Option prototxtOption = Option.builder("t").longOpt(TRAINING_PROTOTXT).hasArg()
            .desc("training/validation prototxt").build();
    options.addOption(prototxtOption);/*ww  w .  java  2  s.co  m*/

    Option solverOption = Option.builder("s").longOpt(SOLVER_PROTOTXT).hasArg().desc("solver prototxt").build();
    options.addOption(solverOption);

    Option dataLayerOpt = Option.builder("c").longOpt(CUSTOM_DATA_LAYERS).hasArg()
            .desc("Comma separated custom data layers").build();
    options.addOption(dataLayerOpt);

    Option outfileOpt = Option.builder("o").longOpt(OUTPUT_FILE).hasArg().desc("Output file").build();
    options.addOption(outfileOpt);

    Option paramsFileOpt = Option.builder("p").longOpt(PARAMS_FILE).hasArg().desc("Params file").build();
    options.addOption(paramsFileOpt);

    Option graphFileOpt = Option.builder("g").longOpt(GRAPH_FILE).hasArg()
            .desc("Image file to visualize computation graph").build();
    options.addOption(graphFileOpt);

    CommandLine line = null;
    try {
        line = clParser.parse(options, args);
    } catch (ParseException e) {
        System.out.println("Exception parsing commandline:" + e.getMessage());
        System.exit(1);
    }

    if ((trainingPrototextPath = getOption(line, TRAINING_PROTOTXT)) == null) {
        bail("Command line argument " + TRAINING_PROTOTXT + " missing");
    }

    if ((solverPrototextPath = getOption(line, SOLVER_PROTOTXT)) == null) {
        bail("Command line argument " + SOLVER_PROTOTXT + " missing");
    }

    String strOutFile = getOption(line, OUTPUT_FILE);
    if (strOutFile == null) {
        bail("Command line argument " + OUTPUT_FILE + " missing");
    }
    outFile = new File(strOutFile);

    paramsFilePath = getOption(line, PARAMS_FILE);

    String dataLayers;
    Config config = Config.getInstance();
    if ((dataLayers = getOption(line, CUSTOM_DATA_LAYERS)) != null) {
        for (String name : dataLayers.split(",")) {
            name = name.trim();
            config.addCustomDataLayer(name);
        }
    }

}

From source file:ai.grakn.migration.base.io.MigrationCLI.java

private MigrationCLI(String[] args, Options options) {
    addOptions(options);//  w ww  . j av a 2  s .co  m
    CommandLineParser parser = new DefaultParser();

    try {
        cmd = parser.parse(defaultOptions, args);
    } catch (ParseException e) {
        die(e.getMessage());
    }

    if (cmd.hasOption("h")) {
        printHelpMessage();
    }

    if (cmd.getOptions().length == 0) {
        printHelpMessage();
        throw new IllegalArgumentException("Helping");
    } else if (cmd.getOptions().length == 1 && cmd.hasOption("h")) {
        throw new IllegalArgumentException("Helping");
    }

    if (!GraknEngineServer.isRunning()) {
        System.out.println(COULD_NOT_CONNECT);
    }
}

From source file:gobblin.runtime.StateStoreBasedWatermarkStorageCli.java

@Override
public void run(String[] args) {
    Options options = new Options();
    options.addOption(HELP);//  w ww.  j a  v a 2  s.c  o  m
    options.addOption(ZK);
    options.addOption(JOB_NAME);
    options.addOption(ROOT_DIR);
    options.addOption(WATCH);

    CommandLine cli;
    try {
        CommandLineParser parser = new DefaultParser();
        cli = parser.parse(options, Arrays.copyOfRange(args, 1, args.length));
    } catch (ParseException pe) {
        System.out.println("Command line parse exception: " + pe.getMessage());
        return;
    }

    if (cli.hasOption(HELP.getOpt())) {
        printUsage(options);
        return;
    }

    TaskState taskState = new TaskState();

    String jobName;
    if (!cli.hasOption(JOB_NAME.getOpt())) {
        log.error("Need Job Name to be specified --", JOB_NAME.getLongOpt());
        throw new RuntimeException("Need Job Name to be specified");
    } else {
        jobName = cli.getOptionValue(JOB_NAME.getOpt());
        log.info("Using job name: {}", jobName);
    }
    taskState.setProp(ConfigurationKeys.JOB_NAME_KEY, jobName);

    String zkAddress = "locahost:2181";
    if (cli.hasOption(ZK.getOpt())) {
        zkAddress = cli.getOptionValue(ZK.getOpt());
    }

    log.info("Using zk address : {}", zkAddress);

    taskState.setProp(StateStoreBasedWatermarkStorage.WATERMARK_STORAGE_TYPE_KEY, "zk");
    taskState.setProp("state.store.zk.connectString", zkAddress);

    if (cli.hasOption(ROOT_DIR.getOpt())) {
        String rootDir = cli.getOptionValue(ROOT_DIR.getOpt());
        taskState.setProp(StateStoreBasedWatermarkStorage.WATERMARK_STORAGE_CONFIG_PREFIX
                + ConfigurationKeys.STATE_STORE_ROOT_DIR_KEY, rootDir);
        log.info("Setting root dir to {}", rootDir);
    } else {
        log.error("Need root directory specified");
        printUsage(options);
        return;
    }

    StateStoreBasedWatermarkStorage stateStoreBasedWatermarkStorage = new StateStoreBasedWatermarkStorage(
            taskState);

    final AtomicBoolean stop = new AtomicBoolean(true);

    if (cli.hasOption(WATCH.getOpt())) {
        stop.set(false);
    }
    try {

        if (!stop.get()) {
            Runtime.getRuntime().addShutdownHook(new Thread() {
                public void run() {
                    stop.set(true);
                }
            });
        }
        do {
            boolean foundWatermark = false;
            try {
                for (CheckpointableWatermarkState wmState : stateStoreBasedWatermarkStorage
                        .getAllCommittedWatermarks()) {
                    foundWatermark = true;
                    System.out.println(wmState.getProperties());
                }
            } catch (IOException ie) {
                Throwables.propagate(ie);
            }

            if (!foundWatermark) {
                System.out.println("No watermarks found.");
            }
            if (!stop.get()) {
                Thread.sleep(1000);
            }
        } while (!stop.get());
    } catch (Exception e) {
        Throwables.propagate(e);
    }
}

From source file:fr.ortolang.diffusion.client.cmd.CopyCommand.java

@Override
public void execute(String[] args) {
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;/*from   w w  w. j av  a2s  . c o  m*/
    String localPath = null;
    String workspace = null;
    String remotePath = null;

    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption("h")) {
            help();
        }
        String[] credentials = getCredentials(cmd);
        String username = credentials[0];
        String password = credentials[1];

        if (cmd.hasOption("w")) {
            workspace = cmd.getOptionValue("w");
        } else {
            System.out.println("Workspace key is needed (-w)");
            help();
        }

        if (cmd.hasOption("m")) {
            //TODO validate (with an enum ?)
            mode = cmd.getOptionValue("m");
        }

        List<String> argList = cmd.getArgList();
        if (argList.size() < 2) {
            System.out.println("Two arguments is needed (localpath and remotepath)");
            help();
        } else {
            localPath = argList.get(0);
            remotePath = argList.get(1);
        }

        client = OrtolangClient.getInstance();
        if (username.length() > 0) {
            client.getAccountManager().setCredentials(username, password);
            client.login(username);
        }
        System.out.println("Connected as user: " + client.connectedProfile());
        if (!Files.exists(Paths.get(localPath))) {
            errors.append("-> Le chemin local (").append(localPath).append(") n'existe pas\r\n");
        } else {
            //TODO Checks if remote Path exist
            if (Files.exists(Paths.get(localPath))) {
                copy(Paths.get(localPath), workspace, remotePath);
            }
        }
        if (errors.length() > 0) {
            System.out.println("## Some errors has been found : ");
            System.out.print(errors.toString());
        }

        client.logout();
        client.close();
    } catch (ParseException e) {
        System.out.println("Failed to parse command line properties " + e.getMessage());
        help();
    } catch (OrtolangClientException | OrtolangClientAccountException e) {
        System.out.println("Unexpected error !!");
        e.printStackTrace();
    }
}

From source file:com.fjn.helper.frameworkex.apache.commons.cli.Ls.java

@Test
public void test() throws ParseException {
    CommandLineParser parser = new DefaultParser();
    String[] args = new String[] { "--block-size=10" };
    CommandLine line = parser.parse(options, args);

    // validate that block-size has been set
    if (line.hasOption("block-size")) {
        // print the value of block-size
        System.out.println(line.getOptionValue("block-size"));
    }/*from www.j  a  v  a2  s  .c o  m*/
}

From source file:com.uber.stream.kafka.mirrormaker.controller.TestControllerConf.java

@Test
public void testCmdControllerConf() throws ParseException {
    String[] args = new String[] { "-helixClusterName", "testHelixClusterName", "-zookeeper", "localhost:2181",
            "-port", "9090", "-mode", "auto", "-env", "dc1.cluster1", "-instanceId", "instance0",
            "-graphiteHost", "graphiteHost0", "-graphitePort", "4844", "-srcKafkaZkPath",
            "localhost:2181/kafka1", "-destKafkaZkPath", "localhost:2181/kafka2", "-enableAutoWhitelist",
            "true", "-autoRebalanceDelayInSeconds", "120", "-patternToExcludeTopics", "__*", "-backUpToGit",
            "true", "-localBackupFilePath", "/tmp/localBackup", "-remoteBackupRepo",
            "git://kafka-mm-controller-backup.git", "-localGitRepoClonePath", "/tmp/kafka-mm-controller-backup",
            "-enableSrcKafkaValidation", "true" };
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;/*from  w w w  .ja  v a2  s .co m*/
    cmd = parser.parse(ControllerConf.constructControllerOptions(), args);
    ControllerConf conf = ControllerConf.getControllerConf(cmd);
    Assert.assertEquals(conf.getHelixClusterName(), "testHelixClusterName");
    Assert.assertEquals(conf.getZkStr(), "localhost:2181");
    Assert.assertEquals(conf.getControllerPort(), "9090");
    Assert.assertEquals(conf.getControllerMode(), "auto");
    Assert.assertEquals(conf.getEnvironment(), "dc1.cluster1");
    Assert.assertEquals(conf.getInstanceId(), "instance0");
    Assert.assertEquals(conf.getGraphiteHost(), "graphiteHost0");
    Assert.assertEquals(conf.getSrcKafkaZkPath(), "localhost:2181/kafka1");
    Assert.assertEquals(conf.getDestKafkaZkPath(), "localhost:2181/kafka2");
    Assert.assertEquals(conf.getAutoRebalanceDelayInSeconds().intValue(), 120);
    Assert.assertEquals(conf.getEnableAutoWhitelist(), true);
    Assert.assertEquals(conf.getPatternToExcludeTopics(), "__*");
    Assert.assertEquals(conf.getBackUpToGit().booleanValue(), true);
    Assert.assertEquals(conf.getLocalBackupFilePath(), null);
    Assert.assertEquals(conf.getRemoteBackupRepo(), "git://kafka-mm-controller-backup.git");
    Assert.assertEquals(conf.getLocalGitRepoPath(), "/tmp/kafka-mm-controller-backup");
    Assert.assertEquals(conf.getEnableSrcKafkaValidation(), true);
}

From source file:at.salzburgresearch.vgi.vgianalyticsframework.activityanalysis.application.HexagonalRasterGenerator.java

public static void launch(Options options, String[] args) {
    /**// w w w. j  av a  2 s . c  om
     * Initialize input parameters
     */
    int crs = 32633;
    double west = 64031;
    double east = 679874;
    double south = 5127838;
    double north = 5451301;

    double width = 10000;
    double height = width * Math.sqrt(3) / 2;

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;
    File homeDirectory = null;

    try {
        cmd = parser.parse(options, args);

        if (cmd.hasOption('h')) {
            HelpFormatter helpFormatter = new HelpFormatter();
            helpFormatter.printHelp("java -jar vgi-activity-1.0.jar [OPTION]...", options);
            return;
        }
        if (cmd.hasOption('d')) {
            homeDirectory = new File(cmd.getOptionValue('d'));
            if (!homeDirectory.exists()) {
                homeDirectory = null;
            }
        } else {
            homeDirectory = null;
            log.error("Cannot find home directory");
            System.exit(0);
        }
        if (cmd.hasOption("no")) {
            north = Double.valueOf(cmd.getOptionValue('n'));
        }
        if (cmd.hasOption("ea")) {
            east = Double.valueOf(cmd.getOptionValue('e'));
        }
        if (cmd.hasOption("so")) {
            south = Double.valueOf(cmd.getOptionValue('s'));
        }
        if (cmd.hasOption("we")) {
            west = Double.valueOf(cmd.getOptionValue('w'));
        }
        if (cmd.hasOption('c')) {
            crs = Integer.valueOf(cmd.getOptionValue('c'));
        }
        if (cmd.hasOption('w')) {
            width = Double.valueOf(cmd.getOptionValue('w'));
        }
    } catch (Exception e) {
        HelpFormatter helpFormatter = new HelpFormatter();
        if (e.getMessage() != null) {
            log.error(e.getMessage() + '\n');
        } else {
            log.error("Unknown error", e);
        }
        helpFormatter.printHelp("java -jar vgi-activity-1.0.jar [OPTION]...", options);
    }

    /**
     * Build feature type
     */
    SimpleFeatureTypeBuilder featureTypePoint = new SimpleFeatureTypeBuilder();
    featureTypePoint.setName("Hexagon");
    try {
        Hints hints = new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.TRUE);
        CRSAuthorityFactory factory = ReferencingFactoryFinder.getCRSAuthorityFactory("EPSG", hints);
        featureTypePoint.setCRS(factory.createCoordinateReferenceSystem("EPSG:" + crs));
    } catch (NoSuchAuthorityCodeException e1) {
        e1.printStackTrace();
    } catch (FactoryException e1) {
        e1.printStackTrace();
    }
    featureTypePoint.add("geom", Polygon.class);
    featureTypePoint.setDefaultGeometry("geom");
    featureTypePoint.add("id", Long.class);
    SimpleFeatureType featureType = featureTypePoint.buildFeatureType();

    /**
     * Generate raster
     */
    DecimalFormat df = new DecimalFormat("000");
    DefaultFeatureCollection raster = new DefaultFeatureCollection("hexagon_raster", featureType);

    double rowOffset = 0.0;
    double columnOffset = 0.0;

    for (int row = 0;; row++) {
        columnOffset = (row % 2 == 0) ? 0 : width / 4 * 3;

        double startY = south + rowOffset;

        double yTop = startY + height;
        double yMiddle = startY + height / 2;
        double yBottom = startY;

        for (int column = 0;; column++) {
            double startX = west + columnOffset + (column * width * 1.5);

            String id = "1" + df.format(row) + df.format(column);

            Coordinate[] coordinatesQuadrant = new Coordinate[7];
            coordinatesQuadrant[0] = new Coordinate(startX, yMiddle);
            coordinatesQuadrant[1] = new Coordinate(startX + width / 4, yBottom);
            coordinatesQuadrant[2] = new Coordinate(startX + width / 4 * 3, yBottom);
            coordinatesQuadrant[3] = new Coordinate(startX + width, yMiddle);
            coordinatesQuadrant[4] = new Coordinate(startX + width / 4 * 3, yTop);
            coordinatesQuadrant[5] = new Coordinate(startX + width / 4, yTop);
            coordinatesQuadrant[6] = coordinatesQuadrant[0];

            /** Assemble feature */
            SimpleFeatureBuilder builder = new SimpleFeatureBuilder(featureType);
            GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
            Polygon hexagon = geometryFactory
                    .createPolygon(geometryFactory.createLinearRing(coordinatesQuadrant), null);
            hexagon.setSRID(crs);
            builder.set("geom", hexagon);
            builder.set("id", id);
            raster.add(builder.buildFeature(id));

            if (startX + width > east)
                break;
        }

        if (startY + height >= north)
            break;

        rowOffset += height / 2;
    }

    final FeatureJSON json = new FeatureJSON(new GeometryJSON(7));
    boolean geometryless = raster.getSchema().getGeometryDescriptor() == null;
    json.setEncodeFeatureCollectionBounds(!geometryless);
    json.setEncodeFeatureCollectionCRS(!geometryless);
    try {
        json.writeFeatureCollection(raster,
                new FileOutputStream(homeDirectory + "/hexagonal_raster.geojson", false));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    log.info("Raster file written!");
}

From source file:jsastrawi.cli.LemmatizeCmd.java

/**
 * Handle lemmatize command/*w  w  w  .  j ava 2 s . c o  m*/
 *
 * @param args arguments
 * @throws IOException IOException
 */
public void handle(String[] args) throws IOException {
    Options options = buildOptions();
    CommandLineParser parser = new DefaultParser();

    try {
        CommandLine cmd = parser.parse(options, args);

        if (args.length == 0 || cmd.hasOption("h")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("lemmatize [args...] WORD...", options);
        } else {
            Set<String> dictionary;

            if (cmd.hasOption('d')) {
                dictionary = getDictionaryFromFile(cmd.getOptionValue('d'));
            } else {
                dictionary = getDefaultDictionary();
            }

            Lemmatizer l = new DefaultLemmatizer(dictionary);

            if (cmd.hasOption("tb")) {
                Map<String, String> map = scanTestBedMapFromFile(cmd.getOptionValue("tb"));
                runTestBed(map, l);
            } else if (!cmd.getArgList().isEmpty()) {
                for (String word : cmd.getArgs()) {
                    output.println(l.lemmatize(word));
                }
            }
        }
    } catch (ParseException ex) {
        Logger.getLogger(LemmatizeCmd.class.getName()).log(Level.SEVERE, null, ex);
    }
}