Example usage for java.util.concurrent ConcurrentHashMap keySet

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

Introduction

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

Prototype

KeySetView keySet

To view the source code for java.util.concurrent ConcurrentHashMap keySet.

Click Source Link

Usage

From source file:org.springframework.cloud.config.server.EncryptionController.java

public Environment decrypt(Environment environment) {
    Environment result = new Environment(environment.getName(), environment.getLabel());
    for (PropertySource source : environment.getPropertySources()) {
        ConcurrentHashMap<Object, Object> map = new ConcurrentHashMap<Object, Object>(source.getSource());
        for (Object key : map.keySet()) {
            String name = key.toString();
            String value = map.get(key).toString();
            if (value.startsWith("{cipher}")) {
                map.remove(key);//from   w w  w  . ja  va 2  s.c  om
                if (encryptor == null) {
                    map.put(name, value);
                } else {
                    try {
                        value = value == null ? null : encryptor.decrypt(value.substring("{cipher}".length()));
                    } catch (Exception e) {
                        value = "<n/a>";
                        name = "invalid." + name;
                        logger.warn("Cannot decrypt key: " + key + " (" + e.getClass() + ": " + e.getMessage()
                                + ")");
                    }
                    map.put(name, value);
                }
            }
        }
        result.add(new PropertySource(source.getName(), map));
    }
    return result;
}

From source file:com.doctor.other.concurrent_hash_map_based_table.ConcurrentHashMapBasedTable.java

/**
 * ?//from w w  w .j  a  v a  2s. co  m
 */
public void clear() {
    for (String rowKey : table.keySet()) {
        ConcurrentHashMap<String, ConcurrentSkipListMap<String, ConcurrentSet<T>>> rowMap = table.get(rowKey);
        for (String columnKey : rowMap.keySet()) {
            ConcurrentSkipListMap<String, ConcurrentSet<T>> columnMap = rowMap.get(columnKey);

            Iterator<String> iterator = columnMap.keySet().iterator();
            while (iterator.hasNext()) {
                String timesplices = iterator.next();
                columnMap.get(timesplices).clear();
                iterator.remove();
            }

        }
        rowMap.clear();
    }

    table.clear();
}

From source file:com.doctor.other.concurrent_hash_map_based_table.ConcurrentHashMapBasedTable.java

private void pruneCache() {
    String expireTime = LocalDateTime.now().minusHours(ttl).format(Util.timeFormatter);
    log.info("{expireTime:{}}", expireTime);

    for (String rowKey : table.keySet()) {
        ConcurrentHashMap<String, ConcurrentSkipListMap<String, ConcurrentSet<T>>> rowMap = table.get(rowKey);
        for (String columnKey : rowMap.keySet()) {
            ConcurrentSkipListMap<String, ConcurrentSet<T>> columnMap = rowMap.get(columnKey);

            Iterator<String> iterator = columnMap.keySet().iterator();
            while (iterator.hasNext()) {
                String timesplices = iterator.next();
                if (timesplices.compareTo(expireTime) < 0) {
                    columnMap.get(timesplices).clear();
                    iterator.remove();//  ww  w. j  a v a 2  s .  com
                } else {
                    break;
                }
            }
        }
    }

}

From source file:com.steffi.index.ImgMapIndex.java

@Override
public ImgIndexHits<T> get(String key, Object value) {
    IndexKeyValue indexKeyValue = new IndexKeyValue(key, value);
    ConcurrentHashMap<Object, Boolean> idElements = getMap().get(indexKeyValue);

    if (idElements == null || idElements.isEmpty())
        return new ImgMapIndexHits<T>(IteratorUtils.emptyIterator(), 0, indexClass);
    else// w ww.  j a va  2s .co  m
        return new ImgMapIndexHits<T>(idElements.keySet().iterator(), idElements.size(), indexClass);

}

From source file:com.redhat.red.offliner.ftest.SinglePlaintextDownloadOfTarballFTest.java

/**
 * In general, we should only have one test method per functional test. This allows for the best parallelism when we
 * execute the tests, especially if the setup takes some time.
 *
 * @throws Exception In case anything (anything at all) goes wrong!
 *///from w  ww .  j  ava 2s. c  o  m
