List of usage examples for java.lang String equals
public boolean equals(Object anObject)
From source file:kellinwood.zipsigner.cmdline.Main.java
public static void main(String[] args) { try {// www . j a v a 2 s . c o m Options options = new Options(); CommandLine cmdLine = null; Option helpOption = new Option("h", "help", false, "Display usage information"); Option modeOption = new Option("m", "keymode", false, "Keymode one of: auto, auto-testkey, auto-none, media, platform, shared, testkey, none"); modeOption.setArgs(1); Option keyOption = new Option("k", "key", false, "PCKS#8 encoded private key file"); keyOption.setArgs(1); Option pwOption = new Option("p", "keypass", false, "Private key password"); pwOption.setArgs(1); Option certOption = new Option("c", "cert", false, "X.509 public key certificate file"); certOption.setArgs(1); Option sbtOption = new Option("t", "template", false, "Signature block template file"); sbtOption.setArgs(1); Option keystoreOption = new Option("s", "keystore", false, "Keystore file"); keystoreOption.setArgs(1); Option aliasOption = new Option("a", "alias", false, "Alias for key/cert in the keystore"); aliasOption.setArgs(1); options.addOption(helpOption); options.addOption(modeOption); options.addOption(keyOption); options.addOption(certOption); options.addOption(sbtOption); options.addOption(pwOption); options.addOption(keystoreOption); options.addOption(aliasOption); Parser parser = new BasicParser(); try { cmdLine = parser.parse(options, args); } catch (MissingOptionException x) { System.out.println("One or more required options are missing: " + x.getMessage()); usage(options); } catch (ParseException x) { System.out.println(x.getClass().getName() + ": " + x.getMessage()); usage(options); } if (cmdLine.hasOption(helpOption.getOpt())) usage(options); Properties log4jProperties = new Properties(); log4jProperties.load(new FileReader("log4j.properties")); PropertyConfigurator.configure(log4jProperties); LoggerManager.setLoggerFactory(new Log4jLoggerFactory()); List<String> argList = cmdLine.getArgList(); if (argList.size() != 2) usage(options); ZipSigner signer = new ZipSigner(); signer.addAutoKeyObserver(new Observer() { @Override public void update(Observable observable, Object o) { System.out.println("Signing with key: " + o); } }); Class bcProviderClass = Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider"); Provider bcProvider = (Provider) bcProviderClass.newInstance(); KeyStoreFileManager.setProvider(bcProvider); signer.loadProvider("org.spongycastle.jce.provider.BouncyCastleProvider"); PrivateKey privateKey = null; if (cmdLine.hasOption(keyOption.getOpt())) { if (!cmdLine.hasOption(certOption.getOpt())) { System.out.println("Certificate file is required when specifying a private key"); usage(options); } String keypw = null; if (cmdLine.hasOption(pwOption.getOpt())) keypw = pwOption.getValue(); else { keypw = new String(readPassword("Key password")); if (keypw.equals("")) keypw = null; } URL privateKeyUrl = new File(keyOption.getValue()).toURI().toURL(); privateKey = signer.readPrivateKey(privateKeyUrl, keypw); } X509Certificate cert = null; if (cmdLine.hasOption(certOption.getOpt())) { if (!cmdLine.hasOption(keyOption.getOpt())) { System.out.println("Private key file is required when specifying a certificate"); usage(options); } URL certUrl = new File(certOption.getValue()).toURI().toURL(); cert = signer.readPublicKey(certUrl); } byte[] sigBlockTemplate = null; if (cmdLine.hasOption(sbtOption.getOpt())) { URL sbtUrl = new File(sbtOption.getValue()).toURI().toURL(); sigBlockTemplate = signer.readContentAsBytes(sbtUrl); } if (cmdLine.hasOption(keyOption.getOpt())) { signer.setKeys("custom", cert, privateKey, sigBlockTemplate); signer.signZip(argList.get(0), argList.get(1)); } else if (cmdLine.hasOption(modeOption.getOpt())) { signer.setKeymode(modeOption.getValue()); signer.signZip(argList.get(0), argList.get(1)); } else if (cmdLine.hasOption((keystoreOption.getOpt()))) { String alias = null; if (!cmdLine.hasOption(aliasOption.getOpt())) { KeyStore keyStore = KeyStoreFileManager.loadKeyStore(keystoreOption.getValue(), (char[]) null); for (Enumeration<String> e = keyStore.aliases(); e.hasMoreElements();) { alias = e.nextElement(); System.out.println("Signing with key: " + alias); break; } } else alias = aliasOption.getValue(); String keypw = null; if (cmdLine.hasOption(pwOption.getOpt())) keypw = pwOption.getValue(); else { keypw = new String(readPassword("Key password")); if (keypw.equals("")) keypw = null; } CustomKeySigner.signZip(signer, keystoreOption.getValue(), null, alias, keypw.toCharArray(), "SHA1withRSA", argList.get(0), argList.get(1)); } else { signer.setKeymode("auto-testkey"); signer.signZip(argList.get(0), argList.get(1)); } } catch (Throwable t) { t.printStackTrace(); } }
From source file:HierarchicalChat.java
/** Main program entry point. */ public static void main(String argv[]) { // Is there anything to do? if (argv.length == 0) { printUsage();/*from w w w .jav a2s . co m*/ System.exit(1); } // Values to be read from parameters String broker = DEFAULT_BROKER_NAME; String username = null; String password = DEFAULT_PASSWORD; String pubTopicname = DEFAULT_PUBLISHER_TOPIC; String subTopicname = DEFAULT_SUBSCRIBER_TOPIC; // Check parameters for (int i = 0; i < argv.length; i++) { String arg = argv[i]; // Options if (!arg.startsWith("-")) { System.err.println("error: unexpected argument - " + arg); printUsage(); System.exit(1); } else { if (arg.equals("-b")) { if (i == argv.length - 1 || argv[i + 1].startsWith("-")) { System.err.println("error: missing broker name:port"); System.exit(1); } broker = argv[++i]; continue; } if (arg.equals("-u")) { if (i == argv.length - 1 || argv[i + 1].startsWith("-")) { System.err.println("error: missing user name"); System.exit(1); } username = argv[++i]; continue; } if (arg.equals("-p")) { if (i == argv.length - 1 || argv[i + 1].startsWith("-")) { System.err.println("error: missing password"); System.exit(1); } password = argv[++i]; continue; } if (arg.equals("-t")) { if (i == argv.length - 1 || argv[i + 1].startsWith("-")) { System.err.println("error: missing publisher topic name"); System.exit(1); } pubTopicname = argv[++i]; continue; } if (arg.equals("-s")) { if (i == argv.length - 1 || argv[i + 1].startsWith("-")) { System.err.println("error: missing subscriber topic name"); System.exit(1); } subTopicname = argv[++i]; continue; } if (arg.equals("-h")) { printUsage(); System.exit(1); } } } // Check values read in. if (username == null) { System.err.println("error: user name must be supplied"); printUsage(); } // Start the JMS client for the "chat". HierarchicalChat chat = new HierarchicalChat(); chat.chatter(broker, username, password, pubTopicname, subTopicname); }
From source file:bankconsoleapp.console.Main.java
/** * @param args the command line arguments *//*ww w . j av a2 s.com*/ public static void main(String[] args) { //Injecting applicationContext to main ApplicationContext context = new ClassPathXmlApplicationContext("bankconsoleapp/applicationContext.xml"); EmployeeService eS = context.getBean("EmployeeService", EmployeeService.class); CustomerService cS = context.getBean("CustomerService", CustomerService.class); SavingService sS = context.getBean("SavingService", SavingService.class); String userName, pass; Scanner in = new Scanner(System.in); boolean user = false; boolean savingRedo = false; do { System.out.println("Enter Employee ID:"); userName = in.nextLine(); for (Employee emp : eS.getAllEmp()) { if (userName.equals(emp.geteID())) { System.out.println("Password:"); pass = in.nextLine(); for (Employee em : eS.getAllEmp()) { if (pass.equals(em.getPassword())) { user = true; } } } } } while (!user); long start = System.currentTimeMillis(); long end = start + 60 * 1000; // 60 seconds * 1000 ms/sec int operation = 0; int userChoice; boolean quit = false; do { System.out.println("ACME Bank Saving System:"); System.out.println("------------------------"); System.out.println("1. Create Customer & Saving Account"); System.out.println("2. Deposit Money"); System.out.println("3. Withdraw Money"); System.out.println("4. View Balance"); System.out.println("5. Quit"); System.out.print("Operation count: " + operation + "(Shut down at 5)"); userChoice = in.nextInt(); switch (userChoice) { case 1: //create customer, then saving account regard to existing customer( maximum 2 SA per Customer) System.out.println("Create Customer :"); String FirstN, LastN, DoB, accNum, answer; Scanner sc = new Scanner(System.in); Customer c = new Customer(); int saID = 0; System.out.println("Enter First Name:"); FirstN = sc.nextLine(); c.setFname(FirstN); System.out.println("Enter Last Name:"); LastN = sc.nextLine(); c.setLname(LastN); System.out.println("Enter Date of Birth:"); DoB = sc.nextLine(); c.setDoB(DoB); do { System.out.println("Creating saving acount, Enter Account Number:"); accNum = sc.nextLine(); c.setSA(accNum); c.setSavingAccounts(c.getSA()); saID++; System.out.println("Create another SA? Y/N?"); answer = sc.nextLine(); if (answer.equals("n")) { savingRedo = true; } if (saID == 2) { System.out.println("Maximum Saving account reached!"); } } while (!savingRedo && saID != 2); cS.createCustomer(c); operation++; break; case 2: // deposit String acNum; int amt; Scanner sc1 = new Scanner(System.in); System.out.println("Enter Saving Account number u wish to do deposit."); acNum = sc1.nextLine(); System.out.println("Enter amount :"); amt = sc1.nextInt(); sS.deposit(acNum, amt); operation++; break; case 3: String acNums; int amts; Scanner sc2 = new Scanner(System.in); System.out.println("Enter Saving Account number u wish to do withdraw."); acNums = sc2.nextLine(); System.out.println("Enter amount :"); amts = sc2.nextInt(); sS.withdraw(acNums, amts); operation++; break; case 4: // view System.out.println("Saving Account Balance:"); System.out.println(sS.getAllSA()); operation++; break; case 5: quit = true; break; default: System.out.println("Wrong choice."); break; } System.out.println(); if (operation == 5) { System.out.println("5 operation reached, System shutdown."); } if (System.currentTimeMillis() > end) { System.out.println("Session Expired."); } } while (!quit && operation != 5 && System.currentTimeMillis() < end); System.out.println("Bye!"); }
From source file:com.cloud.utils.crypt.EncryptionSecretKeyChanger.java
public static void main(String[] args) { List<String> argsList = Arrays.asList(args); Iterator<String> iter = argsList.iterator(); String oldMSKey = null;/* ww w. j ava 2s . c o m*/ String oldDBKey = null; String newMSKey = null; String newDBKey = null; //Parse command-line args while (iter.hasNext()) { String arg = iter.next(); // Old MS Key if (arg.equals("-m")) { oldMSKey = iter.next(); } // Old DB Key if (arg.equals("-d")) { oldDBKey = iter.next(); } // New MS Key if (arg.equals("-n")) { newMSKey = iter.next(); } // New DB Key if (arg.equals("-e")) { newDBKey = iter.next(); } } if (oldMSKey == null || oldDBKey == null) { System.out.println("Existing MS secret key or DB secret key is not provided"); usage(); return; } if (newMSKey == null && newDBKey == null) { System.out.println("New MS secret key and DB secret are both not provided"); usage(); return; } final File dbPropsFile = PropertiesUtil.findConfigFile("db.properties"); final Properties dbProps; EncryptionSecretKeyChanger keyChanger = new EncryptionSecretKeyChanger(); StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor(); keyChanger.initEncryptor(encryptor, oldMSKey); dbProps = new EncryptableProperties(encryptor); PropertiesConfiguration backupDBProps = null; System.out.println("Parsing db.properties file"); try { dbProps.load(new FileInputStream(dbPropsFile)); backupDBProps = new PropertiesConfiguration(dbPropsFile); } catch (FileNotFoundException e) { System.out.println("db.properties file not found while reading DB secret key" + e.getMessage()); } catch (IOException e) { System.out.println("Error while reading DB secret key from db.properties" + e.getMessage()); } catch (ConfigurationException e) { e.printStackTrace(); } String dbSecretKey = null; try { dbSecretKey = dbProps.getProperty("db.cloud.encrypt.secret"); } catch (EncryptionOperationNotPossibleException e) { System.out.println("Failed to decrypt existing DB secret key from db.properties. " + e.getMessage()); return; } if (!oldDBKey.equals(dbSecretKey)) { System.out.println("Incorrect MS Secret Key or DB Secret Key"); return; } System.out.println("Secret key provided matched the key in db.properties"); final String encryptionType = dbProps.getProperty("db.cloud.encryption.type"); if (newMSKey == null) { System.out.println("No change in MS Key. Skipping migrating db.properties"); } else { if (!keyChanger.migrateProperties(dbPropsFile, dbProps, newMSKey, newDBKey)) { System.out.println("Failed to update db.properties"); return; } else { //db.properties updated successfully if (encryptionType.equals("file")) { //update key file with new MS key try { FileWriter fwriter = new FileWriter(keyFile); BufferedWriter bwriter = new BufferedWriter(fwriter); bwriter.write(newMSKey); bwriter.close(); } catch (IOException e) { System.out.println("Failed to write new secret to file. Please update the file manually"); } } } } boolean success = false; if (newDBKey == null || newDBKey.equals(oldDBKey)) { System.out.println("No change in DB Secret Key. Skipping Data Migration"); } else { EncryptionSecretKeyChecker.initEncryptorForMigration(oldMSKey); try { success = keyChanger.migrateData(oldDBKey, newDBKey); } catch (Exception e) { System.out.println("Error during data migration"); e.printStackTrace(); success = false; } } if (success) { System.out.println("Successfully updated secret key(s)"); } else { System.out.println("Data Migration failed. Reverting db.properties"); //revert db.properties try { backupDBProps.save(); } catch (ConfigurationException e) { e.printStackTrace(); } if (encryptionType.equals("file")) { //revert secret key in file try { FileWriter fwriter = new FileWriter(keyFile); BufferedWriter bwriter = new BufferedWriter(fwriter); bwriter.write(oldMSKey); bwriter.close(); } catch (IOException e) { System.out.println("Failed to revert to old secret to file. Please update the file manually"); } } } }
From source file:com.kynetx.RubyRulesetParser.java
public static void main(String[] args) throws Exception { File thefile = new File(args[0]); String result_type = args[1]; try {/*from w ww. j a v a 2 s. c o m*/ ANTLRFileStream input = new ANTLRFileStream(thefile.getCanonicalPath()); com.kynetx.RuleSetLexer lexer = new com.kynetx.RuleSetLexer(input); CommonTokenStream tokens = new CommonTokenStream(lexer); com.kynetx.RuleSetParser parser = new com.kynetx.RuleSetParser(tokens); parser.ruleset(); JSONObject js = new JSONObject(parser.rule_json); if (result_type.equals("validate")) { if (parser.parse_errors.size() > 0) { for (int ii = 0; ii < parser.parse_errors.size(); ii++) { System.out.println("ERROR: " + parser.parse_errors.get(ii)); } } } else { System.out.println(js.toString()); // System.out.println(unescapeUnicode(js.toString())); } } catch (Exception e) { System.out.println("SYSTEM ERROR : " + e.getMessage()); } }
From source file:com.act.lcms.db.io.LoadStandardIonAnalysisTableIntoDB.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 ww.j a v a 2 s. c o m } 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(LoadStandardIonAnalysisTableIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } if (cl.hasOption("help")) { HELP_FORMATTER.printHelp(LoadStandardIonAnalysisTableIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); return; } File inputFile = new File(cl.getOptionValue(OPTION_FILE_PATH)); if (!inputFile.exists()) { System.err.format("Unable to find input file at %s\n", cl.getOptionValue(OPTION_FILE_PATH)); new HelpFormatter().printHelp(LoadConstructAnalysisTableIntoDB.class.getCanonicalName(), opts, true); System.exit(1); } try (DB db = DB.openDBFromCLI(cl)) { db.getConn().setAutoCommit(false); TSVParser parser = new TSVParser(); parser.parse(inputFile); for (Map<String, String> row : parser.getResults()) { Integer standardIonResultId = Integer.parseInt(row.get( ExportStandardIonResultsFromDB.STANDARD_ION_HEADER_FIELDS.STANDARD_ION_RESULT_ID.name())); String dbValueOfMetlinIon = ExportStandardIonResultsFromDB.NULL_VALUE; StandardIonResult ionResult = StandardIonResult.getInstance().getById(db, standardIonResultId); if (ionResult.getManualOverrideId() != null) { // There is an existing manual override ion in the DB CuratedStandardMetlinIon curatedChemical = CuratedStandardMetlinIon.getBestMetlinIon(db, ionResult.getManualOverrideId()); dbValueOfMetlinIon = curatedChemical.getBestMetlinIon(); } String manualPickOfMetlinIon = row .get(ExportStandardIonResultsFromDB.STANDARD_ION_HEADER_FIELDS.MANUAL_PICK.name()); // If the manual metlin ion pick row is not NULL and it is not the same as the value stored in the DB, then // we need to add a new entry to the curated metlin ion table. if (!manualPickOfMetlinIon.equals(ExportStandardIonResultsFromDB.NULL_VALUE) && !manualPickOfMetlinIon.equals(dbValueOfMetlinIon)) { System.out.format("Manual override has been found, so updating the DB\n"); // A manual entry was created. if (!MS1.VALID_MS1_IONS.contains(manualPickOfMetlinIon)) { System.err.format("ERROR: found invalid chemical name: %s\n", manualPickOfMetlinIon); System.exit(-1); } String note = row.get(ExportStandardIonResultsFromDB.STANDARD_ION_HEADER_FIELDS.NOTE.name()); CuratedStandardMetlinIon result = CuratedStandardMetlinIon.insertCuratedStandardMetlinIonIntoDB( db, LocalDateTime.now(CuratedStandardMetlinIon.utcDateTimeZone), cl.getOptionValue(OPTION_AUTHOR), manualPickOfMetlinIon, note, standardIonResultId); if (result == null) { System.err.format( "WARNING: Could not insert curated entry to the curated metlin ion table\n", manualPickOfMetlinIon); System.exit(-1); } else { StandardIonResult getIonResult = StandardIonResult.getInstance().getById(db, standardIonResultId); getIonResult.setManualOverrideId(result.getId()); if (!StandardIonResult.getInstance().update(db, getIonResult)) { System.err.format( "WARNING: Could not insert manual override id to the standard ion table\n", manualPickOfMetlinIon); System.exit(-1); } else { System.out.format( "Successfully committed updates to the standard ion table and the curated metlin ion table\n"); } } } } db.getConn().commit(); } }
From source file:com.browseengine.bobo.serialize.JSONSerializer.java
public static void main(String[] args) throws Exception { class B implements JSONSerializable { transient int tIntVal = 6; String s = "bstring"; float[] fArray = new float[] { 1.3f, 1.2f, 2.5f }; }//www .java 2s. com class C implements JSONExternalizable { private HashMap<String, String> map = new HashMap<String, String>(); public void fromJSON(JSONObject obj) throws JSONSerializationException, JSONException { map.clear(); Iterator iter = obj.keys(); while (iter.hasNext()) { String key = (String) iter.next(); String val = obj.getString(key); map.put(key, val); } } public JSONObject toJSON() throws JSONSerializationException, JSONException { JSONObject retVal = new JSONObject(); Iterator<String> iter = map.keySet().iterator(); while (iter.hasNext()) { String name = iter.next(); String val = map.get(name); retVal.put(name, val); } return retVal; } public void set(String name, String val) { map.put(name, val); } } class A implements JSONSerializable { int intVal = 4; double doubleVal = 1.2; short shortVal = 12; HashMap hash = new HashMap(); int[] intArray = new int[] { 1, 3 }; String[] strArray = new String[] { "john", "wang" }; B[] b = new B[] { new B(), new B() }; B b2 = new B(); C c = new C(); A() { c.set("city", "san jose"); c.set("country", "usa"); } } JSONObject jsonObj = JSONSerializer.serializeJSONObject(new A()); String s1 = jsonObj.toString(); System.out.println(s1); A a = (A) deSerialize(A.class, jsonObj); jsonObj = JSONSerializer.serializeJSONObject(a); String s2 = jsonObj.toString(); System.out.println(s1.equals(s2)); }
From source file:de.unibremen.informatik.tdki.combo.ui.CommandComplete.java
public static void main(String[] args) { JCommander jc = new JCommander(); CommandComplete complete = new CommandComplete(); jc.addCommand("complete", complete); CommandCreate create = new CommandCreate(); jc.addCommand("create", create); CommandDelete delete = new CommandDelete(); jc.addCommand("delete", delete); CommandDropFilters dropFilter = new CommandDropFilters(); jc.addCommand("dropf", dropFilter); CommandExport export = new CommandExport(); jc.addCommand("export", export); CommandHelp help = new CommandHelp(); jc.addCommand("help", help); CommandInit init = new CommandInit(); jc.addCommand("init", init); CommandList list = new CommandList(); jc.addCommand("list", list); CommandLoad load = new CommandLoad(); jc.addCommand("load", load); CommandRewriteDatalog rwDatalog = new CommandRewriteDatalog(); jc.addCommand("rwd", rwDatalog); CommandRewriteFilter rwFilter = new CommandRewriteFilter(); jc.addCommand("rwf", rwFilter); CommandRunStats runStats = new CommandRunStats(); jc.addCommand("runstats", runStats); DBConnPool pool = null;// w ww . j a va2 s .c o m try { jc.parse(args); String command = jc.getParsedCommand(); if (command.equals("help")) { jc.usage(); return; } pool = new DBConnPool(DBConfig.fromPropertyFile()); connection = pool.getConnection(); DBLayout layout = new DBLayout(false, connection); if (command.equals("complete")) { for (String name : complete.getProjects()) { layout.completeData(name); } } else if (command.equals("create")) { for (String name : create.getProjects()) { if (layout.createProject(name)) { System.out.println(name + " already exists; not creating."); } } } else if (command.equals("delete")) { for (String name : delete.getProjects()) { layout.dropProject(name); } } else if (command.equals("dropf")) { dropFilter(); } else if (command.equals("export")) { boolean projectExists = layout.exportProject(export.getProject(), new File(export.getFile())); if (!projectExists) { System.err.println("Project " + export.getProject() + " does not exist."); } } else if (command.equals("init")) { layout.initialize(); } else if (command.equals("list")) { List<String> projects = layout.getProjects(); for (String p : projects) { System.out.println(p); } } else if (command.equals("load")) { boolean projectExists = layout.loadProject(new File(load.getFile()), load.getProject()); if (!projectExists) { System.err.println("Project " + load.getProject() + " does not exist."); } } else if (command.equals("rwd")) { generateDatalog(rwDatalog); } else if (command.equals("rwf")) { generateFilter(rwFilter); } else if (command.equals("runstats")) { for (String name : runStats.getProjects()) { layout.updateStatistics(name); } } } catch (ParameterException e) { System.err.println(e.getMessage()); System.err.println("Try the 'help' command for usage."); } finally { if (pool != null) pool.releaseConnection(connection); } }
From source file:jfractus.app.Main.java
public static void main(String[] args) { createCommandLineOptions();//from w w w . j a va 2 s . c o m GnuParser parser = new GnuParser(); HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.setOptionComparator(null); CommandLine cmdLine = null; try { cmdLine = parser.parse(cliOptions, args); } catch (ParseException e) { System.err.println(Resources.getString("CLIParseError")); return; } String functionsLibPaths = cmdLine.getOptionValue("libraries"); int threadsNum = FractusPreferencesFactory.prefs.getThreadsNumber(); Dimension outSize = new Dimension(FractusPreferencesFactory.prefs.getDefaultImageWidth(), FractusPreferencesFactory.prefs.getDefaultImageHeight()); AntialiasConfig aaConfig = FractusPreferencesFactory.prefs.getDefaultAntialiasConfig(); boolean printProgress = cmdLine.hasOption("progress"); try { String threadsNumString = cmdLine.getOptionValue("threads"); String imageSizeString = cmdLine.getOptionValue("image-size"); String aaMethodString = cmdLine.getOptionValue("antialias"); String samplingSizeString = cmdLine.getOptionValue("sampling-size"); if (functionsLibPaths != null) FunctionsLoaderFactory.loader.setClassPathsFromString(functionsLibPaths); if (aaMethodString != null) { if (aaMethodString.equals("none")) aaConfig.setMethod(AntialiasConfig.Method.NONE); else if (aaMethodString.equals("normal")) aaConfig.setMethod(AntialiasConfig.Method.NORMAL); else throw new BadValueOfArgumentException("Bad value of argument"); } if (threadsNumString != null) threadsNum = Integer.valueOf(threadsNumString).intValue(); if (imageSizeString != null) parseSize(imageSizeString, outSize); if (samplingSizeString != null) { Dimension samplingSize = new Dimension(); parseSize(samplingSizeString, samplingSize); aaConfig.setSamplingSize(samplingSize.width, samplingSize.height); } if (cmdLine.hasOption("save-prefs")) { FunctionsLoaderFactory.loader.putClassPathsToPrefs(); FractusPreferencesFactory.prefs.setThreadsNumber(threadsNum); FractusPreferencesFactory.prefs.setDefaultImageSize(outSize.width, outSize.height); FractusPreferencesFactory.prefs.setDefaultAntialiasConfig(aaConfig); } } catch (ArgumentParseException e) { System.err.println(Resources.getString("CLIParseError")); return; } catch (NumberFormatException e) { System.err.println(Resources.getString("CLIParseError")); return; } catch (BadValueOfArgumentException e) { System.err.println(Resources.getString("CLIBadValueError")); return; } if (cmdLine.hasOption('h') || (cmdLine.hasOption('n') && cmdLine.getArgs().length < 2)) { helpFormatter.printHelp(Resources.getString("CLISyntax"), cliOptions); return; } if (!cmdLine.hasOption('n')) { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } else { String[] cmdArgs = cmdLine.getArgs(); try { FractalDocument fractal = new FractalDocument(); fractal.readFromFile(new File(cmdArgs[0])); FractalRenderer renderer = new FractalRenderer(outSize.width, outSize.height, aaConfig, fractal); FractalImageWriter imageWriter = new FractalImageWriter(renderer, cmdArgs[1]); renderer.setThreadNumber(threadsNum); renderer.prepareFractal(); if (printProgress) { renderer.addRenderProgressListener(new CMDLineProgressEventListener()); imageWriter.addImageWriterProgressListener(new CMDLineImageWriteProgressListener()); } imageWriter.write(); } catch (Exception e) { System.err.println(e.getMessage()); } } }
From source file:com.cloud.test.utils.TestClient.java
public static void main(String[] args) { String host = "http://localhost"; String port = "8080"; String testUrl = "/client/test"; int numThreads = 1; try {//from ww w . j a v a 2 s . c o m // Parameters List<String> argsList = Arrays.asList(args); Iterator<String> iter = argsList.iterator(); while (iter.hasNext()) { String arg = iter.next(); // host if (arg.equals("-h")) { host = "http://" + iter.next(); } if (arg.equals("-p")) { port = iter.next(); } if (arg.equals("-t")) { numThreads = Integer.parseInt(iter.next()); } if (arg.equals("-s")) { sleepTime = Long.parseLong(iter.next()); } if (arg.equals("-c")) { cleanUp = Boolean.parseBoolean(iter.next()); if (!cleanUp) sleepTime = 0L; // no need to wait if we don't ever cleanup } if (arg.equals("-r")) { repeat = Boolean.parseBoolean(iter.next()); } if (arg.equals("-u")) { numOfUsers = Integer.parseInt(iter.next()); } if (arg.equals("-i")) { internet = Boolean.parseBoolean(iter.next()); } } final String server = host + ":" + port + testUrl; s_logger.info("Starting test against server: " + server + " with " + numThreads + " thread(s)"); if (cleanUp) s_logger.info("Clean up is enabled, each test will wait " + sleepTime + " ms before cleaning up"); if (numOfUsers > 0) { s_logger.info("Pre-generating users for test of size : " + numOfUsers); users = new String[numOfUsers]; Random ran = new Random(); for (int i = 0; i < numOfUsers; i++) { users[i] = Math.abs(ran.nextInt()) + "-user"; } } for (int i = 0; i < numThreads; i++) { new Thread(new Runnable() { public void run() { do { String username = null; try { long now = System.currentTimeMillis(); Random ran = new Random(); if (users != null) { username = users[Math.abs(ran.nextInt()) % numOfUsers]; } else { username = Math.abs(ran.nextInt()) + "-user"; } NDC.push(username); String url = server + "?email=" + username + "&password=" + username + "&command=deploy"; s_logger.info("Launching test for user: " + username + " with url: " + url); HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(url); int responseCode = client.executeMethod(method); boolean success = false; String reason = null; if (responseCode == 200) { if (internet) { s_logger.info("Deploy successful...waiting 5 minute before SSH tests"); Thread.sleep(300000L); // Wait 60 seconds so the linux VM can boot up. s_logger.info("Begin Linux SSH test"); reason = sshTest(method.getResponseHeader("linuxIP").getValue()); if (reason == null) { s_logger.info("Linux SSH test successful"); s_logger.info("Begin Windows SSH test"); reason = sshWinTest(method.getResponseHeader("windowsIP").getValue()); } } if (reason == null) { if (internet) { s_logger.info("Windows SSH test successful"); } else { s_logger.info("deploy test successful....now cleaning up"); if (cleanUp) { s_logger.info( "Waiting " + sleepTime + " ms before cleaning up vms"); Thread.sleep(sleepTime); } else { success = true; } } if (users == null) { s_logger.info("Sending cleanup command"); url = server + "?email=" + username + "&password=" + username + "&command=cleanup"; } else { s_logger.info("Sending stop DomR / destroy VM command"); url = server + "?email=" + username + "&password=" + username + "&command=stopDomR"; } method = new GetMethod(url); responseCode = client.executeMethod(method); if (responseCode == 200) { success = true; } else { reason = method.getStatusText(); } } else { // Just stop but don't destroy the VMs/Routers s_logger.info("SSH test failed with reason '" + reason + "', stopping VMs"); url = server + "?email=" + username + "&password=" + username + "&command=stop"; responseCode = client.executeMethod(new GetMethod(url)); } } else { // Just stop but don't destroy the VMs/Routers reason = method.getStatusText(); s_logger.info("Deploy test failed with reason '" + reason + "', stopping VMs"); url = server + "?email=" + username + "&password=" + username + "&command=stop"; client.executeMethod(new GetMethod(url)); } if (success) { s_logger.info("***** Completed test for user : " + username + " in " + ((System.currentTimeMillis() - now) / 1000L) + " seconds"); } else { s_logger.info("##### FAILED test for user : " + username + " in " + ((System.currentTimeMillis() - now) / 1000L) + " seconds with reason : " + reason); } } catch (Exception e) { s_logger.warn("Error in thread", e); try { HttpClient client = new HttpClient(); String url = server + "?email=" + username + "&password=" + username + "&command=stop"; client.executeMethod(new GetMethod(url)); } catch (Exception e1) { } } finally { NDC.clear(); } } while (repeat); } }).start(); } } catch (Exception e) { s_logger.error(e); } }