Example usage for java.util.concurrent ConcurrentHashMap put

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

Introduction

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

Prototype

public V put(K key, V value) 

Source Link

Document

Maps the specified key to the specified value in this table.

Usage

From source file:com.alibaba.jstorm.daemon.supervisor.SyncProcessEvent.java

/**
 * launch a worker in local mode/*from w  w  w. j a va2s  .c  o m*/
 *
 * @param conf
 * @param sharedcontext
 * @param topologyId
 * @param supervisorId
 * @param port
 * @param workerId
 * @param workerThreadPidsAtom
 * @throws Exception
 */
public void launchWorker(Map conf, IContext sharedcontext, String topologyId, String supervisorId, Integer port,
        String workerId, ConcurrentHashMap<String, String> workerThreadPidsAtom) throws Exception {

    String pid = UUID.randomUUID().toString();

    WorkerShutdown worker = Worker.mk_worker(conf, sharedcontext, topologyId, supervisorId, port, workerId,
            null);

    ProcessSimulator.registerProcess(pid, worker);

    workerThreadPidsAtom.put(workerId, pid);

}

From source file:io.crate.integrationtests.BlobHttpIntegrationTest.java

protected boolean mget(String[] uris, Header[][] headers, final String[] expectedContent) throws Throwable {
    final CountDownLatch latch = new CountDownLatch(uris.length);
    final ConcurrentHashMap<Integer, Boolean> results = new ConcurrentHashMap<>(uris.length);
    for (int i = 0; i < uris.length; i++) {
        final int indexerId = i;
        final String uri = uris[indexerId];
        final Header[] header = headers[indexerId];
        final String expected = expectedContent[indexerId];
        Thread thread = new Thread() {
            @Override//from w  w w.j ava 2s . c o m
            public void run() {
                try {
                    CloseableHttpResponse res = get(uri, header);
                    Integer statusCode = res.getStatusLine().getStatusCode();
                    String resultContent = EntityUtils.toString(res.getEntity());
                    if (!resultContent.equals(expected)) {
                        logger.warn(String.format(Locale.ENGLISH,
                                "incorrect response %d -- length: %d expected: %d%n", indexerId,
                                resultContent.length(), expected.length()));
                    }
                    results.put(indexerId,
                            (statusCode >= 200 && statusCode < 300 && expected.equals(resultContent)));
                } catch (Exception e) {
                    logger.warn("**** failed indexing thread {}", e, indexerId);
                } finally {
                    latch.countDown();
                }
            }
        };
        thread.start();
    }
    assertThat(latch.await(30L, TimeUnit.SECONDS), is(true));
    return Iterables.all(results.values(), new Predicate<Boolean>() {
        @Override
        public boolean apply(Boolean input) {
            return input;
        }
    });
}

From source file:org.wso2.carbon.device.mgt.output.adapter.websocket.WebsocketEventAdapter.java

