List of usage examples for java.util Iterator hasNext
boolean hasNext();
From source file:com.github.xbn.examples.io.non_xbn.ReadInActiveAccountsFromFile.java
public static final void main(String[] rqdInputPathInStrArray) { //Read command-line String sSrc = null;//from ww w. ja va 2 s. c o m try { sSrc = rqdInputPathInStrArray[0]; } catch (IndexOutOfBoundsException ibx) { System.out.println("Missing one-and-only required parameter: The full path to Java source-code file."); return; } //Open input file File inputFile = new File(sSrc); Iterator<String> lineItr = null; try { lineItr = FileUtils.lineIterator(inputFile); } catch (IOException iox) { System.out.println("Cannot open \"" + sSrc + "\". " + iox); return; } while (lineItr.hasNext()) { String line = lineItr.next(); String[] userPassIsActive = line.split(" "); String username = userPassIsActive[0]; String password = userPassIsActive[1]; boolean isActive = Boolean.parseBoolean(userPassIsActive[2]); System.out.println("username=" + username + ", password=" + password + ", isActive=" + isActive + ""); } }
From source file:com.hsbc.frc.SevenHero.ClientProxyAuthentication.java
public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); try {//from www .ja v a 2 s . co m httpclient.getCredentialsProvider().setCredentials(new AuthScope("133.13.162.149", 8080), new UsernamePasswordCredentials("43668069", "wf^O^2013")); HttpHost targetHost = new HttpHost("pt.3g.qq.com"); HttpHost proxy = new HttpHost("133.13.162.149", 8080); BasicClientCookie netscapeCookie = null; httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); // httpclient.getCookieStore().addCookie(netscapeCookie); httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); HttpGet httpget = new HttpGet("/"); httpget.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19"); System.out.println("executing request: " + httpget.getRequestLine()); System.out.println("via proxy: " + proxy); System.out.println("to target: " + targetHost); HttpResponse response = httpclient.execute(targetHost, httpget); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } InputStream is = entity.getContent(); StringBuffer sb = new StringBuffer(200); byte data[] = new byte[65536]; int n = 1; do { n = is.read(data); if (n > 0) { sb.append(new String(data)); } } while (n > 0); // System.out.println(sb); EntityUtils.consume(entity); System.out.println("----------------------------------------"); Header[] headerlist = response.getAllHeaders(); for (int i = 0; i < headerlist.length; i++) { Header header = headerlist[i]; if (header.getName().equals("Set-Cookie")) { String setCookie = header.getValue(); String cookies[] = setCookie.split(";"); for (int j = 0; j < cookies.length; j++) { String cookie[] = cookies[j].split("="); CookieManager.cookie.put(cookie[0], cookie[1]); } } System.out.println(header.getName() + ":" + header.getValue()); } String sid = getSid(sb.toString(), "&"); System.out.println("sid: " + sid); httpclient = new DefaultHttpClient(); httpclient.getCredentialsProvider().setCredentials(new AuthScope("133.13.162.149", 8080), new UsernamePasswordCredentials("43668069", "wf^O^2013")); String url = Constant.openUrl + "&" + sid; targetHost = new HttpHost(url); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); httpget = new HttpGet("/"); httpget.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19"); Iterator it = CookieManager.cookie.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); Object key = entry.getKey(); Object value = entry.getValue(); netscapeCookie = new BasicClientCookie((String) (key), (String) (value)); netscapeCookie.setVersion(0); netscapeCookie.setDomain(".qq.com"); netscapeCookie.setPath("/"); // httpclient.getCookieStore().addCookie(netscapeCookie); } response = httpclient.execute(targetHost, httpget); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } }
From source file:com.github.xbn.examples.io.non_xbn.DelimitWordsInATextFile.java
public static final void main(String[] as_1RqdPathToInput) { //Read command-line String sSrc = null;//from www. j av a 2 s.co m try { sSrc = as_1RqdPathToInput[0]; } catch (IndexOutOfBoundsException ibx) { System.out.println("Missing one-and-only required parameter: The full path to input file."); return; } //Open input file File fSrc = new File(sSrc); Iterator<String> lineItr = null; try { lineItr = FileUtils.lineIterator(fSrc); } catch (IOException iox) { System.out.println("Cannot open \"" + sSrc + "\". " + iox); return; } int i = 0; while (lineItr.hasNext()) { i++; String as[] = lineItr.next().split(" "); System.out.println("Line " + i + ": " + Arrays.toString(as)); } }
From source file:edu.gslis.ts.ChunkToFile.java
public static void main(String[] args) { try {/*w w w .ja v a2 s. c om*/ // Get the commandline options Options options = createOptions(); CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse(options, args); String inputPath = cmd.getOptionValue("input"); String indexPath = cmd.getOptionValue("index"); String eventsPath = cmd.getOptionValue("events"); String stopPath = cmd.getOptionValue("stop"); String outputPath = cmd.getOptionValue("output"); IndexWrapper index = IndexWrapperFactory.getIndexWrapper(indexPath); Stopper stopper = new Stopper(stopPath); Map<Integer, FeatureVector> queries = readEvents(eventsPath, stopper); // Setup the filter ChunkToFile f = new ChunkToFile(); if (inputPath != null) { File infile = new File(inputPath); if (infile.isDirectory()) { Iterator<File> files = FileUtils.iterateFiles(infile, null, true); while (files.hasNext()) { File file = files.next(); System.err.println(file.getAbsolutePath()); f.filter(file, queries, index, stopper, outputPath); } } else System.err.println(infile.getAbsolutePath()); f.filter(infile, queries, index, stopper, outputPath); } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.puffywhiteshare.PWSApp.java
/** * @param args/* ww w. j av a2 s .c o m*/ * @throws IOException */ public static void main(String[] args) throws IOException { CloudBucket cloud = new CloudBucket(); logger.info("Test my output bitches"); Yaml y = new Yaml(); File f = new File("Playing.yml"); FileInputStream fis = new FileInputStream(f); Map m = (Map) y.load(fis); Long startFiles = System.currentTimeMillis(); Iterator<File> fileIterator = FileUtils.iterateFiles(new File("/Users/chad/Pictures/."), null, true); do { File file = fileIterator.next(); cloud.add(file); } while (fileIterator.hasNext()); Long endFiles = System.currentTimeMillis(); System.out.println("Files processing took " + ((endFiles - startFiles))); Long startSer = System.currentTimeMillis(); String filename = "cloud.ser"; FileOutputStream fos = null; ObjectOutputStream out = null; try { fos = new FileOutputStream(filename); out = new ObjectOutputStream(fos); out.writeObject(cloud); out.close(); } catch (IOException ex) { ex.printStackTrace(); } Long endSer = System.currentTimeMillis(); System.out.println("Files processing took " + ((endSer - startSer))); logger.info(" Size = " + FileUtils.byteCountToDisplaySize(cloud.getSize())); logger.info("Count = " + cloud.getCount()); /* Set<String> buckets = m.keySet(); System.out.println(m.toString()); for(String bucket : buckets) { logger.info("Bucket = " + bucket); logger.info("Folders = " + m.get(bucket)); List<Object> folders = (List<Object>) m.get(bucket); for(Object folder : folders) { if(folder instanceof String) { logger.info("Folder Root = " + folder); } else if(folder instanceof Map) { logger.info("Folder Map = " + folder); } } BlockingQueue<File> fileFeed = new ArrayBlockingQueue<File>(10); Map folderMap = (Map) m.get(bucket); Set<String> folders = folderMap.entrySet(); for(String folder : folders) { logger.info("Folder = " + folder); } } */ }
From source file:edu.umd.cloud9.example.bigram.AnalyzeBigramRelativeFrequencyJson.java
@SuppressWarnings({ "static-access" }) public static void main(String[] args) { Options options = new Options(); options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT)); CommandLine cmdline = null;/*w w w . j av a 2 s . c om*/ CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); System.exit(-1); } if (!cmdline.hasOption(INPUT)) { System.out.println("args: " + Arrays.toString(args)); HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); formatter.printHelp(AnalyzeBigramRelativeFrequencyJson.class.getName(), options); ToolRunner.printGenericCommandUsage(System.out); System.exit(-1); } String inputPath = cmdline.getOptionValue(INPUT); System.out.println("input path: " + inputPath); List<PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable>> pairs = SequenceFileUtils .readDirectory(new Path(inputPath)); List<PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable>> list1 = Lists.newArrayList(); List<PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable>> list2 = Lists.newArrayList(); for (PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable> p : pairs) { BigramRelativeFrequencyJson.MyTuple bigram = p.getLeftElement(); if (bigram.getJsonObject().get("Left").getAsString().equals("light")) { list1.add(p); } if (bigram.getJsonObject().get("Left").getAsString().equals("contain")) { list2.add(p); } } Collections.sort(list1, new Comparator<PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable>>() { public int compare(PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable> e1, PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable> e2) { if (e1.getRightElement().compareTo(e2.getRightElement()) == 0) { return e1.getLeftElement().compareTo(e2.getLeftElement()); } return e2.getRightElement().compareTo(e1.getRightElement()); } }); Iterator<PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable>> iter1 = Iterators .limit(list1.iterator(), 10); while (iter1.hasNext()) { PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable> p = iter1.next(); BigramRelativeFrequencyJson.MyTuple bigram = p.getLeftElement(); System.out.println(bigram + "\t" + p.getRightElement()); } Collections.sort(list2, new Comparator<PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable>>() { public int compare(PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable> e1, PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable> e2) { if (e1.getRightElement().compareTo(e2.getRightElement()) == 0) { return e1.getLeftElement().compareTo(e2.getLeftElement()); } return e2.getRightElement().compareTo(e1.getRightElement()); } }); Iterator<PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable>> iter2 = Iterators .limit(list2.iterator(), 10); while (iter2.hasNext()) { PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable> p = iter2.next(); BigramRelativeFrequencyJson.MyTuple bigram = p.getLeftElement(); System.out.println(bigram + "\t" + p.getRightElement()); } }
From source file:com.cloud.test.utils.SubmitCert.java
public static void main(String[] args) { // Parameters List<String> argsList = Arrays.asList(args); Iterator<String> iter = argsList.iterator(); while (iter.hasNext()) { String arg = iter.next(); if (arg.equals("-c")) { certFileName = iter.next();/*from w w w . j a v a 2 s . c om*/ } if (arg.equals("-s")) { secretKey = iter.next(); } if (arg.equals("-a")) { apiKey = iter.next(); } if (arg.equals("-action")) { url = "Action=" + iter.next(); } } Properties prop = new Properties(); try { prop.load(new FileInputStream("conf/tool.properties")); } catch (IOException ex) { s_logger.error("Error reading from conf/tool.properties", ex); System.exit(2); } host = prop.getProperty("host"); port = prop.getProperty("port"); if (url.equals("Action=SetCertificate") && certFileName == null) { s_logger.error("Please set path to certificate (including file name) with -c option"); System.exit(1); } if (secretKey == null) { s_logger.error("Please set secretkey with -s option"); System.exit(1); } if (apiKey == null) { s_logger.error("Please set apikey with -a option"); System.exit(1); } if (host == null) { s_logger.error("Please set host in tool.properties file"); System.exit(1); } if (port == null) { s_logger.error("Please set port in tool.properties file"); System.exit(1); } TreeMap<String, String> param = new TreeMap<String, String>(); String req = "GET\n" + host + ":" + prop.getProperty("port") + "\n/" + prop.getProperty("accesspoint") + "\n"; String temp = ""; if (certFileName != null) { cert = readCert(certFileName); param.put("cert", cert); } param.put("AWSAccessKeyId", apiKey); param.put("Expires", prop.getProperty("expires")); param.put("SignatureMethod", prop.getProperty("signaturemethod")); param.put("SignatureVersion", "2"); param.put("Version", prop.getProperty("version")); StringTokenizer str1 = new StringTokenizer(url, "&"); while (str1.hasMoreTokens()) { String newEl = str1.nextToken(); StringTokenizer str2 = new StringTokenizer(newEl, "="); String name = str2.nextToken(); String value = str2.nextToken(); param.put(name, value); } //sort url hash map by key Set c = param.entrySet(); Iterator it = c.iterator(); while (it.hasNext()) { Map.Entry me = (Map.Entry) it.next(); String key = (String) me.getKey(); String value = (String) me.getValue(); try { temp = temp + key + "=" + URLEncoder.encode(value, "UTF-8") + "&"; } catch (Exception ex) { s_logger.error("Unable to set parameter " + value + " for the command " + param.get("command"), ex); } } temp = temp.substring(0, temp.length() - 1); String requestToSign = req + temp; String signature = UtilsForTest.signRequest(requestToSign, secretKey); String encodedSignature = ""; try { encodedSignature = URLEncoder.encode(signature, "UTF-8"); } catch (Exception ex) { ex.printStackTrace(); } String url = "http://" + host + ":" + prop.getProperty("port") + "/" + prop.getProperty("accesspoint") + "?" + temp + "&Signature=" + encodedSignature; s_logger.info("Sending request with url: " + url + "\n"); sendRequest(url); }
From source file:com.glaf.core.util.JsonUtils.java
public static void main(String[] args) throws Exception { Map<String, Object> dataMap = new java.util.HashMap<String, Object>(); dataMap.put("key01", ""); dataMap.put("key02", 12345); dataMap.put("key03", 789.85D); dataMap.put("date", new Date()); Collection<Object> actorIds = new HashSet<Object>(); actorIds.add("sales01"); actorIds.add("sales02"); actorIds.add("sales03"); actorIds.add("sales04"); actorIds.add("sales05"); dataMap.put("actorIds", actorIds.toArray()); dataMap.put("x_sale_actor_actorIds", actorIds); Map<String, Object> xxxMap = new java.util.HashMap<String, Object>(); xxxMap.put("0", "--------"); xxxMap.put("1", "?"); xxxMap.put("2", ""); xxxMap.put("3", ""); dataMap.put("trans", xxxMap); String str = JsonUtils.encode(dataMap); System.out.println(str);//from w w w. j a va2 s. c o m Map<?, ?> p = JsonUtils.decode(str); System.out.println(p); System.out.println(p.get("date").getClass().getName()); String xx = "{name:\"trans\",nodeType:\"select\",children:{\"1\":\"?\",\"3\":\"\",\"2\":\"\",\"0\":\"--------\"}}"; Map<String, Object> xMap = JsonUtils.decode(xx); System.out.println(xMap); Set<Entry<String, Object>> entrySet = xMap.entrySet(); for (Entry<String, Object> entry : entrySet) { String key = entry.getKey(); Object value = entry.getValue(); System.out.println(key + " = " + value); System.out.println(key.getClass().getName() + " " + value.getClass().getName()); if (value instanceof JSONObject) { JSONObject json = (JSONObject) value; Iterator<?> iter = json.keySet().iterator(); while (iter.hasNext()) { String kk = (String) iter.next(); System.out.println(kk + " = " + json.get(kk)); } } } }
From source file:ProducerTool.java
public static void main(String[] args) { ArrayList<ProducerTool> threads = new ArrayList(); ProducerTool producerTool = new ProducerTool(); String[] unknown = CommandLineSupport.setOptions(producerTool, args); if (unknown.length > 0) { System.out.println("Unknown options: " + Arrays.toString(unknown)); System.exit(-1);//from w ww. ja v a2s . c o m } producerTool.showParameters(); for (int threadCount = 1; threadCount <= parallelThreads; threadCount++) { producerTool = new ProducerTool(); CommandLineSupport.setOptions(producerTool, args); producerTool.start(); threads.add(producerTool); } while (true) { Iterator<ProducerTool> itr = threads.iterator(); int running = 0; while (itr.hasNext()) { ProducerTool thread = itr.next(); if (thread.isAlive()) { running++; } } if (running <= 0) { System.out.println("All threads completed their work"); break; } try { Thread.sleep(1000); } catch (Exception e) { } } }
From source file:com.adobe.aem.demomachine.Json2Csv.java
public static void main(String[] args) throws IOException { String inputFile1 = null;// ww w . j a v a 2s. c o m String inputFile2 = null; String outputFile = null; HashMap<String, String> hmReportSuites = new HashMap<String, String>(); // Command line options for this tool Options options = new Options(); options.addOption("c", true, "Filename 1"); options.addOption("r", true, "Filename 2"); options.addOption("o", true, "Filename 3"); CommandLineParser parser = new BasicParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("c")) { inputFile1 = cmd.getOptionValue("c"); } if (cmd.hasOption("r")) { inputFile2 = cmd.getOptionValue("r"); } if (cmd.hasOption("o")) { outputFile = cmd.getOptionValue("o"); } if (inputFile1 == null || inputFile1 == null || outputFile == null) { System.exit(-1); } } catch (ParseException ex) { logger.error(ex.getMessage()); } // List of customers and report suites for these customers String sInputFile1 = readFile(inputFile1, Charset.defaultCharset()); sInputFile1 = sInputFile1.replaceAll("ObjectId\\(\"([0-9a-z]*)\"\\)", "\"$1\""); // Processing the list of report suites for each customer try { JSONArray jCustomers = new JSONArray(sInputFile1.trim()); for (int i = 0, size = jCustomers.length(); i < size; i++) { JSONObject jCustomer = jCustomers.getJSONObject(i); Iterator<?> keys = jCustomer.keys(); String companyName = null; while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("company")) { companyName = jCustomer.getString(key); } } keys = jCustomer.keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("report_suites")) { JSONArray jReportSuites = jCustomer.getJSONArray(key); for (int j = 0, rSize = jReportSuites.length(); j < rSize; j++) { hmReportSuites.put(jReportSuites.getString(j), companyName); System.out.println(jReportSuites.get(j) + " for company " + companyName); } } } } // Creating the out put file PrintWriter writer = new PrintWriter(outputFile, "UTF-8"); writer.println("\"" + "Customer" + "\",\"" + "ReportSuite ID" + "\",\"" + "Number of Documents" + "\",\"" + "Last Updated" + "\""); // Processing the list of SOLR collections String sInputFile2 = readFile(inputFile2, Charset.defaultCharset()); sInputFile2 = sInputFile2.replaceAll("NumberLong\\(\"([0-9a-z]*)\"\\)", "\"$1\""); JSONObject jResults = new JSONObject(sInputFile2.trim()); JSONArray jCollections = jResults.getJSONArray("result"); for (int i = 0, size = jCollections.length(); i < size; i++) { JSONObject jCollection = jCollections.getJSONObject(i); String id = null; String number = null; String lastupdate = null; Iterator<?> keys = jCollection.keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("_id")) { id = jCollection.getString(key); } } keys = jCollection.keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("noOfDocs")) { number = jCollection.getString(key); } } keys = jCollection.keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("latestUpdateDate")) { lastupdate = jCollection.getString(key); } } Date d = new Date(Long.parseLong(lastupdate)); System.out.println(hmReportSuites.get(id) + "," + id + "," + number + "," + lastupdate + "," + new SimpleDateFormat("MM-dd-yyyy").format(d)); writer.println("\"" + hmReportSuites.get(id) + "\",\"" + id + "\",\"" + number + "\",\"" + new SimpleDateFormat("MM-dd-yyyy").format(d) + "\""); } writer.close(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } }