net.sourceforge.argparse4j.inf.Namespace Java Examples

The following examples show how to use net.sourceforge.argparse4j.inf.Namespace. 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: ImportCommand.java    From map-matching with Apache License 2.0 7 votes vote down vote up
@Override
public void run(Bootstrap<?> bootstrap, Namespace args) {
    GraphHopperConfig graphHopperConfiguration = new GraphHopperConfig();
    String vehicle = args.getString("vehicle");
    graphHopperConfiguration.putObject("graph.flag_encoders", vehicle);
    graphHopperConfiguration.putObject("datareader.file", args.getString("datasource"));
    graphHopperConfiguration.putObject("graph.location", "graph-cache");
    // always using fastest weighting, see comment in MatchCommand
    String weightingStr = "fastest";
    List<Profile> profiles = new ArrayList<>();
    for (String v : vehicle.split(",")) {
        v = v.trim();
        profiles.add(new Profile(v + "_profile").setVehicle(v).setWeighting(weightingStr));
    }
    graphHopperConfiguration.setProfiles(profiles);
    GraphHopper hopper = new GraphHopperOSM().init(graphHopperConfiguration);
    hopper.importOrLoad();
}
 
Example #2
Source File: ListDevicesCommand.java    From signal-cli with GNU General Public License v3.0 6 votes vote down vote up
@Override
public int handleCommand(final Namespace ns, final Manager m) {
    if (!m.isRegistered()) {
        System.err.println("User is not registered.");
        return 1;
    }
    try {
        List<DeviceInfo> devices = m.getLinkedDevices();
        for (DeviceInfo d : devices) {
            System.out.println("Device " + d.getId() + (d.getId() == m.getDeviceId() ? " (this device)" : "") + ":");
            System.out.println(" Name: " + d.getName());
            System.out.println(" Created: " + DateUtils.formatTimestamp(d.getCreated()));
            System.out.println(" Last seen: " + DateUtils.formatTimestamp(d.getLastSeen()));
        }
        return 0;
    } catch (IOException e) {
        e.printStackTrace();
        return 3;
    }
}
 
Example #3
Source File: ListIdentitiesCommand.java    From signal-cli with GNU General Public License v3.0 6 votes vote down vote up
@Override
public int handleCommand(final Namespace ns, final Manager m) {
    if (!m.isRegistered()) {
        System.err.println("User is not registered.");
        return 1;
    }
    if (ns.get("number") == null) {
        for (JsonIdentityKeyStore.Identity identity : m.getIdentities()) {
            printIdentityFingerprint(m, identity);
        }
    } else {
        String number = ns.getString("number");
        try {
            List<JsonIdentityKeyStore.Identity> identities = m.getIdentities(number);
            for (JsonIdentityKeyStore.Identity id : identities) {
                printIdentityFingerprint(m, id);
            }
        } catch (InvalidNumberException e) {
            System.out.println("Invalid number: " + e.getMessage());
        }
    }
    return 0;
}
 
Example #4
Source File: ImportProductSets.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
public static void argsHelper(String[] args, PrintStream out) throws Exception {
  ArgumentParser parser = ArgumentParsers.newFor("Import Product Sets").build();
  Subparsers subparsers = parser.addSubparsers().dest("command");

  Subparser importProductSetsParser = subparsers.addParser("import_product_sets");
  importProductSetsParser.addArgument("gcsUri");

  String projectId = System.getenv("PROJECT_ID");
  String computeRegion = System.getenv("REGION_NAME");

  Namespace ns = null;
  try {
    ns = parser.parseArgs(args);
    if (ns.get("command").equals("import_product_sets")) {
      importProductSets(projectId, computeRegion, ns.getString("gcsUri"));
    }
  } catch (ArgumentParserException e) {
    parser.handleError(e);
  }
}
 
Example #5
Source File: DeleteCommand.java    From clue with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(Namespace args, PrintStream out) throws Exception {
  Query q = null;
  String qstring = args.getString("query");
  try{
    q = luceneContext.getQueryBuilder().build(qstring);
  }
  catch(Exception e){
    out.println("cannot parse query: "+e.getMessage());
    return;
  }
  
  out.println("parsed query: " + q);
  
  if (q != null){
    IndexWriter writer = luceneContext.getIndexWriter();
    if (writer != null) {
      writer.deleteDocuments(q);
      writer.commit();
      luceneContext.refreshReader();
    }
    else {
      out.println("unable to open writer, index is in readonly mode");
    }
  }
}
 