@Override
public void init() throws OutputEventAdapterException {
    tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();

    //ExecutorService will be assigned  if it is null
    if (executorService == null) {
        int minThread;
        int maxThread;
        long defaultKeepAliveTime;
        int jobQueSize;

        //If global properties are available those will be assigned else constant values will be assigned
        if (globalProperties.get(WebsocketEventAdapterConstants.ADAPTER_MIN_THREAD_POOL_SIZE_NAME) != null) {
            minThread = Integer.parseInt(
                    globalProperties.get(WebsocketEventAdapterConstants.ADAPTER_MIN_THREAD_POOL_SIZE_NAME));
        } else {//from  w w  w . j a v a 2s  .c  o m
            minThread = WebsocketEventAdapterConstants.ADAPTER_MIN_THREAD_POOL_SIZE;
        }

        if (globalProperties.get(WebsocketEventAdapterConstants.ADAPTER_MAX_THREAD_POOL_SIZE_NAME) != null) {
            maxThread = Integer.parseInt(
                    globalProperties.get(WebsocketEventAdapterConstants.ADAPTER_MAX_THREAD_POOL_SIZE_NAME));
        } else {
            maxThread = WebsocketEventAdapterConstants.ADAPTER_MAX_THREAD_POOL_SIZE;
        }

        if (globalProperties.get(WebsocketEventAdapterConstants.ADAPTER_KEEP_ALIVE_TIME_NAME) != null) {
            defaultKeepAliveTime = Integer.parseInt(
                    globalProperties.get(WebsocketEventAdapterConstants.ADAPTER_KEEP_ALIVE_TIME_NAME));
        } else {
            defaultKeepAliveTime = WebsocketEventAdapterConstants.DEFAULT_KEEP_ALIVE_TIME_IN_MILLIS;
        }

        if (globalProperties.get(WebsocketEventAdapterConstants.ADAPTER_EXECUTOR_JOB_QUEUE_SIZE_NAME) != null) {
            jobQueSize = Integer.parseInt(
                    globalProperties.get(WebsocketEventAdapterConstants.ADAPTER_EXECUTOR_JOB_QUEUE_SIZE_NAME));
        } else {
            jobQueSize = WebsocketEventAdapterConstants.ADAPTER_EXECUTOR_JOB_QUEUE_SIZE;
        }

        executorService = new ThreadPoolExecutor(minThread, maxThread, defaultKeepAliveTime,
                TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(jobQueSize));
    }

    streamId = eventAdapterConfiguration.getOutputStreamIdOfWso2eventMessageFormat();
    if (streamId == null || streamId.isEmpty()) {
        throw new OutputEventAdapterRuntimeException("UI event adapter needs a output stream id");
    }

    // fetch the "streamDefinition" corresponding to the "streamId" and then fetch the different attribute types
    // of the streamDefinition corresponding to the event's streamId. They are required when validating values in
    // the events against the streamDef attributes.
    StreamDefinition streamDefinition = getStreamDefinition(streamId);
    streamMetaAttributes = streamDefinition.getMetaData();
    streamCorrelationAttributes = streamDefinition.getCorrelationData();
    streamPayloadAttributes = streamDefinition.getPayloadData();

    ConcurrentHashMap<Integer, ConcurrentHashMap<String, String>> tenantSpecifcEventOutputAdapterMap = WebsocketEventAdaptorServiceDataHolder
            .getTenantSpecificOutputEventStreamAdapterMap();

    ConcurrentHashMap<String, String> streamSpecifAdapterMap = tenantSpecifcEventOutputAdapterMap.get(tenantId);

    if (streamSpecifAdapterMap == null) {
        streamSpecifAdapterMap = new ConcurrentHashMap<>();
        if (null != tenantSpecifcEventOutputAdapterMap.putIfAbsent(tenantId, streamSpecifAdapterMap)) {
            streamSpecifAdapterMap = tenantSpecifcEventOutputAdapterMap.get(tenantId);
        }
    }

    String adapterName = streamSpecifAdapterMap.get(streamId);

    if (adapterName != null) {
        throw new OutputEventAdapterException(("An Output websocket event adapter \"" + adapterName
                + "\" is already" + " exist for stream id \"" + streamId + "\""));
    } else {
        streamSpecifAdapterMap.put(streamId, eventAdapterConfiguration.getName());

        ConcurrentHashMap<Integer, ConcurrentHashMap<String, LinkedBlockingDeque<Object>>> tenantSpecificStreamMap = WebsocketEventAdaptorServiceDataHolder
                .getTenantSpecificStreamEventMap();
        ConcurrentHashMap<String, LinkedBlockingDeque<Object>> streamSpecificEventsMap = tenantSpecificStreamMap
                .get(tenantId);
        if (streamSpecificEventsMap == null) {
            streamSpecificEventsMap = new ConcurrentHashMap<>();
            if (null != tenantSpecificStreamMap.putIfAbsent(tenantId, streamSpecificEventsMap)) {
                streamSpecificEventsMap = tenantSpecificStreamMap.get(tenantId);
            }
        }
        streamSpecificEvents = streamSpecificEventsMap.get(streamId);
        if (streamSpecificEvents == null) {
            streamSpecificEvents = new LinkedBlockingDeque<>();
            if (null != streamSpecificEventsMap.putIfAbsent(streamId, streamSpecificEvents)) {
                streamSpecificEvents = streamSpecificEventsMap.get(streamId);
            }
        }
    }

    if (globalProperties.get(WebsocketEventAdapterConstants.ADAPTER_EVENT_QUEUE_SIZE_NAME) != null) {
        try {
            queueSize = Integer.parseInt(
                    globalProperties.get(WebsocketEventAdapterConstants.ADAPTER_EVENT_QUEUE_SIZE_NAME));
        } catch (NumberFormatException e) {
            log.error("String does not have the appropriate format for conversion." + e.getMessage());
            queueSize = WebsocketEventAdapterConstants.EVENTS_QUEUE_SIZE;
        }
    } else {
        queueSize = WebsocketEventAdapterConstants.EVENTS_QUEUE_SIZE;
    }
}

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

