List of usage examples for java.util.concurrent.atomic AtomicReference AtomicReference
public AtomicReference(V initialValue)
From source file:com.nextgis.maplibui.mapui.LayerFactoryUI.java
@Override public void createNewLocalTMSLayer(final Context context, final LayerGroup groupLayer, final Uri uri) { String ext = "zip"; String layerName = FileUtil.getFileNameByUri(context, uri, context.getString(R.string.new_layer)); final int lastPeriodPos = layerName.lastIndexOf('.'); if (lastPeriodPos > 0) { ext = layerName.substring(lastPeriodPos).toLowerCase(); layerName = layerName.substring(0, lastPeriodPos); }/* ww w. j a v a 2s. c o m*/ if (context instanceof NGActivity) { NGActivity fragmentActivity = (NGActivity) context; if (ext.equals(".ngrc")) { Intent intent = new Intent(context, LayerFillService.class); intent.setAction(LayerFillService.ACTION_ADD_TASK); intent.putExtra(LayerFillService.KEY_URI, uri); intent.putExtra(LayerFillService.KEY_INPUT_TYPE, LayerFillService.TMS_LAYER); intent.putExtra(LayerFillService.KEY_LAYER_GROUP_ID, groupLayer.getId()); LayerFillProgressDialogFragment.startFill(intent); return; } AtomicReference<Uri> temp = new AtomicReference<>(uri); if (MapUtil.isZippedGeoJSON(context, temp)) { createNewVectorLayer(context, groupLayer, temp.get()); return; } CreateLocalLayerDialog newFragment = new CreateLocalLayerDialog(); newFragment.setLayerGroup(groupLayer).setLayerType(LayerFillService.TMS_LAYER).setUri(uri) .setLayerName(layerName).setTitle(context.getString(R.string.create_tms_layer)) .setTheme(fragmentActivity.getThemeId()) .show(fragmentActivity.getSupportFragmentManager(), "create_tms_layer"); } }
From source file:com.kixeye.janus.client.http.rest.DefaultRestHttpClientTest.java
@Test public void postNoParamsTest() throws Exception { Janus janus = new Janus(VIP_TEST, new ConstServerList(VIP_TEST, "http://localhost:" + server1Port), new RandomLoadBalancer(), new ServerStatsFactory(ServerStats.class, new MetricRegistry())); DefaultRestHttpClient client = new DefaultRestHttpClient(janus, 0, DefaultRestHttpClient.UTF8_STRING_SER_DE, "text/plain"); final AtomicReference<String> requestMethod = new AtomicReference<>(null); final AtomicReference<String> requestPath = new AtomicReference<>(null); testContainer = new Container() { public void handle(Request req, Response resp) { requestMethod.set(req.getMethod()); requestPath.set(req.getTarget()); try { resp.getByteChannel().write(ByteBuffer.wrap(IOUtils.toByteArray(req.getInputStream()))); } catch (IOException e) { logger.error("Unable to write to channel."); }//from w w w. j a va2s . c o m } }; String result = client.post("/test_no_params", "post body", String.class).getBody().deserialize(); Assert.assertNotNull(result); Assert.assertEquals("POST", requestMethod.get()); Assert.assertEquals("/test_no_params", requestPath.get()); }
From source file:com.ccserver.digital.service.LOSService.java
public LosResponseDTO submitCreditCardData(Long appId, String ipAddress) { AtomicReference<Object> refError = new AtomicReference<Object>(""); CreditCardApplicationDTO creditCardDTO = applicationService.getApplication(appId); LosResponseDTO losResponseDTO = new LosResponseDTO(); if (creditCardDTO != null) { if (creditCardDTO.getSubmittedAppTime() != null) { losResponseDTO.setValidationError(new ValidationErrorDTO(Constants.MODIFYING_SUBMITTED_APPLICATION, "The application submitted already")); return losResponseDTO; }//w w w . j a va 2 s .c o m configLos = utilService.getConfigurations(); InitiateSalesProductAgreementCreditCardResponseType result = submitDataToLos(creditCardDTO, refError); ApplicationLOSDTO applicationLOS = creditCardDTO.getApplicationLOS(); if (result == null) { applicationLOS.setErrorMessage("Can not call webservie"); return losResponseDTO; } String status = result.getResponseStatus().getStatus(); losResponseDTO.setStatus(status); if (status.equals("0")) { if (result.getBodyResponse().getAppicationInfo() != null) { String losAppId = result.getBodyResponse().getAppicationInfo().getApplicationId(); if (!StringUtils.isEmpty(losAppId)) { applicationLOS.setLosApplicationId(losAppId); } } applicationLOS.setErrorCode(StringUtils.EMPTY); applicationLOS.setErrorMessage(StringUtils.EMPTY); } else { applicationLOS.setErrorCode(result.getResponseStatus().getGlobalErrorCode()); applicationLOS.setErrorMessage(getErrorDescription(result.getResponseStatus())); logger.error(Utils.getErrorFormatLog("LOSService", "submitCreditCardData", "", "Cannot submit creditCardData", appId, applicationLOS.getErrorMessage())); } applicationService.updateLosInfo(creditCardDTO.getId(), applicationLOS, ipAddress); losResponseDTO.setResponseStatusType(result.getResponseStatus()); return losResponseDTO; } losResponseDTO.setValidationError( new ValidationErrorDTO(Constants.CREDIT_CARD_OBJECT_REQUIRED, "The application is required")); return losResponseDTO; }
From source file:com.opengamma.examples.simulated.livedata.ExampleLiveDataServer.java
@Override protected Map<String, Object> doSubscribe(final Collection<String> uniqueIds) { ArgumentChecker.notNull(uniqueIds, "Subscriptions"); s_logger.debug("doSubscribe on {}", uniqueIds); final Map<String, Object> result = Maps.newHashMap(); final List<String> missingSubscriptions = Lists.newArrayList(); for (final String uniqueId : uniqueIds) { if (!_marketValues.containsKey(uniqueId)) { missingSubscriptions.add(uniqueId); }// w w w.j a v a 2 s.co m result.put(uniqueId, new AtomicReference<String>(uniqueId)); } if (!missingSubscriptions.isEmpty()) { s_logger.error("Could not subscribe to {}", missingSubscriptions); } return result; }
From source file:com.aol.advertising.qiao.management.metrics.StatisticsStore.java
/** * @param key/*from w ww . j a va 2s. c o m*/ * @param imetric */ public void setIntervalMetric(String key, IntervalMetric value) { intvalStats.put(key, new AtomicReference<IntervalMetric>(value)); }
From source file:com.aol.advertising.qiao.management.metrics.StatisticsStore.java
public void updateIntervalMetric(String key, IntervalMetric value) { if (intvalStats.containsKey(key)) { intvalStats.get(key).get().incr(value); } else {/* www . j a v a 2s.c o m*/ intvalStats.put(key, new AtomicReference<IntervalMetric>(value)); } }
From source file:info.archinnov.achilles.test.integration.tests.LWTOperationsIT.java
@Test public void should_notify_listener_when_trying_to_insert_with_lwt_and_ttl_because_already_exist() throws Exception { //Given//www . j a va 2 s.c om final AtomicReference<LWTResultListener.LWTResult> atomicLWTResult = new AtomicReference(null); LWTResultListener listener = new LWTResultListener() { @Override public void onSuccess() { } @Override public void onError(LWTResult lwtResult) { atomicLWTResult.compareAndSet(null, lwtResult); } }; final EntityWithEnum entityWithEnum = new EntityWithEnum(10L, "name", EACH_QUORUM); Map<String, Object> expectedCurrentValues = ImmutableMap.<String, Object>of("id", 10L, "[applied]", false, "consistency_level", EACH_QUORUM.name(), "name", "name"); manager.insert(entityWithEnum); manager.insert(entityWithEnum, OptionsBuilder.ifNotExists().withTtl(100).lwtResultListener(listener)); final LWTResultListener.LWTResult LWTResult = atomicLWTResult.get(); assertThat(LWTResult.operation()).isEqualTo(INSERT); assertThat(LWTResult.currentValues()).isEqualTo(expectedCurrentValues); assertThat(LWTResult.toString()).isEqualTo( "CAS operation INSERT cannot be applied. Current values are: {[applied]=false, consistency_level=EACH_QUORUM, id=10, name=name}"); }
From source file:com.netflix.curator.framework.recipes.queue.TestDistributedQueue.java
@Test public void testErrorMode() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start();/*from w w w .j ava 2 s . c om*/ try { final AtomicReference<CountDownLatch> latch = new AtomicReference<CountDownLatch>( new CountDownLatch(1)); final AtomicInteger count = new AtomicInteger(0); QueueConsumer<TestQueueItem> consumer = new QueueConsumer<TestQueueItem>() { @Override public void consumeMessage(TestQueueItem message) throws Exception { if (count.incrementAndGet() < 2) { throw new Exception(); } latch.get().countDown(); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }; DistributedQueue<TestQueueItem> queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH) .lockPath("/locks").buildQueue(); try { queue.start(); TestQueueItem item = new TestQueueItem("1"); queue.put(item); Assert.assertTrue(timing.awaitLatch(latch.get())); Assert.assertEquals(count.get(), 2); queue.setErrorMode(ErrorMode.DELETE); count.set(0); latch.set(new CountDownLatch(1)); item = new TestQueueItem("1"); queue.put(item); Assert.assertFalse(latch.get().await(5, TimeUnit.SECONDS)); // consumer should get called only once Assert.assertEquals(count.get(), 1); } finally { queue.close(); } } finally { client.close(); } }
From source file:com.bigdata.dastor.db.ColumnFamilyStore.java
ColumnFamilyStore(String table, String columnFamilyName, boolean isSuper, int indexValue) throws IOException { // BIGDATA: //w ww . ja va 2s .com cfMetaData = DatabaseDescriptor.getCFMetaData(table, columnFamilyName); assert cfMetaData != null; table_ = table; columnFamily_ = columnFamilyName; isSuper_ = isSuper; fileIndexGenerator_.set(indexValue); memtable_ = new Memtable(this); binaryMemtable_ = new AtomicReference<BinaryMemtable>(new BinaryMemtable(this)); if (logger_.isDebugEnabled()) logger_.debug("Starting CFS " + columnFamily_); // scan for data files corresponding to this CF List<File> sstableFiles = new ArrayList<File>(); Pattern auxFilePattern = Pattern.compile("(.*)(-Filter\\.db$|-Index\\.db$)"); Pattern tmpCacheFilePattern = Pattern.compile(table + "-" + columnFamilyName + "-(Key|Row)Cache.*\\.tmp$"); for (File file : files()) { String filename = file.getName(); /* look for and remove orphans. An orphan is a -Filter.db or -Index.db with no corresponding -Data.db. */ Matcher matcher = auxFilePattern.matcher(file.getAbsolutePath()); if (matcher.matches()) { String basePath = matcher.group(1); if (!new File(basePath + "-Data.db").exists()) { logger_.info(String.format("Removing orphan %s", file.getAbsolutePath())); FileUtils.deleteWithConfirm(file); continue; } } if (((file.length() == 0 && !filename.endsWith("-Compacted")) || (filename.contains("-" + SSTable.TEMPFILE_MARKER)))) { FileUtils.deleteWithConfirm(file); continue; } if (tmpCacheFilePattern.matcher(filename).matches()) { logger_.info("removing incomplete saved cache " + file.getAbsolutePath()); FileUtils.deleteWithConfirm(file); continue; } if (filename.contains("-Data.db")) { sstableFiles.add(file.getAbsoluteFile()); } } Collections.sort(sstableFiles, new FileUtils.FileComparator()); /* Load the index files and the Bloom Filters associated with them. */ ssTables_ = new SSTableTracker(table, columnFamilyName); Set<String> savedKeys = readSavedCache( DatabaseDescriptor.getSerializedKeyCachePath(table, columnFamilyName), false); List<SSTableReader> sstables = new ArrayList<SSTableReader>(); for (File file : sstableFiles) { String filename = file.getAbsolutePath(); if (SSTable.deleteIfCompacted(filename)) continue; SSTableReader sstable; try { sstable = SSTableReader.open(filename, savedKeys, ssTables_); } catch (IOException ex) { logger_.error("Corrupt file " + filename + "; skipped", ex); continue; } sstables.add(sstable); } ssTables_.add(sstables); }
From source file:org.muhia.app.psi.config.http.CustomHttpClientUtilities.java
public String doGetWithResponseHandler(String url, Map<String, String> allRequestParams) { AtomicReference<String> result = new AtomicReference<>(""); // CloseableHttpResponse response = null; CloseableHttpClient client = null;//from ww w .ja v a 2 s.c o m try { HttpGet httpGet = new HttpGet(url); URIBuilder uriBuilder = new URIBuilder(httpGet.getURI()); allRequestParams.entrySet().forEach((entry) -> { String key = entry.getKey(); String value = entry.getValue(); if (value != null) { uriBuilder.setParameter(key, value); } }); httpGet.setURI(uriBuilder.build()); RequestConfig config = RequestConfig.custom().setConnectTimeout(hcp.getConnectionTimeout()) .setConnectionRequestTimeout(hcp.getConnectionRequestTimeout()) .setSocketTimeout(hcp.getSockectTimeout()).build(); client = HttpClientBuilder.create().setDefaultRequestConfig(config).build(); ResponseHandler<String> responseHandler = (final HttpResponse response) -> { int status = response.getStatusLine().getStatusCode(); if (status >= hcp.getLowerStatusLimit() && status <= hcp.getUpperStatusLimit()) { HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity) : null; } else { throw new ClientProtocolException(hcp.getUnexpectedStatus() + status); } }; result.set(client.execute(httpGet, responseHandler)); client.close(); } catch (IOException | URISyntaxException ex) { // LoggerFactory.getLogger(CustomHttpClientUtil.class).error(ex.getMessage(), // ex); Logger.getLogger(CustomHttpClientUtilities.class.getName()).log(Level.SEVERE, null, ex); } finally { try { if (client != null) { client.close(); } } catch (IOException ex) { // LoggerFactory.getLogger(CustomHttpClientUtil.class).error(ex.getMessage(), // ex); result.set(hcp.getIoExceptionMessage()); Logger.getLogger(CustomHttpClientUtilities.class.getName()).log(Level.SEVERE, null, ex); } } return result.get(); }