List of usage examples for java.util ArrayList iterator
public Iterator<E> iterator()
From source file:course.PrivateCloudController.java
private void initializeRoutes() throws IOException { // this is the blog home page get(new FreemarkerBasedRoute("/", "blog_template.ftl") { @Override/*from ww w.j a va 2 s.c o m*/ public void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request)); // this is where we would normally load up the blog data // but this week, we just display a placeholder. HashMap<String, String> root = new HashMap<String, String>(); template.process(root, writer); } }); get(new FreemarkerBasedRoute("/display_vms", "display_vms.ftl") { @Override public void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { //String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request)); List<Document> posts = new ArrayList<Document>();// = statsDAO.findByDateDescending(10); ManagedEntity[] mes = new InventoryNavigator(Path).searchManagedEntities("VirtualMachine"); SimpleHash root = new SimpleHash(); System.out.println("Display VM: VM list"); BasicDBObject query = new BasicDBObject(); VMsDBCollection.deleteMany(query); //HashMap<String, String> root = new HashMap<String, String>(); if (!(mes == null || mes.length == 0)) { for (int i = 0; i < mes.length; i++) { Document text = new Document(); VirtualMachine vm = (VirtualMachine) mes[i]; if (!vm.getName().contains("Template")) { String name = vm.getName(); text.append("name", name); Document DB_VMs = new Document("_id", name); if (vm.getConfig() != null) { String instanceId = vm.getConfig().getInstanceUuid(); text.append("instanceId", instanceId); } System.out.println("VM Name : " + name); String conectionState = vm.getRuntime().getConnectionState().toString(); text.append("conectionState", conectionState); DB_VMs.append("conectionState", conectionState); String ip = vm.getGuest().getIpAddress(); text.append("ip", ip); DB_VMs.append("ip", ip); String powerState = vm.getRuntime().getPowerState().toString(); text.append("powerState", powerState); if (vm.getTriggeredAlarmState() == null) { text.append("alarmState", "notTriggered"); DB_VMs.append("powerState", "notTriggered"); } else { text.append("alarmState", "Triggered"); DB_VMs.append("powerState", "Triggered"); } String launchTime = writeActualDate(vm.getRuntime().getBootTime()); text.append("launchTime", launchTime); DB_VMs.append("launchTime", launchTime); posts.add(text); VMsDBCollection.insertOne(DB_VMs); } } } root.put("VMs", posts); template.process(root, writer); } }); get(new FreemarkerBasedRoute("/create_vm", "create_vm.ftl") { @Override public void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { SimpleHash root = new SimpleHash(); System.out.println("Inside Create VM backend"); template.process(root, writer); } }); post(new FreemarkerBasedRoute("/create_vm", "/create_vm.ftl") { @Override public void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { if (request.queryParams("Create") != null) { ManagedEntity[] mes = new InventoryNavigator(Path).searchManagedEntities("VirtualMachine"); //Clone VM String vmname = request.queryParams("vmname"); String vm_template = request.queryParams("OS"); VirtualMachine vm = (VirtualMachine) new InventoryNavigator(Path) .searchManagedEntity("VirtualMachine", vm_template); VirtualMachineRuntimeInfo vmri = vm.getRuntime(); HostSystem hs = new HostSystem(vm.getServerConnection(), vmri.getHost()); Datacenter dc = (Datacenter) new InventoryNavigator(Path).searchManagedEntity("Datacenter", "T03-DC"); ResourcePool rp = (ResourcePool) new InventoryNavigator(dc) .searchManagedEntities("ResourcePool")[0]; if (vm == null) { System.out.println("No VM found with name " + vm_template); SimpleHash root = new SimpleHash(); root.put("login_error", "No template available"); template.process(root, writer); } else { try { VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec(); VirtualMachineRelocateSpec locateSpec = new VirtualMachineRelocateSpec(); locateSpec.setPool(rp.getMOR()); cloneSpec.setLocation(locateSpec); cloneSpec.setPowerOn(false); cloneSpec.setTemplate(false); Task task = vm.cloneVM_Task((Folder) vm.getParent(), vmname, cloneSpec); System.out.println("Launching the VM clone task. " + "Please wait ..."); /*String status = task.waitForTask(); if (status == Task.SUCCESS) { System.out.println("VM got cloned successfully."); } else { System.out.println("Failure -: VM cannot be cloned"); }*/ } catch (Exception e) { e.printStackTrace(); } response.redirect("/display_vms"); } } else if (request.queryParams("Cancel") != null) { response.redirect("/display_vms"); } } }); post(new FreemarkerBasedRoute("/display_vms", "display_vms.ftl") { @Override public void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { //String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request)); List<Document> posts = new ArrayList<Document>();// = statsDAO.findByDateDescending(10); SimpleHash root = new SimpleHash(); BasicDBObject query = new BasicDBObject(); ArrayList<String> VM_list = new ArrayList<String>(); MongoCursor<Document> cursor = VMsDBCollection.find(query).iterator(); while (cursor.hasNext()) { String a = cursor.next().toJson(); System.out.println(a); try { JSONObject jsonObject = new JSONObject(a); String vm_name = jsonObject.getString("_id"); VM_list.add(vm_name); } catch (JSONException e) { e.printStackTrace(); } } //take VM list from DB if (request.queryParams("PowerOn") != null) { Iterator vm_iterator = VM_list.iterator(); while (vm_iterator.hasNext()) { String VM_name = vm_iterator.next().toString(); boolean myCheckBox = request.queryParams(VM_name) != null; if (myCheckBox) { System.out.println("Power ON VM " + VM_name); powerOn(VM_name); } } response.redirect("/display_vms"); } else if (request.queryParams("PowerOff") != null) { Iterator vm_iterator = VM_list.iterator(); while (vm_iterator.hasNext()) { String VM_name = vm_iterator.next().toString(); boolean myCheckBox = request.queryParams(VM_name) != null; if (myCheckBox) { System.out.println("Power Off VM " + VM_name); powerOff(VM_name); } } response.redirect("/display_vms"); } else if (request.queryParams("Delete") != null) { Iterator vm_iterator = VM_list.iterator(); while (vm_iterator.hasNext()) { String VM_name = vm_iterator.next().toString(); boolean myCheckBox = request.queryParams(VM_name) != null; if (myCheckBox) { System.out.println("Delete VM " + VM_name); deleteVM(VM_name); } } response.redirect("/display_vms"); } else if (request.queryParams("Get_Chart") != null) { Iterator vm_iterator = VM_list.iterator(); while (vm_iterator.hasNext()) { String VM_name = vm_iterator.next().toString(); boolean myCheckBox = request.queryParams(VM_name) != null; if (myCheckBox) { System.out.println("Get VM " + VM_name + " Charts"); CurrentSelectedVM = VM_name; } } response.redirect("/gChart"); } else if (request.queryParams("Create") != null) { response.redirect("/create_vm"); } else { System.out.println("Invalid "); response.redirect("/display_vms"); // ??? } } }); // google chart handler get(new FreemarkerBasedRoute("/gChart", "GoogleLine.ftl") { @Override public void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request)); if (CurrentSelectedVM != null) { ArrayList<ArrayList> gchartMData = statsDAO.getMGchart(CurrentSelectedVM); ArrayList<ArrayList> gchartCData = statsDAO.getCGchart(CurrentSelectedVM); SimpleHash root = new SimpleHash(); root.put("VMName", CurrentSelectedVM); BasicDBObject query = new BasicDBObject(); query.put("_id", CurrentSelectedVM); MongoCursor<Document> cursor = VMsDBCollection.find(query).iterator(); while (cursor.hasNext()) { String a = cursor.next().toJson(); System.out.println("Json :::: \n" + a); try { JSONObject jsonObject = new JSONObject(a); if (jsonObject.has("ip") && jsonObject.has("_id")) { root.put("IPAD", jsonObject.getString("ip")); System.out.println("IP address for this VM is " + jsonObject.getString("ip")); } } catch (JSONException e) { e.printStackTrace(); } } if (CurrentSelectedVM.contains("Lin")) root.put("vm_type", "Lin"); else if (CurrentSelectedVM.contains("Win")) root.put("vm_type", "Win"); CurrentSelectedVM = null; root.put("usernameVM", "administrator"); root.put("passwordVM", "12!@qwQW"); root.put("gcdata1", gchartMData); root.put("gcdata2", gchartCData); //System.out.println(gchartData); // System.out.println(gchartData.get(0)); template.process(root, writer); } } }); post(new FreemarkerBasedRoute("/gChart", "GoogleLine.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { if (request.queryParams("Home") != null) { response.redirect("/display_vms"); } } }); // handle the signup post post(new FreemarkerBasedRoute("/signup", "signup.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String email = request.queryParams("email"); String username = request.queryParams("username"); String password = request.queryParams("password"); String verify = request.queryParams("verify"); HashMap<String, String> root = new HashMap<String, String>(); root.put("username", StringEscapeUtils.escapeHtml4(username)); root.put("email", StringEscapeUtils.escapeHtml4(email)); if (validateSignup(username, password, verify, email, root)) { // good user System.out.println("Signup: Creating user with: " + username + " " + password); if (!userDAO.addUser(username, password, email)) { // duplicate user root.put("username_error", "Username already in use, Please choose another"); template.process(root, writer); } else { // good user, let's start a session String sessionID = sessionDAO.startSession(username); System.out.println("Session ID is" + sessionID); response.raw().addCookie(new Cookie("session", sessionID)); response.redirect("/login"); } } else { // bad signup System.out.println("User Registration did not validate"); template.process(root, writer); } } }); // present signup form for blog get(new FreemarkerBasedRoute("/signup", "signup.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { SimpleHash root = new SimpleHash(); // initialize values for the form. root.put("username", ""); root.put("password", ""); root.put("email", ""); root.put("password_error", ""); root.put("username_error", ""); root.put("email_error", ""); root.put("verify_error", ""); template.process(root, writer); } }); get(new FreemarkerBasedRoute("/welcome", "welcome.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String cookie = getSessionCookie(request); String username = sessionDAO.findUserNameBySessionId(cookie); if (username == null) { System.out.println("welcome() can't identify the user, redirecting to signup"); response.redirect("/signup"); } else { SimpleHash root = new SimpleHash(); root.put("username", username); template.process(root, writer); } } }); // present the login page get(new FreemarkerBasedRoute("/login", "login.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { SimpleHash root = new SimpleHash(); root.put("username", ""); root.put("login_error", ""); template.process(root, writer); } }); // process output coming from login form. On success redirect folks to the welcome page // on failure, just return an error and let them try again. post(new FreemarkerBasedRoute("/login", "login.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String username = request.queryParams("username"); String password = request.queryParams("password"); System.out.println("Login: User submitted: " + username + " " + password); Document user = userDAO.validateLogin(username, password); if (user != null) { // valid user, let's log them in String sessionID = sessionDAO.startSession(user.get("_id").toString()); if (sessionID == null) { response.redirect("/internal_error"); } else { // set the cookie for the user's browser response.raw().addCookie(new Cookie("session", sessionID)); response.redirect("/display_vms"); } } else { SimpleHash root = new SimpleHash(); root.put("username", StringEscapeUtils.escapeHtml4(username)); root.put("password", ""); root.put("login_error", "Invalid Login"); template.process(root, writer); } } }); // allows the user to logout of the blog get(new FreemarkerBasedRoute("/logout", "signup.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String sessionID = getSessionCookie(request); if (sessionID == null) { // no session to end response.redirect("/login"); } else { // deletes from session table sessionDAO.endSession(sessionID); // this should delete the cookie Cookie c = getSessionCookieActual(request); c.setMaxAge(0); response.raw().addCookie(c); response.redirect("/login"); } } }); // used to process internal errors get(new FreemarkerBasedRoute("/internal_error", "error_template.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { SimpleHash root = new SimpleHash(); root.put("error", "System has encountered an error."); template.process(root, writer); } }); }
From source file:com.krawler.spring.hrms.rec.job.hrmsRecJobDAOImpl.java
public KwlReturnObject transferExternalAppDocs(ArrayList<HrmsDocmap> hrmsDocmaps, User relatedTo) { boolean success = true; ArrayList<Docs> arrayListDocs = new ArrayList<Docs>(); Iterator<HrmsDocmap> itr = hrmsDocmaps.iterator(); try {// ww w. j a v a 2s.co m while (itr.hasNext()) { Docs docs = new Docs(); HrmsDocs hrmsDocs = itr.next().getDocid(); docs.setDocname(hrmsDocs.getDocname()); docs.setDocsize(hrmsDocs.getDocsize()); docs.setDoctype(hrmsDocs.getDoctype()); docs.setDocdesc(hrmsDocs.getDocdesc()); docs.setUploadedon(hrmsDocs.getUploadedon()); docs.setStorename(hrmsDocs.getStorename()); docs.setStorageindex(hrmsDocs.getStorageindex()); docs.setUserid(relatedTo); docs.setCompany(relatedTo.getCompany()); docs.setDeleteflag(0); arrayListDocs.add(docs); } hibernateTemplate.saveOrUpdateAll(arrayListDocs); } catch (Exception e) { success = false; e.printStackTrace(); } finally { return new KwlReturnObject(success, "", "", arrayListDocs, arrayListDocs.size()); } }
From source file:com.planetmayo.debrief.satc_rcp.views.MaintainContributionsView.java
protected void startSlicingOwnshipLegs(String contName) { // hey, let's also ditch any straight leg forecasts Iterator<BaseContribution> conts = activeSolver.getContributions().iterator(); ArrayList<BaseContribution> toRemove = new ArrayList<BaseContribution>(); while (conts.hasNext()) { BaseContribution baseC = conts.next(); if (baseC.isActive()) if (baseC instanceof StraightLegForecastContribution) { toRemove.add(baseC);//from ww w . ja va 2 s . c o m } } // did we find any? if (!toRemove.isEmpty()) { Iterator<BaseContribution> iter = toRemove.iterator(); while (iter.hasNext()) { BaseContribution baseContribution = iter.next(); activeSolver.getContributions().removeContribution(baseContribution); } } // ok, clear any leg markers if (legPlot != null) { graphTabs.setSelection(legTab); legPlot.clearDomainMarkers(); } }
From source file:com.krawler.spring.hrms.rec.job.hrmsRecJobDAOImpl.java
public KwlReturnObject transferExternalAppDocMaps(ArrayList<HrmsDocmap> hrmsDocmaps, ArrayList<Docs> docs, User relatedTo) {/*from w ww . ja v a 2 s . c o m*/ boolean success = true; ArrayList<Docmap> arrayListDocmap = new ArrayList<Docmap>(); Iterator<HrmsDocmap> itr1 = hrmsDocmaps.iterator(); Iterator<Docs> itr2 = docs.iterator(); try { while (itr1.hasNext()) { Docmap docmaps = new Docmap(); HrmsDocmap hrmsDocmap = itr1.next(); docmaps.setDocid(itr2.next()); docmaps.setRecid(relatedTo.getUserID()); arrayListDocmap.add(docmaps); } hibernateTemplate.saveOrUpdateAll(arrayListDocmap); } catch (Exception e) { success = false; e.printStackTrace(); } finally { return new KwlReturnObject(success, "", "", arrayListDocmap, arrayListDocmap.size()); } }
From source file:com.datatorrent.stram.engine.StreamingContainer.java
private synchronized void undeploy(List<Integer> nodeList) { /**//from w ww . j a va 2s . c om * make sure that all the operators which we are asked to undeploy are in this container. */ HashMap<Integer, Node<?>> toUndeploy = new HashMap<Integer, Node<?>>(); for (Integer operatorId : nodeList) { Node<?> node = nodes.get(operatorId); if (node == null) { throw new IllegalArgumentException("Node " + operatorId + " is not hosted in this container!"); } else if (toUndeploy.containsKey(operatorId)) { throw new IllegalArgumentException( "Node " + operatorId + " is requested to be undeployed more than once"); } else { toUndeploy.put(operatorId, node); } } ArrayList<Thread> joinList = new ArrayList<Thread>(); ArrayList<Integer> discoList = new ArrayList<Integer>(); for (Integer operatorId : nodeList) { Thread t = nodes.get(operatorId).context.getThread(); if (t == null || !t.isAlive()) { disconnectNode(operatorId); } else { joinList.add(t); discoList.add(operatorId); nodes.get(operatorId).shutdown(); } } try { Iterator<Integer> iterator = discoList.iterator(); for (Thread t : joinList) { t.join(1000); if (!t.getState().equals(State.TERMINATED)) { t.interrupt(); } disconnectNode(iterator.next()); } logger.info("Undeploy complete."); } catch (InterruptedException ex) { logger.warn("Aborting wait for operators to get deactivated!", ex); } for (Integer operatorId : nodeList) { nodes.remove(operatorId); } }
From source file:com.datatorrent.stram.engine.StreamingContainer.java
public synchronized void deactivate() { ArrayList<Thread> activeThreads = new ArrayList<Thread>(); ArrayList<Integer> activeOperators = new ArrayList<Integer>(); for (Map.Entry<Integer, Node<?>> e : nodes.entrySet()) { Thread t = e.getValue().context.getThread(); if (t == null || !t.isAlive()) { disconnectNode(e.getKey());/*from w ww .j a v a 2s . c om*/ } else { activeThreads.add(t); activeOperators.add(e.getKey()); e.getValue().shutdown(); } } try { Iterator<Integer> iterator = activeOperators.iterator(); for (Thread t : activeThreads) { t.join(1000); if (!t.getState().equals(State.TERMINATED)) { t.interrupt(); } disconnectNode(iterator.next()); } } catch (InterruptedException ex) { logger.warn("Aborting wait for operators to get deactivated!", ex); } for (WindowGenerator wg : activeGenerators.keySet()) { wg.deactivate(); } activeGenerators.clear(); for (Stream stream : activeStreams.keySet()) { stream.deactivate(); } activeStreams.clear(); }
From source file:com.juick.android.MessagesFragment.java
private ArrayList<JuickMessage> filterMessages(ArrayList<JuickMessage> messages) { log("filterMessages start"); SharedPreferences sp = PreferenceManager .getDefaultSharedPreferences(JuickAdvancedApplication.instance.getApplicationContext()); boolean filterNonRussian = sp.getBoolean("filterNonRussian", false); Set<String> filteredOutUsers1 = JuickMessagesAdapter.getFilteredOutUsers(parent); log("filterMessages got filtered out users"); for (Iterator<JuickMessage> iterator = messages.iterator(); iterator.hasNext();) { JuickMessage message = iterator.next(); if (filteredOutUsers1.contains(message.User.UName)) { iterator.remove();//w w w . ja va 2s .com continue; } if (message.getRID() == 0) { // don't check comments if (XMPPService.getAnyJuboMessageFilter() != null) { if (!XMPPService.getAnyJuboMessageFilter().allowMessage(message)) { iterator.remove(); continue; } } if (XMPPService.getAnyJuickBlacklist() != null) { if (!XMPPService.getAnyJuickBlacklist().allowMessage(message)) { iterator.remove(); continue; } } } if (filterNonRussian) { String text = message.Text; int nRussian = 0; while (true) { boolean replaced = false; Matcher matcher = httpURL.matcher(text); if (matcher.find()) { try { text = matcher.replaceAll(""); replaced = true; } catch (Exception e) { // } } if (!replaced) break; } final int limit = text.length(); for (int i = 0; i < limit; i++) { int charCode = (int) text.charAt(i); if (russians.get(charCode)) { nRussian++; break; } } if (!text.contains("No description")) { if (nRussian == 0 && limit > 30) { iterator.remove(); continue; } } } } log("filterMessages end"); return messages; }
From source file:de.csw.expertfinder.mediawiki.api.MediaWikiAPI.java
private MediaWikiArticleIterator getAllVersionsOfArticleInternal(final int articleId, int startRevId, boolean fetchContent) { final ArrayList<Integer> revIds = new ArrayList<Integer>(); Iterator<Element> revisions = getInfoForAllRevisions(articleId, startRevId, fetchContent); Element currentRevision = null; if (revisions.hasNext()) { currentRevision = revisions.next(); }//from ww w . jav a 2s . c om Element nextRevision = null; while (revisions.hasNext()) { nextRevision = revisions.next(); // look ahead if we have a sequence of edits by the same author // we only need to pick the last edit of this sequence. String nextAuthor = nextRevision.getAttribute("user"); String currentAuthor = currentRevision.getAttribute("user"); if (currentAuthor.equals(nextAuthor)) { // continue; } String revId = currentRevision.getAttribute("revid"); revIds.add(Integer.parseInt(revId)); currentRevision = nextRevision; } if (nextRevision != null) { String revId = nextRevision.getAttribute("revid"); revIds.add(Integer.parseInt(revId)); } final Iterator<Integer> revIdIterator = revIds.iterator(); final int revisionCount = revIds.size(); return new MediaWikiArticleIterator(revIdIterator, articleId, this, revisionCount, fetchContent); }
From source file:com.janrain.backplane2.server.Backplane2ControllerTest.java
@Test public void testMessageOrder() throws Exception { // Create source token for the channel String testBus = "testbus"; TokensAndChannel tokensAndChannel = anonTokenRequest(testBus); // Create appropriate token saveGrant(new Grant.Builder(GrantType.CLIENT_CREDENTIALS, GrantState.ACTIVE, "fakeOwnerId", testClient.getClientId(),/* w w w . ja va2s. c om*/ Scope.getEncodedScopesAsString(BackplaneMessage.Field.BUS, "testbus otherbus")).buildGrant()); String token2 = privTokenRequest( Scope.getEncodedScopesAsString(BackplaneMessage.Field.CHANNEL, tokensAndChannel.channel)); ObjectMapper mapper = new ObjectMapper(); Map<String, Object> msg = mapper.readValue(TEST_MSG_1, new TypeReference<Map<String, Object>>() { }); msg.put(BackplaneMessage.Field.BUS.getFieldName(), testBus); msg.put(BackplaneMessage.Field.CHANNEL.getFieldName(), tokensAndChannel.channel); // seed messages long numMessages = bpConfig.getDefaultMaxMessageLimit(); ArrayList<BackplaneMessage> messages = new ArrayList<BackplaneMessage>(); for (int i = 0; i <= numMessages; i++) { messages.add(new BackplaneMessage(testClient.getSourceUrl(), DEFAULT_MESSAGE_RETENTION_SECONDS, MAX_MESSAGE_RETENTION_SECONDS, msg)); } // use #0 to set the 'since' from server time, don't count #0 String since = messages.iterator().next().get(BackplaneMessage.Field.ID); // reverse the list //Collections.reverse(messages); for (BackplaneMessage message : messages) { this.saveMessage(message); } // we assume the message processor is running in another thread... Thread.sleep(3000); // Make the call List<Map<String, Object>> allMsgs = new ArrayList<Map<String, Object>>(); boolean moreMessages = false; do { refreshRequestAndResponse(); request.setRequestURI("/v2/messages"); request.setMethod("GET"); request.setParameter("scope", "channel:" + tokensAndChannel.channel); if (org.apache.commons.lang.StringUtils.isNotBlank(since)) { request.setParameter("since", since); } setOauthBearerTokenAuthorization(request, token2); handlerAdapter.handle(request, response, controller); logger.info("testMessageOrder() => " + response.getContentAsString()); Map<String, Object> returnedBody = mapper.readValue(response.getContentAsString(), new TypeReference<Map<String, Object>>() { }); List<Map<String, Object>> returnedMsgs = (List<Map<String, Object>>) returnedBody.get("messages"); allMsgs.addAll(returnedMsgs); moreMessages = (Boolean) returnedBody.get("moreMessages"); //"messageURL": "https://bp.example.com/v2/message/097a5cc401001f95b45d37aca32a3bd2", String nextURL = returnedBody.get("nextURL").toString(); since = nextURL.substring(nextURL.indexOf("since=") + 6); //Thread.sleep(1000); } while (moreMessages); assertTrue("Expected " + numMessages + " messages, received " + allMsgs.size(), allMsgs.size() == numMessages); // they should be returned in lexicographic order by ID String prev = ""; for (Map<String, Object> m : allMsgs) { assertTrue(m.get("messageURL").toString() + " <= " + prev, m.get("messageURL").toString().compareTo(prev) > 0); prev = (String) m.get("messageURL"); } TokenDAO tokenDAO = daoFactory.getTokenDao(); tokenDAO.delete(tokensAndChannel.bearerToken); tokenDAO.delete(tokensAndChannel.refreshToken); }
From source file:gr.iit.demokritos.cru.cps.api.SubmitExhibitPreferenceList.java
public JSONObject processRequest() throws IOException, ClassNotFoundException, IllegalAccessException, Exception { String response_code = "e0"; String[] exhibit_list_temp = exhibit_list_id.split(";"); ArrayList<String> exhibit_list = new ArrayList<String>(); for (int i = 0; i < exhibit_list_temp.length; i++) { exhibit_list.add(exhibit_list_temp[i]); }//from w w w.jav a 2s . c o m String location = (String) properties.get("location"); String database_name = (String) properties.get("database_name"); String username = (String) properties.get("username"); String password = (String) properties.get("password"); String database_dir = (String) properties.get("wordnet.database.dir"); String thesaurus_de = (String) properties.get("openthesaurus_DE"); String thesaurus_el = (String) properties.get("openthesaurus_EL"); String stopWordsEN = (String) properties.get("stopWordsFile_EN"); String stopWordsGR = (String) properties.get("stopWordsFile_GR"); String stopWordsDE = (String) properties.get("stopWordsFile_DE"); String offensiveWords = (String) properties.get("offensiveWordsFile"); MySQLConnector mysql = new MySQLConnector(location, database_name, username, password); try { Connection connection = mysql.connectToCPSDatabase(); Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT window FROM windows WHERE current_window=1"); int window = -1; while (rs.next()) { window = rs.getInt(1); } rs.close(); CreativityExhibitModelController cemc = new CreativityExhibitModelController( Long.parseLong(application_key), Long.parseLong(user_id), exhibit_list, window); boolean isvalid = cemc.validateClientApplication(mysql); UserManager um = new UserManager(Long.parseLong(application_key), Long.parseLong(user_id)); if (isvalid == true) { isvalid = cemc.validateUser(mysql); System.out.println(""); if (isvalid == true) { Iterator it = exhibit_list.iterator(); while (it.hasNext()) { um.setExhibit_id(Long.parseLong((String) it.next())); isvalid = um.validateExhibit(mysql); if (isvalid == false) { break; } } if (isvalid == true) { cemc.storeExhbitPreferenceList(mysql); preference_list_id = Long.toString(cemc.getPreference_id()); response_code = "OK"; } else { response_code = "e105"; } } else { response_code = "e102"; } } else { response_code = "e101"; } } catch (NumberFormatException ex) { response_code = "e101"; Logger.getLogger(CreateUser.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(SubmitExhibitPreferenceList.class.getName()).log(Level.SEVERE, null, ex); } JSONObject obj = new JSONObject(); obj.put("application_key", application_key); obj.put("user_id", user_id); obj.put("preference_list_id", preference_list_id); obj.put("response_code", response_code); return obj; }