List of usage examples for java.lang String indexOf
public int indexOf(String str)
From source file:de.hpi.fgis.hdrs.tools.Loader.java
public static void main(String[] args) throws IOException { if (2 > args.length) { System.out.println(usage); System.out.println(options); System.exit(1);// www. ja v a 2 s . c o m } if (0 > args[0].indexOf(':')) { args[0] += ":" + Configuration.DEFAULT_RPC_PORT; } Configuration conf = Configuration.create(); Client client = new Client(conf, args[0]); File[] files; String options = ""; if (args[1].startsWith("-")) { options = args[1]; if (3 > args.length) { System.out.println(usage); System.exit(1); } if (0 < options.indexOf('d')) { File dir = new File(args[2]); if (!dir.isDirectory()) { throw new IOException("Directory does not exist."); } files = dir.listFiles(); } else { files = new File[] { new File(args[2]) }; } } else { files = new File[] { new File(args[1]) }; } boolean quiet = 0 < options.indexOf('q'); boolean context = 0 < options.indexOf('c'); boolean bench = 0 < options.indexOf('b'); List<BenchSample> benchSamples = null; if (bench) { benchSamples = new ArrayList<BenchSample>(); } long timeStalled = 0; long timeRouterUpdate = 0; long abortedTransactions = 0; long nBytesTotal = 0; long nTriplesTotal = 0; long timeTotal = 0; for (int i = 0; i < files.length; ++i) { Closeable source = null; TripleScanner scanner = null; try { if (0 < options.indexOf('t')) { TripleFileReader reader = new TripleFileReader(files[i]); reader.open(); scanner = reader.getScanner(); source = reader; } else if (0 < options.indexOf('z')) { GZIPInputStream stream = new GZIPInputStream(new FileInputStream(files[i])); BTCParser parser = new BTCParser(); parser.setSkipContext(!context); scanner = new StreamScanner(stream, parser); source = stream; } else { BTCParser parser = new BTCParser(); parser.setSkipContext(!context); FileSource file = new FileSource(files[i], parser); scanner = file.getScanner(); source = file; } } catch (IOException ioe) { System.out.println("Error: Couldn't open " + files[i] + ". See log for details."); LOG.error("Error: Couldn't open " + files[i] + ":", ioe); continue; } long nBytes = 0; long nTriples = 0; long time = System.currentTimeMillis(); TripleOutputStream out = client.getOutputStream(); while (scanner.next()) { Triple t = scanner.pop(); out.add(t); nBytes += t.serializedSize(); nTriples++; if (!quiet && 0 == (nTriples % (16 * 1024))) { System.out.print(String.format("\rloading... %d triples (%.2f MB, %.2f MB/s)", nTriples, LogFormatUtil.MB(nBytes), LogFormatUtil.MBperSec(nBytes, System.currentTimeMillis() - time))); } } out.close(); time = System.currentTimeMillis() - time; scanner.close(); source.close(); if (!quiet) { System.out.print("\r"); } System.out.println(String.format("%s: %d triples (%.2f MB) loaded " + "in %.2f seconds (%.2f MB/s)", files[i], nTriples, LogFormatUtil.MB(nBytes), time / 1000.0, LogFormatUtil.MBperSec(nBytes, time))); nBytesTotal += nBytes; nTriplesTotal += nTriples; timeTotal += time; timeStalled += out.getTimeStalled(); timeRouterUpdate += out.getTimeRouterUpdate(); abortedTransactions += out.getAbortedTransactions(); if (bench) { benchSamples.add(new BenchSample(time, nTriples, nBytes)); } } client.close(); if (0 == nTriplesTotal) { System.out.println("No triples loaded."); return; } System.out.println( String.format("Done loading. Totals: %d triples (%.2f MB) loaded " + "in %.2f seconds (%.2f MB/s)", nTriplesTotal, LogFormatUtil.MB(nBytesTotal), timeTotal / 1000.0, LogFormatUtil.MBperSec(nBytesTotal, timeTotal))); System.out.println(String.format( " Client stats. Stalled: %.2f s RouterUpdate: %.2f s" + " AbortedTransactions: %d", timeStalled / 1000.0, timeRouterUpdate / 1000.0, abortedTransactions)); if (bench) { System.out.println(); System.out.println("Benchmark Samples:"); System.out.println("time\tsum T\tsum MB\tMB/s"); System.out.println(String.format("%.2f\t%d\t%.2f\t%.2f", 0f, 0, 0f, 0f)); long time = 0, nTriples = 0, nBytes = 0; for (BenchSample sample : benchSamples) { time += sample.time; nTriples += sample.nTriples; nBytes += sample.nBytes; System.out.println(String.format("%.2f\t%d\t%.2f\t%.2f", time / 1000.0, nTriples, LogFormatUtil.MB(nBytes), LogFormatUtil.MBperSec(sample.nBytes, sample.time))); } } }
From source file:com.mycompany.test.Jaroop.java
/** * This is the main program which will receive the request, calls required methods * and processes the response.// w w w . j a va 2s.c o m * @param args * @throws IOException */ public static void main(String[] args) throws IOException { Scanner scannedInput = new Scanner(System.in); String in = ""; if (args.length == 0) { System.out.println("Enter the query"); in = scannedInput.nextLine(); } else { in = args[0]; } in = in.toLowerCase().replaceAll("\\s+", "_"); int httpStatus = checkInvalidInput(in); if (httpStatus == 0) { System.out.print("Not found"); System.exit(0); } String url = "https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=" + in; HttpURLConnection connection = getConnection(url); BufferedReader input = new BufferedReader(new InputStreamReader(connection.getInputStream())); String request = ""; StringBuilder response = new StringBuilder(); while ((request = input.readLine()) != null) { //only appending what ever is required for JSON parsing and ignoring the rest response.append("{"); //appending the key "extract" to the string so that the JSON parser can parse it's value, //also we don't need last 3 paranthesis in the response, excluding them as well. response.append(request.substring(request.indexOf("\"extract"), request.length() - 3)); } parseJSON(response.toString()); }
From source file:MainClass.java
public static void main(String args[]) throws Exception { SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); ServerSocket ss = ssf.createServerSocket(443); while (true) { Socket s = ss.accept();// w ww . j a v a 2 s . c o m PrintStream out = new PrintStream(s.getOutputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream())); String info = null; String request = null; String refer = null; while ((info = in.readLine()) != null) { if (info.startsWith("GET")) { request = info; } if (info.startsWith("Referer:")) { refer = info; } if (info.equals("")) break; } if (request != null) { out.println("HTTP/1.0 200 OK\nMIME_version:1.0\nContent_Type:text/html"); int sp1 = request.indexOf(' '); int sp2 = request.indexOf(' ', sp1 + 1); String filename = request.substring(sp1 + 2, sp2); if (refer != null) { sp1 = refer.indexOf(' '); refer = refer.substring(sp1 + 1, refer.length()); if (!refer.endsWith("/")) { refer = refer + "/"; } filename = refer + filename; } URL con = new URL(filename); InputStream gotoin = con.openStream(); int n = gotoin.available(); byte buf[] = new byte[1024]; out.println("HTTP/1.0 200 OK\nMIME_version:1.0\nContent_Type:text/html"); out.println("Content_Length:" + n + "\n"); while ((n = gotoin.read(buf)) >= 0) { out.write(buf, 0, n); } out.close(); s.close(); in.close(); } } }
From source file:name.livitski.databag.cli.Syntax.java
/** * Diagnostic entry point for the build process to check that all * usage strings that describe the application's syntax are present * in <code>usage.resources</code>. * Absent resources cause a <code>System.err</code> message * and a non-zero exit code./*from www. j a v a2 s. c o m*/ * @param args this method ignores its argument */ @SuppressWarnings("unchecked") public static void main(String[] args) { PrintStream out = System.err; Resources resources = new Resources(); final Class<Syntax> clazz = Syntax.class; String id = null; String legend = null; for (Option option : (Collection<Option>) OPTIONS.getOptions()) { try { id = getOptionId(option); legend = resources.getString(USAGE_BUNDLE, clazz, id).trim(); if (legend.indexOf('.') < legend.length() - 1) { out.printf( "Description of option %s must be a single sentence ending with a period. Got:%n\"%s\"%n", id, legend); System.exit(5); } if (option.hasArg()) resources.getString(USAGE_BUNDLE, clazz, "arg" + id); legend = null; } catch (MissingResourceException missing) { if (null == legend) { out.printf("Option \"%s\" does not have a description string in the resource bundle \"%s\"%n", id, USAGE_BUNDLE); missing.printStackTrace(out); System.exit(1); } out.printf("Required argument spec \"%s\" is missing from the resource bundle \"%s\"%n", getArgumentId(option), USAGE_BUNDLE); missing.printStackTrace(out); System.exit(2); } catch (Exception problem) { out.printf("Error while verifying option \"%s\" in the resource bundle \"%s\"%n", id, USAGE_BUNDLE); problem.printStackTrace(out); System.exit(-1); } } }
From source file:de.jetwick.snacktory.HtmlFetcher.java
public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new FileReader("urls.txt")); String line = null; Set<String> existing = new LinkedHashSet<String>(); while ((line = reader.readLine()) != null) { int index1 = line.indexOf("\""); int index2 = line.indexOf("\"", index1 + 1); String url = line.substring(index1 + 1, index2); String domainStr = SHelper.extractDomain(url, true); String counterStr = ""; // TODO more similarities if (existing.contains(domainStr)) counterStr = "2"; else/*from w ww . ja v a2 s . c o m*/ existing.add(domainStr); String html = new HtmlFetcher().fetchAsString(url, 20000); String outFile = domainStr + counterStr + ".html"; BufferedWriter writer = new BufferedWriter(new FileWriter(outFile)); writer.write(html); writer.close(); } reader.close(); }
From source file:edu.cmu.lti.oaqa.knn4qa.apps.BuildRetrofitLexicons.java
public static void main(String[] args) { Options options = new Options(); options.addOption(CommonParams.GIZA_ROOT_DIR_PARAM, null, true, CommonParams.GIZA_ROOT_DIR_DESC); options.addOption(CommonParams.GIZA_ITER_QTY_PARAM, null, true, CommonParams.GIZA_ITER_QTY_DESC); options.addOption(CommonParams.MEMINDEX_PARAM, null, true, CommonParams.MEMINDEX_DESC); options.addOption(OUT_FILE_PARAM, null, true, OUT_FILE_DESC); options.addOption(MIN_PROB_PARAM, null, true, MIN_PROB_DESC); options.addOption(FORMAT_PARAM, null, true, FORMAT_DESC); CommandLineParser parser = new org.apache.commons.cli.GnuParser(); try {//from w w w.ja v a 2 s. c o m CommandLine cmd = parser.parse(options, args); String gizaRootDir = cmd.getOptionValue(CommonParams.GIZA_ROOT_DIR_PARAM); int gizaIterQty = -1; if (cmd.hasOption(CommonParams.GIZA_ITER_QTY_PARAM)) { gizaIterQty = Integer.parseInt(cmd.getOptionValue(CommonParams.GIZA_ITER_QTY_PARAM)); } else { Usage("Specify: " + CommonParams.GIZA_ITER_QTY_PARAM, options); } String outFileName = cmd.getOptionValue(OUT_FILE_PARAM); if (null == outFileName) { Usage("Specify: " + OUT_FILE_PARAM, options); } String indexDir = cmd.getOptionValue(CommonParams.MEMINDEX_PARAM); if (null == indexDir) { Usage("Specify: " + CommonParams.MEMINDEX_DESC, options); } FormatType outType = FormatType.kOrig; String outTypeStr = cmd.getOptionValue(FORMAT_PARAM); if (null != outTypeStr) { if (outTypeStr.equals(ORIG_TYPE)) { outType = FormatType.kOrig; } else if (outTypeStr.equals(WEIGHTED_TYPE)) { outType = FormatType.kWeighted; } else if (outTypeStr.equals(UNWEIGHTED_TYPE)) { outType = FormatType.kUnweighted; } else { Usage("Unknown format type: " + outTypeStr, options); } } float minProb = 0; if (cmd.hasOption(MIN_PROB_PARAM)) { minProb = Float.parseFloat(cmd.getOptionValue(MIN_PROB_PARAM)); } else { Usage("Specify: " + MIN_PROB_PARAM, options); } System.out.println(String.format( "Saving lexicon to '%s' (output format '%s'), keep only entries with translation probability >= %f", outFileName, outType.toString(), minProb)); // We use unlemmatized text here, because lemmatized dictionary is going to be mostly subset of the unlemmatized one. InMemForwardIndex textIndex = new InMemForwardIndex(FeatureExtractor.indexFileName(indexDir, FeatureExtractor.mFieldNames[FeatureExtractor.TEXT_UNLEMM_FIELD_ID])); InMemForwardIndexFilterAndRecoder filterAndRecoder = new InMemForwardIndexFilterAndRecoder(textIndex); String prefix = gizaRootDir + "/" + FeatureExtractor.mFieldNames[FeatureExtractor.TEXT_UNLEMM_FIELD_ID] + "/"; GizaVocabularyReader answVoc = new GizaVocabularyReader(prefix + "source.vcb", filterAndRecoder); GizaVocabularyReader questVoc = new GizaVocabularyReader(prefix + "target.vcb", filterAndRecoder); GizaTranTableReaderAndRecoder gizaTable = new GizaTranTableReaderAndRecoder(false, // we don't need to flip the table for the purpose prefix + "/output.t1." + gizaIterQty, filterAndRecoder, answVoc, questVoc, (float) FeatureExtractor.DEFAULT_PROB_SELF_TRAN, minProb); BufferedWriter outFile = new BufferedWriter(new FileWriter(outFileName)); for (int srcWordId = 0; srcWordId <= textIndex.getMaxWordId(); ++srcWordId) { GizaOneWordTranRecs tranRecs = gizaTable.getTranProbs(srcWordId); if (null != tranRecs) { String wordSrc = textIndex.getWord(srcWordId); StringBuffer sb = new StringBuffer(); sb.append(wordSrc); for (int k = 0; k < tranRecs.mDstIds.length; ++k) { float prob = tranRecs.mProbs[k]; if (prob >= minProb) { int dstWordId = tranRecs.mDstIds[k]; if (dstWordId == srcWordId && outType != FormatType.kWeighted) continue; // Don't duplicate the word, unless it's probability weighted sb.append(' '); String dstWord = textIndex.getWord(dstWordId); if (null == dstWord) { throw new Exception( "Bug or inconsistent data: Couldn't retriev a word for wordId = " + dstWordId); } if (dstWord.indexOf(':') >= 0) throw new Exception( "Illegal dictionary word '" + dstWord + "' b/c it contains ':'"); sb.append(dstWord); if (outType != FormatType.kOrig) { sb.append(':'); sb.append(outType == FormatType.kWeighted ? prob : 1); } } } outFile.write(sb.toString()); outFile.newLine(); } } outFile.close(); } catch (ParseException e) { e.printStackTrace(); Usage("Cannot parse arguments", options); } catch (Exception e) { e.printStackTrace(); System.err.println("Terminating due to an exception: " + e); System.exit(1); } System.out.println("Terminated successfully!"); }
From source file:com.github.chrbayer84.keybits.KeyBits.java
/** * @param args// www.j av a2s. co m */ public static void main(String[] args) throws Exception { int number_of_addresses = 1; int depth = 1; String usage = "java -jar KeyBits.jar [options]"; // create parameters which can be chosen Option help = new Option("h", "print this message"); Option verbose = new Option("v", "verbose"); Option exprt = new Option("e", "export public key to blockchain"); Option imprt = OptionBuilder.withArgName("string").hasArg() .withDescription("import public key from blockchain").create("i"); Option blockchain_address = OptionBuilder.withArgName("string").hasArg().withDescription("bitcoin address") .create("a"); Option create_wallet = OptionBuilder.withArgName("file name").hasArg().withDescription("create wallet") .create("c"); Option update_wallet = OptionBuilder.withArgName("file name").hasArg().withDescription("update wallet") .create("u"); Option balance_wallet = OptionBuilder.withArgName("file name").hasArg() .withDescription("return balance of wallet").create("b"); Option show_wallet = OptionBuilder.withArgName("file name").hasArg() .withDescription("show content of wallet").create("w"); Option send_coins = OptionBuilder.withArgName("file name").hasArg().withDescription("send satoshis") .create("s"); Option monitor_pending = OptionBuilder.withArgName("file name").hasArg() .withDescription("monitor pending transactions of wallet").create("p"); Option monitor_depth = OptionBuilder.withArgName("file name").hasArg() .withDescription("monitor transaction depths of wallet").create("d"); Option number = OptionBuilder.withArgName("integer").hasArg() .withDescription("in combination with -c, -d, -r or -s").create("n"); Option reset = OptionBuilder.withArgName("file name").hasArg().withDescription("reset wallet").create("r"); Options options = new Options(); options.addOption(help); options.addOption(verbose); options.addOption(imprt); options.addOption(exprt); options.addOption(blockchain_address); options.addOption(create_wallet); options.addOption(update_wallet); options.addOption(balance_wallet); options.addOption(show_wallet); options.addOption(send_coins); options.addOption(monitor_pending); options.addOption(monitor_depth); options.addOption(number); options.addOption(reset); BasicParser parser = new BasicParser(); CommandLine cmd = null; String header = "This is KeyBits v0.01b.1412953962" + System.getProperty("line.separator"); // show help if wrong usage try { cmd = parser.parse(options, args); } catch (Exception e) { printHelp(usage, options, header); } if (cmd.getOptions().length == 0) printHelp(usage, options, header); if (cmd.hasOption("h")) printHelp(usage, options, header); if (cmd.hasOption("v")) System.out.println(header); if (cmd.hasOption("c") && cmd.hasOption("n")) number_of_addresses = new Integer(cmd.getOptionValue("n")).intValue(); if (cmd.hasOption("d") && cmd.hasOption("n")) depth = new Integer(cmd.getOptionValue("n")).intValue(); String checkpoints_file_name = "checkpoints"; if (!new File(checkpoints_file_name).exists()) checkpoints_file_name = null; // --------------------------------------------------------------------- if (cmd.hasOption("c")) { String wallet_file_name = cmd.getOptionValue("c"); String passphrase = HelpfulStuff.insertPassphrase("enter password for " + wallet_file_name); if (!new File(wallet_file_name).exists()) { String passphrase_ = HelpfulStuff.reInsertPassphrase("enter password for " + wallet_file_name); if (!passphrase.equals(passphrase_)) { System.out.println("passwords do not match"); System.exit(0); } } MyWallet.createWallet(wallet_file_name, wallet_file_name + ".chain", number_of_addresses, passphrase); System.exit(0); } if (cmd.hasOption("u")) { String wallet_file_name = cmd.getOptionValue("u"); MyWallet.updateWallet(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name); System.exit(0); } if (cmd.hasOption("b")) { String wallet_file_name = cmd.getOptionValue("b"); System.out.println( MyWallet.getBalanceOfWallet(wallet_file_name, wallet_file_name + ".chain").longValue()); System.exit(0); } if (cmd.hasOption("w")) { String wallet_file_name = cmd.getOptionValue("w"); System.out.println(MyWallet.showContentOfWallet(wallet_file_name, wallet_file_name + ".chain")); System.exit(0); } if (cmd.hasOption("p")) { System.out.println("monitoring of pending transactions ... "); String wallet_file_name = cmd.getOptionValue("p"); MyWallet.monitorPendingTransactions(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name); System.exit(0); } if (cmd.hasOption("d")) { System.out.println("monitoring of transaction depth ... "); String wallet_file_name = cmd.getOptionValue("d"); MyWallet.monitorTransactionDepth(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name, depth); System.exit(0); } if (cmd.hasOption("r") && cmd.hasOption("n")) { long epoch = new Long(cmd.getOptionValue("n")); System.out.println("resetting wallet ... "); String wallet_file_name = cmd.getOptionValue("r"); File chain_file = (new File(wallet_file_name + ".chain")); if (chain_file.exists()) chain_file.delete(); MyWallet.setCreationTime(wallet_file_name, epoch); MyWallet.updateWallet(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name); System.exit(0); } if (cmd.hasOption("s") && cmd.hasOption("a") && cmd.hasOption("n")) { String wallet_file_name = cmd.getOptionValue("s"); String address = cmd.getOptionValue("a"); Integer amount = new Integer(cmd.getOptionValue("n")); String wallet_passphrase = HelpfulStuff.insertPassphrase("enter password for " + wallet_file_name); MyWallet.sendCoins(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name, address, new BigInteger(amount + ""), wallet_passphrase); System.out.println("waiting ..."); Thread.sleep(10000); System.out.println("monitoring of transaction depth ... "); MyWallet.monitorTransactionDepth(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name, 1); System.out.println("transaction fixed in blockchain with depth " + depth); System.exit(0); } // ---------------------------------------------------------------------------------------- // creates public key // ---------------------------------------------------------------------------------------- GnuPGP gpg = new GnuPGP(); if (cmd.hasOption("e")) { BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); String line = null; StringBuffer sb = new StringBuffer(); while ((line = input.readLine()) != null) sb.append(line + "\n"); PGPPublicKeyRing public_key_ring = gpg.getDearmored(sb.toString()); //System.out.println(gpg.showPublicKeys(public_key_ring)); byte[] public_key_ring_encoded = gpg.getEncoded(public_key_ring); String[] addresses = (new Encoding()).encodePublicKey(public_key_ring_encoded); // System.out.println(gpg.showPublicKey(gpg.getDecoded(encoding.decodePublicKey(addresses)))); // file names for message String public_key_file_name = Long.toHexString(public_key_ring.getPublicKey().getKeyID()) + ".wallet"; String public_key_wallet_file_name = public_key_file_name; String public_key_chain_file_name = public_key_wallet_file_name + ".chain"; // hier muss dass passwort noch nach encodeAddresses weitergeleitet werden da sonst zweimal abfrage String public_key_wallet_passphrase = HelpfulStuff .insertPassphrase("enter password for " + public_key_wallet_file_name); if (!new File(public_key_wallet_file_name).exists()) { String public_key_wallet_passphrase_ = HelpfulStuff .reInsertPassphrase("enter password for " + public_key_wallet_file_name); if (!public_key_wallet_passphrase.equals(public_key_wallet_passphrase_)) { System.out.println("passwords do not match"); System.exit(0); } } MyWallet.createWallet(public_key_wallet_file_name, public_key_chain_file_name, 1, public_key_wallet_passphrase); MyWallet.updateWallet(public_key_wallet_file_name, public_key_chain_file_name, checkpoints_file_name); String public_key_address = MyWallet.getAddress(public_key_wallet_file_name, public_key_chain_file_name, 0); System.out.println("address of public key: " + public_key_address); // 10000 additional satoshis for sending transaction to address of recipient of message and 10000 for fees KeyBits.encodeAddresses(public_key_wallet_file_name, public_key_chain_file_name, checkpoints_file_name, addresses, 2 * SendRequest.DEFAULT_FEE_PER_KB.intValue(), depth, public_key_wallet_passphrase); } if (cmd.hasOption("i")) { String location = cmd.getOptionValue("i"); String[] addresses = null; if (location.indexOf(",") > -1) { String[] locations = location.split(","); addresses = MyWallet.getAddressesFromBlockAndTransaction("main.wallet", "main.wallet.chain", checkpoints_file_name, locations[0], locations[1]); } else { addresses = BlockchainDotInfo.getKeys(location); } byte[] encoded = (new Encoding()).decodePublicKey(addresses); PGPPublicKeyRing public_key_ring = gpg.getDecoded(encoded); System.out.println(gpg.getArmored(public_key_ring)); System.exit(0); } }
From source file:com.lfv.lanzius.Main.java
public static void main(String[] args) { /*//from w w w.jav a 2 s . c o m * debug levels: * error - Runtime errors or unexpected conditions. Expect these to be immediately visible on a status console. See also Internationalization. * warn - Use of deprecated APIs, poor use of API, 'almost' errors, other runtime situations that are undesirable or unexpected, but not necessarily "wrong". Expect these to be immediately visible on a status console. See also Internationalization. * info - Interesting runtime events (startup/shutdown). Expect these to be immediately visible on a console, so be conservative and keep to a minimum. See also Internationalization. * debug - detailed information on the flow through the system. Expect these to be written to logs only. */ Log log = null; DOMConfigurator conf = new DOMConfigurator(); DOMConfigurator.configure("data/properties/loggingproperties.xml"); System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger"); try { if (args.length >= 1) { // Help if (args[0].startsWith("-h")) { printUsage(); return; } // List devices else if (args[0].startsWith("-l")) { AudioTest.listDevices(); return; } // Test seleted device else if (args[0].startsWith("-d")) { System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog"); System.setProperty("org.apache.commons.logging.simplelog.defaultlog", "warn"); try { String option = "all"; if (args.length >= 4) option = args[3]; if (option.equals("loop:direct")) AudioTest.testDevicesDirect(Integer.parseInt(args[1]), Integer.parseInt(args[2])); else { if (option.indexOf("debug") != -1) System.setProperty("org.apache.commons.logging.simplelog.defaultlog", "debug"); AudioTest.testDevices(Integer.parseInt(args[1]), Integer.parseInt(args[2]), option, (args.length >= 5) ? args[4] : null, (args.length >= 6) ? args[5] : null, (args.length >= 7) ? args[6] : null); } } catch (Exception ex) { System.out.println(); System.out.println(Config.VERSION); System.out.println(); System.out.println("Usage:"); System.out.println( " yada.jar -d output_device input_device <option> <jitter_buffer> <output_buffer> <input_buffer>"); System.out.println(" option:"); System.out.println(" all(default)"); System.out.println(" clip"); System.out.println(" loop:jspeex"); System.out.println(" loop:null"); System.out.println(" loop:direct"); System.out.println(" loopdebug:jspeex"); System.out.println(" loopdebug:null"); System.out.println(" jitter_buffer:"); System.out.println(" size of jitter buffer in packets (1-20)"); System.out.println(" output_buffer:"); System.out.println(" size of output buffer in packets (1.0-4.0)"); System.out.println(" input_buffer:"); System.out.println(" size of input buffer in packets (1.0-4.0)"); System.out.println(); if (AudioTest.showStackTrace && !(ex instanceof ArrayIndexOutOfBoundsException)) ex.printStackTrace(); } //System.out.println("Exiting..."); return; } else if (args[0].startsWith("-m")) { System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog"); System.setProperty("org.apache.commons.logging.simplelog.defaultlog", "warn"); try { AudioTest.testMicrophoneLevel(Integer.parseInt(args[1])); } catch (Exception ex) { System.out.println(); System.out.println(Config.VERSION); System.out.println(); System.out.println("Usage:"); System.out.println(" yada.jar -m input_device"); System.out.println(); if (AudioTest.showStackTrace && !(ex instanceof ArrayIndexOutOfBoundsException)) ex.printStackTrace(); } return; } else if (args[0].startsWith("-s")) { Packet.randomSeed = 9182736455L ^ System.currentTimeMillis(); if (args.length > 2 && args[1].startsWith("-configuration")) { String configFilename = args[2]; if (args.length > 4 && args[3].startsWith("-exercise")) { String exerciseFilename = args[4]; LanziusServer.start(configFilename, exerciseFilename); } else { LanziusServer.start(configFilename); } } else { LanziusServer.start(); } return; } else if (args[0].startsWith("-f")) { System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog"); System.setProperty( "org.apache.commons.logging.simplelog.log.com.lfv.lanzius.application.FootSwitchController", "debug"); try { System.out.println("Starting footswitch controller test using device " + args[1]); try { boolean inverted = false; if (args.length >= 3) inverted = args[2].toLowerCase().startsWith("inv"); FootSwitchController c = new FootSwitchController(null, args[1], Constants.PERIOD_FTSW_CONNECTED, inverted); c.start(); Thread.sleep(30000); } catch (UnsatisfiedLinkError err) { if (args.length > 1) System.out.println("UnsatisfiedLinkError: " + err.getMessage()); else throw new ArrayIndexOutOfBoundsException(); System.out.println("Missing ftsw library (ftsw.dll or libftsw.so)"); if (!args[1].equalsIgnoreCase("ftdi")) System.out .println("Missing rxtxSerial library (rxtxSerial.dll or librxtxSerial.so)"); if (AudioTest.showStackTrace) err.printStackTrace(); } } catch (Exception ex) { if (ex instanceof NoSuchPortException) System.out.println("The serial port " + args[1] + " does not exist!"); else if (ex instanceof PortInUseException) System.out.println("The serial port " + args[1] + " is already in use!"); System.out.println(); System.out.println(Config.VERSION); System.out.println(); System.out.println("Usage:"); System.out.println(" yada.jar -f interface <invert>"); System.out.println(" interface:"); System.out.println(" ftdi"); System.out.println(" comport (COMx or /dev/ttyx)"); System.out.println(" invert:"); System.out.println(" true"); System.out.println(" false (default)"); System.out.println(); if (AudioTest.showStackTrace && !(ex instanceof ArrayIndexOutOfBoundsException)) ex.printStackTrace(); } return; } else if (args[0].startsWith("-c")) { Packet.randomSeed = 7233103157L ^ System.currentTimeMillis(); if (args.length >= 2) { try { int id = Integer.valueOf(args[1]); if (id <= 0) throw new NumberFormatException(); Controller c = Controller.getInstance(); if (args.length >= 3) { if (args[2].equalsIgnoreCase("test")) { c.setAutoTester(true); } } c.init(id); return; } catch (NumberFormatException ex) { printUsage(); } } else { Controller.getInstance().init(0); } } else printUsage(); } else printUsage(); } catch (Throwable t) { if (log == null) log = LogFactory.getLog(Main.class); log.error("Unhandled exception or error", t); } }
From source file:org.eclipse.swt.snippets.Snippet217.java
public static void main(String[] args) { final Display display = new Display(); Font font = new Font(display, "Tahoma", 16, SWT.NORMAL); final Shell shell = new Shell(display); shell.setText("Snippet 217"); shell.setLayout(new GridLayout()); styledText = new StyledText(shell, SWT.WRAP | SWT.BORDER); styledText.setFont(font);/*w ww . j ava2 s.co m*/ styledText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); styledText.setText(text); Button button = new Button(styledText, SWT.PUSH); button.setText("Button 1"); int offset = text.indexOf('\uFFFC'); addControl(button, offset); button.setLocation(styledText.getLocationAtOffset(offset)); Combo combo = new Combo(styledText, SWT.NONE); combo.add("item 1"); combo.add("another item"); combo.setText(combo.getItem(0)); offset = text.indexOf('\uFFFC', offset + 1); addControl(combo, offset); combo.setLocation(styledText.getLocationAtOffset(offset)); // use a verify listener to dispose the controls styledText.addVerifyListener(event -> { if (event.start == event.end) return; String text = styledText.getText(event.start, event.end - 1); int index = text.indexOf('\uFFFC'); while (index != -1) { StyleRange style = styledText.getStyleRangeAtOffset(event.start + index); if (style != null) { Control control = (Control) style.data; if (control != null) control.dispose(); } index = text.indexOf('\uFFFC', index + 1); } }); // reposition widgets on paint event styledText.addPaintObjectListener(event -> { Control control = (Control) event.style.data; Point pt = control.getSize(); int x = event.x + MARGIN; int y = event.y + event.ascent - 2 * pt.y / 3; control.setLocation(x, y); }); shell.setSize(400, 400); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } font.dispose(); display.dispose(); }
From source file:de.morbz.osmpoispbf.Scanner.java
public static void main(String[] args) { System.out.println("OsmPoisPbf " + VERSION + " started"); // Get input file if (args.length < 1) { System.out.println("Error: Please provide an input file"); System.exit(-1);//from w ww .jav a 2 s. c o m } String inputFile = args[args.length - 1]; // Get output file String outputFile; int index = inputFile.indexOf('.'); if (index != -1) { outputFile = inputFile.substring(0, index); } else { outputFile = inputFile; } outputFile += ".csv"; // Setup CLI parameters options = new Options(); options.addOption("ff", "filterFile", true, "The file that is used to filter categories"); options.addOption("of", "outputFile", true, "The output CSV file to be written"); options.addOption("rt", "requiredTags", true, "Comma separated list of tags that are required [name]"); options.addOption("ut", "undesiredTags", true, "Comma separated list of tags=value combinations that should be filtered [key=value]"); options.addOption("ot", "outputTags", true, "Comma separated list of tags that are exported [name]"); options.addOption("ph", "printHeader", false, "If flag is set, the `outputTags` are printed as first line in the output file."); options.addOption("r", "relations", false, "Parse relations"); options.addOption("nw", "noWays", false, "Don't parse ways"); options.addOption("nn", "noNodes", false, "Don't parse nodes"); options.addOption("u", "allowUnclosedWays", false, "Allow ways that aren't closed"); options.addOption("d", "decimals", true, "Number of decimal places of coordinates [7]"); options.addOption("s", "separator", true, "Separator character for CSV [|]"); options.addOption("v", "verbose", false, "Print all found POIs"); options.addOption("h", "help", false, "Print this help"); // Parse parameters CommandLine line = null; try { line = (new DefaultParser()).parse(options, args); } catch (ParseException exp) { System.err.println(exp.getMessage()); printHelp(); System.exit(-1); } // Help if (line.hasOption("help")) { printHelp(); System.exit(0); } // Get filter file String filterFile = null; if (line.hasOption("filterFile")) { filterFile = line.getOptionValue("filterFile"); } // Get output file if (line.hasOption("outputFile")) { outputFile = line.getOptionValue("outputFile"); } // Check files if (inputFile.equals(outputFile)) { System.out.println("Error: Input and output files are the same"); System.exit(-1); } File file = new File(inputFile); if (!file.exists()) { System.out.println("Error: Input file doesn't exist"); System.exit(-1); } // Check OSM entity types boolean parseNodes = true; boolean parseWays = true; boolean parseRelations = false; if (line.hasOption("noNodes")) { parseNodes = false; } if (line.hasOption("noWays")) { parseWays = false; } if (line.hasOption("relations")) { parseRelations = true; } // Unclosed ways allowed? if (line.hasOption("allowUnclosedWays")) { onlyClosedWays = false; } // Get CSV separator char separator = '|'; if (line.hasOption("separator")) { String arg = line.getOptionValue("separator"); if (arg.length() != 1) { System.out.println("Error: The CSV separator has to be exactly 1 character"); System.exit(-1); } separator = arg.charAt(0); } Poi.setSeparator(separator); // Set decimals int decimals = 7; // OSM default if (line.hasOption("decimals")) { String arg = line.getOptionValue("decimals"); try { int dec = Integer.valueOf(arg); if (dec < 0) { System.out.println("Error: Decimals must not be less than 0"); System.exit(-1); } else { decimals = dec; } } catch (NumberFormatException ex) { System.out.println("Error: Decimals have to be a number"); System.exit(-1); } } Poi.setDecimals(decimals); // Verbose mode? if (line.hasOption("verbose")) { printPois = true; } // Required tags if (line.hasOption("requiredTags")) { String arg = line.getOptionValue("requiredTags"); requiredTags = arg.split(","); } // Undesired tags if (line.hasOption("undesiredTags")) { String arg = line.getOptionValue("undesiredTags"); undesiredTags = new HashMap<>(); for (String undesired : arg.split(",")) { String[] keyVal = undesired.split("="); if (keyVal.length != 2) { System.out.println("Error: Undesired Tags have to formated like tag=value"); System.exit(-1); } if (!undesiredTags.containsKey(keyVal[0])) { undesiredTags.put(keyVal[0], new HashSet<>(1)); } undesiredTags.get(keyVal[0]).add(keyVal[1]); } } // Output tags if (line.hasOption("outputTags")) { String arg = line.getOptionValue("outputTags"); outputTags = arg.split(","); } // Get filter rules FilterFileParser parser = new FilterFileParser(filterFile); filters = parser.parse(); if (filters == null) { System.exit(-1); } // Setup CSV output try { writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF8")); } catch (IOException e) { System.out.println("Error: Output file error"); System.exit(-1); } // Print Header if (line.hasOption("printHeader")) { String header = "category" + separator + "osm_id" + separator + "lat" + separator + "lon"; for (int i = 0; i < outputTags.length; i++) { header += separator + outputTags[i]; } try { writer.write(header + "\n"); } catch (IOException e) { System.out.println("Error: Output file write error"); System.exit(-1); } } // Setup OSMonaut EntityFilter filter = new EntityFilter(parseNodes, parseWays, parseRelations); Osmonaut naut = new Osmonaut(inputFile, filter, false); // Start watch StopWatch stopWatch = new StopWatch(); stopWatch.start(); // Start OSMonaut String finalSeparator = String.valueOf(separator); naut.scan(new IOsmonautReceiver() { boolean entityNeeded; @Override public boolean needsEntity(EntityType type, Tags tags) { // Are there any tags? if (tags.size() == 0) { return false; } // Check required tags for (String tag : requiredTags) { if (!tags.hasKey(tag)) { return false; } } entityNeeded = getCategory(tags, filters) != null; if (undesiredTags != null && entityNeeded) { for (String key : undesiredTags.keySet()) { if (tags.hasKey(key)) { for (String val : undesiredTags.get(key)) { if (tags.hasKeyValue(key, val)) { return false; } } } } } return entityNeeded; } @Override public void foundEntity(Entity entity) { // Check if way is closed if (onlyClosedWays && entity.getEntityType() == EntityType.WAY) { if (!((Way) entity).isClosed()) { return; } } // Get category Tags tags = entity.getTags(); String cat = getCategory(tags, filters); if (cat == null) { return; } // Get center LatLon center = entity.getCenter(); if (center == null) { return; } // Make OSM-ID String type = ""; switch (entity.getEntityType()) { case NODE: type = "node"; break; case WAY: type = "way"; break; case RELATION: type = "relation"; break; } String id = String.valueOf(entity.getId()); // Make output tags String[] values = new String[outputTags.length]; for (int i = 0; i < outputTags.length; i++) { String key = outputTags[i]; if (tags.hasKey(key)) { values[i] = tags.get(key).replaceAll(finalSeparator, "").replaceAll("\"", ""); } } // Make POI poisFound++; Poi poi = new Poi(values, cat, center, type, id); // Output if (printPois && System.currentTimeMillis() > lastMillis + 40) { printPoisFound(); lastMillis = System.currentTimeMillis(); } // Write to file try { writer.write(poi.toCsv() + "\n"); } catch (IOException e) { System.out.println("Error: Output file write error"); System.exit(-1); } } }); // Close writer try { writer.close(); } catch (IOException e) { System.out.println("Error: Output file close error"); System.exit(-1); } // Output results stopWatch.stop(); printPoisFound(); System.out.println(); System.out.println("Elapsed time in milliseconds: " + stopWatch.getElapsedTime()); // Quit System.exit(0); }