Example usage for java.util.concurrent ConcurrentHashMap get

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

Introduction

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

Prototype

public V get(Object key) 

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:com.iitb.cse.Utils.java

public static ConcurrentHashMap<String, String> getAccessPointConnectionDetails() {

    ConcurrentHashMap<String, String> apConnection = new ConcurrentHashMap<String, String>();
    Enumeration macList = Constants.currentSession.connectedClients.keys();

    while (macList.hasMoreElements()) {
        String macAddr = (String) macList.nextElement();
        DeviceInfo device = Constants.currentSession.connectedClients.get(macAddr);

        if (apConnection.get(device.getBssid()) == null) {
            apConnection.put(device.getBssid(), device.getSsid() + "#1");
        } else {//from w w w  .j a v  a  2s. c om
            String ssid_count = apConnection.get(device.getBssid());
            int count = Integer.parseInt(ssid_count.split("#")[1]);
            count++;
            apConnection.put(device.getBssid(), device.getSsid() + "#" + Integer.toString(count));
        }
    }
    return apConnection;
}

From source file:org.objectweb.proactive.core.remoteobject.RemoteObjectSet.java

/**
 * Helper method used to sort the list of protocols
 * @param input/*from  ww  w  .  j a  va 2  s.  com*/
 * @param defOrder
 * @param benchmarkRes
 * @param defUri
 * @return
 */
public static ArrayList<URI> sortProtocols(Collection<URI> input, final List<String> defOrder,
        final ConcurrentHashMap<URI, Integer> benchmarkRes, final URI defUri) {

    ArrayList<URI> output = new ArrayList<URI>();
    output.addAll(input);

    Collections.sort(output, new Comparator<URI>() {
        @Override
        public int compare(URI o1, URI o2) {

            // unreachable uri, they are put at the end of the list
            if (benchmarkRes.containsKey(o1) && benchmarkRes.get(o1) == UNREACHABLE_VALUE) {
                return 1;
            }
            if (benchmarkRes.containsKey(o2) && benchmarkRes.get(o2) == UNREACHABLE_VALUE) {
                return -1;
            }

            // sort accordingly to fixed order
            if (defOrder.contains(o1.getScheme()) && defOrder.contains(o2.getScheme())) {
                return defOrder.indexOf(o1.getScheme()) - defOrder.indexOf(o2.getScheme());
            }
            // the following code means that any protocol present in the default order
            // is preferred to any other protocol, currently this behavior is deactivated

            if (defOrder.contains(o1.getScheme())) {
                return -1;
            }
            if (defOrder.contains(o2.getScheme())) {
                return 1;
            }
            if (benchmarkRes.containsKey(o1) && benchmarkRes.containsKey(o2)) {
                // sort accordingly to benchmark results
                if (benchmarkRes.get(o1) > benchmarkRes.get(o2)) {
                    return -1;
                } else if (benchmarkRes.get(o2) > benchmarkRes.get(o1)) {
                    return 1;
                }
                return 0;
            }

            // undetermined, we have no info
            return 0;
        }
    });

    // finally remove unreachable protocols
    for (ListIterator<URI> it = output.listIterator(output.size()); it.hasPrevious();) {
        URI reachableOrNot = it.previous();
        if (benchmarkRes.containsKey(reachableOrNot) && benchmarkRes.get(reachableOrNot) == UNREACHABLE_VALUE) {
            if (!reachableOrNot.equals(defUri)) {
                it.remove();
            }
        } else {
            // we exit the loop at the first reachable protocol
            break;
        }
    }
    return output;
}

From source file:com.iitb.cse.Utils.java

public static CopyOnWriteArrayList<DeviceInfo> activeClients() {
    //   (Utils.getCurrentTimeStamp().getTime() - device.getLastHeartBeatTime().getTime())/1000 > 60 
    //        int count = 0;

    ConcurrentHashMap<String, DeviceInfo> clients = Constants.currentSession.getConnectedClients();
    Enumeration<String> macList = clients.keys();
    ConcurrentHashMap<String, DeviceInfo> connectedClients = new ConcurrentHashMap<String, DeviceInfo>();
    CopyOnWriteArrayList<DeviceInfo> activeClients = new CopyOnWriteArrayList<DeviceInfo>();

    if (clients != null) {
        while (macList.hasMoreElements()) {
            String macAddr = macList.nextElement();
            DeviceInfo device = clients.get(macAddr);
            if ((Utils.getCurrentTimeStamp().getTime() - device.getLastHeartBeatTime().getTime())
                    / 1000 <= Constants.heartBeatAlive) {
                activeClients.add(device);
                //                   count++;
            }/*from  w w  w.ja v  a 2 s.  c  om*/
        }
    }
    return activeClients;
}

