List of usage examples for java.util.concurrent ConcurrentHashMap put
public V put(K key, V value)
From source file:org.wso2.carbon.governance.metadata.Util.java
private static Map<String, BaseProvider> getBaseProviderMap() throws MetadataException { if (baseProviderMap != null) { return baseProviderMap; }//w ww . j av a 2s .c o m ConcurrentHashMap<String, BaseProvider> providerMap = new ConcurrentHashMap<String, BaseProvider>(); try { FileInputStream fileInputStream = new FileInputStream(getConfigFile()); StAXOMBuilder builder = new StAXOMBuilder(fileInputStream); OMElement configElement = builder.getDocumentElement(); OMElement metadataProviders = configElement.getFirstChildWithName(new QName("metadataProviders")) .getFirstChildWithName(new QName("baseProviders")); Iterator<OMElement> itr = metadataProviders.getChildrenWithLocalName("provider"); while (itr.hasNext()) { OMElement metadataProvider = itr.next(); String providerClass = metadataProvider.getAttributeValue(new QName("class")).trim(); String mediaType = metadataProvider.getAttributeValue(new QName(Constants.ATTRIBUTE_MEDIA_TYPE)); String versionMediaType = metadataProvider .getAttributeValue(new QName(Constants.ATTRIBUTE_VERSION_MEDIA_TYPE)); ClassLoader loader = Thread.currentThread().getContextClassLoader(); Class<BaseProvider> classObj = (Class<BaseProvider>) Class.forName(providerClass, true, loader); if (!providerMap.containsKey(mediaType)) { providerMap.put(mediaType, (BaseProvider) classObj.getConstructors()[0].newInstance(mediaType, versionMediaType)); } else { // log.error("Classification URI already exists") } } } catch (Exception e) { throw new MetadataException(e.getMessage(), e); } return Util.baseProviderMap = providerMap; }
From source file:org.seedstack.mqtt.internal.MqttModuleTest.java
/** * Test method for//w w w .ja v a 2s . c o m * {@link org.seedstack.mqtt.internal.MqttModule#configure()}. */ @Test public void testConfigure(@Mocked final Binder binder, @Mocked final MqttClientUtils mqttClientUtils) { ConcurrentHashMap<String, MqttClientDefinition> mqttClientDefinitions = new ConcurrentHashMap<String, MqttClientDefinition>(); ConcurrentHashMap<String, IMqttClient> mqttClients = new ConcurrentHashMap<String, IMqttClient>(); final String uri = "uri"; final String clientId = "id"; final String clientName = "name"; MqttClientDefinition clientDefinition = new MqttClientDefinition(uri, clientId); mqttClientDefinitions.put(clientName, clientDefinition); mqttClients.put(clientName, mqttClient); MqttModule module = new MqttModule(mqttClients, mqttClientDefinitions); module.configure(binder); new Verifications() { { binder.bind(IMqttClient.class).annotatedWith(Names.named(clientName)).toInstance(mqttClient); } }; }
From source file:de.ks.flatadocdb.index.GlobalIndex.java
public boolean load() { final ObjectMapper mapper = getMapper(); int loaded = 0; Path filePath = repository.getPath().resolve(INDEX_FOLDER).resolve(INDEX_FILE); if (Files.exists(filePath)) { try {/*from www. j a va 2 s. c o m*/ @SuppressWarnings("unchecked") ArrayList<IndexElement> values = mapper.readValue(filePath.toFile(), ArrayList.class); for (IndexElement element : values) { element.setRepository(repository); String id = element.getId(); Serializable naturalId = element.getNaturalId(); idToElement.put(id, element); if (naturalId != null) { naturalIdToElement.put(new NaturalId(element.getEntityClass(), naturalId), element); } } loaded++; } catch (IOException e) { throw new RuntimeException(e); } } filePath = repository.getPath().resolve(INDEX_FOLDER).resolve(QUERY_FILE); if (Files.exists(filePath)) { try { @SuppressWarnings("unchecked") List<QueryWrapper> wrappers = mapper.readValue(filePath.toFile(), List.class); for (QueryWrapper wrapper : wrappers) { Query<?, ?> query = metaModel.getQuery(wrapper.owner, wrapper.queryName); ConcurrentHashMap<IndexElement, Optional<Object>> value = new ConcurrentHashMap<>(); queryElements.put(query, value); for (Map.Entry<String, Optional<Object>> entry : wrapper.elements.entrySet()) { value.put(idToElement.get(entry.getKey()), entry.getValue()); } } loaded++; } catch (IOException e) { throw new RuntimeException(e); } } return loaded == 2; }
From source file:com.epam.gepard.rest.jira.JiraSiteHandler.java
/** * Get a Jira query result in a map form. * * @param query is the jira query/*from w ww .j ava 2 s.c o m*/ * @return with the map of JIRA_ID - ticketInfo in JSONObject pairs as result of a Jira query. * @throws IOException in case of problem * @throws JSONException in case of problem */ public ConcurrentHashMap<String, JSONObject> collectIssues(final String query) throws IOException, JSONException { String jqlURL = getListOfIssuesByQueryUrl(query); WebRequest requestSettings = new WebRequest(new URL(jqlURL), HttpMethod.GET); requestSettings.setAdditionalHeader("Content-type", "application/json"); UnexpectedPage infoPage = webClient.getPage(requestSettings); if (infoPage.getWebResponse().getStatusCode() == HTTP_RESPONSE_OK) { String ticketList = infoPage.getWebResponse().getContentAsString(); JSONObject obj = new JSONObject(ticketList); String maxResults = obj.getString("maxResults"); String total = obj.getString("total"); if (Integer.valueOf(maxResults) < Integer.valueOf(total)) { throw new SimpleGepardException("ERROR: Too many issues belong to given query (" + total + "), please change the query to shorten the result list."); } JSONArray array = obj.getJSONArray("issues"); ConcurrentHashMap<String, JSONObject> map = new ConcurrentHashMap<>(); for (int i = 0; i < array.length(); i++) { JSONObject o = (JSONObject) array.get(i); map.put(o.getString("key"), o); } return map; } throw new SimpleGepardException("ERROR: Cannot fetch Issue list from JIRA, status code:" + infoPage.getWebResponse().getStatusCode()); }
From source file:org.apache.falcon.entity.store.ConfigurationStore.java
private synchronized void updateInternal(EntityType type, Entity entity) throws FalconException { try {//from w w w . java 2 s. c o m if (get(type, entity.getName()) != null) { persist(type, entity); ConcurrentHashMap<String, Entity> entityMap = dictionary.get(type); Entity oldEntity = entityMap.get(entity.getName()); onChange(oldEntity, entity); entityMap.put(entity.getName(), entity); } else { throw new FalconException(entity.toShortString() + " doesn't exist"); } } catch (IOException e) { throw new StoreAccessException(e); } AUDIT.info(type + "/" + entity.getName() + " is replaced into config store"); }
From source file:org.mobicents.servlet.restcomm.http.SmsMessagesEndpoint.java
@SuppressWarnings("unchecked") protected Response putSmsMessage(final String accountSid, final MultivaluedMap<String, String> data, final MediaType responseType) { secure(accountsDao.getAccount(accountSid), "RestComm:Create:SmsMessages"); try {//ww w . j a v a 2s . c o m validate(data); if (normalizePhoneNumbers) normalize(data); } catch (final RuntimeException exception) { return status(BAD_REQUEST).entity(exception.getMessage()).build(); } final String sender = data.getFirst("From"); final String recipient = data.getFirst("To"); final String body = data.getFirst("Body"); ConcurrentHashMap<String, String> customRestOutgoingHeaderMap = new ConcurrentHashMap<String, String>(); Iterator<String> iter = data.keySet().iterator(); while (iter.hasNext()) { String name = iter.next(); if (name.startsWith("X-")) { customRestOutgoingHeaderMap.put(name, data.getFirst(name)); } } final Timeout expires = new Timeout(Duration.create(60, TimeUnit.SECONDS)); try { Future<Object> future = (Future<Object>) ask(aggregator, new CreateSmsSession(), expires); Object object = Await.result(future, Duration.create(10, TimeUnit.SECONDS)); Class<?> klass = object.getClass(); if (SmsServiceResponse.class.equals(klass)) { final SmsServiceResponse<ActorRef> smsServiceResponse = (SmsServiceResponse<ActorRef>) object; if (smsServiceResponse.succeeded()) { // Create an SMS record for the text message. final SmsMessage record = sms(new Sid(accountSid), getApiVersion(data), sender, recipient, body, SmsMessage.Status.SENDING, SmsMessage.Direction.OUTBOUND_API); dao.addSmsMessage(record); // Send the sms. final ActorRef session = smsServiceResponse.get(); final ActorRef observer = observer(); session.tell(new Observe(observer), observer); session.tell(new SmsSessionAttribute("record", record), null); final SmsSessionRequest request = new SmsSessionRequest(sender, recipient, body, customRestOutgoingHeaderMap); session.tell(request, null); if (APPLICATION_JSON_TYPE == responseType) { return ok(gson.toJson(record), APPLICATION_JSON).build(); } else if (APPLICATION_XML_TYPE == responseType) { final RestCommResponse response = new RestCommResponse(record); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else { return null; } } } return status(INTERNAL_SERVER_ERROR).build(); } catch (final Exception exception) { return status(INTERNAL_SERVER_ERROR).entity(exception.getMessage()).build(); } }
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. j a va2 s .c o m*/ 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.opengamma.financial.currency.AbstractCurrencyMatrix.java
protected void addConversion(final Currency source, final Currency target, final CurrencyMatrixValue rate) { ArgumentChecker.notNull(source, "source"); ArgumentChecker.notNull(target, "target"); ArgumentChecker.notNull(rate, "rate"); ConcurrentHashMap<Currency, CurrencyMatrixValue> conversions = _values.get(source); if (conversions == null) { conversions = new ConcurrentHashMap<Currency, CurrencyMatrixValue>(); final ConcurrentHashMap<Currency, CurrencyMatrixValue> newConversions = _values.putIfAbsent(source, conversions);/*from www .ja v a2s. co m*/ if (newConversions != null) { conversions = newConversions; } } if (conversions.put(target, rate) == null) { // Added something to the map, so increase the target's reference count AtomicInteger targetCount = _targets.get(target); if (targetCount == null) { targetCount = new AtomicInteger(1); targetCount = _targets.putIfAbsent(target, targetCount); if (targetCount != null) { // Another thread already inserted the reference count if (targetCount.incrementAndGet() == 1) { // Another thread may have removed the last reference, confirm and re-insert atomically against "remove" synchronized (targetCount) { if (targetCount.get() > 0) { _targets.putIfAbsent(target, targetCount); } } } } } else { if (targetCount.incrementAndGet() == 1) { // Another thread may have removed the last reference, confirm and re-insert atomically against "remove" synchronized (targetCount) { if (targetCount.get() > 0) { _targets.putIfAbsent(target, targetCount); } } } } } }
From source file:org.wso2.carbon.event.input.adaptor.kafka.KafkaEventAdaptorType.java
private void createKafkaAdaptorListener( InputEventAdaptorMessageConfiguration inputEventAdaptorMessageConfiguration, InputEventAdaptorListener inputEventAdaptorListener, InputEventAdaptorConfiguration inputEventAdaptorConfiguration, AxisConfiguration axisConfiguration, String subscriptionId, int tenantId) { Map<String, String> brokerProperties = new HashMap<String, String>(); brokerProperties.putAll(inputEventAdaptorConfiguration.getInputProperties()); String zkConnect = brokerProperties.get(ConsumerKafkaConstants.ADAPTOR_SUSCRIBER_ZOOKEEPER_CONNECT); String groupID = brokerProperties.get(ConsumerKafkaConstants.ADAPTOR_SUSCRIBER_GROUP_ID); String threadsStr = brokerProperties.get(ConsumerKafkaConstants.ADAPTOR_SUSCRIBER_THREADS); String optionalConfiguration = brokerProperties .get(ConsumerKafkaConstants.ADAPTOR_OPTIONAL_CONFIGURATION_PROPERTIES); int threads = Integer.parseInt(threadsStr); String topic = inputEventAdaptorMessageConfiguration.getInputMessageProperties() .get(ConsumerKafkaConstants.ADAPTOR_SUSCRIBER_TOPIC); ConsumerKafkaAdaptor consumerAdaptor = new ConsumerKafkaAdaptor(topic, KafkaEventAdaptorType.createConsumerConfig(zkConnect, groupID, optionalConfiguration)); ConcurrentHashMap<String, ConsumerKafkaAdaptor> tenantSpecificConsumerMap = consumerAdaptorMap .get(tenantId);//from w ww . jav a2s . c o m if (tenantSpecificConsumerMap == null) { tenantSpecificConsumerMap = new ConcurrentHashMap<String, ConsumerKafkaAdaptor>(); consumerAdaptorMap.put(tenantId, tenantSpecificConsumerMap); } tenantSpecificConsumerMap.put(subscriptionId, consumerAdaptor); consumerAdaptor.run(threads, inputEventAdaptorListener); }
From source file:org.apache.marmotta.ucuenca.wk.commons.function.SemanticDistance.java
private List<String> topT(List<String> m, int n) throws IOException, SQLException { int value1 = 1; n = (n <= 0) ? 1 : n;// ww w .j a v a 2s . c o m 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; }