Example usage for java.util.concurrent ConcurrentHashMap containsKey

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

Introduction

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

Prototype

public boolean containsKey(Object key) 

Source Link

Document

Tests if the specified object is a key in this table.

Usage

From source file:org.apache.falcon.entity.store.ConfigurationStore.java

/**
 * @param type - Entity type that is being retrieved
 * @param name - Name as it appears in the entity xml definition
 * @param <T>  - Actual Entity object type
 * @return - Entity object from internal dictionary, If the object is not
 *         loaded in memory yet, it will retrieve it from persistent store
 *         just in time. On startup all the entities will be added to the
 *         dictionary with null reference.
 * @throws FalconException//w  ww.  j ava 2 s .com
 */
@SuppressWarnings("unchecked")
public <T extends Entity> T get(EntityType type, String name) throws FalconException {
    ConcurrentHashMap<String, Entity> entityMap = dictionary.get(type);
    if (entityMap.containsKey(name)) {
        if (updatesInProgress.get() != null && updatesInProgress.get().getEntityType() == type
                && updatesInProgress.get().getName().equals(name)) {
            return (T) updatesInProgress.get();
        }
        T entity = (T) entityMap.get(name);
        if (entity == NULL && shouldPersist) { // Object equality being checked
            try {
                entity = this.restore(type, name);
            } catch (IOException e) {
                throw new StoreAccessException(e);
            }
            entityMap.put(name, entity);
            return entity;
        } else {
            return entity;
        }
    } else {
        return null;
    }
}

From source file:org.wso2.carbon.governance.metadata.Util.java

private static Map<String, BaseProvider> getBaseProviderMap() throws MetadataException {
    if (baseProviderMap != null) {
        return baseProviderMap;
    }/*from w  ww  .  j  a  v a 2  s  .c  om*/

    ConcurrentHashMap<String, BaseProvider> providerMap = new ConcurrentHashMap<String, BaseProvider>();
    try {
        FileInputStream fileInputStream = new FileInputStream(getConfigFile());
        StAXOMBuilder builder = new StAXOMBuilder(fileInputStream);
        OMElement configElement = builder.getDocumentElement();
        OMElement metadataProviders = configElement.getFirstChildWithName(new QName("metadataProviders"))
                .getFirstChildWithName(new QName("baseProviders"));
        Iterator<OMElement> itr = metadataProviders.getChildrenWithLocalName("provider");
        while (itr.hasNext()) {
            OMElement metadataProvider = itr.next();
            String providerClass = metadataProvider.getAttributeValue(new QName("class")).trim();
            String mediaType = metadataProvider.getAttributeValue(new QName(Constants.ATTRIBUTE_MEDIA_TYPE));
            String versionMediaType = metadataProvider
                    .getAttributeValue(new QName(Constants.ATTRIBUTE_VERSION_MEDIA_TYPE));

            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            Class<BaseProvider> classObj = (Class<BaseProvider>) Class.forName(providerClass, true, loader);

            if (!providerMap.containsKey(mediaType)) {
                providerMap.put(mediaType,
                        (BaseProvider) classObj.getConstructors()[0].newInstance(mediaType, versionMediaType));
            } else {
                //                    log.error("Classification URI already exists")
            }
        }
    } catch (Exception e) {
        throw new MetadataException(e.getMessage(), e);
    }

    return Util.baseProviderMap = providerMap;
}

From source file:org.apache.marmotta.ucuenca.wk.commons.function.SemanticDistance.java

