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:org.wso2.carbon.event.output.adapter.ui.UIEventAdapter.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(UIEventAdapterConstants.ADAPTER_MIN_THREAD_POOL_SIZE_NAME) != null) {
            minThread = Integer/*  w  ww.ja  v a  2s.co m*/
                    .parseInt(globalProperties.get(UIEventAdapterConstants.ADAPTER_MIN_THREAD_POOL_SIZE_NAME));
        } else {
            minThread = UIEventAdapterConstants.ADAPTER_MIN_THREAD_POOL_SIZE;
        }

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

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

        if (globalProperties.get(UIEventAdapterConstants.ADAPTER_EXECUTOR_JOB_QUEUE_SIZE_NAME) != null) {
            jobQueSize = Integer.parseInt(
                    globalProperties.get(UIEventAdapterConstants.ADAPTER_EXECUTOR_JOB_QUEUE_SIZE_NAME));
        } else {
            jobQueSize = UIEventAdapterConstants.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");
    }

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

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

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

    String adapterName = streamSpecifAdapterMap.get(streamId);

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

        ConcurrentHashMap<Integer, ConcurrentHashMap<String, LinkedBlockingDeque<Object>>> tenantSpecificStreamMap = UIEventAdaptorServiceInternalValueHolder
                .getTenantSpecificStreamEventMap();
        ConcurrentHashMap<String, LinkedBlockingDeque<Object>> streamSpecificEventsMap = tenantSpecificStreamMap
                .get(tenantId);

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

        if (streamSpecificEvents == null) {
            streamSpecificEvents = new LinkedBlockingDeque<Object>();
            if (null != streamSpecificEventsMap.putIfAbsent(streamId, streamSpecificEvents)) {
                streamSpecificEvents = streamSpecificEventsMap.get(streamId);
            }
        }
    }

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

From source file:com.weibo.api.motan.registry.support.LocalRegistryService.java

@Override
public void doSubscribe(URL url, NotifyListener listener) {

    String subscribeKey = getSubscribeKey(url);
    ConcurrentHashMap<URL, ConcurrentHashSet<NotifyListener>> urlListeners = subscribeListeners
            .get(subscribeKey);//ww  w  . j  av a2s.  co m
    if (urlListeners == null) {
        subscribeListeners.putIfAbsent(subscribeKey,
                new ConcurrentHashMap<URL, ConcurrentHashSet<NotifyListener>>());
        urlListeners = subscribeListeners.get(subscribeKey);
    }

    ConcurrentHashSet<NotifyListener> listeners = urlListeners.get(url);
    if (listeners == null) {
        urlListeners.putIfAbsent(url, new ConcurrentHashSet<NotifyListener>());
        listeners = urlListeners.get(url);
    }

    listeners.add(listener);

    List<URL> urls = discover(url);
    if (urls != null && urls.size() > 0) {
        listener.notify(getUrl(), urls);
    }

    LoggerUtil.info("LocalRegistryService subscribe: url={}", url);
}

From source file:com.pearson.eidetic.driver.threads.RefreshAwsAccountVolumes.java

