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.murati.oszk.audiobook.model.MusicProvider.java

private synchronized void addMediaToCategory(MutableMediaMetadata m, String metadata,
        ConcurrentMap<String, List<String>> newListByMetadata) {
    // Get Key/* w w w  .j  a  v  a2  s.  c om*/
    String metaValueString = m.metadata.getString(metadata);

    for (String mv : metaValueString.split(",")) {

        //TODO: Client resource translations
        String key = mv.replaceAll("\\(.*\\)", "");
        if (key.matches("^(\\d+|\\.).*")) { // Numbers or dots
            Log.i(TAG, "Skipping " + key);
            continue;
        }
        key = TextHelper.Capitalize(key);
        // Get List by Key
        List<String> list = newListByMetadata.get(key);
        if (list == null) {
            list = new ArrayList<>();
            newListByMetadata.put(key, list);
        }

        // Add ebook by key
        String ebook = m.metadata.getString(MediaMetadataCompat.METADATA_KEY_ALBUM);
        if (!list.contains(ebook)) {
            list.add(ebook);
        }
    }
}

From source file:com.cubeia.firebase.server.lobby.systemstate.StateLobby.java

public String printPacketCounts() {
    ConcurrentMap<LobbyPath, Integer> fullPacketCount = new ConcurrentHashMap<LobbyPath, Integer>();
    ConcurrentMap<LobbyPath, Integer> deltaPacketCount = new ConcurrentHashMap<LobbyPath, Integer>();

    for (SnapshotGenerator generator : generators.values()) {
        ConcurrentMap<LobbyPath, FullSnapshot> fullSnapshots = generator.getFullSnapshots();
        ConcurrentMap<LobbyPath, DeltaSnapshot> deltaSnapshots = generator.getDeltaSnapshots();

        for (LobbyPath path : fullSnapshots.keySet()) {
            FullSnapshot fullSnapshot = fullSnapshots.get(path);
            fullPacketCount.put(path, fullSnapshot.getLobbyData().size());
        }/*from  w ww .  ja  v  a2s. c  om*/

        for (LobbyPath path : deltaSnapshots.keySet()) {
            DeltaSnapshot deltaSnapshot = deltaSnapshots.get(path);
            deltaPacketCount.put(path, deltaSnapshot.getLobbyData().size());
        }
    }

    String info = "Lobby Snapshots Per Chached Lobby Path\n";
    info += "-----------------------\n";
    info += "Full Packet Path Count:  " + fullPacketCount.size() + "\n";
    info += "Delta Packet Path Count: " + deltaPacketCount.size() + "\n";
    info += "-----------------------\n";
    info += "FULL PACKET COUNT PER PATH\n";
    for (LobbyPath path : fullPacketCount.keySet()) {
        info += StringUtils.rightPad(path.toString(), 60) + "\t : " + fullPacketCount.get(path) + "\n";
    }
    info += "-----------------------\n";
    info += "DELTA PACKET COUNT PER PATH\n";
    for (LobbyPath path : deltaPacketCount.keySet()) {
        info += StringUtils.rightPad(path.toString(), 60) + "\t : " + deltaPacketCount.get(path) + "\n";
        ;
    }

    return info;
}

From source file:com.epam.catgenome.manager.protein.ProteinSequenceReconstructionManager.java

/**
 * Reconstruct protein sequence for specified gene track.
 *
 * @param geneTrack   gene track/*  ww  w.j  av  a2 s  .  c  o  m*/
 * @param chromosome  chromosome
 * @param referenceId reference genome id
 * @return map of mRNA to corresponding reconstructed protein sequences
 * @throws IOException if error occurred while working with files
 */
