List of usage examples for java.util.concurrent Callable call
V call() throws Exception;
From source file:org.strongswan.android.logic.VpnStateService.java
/** * Update state and notify all listeners about the change. By using a Handler * this is done from the main UI thread and not the initial reporter thread. * Also, in doing the actual state change from the main thread, listeners * see all changes and none are skipped. * * @param change the state update to perform before notifying listeners, returns true if state changed *//*w ww.j ava 2 s . co m*/ private void notifyListeners(final Callable<Boolean> change) { mHandler.post(new Runnable() { @Override public void run() { try { if (change.call()) { /* otherwise there is no need to notify the listeners */ for (VpnStateListener listener : mListeners) { listener.stateChanged(); } } } catch (Exception e) { e.printStackTrace(); } } }); }
From source file:org.pentaho.platform.engine.security.SecurityHelper.java
@Override public <T> T runAsUser(final String principalName, final IParameterProvider paramProvider, final Callable<T> callable) throws Exception { IPentahoSession origSession = PentahoSessionHolder.getSession(); SecurityContext originalContext = SecurityContextHolder.getContext(); try {//w ww. j a v a 2 s. c o m becomeUser(principalName); return callable.call(); } finally { IPentahoSession sessionToDestroy = PentahoSessionHolder.getSession(); if (sessionToDestroy != null && sessionToDestroy != origSession) { try { sessionToDestroy.destroy(); } catch (Exception e) { e.printStackTrace(); } } PentahoSessionHolder.setSession(origSession); SecurityContextHolder.setContext(originalContext); } }
From source file:org.springframework.cloud.stream.binder.kafka.provisioning.KafkaTopicProvisioner.java
public Collection<PartitionInfo> getPartitionsForTopic(final int partitionCount, final boolean tolerateLowerPartitionsOnBroker, final Callable<Collection<PartitionInfo>> callable) { try {/*from w w w .ja v a2 s.c om*/ return this.metadataRetryOperations.execute(new RetryCallback<Collection<PartitionInfo>, Exception>() { @Override public Collection<PartitionInfo> doWithRetry(RetryContext context) throws Exception { Collection<PartitionInfo> partitions = callable.call(); // do a sanity check on the partition set int partitionSize = partitions.size(); if (partitionSize < partitionCount) { if (tolerateLowerPartitionsOnBroker) { logger.warn("The number of expected partitions was: " + partitionCount + ", but " + partitionSize + (partitionSize > 1 ? " have " : " has ") + "been found instead." + "There will be " + (partitionCount - partitionSize) + " idle consumers"); } else { throw new IllegalStateException("The number of expected partitions was: " + partitionCount + ", but " + partitionSize + (partitionSize > 1 ? " have " : " has ") + "been found instead"); } } return partitions; } }); } catch (Exception e) { this.logger.error("Cannot initialize Binder", e); throw new BinderException("Cannot initialize binder:", e); } }
From source file:gda.device.detector.NXDetectorAreaDetectorIntegrationTest.java
@SuppressWarnings("unchecked") @Test/*from w ww . j av a2 s. c om*/ public void testGetPositionCallableTwoPluginsReturningInChunks() throws Exception { // TODO: Two next enableReadAcquisitionTimeAndPeriod(false, false); provAdDet().setAdditionalPluginList( asList((NXPluginBase) adDetectorPlugin1, (NXPluginBase) adDetectorPlugin2)); enableAdditionalPlugins(true, true); Vector<NXDetectorDataAppender> dataAppenders1 = new Vector<NXDetectorDataAppender>(); dataAppenders1 .add(new NXDetectorDataDoubleAppender(Arrays.asList(PLUGIN1_NAMES), Arrays.asList(0., 1., 2.))); dataAppenders1 .add(new NXDetectorDataDoubleAppender(Arrays.asList(PLUGIN1_NAMES), Arrays.asList(10., 11., 12.))); dataAppenders1 .add(new NXDetectorDataDoubleAppender(Arrays.asList(PLUGIN1_NAMES), Arrays.asList(20., 21., 22.))); dataAppenders1 .add(new NXDetectorDataDoubleAppender(Arrays.asList(PLUGIN1_NAMES), Arrays.asList(30., 31., 32.))); when(adDetectorPlugin1.read(anyInt())).thenReturn(dataAppenders1); Vector<NXDetectorDataAppender> dataAppenders2 = new Vector<NXDetectorDataAppender>(); dataAppenders2.add(new NXDetectorDataDoubleAppender(Arrays.asList(PLUGIN2_NAMES), Arrays.asList(3., 4.))); dataAppenders2.add(new NXDetectorDataDoubleAppender(Arrays.asList(PLUGIN2_NAMES), Arrays.asList(13., 14.))); dataAppenders2.add(new NXDetectorDataDoubleAppender(Arrays.asList(PLUGIN2_NAMES), Arrays.asList(23., 24.))); dataAppenders2.add(new NXDetectorDataDoubleAppender(Arrays.asList(PLUGIN2_NAMES), Arrays.asList(33., 34.))); when(adDetectorPlugin2.read(anyInt())).thenReturn(dataAppenders2); det().atScanStart(); Callable<NXDetectorData> readout0 = (Callable<NXDetectorData>) (Callable<?>) provAdDet() .getPositionCallable(); assertArrayEquals(new Double[] { 0., 1., 2., 3., 4. }, readout0.call().getDoubleVals()); Callable<NXDetectorData> readout1 = (Callable<NXDetectorData>) (Callable<?>) provAdDet() .getPositionCallable(); Callable<NXDetectorData> readout2 = (Callable<NXDetectorData>) (Callable<?>) provAdDet() .getPositionCallable(); assertArrayEquals(new Double[] { 10., 11., 12., 13., 14. }, readout1.call().getDoubleVals()); assertArrayEquals(new Double[] { 20., 21., 22., 23., 24. }, readout2.call().getDoubleVals()); Callable<NXDetectorData> readout3 = (Callable<NXDetectorData>) (Callable<?>) provAdDet() .getPositionCallable(); assertArrayEquals(new Double[] { 30., 31., 32., 33., 34. }, readout3.call().getDoubleVals()); }
From source file:org.mule.module.blink1.Blink1Module.java
private void runOnBlink(final int deviceId, final Callable<Integer> action) { final int openResult = blink1.openById(deviceId); if (openResult == FAILED) { throw new MuleRuntimeException( MessageFactory.createStaticMessage("Failed to open blink(1) device ID: " + deviceId)); }/*w ww . java 2 s . c om*/ try { final int actionResult = action.call(); if (actionResult == FAILED) { throw new MuleRuntimeException(MessageFactory .createStaticMessage("Failed to execute action on blink(1) device ID: " + deviceId)); } } catch (final Exception e) { throw new MuleRuntimeException(MessageFactory .createStaticMessage("Failed to execute action on blink(1) device ID: " + deviceId), e); } finally { blink1.close(); } }
From source file:bear.main.FXConf.java
public <V> Future<V> evaluateInFX(final Callable<V> callable) { final SettableFuture<V> future = new SettableFuture<V>(); bearFX.bearFXApp.runLater(new Runnable() { @Override/*from w w w .j a v a 2 s. c o m*/ public void run() { try { future.set(callable.call()); } catch (Exception e) { future.setException(e); } } }); return future; }
From source file:com.palantir.stash.stashbot.managers.JenkinsManager.java
public void updateRepo(Repository repo) { try {/*from w w w.j a v a 2s. c om*/ Callable<Void> visit = new UpdateAllRepositoryVisitor(jenkinsClientManager, jtm, cpm, repo, lf); visit.call(); } catch (Exception e) { log.error("Exception while attempting to create missing jobs for a repo: ", e); } }
From source file:com.amazonaws.services.kinesis.leases.impl.LeaseTaker.java
/** * Scan all leases and update lastRenewalTime. Add new leases and delete old leases. * /*w w w .j a v a2 s . c o m*/ * @param timeProvider callable that supplies the current time * * @return list of expired leases, possibly empty, never null. * * @throws ProvisionedThroughputException if listLeases fails due to lack of provisioned throughput * @throws InvalidStateException if the lease table does not exist * @throws DependencyException if listLeases fails in an unexpected way */ private void updateAllLeases(Callable<Long> timeProvider) throws DependencyException, InvalidStateException, ProvisionedThroughputException { List<T> freshList = leaseManager.listLeases(); try { lastScanTimeNanos = timeProvider.call(); } catch (Exception e) { throw new DependencyException("Exception caught from timeProvider", e); } // This set will hold the lease keys not updated by the previous listLeases call. Set<String> notUpdated = new HashSet<String>(allLeases.keySet()); // Iterate over all leases, finding ones to try to acquire that haven't changed since the last iteration for (T lease : freshList) { String leaseKey = lease.getLeaseKey(); T oldLease = allLeases.get(leaseKey); allLeases.put(leaseKey, lease); notUpdated.remove(leaseKey); if (oldLease != null) { // If we've seen this lease before... if (oldLease.getLeaseCounter().equals(lease.getLeaseCounter())) { // ...and the counter hasn't changed, propagate the lastRenewalNanos time from the old lease lease.setLastCounterIncrementNanos(oldLease.getLastCounterIncrementNanos()); } else { // ...and the counter has changed, set lastRenewalNanos to the time of the scan. lease.setLastCounterIncrementNanos(lastScanTimeNanos); } } else { if (lease.getLeaseOwner() == null) { // if this new lease is unowned, it's never been renewed. lease.setLastCounterIncrementNanos(0L); if (LOG.isDebugEnabled()) { LOG.debug("Treating new lease with key " + leaseKey + " as never renewed because it is new and unowned."); } } else { // if this new lease is owned, treat it as renewed as of the scan lease.setLastCounterIncrementNanos(lastScanTimeNanos); if (LOG.isDebugEnabled()) { LOG.debug("Treating new lease with key " + leaseKey + " as recently renewed because it is new and owned."); } } } } // Remove dead leases from allLeases for (String key : notUpdated) { allLeases.remove(key); } }
From source file:org.apache.oozie.client.OozieClient.java
/** * Allows to impersonate other users in the Oozie server. The current user * must be configured as a proxyuser in Oozie. * <p/>/*from www . j a v a 2s . com*/ * IMPORTANT: impersonation happens only with Oozie client requests done within * doAs() calls. * * @param userName user to impersonate. * @param callable callable with {@link org.apache.oozie.client.OozieClient} calls impersonating the specified user. * @return any response returned by the {@link java.util.concurrent.Callable#call()} method. * @throws Exception thrown by the {@link java.util.concurrent.Callable#call()} method. */ public static <T> T doAs(String userName, Callable<T> callable) throws Exception { notEmpty(userName, "userName"); notNull(callable, "callable"); try { USER_NAME_TL.set(userName); return callable.call(); } finally { USER_NAME_TL.remove(); } }
From source file:com.eucalyptus.objectstorage.pipeline.handlers.ObjectStorageAuthenticationHandler.java
@Override public void handleUpstream(final ChannelHandlerContext ctx, final ChannelEvent channelEvent) throws Exception { if (channelEvent instanceof MessageEvent) { try {/*from www . j a va 2 s . co m*/ final MessageEvent msgEvent = (MessageEvent) channelEvent; Callable<Long> stat = Statistics.startUpstream(ctx.getChannel(), this); this.incomingMessage(ctx, msgEvent); stat.call(); ctx.sendUpstream(channelEvent); } catch (Throwable e) { Channels.fireExceptionCaught(ctx, e); } } else { ctx.sendUpstream(channelEvent); } }