Example #6
Source File: Main.java    From lancoder with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Function to avoid bloated try-catch
 *
 * @param clazz
 *            The class of the container to instantiate
 * @param parsed
 * @return The container
 * @throws UnavailableException
 */
private static Container getContainerInstance(Class<? extends Container> clazz, Namespace argsNamespace) {
	try {
		Container container = clazz.getConstructor().newInstance();
		ConfigManager<? extends Config> manager = getConfigManager(container, argsNamespace);

		container.setConfigManager(manager);
		manager.load();

		return container;
	} catch (Exception e) {
		// java pls
		e.printStackTrace();
		throw new UnsupportedClassVersionError(e.getMessage());
	}
}
 
Example #7
Source File: Game.java    From minecraft-world-downloader with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Parse arguments from the commandline.
 */
public static void init(Namespace args) {
    Game.args = args;

    Coordinate2D.setOffset(-args.getInt("center-x"), -args.getInt("center-z"));

    Palette.setMaskBedrock(args.getBoolean("mask-bedrock"));

    initFolders();

    WorldManager.setSaveServiceVariables(args.getBoolean("mark-new-chunks"), args.getBoolean("write-chunks"));
    if (args.getBoolean("gui")) {
        GuiManager.showGui();
    }
    enableWorldGen = args.getBoolean("enable-world-gen");

    versionHandler = VersionHandler.createVersionHandler();
}
 
Example #8
Source File: JobStartCommand.java    From helios with Apache License 2.0 6 votes vote down vote up
@Override
protected int runWithJob(final Namespace options, final HeliosClient client,
                         final PrintStream out, final boolean json, final Job job,
                         final BufferedReader stdin)
    throws ExecutionException, InterruptedException, IOException {
  final JobId jobId = job.getId();
  final List<String> hosts = options.getList(hostsArg.getDest());

  final Deployment deployment = new Deployment.Builder()
      .setGoal(Goal.START)
      .setJobId(jobId)
      .build();

  if (!json) {
    out.printf("Starting %s on %s%n", jobId, hosts);
  }

  return Utils.setGoalOnHosts(client, out, json, hosts, deployment,
      options.getString(tokenArg.getDest()));
}
 
Example #9
Source File: AbstractFlywayCommand.java    From dropwizard-flyway with Apache License 2.0 6 votes vote down vote up
@Override
protected void run(final Bootstrap<T> bootstrap, final Namespace namespace, final T configuration) throws Exception {
    final PooledDataSourceFactory datasourceFactory = databaseConfiguration.getDataSourceFactory(configuration);
    final FlywayFactory flywayFactory = flywayConfiguration.getFlywayFactory(configuration);

    // Give subclasses an option to set additional config flags for flyway.
    setAdditionalOptions(flywayFactory, namespace);
    
    final Flyway flyway = flywayFactory.build(datasourceFactory.build(bootstrap.getMetricRegistry(), "Flyway"));

    try {
        run(namespace, flyway);
    } catch (FlywayException e) {
        LOG.error("Error while running database command", e);
        throw e;
    }
}
 
Example #10
Source File: CreateKeyspacesCommand.java    From emodb with Apache License 2.0 6 votes vote down vote up
@Override
protected void run(Bootstrap<EmoConfiguration> bootstrap, Namespace namespace, EmoConfiguration emoConfiguration)
        throws Exception {
    _outputOnly = namespace.getBoolean("output_only");

    DdlConfiguration ddlConfiguration = parseDdlConfiguration(toFile(namespace.getString("config-ddl")));
    CuratorFramework curator = null;
    if (!_outputOnly) {
        curator = emoConfiguration.getZooKeeperConfiguration().newCurator();
        curator.start();
    }
    try {
        createKeyspacesIfNecessary(emoConfiguration, ddlConfiguration, curator, bootstrap.getMetricRegistry());

    } finally {
        Closeables.close(curator, true);
    }
}
 
Example #11
Source File: IndexTrimCommand.java    From clue with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(Namespace args, PrintStream out) throws Exception {
  int trimPercent = args.getInt("percent");
  
  if (trimPercent < 0 || trimPercent > 100) {
    throw new IllegalArgumentException("invalid percent: " + trimPercent);
  }
  
  IndexWriter writer = ctx.getIndexWriter();    
  if (writer != null) {      
    IndexReader reader = ctx.getIndexReader();
    
    writer.deleteDocuments(buildDeleteQuery(trimPercent, reader.maxDoc()));
    writer.commit();      
    ctx.refreshReader();
    reader = ctx.getIndexReader();
    out.println("trim successful, index now contains: " + reader.numDocs() + " docs.");
  }
  else {
    out.println("unable to open writer, index is in readonly mode");
  }
}
 