private void loadEntity(final EntityType type) throws FalconException {
    try {//from   ww  w.  j a  va2  s .  co  m
        final ConcurrentHashMap<String, Entity> entityMap = dictionary.get(type);
        FileStatus[] files = fs.globStatus(new Path(storePath, type.name() + Path.SEPARATOR + "*"));
        if (files != null) {
            final ExecutorService service = Executors.newFixedThreadPool(100);
            for (final FileStatus file : files) {
                service.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String fileName = file.getPath().getName();
                            String encodedEntityName = fileName.substring(0, fileName.length() - 4); // drop
                            // ".xml"
                            String entityName = URLDecoder.decode(encodedEntityName, UTF_8);
                            Entity entity = restore(type, entityName);
                            entityMap.put(entityName, entity);
                        } catch (IOException | FalconException e) {
                            LOG.error("Unable to restore entity of", file);
                        }
                    }
                });
            }
            service.shutdown();
            if (service.awaitTermination(10, TimeUnit.MINUTES)) {
                LOG.info("Restored Configurations for entity type: {} ", type.name());
            } else {
                LOG.warn("Time out happened while waiting for all threads to finish while restoring entities "
                        + "for type: {}", type.name());
            }
            // Checking if all entities were loaded
            if (entityMap.size() != files.length) {
                throw new FalconException("Unable to restore configurations for entity type " + type.name());
            }
            for (Entity entity : entityMap.values()) {
                onReload(entity);
            }
        }
    } catch (IOException e) {
        throw new FalconException("Unable to restore configurations", e);
    } catch (InterruptedException e) {
        throw new FalconException(
                "Failed to restore configurations in 10 minutes for entity type " + type.name());
    }
}

From source file:spade.utility.BitcoinTools.java

