Java Code Examples for net.sourceforge.argparse4j.ArgumentParsers#newArgumentParser()

The following examples show how to use net.sourceforge.argparse4j.ArgumentParsers#newArgumentParser() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HiveScriptGenerator.java    From emodb with Apache License 2.0 6 votes vote down vote up
protected void doMain(String args[]) {
    ArgumentParser parser = ArgumentParsers.newArgumentParser(getClass().getSimpleName());

    parser.addArgument("--out")
            .dest("out")
            .metavar("FILE")
            .nargs("?")
            .setDefault("stdout")
            .help("Writes the script to the output file; default is stdout");

    addArguments(parser);

    Namespace namespace = parser.parseArgsOrFail(args);
    String file = namespace.getString("out");

    try (PrintStream out = file.equals("stdout") ? System.out : new PrintStream(new FileOutputStream(file))) {
        generateScript(namespace, out);
    } catch (IOException e) {
        System.err.println("Script generation failed");
        e.printStackTrace(System.err);
    }
}
 
Example 2
Source File: JobListCommandTest.java    From helios with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
  // use a real, dummy Subparser impl to avoid having to mock out every single call
  final ArgumentParser parser = ArgumentParsers.newArgumentParser("test");
  final Subparser subparser = parser.addSubparsers().addParser("list");
  command = new JobListCommand(subparser);

  when(client.jobs()).thenReturn(Futures.immediateFuture(jobs));

  final Map<JobId, JobStatus> statuses = new HashMap<>();
  for (final JobId jobId : jobs.keySet()) {
    // pretend each job is deployed
    final JobStatus status = JobStatus.newBuilder()
        .setDeployments(ImmutableMap.of("host", Deployment.of(jobId, Goal.START)))
        .build();
    statuses.put(jobId, status);
  }

  when(client.jobStatuses(jobs.keySet())).thenReturn(Futures.immediateFuture(statuses));
}
 
Example 3
Source File: JobCreateCommandTest.java    From helios with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
  // use a real, dummy Subparser impl to avoid having to mock out every single call
  final ArgumentParser parser = ArgumentParsers.newArgumentParser("test");
  final Subparser subparser = parser.addSubparsers().addParser("create");

  final Supplier<Map<String, String>> envVarSupplier = new Supplier<Map<String, String>>() {
    @Override
    public Map<String, String> get() {
      return ImmutableMap.copyOf(envVars);
    }
  };

  command = new JobCreateCommand(subparser, envVarSupplier);

  when(client.createJob(argThat(matchesName(JOB_NAME)))).thenReturn(immediateFuture(
      new CreateJobResponse(CreateJobResponse.Status.OK,
          Collections.<String>emptyList(),
          "12345")
  ));
}
 
Example 4
Source File: HostListCommandTest.java    From helios with Apache License 2.0 5 votes vote down vote up
private int runCommand(String... commandArgs)
    throws ExecutionException, InterruptedException, ArgumentParserException {

  final String[] args = new String[1 + commandArgs.length];
  args[0] = "hosts";
  System.arraycopy(commandArgs, 0, args, 1, commandArgs.length);

  // use a real, dummy Subparser impl to avoid having to mock out every single call
  final ArgumentParser parser = ArgumentParsers.newArgumentParser("test");
  final Subparser subparser = parser.addSubparsers().addParser("hosts");
  final HostListCommand command = new HostListCommand(subparser);

  final Namespace options = parser.parseArgs(args);
  return command.run(options, client, out, false, null);
}
 
Example 5
Source File: JoltCli.java    From jolt with Apache License 2.0 5 votes vote down vote up
/**
 * The logic for running DiffyTool has been captured in a helper method that returns a boolean to facilitate unit testing.
 * Since System.exit terminates the JVM it would not be practical to test the main method.
 *
 * @param args the arguments from the command line input
 * @return true if two inputs were read with no differences, false if differences were found or an error was encountered
 */
