List of usage examples for java.util.concurrent.atomic AtomicReference set
public final void set(V newValue)
From source file:com.netflix.curator.framework.recipes.cache.TestPathChildrenCache.java
@Test public void testRebuildAgainstOtherProcesses() throws Exception { final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start();//w w w. jav a 2s . co m try { client.create().forPath("/test"); client.create().forPath("/test/foo"); client.create().forPath("/test/bar"); client.create().forPath("/test/snafu", "original".getBytes()); final CountDownLatch addedLatch = new CountDownLatch(2); final PathChildrenCache cache = new PathChildrenCache(client, "/test", true); cache.getListenable().addListener(new PathChildrenCacheListener() { @Override public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { if (event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED) { if (event.getData().getPath().equals("/test/test")) { addedLatch.countDown(); } } else if (event.getType() == PathChildrenCacheEvent.Type.CHILD_UPDATED) { if (event.getData().getPath().equals("/test/snafu")) { addedLatch.countDown(); } } } }); cache.rebuildTestExchanger = new Exchanger<Object>(); ExecutorService service = Executors.newSingleThreadExecutor(); final AtomicReference<String> deletedPath = new AtomicReference<String>(); Future<Object> future = service.submit(new Callable<Object>() { @Override public Object call() throws Exception { cache.rebuildTestExchanger.exchange(new Object()); // simulate another process adding a node while we're rebuilding client.create().forPath("/test/test"); List<ChildData> currentData = cache.getCurrentData(); Assert.assertTrue(currentData.size() > 0); // simulate another process removing a node while we're rebuilding client.delete().forPath(currentData.get(0).getPath()); deletedPath.set(currentData.get(0).getPath()); cache.rebuildTestExchanger.exchange(new Object()); ChildData childData = null; while (childData == null) { childData = cache.getCurrentData("/test/snafu"); Thread.sleep(1000); } Assert.assertEquals(childData.getData(), "original".getBytes()); client.setData().forPath("/test/snafu", "grilled".getBytes()); cache.rebuildTestExchanger.exchange(new Object()); return null; } }); cache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE); future.get(); Assert.assertTrue(addedLatch.await(10, TimeUnit.SECONDS)); Assert.assertNotNull(cache.getCurrentData("/test/test")); Assert.assertNull(cache.getCurrentData(deletedPath.get())); Assert.assertEquals(cache.getCurrentData("/test/snafu").getData(), "grilled".getBytes()); cache.close(); } finally { client.close(); } }
From source file:net.technicpack.launchercore.install.InstalledPack.java
private void downloadImage(final AtomicReference<BufferedImage> image, final File temp, final String url, final String md5) { if (url.isEmpty() || downloading.get(image).get()) { return;//w w w . j a v a 2 s . com } downloading.get(image).set(true); final String name = getName(); final InstalledPack pack = this; final MirrorStore mirror = mirrorStore; Thread thread = new Thread(name + " Image Download Worker") { @Override public void run() { try { if (temp.exists()) { System.out.println("Pack: " + getName() + " Calculated MD5: " + MD5Utils.getMD5(temp) + " Required MD5: " + md5); } Download download = mirror.downloadFile(url, temp.getName(), temp.getAbsolutePath()); BufferedImage newImage; newImage = ImageIO.read(download.getOutFile()); image.set(newImage); downloading.get(image).set(false); if (refreshListener != null) { refreshListener.refreshPack(pack); } } catch (IOException e) { System.out.println("Failed to download and load image from: " + url); e.printStackTrace(); } } }; thread.start(); }
From source file:org.jasig.ssp.service.impl.PersonServiceImpl.java
@Override public PagingWrapper<Person> syncCoaches() { long methodStart = new Date().getTime(); final Collection<Person> coaches = Lists.newArrayList(); if (Thread.currentThread().isInterrupted()) { LOGGER.info("Abandoning syncCoaches because of thread interruption"); return new PagingWrapper<Person>(coaches); }/*from ww w .ja v a 2 s .c o m*/ final Collection<String> coachUsernames = getAllCoachUsernamesFromDirectory(); long mergeLoopStart = new Date().getTime(); final AtomicLong timeInExternalReads = new AtomicLong(); final AtomicLong timeInExternalWrites = new AtomicLong(); for (final String coachUsername : coachUsernames) { if (Thread.currentThread().isInterrupted()) { LOGGER.info("Abandoning syncCoaches on username {} because of thread interruption", coachUsername); break; } long singlePersonStart = new Date().getTime(); final AtomicReference<Person> coach = new AtomicReference<Person>(); try { withCoachSyncTransaction(new Callable<Object>() { @Override public Object call() throws Exception { long localPersonLookupStart = new Date().getTime(); try { coach.set(personFromUsername(coachUsername)); } catch (final ObjectNotFoundException e) { LOGGER.debug("Coach {} not found", coachUsername); } long localPersonLookupEnd = new Date().getTime(); TIMING_LOGGER.info("Read local coach by username {} in {} ms", coachUsername, localPersonLookupEnd - localPersonLookupStart); // Does coach exist in local SSP.person table? if (coach.get() == null) { // Attempt to find coach in external data try { long externalPersonLookupStart = new Date().getTime(); final ExternalPerson externalPerson = externalPersonService .getByUsername(coachUsername); long externalPersonLookupEnd = new Date().getTime(); long externalPersonLookupElapsed = externalPersonLookupEnd - externalPersonLookupStart; timeInExternalReads.set(timeInExternalReads.get() + externalPersonLookupElapsed); TIMING_LOGGER.info("Read external coach by username {} in {} ms", coachUsername, externalPersonLookupElapsed); long externalPersonSyncStart = new Date().getTime(); coach.set(new Person()); // NOPMD externalPersonService.updatePersonFromExternalPerson(coach.get(), externalPerson, true); long externalPersonSyncEnd = new Date().getTime(); long externalPersonSyncElapsed = externalPersonSyncEnd - externalPersonSyncStart; timeInExternalWrites.set(timeInExternalWrites.get() + externalPersonSyncElapsed); TIMING_LOGGER.info("Synced external coach by username {} in {} ms", coachUsername, externalPersonSyncElapsed); } catch (final ObjectNotFoundException e) { LOGGER.debug("Coach {} not found in external data", coachUsername); } } return coach.get(); } }); } catch (ConstraintViolationException e) { if ("uq_person_school_id".equals(e.getConstraintName())) { LOGGER.warn("Skipping coach with non-unique schoolId '{}' (username '{}')", new Object[] { coach.get().getSchoolId(), coachUsername, e }); coach.set(null); } else if ("unique_person_username".equals(e.getConstraintName())) { LOGGER.warn("Skipping coach with non-unique username '{}' (schoolId '{}')", new Object[] { coachUsername, coach.get().getSchoolId(), e }); coach.set(null); } else { throw e; } } if (coach.get() != null) { coaches.add(coach.get()); } long singlePersonEnd = new Date().getTime(); TIMING_LOGGER.info("SSP coach merge for username {} completed in {} ms", coachUsername, singlePersonEnd - singlePersonStart); } Long mergeLoopEnd = new Date().getTime(); TIMING_LOGGER.info("All SSP merges for {} coaches completed in {} ms. Reading: {} ms. Writing: {} ms", new Object[] { coachUsernames.size(), mergeLoopEnd - mergeLoopStart, timeInExternalReads.get(), timeInExternalWrites.get() }); PagingWrapper pw = new PagingWrapper<Person>(coaches); long methodEnd = new Date().getTime(); TIMING_LOGGER.info("Read and merged PersonAttributesService {} coaches in {} ms", coaches.size(), methodEnd - methodStart); return pw; }
From source file:net.tac42.subtails.service.RESTMusicService.java
private HttpResponse executeWithRetry(Context context, String url, String originalUrl, HttpParams requestParams, List<String> parameterNames, List<Object> parameterValues, List<Header> headers, ProgressListener progressListener, CancellableTask task) throws IOException { Log.i(TAG, "Using URL " + url); final AtomicReference<Boolean> cancelled = new AtomicReference<Boolean>(false); int attempts = 0; while (true) { attempts++;//from w ww . j a v a 2 s.c o m HttpContext httpContext = new BasicHttpContext(); final HttpPost request = new HttpPost(url); if (task != null) { // Attempt to abort the HTTP request if the task is cancelled. task.setOnCancelListener(new CancellableTask.OnCancelListener() { @Override public void onCancel() { cancelled.set(true); request.abort(); } }); } if (parameterNames != null) { List<NameValuePair> params = new ArrayList<NameValuePair>(); for (int i = 0; i < parameterNames.size(); i++) { params.add( new BasicNameValuePair(parameterNames.get(i), String.valueOf(parameterValues.get(i)))); } request.setEntity(new UrlEncodedFormEntity(params, Constants.UTF_8)); } if (requestParams != null) { request.setParams(requestParams); Log.d(TAG, "Socket read timeout: " + HttpConnectionParams.getSoTimeout(requestParams) + " ms."); } if (headers != null) { for (Header header : headers) { request.addHeader(header); } } // Set credentials to get through apache proxies that require authentication. SharedPreferences prefs = Util.getPreferences(context); int instance = prefs.getInt(Constants.PREFERENCES_KEY_SERVER_INSTANCE, 1); String username = prefs.getString(Constants.PREFERENCES_KEY_USERNAME + instance, null); String password = prefs.getString(Constants.PREFERENCES_KEY_PASSWORD + instance, null); httpClient.getCredentialsProvider().setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(username, password)); try { HttpResponse response = httpClient.execute(request, httpContext); detectRedirect(originalUrl, context, httpContext); return response; } catch (IOException x) { request.abort(); if (attempts >= HTTP_REQUEST_MAX_ATTEMPTS || cancelled.get()) { throw x; } if (progressListener != null) { String msg = context.getResources().getString(R.string.music_service_retry, attempts, HTTP_REQUEST_MAX_ATTEMPTS - 1); progressListener.updateProgress(msg); } Log.w(TAG, "Got IOException (" + attempts + "), will retry", x); increaseTimeouts(requestParams); Util.sleepQuietly(2000L); } } }
From source file:org.eclipse.wb.tests.designer.core.palette.ComponentEntryInfoTest.java
/** * Test for "typeParameter" support.//w w w . j a v a2 s. c o m * <p> * Cancel type choosing, and type parameters dialog then. */ public void test_typeParameters_cancel() throws Exception { final ComponentEntryInfo componentEntry = prepare_typeParameters(); // animate createTool() CreationTool creationTool; { final AtomicReference<CreationTool> creationToolResult = new AtomicReference<CreationTool>(); new UiContext().executeAndCheck(new UIRunnable() { public void run(UiContext context) throws Exception { CreationTool result = (CreationTool) componentEntry.createTool(); creationToolResult.set(result); } }, new UIRunnable() { public void run(UiContext context) throws Exception { context.useShell("Generic component creation"); // initial type Text textWidget = context.getTextByLabel("Row type:"); assertEquals("java.lang.Object", textWidget.getText()); // animate "..." button { Button chooseButton = context.getButtonByText("..."); animateChooseButton(chooseButton); } // no changes assertEquals("java.lang.Object", textWidget.getText()); // cancel context.clickButton("Cancel"); } public void animateChooseButton(final Button chooseButton) throws Exception { new UiContext().executeAndCheck(new UIRunnable() { public void run(UiContext context) throws Exception { context.click(chooseButton); } }, new UIRunnable() { public void run(UiContext context) throws Exception { animateOpenTypeSelection(context, "java.lang.String"); context.clickButton("Cancel"); } }); } }); creationTool = creationToolResult.get(); } // type parameter dialog was cancelled, so no tool assertNull(creationTool); }
From source file:eu.eubrazilcc.lvl.storage.oauth2.dao.ResourceOwnerDAO.java
private boolean isValidUsingOwnerId(final String ownerId, final String username, final String password, final @Nullable AtomicReference<String> scopeRef, final @Nullable AtomicReference<String> ownerIdRef) { checkArgument(isNotBlank(ownerId), "Uninitialized or invalid resource owner id"); checkArgument(isNotBlank(username), "Uninitialized or invalid username"); checkArgument(isNotBlank(password), "Uninitialized or invalid password"); final ResourceOwner resourceOwner = find(ownerId); final boolean isValid = (resourceOwner != null && resourceOwner.getUser() != null && username.equals(resourceOwner.getUser().getUserid()) && hashAndSaltPassword(password, resourceOwner.getUser().getSalt()) .equals(resourceOwner.getUser().getPassword())); if (isValid) { if (scopeRef != null) { scopeRef.set(oauthScope(resourceOwner, false)); }// w w w .j a v a 2 s. c o m if (ownerIdRef != null) { ownerIdRef.set(resourceOwner.getOwnerId()); } } return isValid; }
From source file:org.appverse.web.framework.backend.frontfacade.websocket.IntegrationWebsocketTest.java
@Test public void executeTrade() throws Exception { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<Throwable> failure = new AtomicReference<Throwable>(); StompSessionHandler handler = new AbstractTestSessionHandler(failure) { @Override// w ww . java2 s . c o m public void afterConnected(final StompSession session, StompHeaders connectedHeaders) { session.subscribe("/user/queue/position-updates", new StompFrameHandler() { @Override public Type getPayloadType(StompHeaders headers) { return PortfolioPosition.class; } @Override public void handleFrame(StompHeaders headers, Object payload) { PortfolioPosition position = (PortfolioPosition) payload; logger.debug("Got " + position); try { assertEquals(75, position.getShares()); assertEquals("Dell Inc.", position.getCompany()); } catch (Throwable t) { failure.set(t); } finally { session.disconnect(); latch.countDown(); } } }); try { Trade trade = new Trade(); trade.setAction(Trade.TradeAction.Buy); trade.setTicker("DELL"); trade.setShares(25); session.send("/app/trade", trade); } catch (Throwable t) { failure.set(t); latch.countDown(); } } }; //test websocket WebSocketStompClient stompClient = new WebSocketStompClient(sockJsClient); stompClient.setMessageConverter(new MappingJackson2MessageConverter()); stompClient.connect("ws://localhost:{port}/services/websocket/standard", headers, handler, port); if (!latch.await(10, TimeUnit.SECONDS)) { fail("Trade confirmation not received"); } else if (failure.get() != null) { throw new AssertionError("", failure.get()); } //test sockJs stompClient = new WebSocketStompClient(sockJsClient); stompClient.setMessageConverter(new MappingJackson2MessageConverter()); stompClient.connect("http://localhost:{port}/services/websocket/sockJs", headers, handler, port); if (!latch.await(10, TimeUnit.SECONDS)) { fail("Trade confirmation not received"); } else if (failure.get() != null) { throw new AssertionError("", failure.get()); } }
From source file:org.apache.solr.cloud.api.collections.AddReplicaCmd.java
public static ZkNodeProps assignReplicaDetails(SolrCloudManager cloudManager, ClusterState clusterState, ZkNodeProps message, AtomicReference<PolicyHelper.SessionWrapper> sessionWrapper) throws IOException, InterruptedException { boolean skipCreateReplicaInClusterState = message.getBool(SKIP_CREATE_REPLICA_IN_CLUSTER_STATE, false); String collection = message.getStr(COLLECTION_PROP); String node = message.getStr(CoreAdminParams.NODE); String shard = message.getStr(SHARD_ID_PROP); String coreName = message.getStr(CoreAdminParams.NAME); String coreNodeName = message.getStr(CoreAdminParams.CORE_NODE_NAME); Replica.Type replicaType = Replica.Type.valueOf( message.getStr(ZkStateReader.REPLICA_TYPE, Replica.Type.NRT.name()).toUpperCase(Locale.ROOT)); if (StringUtils.isBlank(coreName)) { coreName = message.getStr(CoreAdminParams.PROPERTY_PREFIX + CoreAdminParams.NAME); }// w w w . j av a 2s . c om DocCollection coll = clusterState.getCollection(collection); if (coll == null) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Collection: " + collection + " does not exist"); } if (coll.getSlice(shard) == null) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Collection: " + collection + " shard: " + shard + " does not exist"); } // Kind of unnecessary, but it does put the logic of whether to override maxShardsPerNode in one place. if (!skipCreateReplicaInClusterState) { if (CloudUtil.usePolicyFramework(coll, cloudManager)) { if (node == null) { if (coll.getPolicyName() != null) message.getProperties().put(Policy.POLICY, coll.getPolicyName()); node = Assign.identifyNodes(cloudManager, clusterState, Collections.emptyList(), collection, message, Collections.singletonList(shard), replicaType == Replica.Type.NRT ? 1 : 0, replicaType == Replica.Type.TLOG ? 1 : 0, replicaType == Replica.Type.PULL ? 1 : 0) .get(0).node; sessionWrapper.set(PolicyHelper.getLastSessionWrapper(true)); } } else { node = Assign.getNodesForNewReplicas(clusterState, collection, shard, 1, node, cloudManager) .get(0).nodeName;// TODO: use replica type in this logic too } } log.info("Node Identified {} for creating new replica", node); if (!clusterState.liveNodesContain(node)) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Node: " + node + " is not live"); } if (coreName == null) { coreName = Assign.buildSolrCoreName(cloudManager.getDistribStateManager(), coll, shard, replicaType); } else if (!skipCreateReplicaInClusterState) { //Validate that the core name is unique in that collection for (Slice slice : coll.getSlices()) { for (Replica replica : slice.getReplicas()) { String replicaCoreName = replica.getStr(CORE_NAME_PROP); if (coreName.equals(replicaCoreName)) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Another replica with the same core name already exists" + " for this collection"); } } } } if (coreNodeName != null) { message = message.plus(CoreAdminParams.CORE_NODE_NAME, coreNodeName); } message = message.plus(CoreAdminParams.NAME, coreName); message = message.plus(CoreAdminParams.NODE, node); return message; }
From source file:net.sourceforge.kalimbaradio.androidapp.service.RESTMusicService.java
private HttpResponse executeWithRetry(Context context, String url, String originalUrl, HttpParams requestParams, List<String> parameterNames, List<Object> parameterValues, List<Header> headers, ProgressListener progressListener, CancellableTask task) throws IOException { LOG.info("Using URL " + url); final AtomicReference<Boolean> cancelled = new AtomicReference<Boolean>(false); int attempts = 0; while (true) { attempts++;/*w ww .j a v a2 s . co m*/ HttpContext httpContext = new BasicHttpContext(); final HttpPost request = new HttpPost(url); if (task != null) { // Attempt to abort the HTTP request if the task is cancelled. task.setOnCancelListener(new CancellableTask.OnCancelListener() { @Override public void onCancel() { cancelled.set(true); request.abort(); } }); } if (parameterNames != null) { List<NameValuePair> params = new ArrayList<NameValuePair>(); for (int i = 0; i < parameterNames.size(); i++) { params.add( new BasicNameValuePair(parameterNames.get(i), String.valueOf(parameterValues.get(i)))); } request.setEntity(new UrlEncodedFormEntity(params, Constants.UTF_8)); } if (requestParams != null) { request.setParams(requestParams); LOG.debug("Socket read timeout: " + HttpConnectionParams.getSoTimeout(requestParams) + " ms."); } if (headers != null) { for (Header header : headers) { request.addHeader(header); } } // Set credentials to get through apache proxies that require authentication. ServerSettingsManager.ServerSettings server = Util.getActiveServer(context); httpClient.getCredentialsProvider().setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(server.getUsername(), server.getPassword())); try { HttpResponse response = httpClient.execute(request, httpContext); detectRedirect(originalUrl, context, httpContext); return response; } catch (IOException x) { request.abort(); if (attempts >= HTTP_REQUEST_MAX_ATTEMPTS || cancelled.get()) { throw x; } if (progressListener != null) { String msg = context.getResources().getString(R.string.music_service_retry, attempts, HTTP_REQUEST_MAX_ATTEMPTS - 1); progressListener.updateProgress(msg); } LOG.warn("Got IOException (" + attempts + "), will retry", x); increaseTimeouts(requestParams); Util.sleepQuietly(2000L); } } }
From source file:org.eclipse.wb.tests.designer.core.palette.ComponentEntryInfoTest.java
/** * Test for "typeParameter" support./*w w w . ja v a 2s.co m*/ */ public void test_typeParameters_chooseType() throws Exception { final ComponentEntryInfo componentEntry = prepare_typeParameters(); // animate createTool() CreationTool creationTool; { final AtomicReference<CreationTool> creationToolResult = new AtomicReference<CreationTool>(); new UiContext().executeAndCheck(new UIRunnable() { public void run(UiContext context) throws Exception { CreationTool result = (CreationTool) componentEntry.createTool(); creationToolResult.set(result); } }, new UIRunnable() { public void run(UiContext context) throws Exception { context.useShell("Generic component creation"); // initial type Text textWidget = context.getTextByLabel("Row type:"); assertEquals("java.lang.Object", textWidget.getText()); // animate "..." button { Button chooseButton = context.getButtonByText("..."); animateChooseButton(chooseButton); } // chosen type assertEquals("java.lang.String", textWidget.getText()); // OK context.clickButton("OK"); } public void animateChooseButton(final Button chooseButton) throws Exception { new UiContext().executeAndCheck(new UIRunnable() { public void run(UiContext context) throws Exception { context.click(chooseButton); } }, new UIRunnable() { public void run(UiContext context) throws Exception { animateOpenTypeSelection(context, "java.lang.String"); context.clickButton("OK"); } }); } }); creationTool = creationToolResult.get(); assertNotNull(creationTool); } // prepare new component ComponentInfo newComponent; { ICreationFactory creationFactory = creationTool.getFactory(); creationFactory.activate(); newComponent = (ComponentInfo) creationFactory.getNewObject(); } // new component has "template arguments" { Map<String, String> templateArguments = newComponent.getTemplateArguments(); assertThat(templateArguments).includes(entry("rowType", "java.lang.String")); } }