Example usage for org.apache.commons.cli CommandLine getOptionProperties

List of usage examples for org.apache.commons.cli CommandLine getOptionProperties

Introduction

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

Prototype

public Properties getOptionProperties(String opt) 

Source Link

Document

Retrieve the map of values associated to the option.

Usage

From source file:de.topobyte.livecg.ShowVisualization.java

public static void main(String[] args) {
    EnumNameLookup<Visualization> visualizationSwitch = new EnumNameLookup<Visualization>(Visualization.class,
            true);//  w  w w  .  j  a  v a 2 s .  com

    // @formatter:off
    Options options = new Options();
    OptionHelper.add(options, OPTION_CONFIG, true, false, "path", "config file");
    OptionHelper.add(options, OPTION_VISUALIZATION, true, true, "type",
            "type of visualization. one of <" + VisualizationUtil.getListOfAvailableVisualizations() + ">");
    OptionHelper.add(options, OPTION_STATUS, true, false,
            "status to " + "set the algorithm to. The format depends on the algorithm");
    // @formatter:on

    Option propertyOption = new Option(OPTION_PROPERTIES, "set a special property");
    propertyOption.setArgName("property=value");
    propertyOption.setArgs(2);
    propertyOption.setValueSeparator('=');
    options.addOption(propertyOption);

    CommandLineParser clp = new GnuParser();

    CommandLine line = null;
    try {
        line = clp.parse(options, args);
    } catch (ParseException e) {
        System.err.println("Parsing command line failed: " + e.getMessage());
        new HelpFormatter().printHelp(HELP_MESSAGE, options);
        System.exit(1);
    }

    String[] extra = line.getArgs();
    if (extra.length == 0) {
        System.out.println("Missing file argument");
        new HelpFormatter().printHelp(HELP_MESSAGE, options);
        System.exit(1);
    }
    String input = extra[0];

    StringOption argConfig = ArgumentHelper.getString(line, OPTION_CONFIG);
    if (argConfig.hasValue()) {
        String configPath = argConfig.getValue();
        LiveConfig.setPath(configPath);
    }

    StringOption argVisualization = ArgumentHelper.getString(line, OPTION_VISUALIZATION);
    StringOption argStatus = ArgumentHelper.getString(line, OPTION_STATUS);

    Visualization visualization = visualizationSwitch.find(argVisualization.getValue());
    if (visualization == null) {
        System.err.println("Unsupported visualization '" + argVisualization.getValue() + "'");
        System.exit(1);
    }

    System.out.println("Visualization: " + visualization);

    ContentReader contentReader = new ContentReader();
    Content content = null;
    try {
        content = contentReader.read(new File(input));
    } catch (Exception e) {
        System.out.println("Error while reading input file '" + input + "'. Exception type: "
                + e.getClass().getSimpleName() + ", message: " + e.getMessage());
        System.exit(1);
    }

    Properties properties = line.getOptionProperties(OPTION_PROPERTIES);

    ContentLauncher launcher = null;

    switch (visualization) {
    case GEOMETRY: {
        launcher = new ContentDisplayLauncher();
        break;
    }
    case DCEL: {
        launcher = new DcelLauncher();
        break;
    }
    case FREESPACE: {
        launcher = new FreeSpaceChainsLauncher();
        break;
    }
    case DISTANCETERRAIN: {
        launcher = new DistanceTerrainChainsLauncher();
        break;
    }
    case CHAN: {
        launcher = new ChanLauncher();
        break;
    }
    case FORTUNE: {
        launcher = new FortunesSweepLauncher();
        break;
    }
    case MONOTONE_PIECES: {
        launcher = new MonotonePiecesLauncher();
        break;
    }
    case MONOTONE_TRIANGULATION: {
        launcher = new MonotoneTriangulationLauncher();
        break;
    }
    case TRIANGULATION: {
        launcher = new MonotonePiecesTriangulationLauncher();
        break;
    }
    case SPIP: {
        launcher = new ShortestPathInPolygonLauncher();
        break;
    }
    case BUFFER: {
        launcher = new PolygonBufferLauncher();
        break;
    }
    }

    try {
        launcher.launch(content, true);
    } catch (LaunchException e) {
        System.err.println("Unable to start visualization");
        System.err.println("Error message: " + e.getMessage());
        System.exit(1);
    }
}