protected static boolean runJolt( String[] args ) {
    ArgumentParser parser = ArgumentParsers.newArgumentParser( "jolt" );
    Subparsers subparsers = parser.addSubparsers().help( "transform: given a Jolt transform spec, runs the specified transforms on the input data.\n" +
            "diffy: diff two JSON documents.\n" +
            "sort: sort a JSON document alphabetically for human readability." );

    for ( Map.Entry<String, JoltCliProcessor> entry : JOLT_CLI_PROCESSOR_MAP.entrySet() ) {
        entry.getValue().intializeSubCommand( subparsers );
    }

    Namespace ns;
    try {
        ns = parser.parseArgs( args );
    } catch ( ArgumentParserException e ) {
        parser.handleError( e );
        return false;
    }

    JoltCliProcessor joltToolProcessor = JOLT_CLI_PROCESSOR_MAP.get( args[0] );
    if ( joltToolProcessor != null ) {
        return joltToolProcessor.process( ns );
    } else {
        // TODO: error message, print usage. although I don't think it will ever get to this point.
        return false;
    }
}
 
Example 6
Source File: TPCHGenerator.java    From flink-perf with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	// Parse and handle arguments
	ArgumentParser ap = ArgumentParsers.newArgumentParser("Distributed TPCH");
	ap.defaultHelp(true);
	ap.addArgument("-s", "--scale").setDefault(1.0).help("TPC H Scale (final Size in GB)").type(Double.class);
	ap.addArgument("-p","--parallelism").setDefault(1).help("Parallelism for program").type(Integer.class);
	ap.addArgument("-e", "--extension").setDefault(".csv").help("File extension for generated files");
	ap.addArgument("-o", "--outpath").setDefault("/tmp/").help("Output directory");
	
	Namespace ns = null;
       try {
           ns = ap.parseArgs(args);
       } catch (ArgumentParserException e) {
           ap.handleError(e);
           System.exit(1);
       }
	final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
	env.setParallelism(ns.getInt("parallelism"));
	DistributedTPCH gen = new DistributedTPCH(env);
	gen.setScale(ns.getDouble("scale"));

	String base = ns.getString("outpath");
	String ext = ns.getString("extension");
	gen.generateParts().writeAsFormattedText(base + "parts" + ext, new TpchEntityFormatter());
	gen.generateLineItems().writeAsFormattedText(base + "lineitems" + ext, new TpchEntityFormatter());
	gen.generateOrders().writeAsFormattedText(base + "orders" + ext, new TpchEntityFormatter());
	gen.generateSuppliers().writeAsFormattedText(base + "suppliers" + ext, new TpchEntityFormatter());
	gen.generatePartSuppliers().writeAsFormattedText(base + "partsuppliers" + ext, new TpchEntityFormatter());
	gen.generateRegions().writeAsFormattedText(base + "regions" + ext, new TpchEntityFormatter());
	gen.generateNations().writeAsFormattedText(base + "nations" + ext, new TpchEntityFormatter());
	gen.generateCustomers().writeAsFormattedText(base + "customers" + ext, new TpchEntityFormatter());

	env.execute("Distributed TPCH Generator, Scale = "+gen.getScale());
}
 
Example 7
Source File: Params.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
static ArgumentParser getParser() {
    final ArgumentParser parser = ArgumentParsers.newArgumentParser("jar_file_name");
    parser.description("Validation Tool for Yang Models")
        .formatUsage();

    parser.addArgumentGroup("Required arguments")
        .addArgument("--yang-source-dir")
        .type(File.class)
        .required(true)
        .help("directory containing yang models which will be parsed")
        .dest("yang-source-dir")
        .metavar("");

    return parser;
}
 