public void writeBlocksToCSV(int startIndex, int endIndex) {
    // Block block, int lastBlockId
    int lastBlockId = -1;
    final BitcoinTools bitcoinTools = new BitcoinTools();

    String pattern = "#.##";
    DecimalFormat decimalFormat = new DecimalFormat(pattern);

    final ConcurrentHashMap<Integer, Block> blockMap = new ConcurrentHashMap<Integer, Block>();
    final AtomicInteger currentBlock = new AtomicInteger(startIndex);
    final int stopIndex = endIndex;
    final int totalThreads = Runtime.getRuntime().availableProcessors();

    class BlockFetcher implements Runnable {

        public void run() {

            while (true) {
                if (blockMap.size() > totalThreads * 5) { // max objects to hold in memory max 1 MB * totalThreads * factor
                    try {
                        Thread.sleep(100);
                        continue;
                    } catch (Exception exception) {
                    }/*from   w  ww  . j a  va2 s  .  c o m*/
                }

                int blockToFetch = currentBlock.getAndIncrement();
                try {
                    blockMap.put(blockToFetch, bitcoinTools.getBlock(blockToFetch));
                } catch (JSONException exception) {
                    Bitcoin.log(Level.SEVERE, "Block " + blockToFetch + " has invalid json. Redownloading.",
                            exception);
                    try {
                        blockMap.put(blockToFetch, bitcoinTools.getBlock(blockToFetch));
                    } catch (JSONException ex) {
                        Bitcoin.log(Level.SEVERE, "Block " + blockToFetch + " couldn't be included in CSV.",
                                ex);
                    }
                }
                if (blockToFetch >= stopIndex) {
                    break;
                }
            }
        }
    }

    ArrayList<Thread> workers = new ArrayList<Thread>();
    for (int i = 0; i < totalThreads; i++) {
        Thread th = new Thread(new BlockFetcher());
        workers.add(th);
        th.start();
    }

    int percentageCompleted = 0;

    for (int i = startIndex; i < endIndex; i++) {

        try {

            Block block;
            while (!blockMap.containsKey(i)) {

            }
            block = blockMap.get(i);
            blockMap.remove(i);
            lastBlockId = writeBlockToCSV(block, lastBlockId);

            if ((((i - startIndex + 1) * 100) / (endIndex - startIndex)) > percentageCompleted) {
                Runtime rt = Runtime.getRuntime();
                long totalMemory = rt.totalMemory() / 1024 / 1024;
                long freeMemory = rt.freeMemory() / 1024 / 1024;
                long usedMemory = totalMemory - freeMemory;
                System.out.print("| Cores: " + rt.availableProcessors() + " | Threads: " + totalThreads
                        + " | Heap (MB) - total: " + totalMemory + ", %age free: "
                        + (freeMemory * 100) / totalMemory + " | At Block: " + (i - startIndex + 1) + " / "
                        + (endIndex - startIndex) + " | Percentage Completed: " + percentageCompleted
                        // + " |\r");
                        + " |\n");
            }

            percentageCompleted = ((i - startIndex + 1) * 100) / (endIndex - startIndex);

        } catch (IOException ex) {
            Bitcoin.log(Level.SEVERE, "Unexpected IOException. Stopping CSV creation.", ex);
            break;
        }
    }

    for (int i = 0; i < totalThreads; i++) {
        try {
            workers.get(i).interrupt();
            workers.get(i).join();
        } catch (InterruptedException exception) {
        }
    }

    System.out.println("\n\ndone with creating CSVes!");
}

From source file:org.wso2.carbon.event.input.adaptor.file.FileEventAdaptorType.java

private void createFileAdaptorListener(
        InputEventAdaptorMessageConfiguration inputEventAdaptorMessageConfiguration,
        InputEventAdaptorListener inputEventAdaptorListener,
        InputEventAdaptorConfiguration inputEventAdaptorConfiguration, AxisConfiguration axisConfiguration,
        String subscriptionId) {/*from  w ww .  ja v a2 s  . co  m*/
    log.info("New subscriber added for " + inputEventAdaptorConfiguration.getName());

    ConcurrentHashMap<String, FileTailerManager> tailerManagerConcurrentHashMap = tailerMap
            .get(inputEventAdaptorConfiguration.getName());
    if (tailerManagerConcurrentHashMap == null) {
        tailerManagerConcurrentHashMap = new ConcurrentHashMap<String, FileTailerManager>();
        if (null != tailerMap.putIfAbsent(inputEventAdaptorConfiguration.getName(),
                tailerManagerConcurrentHashMap)) {
            tailerManagerConcurrentHashMap = tailerMap.get(inputEventAdaptorConfiguration.getName());
        }
    }

    String filepath = inputEventAdaptorMessageConfiguration.getInputMessageProperties()
            .get(FileEventAdaptorConstants.EVENT_ADAPTOR_CONF_FILEPATH);
    FileTailerManager fileTailerManager = tailerManagerConcurrentHashMap.get(filepath);

    if (fileTailerManager == null) {
        FileTailerListener listener = new FileTailerListener(new File(filepath).getName());
        Tailer tailer = new Tailer(new File(filepath), listener);
        fileTailerManager = new FileTailerManager(tailer, listener);
        listener.addListener(subscriptionId, inputEventAdaptorListener);
        tailerManagerConcurrentHashMap.put(filepath, fileTailerManager);
        threadPoolExecutor.execute(tailer);
    } else {
        fileTailerManager.getListener().addListener(subscriptionId, inputEventAdaptorListener);
    }
}

From source file:com.gizwits.framework.activity.BaseActivity.java

