Java Code Examples for net.sourceforge.argparse4j.inf.ArgumentParser#parseArgs()

The following examples show how to use net.sourceforge.argparse4j.inf.ArgumentParser#parseArgs() . 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: PredictionApi.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 IOException {
  ArgumentParser parser =
      ArgumentParsers.newFor("PredictionApi")
          .build()
          .defaultHelp(true)
          .description("Prediction API Operation");

  Subparsers subparsers = parser.addSubparsers().dest("command");

  Subparser predictParser = subparsers.addParser("predict");
  predictParser.addArgument("modelId");
  predictParser.addArgument("filePath");

  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("predict")) {
      predict(projectId, computeRegion, ns.getString("modelId"), ns.getString("filePath"));
    }
  } catch (ArgumentParserException e) {
    parser.handleError(e);
  }
}
 
Example 2
Source File: ComparePsnr.java    From graphicsfuzz with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws ArgumentParserException, FileNotFoundException {

    final ArgumentParser parser = ArgumentParsers.newArgumentParser("ComparePsnr")
        .defaultHelp(true)
        .description("Print PSNR for two images.");

    // Required arguments
    parser.addArgument("image1")
        .help("Path of first image.")
        .type(File.class);
    parser.addArgument("image2")
        .help("Path of second image.")
        .type(File.class);

    final Namespace ns = parser.parseArgs(args);

    System.out.println(ImageUtil.comparePsnr(ns.get("image1"), ns.get("image2")));

  }
 
Example 3
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 4
Source File: Generate.java    From graphicsfuzz with Apache License 2.0 6 votes vote down vote up
private static Namespace parse(String[] args) throws ArgumentParserException {
  ArgumentParser parser = ArgumentParsers.newArgumentParser("Generate")
      .defaultHelp(true)
      .description("Generate a shader.");

  // Required arguments
  parser.addArgument("reference-json")
      .help("Input reference shader json file.")
      .type(File.class);

  parser.addArgument("donors")
      .help("Path of folder of donor shaders.")
      .type(File.class);

  parser.addArgument("output")
      .help("Output shader job file file (.json).")
      .type(File.class);

  addGeneratorCommonArguments(parser);

  return parser.parseArgs(args);

}
 
Example 5
Source File: SimpleConsumer.java    From kafka-examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
	
	ArgumentParser parser = argParser();
	
	try {
		Namespace result = parser.parseArgs(args);
		Properties configs = getConsumerConfigs(result);
		List<TopicPartition> partitions = getPartitions(result.getString("topic.partitions"));

		final SimpleConsumer<Serializable, Serializable> consumer = new SimpleConsumer<>(configs, partitions);
		consumer.run();
		
		Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
			
			@Override
			public void run() {
				consumer.close();
			}
		}));
		
	} catch (ArgumentParserException e) {
		if(args.length == 0)
			parser.printHelp();
		else 
			parser.handleError(e);
		System.exit(0);
	}
}
 
Example 6
Source File: PredictionApi.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
static void argsHelper(String[] args) {
  ArgumentParser parser =
      ArgumentParsers.newFor("PredictionApi")
          .build()
          .defaultHelp(true)
          .description("Prediction API Operation");

  parser.addArgument("modelId").required(true);
  parser.addArgument("filePath").required(true);
  parser.addArgument("scoreThreshold").nargs("?").type(String.class).setDefault("");

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

  if (projectId == null || computeRegion == null) {
    System.out.println("Set `GOOGLE_CLOUD_PROJECT` and `REGION_NAME` as specified in the README");
    System.exit(-1);
  }

  try {
    Namespace ns = parser.parseArgs(args);
    predict(
        projectId,
        computeRegion,
        ns.getString("modelId"),
        ns.getString("filePath"),
        ns.getString("scoreThreshold"));
  } catch (ArgumentParserException e) {
    parser.handleError(e);
  }
}
 
Example 7
Source File: BasicConsumeLoop.java    From kafka-examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws InterruptedException {

		ArgumentParser parser = argParser();

		try {
			Namespace result = parser.parseArgs(args);
			List<String> topics = Arrays.asList(result.getString("topics").split(","));
			Properties configs = getConsumerConfigs(result);

			final BasicConsumeLoop<Serializable, Serializable> consumer = new BasicConsumeLoop<>(configs, topics);
			consumer.run();
			
			Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
				
				@Override
				public void run() {
					consumer.close();
				}
			}));
			
		} catch (ArgumentParserException e) {
			if(args.length == 0)
				parser.printHelp();
			else 
				parser.handleError(e);
			System.exit(0);
		}
	}
 