Example 8
Source File: Arguments.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
private static ArgumentParser initializeArgumentParser() {
    final ArgumentParser parser = ArgumentParsers.newArgumentParser(PROGRAM_NAME);

    parser.addArgument("-i", toArgName(ACTIVE_CONNECTION_PARAMETER)).type(Boolean.class)
            .setDefault(false).help(ACTIVE_CONNECTION_HELP);
    parser.addArgument("-ho", toArgName(HOLD_TIMER_PARAMETER)).type(Integer.class)
            .setDefault(INITIAL_HOLD_TIME).help(INITIAL_HOLD_TIME_HELP);
    parser.addArgument("-pr", toArgName(PREFIXES_PARAMETER)).type(Integer.class)
            .setDefault(0).help(PREFIXES_PARAMETER_HELP);
    parser.addArgument("-sc", toArgName(SPEAKERS_COUNT)).type(Integer.class)
            .setDefault(0).help(SPEAKERS_COUNT_HELP);
    parser.addArgument("-mp", toArgName(MULTIPATH_PARAMETER)).type(Boolean.class)
            .setDefault(false).help(MULTIPATH_PARAMETER_HELP);
    parser.addArgument("-" + AS_PARAMETER, toArgName(AS_PARAMETER))
            .type((ArgumentTypeTool<AsNumber>) as -> new AsNumber(Uint32.valueOf(as)))
            .setDefault(new AsNumber(Uint32.valueOf(64496))).help(AS_PARAMETER_HELP);
    parser.addArgument("-ec", toArgName(EXTENDED_COMMUNITIES_PARAMETER))
            .type((ArgumentTypeTool<List<String>>) extComInput ->
                    Arrays.asList(extComInput.split(","))).setDefault(Collections.emptyList())
            .help(EXTENDED_COMMUNITIES_PARAMETER_HELP);
    parser.addArgument("-ll", toArgName(LOG_LEVEL))
            .type((ArgumentTypeTool<Level>) Level::toLevel).setDefault(Level.INFO).help("log levels");
    parser.addArgument("-ra", toArgName(REMOTE_ADDRESS_PARAMETER))
            .type((ArgumentTypeTool<List<InetSocketAddress>>) input ->
                    InetSocketAddressUtil.parseAddresses(input, DEFAULT_REMOTE_PORT))
            .setDefault(Collections.singletonList(REMOTE_ADDRESS))
            .help(REMOTE_ADDRESS_PARAMETER_HELP);
    parser.addArgument("-la", toArgName(LOCAL_ADDRESS_PARAMETER))
            .type((ArgumentTypeTool<InetSocketAddress>) input ->
                    getInetSocketAddress(input, DEFAULT_LOCAL_PORT))
            .setDefault(LOCAL_ADDRESS).help(LOCAL_ADDRESS_PARAMETER_HELP);
    return parser;
}
 
Example 9
Source File: BmpMockArguments.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
private static ArgumentParser initializeArgumentParser() {
    final ArgumentParser parser = ArgumentParsers.newArgumentParser(PROGRAM_NAME);
    parser.addArgument(toArgName(ROUTERS_COUNT_DST))
            .type(Integer.class)
            .setDefault(1);
    parser.addArgument(toArgName(PEERS_COUNT_DST))
            .type(Integer.class)
            .setDefault(0);
    parser.addArgument(toArgName(PRE_POLICY_ROUTES_COUNT_DST))
            .type(Integer.class)
            .setDefault(0);
    parser.addArgument(toArgName(POST_POLICY_ROUTES_COUNT_DST))
            .type(Integer.class).setDefault(0);
    parser.addArgument(toArgName(PASSIVE_MODE_DST))
            .action(Arguments.storeTrue());
    parser.addArgument(toArgName(LOCAL_ADDRESS_DST))
            .type((parser13, arg, value) -> getInetSocketAddress(value, DEFAULT_LOCAL_PORT))
            .setDefault(LOCAL_ADDRESS);
    parser.addArgument("-ra", toArgName(REMOTE_ADDRESS_DST))
            .type((ArgumentTypeTool<List<InetSocketAddress>>) input ->
                    InetSocketAddressUtil.parseAddresses(input, DEFAULT_REMOTE_PORT))
            .setDefault(Collections.singletonList(REMOTE_ADDRESS));
    parser.addArgument(toArgName(LOG_LEVEL_DST))
            .type((parser1, arg, value) -> Level.toLevel(value))
            .setDefault(Level.INFO);
    return parser;
}
 
