List of usage examples for java.util.concurrent Callable call
V call() throws Exception;
From source file:org.codice.ddf.catalog.ui.query.monitor.impl.WorkspaceQueryServiceTest.java
@SuppressWarnings("unchecked") @Test/*from w ww. jav a2 s .c om*/ public void testRun() throws SchedulerException, UnsupportedQueryException, SourceUnavailableException, FederationException { String workspaceId = "3"; QueryUpdateSubscriber queryUpdateSubscriber = mock(QueryUpdateSubscriber.class); WorkspaceService workspaceService = mock(WorkspaceService.class); CatalogFramework catalogFramework = mock(CatalogFramework.class); FilterBuilder filterBuilder = mock(FilterBuilder.class); Scheduler scheduler = mock(Scheduler.class); when(scheduler.getContext()).thenReturn(mock(SchedulerContext.class)); Supplier<Optional<Scheduler>> schedulerSupplier = () -> Optional.of(scheduler); SecurityService securityService = new SecurityService() { @Override public Subject getSystemSubject() { return mock(Subject.class); } @Override public Map<String, Serializable> addSystemSubject(Map<String, Serializable> properties) { return properties; } }; FilterService filterService = mock(FilterService.class); when(filterService.getModifiedDateFilter(any())).thenReturn(mock(Filter.class)); when(filterBuilder.anyOf(Mockito.any(Filter.class))).thenReturn(mock(Or.class)); when(filterBuilder.allOf(Mockito.<Filter>anyVararg())).thenReturn(mock(And.class)); WorkspaceQueryServiceImpl workspaceQueryServiceImpl = new WorkspaceQueryServiceImpl(queryUpdateSubscriber, workspaceService, catalogFramework, filterBuilder, schedulerSupplier, securityService, filterService); workspaceQueryServiceImpl.setQueryTimeInterval(60); String ecql = "area( Polygon((10 10, 20 10, 20 20, 10 10)) ) BETWEEN 10000 AND 30000"; WorkspaceMetacardImpl workspaceMetacard = mock(WorkspaceMetacardImpl.class); when(workspaceMetacard.getId()).thenReturn(workspaceId); QueryMetacardImpl queryMetacardWithSource = mock(QueryMetacardImpl.class); when(queryMetacardWithSource.getSources()).thenReturn(Collections.singletonList("SomeSource")); when(queryMetacardWithSource.getCql()).thenReturn(ecql); Attribute id1 = mock(Attribute.class); when(id1.getValue()).thenReturn("1"); when(queryMetacardWithSource.getAttribute(Metacard.ID)).thenReturn(id1); QueryMetacardImpl queryMetacardWithoutSource = mock(QueryMetacardImpl.class); when(queryMetacardWithoutSource.getSources()).thenReturn(Collections.emptyList()); when(queryMetacardWithoutSource.getCql()).thenReturn(ecql); Attribute id2 = mock(Attribute.class); when(id2.getValue()).thenReturn("2"); when(queryMetacardWithoutSource.getAttribute(Metacard.ID)).thenReturn(id2); Map<String, Pair<WorkspaceMetacardImpl, List<QueryMetacardImpl>>> queryMetacards = Collections .singletonMap(id2.getValue().toString(), new ImmutablePair<>(workspaceMetacard, Arrays.asList(queryMetacardWithSource, queryMetacardWithoutSource))); when(workspaceService.getQueryMetacards()).thenReturn(queryMetacards); long hitCount1 = 10; long hitCount2 = 20; QueryResponse queryResponse = mock(QueryResponse.class); when(queryResponse.getHits()).thenReturn(hitCount1).thenReturn(hitCount2); when(catalogFramework.query(any())).thenReturn(queryResponse); workspaceQueryServiceImpl.setSubject(new Subject() { @Override public String getName() { return ""; } @Override public boolean isGuest() { return false; } @Override public Object getPrincipal() { return null; } @Override public PrincipalCollection getPrincipals() { return null; } @Override public boolean isPermitted(String s) { return false; } @Override public boolean isPermitted(Permission permission) { return false; } @Override public boolean[] isPermitted(String... strings) { return new boolean[0]; } @Override public boolean[] isPermitted(List<Permission> list) { return new boolean[0]; } @Override public boolean isPermittedAll(String... strings) { return false; } @Override public boolean isPermittedAll(Collection<Permission> collection) { return false; } @Override public void checkPermission(String s) throws AuthorizationException { } @Override public void checkPermission(Permission permission) throws AuthorizationException { } @Override public void checkPermissions(String... strings) throws AuthorizationException { } @Override public void checkPermissions(Collection<Permission> collection) throws AuthorizationException { } @Override public boolean hasRole(String s) { return false; } @Override public boolean[] hasRoles(List<String> list) { return new boolean[0]; } @Override public boolean hasAllRoles(Collection<String> collection) { return false; } @Override public void checkRole(String s) throws AuthorizationException { } @Override public void checkRoles(Collection<String> collection) throws AuthorizationException { } @Override public void checkRoles(String... strings) throws AuthorizationException { } @Override public void login(AuthenticationToken authenticationToken) throws AuthenticationException { } @Override public boolean isAuthenticated() { return false; } @Override public boolean isRemembered() { return false; } @Override public Session getSession() { return null; } @Override public Session getSession(boolean b) { return null; } @Override public void logout() { } @Override public <V> V execute(Callable<V> callable) throws ExecutionException { try { return callable.call(); } catch (Exception e) { throw new ExecutionException(e); } } @Override public void execute(Runnable runnable) { } @Override public <V> Callable<V> associateWith(Callable<V> callable) { return null; } @Override public Runnable associateWith(Runnable runnable) { return null; } @Override public void runAs(PrincipalCollection principalCollection) throws NullPointerException, IllegalStateException { } @Override public boolean isRunAs() { return false; } @Override public PrincipalCollection getPreviousPrincipals() { return null; } @Override public PrincipalCollection releaseRunAs() { return null; } }); workspaceQueryServiceImpl.setCronString("0 0 0 * * ?"); workspaceQueryServiceImpl.setQueryTimeoutMinutes(5L); workspaceQueryServiceImpl.run(); ArgumentCaptor<Map> argumentCaptor = ArgumentCaptor.forClass(Map.class); verify(queryUpdateSubscriber).notify(argumentCaptor.capture()); Map queryUpdateSubscriberArgumentRaw = argumentCaptor.getValue(); Map<String, Pair<WorkspaceMetacardImpl, Long>> queryUpdateSubscriberArgument = (Map<String, Pair<WorkspaceMetacardImpl, Long>>) queryUpdateSubscriberArgumentRaw; assertThat(queryUpdateSubscriberArgument.get(workspaceId).getRight(), is(hitCount1 + hitCount2)); }
From source file:android.arch.persistence.room.RoomDatabase.java
/** * Executes the specified {@link Callable} in a database transaction. The transaction will be * marked as successful unless an exception is thrown in the {@link Callable}. * * @param body The piece of code to execute. * @param <V> The type of the return value. * @return The value returned from the {@link Callable}. *//* w w w. j a v a2s . co m*/ public <V> V runInTransaction(Callable<V> body) { beginTransaction(); try { V result = body.call(); setTransactionSuccessful(); return result; } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException("Exception in transaction", e); } finally { endTransaction(); } }
From source file:org.codice.ddf.catalog.ui.query.monitor.impl.TestWorkspaceQueryService.java
@SuppressWarnings("unchecked") @Test//from w w w . j a v a 2s . c o m public void testRun() throws SchedulerException, UnsupportedQueryException, SourceUnavailableException, FederationException { String workspaceId = "3"; QueryUpdateSubscriber queryUpdateSubscriber = mock(QueryUpdateSubscriber.class); WorkspaceService workspaceService = mock(WorkspaceService.class); CatalogFramework catalogFramework = mock(CatalogFramework.class); FilterBuilder filterBuilder = mock(FilterBuilder.class); Supplier<Optional<Scheduler>> schedulerSupplier = Optional::empty; Supplier<Trigger> triggerSupplier = () -> null; SecurityService securityService = new SecurityService() { @Override public Subject getSystemSubject() { return mock(Subject.class); } @Override public Map<String, Serializable> addSystemSubject(Map<String, Serializable> properties) { return properties; } }; FilterService filterService = mock(FilterService.class); when(filterService.getModifiedDateFilter(any())).thenReturn(mock(Filter.class)); when(filterBuilder.anyOf(Mockito.any(Filter.class))).thenReturn(mock(Or.class)); when(filterBuilder.allOf(Mockito.<Filter>anyVararg())).thenReturn(mock(And.class)); WorkspaceQueryService workspaceQueryService = new WorkspaceQueryService(queryUpdateSubscriber, workspaceService, catalogFramework, filterBuilder, schedulerSupplier, securityService, filterService); String ecql = "area( Polygon((10 10, 20 10, 20 20, 10 10)) ) BETWEEN 10000 AND 30000"; WorkspaceMetacardImpl workspaceMetacard = mock(WorkspaceMetacardImpl.class); when(workspaceMetacard.getId()).thenReturn(workspaceId); QueryMetacardImpl queryMetacardWithSource = mock(QueryMetacardImpl.class); when(queryMetacardWithSource.getSources()).thenReturn(Collections.singletonList("SomeSource")); when(queryMetacardWithSource.getCql()).thenReturn(ecql); Attribute id1 = mock(Attribute.class); when(id1.getValue()).thenReturn("1"); when(queryMetacardWithSource.getAttribute(Metacard.ID)).thenReturn(id1); QueryMetacardImpl queryMetacardWithoutSource = mock(QueryMetacardImpl.class); when(queryMetacardWithoutSource.getSources()).thenReturn(Collections.emptyList()); when(queryMetacardWithoutSource.getCql()).thenReturn(ecql); Attribute id2 = mock(Attribute.class); when(id2.getValue()).thenReturn("2"); when(queryMetacardWithoutSource.getAttribute(Metacard.ID)).thenReturn(id2); Map<String, Pair<WorkspaceMetacardImpl, List<QueryMetacardImpl>>> queryMetacards = Collections .singletonMap(id2.getValue().toString(), new ImmutablePair<>(workspaceMetacard, Arrays.asList(queryMetacardWithSource, queryMetacardWithoutSource))); when(workspaceService.getQueryMetacards()).thenReturn(queryMetacards); long hitCount1 = 10; long hitCount2 = 20; QueryResponse queryResponse = mock(QueryResponse.class); when(queryResponse.getHits()).thenReturn(hitCount1).thenReturn(hitCount2); when(catalogFramework.query(any())).thenReturn(queryResponse); workspaceQueryService.setSubject(new Subject() { @Override public boolean isGuest() { return false; } @Override public Object getPrincipal() { return null; } @Override public PrincipalCollection getPrincipals() { return null; } @Override public boolean isPermitted(String s) { return false; } @Override public boolean isPermitted(Permission permission) { return false; } @Override public boolean[] isPermitted(String... strings) { return new boolean[0]; } @Override public boolean[] isPermitted(List<Permission> list) { return new boolean[0]; } @Override public boolean isPermittedAll(String... strings) { return false; } @Override public boolean isPermittedAll(Collection<Permission> collection) { return false; } @Override public void checkPermission(String s) throws AuthorizationException { } @Override public void checkPermission(Permission permission) throws AuthorizationException { } @Override public void checkPermissions(String... strings) throws AuthorizationException { } @Override public void checkPermissions(Collection<Permission> collection) throws AuthorizationException { } @Override public boolean hasRole(String s) { return false; } @Override public boolean[] hasRoles(List<String> list) { return new boolean[0]; } @Override public boolean hasAllRoles(Collection<String> collection) { return false; } @Override public void checkRole(String s) throws AuthorizationException { } @Override public void checkRoles(Collection<String> collection) throws AuthorizationException { } @Override public void checkRoles(String... strings) throws AuthorizationException { } @Override public void login(AuthenticationToken authenticationToken) throws AuthenticationException { } @Override public boolean isAuthenticated() { return false; } @Override public boolean isRemembered() { return false; } @Override public Session getSession() { return null; } @Override public Session getSession(boolean b) { return null; } @Override public void logout() { } @Override public <V> V execute(Callable<V> callable) throws ExecutionException { try { return callable.call(); } catch (Exception e) { throw new ExecutionException(e); } } @Override public void execute(Runnable runnable) { } @Override public <V> Callable<V> associateWith(Callable<V> callable) { return null; } @Override public Runnable associateWith(Runnable runnable) { return null; } @Override public void runAs(PrincipalCollection principalCollection) throws NullPointerException, IllegalStateException { } @Override public boolean isRunAs() { return false; } @Override public PrincipalCollection getPreviousPrincipals() { return null; } @Override public PrincipalCollection releaseRunAs() { return null; } }); workspaceQueryService.run(); ArgumentCaptor<Map> argumentCaptor = ArgumentCaptor.forClass(Map.class); verify(queryUpdateSubscriber).notify(argumentCaptor.capture()); Map queryUpdateSubscriberArgumentRaw = argumentCaptor.getValue(); Map<String, Pair<WorkspaceMetacardImpl, Long>> queryUpdateSubscriberArgument = (Map<String, Pair<WorkspaceMetacardImpl, Long>>) queryUpdateSubscriberArgumentRaw; assertThat(queryUpdateSubscriberArgument.get(workspaceId).getRight(), is(hitCount1 + hitCount2)); }
From source file:org.apache.hadoop.security.token.delegation.web.TestWebDelegationToken.java
public static <T> T doAsKerberosUser(String principal, String keytab, final Callable<T> callable) throws Exception { LoginContext loginContext = null; try {//from w w w. ja v a2s .c o m Set<Principal> principals = new HashSet<Principal>(); principals.add(new KerberosPrincipal(principal)); Subject subject = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>()); loginContext = new LoginContext("", subject, null, new KerberosConfiguration(principal, keytab)); loginContext.login(); subject = loginContext.getSubject(); return Subject.doAs(subject, new PrivilegedExceptionAction<T>() { @Override public T run() throws Exception { return callable.call(); } }); } catch (PrivilegedActionException ex) { throw ex.getException(); } finally { if (loginContext != null) { loginContext.logout(); } } }
From source file:org.gss_project.gss.server.ejb.TransactionHelper.java
/** * Execute the supplied command until it completes, ignoring transaction * rollbacks. Try at least TRANSACTION_RETRIES times before giving up, * each time waiting a random amount of time, using an exponential * backoff scheme. See http://en.wikipedia.org/wiki/Exponential_backoff * for the basic idea./* www . j a v a2 s.co m*/ * * @param command the command to execute * @return the value returned by the command * @throws Exception any other exception thrown by the command */ public T tryExecute(final Callable<T> command) throws Exception { T returnValue = null; // Schedule a Future task to call the command after delay milliseconds. int delay = 0; ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); for (int i = 0; i < TRANSACTION_RETRIES; i++) { final int retry = i; ScheduledFuture<T> future = executor.schedule(new Callable<T>() { @Override public T call() throws Exception { return command.call(); } }, delay, TimeUnit.MILLISECONDS); try { returnValue = future.get(); break; } catch (ExecutionException e) { Throwable cause = e.getCause(); if (!(cause instanceof EJBTransactionRolledbackException) || retry == TRANSACTION_RETRIES - 1) { logger.info("Transaction retry #" + (i + 1) + " failed due to " + cause); executor.shutdownNow(); if (cause instanceof Exception) throw (Exception) cause; if (cause instanceof Error) throw (Error) cause; } delay = MIN_TIMEOUT + (int) (MIN_TIMEOUT * Math.random() * (i + 1)); String origCause = cause.getCause() == null ? cause.getClass().getName() : cause.getCause().getClass().getName(); logger.info( "Transaction retry #" + (i + 1) + " scheduled in " + delay + " msec due to " + origCause); } } executor.shutdownNow(); return returnValue; }
From source file:io.druid.server.namespace.cache.NamespaceExtractionCacheManagerExecutorsTest.java
@Before public void setUp() throws IOException { lifecycle = new Lifecycle(); manager = new OnHeapNamespaceExtractionCacheManager(lifecycle, fnCache, new NoopServiceEmitter(), ImmutableMap.<Class<? extends ExtractionNamespace>, ExtractionNamespaceFunctionFactory<?>>of( URIExtractionNamespace.class, new URIExtractionNamespaceFunctionFactory( ImmutableMap.<String, SearchableVersionedDataFinder>of("file", new LocalFileTimestampVersionFinder())))); tmpFile = Files.createTempFile(tmpDir, "druidTestURIExtractionNS", ".dat").toFile(); tmpFile.deleteOnExit();/*from w w w .j a va 2 s . co m*/ final ObjectMapper mapper = new DefaultObjectMapper(); try (OutputStream ostream = new FileOutputStream(tmpFile)) { try (OutputStreamWriter out = new OutputStreamWriter(ostream)) { out.write(mapper.writeValueAsString(ImmutableMap.<String, String>of("foo", "bar"))); } } factory = new URIExtractionNamespaceFunctionFactory(ImmutableMap .<String, SearchableVersionedDataFinder>of("file", new LocalFileTimestampVersionFinder())) { public Callable<String> getCachePopulator(final URIExtractionNamespace extractionNamespace, final String lastVersion, final Map<String, String> cache) { final Callable<String> superCallable = super.getCachePopulator(extractionNamespace, lastVersion, cache); return new Callable<String>() { @Override public String call() throws Exception { superCallable.call(); return String.format("%d", System.currentTimeMillis()); } }; } }; }
From source file:io.neba.core.resourcemodels.caching.RequestScopedResourceModelCacheTest.java
private void request(final Callable<Object> callable) throws Exception { doAnswer(new Answer<Object>() { @Override/*from w w w. j a v a 2s .com*/ public Object answer(InvocationOnMock invocationOnMock) throws Throwable { return callable.call(); } }).when(this.chain).doFilter(eq(this.request), eq(this.response)); this.testee.doFilter(this.request, this.response, this.chain); }
From source file:org.openbase.display.DisplayView.java
private <V> Future<V> runTask(final Callable<V> callable) throws CouldNotPerformException { try {//from ww w . jav a 2 s .c om if (Platform.isFxApplicationThread()) { try { return CompletableFuture.completedFuture(callable.call()); } catch (Exception ex) { ExceptionPrinter.printHistory(new CouldNotPerformException("Could not perform task!", ex), logger); } } FutureTask<V> future = new FutureTask(() -> { try { return callable.call(); } catch (Exception ex) { throw ExceptionPrinter.printHistoryAndReturnThrowable(ex, logger); } }); Platform.runLater(future); return future; } catch (Exception ex) { throw new CouldNotPerformException("Could not perform task!", ex); } }
From source file:org.apache.hadoop.hbase.regionserver.TestScannerHeartbeatMessages.java
/** * Run the test callable when heartbeats are enabled/disabled. We expect all tests to only pass * when heartbeat messages are enabled (otherwise the test is pointless). When heartbeats are * disabled, the test should throw an exception. * @param testCallable//w w w. j a va2s . c om * @throws InterruptedException */ public void testImportanceOfHeartbeats(Callable<Void> testCallable) throws InterruptedException { HeartbeatRPCServices.heartbeatsEnabled = true; try { testCallable.call(); } catch (Exception e) { fail("Heartbeat messages are enabled, exceptions should NOT be thrown. Exception trace:" + ExceptionUtils.getStackTrace(e)); } HeartbeatRPCServices.heartbeatsEnabled = false; try { testCallable.call(); } catch (Exception e) { return; } finally { HeartbeatRPCServices.heartbeatsEnabled = true; } fail("Heartbeats messages are disabled, an exception should be thrown. If an exception " + " is not thrown, the test case is not testing the importance of heartbeat messages"); }
From source file:com.ignorelist.kassandra.steam.scraper.FileCache.java
@Override public InputStream get(String key, Callable<? extends InputStream> valueLoader) throws ExecutionException { InputStream inputStream = getIfPresent(key); if (null != inputStream) { return inputStream; }//from w w w.jav a 2s . c o m final Lock writeLock = stripedLock.get(key).writeLock(); writeLock.lock(); try { inputStream = getIfPresentNonBlocking(key); if (null != inputStream) { return inputStream; } try { inputStream = valueLoader.call(); try { putNonBlocking(key, inputStream); return getIfPresentNonBlocking(key); } catch (IOException ex) { Logger.getLogger(FileCache.class.getName()).log(Level.SEVERE, "failed to write cache file", ex); throw new ExecutionException("failed to load " + key, ex); } } catch (Exception e) { Logger.getLogger(FileCache.class.getName()).log(Level.SEVERE, null, e); throw new ExecutionException(e); } } finally { writeLock.unlock(); } }