Example 8
Source File: CheckColorComponents.java    From graphicsfuzz with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws ArgumentParserException, IOException {

    final ArgumentParser parser = ArgumentParsers.newArgumentParser("CheckColorComponents")
        .defaultHelp(true)
        .description("Exits with code 0 if and only if the given image uses only the given color "
            + "components as the RGBA values of its pixels.");

    // Required arguments
    parser.addArgument("image")
        .help("Path to PNG image")
        .type(File.class);
    parser.addArgument("components")
        .type(Integer.class)
        .nargs("+")
        .help("Allowed components, each in range 0..255.");

    final Namespace ns = parser.parseArgs(args);

    final File image = ns.get("image");
    final List<Integer> components = ns.get("components");

    if (components.stream().anyMatch(item -> item < 0 || item > 255)) {
      System.err.println("Error: given component list " + components + " includes elements not "
          + "in range 0..255.");
    }

    if (!ImageColorComponents.containsOnlyGivenComponentValues(ImageIO.read(image), components)) {
      System.exit(1);
    }
  }
 
Example 9
Source File: Fragment2Compute.java    From graphicsfuzz with Apache License 2.0 5 votes vote down vote up
private static Namespace parse(String[] args) throws ArgumentParserException {
  ArgumentParser parser = ArgumentParsers.newArgumentParser("Fragment2Compute")
      .defaultHelp(true)
      .description("Turn a fragment shader into a compute shader.");

  // Required arguments
  parser.addArgument("fragment-json")
      .help("Input fragment shader JSON file.")
      .type(File.class);

  parser.addArgument("compute-json")
      .help("Output compute shader JSON file.")
      .type(File.class);

  parser.addArgument("--seed")
      .help("Seed (unsigned 64 bit long integer) for random number generator.")
      .type(String.class);

  parser.addArgument("--vulkan")
      .help("Put all uniforms in uniform blocks and generate "
          + "bindings; required for Vulkan compatibility. "
          + "Also enables vulkan-specific features and performs "
          + "shader validation as Vulkan target.")
      .action(Arguments.storeTrue());

  return parser.parseArgs(args);

}
 
Example 10
Source File: SynthesizeText.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public static void main(String... args) throws Exception {

    ArgumentParser parser =
        ArgumentParsers.newFor("SynthesizeText")
            .build()
            .defaultHelp(true)
            .description("Synthesize a text, text with audio effect profiles, or ssml.");

    MutuallyExclusiveGroup group = parser.addMutuallyExclusiveGroup().required(true);
    group
        .addArgument("--text")
        .help("The text file from which to synthesize speech.")
        .nargs("+")
        .metavar("TEXT", "EFFECTSPROFILE(optional)");
    group.addArgument("--ssml").help("The ssml file from which to synthesize speech.");

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

      if ((namespace.get("text") != null)) {
        if (namespace.getList("text").size() == 2) {
          synthesizeTextWithAudioProfile(
              namespace.getList("text").get(0).toString(),
              namespace.getList("text").get(1).toString());

        } else {
          synthesizeText(namespace.getString("text"));
        }

      } else {
        synthesizeSsml(namespace.getString("ssml"));
      }
    } catch (ArgumentParserException e) {
      parser.handleError(e);
    }
  }
 
Example 11
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 12
Source File: GlslGenerate.java    From graphicsfuzz with Apache License 2.0 5 votes vote down vote up
private static Namespace parse(String[] args) throws ArgumentParserException {
  ArgumentParser parser = ArgumentParsers.newArgumentParser("GlslGenerate")
      .defaultHelp(true)
      .description("Generate a set of shader families.");

  parser.addArgument("references")
      .help("Path to directory of reference shaders.")
      .type(File.class);

  parser.addArgument("donors")
      .help("Path to directory of donor shaders.")
      .type(File.class);

  parser.addArgument("num-variants")
      .help("Number of variants to be produced for each generated shader family.")
      .type(Integer.class);

  parser.addArgument("prefix")
      .help("String with which to prefix shader family names.")
      .type(String.class);

  parser.addArgument("output-dir")
      .help("Output directory for shader families.")
      .type(File.class);

  Generate.addGeneratorCommonArguments(parser);

  GenerateShaderFamily.addFamilyGenerationArguments(parser);

  return parser.parseArgs(args);

}
 