Example 10
Source File: JobStatusCommandTest.java    From helios with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  // use a real, dummy Subparser impl to avoid having to mock out every single call
  final ArgumentParser parser = ArgumentParsers.newArgumentParser("test");
  final Subparser subparser = parser.addSubparsers().addParser("list");
  command = new JobStatusCommand(subparser);

  // defaults for flags
  when(options.getString("job")).thenReturn(null);
  when(options.getString("host")).thenReturn("");
}
 
Example 11
Source File: DeploymentGroupInspectCommandTest.java    From helios with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  // use a real, dummy Subparser impl to avoid having to mock out every single call
  final ArgumentParser parser = ArgumentParsers.newArgumentParser("test");
  final Subparser subparser = parser.addSubparsers().addParser("inspect");

  command = new DeploymentGroupInspectCommand(subparser);

  when(client.deploymentGroup(NAME)).thenReturn(Futures.immediateFuture(DEPLOYMENT_GROUP));
  final ListenableFuture<DeploymentGroup> nullFuture = Futures.immediateFuture(null);
  when(client.deploymentGroup(NON_EXISTENT_NAME)).thenReturn(nullFuture);
}
 
Example 12
Source File: AbstractBinary.java    From rsync4j with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Configures and returns the commandline parser.
 *
 * @return		the parser
 */
protected ArgumentParser getParser() {
  ArgumentParser 	parser;

  parser = ArgumentParsers.newArgumentParser(getClass().getName());
  parser.description(description());
  parser.addArgument("--output-commandline")
    .setDefault(false)
    .dest("outputCommandline")
    .help("output the command-line generated for the wrapped binary")
    .action(Arguments.storeTrue());

  return parser;
}
 
Example 13
Source File: DeploymentGroupStatusCommandTest.java    From helios with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  // use a real, dummy Subparser impl to avoid having to mock out every single call
  final ArgumentParser parser = ArgumentParsers.newArgumentParser("test");
  final Subparser subparser = parser.addSubparsers().addParser("status");

  command = new DeploymentGroupStatusCommand(subparser);
}
 
Example 14
Source File: JobInspectCommandTest.java    From helios with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  // use a real, dummy Subparser impl to avoid having to mock out every single call
  final ArgumentParser parser = ArgumentParsers.newArgumentParser("test");
  final Subparser subparser = parser.addSubparsers().addParser("inspect");
  command = new JobInspectCommand(subparser, TimeZone.getTimeZone("UTC"));

  when(client.jobs(JOB_NAME_VERSION)).thenReturn(Futures.immediateFuture(jobs));
}
 
Example 15
Source File: HostRegisterCommandTest.java    From helios with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  // use a real, dummy Subparser impl to avoid having to mock out every single call
  final ArgumentParser parser = ArgumentParsers.newArgumentParser("test");
  final Subparser subparser = parser.addSubparsers().addParser("register");
  command = new HostRegisterCommand(subparser);
}
 
Example 16
Source File: EmoService.java    From emodb with Apache License 2.0 5 votes vote down vote up
public static void main(String... args) throws Exception {

        ArgumentParser parser = ArgumentParsers.newArgumentParser("emoparser");
        parser.addArgument("server").required(true).help("server");
        parser.addArgument("emo-config").required(true).help("config.yaml");
        parser.addArgument("config-ddl").required(true).help("config-ddl.yaml");

        // Get the path to config-ddl
        String[] first3Args = (String[]) ArrayUtils.subarray(args, 0, Math.min(args.length, 3));
        Namespace result = parser.parseArgs(first3Args);

        // Remove config-ddl arg
        new EmoService(result.getString("config-ddl"), new File(result.getString("emo-config")))
                .run((String[]) ArrayUtils.remove(args, 2));
    }
 