private List<String> topT(List<String> m, int n) throws IOException, SQLException {
    int value1 = 1;
    n = (n <= 0) ? 1 : n;//  ww w .  j ava2s. c om
    if (m.size() == value1) {
        m.add(m.get(0));
    }
    ConcurrentHashMap<String, Double> mapa = new ConcurrentHashMap();
    for (int i = 0; i < m.size(); i++) {
        for (int j = i + 1; j < m.size(); j++) {
            double v = ngd(m.get(i), m.get(j));
            //System.out.print(i+"/"+m.size()+"\t");

            if (mapa.containsKey(m.get(i))) {
                mapa.put(m.get(i), mapa.get(m.get(i)) + v);
            } else {
                mapa.put(m.get(i), v);
            }

            if (mapa.containsKey(m.get(j))) {
                mapa.put(m.get(j), mapa.get(m.get(j)) + v);
            } else {
                mapa.put(m.get(j), v);
            }
        }
    }
    Map<String, Double> sortByValue = sortByValue(mapa);
    List<String> ls = new ArrayList<>();
    ArrayList<String> arrayList = new ArrayList(sortByValue.keySet());
    for (int i = 0; i < n; i++) {
        if (i < sortByValue.size()) {
            ls.add(arrayList.get(i));
            // System.out.println(arrayList.get(i)+"__"+arrayList2.get(i));
        }
    }
    return ls;
}

From source file:org.apache.nifi.lookup.CSVRecordLookupService.java

private void loadCache() throws IllegalStateException, IOException {
    if (lock.tryLock()) {
        try {/*ww w . j  a va2 s  .  com*/
            final ComponentLog logger = getLogger();
            if (logger.isDebugEnabled()) {
                logger.debug("Loading lookup table from file: " + csvFile);
            }

            final FileReader reader = new FileReader(csvFile);
            final CSVParser records = csvFormat.withFirstRecordAsHeader().parse(reader);
            ConcurrentHashMap<String, Record> cache = new ConcurrentHashMap<>();
            RecordSchema lookupRecordSchema = null;
            for (final CSVRecord record : records) {
                final String key = record.get(lookupKeyColumn);

                if (StringUtils.isBlank(key)) {
                    throw new IllegalStateException("Empty lookup key encountered in: " + csvFile);
                } else if (!ignoreDuplicates && cache.containsKey(key)) {
                    throw new IllegalStateException(
                            "Duplicate lookup key encountered: " + key + " in " + csvFile);
                } else if (ignoreDuplicates && cache.containsKey(key)) {
                    logger.warn("Duplicate lookup key encountered: {} in {}", new Object[] { key, csvFile });
                }

                // Put each key/value pair (except the lookup) into the properties
                final Map<String, Object> properties = new HashMap<>();
                record.toMap().forEach((k, v) -> {
                    if (!lookupKeyColumn.equals(k)) {
                        properties.put(k, v);
                    }
                });

                if (lookupRecordSchema == null) {
                    List<RecordField> recordFields = new ArrayList<>(properties.size());
                    properties.forEach((k, v) -> recordFields
                            .add(new RecordField(k, RecordFieldType.STRING.getDataType())));
                    lookupRecordSchema = new SimpleRecordSchema(recordFields);
                }

                cache.put(key, new MapRecord(lookupRecordSchema, properties));
            }

            this.cache = cache;

            if (cache.isEmpty()) {
                logger.warn("Lookup table is empty after reading file: " + csvFile);
            }
        } finally {
            lock.unlock();
        }
    }
}

From source file:unitTests.dataspaces.VFSMountManagerHelperTest.java

/**
 * - Insert a valid file vfs root and a valid proactive vfs root in the list of fake uris
 * - verifies that mountAny returns the file system corresponding to the valid uri
 * - do that for all valid uris of the file system server
 * @throws Exception// w  w w .  j a  va 2s.co  m
 */
@Test
public void testMountAnyOk() throws Exception {
    logger.info("*************** testMountAnyOk");
    String[] validUris = server.getVFSRootURLs();

    for (String validUrl : validUris) {
        ConcurrentHashMap<String, FileObject> fileSystems = new ConcurrentHashMap<String, FileObject>();
        ArrayList<String> uriToMount = new ArrayList<String>(fakeFileUrls);
        uriToMount.add(spacesDir.toURI().toString()); // adds a valid file uri
        uriToMount.addAll(fakeUrls);
        uriToMount.add((int) Math.floor(Math.random() * uriToMount.size()), validUrl);
        VFSMountManagerHelper.mountAny(uriToMount, fileSystems);
        logger.info("Content of map : " + fileSystems.toString());
        Assert.assertTrue("map contains valid Url", fileSystems.containsKey(validUrl));
    }
}