From source file:com.github.thesmartenergy.sparql.generate.generator.CMDGenerator.java

public static void main(String[] args) {

    List<String> formats = Arrays.asList("TTL", "TURTLE", "NTRIPLES", "TRIG", "RDFXML", "JSONLD");

    try {/*from   w w  w .  j ava  2s  .com*/
        CommandLine cl = CMDConfigurations.parseArguments(args);

        String query = "";
        String outputFormat = "TTL";

        if (cl.getArgList().size() == 0) {
            CMDConfigurations.displayHelp();
            return;
        }

        fileManager = FileManager.makeGlobal();
        if (cl.hasOption('l')) {
            Enumeration<String> loggers = LogManager.getLogManager().getLoggerNames();
            while (loggers.hasMoreElements()) {
                java.util.logging.Logger element = LogManager.getLogManager().getLogger(loggers.nextElement());
                element.setLevel(Level.OFF);
            }
            Logger.getRootLogger().setLevel(org.apache.log4j.Level.OFF);

        }
        LOG = Logger.getLogger(CMDGenerator.class);

        //get query file path
        //check if the file exists
        if (cl.hasOption("qf")) {
            String file_path = cl.getOptionValue("qf");
            File f = new File(file_path);
            if (f.exists() && !f.isDirectory()) {
                FileInputStream fisTargetFile = new FileInputStream(f);
                query = IOUtils.toString(fisTargetFile, "UTF-8");
                LOG.debug("\n\nRead SPARQL-Generate Query ..\n" + query + "\n\n");
            } else {
                LOG.error("File " + file_path + " not found.");
            }
        }

        //get query string
        if (cl.hasOption("qs")) {
            query = cl.getOptionValue("qs");
        }
        System.out.println("Query:" + query);

        //get and validate the output format
        if (cl.hasOption("f")) {
            String format = cl.getOptionValue("f");
            if (formats.contains(format)) {
                outputFormat = format;
            } else {
                LOG.error("Invalid output format," + cl.getOptionProperties("f").getProperty("description"));
                return;
            }
        }

        Model configurationModel = null;
        String conf = "";
        if (cl.hasOption("c")) {
            conf = cl.getOptionValue("c");
            configurationModel = ProcessQuery.generateConfiguration(conf);
        }

        String output = ProcessQuery.process(query, conf, outputFormat);
        System.out.println(output);

    } catch (org.apache.commons.cli.ParseException ex) {
        LOG.error(ex);
    } catch (FileNotFoundException ex) {
        LOG.error(ex);
    } catch (IOException ex) {
        LOG.error(ex);
    }

}

From source file:de.topobyte.livecg.CreateImage.java

