Example usage for java.util.concurrent ConcurrentMap put

List of usage examples for java.util.concurrent ConcurrentMap put

Introduction

In this page you can find the example usage for java.util.concurrent ConcurrentMap put.

Prototype

V put(K key, V value);

Source Link

Document

Associates the specified value with the specified key in this map (optional operation).

Usage

From source file:com.romeikat.datamessie.core.base.util.CollectionUtil.java

public <K, V1, V2> ConcurrentMap<K, V2> transformMap(final Map<K, V1> map,
        final Function<V1, V2> transformation) {
    final List<K> indexes = new ArrayList<K>(map.keySet());
    final ConcurrentMap<K, V2> transformedMap = new ConcurrentHashMap<K, V2>();
    new ParallelProcessing<K>(null, indexes) {
        @Override//w  w w .  j  a  v  a2s  . c  o  m
        public void doProcessing(final HibernateSessionProvider sessionProvider, final K index) {
            final V1 value1 = map.get(index);
            final V2 value2;
            try {
                value2 = transformation.apply(value1);
            } catch (final InvalidValueException e) {
                return;
            }
            transformedMap.put(index, value2);
        }
    };
    return transformedMap;
}

From source file:com.networknt.light.rule.validation.AbstractValidationRule.java

public static JsonSchema getSchema(String ruleClass) throws Exception {
    JsonSchema schema = null;//from   ww  w .  ja v a 2  s  . co m
    Map<String, Object> ruleMap = ServiceLocator.getInstance().getMemoryImage("ruleMap");
    ConcurrentMap<Object, Object> cache = (ConcurrentMap<Object, Object>) ruleMap.get("cache");
    if (cache == null) {
        cache = new ConcurrentLinkedHashMap.Builder<Object, Object>().maximumWeightedCapacity(1000).build();
        ruleMap.put("cache", cache);
    } else {
        Map<String, Object> rule = (Map<String, Object>) cache.get(ruleClass);
        if (rule != null) {
            schema = (JsonSchema) rule.get("schema");
        }
    }
    if (schema == null) {
        OrientGraph graph = ServiceLocator.getInstance().getGraph();
        try {
            OIndex<?> validationRuleClassIdx = graph.getRawGraph().getMetadata().getIndexManager()
                    .getIndex("Validation.ruleClass");
            OIdentifiable oid = (OIdentifiable) validationRuleClassIdx.get(ruleClass);
            if (oid != null) {
                ODocument validation = (ODocument) oid.getRecord();
                String json = validation.toJSON();
                JsonNode validationNode = ServiceLocator.getInstance().getMapper().readTree(json);
                JsonNode schemaNode = validationNode.get("schema");
                schema = factory.getJsonSchema(schemaNode);
                Map<String, Object> rule = (Map<String, Object>) cache.get(ruleClass);
                if (rule != null) {
                    rule.put("schema", schema);
                } else {
                    rule = new HashMap<String, Object>();
                    rule.put("schema", schema);
                    cache.put(ruleClass, rule);
                }
            } else {
                // could not find the rule validation schema from db. put null in cache so that
                // the next operation won't check db again.
                Map<String, Object> rule = (Map<String, Object>) cache.get(ruleClass);
                if (rule != null) {
                    rule.put("schema", null);
                } else {
                    rule = new HashMap<String, Object>();
                    rule.put("schema", null);
                    cache.put(ruleClass, rule);
                }
            }
        } catch (Exception e) {
            logger.error("Exception:", e);
            throw e;
        } finally {
            graph.shutdown();
        }
    }
    return schema;
}

From source file:org.elasticsoftware.sip.SipChannelFactoryImpl.java