From source file:org.mule.util.queue.FilePersistenceQueue.java

public File peekFromMessageMap(String queue, String id) {
    ConcurrentHashMap<String, File> messageMap = queueMap.get(queue);
    if (messageMap == null) {
        return null;
    }//ww  w .ja v  a 2  s.  com
    File f = messageMap.get(id);
    if (f != null) {
        messageMap.remove(id);
    }
    return f;
}

From source file:org.apache.vxquery.indexing.MetaFileUtilTest.java

/**
 * Test the update metadata file process.
 *//*from   ww  w .ja va 2s .  c o m*/
@Test
public void step5_testUpdateMetadata()
        throws IOException, ClassNotFoundException, NoSuchAlgorithmException, JAXBException {
    ConcurrentHashMap<String, XmlMetadata> fromFileMap = metaFileUtil.getMetadata();
    XmlMetadata modified = fromFileMap.get(TestConstants.XML_FILE);

    File xml = new File(TestConstants.XML_FILE);
    modified.setMd5(metaFileUtil.generateMD5(xml));

    fromFileMap.replace(TestConstants.XML_FILE, modified);

    metaFileUtil.updateMetadataMap(fromFileMap, TestConstants.INDEX_DIR);

    Assert.assertNotNull(metaFileUtil.getMetadata());

}

From source file:com.netflix.dyno.connectionpool.impl.MonitorConsoleResource.java

@SuppressWarnings("unchecked")
@Path("/topology/{cpName}")
@GET/*from w w w .j  a v  a  2s  . c  om*/
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_JSON)
public String getConnectionPoolToplogy(@PathParam("cpName") String cpName) {

    TokenPoolTopology topology = MonitorConsole.getInstance().getTopology(cpName);
    if (topology == null) {
        return "Not Found: " + cpName;
    }

    ConcurrentHashMap<String, List<TokenStatus>> map = topology.getAllTokens();

    JSONObject json = new JSONObject();

    for (String rack : map.keySet()) {
        List<TokenStatus> tokens = map.get(rack);
        json.put(rack, getTokenStatusMap(tokens));
    }
    return json.toJSONString();
}

From source file:com.vmware.identity.idm.server.RsaAuthSessionCache.java

public AuthenticationSession getSession(String tenantName, String cachedSessionId) {
    ConcurrentHashMap<String, AuthenticationSession> sessionCache = _rsaSessionCacheLookup
            .get(tenantName.toLowerCase());

    if (sessionCache == null) {
        return null;
    }/*from  w w w. j  av a2 s .  c om*/
    return sessionCache.get(cachedSessionId);
}

From source file:org.wso2.carbon.event.processor.core.internal.CarbonEventProcessorManagementService.java

@Override
public void restoreState(byte[] bytes) {
    Map<Integer, ConcurrentHashMap<String, ExecutionPlan>> map = EventProcessorValueHolder
            .getEventProcessorService().getTenantSpecificExecutionPlans();
    HashMap<Integer, HashMap<String, byte[]>> snapshotDataList = (HashMap<Integer, HashMap<String, byte[]>>) ByteSerializer
            .BToO(bytes);/*from w  ww  . j  av a  2 s  .co m*/

    for (Map.Entry<Integer, HashMap<String, byte[]>> tenantEntry : snapshotDataList.entrySet()) {
        for (Map.Entry<String, byte[]> executionPlanData : tenantEntry.getValue().entrySet()) {
            ConcurrentHashMap<String, ExecutionPlan> executionPlanMap = map.get(tenantEntry.getKey());
            if (executionPlanMap != null) {
                ExecutionPlan executionPlan = executionPlanMap.get(executionPlanData.getKey());
                if (executionPlan != null) {
                    executionPlan.getExecutionPlanRuntime().restore(executionPlanData.getValue());
                } else {
                    throw new EventManagementException("No execution plans with name '"
                            + executionPlanData.getKey() + "' exist for tenant  " + tenantEntry.getKey());
                }
            } else {
                throw new EventManagementException(
                        "No execution plans exist for tenant  " + tenantEntry.getKey());
            }
        }
    }
}

From source file:com.redhat.red.offliner.ftest.SinglePlaintextDownloadNoChecksumFTest.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  w  w.  j a  v a2s.com*/
@Test
public void run() throws Exception {
    // We only need one repo server.
    TestRepositoryServer server = newRepositoryServer();

    // Generate some test content
    String path = contentGenerator.newArtifactPath("jar");
    byte[] content = contentGenerator.newBinaryContent(1024);

    // 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.registerContent(path, content);
    server.registerContent(path + Main.SHA_SUFFIX, sha1Hex(content));
    server.registerContent(path + Main.MD5_SUFFIX, md5Hex(content));

    // Write the plaintext file we'll use as input.
    File plaintextList = temporaryFolder.newFile("artifact-list." + getClass().getSimpleName() + ".txt");
    String pathWithChecksum = contentGenerator.newPlaintextEntryWithoutChecksum(path);
    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"));

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

    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));
}