public static void main(String[] args) {
    EnumNameLookup<ExportFormat> exportSwitch = new EnumNameLookup<ExportFormat>(ExportFormat.class, true);

    EnumNameLookup<Visualization> visualizationSwitch = new EnumNameLookup<Visualization>(Visualization.class,
            true);//from   www .j a  v a  2s. co  m

    // @formatter:off
    Options options = new Options();
    OptionHelper.add(options, OPTION_CONFIG, true, false, "path", "config file");
    OptionHelper.add(options, OPTION_INPUT, true, true, "file", "input geometry file");
    OptionHelper.add(options, OPTION_OUTPUT, true, true, "file", "output file");
    OptionHelper.add(options, OPTION_OUTPUT_FORMAT, true, true, "type",
            "type of output. one of <png,svg,tikz,ipe>");
    OptionHelper.add(options, OPTION_VISUALIZATION, true, true, "type",
            "type of visualization. one of <" + VisualizationUtil.getListOfAvailableVisualizations() + ">");
    OptionHelper.add(options, OPTION_STATUS, true, false,
            "status to " + "set the algorithm to. The format depends on the algorithm");
    // @formatter:on

    Option propertyOption = new Option(OPTION_PROPERTIES, "set a special property");
    propertyOption.setArgName("property=value");
    propertyOption.setArgs(2);
    propertyOption.setValueSeparator('=');
    options.addOption(propertyOption);

    CommandLineParser clp = new GnuParser();

    CommandLine line = null;
    try {
        line = clp.parse(options, args);
    } catch (ParseException e) {
        System.err.println("Parsing command line failed: " + e.getMessage());
        new HelpFormatter().printHelp(HELP_MESSAGE, options);
        System.exit(1);
    }

    StringOption argConfig = ArgumentHelper.getString(line, OPTION_CONFIG);
    if (argConfig.hasValue()) {
        String configPath = argConfig.getValue();
        LiveConfig.setPath(configPath);
    }

    StringOption argInput = ArgumentHelper.getString(line, OPTION_INPUT);
    StringOption argOutput = ArgumentHelper.getString(line, OPTION_OUTPUT);
    StringOption argOutputFormat = ArgumentHelper.getString(line, OPTION_OUTPUT_FORMAT);
    StringOption argVisualization = ArgumentHelper.getString(line, OPTION_VISUALIZATION);
    StringOption argStatus = ArgumentHelper.getString(line, OPTION_STATUS);

    ExportFormat exportFormat = exportSwitch.find(argOutputFormat.getValue());
    if (exportFormat == null) {
        System.err.println("Unsupported output format '" + argOutputFormat.getValue() + "'");
        System.exit(1);
    }

    Visualization visualization = visualizationSwitch.find(argVisualization.getValue());
    if (visualization == null) {
        System.err.println("Unsupported visualization '" + argVisualization.getValue() + "'");
        System.exit(1);
    }

    System.out.println("Visualization: " + visualization);
    System.out.println("Output format: " + exportFormat);

    ContentReader contentReader = new ContentReader();
    Content content = null;
    try {
        content = contentReader.read(new File(argInput.getValue()));
    } catch (Exception e) {
        System.out.println("Error while reading input file '" + argInput.getValue() + "'. Exception type: "
                + e.getClass().getSimpleName() + ", message: " + e.getMessage());
        System.exit(1);
    }

    Properties properties = line.getOptionProperties(OPTION_PROPERTIES);

    double zoom = 1;

    String statusArgument = null;
    if (argStatus.hasValue()) {
        statusArgument = argStatus.getValue();
    }

    VisualizationSetup setup = null;

    switch (visualization) {
    case GEOMETRY: {
        setup = new ContentVisualizationSetup();
        break;
    }
    case DCEL: {
        setup = new DcelVisualizationSetup();
        break;
    }
    case FREESPACE: {
        setup = new FreeSpaceVisualizationSetup();
        break;
    }
    case DISTANCETERRAIN: {
        setup = new DistanceTerrainVisualizationSetup();
        break;
    }
    case CHAN: {
        setup = new ChanVisualizationSetup();
        break;
    }
    case MONOTONE_PIECES: {
        setup = new MonotonePiecesVisualizationSetup();
        break;
    }
    case MONOTONE_TRIANGULATION: {
        setup = new MonotoneTriangulationVisualizationSetup();
        break;
    }
    case TRIANGULATION: {
        setup = new MonotonePiecesTriangulationVisualizationSetup();
        break;
    }
    case BUFFER: {
        setup = new BufferVisualizationSetup();
        break;
    }
    case FORTUNE: {
        setup = new FortunesSweepVisualizationSetup();
        break;
    }
    case SPIP: {
        setup = new ShortestPathVisualizationSetup();
        break;
    }
    }

    if (setup == null) {
        System.err.println("Not yet implemented");
        System.exit(1);
    }

    SetupResult setupResult = setup.setup(content, statusArgument, properties, zoom);

    int width = setupResult.getWidth();
    int height = setupResult.getHeight();

    VisualizationPainter visualizationPainter = setupResult.getVisualizationPainter();

    File output = new File(argOutput.getValue());

    visualizationPainter.setZoom(zoom);

    switch (exportFormat) {
    case IPE: {
        try {
            IpeExporter.exportIpe(output, visualizationPainter, width, height);
        } catch (Exception e) {
            System.err.println("Error while exporting. Exception type: " + e.getClass().getSimpleName()
                    + ", message: " + e.getMessage());
            System.exit(1);
        }
        break;
    }
    case PNG: {
        try {
            GraphicsExporter.exportPNG(output, visualizationPainter, width, height);
        } catch (IOException e) {
            System.err.println("Error while exporting. Exception type: " + e.getClass().getSimpleName()
                    + ", message: " + e.getMessage());
            System.exit(1);
        }
        break;
    }
    case SVG: {
        try {
            SvgExporter.exportSVG(output, visualizationPainter, width, height);
        } catch (Exception e) {
            System.err.println("Error while exporting. Exception type: " + e.getClass().getSimpleName()
                    + ", message: " + e.getMessage());
            System.exit(1);
        }
        break;
    }
    case TIKZ: {
        try {
            TikzExporter.exportTikz(output, visualizationPainter, width, height);
        } catch (Exception e) {
            System.err.println("Error while exporting. Exception type: " + e.getClass().getSimpleName()
                    + ", message: " + e.getMessage());
            System.exit(1);
        }
        break;
    }
    }
}