Example #12
Source File: ListCassandraCommand.java    From emodb with Apache License 2.0 6 votes vote down vote up
@Override
protected void run(Bootstrap<EmoConfiguration> bootstrap, Namespace namespace, EmoConfiguration configuration)
        throws Exception {
    String serviceName = namespace.getString("service");

    CuratorFramework curator = configuration.getZooKeeperConfiguration().newCurator();
    curator.start();

    ZooKeeperHostDiscovery hostDiscovery = new ZooKeeperHostDiscovery(curator, serviceName, bootstrap.getMetricRegistry());

    for (ServiceEndPoint endPoint : hostDiscovery.getHosts()) {
        System.out.println(endPoint.getId());
    }

    hostDiscovery.close();
    curator.close();
}
 
Example #13
Source File: PrettyPrint.java    From graphicsfuzz with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {

    try {
      Namespace ns = parse(args);
      long startTime = System.currentTimeMillis();
      TranslationUnit tu = ParseHelper.parse(new File(ns.getString("shader")));
      long endTime = System.currentTimeMillis();

      if (ns.getBoolean("add_braces")) {
        tu = AddBraces.transform(tu);
      }

      prettyPrintShader(ns, tu);

      System.err.println("Time for parsing: " + (endTime - startTime));
    } catch (Throwable exception) {
      exception.printStackTrace();
      System.exit(1);
    }

  }
 
Example #14
Source File: Main.java    From graphicsfuzz with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
  ArgumentParser parser = ArgumentParsers.newArgumentParser("Fuzzer server")
      .defaultHelp(true);

  parser.addArgument("--port")
      .help("Port on which to listen.")
      .setDefault(8080)
      .type(Integer.class);

  try {
    Namespace ns = parser.parseArgs(args);

    ShaderJobFileOperations fileOps = new ShaderJobFileOperations();

    new FuzzerServer(ns.get("port"), fileOps).start();

  } catch (ArgumentParserException ex) {
    ex.getParser().handleError(ex);
  }
}
 
Example #15
Source File: DeploymentGroupStopCommand.java    From helios with Apache License 2.0 6 votes vote down vote up
@Override
int run(final Namespace options, final HeliosClient client, final PrintStream out,
        final boolean json, final BufferedReader stdin)
    throws ExecutionException, InterruptedException, IOException {
  final String name = options.getString(nameArg.getDest());

  final int status = client.stopDeploymentGroup(name).get();

  // TODO(staffam): Support json output

  if (status == Response.Status.NO_CONTENT.getStatusCode()) {
    out.println(format("Deployment-group %s stopped", name));
    return 0;
  } else if (status == Response.Status.NOT_FOUND.getStatusCode()) {
    out.println(format("Deployment-group %s not found", name));
    return 1;
  } else {
    out.println(format("Failed to stop deployment-group %s. Status: %d",
        name, status));
    return 1;
  }
}
 
Example #16
Source File: AtomixAgent.java    From atomix with Apache License 2.0 6 votes vote down vote up
/**
 * Parses unknown arguments, returning an argparse4j namespace.
 *
 * @param unknown the unknown arguments to parse
 * @return the namespace
 * --foo.bar baz --bar.baz foo bar --foo.bar.baz bang
 */
static Namespace parseUnknown(List<String> unknown) {
  Map<String, Object> attrs = new HashMap<>();
  String attr = null;
  for (String arg : unknown) {
    if (arg.startsWith("--")) {
      int splitIndex = arg.indexOf('=');
      if (splitIndex == -1) {
        attr = arg.substring(2);
      } else {
        attrs.put(arg.substring(2, splitIndex), arg.substring(splitIndex + 1));
        attr = null;
      }
    } else if (attr != null) {
      attrs.put(attr, arg);
      attr = null;
    }
  }
  return new Namespace(attrs);
}
 
Example #17
Source File: FragmentShaderToShaderJob.java    From graphicsfuzz with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {

    try {
      Namespace ns = parse(args);
      long startTime = System.currentTimeMillis();
      final TranslationUnit tu = ParseHelper.parse(new File(ns.getString("shader")));
      long endTime = System.currentTimeMillis();
      System.err.println("Time for parsing: " + (endTime - startTime));

      startTime = System.currentTimeMillis();
      final ShaderJob result = createShaderJob(tu, new RandomWrapper(ArgsUtil.getSeedArgument(ns)));
      endTime = System.currentTimeMillis();
      System.err.println("Time for creating shader job: " + (endTime - startTime));

      final ShaderJobFileOperations fileOperations = new ShaderJobFileOperations();
      fileOperations.writeShaderJobFile(result, new File(ns.getString("output")));
    } catch (Throwable exception) {
      exception.printStackTrace();
      System.exit(1);
    }
  }
 
Example #18
Source File: SharedVariablesCliActionHandler.java    From Repeat with Apache License 2.0 6 votes vote down vote up
private void handleSet(Namespace namespace) {
	String space = namespace.getString("namespace");
	String variable = namespace.getString("variable");
	if (variable.isEmpty()) {
		LOGGER.warning("Variable name must be provided.");
		CliExitCodes.INVALID_ARGUMENTS.exit();
	}
	String value = namespace.getString("value");
	if (value.isEmpty()) {
		LOGGER.warning("Variable value must be provided.");
		CliExitCodes.INVALID_ARGUMENTS.exit();
	}

	SharedVariablesSetMessage message = SharedVariablesSetMessage.of().setNamespace(space).setVariable(variable).setValue(value);
	sendRequest("/var/set", message);
}
 
Example #19
Source File: Utils.java    From helios with Apache License 2.0 6 votes vote down vote up
public static Map<String, String> argToStringMap(final Namespace namespace, final Argument arg) {
  final List<List<String>> args = namespace.getList(arg.getDest());
  final Map<String, String> map = Maps.newHashMap();
  if (args != null) {
    for (final List<String> group : args) {
      for (final String s : group) {
        final String[] parts = s.split("=", 2);
        if (parts.length != 2) {
          throw new IllegalArgumentException("Bad " + arg.textualName() + " value: " + s);
        }
        map.put(parts[0], parts[1]);
      }
    }
  }
  return map;
}
 
Example #20
Source File: DiffyCliProcessor.java    From jolt with Apache License 2.0 5 votes vote down vote up
/**
 * Process the Diffy Subcommand
 *
 * @param ns Namespace which contains parsed commandline arguments
 * @return true if no differences are found, false if a difference is found or an error occurs
 */
@Override
public boolean process( Namespace ns ) {
    boolean suppressOutput = ns.getBoolean( "s" );

    Object jsonObject1 = JoltCliUtilities.createJsonObjectFromFile( (File) ns.get( "filePath1" ), suppressOutput );
    File file = ns.get( "filePath2" );
    Object jsonObject2 = JoltCliUtilities.readJsonInput( file, suppressOutput );

    Diffy diffy;
    if ( ns.getBoolean( "a" ) ) {
        diffy = new ArrayOrderObliviousDiffy();
    } else {
        diffy = new Diffy();
    }
    Diffy.Result result = diffy.diff( jsonObject1, jsonObject2 );

    if ( result.isEmpty() ) {
        JoltCliUtilities.printToStandardOut( "Diffy found no differences", suppressOutput );
        return true;
    } else {
        try {
            JoltCliUtilities.printToStandardOut( "Differences found. Input #1 contained this:\n" +
                    JsonUtils.toPrettyJsonString( result.expected ) + "\n" +
                    "Input #2 contained this:\n" +
                    JsonUtils.toPrettyJsonString( result.actual ), suppressOutput );

        }
        catch ( Exception e ) {
            JoltCliUtilities.printToStandardOut( "Differences found, but diffy encountered an error while writing the result.", suppressOutput );
        }
        return false;
    }
}
 
Example #21
Source File: DbValidateCommand.java    From dropwizard-flyway with Apache License 2.0 5 votes vote down vote up
@Override
protected void setAdditionalOptions(FlywayFactory flywayFactory, Namespace namespace) {
    final Boolean outOfOrder = namespace.getBoolean(OUT_OF_ORDER);
    final Boolean cleanOnValidationError = namespace.getBoolean(CLEAN_ON_VALIDATION_ERROR);
    
    if (outOfOrder != null) {
        flywayFactory.setOutOfOrder(outOfOrder);
    }

    if (cleanOnValidationError != null) {
        flywayFactory.setCleanOnValidationError(cleanOnValidationError);
    }

}
 
Example #22
Source File: SetPinCommand.java    From signal-cli with GNU General Public License v3.0 5 votes vote down vote up
@Override
public int handleCommand(final Namespace ns, final Manager m) {
    if (!m.isRegistered()) {
        System.err.println("User is not registered.");
        return 1;
    }
    try {
        String registrationLockPin = ns.getString("registrationLockPin");
        m.setRegistrationLockPin(Optional.of(registrationLockPin));
        return 0;
    } catch (IOException e) {
        System.err.println("Set pin error: " + e.getMessage());
        return 3;
    }
}
 
Example #23
Source File: TaskCliActionHandler.java    From Repeat with Apache License 2.0 5 votes vote down vote up
private TaskGroupMessage getGroup(Namespace namespace) {
	String groupName = namespace.getString("group");
	TaskGroupMessage taskGroupMessage = TaskGroupMessage.of();
	if (NumberUtility.isNonNegativeInteger(groupName)) {
		taskGroupMessage.setIndex(Integer.parseInt(groupName));
	} else {
		taskGroupMessage.setName(groupName);
	}
	return taskGroupMessage;
}
 
Example #24
Source File: HelpCommand.java    From clue with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(Namespace args, PrintStream out) {
  Collection<ClueCommand> commands = ctx.getCommandRegistry().getAvailableCommands();
  
  for (ClueCommand cmd : commands){
    out.println(cmd.getName()+" - " + cmd.help());
  }
  out.flush();
}
 
Example #25
Source File: GenerateAesKeyCommand.java    From keywhiz with Apache License 2.0 5 votes vote down vote up
@Override public void run(Bootstrap<?> bootstrap, Namespace namespace) throws Exception {
  char[] password = namespace.getString("storepass").toCharArray();
  Path destination = Paths.get(namespace.get("keystore"));
  int keySize = namespace.getInt("keysize");
  String alias = namespace.getString("alias");

  generate(password, destination, keySize, alias, SecureRandom.getInstanceStrong());
  System.out.println(format("Generated a %d-bit AES key at %s with alias %s", keySize,
      destination.toAbsolutePath(), alias));
}
 
Example #26
Source File: GuiceyAppRule.java    From dropwizard-guicey with MIT License 5 votes vote down vote up
private void startCommand(final Bootstrap<C> bootstrap) throws Exception {
    command = new TestCommand<>(application);

    final ImmutableMap.Builder<String, Object> file = ImmutableMap.builder();
    if (!Strings.isNullOrEmpty(configPath)) {
        file.put("file", configPath);
    }
    final Namespace namespace = new Namespace(file.build());

    command.run(bootstrap, namespace);
}
 
Example #27
Source File: InitializeCommand.java    From robe with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
@UnitOfWork
protected void run(Environment environment, Namespace namespace, T configuration) throws Exception {
    LOGGER.info("Initialize Starting...");
    LOGGER.info("Starting to create initial data.");
    execute(configuration);
    if (!"TEST".equals(System.getProperty("env"))) {
        System.exit(0);
    }
}
 
Example #28
Source File: Utils.java    From helios with Apache License 2.0 5 votes vote down vote up
/**
 * Return the timeout value to use, first checking the argument provided to the CLI invocation,
 * then an environment variable, then the default value.
 */
private static int parseTimeout(
    final Namespace options, final String dest,
    final String envVarName, final int defaultValue) {

  if (options.getInt(dest) != null) {
    return options.getInt(dest);
  }
  if (System.getenv(envVarName) != null) {
    // if this is not an integer then let it blow up
    return Integer.parseInt(System.getenv(envVarName));
  }
  return defaultValue;
}
 
Example #29
Source File: RemovePinCommand.java    From signal-cli with GNU General Public License v3.0 5 votes vote down vote up
@Override
public int handleCommand(final Namespace ns, final Manager m) {
    if (!m.isRegistered()) {
        System.err.println("User is not registered.");
        return 1;
    }
    try {
        m.setRegistrationLockPin(Optional.absent());
        return 0;
    } catch (IOException e) {
        System.err.println("Remove pin error: " + e.getMessage());
        return 3;
    }
}
 
Example #30
Source File: CliMain.java    From styx with Apache License 2.0 5 votes vote down vote up
private CliMain(
    StyxCliParser parser,
    Namespace namespace,
    String apiHost,
    CliOutput cliOutput,
    CliContext cliContext,
    boolean debug) {
  this.parser = Objects.requireNonNull(parser);
  this.namespace = Objects.requireNonNull(namespace);
  this.apiHost = Objects.requireNonNull(apiHost);
  this.cliOutput = Objects.requireNonNull(cliOutput);
  this.cliContext = Objects.requireNonNull(cliContext);
  this.debug = debug;
}