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.azure.management.sql.CapabilitiesOperationsImpl.java

/**
* Returns information about the Azure SQL capabilities available for the
* specified region./*from www  .j  a v a  2 s  .co m*/
*
* @param locationName Required. The name of the region for which the Azure
* SQL capabilities are retrieved.
* @return Represents the response to a Get Azure Sql capabilities request
*/
@Override
public Future<LocationCapabilitiesGetResponse> getAsync(final String locationName) {
    return this.getClient().getExecutorService().submit(new Callable<LocationCapabilitiesGetResponse>() {
        @Override
        public LocationCapabilitiesGetResponse call() throws Exception {
            return get(locationName);
        }
    });
}

From source file:at.beris.virtualfile.client.ftp.FtpClient.java

@Override
public void createFile(final String path) throws IOException {
    LOGGER.debug("createFile (path : {})", path);
    executionHandler(new Callable<Void>() {
        @Override//  w  w w .ja  v a2 s .  c o m
        public Void call() throws Exception {
            try (ByteArrayInputStream inputStream = new ByteArrayInputStream(new byte[] {})) {
                checkConnection();
                ftpClient.storeFile(path, inputStream);
            } catch (IOException e) {
                throw e;
            }
            return null;
        }
    });
}

From source file:pt.webdetails.cpf.messaging.BeanyPluginCall.java

private void runThroughService(Map<String, String[]> params) throws Exception {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    String path = Util.joinPath("/", pluginId, "api", servicePath, methodPath);
    final JAXRSPluginServlet pluginServlet = getApiBean(pluginId);
    final MockHttpServletRequest request = new MockHttpServletRequest(path, params);
    final MockHttpServletResponse response = new MockHttpServletResponse(outputStream);
    // at this point there
    ClassLoaderAwareCaller caller = new ClassLoaderAwareCaller(getPluginManager().getClassLoader(pluginId));
    caller.callInClassLoader(new Callable<Object>() {
        @Override//w  ww  .ja  v a 2s .  co  m
        public Object call() throws Exception {
            pluginServlet.service(request, response);
            return null;
        }
    });
    contents = outputStream.toByteArray();
}

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

/**
* Retrieves the specified quota from the server.
*
* @param serverName Required. The name of the Azure SQL Database Server
* from which to retrieve the quota./*  ww  w  .jav  a  2s  .c  o  m*/
* @param quotaName Required. The name of the quota to retrieve.
* @return Represents the response structure for the Quota Get operation.
*/
@Override
public Future<QuotaGetResponse> getAsync(final String serverName, final String quotaName) {
    return this.getClient().getExecutorService().submit(new Callable<QuotaGetResponse>() {
        @Override
        public QuotaGetResponse call() throws Exception {
            return get(serverName, quotaName);
        }
    });
}

From source file:rk.java.compute.cep.ComputeService.java

public ComputeService(BlockingQueue<IPriceTick> queue, final int numberOfTickSources,
        IPriceEventSink eventbus) {/*from  ww  w. ja  v  a 2s . c om*/
    this.feedQueue = queue;
    this.numberOfTickSources = numberOfTickSources;
    this.eventbus = eventbus;
    this.handlerCache = new ConcurrentHashMap<String, Compute>();
    this.stopWatch = new StopWatch("Dispatcher Task");
    executorService = Executors.newCachedThreadPool();
    ecs = new ExecutorCompletionService<StopWatch>(executorService);
    dispatchTaskFuture = ecs.submit(new Callable<StopWatch>() {
        @Override
        public StopWatch call() throws Exception {
            stopWatch.start();
            run();
            stopWatch.stop();
            return stopWatch;
        }
    });
}

From source file:fitnesse.FitNesseExpediter.java

private Response makeResponse(final Request request) throws Exception {
    Response response;/*from  w  w w .ja  va 2s . c om*/
    try {
        executorService.submit(new Callable<Request>() {
            @Override
            public Request call() throws Exception {
                request.parse();
                return request;
            }
        }).get(requestParsingTimeLimit, TimeUnit.MILLISECONDS);

        if (request.hasBeenParsed()) {
            if (context.contextRoot.equals(request.getRequestUri() + "/")) {
                response = new SimpleResponse();
                response.redirect(context.contextRoot, "");
            } else {
                response = createGoodResponse(request);
            }
        } else {
            response = reportError(request, 400, "The request could not be parsed.");
        }
    } catch (SocketException se) {
        throw se;
    } catch (TimeoutException e) {
        String message = "The client request has been unproductive for too long. It has timed out and will no longer be processed.";
        LOG.log(Level.FINE, message, e);
        response = reportError(request, 408, message);
    } catch (HttpException e) {
        LOG.log(Level.FINE, "An error occured while fulfilling user request", e);
        response = reportError(request, 400, e.getMessage());
    } catch (Exception e) {
        LOG.log(Level.WARNING, "An error occured while fulfilling user request", e);
        response = reportError(request, e);
    }

    // Add those as default headers?
    response.addHeader("Server", "FitNesse-" + context.version);
    response.addHeader("Connection", "close");
    return response;
}

From source file:com.danperron.gamesdbclient.impl.GamesDBClientImpl.java

