List of usage examples for org.apache.commons.cli ParseException printStackTrace
public void printStackTrace()
From source file:com.akana.demo.freemarker.templatetester.App.java
public static void main(String[] args) { final Options options = new Options(); @SuppressWarnings("static-access") Option optionContentType = OptionBuilder.withArgName("content-type").hasArg() .withDescription("content type of model").create("content"); @SuppressWarnings("static-access") Option optionUrlPath = OptionBuilder.withArgName("httpRequestLine").hasArg() .withDescription("url path and parameters in HTTP Request Line format").create("url"); @SuppressWarnings("static-access") Option optionRootMessageName = OptionBuilder.withArgName("messageName").hasArg() .withDescription("root data object name, defaults to 'message'").create("root"); @SuppressWarnings("static-access") Option optionAdditionalMessages = OptionBuilder.withArgName("dataModelPaths") .hasArgs(Option.UNLIMITED_VALUES).withDescription("additional message object data sources") .create("messages"); @SuppressWarnings("static-access") Option optionDebugMessages = OptionBuilder.hasArg(false) .withDescription("Shows debug information about template processing").create("debug"); Option optionHelp = new Option("help", "print this message"); options.addOption(optionHelp);//ww w .ja va2s. c o m options.addOption(optionContentType); options.addOption(optionUrlPath); options.addOption(optionRootMessageName); options.addOption(optionAdditionalMessages); options.addOption(optionDebugMessages); CommandLineParser parser = new DefaultParser(); CommandLine cmd; try { cmd = parser.parse(options, args); // Check for help flag if (cmd.hasOption("help")) { showHelp(options); return; } String[] remainingArguments = cmd.getArgs(); if (remainingArguments.length < 2) { showHelp(options); return; } String ftlPath, dataPath = "none"; ftlPath = remainingArguments[0]; dataPath = remainingArguments[1]; String contentType = "text/xml"; // Discover content type from file extension String ext = FilenameUtils.getExtension(dataPath); if (ext.equals("json")) { contentType = "json"; } else if (ext.equals("txt")) { contentType = "txt"; } // Override discovered content type if (cmd.hasOption("content")) { contentType = cmd.getOptionValue("content"); } // Root data model name String rootMessageName = "message"; if (cmd.hasOption("root")) { rootMessageName = cmd.getOptionValue("root"); } // Additional data models String[] additionalModels = new String[0]; if (cmd.hasOption("messages")) { additionalModels = cmd.getOptionValues("messages"); } // Debug Info if (cmd.hasOption("debug")) { System.out.println(" Processing ftl : " + ftlPath); System.out.println(" with data model: " + dataPath); System.out.println(" with content-type: " + contentType); System.out.println(" data model object: " + rootMessageName); if (cmd.hasOption("messages")) { System.out.println("additional models: " + additionalModels.length); } } Configuration cfg = new Configuration(Configuration.VERSION_2_3_23); cfg.setDirectoryForTemplateLoading(new File(".")); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); /* Create the primary data-model */ Map<String, Object> message = new HashMap<String, Object>(); if (contentType.contains("json") || contentType.contains("txt")) { message.put("contentAsString", FileUtils.readFileToString(new File(dataPath), StandardCharsets.UTF_8)); } else { message.put("contentAsXml", freemarker.ext.dom.NodeModel.parse(new File(dataPath))); } if (cmd.hasOption("url")) { message.put("getProperty", new AkanaGetProperty(cmd.getOptionValue("url"))); } Map<String, Object> root = new HashMap<String, Object>(); root.put(rootMessageName, message); if (additionalModels.length > 0) { for (int i = 0; i < additionalModels.length; i++) { Map<String, Object> m = createMessageFromFile(additionalModels[i], contentType); root.put("message" + i, m); } } /* Get the template (uses cache internally) */ Template temp = cfg.getTemplate(ftlPath); /* Merge data-model with template */ Writer out = new OutputStreamWriter(System.out); temp.process(root, out); } catch (ParseException e) { showHelp(options); System.exit(1); } catch (IOException e) { System.out.println("Unable to parse ftl."); e.printStackTrace(); } catch (SAXException e) { System.out.println("XML parsing issue."); e.printStackTrace(); } catch (ParserConfigurationException e) { System.out.println("Unable to configure parser."); e.printStackTrace(); } catch (TemplateException e) { System.out.println("Unable to parse template."); e.printStackTrace(); } }
From source file:microbiosima.SelectiveMicrobiosima.java
/** * @param args/* www . jav a 2 s .com*/ * the command line arguments * @throws java.io.FileNotFoundException * @throws java.io.UnsupportedEncodingException */ public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException { int populationSize = 500;//Integer.parseInt(parameters[1]); int microSize = 1000;//Integer.parseInt(parameters[2]); int numberOfSpecies = 150;//Integer.parseInt(parameters[3]); int numberOfGeneration = 10000; int Ngene = 10; int numberOfObservation = 100; int numberOfReplication = 10; double Ngenepm = 5; double pctEnv = 0; double pctPool = 0; double msCoeff = 1; double hsCoeff = 1; boolean HMS_or_TMS = true; Options options = new Options(); Option help = new Option("h", "help", false, "print this message"); Option version = new Option("v", "version", false, "print the version information and exit"); options.addOption(help); options.addOption(version); options.addOption(Option.builder("o").longOpt("obs").hasArg().argName("OBS") .desc("Number generation for observation [default: 100]").build()); options.addOption(Option.builder("r").longOpt("rep").hasArg().argName("REP") .desc("Number of replication [default: 1]").build()); Builder C = Option.builder("c").longOpt("config").numberOfArgs(6).argName("Pop Micro Spec Gen") .desc("Four Parameters in the following orders: " + "(1) population size, (2) microbe size, (3) number of species, (4) number of generation, (5) number of total traits, (6)number of traits per microbe" + " [default: 500 1000 150 10000 10 5]"); options.addOption(C.build()); HelpFormatter formatter = new HelpFormatter(); String syntax = "microbiosima pctEnv pctPool"; String header = "\nSimulates the evolutionary and ecological dynamics of microbiomes within a population of hosts.\n\n" + "required arguments:\n" + " pctEnv Percentage of environmental acquisition\n" + " pctPool Percentage of pooled environmental component\n" + " msCoeff Parameter related to microbe selection strength\n" + " hsCoeff Parameter related to host selection strength\n" + " HMS_or_TMS String HMS or TMS to specify host-mediated or trait-mediated microbe selection\n" + "\noptional arguments:\n"; String footer = "\n"; formatter.setWidth(80); CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); String[] pct_config = cmd.getArgs(); if (cmd.hasOption("h") || args.length == 0) { formatter.printHelp(syntax, header, options, footer, true); System.exit(0); } if (cmd.hasOption("v")) { System.out.println("Microbiosima " + VERSION); System.exit(0); } if (pct_config.length != 5) { System.out.println( "ERROR! Required exactly five argumennts for pct_env, pct_pool, msCoeff, hsCoeff and HMS_or_TMS. It got " + pct_config.length + ": " + Arrays.toString(pct_config)); formatter.printHelp(syntax, header, options, footer, true); System.exit(3); } else { pctEnv = Double.parseDouble(pct_config[0]); pctPool = Double.parseDouble(pct_config[1]); msCoeff = Double.parseDouble(pct_config[2]); hsCoeff = Double.parseDouble(pct_config[3]); if (pct_config[4].equals("HMS")) HMS_or_TMS = true; if (pct_config[4].equals("TMS")) HMS_or_TMS = false; if (pctEnv < 0 || pctEnv > 1) { System.out.println( "ERROR: pctEnv (Percentage of environmental acquisition) must be between 0 and 1 (pctEnv=" + pctEnv + ")! EXIT"); System.exit(3); } if (pctPool < 0 || pctPool > 1) { System.out.println( "ERROR: pctPool (Percentage of pooled environmental component must) must be between 0 and 1 (pctPool=" + pctPool + ")! EXIT"); System.exit(3); } if (msCoeff < 1) { System.out.println( "ERROR: msCoeff (parameter related to microbe selection strength) must be not less than 1 (msCoeff=" + msCoeff + ")! EXIT"); System.exit(3); } if (hsCoeff < 1) { System.out.println( "ERROR: hsCoeff (parameter related to host selection strength) must be not less than 1 (hsCoeff=" + hsCoeff + ")! EXIT"); System.exit(3); } if (!(pct_config[4].equals("HMS") || pct_config[4].equals("TMS"))) { System.out.println( "ERROR: HMS_or_TMS (parameter specifying host-mediated or trait-mediated selection) must be either 'HMS' or 'TMS' (HMS_or_TMS=" + pct_config[4] + ")! EXIT"); System.exit(3); } } if (cmd.hasOption("config")) { String[] configs = cmd.getOptionValues("config"); populationSize = Integer.parseInt(configs[0]); microSize = Integer.parseInt(configs[1]); numberOfSpecies = Integer.parseInt(configs[2]); numberOfGeneration = Integer.parseInt(configs[3]); Ngene = Integer.parseInt(configs[4]); Ngenepm = Double.parseDouble(configs[5]); if (Ngenepm > Ngene) { System.out.println( "ERROR: number of traits per microbe must not be greater than number of total traits! EXIT"); System.exit(3); } } if (cmd.hasOption("obs")) { numberOfObservation = Integer.parseInt(cmd.getOptionValue("obs")); } if (cmd.hasOption("rep")) { numberOfReplication = Integer.parseInt(cmd.getOptionValue("rep")); } } catch (ParseException e) { e.printStackTrace(); System.exit(3); } StringBuilder sb = new StringBuilder(); sb.append("Configuration Summary:").append("\n\tPopulation size: ").append(populationSize) .append("\n\tMicrobe size: ").append(microSize).append("\n\tNumber of species: ") .append(numberOfSpecies).append("\n\tNumber of generation: ").append(numberOfGeneration) .append("\n\tNumber generation for observation: ").append(numberOfObservation) .append("\n\tNumber of replication: ").append(numberOfReplication) .append("\n\tNumber of total traits: ").append(Ngene).append("\n\tNumber of traits per microbe: ") .append(Ngenepm).append("\n"); System.out.println(sb.toString()); double[] environment = new double[numberOfSpecies]; for (int i = 0; i < numberOfSpecies; i++) { environment[i] = 1 / (double) numberOfSpecies; } int[] fitnessToHost = new int[Ngene]; int[] fitnessToMicrobe = new int[Ngene]; for (int rep = 0; rep < numberOfReplication; rep++) { String prefix = "" + (rep + 1) + "_"; String sufix; if (HMS_or_TMS) sufix = "_E" + pctEnv + "_P" + pctPool + "_HS" + hsCoeff + "_HMS" + msCoeff + ".txt"; else sufix = "_E" + pctEnv + "_P" + pctPool + "_HS" + hsCoeff + "_TMS" + msCoeff + ".txt"; System.out.println("Output 5 result files in the format of: " + prefix + "[****]" + sufix); try { PrintWriter file1 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "gamma_diversity" + sufix))); PrintWriter file2 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "alpha_diversity" + sufix))); PrintWriter file3 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "beta_diversity" + sufix))); PrintWriter file4 = new PrintWriter(new BufferedWriter(new FileWriter(prefix + "sum" + sufix))); PrintWriter file5 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "inter_generation_distance" + sufix))); PrintWriter file6 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "environment_population_distance" + sufix))); PrintWriter file7 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "host_fitness" + sufix))); PrintWriter file8 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "cos_theta" + sufix))); PrintWriter file9 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "host_fitness_distribution" + sufix))); PrintWriter file10 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "microbiome_fitness_distribution" + sufix))); PrintWriter file11 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "bacteria_contents" + sufix))); PrintWriter file12 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "individual_bacteria_contents" + sufix))); for (int i = 0; i < Ngene; i++) { fitnessToMicrobe[i] = MathUtil.getNextInt(2) - 1; fitnessToHost[i] = MathUtil.getNextInt(2) - 1; } MathUtil.setSeed(rep % numberOfReplication); SelectiveSpeciesRegistry ssr = new SelectiveSpeciesRegistry(numberOfSpecies, Ngene, Ngenepm, msCoeff, fitnessToHost, fitnessToMicrobe); MathUtil.setSeed(); SelectivePopulation population = new SelectivePopulation(microSize, environment, populationSize, pctEnv, pctPool, 0, 0, ssr, hsCoeff, HMS_or_TMS); while (population.getNumberOfGeneration() < numberOfGeneration) { population.sumSpecies(); if (population.getNumberOfGeneration() % numberOfObservation == 0) { //file1.print(population.gammaDiversity(false)); //file2.print(population.alphaDiversity(false)); //file1.print("\t"); //file2.print("\t"); file1.println(population.gammaDiversity(true)); file2.println(population.alphaDiversity(true)); //file3.print(population.betaDiversity(true)); //file3.print("\t"); file3.println(population.BrayCurtis(true)); file4.println(population.printOut()); file5.println(population.interGenerationDistance()); file6.println(population.environmentPopulationDistance()); file7.print(population.averageHostFitness()); file7.print("\t"); file7.println(population.varianceHostFitness()); file8.println(population.cosOfMH()); file9.println(population.printOutHFitness()); file10.println(population.printOutMFitness()); file11.println(population.printBacteriaContents()); } population.getNextGen(); } for (SelectiveIndividual host : population.getIndividuals()) { file12.println(host.printBacteriaContents()); } file1.close(); file2.close(); file3.close(); file4.close(); file5.close(); file6.close(); file7.close(); file8.close(); file9.close(); file10.close(); file11.close(); file12.close(); } catch (IOException e) { e.printStackTrace(); } } }
From source file:com.zimbra.qa.unittest.prov.ldap.TestLdapReadTimeout.java
/** * /Users/pshao/dev/workspace/sandbox/sandbox/bin>/System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home/bin/java LdapReadTimeout * /System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home/bin/java LdapReadTimeout * /* w w w. j a v a 2s . co m*/ * zmjava com.zimbra.qa.unittest.TestLdapReadTimeout -s 5 * zmjava com.zimbra.qa.unittest.TestLdapReadTimeout -H ldap://localhost:389 -D uid=zimbra,cn=admins,cn=zimbra -w zimbra -s 5 * * @param args */ public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(O_HELP, false, "print usage"); options.addOption(O_SLEEP, true, "upon hitting an Exception, minutes to wait until exiting the program. " + "If not specified, will exit immediately."); options.addOption(O_URI, true, "URI. e.g. ldap://localhost:389"); options.addOption(O_BINDDN, true, "bind DN"); options.addOption(O_PASSWORD, true, "password"); CommandLine cl = null; try { CommandLineParser parser = new GnuParser(); cl = parser.parse(options, args); if (cl == null) { throw new ParseException(""); } } catch (ParseException e) { usage(options); e.printStackTrace(); System.exit(1); } if (cl.hasOption(O_HELP)) { usage(options); System.exit(0); } String uri = null; String bindDN = null; String password = null; Integer minutesToWait = null; if (cl.hasOption(O_URI)) { uri = cl.getOptionValue(O_URI); } else { uri = "ldap://localhost:389"; } if (cl.hasOption(O_BINDDN)) { bindDN = cl.getOptionValue(O_BINDDN); } else { bindDN = "uid=zimbra,cn=admins,cn=zimbra"; } if (cl.hasOption(O_PASSWORD)) { password = cl.getOptionValue(O_PASSWORD); } else { password = "zimbra"; } if (cl.hasOption(O_SLEEP)) { String wait = cl.getOptionValue(O_SLEEP); try { minutesToWait = Integer.valueOf(wait); } catch (NumberFormatException e) { usage(options); e.printStackTrace(); System.exit(1); } } LdapReadTimeoutTester tester = null; try { // tester = new JNDITest(uri, bindDN, password); // fails tester = new UnboundIDTest(uri, bindDN, password); // works System.out.println("============="); System.out.println(tester.getClass().getCanonicalName()); System.out.println("LDAP server URI: " + uri); System.out.println("bind DN: " + bindDN); System.out.println("============="); System.out.println(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } long startTime = System.currentTimeMillis(); test(tester); long endTime = System.currentTimeMillis(); long elapsed = endTime - startTime; SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println(); System.out.println(tester.getClass().getCanonicalName()); System.out.println("Started at: " + fmt.format(new Date(startTime))); System.out.println("Ended at: " + fmt.format(new Date(endTime))); System.out.println("Elapsed = " + (elapsed / 1000) + " seconds"); System.out.println(); if (minutesToWait != null) { System.out.println("Sleeping for " + minutesToWait + " minutes before exiting..."); Thread.sleep(minutesToWait * 60 * 1000); } }
From source file:com.chezzverse.timelogger.server.TimeLoggerServerMain.java
public static void main(String[] args) { // Initialize the default configuration file to the hard coded default path value. String configFileName = _DEFAULT_CONFIG_FILE; // Create all the available options Option portOpt = new Option("p", "port", true, "Set the listen port for the http server " + "instance."); portOpt.setArgName("number"); Option htmlOpt = new Option("h", "html-root", true, "Set the root directory that " + "contains the required html files."); htmlOpt.setArgName("directory"); Option configOpt = new Option("c", "config", true, "Get configuration options from the " + "specified file"); Option backlogOpt = new Option("b", "backlog", true, "Set the number of connections to " + "queue for the server."); Options opts = new Options(); opts.addOption(portOpt);//from www . j a v a 2 s .c o m opts.addOption(htmlOpt); opts.addOption(configOpt); opts.addOption(backlogOpt); CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; HelpFormatter formatter = new HelpFormatter(); try { // Parse the command line arguments. cmd = parser.parse(opts, args); // Fist check to see if there is a custom defined config file, and load the config file. if (cmd.hasOption("c")) { configFileName = cmd.getOptionValue("c"); } TimeLoggerConfig.getInstance().LoadConfigFile(configFileName); // Process the rest of the args and override any settings in the config file. if (cmd.hasOption("h")) { TimeLoggerConfig.getInstance().htmlRoot = cmd.getOptionValue("h"); } if (cmd.hasOption("p")) { TimeLoggerConfig.getInstance().port = Integer.parseInt(cmd.getOptionValue("p")); } if (cmd.hasOption("b")) { TimeLoggerConfig.getInstance().maxBackLog = Integer.parseInt(cmd.getOptionValue("b")); } } catch (ParseException e) { System.out.println("Invalid argument."); formatter.printHelp("TimeLoggerServer", opts); System.exit(1); } catch (NumberFormatException e) { System.out.println("Invalid argument."); formatter.printHelp("TimeLoggerServer", opts); System.exit(1); } catch (Exception e) { e.printStackTrace(); } TimeLoggerApp app = new TimeLoggerApp(); if (app != null) { app.run(); } else { System.exit(3); // Strange termination } }
From source file:com.intuit.s3encrypt.S3Encrypt.java
public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { // create Options object Options options = new Options(); options.addOption(create_bucket);/* ww w . jav a 2 s . co m*/ options.addOption(create_key); options.addOption(delete_bucket); options.addOption(get); options.addOption(help); options.addOption(inspect); options.addOption(keyfile); options.addOption(list_buckets); options.addOption(list_objects); options.addOption(put); options.addOption(remove); options.addOption(rotate); options.addOption(rotateall); options.addOption(rotateKey); // CommandLineParser parser = new GnuParser(); // Changed from above GnuParser to below PosixParser because I found code which allows for multiple arguments PosixParser parser = new PosixParser(); CommandLine cmd; try { cmd = parser.parse(options, args); Logger.getRootLogger().setLevel(Level.OFF); if (cmd.hasOption("help")) { HelpFormatter help = new HelpFormatter(); System.out.println(); help.printHelp("S3Encrypt", options); System.out.println(); System.exit(1); } else if (cmd.hasOption("create_key")) { keyname = cmd.getOptionValue("keyfile"); createKeyFile(keyname); key = new File(keyname); } else { if (cmd.hasOption("keyfile")) { keyname = cmd.getOptionValue("keyfile"); } key = new File(keyname); } if (!(key.exists())) { System.out.println("Key does not exist or not provided"); System.exit(1); } // AmazonS3 s3 = new AmazonS3Client(new ClasspathPropertiesFileCredentialsProvider()); ClasspathPropertiesFileCredentialsProvider credentials = new ClasspathPropertiesFileCredentialsProvider( ".s3encrypt"); EncryptionMaterials encryptionMaterials = new EncryptionMaterials(getKeyFile(keyname)); AmazonS3EncryptionClient s3 = new AmazonS3EncryptionClient(credentials.getCredentials(), encryptionMaterials); // Region usWest2 = Region.getRegion(Regions.US_WEST_2); // s3.setRegion(usWest2); if (cmd.hasOption("create_bucket")) { String bucket = cmd.getOptionValue("create_bucket"); System.out.println("Creating bucket " + bucket + "\n"); s3.createBucket(bucket); } else if (cmd.hasOption("delete_bucket")) { String bucket = cmd.getOptionValue("delete_bucket"); System.out.println("Deleting bucket " + bucket + "\n"); s3.deleteBucket(bucket); } else if (cmd.hasOption("get")) { String[] searchArgs = cmd.getOptionValues("get"); String bucket = searchArgs[0]; String filename = searchArgs[1]; getS3Object(cmd, s3, bucket, filename); } else if (cmd.hasOption("inspect")) { String[] searchArgs = cmd.getOptionValues("inspect"); String bucket = searchArgs[0]; String filename = searchArgs[1]; String keyname = "encryption_key"; String metadata = inspectS3Object(cmd, s3, bucket, filename, keyname); System.out.println(metadata); } else if (cmd.hasOption("list_buckets")) { System.out.println("Listing buckets"); for (Bucket bucket : s3.listBuckets()) { System.out.println(bucket.getName()); } System.out.println(); } else if (cmd.hasOption("list_objects")) { String bucket = cmd.getOptionValue("list_objects"); System.out.println("Listing objects"); ObjectListing objectListing = s3.listObjects(new ListObjectsRequest().withBucketName(bucket)); for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) { System.out.println(objectSummary.getKey() + " " + "(size = " + objectSummary.getSize() + ")"); } System.out.println(); } else if (cmd.hasOption("put")) { String[] searchArgs = cmd.getOptionValues("put"); String bucket = searchArgs[0]; String filename = searchArgs[1]; String metadataKeyname = "encryption_key"; String key = keyname; putS3Object(cmd, s3, bucket, filename, metadataKeyname, key); } else if (cmd.hasOption("remove")) { String[] searchArgs = cmd.getOptionValues("remove"); String bucket = searchArgs[0]; String filename = searchArgs[1]; System.out.println("Removing object in S3 from BUCKET = " + bucket + " FILENAME = " + filename); s3.deleteObject(new DeleteObjectRequest(bucket, filename)); System.out.println(); } else if (cmd.hasOption("rotate")) { String[] searchArgs = cmd.getOptionValues("rotate"); String bucket = searchArgs[0]; String filename = searchArgs[1]; String key1 = cmd.getOptionValue("keyfile"); String key2 = cmd.getOptionValue("rotateKey"); String metadataKeyname = "encryption_key"; System.out.println("Supposed to get object from here OPTION VALUE = " + bucket + " FILENAME = " + filename + " KEY1 = " + key1 + " KEY2 = " + key2); EncryptionMaterials rotateEncryptionMaterials = new EncryptionMaterials(getKeyFile(key2)); AmazonS3EncryptionClient rotateS3 = new AmazonS3EncryptionClient(credentials.getCredentials(), rotateEncryptionMaterials); getS3Object(cmd, s3, bucket, filename); putS3Object(cmd, rotateS3, bucket, filename, metadataKeyname, key2); } else if (cmd.hasOption("rotateall")) { String[] searchArgs = cmd.getOptionValues("rotateall"); String bucket = searchArgs[0]; String key1 = searchArgs[1]; String key2 = searchArgs[2]; System.out.println("Supposed to rotateall here for BUCKET NAME = " + bucket + " KEY1 = " + key1 + " KEY2 = " + key2); } else { System.out.println("Something went wrong... "); System.exit(1); } } catch (ParseException e) { e.printStackTrace(); } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which " + "means your request made it " + "to Amazon S3, but was rejected with an error response" + " for some reason."); System.out.println("Error Message: " + ase.getMessage()); System.out.println("HTTP Status Code: " + ase.getStatusCode()); System.out.println("AWS Error Code: " + ase.getErrorCode()); System.out.println("Error Type: " + ase.getErrorType()); System.out.println("Request ID: " + ase.getRequestId()); } catch (AmazonClientException ace) { System.out.println("Caught an AmazonClientException, which " + "means the client encountered " + "an internal error while trying to " + "communicate with S3, " + "such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } }
From source file:it.polimi.tower4clouds.rules.batch.BatchTool.java
public static void main(String[] args) { Options options = buildOptions();/* w ww. j a v a2 s .co m*/ CommandLineParser parser = new BasicParser(); HelpFormatter formatter = new HelpFormatter(); FileInputStream inputFile = null; try { // parse the command line arguments CommandLine cmd = parser.parse(options, args); if (cmd.getOptions().length != 1) { System.err.println("Parsing failed: Reason: one and only one option is required"); formatter.printHelp("qos-models", options); } else if (cmd.hasOption("h")) { formatter.printHelp("qos-models", options); } else if (cmd.hasOption("v")) { String file = cmd.getOptionValue("v"); inputFile = new FileInputStream(file); MonitoringRules rules = XMLHelper.deserialize(inputFile, MonitoringRules.class); RulesValidator validator = new RulesValidator(); Set<Problem> problems = validator.validateAllRules(rules); printResult(problems); } else if (cmd.hasOption("c")) { String file = cmd.getOptionValue("c"); inputFile = new FileInputStream(file); Constraints constraints = XMLHelper.deserialize(inputFile, Constraints.class); QoSValidator validator = new QoSValidator(); Set<Problem> problems = validator.validateAllConstraints(constraints); printResult(problems); } else if (cmd.hasOption("r")) { String file = cmd.getOptionValue("r"); inputFile = new FileInputStream(file); Constraints constraints = XMLHelper.deserialize(inputFile, Constraints.class); MonitoringRuleFactory factory = new MonitoringRuleFactory(); MonitoringRules rules = factory.makeRulesFromQoSConstraints(constraints); XMLHelper.serialize(rules, System.out); } } catch (ParseException e) { System.err.println("Parsing failed. Reason: " + e.getMessage()); formatter.printHelp("qos-models", options); } catch (FileNotFoundException e) { System.err.println("Could not locate input file: " + e.getMessage()); } catch (JAXBException | SAXException e) { System.err.println("Input file could not be parsed: "); e.printStackTrace(); } catch (Exception e) { System.err.println("Unknown error: "); e.printStackTrace(); } finally { if (inputFile != null) { try { inputFile.close(); } catch (IOException e) { } } } }
From source file:at.newmedialab.ldpath.backend.linkeddata.LDQuery.java
public static void main(String[] args) { Options options = buildOptions();// w w w.j a va 2 s .c om CommandLineParser parser = new PosixParser(); try { CommandLine cmd = parser.parse(options, args); Level logLevel = Level.WARN; if (cmd.hasOption("loglevel")) { String logLevelName = cmd.getOptionValue("loglevel"); if ("DEBUG".equals(logLevelName.toUpperCase())) { logLevel = Level.DEBUG; } else if ("INFO".equals(logLevelName.toUpperCase())) { logLevel = Level.INFO; } else if ("WARN".equals(logLevelName.toUpperCase())) { logLevel = Level.WARN; } else if ("ERROR".equals(logLevelName.toUpperCase())) { logLevel = Level.ERROR; } else { log.error("unsupported log level: {}", logLevelName); } } if (logLevel != null) { for (String logname : new String[] { "at", "org", "net", "com" }) { ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory .getLogger(logname); logger.setLevel(logLevel); } } String format = null; if (cmd.hasOption("format")) { format = cmd.getOptionValue("format"); } GenericSesameBackend backend; if (cmd.hasOption("store")) { backend = new LDPersistentBackend(new File(cmd.getOptionValue("store"))); } else { backend = new LDMemoryBackend(); } Resource context = null; if (cmd.hasOption("context")) { context = backend.getRepository().getValueFactory().createURI(cmd.getOptionValue("context")); } if (backend != null && context != null) { LDPath<Value> ldpath = new LDPath<Value>(backend); if (cmd.hasOption("path")) { String path = cmd.getOptionValue("path"); for (Value v : ldpath.pathQuery(context, path, null)) { System.out.println(v.stringValue()); } } else if (cmd.hasOption("program")) { File file = new File(cmd.getOptionValue("program")); Map<String, Collection<?>> result = ldpath.programQuery(context, new FileReader(file)); for (String field : result.keySet()) { StringBuilder line = new StringBuilder(); line.append(field); line.append(" = "); line.append("{"); for (Iterator it = result.get(field).iterator(); it.hasNext();) { line.append(it.next().toString()); if (it.hasNext()) { line.append(", "); } } line.append("}"); System.out.println(line); } } } if (backend instanceof LDPersistentBackend) { ((LDPersistentBackend) backend).shutdown(); } } catch (ParseException e) { System.err.println("invalid arguments"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("LDQuery", options, true); } catch (LDPathParseException e) { System.err.println("path or program could not be parsed"); e.printStackTrace(); } catch (FileNotFoundException e) { System.err.println("file or program could not be found"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("LDQuery", options, true); } catch (IOException e) { System.err.println("could not access cache data directory"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("LDQuery", options, true); } }
From source file:net.lldp.checksims.ChecksimsRunner.java
/** * CLI entrypoint of Checksims./*w w w .ja va 2 s . co m*/ * * @param args CLI arguments */ public static void main(String[] args) { try { ChecksimsCommandLine.runCLI(args); } catch (ParseException e) { System.err.println(e.getMessage()); System.exit(-1); } catch (ChecksimsException e) { System.err.println(e.toString()); if (e.getCause() != null) { System.err.println("Caused by: " + e.getCause().toString()); } // Print the stack trace for internal exceptions, they may be serious e.printStackTrace(); System.exit(-1); } catch (IOException e) { System.err.println("I/O Error!"); System.err.println(e.getMessage()); System.exit(-1); } System.exit(0); }
From source file:fr.inria.atlanmod.atl_mr.utils.NeoEMFHBaseMigrator.java
public static void main(String[] args) { Options options = new Options(); Option inputOpt = OptionBuilder.create(IN); inputOpt.setArgName("INPUT"); inputOpt.setDescription("Input file, both of xmi and zxmi extensions are supported"); inputOpt.setArgs(1);// w w w . jav a 2 s. c o m inputOpt.setRequired(true); Option outputOpt = OptionBuilder.create(OUT); outputOpt.setArgName("OUTPUT"); outputOpt.setDescription("Output HBase resource URI"); outputOpt.setArgs(1); outputOpt.setRequired(true); Option inClassOpt = OptionBuilder.create(E_PACKAGE); inClassOpt.setArgName("METAMODEL"); inClassOpt.setDescription("URI of the ecore Metamodel"); inClassOpt.setArgs(1); inClassOpt.setRequired(true); options.addOption(inputOpt); options.addOption(outputOpt); options.addOption(inClassOpt); CommandLineParser parser = new PosixParser(); try { CommandLine commandLine = parser.parse(options, args); URI sourceUri = URI.createFileURI(commandLine.getOptionValue(IN)); URI targetUri = URI.createURI(commandLine.getOptionValue(OUT)); URI metamodelUri = URI.createFileURI(commandLine.getOptionValue(E_PACKAGE)); NeoEMFHBaseMigrator.class.getClassLoader().loadClass(commandLine.getOptionValue(E_PACKAGE)) .getMethod("init").invoke(null); //org.eclipse.gmt.modisco.java.kyanos.impl.JavaPackageImpl.init(); ResourceSet resourceSet = new ResourceSetImpl(); resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("ecore", new EcoreResourceFactoryImpl()); resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi", new XMIResourceFactoryImpl()); resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("zxmi", new XMIResourceFactoryImpl()); resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put(KyanosURI.KYANOS_HBASE_SCHEME, KyanosResourceFactory.eINSTANCE); //Registering the metamodel // Resource MMResource = resourceSet.createResource(metamodelUri); // MMResource.load(Collections.EMPTY_MAP); // ATLMRUtils.registerPackages(resourceSet, MMResource); //Loading the XMI resource Resource sourceResource = resourceSet.createResource(sourceUri); Map<String, Object> loadOpts = new HashMap<String, Object>(); if ("zxmi".equals(sourceUri.fileExtension())) { loadOpts.put(XMIResource.OPTION_ZIP, Boolean.TRUE); } Runtime.getRuntime().gc(); long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); LOG.log(Level.INFO, MessageFormat.format("Used memory before loading: {0}", ATLMRUtils.byteCountToDisplaySize(initialUsedMemory))); LOG.log(Level.INFO, "Loading source resource"); sourceResource.load(loadOpts); LOG.log(Level.INFO, "Source resource loaded"); Runtime.getRuntime().gc(); long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); LOG.log(Level.INFO, MessageFormat.format("Used memory after loading: {0}", ATLMRUtils.byteCountToDisplaySize(finalUsedMemory))); LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}", ATLMRUtils.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory))); Resource targetResource = resourceSet.createResource(targetUri); Map<String, Object> saveOpts = new HashMap<String, Object>(); targetResource.save(saveOpts); LOG.log(Level.INFO, "Start moving elements"); targetResource.getContents().clear(); targetResource.getContents().addAll(sourceResource.getContents()); LOG.log(Level.INFO, "End moving elements"); LOG.log(Level.INFO, "Start saving"); targetResource.save(saveOpts); LOG.log(Level.INFO, "Saved"); if (targetResource instanceof KyanosHbaseResourceImpl) { KyanosHbaseResourceImpl.shutdownWithoutUnload((KyanosHbaseResourceImpl) targetResource); } else { targetResource.unload(); } } catch (ParseException e) { ATLMRUtils.showError(e.toString()); ATLMRUtils.showError("Current arguments: " + Arrays.toString(args)); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar <this-file.jar>", options, true); } catch (Throwable e) { ATLMRUtils.showError(e.toString()); e.printStackTrace(); } }
From source file:fr.inria.atlanmod.kyanos.benchmarks.KyanosMapCreator.java
public static void main(String[] args) { Options options = new Options(); Option inputOpt = OptionBuilder.create(IN); inputOpt.setArgName("INPUT"); inputOpt.setDescription("Input file"); inputOpt.setArgs(1);/*from w ww . j av a2 s .c o m*/ inputOpt.setRequired(true); Option outputOpt = OptionBuilder.create(OUT); outputOpt.setArgName("OUTPUT"); outputOpt.setDescription("Output directory"); outputOpt.setArgs(1); outputOpt.setRequired(true); Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS); inClassOpt.setArgName("CLASS"); inClassOpt.setDescription("FQN of EPackage implementation class"); inClassOpt.setArgs(1); inClassOpt.setRequired(true); options.addOption(inputOpt); options.addOption(outputOpt); options.addOption(inClassOpt); CommandLineParser parser = new PosixParser(); try { PersistenceBackendFactoryRegistry.getFactories().put(NeoMapURI.NEO_MAP_SCHEME, new MapPersistenceBackendFactory()); CommandLine commandLine = parser.parse(options, args); URI sourceUri = URI.createFileURI(commandLine.getOptionValue(IN)); URI targetUri = NeoMapURI.createNeoMapURI(new File(commandLine.getOptionValue(OUT))); Class<?> inClazz = KyanosMapCreator.class.getClassLoader() .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS)); inClazz.getMethod("init").invoke(null); ResourceSet resourceSet = new ResourceSetImpl(); resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi", new XMIResourceFactoryImpl()); resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("zxmi", new XMIResourceFactoryImpl()); resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put(NeoMapURI.NEO_MAP_SCHEME, PersistentResourceFactory.eINSTANCE); Resource sourceResource = resourceSet.createResource(sourceUri); Map<String, Object> loadOpts = new HashMap<String, Object>(); if ("zxmi".equals(sourceUri.fileExtension())) { loadOpts.put(XMIResource.OPTION_ZIP, Boolean.TRUE); } Runtime.getRuntime().gc(); long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); LOG.log(Level.INFO, MessageFormat.format("Used memory before loading: {0}", MessageUtil.byteCountToDisplaySize(initialUsedMemory))); LOG.log(Level.INFO, "Loading source resource"); sourceResource.load(loadOpts); LOG.log(Level.INFO, "Source resource loaded"); Runtime.getRuntime().gc(); long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); LOG.log(Level.INFO, MessageFormat.format("Used memory after loading: {0}", MessageUtil.byteCountToDisplaySize(finalUsedMemory))); LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}", MessageUtil.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory))); Resource targetResource = resourceSet.createResource(targetUri); Map<String, Object> saveOpts = new HashMap<String, Object>(); List<StoreOption> storeOptions = new ArrayList<StoreOption>(); storeOptions.add(MapResourceOptions.EStoreMapOption.AUTOCOMMIT); saveOpts.put(MapResourceOptions.STORE_OPTIONS, storeOptions); targetResource.save(saveOpts); LOG.log(Level.INFO, "Start moving elements"); targetResource.getContents().clear(); targetResource.getContents().addAll(sourceResource.getContents()); LOG.log(Level.INFO, "End moving elements"); LOG.log(Level.INFO, "Start saving"); targetResource.save(saveOpts); LOG.log(Level.INFO, "Saved"); if (targetResource instanceof PersistentResourceImpl) { PersistentResourceImpl.shutdownWithoutUnload((PersistentResourceImpl) targetResource); } else { targetResource.unload(); } } catch (ParseException e) { MessageUtil.showError(e.toString()); MessageUtil.showError("Current arguments: " + Arrays.toString(args)); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar <this-file.jar>", options, true); } catch (Throwable e) { MessageUtil.showError(e.toString()); e.printStackTrace(); } }