@Test
public void run() throws Exception {
    // Generate some test content
    String path = contentGenerator.newArtifactPath("tar.gz");
    Map<String, byte[]> entries = new HashMap<>();
    entries.put(contentGenerator.newArtifactPath("jar"), contentGenerator.newBinaryContent(2400));
    entries.put(contentGenerator.newArtifactPath("jar"), contentGenerator.newBinaryContent(2400));

    final File tgz = makeTarball(entries);

    System.out.println("tar content array has length: " + tgz.length());

    // We only need one repo server.
    ExpectationServer server = new ExpectationServer();
    server.start();

    // Register the generated content by writing it to the path within the repo server's dir structure.
    // This way when the path is requested it can be downloaded instead of returning a 404.
    server.expect("GET", server.formatUrl(path), (req, resp) -> {
        //            Content-Length: 47175
        //            Content-Type: application/x-gzip
        resp.setHeader("Content-Encoding", "gzip");
        resp.setHeader("Content-Type", "application/x-gzip");

        byte[] raw = FileUtils.readFileToByteArray(tgz);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        GzipCompressorOutputStream gzout = new GzipCompressorOutputStream(baos);
        gzout.write(raw);
        gzout.finish();

        byte[] content = baos.toByteArray();

        resp.setHeader("Content-Length", Long.toString(content.length));
        OutputStream respStream = resp.getOutputStream();
        respStream.write(content);
        respStream.flush();

        System.out.println("Wrote content with length: " + content.length);
    });

    byte[] content = FileUtils.readFileToByteArray(tgz);

    server.expect("GET", server.formatUrl(path + Main.SHA_SUFFIX), 200, sha1Hex(content));
    server.expect("GET", server.formatUrl(path + Main.MD5_SUFFIX), 200, md5Hex(content));

    // Write the plaintext file we'll use as input.
    File plaintextList = temporaryFolder.newFile("artifact-list." + getClass().getSimpleName() + ".txt");
    String pathWithChecksum = contentGenerator.newPlaintextEntryWithChecksum(path, content);
    FileUtils.write(plaintextList, pathWithChecksum);

    Options opts = new Options();
    opts.setBaseUrls(Collections.singletonList(server.getBaseUri()));

    // Capture the downloads here so we can verify the content.
    File downloads = temporaryFolder.newFolder();

    opts.setDownloads(downloads);
    opts.setLocations(Collections.singletonList(plaintextList.getAbsolutePath()));
    opts.setConnections(1);

    // run `new Main(opts).run()` and return the Main instance so we can query it for errors, etc.
    Main finishedMain = run(opts);
    ConcurrentHashMap<String, Throwable> errors = finishedMain.getErrors();
    System.out.printf("ERRORS:\n\n%s\n\n\n",
            StringUtils.join(errors.keySet().stream()
                    .map(k -> "ERROR: " + k + ": " + errors.get(k).getMessage() + "\n  "
                            + StringUtils.join(errors.get(k).getStackTrace(), "\n  "))
                    .collect(Collectors.toList()), "\n\n"));

    File downloaded = new File(downloads, path);
    assertThat("File: " + path + " doesn't seem to have been downloaded!", downloaded.exists(), equalTo(true));
    //        assertThat( "Downloaded file: " + path + " contains the wrong content!",
    //                    FileUtils.readFileToByteArray( downloaded ), equalTo( content ) );

    File tarball = new File(downloads, path);
    System.out.println("Length of downloaded file: " + tarball.length());

    File tmp = new File("/tmp/download.tar.gz");
    File tmp2 = new File("/tmp/content.tar.gz");
    FileUtils.writeByteArrayToFile(tmp2, content);
    FileUtils.copyFile(tarball, tmp);

    try (TarArchiveInputStream tarIn = new TarArchiveInputStream(
            new GzipCompressorInputStream(new FileInputStream(tarball)))) {
        TarArchiveEntry entry = null;
        while ((entry = tarIn.getNextTarEntry()) != null) {
            byte[] entryData = new byte[(int) entry.getSize()];
            int read = tarIn.read(entryData, 0, entryData.length);
            assertThat("Not enough bytes read for: " + entry.getName(), read, equalTo((int) entry.getSize()));
            assertThat(entry.getName() + ": data doesn't match input",
                    Arrays.equals(entries.get(entry.getName()), entryData), equalTo(true));
        }
    }

    assertThat("Wrong number of downloads logged. Should have been 3 including checksums.",
            finishedMain.getDownloaded(), equalTo(3));
    assertThat("Errors should be empty!", errors.isEmpty(), equalTo(true));

}

