Example usage for java.util.concurrent Callable Callable

List of usage examples for java.util.concurrent Callable Callable

Introduction

In this page you can find the example usage for java.util.concurrent Callable Callable.

Prototype

Callable

Source Link

Usage

From source file:com.microsoft.windowsazure.management.SubscriptionOperationsImpl.java

/**
* The Get Subscription operation returns account and resource allocation
* information for the specified subscription.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/hh403995.aspx for
* more information)//from   ww w  .  ja v a 2s  .  c  om
*
* @return The Get Subscription operation response.
*/
@Override
public Future<SubscriptionGetResponse> getAsync() {
    return this.getClient().getExecutorService().submit(new Callable<SubscriptionGetResponse>() {
        @Override
        public SubscriptionGetResponse call() throws Exception {
            return get();
        }
    });
}

From source file:io.druid.metadata.SQLMetadataConnector.java

public <T> T retryTransaction(final TransactionCallback<T> callback) {
    final Callable<T> call = new Callable<T>() {
        @Override/*  w w w  .ja va2  s.  c o  m*/
        public T call() throws Exception {
            return getDBI().inTransaction(callback);
        }
    };
    final int maxTries = 10;
    try {
        return RetryUtils.retry(call, shouldRetry, maxTries);
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:org.atomserver.ThrottledAtomServer.java

/**
 * Wrap a call to the super class' method (i.e. AtomServer's createEntry)
 * in a CallableTask so that it can be placed onto a blocking work queue,
 * and executed in a controlled fashion.
 *
 * @param request The Abdera RequestContext
 * @return The Abdera ResponseContext//from  w  w w.  j a va 2 s  .com
 */
public ResponseContext createEntry(final RequestContext request) {
    final String t_user = AtomServerUserInfo.getUser();
    Callable<ResponseContext> callableTask = new Callable<ResponseContext>() {
        public ResponseContext call() {
            AtomServerUserInfo.setUser(t_user);
            return getAtomServer().createEntry(request);
        }
    };
    return executePooledTask(request, callableTask);
}

From source file:com.microsoft.azure.management.sql.SecureConnectionPolicyOperationsImpl.java

/**
* Creates or updates an Azure SQL Database Server Firewall rule.
*
* @param resourceGroupName Required. The name of the Resource Group to
* which the server belongs./*from ww w . jav a 2 s  . c o  m*/
* @param serverName Required. The name of the Azure SQL Database Server on
* which the database is hosted.
* @param databaseName Required. The name of the Azure SQL Database for
* which the policy applies.
* @param parameters Required. The required parameters for createing or
* updating a secure connection policy.
* @return A standard service response including an HTTP status code and
* request ID.
*/
@Override
public Future<OperationResponse> createOrUpdateDatabasePolicyAsync(final String resourceGroupName,
        final String serverName, final String databaseName,
        final DatabaseSecureConnectionPolicyCreateOrUpdateParameters parameters) {
    return this.getClient().getExecutorService().submit(new Callable<OperationResponse>() {
        @Override
        public OperationResponse call() throws Exception {
            return createOrUpdateDatabasePolicy(resourceGroupName, serverName, databaseName, parameters);
        }
    });
}

From source file:be.solidx.hot.data.rest.RestDataStore.java

@RequestMapping(value = "/{dbname}", method = RequestMethod.GET)
synchronized public DeferredResult<ResponseEntity<byte[]>> showTables(final HttpServletRequest httpRequest,
        @PathVariable final String dbname) {

    Callable<ResponseEntity<byte[]>> blocking = new Callable<ResponseEntity<byte[]>>() {

        @Override// w w w  .  j  a  va2  s  .  co  m
        public ResponseEntity<byte[]> call() throws Exception {
            DB<Map<String, Object>> db = dbMap.get(dbname);
            if (db == null) {
                return buildEmptyResponse(HttpStatus.NOT_FOUND);
            }
            List<Map<String, Object>> links = new ArrayList<Map<String, Object>>();
            for (String collectionName : db.listCollections()) {
                Map<String, Object> entry = new HashMap<String, Object>();
                entry.put(REL, collectionName);
                entry.put(HREF, getDatastoreUri(httpRequest, dbname).path("/" + collectionName).build().toUri()
                        .toASCIIString());
                links.add(entry);
            }
            Map<String, Object> response = new HashMap<String, Object>();
            response.put(LINKS, links);
            return buildJSONResponse(response, HttpStatus.OK);
        }
    };

    return blockingCall(blocking);
}

From source file:com.emc.ecs.sync.target.CasTarget.java

@Override
public void filter(final SyncObject obj) {
    timeOperationStart(CasUtil.OPERATION_TOTAL);

    if (!(obj instanceof ClipSyncObject))
        throw new UnsupportedOperationException("sync object was not a CAS clip");
    final ClipSyncObject clipSync = (ClipSyncObject) obj;

    FPClip clip = null;/*from w  ww .j  a  v  a 2s  .co m*/
    FPTag tag = null;
    int targetTagNum = 0;
    try (final InputStream cdfIn = clipSync.getInputStream()) {
        // first clone the clip via CDF raw write
        clip = TimingUtil.time(this, CasUtil.OPERATION_WRITE_CDF, new Callable<FPClip>() {
            @Override
            public FPClip call() throws Exception {
                return new FPClip(pool, clipSync.getRawSourceIdentifier(), cdfIn, CLIP_OPTIONS);
            }
        });
        clipSync.setTargetIdentifier(clipSync.getRawSourceIdentifier());

        // next write the blobs

        for (ClipTag sourceTag : clipSync.getTags()) {
            tag = clip.FetchNext(); // this should sync the tag indexes
            if (sourceTag.isBlobAttached()) { // only stream if the tag has a blob
                timedStreamBlob(tag, sourceTag);
            }
            tag.Close();
            tag = null;
        }

        final FPClip fClip = clip;
        String destClipId = TimingUtil.time(this, CasUtil.OPERATION_WRITE_CLIP, new Callable<String>() {
            @Override
            public String call() throws Exception {
                return fClip.Write();
            }
        });
        if (!destClipId.equals(clipSync.getRawSourceIdentifier()))
            throw new RuntimeException(String.format("clip IDs do not match\n    [%s != %s]",
                    clipSync.getRawSourceIdentifier(), destClipId));

        log.debug("Wrote source {} to dest {}", clipSync.getSourceIdentifier(), clipSync.getTargetIdentifier());

        timeOperationComplete(CasUtil.OPERATION_TOTAL);
    } catch (Throwable t) {
        timeOperationFailed(CasUtil.OPERATION_TOTAL);
        if (t instanceof RuntimeException)
            throw (RuntimeException) t;
        if (t instanceof FPLibraryException)
            throw new RuntimeException(
                    "Failed to store object: " + CasUtil.summarizeError((FPLibraryException) t), t);
        throw new RuntimeException("Failed to store object: " + t.getMessage(), t);
    } finally {
        // close current tag ref
        try {
            if (tag != null)
                tag.Close();
        } catch (Throwable t) {
            log.warn("could not close tag " + clipSync.getRawSourceIdentifier() + "." + targetTagNum, t);
        }
        // close clip
        try {
            if (clip != null)
                clip.Close();
        } catch (Throwable t) {
            log.warn("could not close clip " + clipSync.getRawSourceIdentifier(), t);
        }
    }
}

From source file:com.microsoft.windowsazure.management.sql.SqlManagementIntegrationTestBase.java

protected static void createStorageService() throws Exception {
    // reinitialize configuration from known state
    Configuration config = createConfiguration();

    // add LoggingFilter to any pipeline that is created
    Registry builder = (Registry) config.getBuilder();
    builder.alter(StorageManagementClient.class, Client.class, new Alteration<Client>() {
        @Override//from w  ww  .ja  v a  2 s . c  om
        public Client alter(String profile, Client client, Builder builder, Map<String, Object> properties) {
            client.addFilter(new LoggingFilter());
            return client;
        }
    });

    storageManagementClient = StorageManagementService.create(config);
    addClient((ServiceClient<?>) storageManagementClient, new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            createStorageService();
            return null;
        }
    });
    addRegexRule("azsql[a-z]{10}");
}

