List of usage examples for java.lang String equalsIgnoreCase
public boolean equalsIgnoreCase(String anotherString)
From source file:me.ryandowling.TwitchTools.java
public static void main(String[] args) { loadSettings();//from w w w. j av a 2s . c om Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { saveSettings(); } }); if (args.length == 0) { System.err.println("Invalid number of arguments specified!"); System.exit(1); } else if (args.length >= 1 && args.length <= 4) { switch (args[0]) { case "Followers": if (args.length == 4) { new Followers(args[1], Integer.parseInt(args[2]), Boolean.parseBoolean(args[3])).run(); } else { System.err.println("Invalid number of arguments specified!"); System.exit(1); } break; case "MicrophoneStatus": if (args.length == 3) { final int delay = Integer.parseInt(args[1]); final boolean guiDisplay = Boolean.parseBoolean(args[2]); new MicrophoneStatus(delay, guiDisplay); } else { System.err.println("Invalid number of arguments specified!"); System.err.println("Arguments are: [delay in ms for updates] [if the gui should show]!"); System.err.println("For example: [100] [true]!"); System.exit(1); } break; case "NowPlayingConverter": if (args.length == 2) { final int delay = Integer.parseInt(args[1]); new NowPlayingConverter(delay).run(); } else { System.err.println("Invalid number of arguments specified!"); System.err.println("Arguments are: [delay in ms for updates]!"); System.err.println("For example: [100]!"); System.exit(1); } break; case "MusicCreditsGenerator": if (args.length == 2) { final String type = args[1]; if (type.equalsIgnoreCase("html") || type.equalsIgnoreCase("october") || type.equalsIgnoreCase("markdown")) { new MusicCreditsGenerator(type).run(); } else { System.err.println("Invalid type argument specified!"); System.err.println("Arguments are: [type of output to generate (html|markdown|october)]!"); System.err.println("For example: [html]!"); System.exit(1); } } else { System.err.println("Invalid number of arguments specified!"); System.err.println("Arguments are: [delay in ms for updates]!"); System.err.println("For example: [100]!"); System.exit(1); } break; case "SteamGamesGenerator": if (args.length == 2) { final String type = args[1]; if (type.equalsIgnoreCase("october")) { new SteamGamesGenerator(type).run(); } else { System.err.println("Invalid type argument specified!"); System.err.println("Arguments are: [type of output to generate (october)]!"); System.err.println("For example: [october]!"); System.exit(1); } } else { System.err.println("Invalid number of arguments specified!"); System.err.println("Arguments are: [delay in ms for updates]!"); System.err.println("For example: [100]!"); System.exit(1); } break; case "FoobarControls": if (args.length == 1) { new FoobarControls().run(); } else { System.err.println("Invalid number of arguments specified!"); System.err.println("There are no arguments to provide!"); System.exit(1); } break; default: System.err.println("Invalid tool name specified!"); System.exit(1); } } }
From source file:com.ibm.crail.storage.StorageServer.java
public static void main(String[] args) throws Exception { Logger LOG = CrailUtils.getLogger(); CrailConfiguration conf = new CrailConfiguration(); CrailConstants.updateConstants(conf); CrailConstants.printConf();/*from w w w . ja v a2s.co m*/ CrailConstants.verify(); int splitIndex = 0; for (String param : args) { if (param.equalsIgnoreCase("--")) { break; } splitIndex++; } //default values StringTokenizer tokenizer = new StringTokenizer(CrailConstants.STORAGE_TYPES, ","); if (!tokenizer.hasMoreTokens()) { throw new Exception("No storage types defined!"); } String storageName = tokenizer.nextToken(); int storageType = 0; HashMap<String, Integer> storageTypes = new HashMap<String, Integer>(); storageTypes.put(storageName, storageType); for (int type = 1; tokenizer.hasMoreElements(); type++) { String name = tokenizer.nextToken(); storageTypes.put(name, type); } int storageClass = -1; //custom values if (args != null) { Option typeOption = Option.builder("t").desc("storage type to start").hasArg().build(); Option classOption = Option.builder("c").desc("storage class the server will attach to").hasArg() .build(); Options options = new Options(); options.addOption(typeOption); options.addOption(classOption); CommandLineParser parser = new DefaultParser(); try { CommandLine line = parser.parse(options, Arrays.copyOfRange(args, 0, splitIndex)); if (line.hasOption(typeOption.getOpt())) { storageName = line.getOptionValue(typeOption.getOpt()); storageType = storageTypes.get(storageName).intValue(); } if (line.hasOption(classOption.getOpt())) { storageClass = Integer.parseInt(line.getOptionValue(classOption.getOpt())); } } catch (ParseException e) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Storage tier", options); System.exit(-1); } } if (storageClass < 0) { storageClass = storageType; } StorageTier storageTier = StorageTier.createInstance(storageName); if (storageTier == null) { throw new Exception("Cannot instantiate datanode of type " + storageName); } String extraParams[] = null; splitIndex++; if (args.length > splitIndex) { extraParams = new String[args.length - splitIndex]; for (int i = splitIndex; i < args.length; i++) { extraParams[i - splitIndex] = args[i]; } } storageTier.init(conf, extraParams); storageTier.printConf(LOG); RpcClient rpcClient = RpcClient.createInstance(CrailConstants.NAMENODE_RPC_TYPE); rpcClient.init(conf, args); rpcClient.printConf(LOG); ConcurrentLinkedQueue<InetSocketAddress> namenodeList = CrailUtils.getNameNodeList(); ConcurrentLinkedQueue<RpcConnection> connectionList = new ConcurrentLinkedQueue<RpcConnection>(); while (!namenodeList.isEmpty()) { InetSocketAddress address = namenodeList.poll(); RpcConnection connection = rpcClient.connect(address); connectionList.add(connection); } RpcConnection rpcConnection = connectionList.peek(); if (connectionList.size() > 1) { rpcConnection = new RpcDispatcher(connectionList); } LOG.info("connected to namenode(s) " + rpcConnection.toString()); StorageServer server = storageTier.launchServer(); StorageRpcClient storageRpc = new StorageRpcClient(storageType, CrailStorageClass.get(storageClass), server.getAddress(), rpcConnection); HashMap<Long, Long> blockCount = new HashMap<Long, Long>(); long sumCount = 0; while (server.isAlive()) { StorageResource resource = server.allocateResource(); if (resource == null) { break; } else { storageRpc.setBlock(resource.getAddress(), resource.getLength(), resource.getKey()); DataNodeStatistics stats = storageRpc.getDataNode(); long newCount = stats.getFreeBlockCount(); long serviceId = stats.getServiceId(); long oldCount = 0; if (blockCount.containsKey(serviceId)) { oldCount = blockCount.get(serviceId); } long diffCount = newCount - oldCount; blockCount.put(serviceId, newCount); sumCount += diffCount; LOG.info("datanode statistics, freeBlocks " + sumCount); } } while (server.isAlive()) { DataNodeStatistics stats = storageRpc.getDataNode(); long newCount = stats.getFreeBlockCount(); long serviceId = stats.getServiceId(); long oldCount = 0; if (blockCount.containsKey(serviceId)) { oldCount = blockCount.get(serviceId); } long diffCount = newCount - oldCount; blockCount.put(serviceId, newCount); sumCount += diffCount; LOG.info("datanode statistics, freeBlocks " + sumCount); Thread.sleep(2000); } }
From source file:edu.msu.cme.rdp.classifier.ClassifierCmd.java
/** * This is the main method to do classification. * <p>Usage: java ClassifierCmd queryFile outputFile [property file]. * <br>//from w ww. ja v a2 s . c om * queryFile can be one of the following formats: Fasta, Genbank and EMBL. * <br> * outputFile will be used to save the classification output. * <br> * property file contains the mapping of the training files. * <br> * Note: the training files and the property file should be in the same directory. * The default property file is set to data/classifier/16srrna/rRNAClassifier.properties. */ public static void main(String[] args) throws Exception { String queryFile = null; String outputFile = null; String propFile = null; String gene = null; ClassificationResultFormatter.FORMAT format = CmdOptions.DEFAULT_FORMAT; int min_bootstrap_words = Classifier.MIN_BOOTSTRSP_WORDS; try { CommandLine line = new PosixParser().parse(options, args); if (line.hasOption(CmdOptions.OUTFILE_SHORT_OPT)) { outputFile = line.getOptionValue(CmdOptions.OUTFILE_SHORT_OPT); } else { throw new Exception("outputFile must be specified"); } 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 { propFile = line.getOptionValue(CmdOptions.TRAINPROPFILE_SHORT_OPT); } } 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("filterbyconf")) { format = ClassificationResultFormatter.FORMAT.filterbyconf; } else if (f.equalsIgnoreCase("db")) { format = ClassificationResultFormatter.FORMAT.dbformat; } else { throw new IllegalArgumentException( "Not valid output format, only allrank, fixrank, filterbyconf and db allowed"); } } if (line.hasOption(CmdOptions.GENE_SHORT_OPT)) { if (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)) { throw new IllegalArgumentException(gene + " is NOT valid, only allows " + ClassifierFactory.RRNA_16S_GENE + " and " + ClassifierFactory.FUNGALLSU_GENE); } } if (line.hasOption(CmdOptions.MIN_BOOTSTRAP_WORDS_SHORT_OPT)) { min_bootstrap_words = Integer .parseInt(line.getOptionValue(CmdOptions.MIN_BOOTSTRAP_WORDS_SHORT_OPT)); if (min_bootstrap_words < Classifier.MIN_BOOTSTRSP_WORDS) { throw new IllegalArgumentException(CmdOptions.MIN_BOOTSTRAP_WORDS_LONG_OPT + " must be at least " + Classifier.MIN_BOOTSTRSP_WORDS); } } args = line.getArgs(); if (args.length != 1) { throw new Exception("Expect one query file"); } queryFile = args[0]; } catch (Exception e) { System.out.println("Command Error: " + e.getMessage()); new HelpFormatter().printHelp(120, "ClassifierCmd [options] <samplefile>\nNote this is the legacy command for one sample classification ", "", options, ""); return; } if (propFile == null && gene == null) { gene = CmdOptions.DEFAULT_GENE; } ClassifierCmd classifierCmd = new ClassifierCmd(); printLicense(); classifierCmd.doClassify(queryFile, outputFile, propFile, format, gene, min_bootstrap_words); }
From source file:com.datastax.dse.demos.solr.Wikipedia.java
public static void main(String[] args) { if (args.length == 0) usage();/*from w w w.j av a2s . c om*/ System.out.println("args: " + Arrays.asList(args)); // parse args for (int i = 0; i < args.length; i = i + 2) { if (args[i].startsWith("--")) { try { String arg = args[i].substring(2); String value = args[i + 1]; if (arg.equalsIgnoreCase("wikifile")) wikifile = value; if (arg.equalsIgnoreCase("limit")) limit = Integer.parseInt(value); if (arg.equalsIgnoreCase("host")) host = value; if (arg.equalsIgnoreCase("scheme")) scheme = value; if (arg.equalsIgnoreCase("user")) user = value; if (arg.equalsIgnoreCase("password")) password = value; } catch (Throwable t) { usage(); } } } url = String.format(urlTemplate, scheme, host); // Initialize Solr with our custom HTTP Client helpers - which handle // SSL & Kerberos. We must have dse.yaml on the classpath for this try { if (DseConfig.isSslEnabled()) { SolrHttpClientInitializer .initEncryption(new EncryptionOptions().withSSLContext(DseConfig.getSSLContext()) .withHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)); } if (DseConfig.isKerberosEnabled()) { // Obtain kerberos credentials from local ticket cache AuthenticationOptions options = new AuthenticationOptions(); if (DseConfig.isSslEnabled()) { options.withSSLContext(DseConfig.getSSLContext()) .withHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } SolrHttpClientInitializer.initAuthentication(options); } } catch (Exception e) { System.out.println("Fatal error when initializing Solr clients, exiting"); e.printStackTrace(); System.exit(1); } System.out.println("Start indexing wikipedia..."); long startTime = System.currentTimeMillis(); indexWikipedia(); long endTime = System.currentTimeMillis(); System.out.println("Finished"); System.exit(0); }
From source file:io.github.the28awg.okato.App.java
public static void main(String[] args) { Options options = new Options(); options.addOption(Option.builder().longOpt("token").hasArg().required().argName("token") .desc(" ? ? ??").build()); options.addOption(Option.builder("t").longOpt("type").hasArg().required().argName("type") .desc(" [city, street, building]").build()); options.addOption(Option.builder("q").longOpt("query").hasArg().argName("query") .desc(" ? ? ").build()); options.addOption(Option.builder("c").longOpt("city_id").hasArg().argName("city_id") .desc(" (? )").build()); options.addOption(Option.builder("s").longOpt("street_id").hasArg().argName("street_id") .desc(" ").build()); CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd;// w w w . jav a2 s . c o m try { cmd = parser.parse(options, args); } catch (ParseException e) { System.out.println(e.getMessage()); formatter.printHelp("okato", options); System.exit(1); return; } AddressFactory.token(cmd.getOptionValue("token")); String arg_type = cmd.getOptionValue("type"); String arg_city_id = cmd.getOptionValue("city_id", ""); String arg_street_id = cmd.getOptionValue("street_id", ""); String arg_query = cmd.getOptionValue("query", ""); if (arg_type.equalsIgnoreCase("city")) { try { log(SimpleOkato.toSimpleResponse( AddressFactory.service().city(AddressFactory.token(), arg_query).execute().body())); } catch (IOException e) { e.printStackTrace(); } } else if (arg_type.equalsIgnoreCase("street")) { try { log(SimpleOkato.toSimpleResponse(AddressFactory.service() .street(AddressFactory.token(), arg_city_id, arg_query).execute().body())); } catch (IOException e) { e.printStackTrace(); } } else if (arg_type.equalsIgnoreCase("building")) { try { log(SimpleOkato.toSimpleResponse(AddressFactory.service() .building(AddressFactory.token(), arg_city_id, arg_street_id, arg_query).execute().body())); } catch (IOException e) { e.printStackTrace(); } } }
From source file:com.denimgroup.threadfix.importer.cli.CommandLineMigration.java
public static void main(String[] args) { if (!check(args)) return;//from www . j a va 2 s. c o m try { String inputScript = args[0]; String inputMySqlConfig = args[1]; String outputScript = "import.sql"; String outputMySqlConfigTemp = "jdbc_temp.properties"; String errorLogFile = "error.log"; String fixedSqlFile = "error_sql.sql"; String errorLogAttemp1 = "error1.log"; String infoLogFile = "info.log"; String rollbackScript = "rollback.sql"; deleteFile(outputScript); deleteFile(errorLogFile); deleteFile(errorLogFile); deleteFile(fixedSqlFile); deleteFile(errorLogAttemp1); deleteFile(infoLogFile); deleteFile(rollbackScript); PrintStream infoPrintStream = new PrintStream(new FileOutputStream(new File(infoLogFile))); System.setOut(infoPrintStream); long startTime = System.currentTimeMillis(); copyFile(inputMySqlConfig, outputMySqlConfigTemp); LOGGER.info("Creating threadfix table in mySql database ..."); ScriptRunner scriptRunner = SpringConfiguration.getContext().getBean(ScriptRunner.class); startTime = printTimeConsumed(startTime); convert(inputScript, outputScript); startTime = printTimeConsumed(startTime); PrintStream errPrintStream = new PrintStream(new FileOutputStream(new File(errorLogFile))); System.setErr(errPrintStream); LOGGER.info("Sending sql script to MySQL server ..."); scriptRunner.run(outputScript, outputMySqlConfigTemp); long errorCount = scriptRunner.checkRunningAndFixStatements(errorLogFile, fixedSqlFile); long lastCount = errorCount + 1; int times = 1; int sameFixedSet = 0; // Repeat while (errorCount > 0) { //Flush error log screen to other file errPrintStream = new PrintStream(new FileOutputStream(new File(errorLogAttemp1))); System.setErr(errPrintStream); times += 1; if (errorCount == lastCount) { sameFixedSet++; } else { sameFixedSet = 0; } LOGGER.info("Found " + errorCount + " error statements. Sending fixed sql script to MySQL server " + times + " times ..."); scriptRunner.run(fixedSqlFile, outputMySqlConfigTemp); lastCount = errorCount; errorCount = scriptRunner.checkRunningAndFixStatements(errorLogAttemp1, fixedSqlFile); if (errorCount > lastCount || sameFixedSet > SAME_SET_TRY_LIMIT) break; } if (errorCount > 0) { LOGGER.error("After " + times + " of trying, still found errors in sql script. " + "Please check error_sql.sql and error1.log for more details."); LOGGER.info("Do you want to keep data in MySQL, and then import manually error statements (y/n)? "); try (java.util.Scanner in = new java.util.Scanner(System.in)) { String answer = in.nextLine(); if (!answer.equalsIgnoreCase("y")) { rollbackData(scriptRunner, outputMySqlConfigTemp, rollbackScript); } else { LOGGER.info( "Data imported to MySQL, but still have some errors. Please check error_sql.sql and error1.log to import manually."); } } } else { printTimeConsumed(startTime); LOGGER.info("Migration successfully finished"); } deleteFile(outputMySqlConfigTemp); } catch (Exception e) { LOGGER.error("Error: ", e); } }
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/*ww w . j ava 2 s . c om*/ * @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.asquareb.kaaval.MachineKey.java
/** * Main method to execute as a command line utility. Provides the option to * encrypt a string, decrypt a encrypted string or exit from the program *///from w w w . java2s . c o m public static void main(String[] args) { String originalPassword = null; String encryptedPassword = null; try { final BufferedReader cin = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter E - Encrypt,D - Decrypt,X - Exit :"); final String choice = cin.readLine(); final Random rand = new Random(); boolean phraseCorrect = false; String app = null; if (choice.equalsIgnoreCase("E")) { System.out.print("Enter the string to encrypt :"); originalPassword = cin.readLine(); System.out.println("Choose a phrase of min 8 chars in length "); System.out.println(" Also the password should include 2 Cap,"); System.out.println(" 2 small letters,2 numeric and 2 non alpha numeric chars"); while (!phraseCorrect) { System.out.print("Enter a phrase to encrypt :"); password = cin.readLine().toCharArray(); phraseCorrect = PasswordRules.verifyPassword(password); } System.out.print("Enter application code :"); app = cin.readLine(); app += (rand.nextInt(10000)); encryptedPassword = encrypt(originalPassword, app); System.out.println("Encrypted password :" + encryptedPassword); System.out.println("Key stored in :" + app); System.out.println("*** Provide the encrypted string to app team"); System.out.println("*** Store the key file in a secure durectory"); System.out.println("*** Inform the key file name and location to app team"); } else if (choice.equalsIgnoreCase("D")) { System.out.print("Enter the string to Decrypt :"); encryptedPassword = cin.readLine(); System.out.print("Enter the name of key file :"); app = cin.readLine(); final String decryptedPassword = decrypt(encryptedPassword, app); System.out.print("Decrypted string :" + decryptedPassword); } return; } catch (KaavalException e) { e.PrintProtectException(); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.referencelogic.xmlormupload.main.XmlormuploadMain.java
public static void main(String args[]) { PropertyConfigurator.configure("log4j.properties"); isDebugging = log.isDebugEnabled();/*from w w w .ja v a2 s . com*/ for (String s : args) { log.debug("Processing parameter: " + s); if (matchRegex && matchRegexStr.equals("")) { matchRegexStr = s; log.debug("Set regex string to: " + matchRegexStr); } if (s.equalsIgnoreCase("--restrict")) { matchRegex = true; log.debug("Got restrict flag, so matching regex"); } } new XmlormuploadMain().run(); }
From source file:edu.usf.cutr.siri.SiriParserJacksonExample.java
/** * Takes in a path to a JSON or XML file, parses the contents into a Siri object, * and prints out the contents of the Siri object. * /*from ww w . j a va2s .c o m*/ * @param args path to the JSON or XML file located on disk */ public static void main(String[] args) { if (args[0] == null) { System.out.println("Proper Usage is: java JacksonSiriParserExample path-to-siri-file-to-parse"); System.exit(0); } try { //Siri object we're going to instantiate based on JSON or XML data Siri siri = null; //Get example JSON or XML from file File file = new File(args[0]); System.out.println("Input file = " + file.getAbsolutePath()); /* * Alternately, instead of passing in a File, a String encoded in JSON or XML can be * passed into Jackson for parsing. Uncomment the below line to read the * JSON or XML into the String. */ //String inputExample = readFile(file); String extension = FilenameUtils.getExtension(args[0]); if (extension.equalsIgnoreCase("json")) { System.out.println("Parsing JSON..."); ObjectMapper mapper = null; try { mapper = (ObjectMapper) SiriUtils.readFromCache(SiriUtils.OBJECT_MAPPER); } catch (Exception e) { System.out.println("Error reading from cache: " + e); } if (mapper == null) { // instantiate ObjectMapper like normal if cache read failed mapper = new ObjectMapper(); //Jackson 2.0 configuration settings mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true); mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true); mapper.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true); mapper.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true); //Tell Jackson to expect the JSON in PascalCase, instead of camelCase mapper.setPropertyNamingStrategy(new PropertyNamingStrategy.PascalCaseStrategy()); } //Deserialize the JSON from the file into the Siri object siri = mapper.readValue(file, Siri.class); /* * Alternately, you can also deserialize the JSON from a String into the Siri object. * Uncomment the below line to parsing the JSON from a String instead of the File. */ //siri = mapper.readValue(inputExample, Siri.class); //Write the ObjectMapper to the cache, to speed up parsing for the next execution SiriUtils.forceCacheWrite(mapper); } if (extension.equalsIgnoreCase("xml")) { System.out.println("Parsing XML..."); //Use Aalto StAX implementation explicitly XmlFactory f = new XmlFactory(new InputFactoryImpl(), new OutputFactoryImpl()); JacksonXmlModule module = new JacksonXmlModule(); /** * Tell Jackson that Lists are using "unwrapped" style (i.e., * there is no wrapper element for list). This fixes the error * "com.fasterxml.jackson.databind.JsonMappingException: Can not * >> instantiate value of type [simple type, class >> * uk.org.siri.siri.VehicleMonitoringDelivery] from JSON String; * no >> single-String constructor/factory method (through * reference chain: >> * uk.org.siri.siri.Siri["ServiceDelivery"]-> * uk.org.siri.siri.ServiceDel >> * ivery["VehicleMonitoringDelivery"])" * * NOTE - This requires Jackson v2.1 */ module.setDefaultUseWrapper(false); /** * Handles "xml:lang" attribute, which is used in SIRI * NaturalLanguage String, and looks like: <Description * xml:lang="EN">b/d 1:00pm until f/n. loc al and express buses * run w/delays & detours. POTUS visit in MANH. Allow additional * travel time Details at www.mta.info</Description> * * Passing "Value" (to match expected name in XML to map, * considering naming strategy) will make things work. This is * since JAXB uses pseudo-property name of "value" for XML Text * segments, whereas Jackson by default uses "" (to avoid name * collisions). * * NOTE - This requires Jackson v2.1 * * NOTE - This still requires a CustomPascalCaseStrategy to * work. Please see the CustomPascalCaseStrategy in this app * that is used below. */ module.setXMLTextElementName("Value"); XmlMapper xmlMapper = null; try { xmlMapper = (XmlMapper) SiriUtils.readFromCache(SiriUtils.XML_MAPPER); } catch (Exception e) { System.out.println("Error reading from cache: " + e); } if (xmlMapper == null) { xmlMapper = new XmlMapper(f, module); xmlMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); xmlMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true); xmlMapper.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true); xmlMapper.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true); /** * Tell Jackson to expect the XML in PascalCase, instead of camelCase * NOTE: We need the CustomPascalStrategy here to handle XML * namespace attributes such as xml:lang. See the comments in * CustomPascalStrategy for details. */ xmlMapper.setPropertyNamingStrategy(new CustomPascalCaseStrategy()); } //Parse the SIRI XML response siri = xmlMapper.readValue(file, Siri.class); //Write the XmlMapper to the cache, to speed up parsing for the next execution SiriUtils.forceCacheWrite(xmlMapper); } //If we successfully retrieved and parsed JSON or XML, print the contents if (siri != null) { SiriUtils.printContents(siri); } } catch (IOException e) { System.err.println("Error reading or parsing input file: " + e); } }