List of usage examples for java.util HashMap keySet
public Set<K> keySet()
From source file:com.wms.studio.cache.lock.SyncLockMapCache.java
@Override public Set<K> keys() { try {/* w w w. j av a2s. c o m*/ HashMap<K, V> attributes = memcachedClient.get(name); if (attributes != null) { Set<K> keys = attributes.keySet(); if (!keys.isEmpty()) return Collections.unmodifiableSet(keys); } } catch (Exception e) { log.fatal("?MemCache,.", e); } return Collections.emptySet(); }
From source file:com.bbc.remarc.util.ResourceManager.java
private static void createDocumentsFromFileMap(HashMap<String, List<File>> fileMap, HashMap<String, ResourceType> typeMap, File properties, String resourcesDir) { DB db = MongoClient.getDB();//w w w .j a v a 2 s . c om Properties documentProps = processPropertiesFile(properties); if (documentProps == null) { log.error("could not create properties file. Abort directory."); return; } String theme = documentProps.getProperty("theme"); String decade = documentProps.getProperty("decade"); if (theme == null && decade == null) { log.error("ERROR! Properties file contained neither THEME nor DECADE. Abort directory."); return; } // now we process each key (document) in the hashmap, copying the // resources (file array) into the correct folder Set<String> keys = fileMap.keySet(); for (String key : keys) { log.debug("processing [" + key + "]"); // create document with id, theme and decade BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start(); documentBuilder.add("id", key); documentBuilder.add("theme", theme); documentBuilder.add("decade", decade); // based upon the documentType, we can determine all our urls and // storage variables ResourceType documentType = typeMap.get(key); File fileDestDirectory = null; // Get the relative base URL from an Environment variable if it has been set String relativefileBaseUrl = System.getenv(Configuration.ENV_BASE_URL); if (relativefileBaseUrl == null || "".equals(relativefileBaseUrl)) { relativefileBaseUrl = Configuration.DEFAULT_RELATIVE_BASE_URL; } else { relativefileBaseUrl += Configuration.CONTENT_DIR; } String mongoCollection = ""; switch (documentType) { case IMAGE: mongoCollection = "images"; fileDestDirectory = new File(resourcesDir + Configuration.IMAGE_DIR_NAME); relativefileBaseUrl += Configuration.IMAGE_DIR; break; case AUDIO: mongoCollection = "audio"; fileDestDirectory = new File(resourcesDir + Configuration.AUDIO_DIR_NAME); relativefileBaseUrl += Configuration.AUDIO_DIR; break; case VIDEO: mongoCollection = "video"; fileDestDirectory = new File(resourcesDir + Configuration.VIDEO_DIR_NAME); relativefileBaseUrl += Configuration.VIDEO_DIR; break; default: break; } List<File> files = fileMap.get(key); for (File resource : files) { log.debug("--- processing [" + resource.getName() + "]"); String resourceLocation = relativefileBaseUrl + resource.getName(); String extension = FilenameUtils.getExtension(resource.getName()); ResourceType fileType = getTypeFromExtension(extension); // now determine the value to store the resource under in MongoDB, different if an image or metadata String urlKey; switch (fileType) { case IMAGE: urlKey = "imageUrl"; break; case INFORMATION: urlKey = "metadata"; break; default: urlKey = (extension + "ContentUrl"); break; } // If the file is a metadata file, we want to read from it, otherwise we just add the location to the db if (fileType == ResourceType.INFORMATION) { String metadata = processMetadata(resource.getPath()); documentBuilder.add(urlKey, metadata); } else { documentBuilder.add(urlKey, resourceLocation); } } // insert the document into the database try { DBObject obj = documentBuilder.get(); log.debug("writing document to collection (" + mongoCollection + "): " + obj); db.requestStart(); DBCollection collection = db.getCollection(mongoCollection); collection.insert(documentBuilder.get()); } finally { db.requestDone(); } // write all the resource files to the correct directory log.debug("copying resources into " + fileDestDirectory.getPath()); for (File resource : files) { // We don't want to copy the metadata into the directory, so remove it here String extension = FilenameUtils.getExtension(resource.getName()); ResourceType fileType = getTypeFromExtension(extension); if (fileType != ResourceType.INFORMATION) { try { FileUtils.copyFileToDirectory(resource, fileDestDirectory); } catch (IOException e) { log.error("ERROR! Couldn't copy resource to directory: " + e); } } } } }
From source file:com.tremolosecurity.proxy.postProcess.PushRequestProcess.java
@Override public void postProcess(HttpFilterRequest req, HttpFilterResponse resp, UrlHolder holder, HttpFilterChain chain) throws Exception { boolean isText; HashMap<String, String> uriParams = (HashMap<String, String>) req.getAttribute("TREMOLO_URI_PARAMS"); StringBuffer proxyToURL = new StringBuffer(); proxyToURL.append(holder.getProxyURL(uriParams)); boolean first = true; for (NVP p : req.getQueryStringParams()) { if (first) { proxyToURL.append('?'); first = false;/* w w w . j ava2s . c o m*/ } else { proxyToURL.append('&'); } proxyToURL.append(p.getName()).append('=').append(URLEncoder.encode(p.getValue(), "UTF-8")); } HttpEntity entity = null; if (req.isMultiPart()) { MultipartEntityBuilder mpeb = MultipartEntityBuilder.create() .setMode(HttpMultipartMode.BROWSER_COMPATIBLE); for (String name : req.getFormParams()) { /*if (queryParams.contains(name)) { continue; }*/ for (String val : req.getFormParamVals(name)) { //ent.addPart(name, new StringBody(val)); mpeb.addTextBody(name, val); } } HashMap<String, ArrayList<FileItem>> files = req.getFiles(); for (String name : files.keySet()) { for (FileItem fi : files.get(name)) { //ent.addPart(name, new InputStreamBody(fi.getInputStream(),fi.getContentType(),fi.getName())); mpeb.addBinaryBody(name, fi.get(), ContentType.create(fi.getContentType()), fi.getName()); } } entity = mpeb.build(); } else if (req.isParamsInBody()) { List<NameValuePair> formparams = new ArrayList<NameValuePair>(); for (String paramName : req.getFormParams()) { for (String val : req.getFormParamVals(paramName)) { formparams.add(new BasicNameValuePair(paramName, val)); } } entity = new UrlEncodedFormEntity(formparams, "UTF-8"); } else { byte[] msgData = (byte[]) req.getAttribute(ProxySys.MSG_BODY); ByteArrayEntity bentity = new ByteArrayEntity(msgData); bentity.setContentType(req.getContentType()); entity = bentity; } MultipartRequestEntity frm; CloseableHttpClient httpclient = this.getHttp(proxyToURL.toString(), req.getServletRequest(), holder.getConfig()); //HttpPost httppost = new HttpPost(proxyToURL.toString()); HttpEntityEnclosingRequestBase httpMethod = new EntityMethod(req.getMethod(), proxyToURL.toString());//this.getHttpMethod(proxyToURL.toString()); setHeadersCookies(req, holder, httpMethod, proxyToURL.toString()); httpMethod.setEntity(entity); HttpContext ctx = (HttpContext) req.getSession().getAttribute(ProxySys.HTTP_CTX); HttpResponse response = httpclient.execute(httpMethod, ctx); postProcess(req, resp, holder, response, proxyToURL.toString(), chain, httpMethod); }
From source file:com.mythesis.profileanalysis.WordVectorFinder.java
/** * a method that calculates the word vector for a specific domain * @param domain the general domain//from w w w.j av a 2 s.c o m * @param wordVectorDirectory the directory where i will save the word vector * @param LDAdirectory LDA directory * @param nTopTopics number of top topics * @param choice how to select the top topics (1 for average, 2 for median, 3 for number of documents that have probability higher than 1/nTopics) * @param top_words number of top words * @param nTopics total number of topics */ public void getWordVector(String domain, String wordVectorDirectory, String LDAdirectory, int nTopTopics, int choice, int top_words, int nTopics) { String path = LDAdirectory; LDAtopicsWords rk = new LDAtopicsWords(); if (nTopTopics > nTopics) nTopTopics = nTopics; //get a number of top topics and a number of top words from every topic HashMap<Integer, HashMap<String, Double>> topicwordprobmap = rk.readFile(path, top_words, nTopics, nTopTopics, choice); List<String> wordVector = new ArrayList<>(); for (Integer topicindex : topicwordprobmap.keySet()) { //iterate through every topic Set keySet = topicwordprobmap.get(topicindex).keySet(); Iterator iterator = keySet.iterator(); while (iterator.hasNext()) { //iterate through every word String word = iterator.next().toString(); if (!wordVector.contains(word)) { wordVector.add(word); //put the word in word vector } } } //store the word vector File wordVectorFile = new File(wordVectorDirectory + "wordVector" + domain + ".txt"); try { FileUtils.writeLines(wordVectorFile, wordVector); } catch (IOException ex) { Logger.getLogger(WordVectorFinder.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.deploymentio.ec2namer.helpers.InstanceTagger.java
/** * Tags the EC2 instance we are naming. The tag's name/values are provided * in the request. Additionally, if no <code>Name</code> tag is provided, * this method will add one in the format of * <code>{environment}:{reserved-name}</code>. * //from www. j a va 2 s . c om * @param req * the namer request * @param context * the lambda function execution context * @param name * the reserved name for this instance * @throws IOException * if the instance cannot be tagged */ public void tag(NamerRequest req, LambdaContext context, ReservedName name) throws IOException { HashMap<String, String> map = new HashMap<>(req.getRequestedTags()); if (!map.containsKey("Name")) { map.put("Name", req.getEnvironment() + ":" + name.getHostname()); } ArrayList<Tag> tags = new ArrayList<>(); for (String key : map.keySet()) { String val = map.get(key); tags.add(new Tag().withKey(key).withValue(val)); } ec2.createTags(new CreateTagsRequest().withResources(req.getInstanceId()).withTags(tags)); }
From source file:tn.mariages.gui.Statistiques.java
private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened //////// w w w. jav a 2 s . c om DefaultPieDataset dataset;//Dataset qui va contenir les Donnes JFreeChart graphe; //Graphe ChartPanel cp; //Panel dataset = new DefaultPieDataset(); panierProduitDAO ppDAO = new panierProduitDAO(); PanierProduit pp = new PanierProduit(); HashMap<Integer, Integer> top10BestSeller = ppDAO.getTop10BestSeller(); ProduitDAO pDAO = new ProduitDAO(); Iterator<Integer> i = top10BestSeller.keySet().iterator(); while (i.hasNext()) { Integer key = i.next(); System.out.println("key: " + key + " value: " + top10BestSeller.get(key)); Produit DisplayProdByID = pDAO.DisplayProdByID(key); dataset.setValue("" + DisplayProdByID.getNomProd(), new Double(top10BestSeller.get(key))); } graphe = ChartFactory.createPieChart("Top Ventes Produits", dataset); ChartPanel CP = new ChartPanel(graphe); JOptionPane.showMessageDialog(this, "id " + id + " Type : " + typeDeComptes); ///// }
From source file:com.snowplowanalytics.snowplow.tracker.emitter.Emitter.java
@SuppressWarnings("unchecked") protected HttpResponse sendGetData(Payload payload) { HashMap hashMap = (HashMap) payload.getMap(); Iterator<String> iterator = hashMap.keySet().iterator(); HttpResponse httpResponse = null;//from w w w . j a v a 2 s . c om while (iterator.hasNext()) { String key = iterator.next(); String value = (String) hashMap.get(key); uri.setParameter(key, value); } try { HttpGet httpGet = new HttpGet(uri.build()); if (requestMethod == RequestMethod.Asynchronous) { Future<HttpResponse> future = httpAsyncClient.execute(httpGet, null); httpResponse = future.get(); } else { httpResponse = httpClient.execute(httpGet); } logger.debug(httpResponse.getStatusLine().toString()); } catch (IOException e) { logger.error("Error when sending HTTP GET error."); e.printStackTrace(); } catch (URISyntaxException e) { logger.error("Error when creating HTTP GET request. Probably parsing error.."); e.printStackTrace(); } catch (InterruptedException e) { logger.error("Interruption error when sending HTTP GET request."); e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return httpResponse; }
From source file:com.thoughtworks.go.server.controller.MyGoController.java
private ModelAndView render(HttpServletRequest request, Message message, HashMap<String, Object> data) { User user = userService.load(getUserId(request)); user.populateModel(data);/*from w w w . ja v a 2s. co m*/ for (String key : data.keySet()) { if (StringUtils.isNotBlank(request.getParameter(key))) { data.put(key, request.getParameter(key)); } } List<PipelineConfigs> groups = securityService.viewableGroupsFor(getUserName()); data.put("pipelines", new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create() .toJson(getPipelineModelsSortedByNameFor(groups))); data.put("l", localizer); data.put("escaper", new Escaper()); message.populateModel(data); return new ModelAndView("mycruise/mycruise-tab", data); }
From source file:org.forgerock.openam.mobile.commons.FormRestRequest.java
/** * Alters the request to insert additional HTTP POST x-www-form-urlencoded data *//* w w w . j a va2s. c o m*/ public void insertData(HashMap<String, String> formParameters) { if (formParameters == null) { return; } HttpPost request = getRequest(); try { List<NameValuePair> data = new ArrayList<NameValuePair>(); for (String s : formParameters.keySet()) { NameValuePair nvp = new BasicNameValuePair(s, formParameters.get(s)); data.add(nvp); } UrlEncodedFormEntity formData = new UrlEncodedFormEntity(data); formData.setContentType(CONTENT_TYPE); request.setEntity(formData); } catch (UnsupportedEncodingException e) { fail(TAG, "Unable to set entity."); } }
From source file:afest.datastructures.tree.decision.erts.informationfunctions.GeneralizedNormalizedShannonEntropy.java
@Override public <T extends ITrainingPoint<R, C>> double getScore(Collection<T> set, ISplit<R> split) { HashMap<Boolean, ArrayList<T>> splitSeparation = InformationFunctionsUtils.performSplit(set, split); HashMap<Boolean, Integer> countSeparation = new HashMap<Boolean, Integer>(); for (Boolean key : splitSeparation.keySet()) { ArrayList<T> elements = splitSeparation.get(key); countSeparation.put(key, elements.size()); }/*from w ww .j a va2 s. c o m*/ HashMap<C, Integer> countContent = groupElementsByContent(set); HashMap<C, Integer> countContentTrue = groupElementsByContent(splitSeparation.get(true)); HashMap<C, Integer> countContentFalse = groupElementsByContent(splitSeparation.get(false)); double ht = getEntropy(countSeparation, set.size()); double hc = getEntropy(countContent, set.size()); double dSize = (double) set.size(); double pTrue = countSeparation.get(true) / dSize; double hct = 0; for (Integer count : countContentTrue.values()) { double prob1 = count / dSize; double prob2 = prob1 / pTrue; hct -= prob1 * MathUtils.log(2, prob2); } for (Integer count : countContentFalse.values()) { double prob1 = count / dSize; double prob2 = 1 - (prob1 / pTrue); // pFalse hct -= prob1 * MathUtils.log(2, prob2); } // Mutual Information double itc = hc - hct; // Normalization double ctc = 2 * itc / (hc + ht); return ctc; }