From source file:org.openhab.io.caldav.internal.CalDavLoaderImpl.java

private synchronized void addEventToMap(EventContainer eventContainer, boolean createTimer) {
    CalendarRuntime calendarRuntime = EventStorage.getInstance().getEventCache()
            .get(eventContainer.getCalendarId());

    ConcurrentHashMap<String, EventContainer> eventContainerMap = calendarRuntime.getEventMap();

    if (eventContainerMap.containsKey(eventContainer.getEventId())) {
        EventContainer eventContainerOld = eventContainerMap.get(eventContainer.getEventId());
        // event is already in map
        if (eventContainer.getLastChanged().isAfter(eventContainerOld.getLastChanged())) {
            log.debug("event is already in event map and newer -> delete the old one, reschedule timer");
            // cancel old jobs
            for (String timerKey : eventContainerOld.getTimerMap()) {
                try {
                    this.scheduler.deleteJob(JobKey.jobKey(timerKey));
                } catch (SchedulerException e) {
                    log.error("cannot cancel event with job-id: " + timerKey, e);
                }/*from ww  w. j  a  v a 2  s  .  c  o m*/
            }
            eventContainerOld.getTimerMap().clear();

            // override event
            eventContainerMap.put(eventContainer.getEventId(), eventContainer);

            for (EventNotifier notifier : eventListenerList) {
                for (CalDavEvent event : eventContainerOld.getEventList()) {
                    log.trace("notify listener... {}", notifier);
                    try {
                        notifier.eventRemoved(event);
                    } catch (Exception e) {
                        log.error("error while invoking listener", e);
                    }
                }
            }
            for (EventNotifier notifier : eventListenerList) {
                for (CalDavEvent event : eventContainer.getEventList()) {
                    log.trace("notify listener... {}", notifier);
                    try {
                        notifier.eventLoaded(event);
                    } catch (Exception e) {
                        log.error("error while invoking listener", e);
                    }
                }
            }

            if (createTimer) {
                int index = 0;
                for (CalDavEvent event : eventContainer.getEventList()) {
                    if (event.getEnd().isAfterNow()) {
                        try {
                            createJob(eventContainer, event, index);
                        } catch (SchedulerException e) {
                            log.error("cannot create jobs for event: " + event.getShortName());
                        }
                    }
                    index++;
                }
            }
        } else {
            // event is already in map and not updated, ignoring
        }
    } else {
        // event is new
        eventContainerMap.put(eventContainer.getEventId(), eventContainer);
        log.trace("listeners for events: {}", eventListenerList.size());
        for (EventNotifier notifier : eventListenerList) {
            for (CalDavEvent event : eventContainer.getEventList()) {
                log.trace("notify listener... {}", notifier);
                try {
                    notifier.eventLoaded(event);
                } catch (Exception e) {
                    log.error("error while invoking listener", e);
                }
            }
        }
        if (createTimer) {
            int index = 0;
            for (CalDavEvent event : eventContainer.getEventList()) {
                if (event.getEnd().isAfterNow()) {
                    try {
                        createJob(eventContainer, event, index);
                    } catch (SchedulerException e) {
                        log.error("cannot create jobs for event: " + event.getShortName());
                    }
                }
                index++;
            }
        }
    }
}

From source file:com.uber.tchannel.ping.PingClient.java

public void run() throws Exception {
    TChannel tchannel = new TChannel.Builder("ping-client").build();
    SubChannel subChannel = tchannel.makeSubChannel("ping-server");
    final ConcurrentHashMap<String, Integer> msgs = new ConcurrentHashMap<String, Integer>();
    final CountDownLatch done = new CountDownLatch(requests);

    for (int i = 0; i < requests; i++) {
        JsonRequest<Ping> request = new JsonRequest.Builder<Ping>("ping-server", "ping")
                .setBody(new Ping("{'key': 'ping?'}")).setHeader("some", "header").setTimeout(100 + i).build();
        TFuture<JsonResponse<Pong>> f = subChannel.send(request, InetAddress.getByName(host), port);

        f.addCallback(new TFutureCallback<JsonResponse<Pong>>() {
            @Override/*from   w ww. ja v a 2s .  c  om*/
            public void onResponse(JsonResponse<Pong> pongResponse) {
                done.countDown();
                String msg = pongResponse.toString();
                if (msgs.containsKey(msg)) {
                    msgs.put(msg, msgs.get(msg) + 1);
                } else {
                    msgs.put(msg, 1);
                }
            }
        });
    }

    done.await();
    for (String msg : msgs.keySet()) {
        System.out.println(String.format("%s\n\tcount:%d", msg, msgs.get(msg)));
    }

    tchannel.shutdown(false);
}

