Example usage for java.util.concurrent ConcurrentMap containsKey

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

Introduction

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

Prototype

boolean containsKey(Object key);

Source Link

Document

Returns true if this map contains a mapping for the specified key.

Usage

From source file:com.sastix.cms.server.services.cache.hazelcast.HazelcastCacheService.java

@Override
public void removeCachedResource(RemoveCacheDTO removeCacheDTO) throws DataNotFound, CacheValidationException {
    LOG.info("HazelcastCacheService->removeCachedResource");
    nullValidationChecker(removeCacheDTO, RemoveCacheDTO.class);
    String cacheKey = removeCacheDTO.getCacheKey();
    String cacheRegion = removeCacheDTO.getCacheRegion();

    if (cacheKey == null) {
        throw new CacheValidationException("You cannot remove a cached a resource with a null cache key");
    }/*from   w  w w  .  j  ava  2  s  . co m*/

    if (!StringUtils.isEmpty(cacheRegion)) {
        ConcurrentMap<String, String> cMap = cm.getCache(cacheRegion);
        if (cMap.containsKey(cacheKey)) {
            cMap.remove(cacheKey);
        } else {
            throw new DataNotFound(
                    "Nothing to remove. There is no cached resource with the given key: " + cacheKey);
        }
    } else {
        if (this.cache.containsKey(cacheKey)) {
            this.cache.remove(cacheKey);
        } else {
            throw new DataNotFound(
                    "Nothing to remove. There is no cached resource with the given key: " + cacheKey);
        }
    }
}

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   ww w . j  a va  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:org.jasig.portlet.proxy.service.web.HttpContentRequestImpl.java

public HttpContentRequestImpl(PortletRequest request, IExpressionProcessor expressionProcessor) {
    this();/* w  w  w .j  a  v a2s.  co  m*/

    // If a URL parameter has been specified, check to make sure that it's
    // one that the portlet rewrote (we want to prevent this portlet from
    // acting as an open proxy).  If we did rewrite this URL, set the URL
    // to be proxied to the requested one
    final String urlParam = request.getParameter(HttpContentServiceImpl.URL_PARAM);
    if (urlParam != null) {
        final PortletSession session = request.getPortletSession();
        @SuppressWarnings("unchecked")
        final ConcurrentMap<String, String> rewrittenUrls = (ConcurrentMap<String, String>) session
                .getAttribute(URLRewritingFilter.REWRITTEN_URLS_KEY);
        if (!rewrittenUrls.containsKey(urlParam)) {
            throw new RuntimeException("Illegal URL " + urlParam);
        }

        setProxiedLocation(expressionProcessor.process(urlParam, request));
    }

    // otherwise use the default starting URL for this proxy portlet
    else {
        final PortletPreferences preferences = request.getPreferences();
        String location = null;
        if (WindowState.MAXIMIZED.equals(request.getWindowState())) {
            location = preferences.getValue(CONTENT_LOCATION_MAXIMIZED_PREFERENCE, null);
        }
        if (location == null || location.length() == 0) {
            location = preferences.getValue(CONTENT_LOCATION_PREFERENCE, null);
        }
        String url = expressionProcessor.process(location, request);

        setProxiedLocation(url);
    }

    final Map<String, String[]> params = request.getParameterMap();
    for (Map.Entry<String, String[]> param : params.entrySet()) {
        if (!param.getKey().startsWith(HttpContentServiceImpl.PROXY_PORTLET_PARAM_PREFIX)) {
            IFormField formField = new FormFieldImpl(param.getKey(), param.getValue());
            this.parameters.put(param.getKey(), formField);
        }
    }

    this.isForm = Boolean.valueOf(request.getParameter(HttpContentServiceImpl.IS_FORM_PARAM));
    this.method = request.getParameter(HttpContentServiceImpl.FORM_METHOD_PARAM);

    this.httpContext = HttpClientContext.create();

}

From source file:com.enonic.cms.web.portal.services.UserServicesAccessManagerImpl.java

private void parseAndAddRules(String accessRules, AccessPermission accessPermission,
        ConcurrentMap<String, AccessPermission> siteRules, SiteKey site) {
    accessRules = StringUtils.trimToEmpty(accessRules);
    String[] ruleItems = accessRules.split(",");
    for (String ruleItem : ruleItems) {
        ruleItem = ruleItem.trim();//from w w  w.  ja  v  a2  s  . co  m
        if (ruleItem.isEmpty()) {
            continue;
        }
        if (siteRules.containsKey(ruleItem)) {
            throw new IllegalArgumentException(
                    "Duplicated value for http service access rule '" + ruleItem + "' on site " + site);
        }
        siteRules.put(ruleItem, accessPermission);
    }
}

