List of usage examples for java.util HashMap get
public V get(Object key)
From source file:com.clustercontrol.notify.util.NotifyRelationCache.java
/** * ID?????/*from www. ja v a2 s .c om*/ * * @param notifyGroupId ID * @return ???? */ public static List<NotifyRelationInfo> getNotifyList(String notifyGroupId) { try { { HashMap<String, List<NotifyRelationInfo>> cache = getCache(); // ????????????????????????? // (?????????????????????????) List<NotifyRelationInfo> notifyList = cache.get(notifyGroupId); if (notifyList != null) { return notifyList; } // ???????????? if (onCache(notifyGroupId)) { return new ArrayList<NotifyRelationInfo>(); } } m_log.debug("getNotifyIdList() : Job Master or Job Session. " + notifyGroupId); List<NotifyRelationInfo> nriList = QueryUtil.getNotifyRelationInfoByNotifyGroupId(notifyGroupId); return nriList; } catch (Exception e) { m_log.warn("getNotifyList() : " + e.getClass().getSimpleName() + ", " + e.getMessage(), e); return new ArrayList<NotifyRelationInfo>(); // ?? } }
From source file:com.jajja.jorm.Database.java
public static Context context(String database) { HashMap<String, Context> map = contextStack(database); Context activeContext = map.get(database); if (activeContext == null) { activeContext = new Context(database); map.put(database, activeContext); }//w w w . j a va 2 s .c om return activeContext; }
From source file:org.dojotoolkit.zazl.internal.XMLHttpRequestUtils.java
@SuppressWarnings({ "unchecked", "rawtypes" }) public static String xhrRequest(String shrDataString) { InputStream is = null;/*from w ww .ja v a2 s . c o m*/ String json = null; try { logger.logp(Level.FINER, XMLHttpRequestUtils.class.getName(), "xhrRequest", "shrDataString [" + shrDataString + "]"); Map<String, Object> xhrData = (Map<String, Object>) JSONParser.parse(new StringReader(shrDataString)); String url = (String) xhrData.get("url"); String method = (String) xhrData.get("method"); List headers = (List) xhrData.get("headers"); URL requestURL = createURL(url); URI uri = new URI(requestURL.toString()); HashMap httpMethods = new HashMap(7); httpMethods.put("DELETE", new HttpDelete(uri)); httpMethods.put("GET", new HttpGet(uri)); httpMethods.put("HEAD", new HttpHead(uri)); httpMethods.put("OPTIONS", new HttpOptions(uri)); httpMethods.put("POST", new HttpPost(uri)); httpMethods.put("PUT", new HttpPut(uri)); httpMethods.put("TRACE", new HttpTrace(uri)); HttpUriRequest request = (HttpUriRequest) httpMethods.get(method.toUpperCase()); if (request.equals(null)) { throw new Error("SYNTAX_ERR"); } for (Object header : headers) { StringTokenizer st = new StringTokenizer((String) header, ":"); String name = st.nextToken(); String value = st.nextToken(); request.addHeader(name, value); } HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(request); Map headerMap = new HashMap(); HeaderIterator headerIter = response.headerIterator(); while (headerIter.hasNext()) { Header header = headerIter.nextHeader(); headerMap.put(header.getName(), header.getValue()); } int status = response.getStatusLine().getStatusCode(); String statusText = response.getStatusLine().toString(); is = response.getEntity().getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = null; StringBuffer sb = new StringBuffer(); while ((line = br.readLine()) != null) { sb.append(line); sb.append('\n'); } Map m = new HashMap(); m.put("status", new Integer(status)); m.put("statusText", statusText); m.put("responseText", sb.toString()); m.put("headers", headerMap.toString()); StringWriter w = new StringWriter(); JSONSerializer.serialize(w, m); json = w.toString(); logger.logp(Level.FINER, XMLHttpRequestUtils.class.getName(), "xhrRequest", "json [" + json + "]"); } catch (Throwable e) { logger.logp(Level.SEVERE, XMLHttpRequestUtils.class.getName(), "xhrRequest", "Failed request for [" + shrDataString + "]", e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } } return json; }
From source file:com.ciphertool.sentencebuilder.dao.IndexedWordMapDao.java
/** * @param allWords/*from w ww . j av a2s. c o m*/ * the List of all Words pulled in from the constructor * @return a Map of all Words keyed by their length */ protected static Map<Integer, ArrayList<Word>> mapByWordLength(List<Word> allWords) { if (allWords == null || allWords.isEmpty()) { throw new IllegalArgumentException( "Error mapping Words by length. The supplied List of Words cannot be null or empty."); } HashMap<Integer, ArrayList<Word>> byLength = new HashMap<Integer, ArrayList<Word>>(); for (Word w : allWords) { Integer wordLength = w.getId().getWord().length(); // Add the part of speech to the map if it doesn't exist if (!byLength.containsKey(wordLength)) { byLength.put(wordLength, new ArrayList<Word>()); } byLength.get(wordLength).add(w); } return byLength; }
From source file:org.easyrec.utils.MyUtils.java
/** * This function sorts the Strings in the * given list by their first occurence in the given text. * * @param listToOrder e.g. FORMULA_1_DRIVERS = {"Lewis Hamilton","Heikki Kovalainen","Felipe Massa"} * @param textToParse e.g. "Felipe Masse is on fire. His is ahead of Lewis Hamilton" * @param fuzzy: tokenize Strings and ordery by their occurence e.g. "Lewis Hamilton" --> {"Lewis","Hamilton"} * @return {"Felipe Massa","Lewis Hamilton"} *///www . j a v a 2s .co m @SuppressWarnings({ "UnusedDeclaration" }) public static List<String> orderByFirstOccurenceInText(String listToOrder[], String textToParse, boolean fuzzy) { List<String> sortedList = new ArrayList<String>(); HashMap<Integer, String> h = new HashMap<Integer, String>(); if (listToOrder != null && !textToParse.equals("")) { for (String s : listToOrder) { if (textToParse.indexOf(s) > 0) { h.put(textToParse.indexOf(s), s); } } List<Integer> keys = new ArrayList<Integer>(h.keySet()); Collections.sort(keys); for (Integer k : keys) { sortedList.add(h.get(k)); } } if (fuzzy) { sortedList.addAll(orderByFuzzyFirstOccurenceInText(listToOrder, textToParse)); } return sortedList; }
From source file:br.net.fabiozumbi12.RedProtect.hooks.MojangUUIDs.java
public static String getName(String UUID) { try {/* w ww.ja v a 2s . c o m*/ URL url = new URL("https://api.mojang.com/user/profiles/" + UUID.replaceAll("-", "") + "/names"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = in.readLine(); if (line == null) { return null; } JSONArray array = (JSONArray) new JSONParser().parse(line); HashMap<Long, String> names = new HashMap<Long, String>(); String name = ""; for (Object profile : array) { JSONObject jsonProfile = (JSONObject) profile; if (jsonProfile.containsKey("changedToAt")) { names.put((long) jsonProfile.get("changedToAt"), (String) jsonProfile.get("name")); continue; } name = (String) jsonProfile.get("name"); } if (!names.isEmpty()) { Long key = Collections.max(names.keySet()); return names.get(key); } else { return name; } } catch (Exception ex) { ex.printStackTrace(); } return null; }
From source file:fr.lissi.belilif.om2m.rest.WebServiceActions.java
/** * Do delete./* ww w . j ava2 s .c o m*/ * * @param uri the uri * @param headers the headers * @return the http get simple resp * @throws ClientProtocolException the client protocol exception * @throws IOException Signals that an I/O exception has occurred. * @throws HttpResponseException the http response exception */ public static HttpGetSimpleResp doDelete(String uri, HashMap<String, String> headers) throws ClientProtocolException, IOException, HttpResponseException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGetSimpleResp resp = new HttpGetSimpleResp(); try { HttpDelete httpDelete = new HttpDelete(uri); for (String key : headers.keySet()) { httpDelete.addHeader(key, headers.get(key)); } CloseableHttpResponse response = httpclient.execute(httpDelete); resp.setStatusCode(response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NO_CONTENT) { try { HttpEntity entity = response.getEntity(); if (entity != null) { // TODO to use for performance in the future resp.setResult(new BasicResponseHandler().handleResponse(response)); } EntityUtils.consume(entity); } finally { response.close(); } } else { // TODO optimiz (repeating code) throw new HttpResponseException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); } } finally { httpclient.close(); } return resp; }
From source file:com.clustercontrol.jobmanagement.util.JobMultiplicityCache.java
/** * waitQueue??//from ww w. ja va 2 s. c o m * * ??????????????? * waitQueue????? * * ??????waitQueue?????? * ???????????? * * @param pk */ public static void removeWait(JobSessionNodeEntityPK pk) { try { _lock.writeLock(); HashMap<String, Queue<JobSessionNodeEntityPK>> waitingCache = getWaitingCache(); Queue<JobSessionNodeEntityPK> waitingQueue = waitingCache.get(pk.getFacilityId()); if (waitingQueue != null) { if (waitingQueue.remove(pk)) { m_log.info("removeWait " + pk); storeWaitingCache(waitingCache); } } } finally { _lock.writeUnlock(); } }
From source file:com.vmware.admiral.request.compute.NetworkProfileQueryUtils.java
private static void getNetworkConstraints(ServiceHost host, URI referer, ComputeDescription computeDescription, HashMap<String, ComputeNetwork> contextComputeNetworks, BiConsumer<Set<String>, Throwable> consumer) { DeferredResult<List<ComputeNetwork>> result = DeferredResult .allOf(computeDescription.networkInterfaceDescLinks.stream().map(nicDescLink -> { Operation op = Operation.createGet(host, nicDescLink).setReferer(referer); return host.sendWithDeferredResult(op, NetworkInterfaceDescription.class); }).map(nid -> nid.thenCompose(nic -> { ComputeNetwork computeNetwork = contextComputeNetworks.get(nic.name); if (computeNetwork == null) { throw new LocalizableValidationException( String.format("Could not find context network component with name '%s'.", nic.name), "compute.network.component.not.found", nic.name); }//from www .ja va 2 s . co m return DeferredResult.completed(computeNetwork); })).collect(Collectors.toList())); result.whenComplete((all, e) -> { if (e != null) { consumer.accept(null, e); return; } // Remove networks that don't have any constraints all.removeIf(cn -> cn.networkProfileLinks == null || cn.networkProfileLinks.isEmpty()); if (all.isEmpty()) { consumer.accept(null, null); return; } Set<String> networkProfileLinks = all.get(0).networkProfileLinks; all.forEach(cn -> networkProfileLinks.retainAll(cn.networkProfileLinks)); consumer.accept(networkProfileLinks, null); }); }
From source file:at.treedb.jslib.JsLib.java
/** * Loads an external JavaScript library. * /*w w w . j av a2s. com*/ * @param dao * {@code DAOiface} (data access object) * @param name * library name * @param version * optional library version. If this parameter is null the * library with the highest version number will be loaded * @return {@code JsLib} object * @throws Exception */ @SuppressWarnings("resource") public static synchronized JsLib load(DAOiface dao, String name, String version) throws Exception { initJsLib(dao); if (jsLibs == null) { return null; } JsLib lib = null; synchronized (lockObj) { HashMap<Version, JsLib> v = jsLibs.get(name); if (v == null) { return null; } if (version != null) { lib = v.get(new Version(version)); } else { Version[] array = v.keySet().toArray(new Version[v.size()]); Arrays.sort(array); // return the library with the highest version number lib = v.get(array[array.length - 1]); } } if (lib != null) { if (!lib.isExtracted) { // load binary archive data lib.callbackAfterLoad(dao); // detect zip of 7z archive MimeType mtype = ContentInfo.getContentInfo(lib.data); int totalSize = 0; HashMap<String, byte[]> dataMap = null; String libName = "jsLib" + lib.getHistId(); String classPath = lib.getName() + "/java/classes/"; if (mtype != null) { // ZIP archive if (mtype.equals(MimeType.ZIP)) { dataMap = new HashMap<String, byte[]>(); lib.zipInput = new ZipArchiveInputStream(new ByteArrayInputStream(lib.data)); do { ZipArchiveEntry entry = lib.zipInput.getNextZipEntry(); if (entry == null) { break; } if (entry.isDirectory()) { continue; } int size = (int) entry.getSize(); totalSize += size; byte[] data = new byte[size]; lib.zipInput.read(data, 0, size); dataMap.put(entry.getName(), data); if (entry.getName().contains(classPath)) { lib.javaFiles.add(entry.getName()); } } while (true); lib.zipInput.close(); lib.isExtracted = true; // 7-zip archive } else if (mtype.equals(MimeType._7Z)) { dataMap = new HashMap<String, byte[]>(); File tempFile = FileStorage.getInstance().createTempFile(libName, ".7z"); tempFile.deleteOnExit(); Stream.writeByteStream(tempFile, lib.data); lib.sevenZFile = new SevenZFile(tempFile); do { SevenZArchiveEntry entry = lib.sevenZFile.getNextEntry(); if (entry == null) { break; } if (entry.isDirectory()) { continue; } int size = (int) entry.getSize(); totalSize += size; byte[] data = new byte[size]; lib.sevenZFile.read(data, 0, size); dataMap.put(entry.getName(), data); if (entry.getName().contains(classPath)) { lib.javaFiles.add(entry.getName()); } } while (true); lib.sevenZFile.close(); lib.isExtracted = true; } } if (!lib.isExtracted) { throw new Exception("JsLib.load(): No JavaScript archive extracted!"); } // create a buffer for the archive byte[] buf = new byte[totalSize]; int offset = 0; // enumerate the archive entries for (String n : dataMap.keySet()) { byte[] d = dataMap.get(n); System.arraycopy(d, 0, buf, offset, d.length); lib.archiveMap.put(n, new ArchiveEntry(offset, d.length)); offset += d.length; } // create a temporary file containing the extracted archive File tempFile = FileStorage.getInstance().createTempFile(libName, ".dump"); lib.dumpFile = tempFile; tempFile.deleteOnExit(); Stream.writeByteStream(tempFile, buf); FileInputStream inFile = new FileInputStream(tempFile); // closed by the GC lib.inChannel = inFile.getChannel(); // discard the archive data - free the memory lib.data = null; dataMap = null; } } return lib; }