List of usage examples for org.apache.commons.cli DefaultParser DefaultParser
DefaultParser
From source file:gobblin.runtime.util.JobStateToJsonConverter.java
@SuppressWarnings("all") public static void main(String[] args) throws Exception { Option sysConfigOption = Option.builder("sc").argName("system configuration file") .desc("Gobblin system configuration file").longOpt("sysconfig").hasArgs().build(); Option storeUrlOption = Option.builder("u").argName("gobblin state store URL") .desc("Gobblin state store root path URL").longOpt("storeurl").hasArgs().required().build(); Option jobNameOption = Option.builder("n").argName("gobblin job name").desc("Gobblin job name") .longOpt("name").hasArgs().required().build(); Option jobIdOption = Option.builder("i").argName("gobblin job id").desc("Gobblin job id").longOpt("id") .hasArgs().build();//w w w . j a v a2s . com Option convertAllOption = Option.builder("a") .desc("Whether to convert all past job states of the given job").longOpt("all").build(); Option keepConfigOption = Option.builder("kc").desc("Whether to keep all configuration properties") .longOpt("keepConfig").build(); Option outputToFile = Option.builder("t").argName("output file name").desc("Output file name") .longOpt("toFile").hasArgs().build(); Options options = new Options(); options.addOption(sysConfigOption); options.addOption(storeUrlOption); options.addOption(jobNameOption); options.addOption(jobIdOption); options.addOption(convertAllOption); options.addOption(keepConfigOption); options.addOption(outputToFile); CommandLine cmd = null; try { CommandLineParser parser = new DefaultParser(); cmd = parser.parse(options, args); } catch (ParseException pe) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("JobStateToJsonConverter", options); System.exit(1); } Properties sysConfig = new Properties(); if (cmd.hasOption(sysConfigOption.getLongOpt())) { sysConfig = JobConfigurationUtils.fileToProperties(cmd.getOptionValue(sysConfigOption.getLongOpt())); } JobStateToJsonConverter converter = new JobStateToJsonConverter(sysConfig, cmd.getOptionValue('u'), cmd.hasOption("kc")); StringWriter stringWriter = new StringWriter(); if (cmd.hasOption('i')) { converter.convert(cmd.getOptionValue('n'), cmd.getOptionValue('i'), stringWriter); } else { if (cmd.hasOption('a')) { converter.convertAll(cmd.getOptionValue('n'), stringWriter); } else { converter.convert(cmd.getOptionValue('n'), stringWriter); } } if (cmd.hasOption('t')) { Closer closer = Closer.create(); try { FileOutputStream fileOutputStream = closer.register(new FileOutputStream(cmd.getOptionValue('t'))); OutputStreamWriter outputStreamWriter = closer.register( new OutputStreamWriter(fileOutputStream, ConfigurationKeys.DEFAULT_CHARSET_ENCODING)); BufferedWriter bufferedWriter = closer.register(new BufferedWriter(outputStreamWriter)); bufferedWriter.write(stringWriter.toString()); } catch (Throwable t) { throw closer.rethrow(t); } finally { closer.close(); } } else { System.out.println(stringWriter.toString()); } }
From source file:io.scigraph.owlapi.loader.BatchOwlLoader.java
public static void main(String[] args) throws Exception { CommandLineParser parser = new DefaultParser(); CommandLine cmd = null;//from ww w . ja v a2 s.co m try { cmd = parser.parse(getOptions(), args); } catch (ParseException e) { System.err.println(e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(BatchOwlLoader.class.getSimpleName(), getOptions()); System.exit(-1); } OwlLoadConfigurationLoader owlLoadConfigurationLoader = new OwlLoadConfigurationLoader( new File(cmd.getOptionValue('c').trim())); OwlLoadConfiguration config = owlLoadConfigurationLoader.loadConfig(); load(config); // TODO: Is Guice causing this to hang? #44 System.exit(0); }
From source file:gobblin.yarn.GobblinApplicationMaster.java
public static void main(String[] args) throws Exception { Options options = buildOptions();//from w ww . j a v a 2 s . c om try { CommandLine cmd = new DefaultParser().parse(options, args); if (!cmd.hasOption(GobblinClusterConfigurationKeys.APPLICATION_NAME_OPTION_NAME)) { printUsage(options); System.exit(1); } Log4jConfigurationHelper.updateLog4jConfiguration(GobblinApplicationMaster.class, GobblinYarnConfigurationKeys.GOBBLIN_YARN_LOG4J_CONFIGURATION_FILE, GobblinYarnConfigurationKeys.GOBBLIN_YARN_LOG4J_CONFIGURATION_FILE); LOGGER.info(JvmUtils.getJvmInputArguments()); ContainerId containerId = ConverterUtils .toContainerId(System.getenv().get(ApplicationConstants.Environment.CONTAINER_ID.key())); try (GobblinApplicationMaster applicationMaster = new GobblinApplicationMaster( cmd.getOptionValue(GobblinClusterConfigurationKeys.APPLICATION_NAME_OPTION_NAME), containerId, ConfigFactory.load(), new YarnConfiguration())) { applicationMaster.start(); } } catch (ParseException pe) { printUsage(options); System.exit(1); } }
From source file:com.hpe.nv.samples.advanced.AdvMultipleTestsConcurrent.java
public static void main(String[] args) throws Exception { try {/*from w ww .jav a 2 s. c o m*/ // program arguments Options options = new Options(); options.addOption("i", "server-ip", true, "[mandatory] NV Test Manager IP"); options.addOption("o", "server-port", true, "[mandatory] NV Test Manager port"); options.addOption("u", "username", true, "[mandatory] NV username"); options.addOption("w", "password", true, "[mandatory] NV password"); options.addOption("e", "ssl", true, "[optional] Pass true to use SSL. Default: false"); options.addOption("y", "proxy", true, "[optional] Proxy server host:port"); options.addOption("t", "site-url", true, "[optional] Site under test URL. Default: HPE Network Virtualization site URL. If you change this value, make sure to change the --xpath argument too"); options.addOption("x", "xpath", true, "[optional] Parameter for ExpectedConditions.visibilityOfElementLocated(By.xpath(...)) method. Use an xpath expression of some element in the site. Default: //div[@id='content']"); options.addOption("a", "active-adapter-ip", true, "[optional] Active adapter IP. Default: --server-ip argument"); options.addOption("f", "first-zip-result-file-path", true, "[optional] [optional] File path to store the first test analysis results as a .zip file"); options.addOption("s", "second-zip-result-file-path", true, "[optional] File path to store the second test analysis results as a .zip file"); options.addOption("c", "first-test-flow-tcp-port", true, "[optional] TCP port to define in the flow of the first test"); options.addOption("p", "second-test-flow-tcp-port", true, "[optional] TCP port to define in the flow of the second test"); options.addOption("k", "analysis-ports", true, "[optional] A comma-separated list of ports for test analysis"); options.addOption("b", "browser", true, "[optional] The browser for which the Selenium WebDriver is built. Possible values: Chrome and Firefox. Default: Firefox"); options.addOption("d", "debug", true, "[optional] Pass true to view console debug messages during execution. Default: false"); options.addOption("h", "help", false, "[optional] Generates and prints help information"); // parse and validate the command line arguments CommandLineParser parser = new DefaultParser(); CommandLine line = parser.parse(options, args); if (line.hasOption("help")) { // print help if help argument is passed HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("AdvMultipleTestsConcurrent.java", options); return; } if (line.hasOption("server-ip")) { serverIp = line.getOptionValue("server-ip"); if (serverIp.equals("0.0.0.0")) { throw new Exception( "Please replace the server IP argument value (0.0.0.0) with your NV Test Manager IP"); } } else { throw new Exception("Missing argument -i/--server-ip <serverIp>"); } if (line.hasOption("server-port")) { serverPort = Integer.parseInt(line.getOptionValue("server-port")); } else { throw new Exception("Missing argument -o/--server-port <serverPort>"); } if (line.hasOption("username")) { username = line.getOptionValue("username"); } else { throw new Exception("Missing argument -u/--username <username>"); } if (line.hasOption("password")) { password = line.getOptionValue("password"); } else { throw new Exception("Missing argument -w/--password <password>"); } if (line.hasOption("ssl")) { ssl = Boolean.parseBoolean(line.getOptionValue("ssl")); } if (line.hasOption("site-url")) { siteUrl = line.getOptionValue("site-url"); } else { siteUrl = "http://www8.hp.com/us/en/software-solutions/network-virtualization/index.html"; } if (line.hasOption("xpath")) { xpath = line.getOptionValue("xpath"); } else { xpath = "//div[@id='content']"; } if (line.hasOption("first-zip-result-file-path")) { firstZipResultFilePath = line.getOptionValue("first-zip-result-file-path"); } if (line.hasOption("second-zip-result-file-path")) { secondZipResultFilePath = line.getOptionValue("second-zip-result-file-path"); } if (line.hasOption("proxy")) { proxySetting = line.getOptionValue("proxy"); } if (line.hasOption("active-adapter-ip")) { activeAdapterIp = line.getOptionValue("active-adapter-ip"); } else { activeAdapterIp = serverIp; } if (line.hasOption("analysis-ports")) { String analysisPortsStr = line.getOptionValue("analysis-ports"); analysisPorts = analysisPortsStr.split(","); } else { analysisPorts = new String[] { "80", "8080" }; } if (line.hasOption("firstTestFlowTcpPort")) { firstTestFlowTcpPort = Integer.parseInt(line.getOptionValue("firstTestFlowTcpPort")); } else { firstTestFlowTcpPort = 8080; } if (line.hasOption("secondTestFlowTcpPort")) { secondTestFlowTcpPort = Integer.parseInt(line.getOptionValue("secondTestFlowTcpPort")); } else { secondTestFlowTcpPort = 80; } if (line.hasOption("browser")) { browser = line.getOptionValue("browser"); } else { browser = "Firefox"; } if (line.hasOption("debug")) { debug = Boolean.parseBoolean(line.getOptionValue("debug")); } String newLine = System.getProperty("line.separator"); String testDescription = "*** This sample shows how to run several tests concurrently with different flow definitions. ***" + newLine + "*** When running NV tests in parallel, make sure that: ***" + newLine + "*** * each test is configured to use multi-user mode ***" + newLine + "*** * the include/exclude IP ranges in the tests' flows do not overlap - this ensures data separation between the tests ***" + newLine + "*** * your NV Test Manager license supports multiple flows running in parallel ***" + newLine + "*** ***" + newLine + "*** You can view the actual steps of this sample in the AdvMultipleTestsConcurrent.java file. ***" + newLine; // print the sample's description System.out.println(testDescription); // start console spinner if (!debug) { spinner = new Thread(new Spinner()); spinner.start(); } // sample execution steps /***** Part 1 - Initialize the TestManager object and set the active adapter *****/ printPartDescription( "\b------ Part 1 - Initialize the TestManager object and set the active adapter"); initTestManager(); setActiveAdapter(); printPartSeparator(); /***** Part 2 - Start the first NV test with the flow "Flow1" *****/ printPartDescription("------ Part 2 - Start the first NV test with flow \"Flow1\""); startTest("Flow1"); testRunning = true; connectToTransactionManager("Flow1"); printPartSeparator(); /***** Part 3 - Start the second NV test with the flow "Flow2" *****/ printPartDescription("------ Part 3 - Start the second NV test with flow \"Flow2\""); startTest("Flow2"); connectToTransactionManager("Flow2"); printPartSeparator(); /***** Part 4 - Run the "Home Page" transactions in both tests *****/ printPartDescription("------ Part 4 - Run the \"Home Page\" transactions in both tests"); startTransaction("Flow1"); flow1TransactionInProgress = true; startTransaction("Flow2"); flow2TransactionInProgress = true; buildSeleniumWebDriver(); seleniumNavigateToPage(); stopTransaction("Flow1"); flow1TransactionInProgress = false; stopTransaction("Flow2"); flow2TransactionInProgress = false; printPartSeparator(); /***** Part 5 - Stop both tests, analyze them and print the results *****/ printPartDescription("------ Part 5 - Stop both tests, analyze them and print the results"); stopTest("Flow1"); stopTest("Flow2"); testRunning = false; analyzeTest("Flow1"); analyzeTest("Flow2"); driverCloseAndQuit(); printPartSeparator(); doneCallback(); } catch (Exception e) { try { handleError(e.getMessage()); } catch (Exception e2) { System.out.println("Error occurred: " + e2.getMessage()); } } }
From source file:com.twentyn.bioreactor.pH.ControlSystem.java
public static void main(String[] args) throws Exception { Options opts = new Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());/*from w w w . ja v a 2s . c o m*/ } CommandLine cl = null; try { CommandLineParser parser = new DefaultParser(); cl = parser.parse(opts, args); } catch (ParseException e) { LOGGER.error(String.format("Argument parsing failed: %s\n", e.getMessage())); HELP_FORMATTER.printHelp(ControlSystem.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } if (cl.hasOption("help")) { HELP_FORMATTER.printHelp(ControlSystem.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); return; } SOLUTION solution = null; String acidOrBase = cl.getOptionValue(OPTION_CONTROL_SOLUTION); if (acidOrBase.equals(SOLUTION.ACID.name())) { solution = SOLUTION.ACID; } if (acidOrBase.equals(SOLUTION.BASE.name())) { solution = SOLUTION.BASE; } if (solution == null) { LOGGER.error("Input solution is neither %s or %s", SOLUTION.ACID.name(), SOLUTION.BASE.name()); return; } Double targetPH = Double.parseDouble(cl.getOptionValue(OPTION_TARGET_PH)); File sensorReadingDataFile = new File( cl.getOptionValue(OPTION_SENSOR_READING_FILE_LOCATION, SENSOR_READING_FILE_LOCATION)); MotorPinConfiguration motorPinConfiguration = new MotorPinConfiguration( MotorPinConfiguration.PinNumberingScheme.BOARD); motorPinConfiguration.initializeGPIOPinsAndSetConfigToStartState(); ControlSystem controlSystem = new ControlSystem(motorPinConfiguration, solution, targetPH, sensorReadingDataFile); controlSystem.registerModuleForObjectMapper(new JodaModule()); try { controlSystem.run(); } finally { LOGGER.info("Shutting down"); controlSystem.shutdownFermentation(); } }
From source file:com.example.dlp.Redact.java
/** Command line application to redact strings, images using the Data Loss Prevention API. */ public static void main(String[] args) throws Exception { OptionGroup optionsGroup = new OptionGroup(); optionsGroup.setRequired(true);//ww w. j a v a 2 s. c om Option stringOption = new Option("s", "string", true, "redact string"); optionsGroup.addOption(stringOption); Option fileOption = new Option("f", "file path", true, "redact input file path"); optionsGroup.addOption(fileOption); Options commandLineOptions = new Options(); commandLineOptions.addOptionGroup(optionsGroup); Option minLikelihoodOption = Option.builder("minLikelihood").hasArg(true).required(false).build(); commandLineOptions.addOption(minLikelihoodOption); Option replaceOption = Option.builder("r").longOpt("replace string").hasArg(true).required(false).build(); commandLineOptions.addOption(replaceOption); Option infoTypesOption = Option.builder("infoTypes").hasArg(true).required(false).build(); infoTypesOption.setArgs(Option.UNLIMITED_VALUES); commandLineOptions.addOption(infoTypesOption); Option outputFilePathOption = Option.builder("o").hasArg(true).longOpt("outputFilePath").required(false) .build(); commandLineOptions.addOption(outputFilePathOption); CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd; try { cmd = parser.parse(commandLineOptions, args); } catch (ParseException e) { System.out.println(e.getMessage()); formatter.printHelp(Redact.class.getName(), commandLineOptions); System.exit(1); return; } String replacement = cmd.getOptionValue(replaceOption.getOpt(), "_REDACTED_"); List<InfoType> infoTypesList = new ArrayList<>(); String[] infoTypes = cmd.getOptionValues(infoTypesOption.getOpt()); if (infoTypes != null) { for (String infoType : infoTypes) { infoTypesList.add(InfoType.newBuilder().setName(infoType).build()); } } Likelihood minLikelihood = Likelihood.valueOf( cmd.getOptionValue(minLikelihoodOption.getOpt(), Likelihood.LIKELIHOOD_UNSPECIFIED.name())); // string inspection if (cmd.hasOption("s")) { String source = cmd.getOptionValue(stringOption.getOpt()); redactString(source, replacement, minLikelihood, infoTypesList); } else if (cmd.hasOption("f")) { String filePath = cmd.getOptionValue(fileOption.getOpt()); String outputFilePath = cmd.getOptionValue(outputFilePathOption.getOpt()); redactImage(filePath, minLikelihood, infoTypesList, outputFilePath); } }
From source file:com.hpe.nv.samples.advanced.AdvAllTestClassMethods.java
public static void main(String[] args) throws Exception { try {//from w w w. j ava 2 s . co m // program arguments Options options = new Options(); options.addOption("i", "server-ip", true, "[mandatory] NV Test Manager IP"); options.addOption("o", "server-port", true, "[mandatory] NV Test Manager port"); options.addOption("u", "username", true, "[mandatory] NV username"); options.addOption("w", "password", true, "[mandatory] NV password"); options.addOption("e", "ssl", true, "[optional] Pass true to use SSL. Default: false"); options.addOption("y", "proxy", true, "[optional] Proxy server host:port"); options.addOption("t", "site-url", true, "[optional] Site under test URL. Default: Default: HPE Network Virtualization site URL. If you change this value, make sure to change the --xpath argument too"); options.addOption("x", "xpath", true, "[optional] Parameter for ExpectedConditions.visibilityOfElementLocated(By.xpath(...)) method. Use an xpath expression of some element in the site. Default: //div[@id='content']"); options.addOption("a", "active-adapter-ip", true, "[optional] Active adapter IP. Default: --server-ip argument"); options.addOption("m", "mode", true, "[mandatory] Test mode - ntx or custom"); options.addOption("n", "ntx-file-path", true, "[mandatory in ntx mode] File path of an .ntx/.ntxx file - used to start the test in ntx mode"); options.addOption("z", "zip-result-file-path", true, "[optional] File path to store the analysis results as a .zip file"); options.addOption("k", "analysis-ports", true, "[optional] A comma-separated list of ports for test analysis"); options.addOption("p", "packet-list-id", true, "[optional] A packet list ID used for capturing a specific packet list and downloading its corresponding .shunra file"); options.addOption("c", "packet-list-file-path", true, "[optional] .pcap file path - used to store all captured packet lists"); options.addOption("s", "shunra-file-path", true, "[optional] .shunra file path for download"); options.addOption("b", "browser", true, "[optional] The browser for which the Selenium WebDriver is built. Possible values: Chrome and Firefox. Default: Firefox"); options.addOption("d", "debug", true, "[optional] Pass true to view console debug messages during execution. Default: false"); options.addOption("h", "help", false, "[optional] Generates and prints help information"); // parse and validate the command line arguments CommandLineParser parser = new DefaultParser(); CommandLine line = parser.parse(options, args); if (line.hasOption("help")) { // print help if help argument is passed HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("AdvAllTestClassMethods.java", options); return; } if (line.hasOption("mode")) { mode = ((String) line.getOptionValue("mode")).toLowerCase(); } else { throw new Exception("Missing argument -m/--mode <mode>"); } if (!mode.equals("custom") && !mode.equals("ntx")) { throw new Exception("Mode not supported. Supported modes are: ntx or custom"); } if (mode.equals("ntx")) { if (line.hasOption("ntx-file-path")) { ntxFilePath = line.getOptionValue("ntx-file-path"); } else { throw new Exception("Missing argument -n/--ntx-file-path <ntxFilePath>"); } } if (line.hasOption("server-ip")) { serverIp = line.getOptionValue("server-ip"); if (serverIp.equals("0.0.0.0")) { throw new Exception( "Please replace the server IP argument value (0.0.0.0) with your NV Test Manager IP"); } } else { throw new Exception("Missing argument -i/--server-ip <serverIp>"); } if (line.hasOption("server-port")) { serverPort = Integer.parseInt(line.getOptionValue("server-port")); } else { throw new Exception("Missing argument -o/--server-port <serverPort>"); } if (line.hasOption("username")) { username = line.getOptionValue("username"); } else { throw new Exception("Missing argument -u/--username <username>"); } if (line.hasOption("password")) { password = line.getOptionValue("password"); } else { throw new Exception("Missing argument -w/--password <password>"); } if (line.hasOption("ssl")) { ssl = Boolean.parseBoolean(line.getOptionValue("ssl")); } if (line.hasOption("zip-result-file-path")) { zipResultFilePath = line.getOptionValue("zip-result-file-path"); } if (line.hasOption("packet-list-id")) { packetListId = line.getOptionValue("packet-list-id"); } if (line.hasOption("packet-list-file-path")) { packetListFilePath = line.getOptionValue("packet-list-file-path"); } if (line.hasOption("shunra-file-path")) { shunraFilePath = line.getOptionValue("shunra-file-path"); } if (line.hasOption("site-url")) { siteUrl = line.getOptionValue("site-url"); } else { siteUrl = "http://www8.hp.com/us/en/software-solutions/network-virtualization/index.html"; } if (line.hasOption("xpath")) { xpath = line.getOptionValue("xpath"); } else { xpath = "//div[@id='content']"; } if (line.hasOption("proxy")) { proxySetting = line.getOptionValue("proxy"); } if (line.hasOption("active-adapter-ip")) { activeAdapterIp = line.getOptionValue("active-adapter-ip"); } else { activeAdapterIp = serverIp; } if (line.hasOption("analysis-ports")) { String analysisPortsStr = line.getOptionValue("analysis-ports"); analysisPorts = analysisPortsStr.split(","); } else { analysisPorts = new String[] { "80", "8080" }; } if (line.hasOption("browser")) { browser = line.getOptionValue("browser"); } else { browser = "Firefox"; } if (line.hasOption("debug")) { debug = Boolean.parseBoolean(line.getOptionValue("debug")); } String newLine = System.getProperty("line.separator"); String testDescription = "*** This sample demonstrates all of the Test class APIs except for the ***" + newLine + "*** real-time update API, which is demonstrated in AdvRealtimeUpdate.java. ***" + newLine + "*** You can start the test in this sample using either the NTX or Custom modes. ***" + newLine + "*** ***" + newLine + "*** You can view the actual steps of this sample in the AdvAllTestClassMethods.java file. ***" + newLine; // print the sample's description System.out.println(testDescription); // start console spinner if (!debug) { spinner = new Thread(new Spinner()); spinner.start(); } // sample execution steps /***** Part 1 - Initialize the TestManager object to pass logon credentials, the NV Test Manager IP, the port, and so on *****/ printPartDescription( "\b------ Part 1 - Initialize the TestManager object to pass logon credentials, the NV Test Manager IP, the port, and so on"); initTestManager(); printPartSeparator(); /***** Part 2 - Set the active adapter and start the NV test *****/ printPartDescription("------ Part 2 - Set the active adapter and start the NV test"); setActiveAdapter(); startTest(); testRunning = true; connectToTransactionManager(); printPartSeparator(); /***** Part 3 - Start packet list capture, get the packet list information and print it to the console (if the --debug argument is set to true) *****/ printPartDescription( "------ Part 3 - Start packet list capture, get the packet list information and print it to the console (if the --debug argument is set to true)"); startPacketListCapture(); getPacketListInfo(); printPartSeparator(); /***** Part 4 - Start the NV transaction and navigate to the site *****/ printPartDescription("------ Part 4 - Start the NV transaction and navigate to the site"); startTransaction(); transactionInProgress = true; buildSeleniumWebDriver(); seleniumNavigateToPage(); printPartSeparator(); /***** Part 5 - Get the NV test statistics and print the Client-in statistics to the console (if the --debug argument is set to true) *****/ printPartDescription( "------ Part 5 - Get the NV test statistics and print the Client-in statistics to the console (if the --debug argument is set to true)"); getTestStatistics(); printPartSeparator(); /***** Part 6 - Stop the NV transaction and the packet list capture, get the packet list information and print it to the console (if the --debug argument is set to true) *****/ printPartDescription( "------ Part 6 - Stop the NV transaction and the packet list capture, get the packet list information and print it to the console (if the --debug argument is set to true)"); stopTransaction(); transactionInProgress = false; stopPacketListCapture(); getPacketListInfo(); printPartSeparator(); /***** Part 7 - Disconnect from the transaction manager and stop the NV test *****/ printPartDescription("------ Part 7 - Disconnect from the transaction manager and stop the NV test"); disconnectFromTransactionManager(); stopTest(); testRunning = false; printPartSeparator(); /***** Part 8 - Analyze the NV test and print the results to the console *****/ printPartDescription("------ Part 8 - Analyze the NV test and print the results to the console"); analyzeTest(); printPartSeparator(); /***** Part 9 - Download the specified packet list and the .shunra file *****/ printPartDescription("------ Part 9 - Download the specified packet list and the .shunra file"); downloadPacketList(); downloadShunra(); printPartSeparator(); doneCallback(); } catch (Exception e) { try { handleError(e.getMessage()); } catch (Exception e2) { System.out.println("Error occurred: " + e2.getMessage()); } } }
From source file:com.emc.ecs.smart.SmartUploader.java
/** * Use commons-cli to parse command line arguments and start the upload. *///from w w w . j a v a 2 s. c om public static void main(String[] args) { Options opts = new Options(); // Optional params opts.addOption(Option.builder().longOpt(THREADS_OPT).hasArg().argName("thread-count") .desc("Sets the number of threads to upload concurrently. Default is " + DEFAULT_THREADS).build()); opts.addOption(Option.builder().longOpt(SIMPLE_OPT) .desc("For comparison purposes, do a simple single-stream upload instead of a concurrent upload.") .build()); opts.addOption(Option.builder().longOpt(SEGMENT_SIZE_OPT).hasArg().argName("bytes") .desc("Size of each upload segment in bytes. Defaults to 2MB for uploads less than 128MB and " + "128MB for objects greater than or equal to 128MB.") .build()); opts.addOption(Option.builder().longOpt(FILE_OPT).hasArg().argName("path-to-file").required() .desc("(Required) The path to the file to upload.").build()); opts.addOption(Option.builder().longOpt(URL_OPT).hasArg().argName("presigned-upload-url").required() .desc("URL used to PUT the file to create an object").build()); opts.addOption(Option.builder().longOpt(CONTENT_TYPE_OPT).hasArg().argName("mimetype") .desc("Value to use for the Content-Type header. Defaults to application/octet-stream.").build()); opts.addOption(Option.builder().longOpt(VERIFY_URL_OPT).hasArg().argName("url") .desc("If specified, read back the object from this URL and compare with the local file.").build()); opts.addOption(Option.builder().longOpt(LOG_LEVEL_OPT).hasArg().argName("level").type(Level.class) .desc("Sets the log level: DEBUG, INFO, WARN, ERROR, or FATAL. Default is ERROR.").build()); opts.addOption(Option.builder().longOpt(LOG_FILE_OPT).hasArg().argName("filename") .desc("Filename to write log messages. Setting to STDOUT or STDERR will write log messages to the " + "appropriate process stream. Default is STDERR.") .build()); opts.addOption(Option.builder().longOpt(LOG_PATTERN_OPT).hasArg().argName("log4j-pattern") .desc("Sets the " + "Log4J pattern to use when writing log messages. Defaults to " + "'%d{yyyy-MM-dd HH:mm:ss} %-5p [%t] %c{1}:%L - %m%n'") .build()); opts.addOption(Option.builder().longOpt(STANDARD_MD5) .desc("Use standard Java IO for local checksum " + "instead of NIO").build()); opts.addOption(Option.builder().longOpt(RETRY_DELAY_OPT).hasArg().argName("milliseconds") .desc("Initial retry delay in ms. Subsequent retries will continue to double this exponentially. " + "The default value is " + RETRY_DELAY) .build()); opts.addOption(Option.builder().longOpt(RETRY_COUNT_OPT).hasArg().argName("count") .desc("Number of times to " + "retry failed transactions. Set to zero to disable retries. Defaults to " + RETRY_COUNT) .build()); opts.addOption(Option.builder().longOpt(SAVE_MD5).hasArg().argName("path-to-file") .desc("Sets the file location where the local MD5 hash will be written.").build()); DefaultParser dp = new DefaultParser(); CommandLine cmd = null; try { cmd = dp.parse(opts, args); } catch (ParseException e) { System.err.println("Error: " + e.getMessage()); HelpFormatter hf = new HelpFormatter(); hf.printHelp("java -jar SmartUploader.jar", opts, true); System.exit(255); } // Required options. String url = cmd.getOptionValue(URL_OPT); String file = cmd.getOptionValue(FILE_OPT); SmartUploader uploader = null; try { uploader = new SmartUploader(new URL(url), new File(file).toPath()); } catch (MalformedURLException e) { System.err.println("Could not parse upload URL: " + e.getMessage()); System.exit(2); } if (cmd.hasOption(SEGMENT_SIZE_OPT)) { uploader.setSegmentSize(Integer.parseInt(cmd.getOptionValue(SEGMENT_SIZE_OPT))); } if (cmd.hasOption(THREADS_OPT)) { uploader.setThreadCount(Integer.parseInt(cmd.getOptionValue(THREADS_OPT))); } if (cmd.hasOption(SIMPLE_OPT)) { uploader.setSimpleMode(true); } if (cmd.hasOption(CONTENT_TYPE_OPT)) { uploader.setContentType(cmd.getOptionValue(CONTENT_TYPE_OPT)); } if (cmd.hasOption(VERIFY_URL_OPT)) { try { uploader.setVerifyUrl(new URL(cmd.getOptionValue(VERIFY_URL_OPT))); } catch (MalformedURLException e) { System.err.println("Could not parse verify URL: " + e.getMessage()); System.exit(3); } } if (cmd.hasOption(STANDARD_MD5)) { uploader.setStandardChecksum(true); } if (cmd.hasOption(RETRY_COUNT_OPT)) { uploader.setRetryCount(Integer.parseInt(cmd.getOptionValue(RETRY_COUNT_OPT))); } if (cmd.hasOption(RETRY_DELAY_OPT)) { uploader.setRetryDelay(Integer.parseInt(cmd.getOptionValue(RETRY_DELAY_OPT))); } if (cmd.hasOption(SAVE_MD5)) { uploader.setSaveMD5(cmd.getOptionValue(SAVE_MD5)); } // // Configure Logging // // Pattern String layoutString = "%d{yyyy-MM-dd HH:mm:ss} %-5p [%t] %c{1}:%L - %m%n"; if (cmd.hasOption(LOG_PATTERN_OPT)) { layoutString = cmd.getOptionValue(LOG_PATTERN_OPT); } PatternLayout layout = new PatternLayout(layoutString); // Appender String logFileName = "STDERR"; if (cmd.hasOption(LOG_FILE_OPT)) { logFileName = cmd.getOptionValue(LOG_FILE_OPT); } Appender appender = null; if (logFileName.equals("STDERR")) { appender = new ConsoleAppender(layout, "System.err"); } else if (logFileName.equals("STDOUT")) { appender = new ConsoleAppender(layout, "System.out"); } else { // Just a regular file. try { appender = new FileAppender(layout, logFileName); } catch (IOException e) { System.err.println("FATAL: Could not configure appender"); e.printStackTrace(); System.exit(8); } } LogManager.getRootLogger().addAppender(appender); // Log level String logLevel = "ERROR"; if (cmd.hasOption(LOG_LEVEL_OPT)) { logLevel = cmd.getOptionValue(LOG_LEVEL_OPT); } LogManager.getRootLogger().setLevel(Level.toLevel(logLevel)); // // Start the upload // uploader.doUpload(); System.exit(0); }
From source file:com.act.biointerpretation.l2expansion.L2FilteringDriver.java
public static void main(String[] args) throws Exception { // Build command line parser. Options opts = new Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());//from w ww.ja va 2 s . c o m } CommandLine cl = null; try { CommandLineParser parser = new DefaultParser(); cl = parser.parse(opts, args); } catch (ParseException e) { LOGGER.error("Argument parsing failed: %s", e.getMessage()); HELP_FORMATTER.printHelp(L2FilteringDriver.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } // Print help. if (cl.hasOption(OPTION_HELP)) { HELP_FORMATTER.printHelp(L2FilteringDriver.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); return; } checkFilterOptionIsValid(OPTION_CHEMICAL_FILTER, cl); checkFilterOptionIsValid(OPTION_REACTION_FILTER, cl); // Get corpus files. File corpusFile = new File(cl.getOptionValue(OPTION_INPUT_CORPUS)); if (!corpusFile.exists()) { LOGGER.error("Input corpus file does not exist."); return; } File outputFile = new File(cl.getOptionValue(OPTION_OUTPUT_PATH)); outputFile.createNewFile(); if (outputFile.isDirectory()) { LOGGER.error("Output file is directory."); System.exit(1); } LOGGER.info("Reading corpus from file."); L2PredictionCorpus predictionCorpus = L2PredictionCorpus.readPredictionsFromJsonFile(corpusFile); LOGGER.info("Read in corpus with %d predictions.", predictionCorpus.getCorpus().size()); LOGGER.info("Corpus has %d distinct substrates.", predictionCorpus.getUniqueSubstrateInchis().size()); if (cl.hasOption(OPTION_FILTER_SUBSTRATES)) { LOGGER.info("Filtering by substrates."); File substratesFile = new File(cl.getOptionValue(OPTION_FILTER_SUBSTRATES)); L2InchiCorpus inchis = new L2InchiCorpus(); inchis.loadCorpus(substratesFile); Set<String> inchiSet = new HashSet<String>(); inchiSet.addAll(inchis.getInchiList()); predictionCorpus = predictionCorpus .applyFilter(prediction -> inchiSet.containsAll(prediction.getSubstrateInchis())); predictionCorpus.writePredictionsToJsonFile(outputFile); LOGGER.info("Done writing filtered corpus to file."); return; } if (cl.hasOption(OPTION_SPLIT_BY_RO)) { LOGGER.info("Splitting corpus into distinct corpuses for each ro."); Map<String, L2PredictionCorpus> corpusMap = predictionCorpus .splitCorpus(prediction -> prediction.getProjectorName()); for (Map.Entry<String, L2PredictionCorpus> entry : corpusMap.entrySet()) { String fileName = cl.getOptionValue(OPTION_OUTPUT_PATH) + "." + entry.getKey(); File oneOutputFile = new File(fileName); entry.getValue().writePredictionsToJsonFile(oneOutputFile); } LOGGER.info("Done writing split corpuses to file."); return; } predictionCorpus = runDbLookups(cl, predictionCorpus, opts); LOGGER.info("Applying filters."); predictionCorpus = applyFilter(predictionCorpus, ALL_CHEMICALS_IN_DB, cl, OPTION_CHEMICAL_FILTER); predictionCorpus = applyFilter(predictionCorpus, REACTION_MATCHES_DB, cl, OPTION_REACTION_FILTER); LOGGER.info("Filtered corpus has %d predictions.", predictionCorpus.getCorpus().size()); LOGGER.info("Printing final corpus."); predictionCorpus.writePredictionsToJsonFile(outputFile); LOGGER.info("L2FilteringDriver complete!."); }
From source file:com.act.lcms.db.io.ExportStandardIonResultsFromDB.java
public static void main(String[] args) throws Exception { Options opts = new Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());/* w w w . j av a2 s .com*/ } CommandLine cl = null; try { CommandLineParser parser = new DefaultParser(); cl = parser.parse(opts, args); } catch (ParseException e) { System.err.format("Argument parsing failed: %s\n", e.getMessage()); HELP_FORMATTER.printHelp(ExportStandardIonResultsFromDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } if (cl.hasOption("help")) { HELP_FORMATTER.printHelp(ExportStandardIonResultsFromDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); return; } try (DB db = DB.openDBFromCLI(cl)) { List<String> chemicalNames = new ArrayList<>(); if (cl.hasOption(OPTION_CONSTRUCT)) { // Extract the chemicals in the pathway and their product masses, then look up info on those chemicals List<Pair<ChemicalAssociatedWithPathway, Double>> productMasses = Utils .extractMassesForChemicalsAssociatedWithConstruct(db, cl.getOptionValue(OPTION_CONSTRUCT)); for (Pair<ChemicalAssociatedWithPathway, Double> pair : productMasses) { chemicalNames.add(pair.getLeft().getChemical()); } } if (cl.hasOption(OPTION_CHEMICALS)) { chemicalNames.addAll(Arrays.asList(cl.getOptionValues(OPTION_CHEMICALS))); } if (chemicalNames.size() == 0) { System.err.format("No chemicals can be found from the input query.\n"); System.exit(-1); } List<String> standardIonHeaderFields = new ArrayList<String>() { { add(STANDARD_ION_HEADER_FIELDS.CHEMICAL.name()); add(STANDARD_ION_HEADER_FIELDS.BEST_ION_FROM_ALGO.name()); add(STANDARD_ION_HEADER_FIELDS.MANUAL_PICK.name()); add(STANDARD_ION_HEADER_FIELDS.AUTHOR.name()); add(STANDARD_ION_HEADER_FIELDS.DIAGNOSTIC_PLOTS.name()); add(STANDARD_ION_HEADER_FIELDS.NOTE.name()); } }; String outAnalysis; if (cl.hasOption(OPTION_OUTPUT_PREFIX)) { outAnalysis = cl.getOptionValue(OPTION_OUTPUT_PREFIX) + "." + TSV_FORMAT; } else { outAnalysis = String.join("-", chemicalNames) + "." + TSV_FORMAT; } File lcmsDir = new File(cl.getOptionValue(OPTION_DIRECTORY)); if (!lcmsDir.isDirectory()) { System.err.format("File at %s is not a directory\n", lcmsDir.getAbsolutePath()); HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } String plottingDirectory = cl.getOptionValue(OPTION_PLOTTING_DIR); TSVWriter<String, String> resultsWriter = new TSVWriter<>(standardIonHeaderFields); resultsWriter.open(new File(outAnalysis)); // For each chemical, create a TSV row and a corresponding diagnostic plot for (String chemicalName : chemicalNames) { List<String> graphLabels = new ArrayList<>(); List<Double> yMaxList = new ArrayList<>(); String outData = plottingDirectory + "/" + chemicalName + ".data"; String outImg = plottingDirectory + "/" + chemicalName + ".pdf"; // For each diagnostic plot, open a new file stream. try (FileOutputStream fos = new FileOutputStream(outData)) { List<StandardIonResult> getResultByChemicalName = StandardIonResult.getByChemicalName(db, chemicalName); if (getResultByChemicalName != null && getResultByChemicalName.size() > 0) { // PART 1: Get the best metlin ion across all standard ion results for a given chemical String bestGlobalMetlinIon = AnalysisHelper .scoreAndReturnBestMetlinIonFromStandardIonResults(getResultByChemicalName, new HashMap<>(), true, true); // PART 2: Plot all the graphs related to the chemical. The plots are structured as follows: // // Page 1: All graphs (water, MeOH, Yeast) for Global ion picked (best ion among ALL standard ion runs for // the given chemical) by the algorithm // Page 2: All graphs for M+H // Page 3: All graphs for Local ions picked (best ion within a SINGLE standard ion run) + negative controls // for Yeast. // // Each page is demarcated by a blank graph. // Arrange results based on media Map<String, List<StandardIonResult>> categories = StandardIonResult .categorizeListOfStandardWellsByMedia(db, getResultByChemicalName); // This set contains all the best metlin ions corresponding to all the standard ion runs. Set<String> bestLocalIons = new HashSet<>(); bestLocalIons.add(bestGlobalMetlinIon); bestLocalIons.add(DEFAULT_ION); for (StandardIonResult result : getResultByChemicalName) { bestLocalIons.add(result.getBestMetlinIon()); } // We sort the best local ions are follows: // 1) Global best ion spectra 2) M+H spectra 3) Local best ion spectra List<String> bestLocalIonsArray = new ArrayList<>(bestLocalIons); Collections.sort(bestLocalIonsArray, new Comparator<String>() { @Override public int compare(String o1, String o2) { if (o1.equals(bestGlobalMetlinIon) && !o2.equals(bestGlobalMetlinIon)) { return -1; } else if (o1.equals(DEFAULT_ION) && !o2.equals(bestGlobalMetlinIon)) { return -1; } else { return 1; } } }); // This variable stores the index of the array at which all the remaining spectra are contained in one // page. This happens right after the M+H ion spectra. Integer combineAllSpectraIntoPageThreeFromIndex = 0; for (int i = 0; i < bestLocalIonsArray.size(); i++) { if (bestLocalIonsArray.get(i).equals(DEFAULT_ION)) { combineAllSpectraIntoPageThreeFromIndex = i + 1; } } for (int i = 0; i < bestLocalIonsArray.size(); i++) { String ion = bestLocalIonsArray.get(i); for (Map.Entry<String, List<StandardIonResult>> mediaToListOfIonResults : categories .entrySet()) { for (StandardIonResult result : mediaToListOfIonResults.getValue()) { // For every standard ion result, we plot the best global metlin ion and M+H. These plots are in the // pages 1 and 2. For all page 3 (aka miscellaneous spectra), we only plot the best local ion // corresponding to it's spectra and not some other graph's spectra. In the below condition, // we reach the page 3 case with not the same best ion as the spectra, in which case we just continue // and not draw anything on the page. if (i >= combineAllSpectraIntoPageThreeFromIndex && !(result.getBestMetlinIon().equals(ion))) { continue; } StandardWell positiveWell = StandardWell.getInstance().getById(db, result.getStandardWellId()); String positiveControlChemical = positiveWell.getChemical(); ScanData<StandardWell> encapsulatedDataForPositiveControl = AnalysisHelper .getScanDataForWell(db, lcmsDir, positiveWell, positiveControlChemical, positiveControlChemical); Set<String> singletonSet = Collections.singleton(ion); String additionalInfo = generateAdditionalLabelInformation(positiveWell, result, ion); List<String> labels = AnalysisHelper .writeScanData(fos, lcmsDir, MAX_INTENSITY, encapsulatedDataForPositiveControl, false, false, singletonSet) .stream().map(label -> label + additionalInfo) .collect(Collectors.toList()); yMaxList.add(encapsulatedDataForPositiveControl.getMs1ScanResults() .getMaxIntensityForIon(ion)); List<String> negativeLabels = null; // Only do the negative control in the miscellaneous page (page 3) and if the well is in yeast media. if (mediaToListOfIonResults.getKey() .equals(StandardWell.MEDIA_TYPE.YEAST.name()) && (i >= combineAllSpectraIntoPageThreeFromIndex && (result.getBestMetlinIon().equals(ion)))) { //TODO: Change the representative negative well to one that displays the highest noise in the future. // For now, we just use the first index among the negative wells. int representativeIndex = 0; StandardWell representativeNegativeControlWell = StandardWell.getInstance() .getById(db, result.getNegativeWellIds().get(representativeIndex)); ScanData encapsulatedDataForNegativeControl = AnalysisHelper .getScanDataForWell(db, lcmsDir, representativeNegativeControlWell, positiveWell.getChemical(), representativeNegativeControlWell.getChemical()); String negativePlateAdditionalInfo = generateAdditionalLabelInformation( representativeNegativeControlWell, null, null); negativeLabels = AnalysisHelper.writeScanData(fos, lcmsDir, MAX_INTENSITY, encapsulatedDataForNegativeControl, false, false, singletonSet) .stream().map(label -> label + negativePlateAdditionalInfo) .collect(Collectors.toList()); yMaxList.add(encapsulatedDataForNegativeControl.getMs1ScanResults() .getMaxIntensityForIon(ion)); } graphLabels.addAll(labels); if (negativeLabels != null) { graphLabels.addAll(negativeLabels); } } } // Add a blank graph to demarcate pages. if (i < combineAllSpectraIntoPageThreeFromIndex) { graphLabels.addAll(AnalysisHelper.writeScanData(fos, lcmsDir, 0.0, BLANK_SCAN, false, false, new HashSet<>())); yMaxList.add(0.0d); } } // We need to pass the yMax values as an array to the Gnuplotter. Double fontScale = null; if (cl.hasOption(FONT_SCALE)) { try { fontScale = Double.parseDouble(cl.getOptionValue(FONT_SCALE)); } catch (IllegalArgumentException e) { System.err.format("Argument for font-scale must be a floating point number.\n"); System.exit(1); } } Double[] yMaxes = yMaxList.toArray(new Double[yMaxList.size()]); Gnuplotter plotter = fontScale == null ? new Gnuplotter() : new Gnuplotter(fontScale); plotter.plot2D(outData, outImg, graphLabels.toArray(new String[graphLabels.size()]), "time", null, "intensity", "pdf", null, null, yMaxes, outImg + ".gnuplot"); Map<String, String> row = new HashMap<>(); row.put(STANDARD_ION_HEADER_FIELDS.CHEMICAL.name(), chemicalName); row.put(STANDARD_ION_HEADER_FIELDS.BEST_ION_FROM_ALGO.name(), bestGlobalMetlinIon); row.put(STANDARD_ION_HEADER_FIELDS.DIAGNOSTIC_PLOTS.name(), outImg); resultsWriter.append(row); resultsWriter.flush(); } } } resultsWriter.flush(); resultsWriter.close(); } }