List of usage examples for java.lang String length
public int length()
From source file:baldrickv.s3streamingtool.S3StreamingTool.java
public static void main(String args[]) throws Exception { BasicParser p = new BasicParser(); Options o = getOptions();// w ww. j a v a 2 s. c om CommandLine cl = p.parse(o, args); if (cl.hasOption('h')) { HelpFormatter hf = new HelpFormatter(); hf.setWidth(80); StringBuilder sb = new StringBuilder(); sb.append("\n"); sb.append("Upload:\n"); sb.append(" -u -r creds -s 50M -b my_bucket -f hda1.dump -t 10\n"); sb.append("Download:\n"); sb.append(" -d -r creds -s 50M -b my_bucket -f hda1.dump -t 10\n"); sb.append("Upload encrypted:\n"); sb.append(" -u -r creds -z -k secret_key -s 50M -b my_bucket -f hda1.dump -t 10\n"); sb.append("Download encrypted:\n"); sb.append(" -d -r creds -z -k secret_key -s 50M -b my_bucket -f hda1.dump -t 10\n"); sb.append("Cleanup in-progress multipart uploads\n"); sb.append(" -c -r creds -b my_bucket\n"); System.out.println(sb.toString()); hf.printHelp("See above", o); return; } int n = 0; if (cl.hasOption('d')) n++; if (cl.hasOption('u')) n++; if (cl.hasOption('c')) n++; if (cl.hasOption('m')) n++; if (n != 1) { System.err.println("Must specify at exactly one of -d, -u, -c or -m"); System.exit(-1); } if (cl.hasOption('m')) { //InputStream in = new java.io.BufferedInputStream(System.in,1024*1024*2); InputStream in = System.in; System.out.println(TreeHashGenerator.calculateTreeHash(in)); return; } require(cl, 'b'); if (cl.hasOption('d') || cl.hasOption('u')) { require(cl, 'f'); } if (cl.hasOption('z')) { require(cl, 'k'); } AWSCredentials creds = null; if (cl.hasOption('r')) { creds = Utils.loadAWSCredentails(cl.getOptionValue('r')); } else { if (cl.hasOption('i') && cl.hasOption('e')) { creds = new BasicAWSCredentials(cl.getOptionValue('i'), cl.getOptionValue('e')); } else { System.out.println("Must specify either credential file (-r) or AWS key ID and secret (-i and -e)"); System.exit(-1); } } S3StreamConfig config = new S3StreamConfig(); config.setEncryption(false); if (cl.hasOption('z')) { config.setEncryption(true); config.setSecretKey(Utils.loadSecretKey(cl.getOptionValue("k"))); } if (cl.hasOption("encryption-mode")) { config.setEncryptionMode(cl.getOptionValue("encryption-mode")); } config.setS3Bucket(cl.getOptionValue("bucket")); if (cl.hasOption("file")) { config.setS3File(cl.getOptionValue("file")); } if (cl.hasOption("threads")) { config.setIOThreads(Integer.parseInt(cl.getOptionValue("threads"))); } if (cl.hasOption("blocksize")) { String s = cl.getOptionValue("blocksize"); s = s.toUpperCase(); int multi = 1; int end = 0; while ((end < s.length()) && (s.charAt(end) >= '0') && (s.charAt(end) <= '9')) { end++; } int size = Integer.parseInt(s.substring(0, end)); if (end < s.length()) { String m = s.substring(end); if (m.equals("K")) multi = 1024; else if (m.equals("M")) multi = 1048576; else if (m.equals("G")) multi = 1024 * 1024 * 1024; else if (m.equals("KB")) multi = 1024; else if (m.equals("MB")) multi = 1048576; else if (m.equals("GB")) multi = 1024 * 1024 * 1024; else { System.out.println("Unknown suffix on block size. Only K,M and G understood."); System.exit(-1); } } size *= multi; config.setBlockSize(size); } Logger.getLogger("").setLevel(Level.FINE); S3StreamingDownload.log.setLevel(Level.FINE); S3StreamingUpload.log.setLevel(Level.FINE); config.setS3Client(new AmazonS3Client(creds)); config.setGlacierClient(new AmazonGlacierClient(creds)); config.getGlacierClient().setEndpoint("glacier.us-west-2.amazonaws.com"); if (cl.hasOption("glacier")) { config.setGlacier(true); config.setStorageInterface(new StorageGlacier(config.getGlacierClient())); } else { config.setStorageInterface(new StorageS3(config.getS3Client())); } if (cl.hasOption("bwlimit")) { config.setMaxBytesPerSecond(Double.parseDouble(cl.getOptionValue("bwlimit"))); } if (cl.hasOption('c')) { if (config.getGlacier()) { GlacierCleanupMultipart.cleanup(config); } else { S3CleanupMultipart.cleanup(config); } return; } if (cl.hasOption('d')) { config.setOutputStream(System.out); S3StreamingDownload.download(config); return; } if (cl.hasOption('u')) { config.setInputStream(System.in); S3StreamingUpload.upload(config); return; } }
From source file:edu.oregonstate.eecs.mcplan.domains.spbj.SpBjSimulator.java
public static void main(final String[] argv) throws IOException { final int seed = 43; final RandomGenerator rng = new MersenneTwister(seed); // final Deck deck = new InfiniteSpanishDeck( rng ); // TODO: Debugging code final Deque<Card> stacked = new ArrayDeque<Card>(); for (int i = 0; i < 20; ++i) { stacked.push(Card.C_2c);// ww w . j a va 2s . co m stacked.push(Card.C_2d); stacked.push(Card.C_2h); stacked.push(Card.C_2s); } final Deck deck = new StackedDeck(stacked); // final ArrayList<ArrayList<Card>> test_hands = new ArrayList<ArrayList<Card>>(); // test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_Kc, Card.C_9h, Card.C_2c ) ) ); // test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_6c, Card.C_7h, Card.C_8c ) ) ); // test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_6c, Card.C_7c, Card.C_8c ) ) ); // test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_6s, Card.C_7s, Card.C_8s ) ) ); // test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_7c, Card.C_7h, Card.C_7c ) ) ); // test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_7c, Card.C_7c, Card.C_7c ) ) ); // test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_7s, Card.C_7s, Card.C_7s ) ) ); // test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_3c, Card.C_3c, Card.C_3c, Card.C_3c, Card.C_9c ) ) ); // test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_3c, Card.C_3c, Card.C_3c, Card.C_3c, Card.C_3c, Card.C_6c ) ) ); // test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_3c, Card.C_3c, Card.C_3c, Card.C_3c, Card.C_3c, Card.C_3c, Card.C_3c ) ) ); // test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_3c, Card.C_3c, Card.C_3c, Card.C_3c, Card.C_3c, Card.C_3c, Card.C_2c, Card.C_Ac ) ) ); // // final ArrayList<ArrayList<Card>> dealer_test_hands = new ArrayList<ArrayList<Card>>(); // dealer_test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_Kc, Card.C_Kc ) ) ); // dealer_test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_Kc, Card.C_Ac ) ) ); // // for( final ArrayList<Card> dealer_cards : dealer_test_hands ) { // for( final ArrayList<Card> cards : test_hands ) { // final SpBjState s = new SpBjState( deck ); // s.init(); // s.dealer_hand.clear(); // s.dealer_hand.addAll( dealer_cards ); // s.player_hand.hands.set( 0, cards ); // final SpBjSimulator sim = new SpBjSimulator( s ); // sim.takeAction( new JointAction<SpBjAction>( // new SpBjAction( new SpBjActionCategory[] { SpBjActionCategory.Pass } ) ) ); // // System.out.print( "Hand: " ); // System.out.print( sim.state().player_hand ); // System.out.print( " (" ); // final ArrayList<int[]> values = sim.state().player_hand.values(); // for( int i = 0; i < values.size(); ++i ) { // if( i > 0 ) { // System.out.print( ", " ); // } // System.out.print( Arrays.toString( values.get( i ) ) ); // } // System.out.println( ")" ); // // System.out.print( "Reward: " ); // System.out.println( Arrays.toString( sim.reward() ) ); // System.out.print( "Dealer hand: " ); // System.out.print( sim.state().dealerHand().toString() ); // System.out.print( " (" ); // System.out.print( SpBjHand.handValue( sim.state().dealerHand() )[0] ); // System.out.println( ")" ); // System.out.println( "----------------------------------------" ); // } // } while (true) { final SpBjState s = new SpBjState(deck); s.init(); final SpBjSimulator sim = new SpBjSimulator(s); final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while (!s.isTerminal()) { System.out.print("Dealer showing: "); System.out.println(sim.state().dealerUpcard()); System.out.print("Hand: "); System.out.print(sim.state().player_hand); System.out.print(" ("); final ArrayList<int[]> values = sim.state().player_hand.values(); for (int i = 0; i < values.size(); ++i) { if (i > 0) { System.out.print(", "); } System.out.print(Arrays.toString(values.get(i))); } System.out.println(")"); final SpBjActionGenerator actions = new SpBjActionGenerator(); actions.setState(sim.state(), 0); for (final SpBjAction a : Fn.in(actions)) { System.out.println(a); } final String cmd = reader.readLine(); assert (cmd.length() == sim.state().player_hand.Nhands); final SpBjActionCategory[] cat = new SpBjActionCategory[cmd.length()]; for (int i = 0; i < cmd.length(); ++i) { final char c = cmd.charAt(i); if ('h' == c) { cat[i] = SpBjActionCategory.Hit; } else if ('p' == c) { cat[i] = SpBjActionCategory.Pass; } else if ('d' == c) { cat[i] = SpBjActionCategory.Double; } else if ('s' == c) { cat[i] = SpBjActionCategory.Split; } } sim.takeAction(new JointAction<SpBjAction>(new SpBjAction(cat))); } System.out.print("Hand: "); System.out.print(sim.state().player_hand); System.out.print(" ("); final ArrayList<int[]> values = sim.state().player_hand.values(); for (int i = 0; i < values.size(); ++i) { if (i > 0) { System.out.print(", "); } System.out.print(Arrays.toString(values.get(i))); } System.out.println(")"); System.out.print("Reward: "); System.out.println(Arrays.toString(sim.reward())); System.out.print("Dealer hand: "); System.out.print(sim.state().dealerHand().toString()); System.out.print(" ("); System.out.print(SpBjHand.handValue(sim.state().dealerHand())[0]); System.out.println(")"); System.out.println("----------------------------------------"); } }
From source file:kilim.tools.DumpClass.java
public static void main(String[] args) throws IOException { String name = args.length == 2 ? args[1] : args[0]; if (name.endsWith(".jar")) { try {/*ww w .j av a 2 s .c o m*/ Enumeration<JarEntry> e = new JarFile(name).entries(); while (e.hasMoreElements()) { ZipEntry en = (ZipEntry) e.nextElement(); String n = en.getName(); if (!n.endsWith(".class")) continue; n = n.substring(0, n.length() - 6).replace('/', '.'); new DumpClass(n); } } catch (Exception e) { e.printStackTrace(); } } else { new DumpClass(name); } }
From source file:POP3Demo.java
public static void main(String[] args) throws Exception { int POP3Port = 110; Socket client = new Socket("127.0.0.1", POP3Port); InputStream is = client.getInputStream(); BufferedReader sockin = new BufferedReader(new InputStreamReader(is)); OutputStream os = client.getOutputStream(); PrintWriter sockout = new PrintWriter(os, true); String cmd = "user Smith"; sockout.println(cmd);/*from ww w . j a v a2s . co m*/ String reply = sockin.readLine(); cmd = "pass "; sockout.println(cmd + "popPassword"); reply = sockin.readLine(); cmd = "stat"; sockout.println(cmd); reply = sockin.readLine(); if (reply == null) return; cmd = "retr 1"; sockout.println(cmd); if (cmd.toLowerCase().startsWith("retr") && reply.charAt(0) == '+') do { reply = sockin.readLine(); System.out.println("S:" + reply); if (reply != null && reply.length() > 0) if (reply.charAt(0) == '.') break; } while (true); cmd = "quit"; sockout.println(cmd); client.close(); }
From source file:ExecuteSQL.java
public static void main(String[] args) { Connection conn = null; // Our JDBC connection to the database server try {//from www . j av a 2 s .c o m String driver = null, url = null, user = "", password = ""; // Parse all the command-line arguments for (int n = 0; n < args.length; n++) { if (args[n].equals("-d")) driver = args[++n]; else if (args[n].equals("-u")) user = args[++n]; else if (args[n].equals("-p")) password = args[++n]; else if (url == null) url = args[n]; else throw new IllegalArgumentException("Unknown argument."); } // The only required argument is the database URL. if (url == null) throw new IllegalArgumentException("No database specified"); // If the user specified the classname for the DB driver, load // that class dynamically. This gives the driver the opportunity // to register itself with the DriverManager. if (driver != null) Class.forName(driver); // Now open a connection the specified database, using the // user-specified username and password, if any. The driver // manager will try all of the DB drivers it knows about to try to // parse the URL and connect to the DB server. conn = DriverManager.getConnection(url, user, password); // Now create the statement object we'll use to talk to the DB Statement s = conn.createStatement(); // Get a stream to read from the console BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // Loop forever, reading the user's queries and executing them while (true) { System.out.print("sql> "); // prompt the user System.out.flush(); // make the prompt appear now. String sql = in.readLine(); // get a line of input from user // Quit when the user types "quit". if ((sql == null) || sql.equals("quit")) break; // Ignore blank lines if (sql.length() == 0) continue; // Now, execute the user's line of SQL and display results. try { // We don't know if this is a query or some kind of // update, so we use execute() instead of executeQuery() // or executeUpdate() If the return value is true, it was // a query, else an update. boolean status = s.execute(sql); // Some complex SQL queries can return more than one set // of results, so loop until there are no more results do { if (status) { // it was a query and returns a ResultSet ResultSet rs = s.getResultSet(); // Get results printResultsTable(rs, System.out); // Display them } else { // If the SQL command that was executed was some // kind of update rather than a query, then it // doesn't return a ResultSet. Instead, we just // print the number of rows that were affected. int numUpdates = s.getUpdateCount(); System.out.println("Ok. " + numUpdates + " rows affected."); } // Now go see if there are even more results, and // continue the results display loop if there are. status = s.getMoreResults(); } while (status || s.getUpdateCount() != -1); } // If a SQLException is thrown, display an error message. // Note that SQLExceptions can have a general message and a // DB-specific message returned by getSQLState() catch (SQLException e) { System.err.println("SQLException: " + e.getMessage() + ":" + e.getSQLState()); } // Each time through this loop, check to see if there were any // warnings. Note that there can be a whole chain of warnings. finally { // print out any warnings that occurred SQLWarning w; for (w = conn.getWarnings(); w != null; w = w.getNextWarning()) System.err.println("WARNING: " + w.getMessage() + ":" + w.getSQLState()); } } } // Handle exceptions that occur during argument parsing, database // connection setup, etc. For SQLExceptions, print the details. catch (Exception e) { System.err.println(e); if (e instanceof SQLException) System.err.println("SQL State: " + ((SQLException) e).getSQLState()); System.err.println( "Usage: java ExecuteSQL [-d <driver>] " + "[-u <user>] [-p <password>] <database URL>"); } // Be sure to always close the database connection when we exit, // whether we exit because the user types 'quit' or because of an // exception thrown while setting things up. Closing this connection // also implicitly closes any open statements and result sets // associated with it. finally { try { conn.close(); } catch (Exception e) { } } }
From source file:de.uni_rostock.goodod.evaluator.EvaluatorApp.java
public static void main(String[] args) { Logger root = Logger.getRootLogger(); if (false == root.getAllAppenders().hasMoreElements()) { root.addAppender(new ConsoleAppender(new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN))); root.setLevel(Level.INFO); }/*from w ww . ja va 2 s . com*/ config = Configuration.getConfiguration(args); if (config.getBoolean("helpMode", false)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("evaluator [option]... <test_spec.plist | ontology1.owl ontology2.owl> ", config.getOptions()); System.exit(0); } if (config.getBoolean("debug", false)) { root.setLevel(Level.DEBUG); } OntologyTest theTest = null; String testFile = config.getString("testFile"); try { theTest = new OntologyTest(config.configurationAt("testDescription")); theTest.executeTest(); } catch (Throwable e) { logger.fatal("Fatal error", e); System.exit(1); } logger.info(theTest.toString()); String similarityType = config.getString("similarity"); String baseName = similarityType + "-" + testFile.substring(0, (testFile.length() - 6)); File precisionFile = null; File recallFile = null; File fmeasureFile = null; File similarityFile = null; precisionFile = new File(baseName + ".precision.csv"); recallFile = new File(baseName + ".recall.csv"); fmeasureFile = new File(baseName + ".fmeasure.csv"); similarityFile = new File(baseName + ".csv"); try { if (theTest.providesFMeasure()) { theTest.writePrecisionTable(new FileWriter(precisionFile)); theTest.writeRecallTable(new FileWriter(recallFile)); theTest.writeFMeasureTable(new FileWriter(fmeasureFile)); } else { theTest.writeSimilarityTable(new FileWriter(similarityFile)); } } catch (IOException e) { logger.warn("Could not write test data", e); } }
From source file:edu.ku.brc.util.GeoRefConverter.java
/** * @param args//from w ww. j ava2 s . c o m * @throws Exception * @throws Exception */ public static void main(String[] args) throws Exception { String destFormat = GeoRefFormat.DMS_PLUS_MINUS.name(); String[] inputStrings = new String[] { // +/- Deg Min Sec "//+/- Deg Min Sec", "0 0 0", "0 0 0.", "-32 45 16.8232", "-32d 45' 16.8232\"", "-32d45'16.8232\"", "-3245'16.8232\"", "-32 45' 16.82\"", "-32 45 16.82", "-32 45 6.8232", "-32 45 6.82", "-32 45 0.82", "-132 45 16.82151", "-132 45 6.82", "32 45 16.8232", "32 45 16.82", "32 45 6.8232", "32 45 6.82", "32 45 0.82", "132 45 16.82151", "132 45 6.82", // Deg Min Sec N/S/E/W "//Deg Min Sec N/S/E/W", "32 45 16.8232 N", "32 45 16.82 N", "32d45'16.82\" N", "32d45'16.82\"N", "32d 45' 16.82\" N", "32 45' 16.82\" N", "32 45 16.82 N", "32 45 6.8232 N", "32 45 6.82 N", "32 45 0.82 N", "132 45 16.82151 N", "132 45 6.82 N", "32 45 16.8232 S", "32 45 16.82 S", "32 45 6.8232 S", "32 45 6.82 S", "32 45 0.82 S", "132 45 16.82151 S", "132 45 6.82 S", "32 45 16.8232 E", "32 45 16.82 E", "32 45 6.8232 E", "32 45 6.82 E", "32 45 0.82 E", "132 45 16.82151 E", "132 45 6.82 E", "32 45 16.8232 W", "32 45 16.82 W", "32 45 6.8232 W", "32 45 6.82 W", "32 45 0.82 W", "132 45 16.82151 W", "132 45 6.82 W", // +/- Deg Min "//+/- Deg Min", "0 0", "0 0.", "-32 16.8232", "-32 16.82", "-32 16.82'", "-3216.82", "-32d 16", "-32 16.82", "-32 6.8232", "-32 6.82", "-32 0.82", "-132 16.82151", "-132 6.82", "32 16.8232", "32 16.82", "32 6.8232", "32 6.82", "32 0.82", "132 16.82151", "132 6.82", // Deg Min N/S/E/W "//Deg Min N/S/E/W", "32 16.8232 N", "32 16.82 N", "32 6.8232 N", "32 6.82 N", "32 0.82 N", "132 16.82151 N", "132 6.82 N", "32 16.8232 S", "32 16.82 S", "32 6.8232 S", "32 6.82 S", "32 0.82 S", "132 16.82151 S", "132 6.82 S", "32 16.8232 E", "32 16.82 E", "32 6.8232 E", "32 6.82 E", "32 0.82 E", "132 16.82151 E", "132 6.82 E", "32 16.8232 W", "32 16.82 W", "32 6.8232 W", "32 6.82 W", "32 0.82 W", "132 16.82151 W", "132 6.82 W", // +/- Decimal Degrees "//+/- Decimal Degrees", "0", "0.", "-16.8232", "-16.8232", "-16.82", "-6.8232", "-6.82", "-0.82", "-116.82151", "-116.82", "-1.82", "16.8232", "16.82", "6.8232", "6.82", "0.82", "116.82151", "116.82", "1.82", // Decimal Degrees N/S/E/W "//Decimal Degrees N/S/E/W", "16.8232 N", "16.82 N", "16.8232 N", "16.82 N", "16.8232N", "16.82N", "6.8232 N", "6.82 N", "0.82 N", "116.82151 N", "116.82 N", "1.82 N", "16.8232 S", "16.82 S", "6.8232 S", "6.82 S", "0.82 S", "116.82151 S", "116.82 S", "1.82 S", "16.8232 E", "16.82 E", "6.8232 E", "6.82 E", "0.82 E", "116.82151 E", "116.82 E", "1.82 E", "16.8232 W", "16.82 W", "6.8232 W", "6.82 W", "0.82 W", "116.82151 W", "116.82 W", "1.82 W", "41 43." }; for (String input : inputStrings) { if (input.length() == 0) { continue; } if (input.startsWith("//")) { System.out.println(); System.out.println("----------------------------------"); System.out.println("----------------------------------"); System.out.println(input.substring(2)); System.out.println("----------------------------------"); System.out.println("----------------------------------"); continue; } System.out.println("Input: " + input); BigDecimal degreesPlusMinus = null; for (GeoRefFormat format : GeoRefFormat.values()) { if (input.matches(format.regex)) { System.out.println("Format match: " + format.name()); degreesPlusMinus = format.convertToDecimalDegrees(input); break; } } // if we weren't able to find a matching format, throw an exception if (degreesPlusMinus == null) { System.out.println("No matching format found"); System.out.println("----------------------------------"); continue; } int decimalFmtLen = 0; int decIndex = input.lastIndexOf('.'); if (decIndex > -1 && input.length() > decIndex) { decimalFmtLen = input.length() - decIndex; } String convertedVal = null; if (destFormat == GeoRefFormat.DMS_PLUS_MINUS.name()) { convertedVal = LatLonConverter.convertToSignedDDMMSS(degreesPlusMinus, Math.min(LatLonConverter.DDMMSS_LEN, decimalFmtLen)); } else if (destFormat == GeoRefFormat.DM_PLUS_MINUS.name()) { convertedVal = LatLonConverter.convertToSignedDDMMMM(degreesPlusMinus, Math.min(LatLonConverter.DDMMMM_LEN, decimalFmtLen)); } else if (destFormat == GeoRefFormat.D_PLUS_MINUS.name()) { convertedVal = LatLonConverter.convertToSignedDDDDDD(degreesPlusMinus, Math.min(LatLonConverter.DDDDDD_LEN, decimalFmtLen)); } System.out.println("Converted value: " + convertedVal); System.out.println("----------------------------------"); } GeoRefConverter converter = new GeoRefConverter(); for (String input : inputStrings) { if (input.length() == 0) { continue; } if (input.startsWith("//")) { System.out.println(); System.out.println("----------------------------------"); System.out.println("----------------------------------"); System.out.println(input.substring(2)); System.out.println("----------------------------------"); System.out.println("----------------------------------"); continue; } System.out.println("Input: " + input); String decimalDegrees = converter.convert(input, GeoRefConverter.GeoRefFormat.D_PLUS_MINUS.name()); System.out.println("Decimal degrees: " + decimalDegrees); } System.out.println("----------------------------------"); System.out.println("----------------------------------"); System.out.println("----------------------------------"); System.out.println("----------------------------------"); System.out.println("----------------------------------"); System.out.println("----------------------------------"); System.out.println("----------------------------------"); System.out.println("----------------------------------"); String problemString = "41 43 18."; System.out.println("input: " + problemString); String d = converter.convert(problemString, GeoRefFormat.D_PLUS_MINUS.name()); String dm = converter.convert(problemString, GeoRefFormat.DM_PLUS_MINUS.name()); String dms = converter.convert(problemString, GeoRefFormat.DMS_PLUS_MINUS.name()); System.out.println(d + " : " + dm + " : " + dms); problemString = d; System.out.println("input: " + problemString); String d2 = converter.convert(problemString, GeoRefFormat.D_PLUS_MINUS.name()); String dm2 = converter.convert(problemString, GeoRefFormat.DM_PLUS_MINUS.name()); String dms2 = converter.convert(problemString, GeoRefFormat.DMS_PLUS_MINUS.name()); System.out.println(d2 + " : " + dm2 + " : " + dms2); problemString = dm; System.out.println("input: " + problemString); String d3 = converter.convert(problemString, GeoRefFormat.D_PLUS_MINUS.name()); String dm3 = converter.convert(problemString, GeoRefFormat.DM_PLUS_MINUS.name()); String dms3 = converter.convert(problemString, GeoRefFormat.DMS_PLUS_MINUS.name()); System.out.println(d3 + " : " + dm3 + " : " + dms3); }
From source file:eu.fbk.dkm.sectionextractor.pantheon.WikipediaGoodTextExtractor.java
public static void main(String args[]) throws IOException { CommandLineWithLogger commandLineWithLogger = new CommandLineWithLogger(); commandLineWithLogger.addOption(OptionBuilder.withArgName("file").hasArg() .withDescription("wikipedia xml dump file").isRequired().withLongOpt("wikipedia-dump").create("d")); commandLineWithLogger.addOption(OptionBuilder.withArgName("dir").hasArg() .withDescription("output directory in which to store output files").isRequired() .withLongOpt("output-dir").create("o")); commandLineWithLogger/*from ww w . j a va 2s. c o m*/ .addOption(OptionBuilder.withDescription("use NAF format").withLongOpt("naf").create("n")); commandLineWithLogger.addOption(OptionBuilder.withDescription("tokenize and ssplit with Stanford") .withLongOpt("stanford").create("s")); commandLineWithLogger.addOption(OptionBuilder.withArgName("file").hasArg().withDescription("Filter file") .withLongOpt("filter").create("f")); commandLineWithLogger.addOption(OptionBuilder.withArgName("file").hasArg() .withDescription("ID and category file").withLongOpt("idcat").create("i")); commandLineWithLogger.addOption(OptionBuilder.withArgName("file").hasArg().withDescription("Redirect file") .withLongOpt("redirect").create("r")); commandLineWithLogger.addOption(OptionBuilder.withArgName("int").hasArg() .withDescription( "number of threads (default " + AbstractWikipediaXmlDumpParser.DEFAULT_THREADS_NUMBER + ")") .withLongOpt("num-threads").create("t")); commandLineWithLogger.addOption(OptionBuilder.withArgName("int").hasArg() .withDescription("number of pages to process (default all)").withLongOpt("num-pages").create("p")); commandLineWithLogger.addOption(OptionBuilder.withArgName("int").hasArg() .withDescription("receive notification every n pages (default " + AbstractWikipediaExtractor.DEFAULT_NOTIFICATION_POINT + ")") .withLongOpt("notification-point").create("b")); commandLineWithLogger.addOption(new Option("n", "NAF format")); CommandLine commandLine = null; try { commandLine = commandLineWithLogger.getCommandLine(args); PropertyConfigurator.configure(commandLineWithLogger.getLoggerProps()); } catch (Exception e) { System.exit(1); } int numThreads = Integer.parseInt(commandLine.getOptionValue("num-threads", Integer.toString(AbstractWikipediaXmlDumpParser.DEFAULT_THREADS_NUMBER))); int numPages = Integer.parseInt(commandLine.getOptionValue("num-pages", Integer.toString(AbstractWikipediaExtractor.DEFAULT_NUM_PAGES))); int notificationPoint = Integer.parseInt(commandLine.getOptionValue("notification-point", Integer.toString(AbstractWikipediaExtractor.DEFAULT_NOTIFICATION_POINT))); boolean nafFormat = commandLine.hasOption("n"); boolean useStanford = commandLine.hasOption("s"); HashMap<Integer, String> idCategory = new HashMap<>(); String idcatFileName = commandLine.getOptionValue("idcat"); if (idcatFileName != null) { logger.info("Loading categories"); File idcatFile = new File(idcatFileName); if (idcatFile.exists()) { List<String> lines = Files.readLines(idcatFile, Charsets.UTF_8); for (String line : lines) { line = line.trim(); if (line.length() == 0) { continue; } String[] parts = line.split("\\s+"); if (parts.length < 3) { continue; } idCategory.put(Integer.parseInt(parts[1]), parts[2]); } } } HashMap<String, String> redirects = new HashMap<>(); String redirectFileName = commandLine.getOptionValue("redirect"); if (redirectFileName != null) { logger.info("Loading redirects"); File redirectFile = new File(redirectFileName); if (redirectFile.exists()) { List<String> lines = Files.readLines(redirectFile, Charsets.UTF_8); for (String line : lines) { line = line.trim(); if (line.length() == 0) { continue; } String[] parts = line.split("\\t+"); if (parts.length < 2) { continue; } redirects.put(parts[0], parts[1]); } } } HashSet<String> pagesToConsider = null; String filterFileName = commandLine.getOptionValue("filter"); if (filterFileName != null) { logger.info("Loading file list"); File filterFile = new File(filterFileName); if (filterFile.exists()) { pagesToConsider = new HashSet<>(); List<String> lines = Files.readLines(filterFile, Charsets.UTF_8); for (String line : lines) { line = line.trim(); if (line.length() == 0) { continue; } line = line.replaceAll("\\s+", "_"); pagesToConsider.add(line); addRedirects(pagesToConsider, redirects, line, 0); } } } ExtractorParameters extractorParameters = new ExtractorParameters( commandLine.getOptionValue("wikipedia-dump"), commandLine.getOptionValue("output-dir")); File outputFolder = new File(commandLine.getOptionValue("output-dir")); if (!outputFolder.exists()) { boolean mkdirs = outputFolder.mkdirs(); if (!mkdirs) { throw new IOException("Unable to create folder " + outputFolder.getAbsolutePath()); } } WikipediaExtractor wikipediaPageParser = new WikipediaGoodTextExtractor(numThreads, numPages, extractorParameters.getLocale(), outputFolder, nafFormat, pagesToConsider, useStanford, idCategory); wikipediaPageParser.setNotificationPoint(notificationPoint); wikipediaPageParser.start(extractorParameters); logger.info("extraction ended " + new Date()); }
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./*ww w .j a v a 2 s. 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:Main.java
public static void main(String[] args) { String text = "one\ntwo\nthree\nfour\nfive"; JFrame frame = new JFrame("title"); JTextArea textArea = new JTextArea(text, 1, 30); // shows only one line JScrollPane scrollPane = new JScrollPane(textArea); frame.add(scrollPane);/* w w w .j a va2 s .c o m*/ frame.pack(); frame.setVisible(true); final JViewport viewport = scrollPane.getViewport(); textArea.addCaretListener(e -> { System.out.println("First : " + viewport.getViewPosition()); System.out.println("Second: " + viewport.getViewPosition()); }); textArea.setCaretPosition(text.length()); }