@Transactional(propagation = Propagation.REQUIRED)
public Map<Gene, List<ProteinSequenceEntry>> reconstructProteinSequence(final Track<Gene> geneTrack,
        final Chromosome chromosome, final Long referenceId, boolean collapsedTrack)
        throws GeneReadingException {
    // Load CDS from gene file in specified interval [startIndex, endIndex].

    double time1 = Utils.getSystemTimeMilliseconds();
    Map<Gene, List<Gene>> mrnaToCdsMap = loadCds(geneTrack, chromosome, collapsedTrack);
    double time2 = Utils.getSystemTimeMilliseconds();
    LOGGER.info("loading CDS took {} ms", time2 - time1);

    time1 = Utils.getSystemTimeMilliseconds();
    ConcurrentMap<Gene, List<ProteinSequenceEntry>> mrnaToAminoAcidsMap = new ConcurrentHashMap<>();
    for (Map.Entry<Gene, List<Gene>> mrnaToCdsEntry : mrnaToCdsMap.entrySet()) {
        List<Gene> cdsList = mrnaToCdsEntry.getValue();
        List<Integer> frames = cdsList.stream().map(Gene::getFrame).collect(Collectors.toList());
        List<List<Sequence>> cdsNucleotides = loadCdsNucleatides(cdsList, referenceId, chromosome);
        if (cdsNucleotides == null) {
            continue;
        }

        // Convert nucleotide triple -> amino acid for all CDS.
        Map<Gene, List<ProteinSequenceEntry>> cdsToAminoAcidsMap = getAminoAcids(geneTrack, cdsList,
                cdsNucleotides, frames);

        List<ProteinSequenceEntry> aminoAcids = new ArrayList<>();
        cdsToAminoAcidsMap.values().stream().forEach(aminoAcids::addAll);
        mrnaToAminoAcidsMap.put(mrnaToCdsEntry.getKey(), aminoAcids);
    }
    time2 = Utils.getSystemTimeMilliseconds();
    LOGGER.info("protein sequence reconstruction took {} ms", time2 - time1);

    return mrnaToAminoAcidsMap;
}

From source file:com.networknt.light.rule.AbstractBfnRule.java

public boolean getBfnPost(Object... objects) throws Exception {
    Map<String, Object> inputMap = (Map<String, Object>) objects[0];
    Map<String, Object> data = (Map<String, Object>) inputMap.get("data");
    String rid = (String) data.get("@rid");
    String host = (String) data.get("host");
    if (rid == null) {
        inputMap.put("result", "@rid is required");
        inputMap.put("responseCode", 400);
        return false;
    }//  w ww. java2  s  . c  o m
    Integer pageSize = (Integer) data.get("pageSize");
    Integer pageNo = (Integer) data.get("pageNo");
    if (pageSize == null) {
        inputMap.put("result", "pageSize is required");
        inputMap.put("responseCode", 400);
        return false;
    }
    if (pageNo == null) {
        inputMap.put("result", "pageNo is required");
        inputMap.put("responseCode", 400);
        return false;
    }
    String sortDir = (String) data.get("sortDir");
    String sortedBy = (String) data.get("sortedBy");
    if (sortDir == null) {
        sortDir = "desc";
    }
    if (sortedBy == null) {
        sortedBy = "createDate";
    }
    boolean allowPost = false;
    Map<String, Object> payload = (Map<String, Object>) inputMap.get("payload");
    if (payload != null) {
        Map<String, Object> user = (Map<String, Object>) payload.get("user");
        List roles = (List) user.get("roles");
        if (roles.contains("owner")) {
            allowPost = true;
        } else if (roles.contains("admin") || roles.contains("blogAdmin") || roles.contains("blogUser")) {
            if (host.equals(user.get("host"))) {
                allowPost = true;
            }
        }
    }

    // TODO support the following lists: recent, popular, controversial
    // Get the page from cache.
    List<String> list = null;
    Map<String, Object> bfnMap = ServiceLocator.getInstance().getMemoryImage("bfnMap");
    ConcurrentMap<Object, Object> listCache = (ConcurrentMap<Object, Object>) bfnMap.get("listCache");
    if (listCache == null) {
        listCache = new ConcurrentLinkedHashMap.Builder<Object, Object>().maximumWeightedCapacity(1000).build();
        bfnMap.put("listCache", listCache);
    } else {
        list = (List<String>) listCache.get(rid + sortedBy);
    }

    ConcurrentMap<Object, Object> postCache = (ConcurrentMap<Object, Object>) bfnMap.get("postCache");
    if (postCache == null) {
        postCache = new ConcurrentLinkedHashMap.Builder<Object, Object>().maximumWeightedCapacity(1000).build();
        bfnMap.put("postCache", postCache);
    }

    if (list == null) {
        // get the list for db
        list = new ArrayList<String>();
        String json = getBfnPostDb(rid, sortedBy);
        if (json != null) {
            // convert json to list of maps.
            List<Map<String, Object>> posts = mapper.readValue(json,
                    new TypeReference<ArrayList<HashMap<String, Object>>>() {
                    });
            for (Map<String, Object> post : posts) {
                String postRid = (String) post.get("rid");
                list.add(postRid);
                post.remove("@rid");
                post.remove("@type");
                post.remove("@version");
                post.remove("@fieldTypes");
                postCache.put(postRid, post);
            }
        }
        listCache.put(rid + sortedBy, list);
    }
    long total = list.size();
    if (total > 0) {
        List<Map<String, Object>> posts = new ArrayList<Map<String, Object>>();
        for (int i = pageSize * (pageNo - 1); i < Math.min(pageSize * pageNo, list.size()); i++) {
            String postRid = list.get(i);
            Map<String, Object> post = (Map<String, Object>) postCache.get(postRid);
            posts.add(post);
        }
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("total", total);
        result.put("posts", posts);
        result.put("allowPost", allowPost);
        inputMap.put("result", mapper.writeValueAsString(result));
        return true;
    } else {
        // there is no post available. but still need to return allowPost
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("total", 0);
        result.put("allowPost", allowPost);
        inputMap.put("result", mapper.writeValueAsString(result));
        return true;
    }
}