From source file:com.sworddance.beans.BeanWorker.java

/**
 * @param clazz/*from  w  ww.j  av  a  2s. co  m*/
 * @param propMap
 * @param propertyName
 * @param readOnly if true and if propertyMethodChain has not been found then only the get method is searched for.
 * @return the propertyMethodChain
 * @throws ApplicationIllegalArgumentException if the propertyName is not actually a property.
 */
protected PropertyMethodChain addPropertyMethodChainIfAbsent(Class<?> clazz,
        ConcurrentMap<String, PropertyMethodChain> propMap, String propertyName, boolean readOnly)
        throws ApplicationIllegalArgumentException {
    if (!propMap.containsKey(propertyName)) {
        List<PropertyMethodChain> propertyMethodChains = newPropertyMethodChain(clazz, propertyName, readOnly,
                allowIntermediateProperties);
        ApplicationIllegalArgumentException.valid(isNotEmpty(propertyMethodChains), clazz,
                " has no property named '", propertyName, "'");
        for (PropertyMethodChain propertyMethodChain : propertyMethodChains) {
            propMap.putIfAbsent(propertyMethodChain.getProperty(), propertyMethodChain);
        }
    } else {
        // TODO: check to see if readOnly is false
    }
    return propMap.get(propertyName);
}

From source file:com.censoredsoftware.infractions.bukkit.legacy.CommandHandler.java