Example 17
Source File: EmoServiceWithZK.java    From emodb with Apache License 2.0 4 votes vote down vote up
public static void main(String... args) throws Exception {

        // Remove all nulls and empty strings from the argument list.  This can happen as if the maven command
        // starts the service with no permission YAML files.
        args = Arrays.stream(args).filter(arg -> !Strings.isNullOrEmpty(arg)).toArray(String[]::new);

        // Start cassandra if necessary (cassandra.yaml is provided)
        ArgumentParser parser = ArgumentParsers.newArgumentParser("java -jar emodb-web-local*.jar");
        parser.addArgument("server").required(true).help("server");
        parser.addArgument("emo-config").required(true).help("config.yaml - EmoDB's config file");
        parser.addArgument("emo-config-ddl").required(true).help("config-ddl.yaml - EmoDB's cassandra schema file");
        parser.addArgument("cassandra-yaml").nargs("?").help("cassandra.yaml - Cassandra configuration file to start an" +
                " in memory embedded Cassandra.");
        parser.addArgument("-z","--zookeeper").dest("zookeeper").action(Arguments.storeTrue()).help("Starts zookeeper");
        parser.addArgument("-p","--permissions-yaml").dest("permissions").nargs("*").help("Permissions file(s)");

        // Get the path to cassandraYaml or if zookeeper is available
        Namespace result = parser.parseArgs(args);
        String cassandraYaml = result.getString("cassandra-yaml");
        boolean startZk = result.getBoolean("zookeeper");
        String emoConfigYaml = result.getString("emo-config");
        List<String> permissionsYamls = result.getList("permissions");

        String[] emoServiceArgs = args;

        // Start ZooKeeper
        TestingServer zooKeeperServer = null;
        if (startZk) {
            zooKeeperServer = isLocalZooKeeperRunning() ? null : startLocalZooKeeper();
            emoServiceArgs = (String[]) ArrayUtils.removeElement(args, "-z");
            emoServiceArgs = (String[]) ArrayUtils.removeElement(emoServiceArgs, "--zookeeper");

        }
        boolean success = false;


        if (cassandraYaml != null) {
            // Replace $DIR$ so we can correctly specify location during runtime
            File templateFile = new File(cassandraYaml);
            String baseFile = Files.toString(templateFile, Charset.defaultCharset());
            // Get the jar location
            String path = EmoServiceWithZK.class.getProtectionDomain().getCodeSource().getLocation().getPath();
            String parentDir = new File(path).getParent();
            String newFile = baseFile.replace("$DATADIR$", new File(parentDir, "data").getAbsolutePath());
            newFile = newFile.replace("$COMMITDIR$", new File(parentDir, "commitlog").getAbsolutePath());
            newFile = newFile.replace("$CACHEDIR$", new File(parentDir, "saved_caches").getAbsolutePath());
            File newYamlFile = new File(templateFile.getParent(), "emo-cassandra.yaml");
            Files.write(newFile, newYamlFile, Charset.defaultCharset());

            startLocalCassandra(newYamlFile.getAbsolutePath());
            emoServiceArgs = (String[]) ArrayUtils.removeElement(emoServiceArgs, cassandraYaml);
        }

        // If permissions files were configured remove them from the argument list
        int permissionsIndex = Math.max(ArrayUtils.indexOf(emoServiceArgs, "-p"), ArrayUtils.indexOf(emoServiceArgs, "--permissions-yaml"));
        if (permissionsIndex >= 0) {
            int permissionsArgCount = 1 + permissionsYamls.size();
            for (int i=0; i < permissionsArgCount; i++) {
                emoServiceArgs = (String[]) ArrayUtils.remove(emoServiceArgs, permissionsIndex);
            }
        }

        try {
            EmoService.main(emoServiceArgs);
            success = true;

            setPermissionsFromFiles(permissionsYamls, emoConfigYaml);
        } catch (Throwable t) {
            t.printStackTrace();
        } finally {
            // The main web server command returns immediately--don't stop ZooKeeper/Cassandra in that case.
            if (zooKeeperServer != null && !(success && args.length > 0 && "server".equals(args[0]))) {
                zooKeeperServer.stop();
                service.shutdown();
            }
        }
    }
 
Example 18
Source File: ComplianceToolModeTest.java    From verify-service-provider with MIT License 4 votes vote down vote up
private Subparser createParser() {
    final ArgumentParser p = ArgumentParsers.newArgumentParser("Usage:", false);
    return p.addSubparsers().addParser("development", false);
}