List of usage examples for java.util.concurrent.atomic AtomicReference get
public final V get()
From source file:de.codesourcery.eve.skills.market.impl.EveCentralMarketDataProvider.java
private static Map<InventoryType, PriceInfoQueryResult> runOnEventThread(final PriceCallable r) throws PriceInfoUnavailableException { if (SwingUtilities.isEventDispatchThread()) { return r.call(); }/* w w w . j av a 2s.c o m*/ final AtomicReference<Map<InventoryType, PriceInfoQueryResult>> result = new AtomicReference<Map<InventoryType, PriceInfoQueryResult>>(); try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { try { result.set(r.call()); } catch (PriceInfoUnavailableException e) { throw new RuntimeException(e); } } }); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (InvocationTargetException e) { Throwable wrapped = e.getTargetException(); if (wrapped instanceof RuntimeException) { if (wrapped.getCause() instanceof PriceInfoUnavailableException) { throw (PriceInfoUnavailableException) wrapped.getCause(); } throw (RuntimeException) wrapped; } else if (e.getTargetException() instanceof Error) { throw (Error) wrapped; } throw new RuntimeException(e.getTargetException()); } return result.get(); }
From source file:org.workspace7.moviestore.controller.ShoppingCartController.java
/** * @param modelAndView/*w w w . j a va 2 s . co m*/ * @param session * @param response * @return */ @GetMapping("/cart/show") public ModelAndView showCart(ModelAndView modelAndView, HttpSession session, HttpServletResponse response) { final String hostname = System.getenv().getOrDefault("HOSTNAME", "unknown"); modelAndView.addObject("hostname", hostname); MovieCart movieCart = (MovieCart) session.getAttribute(SESSION_ATTR_MOVIE_CART); log.info("Showing Cart {}", movieCart); if (movieCart != null) { modelAndView.addObject("movieCart", movieCart); AtomicReference<Double> cartTotal = new AtomicReference<>(0.0); Map<String, Integer> movieItems = movieCart.getMovieItems(); List<MovieCartItem> cartMovies = movieCart.getMovieItems().keySet().stream().map(movieId -> { Movie movie = movieDBHelper.query(movieId); int quantity = movieItems.get(movieId); double total = quantity * movie.getPrice(); cartTotal.updateAndGet(aDouble -> aDouble + total); log.info("Movie:{} total for {} items is {}", movie, quantity, total); return MovieCartItem.builder().movie(movie).quantity(quantity).total(total).build(); }).collect(Collectors.toList()); modelAndView.addObject("cartItems", cartMovies); modelAndView.addObject("cartCount", cartMovies.size()); modelAndView.addObject("cartTotal", "" + DecimalFormat.getCurrencyInstance(Locale.US).format(cartTotal.get())); modelAndView.setViewName("cart"); } else { modelAndView.setViewName("redirect:/"); } return modelAndView; }
From source file:edu.rit.flick.genetics.FastFileDeflator.java
@Override public File deflate(final Configuration configuration, final File fileIn, final File fileOut) { assert fileIn.exists(); try {//from w w w .j a v a 2 s.c o m // Deflate to Directory final String outputDirectoryPath = fileOut.getPath() .replaceAll("." + Files.getFileExtension(fileOut.getPath()), FLICK_FAST_FILE_TMP_DIR_SUFFIX); final File tmpOutputDirectory = new File(outputDirectoryPath); if (tmpOutputDirectory.exists()) FileUtils.deleteDirectory(tmpOutputDirectory); tmpOutputDirectory.mkdirs(); final AtomicReference<Thread> cleanHookAtomic = new AtomicReference<Thread>(); // Deflate Fast file to a temporary directory final Thread deflateToDirectoryThread = new Thread(() -> { try { // Deflate Fast file to a temporary directory deflateToDirectory(fileIn, tmpOutputDirectory); // Remove unused buffer space removeUnusedBufferSpace(outputDirectoryPath); // Compress Directory to a zip file deflateToFile(tmpOutputDirectory, fileOut); Runtime.getRuntime().removeShutdownHook(cleanHookAtomic.get()); } catch (final Exception e) { if (!interrupted) System.err.println(e.getMessage()); } }, "Default_Deflation_Thread"); // Make cleaning hook final Thread cleanHook = new Thread(() -> { interrupted = true; configuration.setFlag(VERBOSE_FLAG, false); configuration.setFlag(DELETE_FLAG, false); try { if (deflateToDirectoryThread.isAlive()) deflateToDirectoryThread.interrupt(); // Remove unused buffer space removeUnusedBufferSpace(outputDirectoryPath); // Delete files that were not able to be processed FileUtils.deleteQuietly(tmpOutputDirectory); System.out.println(); } catch (final IOException | InterruptedException e) { e.printStackTrace(); } }, "Deflation_Cleaning_Thread"); cleanHookAtomic.set(cleanHook); Runtime.getRuntime().addShutdownHook(cleanHook); deflateToDirectoryThread.start(); deflateToDirectoryThread.join(); } catch (final IOException | InterruptedException e) { e.printStackTrace(); } return fileOut; }
From source file:com.opopov.cloud.image.DecodeImageTest.java
@Test public void testLoadImage() throws Exception { ImageStitchingConfiguration config = new ImageStitchingConfiguration(); config.setRowCount(3);//from w w w . j a v a 2 s . c o m config.setColumnCount(3); config.setSourceHeight(256); config.setSourceWidth(256); String[][] imageUrls = new String[][] { //rows left to right, top to bottom { "z15/9/x9650/5/y5596", "z15/9/x9650/5/y5597", "z15/9/x9650/5/y5598" }, { "z15/9/x9651/5/y5596", "z15/9/x9651/5/y5597", "z15/9/x9651/5/y5598" }, { "z15/9/x9652/5/y5596", "z15/9/x9652/5/y5597", "z15/9/x9652/5/y5598" } }; String pattern = "http://www.opopov.com/osmtopo1/%s.png"; for (String[] row : imageUrls) { for (String cell : row) { config.getUrlList().add(String.format(pattern, cell)); } } final AtomicReference<byte[]> buffer = new AtomicReference<>(); DeferredResult<ResponseEntity<?>> result = service.getStitchedImage(config); result.setResultHandler(new DeferredResult.DeferredResultHandler() { @Override public void handleResult(Object result) { ResponseEntity<byte[]> responseEntity = (ResponseEntity<byte[]>) result; buffer.set(responseEntity.getBody()); } }); Thread.sleep(TIMEOUT_MILLIS); InputStream is = getClass().getResourceAsStream("/horizontal-stitched-test-1-frame.png"); byte[] expectedBytes = IOUtils.toByteArray(is); // Uncomment the lines below to see the generated stitched image // FileOutputStream fos = new FileOutputStream("/tmp/horizontal-stitched-test-1-frame.png"); // IOUtils.write(buffer.get(), fos); // fos.close(); Assert.assertTrue("Image data of stitched PNG image", Arrays.equals(expectedBytes, buffer.get())); }
From source file:com.urswolfer.intellij.plugin.gerrit.rest.GerritUtil.java
private <T> T doAccessToGerritWithModalProgress(@NotNull final Project project, @NotNull final ThrowableComputable<T, Exception> computable) { final AtomicReference<T> result = new AtomicReference<T>(); final AtomicReference<Exception> exception = new AtomicReference<Exception>(); ProgressManager.getInstance().run(new Task.Modal(project, "Access to Gerrit", true) { public void run(@NotNull ProgressIndicator indicator) { try { result.set(computable.compute()); } catch (Exception e) { exception.set(e);//w ww . j av a 2s. c om } } }); //noinspection ThrowableResultOfMethodCallIgnored if (exception.get() == null) { return result.get(); } throw Throwables.propagate(exception.get()); }
From source file:com.microsoft.gittf.client.clc.commands.framework.Command.java
private TFSTeamProjectCollection getConnection(final URI serverURI, final AtomicReference<Credentials> credentials) throws Exception { Check.notNull(serverURI, "serverURI"); //$NON-NLS-1$ Check.notNull(credentials, "credentials"); //$NON-NLS-1$ if (connection == null) { getProgressMonitor().displayMessage(Messages.getString("Command.ConnectingToTFS")); //$NON-NLS-1$ boolean authenticated = false, isHostedServer = false; int connectionTryCount = 0; while (!authenticated) { connectionTryCount++;// ww w . j a v a2s . c o m connection = new TFSTeamProjectCollection(serverURI, credentials.get(), new GitTFConnectionAdvisor()); try { connection.ensureAuthenticated(); authenticated = true; } catch (TECoreException e) { if (e.getCause() != null && e.getCause() instanceof EndpointNotFoundException) { throw new Exception(Messages.formatString("Command.InvalidServerMissingCollectionFormat", //$NON-NLS-1$ serverURI.toString()), e); } if (connectionTryCount > 3) { if (isHostedServer) { throw new Exception(Messages.formatString("Command.FailedToConnectToHostedFormat", //$NON-NLS-1$ serverURI.toString()), e); } throw e; } if (e instanceof ACSUnauthorizedException || e instanceof TFSFederatedAuthException || (e.getCause() != null && (e.getCause() instanceof AuthenticationException || e.getCause() instanceof UnauthorizedException))) { if (connectionTryCount == 1) { isHostedServer = e instanceof TFSFederatedAuthException; } Credentials newCredentials = promptForCredentials(connection.getCredentials()); if (newCredentials == null) { throw e; } credentials.set(newCredentials); } else { throw e; } } } } return connection; }
From source file:hudson.plugins.jobConfigHistory.FileHistoryDao.java
File createNewHistoryEntry(Node node, final String operation) { try {/*from w ww . jav a2 s. c o m*/ final AtomicReference<Calendar> timestampHolder = new AtomicReference<Calendar>(); final File timestampedDir = getRootDir(node, timestampHolder); LOG.log(Level.FINE, "{0} on {1}", new Object[] { this, timestampedDir }); createHistoryXmlFile(timestampHolder.get(), timestampedDir, operation); assert timestampHolder.get() != null; return timestampedDir; } catch (IOException e) { // If not able to create the history entry, log, but continue without it. // A known issue is where Hudson core fails to move the folders on rename, // but continues as if it did. // Reference https://issues.jenkins-ci.org/browse/JENKINS-8318 throw new RuntimeException( "Unable to create history entry for configuration file of node " + node.getDisplayName(), e); } }
From source file:hudson.plugins.jobConfigHistory.FileHistoryDao.java
/** * Creates a new history entry./*from w w w .j ava 2s.c o m*/ * * @param xmlFile to save. * @param operation description * * @return timestampedDir */ File createNewHistoryEntry(final XmlFile xmlFile, final String operation) { try { final AtomicReference<Calendar> timestampHolder = new AtomicReference<Calendar>(); final File timestampedDir = getRootDir(xmlFile, timestampHolder); LOG.log(Level.FINE, "{0} on {1}", new Object[] { this, timestampedDir }); createHistoryXmlFile(timestampHolder.get(), timestampedDir, operation); assert timestampHolder.get() != null; return timestampedDir; } catch (IOException e) { // If not able to create the history entry, log, but continue without it. // A known issue is where Hudson core fails to move the folders on rename, // but continues as if it did. // Reference https://issues.jenkins-ci.org/browse/JENKINS-8318 throw new RuntimeException( "Unable to create history entry for configuration file: " + xmlFile.getFile().getAbsolutePath(), e); } }
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 av a2s. co 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:org.zodiark.service.publisher.PublisherServiceImpl.java
/** * {@inheritDoc}//from w w w . j a va 2 s .co m */ @Override public PublisherEndpoint createSession(final Envelope e, final AtmosphereResource r) { if (!e.getMessage().hasData()) { error(e, r, utils.errorMessage("error", e.getMessage().getUUID())); return null; } final String uuid = e.getUuid(); PublisherEndpoint p = endpoints.get(uuid); if (p == null) { p = context.newInstance(PublisherEndpoint.class); p.uuid(uuid).resource(r); endpoints.put(uuid, p); final AtomicReference<PublisherEndpoint> publisher = new AtomicReference<>(p); String data = e.getMessage().getData(); e.getMessage().setData(injectIp(r.getRequest().getRemoteAddr(), data)); eventBus.message(DB_POST_PUBLISHER_SESSION_CREATE, new RetrieveMessage(p.uuid(), e.getMessage()), new Reply<Status, String>() { @Override public void ok(final Status status) { final PublisherEndpoint p = publisher.get(); logger.trace("{} succeed for {}", DB_POST_PUBLISHER_SESSION_CREATE, p); eventBus.message(DB_ENDPOINT_STATE, new RetrieveMessage(p.uuid(), e.getMessage()), new Reply<EndpointState, String>() { @Override public void ok(EndpointState state) { p.state(state); eventBus.message(DB_PUBLISHER_AVAILABLE_ACTIONS_PASSTHROUGHT, new RetrieveMessage(p.uuid(), e.getMessage()), new Reply<String, String>() { @Override public void ok(String passthrough) { utils.succesPassThrough(e, p, DB_PUBLISHER_AVAILABLE_ACTIONS_PASSTHROUGHT, passthrough); eventBus.message(DB_PUBLISHER_LOAD_CONFIG_GET, new RetrieveMessage(p.uuid(), e.getMessage()), new Reply<String, String>() { @Override public void ok(String passthrough) { utils.succesPassThrough(e, p, DB_PUBLISHER_LOAD_CONFIG, passthrough); utils.passthroughEvent( DB_PUBLISHER_LOAD_CONFIG_ERROR_PASSTHROUGHT, e, p); } @Override public void fail( ReplyException replyException) { utils.failPassThrough(e, p, replyException); } }); } @Override public void fail(ReplyException replyException) { utils.failPassThrough(e, p, replyException); } }); } @Override public void fail(ReplyException replyException) { error(e, publisher.get(), utils.errorMessage("error", e.getMessage().getUUID())); } }); } @Override public void fail(ReplyException replyException) { error(e, publisher.get(), utils.constructMessage(DB_POST_PUBLISHER_SESSION_CREATE, "error", e.getMessage().getUUID())); } }); } r.addEventListener(new OnDisconnect() { @Override public void onDisconnect(AtmosphereResourceEvent event) { logger.debug("Publisher {} disconnected", uuid); endpoints.remove(uuid); } }); return p; }