From source file:org.starnub.commandparser.CommandParser.java

private void handleCommand(ObjectEvent objectEvent) {
    StarNubEventTwo starNubEventTwo = (StarNubEventTwo) objectEvent;
    PlayerSession playerSession = (PlayerSession) starNubEventTwo.getEVENT_DATA();
    String fullCommandString = (String) starNubEventTwo.getEVENT_DATA_2();

    List<String> argsList = new ArrayList<>();
    Matcher m = Pattern.compile("([^\"]\\S*|\".+?\")\\s*").matcher(fullCommandString);
    while (m.find()) {
        argsList.add(m.group(1).replace("\"", ""));
    }/*from w ww . j  a va2  s .c o  m*/

    if (argsList.size() < 1) {
        return;
    }

    String commandString = argsList.get(0).replace("/", "").toLowerCase();
    ConcurrentHashMap<String, Command> commands = PluggableManager.getInstance().getCOMMANDS();
    Command command = commands.get(commandString);

    if (command == null) {
        new StarNubEventTwo("Player_Command_Failed_No_Command", playerSession, fullCommandString);
        sendChatMessage(playerSession,
                "Command named \"" + commandString + "\" does not exist or is not loaded.");
        return;
    }

    /* Splits are number of splits on spaces , I.E /r hi how are you (split on 2) = [hi, how are you] */
    int customSplit = command.getCustomSplit();
    boolean fullPermission = true;
    if (customSplit != 0) {
        System.out.println(argsList);
        argsList.clear();
        Collections.addAll(argsList, StringUtils.stripAll(fullCommandString.split(" ", customSplit + 2)));
        System.out.println(argsList);
        fullPermission = false;
    }

    /* Remove the plugin command from the args list*/
    argsList.remove(0);

    CanUse canUse = command.getCanUse();
    Connection connection = playerSession.getCONNECTION();
    boolean isInGame = true;
    if (!(connection instanceof ProxyConnection)) {
        isInGame = false;
    }

    switch (canUse) {
    case PLAYER: {
        if (!isInGame) {
            new StarNubEventTwo("Player_Command_Failed_Remote_Player_Cannot_Use", playerSession,
                    fullCommandString);
            sendChatMessage(playerSession, "Remote Player's cannot use the command \"" + commandString + "\".");
            return;
        }
        break;
    }
    case REMOTE_PLAYER: {
        if (isInGame) {
            new StarNubEventTwo("Player_Command_Failed_Player_Cannot_Use", playerSession, fullCommandString);
            sendChatMessage(playerSession, "Player's cannot use the command \"" + commandString + "\".");
            return;
        }
        break;
    }
    }

    String commandOwner = command.getDetails().getORGANIZATION().toLowerCase();
    String main_arg = null;
    String args[];
    boolean hasPermission;
    if (argsList.size() > 0) {
        main_arg = argsList.get(0);
        boolean hasMainArg = false;
        for (String arg : command.getMainArgs()) {
            if (arg.equals(main_arg)) {
                hasMainArg = true;
                break;
            }
        }
        if (!hasMainArg) {
            sendChatMessage(playerSession, "Command named \"" + commandString
                    + "\" does not have any main argument named \"" + main_arg + "\'.");
            return;
        }
        args = argsList.toArray(new String[argsList.size()]);
        hasPermission = playerSession.hasPermission(commandOwner, commandString, main_arg, true);
    } else {
        args = new String[0];
        fullPermission = false;
        hasPermission = playerSession.hasPermission(commandOwner, commandString, true);
    }

    if (!hasPermission) {
        String failedCommand = commandString;
        String permissionString = commandOwner + "." + commandString;
        if (fullPermission) {
            failedCommand = failedCommand + " " + main_arg;
            permissionString = permissionString + "." + main_arg;
        }
        new StarNubEventTwo("Player_Command_Failed_Permissions", playerSession, fullCommandString);
        sendChatMessage(playerSession, "You do not have permission to use the command \"/" + failedCommand
                + "\"." + " Permission required: \"" + permissionString + "\".");
        return;
    }
    new StarNubEventTwo("Player_Command_Delivered_To_Plugin", playerSession, fullCommandString);
    command.onCommand(playerSession, commandString, args.length, args);
}