Java Code Examples for net.sourceforge.argparse4j.inf.Namespace#getString()

The following examples show how to use net.sourceforge.argparse4j.inf.Namespace#getString() . 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: 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 3
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 4
Source File: Main.java    From pcgen with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Initialize Main - must be called before any other getter can be used.
 *
 * @param argv the command line arguments to be parsed
 */
private static Namespace parseCommands(String[] argv)
{
	Namespace args = getParser().parseArgsOrFail(argv);

	if (args.getInt("verbose") > 0)
	{

		Logging.setCurrentLoggingLevel(Logging.DEBUG);
	}

	settingsDir = args.getString("settingsdir");
	campaignMode = args.getString("campaignmode");
	characterSheet = args.get("D");
	exportSheet = args.get("E");
	partyFile = args.get("p");
	characterFile = args.get("c");
	outputFile = args.get("o");
	startNameGen = args.get("name_generator");

	return args;
}
 
Example 5
Source File: HostRegisterCommand.java    From helios with Apache License 2.0 6 votes vote down vote up
@Override
int run(final Namespace options, final HeliosClient client, PrintStream out, final boolean json,
        final BufferedReader stdin)
    throws ExecutionException, InterruptedException {
  final String host = options.getString(hostArg.getDest());
  final String id = options.getString(idArg.getDest());

  if (isNullOrEmpty(host) || isNullOrEmpty(id)) {
    out.print("You must specify the hostname and id.");
    return 1;
  }

  out.printf("Registering host %s with id %s%n", host, id);

  int code = 0;
  out.printf("%s: ", host);
  final int result = client.registerHost(host, id).get();
  if (result == 200) {
    out.printf("done%n");
  } else {
    out.printf("failed: %s%n", result);
    code = 1;
  }

  return code;
}
 
Example 6
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 7
Source File: SharedVariablesCliActionHandler.java    From Repeat with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(Namespace namespace) {
	String action = namespace.getString("action");
	if (action.equals("get")) {
		handleGet(namespace);
	} else if (action.equals("set")) {
		handleSet(namespace);
	} else {
		LOGGER.log(Level.SEVERE, "Unknown task action " + action);
		CliExitCodes.UNKNOWN_ACTION.exit();
	}
}
 
Example 8
Source File: ConsumerRebalancer.java    From kafka-examples with Apache License 2.0 5 votes vote down vote up
private static RecordProcessor<Serializable, Serializable> getRecordProcessor(Namespace result) {
	
	String clientId = result.getString("clientId");
	String processorType = result.getString("processor");
	RecordProcessor<Serializable, Serializable> processor = null;
	if("sync".equals(processorType)) 
		processor = new SyncRecordProcessor<>(clientId);
	else
		processor = new AsyncRecordProcessor<>(clientId);
	return processor;
}
 
Example 9
Source File: AtomixAgent.java    From atomix with Apache License 2.0 5 votes vote down vote up
/**
 * Builds a REST service for the given Atomix instance from the given namespace.
 *
 * @param atomix the Atomix instance
 * @param namespace the namespace from which to build the service
 * @return the managed REST service
 */
private static ManagedRestService buildRestService(Atomix atomix, Namespace namespace) {
  final String httpHost = namespace.getString("http_host");
  final Integer httpPort = namespace.getInt("http_port");
  return RestService.builder()
      .withAtomix(atomix)
      .withAddress(Address.from(httpHost, httpPort))
      .build();
}
 
Example 10
Source File: TaskCliActionHandler.java    From Repeat with Apache License 2.0 5 votes vote down vote up
private void handleAdd(Namespace namespace) {
	TaskGroupMessage taskGroupMessage = getGroup(namespace);
	TaskMessage taskMessage = getTask(namespace);

	String filePath = namespace.getString("source_file");
	if (!Files.isRegularFile(Paths.get(filePath))) {
		LOGGER.severe("File '" + filePath + "' does not exist.");
		CliExitCodes.INVALID_ARGUMENTS.exit();
	}

	TaskAddMessage message = TaskAddMessage.of().setFilePath(filePath)
			.setTaskIdentifier(TaskIdentifier.of().setGroup(taskGroupMessage).setTask(taskMessage));
	sendRequest("/task/add", message);
}
 