From source file:org.objectweb.proactive.extensions.dataspaces.vfs.VFSSpacesMountManagerImpl.java

/**
 * Unmount all file systems for the given dataspace
 * @param spaceUri dataspace uri/*from  www .  j a  v a 2 s  .c om*/
 */
private void unmountAllFileSystems(final DataSpacesURI spaceUri) {

    DataSpacesURI spacePart = spaceUri.getSpacePartOnly();

    final ConcurrentHashMap<String, FileObject> spaceRoots = mountedSpaces.remove(spacePart);

    VFSMountManagerHelper.closeFileSystems(spaceRoots.keySet());
}

From source file:org.deviceconnect.android.deviceplugin.hvcc2w.setting.fragment.HVCC2WRegisterFaceRecognitionDataFragment.java

/**
 * Initial List View.//  ww  w.j  av a 2  s  .c o  m
 */
private void initListView() {
    HVCManager.INSTANCE.getCameraList(new HVCManager.ResponseListener() {
        @Override
        public void onReceived(String json) {
            ConcurrentHashMap<String, HVCCameraInfo> camera = HVCManager.INSTANCE.getHVCDevices();
            if (camera.size() == 0) {
                return;
            }
            String[] names = new String[camera.size()];
            int i = 0;
            for (String key : camera.keySet()) {
                names[i] = key;
                i++;
            }
            final String[] serviceIds = names;
            final int[] pos = new int[1];
            if (mServiceId == null) {
                HVCC2WDialogFragment.showSelectDialog(getActivity(), getString(R.string.select_dialog_message),
                        serviceIds, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                pos[0] = i;
                            }
                        }, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                mServiceId = serviceIds[pos[0]];
                                mRegister.setVisibility(View.VISIBLE);
                                mUnregister.setVisibility(View.VISIBLE);

                                List<FaceRecognitionObject> objects = HVCStorage.INSTANCE
                                        .getFaceRecognitionDatasForDeviceId(mServiceId);
                                for (FaceRecognitionObject object : objects) {
                                    mAdapter.add(object.getName());
                                }
                                mListView.setAdapter(mAdapter);
                            }
                        }, null);
            } else {
                List<FaceRecognitionObject> objects = HVCStorage.INSTANCE
                        .getFaceRecognitionDatasForDeviceId(mServiceId);
                for (FaceRecognitionObject object : objects) {
                    mAdapter.add(object.getName());
                }
                mListView.setAdapter(mAdapter);
            }
            mAdapter.notifyDataSetChanged();
        }
    });
    mAdapter.clear();
}

From source file:com.app.server.EARDeployer.java

/**
 * This method removes the executor services from the executor services
 * map.// w  w w.  ja v a 2 s.c  o m
 * 
 * @param jarFile
 * @param classList
 * @throws FileSystemException
 */