Example 13
Source File: RedosTester.java    From ReScue with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) {
	ArgumentParser parser = ArgumentParsers.newFor("ReScue").build();
	parser.defaultHelp(true);
	parser.description("ReScue is a tool to auto detect ReDoS vulnerabilities in regexes. (noSeeding, noIncubating and noPumping are mutex arguments, and only used for testing)");
	parser.addArgument("-q", "--quiet").action(Arguments.storeTrue()).help("Quiet mode, hide input tips.");
	parser.addArgument("-v", "--visual").action(Arguments.storeTrue()).help("Show e-NFA of the input regex.");
	parser.addArgument("-ml", "--maxLength").setDefault(128).help("Maximum string length.");
	parser.addArgument("-pz", "--popSize").setDefault(200).help("Maximum population size.");
	parser.addArgument("-g", "--generation").setDefault(200).help("Maximum generations.");
	parser.addArgument("-cp", "--crossPossibility").setDefault("10").help("The crossover possibility, default is 10, means 10%.");
	parser.addArgument("-mp", "--mutatePossibility").setDefault("10").help("The mutation possibility, default is 10, means 10%.");
	
	parser.addArgument("-ns", "--noSeeding").action(Arguments.storeTrue()).help("No seeding version of ReScue, only used for evaluation & testing.");
	parser.addArgument("-ni", "--noIncubating").action(Arguments.storeTrue()).help("No incubating version of ReScue, only used for evaluation & testing.");
	parser.addArgument("-np", "--noPumping").action(Arguments.storeTrue()).help("No pumping version of ReScue, only used for evaluation & testing.");
	
	if (args.length == 0) {
		parser.printHelp();
		return ;
	}
	
	Namespace ns = null;
	try {
		ns = parser.parseArgs(args);
		System.out.println(ns.getBoolean("unittest"));
	} catch (ArgumentParserException e1) {
		e1.printStackTrace();
		System.exit(-1);
	}
	
	if (ns.getBoolean("visual")){
		RedosTester.testView();
	} else {
		// These values are used for test
		int sl = 64; // The deprecated seed length
		int ml = 128;
		int pz = 200;
		int g = 200;
		int mp = 10;
		int cp = 5;
		
		// Read input arguments
		boolean quiet = ns.getBoolean("quiet");
		sl = ns.getInt("maxLength");
		ml = ns.getInt("maxLength");
		pz = ns.getInt("popSize");
		g = ns.getInt("generation");
		cp = ns.getInt("crossPossibility");
		mp = ns.getInt("mutatePossibility");
		
		if (!quiet) System.out.print("Input regex: ");
		
		Scanner input = new Scanner(System.in);
		String regex = input.hasNextLine() ? input.nextLine() : null;
		input.close();
		
		if (regex == null || regex.length() < 1) {
			System.out.println("Please check your regex.");
			return ;
		}
		
		RedosAttacker atk = null;
		if (ns.getBoolean("noSeeding")) atk = new GeneticAttackerWithoutSeeding(sl, ml, pz, g, (double)mp / (double)100, (double)cp / (double) 100);
		else if (ns.getBoolean("noIncubating")) atk = new GeneticAttackerWithoutIncubating(sl, ml, pz, g, (double)mp / (double)100, (double)cp / (double) 100);
		else if (ns.getBoolean("noPumping")) atk = new GeneticAttackerWithoutPumping(sl, ml, pz, g, (double)mp / (double)100, (double)cp / (double) 100);
		else atk = new GeneticAttacker(sl, ml, pz, g, (double)mp / (double)100, (double)cp / (double) 100);
		
		RedosTester rt = new RedosTester(atk, regex);
		rt.attackAndPrint();
	}
}
 