From source file:dk.alexandra.fresco.suite.spdz.configuration.SpdzConfiguration.java

static SpdzConfiguration fromCmdLine(SCEConfiguration sceConf, CommandLine cmd) throws ParseException {
    Properties p = cmd.getOptionProperties("D");
    //TODO: Figure out a meaningful default for the below 
    final int maxBitLength = Integer.parseInt(p.getProperty("spdz.maxBitLength", "64"));
    if (maxBitLength < 2) {
        throw new ParseException("spdz.maxBitLength must be > 1");
    }/*from   w w w.  ja  v a  2 s .com*/
    final String triplePath = p.getProperty("spdz.triplePath", "/triples");
    final boolean useDummyData = Boolean.parseBoolean(p.getProperty("spdz.useDummyData", "False"));

    return new SpdzConfiguration() {

        @Override
        public String getTriplePath() {
            return triplePath;
        }

        @Override
        public int getMaxBitLength() {
            return maxBitLength;
        }

        @Override
        public boolean useDummyData() {
            return useDummyData;
        }
    };
}

From source file:dk.alexandra.fresco.suite.bgw.configuration.BgwConfiguration.java

public static BgwConfiguration fromCmdLine(SCEConfiguration sceConf, CommandLine cmd) throws ParseException {
    // Validate BGW specific arguments.
    Properties p = cmd.getOptionProperties("D");
    if (!p.containsKey("bgw.threshold")) {
        throw new ParseException("BGW requires setting -Dbgw.threshold=[int]");
    }//  w  w  w  .  j a va2  s. c o m

    try {
        final int threshold = Integer.parseInt(p.getProperty("bgw.threshold"));
        if (threshold < 1)
            throw new ParseException("bgw.threshold must be > 0");
        if (threshold > sceConf.getParties().size() / 2)
            throw new ParseException("bgw.threshold must be < n/2");

        final BigInteger modulus = new BigInteger(p.getProperty("bgw.modulus", "618970019642690137449562111"));
        if (!modulus.isProbablePrime(40)) {
            throw new ParseException("BGW Modulus must be a prime number");
        }

        return new BgwConfiguration() {

            @Override
            public int getThreshold() {
                return threshold;
            }

            @Override
            public BigInteger getModulus() {
                return modulus;
            }

        };
    } catch (NumberFormatException e) {
        throw new ParseException("Invalid bgw.threshold value: '" + p.getProperty("bgw.threshold") + "'");
    }
}

From source file:com.asakusafw.yaess.tools.log.cli.Main.java

private static Map<String, String> parseArgs(CommandLine cmd, Option opt) {
    Properties props = cmd.getOptionProperties(opt.getOpt());
    Map<String, String> results = new TreeMap<>();
    for (Map.Entry<Object, Object> entry : props.entrySet()) {
        results.put((String) entry.getKey(), (String) entry.getValue());
    }//from w w w  .ja va 2 s.c o  m
    return results;
}

From source file:io.silverware.microservices.Boot.java

