List of usage examples for org.apache.commons.cli DefaultParser DefaultParser
DefaultParser
From source file:com.khubla.jvmbasic.jvmbasicc.JVMBasic.java
/** * start here//from w w w . j a v a2 s . c o m * <p> * -file src\test\resources\bas\easy\print.bas -verbose true * </p> */ public static void main(String[] args) { try { System.out.println("khubla.com jvmBASIC Compiler"); /* * options */ final Options options = new Options(); Option oo = Option.builder().argName(OUTPUT_OPTION).longOpt(OUTPUT_OPTION).type(String.class).hasArg() .required(false).desc("target directory to output to").build(); options.addOption(oo); oo = Option.builder().argName(FILE_OPTION).longOpt(FILE_OPTION).type(String.class).hasArg() .required(true).desc("file to compile").build(); options.addOption(oo); oo = Option.builder().argName(VERBOSE_OPTION).longOpt(VERBOSE_OPTION).type(String.class).hasArg() .required(false).desc("verbose output").build(); options.addOption(oo); /* * parse */ final CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (final Exception e) { e.printStackTrace(); final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("posix", options); System.exit(0); } /* * verbose output? */ final Boolean verbose = Boolean.parseBoolean(cmd.getOptionValue(VERBOSE_OPTION)); /* * get the file */ final String filename = cmd.getOptionValue(FILE_OPTION); final String outputDirectory = cmd.getOptionValue(OUTPUT_OPTION); if (null != filename) { /* * filename */ final String basFileName = System.getProperty("user.dir") + "/" + filename; final File fl = new File(basFileName); if (true == fl.exists()) { /* * show the filename */ System.out.println("Compiling: " + fl.getCanonicalFile()); /* * compiler */ final JVMBasicCompiler jvmBasicCompiler = new JVMBasicCompiler(); /* * compile */ jvmBasicCompiler.compileToClassfile(basFileName, null, outputDirectory, verbose, true, true); } else { throw new Exception("Unable to find: '" + basFileName + "'"); } } else { throw new Exception("File was not supplied"); } } catch (final Exception e) { e.printStackTrace(); } }
From source file:com.dattack.dbping.cli.PingCli.java
/** * The <code>main</code> method. * * @param args//from w w w .j a v a 2s.c o m * the program arguments */ public static void main(final String[] args) { final Options options = createOptions(); try { final CommandLineParser parser = new DefaultParser(); final CommandLine cmd = parser.parse(options, args); final String[] filenames = cmd.getOptionValues(FILE_OPTION); final String[] taskNames = cmd.getOptionValues(TASK_NAME_OPTION); HashSet<String> hs = null; if (taskNames != null) { hs = new HashSet<>(Arrays.asList(taskNames)); } final PingEngine ping = new PingEngine(); ping.execute(filenames, hs); } catch (@SuppressWarnings("unused") final ParseException e) { showUsage(options); } catch (final ConfigurationException | DattackParserException e) { System.err.println(e.getMessage()); } }
From source file:br.com.riselabs.cotonet.Main.java
/** * @param args/*from www . j av a 2s.c o m*/ * @throws EmptyContentException * @throws IOException * @throws NullPointerException * @throws InvalidNumberOfTagsException */ public static void main(String[] args) { CommandLineParser parser = new DefaultParser(); Options options = new Options(); options.addOption(Option.builder("c").longOpt("chunkBased").desc( "c - build a conflict chunk-based network with the developers that in fact conflits with each other." + " Additionally to the c argument the user should provide a path. This path should have" + " a file containig the repository's URL of the target systems.") .hasArg().build()); options.addOption(Option.builder("cf").longOpt("chunkBasedFullGraph") .desc("cf - like c, build a conflict chunk-based network adding all developers involved in " + "identified chunk conflicts. Additionally to the cf argument the user should provide a path. " + "This path should have a file containig the repository's URL of the target systems.") .hasArg().build()); options.addOption(Option.builder("f").longOpt("fileBase").desc( " f - build a conflict file-based network. In other others all developers that contribute to some" + " conflict at file level should be part of this network. This network is based on network provides " + "by cf, adding edges between developers of different chunks. Additionally to the f argument the" + " user should provide a path. This path should have afile containig the repository's URL of " + "the target systems.") .hasArg().build()); /* * options.addOption( Option.builder("rw").longOpt("rewrite-aux"). * desc("Rewrite auxilary files (e.g., *.conf, *.sh) " + "_WITHOUT_ " + * "the recreation of the merge scenarios based tags.").hasArg(false). * build()); * * options.addOption( Option.builder("rwt").longOpt("rewrite-tagfile"). * desc("Rewrite auxilary files (e.g., *.conf, *.sh) " + "_INCLUDING_ " * + "the recreation of the merge scenarios based tags.").hasArg(false). * build()); */ options.addOption("h", "help", false, "Print this help page"); File reposListFile = null; Boolean skipCloneAndNetworks = false; try { CommandLine cmd = parser.parse(options, args); // user is looking for help if (cmd.hasOption("h")) { new HelpFormatter().printHelp("java ", options); System.exit(0); } /* "c", "cf", and "f" are the three available options * "c" builds the chunk-based network with developers that contribute to the conflict * "cf" builds the chunk-based network with developers that contribute to the conflict and developers * that are part of the chunk, but don't contribute to the conflict * "f" builds the file-based network with developers that contribute to the chunk into a target file */ else if (cmd.hasOption("c") || cmd.hasOption("cf") || cmd.hasOption("f")) { String urlsFilePath = null; NetworkType type; if (cmd.hasOption("c")) { urlsFilePath = cmd.getOptionValue("c"); type = NetworkType.CHUNK_BASED; } else if (cmd.hasOption("cf")) { urlsFilePath = cmd.getOptionValue("cf"); type = NetworkType.CHUNK_BASED_FULL; } else { urlsFilePath = cmd.getOptionValue("f"); type = NetworkType.FILE_BASED; } System.out.println(urlsFilePath); reposListFile = new File(urlsFilePath); // Ends execution if file not found. if (!reposListFile.exists()) { System.out.println("COTONET ended without retrive any repository.\n\n" + "The file containig the repository's URL of the target systems was not found. " + "Check wether the file \"" + urlsFilePath + "\" exists."); System.exit(1); } skipCloneAndNetworks = (cmd.hasOption("rw") || cmd.hasOption("rwt")) ? true : false; MainThread m = new MainThread(type, reposListFile, skipCloneAndNetworks); m.start(); m.join(); Logger.log("COTONET finished. Files rewritten."); } else { System.out.println("COTONET ended without retrive any repository.\n\n" + "You should use 'h' if you are looking for help. Otherwise," + " the 'l' or 'fc' option is mandatory."); System.exit(1); } } catch (ParseException e) { new HelpFormatter().printHelp("java ", options); } catch (Exception e) { Logger.log(e.getMessage()); } }
From source file:MainServer.java
public static void main(String[] args) { int port = 1234; String filepath = ""; String complete_path = ""; String connection_type = ""; String ip_address = ""; int port_out = 0; int delay = 20; //20 by default //parse commands using getOpt (cli) //add Options Options options = new Options(); options.addOption("p", true, "port_to_listen_on"); options.addOption("d", true, "directory"); options.addOption("T", false, "TCP mode"); options.addOption("U", false, "UDP mode"); options.addOption("s", true, "iPAddress"); options.addOption("P", true, "port_to_connect_to"); options.addOption("D", true, "delay"); CommandLineParser clp = new DefaultParser(); try {// ww w. j a v a 2 s .co m CommandLine cl = clp.parse(options, args); //options for the server if (cl.hasOption("p")) { port = Integer.parseInt(cl.getOptionValue("p")); } else { System.err.println("No valid port selected."); return; } if (cl.hasOption("d")) { filepath = cl.getOptionValue("d"); //if there a '/' in front, remove it to make it a valid directory if (filepath.substring(0, 1).equalsIgnoreCase("/")) { filepath = filepath.substring(1); } } else { System.err.println("No valid directory given."); return; } if (cl.hasOption("D")) { delay = Integer.parseInt(cl.getOptionValue("D")); } //options for the client if (cl.hasOption("T")) { connection_type = "T"; } else if (cl.hasOption("U")) { connection_type = "U"; } if (cl.hasOption("s")) { ip_address = cl.getOptionValue("s"); } if (cl.hasOption("P")) { port_out = Integer.parseInt(cl.getOptionValue("P")); } } catch (ParseException e) { //TODO: handle exception } //create directory (if it doesn't already exist) try { Files.createDirectories(Paths.get(filepath)); } catch (Exception e) { //TODO: handle exception System.err.println("Couldn't create directory"); System.err.println(filepath); } //read in required files (create them if they dont already exist) try { Files.createFile(Paths.get(filepath + "/gossip.txt")); Files.createFile(Paths.get(filepath + "/peers.txt")); } catch (Exception e) { //TODO: handle exception } WriteToFiles.readFiles(filepath); //start the servers TCPServerSock tcpServer = new TCPServerSock(port, filepath, delay); UDPServer udpServer = new UDPServer(port, filepath); Thread tcpThread = new Thread(tcpServer); Thread udpThread = new Thread(udpServer); tcpThread.start(); udpThread.start(); //start the client if (!connection_type.equals("") && port_out != 0 && !ip_address.equals("")) { Client client = new Client(ip_address, port_out, connection_type); Thread clientThread = new Thread(client); clientThread.start(); } //Start thread to forget peers ForgetPeer forgetPeer = new ForgetPeer(filepath + "/peers.txt", delay); Thread forgetPeerThread = new Thread(forgetPeer); forgetPeerThread.start(); }
From source file:com.google.api.codegen.grpcmetadatagen.GrpcMetadataGeneratorTool.java
public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption("h", "help", false, "show usage"); options.addOption(Option.builder().longOpt("descriptor_set") .desc("The descriptor set representing the compiled input protos.").hasArg() .argName("DESCRIPTOR-SET").required(true).build()); options.addOption(//from w w w .j a va 2s.c om Option.builder().longOpt("service_yaml").desc("The service YAML configuration file or files.") .hasArg().argName("SERVICE-YAML").required(true).build()); options.addOption( Option.builder("i").longOpt("input").desc("The input directory containing the gRPC package.") .hasArg().argName("INPUT-DIR").required(true).build()); options.addOption( Option.builder("o").longOpt("output").desc("The directory in which to output the generated config.") .hasArg().argName("OUTPUT-DIR").required(true).build()); options.addOption( Option.builder("l").longOpt("language").desc("The language for which to generate package metadata.") .hasArg().argName("LANGUAGE").required(true).build()); options.addOption(Option.builder("c").longOpt("metadata_config") .desc("The YAML file configuring the package metadata.").hasArg().argName("METADATA-CONFIG") .required(true).build()); CommandLine cl = (new DefaultParser()).parse(options, args); if (cl.hasOption("help")) { HelpFormatter formater = new HelpFormatter(); formater.printHelp("ConfigGeneratorTool", options); } generate(cl.getOptionValue("descriptor_set"), cl.getOptionValues("service_yaml"), cl.getOptionValue("input"), cl.getOptionValue("output"), cl.getOptionValue("language"), cl.getOptionValue("metadata_config")); }
From source file:com.quattroresearch.helm.HlConfigEntry.java
public static void main(String[] args) throws Exception { CommandLineParser cmdline_parser = new DefaultParser(); Options options = new Options(); String usage = "Usage: -i <input_file> -o <output_file> -c <highlight_config_file>"; String errorLine;//from w w w. j a va 2 s.c o m if (args.length < 6) { log(usage); return; } options.addOption("c", true, "config file containing highlighting options"); options.addOption("i", true, "input file containing HELM string"); options.addOption("o", true, "output file containing highlighted HELM string"); try { // parse the command line arguments CommandLine cmd_line = cmdline_parser.parse(options, args); String cfilename = cmd_line.getOptionValue("c"); log("Cfg filename=" + cfilename); String ofilename = cmd_line.getOptionValue("o"); log("Output filename=" + ofilename); String ifilename = cmd_line.getOptionValue("i"); log("Input filename=" + ifilename); if (cfilename == null || ofilename == null || ifilename == null || cfilename.equals("") || ifilename.equals("") || ofilename.equals("")) { log(usage); return; } if (!(errorLine = setupHlConfigEntries(cfilename)).equals("")) { // in case of error, a non-empty string will be returned log("Bad entry in " + cfilename + ": '" + errorLine + "': missing category, keyword or value, exiting..."); // error return; } handleInputOutputFiles(ifilename, ofilename); } catch (IOException e) { System.out.println(e); } }
From source file:io.apicurio.studio.tools.release.ReleaseTool.java
/** * Main method./*w w w . j ava 2 s.c om*/ * @param args */ public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption("n", "release-name", true, "The name of the new release."); options.addOption("p", "prerelease", false, "Indicate that this is a pre-release."); options.addOption("t", "release-tag", true, "The tag name of the new release."); options.addOption("o", "previous-tag", true, "The tag name of the previous release."); options.addOption("g", "github-pat", true, "The GitHub PAT (for authentication/authorization)."); options.addOption("a", "artifact", true, "The binary release artifact (full path)."); options.addOption("d", "output-directory", true, "Where to store output file(s)."); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); if (!cmd.hasOption("n") || !cmd.hasOption("t") || !cmd.hasOption("o") || !cmd.hasOption("g") || !cmd.hasOption("a")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("release-studio", options); System.exit(1); } // Arguments (command line) String releaseName = cmd.getOptionValue("n"); boolean isPrerelease = cmd.hasOption("p"); String releaseTag = cmd.getOptionValue("t"); String oldReleaseTag = cmd.getOptionValue("o"); String githubPAT = cmd.getOptionValue("g"); String artifact = cmd.getOptionValue("a"); File outputDir = new File(""); if (cmd.hasOption("d")) { outputDir = new File(cmd.getOptionValue("d")); if (!outputDir.exists()) { outputDir.mkdirs(); } } File releaseArtifactFile = new File(artifact); File releaseArtifactSigFile = new File(artifact + ".asc"); String releaseArtifact = releaseArtifactFile.getName(); String releaseArtifactSig = releaseArtifactSigFile.getName(); if (!releaseArtifactFile.isFile()) { System.err.println("Missing file: " + releaseArtifactFile.getAbsolutePath()); System.exit(1); } if (!releaseArtifactSigFile.isFile()) { System.err.println("Missing file: " + releaseArtifactSigFile.getAbsolutePath()); System.exit(1); } System.out.println("========================================="); System.out.println("Creating Release: " + releaseTag); System.out.println("Previous Release: " + oldReleaseTag); System.out.println(" Name: " + releaseName); System.out.println(" Artifact: " + releaseArtifact); System.out.println(" Pre-Release: " + isPrerelease); System.out.println("========================================="); String releaseNotes = ""; // Step #1 - Generate Release Notes // * Grab info about the previous release (extract publish date) // * Query all Issues for ones closed since that date // * Generate Release Notes from the resulting Issues try { System.out.println("Getting info about release " + oldReleaseTag); HttpResponse<JsonNode> response = Unirest .get("https://api.github.com/repos/apicurio/apicurio-studio/releases/tags/v" + oldReleaseTag) .header("Accept", "application/json").header("Authorization", "token " + githubPAT).asJson(); if (response.getStatus() != 200) { throw new Exception("Failed to get old release info: " + response.getStatusText()); } JsonNode body = response.getBody(); String publishedDate = body.getObject().getString("published_at"); if (publishedDate == null) { throw new Exception("Could not find Published Date for previous release " + oldReleaseTag); } System.out.println("Release " + oldReleaseTag + " was published on " + publishedDate); List<JSONObject> issues = getIssuesForRelease(publishedDate, githubPAT); System.out.println("Found " + issues.size() + " issues closed in release " + releaseTag); System.out.println("Generating Release Notes"); releaseNotes = generateReleaseNotes(releaseName, releaseTag, issues); System.out.println("------------ Release Notes --------------"); System.out.println(releaseNotes); System.out.println("-----------------------------------------"); } catch (Exception e) { e.printStackTrace(); System.exit(1); } String assetUploadUrl = null; // Step #2 - Create a GitHub Release try { System.out.println("\nCreating GitHub Release " + releaseTag); JSONObject body = new JSONObject(); body.put("tag_name", "v" + releaseTag); body.put("name", releaseName); body.put("body", releaseNotes); body.put("prerelease", isPrerelease); HttpResponse<JsonNode> response = Unirest .post("https://api.github.com/repos/apicurio/apicurio-studio/releases") .header("Accept", "application/json").header("Content-Type", "application/json") .header("Authorization", "token " + githubPAT).body(body).asJson(); if (response.getStatus() != 201) { throw new Exception("Failed to create release in GitHub: " + response.getStatusText()); } assetUploadUrl = response.getBody().getObject().getString("upload_url"); if (assetUploadUrl == null || assetUploadUrl.trim().isEmpty()) { throw new Exception("Failed to get Asset Upload URL for newly created release!"); } } catch (Exception e) { e.printStackTrace(); System.exit(1); } // Step #3 - Upload Release Artifact (zip file) System.out.println("\nUploading Quickstart Artifact: " + releaseArtifact); try { String artifactUploadUrl = createUploadUrl(assetUploadUrl, releaseArtifact); byte[] artifactData = loadArtifactData(releaseArtifactFile); System.out.println("Uploading artifact asset: " + artifactUploadUrl); HttpResponse<JsonNode> response = Unirest.post(artifactUploadUrl).header("Accept", "application/json") .header("Content-Type", "application/zip").header("Authorization", "token " + githubPAT) .body(artifactData).asJson(); if (response.getStatus() != 201) { throw new Exception("Failed to upload asset: " + releaseArtifact, new Exception(response.getStatus() + "::" + response.getStatusText())); } Thread.sleep(1000); artifactUploadUrl = createUploadUrl(assetUploadUrl, releaseArtifactSig); artifactData = loadArtifactData(releaseArtifactSigFile); System.out.println("Uploading artifact asset: " + artifactUploadUrl); response = Unirest.post(artifactUploadUrl).header("Accept", "application/json") .header("Content-Type", "text/plain").header("Authorization", "token " + githubPAT) .body(artifactData).asJson(); if (response.getStatus() != 201) { throw new Exception("Failed to upload asset: " + releaseArtifactSig, new Exception(response.getStatus() + "::" + response.getStatusText())); } } catch (Exception e) { e.printStackTrace(); System.exit(1); } Thread.sleep(1000); // Step #4 - Download Latest Release JSON for inclusion in the project web site try { System.out.println("Getting info about the release."); HttpResponse<JsonNode> response = Unirest .get("https://api.github.com/repos/apicurio/apicurio-studio/releases/latest") .header("Accept", "application/json").asJson(); if (response.getStatus() != 200) { throw new Exception("Failed to get release info: " + response.getStatusText()); } JsonNode body = response.getBody(); String publishedDate = body.getObject().getString("published_at"); if (publishedDate == null) { throw new Exception("Could not find Published Date for release."); } String fname = publishedDate.replace(':', '-'); File outFile = new File(outputDir, fname + ".json"); System.out.println("Writing latest release info to: " + outFile.getAbsolutePath()); String output = body.getObject().toString(4); try (FileOutputStream fos = new FileOutputStream(outFile)) { fos.write(output.getBytes("UTF-8")); fos.flush(); } System.out.println("Release info successfully written."); } catch (Exception e) { e.printStackTrace(); System.exit(1); } System.out.println("========================================="); System.out.println("All Done!"); System.out.println("========================================="); }
From source file:ab.demo.MainEntry.java
public static void main(String args[]) { LoggingHandler.initConsoleLog();//from w w w .ja v a 2s. c o m //args = new String[]{"-su"}; Options options = new Options(); options.addOption("s", "standalone", false, "runs the reinforcement learning agent in standalone mode"); options.addOption("p", "proxyPort", true, "the port which is to be used by the proxy"); options.addOption("h", "help", false, "displays this help"); options.addOption("n", "naiveAgent", false, "runs the naive agent in standalone mode"); options.addOption("c", "competition", false, "runs the naive agent in the server/client competition mode"); options.addOption("u", "updateDatabaseTables", false, "executes CREATE TABLE IF NOT EXIST commands"); options.addOption("l", "level", true, "if set the agent is playing only in this one level"); options.addOption("m", "manual", false, "runs the empirical threshold determination agent in standalone mode"); options.addOption("r", "real", false, "shows the recognized shapes in a new frame"); CommandLineParser parser = new DefaultParser(); CommandLine cmd; StandaloneAgent agent; Properties properties = new Properties(); InputStream configInputStream = null; try { Class.forName("org.sqlite.JDBC"); //parse configuration file configInputStream = new FileInputStream("config.properties"); properties.load(configInputStream); } catch (IOException exception) { exception.printStackTrace(); } catch (ClassNotFoundException exception) { exception.printStackTrace(); } finally { if (configInputStream != null) { try { configInputStream.close(); } catch (IOException exception) { exception.printStackTrace(); } } } String dbPath = properties.getProperty("db_path"); String dbUser = properties.getProperty("db_user"); String dbPass = properties.getProperty("db_pass"); DBI dbi = new DBI(dbPath, dbUser, dbPass); QValuesDAO qValuesDAO = dbi.open(QValuesDAO.class); GamesDAO gamesDAO = dbi.open(GamesDAO.class); MovesDAO movesDAO = dbi.open(MovesDAO.class); ProblemStatesDAO problemStatesDAO = dbi.open(ProblemStatesDAO.class); try { cmd = parser.parse(options, args); if (cmd.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("help", options); return; } int proxyPort = 9000; if (cmd.hasOption("proxyPort")) { proxyPort = Integer.parseInt(cmd.getOptionValue("proxyPort")); logger.info("Set proxy port to " + proxyPort); } Proxy.setPort(proxyPort); LoggingHandler.initFileLog(); if (cmd.hasOption("standalone")) { agent = new ReinforcementLearningAgent(gamesDAO, movesDAO, problemStatesDAO, qValuesDAO); } else if (cmd.hasOption("naiveAgent")) { agent = new NaiveStandaloneAgent(); } else if (cmd.hasOption("manual")) { agent = new ManualGamePlayAgent(gamesDAO, movesDAO, problemStatesDAO); } else if (cmd.hasOption("competition")) { System.out.println("We haven't implemented a competition ready agent yet."); return; } else { System.out.println("Please specify which solving strategy we should be using."); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("help", options); return; } if (cmd.hasOption("updateDatabaseTables")) { qValuesDAO.createTable(); gamesDAO.createTable(); movesDAO.createTable(); problemStatesDAO.createTable(); problemStatesDAO.createObjectsTable(); } if (cmd.hasOption("level")) { agent.setFixedLevel(Integer.parseInt(cmd.getOptionValue("level"))); } if (cmd.hasOption("real")) { ShowSeg.useRealshape = true; Thread thread = new Thread(new ShowSeg()); thread.start(); } } catch (UnrecognizedOptionException e) { System.out.println("Unrecognized commandline option: " + e.getOption()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("help", options); return; } catch (ParseException e) { System.out.println( "There was an error while parsing your command line input. Did you rechecked your syntax before running?"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("help", options); return; } agent.run(); }
From source file:kafka.benchmark.AdvertisingTopology.java
public static void main(final String[] args) throws Exception { Options opts = new Options(); opts.addOption("conf", true, "Path to the config file."); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(opts, args); String configPath = cmd.getOptionValue("conf"); Map<?, ?> conf = Utils.findAndReadConfigFile(configPath, true); Map<String, ?> benchmarkParams = getKafkaConfs(conf); LOG.info("conf: {}", conf); LOG.info("Parameters used: {}", benchmarkParams); KStreamBuilder builder = new KStreamBuilder(); // builder.addStateStore( // Stores.create("config-params") // .withStringKeys().withStringValues() // .inMemory().maxEntries(10).build(), "redis"); String topicsArr[] = { (String) benchmarkParams.get("topic") }; KStream<String, ?> source1 = builder.stream(topicsArr); Properties props = new Properties(); props.putAll(benchmarkParams);// w w w . ja v a 2 s. c o m // props.put(StreamsConfig.APPLICATION_ID_CONFIG, "kafka-benchmarks"); // props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); //// props.put(StreamsConfig.ZOOKEEPER_CONNECT_CONFIG, "localhost:2181"); props.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName()); props.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName()); // setting offset reset to earliest so that we can re-run the demo code with the same pre-loaded data // props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); source1 // Parse the String as JSON .mapValues(input -> { JSONObject obj = new JSONObject(input.toString()); //System.out.println(obj.toString()); String[] tuple = { obj.getString("user_id"), obj.getString("page_id"), obj.getString("ad_id"), obj.getString("ad_type"), obj.getString("event_type"), obj.getString("event_time"), obj.getString("ip_address") }; return tuple; }) // Filter the records if event type is "view" .filter(new Predicate<String, String[]>() { @Override public boolean test(String key, String[] value) { return value[4].equals("view"); // "event_type" } }) // project the event .mapValues(input -> { String[] arr = (String[]) input; return new String[] { arr[2], arr[5] }; // "ad_id" and "event_time" }) // perform join with redis data .transformValues(new RedisJoinBolt(benchmarkParams)).filter((key, value) -> value != null) // create key from value .map((key, value) -> { String[] arr = (String[]) value; return new KeyValue<String, String[]>(arr[0], arr); }) // process campaign .aggregateByKey(new Initializer<List<String[]>>() { @Override public List<String[]> apply() { return new ArrayList<String[]>(); } }, new Aggregator<String, String[], List<String[]>>() { @Override public List<String[]> apply(String aggKey, String[] value, List<String[]> aggregate) { aggregate.add(value); return aggregate; } }, // UnlimitedWindows.of("kafka-test-unlim"), // HoppingWindows.of("kafka-test-hopping").with(12L).every(5L), TumblingWindows.of("kafka-test-tumbling").with(WINDOW_SIZE), strSerde, arrSerde) .toStream().process(new CampaignProcessor(benchmarkParams)); KafkaStreams streams = new KafkaStreams(builder, props); streams.start(); }
From source file:com.khubla.jvmbasic.jvmbasicwww.JVMBASICWWW.java
public static void main(String[] args) { try {/* w ww. ja v a 2 s.co m*/ System.out.println("khubla.com jvmBasic www server"); /* * options */ final Options options = new Options(); Option oo = Option.builder().argName(SOURCEDIR_OPTION).longOpt(SOURCEDIR_OPTION).type(String.class) .hasArg().required(false).desc("source dir").build(); options.addOption(oo); oo = Option.builder().argName(CLASSDIR_OPTION).longOpt(CLASSDIR_OPTION).type(String.class).hasArg() .required(false).desc("class dir").build(); options.addOption(oo); oo = Option.builder().argName(PORT_OPTION).longOpt(PORT_OPTION).type(String.class).hasArg() .required(false).desc("TCP port").build(); options.addOption(oo); /* * parse */ final CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (final Exception e) { final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("posix", options); System.exit(0); } /* * input dir */ final String sourceDir = cmd.getOptionValue(SOURCEDIR_OPTION, SOURCEDIR_DEFAULT); /* * class dir */ final String classdir = cmd.getOptionValue(CLASSDIR_OPTION, CLASSDIR_DEFAULT); /* * port */ int port = Integer.parseInt(cmd.getOptionValue(PORT_OPTION, PORT_DEFAULT)); /* * output the config */ System.out.println("Source directory: " + sourceDir); System.out.println("Class directory: " + classdir); System.out.println("HTTP port: " + port); /* * configuration */ final ServerConfiguration serverConfiguration = new ServerConfiguration(sourceDir, classdir, port); /* * server */ final JVMBasicWebServer jvmBasicWebServer = new JVMBasicWebServer(serverConfiguration); jvmBasicWebServer.listen(); } catch (final Exception e) { e.printStackTrace(); } }