List of usage examples for java.util List toString
public String toString()
From source file:dev.meng.wikidata.pageview.Consolidator.java
public void consolidate() { try {/*www. jav a 2s .c o m*/ List<String> langs = DB.PAGECOUNT.PAGE.retrieveAllLangs(); for (String lang : langs) { Logger.log(this.getClass(), LogLevel.INFO, "Consolidating " + lang); List<Map<Page, Object>> newPageRecords = new LinkedList<>(); Map<String, List<Integer>> newToOldPageIdMap = new HashMap<>(); List<String> titles = new LinkedList<>(); Map<String, Integer> oldTitleToOldIdMap = new HashMap<>(); List<Map<dev.meng.wikidata.pagecount.db.Page, Object>> oldPageRecords = DB.PAGECOUNT.PAGE .retrieveUnconsolidatedRecordsByLang(lang); for (Map<dev.meng.wikidata.pagecount.db.Page, Object> record : oldPageRecords) { titles.add((String) record.get(dev.meng.wikidata.pagecount.db.Page.TITLE)); oldTitleToOldIdMap.put((String) record.get(dev.meng.wikidata.pagecount.db.Page.TITLE), (int) record.get(dev.meng.wikidata.pagecount.db.Page.ID)); } Map<String, List<String>> titleMap = new HashMap<>(); for (String title : titles) { String urlDecoded = title; if (title.contains("%")) { urlDecoded = CodecUtils.asciiToUnicode(title, AsciiToUnicodeFormat.PERCENTAGE_HEX); } String decoded = urlDecoded; if (urlDecoded.contains("\\x")) { decoded = CodecUtils.asciiToUnicode(urlDecoded, AsciiToUnicodeFormat.SLASH_X_HEX); } List<String> encodedTitleList = titleMap.get(decoded); if (encodedTitleList == null) { encodedTitleList = new LinkedList<>(); } encodedTitleList.add(title); titleMap.put(decoded, encodedTitleList); } List<String> decodedTitles = new LinkedList<>(titleMap.keySet()); Map<String, String>[] queryResult = queryPageIds(lang, decodedTitles); Map<String, String> norms = queryResult[0]; Map<String, String> pageIds = queryResult[1]; for (String title : decodedTitles) { String normalizedTitle = norms.get(title); String newPageId = pageIds.get(normalizedTitle); if (newPageId != null) { List<Integer> oldPageIdList = new LinkedList<>(); for (String oldTitle : titleMap.get(title)) { oldPageIdList.add(oldTitleToOldIdMap.get(oldTitle)); } List<Integer> oldPageIds = newToOldPageIdMap.get(newPageId); if (oldPageIds == null) { oldPageIds = new LinkedList<>(); Map<Page, Object> pageRecord = new HashMap<>(); pageRecord.put(Page.PAGE_ID, newPageId); pageRecord.put(Page.TITLE, normalizedTitle); pageRecord.put(Page.LANG, lang); newPageRecords.add(pageRecord); } else { Logger.log(this.getClass(), LogLevel.WARNING, "Mapping of same page ids: existing: " + oldPageIds.toString() + " and " + oldPageIdList.toString() + ", new: " + newPageId); } oldPageIds.addAll(oldPageIdList); newToOldPageIdMap.put(newPageId, oldPageIds); } } DB.PAGEVIEW.PAGE.insertOrIgnoreBatch(newPageRecords); Map<String, Integer> newPageIdToIdMap = DB.PAGEVIEW.PAGE.retrievePageIdToIdMapByUnique(lang, newPageRecords); List<Map<View, Object>> newViewRecords = new LinkedList<>(); for (String newPageId : newPageIdToIdMap.keySet()) { int newId = newPageIdToIdMap.get(newPageId); Map<Long, Map<View, Object>> newViewRecordsById = new HashMap<>(); for (int oldId : newToOldPageIdMap.get(newPageId)) { List<Map<dev.meng.wikidata.pagecount.db.View, Object>> oldViewRecords = DB.PAGECOUNT.VIEW .retrieveByPageId(oldId); for (Map<dev.meng.wikidata.pagecount.db.View, Object> oldViewRecord : oldViewRecords) { long timestamp = (long) oldViewRecord .get(dev.meng.wikidata.pagecount.db.View.TIMESTAMP); Map<View, Object> newViewRecordById = newViewRecordsById.get(timestamp); if (newViewRecordById == null) { newViewRecordById = new HashMap<>(); newViewRecordById.put(View.PAGE_ID, newId); newViewRecordById.put(View.TIMESTAMP, timestamp); newViewRecordById.put(View.FREQUENCY, 0L); newViewRecordById.put(View.SIZE, 0L); } long newFrequency = (long) newViewRecordById.get(View.FREQUENCY) + ((Number) oldViewRecord.get(dev.meng.wikidata.pagecount.db.View.FREQUENCY)) .longValue(); long newSize = (long) newViewRecordById.get(View.SIZE) + ((Number) oldViewRecord.get(dev.meng.wikidata.pagecount.db.View.SIZE)) .longValue(); newViewRecordById.put(View.FREQUENCY, newFrequency); newViewRecordById.put(View.SIZE, newSize); newViewRecordsById.put(timestamp, newViewRecordById); } } newViewRecords.addAll(newViewRecordsById.values()); } DB.PAGEVIEW.VIEW.insertOrIgnoreBatch(newViewRecords); for (Map<dev.meng.wikidata.pagecount.db.Page, Object> record : oldPageRecords) { record.put(dev.meng.wikidata.pagecount.db.Page.CONSOLIDATED, true); } DB.PAGECOUNT.PAGE.insertOrReplaceBatch(oldPageRecords); } } catch (SQLException ex) { Logger.log(this.getClass(), LogLevel.ERROR, ex); } catch (StringConvertionException ex) { Logger.log(this.getClass(), LogLevel.ERROR, ex); } }
From source file:nosqltools.JSONUtilities.java
public String printDiff(JsonNode resCompNode) { String opType = ""; String path = ""; String value = ""; Iterator<JsonNode> elements = null; ArrayNode opNodes = (ArrayNode) resCompNode; List<String> res = new ArrayList<String>(); elements = opNodes.elements();/*www .ja va 2 s . c om*/ while (elements.hasNext()) { JsonNode opNode = elements.next(); //stores the type of operation performed opType = opNode.get("op").textValue(); //stores the path of the nodes visited path = opNode.get("path").textValue().substring(1); if (!opType.equals("remove")) { //the value is not shown the the operation is removed because of null pointer exception //stores the value of the operation value = ": " + opNode.get("value").toString(); } else { value = " "; } res.add(opType + " operation -> " + path + value); } return res.toString(); }
From source file:cn.kangeqiu.kq.activity.LoginActivity.java
private void processContactsAndGroups() throws EaseMobException { // demo??????username?? List<String> usernames = EMContactManager.getInstance().getContactUserNames(); System.out.println("----------------" + usernames.toString()); EMLog.d("roster", "contacts size: " + usernames.size()); Map<String, User> userlist = new HashMap<String, User>(); for (String username : usernames) { User user = new User(); user.setUsername(username);/*from w ww. j av a2 s.c om*/ setUserHearder(username, user); userlist.put(username, user); } // user"" User newFriends = new User(); newFriends.setUsername(Constant.NEW_FRIENDS_USERNAME); String strChat = getResources().getString(R.string.Application_and_notify); newFriends.setNick(strChat); userlist.put(Constant.NEW_FRIENDS_USERNAME, newFriends); // "?" User groupUser = new User(); String strGroup = getResources().getString(R.string.group_chat); groupUser.setUsername(Constant.GROUP_USERNAME); groupUser.setNick(strGroup); groupUser.setHeader(""); userlist.put(Constant.GROUP_USERNAME, groupUser); // BaseApplication.getInstance().setContactList(userlist); // db UserDao dao = new UserDao(LoginActivity.this); List<User> users = new ArrayList<User>(userlist.values()); dao.saveContactList(users); // ???? List<String> blackList = EMContactManager.getInstance().getBlackListUsernamesFromServer(); // ???? EMContactManager.getInstance().saveBlackList(blackList); // ??(??groupidgroupname????members),sdkdb EMGroupManager.getInstance().getGroupsFromServer(); }
From source file:ch.epfl.eagle.daemon.scheduler.Scheduler.java
public List<TTaskLaunchSpec> getTask(String requestId, THostPort nodeMonitorAddress, THostPort oldNodeMonitorAddress) { /*/*from www . j av a 2 s .c o m*/ * TODO: Consider making this synchronized to avoid the need for * synchronization in the task placers (although then we'd lose the * ability to parallelize over task placers). */ LOG.debug(Logging.functionCall(requestId, nodeMonitorAddress)); TaskPlacer taskPlacer = requestTaskPlacers.get(requestId); if (taskPlacer == null) { LOG.debug("Received getTask() request for request " + requestId + ", which had no more " + "unplaced tasks"); return Lists.newArrayList(); } synchronized (taskPlacer) { List<TTaskLaunchSpec> taskLaunchSpecs = taskPlacer.assignTask(nodeMonitorAddress, oldNodeMonitorAddress); if (taskLaunchSpecs == null || taskLaunchSpecs.size() > 1) { LOG.error("Received invalid task placement for request " + requestId + ": " + taskLaunchSpecs.toString()); return Lists.newArrayList(); } else if (taskLaunchSpecs.size() == 1) { AUDIT_LOG.info(Logging.auditEventString("scheduler_assigned_task", requestId, taskLaunchSpecs.get(0).taskId, nodeMonitorAddress.getHost())); } else { AUDIT_LOG.info(Logging.auditEventString("scheduler_get_task_no_task", requestId, nodeMonitorAddress.getHost())); } if (taskPlacer.allTasksPlaced()) { LOG.debug("All tasks placed for request " + requestId); requestTaskPlacers.remove(requestId); if (useCancellation) { Set<THostPort> outstandingNodeMonitors = taskPlacer.getOutstandingNodeMonitorsForCancellation(); for (THostPort nodeMonitorToCancel : outstandingNodeMonitors) { cancellationService.addCancellation(requestId, nodeMonitorToCancel); } } } return taskLaunchSpecs; } }
From source file:de.ncoder.studipsync.studip.jsoup.JsoupStudipAdapter.java
@Override public List<Seminar> parseSeminars() throws StudipException { ensureLoggedIn();/*from w w w.jav a 2 s . c o m*/ navigate(PAGE_SEMINARS); Elements events = document.select("#content>table:first-of-type>tbody>tr"); List<Seminar> seminars = new ArrayList<>(); for (org.jsoup.nodes.Element event : events) { if (event.select(">td").size() > 4) { Elements info = event.select(">td:nth-of-type(4)>a:first-of-type"); Elements font = info.select("font"); if (info.size() >= 1 && font.size() >= 2) { Seminar seminar = Seminar.getSeminar(info.get(0).absUrl("href"), font.get(0).text().trim(), font.get(1).text().trim()); seminars.add(seminar); } } } log.debug("Parsed " + seminars.size() + " seminars."); log.trace(seminars.toString()); return seminars; }
From source file:com.odoo.orm.OSyncHelper.java
/** * Delete record in local.// www .j a v a2s.c om * * @param model * the model */ private void deleteRecordInLocal(OModel model) { try { List<Integer> ids = model.ids(); ODomain domain = new ODomain(); domain.add("id", "in", new JSONArray(ids.toString())); JSONObject result = mOdoo.search_read(model.getModelName(), new JSONObject(), domain.get()); JSONArray records = result.getJSONArray("records"); if (records.length() > 0) { for (int i = 0; i < records.length(); i++) { Integer server_id = records.getJSONObject(i).getInt("id"); ids.remove(ids.indexOf(server_id)); } } model.checkInActiveRecord(true); for (Integer id : ids) model.delete("id = ? ", new Object[] { id }); model.checkInActiveRecord(false); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.restcomm.connect.http.GeolocationEndpoint.java
public Response putGeolocation(final String accountSid, final MultivaluedMap<String, String> data, GeolocationType geolocationType, final MediaType responseType) { Account account;//ww w . ja va2 s .c o m try { account = accountsDao.getAccount(accountSid); secure(account, "RestComm:Create:Geolocation", SecuredType.SECURED_APP); } catch (final Exception exception) { return status(UNAUTHORIZED).build(); } try { validate(data, geolocationType); } catch (final NullPointerException nullPointerException) { // API compliance check regarding missing mandatory parameters return status(BAD_REQUEST).entity(nullPointerException.getMessage()).build(); } catch (final IllegalArgumentException illegalArgumentException) { // API compliance check regarding malformed parameters cause = illegalArgumentException.getMessage(); rStatus = responseStatus.Failed.toString(); } catch (final UnsupportedOperationException unsupportedOperationException) { // API compliance check regarding parameters not allowed for Immediate type of Geolocation return status(BAD_REQUEST).entity(unsupportedOperationException.getMessage()).build(); } /*********************************************/ /*** Query GMLC for Location Data, stage 1 ***/ /*********************************************/ try { String targetMSISDN = data.getFirst("DeviceIdentifier"); Configuration gmlcConf = configuration.subset("gmlc"); String gmlcURI = gmlcConf.getString("gmlc-uri"); // Authorization for further stage of the project String gmlcUser = gmlcConf.getString("gmlc-user"); String gmlcPassword = gmlcConf.getString("gmlc-password"); // Credentials credentials = new UsernamePasswordCredentials(gmlcUser, gmlcPassword); URL url = new URL(gmlcURI + targetMSISDN); HttpClient client = HttpClientBuilder.create().build(); HttpGet request = new HttpGet(String.valueOf(url)); // Authorization for further stage of the project request.addHeader("User-Agent", gmlcUser); request.addHeader("User-Password", gmlcPassword); HttpResponse response = client.execute(request); final HttpEntity entity = response.getEntity(); if (entity != null) { InputStream stream = entity.getContent(); try { BufferedReader br = new BufferedReader(new InputStreamReader(stream)); String gmlcResponse = null; while (null != (gmlcResponse = br.readLine())) { List<String> items = Arrays.asList(gmlcResponse.split("\\s*,\\s*")); if (logger.isInfoEnabled()) { logger.info("Data retrieved from GMLC: " + items.toString()); } for (String item : items) { for (int i = 0; i < items.size(); i++) { if (item.contains("mcc")) { String token = item.substring(item.lastIndexOf("=") + 1); data.putSingle("MobileCountryCode", token); } if (item.contains("mnc")) { String token = item.substring(item.lastIndexOf("=") + 1); data.putSingle("MobileNetworkCode", token); } if (item.contains("lac")) { String token = item.substring(item.lastIndexOf("=") + 1); data.putSingle("LocationAreaCode", token); } if (item.contains("cellid")) { String token = item.substring(item.lastIndexOf("=") + 1); data.putSingle("CellId", token); } if (item.contains("aol")) { String token = item.substring(item.lastIndexOf("=") + 1); data.putSingle("LocationAge", token); } if (item.contains("vlrNumber")) { String token = item.substring(item.lastIndexOf("=") + 1); data.putSingle("NetworkEntityAddress", token); } if (item.contains("latitude")) { String token = item.substring(item.lastIndexOf("=") + 1); data.putSingle("DeviceLatitude", token); } if (item.contains("longitude")) { String token = item.substring(item.lastIndexOf("=") + 1); data.putSingle("DeviceLongitude", token); } if (item.contains("civicAddress")) { String token = item.substring(item.lastIndexOf("=") + 1); data.putSingle("FormattedAddress", token); } } } if (gmlcURI != null && gmlcResponse != null) { // For debugging/logging purposes only if (logger.isDebugEnabled()) { logger.debug("Geolocation data of " + targetMSISDN + " retrieved from GMCL at: " + gmlcURI); logger.debug( "MCC (Mobile Country Code) = " + getInteger("MobileCountryCode", data)); logger.debug("MNC (Mobile Network Code) = " + data.getFirst("MobileNetworkCode")); logger.debug("LAC (Location Area Code) = " + data.getFirst("LocationAreaCode")); logger.debug("CI (Cell ID) = " + data.getFirst("CellId")); logger.debug("AOL (Age of Location) = " + getInteger("LocationAge", data)); logger.debug("NNN (Network Node Number/Address) = " + +getLong("NetworkEntityAddress", data)); logger.debug("Devide Latitude = " + data.getFirst("DeviceLatitude")); logger.debug("Devide Longitude = " + data.getFirst("DeviceLongitude")); logger.debug("Civic Address = " + data.getFirst("FormattedAddress")); } } } } finally { stream.close(); } } } catch (Exception ex) { if (logger.isInfoEnabled()) { logger.info("Problem while trying to retrieve data from GMLC"); } return status(INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build(); } Geolocation geolocation = createFrom(new Sid(accountSid), data, geolocationType); if (geolocation.getResponseStatus() != null && geolocation.getResponseStatus().equals(responseStatus.Rejected.toString())) { if (APPLICATION_XML_TYPE == responseType) { final RestCommResponse response = new RestCommResponse(geolocation); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE == responseType) { return ok(gson.toJson(geolocation), APPLICATION_JSON).build(); } else { return null; } } else { dao.addGeolocation(geolocation); if (APPLICATION_XML_TYPE == responseType) { final RestCommResponse response = new RestCommResponse(geolocation); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE == responseType) { return ok(gson.toJson(geolocation), APPLICATION_JSON).build(); } else { return null; } } }
From source file:apimanager.ZohoReportsAPIManager.java
public boolean delete(JSONObject urlParams, JSONObject criteria) { // CloseableHttpClient httpclient = HttpClients.createDefault(); // HttpPost post = new HttpPost("https://reportsapi.zoho.com/api/harshavardhan.r@zohocorp.com/Test/Name_password?ZOHO_ACTION=DELETE&ZOHO_OUTPUT_FORMAT=json&ZOHO_ERROR_FORMAT=json&authtoken=7ed717b94bc30455aad11ce5d31d34f9&ZOHO_API_VERSION=1.0"); /*try {//from w ww.j a v a2 s . c o m List<NameValuePair> nameValuePairs = new ArrayList<>(1); nameValuePairs.add(new BasicNameValuePair("ZOHO_CRITERIA", "(\"Name\" = 'harshaViaPostimportNet15')")); post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(post); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = ""; while ((line = rd.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); }*/ loggerObj.log(Level.INFO, "Inisde Delete method"); JSONObject httpPostObjectParams = new JSONObject(); String emailaddr = (String) urlParams.get("URLEmail"); String dbName = (String) urlParams.get("DBName"); String tableName = (String) urlParams.get("TableName"); String authToken = (String) urlParams.get(AUTHTOKEN); String url = "https://reportsapi.zoho.com/api/" + emailaddr + "/" + dbName + "/" + tableName + "?ZOHO_ACTION=DELETE&ZOHO_OUTPUT_FORMAT=json&ZOHO_ERROR_FORMAT=json&authtoken=" + authToken + "&ZOHO_API_VERSION=1.0"; loggerObj.log(Level.INFO, "url params are:" + url); httpPostObjectParams.put("url", url); JSONObject postParams = null; List<NameValuePair> nameValuePairs = new ArrayList<>(criteria.size()); //multiple criteria wont work. Need to test how how multiple criteria has to be given// for (Iterator iterator = criteria.keySet().iterator(); iterator.hasNext();) { String key = (String) iterator.next(); nameValuePairs.add(new BasicNameValuePair("ZOHO_CRITERIA", "(\"" + key + "\" = '" + (String) criteria.get(key) + "')")); } UrlEncodedFormEntity formParameters = null; try { formParameters = new UrlEncodedFormEntity(nameValuePairs); } catch (UnsupportedEncodingException ex) { loggerObj.log(Level.INFO, "The delete criteria cannot be encoded properly" + ex.toString()); return false; } loggerObj.log(Level.INFO, "httpPost form params are:" + nameValuePairs.toString()); HttpsClient httpsClientObj = new HttpsClient(); boolean isSuccessfulPost = httpsClientObj.httpsPost(url, null, formParameters); return isSuccessfulPost; }
From source file:de.tudarmstadt.lt.lm.app.StartLM.java
void computeSequenceProbabilities() { if (_providerService == null) { System.out.println("LM Server is not runnning."); return;//from w w w. j av a 2 s . c om } for (String input_line = null; !":q".equals((input_line = readInput(String.format( "Enter sequence, e.g. 'hello world'. Type ':q' to quit computing sequence probabilities: %n%s $> ", _name))));) { input_line = input_line.trim(); try { _providerService.resetPerplexity(); double log10_prob_ = _providerService.getSequenceLog10Probability(input_line); double prob10_ = Math.pow(10, log10_prob_); double log2_prob_ = log10_prob_ / Math.log10(2); System.out.format("+++%nprob=%g (log10=%g, log2=%g) %n", prob10_, log10_prob_, log2_prob_); double perp = _providerService.getPerplexity(input_line, false); System.out.format("perp=%g %n%n", perp); perp = _providerService.getPerplexity(input_line, true); System.out.format("perp (no-oov)=%g %n%n", perp); double log10_prob, prob10, log2_prob; List<String>[] ngram_sequence = _providerService.getNgrams(input_line); System.out.format("+++ #ngrams= %d +++ %n", ngram_sequence.length); System.out.format("[initial cumulative Perp=%g] %n%n", _providerService.getPerplexity()); for (int i = 0; i < ngram_sequence.length; i++) { List<String> ngram = ngram_sequence[i]; log10_prob = _providerService.getNgramLog10Probability(ngram); prob10 = Math.pow(10, log10_prob); log2_prob = log10_prob / Math.log10(2); int[] ngram_ids = _providerService.getNgramAsIds(ngram); List<String> ngram_lm = _providerService.getNgramAsWords(ngram_ids); System.out.format("%s %n => %s %n = %g (log10=%g, log2=%g) %n", ngram.toString(), ngram_lm.toString(), prob10, log10_prob, log2_prob); _providerService.addToPerplexity(ngram); System.out.format(" [cumulative perp=%g] %n%n", _providerService.getPerplexity()); } System.out.format("+++ #ngrams= %d +++ %n", ngram_sequence.length); System.out.format("prob=%g (log10=%g, log2=%g) %n", prob10_, log10_prob_, log2_prob_); System.out.format("perp=%g %n%n", perp); } catch (Exception e) { LOG.warn("{}: {}", e.getClass().getSimpleName(), e.getMessage()); } } }
From source file:com.omertron.slackbot.listeners.BoardGameListener.java
/** * Format the collection item (game) into an attachment * * @param game//from w ww . j a va2 s . c o m * @return */ private SlackAttachment createGameAttachment(CollectionItem game) { SlackAttachment sa = new SlackAttachment(); String year = game.getYearPublished() == null ? UNKNOWN : " (" + game.getYearPublished() + ")"; sa.setFallback(INFORMATION_ON + game.getName()); sa.setTitle(game.getName() + year); sa.setTitleLink(Constants.BGG_LINK_GAME + game.getObjectId()); sa.setAuthorIcon(game.getThumbnail()); sa.setText(StringEscapeUtils.unescapeHtml4(game.getComment())); sa.setColor(Constants.ATTACH_COLOUR_GOOD); sa.setThumbUrl(formatHttpLink(game.getThumbnail())); sa.addField(BGG_ID, String.valueOf(game.getObjectId()), true); if (game.getStats() != null && game.getStats().getRating() != null) { float value = game.getStats().getRating().getValue(); sa.addField("Rating", "" + (value > 0 ? value : "Not Rated"), true); } if (game.getNumPlays() > 0) { sa.addField("Num Plays", "" + game.getNumPlays(), true); } LOG.info("Owner Status: {}", game.getOwnerStatus().toString()); List<String> status = calculateStatus(game.getOwnerStatus()); if (!status.isEmpty()) { sa.addField("Owner Status", StringUtils.join(status, ","), true); } LOG.info("Status: {}", status.toString()); return sa; }