Example 11
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 12
Source File: TaskCliActionHandler.java    From Repeat with Apache License 2.0 5 votes vote down vote up
private TaskMessage getTask(Namespace namespace) {
	String taskName = namespace.getString("name");
	if (taskName.isEmpty()) {
		LOGGER.warning("Task must be specified.");
		CliExitCodes.INVALID_ARGUMENTS.exit();
	}

	TaskMessage taskMessage = TaskMessage.of();
	if (NumberUtility.isNonNegativeInteger(taskName)) {
		taskMessage.setIndex(Integer.parseInt(taskName));
	} else {
		taskMessage.setName(taskName);
	}
	return taskMessage;
}
 
Example 13
Source File: EncryptConfigurationApiKeyCommand.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Override
protected void run(Bootstrap<EmoConfiguration> bootstrap, Namespace namespace, EmoConfiguration configuration)
        throws Exception {
    String apiKey = namespace.getString("api_key");
    String cluster = Objects.firstNonNull(namespace.getString("cluster"), configuration.getCluster());

    ApiKeyEncryption encryption = new ApiKeyEncryption(cluster);
    System.out.println(encryption.encrypt(apiKey));
}
 
Example 14
Source File: ItemSimilarityProcessor.java    From seldon-server with Apache License 2.0 5 votes vote down vote up
public ItemSimilarityProcessor(final Namespace ns)
{
	this.windowSecs = ns.getInt("window_secs");
	this.windowProcessed = ns.getInt("window_processed");
	this.outputTopic = ns.getString("output_topic");
	this.kafkaServers = ns.getString("kafka");
	System.out.println(ns);
	this.streamJaccard = new StreamingJaccardSimilarity(windowSecs, ns.getInt("hashes"), ns.getInt("min_activity"));
	//createOutputSimilaritiesTimer(ns);
}
 
Example 15
Source File: DeploymentGroupRemoveCommand.java    From helios with Apache License 2.0 5 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 RemoveDeploymentGroupResponse status = client.removeDeploymentGroup(name).get();

  if (status == null) {
    throw new RuntimeException("The Helios master could not remove the given deployment group.");
  }

  final boolean failed = status.getStatus() != RemoveDeploymentGroupResponse.Status.REMOVED;

  if (json) {
    out.println(status.toJsonString());
  } else {
    if (failed) {
      out.println(format("Failed to remove deployment-group %s, status: %s",
          name, status.getStatus()));
    } else {
      out.println(format("Deployment-group %s removed", name));
    }
  }

  return failed ? 1 : 0;
}
 
Example 16
Source File: UnregisterCassandraCommand.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Override
protected void run(Bootstrap<EmoConfiguration> bootstrap, Namespace namespace, EmoConfiguration configuration)
        throws Exception {
    String hostString = namespace.getString("host");
    String serviceName = namespace.getString("service");

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

    HostAndPort host = HostAndPort.fromString(hostString).withDefaultPort(9160);

    ServiceEndPoint endPoint = new ServiceEndPointBuilder()
            .withServiceName(serviceName)
            .withId(host.toString())
            .build();

    String dir = ZKPaths.makePath("ostrich", endPoint.getServiceName());
    String path = ZKPaths.makePath(dir, endPoint.getId());

    curator.newNamespaceAwareEnsurePath(dir).ensure(curator.getZookeeperClient());
    try {
        curator.delete().forPath(path);
        System.out.println("Deleted.");
    } catch (KeeperException.NoNodeException e) {
        System.out.println("Not found.");
    }

    curator.close();
}
 
