List of usage examples for java.lang Exception Exception
public Exception(Throwable cause)
From source file:di.uniba.it.tri.aan.AAN2file.java
/** * Convert ACL dataset in a single file for each paper with year reference * aan_dir output_dir//from www.ja v a 2 s . c o m * * @param args the command line arguments */ public static void main(String[] args) { try { if (args.length > 1) { AAN2file ann = new AAN2file(); ann.build(args[0], args[1]); } else { throw new Exception("Illegal arguments"); } } catch (Exception ex) { Logger.getLogger(AAN2file.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:eu.cognitum.readandwrite.App.java
public static void main(String[] args) { try {/*from w ww .jav a2s .c o m*/ String configFile = 0 == args.length ? "example.properties" : args[0]; CONFIGURATION = new Properties(); File f = new File(configFile); if (!f.exists()) { LOGGER.warning("configuration not found at " + configFile); return; } LOGGER.info("loading configuration file " + f.getAbsoluteFile()); CONFIGURATION.load(new FileInputStream(f)); String ip = CONFIGURATION.getProperty(PROP_STORAGE_HOSTNAME); String keyspace = CONFIGURATION.getProperty(PROP_STORAGE_KEYSPACE); String directory = CONFIGURATION.getProperty(PROP_STORAGE_DIRECTORY); // N of articles to be generated. int Narticles = 100000; // size of the buffer to commit each time int commitBufferSize = 100; // N of articles to commit before trying reads int readStep = 100; String currentNamespace = "http://mynamespace#"; LOGGER.log(Level.INFO, "Generating the rdf..."); GenerateRdf rdfGenerator = new GenerateRdf(currentNamespace, "tmp.rdf"); rdfGenerator.generateAndSaveRdf(Narticles); LOGGER.log(Level.INFO, "Generated the rdf!"); ArrayList<SimulateReadAndWrite> simulateAll = new ArrayList<SimulateReadAndWrite>(); int Ndbs = 0; DBS[] chosenDbs = { DBS.NATIVE }; //DBS[] chosenDbs = DBS.values(); for (DBS dbs : chosenDbs) { SailRepository sr; switch (dbs) { case NATIVE: sr = createNativeStoreConnection(directory); break; case TITAN: sr = createTitanConnection(ip, keyspace); break; case NEO4J: sr = createNeo4jConnection(keyspace); break; case ORIENT: sr = createOrientConnection(keyspace); break; default: sr = null; break; } if (sr == null) { throw new Exception("Something wrong while connecting to " + dbs.toString()); } simulateAll.add(new SimulateReadAndWrite(sr, "test" + dbs.toString(), Narticles, readStep, commitBufferSize, dbs.toString(), keyspace, currentNamespace, rdfGenerator)); simulateAll.get(Ndbs).start(); Ndbs++; } int Nfinished = 0; int k; while (Nfinished != Ndbs) { Nfinished = 0; k = 0; for (DBS dbs : chosenDbs) { if (simulateAll.get(k).IsProcessCompleted()) { Nfinished++; } else { System.out.println(String.format("Process for db %s is at %.2f", dbs.toString(), simulateAll.get(k).GetProgress())); } k++; } Thread.sleep(10000); } } catch (Exception ex) { LOGGER.log(Level.SEVERE, null, ex); } }
From source file:edu.msu.cme.rdp.multicompare.Reprocess.java
/** * This class reprocesses the classification results (allrank output) and print out hierarchy output file, based on the confidence cutoff; * and print out only the detail classification results with assignment at certain rank with confidence above the cutoff or/and matching a given taxon. * @param args/* w w w . j av a2 s .co m*/ * @throws Exception */ public static void main(String[] args) throws Exception { PrintWriter assign_out = new PrintWriter(new NullWriter()); float conf = 0.8f; PrintStream heir_out = null; String hier_out_filename = null; ClassificationResultFormatter.FORMAT format = ClassificationResultFormatter.FORMAT.allRank; String rank = null; String taxonFilterFile = null; String train_propfile = null; String gene = null; List<MCSample> samples = new ArrayList(); try { CommandLine line = new PosixParser().parse(options, args); if (line.hasOption(CmdOptions.HIER_OUTFILE_SHORT_OPT)) { hier_out_filename = line.getOptionValue(CmdOptions.HIER_OUTFILE_SHORT_OPT); heir_out = new PrintStream(hier_out_filename); } else { throw new Exception( "It make sense to provide output filename for " + CmdOptions.HIER_OUTFILE_LONG_OPT); } if (line.hasOption(CmdOptions.OUTFILE_SHORT_OPT)) { assign_out = new PrintWriter(line.getOptionValue(CmdOptions.OUTFILE_SHORT_OPT)); } if (line.hasOption(CmdOptions.RANK_SHORT_OPT)) { rank = line.getOptionValue(CmdOptions.RANK_SHORT_OPT); } if (line.hasOption(CmdOptions.TAXON_SHORT_OPT)) { taxonFilterFile = line.getOptionValue(CmdOptions.TAXON_SHORT_OPT); } if (line.hasOption(CmdOptions.BOOTSTRAP_SHORT_OPT)) { conf = Float.parseFloat(line.getOptionValue(CmdOptions.BOOTSTRAP_SHORT_OPT)); if (conf < 0 || conf > 1) { throw new IllegalArgumentException("Confidence must be in the range [0,1]"); } } if (line.hasOption(CmdOptions.FORMAT_SHORT_OPT)) { String f = line.getOptionValue(CmdOptions.FORMAT_SHORT_OPT); if (f.equalsIgnoreCase("allrank")) { format = ClassificationResultFormatter.FORMAT.allRank; } else if (f.equalsIgnoreCase("fixrank")) { format = ClassificationResultFormatter.FORMAT.fixRank; } else if (f.equalsIgnoreCase("db")) { format = ClassificationResultFormatter.FORMAT.dbformat; } else if (f.equalsIgnoreCase("filterbyconf")) { format = ClassificationResultFormatter.FORMAT.filterbyconf; } else { throw new IllegalArgumentException( "Not valid output format, only allrank, fixrank, filterbyconf and db allowed"); } } if (line.hasOption(CmdOptions.TRAINPROPFILE_SHORT_OPT)) { if (gene != null) { throw new IllegalArgumentException( "Already specified the gene from the default location. Can not specify train_propfile"); } else { train_propfile = line.getOptionValue(CmdOptions.TRAINPROPFILE_SHORT_OPT); } } if (line.hasOption(CmdOptions.GENE_SHORT_OPT)) { if (train_propfile != null) { throw new IllegalArgumentException( "Already specified train_propfile. Can not specify gene any more"); } gene = line.getOptionValue(CmdOptions.GENE_SHORT_OPT).toLowerCase(); if (!gene.equals(ClassifierFactory.RRNA_16S_GENE) && !gene.equals(ClassifierFactory.FUNGALLSU_GENE) && !gene.equals(ClassifierFactory.FUNGALITS_warcup_GENE) && !gene.equals(ClassifierFactory.FUNGALITS_unite_GENE)) { throw new IllegalArgumentException(gene + " is NOT valid, only allows " + ClassifierFactory.RRNA_16S_GENE + ", " + ClassifierFactory.FUNGALLSU_GENE + ", " + ClassifierFactory.FUNGALITS_warcup_GENE + " and " + ClassifierFactory.FUNGALITS_unite_GENE); } } args = line.getArgs(); if (args.length < 1) { throw new Exception("Incorrect number of command line arguments"); } for (String arg : args) { String[] inFileNames = arg.split(","); String inputFile = inFileNames[0]; File idmappingFile = null; if (inFileNames.length == 2) { idmappingFile = new File(inFileNames[1]); if (!idmappingFile.exists()) { System.err.println("Failed to find input file \"" + inFileNames[1] + "\""); return; } } MCSample nextSample = new MCSampleResult(inputFile, idmappingFile); samples.add(nextSample); } } catch (Exception e) { System.out.println("Command Error: " + e.getMessage()); new HelpFormatter().printHelp(120, "Reprocess [options] <Classification_allrank_result>[,idmappingfile] ...", "", options, ""); return; } if (train_propfile == null && gene == null) { gene = ClassifierFactory.RRNA_16S_GENE; } HashSet<String> taxonFilter = null; if (taxonFilterFile != null) { taxonFilter = readTaxonFilterFile(taxonFilterFile); } MultiClassifier multiClassifier = new MultiClassifier(train_propfile, gene); DefaultPrintVisitor printVisitor = new DefaultPrintVisitor(heir_out, samples); MultiClassifierResult result = multiClassifier.multiClassificationParser(samples, conf, assign_out, format, rank, taxonFilter); result.getRoot().topDownVisit(printVisitor); assign_out.close(); heir_out.close(); if (multiClassifier.hasCopyNumber()) { // print copy number corrected counts File cn_corrected_s = new File(new File(hier_out_filename).getParentFile(), "cncorrected_" + hier_out_filename); PrintStream cn_corrected_hier_out = new PrintStream(cn_corrected_s); printVisitor = new DefaultPrintVisitor(cn_corrected_hier_out, samples, true); result.getRoot().topDownVisit(printVisitor); cn_corrected_hier_out.close(); } }
From source file:com.hpe.nv.samples.basic.BasicNVTest.java
public static void main(String[] args) { try {// w ww. j av a 2s .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("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("BasicNVTest.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("proxy")) { proxySetting = line.getOptionValue("proxy"); } 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 the use of the most basic NV methods. ***" + newLine + "*** ***" + newLine + "*** First, the sample creates a TestManager object and initializes it. ***" + newLine + "*** The sample starts an NV test over an emulated \"3G Busy\" network. ***" + newLine + "*** (\"3G Busy\" is one of NV's built-in network profiles. A network profile specifies the ***" + newLine + "*** network traffic behavior, including latency, packet loss, and incoming/outgoing bandwidth. ***" + newLine + "*** Network profiles are used to emulate traffic over real-world networks.) ***" + newLine + "*** ***" + newLine + "*** Next, the sample navigates to the home page in the HPE Network Virtualization website ***" + newLine + "*** using the Selenium WebDriver. ***" + newLine + "*** ***" + newLine + "*** Finally, the sample stops the NV test. ***" + newLine + "*** ***" + newLine + "*** You can view the actual steps of this sample in the BasicNVTest.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 - Create a TestManager object and initialize it *****/ printPartDescription("\b------ Part 1 - Create a TestManager object and initialize it"); initTestManager(); printPartSeparator(); /***** Part 2 - Start the NV test with the "3G Busy" network scenario *****/ printPartDescription("------ Part 2 - Start the NV test with the \"3G Busy\" network scenario"); startTest(); testRunning = true; printPartSeparator(); /***** Part 3 - Navigate to the HPE Network Virtualization website *****/ printPartDescription("------ Part 3 - Navigate to the HPE Network Virtualization website"); buildSeleniumWebDriver(); seleniumNavigateToPage(); driverCloseAndQuit(); printPartSeparator(); /***** Part 4 - Stop the NV test *****/ printPartDescription("------ Part 4 - Stop the NV test"); stopTest(); testRunning = false; printPartSeparator(); doneCallback(); } catch (Exception e) { try { handleError(e.getMessage()); } catch (Exception e2) { System.out.println("Error occurred: " + e2.getMessage()); } } }
From source file:com.blackducksoftware.tools.nrt.NoticeReportTool.java
/** * @param args// w w w . ja v a2 s . com * @throws Exception */ public static void main(String[] args) throws Exception { System.out.println("Notice Report Tool for Black Duck Suite"); CommandLineParser parser = new DefaultParser(); options.addOption("h", "help", false, "show help."); Option applicationOption = new Option(NRTConstants.CL_APPLICATION_TYPE, true, "Application type [PROTEX|CODECENTER] (required)"); applicationOption.setRequired(true); options.addOption(applicationOption); Option configFileOption = new Option(NRTConstants.CL_CONFIG_FILE, true, "Location of configuration file (required)"); configFileOption.setRequired(true); options.addOption(configFileOption); Option projectNameOption = new Option(NRTConstants.CL_PROJECT_NAME, true, "Name of Protex project (will override configuration file)"); projectNameOption.setRequired(false); options.addOption(projectNameOption); File configFile = null; APPLICATION applicationType = null; String projectName = null; try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) { help(); } // Config File if (cmd.hasOption(NRTConstants.CL_CONFIG_FILE)) { String configFilePath = cmd.getOptionValue(NRTConstants.CL_CONFIG_FILE); log.info("Config file location: " + configFilePath); configFile = new File(configFilePath); if (!configFile.exists()) { log.error("Configuration file does not exist at location: " + configFile); System.exit(-1); } } else { log.error("Must specify configuration file!"); help(); } if (cmd.hasOption(NRTConstants.CL_APPLICATION_TYPE)) { String bdsApplicationType = cmd.getOptionValue(NRTConstants.CL_APPLICATION_TYPE); try { applicationType = APPLICATION.valueOf(bdsApplicationType); } catch (IllegalArgumentException e) { log.error("No such application type recognized: " + bdsApplicationType); help(); } } else { help(); } if (cmd.hasOption(NRTConstants.CL_PROJECT_NAME)) { projectName = cmd.getOptionValue(NRTConstants.CL_PROJECT_NAME); log.info("User specified project name: " + projectName); } NoticeReportProcessor processor = new NoticeReportProcessor(configFile.getAbsolutePath(), applicationType, projectName); try { processor.connect(); } catch (Exception e) { log.error("Connection problems: " + e.getMessage()); throw new Exception(e); } processor.processReport(); } catch (Exception e) { log.error("Error: " + e.getMessage()); help(); } }
From source file:OverwriteProperties.java
/** * The main program for the OverwriteProperties class * * @param args The command line arguments * @exception Exception Description of the Exception *//* w w w .ja va 2 s. co m*/ public static void main(String[] args) throws Exception { OverwriteProperties overwriteProperties = new OverwriteProperties(); try { if (args.length < 3) { System.out.println( "Usage: java OverwriteProperties c:/temp/File1.props c:/temp/File2.props c:/include-root/"); System.out.println("Usage: File1 will be modified, new parameters from File 2 will be added,"); System.out.println( "Usage: and same parameters will be updated. The include-root is where include files are found."); throw new Exception("Incorrect number of arguments supplied"); } overwriteProperties.setBaseProperties(new File(args[0])); overwriteProperties.setProperties(new File(args[1])); overwriteProperties.setIncludeRoot(new File(args[2])); overwriteProperties.execute(); } catch (FileNotFoundException ex) { System.err.println(ex.getMessage()); } catch (IOException ex) { System.err.println(ex.getMessage()); } catch (SecurityException ex) { System.err.println(ex.getMessage()); } }
From source file:edu.msu.cme.rdp.seqmatch.cli.SeqMatchMain.java
public static void main(String[] args) throws Exception { if (args.length == 0) { System.err.println("USAGE: SeqMatchMain [train|seqmatch] <args>"); return;// w w w .j a v a 2s. c om } String cmd = args[0]; args = Arrays.copyOfRange(args, 1, args.length); if (cmd.equals("train")) { if (args.length != 2) { System.err.println("USAGE: train <reference sequences> <trainee_out_file_prefix>" + "\nMultiple trainee output files might be created, each containing maximum " + Trainee.MAX_NUM_SEQ + " sequences"); return; } File refSeqs = new File(args[0]); File traineeFileOut = new File(args[1]); //maybe more than 1 trainee files need to be created, depending on the number of seqs CreateMultiMatchFromFile.getMultiTrainee(refSeqs, traineeFileOut); } else if (cmd.equals("seqmatch")) { File refFile = null; File queryFile = null; HashMap<String, String> descMap = new HashMap<String, String>(); PrintStream out = new PrintStream(System.out); int knn = 20; float minSab = .5f; try { CommandLine line = new PosixParser().parse(options, args); if (line.hasOption("knn")) { knn = Integer.parseInt(line.getOptionValue("knn")); } if (line.hasOption("sab")) { minSab = Float.parseFloat(line.getOptionValue("sab")); } if (line.hasOption("desc")) { descMap = readDesc(new File(line.getOptionValue("desc"))); } if (line.hasOption("outFile")) { out = new PrintStream(new File(line.getOptionValue("outFile"))); } args = line.getArgs(); if (args.length != 2) { throw new Exception("Unexpected number of command line arguments"); } refFile = new File(args[0]); queryFile = new File(args[1]); } catch (Exception e) { new HelpFormatter().printHelp("seqmatch <refseqs | trainee_file_or_dir> <query_file>\n" + " trainee_file_or_dir is a single trainee file or a directory containing multiple trainee files", options); System.err.println("Error: " + e.getMessage()); return; } SeqMatch seqmatch = null; if (refFile.isDirectory()) { // a directory of trainee files List<SeqMatch> engineList = new ArrayList<SeqMatch>(); for (File f : refFile.listFiles()) { if (!f.isHidden()) { TwowaySeqMatch match = new TwowaySeqMatch(new SeqMatchEngine(new StorageTrainee(f))); engineList.add(match); } } seqmatch = new MultiTraineeSeqMatch(engineList); } else { // a single fasta file or trainee file if (SeqUtils.guessFileFormat(refFile) == SequenceFormat.UNKNOWN) { seqmatch = CLISeqMatchFactory.trainTwowaySeqMatch(new StorageTrainee(refFile)); } else { seqmatch = CreateMultiMatchFromFile.getMultiMatch(refFile); } } out.println("query name\tmatch seq\torientation\tS_ab score\tunique oligomers\tdescription"); SeqReader reader = new SequenceReader(queryFile); Sequence seq; while ((seq = reader.readNextSequence()) != null) { SeqMatchResultSet resultSet = seqmatch.match(seq, knn); for (SeqMatchResult result : resultSet) { char r = '+'; if (result.isReverse()) { r = '-'; } if (result.getScore() > minSab) { out.println(seq.getSeqName() + "\t" + result.getSeqName() + "\t" + r + "\t" + result.getScore() + "\t" + resultSet.getQueryWordCount() + "\t" + descMap.get(result.getSeqName())); } } } out.close(); } else { throw new IllegalArgumentException("USAGE: SeqMatchMain [train|seqmatch] <args>"); } }
From source file:org.acme.insurance.policyquote.test.WorkServiceMain.java
public static void main(String... args) throws Exception { serverHostname = System.getProperty("serverHostname", serverHostname); Set<String> policies = new HashSet<String>(); for (String arg : args) { arg = Strings.trimToNull(arg);// w w w . j a v a 2s . com if (arg != null) { if (arg.equals(CONFIDENTIALITY) || arg.equals(CLIENT_AUTHENTICATION) || arg.equals(HELP)) { policies.add(arg); } else { LOGGER.error(MAVEN_USAGE); throw new Exception(MAVEN_USAGE); } } } if (policies.contains(HELP)) { LOGGER.info(MAVEN_USAGE); } else { final String scheme; final int port; if (policies.contains(CONFIDENTIALITY)) { LOGGER.info("Invoking service via SSL..."); scheme = "https"; port = 443; SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, null, null); SSLSocketFactory sf = new SSLSocketFactory(sslcontext, SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); Scheme https = new Scheme(scheme, port, sf); SchemeRegistry sr = new SchemeRegistry(); sr.register(https); } else { scheme = "http"; port = 8080; } Element assertion = policies.contains(CLIENT_AUTHENTICATION) ? getAssertion() : null; invokeWorkService(scheme, port, assertion); } }
From source file:com.hpe.nv.samples.basic.BasicAnalyzeNVTest.java
public static void main(String[] args) { try {/*from ww w.j a va2 s .c om*/ // 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("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("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("BasicAnalyzeNVTest.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("zip-result-file-path")) { zipResultFilePath = line.getOptionValue("zip-result-file-path"); } if (line.hasOption("proxy")) { proxySetting = line.getOptionValue("proxy"); } 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 the use of the most basic NV methods. ***" + newLine + "*** ***" + newLine + "*** First, the sample creates a TestManager object and initializes it. ***" + newLine + "*** The sample starts an NV test over an emulated \"3G Busy\" network. ***" + newLine + "*** ***" + newLine + "*** Next, the sample navigates to the home page in the HPE Network Virtualization website ***" + newLine + "*** using the Selenium WebDriver. ***" + newLine + "*** ***" + newLine + "*** Finally, the sample stops the NV test, analyzes it, and prints the path of the analysis .zip file to the console. ***" + newLine + "*** ***" + newLine + "*** You can view the actual steps of this sample in the BasicAnalyzeNVTest.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 - Create a TestManager object and initialize it *****/ printPartDescription("\b------ Part 1 - Create a TestManager object and initialize it"); initTestManager(); printPartSeparator(); /***** Part 2 - Start the NV test with the "3G Busy" network scenario *****/ printPartDescription("------ Part 2 - Start the NV test with the \"3G Busy\" network scenario"); startTest(); testRunning = true; printPartSeparator(); /***** Part 3 - Navigate to the HPE Network Virtualization website *****/ printPartDescription("------ Part 3 - Navigate to the HPE Network Virtualization website"); buildSeleniumWebDriver(); seleniumNavigateToPage(); driverCloseAndQuit(); printPartSeparator(); /***** Part 4 - Stop the NV test, analyze it and print the results to the console *****/ printPartDescription( "------ Part 4 - Stop the NV test, analyze it and print the results to the console"); stopTestAndAnalyze(); testRunning = false; printPartSeparator(); doneCallback(); } catch (Exception e) { try { handleError(e.getMessage()); } catch (Exception e2) { System.out.println("Error occurred: " + e2.getMessage()); } } }
From source file:io.apicurio.studio.tools.release.ReleaseTool.java
/** * Main method.// w ww.jav a 2 s . co m * @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("========================================="); }