@Override
public Future<GetGamesListResponse> searchGames(final String query, final Platform platform) {

    return executorService.submit(new Callable<GetGamesListResponse>() {
        @Override//from   www.j  a v  a  2 s. c  o m
        public GetGamesListResponse call() throws GamesDBClientException {
            final RequestBuilder requestBuilder = RequestBuilder
                    .get("http://thegamesdb.net/api/GetGamesList.php");

            if (!Strings.isNullOrEmpty(query)) {
                requestBuilder.addParameter("name", query);
            }

            if (platform != null) {
                requestBuilder.addParameter("platform", platform.value());
            }

            final HttpUriRequest request = requestBuilder.build();

            try (CloseableHttpResponse response = httpClient.execute(request)) {
                final int statusCode = response.getStatusLine().getStatusCode();

                if (statusCode != HttpStatus.SC_OK) {
                    throw new GamesDBClientException(
                            String.format("GetGamesList responded with %d status.", statusCode));
                }

                return xmlMapper.readValue(response.getEntity().getContent(), GetGamesListResponse.class);
            } catch (IOException ex) {
                throw new GamesDBClientException("Error while attempting to search.", ex);
            }
        }
    });
}

From source file:org.apache.cxf.dosgi.singlebundle.SPIActivator.java

protected void register(final Bundle bundle) {
    Map<String, Callable<Class>> map = factories.get(bundle.getBundleId());

    Vector<URL> v = new Vector<URL>();
    try {//www.  j ava2s .c o m
        Resource[] resources = new OsgiBundleResourcePatternResolver(bundle)
                .getResources("classpath*:META-INF/services/*");
        for (Resource r : resources) {
            v.add(r.getURL());
        }
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    Enumeration<URL> e = v.elements();
    if (e != null) {
        while (e.hasMoreElements()) {
            final URL u = (URL) e.nextElement();
            final String url = u.toString();
            if (url.endsWith("/")) {
                continue;
            }
            final String factoryId = url.substring(url.lastIndexOf("/") + 1);
            if (map == null) {
                map = new HashMap<String, Callable<Class>>();
                factories.put(bundle.getBundleId(), map);
            }
            map.put(factoryId, new Callable<Class>() {
                public Class call() throws Exception {
                    BufferedReader br = new BufferedReader(new InputStreamReader(u.openStream(), "UTF-8"));
                    String factoryClassName = br.readLine();
                    br.close();
                    return bundle.loadClass(factoryClassName);
                }
            });
        }
    }
    if (map != null) {
        for (Map.Entry<String, Callable<Class>> entry : map.entrySet()) {
            OsgiLocator.register(entry.getKey(), entry.getValue());
        }
    }
}

From source file:com.atomicleopard.thundr.ftp.FtpSession.java

public boolean getFile(final String filename, final OutputStream os) {
    return timeLogAndCatch("Get file " + filename, new Callable<Boolean>() {
        @Override// w w  w. j  a v a 2 s  .c  o m
        public Boolean call() throws Exception {
            return preparedClient.retrieveFile(filename, os);
        }
    });
}

From source file:learn.jersey.services.BufferedMutatorExample.java

@Override
public int run(String[] args) throws InterruptedException, ExecutionException, TimeoutException {

    /** a callback invoked when an asynchronous write fails. */
    final BufferedMutator.ExceptionListener listener = new BufferedMutator.ExceptionListener() {
        @Override//w ww . j  a v a  2s . c o  m
        public void onException(RetriesExhaustedWithDetailsException e, BufferedMutator mutator) {
            for (int i = 0; i < e.getNumExceptions(); i++) {
                LOG.info("Failed to sent put " + e.getRow(i) + ".");
            }
        }
    };
    BufferedMutatorParams params = new BufferedMutatorParams(TABLE).listener(listener);

    //
    // step 1: create a single Connection and a BufferedMutator, shared by
    // all worker threads.
    //
    try (final Connection conn = ConnectionFactory.createConnection(getConf());
            final BufferedMutator mutator = conn.getBufferedMutator(params)) {

        /** worker pool that operates on BufferedTable instances */
        final ExecutorService workerPool = Executors.newFixedThreadPool(POOL_SIZE);
        List<Future<Void>> futures = new ArrayList<>(TASK_COUNT);

        for (int i = 0; i < TASK_COUNT; i++) {
            futures.add(workerPool.submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    //
                    // step 2: each worker sends edits to the shared
                    // BufferedMutator instance. They all use
                    // the same backing buffer, call-back "listener", and
                    // RPC executor pool.
                    //
                    Put p = new Put(Bytes.toBytes("someRow"));
                    p.addColumn(FAMILY, Bytes.toBytes("someQualifier"), Bytes.toBytes("some value"));
                    mutator.mutate(p);
                    // do work... maybe you want to call mutator.flush()
                    // after many edits to ensure any of
                    // this worker's edits are sent before exiting the
                    // Callable
                    return null;
                }
            }));
        }

        //
        // step 3: clean up the worker pool, shut down.
        //
        for (Future<Void> f : futures) {
            f.get(5, TimeUnit.MINUTES);
        }
        workerPool.shutdown();
    } catch (IOException e) {
        // exception while creating/destroying Connection or BufferedMutator
        LOG.info("exception while creating/destroying Connection or BufferedMutator", e);
    } // BufferedMutator.close() ensures all work is flushed. Could be the
      // custom listener is
      // invoked from here.
    return 0;
}