public void deleteExecutorServicesEar(URL url) throws FileSystemException {
    try {
        File file = new File(url.toURI());
        String fileName = file.getName();
        synchronized (urlClassLoaderMap) {
            ConcurrentHashMap map = (ConcurrentHashMap) filesMap.get(fileName);
            if (map != null) {
                //log.info("ClassLoader Map=\n\n\n\n"+urlClassLoaderMap);
                Set keysinclassloadermap = map.keySet();
                log.info(keysinclassloadermap.size());
                Iterator classloaders = keysinclassloadermap.iterator();
                while (classloaders.hasNext()) {
                    String classloader = (String) classloaders.next();
                    log.info("ClassLoader=" + classloader);
                    ClassLoader webClassLoader = (ClassLoader) this.urlClassLoaderMap.get(map.get(classloader));
                    this.urlClassLoaderMap.remove(map.get(classloader));
                    ClassLoaderUtil.cleanupJarFileFactory(ClassLoaderUtil.closeClassLoader(webClassLoader));
                    urlClassLoaderMap.remove(map.get(classloader));
                    try {
                        if (webClassLoader instanceof WebClassLoader)
                            ((WebClassLoader) webClassLoader).close();
                        else if (webClassLoader instanceof VFSClassLoader) {
                            FileObject[] fObj = ((VFSClassLoader) webClassLoader).getFileObjects();
                            for (FileObject obj : fObj) {
                                obj.close();
                            }
                        }
                    } catch (Throwable e) {
                        log.error("Error in closing the classLoader", e);
                        // TODO Auto-generated catch block
                        //e.printStackTrace();
                    }
                    /*if (classloader.contains(deployDirectory +"/"+ fileName)) {
                       log.info("removing classloader" + deployDirectory
                      + classloader);
                          File warDir=new File(fileName);
                          if(warDir.exists()){                                    
                      warDeployer.deleteDir(warDir);
                          }
                          //log.info("Before Remove class loader\n\n\n\n"+this.urlClassLoaderMap);                           
                          //log.info("Remove class loader\n\n\n\n"+this.urlClassLoaderMap);
                    }*/
                }
                System.gc();
                classloaders = keysinclassloadermap.iterator();
                while (classloaders.hasNext()) {
                    String classloader = (String) classloaders.next();
                    if (classloader.endsWith(".war")) {
                        mbeanServer.invoke(warObjectName, "removeServlets",
                                new Object[] { (String) map.get(classloader), classloader },
                                new String[] { String.class.getName(), String.class.getName() });
                        File warDir = new File((String) map.get(classloader));
                        if (warDir.exists()) {
                            deleteDir(warDir);
                        }
                    }
                }
                log.info(this.urlClassLoaderMap);
            }
            filesMap.remove(fileName);
        }
    } catch (Exception ex) {
        try {
            log.error("Error in removing the executor services configuration for the file name "
                    + url.toURI().toString(), ex);
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //ex.printStackTrace();
    }
}

From source file:com.athena.sqs.MessageAggregator.java

/**
 * Aggregate splitted messages into single message.
 * @param rawData base64 string/*from www.j  a  v a 2s. c o m*/
 * @throws MessageException
 */
public void aggregate(String rawString) throws MessageException {
    try {
        BASE64Decoder decoder = new BASE64Decoder();

        int index = rawString.indexOf(MessageContext.DATA_DELIMITER);

        // 1. Split header
        String[] header = parseHeader(rawString.substring(0, index));
        String content = rawString.substring(index + 2);

        // 2. Assign header value to local variable
        MessageTransferType transferType = MessageTransferType.valueOf(header[0]);
        String businessName = header[1];
        String transactionId = header[2];
        MessageSplitType splitType = MessageSplitType.valueOf(header[3]);
        int current = Integer.parseInt(header[4]);
        int total = Integer.parseInt(header[5]);

        // 3 Check Message Single
        switch (splitType) {
        case SINGLE:
            // TODO single message work
            doProcess(transactionId, new String(decoder.decodeBuffer(content)));
            return;
        case MULTI:
            break;
        }

        logger.debug("Transaction ID : " + transactionId);

        // 4. Check Message Order
        // If transaction id is not exist in txMap, create new tx map object
        if (!txMap.containsKey(transactionId)) {
            ConcurrentHashMap<Integer, String> orderedMessages = new ConcurrentHashMap<Integer, String>();
            orderedMessages.put(current, content);

            txMap.put(transactionId, orderedMessages);
        } else {
            // Already same transaction message was inserted
            ConcurrentHashMap<Integer, String> orderedMessages = txMap.get(transactionId);
            orderedMessages.put(current, content);

            // Message compare
            if (orderedMessages.size() == total) {
                // All messages arrived
                Object[] key = orderedMessages.keySet().toArray();
                Arrays.sort(key);

                String finalMessage = "";
                for (int i = 0; i < key.length; i++) {
                    finalMessage += orderedMessages.get(key[i]);
                }

                logger.debug("===== [ " + transactionId + "] ======");
                logger.debug(new String(decoder.decodeBuffer(finalMessage)));
                boolean isDelete = txMap.remove(transactionId, orderedMessages);
                if (!isDelete) {
                    throw new MessageException("Can't delete message from transaction map");
                }

                doProcess(transactionId, new String(decoder.decodeBuffer(finalMessage)));
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.web.server.WarDeployer.java

public WarDeployer(String scanDirectory, String farmwarDir, String clusterGroup, Hashtable urlClassLoaderMap,
        Hashtable executorServiceMap, Hashtable messagingClassMap, ConcurrentHashMap servletMapping,
        MessagingElem messagingElem, ConcurrentHashMap sessionObjects) {
    this.scanDirectory = scanDirectory;
    this.urlClassLoaderMap = urlClassLoaderMap;
    this.executorServiceMap = executorServiceMap;
    this.messagingClassMap = messagingClassMap;
    this.servletMapping = servletMapping;
    this.sessionObjects = sessionObjects;
    farmWarFileTransfer = FarmWarFileTransfer.getInstance(scanDirectory + "/", farmwarDir, clusterGroup);
    try {//from  w  w w . j  a  v  a  2 s. c  o  m
        farmWarFileTransfer.start();
    } catch (Exception e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    }
    try {
        DigesterLoader serverdigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() {

            protected void loadRules() {
                // TODO Auto-generated method stub
                try {
                    loadXMLRules(new InputSource(new FileInputStream("./config/executorservices-config.xml")));
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        });
        serverdigester = serverdigesterLoader.newDigester();
    } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        DigesterLoader serverdigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() {

            protected void loadRules() {
                // TODO Auto-generated method stub
                try {
                    loadXMLRules(new InputSource(new FileInputStream("./config/messagingclass-rules.xml")));
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        });
        messagedigester = serverdigesterLoader.newDigester();
    } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        DigesterLoader serverdigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() {

            protected void loadRules() {
                // TODO Auto-generated method stub
                try {
                    loadXMLRules(new InputSource(new FileInputStream("./config/webxml-rules.xml")));
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        });
        webxmldigester = serverdigesterLoader.newDigester();
    } catch (Exception ex) {
        //ex.printStackTrace();
    }
    synchronized (messagingElem) {
        this.messagingElem = messagingElem;
        ConcurrentHashMap randomQueue = messagingElem.randomQueue;
        Set<String> randomQueueSet = randomQueue.keySet();
        Iterator<String> ite = randomQueueSet.iterator();
        while (ite.hasNext()) {
            Queue queue = (Queue) randomQueue.get(ite.next());
            ConcurrentHashMap randomqueuemap = (ConcurrentHashMap) messagingClassMap.get("RandomQueue");
            if (randomqueuemap == null) {
                randomqueuemap = new ConcurrentHashMap();
                messagingClassMap.put("RandomQueue", randomqueuemap);
            }
            CopyOnWriteArrayList randomqueuelist = (CopyOnWriteArrayList) randomqueuemap
                    .get(queue.getQueuename());
            if (randomqueuelist == null)
                randomqueuemap.put(queue.getQueuename(), new CopyOnWriteArrayList());
        }

        ConcurrentHashMap roundrobinQueue = messagingElem.roundrobinQueue;
        Set<String> roundrobinQueueSet = roundrobinQueue.keySet();
        ite = roundrobinQueueSet.iterator();
        while (ite.hasNext()) {
            Queue queue = (Queue) roundrobinQueue.get(ite.next());
            ConcurrentHashMap roundrobinqueuemap = (ConcurrentHashMap) messagingClassMap.get("RoundRobinQueue");
            if (roundrobinqueuemap == null) {
                roundrobinqueuemap = new ConcurrentHashMap();
                messagingClassMap.put("RoundRobinQueue", roundrobinqueuemap);
            }
            CopyOnWriteArrayList randomqueuelist = (CopyOnWriteArrayList) roundrobinqueuemap
                    .get(queue.getQueuename());
            if (randomqueuelist == null)
                roundrobinqueuemap.put(queue.getQueuename(), new CopyOnWriteArrayList());
        }

        ConcurrentHashMap topicMap = messagingElem.topicMap;
        Set<String> topicSet = topicMap.keySet();
        Iterator<String> iter = topicSet.iterator();
        while (iter.hasNext()) {
            Topic topic = (Topic) topicMap.get(iter.next());
            ConcurrentHashMap topicmap = (ConcurrentHashMap) messagingClassMap.get("Topic");
            if (topicmap == null) {
                topicmap = new ConcurrentHashMap();
                messagingClassMap.put("Topic", topicmap);
            }
            CopyOnWriteArrayList randomqueuelist = (CopyOnWriteArrayList) topicmap.get(topic.getTopicname());
            if (randomqueuelist == null)
                topicmap.put(topic.getTopicname(), new CopyOnWriteArrayList());
        }
        System.out.println(messagingClassMap);
    }

}