List of usage examples for java.util.concurrent ExecutorService submit
Future<?> submit(Runnable task);
From source file:com.tasktop.c2c.server.ssh.server.commands.AbstractInteractiveProxyCommand.java
protected void performCommand(Environment env, ProjectService service, String projectId, String path, String requestPath, RequestHeadersSupport headers) throws CommandException { String internalProxyUri = service.computeInternalProxyBaseUri(false); if (internalProxyUri == null) { throw new IllegalStateException(); }/*from w w w . j a va 2s .c om*/ URI targetUri; try { if (!internalProxyUri.endsWith("/")) { internalProxyUri += "/"; } internalProxyUri += getName() + '/' + path; targetUri = new URI(internalProxyUri); } catch (URISyntaxException e) { throw new RuntimeException(e); } String host = targetUri.getHost(); int port = targetUri.getPort(); if (port < 0) { port = 80; } if (targetUri.getScheme() == null || !targetUri.getScheme().equalsIgnoreCase("http")) { throw new IllegalStateException("scheme " + targetUri.getScheme() + " is not supported"); } HeaderGroup headerGroup = computeHeaders(targetUri); for (Entry<String, List<String>> headerEntry : headers.getRequestHeaders().entrySet()) { for (String value : headerEntry.getValue()) { headerGroup.addHeader(new Header(headerEntry.getKey(), value)); } } getLogger().info("Proxying " + getName() + " to " + targetUri); try { Socket socket = socketFactory.openConnection(host, port); try { // initiate an HTTP request with Transfer-Encoding: chunked OutputStream proxyOut = socket.getOutputStream(); emitHttpRequestLine(proxyOut, targetUri); emitHeaders(proxyOut, headerGroup); proxyOut.flush(); List<Callable<Void>> tasks = new ArrayList<Callable<Void>>(3); FlushingChunkedOutputStream chunkedRequestOut = new FlushingChunkedOutputStream(proxyOut); tasks.add(new InputPipe(in, chunkedRequestOut, bufferSize, Thread.currentThread()).flush(true)); // start these pipes ExecutorService executor = Executors.newFixedThreadPool(tasks.size()); try { for (Callable<Void> task : tasks) { executor.submit(task); } InputStream proxyInput = socket.getInputStream(); try { readHttpResponse(proxyInput); MultiplexingInputStream input = new MultiplexingInputStream( new ChunkedInputStream(proxyInput)); for (;;) { PacketType packetType = input.getPacketType(); if (packetType == null) { break; } int length = input.getPacketLength(); processData(input, packetType, length); } } finally { try { executor.shutdown(); executor.awaitTermination(1000L, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { // ignore } } } finally { executor.shutdownNow(); try { executor.awaitTermination(3000L, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { // ignore } Thread.interrupted(); try { // attempt to close the chunked output, since this will make us a well-behaved client // by sending the closing chunk. chunkedRequestOut.close(); } catch (Throwable t) { // ignore } } } finally { socket.close(); } } catch (ConnectException e) { getLogger().error(e.getMessage(), e); throw new CommandException(-1, "Service temporarily unavailable"); } catch (IOException e) { getLogger().warn(e.getMessage(), e); throw new CommandException(-1, e.getMessage()); } }
From source file:com.marketplace.Main.java
/** * Creates <code>PackageThread</code> for each package name found in the * file.// www . j a v a 2 s . co m * * @return a set containing <code>PackageThread</code> */ private Set<Future<?>> createPackageThread() { log.info("Creating threads for fetching apps via packages."); if (this.packageFile == null) { System.err.println("Please pass the location of file"); System.exit(1); } Fetcher fetcher = new Fetcher(); ExecutorService executorService = Executors.newFixedThreadPool(22); Set<Future<?>> set = new HashSet<Future<?>>(); Session[] sessions = this.sessionManager.getSessions(); List<String> packageNames = fetcher.readFile(this.packageFile); Iterator<String> iterator = packageNames.iterator(); for (int i = sessions.length; i > 0; i--) { while (iterator.hasNext()) { set.add(executorService.submit(new PackageThread(sessions[i - 1], fetcher, iterator.next()))); } iterator = packageNames.iterator(); } return set; }
From source file:fr.mby.opa.pics.web.controller.PicsController.java
@RequestMapping(value = "rebuildThumbnails/{width}/{height}/{format}", method = RequestMethod.GET) public String rebuildThumbnails(@PathVariable final Integer width, @PathVariable final Integer height, @PathVariable final String format, final HttpServletRequest request, final HttpServletResponse response) throws Exception { final Integer selectedWidth = (width != null) ? width : 800; final Integer selectedHeight = (height != null) ? height : 200; final String selectedFormat = (format != null) ? format : "jpg"; final ExecutorService rebuildThumbnailsExecutor = Executors .newFixedThreadPool(Runtime.getRuntime().availableProcessors()); Long since = 0L;//from w w w.ja v a 2 s . c o m List<Picture> pictures = null; do { pictures = this.pictureDao.findAllPictures(since); final Collection<Future<Void>> futures = new ArrayList<>(pictures.size()); for (final Picture picture : pictures) { final Future<Void> future = rebuildThumbnailsExecutor.submit(new Callable<Void>() { @Override public Void call() throws Exception { final BinaryImage generated = PicsController.this.pictureService.generateThumbnail(picture, selectedWidth, selectedHeight, true, selectedFormat); // Set the old Id to update final BinaryImage thumbnailToUpdate = picture.getThumbnail(); thumbnailToUpdate.setData(generated.getData()); thumbnailToUpdate.setFormat(generated.getFormat()); thumbnailToUpdate.setWidth(generated.getWidth()); thumbnailToUpdate.setHeight(generated.getHeight()); picture.setThumbnail(generated); picture.setThumbnailWidth(generated.getWidth()); picture.setThumbnailHeight(generated.getHeight()); picture.setThumbnailFormat(generated.getFormat()); picture.setThumbnailSize(generated.getData().length); PicsController.this.pictureDao.updatePicture(picture); // Free memory picture.setThumbnail(null); picture.setImage(null); return null; } }); since = picture.getOriginalTime().getTime(); futures.add(future); } for (final Future<Void> future : futures) { future.get(); } } while (pictures != null && pictures.size() > 0); return "index"; }
From source file:com.netflix.genie.client.JobClientIntegrationTests.java
/** * Method to test submitting/killing a job. * * @throws Exception If there is any problem. *///from w ww.jav a 2 s. c o m @Test public void submitAndKillJob() throws Exception { createClusterAndCommandForTest(); final String jobId = UUID.randomUUID().toString(); final List<ClusterCriteria> clusterCriteriaList = Lists .newArrayList(new ClusterCriteria(Sets.newHashSet("laptop"))); final Set<String> commandCriteria = Sets.newHashSet("bash"); final String depFile1 = this.resourceLoader.getResource("/dep1").getFile().getAbsolutePath(); final Set<String> dependencies = Sets.newHashSet(depFile1); final String setUpFile = this.resourceLoader.getResource("/setupfile").getFile().getAbsolutePath(); final JobRequest jobRequest = new JobRequest.Builder(JOB_NAME, JOB_USER, JOB_VERSION, "-c 'echo HELLO WORLD!!!'", clusterCriteriaList, commandCriteria).withId(jobId) .withDisableLogArchival(true).withSetupFile(setUpFile).withDependencies(dependencies) .withDescription(JOB_DESCRIPTION).build(); final ExecutorService executors = Executors.newFixedThreadPool(2); final Future<String> jobFuture; try { jobFuture = executors.submit(() -> jobClient.submitJob(jobRequest)); executors.submit(() -> { boolean result = true; while (result) { try { jobClient.getJob(jobId); jobClient.killJob(jobId); Thread.sleep(1000); result = false; } catch (Exception ignored) { result = true; } } }); } finally { executors.shutdown(); executors.awaitTermination(Integer.MAX_VALUE, TimeUnit.HOURS); } final Job job = jobClient.getJob(jobId); Assert.assertEquals(jobId, jobFuture.get()); Assert.assertEquals(JobStatus.KILLED, job.getStatus()); }
From source file:ca.ualberta.cmput301w13t11.FoodBook.model.ServerClient.java
/** * Uploads the given recipe to the server. * @param recipe The recipe to be uploaded. * ReturnCode.ERROR if anything goes wrong, ReturnCode.ALREADY_EXISTS if a recipe * by that name already exists on the server (this will eventually be modified to check * against URI instead of Recipe title), ReturnCode.SUCCESS if the recipe was successfully * uploaded, or ReturnCode.BUSY if the network is not responding or the operation is * taking too long.// w ww . ja v a 2 s.com */ public ReturnCode uploadRecipe(Recipe recipe) throws IllegalStateException, IOException { ExecutorService executor = Executors.newSingleThreadExecutor(); Future<ReturnCode> future = executor.submit(new UploadRecipeTask(recipe)); ReturnCode ret = ReturnCode.ERROR; try { ret = future.get(TIMEOUT_PERIOD, TimeUnit.SECONDS); } catch (TimeoutException te) { logger.log(Level.SEVERE, "Upload Recipe operation timed out."); return ReturnCode.BUSY; } catch (Exception e) { logger.log(Level.SEVERE, "Exception during upload recipe operation."); return ReturnCode.ERROR; } /* Got here so the operation finished. */ executor.shutdownNow(); return ret; }
From source file:ca.ualberta.cmput301w13t11.FoodBook.model.ServerClient.java
/** * Performs a search of online recipes by keywords. * @param str The string of keywords we wish to search by. * @return ReturnCode.ERROR if anything goes wrong, ReturnCode.NO_RESULTS if * the search returned no results, ReturnCode.SUCCESS if the search was successful, * in which case the results are written to the database and the observing views * are notified, ReturnCode.BUSY if the server was busy or the operation took * longer than TIME_PERIOD seconds./*from ww w. j ava 2 s .c om*/ */ public ReturnCode searchByKeywords(String str) throws ClientProtocolException, IOException { ExecutorService executor = Executors.newSingleThreadExecutor(); Future<ReturnCode> future = executor.submit(new SearchByKeywordsTask(str)); ReturnCode ret = ReturnCode.ERROR; try { ret = future.get(TIMEOUT_PERIOD, TimeUnit.SECONDS); } catch (TimeoutException te) { logger.log(Level.SEVERE, "Search by Keywords operation timed out."); return ReturnCode.BUSY; } catch (Exception e) { logger.log(Level.SEVERE, "Exception during Search by Keywords operation."); return ReturnCode.ERROR; } /* Got here so the operation finished. */ executor.shutdownNow(); return ret; }
From source file:ca.ualberta.cmput301w13t11.FoodBook.model.ServerClient.java
/** * Upload the given Photo to the appropriate Recipe. * @param (Photo) photo The photo to be added to the server-side version of the Recipe. * @param (long) uri The uri of the Recipe to be updated. * @return NOT_FOUND if the Recipe cannot be found on the server, * ERROR on any other error occurred while attempting to upload, * SUCCESS on successful upload. *//*from w ww .ja va 2s.co m*/ public ReturnCode uploadPhotoToRecipe(Photo photo, long uri) { ExecutorService executor = Executors.newSingleThreadExecutor(); Future<ReturnCode> future = executor.submit(new UploadPhotoTask(photo, uri)); ReturnCode ret = ReturnCode.ERROR; try { ret = future.get(TIMEOUT_PERIOD + UPLOAD_PHOTO_GRACE_PERIOD, TimeUnit.SECONDS); } catch (TimeoutException te) { logger.log(Level.SEVERE, "Upload photo operation timed out."); return ReturnCode.BUSY; } catch (Exception e) { logger.log(Level.SEVERE, "Exception during upload photo operation."); return ReturnCode.ERROR; } /* Got here so the operation finished. */ executor.shutdownNow(); return ret; }
From source file:ca.ualberta.cmput301w13t11.FoodBook.model.ServerClient.java
/** * Query the server for Recipes which contains at subset of the given ingredients list. * @param ingredients The list of ingredients by which to search. * @return ReturnCode.ERROR if anything goes wrong, ReturnCode.NO_RESULTS if * the search returned no results, ReturnCode.SUCCESS if the search was successful, * in which case the results are written to the database and the observing views * are notified, ReturnCode.BUSY if the server was busy or the operation took * longer than TIME_PERIOD seconds.// ww w.j a v a 2s . com */ public ReturnCode searchByIngredients(ArrayList<Ingredient> ingredients) { ExecutorService executor = Executors.newSingleThreadExecutor(); Future<ReturnCode> future = executor.submit(new SearchByIngredientsTask(ingredients)); ReturnCode ret = ReturnCode.ERROR; try { ret = future.get(TIMEOUT_PERIOD, TimeUnit.SECONDS); } catch (TimeoutException te) { logger.log(Level.SEVERE, "Search by Ingredients operation timed out."); return ReturnCode.BUSY; } catch (Exception e) { logger.log(Level.SEVERE, "Exception during Search by Ingredients operation."); return ReturnCode.ERROR; } /* Got here so the operation finished. */ executor.shutdownNow(); return ret; }
From source file:com.joyent.manta.client.MantaClientIT.java
@Test public final void canCreateStreamInOneThreadAndCloseInAnother() throws Exception { final String name = UUID.randomUUID().toString(); final String path = testPathPrefix + name; try (InputStream in = new RandomInputStream(8000)) { mantaClient.put(path, in);/*ww w. j a v a2 s . c om*/ } File temp = File.createTempFile("object-" + name, ".data"); FileUtils.forceDeleteOnExit(temp); FileOutputStream out = new FileOutputStream(temp); Callable<InputStream> callable = () -> mantaClient.getAsInputStream(path); ExecutorService service = Executors.newFixedThreadPool(1); InputStream in = service.submit(callable).get(); try { IOUtils.copyLarge(in, out); } finally { in.close(); out.close(); } }