List of usage examples for java.util.concurrent.atomic AtomicReference AtomicReference
public AtomicReference(V initialValue)
From source file:com.ccserver.digital.service.LOSService.java
public LosResponseDTO submitCreditCardDocument(Long creditCardId) { AtomicReference<Object> refError = new AtomicReference<Object>(""); CreditCardApplication app = repository.findOne(creditCardId); LosResponseDTO losResponseDTO = new LosResponseDTO(); if (app == null || !Arrays.asList(new Status[] { Status.SubmittedApp, Status.Processing, Status.No_wf_initiated }) .contains(app.getStatus())) { losResponseDTO.setValidationError(new ValidationErrorDTO(Constants.APPLICATION_FIELD_INVALID, "The application status is invalid!")); return losResponseDTO; }/* w w w . j a va 2s . c o m*/ if (app.getSubmittedDocTime() != null) { losResponseDTO.setValidationError(new ValidationErrorDTO(Constants.MODIFYING_SUBMITTED_DOCUMENT, "The application's document submitted already")); return losResponseDTO; } List<CreditCardApplicationDocumentThumbNailDTO> entities = docService .getDocumentsThumbNailByApplicationId(creditCardId); if (CollectionUtils.isEmpty(entities)) { losResponseDTO.setValidationError( new ValidationErrorDTO(Constants.OBJECT_REQUIRED, "The application's documents are required!")); return losResponseDTO; } configLos = utilService.getConfigurations(); String messageId = java.util.UUID.randomUUID().toString(); com.vpbank.entity.vn.ba251.bd324.documentservice.configuredocumenthandlingoperationcreditcard._1.ObjectFactory objectFactory = new com.vpbank.entity.vn.ba251.bd324.documentservice.configuredocumenthandlingoperationcreditcard._1.ObjectFactory(); JAXBElement<ConfigureDocumentHandlingOperationCreditCardRequestType> jaxbRequest = objectFactory .createConfigureDocumentHandlingOperationCreditCardRequest( getRequestOfDoc(app, entities, messageId, refError)); if (refError.get().toString() != "") { losResponseDTO.setValidationError( new ValidationErrorDTO(Constants.FILE_SIZE_LIMIT_ERROR, "File Size is exceeded!")); return losResponseDTO; } Object result = null; try { result = new ExternalGatewaySupport(LOS_DOCUMENT_PACKAGE).getWebServiceTemplate() .marshalSendAndReceive(losConfig.getUrlDoc(), jaxbRequest, null); } catch (Exception ex) { logger.error(Utils.getErrorFormatLog("LOSService", "submitCreditCardDocument", "", "Can not call webservice", losConfig.getUrlDoc(), ex)); } if (result != null) { ConfigureDocumentHandlingOperationCreditCardResponseType resultResponse = ((JAXBElement<ConfigureDocumentHandlingOperationCreditCardResponseType>) result) .getValue(); String status = resultResponse.getResponseStatus().getStatus(); losResponseDTO.setStatus(status); ApplicationLOSDTO losApplicationDTO = mapper.applicationLOSToDTO(app.getApplicationLOS()); losApplicationDTO.setMessageDocId(messageId); if (status.equals("0")) { losApplicationDTO.setDocErrorCode(StringUtils.EMPTY); losApplicationDTO.setDocErrorMessage(StringUtils.EMPTY); CreditCardApplicationDTO dto = applicationService.updateLosDocStatus(app.getId(), Status.Processing, losApplicationDTO); losResponseDTO.setAppDTO(dto); } else { losApplicationDTO.setDocErrorCode(resultResponse.getResponseStatus().getGlobalErrorCode()); losApplicationDTO.setDocErrorMessage(getErrorDescription(resultResponse.getResponseStatus())); applicationService.updateLosDocStatus(app.getId(), null, losApplicationDTO); } losResponseDTO.setResponseStatusType(resultResponse.getResponseStatus()); return losResponseDTO; } losResponseDTO.setValidationError( new ValidationErrorDTO(Constants.APPLICATION_DOC_UNEXPECT_ERROR, "Unexpect error!")); return losResponseDTO; }
From source file:com.facebook.RequestTests.java
@LargeTest public void testShareOpenGraphContent() throws Exception { ShareOpenGraphObject ogObject = new ShareOpenGraphObject.Builder().putString("og:title", "a title") .putString("og:type", TEST_OG_OBJECT_TYPE).putString("og:description", "a description").build(); ShareOpenGraphAction ogAction = new ShareOpenGraphAction.Builder().setActionType(TEST_OG_ACTION_TYPE) .putObject("test", ogObject).build(); ShareOpenGraphContent content = new ShareOpenGraphContent.Builder().setAction(ogAction) .setPreviewPropertyName("test").build(); final ShareApi shareApi = new ShareApi(content); final AtomicReference<String> actionId = new AtomicReference<>(null); getActivity().runOnUiThread(new Runnable() { @Override/*from w ww.j a v a 2 s . c om*/ public void run() { shareApi.share(new FacebookCallback<Sharer.Result>() { @Override public void onSuccess(Sharer.Result result) { actionId.set(result.getPostId()); notifyShareFinished(); } @Override public void onCancel() { notifyShareFinished(); } @Override public void onError(FacebookException error) { notifyShareFinished(); } private void notifyShareFinished() { synchronized (shareApi) { shareApi.notifyAll(); } } }); } }); synchronized (shareApi) { shareApi.wait(REQUEST_TIMEOUT_MILLIS); } assertNotNull(actionId.get()); }
From source file:info.archinnov.achilles.test.integration.tests.LWTOperationsIT.java
@Test public void should_notify_listener_when_failing_cas_update() throws Exception { //Given/*from w w w. j a va2 s .c o m*/ final AtomicReference<LWTResultListener.LWTResult> atomicCASResult = new AtomicReference(null); LWTResultListener listener = new LWTResultListener() { @Override public void onSuccess() { } @Override public void onError(LWTResult lwtResult) { atomicCASResult.compareAndSet(null, lwtResult); } }; final EntityWithEnum entityWithEnum = new EntityWithEnum(10L, "John", EACH_QUORUM); final EntityWithEnum managed = manager.insert(entityWithEnum); Map<String, Object> expectedCurrentValues = ImmutableMap.<String, Object>of("[applied]", false, "consistency_level", EACH_QUORUM.name(), "name", "John"); managed.setName("Helen"); //When manager.update(managed, ifEqualCondition("name", "name").ifEqualCondition("consistency_level", EACH_QUORUM) .lwtResultListener(listener)); final LWTResultListener.LWTResult LWTResult = atomicCASResult.get(); assertThat(LWTResult).isNotNull(); assertThat(LWTResult.operation()).isEqualTo(UPDATE); assertThat(LWTResult.currentValues()).isEqualTo(expectedCurrentValues); assertThat(LWTResult.toString()).isEqualTo( "CAS operation UPDATE cannot be applied. Current values are: {[applied]=false, consistency_level=EACH_QUORUM, name=John}"); }
From source file:com.yahoo.pulsar.broker.loadbalance.SimpleLoadManagerImplTest.java
@Test(enabled = true) public void testPrimary() throws Exception { LoadManager loadManager = new SimpleLoadManagerImpl(pulsar1); PulsarResourceDescription rd = new PulsarResourceDescription(); rd.put("memory", new ResourceUsage(1024, 4096)); rd.put("cpu", new ResourceUsage(10, 100)); rd.put("bandwidthIn", new ResourceUsage(250 * 1024, 1024 * 1024)); rd.put("bandwidthOut", new ResourceUsage(550 * 1024, 1024 * 1024)); ResourceUnit ru1 = new SimpleResourceUnit( "http://" + pulsar1.getAdvertisedAddress() + ":" + pulsar1.getConfiguration().getWebServicePort(), rd);//from w ww . j a va 2 s . c om Set<ResourceUnit> rus = new HashSet<ResourceUnit>(); rus.add(ru1); LoadRanker lr = new ResourceAvailabilityRanker(); // inject the load report and rankings Map<ResourceUnit, com.yahoo.pulsar.common.policies.data.loadbalancer.LoadReport> loadReports = new HashMap<>(); com.yahoo.pulsar.common.policies.data.loadbalancer.LoadReport loadReport = new com.yahoo.pulsar.common.policies.data.loadbalancer.LoadReport(); loadReport.setSystemResourceUsage(new SystemResourceUsage()); loadReports.put(ru1, loadReport); setObjectField(SimpleLoadManagerImpl.class, loadManager, "currentLoadReports", loadReports); ResourceUnitRanking ranking = new ResourceUnitRanking(loadReport.getSystemResourceUsage(), new HashSet<String>(), new ResourceQuota(), new HashSet<String>(), new ResourceQuota()); Map<ResourceUnit, ResourceUnitRanking> rankings = new HashMap<>(); rankings.put(ru1, ranking); setObjectField(SimpleLoadManagerImpl.class, loadManager, "resourceUnitRankings", rankings); AtomicReference<Map<Long, Set<ResourceUnit>>> sortedRankingsInstance = new AtomicReference<>( Maps.newTreeMap()); sortedRankingsInstance.get().put(lr.getRank(rd), rus); setObjectField(SimpleLoadManagerImpl.class, loadManager, "sortedRankings", sortedRankingsInstance); ResourceUnit found = ((SimpleLoadManagerImpl) loadManager) .getLeastLoaded(new NamespaceName("pulsar/use/primary-ns.10")); // broker is not active so found should be null assertNotEquals(found, null, "did not find a broker when expected one to be found"); }
From source file:com.netflix.curator.framework.recipes.queue.DistributedQueue.java
boolean internalPut(final T item, MultiItem<T> multiItem, String path, int maxWait, TimeUnit unit) throws Exception { if (!blockIfMaxed(maxWait, unit)) { return false; }//from w ww. j a va2s . c om final MultiItem<T> givenMultiItem = multiItem; if (item != null) { final AtomicReference<T> ref = new AtomicReference<T>(item); multiItem = new MultiItem<T>() { @Override public T nextItem() throws Exception { return ref.getAndSet(null); } }; } putCount.incrementAndGet(); byte[] bytes = ItemSerializer.serialize(multiItem, serializer); if (putInBackground) { doPutInBackground(item, path, givenMultiItem, bytes); } else { doPutInForeground(item, path, givenMultiItem, bytes); } return true; }
From source file:org.zodiark.service.subscriber.SubscriberServiceImpl.java
@Override public SubscriberEndpoint createSession(final Envelope e, AtmosphereResource r) { String uuid = e.getUuid();/*from www . j a v a2s .c om*/ SubscriberEndpoint s = endpoints.get(uuid); if (s == null || !s.hasSession()) { s = createEndpoint(r, e.getMessage()); endpoints.put(uuid, s); final AtomicReference<SubscriberEndpoint> subscriberEndpoint = new AtomicReference<>(s); eventBus.message(DB_ENDPOINT_STATE, new RetrieveMessage(s.uuid(), e.getMessage()), new Reply<EndpointState, String>() { @Override public void ok(EndpointState state) { SubscriberEndpoint s = subscriberEndpoint.get(); // Subscriber will be deleted in case an error happens. s.hasSession(true).state(state).publisherEndpoint(retrieve(state.publisherUUID())); utils.statusEvent(DB_POST_SUBSCRIBER_SESSION_CREATE, e, s); } @Override public void fail(ReplyException replyException) { error(e, subscriberEndpoint.get(), utils.constructMessage(DB_ENDPOINT_STATE, "error", e.getMessage().getUUID())); } }); } else { error(e, r, new Message().setPath("/error").setData("unauthorized")); } return s; }
From source file:com.springsource.insight.plugin.apache.http.hc4.HttpClientExecutionCollectionAspectTest.java
private void runResponseHandlerTest(String testName, HttpHost host, HttpContext context) throws IOException { HttpClient httpClient = new DefaultHttpClient(); String uri = createTestUri(testName); HttpGet request = new HttpGet(uri); // must be final or the anonymous class cannot reference it... final AtomicReference<HttpResponse> rspRef = new AtomicReference<HttpResponse>(null); ResponseHandler<HttpResponse> handler = new ResponseHandler<HttpResponse>() { public HttpResponse handleResponse(HttpResponse response) throws ClientProtocolException, IOException { HttpResponse prevValue = rspRef.getAndSet(response); assertNull("Duplicate response handling", prevValue); return response; }// w w w .j a v a2 s .c om }; HttpResponse response; if (host == null) { response = (context == null) ? httpClient.execute(request, handler) : httpClient.execute(request, handler, context); } else { response = (context == null) ? httpClient.execute(host, request, handler) : httpClient.execute(host, request, handler, context); } assertSame("Mismatched reference and return value", response, rspRef.get()); handleResponse(testName, uri, request, response, true); }
From source file:com.smartsheet.api.internal.SmartsheetImpl.java
/** * Create an instance with given server URI, HttpClient (optional) and JsonSerializer (optional) * * Exceptions: - IllegalArgumentException : if serverURI/version/accessToken is null/empty * * @param baseURI the server uri/*from w w w.j av a 2 s . c om*/ * @param accessToken the access token * @param httpClient the http client (optional) * @param jsonSerializer the json serializer (optional) */ public SmartsheetImpl(String baseURI, String accessToken, HttpClient httpClient, JsonSerializer jsonSerializer) { Util.throwIfNull(baseURI); Util.throwIfEmpty(baseURI); this.baseURI = URI.create(baseURI); this.accessToken = new AtomicReference<String>(accessToken); this.jsonSerializer = ((jsonSerializer == null) ? new JacksonJsonSerializer() : jsonSerializer); this.httpClient = ((httpClient == null) ? new DefaultHttpClient(HttpClients.createDefault(), this.jsonSerializer) : httpClient); this.assumedUser = new AtomicReference<String>(null); this.changeAgent = new AtomicReference<String>(null); this.userAgent = new AtomicReference<String>(generateUserAgent(null)); // Initialize resources this.home = new AtomicReference<HomeResources>(); this.workspaces = new AtomicReference<WorkspaceResources>(); this.folders = new AtomicReference<FolderResources>(); this.templates = new AtomicReference<TemplateResources>(); this.sheets = new AtomicReference<SheetResources>(); this.sights = new AtomicReference<SightResources>(); this.favorites = new AtomicReference<FavoriteResources>(); this.users = new AtomicReference<UserResources>(); this.groups = new AtomicReference<GroupResources>(); this.search = new AtomicReference<SearchResources>(); this.reports = new AtomicReference<ReportResources>(); this.serverInfo = new AtomicReference<ServerInfoResources>(); this.tokens = new AtomicReference<TokenResources>(); this.contacts = new AtomicReference<ContactResources>(); this.imageUrls = new AtomicReference<ImageUrlResources>(); this.webhooks = new AtomicReference<WebhookResources>(); this.passthrough = new AtomicReference<PassthroughResources>(); }
From source file:info.archinnov.achilles.test.integration.tests.LWTOperationsIT.java
@Test public void should_notify_listener_when_failing_cas_update_with_ttl() throws Exception { //Given/*from w ww . ja va2s .c om*/ final AtomicReference<LWTResultListener.LWTResult> atomicCASResult = new AtomicReference(null); LWTResultListener listener = new LWTResultListener() { @Override public void onSuccess() { } @Override public void onError(LWTResult lwtResult) { atomicCASResult.compareAndSet(null, lwtResult); } }; final EntityWithEnum entityWithEnum = new EntityWithEnum(10L, "John", EACH_QUORUM); final EntityWithEnum managed = manager.insert(entityWithEnum); Map<String, Object> expectedCurrentValues = ImmutableMap.<String, Object>of("[applied]", false, "consistency_level", EACH_QUORUM.name(), "name", "John"); managed.setName("Helen"); //When manager.update(managed, ifEqualCondition("name", "name").ifEqualCondition("consistency_level", EACH_QUORUM) .lwtResultListener(listener).withTtl(100)); final LWTResultListener.LWTResult LWTResult = atomicCASResult.get(); assertThat(LWTResult).isNotNull(); assertThat(LWTResult.operation()).isEqualTo(UPDATE); assertThat(LWTResult.currentValues()).isEqualTo(expectedCurrentValues); assertThat(LWTResult.toString()).isEqualTo( "CAS operation UPDATE cannot be applied. Current values are: {[applied]=false, consistency_level=EACH_QUORUM, name=John}"); }
From source file:com.facebook.RequestTests.java
@LargeTest public void testShareOpenGraphContentWithBadType() throws Exception { ShareOpenGraphObject ogObject = new ShareOpenGraphObject.Builder().putString("og:title", "a title") .putString("og:type", TEST_OG_OBJECT_TYPE).putString("og:description", "a description").build(); ShareOpenGraphAction ogAction = new ShareOpenGraphAction.Builder() .setActionType(TEST_OG_ACTION_TYPE + "bad").putObject("test", ogObject).build(); ShareOpenGraphContent content = new ShareOpenGraphContent.Builder().setAction(ogAction) .setPreviewPropertyName("test").build(); final ShareApi shareApi = new ShareApi(content); final AtomicReference<String> actionId = new AtomicReference<>(null); final AtomicBoolean errorOccurred = new AtomicBoolean(false); getActivity().runOnUiThread(new Runnable() { @Override//from www .j av a 2s . c om public void run() { shareApi.share(new FacebookCallback<Sharer.Result>() { @Override public void onSuccess(Sharer.Result result) { actionId.set(result.getPostId()); notifyShareFinished(); } @Override public void onCancel() { notifyShareFinished(); } @Override public void onError(FacebookException error) { errorOccurred.set(true); notifyShareFinished(); } private void notifyShareFinished() { synchronized (shareApi) { shareApi.notifyAll(); } } }); } }); synchronized (shareApi) { shareApi.wait(REQUEST_TIMEOUT_MILLIS); } assertNull(actionId.get()); assertTrue(errorOccurred.get()); }