private HashMap<Integer, ConcurrentHashMap<Region, ArrayList<Volume>>> refreshCreateSnapshotVolumes(
        Volume volume, JSONObject createSnapshot, ConcurrentHashMap<Region, ArrayList<Volume>> localVolumeTime,
        ConcurrentHashMap<Region, ArrayList<Volume>> localVolumeNoTime, Region region) {
    HashMap<Integer, ConcurrentHashMap<Region, ArrayList<Volume>>> resultSet = new HashMap();
    //New volume detected! Return value continue     
    if (!localVolumeNoTime.get(region).contains(volume) && !localVolumeTime.get(region).contains(volume)) {
        if (createSnapshot.containsKey("RunAt")) {//Add tries
            try {
                localVolumeTime.get(region).add(volume);
            } catch (Exception e) {
                logger.info("awsAccountNickname=\"" + uniqueAwsAccountIdentifier_
                        + "\",Event=\"Error\", Error=\"error adding vol to VolumeTime_\", Volume_id=\""
                        + volume.getVolumeId() + "\", stacktrace=\"" + e.toString() + System.lineSeparator()
                        + StackTrace.getStringFromStackTrace(e) + "\"");
            }/*from  w w  w. j  a v a 2 s .c o  m*/
            volTimeHasTag_.put(volume, true);
        } else {
            try {
                localVolumeNoTime.get(region).add(volume);
            } catch (Exception e) {
                logger.info("awsAccountNickname=\"" + uniqueAwsAccountIdentifier_
                        + "\",Event=\"Error\", Error=\"error adding vol to VolumeTime_\", Volume_id=\""
                        + volume.getVolumeId() + "\", stacktrace=\"" + e.toString() + System.lineSeparator()
                        + StackTrace.getStringFromStackTrace(e) + "\"");
            }
            volNoTimeHasTag_.put(volume, true);
        }
        resultSet.put(0, localVolumeTime);
        resultSet.put(1, localVolumeNoTime);
        return resultSet;
    }

    //Old volume Tag is left unchanged
    if ((createSnapshot.containsKey("RunAt")) && localVolumeTime.get(region).contains(volume)) {
        volTimeHasTag_.replace(volume, true);
    } else if (!(createSnapshot.containsKey("RunAt")) && localVolumeNoTime.get(region).contains(volume)) {
        volNoTimeHasTag_.replace(volume, true);

        //If we change the value of the tag.
    } else if ((createSnapshot.containsKey("RunAt")) && localVolumeNoTime.get(region).contains(volume)) {
        volTimeHasTag_.put(volume, true);
        volNoTimeHasTag_.replace(volume, false);
        try {
            localVolumeTime.get(region).add(volume);
        } catch (Exception e) {
            logger.info("awsAccountNickname=\"" + uniqueAwsAccountIdentifier_
                    + "\",Event=\"Error\", Error=\"error adding vol to VolumeNoTime_\", Volume_id=\""
                    + volume.getVolumeId() + "\", stacktrace=\"" + e.toString() + System.lineSeparator()
                    + StackTrace.getStringFromStackTrace(e) + "\"");
        }
    } else if (!(createSnapshot.containsKey("RunAt")) && localVolumeTime.get(region).contains(volume)) {
        volNoTimeHasTag_.put(volume, true);
        volTimeHasTag_.replace(volume, false);
        try {
            localVolumeNoTime.get(region).add(volume);
        } catch (Exception e) {
            logger.info("awsAccountNickname=\"" + uniqueAwsAccountIdentifier_
                    + "\",Event=\"Error\", Error=\"error adding vol to VolumeNoTime_\", Volume_id=\""
                    + volume.getVolumeId() + "\", stacktrace=\"" + e.toString() + System.lineSeparator()
                    + StackTrace.getStringFromStackTrace(e) + "\"");
        }
    } else {
        logger.error(
                "Event=Error, Error=\"Malformed Eidetic Tag\", Volume_id=\"" + volume.getVolumeId() + "\"");
    }
    resultSet.put(0, localVolumeTime);
    resultSet.put(1, localVolumeNoTime);
    return resultSet;
}

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;//from  w  ww  .j  ava  2 s  .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.wso2.carbon.event.output.adaptor.mysql.MysqlEventAdaptorType.java

/**
 * @param outputEventMessageConfiguration
 *                 - topic name to publish messages
 * @param message  - is and Object[]{Event, EventDefinition}
 * @param outputEventAdaptorConfiguration
 *
 * @param tenantId//from w  w  w  .j ava2 s. c o  m
 */
public void publish(OutputEventAdaptorMessageConfiguration outputEventMessageConfiguration, Object message,
        OutputEventAdaptorConfiguration outputEventAdaptorConfiguration, int tenantId) {
    Connection con = null;
    PreparedStatement stmt = null;
    try {
        if (message instanceof Map) {
            //                String databaseName = outputEventMessageConfiguration.getOutputMessageProperties().get(MysqlEventAdaptorConstants.ADAPTOR_MYSQL_DATABASE_NAME);
            String tableName = outputEventMessageConfiguration.getOutputMessageProperties()
                    .get(MysqlEventAdaptorConstants.ADAPTOR_MYSQL_TABLE_NAME);
            String executionMode = outputEventMessageConfiguration.getOutputMessageProperties()
                    .get(MysqlEventAdaptorConstants.ADAPTOR_MYSQL_EXECUTION_MODE);
            String updateColKeys = outputEventMessageConfiguration.getOutputMessageProperties()
                    .get(MysqlEventAdaptorConstants.ADAPTOR_MYSQL_UPDATE_KEYS);

            ConcurrentHashMap<String, TableInfo> tableInfoMap = tables.get(outputEventMessageConfiguration);

            TableInfo tableInfo;
            if (tableInfoMap == null || tableInfoMap.get(tableName) == null) {
                tableInfo = initializeDatabaseTableInfo(tableName, executionMode, updateColKeys, message,
                        outputEventAdaptorConfiguration);
                if (tableInfoMap == null) {
                    tableInfoMap = new ConcurrentHashMap<String, TableInfo>();
                    tables.put(outputEventAdaptorConfiguration, tableInfoMap);
                }
                if (tableInfo != null) {
                    tableInfoMap.put(tableName, tableInfo);
                } else {
                    throw new OutputEventAdaptorEventProcessingException("Unable to initialize the table.");
                }
            } else {
                tableInfo = tableInfoMap.get(tableName);
            }

            con = pooledDataSources.get(outputEventAdaptorConfiguration).getConnection();
            Map<String, Object> map = (Map<String, Object>) message;

            boolean executeInsert = true;
            synchronized (this) {
                if (tableInfo.isUpdateMode()) {
                    stmt = con.prepareStatement(tableInfo.getPreparedExistenceCheckStatement());
                    boolean success = populateStatement(map, stmt, tableInfo.getExistenceCheckColumnOrder(),
                            true);
                    if (!success) {
                        log.debug("Null value detected in the composite keys. Can't proceed to update the DB.");
                        return;
                    }
                    ResultSet rs = stmt.executeQuery();
                    if (rs.next()) {
                        executeInsert = false;
                        stmt = con.prepareStatement(tableInfo.getPreparedUpdateStatement());
                        populateStatement(map, stmt, tableInfo.getUpdateColumnOrder(), false);
                        stmt.execute();
                    }
                }

                if (executeInsert) {
                    stmt = con.prepareStatement(tableInfo.getPreparedInsertStatement());
                    populateStatement(map, stmt, tableInfo.getInsertColumnOrder(), false);
                    stmt.execute();
                }
            }
        }
    } catch (SQLException e) {
        log.error(e);
    } finally {
        cleanupConnections(stmt, con);
    }
}

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