Example 17
Source File: JobStatusCommand.java    From helios with Apache License 2.0 4 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 {
  final String jobIdString = options.getString(jobArg.getDest());
  final String hostPattern = options.getString(hostArg.getDest());
  final boolean full = options.getBoolean(fullArg.getDest());

  if (Strings.isNullOrEmpty(jobIdString) && Strings.isNullOrEmpty(hostPattern)) {
    if (!json) {
      out.printf("WARNING: listing status of all hosts in the cluster is a slow operation. "
                 + "Consider adding the --job and/or --host flag(s)!");
    }
  }

  final Set<JobId> jobIds = client.jobs(jobIdString, hostPattern).get().keySet();

  if (!Strings.isNullOrEmpty(jobIdString) && jobIds.isEmpty()) {
    if (json) {
      out.println("{ }");
    } else {
      out.printf("job id matcher \"%s\" matched no jobs%n", jobIdString);
    }
    return 1;
  }

  final Map<JobId, JobStatus> statuses = new TreeMap<>(client.jobStatuses(jobIds).get());

  if (json) {
    showJsonStatuses(out, hostPattern, jobIds, statuses);
    return 0;
  }

  final JobStatusTable table = jobStatusTable(out, full);

  final boolean noHostMatchedEver = showStatusesForHosts(hostPattern, jobIds, statuses,
      new HostStatusDisplayer() {
        @Override
        public void matchedStatus(JobStatus jobStatus, Iterable<String> matchingHosts,
                                  Map<String, TaskStatus> taskStatuses) {
          displayTask(full, table, jobStatus.getJob().getId(), jobStatus, taskStatuses,
              matchingHosts);
        }
      });

  if (noHostMatchedEver) {
    String domainsSwitchString = "";

    final List<String> domains = options.get("domains");
    if (domains.size() > 0) {
      domainsSwitchString = "-d " + Joiner.on(",").join(domains);
    }
    out.printf("There are no jobs deployed to hosts with the host pattern '%s'%n"
               + "Run 'helios %s hosts %s' to check your host exists and is up.%n",
        hostPattern, domainsSwitchString, hostPattern);
    return 1;
  }

  table.print();

  return 0;
}
 
Example 18
Source File: DeploymentGroupInspectCommand.java    From helios with Apache License 2.0 4 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 DeploymentGroup deploymentGroup = client.deploymentGroup(name).get();

  if (deploymentGroup == null) {
    if (json) {
      final Map<String, Object> output = Maps.newHashMap();
      output.put("status", "DEPLOYMENT_GROUP_NOT_FOUND");
      out.print(Json.asStringUnchecked(output));
    } else {
      out.printf("Unknown deployment group: %s%n", name);
    }
    return 1;
  }

  if (json) {
    out.println(Json.asPrettyStringUnchecked(deploymentGroup));
  } else {
    out.printf("Name: %s%n", deploymentGroup.getName());
    out.printf("Host selectors:%n");
    for (final HostSelector hostSelector : deploymentGroup.getHostSelectors()) {
      out.printf("  %s%n", hostSelector.toPrettyString());
    }
    out.printf("Job: %s%n", deploymentGroup.getJobId());

    if (deploymentGroup.getRollingUpdateReason() != null) {
      out.printf("Rolling update reason: %s%n", deploymentGroup.getRollingUpdateReason());
    }

    final RolloutOptions rolloutOptions = deploymentGroup.getRolloutOptions();
    if (rolloutOptions != null) {
      out.printf("Rollout options:%n");
      out.printf("  Migrate: %s%n", rolloutOptions.getMigrate());
      out.printf("  Overlap: %s%n", rolloutOptions.getOverlap());
      out.printf("  Parallelism: %d%n", rolloutOptions.getParallelism());
      out.printf("  Timeout: %d%n", rolloutOptions.getTimeout());
      if (!isNullOrEmpty(rolloutOptions.getToken())) {
        out.printf("  Token: %s%n", rolloutOptions.getToken());
      }
      out.printf("  Ignore failures: %b%n", rolloutOptions.getIgnoreFailures());
    }

  }

  return 0;
}
 
Example 19
Source File: MasterParser.java    From helios with Apache License 2.0 4 votes vote down vote up
public MasterParser(final String... args) throws ArgumentParserException {
  super("helios-master", "Spotify Helios Master", args);

  final Namespace options = getNamespace();
  final InetSocketAddress httpAddress = parseSocketAddress(options.getString(httpArg.getDest()));
  final InetSocketAddress adminAddress = parseSocketAddress(
      options.getString(adminArg.getDest()));

  String masterPassword = System.getenv(ZK_MASTER_PASSWORD_ENVVAR);
  if (masterPassword == null) {
    masterPassword = options.getString(zkAclMasterPassword.getDest());
  }

  final MasterConfig config = new MasterConfig()
      .setZooKeeperConnectString(getZooKeeperConnectString())
      .setZooKeeperSessionTimeoutMillis(getZooKeeperSessionTimeoutMillis())
      .setZooKeeperConnectionTimeoutMillis(getZooKeeperConnectionTimeoutMillis())
      .setZooKeeperClusterId(getZooKeeperClusterId())
      .setNoZooKeeperMasterRegistration(getNoZooKeeperRegistration())
      .setZooKeeperEnableAcls(getZooKeeperEnableAcls())
      .setZookeeperAclAgentUser(getZooKeeperAclAgentUser())
      .setZooKeeperAclAgentDigest(options.getString(zkAclAgentDigest.getDest()))
      .setZookeeperAclMasterUser(getZooKeeperAclMasterUser())
      .setZooKeeperAclMasterPassword(masterPassword)
      .setDomain(getDomain())
      .setName(getName())
      .setStatsdHostPort(getStatsdHostPort())
      .setInhibitMetrics(getInhibitMetrics())
      .setSentryDsn(getSentryDsn())
      .setServiceRegistryAddress(getServiceRegistryAddress())
      .setServiceRegistrarPlugin(getServiceRegistrarPlugin())
      .setAdminEndpoint(adminAddress)
      .setHttpEndpoint(httpAddress)
      .setKafkaBrokers(getKafkaBrokers())
      .setPubsubPrefixes(getPubsubPrefixes())
      .setStateDirectory(getStateDirectory())
      .setAgentReapingTimeout(options.getLong(agentReapingTimeout.getDest()))
      .setJobRetention(options.getLong(jobRetention.getDest()))
      .setFfwdConfig(ffwdConfig(options))
      .setWhitelistedCapabilities(ImmutableSet.copyOf(
          options.getList(whitelistedCapabilities.getDest())))
      .setJobHistoryReapingEnabled(options.getBoolean(jobHistoryReapingEnabled.getDest()));

  this.masterConfig = config;
}
 
Example 20
Source File: BasicConsumerExample.java    From kafka-examples with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
    ArgumentParser parser = argParser();

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

        /* parse args */
        String brokerList = res.getString("bootstrap.servers");
        String topic = res.getString("topic");
        String serializer = res.getString("serializer");


        Properties consumerConfig = new Properties();
        consumerConfig.put("group.id", "my-group");
        consumerConfig.put("bootstrap.servers",brokerList);
        consumerConfig.put("auto.offset.reset","earliest");
        consumerConfig.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.ByteArrayDeserializer");
        consumerConfig.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.ByteArrayDeserializer");

        KafkaConsumer<byte[], byte[]> consumer = new KafkaConsumer<>(consumerConfig);
        consumer.subscribe(Collections.singletonList(topic));

        while (true) {
            ConsumerRecords<byte[], byte[]> records = consumer.poll(1000);
            for (ConsumerRecord<byte[], byte[]> record : records) {
                System.out.printf("Received Message topic =%s, partition =%s, offset = %d, key = %s, value = %s\n", record.topic(), record.partition(), record.offset(), deserialize(record.key()), deserialize(record.value()));
            }

            consumer.commitSync();
        }

    } catch (ArgumentParserException e) {
        if (args.length == 0) {
            parser.printHelp();
            System.exit(0);
        } else {
            parser.handleError(e);
            System.exit(1);
        }
    }

}