@Override
public boolean onCommand(CommandSender sender, Command c, String label, String[] args) {
    Player p = null;// w ww  .  j  a  va 2 s. com
    if (sender instanceof Player)
        p = (Player) sender;
    if (c.getName().equalsIgnoreCase("infractions")) {
        MiscUtil.sendMessage(p, "---------------");
        MiscUtil.sendMessage(p, "INFRACTIONS HELP");
        MiscUtil.sendMessage(p, "---------------");
        if (MiscUtil.hasPermissionOrOP(p, "infractions.mod")) {
            MiscUtil.sendMessage(p, ChatColor.GRAY + "  /cite <player> <infraction> [proof-url]");
            MiscUtil.sendMessage(p, ChatColor.GRAY + "  /uncite <player> <key>" + ChatColor.WHITE
                    + " - Find the key with " + ChatColor.YELLOW + "/history" + ChatColor.WHITE + ".");
        }
        MiscUtil.sendMessage(p, ChatColor.GRAY + "  /history [player]");
        MiscUtil.sendMessage(p,
                ChatColor.GRAY + "  /reasons " + ChatColor.WHITE + "- Shows all valid infraction reasons.");
        MiscUtil.sendMessage(p,
                ChatColor.GRAY + "  /virtues " + ChatColor.WHITE + "- Shows all valid virtue types.");
        return true;
    } else if (c.getName().equalsIgnoreCase("reasons")) {
        MiscUtil.sendMessage(p, "------------------");
        MiscUtil.sendMessage(p, "INFRACTION REASONS");
        MiscUtil.sendMessage(p, "------------------");

        for (int i = 1; i < 6; i++) {
            MiscUtil.sendMessage(p,
                    (i < 3 ? ChatColor.GREEN : i < 5 ? ChatColor.YELLOW : ChatColor.RED) + "Level " + i + ":");
            for (int j = 0; j < SettingUtil.getLevel(i).size(); j++)
                MiscUtil.sendMessage(p, "  " + SettingUtil.getLevel(i).get(j));
        }
        return true;
    } else if (c.getName().equalsIgnoreCase("cite")) {
        if (!MiscUtil.hasPermissionOrOP(p, "infractions.mod")) {
            MiscUtil.sendMessage(p, "You do not have enough permissions.");
            return true;
        }
        if (SettingUtil.getSettingBoolean("require_proof")) {
            if ((args.length != 3)) {
                MiscUtil.sendMessage(p, "You must provide a valid URL as proof.");
                return false;
            }
            if (!URLUtil.isValidURL(args[2])) {
                MiscUtil.sendMessage(p, "You must provide a valid URL as proof.");
                return false;
            }
        }
        if (args.length == 0 || args.length == 1) {
            MiscUtil.sendMessage(p, "Not enough arguments.");
            return false;
        }

        if (Infractions.getCompleteDossier(args[0]) == null) {
            MiscUtil.sendMessage(p, "This player hasn't joined yet.");
            return true;
        }
        // Levels
        Integer level = SettingUtil.getLevel(args[1]);
        if (level != null) {
            if (args.length == 3) {
                if (!URLUtil.isValidURL(args[2])) {
                    MiscUtil.sendMessage(p, "You must provide a valid URL as proof.");
                    return false;
                }
                MiscUtil.addInfraction(MiscUtil.getInfractionsPlayer(args[0]), sender, level, args[1],
                        URLUtil.convertURL(args[2]));
            } else {
                MiscUtil.addInfraction(MiscUtil.getInfractionsPlayer(args[0]), sender, level, args[1],
                        "No proof.");
            }
            MiscUtil.sendMessage(p, ChatColor.GOLD + "Success! " + ChatColor.WHITE + "The level " + level
                    + " infraction has been received.");
            MiscUtil.kickNotify(MiscUtil.getInfractionsPlayer(args[0]), args[1]);
            return true;
        }
    } else if (c.getName().equalsIgnoreCase("uncite")) {
        if (!(args.length == 2)) {
            MiscUtil.sendMessage(p, "Not enough arguments.");
            return false;
        }
        if (!MiscUtil.hasPermissionOrOP(p, "infractions.mod")) {
            MiscUtil.sendMessage(p, "You do not have enough permissions.");
            return true;
        }

        if (MiscUtil.removeInfraction(MiscUtil.getInfractionsPlayer(args[0]), args[1])) {
            MiscUtil.sendMessage(p, "Infraction removed!");
            try {
                MiscUtil.checkScore(MiscUtil.getInfractionsPlayer(args[0]));
            } catch (NullPointerException e) {
                // player is offline
            }
            return true;
        }
        MiscUtil.sendMessage(p, "No such infraction.");
        return true;
    } else if (c.getName().equalsIgnoreCase("history")) {
        if (!(args.length == 1) && !(p == null)) {
            if (MiscUtil.ignore(p)) {
                sender.sendMessage(ChatColor.YELLOW + "Infractions does not track your history.");
                return true;
            }

            p.performCommand("history " + p.getName());
            return true;
        }
        if ((p == null) && !(args.length == 1)) {
            log.info("You must provide a username in the console.");
            return false;
        }

        if (!MiscUtil.hasPermissionOrOP(p, "infractions.mod") && !p.getName().toLowerCase().equals(args[0])) {
            p.sendMessage(ChatColor.RED + "You don't have permission to do that.");
            return true;
        }

        /**
         * DISPLAY ALL CURRENT INFRACTIONS
         */

        String player = MiscUtil.getInfractionsPlayer(args[0]);
        if (player != null) {
            sender.sendMessage("   ");

            CompleteDossier dossier = Infractions.getCompleteDossier(player);

            Integer maxScore = MiscUtil.getMaxScore(Infractions.getCompleteDossier(player).getId());
            String chatLevel = InfractionsPlugin.getLevelForChat(player);
            MiscUtil.sendMessage(p,
                    ChatColor.WHITE + (chatLevel.equals("") ? "" : chatLevel + " ") + ChatColor.YELLOW + player
                            + ChatColor.WHITE + " - " + MiscUtil.getScore(player)
                            + (maxScore == null ? " points towards a ban."
                                    : " points out of " + maxScore + " until a ban."));

            try {
                boolean staff = MiscUtil.hasPermissionOrOP(p, "infractions.mod");
                Set<Infraction> infractions = dossier.getInfractions();
                if (!infractions.isEmpty()) {
                    for (Infraction infraction : infractions) {
                        MiscUtil.sendMessage(p,
                                ChatColor.DARK_RED + " " + ChatColor.DARK_PURPLE
                                        + StringUtils.capitalize(infraction.getReason()) + ChatColor.DARK_GRAY
                                        + " - " + ChatColor.BLUE + FORMAT.format(infraction.getDateCreated()));
                        MiscUtil.sendMessage(p, ChatColor.DARK_GRAY + "     Penalty: " + ChatColor.GRAY
                                + infraction.getScore());
                        MiscUtil.sendMessage(p,
                                ChatColor.DARK_GRAY + "     Proof: " + ChatColor.GRAY
                                        + Iterables.getFirst(Collections2.transform(infraction.getEvidence(),
                                                new Function<Evidence, Object>() {
                                                    @Override
                                                    public String apply(Evidence evidence) {
                                                        return evidence.getRawData();
                                                    }
                                                }), "No Proof."));
                        if (staff) {
                            String id = MiscUtil.getInfractionId(infraction);
                            MiscUtil.sendMessage(p, ChatColor.DARK_GRAY + "     Key: " + ChatColor.GRAY + id);
                            String issuerId = infraction.getIssuer().getId();
                            if (IssuerType.STAFF.equals(infraction.getIssuer().getType())) {
                                UUID issuerUUID = UUID.fromString(issuerId);
                                ConcurrentMap<UUID, LegacyDossier> map = DataManager.getManager()
                                        .getMapFor(LegacyDossier.class);
                                if (map.containsKey(issuerUUID)
                                        && map.get(issuerUUID) instanceof CompleteDossier) {
                                    CompleteDossier issuerDossier = (LegacyCompleteDossier) map.get(issuerUUID);
                                    issuerId = issuerDossier.getLastKnownName();
                                } else {
                                    issuerId = "INVALID UUID: " + issuerId;
                                }
                            }
                            MiscUtil.sendMessage(p,
                                    ChatColor.DARK_GRAY + "     Issuer: " + ChatColor.GRAY + issuerId);
                        }
                    }
                } else
                    MiscUtil.sendMessage(p, ChatColor.DARK_GREEN + " " + ChatColor.WHITE
                            + "No infractions found for this player.");
                if (!staff)
                    return true;
                Set<InetAddress> addresses = dossier.getAssociatedIPAddresses();
                MiscUtil.sendMessage(p,
                        ChatColor.BLUE + " " + ChatColor.DARK_AQUA + "Associated IP Addresses:");
                if (addresses.isEmpty())
                    MiscUtil.sendMessage(p, ChatColor.GRAY + "     No currently known addresses.");
                else
                    for (InetAddress address : addresses) {
                        MiscUtil.sendMessage(p, ChatColor.GRAY + "     " + address.getHostAddress());
                        Collection<String> others = AsyncIPMatcherTask.getRelatives(dossier.getId());
                        if (others.size() > 1) {
                            MiscUtil.sendMessage(p, ChatColor.DARK_GRAY + "       - also associated with:");
                            for (String other : others) {
                                if (other.equals(player))
                                    continue;
                                MiscUtil.sendMessage(p,
                                        ChatColor.GRAY + "         " + ChatColor.YELLOW + other);
                            }
                        }
                    }

                sender.sendMessage("   ");
                return true;
            } catch (NullPointerException e) {
                return true;
            }
        } else {
            MiscUtil.sendMessage(p, "A player with the name \"" + args[0] + "\" cannot be found.");
            return true;
        }
    } else if (c.getName().equalsIgnoreCase("clearhistory") && p != null
            && p.hasPermission("infractions.clearhistory") && args.length > 0) {
        try {
            Player remove = Bukkit.getServer().matchPlayer(args[0]).get(0);
            Infractions.removeDossier(remove.getUniqueId());
            remove.kickPlayer(ChatColor.GREEN + "Your Infractions history has been reset--please join again.");
            return true;
        } catch (Exception error) {
            sender.sendMessage(ChatColor.RED + "Could not find that player...");
            return false;
        }
    }
    MiscUtil.sendMessage(p, "Something went wrong, please try again.");
    return false;
}

From source file:com.googlecode.concurrentlinkedhashmap.ConcurrentMapTest.java

@Test(dataProvider = "guardedMap")
public void removeConditionally(ConcurrentMap<Integer, Integer> map) {
    map.put(1, 2);//from   w  w w  .  j  ava2 s.co  m
    assertThat(map.remove(1, -2), is(false));
    assertThat(map.remove(1, 2), is(true));
    assertThat(map.get(1), is(nullValue()));
    assertThat(map.containsKey(1), is(false));
    assertThat(map.containsValue(2), is(false));
    assertThat(map, is(emptyMap()));
}

From source file:com.weibo.api.motan.core.extension.ExtensionLoader.java

@SuppressWarnings("unchecked")
private ConcurrentMap<String, Class<T>> loadClass(List<String> classNames) {
    ConcurrentMap<String, Class<T>> map = new ConcurrentHashMap<String, Class<T>>();

    for (String className : classNames) {
        try {//  ww w .  j a  v  a2  s. c om
            Class<T> clz;
            if (classLoader == null) {
                clz = (Class<T>) Class.forName(className);
            } else {
                clz = (Class<T>) Class.forName(className, true, classLoader);
            }

            checkExtensionType(clz);

            String spiName = getSpiName(clz);

            if (map.containsKey(spiName)) {
                failThrows(clz, ":Error spiName already exist " + spiName);
            } else {
                map.put(spiName, clz);
            }
        } catch (Exception e) {
            failLog(type, "Error load spi class", e);
        }
    }

    return map;

}

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

public Object loadClass(ConcurrentMap<String, ServiceClass> serviceMap, String className) {
    boolean isGroovy = ServiceClass.isGroovyScript(className);
    try {//w  ww  . j ava2  s .com
        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);
    }
}