/**
 * ??//ww w  . j a v a2s.  co m
 * 
 * @param map
 *            the map
 * @param json
 *            the json
 * @throws JSONException
 *             the JSON exception
 */
protected void inputDataToMaps(ConcurrentHashMap<String, Object> map, String json) throws JSONException {
    Log.i("revjson", json);
    JSONObject receive = new JSONObject(json);
    Iterator actions = receive.keys();
    while (actions.hasNext()) {

        String action = actions.next().toString();
        Log.i("revjson", "action=" + action);
        // 
        if (action.equals("cmd") || action.equals("qos") || action.equals("seq") || action.equals("version")) {
            continue;
        }
        JSONObject params = receive.getJSONObject(action);
        Log.i("revjson", "params=" + params);
        Iterator it_params = params.keys();
        while (it_params.hasNext()) {
            String param = it_params.next().toString();
            Object value = params.get(param);
            map.put(param, value);
            Log.i(TAG, "Key:" + param + ";value" + value);
        }
    }
}

From source file:org.wso2.cep.broker.RDBMSBrokerType.java

@Override
public void publish(String topic, Object message, BrokerConfiguration brokerConfiguration)
        throws BrokerEventProcessingException {
    try {/*from  www  .j a  va 2  s .  c o m*/
        String[] topicItems = topic.split("\\.");
        String databaseName = topicItems[0].trim();
        String tableName = topicItems[1].trim();

        ConcurrentHashMap<String, Connection> connectionMap = jdbcConnections.get(brokerConfiguration);

        if (connectionMap == null) {
            connectionMap = new ConcurrentHashMap<String, Connection>();
            jdbcConnections.put(brokerConfiguration, connectionMap);
        }
        Connection connection = connectionMap.get(databaseName);

        if (connection == null) {
            Class.forName(driverClassName);
            connection = DriverManager.getConnection(urlPrefix + "://"
                    + brokerConfiguration.getProperties().get(BROKER_CONF_RDBMS_PROPERTY_HOSTNAME_REFERENCE)
                    + ":" + brokerConfiguration.getProperties().get(BROKER_CONF_RDBMS_PROPERTY_PORT_REFERENCE)
                    + "/" + databaseName + "?user="
                    + brokerConfiguration.getProperties().get(BROKER_CONF_RDBMS_PROPERTY_USER_NAME_REFERENCE)
                    + "&password="
                    + brokerConfiguration.getProperties().get(BROKER_CONF_RDBMS_PROPERTY_PASSWORD_REFERENCE));
            connectionMap.put(databaseName, connection);
        }

        ConcurrentHashMap<String, TableInfo> tableInfoMap = tables.get(brokerConfiguration);
        TableInfo tableInfo;
        if (tableInfoMap == null || tableInfoMap.get(topic) == null) {
            tableInfo = initializeTableInfo(databaseName, tableName, message, brokerConfiguration, connection);
            if (tableInfoMap == null) {
                tableInfoMap = new ConcurrentHashMap<String, TableInfo>();
                tables.put(brokerConfiguration, tableInfoMap);
            }
        } else {
            tableInfo = tableInfoMap.get(topic);
        }

        PreparedStatement preparedStatement = tableInfo.getPreparedStatement();
        Map<String, Object> map = (Map<String, Object>) message;
        Attribute attribute;
        for (int i = 0; i < tableInfo.getColumnOrder().size(); i++) {
            attribute = tableInfo.getColumnOrder().get(i);
            switch (attribute.getType()) {
            case INT:
                preparedStatement.setInt(i + 1, (Integer) map.get(attribute.getName()));
                break;
            case LONG:
                preparedStatement.setLong(i + 1, (Long) map.get(attribute.getName()));
                break;
            case FLOAT:
                preparedStatement.setFloat(i + 1, (Float) map.get(attribute.getName()));
                break;
            case DOUBLE:
                preparedStatement.setDouble(i + 1, (Double) map.get(attribute.getName()));
                break;
            case STRING:
                preparedStatement.setString(i + 1, (String) map.get(attribute.getName()));
                break;
            case BOOL:
                preparedStatement.setBoolean(i + 1, (Boolean) map.get(attribute.getName()));
                break;
            }
        }
        preparedStatement.executeUpdate();
    } catch (SQLException e) {
        log.error(e);
    } catch (ClassNotFoundException e) {
        log.error(e);
    }
}