private Channel assureOpen(ConcurrentMap<String, Channel> cache, SipUser user) {

    // check is channel is open
    Channel c = cache.get(key(user));
    if (c != null && c.isConnected() && c.isOpen()) {
        if (log.isDebugEnabled()) {
            log.debug(String.format("assureOpen. Cache hit [%s]", key(user)));
        }/*  ww w .j a  v a 2  s .  co m*/
        return c;
    }

    try {
        if (log.isDebugEnabled()) {
            log.debug(String.format("assureOpen. Connecting address[%s:%d]", user.getDomain(), user.getPort()));
        }
        c = createChannel(user.getDomain(), user.getPort());
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
    cache.put(key(user), c);
    return c;
}

From source file:com.torrenttunes.android.model.MusicProvider.java

private synchronized void buildListsByArtist() {
    ConcurrentMap<String, List<MediaMetadataCompat>> newMusicListByArtist = new ConcurrentHashMap<>();

    for (MutableMediaMetadataCompat m : mMusicListById.values()) {
        String artistMBID = m.metadata.getString(MediaMetadataCompat.METADATA_KEY_ARTIST);
        List<MediaMetadataCompat> list = newMusicListByArtist.get(artistMBID);
        if (list == null) {
            list = new ArrayList<>();
            newMusicListByArtist.put(artistMBID, list);
        }/*w w  w .ja v  a2 s.  co  m*/
        list.add(m.metadata);
    }
    mMusicListByArtist = newMusicListByArtist;
}

From source file:com.networknt.light.rule.product.AbstractProductRule.java

protected Map<String, Object> refreshCache(String host) {
    Map<String, Object> productMap = (Map<String, Object>) ServiceLocator.getInstance()
            .getMemoryImage("productMap");
    Map<String, Object> criteria = new HashMap<String, Object>();
    criteria.put("host", host);
    criteria.put("sortedBy", "updateDate");
    criteria.put("sortDir", "DESC");
    List<ODocument> products = searchProductDb(criteria);
    Map<String, Object> hostMap = new ConcurrentHashMap<String, Object>(2, 0.9f, 1);
    List<String> newList = new ArrayList<String>();
    ConcurrentMap<Object, Object> cache = (ConcurrentMap<Object, Object>) productMap.get("cache");
    if (cache == null) {
        cache = new ConcurrentLinkedHashMap.Builder<Object, Object>().maximumWeightedCapacity(1000).build();
        productMap.put("cache", cache);
    }//from ww w. java2 s . c  o m
    int i = 0;
    int pageSize = 2; // TODO get from config
    for (ODocument product : products) {
        // cache the first page for now. most people will read the first page as it contains
        // new posts.
        if (i < pageSize) {
            cache.put(product.field("@rid").toString(), product);
        }
        newList.add(product.field("@rid").toString());
    }
    hostMap.put("newList", newList);

    // TODO build hot list

    productMap.put(host, hostMap);
    return hostMap;
}

From source file:at.alladin.rmbt.android.util.CheckSettingsTask.java

/**
* 
*//* w  w  w.  j  a  va  2 s  .  c o  m*/
@Override
protected void onPostExecute(final JSONArray resultList) {
    try {
        if (serverConn.hasError())
            hasError = true;
        else if (resultList != null && resultList.length() > 0) {

            JSONObject resultListItem;

            try {
                resultListItem = resultList.getJSONObject(0);

                /* UUID */

                final String uuid = resultListItem.optString("uuid", "");
                if (uuid != null && uuid.length() != 0)
                    ConfigHelper.setUUID(activity.getApplicationContext(), uuid);

                /* urls */

                final ConcurrentMap<String, String> volatileSettings = ConfigHelper.getVolatileSettings();

                final JSONObject urls = resultListItem.optJSONObject("urls");
                if (urls != null) {
                    final Iterator<String> keys = urls.keys();

                    while (keys.hasNext()) {
                        final String key = keys.next();
                        final String value = urls.optString(key, null);
                        if (value != null) {
                            volatileSettings.put("url_" + key, value);
                            if ("statistics".equals(key)) {
                                ConfigHelper.setCachedStatisticsUrl(value, activity);
                            } else if ("control_ipv4_only".equals(key)) {
                                ConfigHelper.setCachedControlServerNameIpv4(value, activity);
                            } else if ("control_ipv6_only".equals(key)) {
                                ConfigHelper.setCachedControlServerNameIpv6(value, activity);
                            } else if ("url_ipv4_check".equals(key)) {
                                ConfigHelper.setCachedIpv4CheckUrl(value, activity);
                            } else if ("url_ipv6_check".equals(key)) {
                                ConfigHelper.setCachedIpv6CheckUrl(value, activity);
                            }
                        }
                    }
                }

                /* qos names */
                final JSONArray qosNames = resultListItem.optJSONArray("qostesttype_desc");
                if (qosNames != null) {
                    final Map<String, String> qosNamesMap = new HashMap<String, String>();
                    for (int i = 0; i < qosNames.length(); i++) {
                        JSONObject json = qosNames.getJSONObject(i);
                        qosNamesMap.put(json.optString("test_type"), json.optString("name"));
                    }
                    ConfigHelper.setCachedQoSNames(qosNamesMap, activity);
                }

                /* map server */

                final JSONObject mapServer = resultListItem.optJSONObject("map_server");
                if (mapServer != null) {
                    final String host = mapServer.optString("host");
                    final int port = mapServer.optInt("port");
                    final boolean ssl = mapServer.optBoolean("ssl");
                    if (host != null && port > 0)
                        ConfigHelper.setMapServer(host, port, ssl);
                }

                /* control server version */
                final JSONObject versions = resultListItem.optJSONObject("versions");
                if (versions != null) {
                    if (versions.has("control_server_version")) {
                        ConfigHelper.setControlServerVersion(activity,
                                versions.optString("control_server_version"));
                    }
                }

                // ///////////////////////////////////////////////////////
                // HISTORY / FILTER

                final JSONObject historyObject = resultListItem.getJSONObject("history");

                final JSONArray deviceArray = historyObject.getJSONArray("devices");
                final JSONArray networkArray = historyObject.getJSONArray("networks");

                final String historyDevices[] = new String[deviceArray.length()];

                for (int i = 0; i < deviceArray.length(); i++)
                    historyDevices[i] = deviceArray.getString(i);

                final String historyNetworks[] = new String[networkArray.length()];

                for (int i = 0; i < networkArray.length(); i++)
                    historyNetworks[i] = networkArray.getString(i);

                // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////

                activity.setSettings(historyDevices, historyNetworks);

                activity.setHistoryDirty(true);

            } catch (final JSONException e) {
                e.printStackTrace();
            }

        } else
            Log.i(DEBUG_TAG, "LEERE LISTE");
    } finally {
        if (endTaskListener != null)
            endTaskListener.taskEnded(resultList);
    }
}

From source file:com.palantir.atlasdb.transaction.impl.SerializableTransaction.java

private void setRangeEnd(String table, RangeRequest range, byte[] maxRow) {
    Validate.notNull(maxRow);// w  ww  .  j a v a 2s.c o  m
    ConcurrentMap<RangeRequest, byte[]> rangeEnds = rangeEndByTable.get(table);
    if (rangeEnds == null) {
        ConcurrentMap<RangeRequest, byte[]> newMap = Maps.newConcurrentMap();
        rangeEndByTable.putIfAbsent(table, newMap);
        rangeEnds = rangeEndByTable.get(table);
    }

    if (maxRow.length == 0) {
        rangeEnds.put(range, maxRow);
    }

    while (true) {
        byte[] curVal = rangeEnds.get(range);
        if (curVal == null) {
            byte[] oldVal = rangeEnds.putIfAbsent(range, maxRow);
            if (oldVal == null) {
                return;
            } else {
                continue;
            }
        }
        if (curVal.length == 0) {
            return;
        }
        if (UnsignedBytes.lexicographicalComparator().compare(curVal, maxRow) >= 0) {
            return;
        }
        if (rangeEnds.replace(range, curVal, maxRow)) {
            return;
        }
    }
}

From source file:com.sm.store.loader.ThreadLoader.java

public Object loadClass(ConcurrentMap<String, ServiceClass> serviceMap, String className) {
    boolean isGroovy = ServiceClass.isGroovyScript(className);
    try {//from  w  w w.  jav a  2  s .  c  o  m
        logger.info("Put " + className + " into serviceMap");
        Object instance;
        String url = null;
        if (isGroovy) {
            //String scriptPath = System.getProperty("scriptPath", "./config/script")+"/";
            logger.info("script path " + scriptPath + " class name " + className);
            url = new File(scriptPath + className).getCanonicalPath();
            instance = loadGroovyClass(new File(url));
            ServiceClass service = new ServiceClass(null, instance);
            service.setUrl(url);
            serviceMap.put(className, service);
        } else {
            instance = loadJavaClass(className);
            //serviceMap.put( name, instance );
            Method[] methods = instance.getClass().getDeclaredMethods();
            for (Method method : methods) {
                if (serviceMap.containsKey(className + "." + method.getName()))
                    continue;
                ServiceClass service = new ServiceClass(method, instance);
                serviceMap.put(className + "." + method.getName(), service);
                logger.info("Put " + className + "." + method.getName() + " into methodMap");
            }
        }
        logger.info("setting store nameMap for " + className);
        return instance;
    } catch (Exception ex) {
        throw new RuntimeException(ex.getMessage(), ex);
    }
}

From source file:com.romeikat.datamessie.core.rss.task.rssCrawling.SourceCrawler.java

private ConcurrentMap<String, DownloadResult> downloadEntries(final long sourceId, final Set<String> urls) {
    final ConcurrentMap<String, DownloadResult> downloadResults = new ConcurrentHashMap<String, DownloadResult>();

    final List<String> urlsList = Lists.newArrayList(urls);
    new ParallelProcessing<String>(null, urlsList, documentsParallelismFactor) {
        @Override/*  w w  w  .  j  av  a2 s .  c  o  m*/
        public void doProcessing(final HibernateSessionProvider sessionProvider, final String url) {
            try {
                LOG.debug("Source {}: downloading {}", sourceId, url);

                final DownloadResult downloadResult = contentDownloader.downloadContent(url);
                downloadResults.put(url, downloadResult);
            } catch (final Exception e) {
                LOG.error(String.format("Source %s: could not download URL %s", sourceId, url), e);
            }
        }
    };

    return downloadResults;
}

From source file:org.onosproject.store.trivial.SimpleGroupStore.java

/**
 * Updates the existing group entry with the information
 * from group description.//from   w w  w  . java 2s.  co m
 *
 * @param deviceId the device ID
 * @param oldAppCookie the current group key
 * @param type update type
 * @param newBuckets group buckets for updates
 * @param newAppCookie optional new group key
 */
@Override
public void updateGroupDescription(DeviceId deviceId, GroupKey oldAppCookie, UpdateType type,
        GroupBuckets newBuckets, GroupKey newAppCookie) {
    // Check if a group is existing with the provided key
    Group oldGroup = getGroup(deviceId, oldAppCookie);
    if (oldGroup == null) {
        return;
    }

    List<GroupBucket> newBucketList = getUpdatedBucketList(oldGroup, type, newBuckets);
    if (newBucketList != null) {
        // Create a new group object from the old group
        GroupBuckets updatedBuckets = new GroupBuckets(newBucketList);
        GroupKey newCookie = (newAppCookie != null) ? newAppCookie : oldAppCookie;
        GroupDescription updatedGroupDesc = new DefaultGroupDescription(oldGroup.deviceId(), oldGroup.type(),
                updatedBuckets, newCookie, oldGroup.givenGroupId(), oldGroup.appId());
        StoredGroupEntry newGroup = new DefaultGroup(oldGroup.id(), updatedGroupDesc);
        newGroup.setState(GroupState.PENDING_UPDATE);
        newGroup.setLife(oldGroup.life());
        newGroup.setPackets(oldGroup.packets());
        newGroup.setBytes(oldGroup.bytes());
        // Remove the old entry from maps and add new entry using new key
        ConcurrentMap<GroupKey, StoredGroupEntry> keyTable = getGroupKeyTable(oldGroup.deviceId());
        ConcurrentMap<GroupId, StoredGroupEntry> idTable = getGroupIdTable(oldGroup.deviceId());
        keyTable.remove(oldGroup.appCookie());
        idTable.remove(oldGroup.id());
        keyTable.put(newGroup.appCookie(), newGroup);
        idTable.put(newGroup.id(), newGroup);
        notifyDelegate(new GroupEvent(Type.GROUP_UPDATE_REQUESTED, newGroup));
    }
}