List of usage examples for java.util List get
E get(int index);
From source file:Main.java
public static void main(String[] args) { List<String> list = new LinkedList<String>(); list.add("a"); list.add("b"); list.add("c"); list.add("d"); list.add("e"); list.add("f"); Collections.sort(list);//w ww .jav a2 s . c o m System.out.println(list); int index = Collections.binarySearch(list, "c"); if (index > 0) { System.out.println("Found at index = " + index); String month = (String) list.get(index); System.out.println(month); } }
From source file:kindleclippings.quizlet.QuizletSync.java
public static void main(String[] args) throws IOException, JSONException, URISyntaxException, InterruptedException, BackingStoreException { ProgressMonitor progress = new ProgressMonitor(null, "QuizletSync", "loading Kindle clippings file", 0, 100);/*from ww w.j av a2 s .co m*/ progress.setMillisToPopup(0); progress.setMillisToDecideToPopup(0); progress.setProgress(0); try { Map<String, List<Clipping>> books = readClippingsFile(); if (books == null) return; if (books.isEmpty()) { JOptionPane.showMessageDialog(null, "no clippings to be uploaded", "QuizletSync", JOptionPane.OK_OPTION); return; } progress.setNote("checking Quizlet account"); progress.setProgress(5); Preferences prefs = getPrefs(); QuizletAPI api = new QuizletAPI(prefs.get("access_token", null)); Collection<TermSet> sets = null; try { progress.setNote("checking Quizlet library"); progress.setProgress(10); sets = api.getSets(prefs.get("user_id", null)); } catch (IOException e) { if (e.toString().contains("401")) { // Not Authorized => Token has been revoked clearPrefs(); prefs = getPrefs(); api = new QuizletAPI(prefs.get("access_token", null)); sets = api.getSets(prefs.get("user_id", null)); } else { throw e; } } progress.setProgress(15); progress.setMaximum(15 + books.size()); progress.setNote("uploading new notes"); Map<String, TermSet> indexedSets = new HashMap<String, TermSet>(sets.size()); for (TermSet t : sets) { indexedSets.put(t.getTitle(), t); } int pro = 15; int createdSets = 0; int createdTerms = 0; int updatedTerms = 0; for (List<Clipping> c : books.values()) { String book = c.get(0).getBook(); progress.setNote(book); progress.setProgress(pro++); TermSet termSet = indexedSets.get(book); if (termSet == null) { if (c.size() < 2) { System.err.println("ignored [" + book + "] (need at least two notes)"); continue; } addSet(api, book, c); createdSets++; createdTerms += c.size(); continue; } // compare against existing terms for (Clipping cl : c) { if (!checkExistingTerm(cl, termSet)) { addTerm(api, termSet, cl); updatedTerms++; } } } progress.setProgress(pro++); if (createdSets == 0 && updatedTerms == 0) { JOptionPane.showMessageDialog(null, "Done.\nNo new data was uploaded", "QuizletSync", JOptionPane.OK_OPTION); } else if (createdSets > 0) { JOptionPane.showMessageDialog(null, String.format( "Done.\nCreated %d new sets with %d cards, and added %d cards to existing sets", createdSets, createdTerms, updatedTerms), "QuizletSync", JOptionPane.OK_OPTION); } else { JOptionPane.showMessageDialog(null, String.format("Done.\nAdded %d cards to existing sets", updatedTerms), "QuizletSync", JOptionPane.OK_OPTION); } } finally { progress.close(); } System.exit(0); }
From source file:AmazonKinesisCreate.java
public static void main(String[] args) throws Exception { init();/*from w ww. java2s.c o m*/ final String myStreamName = "philsteststream"; final Integer myStreamSize = 1; // Create a stream. The number of shards determines the provisioned throughput. CreateStreamRequest createStreamRequest = new CreateStreamRequest(); createStreamRequest.setStreamName(myStreamName); createStreamRequest.setShardCount(myStreamSize); // pt kinesisClient.createStream(createStreamRequest); // The stream is now being created. LOG.info("Creating Stream : " + myStreamName); waitForStreamToBecomeAvailable(myStreamName); // list all of my streams ListStreamsRequest listStreamsRequest = new ListStreamsRequest(); listStreamsRequest.setLimit(10); ListStreamsResult listStreamsResult = kinesisClient.listStreams(listStreamsRequest); List<String> streamNames = listStreamsResult.getStreamNames(); while (listStreamsResult.isHasMoreStreams()) { if (streamNames.size() > 0) { listStreamsRequest.setExclusiveStartStreamName(streamNames.get(streamNames.size() - 1)); } listStreamsResult = kinesisClient.listStreams(listStreamsRequest); streamNames.addAll(listStreamsResult.getStreamNames()); } LOG.info("Printing my list of streams : "); // print all of my streams. if (!streamNames.isEmpty()) { System.out.println("List of my streams: "); } for (int i = 0; i < streamNames.size(); i++) { System.out.println(streamNames.get(i)); } LOG.info("Putting records in stream : " + myStreamName); // Write 10 records to the stream for (int j = 0; j < 10; j++) { try { PutRecordRequest putRecordRequest = new PutRecordRequest(); putRecordRequest.setStreamName(myStreamName); putRecordRequest.setData(ByteBuffer.wrap(String.format("testData-%d", j).getBytes())); putRecordRequest.setPartitionKey(String.format("partitionKey-%d", j)); PutRecordResult putRecordResult = kinesisClient.putRecord(putRecordRequest); System.out.println("Successfully putrecord, partition key : " + putRecordRequest.getPartitionKey() + ", ShardID : " + putRecordResult.getShardId()); Thread.sleep(1000); } catch (Exception e) { e.printStackTrace(); } } // Delete the stream. /* LOG.info("Deleting stream : " + myStreamName); DeleteStreamRequest deleteStreamRequest = new DeleteStreamRequest(); deleteStreamRequest.setStreamName(myStreamName); kinesisClient.deleteStream(deleteStreamRequest); // The stream is now being deleted. LOG.info("Stream is now being deleted : " + myStreamName); LOG.info("Streaming completed" + myStreamName); */ }
From source file:is.landsbokasafn.deduplicator.indexer.IndexingLauncher.java
public static void main(String[] args) throws Exception { loadConfiguration();//from w ww.j av a 2 s . c o m // Set default values for all settings boolean verbose = readBooleanConfig(VERBOSE_CONF_KEY, true); boolean etag = readBooleanConfig(ETAG_CONF_KEY, false); boolean canonical = readBooleanConfig(CANONICAL_CONF_KEY, true); boolean indexURL = readBooleanConfig(INDEX_URL_KEY, true); boolean addToIndex = readBooleanConfig(ADD_TO_INDEX_CONF_KEY, false); String mimefilter = readStringConfig(MIME_CONF_KEY, "^text/.*"); boolean whitelist = readBooleanConfig(WHITELIST_CONF_KEY, false); String iteratorClassName = readStringConfig(ITERATOR_CONF_KEY, WarcIterator.class.getName()); // Parse command line options CommandLineParser clp = new CommandLineParser(args, new PrintWriter(System.out)); Option[] opts = clp.getCommandLineOptions(); for (int i = 0; i < opts.length; i++) { Option opt = opts[i]; switch (opt.getId()) { case 'w': whitelist = true; break; case 'a': addToIndex = true; break; case 'e': etag = true; break; case 'h': clp.usage(0); break; case 'i': iteratorClassName = opt.getValue(); break; case 'm': mimefilter = opt.getValue(); break; case 'u': indexURL = false; break; case 's': canonical = false; break; case 'v': verbose = true; break; } } if (!indexURL && canonical) { canonical = false; } List<String> cargs = clp.getCommandLineArguments(); if (cargs.size() != 2) { // Should be exactly two arguments. Source and target! clp.usage(0); } String source = cargs.get(0); String target = cargs.get(1); // Load the CrawlDataIterator CrawlDataIterator iterator = (CrawlDataIterator) Class.forName(iteratorClassName).newInstance(); // Print initial stuff System.out.println("Indexing: " + source); System.out.println(" - Index URL: " + indexURL); System.out.println(" - Mime filter: " + mimefilter + " (" + (whitelist ? "whitelist" : "blacklist") + ")"); System.out.println(" - Includes" + (canonical ? " <canonical URL>" : "") + (etag ? " <etag>" : "")); System.out.println(" - Iterator: " + iteratorClassName); System.out.println(" - " + iterator.getSourceType()); System.out.println("Target: " + target); if (addToIndex) { System.out.println(" - Add to existing index (if any)"); } else { System.out.println(" - New index (erases any existing index at " + "that location)"); } iterator.initialize(source); // Create the index long start = System.currentTimeMillis(); IndexBuilder di = new IndexBuilder(target, indexURL, canonical, etag, addToIndex); di.writeToIndex(iterator, mimefilter, !whitelist, verbose); // Clean-up di.close(); System.out.println("Total run time: " + DateUtils.formatMillisecondsToConventional(System.currentTimeMillis() - start)); }
From source file:com.mq.rocketmq.ordermessage.Consumer.java
public static void main(String[] args) throws MQClientException { DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("please_rename_unique_group_name_3"); consumer.setNamesrvAddr("10.115.101.84:9876"); /**//from ww w. j a v a 2s .c om * Consumer?<br> * ??? */ consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET); consumer.subscribe("TopicTest", "TagA || TagC || TagD"); consumer.registerMessageListener(new MessageListenerOrderly() { AtomicLong consumeTimes = new AtomicLong(0); public ConsumeOrderlyStatus consumeMessage(List<MessageExt> msgs, ConsumeOrderlyContext context) { context.setAutoCommit(false); this.consumeTimes.incrementAndGet(); String msg = String.format("%s,%s,%s,%s,%s", this.consumeTimes.get(), Thread.currentThread().getName(), "Receive New Messages:", new String(msgs.get(0).getBody()), msgs.get(0).getTags()); // if ((this.consumeTimes.get() % 2) == 0) { // System.out.println(String.format("%s,%s","Commit",msg)); // return ConsumeOrderlyStatus.COMMIT; // } // else if ((this.consumeTimes.get() % 3) == 0) { // return ConsumeOrderlyStatus.ROLLBACK; // } // else if ((this.consumeTimes.get() % 3) == 0) { // System.out.println(String.format("%s,%s","Commit",msg)); // return ConsumeOrderlyStatus.COMMIT; // } // else if ((this.consumeTimes.get() % 5) == 0) { // context.setSuspendCurrentQueueTimeMillis(3000); // return ConsumeOrderlyStatus.SUSPEND_CURRENT_QUEUE_A_MOMENT; // } System.out.println(String.format("%s,%s", "SUCCESS", msg)); return ConsumeOrderlyStatus.SUCCESS; } }); consumer.start(); System.out.println("Consumer Started."); }
From source file:AmazonKinesisDelete.java
public static void main(String[] args) throws Exception { init();//from w ww. j av a 2 s. c om //final String myStreamName = "anotestBstream"; //final Integer myStreamSize = 1; // Create a stream. The number of shards determines the provisioned throughput. // CreateStreamRequest createStreamRequest = new CreateStreamRequest(); // createStreamRequest.setStreamName(myStreamName); // createStreamRequest.setShardCount(myStreamSize); // pt // kinesisClient.createStream(createStreamRequest); // The stream is now being created. // LOG.info("Creating Stream : " + myStreamName); // waitForStreamToBecomeAvailable(myStreamName); // list all of my streams ListStreamsRequest listStreamsRequest = new ListStreamsRequest(); listStreamsRequest.setLimit(10); ListStreamsResult listStreamsResult = kinesisClient.listStreams(listStreamsRequest); List<String> streamNames = listStreamsResult.getStreamNames(); while (listStreamsResult.isHasMoreStreams()) { if (streamNames.size() > 0) { listStreamsRequest.setExclusiveStartStreamName(streamNames.get(streamNames.size() - 1)); } listStreamsResult = kinesisClient.listStreams(listStreamsRequest); streamNames.addAll(listStreamsResult.getStreamNames()); } LOG.info("Printing my list of streams : "); // print all of my streams. if (!streamNames.isEmpty()) { System.out.println("List of my streams: "); } for (int i = 0; i < streamNames.size(); i++) { System.out.println(streamNames.get(i)); String actStreamName = streamNames.get(i); DeleteStreamRequest deleteStreamRequest = new DeleteStreamRequest(); //deleteStreamRequest.setStreamName(myStreamName); deleteStreamRequest.setStreamName(actStreamName); kinesisClient.deleteStream(deleteStreamRequest); // The stream is now being deleted. LOG.info("Stream is now being deleted : " + actStreamName); } /* LOG.info("Putting records in stream : " + myStreamName); // Write 10 records to the stream for (int j = 0; j < 10; j++) { PutRecordRequest putRecordRequest = new PutRecordRequest(); putRecordRequest.setStreamName(myStreamName); putRecordRequest.setData(ByteBuffer.wrap(String.format("testData-%d", j).getBytes())); putRecordRequest.setPartitionKey(String.format("partitionKey-%d", j)); PutRecordResult putRecordResult = kinesisClient.putRecord(putRecordRequest); System.out.println("Successfully putrecord, partition key : " + putRecordRequest.getPartitionKey() + ", ShardID : " + putRecordResult.getShardId()); } */ // Delete the stream. /* LOG.info("Deleting stream : " + myStreamName); DeleteStreamRequest deleteStreamRequest = new DeleteStreamRequest(); deleteStreamRequest.setStreamName(myStreamName); kinesisClient.deleteStream(deleteStreamRequest); // The stream is now being deleted. LOG.info("Stream is now being deleted : " + myStreamName); LOG.info("Streaming completed" + myStreamName); */ }
From source file:de.tudarmstadt.ukp.experiments.argumentation.clustering.entropy.MatrixExperiments.java
public static void main(String[] args) throws Exception { File in = new File(args[0]); List<String> lines = IOUtils.readLines(new FileInputStream(in)); int rows = lines.size(); int cols = lines.iterator().next().split("\\s+").length; double[][] matrix = new double[rows][cols]; Map<Integer, Double> clusterEntropy = new HashMap<>(); for (int i = 0; i < rows; i++) { String line = lines.get(i); String[] split = line.split("\\s+"); for (int j = 0; j < split.length; j++) { Double value = Double.valueOf(split[j]); matrix[i][j] = value;//from ww w. j a v a 2s . co m } // entropy of the cluster Vector v = new DenseVector(matrix[i]); // System.out.print(VectorUtils.entropy(v)); double entropy = VectorUtils.entropy(VectorUtils.normalize(v)); System.out.print(entropy); System.out.print(" "); clusterEntropy.put(i, entropy); } Map<Integer, Double> sorted = sortByValue(clusterEntropy); System.out.println(sorted); HeatChart map = new HeatChart(matrix); // Step 2: Customise the chart. map.setTitle("This is my heat chart title"); map.setXAxisLabel("X Axis"); map.setYAxisLabel("Y Axis"); // Step 3: Output the chart to a file. map.saveToFile(new File("/tmp/java-heat-chart.png")); }
From source file:com.joymove.service.impl.JOYUserServiceImpl.java
public static void main(String[] args) throws Exception { ApplicationContext context = new ClassPathXmlApplicationContext("classpath:test.xml"); Map<String, Object> likeCondition = new HashMap<String, Object>(); JOYUser user = new JOYUser(); DateFormat formatWithTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); user.registerTime = formatWithTime.parse("2013-04-29 15:08:41"); JOYUserDao dao = (JOYUserDao) context.getBean("JOYUserDao"); likeCondition.putAll(user.toMap());/*from w w w. j av a 2s. co m*/ likeCondition.put("filter", user); List<Map<String, Object>> mapList = dao.getPagedRecordList(likeCondition); for (int i = 0; i < mapList.size(); i++) { JOYUser userObj = new JOYUser(); user.fromMap(mapList.get(i)); System.out.println(user); } /* JOYPayHistoryService service = (JOYPayHistoryService)context.getBean("JOYPayHistoryService"); JOYPayHistory payHistoryNew = new JOYPayHistory(); payHistoryNew.balance = 0.2; payHistoryNew.type = 2; service.deleteByProperties(payHistoryNew); /* JOYUserService service = (JOYUserService)context.getBean("JOYUserService"); JOYUser user = new JOYUser(); user.mobileNo = "18500217642"; List<Map<String,Object>> mapList = service.getExtendInfoPagedList(" select u.*, m.driverLicenseNumber from JOY_Users u left join JOY_DriverLicense m on u.mobileNo = m.mobileNo ",user); // JOYUser user2 = new JOYUser(); Map<String,Object> t = mapList.get(0); Iterator i =t.entrySet().iterator(); JSONObject tt = new JSONObject(); while(i.hasNext()) { Map.Entry<String,Object> haha = (Map.Entry<String,Object>)i.next(); if(String.valueOf(haha.getValue()).equals("null")) { logger.trace(haha.getKey()+" is null"); } } /* user2.username = "?"; user.mobileNo="18500217642"; service.updateRecord(user2,user); user = service.getNeededRecord(user); logger.trace(user); /* JOYOrderService service = (JOYOrderService) context.getBean("JOYOrderService"); JOYOrder order = new JOYOrder(); order = service.getNeededRecord(order); JOYOrder order2 = new JOYOrder(); order2.startTime = order.startTime; order = new JOYOrder(); order.startTime = new Date(System.currentTimeMillis()); service.updateRecord(order,order2); /* JOYNReserveOrderService service = (JOYNReserveOrderService)context.getBean("JOYNReserveOrderService"); JOYReserveOrder order = new JOYReserveOrder(); //service.insertRecord(order); JOYReserveOrder order2 = new JOYReserveOrder(); order2.mobileNo = "18500217642"; order2.startTime = new Date(System.currentTimeMillis()); service.insertRecord(order2); order2.startTime = null; order = service.getNeededRecord(order2); order.startTime = new Date(System.currentTimeMillis()); service.updateRecord(order,order2); order2.startTime = order.startTime; order2.mobileNo = null; order = service.getNeededRecord(order2); logger.trace(order); /* order.delFlag = 1; order.startTime = new Date(System.currentTimeMillis()+30); service.updateRecord(order,order2); order2.mobileNo = null; order2.startTime = order.startTime; order = service.getNeededRecord(order2); logger.trace(order); //service.deleteByProperties(order); /* JOYIdAuthInfoService service = (JOYIdAuthInfoService)context.getBean("JOYIdAuthInfoService"); JOYIdAuthInfo dl = new JOYIdAuthInfo(); dl.idAuthInfo = "nihao".getBytes(); dl.idAuthInfo_back = "Hello world".getBytes(); JOYIdAuthInfo dl2 = new JOYIdAuthInfo(); dl2.mobileNo = "15577586649"; service.updateRecord(dl,dl2); service.getNeededList(dl2,null,null); List<JOYIdAuthInfo> dList = service.getNeededList(dl,null,null); logger.trace(dList.get(0)); for(int i=0;i<dList.get(0).idAuthInfo.length;i++) System.out.format("%c",dList.get(0).idAuthInfo[i]); /* JOYUser user = new JOYUser(); JOYUser user1 = new JOYUser(); user.mobileNo = ("18500217642"); List<JOYUser> userList = service.getNeededList(user,0,10); logger.trace("sdfdsdsf :"+userList.size()); JOYUser u = userList.get(0); logger.trace(u); */ }
From source file:org.openplans.delayfeeder.LoadFeeds.java
public static void main(String args[]) throws HibernateException, IOException { if (args.length != 1) { System.out.println("expected one argument: the path to a csv of agency,route,url"); }/* w w w . j a v a 2 s.c om*/ GenericApplicationContext context = new GenericApplicationContext(); XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(context); xmlReader.loadBeanDefinitions("org/openplans/delayfeeder/application-context.xml"); xmlReader.loadBeanDefinitions("data-sources.xml"); SessionFactory sessionFactory = (SessionFactory) context.getBean("sessionFactory"); Session session = sessionFactory.getCurrentSession(); Transaction tx = session.beginTransaction(); FileReader fileReader = new FileReader(new File(args[0])); BufferedReader bufferedReader = new BufferedReader(fileReader); while (bufferedReader.ready()) { String line = bufferedReader.readLine().trim(); if (line.startsWith("#")) { continue; } if (line.length() < 3) { //blank or otherwise broken line continue; } String[] parts = line.split(","); String agency = parts[0]; String route = parts[1]; String url = parts[2]; Query query = session.createQuery("from RouteFeed where agency = :agency and route = :route"); query.setParameter("agency", agency); query.setParameter("route", route); @SuppressWarnings("rawtypes") List list = query.list(); RouteFeed feed; if (list.size() == 0) { feed = new RouteFeed(); feed.agency = agency; feed.route = route; feed.lastEntry = new GregorianCalendar(); } else { feed = (RouteFeed) list.get(0); } if (!url.equals(feed.url)) { feed.url = url; feed.lastEntry.setTimeInMillis(0); } session.saveOrUpdate(feed); } tx.commit(); }
From source file:com.ds.test.ClientFormLogin.java
public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); try {/*from w ww. j av a 2s . c o m*/ HttpGet httpget = new HttpGet("http://www.iteye.com/login"); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println("Login form get: " + response.getStatusLine()); System.out.println("cookies:"); List<Cookie> cookies = httpclient.getCookieStore().getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println(cookies.get(i).toString()); } } /* HeaderIterator hi = response.headerIterator(); while(hi.hasNext()){ System.out.println(hi.next()); } EntityUtils.consume(entity); */ String token = parseHtml(EntityUtils.toString(entity)); httpget.releaseConnection(); System.out.println("********************************************************"); HttpPost httpost = new HttpPost("http://www.iteye.com/login"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("name", "")); nvps.add(new BasicNameValuePair("password", "")); nvps.add(new BasicNameValuePair("authenticity_token", token)); httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); response = httpclient.execute(httpost); entity = response.getEntity(); System.out.println("Login form get: " + response.getStatusLine()); EntityUtils.consume(entity); System.out.println("Post logon cookies:"); cookies = httpclient.getCookieStore().getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println(cookies.get(i).toString()); } } System.out.println("********************************************************"); HttpGet httpget2 = new HttpGet("http://www.iteye.com/login"); HttpResponse response2 = httpclient.execute(httpget2); HttpEntity entity2 = response2.getEntity(); System.out.println("Login form get: " + response2.getStatusLine()); print(response2); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } }