Java Code Examples for net.sourceforge.argparse4j.inf.Namespace#getList()
The following examples show how to use
net.sourceforge.argparse4j.inf.Namespace#getList() .
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: RenderCommand.java From dropwizard-java8 with Apache License 2.0 | 6 votes |
@Override protected void run(Bootstrap<HelloWorldConfiguration> bootstrap, Namespace namespace, HelloWorldConfiguration configuration) throws Exception { final Template template = configuration.buildTemplate(); if (namespace.getBoolean("include-default")) { LOGGER.info("DEFAULT => {}", template.render(Optional.<String>empty())); } for (String name : namespace.<String>getList("names")) { for (int i = 0; i < 1000; i++) { LOGGER.info("{} => {}", name, template.render(Optional.of(name))); Thread.sleep(1000); } } }
Example 2
Source File: Utils.java From helios with Apache License 2.0 | 6 votes |
public static List<HostSelector> parseHostSelectors(final Namespace namespace, final Argument arg) { final List<List<String>> args = namespace.getList(arg.getDest()); final List<HostSelector> ret = Lists.newArrayList(); if (args != null) { for (final List<String> group : args) { for (final String s : group) { final HostSelector hostSelector = HostSelector.parse(s); if (hostSelector == null) { throw new IllegalArgumentException(format("Bad host selector expression: '%s'", s)); } ret.add(hostSelector); } } } return ret; }
Example 3
Source File: JobWatchCommand.java From helios with Apache License 2.0 | 6 votes |
@Override int run(final Namespace options, final List<TargetAndClient> clients, final PrintStream out, final boolean json, final BufferedReader stdin) throws ExecutionException, InterruptedException, IOException { final boolean exact = options.getBoolean(exactArg.getDest()); final List<String> prefixes = options.getList(prefixesArg.getDest()); final String jobIdString = options.getString(jobsArg.getDest()); final List<ListenableFuture<Map<JobId, Job>>> jobIdFutures = Lists.newArrayList(); for (final TargetAndClient cc : clients) { jobIdFutures.add(cc.getClient().jobs(jobIdString)); } final Set<JobId> jobIds = Sets.newHashSet(); for (final ListenableFuture<Map<JobId, Job>> future : jobIdFutures) { jobIds.addAll(future.get().keySet()); } watchJobsOnHosts(out, exact, prefixes, jobIds, options.getInt(intervalArg.getDest()), clients); return 0; }
Example 4
Source File: Utils.java From helios with Apache License 2.0 | 6 votes |
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 5
Source File: JobStopCommand.java From helios with Apache License 2.0 | 6 votes |
@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.STOP) .setJobId(jobId) .build(); if (!json) { out.printf("Stopping %s on %s%n", jobId, hosts); } return Utils.setGoalOnHosts(client, out, json, hosts, deployment, options.getString(tokenArg.getDest())); }
Example 6
Source File: JobStartCommand.java From helios with Apache License 2.0 | 6 votes |
@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 7
Source File: SearchCommand.java From clue with Apache License 2.0 | 5 votes |
@Override public void execute(Namespace args, PrintStream out) throws Exception { IndexReader r = ctx.getIndexReader(); IndexSearcher searcher = new IndexSearcher(r); List<String> qlist = args.getList("query"); String qstring = CmdlineHelper.toString(qlist); Query q = null; try{ q = CmdlineHelper.toQuery(qlist, ctx.getQueryBuilder()); } catch(Exception e){ out.println("cannot parse query: "+e.getMessage()); return; } out.println("parsed query: " + q); int count = args.getInt("num"); long start = System.currentTimeMillis(); TopDocs td = searcher.search(q, count); long end = System.currentTimeMillis(); out.println("numhits: " + td.totalHits); out.println("time: " + (end-start) + "ms"); ScoreDoc[] docs = td.scoreDocs; for (ScoreDoc doc : docs){ out.println("doc: " + doc.doc + ", score: " + doc.score); } }
Example 8
Source File: CliMain.java From styx with Apache License 2.0 | 5 votes |
private Map<String, String> getEnvVars(Namespace namespace, Argument argument) { final List<String> args = namespace.getList(argument.getDest()); return args == null ? Collections.emptyMap() : args.stream() .map(s -> Splitter.on('=').splitToList(s)) .peek(kv -> Preconditions.checkArgument(kv.size() == 2)) .collect(toMap(kv -> kv.get(0), kv -> kv.get(1))); }
Example 9
Source File: ExplainCommand.java From clue with Apache License 2.0 | 5 votes |
@Override public void execute(Namespace args, PrintStream out) throws Exception { List<String> qlist = args.getList("query"); String qstring = CmdlineHelper.toString(qlist); List<Integer> docidList = args.getList("docs"); IndexReader r = ctx.getIndexReader(); IndexSearcher searcher = new IndexSearcher(r); Query q = null; try{ q = CmdlineHelper.toQuery(qlist, ctx.getQueryBuilder()); } catch(Exception e){ out.println("cannot parse query: "+e.getMessage()); return; } out.println("parsed query: "+q); for (Integer docid : docidList) { Explanation expl = searcher.explain(q, docid); out.println(expl); } out.flush(); }
Example 10
Source File: GetBoundsCommand.java From map-matching with Apache License 2.0 | 5 votes |
@Override public void run(Bootstrap bootstrap, Namespace args) { XmlMapper xmlMapper = new XmlMapper(); BBox bbox = BBox.createInverse(false); for (File gpxFile : args.<File>getList("gpx")) { try { Gpx gpx = xmlMapper.readValue(gpxFile, Gpx.class); for (Trk trk : gpx.trk) { List<Observation> inputGPXEntries = trk.getEntries(); for (Observation entry : inputGPXEntries) { bbox.update(entry.getPoint().getLat(), entry.getPoint().getLon()); } } } catch (IOException e) { throw new RuntimeException(e); } } System.out.println("bounds: " + bbox); // show download only for small areas if (bbox.maxLat - bbox.minLat < 0.1 && bbox.maxLon - bbox.minLon < 0.1) { double delta = 0.01; System.out.println("Get small areas via\n" + "wget -O extract.osm 'http://overpass-api.de/api/map?bbox=" + (bbox.minLon - delta) + "," + (bbox.minLat - delta) + "," + (bbox.maxLon + delta) + "," + (bbox.maxLat + delta) + "'"); } }
Example 11
Source File: AllTablesReportCommand.java From emodb with Apache License 2.0 | 5 votes |
@Override protected void run(Environment environment, Namespace namespace, EmoConfiguration configuration) throws Exception { String id = namespace.getString("id"); AllTablesReportOptions options = new AllTablesReportOptions(); options.setReadOnly(namespace.getBoolean("readOnly")); List<String> placements = namespace.getList("placements"); if (placements != null && !placements.isEmpty()) { options.setPlacements(ImmutableSet.copyOf(placements)); } Integer shardId = namespace.getInt("shard"); if (shardId != null) { options.setFromShardId(shardId); } String table = namespace.getString("table"); if (table != null) { options.setFromTableUuid(TableUuidFormat.decode(table)); } Injector injector = Guice.createInjector(new EmoModule(configuration, environment, EmoServiceMode.CLI_TOOL)); ContainerLifeCycle containerLifeCycle = new ContainerLifeCycle(); environment.lifecycle().attach(containerLifeCycle); containerLifeCycle.start(); try { AllTablesReportGenerator generator = injector.getInstance(AllTablesReportGenerator.class); AllTablesReportResult result = generator.runReport(id, options); System.out.println(result); } finally { containerLifeCycle.stop(); } }
Example 12
Source File: JobUndeployCommand.java From helios with Apache License 2.0 | 4 votes |
@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 boolean all = options.getBoolean(allArg.getDest()); final boolean yes = options.getBoolean(yesArg.getDest()); final List<String> hosts; if (all) { final JobStatus status = client.jobStatus(jobId).get(); hosts = ImmutableList.copyOf(status.getDeployments().keySet()); if (hosts.isEmpty()) { out.printf("%s is not currently deployed on any hosts.", jobId); return 0; } if (!yes) { out.printf("This will undeploy %s from %s%n", jobId, hosts); final boolean confirmed = Utils.userConfirmed(out, stdin); if (!confirmed) { return 1; } } } else { hosts = options.getList(hostsArg.getDest()); if (hosts.isEmpty()) { out.println("Please either specify a list of hosts or use the -a/--all flag."); return 1; } } if (!json) { out.printf("Undeploying %s from %s%n", jobId, hosts); } int code = 0; final HostResolver resolver = HostResolver.create(client); for (final String candidateHost : hosts) { final String host = resolver.resolveName(candidateHost); if (!json) { out.printf("%s: ", host); } final String token = options.getString(tokenArg.getDest()); final JobUndeployResponse response = client.undeploy(jobId, host, token).get(); if (response.getStatus() == JobUndeployResponse.Status.OK) { if (!json) { out.println("done"); } else { out.print(response.toJsonString()); } } else { if (!json) { out.println("failed: " + response); } else { out.print(response.toJsonString()); } code = -1; } } return code; }
Example 13
Source File: JobDeployCommand.java From helios with Apache License 2.0 | 4 votes |
@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 { final JobId jobId = job.getId(); final List<String> hosts = options.getList(hostsArg.getDest()); final Deployment deployment = Deployment.of(jobId, options.getBoolean(noStartArg.getDest()) ? STOP : START); if (!json) { out.printf("Deploying %s on %s%n", deployment, hosts); } int code = 0; final HostResolver resolver = HostResolver.create(client); final List<String> resolvedHosts = Lists.newArrayList(); for (final String candidateHost : hosts) { final String host = resolver.resolveName(candidateHost); resolvedHosts.add(host); if (!json) { out.printf("%s: ", host); } final String token = options.getString(tokenArg.getDest()); final JobDeployResponse result = client.deploy(deployment, host, token).get(); if (result.getStatus() == JobDeployResponse.Status.OK) { if (!json) { out.printf("done%n"); } else { out.print(result.toJsonString()); } } else { if (!json) { out.printf("failed: %s%n", result); } else { out.print(result.toJsonString()); } code = 1; } } if (code == 0 && options.getBoolean(watchArg.getDest())) { JobWatchCommand.watchJobsOnHosts(out, true, resolvedHosts, ImmutableList.of(jobId), options.getInt(intervalArg.getDest()), client); } return code; }
Example 14
Source File: AtomixAgent.java From atomix with Apache License 2.0 | 4 votes |
/** * Creates an Atomix configuration from the given namespace. * * @param namespace the namespace from which to create the configuration * @return the Atomix configuration for the given namespace */ static AtomixConfig createConfig(Namespace namespace) { final List<File> configFiles = namespace.getList("config"); final String memberId = namespace.getString("member"); final Address address = namespace.get("address"); final String host = namespace.getString("host"); final String rack = namespace.getString("rack"); final String zone = namespace.getString("zone"); final List<NodeConfig> bootstrap = namespace.getList("bootstrap"); final boolean multicastEnabled = namespace.getBoolean("multicast"); final String multicastGroup = namespace.get("multicast_group"); final Integer multicastPort = namespace.get("multicast_port"); System.setProperty("atomix.data", namespace.getString("data_dir")); // If a configuration was provided, merge the configuration's member information with the provided command line arguments. AtomixConfig config; if (configFiles != null && !configFiles.isEmpty()) { System.setProperty("atomix.config.resources", ""); config = Atomix.config(configFiles); } else { config = Atomix.config(); } if (memberId != null) { config.getClusterConfig().getNodeConfig().setId(memberId); } if (address != null) { config.getClusterConfig().getNodeConfig().setAddress(address); } if (host != null) { config.getClusterConfig().getNodeConfig().setHostId(host); } if (rack != null) { config.getClusterConfig().getNodeConfig().setRackId(rack); } if (zone != null) { config.getClusterConfig().getNodeConfig().setZoneId(zone); } if (bootstrap != null && !bootstrap.isEmpty()) { config.getClusterConfig().setDiscoveryConfig(new BootstrapDiscoveryConfig().setNodes(bootstrap)); } if (multicastEnabled) { config.getClusterConfig().getMulticastConfig().setEnabled(true); if (multicastGroup != null) { config.getClusterConfig().getMulticastConfig().setGroup(multicastGroup); } if (multicastPort != null) { config.getClusterConfig().getMulticastConfig().setPort(multicastPort); } if (bootstrap == null || bootstrap.isEmpty()) { config.getClusterConfig().setDiscoveryConfig(new MulticastDiscoveryConfig()); } } return config; }
Example 15
Source File: Main.java From signal-cli with GNU General Public License v3.0 | 4 votes |
private static Namespace parseArgs(String[] args) { ArgumentParser parser = ArgumentParsers.newFor("signal-cli") .build() .defaultHelp(true) .description("Commandline interface for Signal.") .version(BaseConfig.PROJECT_NAME + " " + BaseConfig.PROJECT_VERSION); parser.addArgument("-v", "--version") .help("Show package version.") .action(Arguments.version()); parser.addArgument("--config") .help("Set the path, where to store the config (Default: $XDG_DATA_HOME/signal-cli , $HOME/.local/share/signal-cli)."); MutuallyExclusiveGroup mut = parser.addMutuallyExclusiveGroup(); mut.addArgument("-u", "--username") .help("Specify your phone number, that will be used for verification."); mut.addArgument("--dbus") .help("Make request via user dbus.") .action(Arguments.storeTrue()); mut.addArgument("--dbus-system") .help("Make request via system dbus.") .action(Arguments.storeTrue()); Subparsers subparsers = parser.addSubparsers() .title("subcommands") .dest("command") .description("valid subcommands") .help("additional help"); final Map<String, Command> commands = Commands.getCommands(); for (Map.Entry<String, Command> entry : commands.entrySet()) { Subparser subparser = subparsers.addParser(entry.getKey()); entry.getValue().attachToSubparser(subparser); } Namespace ns; try { ns = parser.parseArgs(args); } catch (ArgumentParserException e) { parser.handleError(e); return null; } if ("link".equals(ns.getString("command"))) { if (ns.getString("username") != null) { parser.printUsage(); System.err.println("You cannot specify a username (phone number) when linking"); System.exit(2); } } else if (!ns.getBoolean("dbus") && !ns.getBoolean("dbus_system")) { if (ns.getString("username") == null) { parser.printUsage(); System.err.println("You need to specify a username (phone number)"); System.exit(2); } if (!PhoneNumberFormatter.isValidNumber(ns.getString("username"), null)) { System.err.println("Invalid username (phone number), make sure you include the country code."); System.exit(2); } } if (ns.getList("recipient") != null && !ns.getList("recipient").isEmpty() && ns.getString("group") != null) { System.err.println("You cannot specify recipients by phone number and groups at the same time"); System.exit(2); } return ns; }
Example 16
Source File: EmoServiceWithZK.java From emodb with Apache License 2.0 | 4 votes |
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 17
Source File: MatchCommand.java From map-matching with Apache License 2.0 | 4 votes |
@Override public void run(Bootstrap bootstrap, Namespace args) { GraphHopperConfig graphHopperConfiguration = new GraphHopperConfig(); String ghFolder = "graph-cache"; graphHopperConfiguration.putObject("graph.location", ghFolder); String vehicle = args.getString("vehicle"); if (Helper.isEmpty(vehicle)) vehicle = EncodingManager.create(new DefaultEncodedValueFactory(), new DefaultFlagEncoderFactory(), ghFolder).fetchEdgeEncoders().get(0).toString(); // Penalizing inner-link U-turns only works with fastest weighting, since // shortest weighting does not apply penalties to unfavored virtual edges. String weightingStr = "fastest"; Profile profile = new Profile(vehicle + "_profile").setVehicle(vehicle).setWeighting(weightingStr).setTurnCosts(false); graphHopperConfiguration.setProfiles(Collections.singletonList(profile)); GraphHopper hopper = new GraphHopperOSM().init(graphHopperConfiguration); System.out.println("loading graph from cache"); hopper.load(graphHopperConfiguration.getString("graph.location", ghFolder)); PMap hints = new PMap().putObject(MAX_VISITED_NODES, args.get("max_visited_nodes")); hints.putObject("profile", profile.getName()); MapMatching mapMatching = new MapMatching(hopper, hints); mapMatching.setTransitionProbabilityBeta(args.getDouble("transition_probability_beta")); mapMatching.setMeasurementErrorSigma(args.getInt("gps_accuracy")); StopWatch importSW = new StopWatch(); StopWatch matchSW = new StopWatch(); Translation tr = new TranslationMap().doImport().getWithFallBack(Helper.getLocale(args.getString("instructions"))); final boolean withRoute = !args.getString("instructions").isEmpty(); XmlMapper xmlMapper = new XmlMapper(); Weighting weighting = hopper.createWeighting(hopper.getProfiles().get(0), hints); for (File gpxFile : args.<File>getList("gpx")) { try { importSW.start(); Gpx gpx = xmlMapper.readValue(gpxFile, Gpx.class); if (gpx.trk == null) { throw new IllegalArgumentException("No tracks found in GPX document. Are you using waypoints or routes instead?"); } if (gpx.trk.size() > 1) { throw new IllegalArgumentException("GPX documents with multiple tracks not supported yet."); } List<Observation> measurements = gpx.trk.get(0).getEntries(); importSW.stop(); matchSW.start(); MatchResult mr = mapMatching.doWork(measurements); matchSW.stop(); System.out.println(gpxFile); System.out.println("\tmatches:\t" + mr.getEdgeMatches().size() + ", gps entries:" + measurements.size()); System.out.println("\tgpx length:\t" + (float) mr.getGpxEntriesLength() + " vs " + (float) mr.getMatchLength()); String outFile = gpxFile.getAbsolutePath() + ".res.gpx"; System.out.println("\texport results to:" + outFile); ResponsePath responsePath = new ResponsePath(); new PathMerger(mr.getGraph(), weighting). doWork(responsePath, Collections.singletonList(mr.getMergedPath()), hopper.getEncodingManager(), tr); if (responsePath.hasErrors()) { System.err.println("Problem with file " + gpxFile + ", " + responsePath.getErrors()); continue; } try (BufferedWriter writer = new BufferedWriter(new FileWriter(outFile))) { long time = gpx.trk.get(0).getStartTime() .map(Date::getTime) .orElse(System.currentTimeMillis()); writer.append(GpxFromInstructions.createGPX(responsePath.getInstructions(), gpx.trk.get(0).name != null ? gpx.trk.get(0).name : "", time, hopper.hasElevation(), withRoute, true, false, Constants.VERSION, tr)); } } catch (Exception ex) { importSW.stop(); matchSW.stop(); System.err.println("Problem with file " + gpxFile); ex.printStackTrace(System.err); } } System.out.println("gps import took:" + importSW.getSeconds() + "s, match took: " + matchSW.getSeconds()); }
Example 18
Source File: PurgeDatabusEventsCommand.java From emodb with Apache License 2.0 | 4 votes |
@Override protected void run(Bootstrap<EmoConfiguration> bootstrap, Namespace namespace, EmoConfiguration config) throws Exception { String host = namespace.getString("host"); int limit = namespace.getInt("limit"); String subscription = namespace.getString("subscription"); String apiKey = namespace.getString("api_key"); Set<String> tables = Sets.newHashSet(namespace.<String>getList("table")); List<String> keys = namespace.getList("key"); Set<String> keySet = keys != null ? Sets.newHashSet(keys) : null; System.out.println("Connecting..."); URI uri = URI.create(host).resolve(DatabusClient.SERVICE_PATH + "/_raw"); MetricRegistry metricRegistry = bootstrap.getMetricRegistry(); Client client = createDefaultJerseyClient(config.getHttpClientConfiguration(), metricRegistry, ""); QueueService databus = QueueServiceAuthenticator.proxied(new QueueClient(uri, new JerseyEmoClient(client))) .usingCredentials(apiKey); for (;;) { List<Message> events = databus.peek(subscription, 5000); List<String> ids = Lists.newArrayList(); for (Message event : events) { //noinspection unchecked Map<String, String> coord = (Map<String, String>) checkNotNull(event.getPayload()); String table = checkNotNull(coord.get("table")); String key = checkNotNull(coord.get("key")); if (tables.contains(table) && (keySet == null || keySet.contains(key))) { ids.add(event.getId()); if (--limit <= 0) { break; } } } if (ids.isEmpty()) { System.out.println("All matching events of the first " + events.size() + " have been purged."); break; } System.out.println("Purging " + ids.size() + " events..."); databus.acknowledge(subscription, ids); if (limit == 0) { System.out.println("Limit reached."); break; } } }