Example 14
Source File: ModelApi.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
public static void argsHelper(String[] args, PrintStream out) throws Exception {

    ArgumentParser parser =
        ArgumentParsers.newFor("ModelApi")
            .build()
            .defaultHelp(true)
            .description("Model API operations");
    Subparsers subparsers = parser.addSubparsers().dest("command");

    Subparser createModelParser = subparsers.addParser("create_model");
    createModelParser.addArgument("datasetId");
    createModelParser.addArgument("modelName");

    Subparser listModelParser = subparsers.addParser("list_models");
    listModelParser.addArgument("filter").nargs("?").setDefault("");

    Subparser getModelParser = subparsers.addParser("get_model");
    getModelParser.addArgument("modelId");

    Subparser listModelEvaluationsParser = subparsers.addParser("list_model_evaluations");
    listModelEvaluationsParser.addArgument("modelId");
    listModelEvaluationsParser.addArgument("filter").nargs("?").setDefault("");

    Subparser getModelEvaluationParser = subparsers.addParser("get_model_evaluation");
    getModelEvaluationParser.addArgument("modelId");
    getModelEvaluationParser.addArgument("modelEvaluationId");

    Subparser deleteModelParser = subparsers.addParser("delete_model");
    deleteModelParser.addArgument("modelId");

    Subparser getOperationStatusParser = subparsers.addParser("get_operation_status");
    getOperationStatusParser.addArgument("operationFullId");

    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("create_model")) {
        createModel(projectId, computeRegion, ns.getString("datasetId"), ns.getString("modelName"));
      }
      if (ns.get("command").equals("list_models")) {
        listModels(projectId, computeRegion, ns.getString("filter"));
      }
      if (ns.get("command").equals("get_model")) {
        getModel(projectId, computeRegion, ns.getString("modelId"));
      }
      if (ns.get("command").equals("list_model_evaluations")) {
        listModelEvaluations(
            projectId, computeRegion, ns.getString("modelId"), ns.getString("filter"));
      }
      if (ns.get("command").equals("get_model_evaluation")) {
        getModelEvaluation(
            projectId, computeRegion, ns.getString("modelId"), ns.getString("modelEvaluationId"));
      }
      if (ns.get("command").equals("delete_model")) {
        deleteModel(projectId, computeRegion, ns.getString("modelId"));
      }
      if (ns.get("command").equals("get_operation_status")) {
        getOperationStatus(ns.getString("operationFullId"));
      }
    } catch (ArgumentParserException e) {
      parser.handleError(e);
    }
  }
 
Example 15
Source File: ProductSetManagement.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
public static void argsHelper(String[] args, PrintStream out) throws Exception {
  ArgumentParser parser = ArgumentParsers.newFor("Product Set Management").build();
  Subparsers subparsers = parser.addSubparsers().dest("command");

  Subparser createProductSetParser = subparsers.addParser("create_product_set");
  createProductSetParser.addArgument("productSetId");
  createProductSetParser.addArgument("productSetDisplayName");

  subparsers.addParser("list_product_sets");

  Subparser getProductSetParser = subparsers.addParser("get_product_set");
  getProductSetParser.addArgument("productSetId");

  Subparser deleteProductSetParser = subparsers.addParser("delete_product_set");
  deleteProductSetParser.addArgument("productSetId");

  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("create_product_set")) {
      createProductSet(
          projectId,
          computeRegion,
          ns.getString("productSetId"),
          ns.getString("productSetDisplayName"));
    }
    if (ns.get("command").equals("list_product_sets")) {
      listProductSets(projectId, computeRegion);
    }
    if (ns.get("command").equals("get_product_set")) {
      getProductSet(projectId, computeRegion, ns.getString("productSetId"));
    }
    if (ns.get("command").equals("delete_product_set")) {
      deleteProductSet(projectId, computeRegion, ns.getString("productSetId"));
    }

  } catch (ArgumentParserException e) {
    parser.handleError(e);
  }
}
 