From source file:com.netflix.curator.framework.recipes.queue.QueueSharder.java

/**
 * The sharder must be started//from w  w w. ja v a2 s  .com
 *
 * @throws Exception errors
 */
public void start() throws Exception {
    Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED),
            "Cannot be started more than once");

    client.newNamespaceAwareEnsurePath(queuePath).ensure(client.getZookeeperClient());

    getInitialQueues();
    leaderLatch.start();

    service.submit(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            try {
                while (!Thread.currentThread().isInterrupted() && (state.get() == State.STARTED)) {
                    Thread.sleep(policies.getThresholdCheckMs());
                    checkThreshold();
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            return null;
        }
    });
}

From source file:com.microsoft.azure.management.sql.ServiceTierAdvisorOperationsImpl.java

/**
* Returns information about a service tier advisor.
*
* @param resourceGroupName Required. The name of the Resource Group.
* @param serverName Required. The name of server.
* @param databaseName Required. The name of database.
* @param serviceTierAdvisorName Required. The name of service tier advisor.
* @return Represents the response to a get service tier advisor request.
*//*from  ww w. j  av  a2 s.  com*/
@Override
public Future<ServiceTierAdvisorGetResponse> getAsync(final String resourceGroupName, final String serverName,
        final String databaseName, final String serviceTierAdvisorName) {
    return this.getClient().getExecutorService().submit(new Callable<ServiceTierAdvisorGetResponse>() {
        @Override
        public ServiceTierAdvisorGetResponse call() throws Exception {
            return get(resourceGroupName, serverName, databaseName, serviceTierAdvisorName);
        }
    });
}

From source file:com.netflix.dyno.connectionpool.impl.lb.CircularListTest.java

@Test
public void testSingleThreadWithElementRemove() throws Exception {

    final AtomicBoolean stop = new AtomicBoolean(false);

    Future<Map<Integer, Integer>> future = threadPool.submit(new Callable<Map<Integer, Integer>>() {

        @Override//from  w  w w .j a  va  2s .  co  m
        public Map<Integer, Integer> call() throws Exception {

            TestWorker worker = new TestWorker();

            while (!stop.get()) {
                worker.process();
            }

            return worker.map;
        }
    });

    Thread.sleep(200);

    List<Integer> newList = new ArrayList<Integer>();
    newList.addAll(iList);

    final List<Integer> removedElements = new ArrayList<Integer>();
    removedElements.add(newList.remove(2));
    removedElements.add(newList.remove(5));
    removedElements.add(newList.remove(6));

    cList.swapWithList(newList);

    Thread.sleep(200);
    stop.set(true);

    Map<Integer, Integer> result = future.get();

    Map<Integer, Integer> subMap = CollectionUtils.filterKeys(result, new Predicate<Integer>() {
        @Override
        public boolean apply(Integer input) {
            return !removedElements.contains(input);
        }
    });

    checkValues(new ArrayList<Integer>(subMap.values()));
}