/**
 * Creates initial context pre-filled with system properties, command line arguments, custom property file and default property file.
 *
 * @param args Command line arguments.//  w ww  .ja va  2  s .  co m
 * @return Initial context pre-filled with system properties, command line arguments, custom property file and default property file.
 */
@SuppressWarnings("static-access")
private static Context getInitialContext(final String... args) {
    final Context context = new Context();
    final Map<String, Object> contextProperties = context.getProperties();
    final Options options = new Options();
    final CommandLineParser commandLineParser = new DefaultParser();

    System.getProperties().forEach((key, value) -> contextProperties.put((String) key, value));

    options.addOption(Option.builder(PROPERTY_LETTER).argName("property=value").numberOfArgs(2).valueSeparator()
            .desc("system properties").build());
    options.addOption(Option.builder(PROPERTY_FILE_LETTER).longOpt("properties").desc("Custom property file")
            .hasArg().argName("PROPERTY_FILE").build());

    try {
        final CommandLine commandLine = commandLineParser.parse(options, args);
        commandLine.getOptionProperties(PROPERTY_LETTER)
                .forEach((key, value) -> contextProperties.put((String) key, value));

        // process custom properties file
        if (commandLine.hasOption(PROPERTY_FILE_LETTER)) {
            final File propertiesFile = new File(commandLine.getOptionValue(PROPERTY_FILE_LETTER));
            if (propertiesFile.exists()) {
                final Properties props = loadProperties();
                props.forEach((key, val) -> contextProperties.putIfAbsent(key.toString(), val));
            } else {
                log.error("Specified property file %s does not exists.", propertiesFile.getAbsolutePath());
            }
        }
    } catch (ParseException pe) {
        log.error("Cannot parse arguments: ", pe);
        new HelpFormatter().printHelp("SilverWare usage:", options);
        System.exit(1);
    }

    // now add in default properties from silverware.properties on a classpath
    loadProperties().forEach((key, val) -> contextProperties.putIfAbsent(key.toString(), val));

    context.getProperties().put(Executor.SHUTDOWN_HOOK, "true");

    return context;
}

From source file:com.twitter.heron.apiserver.Runtime.java

private static String loadOverrides(CommandLine cmd) throws IOException {
    return ConfigUtils.createOverrideConfiguration(cmd.getOptionProperties(Flag.Property.name));
}

From source file:com.haulmont.yarg.console.ConsoleRunner.java

private static Map<String, Object> parseReportParams(CommandLine cmd, Report report) {
    if (cmd.hasOption(REPORT_PARAMETER)) {
        Map<String, Object> params = new HashMap<String, Object>();
        Properties optionProperties = cmd.getOptionProperties(REPORT_PARAMETER);
        for (ReportParameter reportParameter : report.getReportParameters()) {
            String paramValueStr = optionProperties.getProperty(reportParameter.getAlias());
            if (paramValueStr != null) {
                params.put(reportParameter.getAlias(),
                        converter.convertFromString(reportParameter.getParameterClass(), paramValueStr));
            }// w  ww.  j a v a  2 s  .  c o m
        }

        return params;
    } else {
        return Collections.emptyMap();
    }
}

From source file:com.asakusafw.yaess.tools.GenerateExecutionId.java

static Configuration parseConfiguration(String[] args) throws ParseException {
    assert args != null;
    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(OPTIONS, args);

    String batchId = cmd.getOptionValue(OPT_BATCH_ID.getOpt());
    String flowId = cmd.getOptionValue(OPT_FLOW_ID.getOpt());
    Properties arguments = cmd.getOptionProperties(OPT_ARGUMENT.getOpt());

    SortedMap<String, String> pairs = new TreeMap<>();
    for (Map.Entry<Object, Object> entry : arguments.entrySet()) {
        Object key = entry.getKey();
        Object value = entry.getValue();
        if (key instanceof String && value instanceof String) {
            pairs.put((String) key, (String) value);
        }//from   w  w  w  .j a  v a 2s . c o m
    }
    Configuration result = new Configuration();
    result.batchId = batchId;
    result.flowId = flowId;
    result.arguments = pairs;
    return result;
}