Example 16
Source File: RunShaderFamily.java    From graphicsfuzz with Apache License 2.0 4 votes vote down vote up
public static void mainHelper(
    String[] args,
    FuzzerServiceManager.Iface managerOverride)
    throws ShaderDispatchException, InterruptedException, IOException, ArgumentParserException {

  ArgumentParser parser = ArgumentParsers.newArgumentParser("RunShaderFamily")
      .defaultHelp(true)
      .description("Get images for all shaders in a shader set.");

  parser.addArgument("--verbose")
      .action(Arguments.storeTrue())
      .help("Verbose output.");

  parser.addArgument("--server")
      .help(
          "URL of server to use for sending get image requests.")
      .type(String.class);

  parser.addArgument("--worker")
      .help("The name of the worker used for get image requests. Used with --server.")
      .type(String.class);

  parser.addArgument("--output")
      .help("Output directory.")
      .setDefault(new File("."))
      .type(File.class);

  parser.addArgument("shader_family")
      .help("Shader family directory, or prefix of single shader job")
      .type(String.class);

  Namespace ns = parser.parseArgs(args);

  final boolean verbose = ns.get("verbose");
  final String shaderFamily = ns.get("shader_family");
  final String server = ns.get("server");
  final String worker = ns.get("worker");
  final File outputDir = ns.get("output");

  if (managerOverride != null && (server == null || worker == null)) {
    throw new ArgumentParserException(
        "Must supply server (dummy string) and worker name when executing in server process.",
        parser);
  }

  if (server != null) {
    if (worker == null) {
      throw new ArgumentParserException("With --server, must supply --worker name.", parser);
    }
  }

  IShaderDispatcher imageGenerator =
      server == null
          ? new LocalShaderDispatcher(false)
          : new RemoteShaderDispatcher(
              server + "/manageAPI",
              worker,
              managerOverride,
              new AtomicLong());

  FileUtils.forceMkdir(outputDir);

  if (!new File(shaderFamily).isDirectory()) {
    if (!new File(shaderFamily + ".json").exists()) {
      throw new ArgumentParserException(
          "Shader family must be a directory or the prefix of a single shader job.", parser);
    }
    // Special case: run get image on a single shader.
    runShader(outputDir, shaderFamily, imageGenerator,
        Optional.empty());
    return;
  }

  IShaderSet shaderSet = new LocalShaderSet(new File(shaderFamily));

  runShaderFamily(shaderSet, outputDir, imageGenerator);
}
 
Example 17
Source File: ProductManagement.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
public void argsHelper(String[] args, PrintStream out) throws Exception {
  ArgumentParser parser = ArgumentParsers.newFor("Product Management").build();
  Subparsers subparsers = parser.addSubparsers().dest("command");

  Subparser createProductParser = subparsers.addParser("create_product");
  createProductParser.addArgument("productId");
  createProductParser.addArgument("productDisplayName");
  createProductParser.addArgument("productCategory");
  createProductParser.addArgument("productDescription");
  createProductParser.addArgument("productLabels").nargs("?").setDefault("");

  subparsers.addParser("list_products");

  Subparser getProductParser = subparsers.addParser("get_product");
  getProductParser.addArgument("productId");

  Subparser updateProductLabelsParser = subparsers.addParser("update_product_labels");
  updateProductLabelsParser.addArgument("productId");
  updateProductLabelsParser.addArgument("productLabels");

  Subparser deleteProductParser = subparsers.addParser("delete_product");
  deleteProductParser.addArgument("productId");

  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("create_product")) {
      createProduct(
          projectId,
          computeRegion,
          ns.getString("productId"),
          ns.getString("productDisplayName"),
          ns.getString("productCategory"));
    }
    if (ns.get("command").equals("list_products")) {
      listProducts(projectId, computeRegion);
    }
    if (ns.get("command").equals("get_product")) {
      getProduct(projectId, computeRegion, ns.getString("productId"));
    }
    if (ns.get("command").equals("update_product_labels")) {
      updateProductLabels(
          projectId, computeRegion, ns.getString("productId"), ns.getString("productLabels"));
    }
    if (ns.get("command").equals("delete_product")) {
      deleteProduct(projectId, computeRegion, ns.getString("productId"));
    }
  } catch (ArgumentParserException e) {
    parser.handleError(e);
  }
}
 
Example 18
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);
        }
    }

}
 
Example 19
Source File: ProductSearch.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
public static void argsHelper(String[] args, PrintStream out) throws Exception {
  ArgumentParser parser = ArgumentParsers.newFor("Product Search").build();
  Subparsers subparsers = parser.addSubparsers().dest("command");

  Subparser getSimilarProductsFileParser = subparsers.addParser("get_similar_products_file");
  getSimilarProductsFileParser.addArgument("productSetId");
  getSimilarProductsFileParser.addArgument("productCategory");
  getSimilarProductsFileParser.addArgument("filePath");
  getSimilarProductsFileParser.addArgument("filter").nargs("?").setDefault("");

  Subparser getSimilarProductsGcsParser = subparsers.addParser("get_similar_products_gcs");
  getSimilarProductsGcsParser.addArgument("productSetId");
  getSimilarProductsGcsParser.addArgument("productCategory");
  getSimilarProductsGcsParser.addArgument("gcsUri");
  getSimilarProductsGcsParser.addArgument("filter").nargs("?").setDefault("");

  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("get_similar_products_file")) {
      getSimilarProductsFile(
          projectId,
          computeRegion,
          ns.getString("productSetId"),
          ns.getString("productCategory"),
          ns.getString("filePath"),
          ns.getString("filter"));
    } else if (ns.get("command").equals("get_similar_products_gcs")) {
      getSimilarProductsGcs(
          projectId,
          computeRegion,
          ns.getString("productSetId"),
          ns.getString("productCategory"),
          ns.getString("gcsUri"),
          ns.getString("filter"));
    }

  } catch (ArgumentParserException e) {
    parser.handleError(e);
  }
}
 
