List of usage examples for java.util.concurrent Callable Callable
Callable
From source file:org.eclipse.virgo.ide.runtime.internal.core.command.AbstractJmxServerCommand.java
protected final Object execute(final JmxServerCommandTemplate template) throws TimeoutException { Callable<Object> deployOperation = new Callable<Object>() { public Object call() throws Exception { JMXConnector connector = null; try { connector = getJmxConnector(); return template.invokeOperation(connector.getMBeanServerConnection()); } finally { if (connector != null) { try { connector.close(); } catch (IOException e) { SpringCore.log(e); }/* w ww. ja v a2 s. com*/ } } } }; FutureTask<Object> task = new FutureTask<Object>(deployOperation); ServerCorePlugin.EXECUTOR.submit(task); try { return task.get(30, TimeUnit.SECONDS); } catch (InterruptedException e) { // swallow exception here } catch (ExecutionException e) { // swallow exception here } return null; }
From source file:org.jasig.portlet.blackboardvcportlet.dao.impl.MultimediaDaoImplTest.java
@Test public void testDeleteMultimedia() { this.execute(new Callable<Object>() { @Override/*from ww w .ja v a2 s. c o m*/ public Object call() { final BlackboardMultimediaResponse response = new BlackboardMultimediaResponse(); response.setCreatorId("test@example.com"); response.setDescription("super sweet media"); response.setMultimediaId(183838); response.setSize(1024); final Multimedia mm = dao.createMultimedia(response, "aliens_exist.pdf"); dao.deleteMultimedia(mm); Multimedia shouldBeNull = dao.getMultimediaByBlackboardId(mm.getBbMultimediaId()); assertNull(shouldBeNull); return null; } }); }
From source file:org.fcrepo.indexer.solr.SolrIndexer.java
@Override public Callable<UpdateResponse> updateSynch(final String id, final NamedFields fields) { LOGGER.debug("Received request for update to: {}", id); return new Callable<UpdateResponse>() { @Override/*from w ww. j a va 2 s. c o m*/ public UpdateResponse call() { try { LOGGER.debug("Executing request to Solr index for identifier: {} with fields: {}", id, fields); // add the identifier of the resource as a unique index-key fields.put("id", asList(id)); // pack the fields into a Solr input doc final SolrInputDocument inputDoc = fromMap(fields); LOGGER.debug("Created SolrInputDocument: {}", inputDoc); final UpdateResponse resp = server.add(inputDoc); if (resp.getStatus() == 0) { LOGGER.debug("Update request was successful for: {}", id); } else { LOGGER.error("Update request returned error code: {} for identifier: {}", resp.getStatus(), id); } LOGGER.debug("Received result from Solr request."); return resp; } catch (final SolrServerException | IOException e) { LOGGER.error("Update exception: {}!", e); throw propagate(e); } } }; }
From source file:io.fabric8.forge.camel.commands.project.helper.CamelCommandsHelper.java
public static Callable<Iterable<ComponentDto>> createAllComponentDtoValues(final Project project, final CamelCatalog camelCatalog, final UISelectOne<String> componentCategoryFilter, final boolean excludeComponentsOnClasspath) { // use callable so we can live update the filter return new Callable<Iterable<ComponentDto>>() { @Override//from ww w.java 2 s .co m public Iterable<ComponentDto> call() throws Exception { String label = componentCategoryFilter.getValue(); return new CamelComponentsCompleter(project, camelCatalog, null, excludeComponentsOnClasspath, true, false, false).getValueChoices(label); } }; }
From source file:de.btobastian.javacord.entities.impl.ImplInviteBuilder.java
@Override public Future<Invite> create(FutureCallback<Invite> callback) { ListenableFuture<Invite> future = api.getThreadPool().getListeningExecutorService() .submit(new Callable<Invite>() { @Override//from w w w.java2 s. c o m public Invite call() throws Exception { logger.debug( "Trying to create invite for channel {} (max uses: {}, temporary: {}, max age: {}", textChannel == null ? voiceChannel : textChannel, maxUses, temporary, maxAge); JSONObject jsonParam = new JSONObject(); if (maxUses > 0) { jsonParam.put("max_uses", maxUses); } if (temporary > -1) { jsonParam.put("temporary", temporary == 1); } if (maxAge > 0) { jsonParam.put("max_age", maxAge); } String channelId = textChannel == null ? voiceChannel.getId() : textChannel.getId(); HttpResponse<JsonNode> response = Unirest .post("https://discordapp.com/api/channels/" + channelId + "/invites") .header("authorization", api.getToken()).header("Content-Type", "application/json") .body(jsonParam.toString()).asJson(); api.checkResponse(response); api.checkRateLimit(response, RateLimitType.UNKNOWN, null, null); JSONObject data = response.getBody().getObject(); logger.debug("Created invite for channel {} (max uses: {}, temporary: {}, max age: {}", textChannel == null ? voiceChannel : textChannel, maxUses, temporary, data.has("max_age") ? data.getInt("max_age") : -1); return new ImplInvite(api, data); } }); if (callback != null) { Futures.addCallback(future, callback); } return future; }
From source file:cherry.chart.app.LineChartBatch.java
@Override public ExitStatus execute(String... args) { int nThread = (args.length < 1 ? defaultNumThread : parseInt(args[0])); int count = (args.length < 2 ? defaultCount : parseInt(args[1])); ExecutorService executorService = Executors.newFixedThreadPool(nThread); List<Future<Boolean>> tasks = new LinkedList<>(); for (int i = 0; i < count; i++) { final String numStr = String.valueOf(i); tasks.add(executorService.submit(new Callable<Boolean>() { @Override//from w w w .ja v a2 s. com public Boolean call() { File f = new File(toDir, format(file, numStr)); String t = format(title, numStr); CategoryDataset dataset = createDataset(); JFreeChart chart = ChartFactory.createLineChart(t, xLabel, yLabel, dataset); try (OutputStream out = new FileOutputStream(f)) { ChartUtilities.writeChartAsPNG(out, chart, width, height); return true; } catch (IOException ex) { log.error("failed to create file", ex); return false; } } })); } boolean success = true; for (Future<Boolean> future : tasks) { try { success &= future.get(); } catch (ExecutionException | InterruptedException ex) { log.error("failed to get result", ex); success = false; } } return (success ? ExitStatus.NORMAL : ExitStatus.ERROR); }
From source file:co.cask.cdap.internal.app.services.ProgramLifecycleServiceTest.java
@Test public void testInvalidFlowRunRecord() throws Exception { // Create App with Flow and the deploy HttpResponse response = deploy(WordCountApp.class, Constants.Gateway.API_VERSION_3_TOKEN, TEST_NAMESPACE1); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); final Id.Program wordcountFlow1 = Id.Program.from(TEST_NAMESPACE1, "WordCountApp", ProgramType.FLOW, "WordCountFlow"); // flow is stopped initially Assert.assertEquals("STOPPED", getProgramStatus(wordcountFlow1)); // start a flow and check the status startProgram(wordcountFlow1);//from w w w . jav a2 s . c om waitState(wordcountFlow1, ProgramRunStatus.RUNNING.toString()); // Wait until we have a run record Tasks.waitFor(1, new Callable<Integer>() { @Override public Integer call() throws Exception { return getProgramRuns(wordcountFlow1, ProgramRunStatus.RUNNING.toString()).size(); } }, 5, TimeUnit.SECONDS); // Get the RunRecord List<RunRecord> runRecords = getProgramRuns(wordcountFlow1, ProgramRunStatus.RUNNING.toString()); Assert.assertEquals(1, runRecords.size()); RunRecord rr = runRecords.get(0); // Check the RunRecords status Assert.assertEquals(ProgramRunStatus.RUNNING, rr.getStatus()); // Lets set the runtime info to off RuntimeInfo runtimeInfo = runtimeService.lookup(wordcountFlow1, RunIds.fromString(rr.getPid())); ProgramController programController = runtimeInfo.getController(); programController.stop(); Thread.sleep(2000); // Verify that the status of that run is KILLED RunRecordMeta runRecordMeta = store.getRun(wordcountFlow1, rr.getPid()); Assert.assertEquals(ProgramRunStatus.KILLED, runRecordMeta.getStatus()); // Use the store manipulate state to be RUNNING long now = System.currentTimeMillis(); long nowSecs = TimeUnit.MILLISECONDS.toSeconds(now); store.setStart(wordcountFlow1, rr.getPid(), nowSecs); // Now check again via Store to assume data store is wrong. runRecordMeta = store.getRun(wordcountFlow1, rr.getPid()); Assert.assertEquals(ProgramRunStatus.RUNNING, runRecordMeta.getStatus()); // Verify there is NO FAILED run record for the application runRecords = getProgramRuns(wordcountFlow1, ProgramRunStatus.FAILED.toString()); Assert.assertEquals(0, runRecords.size()); // Lets fix it Set<String> processedInvalidRunRecordIds = Sets.newHashSet(); programLifecycleService.validateAndCorrectRunningRunRecords(ProgramType.FLOW, processedInvalidRunRecordIds); // Verify there is one FAILED run record for the application runRecords = getProgramRuns(wordcountFlow1, ProgramRunStatus.FAILED.toString()); Assert.assertEquals(1, runRecords.size()); rr = runRecords.get(0); Assert.assertEquals(ProgramRunStatus.FAILED, rr.getStatus()); }
From source file:com.norman0406.slimgress.API.Interface.Interface.java
public AuthSuccess authenticate(final String token) { FutureTask<AuthSuccess> future = new FutureTask<AuthSuccess>(new Callable<AuthSuccess>() { @Override//from ww w . j a v a 2s . c om public AuthSuccess call() throws Exception { // see http://blog.notdot.net/2010/05/Authenticating-against-App-Engine-from-an-Android-app // also use ?continue= (?) String login = mApiBaseURL + mApiLogin + token; HttpGet get = new HttpGet(login); try { HttpResponse response = null; synchronized (Interface.this) { mClient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false); Log.i("Interface", "executing authentication"); response = mClient.execute(get); } assert (response != null); @SuppressWarnings("unused") String content = EntityUtils.toString(response.getEntity()); response.getEntity().consumeContent(); if (response.getStatusLine().getStatusCode() == 401) { // the token has expired Log.i("Interface", "401: authentication token has expired"); return AuthSuccess.TokenExpired; } else if (response.getStatusLine().getStatusCode() != 302) { // Response should be a redirect Log.i("Interface", "unknown error: " + response.getStatusLine().getReasonPhrase()); return AuthSuccess.UnknownError; } else { // get cookie synchronized (Interface.this) { for (Cookie cookie : mClient.getCookieStore().getCookies()) { if (cookie.getName().equals("SACSID")) { // secure cookie! (ACSID is non-secure http cookie) mCookie = cookie.getValue(); } } } if (mCookie == null) { Log.i("Interface", "authentication token has expired"); return AuthSuccess.TokenExpired; } Log.i("Interface", "authentication successful"); return AuthSuccess.Successful; } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { synchronized (Interface.this) { mClient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true); } } return AuthSuccess.Successful; } }); // start thread new Thread(future).start(); // obtain authentication return value AuthSuccess retVal = AuthSuccess.UnknownError; try { retVal = future.get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return retVal; }
From source file:com.microsoft.azure.management.network.UsageOperationsImpl.java
/** * Lists compute usages for a subscription. * * @param location Required. The location upon which resource usage is * queried.//from w ww . ja v a2 s . c o m * @return The List Usages operation response. */ @Override public Future<UsagesListResponse> listAsync(final String location) { return this.getClient().getExecutorService().submit(new Callable<UsagesListResponse>() { @Override public UsagesListResponse call() throws Exception { return list(location); } }); }
From source file:com.aol.advertising.qiao.injector.RandomIntegerDataSource.java
protected void _registerStatsCollector() { if (statsCollector != null) statsCollector.register(new Callable<Void>() { @Override/*from w ww .j a v a 2 s . c o m*/ public Void call() { if (numGenerated.get() > 0) eventPublisher.publishEvent(new StatsEvent(this, this.getClass().getSimpleName(), funnelId, StatsOp.INCRBY, "random_input", numGenerated.getAndSet(0))); return null; } }); }