List of usage examples for java.util.concurrent Callable Callable
Callable
From source file:com.wavemaker.app.build.maven.plugin.handler.VariableServiceDefGenerationHandler.java
private void buildServiceDefsForAllServices(final Folder servicesFolder) { if (servicesFolder.exists()) { List<Folder> serviceFolders = servicesFolder.list().folders().fetchAll(); if (serviceFolders.size() > 0) { for (final Folder serviceFolder : serviceFolders) { serviceVsServiceDefs.put(serviceFolder.getName(), executorService.submit(new Callable<Map<String, ServiceDefinition>>() { @Override public Map<String, ServiceDefinition> call() throws Exception { return buildServiceDefs(serviceFolder); }// w w w. jav a 2s . co m })); } } for (String service : serviceVsServiceDefs.keySet()) { handleFutureIfException(serviceVsServiceDefs.get(service)); } } }
From source file:net.malisis.advert.advert.ServerAdvert.java
@Override protected void downloadFile() { if (checkOldFile()) return;/* w w w . ja v a 2s . com*/ if (task != null && !task.isDone()) return; task = threadPool.submit(new Callable<Void>() { @Override public Void call() throws Exception { byte[] img = null; try { img = Resources.toByteArray(new URL(url)); } catch (Exception e) { setError(e.getMessage()); MalisisAdvert.log.error(e); } writeFile(img); writeListing(); sendImageData(); return null; } }); }
From source file:org.waveprotocol.box.server.waveserver.SolrWaveIndexerImpl.java
@Override public ListenableFuture<Void> onWaveInit(final WaveletName waveletName) { ListenableFutureTask<Void> task = ListenableFutureTask.create(new Callable<Void>() { @Override/*from ww w. jav a2 s .com*/ public Void call() throws Exception { ReadableWaveletData waveletData; try { waveletData = waveletDataProvider.getReadableWaveletData(waveletName); updateIndex(waveletData); } catch (WaveServerException e) { LOG.log(Level.SEVERE, "Failed to initialize index for " + waveletName, e); throw e; } return null; } }); executor.execute(task); return task; }
From source file:no.uis.fsws.proxy.StudinfoProxyImpl.java
@Override @SneakyThrows/* ww w.j av a 2s. c o m*/ public List<Emne> getEmnerForOrgenhet(final XMLGregorianCalendar arstall, final Terminkode terminkode, final Sprakkode sprak, final int institusjonsnr, final Integer fakultetsnr, final Integer instituttnr, final Integer gruppenr) { final StudInfoImport svc = getServiceForPrincipal(); Future<List<Emne>> future = executor.submit(new Callable<List<Emne>>() { @Override public List<Emne> call() throws Exception { final FsStudieinfo sinfo = svc.fetchSubjects(institusjonsnr, fakultetsnr == null ? -1 : fakultetsnr.intValue(), arstall.getYear(), terminkode.toString(), sprak.toString()); return sinfo.getEmne(); } }); return future.get(timeoutMinutes, TimeUnit.MINUTES); }
From source file:com.netflix.curator.framework.recipes.cache.TestNodeCache.java
@Test public void testRebuildAgainstOtherProcesses() throws Exception { NodeCache cache = null;//from w w w .j ava 2 s .co m final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { client.create().forPath("/test"); client.create().forPath("/test/snafu", "original".getBytes()); final CountDownLatch latch = new CountDownLatch(1); cache = new NodeCache(client, "/test/snafu"); cache.getListenable().addListener(new NodeCacheListener() { @Override public void nodeChanged() throws Exception { latch.countDown(); } }); cache.rebuildTestExchanger = new Exchanger<Object>(); ExecutorService service = Executors.newSingleThreadExecutor(); final NodeCache finalCache = cache; Future<Object> future = service.submit(new Callable<Object>() { @Override public Object call() throws Exception { finalCache.rebuildTestExchanger.exchange(new Object(), 10, TimeUnit.SECONDS); // simulate another process updating the node while we're rebuilding client.setData().forPath("/test/snafu", "other".getBytes()); ChildData currentData = finalCache.getCurrentData(); Assert.assertNotNull(currentData); finalCache.rebuildTestExchanger.exchange(new Object(), 10, TimeUnit.SECONDS); return null; } }); cache.start(false); future.get(); Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); Assert.assertNotNull(cache.getCurrentData()); Assert.assertEquals(cache.getCurrentData().getData(), "other".getBytes()); } finally { IOUtils.closeQuietly(cache); IOUtils.closeQuietly(client); } }
From source file:net.i2cat.netconf.messageQueue.MessageQueue.java
/** * Wait for a new message with the id <code>messageId</code> to arrive in the queue. * * @param messageId a string identifying the message to consume. * @param timeout a long indicating the length of the timeout in milliseconds. If zero or less, no timeout. * @throws Exception an UncheckedTimeoutException if there is no message with <code>messageId</code> after waiting for the specified timeout. * @return//ww w. j av a 2s .com */ public RPCElement blockingConsumeById(String messageId, long timeout) throws Exception { final String messageIdFinal = messageId; Callable<RPCElement> consumeCaller = new Callable<RPCElement>() { public RPCElement call() throws Exception { RPCElement element; synchronized (queue) { while ((element = consumeById(messageIdFinal)) == null) { try { log.debug("Waiting (" + messageIdFinal + ")..."); queue.wait(); } catch (InterruptedException e) { // Do nothing. It's probably a timeout. } } } return element; } }; if (timeout <= 0) { return consumeCaller.call(); } SimpleTimeLimiter timeLimiter = new SimpleTimeLimiter(); try { return timeLimiter.callWithTimeout(consumeCaller, timeout, TimeUnit.MILLISECONDS, true); } catch (UncheckedTimeoutException e) { log.debug("BlockingConsumeById(messageId=" + messageId + ") failed due to timeout.", e); throw e; } catch (Exception e) { log.debug("BlockingConsumeById(messageId=" + messageId + ") failed.", e); throw e; } }
From source file:net.bhira.sample.api.controller.CompanyController.java
/** * Fetch the instance of {@link net.bhira.sample.model.Company} represented by given companyId * and return it as JSON object./*from w w w .ja v a 2 s .com*/ * * @param companyId * the ID for {@link net.bhira.sample.model.Company}. * @param response * the http response to which the results will be written. * @return an instance of {@link net.bhira.sample.model.Company} as JSON. */ @RequestMapping(value = "/company/{companyId}", method = RequestMethod.GET) @ResponseBody public Callable<String> getCompany(@PathVariable long companyId, HttpServletResponse response) { return new Callable<String>() { public String call() throws Exception { String body = ""; try { LOG.debug("servicing GET company/{}", companyId); Company company = companyService.load(companyId); LOG.debug("GET company/{}, found = {}", companyId, company != null); if (company == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } else { body = JsonUtil.createGson().toJson(company); } } catch (Exception ex) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); body = ex.getLocalizedMessage(); LOG.warn("Error loading company/{}. {}", companyId, body); LOG.debug("Load error stacktrace: ", ex); } return body; } }; }
From source file:com.graphhopper.jsprit.analysis.toolbox.ConcurrentBenchmarker.java
public void run() { System.out.println("start benchmarking [nuOfInstances=" + benchmarkInstances.size() + "][runsPerInstance=" + runs + "]"); double startTime = System.currentTimeMillis(); ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 1); List<Future<BenchmarkResult>> futures = new ArrayList<Future<BenchmarkResult>>(); for (final BenchmarkInstance p : benchmarkInstances) { Future<BenchmarkResult> futureResult = executor.submit(new Callable<BenchmarkResult>() { @Override/*ww w. ja va 2 s .co m*/ public BenchmarkResult call() throws Exception { return runAlgoAndGetResult(p); } }); futures.add(futureResult); } try { int count = 1; for (Future<BenchmarkResult> f : futures) { BenchmarkResult r = f.get(); print(r, count); results.add(f.get()); count++; } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } executor.shutdown(); print(results); System.out.println("done [time=" + (System.currentTimeMillis() - startTime) / 1000 + "sec]"); }
From source file:com.cloudera.alfredo.server.TestKerberosAuthenticationHandler.java
public void testRequestWithAuthorization() throws Exception { String token = KerberosTestUtils.doAsClient(new Callable<String>() { @Override/*from w ww . ja v a 2 s . c om*/ public String call() throws Exception { GSSManager gssManager = GSSManager.getInstance(); GSSContext gssContext = null; try { String servicePrincipal = KerberosTestUtils.getServerPrincipal(); GSSName serviceName = gssManager.createName(servicePrincipal, GSSUtil.NT_GSS_KRB5_PRINCIPAL); gssContext = gssManager.createContext(serviceName, GSSUtil.GSS_KRB5_MECH_OID, null, GSSContext.DEFAULT_LIFETIME); gssContext.requestCredDeleg(true); gssContext.requestMutualAuth(true); byte[] inToken = new byte[0]; byte[] outToken = gssContext.initSecContext(inToken, 0, inToken.length); Base64 base64 = new Base64(0); return base64.encodeToString(outToken); } finally { if (gssContext != null) { gssContext.dispose(); } } } }); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); Mockito.when(request.getHeader(KerberosAuthenticator.AUTHORIZATION)) .thenReturn(KerberosAuthenticator.NEGOTIATE + " " + token); AuthenticationToken authToken = handler.authenticate(request, response); if (authToken != null) { Mockito.verify(response).setHeader(Mockito.eq(KerberosAuthenticator.WWW_AUTHENTICATE), Mockito.matches(KerberosAuthenticator.NEGOTIATE + " .*")); Mockito.verify(response).setStatus(HttpServletResponse.SC_OK); assertEquals(KerberosTestUtils.getClientPrincipal(), authToken.getName()); assertTrue(KerberosTestUtils.getClientPrincipal().startsWith(authToken.getUserName())); assertEquals(KerberosAuthenticationHandler.TYPE, authToken.getType()); } else { Mockito.verify(response).setHeader(Mockito.eq(KerberosAuthenticator.WWW_AUTHENTICATE), Mockito.matches(KerberosAuthenticator.NEGOTIATE + " .*")); Mockito.verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } }
From source file:com.link_intersystems.lang.ContextAwareTest.java
@Test(expected = IOException.class) public void callable() throws Exception { final TestContextAware contextAware = new TestContextAware(); try {/* w w w .ja v a2s .co m*/ contextAware.runInContext(new Callable<String>() { public String call() throws Exception { assertTrue(contextAware.isActivated()); throw new IOException(); } }); } catch (Exception e) { throw e; } assertFalse(contextAware.isActivated()); }