From source file:cc.osint.graphd.server.GraphServerHandler.java

public String executeRequest(Channel responseChannel, String clientId,
        ConcurrentHashMap<String, String> clientState, String request) throws Exception {
    StringBuffer rsb = new StringBuffer();
    String cmd;/*from   ww  w  .  ja  va  2s . co  m*/
    String[] args;

    if (request.indexOf(GraphServerProtocol.SPACE) != -1) {
        cmd = request.substring(0, request.indexOf(GraphServerProtocol.SPACE)).trim().toLowerCase();
        args = request.substring(request.indexOf(GraphServerProtocol.SPACE)).trim()
                .split(GraphServerProtocol.SPACE);
    } else {
        cmd = request.trim().toLowerCase();
        args = new String[0];
    }

    // USE GRAPH: use <graphName>
    if (cmd.equals(GraphServerProtocol.CMD_USE)) {
        if (null == nameGraphMap.get(args[0])) {
            rsb.append(GraphServerProtocol.R_ERR);
            rsb.append(" DB_NOT_EXIST");
        } else {
            if (null != clientState.get(ST_DB))
                clientState.remove(ST_DB);
            clientState.put(ST_DB, args[0]);
            rsb.append(GraphServerProtocol.R_OK);
        }

        // CREATE GRAPH: create <graphName>
    } else if (cmd.equals(GraphServerProtocol.CMD_CREATE)) {
        if (null != nameGraphMap.get(args[0])) {
            rsb.append(GraphServerProtocol.R_ERR);
            rsb.append(" DB_ALREADY_EXISTS");
        } else {
            Graph newGraph = new Graph(args[0]);
            nameGraphMap.put(args[0], newGraph);
            WeakReference<Graph> graphRef = new WeakReference<Graph>(newGraph);
            GraphCommandExecutor graphCommandExecutor = new GraphCommandExecutor(args[0], graphRef);
            graphCommandExecutorService.execute(graphCommandExecutor);
            graphCommandExecutorMap.put(args[0], graphCommandExecutor);

            rsb.append(GraphServerProtocol.R_OK);
        }

        // DROP GRAPH: drop <graphName>
    } else if (cmd.equals(GraphServerProtocol.CMD_DROP)) {
        if (null == nameGraphMap.get(args[0])) {
            rsb.append(GraphServerProtocol.R_ERR);
            rsb.append(" DB_NOT_EXIST");
        } else {
            nameGraphMap.remove(args[0]);
            graphCommandExecutorMap.remove(args[0]);
            // TODO: DROP <KEY>
            // TODO: KILL graphCommandExecutor (via poisonPill message)
            rsb.append(GraphServerProtocol.R_OK);
        }

        // NAME THIS CONNECTION: namecon <name>
    } else if (cmd.equals(GraphServerProtocol.CMD_NAMECON)) {
        clientState.put(ST_NAMECON, args[0] + "-" + clientId);
        rsb.append(clientState.get(ST_NAMECON));
        rsb.append(GraphServerProtocol.NL);
        rsb.append(GraphServerProtocol.R_OK);

        // DUMP CLIENT STATE: clstate
    } else if (cmd.equals(GraphServerProtocol.CMD_CLSTATE)) {
        JSONObject result = new JSONObject(clientState);
        rsb.append(result.toString());
        rsb.append(GraphServerProtocol.NL);
        rsb.append(GraphServerProtocol.R_OK);

        // SERVER STATUS: sstat
    } else if (cmd.equals(GraphServerProtocol.CMD_SSTAT)) {
        JSONObject result = new JSONObject();
        JSONObject names = new JSONObject();
        names.put("TYPE_FIELD", Graph.TYPE_FIELD);
        names.put("KEY_FIELD", Graph.KEY_FIELD);
        names.put("WEIGHT_FIELD", Graph.WEIGHT_FIELD);
        names.put("EDGE_SOURCE_FIELD", Graph.EDGE_SOURCE_FIELD);
        names.put("EDGE_TARGET_FIELD", Graph.EDGE_TARGET_FIELD);
        names.put("RELATION_FIELD", Graph.RELATION_FIELD);
        names.put("VERTEX_TYPE", Graph.VERTEX_TYPE);
        names.put("EDGE_TYPE", Graph.EDGE_TYPE);
        result.put("names", names);

        rsb.append(result.toString());
        rsb.append(GraphServerProtocol.NL);
        rsb.append(GraphServerProtocol.R_OK);

        // LIST NAMED GRAPHS
    } else if (cmd.equals(GraphServerProtocol.CMD_LISTG)) {
        for (String name : nameGraphMap.keySet()) {
            rsb.append(name);
            rsb.append(GraphServerProtocol.NL);
        }
        rsb.append(GraphServerProtocol.R_OK);

        // GRAPH STATUS: gstat <name>
    } else if (cmd.equals(GraphServerProtocol.CMD_GSTAT)) {
        Graph gr0 = nameGraphMap.get(args[0]);
        if (null == gr0) {
            rsb.append(GraphServerProtocol.R_NOT_EXIST);
        } else {
            JSONObject result = new JSONObject();
            result.put("vertex_count", gr0.numVertices());
            result.put("edge_count", gr0.numEdges());
            rsb.append(result.toString());
            rsb.append(GraphServerProtocol.NL);
            rsb.append(GraphServerProtocol.R_OK);
        }

    } else {

        //
        // graph-specific operations
        //

        WeakReference<InboundChannelProcess> inboundChannelProcessRef = inboundChannelMap.get(clientId);

        //
        // async override handler
        // 

        if (cmd.startsWith("&")) {
            cmd = cmd.substring(1);
            request = request.substring(1);
            responseChannel.write(graphCommandExecutorMap.get(clientState.get(GraphServerHandler.ST_DB))
                    .execute(responseChannel, clientId, clientState, inboundChannelProcessRef.get(), request,
                            cmd, args)
                    + GraphServerProtocol.NL);
        } else {

            //
            // graph-specific, queue-driven ordered operations
            //

            GraphCommand graphCommand = new GraphCommand();
            graphCommand.responseChannel = responseChannel;
            graphCommand.clientId = clientId;
            graphCommand.clientState = clientState;
            graphCommand.inboundChannelProcess = inboundChannelProcessRef.get();
            graphCommand.request = request;
            graphCommand.cmd = cmd;
            graphCommand.args = args;
            graphCommand.poisonPill = false;

            graphCommandExecutorMap.get(clientState.get(GraphServerHandler.ST_DB)).queue(graphCommand);
        }

        // a null return value indicates it's been queued for execution
        // by the appropriate GraphCommandExecutor
        return null;
    }

    // unknown request
    if (rsb.toString().equals("")) {
        log.info("GraphServerProtocol.R_UNK: " + cmd);
        rsb.append(GraphServerProtocol.R_UNK);
        rsb.append(GraphServerProtocol.SPACE);
        rsb.append(cmd);
    }
    rsb.append(GraphServerProtocol.NL);
    return rsb.toString();
}

From source file:fastcall.FastCallSNP.java

private void calculateVCF(ConcurrentHashMap<Integer, String> posVCFMap, List<Integer> positionList,
        int currentChr, int startPos, String chrSeq, int[][] depth, String[][] base) {
    positionList.parallelStream().forEach(position -> {
        int index = position - startPos;
        byte refBase = (byte) (chrSeq.charAt(position - 1));
        int baseIndex = Arrays.binarySearch(bases, refBase);
        if (baseIndex < 0) {

        } else {/*from   ww  w .  j  a va2s  . c o  m*/
            String vcfStr = this.getVCFString(base[index], depth[index], currentChr, position, refBase);
            if (vcfStr != null) {
                posVCFMap.put(position,
                        this.getVCFString(base[index], depth[index], currentChr, position, refBase));
            }
        }
    });
}