From source file:org.onebusaway.transit_data_federation.impl.service_alerts.ServiceAlertsServiceImpl.java

private <T> void updateReferences(ServiceAlert existingServiceAlert, ServiceAlert serviceAlert,
        ConcurrentMap<T, Set<AgencyAndId>> map, AffectsKeyFactory<T> affectsKeyFactory) {

    Set<T> existingEffects = Collections.emptySet();
    if (existingServiceAlert != null) {
        existingEffects = affectsKeyFactory.getKeysForAffects(existingServiceAlert);
    }/*from  ww  w .jav  a  2s  . c om*/

    Set<T> newEffects = Collections.emptySet();
    if (serviceAlert != null) {
        newEffects = affectsKeyFactory.getKeysForAffects(serviceAlert);
    }

    for (T existingEffect : existingEffects) {
        if (newEffects.contains(existingEffect))
            continue;
        AgencyAndId id = ServiceAlertLibrary.agencyAndId(existingServiceAlert.getId());
        Set<AgencyAndId> ids = map.get(existingEffect);
        ids.remove(id);
        if (ids.isEmpty())
            map.remove(existingEffect);
    }

    for (T newEffect : newEffects) {
        if (existingEffects.contains(newEffect))
            continue;
        AgencyAndId id = ServiceAlertLibrary.agencyAndId(serviceAlert.getId());
        Set<AgencyAndId> ids = map.get(newEffect);
        if (ids == null) {
            ids = new HashSet<AgencyAndId>();
            map.put(newEffect, ids);
        }
        ids.add(id);
    }
}

From source file:com.networknt.light.rule.catalog.AbstractCatalogRule.java

public boolean getCatalogProduct(Object... objects) throws Exception {
    Map<String, Object> inputMap = (Map<String, Object>) objects[0];
    Map<String, Object> data = (Map<String, Object>) inputMap.get("data");
    String rid = (String) data.get("@rid");
    String host = (String) data.get("host");
    if (rid == null) {
        inputMap.put("result", "@rid is required");
        inputMap.put("responseCode", 400);
        return false;
    }// w  w  w .  j  a v  a2  s .  c  om
    Integer pageSize = (Integer) data.get("pageSize");
    Integer pageNo = (Integer) data.get("pageNo");
    if (pageSize == null) {
        inputMap.put("result", "pageSize is required");
        inputMap.put("responseCode", 400);
        return false;
    }
    if (pageNo == null) {
        inputMap.put("result", "pageNo is required");
        inputMap.put("responseCode", 400);
        return false;
    }
    String sortDir = (String) data.get("sortDir");
    String sortedBy = (String) data.get("sortedBy");
    if (sortDir == null) {
        sortDir = "desc";
    }
    if (sortedBy == null) {
        sortedBy = "createDate";
    }
    boolean allowAdd = false;
    Map<String, Object> payload = (Map<String, Object>) inputMap.get("payload");
    if (payload != null) {
        Map<String, Object> user = (Map<String, Object>) payload.get("user");
        List roles = (List) user.get("roles");
        if (roles.contains("owner")) {
            allowAdd = true;
        } else if (roles.contains("admin") || roles.contains("catalogAdmin")
                || roles.contains("productAdmin")) {
            if (host.equals(user.get("host"))) {
                allowAdd = true;
            }
        }
    }

    // TODO support the following lists: recent, popular
    // Get the page from cache.
    List<String> list = null;
    Map<String, Object> branchMap = ServiceLocator.getInstance().getMemoryImage("branchMap");
    ConcurrentMap<Object, Object> listCache = (ConcurrentMap<Object, Object>) branchMap.get("listCache");
    if (listCache == null) {
        listCache = new ConcurrentLinkedHashMap.Builder<Object, Object>().maximumWeightedCapacity(1000).build();
        branchMap.put("listCache", listCache);
    } else {
        list = (List<String>) listCache.get(rid + sortedBy);
    }

    ConcurrentMap<Object, Object> productCache = (ConcurrentMap<Object, Object>) branchMap.get("productCache");
    if (productCache == null) {
        productCache = new ConcurrentLinkedHashMap.Builder<Object, Object>().maximumWeightedCapacity(1000)
                .build();
        branchMap.put("productCache", productCache);
    }

    if (list == null) {
        // get the list for db
        list = new ArrayList<String>();
        String json = getCatalogProductDb(rid, sortedBy);
        if (json != null) {
            // convert json to list of maps.
            List<Map<String, Object>> products = mapper.readValue(json,
                    new TypeReference<ArrayList<HashMap<String, Object>>>() {
                    });
            for (Map<String, Object> product : products) {
                String productRid = (String) product.get("rid");
                list.add(productRid);
                product.remove("@rid");
                product.remove("@type");
                product.remove("@version");
                product.remove("@fieldTypes");
                productCache.put(productRid, product);
            }
        }
        listCache.put(rid + sortedBy, list);
    }
    long total = list.size();
    if (total > 0) {
        List<Map<String, Object>> products = new ArrayList<Map<String, Object>>();
        for (int i = pageSize * (pageNo - 1); i < Math.min(pageSize * pageNo, list.size()); i++) {
            String productRid = list.get(i);
            Map<String, Object> product = (Map<String, Object>) productCache.get(productRid);
            products.add(product);
        }
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("total", total);
        result.put("products", products);
        result.put("allowAdd", allowAdd);
        inputMap.put("result", mapper.writeValueAsString(result));
        return true;
    } else {
        // there is no product available. but still need to return allowAdd
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("total", 0);
        result.put("allowAdd", allowAdd);
        inputMap.put("result", mapper.writeValueAsString(result));
        return true;
    }
}

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./* ww  w . j ava2s .com*/
 *
 * @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.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  www.j a v  a2  s  .  c om*/
    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:edu.illinois.cs.cogcomp.pipeline.server.ServerClientAnnotator.java

/**
 * The method is synchronized since the caching seems to have issues upon mult-threaded caching
 * @param overwrite if true, it would overwrite the values on cache
 *///from  w  w w.j av a 2  s.  c o m
public synchronized TextAnnotation annotate(String str, boolean overwrite) throws Exception {
    String viewsConnected = Arrays.toString(viewsToAdd);
    String views = viewsConnected.substring(1, viewsConnected.length() - 1).replace(" ", "");
    ConcurrentMap<String, byte[]> concurrentMap = (db != null)
            ? db.hashMap(viewName, Serializer.STRING, Serializer.BYTE_ARRAY).createOrOpen()
            : null;
    String key = DigestUtils.sha1Hex(str + views);
    if (!overwrite && concurrentMap != null && concurrentMap.containsKey(key)) {
        byte[] taByte = concurrentMap.get(key);
        return SerializationHelper.deserializeTextAnnotationFromBytes(taByte);
    } else {
        URL obj = new URL(url + ":" + port + "/annotate");
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("charset", "utf-8");
        con.setRequestProperty("Content-Type", "text/plain; charset=utf-8");

        con.setDoOutput(true);
        con.setUseCaches(false);

        OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
        wr.write("text=" + URLEncoder.encode(str, "UTF-8") + "&views=" + views);
        wr.flush();

        InputStreamReader reader = new InputStreamReader(con.getInputStream());
        BufferedReader in = new BufferedReader(reader);
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        reader.close();
        wr.close();
        con.disconnect();
        TextAnnotation ta = SerializationHelper.deserializeFromJson(response.toString());
        if (concurrentMap != null) {
            concurrentMap.put(key, SerializationHelper.serializeTextAnnotationToBytes(ta));
            this.db.commit();
        }
        return ta;
    }
}

From source file:com.github.podd.example.ExamplePoddClient.java

/**
 * @param potUriMap//from   w w  w .j  a  v  a 2 s .co  m
 * @param plantId
 * @param nextProjectID
 * @param nextTrayURI
 * @return
 * @throws PoddClientException
 * @throws GraphUtilException
 */
private URI getPotUri(final ConcurrentMap<String, ConcurrentMap<URI, URI>> potUriMap, final String plantId,
        final InferredOWLOntologyID nextProjectID, final URI nextTrayURI)
        throws PoddClientException, GraphUtilException {
    URI nextPotURI;
    if (potUriMap.containsKey(plantId)) {
        nextPotURI = potUriMap.get(plantId).keySet().iterator().next();
    } else {
        final Model plantIdSparqlResults = this.doSPARQL(
                String.format(ExampleSpreadsheetConstants.TEMPLATE_SPARQL_BY_TYPE_LABEL_STRSTARTS,
                        RenderUtils.escape(plantId), RenderUtils.getSPARQLQueryString(PODD.PODD_SCIENCE_POT)),
                Arrays.asList(nextProjectID));

        if (plantIdSparqlResults.isEmpty()) {
            this.log.debug(
                    "Could not find an existing container for pot barcode, assigning a temporary URI: {} {}",
                    plantId, nextProjectID);

            nextPotURI = RestletPoddClientImpl.vf
                    .createURI(RestletPoddClientImpl.TEMP_UUID_PREFIX + "pot:" + UUID.randomUUID().toString());
        } else {
            nextPotURI = GraphUtil.getUniqueSubjectURI(plantIdSparqlResults, RDF.TYPE, PODD.PODD_SCIENCE_POT);
        }

        ConcurrentMap<URI, URI> nextPotUriMap = new ConcurrentHashMap<>();
        final ConcurrentMap<URI, URI> putIfAbsent2 = potUriMap.putIfAbsent(plantId, nextPotUriMap);
        if (putIfAbsent2 != null) {
            nextPotUriMap = putIfAbsent2;
        }
        nextPotUriMap.put(nextPotURI, nextTrayURI);
    }
    return nextPotURI;
}