@Override
public void publish(String topic, Object message, BrokerConfiguration brokerConfiguration)
        throws BrokerEventProcessingException {
    try {/*  w  w  w  .ja va 2  s  .  co  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:org.sindice.siren.index.Utils.java

/**
 * Flatten a list of triples to n-tuples containing many objects for the same
 * predicate. Generate one n-tuple per predicate.
 * /*from  w  w  w. j  a  va  2 s .  co m*/
 * @param values
 *          The list of n-triples.
 * @return The n-tuples concatenated.
 */
private static synchronized void flattenNTriples(final StringBuilder triples,
        final ConcurrentHashMap<String, ConcurrentSkipListSet<String>> map,
        final ConcurrentSkipListSet<String> types, final ConcurrentSkipListSet<String> label,
        final ConcurrentSkipListSet<String> description, final boolean isOut) {
    try {
        initParser();
        parser.parse(new StringReader(triples.toString()), "");
        for (Statement st : collector.getStatements()) {
            sb.setLength(0);
            final String subject = sb.append('<').append(st.getSubject().toString()).append('>').toString();
            sb.setLength(0);
            final String predicate = sb.append('<').append(st.getPredicate().toString()).append('>').toString();
            sb.setLength(0);
            final String object = (st.getObject() instanceof URI)
                    ? sb.append('<').append(st.getObject().toString()).append('>').toString()
                    : st.getObject().toString();
            if (label != null && predicate.equals(RDFS_LABEL))
                label.add(object);
            if (description != null && predicate.equals(DC_DESCRIPTION))
                description.add(object);
            if (description != null && predicate.equals(DBP_ABSTRACT))
                description.add(object);
            if (types != null && predicate.equals(RDF_TYPE)) {
                types.add(object);
            } else {
                ConcurrentSkipListSet<String> hs = map.get(predicate);
                final String toAdd = isOut ? object : subject;
                if (hs == null) {
                    hs = new ConcurrentSkipListSet<String>();
                    map.put(predicate, hs);
                }
                if (hs.size() < 65535) // 2 ^ 16 - 1
                    hs.add(toAdd);
            }
        }
    } catch (RDFParseException e1) {
    } catch (RDFHandlerException e1) {
    } catch (IOException e1) {
    }
    triples.setLength(0);
}

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

public void unsubscribe(InputEventAdaptorMessageConfiguration inputEventAdaptorMessageConfiguration,
        InputEventAdaptorConfiguration inputEventAdaptorConfiguration, AxisConfiguration axisConfiguration,
        String subscriptionId) {// ww w. jav a  2s  . co  m

    ConcurrentHashMap<InputEventAdaptorMessageConfiguration, ConcurrentHashMap<String, EventAdaptorConf>> tenantSpecificAdaptorListenerMap = inputEventAdaptorListenerMap
            .get(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true));
    if (tenantSpecificAdaptorListenerMap != null) {
        Map<String, EventAdaptorConf> map = tenantSpecificAdaptorListenerMap
                .get(inputEventAdaptorMessageConfiguration);
        if (map != null) {
            map.remove(subscriptionId);
        }
    }

}

From source file:com.yahoo.elide.core.EntityDictionary.java

/**
 * Retrieve the accessible object for a field.
 *
 * @param targetClass the object to get//from   w w  w.j  av  a2  s .  co m
 * @param fieldName the field name to get or invoke equivalent get method
 * @return the value
 */
public AccessibleObject getAccessibleObject(Class<?> targetClass, String fieldName) {
    ConcurrentHashMap<String, AccessibleObject> map = entityBinding(targetClass).accessibleObject;
    return map.get(fieldName);
}

From source file:com.yahoo.elide.core.EntityDictionary.java

/**
 * Get the true field/method name from an alias.
 *
 * @param entityClass Entity name//from w  w  w  .  ja v  a2  s. co  m
 * @param alias Alias to convert
 * @return Real field/method name as a string. null if not found.
 */
public String getNameFromAlias(Class<?> entityClass, String alias) {
    ConcurrentHashMap<String, String> map = entityBinding(entityClass).aliasesToFields;
    if (map != null) {
        return map.get(alias);
    }
    return null;
}