List of usage examples for java.util.concurrent.atomic AtomicReference get
public final V get()
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/* www .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:com.microsoft.tfs.core.clients.versioncontrol.internal.WebServiceLayerLocalWorkspaces.java
/** * Given a workspace, returns all pending changes for that workspace by * calling QueryPendingSets on the server. *//*w w w . j a v a2s .c om*/ @Override public PendingChange[] queryServerPendingChanges(final Workspace workspace, final ItemSpec[] itemSpecs, final boolean generateDownloadUrls, final String[] itemPropertyFilters) { Failure[] failures; PendingSet[] pendingSets; if (workspace.getLocation().equals(WorkspaceLocation.LOCAL)) { final _Repository4Soap_QueryPendingSetsWithLocalWorkspacesResponse response; try { response = getRepository4().queryPendingSetsWithLocalWorkspaces(null, null, workspace.getName(), workspace.getOwnerName(), (_ItemSpec[]) WrapperUtils.unwrap(_ItemSpec.class, itemSpecs), generateDownloadUrls, null /* * TODO pass itemPropertyFilters, but servers <= * 2011-10-19 throw null ref exception if you do */); } catch (final ProxyException e) { throw VersionControlExceptionMapper.map(e); } pendingSets = (PendingSet[]) WrapperUtils.wrap(PendingSet.class, response.getQueryPendingSetsWithLocalWorkspacesResult()); failures = (Failure[]) WrapperUtils.wrap(Failure.class, response.getFailures()); } else { final AtomicReference<Failure[]> failuresHolder = new AtomicReference<Failure[]>(); pendingSets = super.queryPendingSets(null, null, workspace.getName(), workspace.getOwnerName(), itemSpecs, generateDownloadUrls, failuresHolder, false, null); failures = failuresHolder.get(); } getVersionControlClient().reportFailures(workspace, failures); if (pendingSets.length == 0) { return new PendingChange[0]; } else { return pendingSets[0].getPendingChanges(); } }
From source file:com.king.platform.net.http.integration.MultiPart.java
@Test public void postMultiPart() throws Exception { AtomicReference<List<FileItem>> partReferences = new AtomicReference<>(); AtomicReference<Exception> exceptionReference = new AtomicReference<>(); integrationServer.addServlet(new HttpServlet() { @Override/*from w w w. j av a2s .c o m*/ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory()); try { List<FileItem> fileItems = servletFileUpload.parseRequest(req); partReferences.set(fileItems); } catch (FileUploadException e) { exceptionReference.set(e); } } }, "/testMultiPart"); httpClient .createPost( "http://localhost:" + port + "/testMultiPart") .idleTimeoutMillis( 0) .totalRequestTimeoutMillis( 0) .content( new MultiPartBuilder() .addPart( MultiPartBuilder .create("text1", "Message 1", StandardCharsets.ISO_8859_1) .contentType("multipart/form-data")) .addPart(MultiPartBuilder.create("binary1", new byte[] { 0x00, 0x01, 0x02 }) .contentType("application/octet-stream").charset(StandardCharsets.UTF_8) .fileName("application.bin")) .addPart(MultiPartBuilder.create("text2", "Message 2", StandardCharsets.ISO_8859_1)) .build()) .build().execute().join(); assertNull(exceptionReference.get()); List<FileItem> fileItems = partReferences.get(); FileItem fileItem = fileItems.get(1); assertEquals("application/octet-stream; charset=UTF-8", fileItem.getContentType()); assertEquals("binary1", fileItem.getFieldName()); assertEquals("application.bin", fileItem.getName()); }
From source file:com.facebook.RequestTests.java
@LargeTest public void testExecuteUploadPhotoToAlbum() throws InterruptedException, JSONException { // first create an album Bundle params = new Bundle(); params.putString("name", "Foo"); GraphRequest request = new GraphRequest(AccessToken.getCurrentAccessToken(), "me/albums", params, HttpMethod.POST);//from w w w . j ava 2 s.c om GraphResponse response = request.executeAndWait(); JSONObject jsonResponse = response.getJSONObject(); assertNotNull(jsonResponse); String albumId = jsonResponse.optString("id"); assertNotNull(albumId); // upload an image to the album Bitmap image = createTestBitmap(128); SharePhoto photo = new SharePhoto.Builder().setBitmap(image).setUserGenerated(true).build(); SharePhotoContent content = new SharePhotoContent.Builder().addPhoto(photo).build(); final ShareApi shareApi = new ShareApi(content); shareApi.setGraphNode(albumId); final AtomicReference<String> imageId = new AtomicReference<>(null); getActivity().runOnUiThread(new Runnable() { @Override public void run() { shareApi.share(new FacebookCallback<Sharer.Result>() { @Override public void onSuccess(Sharer.Result result) { imageId.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(imageId.get()); // now check to see if the image is in the album GraphRequest listRequest = new GraphRequest(AccessToken.getCurrentAccessToken(), albumId + "/photos"); GraphResponse listResponse = listRequest.executeAndWait(); JSONObject listObject = listResponse.getJSONObject(); assertNotNull(listObject); JSONArray jsonList = listObject.optJSONArray("data"); assertNotNull(jsonList); boolean found = false; for (int i = 0; i < jsonList.length(); i++) { JSONObject imageObject = jsonList.getJSONObject(i); if (imageId.get().equals(imageObject.optString("id"))) { found = true; } } assertTrue(found); }
From source file:com.microsoft.tfs.core.clients.versioncontrol.Workstation.java
/** * Call Workstation.Current.ReloadCache() to force a reload of the cache * file from disk.//ww w . j a v a 2s . c o m */ public void reloadCache() { boolean cacheReloaded = false; final AtomicReference<InternalWorkspaceConflictInfo[]> outConflictingWorkspaces = new AtomicReference<InternalWorkspaceConflictInfo[]>(); synchronized (cacheMutex) { if (cacheEnabled) { // Force a reload of the cache file before raising the // notification. cacheFileChanged = true; cacheReloaded = ensureCacheLoaded(outConflictingWorkspaces); } } if (cacheReloaded) { onNonFatalError(outConflictingWorkspaces.get()); // Let the listeners (Client objects) know. onCacheFileReloaded(); } }
From source file:de.sainth.recipe.backend.db.repositories.CookbookRepository.java
public Cookbook save(Cookbook cookbook) { AtomicReference<Cookbook> bu = new AtomicReference<>(); create.transaction(configuration -> { Long id = null;//ww w . ja v a 2 s . c o m if (cookbook.getId() != null) { id = using(configuration).select(COOKBOOKS.ID).from(COOKBOOKS) .where(COOKBOOKS.ID.eq(cookbook.getId())).forUpdate().fetchOneInto(Long.class); } CookbooksRecord cookbooksRecord; if (cookbook.getId() == null || id == null) { cookbooksRecord = using(configuration) .insertInto(COOKBOOKS, COOKBOOKS.NAME, COOKBOOKS.DESCRIPTION, COOKBOOKS.AUTHOR) .values(cookbook.getName(), cookbook.getDescription(), cookbook.getAuthor().getId()) .returning().fetchOne(); } else { cookbooksRecord = using(configuration).update(COOKBOOKS).set(COOKBOOKS.NAME, cookbook.getName()) .set(COOKBOOKS.DESCRIPTION, cookbook.getDescription()).returning().fetchOne(); } List<CookbookRecipe> cookbookRecipes = selectCookbookRecipes( cookbook.getRecipes().stream().map(CookbookRecipe::getId).collect(Collectors.toList()), cookbook.getAuthor().getId()); BatchBindStep batchInsert = using(configuration).batch( create.insertInto(COOKBOOKS_RECIPES, COOKBOOKS_RECIPES.COOKBOOK, COOKBOOKS_RECIPES.RECIPE) .values((Long) null, null)); for (CookbookRecipe r : cookbookRecipes) { batchInsert.bind(cookbooksRecord.getId(), r.getId()); } batchInsert.execute(); bu.set(new Cookbook(cookbooksRecord.getId(), cookbooksRecord.getName(), cookbooksRecord.getDescription(), cookbook.getAuthor(), cookbookRecipes)); }); return bu.get(); }
From source file:org.eclipse.aether.transport.http.HttpTransporterTest.java
@Test(timeout = 20000L) public void testConcurrency() throws Exception { httpServer.setAuthentication("testuser", "testpass"); auth = new AuthenticationBuilder().addUsername("testuser").addPassword("testpass").build(); newTransporter(httpServer.getHttpUrl()); final AtomicReference<Throwable> error = new AtomicReference<Throwable>(); Thread threads[] = new Thread[20]; for (int i = 0; i < threads.length; i++) { final String path = "repo/file.txt?i=" + i; threads[i] = new Thread() { @Override//from www . j av a2s . c o m public void run() { try { for (int j = 0; j < 100; j++) { GetTask task = new GetTask(URI.create(path)); transporter.get(task); assertEquals("test", task.getDataString()); } } catch (Throwable t) { error.compareAndSet(null, t); System.err.println(path); t.printStackTrace(); } } }; threads[i].setName("Task-" + i); } for (Thread thread : threads) { thread.start(); } for (Thread thread : threads) { thread.join(); } assertNull(String.valueOf(error.get()), error.get()); }
From source file:com.microsoft.tfs.client.clc.Application.java
/** * Does almost all of the work of the command-line client. This method is * invoked from the static main() method, and also recursively when a * command file is encountered./*from w w w . j a v a2s . c o m*/ * * @param args * the command-line arguments as passed into the process by the Java * virtual machine (or in that style, but parsed from a command * file). * @param recursiveCall * true if this method was called recursively from itself, false * otherwise. * @return the status code to exit the process with. */ private int run(final String[] args, final boolean recursiveCall) { log.debug("Entering CLC application"); //$NON-NLS-1$ log.debug("Command line: "); //$NON-NLS-1$ for (int i = 0; i < args.length; i++) { final int p = args[i].toLowerCase().indexOf("login:"); //$NON-NLS-1$ if (p < 0) { log.debug(" args[" + i + "]: " + args[i]); //$NON-NLS-1$ //$NON-NLS-2$ } else { log.debug(" args[" + i + "]: " + args[i].substring(0, p + 6) + "*******"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } } /* * create and cache the options map and commands map we also set the * maps on the static Help class so the Help class always has access to * them */ optionsMap = createOptionsMap(); commandsMap = createCommandsMap(); Help.init(commandsMap, optionsMap); Command c = null; int ret = ExitCode.UNKNOWN; boolean printExitCode = false; try { final String[] tokens = args.clone(); log.debug("Parse and prepare arguments."); //$NON-NLS-1$ /* * Check to see if the first argument is a file containing commands. * Don't allow this if we're being called recursively. */ if (recursiveCall == false && tokens.length > 0 && tokens[0].startsWith("@")) //$NON-NLS-1$ { /* * Search all the arguments for the "continue on error" and * output separator options. */ boolean continueOnError = false; String outputSeparator = null; for (int i = 0; i < tokens.length; i++) { if (tokens[i] == null || tokens[i].length() == 0) { continue; } try { final Option o = optionsMap.findOption(tokens[i]); if (o instanceof OptionContinueOnError) { continueOnError = true; } else if (o instanceof OptionOutputSeparator) { outputSeparator = ((OptionOutputSeparator) o).getValue(); } } catch (final Exception e) { // Ignore. } } try { ret = runCommandFile(tokens, continueOnError, outputSeparator); } catch (final FileNotFoundException e) { final String messageFormat = Messages.getString("Application.CommandFileCoundNotBeFoundFormat"); //$NON-NLS-1$ final String message = MessageFormat.format(messageFormat, tokens[0].substring(1)); display.printErrorLine(message); } catch (final IOException e) { final String messageFormat = Messages .getString("Application.ErrorReadingFromCommandFileFormat"); //$NON-NLS-1$ final String message = MessageFormat.format(messageFormat, tokens[0].substring(1), e.getLocalizedMessage()); log.warn(message, e); display.printErrorLine(message); } return ret; } final ArrayList<Option> options = new ArrayList<Option>(); final ArrayList<String> freeArguments = new ArrayList<String>(); /* * Parse all the args into a command, its options, and free * arguments. */ final AtomicReference<Exception> outException = new AtomicReference<Exception>(); c = parseTokens(args, options, freeArguments, outException); /* * Set the display on the command as soon as possible, so it can * write errors/messages. */ if (c != null) { c.setInput(input); c.setDisplay(display); } /* * Search for the help option anywhere in the command line. * Microsoft's client does this for user convenience. Also look for * the exit code option while we're searching. */ boolean foundHelpOption = false; for (int i = 0; i < options.size(); i++) { if (options.get(i) instanceof OptionHelp) { foundHelpOption = true; } if (options.get(i) instanceof OptionExitCode) { printExitCode = true; } } final boolean invalidCommandArguments = outException.get() != null; if (tokens.length == 0 || c == null || foundHelpOption || invalidCommandArguments) { if (invalidCommandArguments) { final String messageFormat = Messages.getString("Application.AnArgumentErrorOccurredFormat"); //$NON-NLS-1$ final String message = MessageFormat.format(messageFormat, outException.get().getLocalizedMessage()); display.printErrorLine(message); } Help.show(c, display); return invalidCommandArguments ? ExitCode.FAILURE : ExitCode.SUCCESS; } c.setOptions(options.toArray(new Option[0]), commandsMap.getGlobalOptions()); c.setFreeArguments(freeArguments.toArray(new String[0])); log.debug("Execute the command implementation."); //$NON-NLS-1$ c.run(); log.debug("Close the command: Flush any remaining notifications and remove the manager"); //$NON-NLS-1$ c.close(); ret = c.getExitCode(); } catch (final CanceledException e) { getDisplay().printErrorLine(""); //$NON-NLS-1$ getDisplay().printErrorLine(Messages.getString("Application.CommandCanceled")); //$NON-NLS-1$ ret = ExitCode.FAILURE; } catch (final InputValidationException e) { final String messageFormat = Messages.getString("Application.AnInputValidationErrorOccurredFormat"); //$NON-NLS-1$ final String message = MessageFormat.format(messageFormat, e.getLocalizedMessage()); display.printErrorLine(message); ret = ExitCode.FAILURE; } catch (final ArgumentException e) { /* * Argument exceptions happen when the user supplies an incorrect * command, misspelled options, the wrong option values, is missing * an option, or other similar error. We should show the help to the * user in this case. */ final String messageFormat = Messages.getString("Application.AnArgumentErrorOccurredFormat"); //$NON-NLS-1$ final String message = MessageFormat.format(messageFormat, e.getLocalizedMessage()); display.printErrorLine(message); Help.show(c, display); ret = ExitCode.FAILURE; } catch (final IllegalArgumentException e) { /* * Same as above but returned by some low level Core or Common * classes, e.g. HttpHost. */ CLCTelemetryHelper.sendException(e); final String messageFormat = Messages.getString("Application.AnArgumentErrorOccurredFormat"); //$NON-NLS-1$ final String message = MessageFormat.format(messageFormat, e.getLocalizedMessage()); display.printErrorLine(message); ret = ExitCode.FAILURE; } catch (final CLCException e) { /* * CLCExceptions have messages that are meaningful to users. */ final String messageFormat = Messages.getString("Application.AClientErrorOccurredFormat"); //$NON-NLS-1$ final String message = MessageFormat.format(messageFormat, e.getLocalizedMessage()); log.error(message, e); display.printErrorLine(message); ret = ExitCode.FAILURE; } catch (final MalformedURLException e) { final String messageFormat = Messages.getString("Application.StringCouldNotBeConvertedToURLFormat"); //$NON-NLS-1$ final String message = MessageFormat.format(messageFormat, e.getLocalizedMessage()); log.info(message, e); display.printErrorLine(message); ret = ExitCode.FAILURE; } catch (final LicenseException e) { final String messageFormat = Messages.getString("Application.LicenseErrorFormat"); //$NON-NLS-1$ final String message = MessageFormat.format(messageFormat, e.getLocalizedMessage()); log.error(message, e); display.printErrorLine(message); if (e.getType() == LicenseExceptionType.EULA) { display.printErrorLine(Messages.getString("Application.RunTfEulaToAccept")); //$NON-NLS-1$ } else { display.printErrorLine(Messages.getString("Application.RunTfProductkeyToInstall")); //$NON-NLS-1$ } ret = ExitCode.FAILURE; } catch (final AuthenticationSecurityException e) { /* * Thrown when using insecure credentials over an insecure channel. */ log.error(e); display.printErrorLine(e.getLocalizedMessage()); ret = ExitCode.FAILURE; } catch (final TFSFederatedAuthException e) { /* * FederatedAuthenticationException is thrown when * DefaultFederatedAuthenticationHandler decided not to try to auth, * which only happens because the username and/or password weren't * available. */ final String message = Messages.getString("Command.FedAuthRequiresUsernamePassword"); //$NON-NLS-1$ log.error(message, e); display.printErrorLine(message); ret = ExitCode.FAILURE; } catch (final ProxyException e) { final String message = MessageFormat.format( Messages.getString("Application.ProblemContactingServerFormat"), //$NON-NLS-1$ e.getLocalizedMessage()); log.error(message, e); display.printErrorLine(message); ret = ExitCode.FAILURE; } catch (final TECoreException e) { /* * The most basic core exception class. All lower level (SOAP) * exceptions are wrapped in these. */ CLCTelemetryHelper.sendException(e); final String messageFormat = Messages.getString("Application.AnErrorOccurredFormat"); //$NON-NLS-1$ final String message = MessageFormat.format(messageFormat, e.getLocalizedMessage()); log.error(message, e); display.printErrorLine(message); ret = ExitCode.FAILURE; } catch (final Throwable e) { CLCTelemetryHelper.sendException(new Exception("Unexpected exception.", e)); //$NON-NLS-1$ log.error("Unexpected exception: ", e); //$NON-NLS-1$ } // If the exit code never got set, set it to 0. if (ret == ExitCode.UNKNOWN) { ret = ExitCode.SUCCESS; } if (printExitCode) { final String messageFormat = Messages.getString("Application.ExitCodeFormat"); //$NON-NLS-1$ final String message = MessageFormat.format(messageFormat, Integer.toString(ret)); display.printLine(message); display.printLine(""); //$NON-NLS-1$ } CLCTelemetryHelper.sendCommandFinishedEvent(c, ret); log.debug("Leaving CLC application"); //$NON-NLS-1$ return ret; }
From source file:test.java.com.spotify.docker.client.DefaultDockerClientTest.java
@Test public void testBuildImageIdWithAuth() throws Exception { final String dockerDirectory = Resources.getResource("dockerDirectory").getPath(); final AtomicReference<String> imageIdFromMessage = new AtomicReference<>(); final DefaultDockerClient sut2 = DefaultDockerClient.builder().uri(dockerEndpoint).authConfig(authConfig) .build();/*ww w . j av a 2 s.com*/ final String returnedImageId = sut2.build(Paths.get(dockerDirectory), "test", new ProgressHandler() { @Override public void progress(ProgressMessage message) throws DockerException { final String imageId = message.buildImageId(); if (imageId != null) { imageIdFromMessage.set(imageId); } } }); assertThat(returnedImageId, is(imageIdFromMessage.get())); }
From source file:com.netflix.curator.framework.recipes.leader.TestLeaderSelectorCluster.java
@Test public void testLostRestart() throws Exception { final Timing timing = new Timing(); CuratorFramework client = null;/*from ww w .j a v a 2 s.c om*/ TestingCluster cluster = new TestingCluster(3); cluster.start(); try { client = CuratorFrameworkFactory.newClient(cluster.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); client.sync("/", null); final AtomicReference<Exception> error = new AtomicReference<Exception>(null); final AtomicReference<String> lockNode = new AtomicReference<String>(null); final Semaphore semaphore = new Semaphore(0); final CountDownLatch lostLatch = new CountDownLatch(1); final CountDownLatch internalLostLatch = new CountDownLatch(1); LeaderSelectorListener listener = new LeaderSelectorListener() { @Override public void takeLeadership(CuratorFramework client) throws Exception { try { List<String> names = client.getChildren().forPath("/leader"); if (names.size() != 1) { semaphore.release(); Exception exception = new Exception("Names size isn't 1: " + names.size()); error.set(exception); return; } lockNode.set(names.get(0)); semaphore.release(); if (!timing.multiple(4).awaitLatch(internalLostLatch)) { error.set(new Exception("internalLostLatch await failed")); } } finally { lostLatch.countDown(); } } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if (newState == ConnectionState.LOST) { internalLostLatch.countDown(); } } }; LeaderSelector selector = new LeaderSelector(client, "/leader", listener); selector.start(); Assert.assertTrue(timing.multiple(4).acquireSemaphore(semaphore)); if (error.get() != null) { throw new AssertionError(error.get()); } Collection<InstanceSpec> instances = cluster.getInstances(); cluster.stop(); Assert.assertTrue(timing.multiple(4).awaitLatch(lostLatch)); timing.sleepABit(); Assert.assertFalse(selector.hasLeadership()); Assert.assertNotNull(lockNode.get()); cluster = new TestingCluster(instances.toArray(new InstanceSpec[instances.size()])); cluster.start(); try { client.delete().forPath(ZKPaths.makePath("/leader", lockNode.get())); // simulate the lock deleting due to session expiration } catch (Exception ignore) { // ignore } Assert.assertTrue(semaphore.availablePermits() == 0); Assert.assertFalse(selector.hasLeadership()); selector.requeue(); Assert.assertTrue(timing.multiple(4).acquireSemaphore(semaphore)); } finally { IOUtils.closeQuietly(client); IOUtils.closeQuietly(cluster); } }