List of usage examples for java.util HashMap entrySet
Set entrySet
To view the source code for java.util HashMap entrySet.
Click Source Link
From source file:Logic.mongoC.java
public void masInter(String usuario) { HashMap<String, String> conteo = new HashMap(); Document soloN = this.coll.find(eq("ScreenName", usuario)).first(); usuario regreso = this.gson.fromJson(soloN.getString("todo"), usuario.class); for (twitt t : regreso.getTimeline()) { Date d = t.getFecha();/*www . jav a2 s . c om*/ System.out.println(d.getDay()); for (String men : t.getPersonas()) { if (conteo.containsKey(men)) { int cl = Integer.valueOf(conteo.get(men)); cl++; conteo.put(men, String.valueOf(cl)); } else { conteo.put(men, "1"); } } } JFreeChart Grafica; DefaultCategoryDataset Datos = new DefaultCategoryDataset(); for (Map.Entry<String, String> entry : conteo.entrySet()) { String key = entry.getKey().toString(); Integer value = Integer.valueOf(entry.getValue()); Datos.addValue(value, usuario, key); System.out.println("KEY " + key + " vaue " + value); } Grafica = ChartFactory.createBarChart("Interacciones con usuarios", "Usuarios", "Numero de interacciones", Datos, PlotOrientation.VERTICAL, true, true, false); ChartPanel Panel = new ChartPanel(Grafica); JFrame Ventana = new JFrame("JFreeChart"); Ventana.getContentPane().add(Panel); Ventana.pack(); Ventana.setVisible(true); Ventana.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); }
From source file:com.volley.air.toolbox.HurlStack.java
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws AuthFailureError, IOException { String url = request.getUrl(); HashMap<String, String> map = new HashMap<>(); map.putAll(request.getHeaders());//from ww w.java2 s . c om map.putAll(additionalHeaders); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); if (!TextUtils.isEmpty(mUserAgent)) { connection.setRequestProperty(HEADER_USER_AGENT, mUserAgent); } for (Entry<String, String> entry : map.entrySet()) { connection.addRequestProperty(entry.getKey(), entry.getValue()); } if (request instanceof MultiPartRequest) { setConnectionParametersForMultipartRequest(connection, request); } else { setConnectionParametersForRequest(connection, request); } // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode = connection.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could // not be retrieved. // Signal to the caller that something was wrong with the // connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection)); for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } return response; }
From source file:com.cloudbees.api.BeesClientBase.java
protected String executeUpload(String uploadURL, Map<String, String> params, Map<String, File> files, UploadProgress writeListener) throws Exception { HashMap<String, String> clientParams = getDefaultParameters(); clientParams.putAll(params);// w w w . j a v a 2 s .co m PostMethod filePost = new PostMethod(uploadURL); try { ArrayList<Part> parts = new ArrayList<Part>(); int fileUploadSize = 0; for (Map.Entry<String, File> fileEntry : files.entrySet()) { FilePart filePart = new FilePart(fileEntry.getKey(), fileEntry.getValue()); parts.add(filePart); fileUploadSize += filePart.length(); //TODO: file params are not currently included in the signature, // we should hash the file contents so we can verify them } for (Map.Entry<String, String> entry : clientParams.entrySet()) { parts.add(new StringPart(entry.getKey(), entry.getValue())); } // add the signature String signature = calculateSignature(clientParams); parts.add(new StringPart("sig", signature)); ProgressUploadEntity uploadEntity = new ProgressUploadEntity(parts.toArray(new Part[parts.size()]), filePost.getParams(), writeListener, fileUploadSize); filePost.setRequestEntity(uploadEntity); HttpClient client = HttpClientHelper.createClient(this.beesClientConfiguration); client.getHttpConnectionManager().getParams().setConnectionTimeout(10000); int status = client.executeMethod(filePost); String response = getResponseString(filePost.getResponseBodyAsStream()); if (status == HttpStatus.SC_OK) { trace("upload complete, response=" + response); } else { trace("upload failed, response=" + HttpStatus.getStatusText(status)); } return response; } finally { filePost.releaseConnection(); } }
From source file:com.google.gwt.emultest.java.util.HashMapTest.java
public void testClone() { HashMap<String, String> srcMap = new HashMap<String, String>(); checkEmptyHashMapAssumptions(srcMap); HashMap<String, String> dstMap = cloneMap(srcMap); assertNotNull(dstMap);//w w w . j av a 2s . c om assertEquals(dstMap.size(), srcMap.size()); // assertTrue(dstMap.values().toArray().equals(srcMap.values().toArray())); assertTrue(dstMap.keySet().equals(srcMap.keySet())); assertTrue(dstMap.entrySet().equals(srcMap.entrySet())); // Check non-empty clone behavior srcMap.put(KEY_1, VALUE_1); srcMap.put(KEY_2, VALUE_2); srcMap.put(KEY_3, VALUE_3); dstMap = cloneMap(srcMap); assertNotNull(dstMap); assertEquals(dstMap.size(), srcMap.size()); assertTrue(dstMap.keySet().equals(srcMap.keySet())); assertTrue(dstMap.entrySet().equals(srcMap.entrySet())); }
From source file:fr.isen.browser5.Util.UrlLoader.java
private void load(String url, Object... args) { String method = null, action = null; HashMap<String, String> params = null; if (args.length == 3) { method = (String) args[0]; action = (String) args[1]; params = (HashMap<String, String>) args[2]; }/* ww w .ja va 2 s. c o m*/ try { url = Str.checkProtocol(url); String urlParameters = ""; if (method != null) { url = Str.removeLastSlash(url); if (action.startsWith("/")) { action = action.substring(1); } if (action.startsWith("http://") || action.startsWith("https://")) { url = action; } else { url += "/" + action; } int i = 0; for (Map.Entry<String, String> entry : params.entrySet()) { urlParameters += entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), "UTF-8"); if (!(i++ == params.size() - 1)) { urlParameters += "&"; } } if (method.equals("GET")) { url += "?" + urlParameters; } } else { method = "GET"; } System.out.println(); System.out.println("Loading url: " + url); URL obj = new URL(url); connection = (HttpURLConnection) obj.openConnection(); connection.setReadTimeout(10000); connection.addRequestProperty("Accept-Language", "en-US,en;q=0.8"); connection.addRequestProperty("User-Agent", "Lynx/2.8.8dev.3 libwww-FM/2.14 SSL-MM/1.4.1"); connection.setRequestMethod(method); if (method.equals("POST")) { byte[] postData = urlParameters.getBytes(Charset.forName("UTF-8")); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(postData.length)); connection.setRequestProperty("Content-Language", "en-US"); connection.setDoInput(true); connection.setDoOutput(true); try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) { wr.write(postData); } } if (handleRedirects()) return; handleConnectionResponse(); } catch (IOException ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(null, ex.getMessage(), ex.getClass().getSimpleName(), JOptionPane.ERROR_MESSAGE); } }
From source file:com.jci.po.repo.PoRepoImpl.java
public BatchUpdateRes batchUpdate(BatchUpdateReq request) { BatchUpdateRes response = new BatchUpdateRes(); String erpName = request.getErpName(); HashMap<String, List<PoEntity>> tableNameToEntityMap = request.getTableNameToEntityMap(); List<String> errorList = new ArrayList<>(); List<String> successList = new ArrayList<>(); CloudTable cloudTable = null;//from w ww .ja v a 2s . c o m PoEntity entity = null; int successCount = 0; for (Map.Entry<String, List<PoEntity>> entry : tableNameToEntityMap.entrySet()) { try { cloudTable = azureStorage.getTable(entry.getKey()); } catch (Exception e) { LOG.error("### Exception in PoRepoImpl.batchUpdate.getTable ###" + e); response.setError(true); response.setMessage("The Application has encountered an error! Table does not exist !"); continue; } // Define a batch operation. TableBatchOperation batchOperation = new TableBatchOperation(); List<PoEntity> value = entry.getValue(); for (int i = 0; i < value.size(); i++) { entity = value.get(i); entity.setGlobalId(request.getGlobalId()); entity.setUserName(request.getUserName()); entity.setComment(request.getComment()); entity.setSupplierDeliveryState(2); successCount = successCount + 1; successList.add(entity.getRowKey()); batchOperation.insertOrMerge(entity); if (i != 0 && (i % batchSize) == 0) { try { cloudTable.execute(batchOperation); batchOperation.clear(); } catch (Exception e) { response.setError(true); response.setMessage("The Application has encountered an error!"); successCount = successCount - 1; LOG.error("### Exception in PoRepoImpl.batchUpdate.execute ###" + e); continue; } } } if (batchOperation.size() > 0) { try { cloudTable.execute(batchOperation); } catch (Exception e) { response.setError(true); response.setMessage("The Application has encountered an error!"); successCount = successCount - 1; LOG.error("### Exception in PoRepoImpl.batchUpdate.execute ###" + e); continue; } } } response.setErrorList(errorList); response.setSuccessList(successList); //Insert MIsc data: need to make sure only for podetails MiscDataEntity miscEntity = null; try { miscEntity = getStatusCountEntity("STATUS_COUNT", erpName); } catch (InvalidKeyException | URISyntaxException | StorageException e) { LOG.error("### Exception in PoRepoImpl.batchUpdate ####", e); response.setError(true); response.setMessage("The Application has encountered an error!"); } if (successCount > 0) { int sum1 = miscEntity.getProcessedCount() + successCount; miscEntity.setProcessedCount(sum1); int sum2 = miscEntity.getErrorCount() - successCount; miscEntity.setErrorCount(sum2); try { updateStatusCountEntity(miscEntity); } catch (InvalidKeyException | URISyntaxException | StorageException e) { LOG.error("### Exception in PoRepoImpl.batchUpdate ####", e); response.setError(true); response.setMessage("The Application has encountered an error!"); } } return response; }
From source file:com.uber.hoodie.common.model.HoodieTableMetadata.java
/** * Takes a bunch of file versions, and returns a map keyed by fileId, with the necessary * version safety checking. Returns a map of commitTime and Sorted list of FileStats * ( by reverse commit time )//w ww . ja va2 s. c om * * @param maxCommitTime maximum permissible commit time * * @return */ private Map<String, List<FileStatus>> groupFilesByFileId(FileStatus[] files, String maxCommitTime) throws IOException { HashMap<String, List<FileStatus>> fileIdtoVersions = new HashMap<>(); for (FileStatus file : files) { String filename = file.getPath().getName(); String fileId = FSUtils.getFileId(filename); String commitTime = FSUtils.getCommitTime(filename); if (isCommitTsSafe(commitTime) && HoodieCommits.isCommit1BeforeOrOn(commitTime, maxCommitTime)) { if (!fileIdtoVersions.containsKey(fileId)) { fileIdtoVersions.put(fileId, new ArrayList<FileStatus>()); } fileIdtoVersions.get(fileId).add(file); } } for (Map.Entry<String, List<FileStatus>> entry : fileIdtoVersions.entrySet()) { Collections.sort(fileIdtoVersions.get(entry.getKey()), new Comparator<FileStatus>() { @Override public int compare(FileStatus o1, FileStatus o2) { String o1CommitTime = FSUtils.getCommitTime(o1.getPath().getName()); String o2CommitTime = FSUtils.getCommitTime(o2.getPath().getName()); // Reverse the order return o2CommitTime.compareTo(o1CommitTime); } }); } return fileIdtoVersions; }
From source file:fastcall.FastCallSNP.java
private ConcurrentHashMap<BufferedReader, List<String>> getReaderRemainderMap( HashMap<String, BufferedReader> bamPathPileupReaderMap) { ArrayList<String> empty = new ArrayList(); ConcurrentHashMap<BufferedReader, List<String>> readerRemainderMap = new ConcurrentHashMap(); Set<Map.Entry<String, BufferedReader>> enties = bamPathPileupReaderMap.entrySet(); enties.stream().forEach(e -> {//from ww w . j a va2 s . co m readerRemainderMap.put(e.getValue(), empty); }); return readerRemainderMap; }
From source file:com.yahoo.dba.perf.myperf.springmvc.VardiffController.java
@Override protected ModelAndView handleRequestImpl(HttpServletRequest req, HttpServletResponse resp) throws Exception { int status = Constants.STATUS_OK; String message = "OK"; logger.info("receive url " + req.getQueryString()); QueryParameters qps = null;//from w w w.j a v a2 s . c om DBInstanceInfo dbinfo = null; DBInstanceInfo dbinfo2 = null; DBConnectionWrapper connWrapper = null; DBConnectionWrapper connWrapper2 = null; qps = WebAppUtil.parseRequestParameter(req); qps.setSql("mysql_global_variables"); qps.getSqlParams().put("p_1", ""); String group2 = req.getParameter("p_1"); String host2 = req.getParameter("p_2"); //validation input String validation = qps.validate(); if (validation == null || validation.isEmpty()) { //do we have such query? try { QueryInputValidator.validateSql(this.frameworkContext.getSqlManager(), qps); } catch (Exception ex) { validation = ex.getMessage(); } } if (validation != null && !validation.isEmpty()) return this.respondFailure(validation, req); dbinfo = this.frameworkContext.getDbInfoManager().findDB(qps.getGroup(), qps.getHost()); if (dbinfo == null) return this.respondFailure("Cannot find record for DB (" + qps.getGroup() + ", " + qps.getHost() + ")", req); dbinfo2 = this.frameworkContext.getDbInfoManager().findDB(group2, host2); if (dbinfo2 == null) return this.respondFailure("Cannot find record for DB (" + group2 + ", " + host2 + ")", req); try { connWrapper = WebAppUtil.getDBConnection(req, this.frameworkContext, dbinfo); if (connWrapper == null) { status = Constants.STATUS_BAD; message = "failed to connect to target db (" + dbinfo + ")"; } else { connWrapper2 = WebAppUtil.getDBConnection(req, this.frameworkContext, dbinfo2); if (connWrapper2 == null) { status = Constants.STATUS_BAD; message = "failed to connect to target db (" + dbinfo2 + ")"; } } } catch (Throwable th) { logger.log(Level.SEVERE, "Exception", th); status = Constants.STATUS_BAD; message = "Failed to get connection to target db (" + dbinfo + "): " + th.getMessage(); } if (status == -1) return this.respondFailure(message, req); //when we reach here, at least we have valid query and can connect to db WebAppUtil.storeLastDbInfoRequest(qps.getGroup(), qps.getHost(), req); ModelAndView mv = null; ResultList rList = null; ResultList rList2 = null; try { rList = this.frameworkContext.getQueryEngine().executeQueryGeneric(qps, connWrapper, qps.getMaxRows()); rList2 = this.frameworkContext.getQueryEngine().executeQueryGeneric(qps, connWrapper2, qps.getMaxRows()); logger.info("Done query " + qps.getSql() + " with " + (rList != null ? rList.getRows().size() : 0) + " records, " + (rList2 != null ? rList2.getRows().size() : 0) + " records"); WebAppUtil.closeDBConnection(req, connWrapper, false); WebAppUtil.closeDBConnection(req, connWrapper2, false); } catch (Throwable ex) { logger.log(Level.SEVERE, "Exception", ex); if (ex instanceof SQLException) { SQLException sqlEx = SQLException.class.cast(ex); String msg = ex.getMessage(); logger.info(sqlEx.getSQLState() + ", " + sqlEx.getErrorCode() + ", " + msg); //check if the connection is still good if (!DBUtils.checkConnection(connWrapper.getConnection())) { WebAppUtil.closeDBConnection(req, connWrapper, true); } else WebAppUtil.closeDBConnection(req, connWrapper, true); if (!DBUtils.checkConnection(connWrapper2.getConnection())) { WebAppUtil.closeDBConnection(req, connWrapper2, true); } else WebAppUtil.closeDBConnection(req, connWrapper2, true); } else { WebAppUtil.closeDBConnection(req, connWrapper, false); WebAppUtil.closeDBConnection(req, connWrapper2, false); } status = Constants.STATUS_BAD; message = "Exception: " + ex.getMessage(); } if (status == Constants.STATUS_BAD) return this.respondFailure(message, req); HashMap<String, String> param1 = new HashMap<String, String>(rList.getRows().size()); HashMap<String, String> param2 = new HashMap<String, String>(rList2.getRows().size()); for (ResultRow r : rList.getRows()) { param1.put(r.getColumns().get(0), r.getColumns().get(1)); } for (ResultRow r : rList2.getRows()) { param2.put(r.getColumns().get(0), r.getColumns().get(1)); } ColumnDescriptor desc = new ColumnDescriptor(); desc.addColumn("VARIABLE_NAME", false, 1); desc.addColumn("DB1", false, 2); desc.addColumn("DB2", false, 3); ResultList fList = new ResultList(); fList.setColumnDescriptor(desc); HashSet<String> diffSet = new HashSet<String>(); for (Map.Entry<String, String> e : param1.entrySet()) { String k = e.getKey(); String v = e.getValue(); if (v != null) v = v.trim(); else v = ""; String v2 = null; if (param2.containsKey(k)) v2 = param2.get(k); if (v2 != null) v2 = v2.trim(); else v2 = ""; if (!v.equals(v2)) { ResultRow row = new ResultRow(); List<String> cols = new ArrayList<String>(); cols.add(k); cols.add(v); cols.add(v2); row.setColumns(cols); row.setColumnDescriptor(desc); fList.addRow(row); diffSet.add(k); } } for (Map.Entry<String, String> e : param2.entrySet()) { String k = e.getKey(); String v = e.getValue(); if (v == null || v.isEmpty()) continue; if (diffSet.contains(k) || param1.containsKey(k)) continue; ResultRow row = new ResultRow(); List<String> cols = new ArrayList<String>(); cols.add(k); cols.add(""); cols.add(v); row.setColumns(cols); row.setColumnDescriptor(desc); fList.addRow(row); } mv = new ModelAndView(this.jsonView); if (req.getParameter("callback") != null && req.getParameter("callback").trim().length() > 0) mv.addObject("callback", req.getParameter("callback"));//YUI datasource binding mv.addObject("json_result", ResultListUtil.toJSONString(fList, qps, status, message)); return mv; }
From source file:eu.freme.eservices.elink.api.DataEnricher.java
/** * Called to enrich NIF document template using LDF endpoint. * @param model The NIF document represented as Jena model. * @param template The template to be used for enrichment. * @param templateParams Map of user defined parameters. *//* w w w .ja va 2 s. c o m*/ public Model enrichWithTemplateLDF(Model model, Template template, HashMap<String, String> templateParams) { try { StmtIterator ex = model.listStatements((Resource) null, model.getProperty("http://www.w3.org/2005/11/its/rdf#taIdentRef"), (RDFNode) null); Model enrichment = ModelFactory.createDefaultModel(); // Iterating through every entity and enriching it. while (ex.hasNext()) { Statement stm = ex.nextStatement(); String entityURI = stm.getObject().asResource().getURI(); // Replacing the entity_uri fields in the template with the entity URI. String query = template.getQuery().replaceAll("@@@entity_uri@@@", entityURI); Map.Entry resModel; // Replacing the other custom fields in the template with the corresponding values. for (Iterator e = templateParams.entrySet().iterator(); e.hasNext(); query = query .replaceAll("@@@" + (String) resModel.getKey() + "@@@", (String) resModel.getValue())) { resModel = (Map.Entry) e.next(); } // Executing the enrichment. Model ldfModel; LinkedDataFragmentGraph ldfg = new LinkedDataFragmentGraph(template.getEndpoint()); ldfModel = ModelFactory.createModelForGraph(ldfg); Query qry = QueryFactory.create(query); QueryExecution qe = QueryExecutionFactory.create(qry, ldfModel); Model enrichedModel = qe.execConstruct(); enrichment.add(enrichedModel); qe.close(); } model.add(enrichment); return model; //} catch (Exception ex) { // logger.error(getFullStackTrace(ex)); // throw new BadRequestException("It seems your SPARQL template is not correctly defined."); } catch (HttpException ex) { logger.error(getFullStackTrace(ex)); throw new ExternalServiceFailedException( ex.getMessage() + ": The remote triple store could not be reached."); } }