From source file:starnubserver.connections.player.session.PlayerSession.java

private boolean hasSubPermission(String basePermission, String subPermission, boolean checkWildCards) {
    if (PERMISSIONS.containsKey("*") && checkWildCards) {
        return true;
    }/*from   w  ww . j  av  a2 s.  c  o  m*/
    ConcurrentHashMap<String, ArrayList<String>> concurrentHashMap = PERMISSIONS.get(basePermission);
    if (concurrentHashMap == null) {
        return false;
    }
    if (checkWildCards) {
        return concurrentHashMap.containsKey("*") || concurrentHashMap.containsKey(subPermission);
    } else {
        return false;
    }
}

From source file:org.apache.marmotta.ucuenca.wk.commons.function.SemanticDistance.java

/**
 * @param args the command line arguments
 *//* w  ww. j  a v a 2s .  c  o m*/
public synchronized double semanticKeywordsDistance(List<String> a, List<String> b)
        throws ClassNotFoundException, SQLException, IOException {
    Class.forName("org.postgresql.Driver");
    conn = DriverManager.getConnection(dburl, user, pass);
    ConcurrentHashMap<String, List<String>> map = new ConcurrentHashMap<>();
    List<String> authors = new ArrayList();
    authors.add("a1");
    authors.add("a2");
    ConcurrentHashMap<String, Double> result = new ConcurrentHashMap<>();
    double avg = 0;
    double har = 0;
    for (int i = 0; i < authors.size(); i++) {
        for (int j = i + 1; j < authors.size(); j++) {
            String a1 = authors.get(i);
            String a2 = authors.get(j);
            List<String> ka1 = null;
            List<String> ka2 = null;
            if (map.containsKey(a1)) {
                ka1 = map.get(a1);
            } else {
                ka1 = formatList(a);//consultado2R(a1, Endpoints.get(i));
                map.put(a1, ka1);
            }
            if (map.containsKey(a2)) {
                ka2 = map.get(a2);
            } else {
                ka2 = formatList(b);//consultado2R(a2, Endpoints.get(j));
                map.put(a2, ka2);
            }
            double sum = 0;
            double num = 0;

            for (String t1 : ka1) {
                for (String t2 : ka2) {
                    num++;
                    String tt1 = t1;
                    String tt2 = t2;
                    double v = ngd(tt1, tt2);
                    sum += v;
                }
            }
            double prom = sum / num;
            if (num == 0 && sum == 0) {
                prom = 2;
            }
            result.put(i + "," + j, prom);

            avg = avg(avg, prom);
            har = har(har, prom);
        }
    }

    conn.close();
    return mapEntry(result);
}

From source file:org.starnub.starnubserver.connections.player.session.PlayerSession.java

private boolean hasFullPermission(String basePermission, String subPermission, String fullPermission,
        boolean checkWildCards) {
    if (PERMISSIONS.containsKey("*") && checkWildCards) {
        return true;
    }/* w  ww . j  a va  2  s  .  c  o m*/
    ConcurrentHashMap<String, ArrayList<String>> concurrentHashMap = PERMISSIONS.get(basePermission);
    if (concurrentHashMap == null) {
        return false;
    }
    if (concurrentHashMap.containsKey("*") && checkWildCards) {
        return true;
    }
    ArrayList<String> strings = concurrentHashMap.get(subPermission);
    if (strings == null) {
        return false;
    }
    if (checkWildCards) {
        return strings.contains("*") || strings.contains(fullPermission);
    } else {
        return false;
    }
}