List of usage examples for java.util.concurrent ConcurrentMap get
V get(Object key);
From source file:org.apereo.portal.portlet.registry.PortletEntityRegistryImpl.java
protected IPortletDefinition getPortletDefinition(HttpServletRequest request, IUserInstance userInstance, String portletDefinitionIdStr) { request = this.portalRequestUtils.getOriginalPortalRequest(request); final ConcurrentMap<String, IPortletDefinition> portletDefinitions = PortalWebUtils .getMapRequestAttribute(request, PORTLET_DEFINITION_LOOKUP_MAP_ATTRIBUTE); IPortletDefinition portletDefinition = portletDefinitions.get(portletDefinitionIdStr); if (portletDefinition == NO_PERMISSION_PORTLET_DEFINITION) { return null; }//from w w w.j a va 2 s .c o m if (portletDefinition != null) { return portletDefinition; } portletDefinition = this.portletDefinitionRegistry.getPortletDefinition(portletDefinitionIdStr); portletDefinition = checkPortletDefinitionRenderPermissions(userInstance, portletDefinition); if (portletDefinition == null) { portletDefinitions.put(portletDefinitionIdStr, NO_PERMISSION_PORTLET_DEFINITION); } else { portletDefinitions.put(portletDefinitionIdStr, portletDefinition); } return portletDefinition; }
From source file:org.opendaylight.ovsdb.plugin.impl.ConfigurationServiceImpl.java
@Override public ConcurrentMap<UUID, Row<GenericTableSchema>> getRows(Node node, String databaseName, String tableName) throws OvsdbPluginException { ConcurrentMap<String, Row> ovsTable = ovsdbInventoryService.getTableCache(node, databaseName, tableName); if (ovsTable == null) return null; ConcurrentMap<UUID, Row<GenericTableSchema>> tableDB = Maps.newConcurrentMap(); for (String uuidStr : ovsTable.keySet()) { tableDB.put(new UUID(uuidStr), ovsTable.get(uuidStr)); }//from w ww . ja v a 2 s . co m return tableDB; }
From source file:com.engine.QuoteServletData.java
/** * * @param id - zTblOpp4.ID/* w w w . j a v a 2 s . co m*/ */ public QuoteServletData(String id) { items = new ArrayList<>(); java.sql.Connection con = null; java.sql.PreparedStatement stmt = null; java.sql.ResultSet rs = null; try { con = ControlPanelPool.getInstance().getConnection(); /* stmt = con.prepareStatement("SELECT * FROM zTblOpp4 WHERE z3ID = ?"); stmt.setString(1, id); rs = stmt.executeQuery(); originZip = ""; country = ""; while (rs.next()) { originZip = rs.getString("ZIP"); country = rs.getString("COUNTRY"); } productClass = ""; */ System.out.println("tblOppMngr4.z4ID = " + id); String z3Id = ""; String z1Id = ""; stmt = con.prepareStatement("SELECT * FROM tblOppMngr4 WHERE z4ID = ?"); stmt.setString(1, id); rs = stmt.executeQuery(); while (rs.next()) { z3Id = rs.getString("z3ID"); z1Id = rs.getString("z1ID"); originZip = rs.getString("SFZIP"); } stmt = con.prepareStatement("SELECT * FROM tblOppMngr1 WHERE z1ID = ?"); stmt.setString(1, z1Id); rs = stmt.executeQuery(); while (rs.next()) { destinationZip = rs.getString("STZIP"); } //https://www.zipcodeapi.com/rest/NGaSQLHFvsGMP1rbcB7RJbb67rX5JAqxgAq6m7LSAsEpt5BFGIxqUIw29u7S4xqk/distance.json/10801/08854/mile //get the warehouse and compare the zip codes and find out which one is the closest and use that //for generating the quote that is crossdock //while the regular quote should be generated as well //the warehouse should also be checked to be able to handle the hazmat material if the matrial is hazmat //when it is a crossdock the notify prior to delivery fee should be added //if it is a direct order do not notify prior to delivery stmt = con.prepareStatement("SELECT * FROM tblOppMngr3 WHERE z1ID = ?"); stmt.setString(1, z1Id); rs = stmt.executeQuery(); while (rs.next()) { if (rs.getString("HZMT") != null && !rs.getString("HZMT").isEmpty()) { if (rs.getString("HZMT").startsWith("Haz")) { productClass = "85"; } if (rs.getString("HZMT").startsWith("Non")) { productClass = "65"; } } else { productClass = "65"; } productUm = rs.getString("UNITMEASURE") == null ? "LB" : rs.getString("UNITMEASURE"); productWeight = (rs.getDouble("QUANT") == 0 ? 1 : rs.getDouble("QUANT")) * (rs.getDouble("MEASURE") == 0 ? 1 : rs.getDouble("MEASURE")); Item it = new Item(rs.getString("ID"), productClass, String.valueOf(productWeight)); items.add(it); } stmt = con.prepareStatement("SELECT * FROM tblUMMultiplier WHERE UM = ?"); stmt.setString(1, productUm); rs = stmt.executeQuery(); while (rs.next()) { productWeight = productWeight * rs.getFloat("LBmultplier"); } stmt = con.prepareStatement("SELECT * FROM tblWarehouse WHERE Active = 1"); ConcurrentMap<String, String> warehouseZip = new ConcurrentHashMap<>(); rs = stmt.executeQuery(); while (rs.next()) { if (rs.getString("WHZIP") != null) { warehouseZip.put(rs.getString("WHZIP"), ""); } } for (String key : warehouseZip.keySet()) { if (key.matches("[0-9]+")) { URL url = new URL("http://10.1.1.58:8080/zip/distance?zip1=" + originZip + "&zip2=" + key); URLConnection conn = url.openConnection(); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; while ((inputLine = br.readLine()) != null) { warehouseZip.put(key, inputLine.substring(1, inputLine.length() - 1)); } br.close(); } } double min = 10000.0; for (String key : warehouseZip.keySet()) { if (!warehouseZip.get(key).isEmpty() && warehouseZip.get(key) != null) { if (Double.valueOf(warehouseZip.get(key)) < min) { min = Double.valueOf(warehouseZip.get(key)); whZip = key; } } } con.close(); } catch (IOException | SQLException | PropertyVetoException ex) { Logger.getLogger(QuoteServletData.class.getName()).log(Level.SEVERE, null, ex); } finally { DbUtils.closeQuietly(con, stmt, rs); } }
From source file:alluxio.job.move.MoveDefinition.java
/** * {@inheritDoc}//ww w.j a va2s.com * * Assigns each worker to move whichever files it has the most blocks for. If no worker has blocks * for a file, a random worker is chosen. */ @Override public Map<WorkerInfo, ArrayList<MoveCommand>> selectExecutors(MoveConfig config, List<WorkerInfo> jobWorkerInfoList, JobMasterContext jobMasterContext) throws Exception { AlluxioURI source = new AlluxioURI(config.getSource()); AlluxioURI destination = new AlluxioURI(config.getDestination()); if (source.equals(destination)) { return new HashMap<WorkerInfo, ArrayList<MoveCommand>>(); } checkMoveValid(config); List<BlockWorkerInfo> alluxioWorkerInfoList = AlluxioBlockStore.create(mFileSystemContext).getAllWorkers(); Preconditions.checkState(!jobWorkerInfoList.isEmpty(), "No workers are available"); List<URIStatus> allPathStatuses = getPathStatuses(source); ConcurrentMap<WorkerInfo, ArrayList<MoveCommand>> assignments = Maps.newConcurrentMap(); ConcurrentMap<String, WorkerInfo> hostnameToWorker = Maps.newConcurrentMap(); for (WorkerInfo workerInfo : jobWorkerInfoList) { hostnameToWorker.put(workerInfo.getAddress().getHost(), workerInfo); } List<String> keys = new ArrayList<>(); keys.addAll(hostnameToWorker.keySet()); // Assign each file to the worker with the most block locality. for (URIStatus status : allPathStatuses) { if (status.isFolder()) { moveDirectory(status.getPath(), source.getPath(), destination.getPath()); } else { WorkerInfo bestJobWorker = getBestJobWorker(status, alluxioWorkerInfoList, jobWorkerInfoList, hostnameToWorker); String destinationPath = computeTargetPath(status.getPath(), source.getPath(), destination.getPath()); assignments.putIfAbsent(bestJobWorker, Lists.<MoveCommand>newArrayList()); assignments.get(bestJobWorker).add(new MoveCommand(status.getPath(), destinationPath)); } } return assignments; }
From source file:com.engine.QuoteServlet.java
private String lookupNearestWarehouse(String originZip) { String zip = ""; java.sql.Connection con = null; java.sql.PreparedStatement stmt = null; java.sql.ResultSet rs = null; try {/*from www. j a v a 2s . co m*/ con = ControlPanelPool.getInstance().getConnection(); stmt = con.prepareStatement("SELECT * FROM tblWarehouse WHERE Active = 1"); ConcurrentMap<String, String> warehouseZip = new ConcurrentHashMap<>(); rs = stmt.executeQuery(); while (rs.next()) { if (rs.getString("WHZIP") != null) { warehouseZip.put(rs.getString("WHZIP"), ""); } } for (String key : warehouseZip.keySet()) { if (key.matches("[0-9]+")) { URL url = new URL("http://10.1.1.58:8080/zip/distance?zip1=" + originZip + "&zip2=" + key); URLConnection conn = url.openConnection(); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; while ((inputLine = br.readLine()) != null) { warehouseZip.put(key, inputLine.substring(1, inputLine.length() - 1)); } br.close(); } } double min = 10000.0; for (String key : warehouseZip.keySet()) { if (!warehouseZip.get(key).isEmpty() && warehouseZip.get(key) != null) { if (Double.valueOf(warehouseZip.get(key)) < min) { min = Double.valueOf(warehouseZip.get(key)); zip = key; } } } con.close(); } catch (IOException | SQLException | PropertyVetoException ex) { Logger.getLogger(QuoteServlet.class.getName()).log(Level.SEVERE, null, ex); } finally { DbUtils.closeQuietly(con, stmt, rs); } return zip; }
From source file:com.murati.oszk.audiobook.model.MusicProvider.java
private Collection<MediaBrowserCompat.MediaItem> createGroupList( ConcurrentMap<String, List<String>> categoryMap, String mediaIdCategory, Uri imageUri, Resources resources) {/*from w w w . j av a 2 s . co m*/ if (mCurrentState != State.INITIALIZED) return Collections.emptyList(); TreeSet<String> sortedCategoryList = new TreeSet<String>(collator); sortedCategoryList.addAll(categoryMap.keySet()); List<MediaBrowserCompat.MediaItem> categoryList = new ArrayList<MediaBrowserCompat.MediaItem>(); for (String categoryName : sortedCategoryList) { try { MediaBrowserCompat.MediaItem browsableCategory = createGroupItem( createMediaID(null, mediaIdCategory, categoryName), categoryName, String.format(resources.getString(R.string.browse_title_count), String.valueOf(categoryMap.get(categoryName).size())), imageUri); categoryList.add(browsableCategory); } catch (Exception e) { //TODO: log } } return categoryList; }
From source file:org.opendaylight.controller.protocol_plugin.openflow.internal.TopologyServiceShim.java
/** * Update local cache and return true if it needs to notify upper layer * Topology listeners./*from w w w . j a v a2s.co m*/ * * @param container * The network container * @param edge * The edge * @param type * The update type * @param props * The edge properties * @return true if it needs to notify upper layer Topology listeners */ private boolean updateLocalEdgeMap(String container, Edge edge, UpdateType type, Set<Property> props) { ConcurrentMap<NodeConnector, Pair<Edge, Set<Property>>> edgePropsMap = edgeMap.get(container); NodeConnector src = edge.getTailNodeConnector(); Pair<Edge, Set<Property>> edgeProps = new ImmutablePair<Edge, Set<Property>>(edge, props); boolean rv = false; switch (type) { case ADDED: case CHANGED: if (edgePropsMap == null) { edgePropsMap = new ConcurrentHashMap<NodeConnector, Pair<Edge, Set<Property>>>(); rv = true; } else { if (edgePropsMap.containsKey(src) && edgePropsMap.get(src).equals(edgeProps)) { // Entry already exists. No update. rv = false; } else { rv = true; } } if (rv) { edgePropsMap.put(src, edgeProps); edgeMap.put(container, edgePropsMap); } break; case REMOVED: if ((edgePropsMap != null) && edgePropsMap.containsKey(src)) { edgePropsMap.remove(src); if (edgePropsMap.isEmpty()) { edgeMap.remove(container); } else { edgeMap.put(container, edgePropsMap); } rv = true; } break; default: logger.debug("notifyLocalEdgeMap: invalid {} for Edge {} in container {}", new Object[] { type.getName(), edge, container }); } if (rv) { logger.debug("notifyLocalEdgeMap: {} for Edge {} in container {}", new Object[] { type.getName(), edge, container }); } return rv; }
From source file:org.onosproject.store.device.impl.GossipDeviceStore.java
private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId, Timestamped<PortDescription> deltaDesc) { Device device = devices.get(deviceId); checkArgument(device != null, DEVICE_NOT_FOUND, deviceId); Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId); checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId); synchronized (descsMap) { if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) { log.debug("Ignoring outdated event: {}", deltaDesc); return null; }//from w w w .j av a 2s.co m DeviceDescriptions descs = descsMap.get(providerId); // assuming all providers must to give DeviceDescription verify(descs != null, "Device description for Device ID %s from Provider %s was not found", deviceId, providerId); ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId); final PortNumber number = deltaDesc.value().portNumber(); final Port oldPort = ports.get(number); final Port newPort; final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number); if (existingPortDesc == null || deltaDesc.isNewer(existingPortDesc)) { // on new port or valid update // update description descs.putPortDesc(deltaDesc); newPort = composePort(device, number, descsMap); } else { // same or outdated event, ignored. log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc); return null; } if (oldPort == null) { return createPort(device, newPort, ports); } else { return updatePort(device, oldPort, newPort, ports); } } }
From source file:hr.diskobolos.persistence.impl.EvaluationAnswerPersistenceImpl.java
@Override public ConcurrentMap<TermsOfConditionStatus, AtomicLong> fetchTermsOfCompetitionStatistic() { CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<EvaluationAnswer> cq = cb.createQuery(EvaluationAnswer.class); Root<EvaluationAnswer> evaluationAnswer = cq.from(EvaluationAnswer.class); Join<EvaluationAnswer, QuestionChoicesDef> choiceDef = evaluationAnswer.join(EvaluationAnswer_.answer); Join<QuestionChoicesDef, EvaluationQuestionDef> questionDef = choiceDef .join(QuestionChoicesDef_.evaluationQuestionDef); ParameterExpression<QuestionnaireType> questionnaireType = cb.parameter(QuestionnaireType.class, "questionnaireType"); cq.select(evaluationAnswer);/*from w w w .ja va2s.com*/ cq.where(cb.equal(questionDef.get(EvaluationQuestionDef_.questionnaireType), questionnaireType)); TypedQuery<EvaluationAnswer> query = entityManager.createQuery(cq); query.setParameter("questionnaireType", QuestionnaireType.TERMS_OF_CONDITION); List<EvaluationAnswer> evaluationAnswers = query.getResultList(); ConcurrentMap<TermsOfConditionStatus, AtomicLong> distributionByTermsOfCompetitionStatus = new ConcurrentHashMap<>(); List<EvaluationQuestionnaireDefEnum> questionnaireDef = Arrays .asList(EvaluationQuestionnaireDefEnum.values()); long numberOfQuestion = questionnaireDef.stream() .filter(q -> q.getQuestionnaireType().equals(QuestionnaireType.TERMS_OF_CONDITION)) .collect(Collectors.counting()); List<MemberRegister> memberRegisters = evaluationAnswers.stream() .filter(StreamUtil.distinctByKey((EvaluationAnswer e) -> e.getMemberRegister().getId())) .map(EvaluationAnswer::getMemberRegister).collect(Collectors.toList()); memberRegisters.stream().forEach((memberRegister) -> { TermsOfConditionStatus termsOfConditionStatus = TermsOfConditionStatus.NONE; if (evaluationAnswers.stream().filter(m -> m.getMemberRegister().equals(memberRegister)) .count() == numberOfQuestion) { boolean isValid = evaluationAnswers.stream() .filter(m -> m.getMemberRegister().equals(memberRegister)) .allMatch(e -> e.getAnswer().getLabel() .equals(messageSource.getMessage("QuestionChoicesDef.yes", null, Locale.ENGLISH))); termsOfConditionStatus = isValid ? TermsOfConditionStatus.VALID : TermsOfConditionStatus.INVALID; } distributionByTermsOfCompetitionStatus.putIfAbsent(termsOfConditionStatus, new AtomicLong(0)); distributionByTermsOfCompetitionStatus.get(termsOfConditionStatus).incrementAndGet(); }); return distributionByTermsOfCompetitionStatus; }
From source file:org.danann.cernunnos.DynamicCacheHelper.java
public V getCachedObject(TaskRequest req, TaskResponse res, K key, Factory<K, V> factory) { final CacheMode cacheMode = CacheMode.valueOf((String) this.cacheModelPhrase.evaluate(req, res)); if (this.logger.isDebugEnabled()) { this.logger.debug("Getting cached object for '" + key + "' using cache mode " + cacheMode + " and factory " + factory); }/*ww w. ja v a2 s . c o m*/ //Load the cache only if cache-all is enabled final ConcurrentMap<Tuple<Serializable, K>, Object> cache; final Tuple<Serializable, K> compoundCacheKey; switch (cacheMode) { case NONE: { return factory.createObject(key); } default: case ONE: { cache = null; compoundCacheKey = null; } break; case ALL: { cache = (ConcurrentMap<Tuple<Serializable, K>, Object>) this.cachePhrase.evaluate(req, res); final Serializable cacheNamespace = factory.getCacheNamespace(key); compoundCacheKey = new Tuple<Serializable, K>(cacheNamespace, key); } break; } //Determine the object to synchronize around final Object syncTarget = factory.getMutex(key); //get or create & cache the target object V instance = null; synchronized (syncTarget) { //Get the object from the local variables if no cache is available if (cache == null) { //Try for a thread-local instance first if (this.compareKeys(key, this.threadKeyHolder.get())) { instance = this.threadInstanceHolder.get(); } //Next try for a singleton instance else if (this.compareKeys(key, this.key)) { instance = this.instance; } } //Look in the passed cache for the instance else { final Object object = cache.get(compoundCacheKey); //If the cached object is a ThreadLocal use it for the instance if (object instanceof ThreadLocal<?>) { instance = ((ThreadLocal<V>) object).get(); } //If not assume it is the instance else { instance = (V) object; } } //If no instance was found create and cache one if (instance == null) { instance = factory.createObject(key); final boolean threadSafe = factory.isThreadSafe(key, instance); if (this.logger.isDebugEnabled()) { this.logger.debug( "Cache miss for '" + key + "' created '" + instance + "' threadSafe=" + threadSafe); } //If no cache is available store the instance in the local variables if (cache == null) { if (threadSafe) { this.instance = instance; this.key = key; } else { this.threadInstanceHolder.set(instance); this.threadKeyHolder.set(key); } } //Cache available store there else { if (threadSafe) { cache.put(compoundCacheKey, instance); } else { ThreadLocal<V> threadInstanceHolder = (ThreadLocal<V>) cache.get(compoundCacheKey); if (threadInstanceHolder == null) { threadInstanceHolder = new ThreadLocal<V>(); while (true) { Object existing = cache.putIfAbsent(compoundCacheKey, threadInstanceHolder); if (existing == null) { //nothing existed for that key, put was successful break; } if (existing instanceof ThreadLocal) { //Existing ThreadLocal, just use it threadInstanceHolder = (ThreadLocal) existing; break; } //something other than a ThreadLocal already exists, try replacing with the ThreadLocal final boolean replaced = cache.replace(compoundCacheKey, threadInstanceHolder, existing); if (replaced) { //Replace worked! break; } //Replace didn't work, try the whole process again, yay non-blocking! } if (cache instanceof EvictionAwareCache) { ((EvictionAwareCache) cache) .registerCacheEvictionListener(ThreadLocalCacheEvictionListener.INSTANCE); } } threadInstanceHolder.set(instance); } } } else if (this.logger.isDebugEnabled()) { this.logger.debug("Cache hit for '" + key + "' using '" + instance + "'"); } } return instance; }