Example 20
Source File: MetaStep.java    From metastore with Apache License 2.0 4 votes vote down vote up
public MetaStep(String... args) throws IOException, ArgumentParserException {
  ArgumentParser parser = ArgumentParsers.newFor("metastep").build();

  Subparsers subparsers = parser.addSubparsers().help("sub-command help");

  Subparser submitParser = subparsers.addParser("publish").help("publish help");
  submitParser.setDefault("sub-command", "publish");
  submitParser.addArgument("--package_prefix").required(false);
  submitParser.addArgument("--package_name").required(false);
  submitParser.addArgument("--file_name").required(false);
  submitParser.addArgument("--descriptor_set").required(false);
  submitParser.addArgument("--profile").required(false);
  submitParser.addArgument("--workspace").required(false);
  submitParser.addArgument("--server").required(true);
  submitParser.addArgument("--registry").required(false);
  submitParser.addArgument("--tls").required(false);
  submitParser.addArgument("--tls_env").required(false);
  submitParser.addArgument("--source").required(false);
  submitParser.addArgument("--comment").required(true);
  submitParser.addArgument("--user").required(false);
  submitParser.addArgument("--email").required(false);
  submitParser.addArgument("--include").nargs("*").required(false);

  Subparser validateParser = subparsers.addParser("validate").help("validate help");
  validateParser.setDefault("sub-command", "validate");
  validateParser.addArgument("--package_prefix").required(false);
  validateParser.addArgument("--package_name").required(false);
  validateParser.addArgument("--file_name").required(false);
  validateParser.addArgument("--descriptor_set").required(false);
  validateParser.addArgument("--profile").required(false);
  validateParser.addArgument("--workspace").required(false);
  validateParser.addArgument("--server").required(true);
  validateParser.addArgument("--registry").required(false);
  validateParser.addArgument("--tls").required(false);
  validateParser.addArgument("--tls_env").required(false);
  validateParser.addArgument("--source").required(false);
  validateParser.addArgument("--include").nargs("*").required(false);
  res = parser.parseArgs(args);

  descriptorFile = File.createTempFile("descriptor", ".pb");

  String server = res.getString("server");
  String[] sp = server.split(":");
  String host = sp[0];
  int port = Integer.parseInt(sp[1]);

  String protoWorkspace = res.getString("workspace");
  if (protoWorkspace == null) {
    protoWorkspace = "/var/workspace";
  }
  workspace = new File(protoWorkspace);
  System.out.println("Workspace set to: " + workspace);

  protoIncludes = res.getList("include");
  if (protoIncludes == null) {
    protoIncludes = new ArrayList<>();
  }
  protoIncludes.add("/usr/include");

  if (res.get("source") != null) {
    includeSource = true;
  }

  String tlsFileName = res.getString("tls");
  if (tlsFileName == null) {
    String tlsEnv = res.getString("tls_env");
    if (tlsEnv != null) {
      File tlsFile = File.createTempFile("tls", ".pem");
      tlsFileName = tlsFile.getAbsolutePath();
      String tlsBase64 = System.getenv(tlsEnv);
      if (tlsBase64 == null) {
        throw new RuntimeException("No ENVIRONMENT_VARIABLE of name " + tlsEnv + " found.");
      }
      try (FileOutputStream writer = new FileOutputStream(tlsFile)) {
        writer.write(Base64.getDecoder().decode(tlsBase64));
      }
    }
  }

  NettyChannelBuilder channelBuilder = NettyChannelBuilder.forAddress(host, port);
  if (tlsFileName != null) {
    SslContext sslContext =
        GrpcSslContexts.forClient().trustManager(new File(tlsFileName)).build();

    channelBuilder.sslContext(sslContext).useTransportSecurity().build();
  } else {
    channelBuilder.usePlaintext();
  }
  schemaRegistry = RegistryGrpc.newBlockingStub(channelBuilder.build());
}