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.compute.OperatingSystemOperationsImpl.java

/**
* The List Operating Systems operation lists the versions of the guest
* operating system that are currently available in Windows Azure. The
* 2010-10-28 version of List Operating Systems also indicates what family
* an operating system version belongs to. Currently Azure supports two
* operating system families: the Azure guest operating system that is
* substantially compatible with Windows Server 2008 SP2, and the Azure
* guest operating system that is substantially compatible with Windows
* Server 2008 R2.  (see// w  w w  .  ja  va 2  s  .c  om
* http://msdn.microsoft.com/en-us/library/windowsazure/ff684168.aspx for
* more information)
*
* @return The List Operating Systems operation response.
*/
@Override
public Future<OperatingSystemListResponse> listAsync() {
    return this.getClient().getExecutorService().submit(new Callable<OperatingSystemListResponse>() {
        @Override
        public OperatingSystemListResponse call() throws Exception {
            return list();
        }
    });
}

From source file:jp.primecloud.auto.process.lb.PuppetLoadBalancerProcess.java

public void configure(final Long loadBalancerNo, final Long componentNo, List<Long> instanceNos) {
    final Map<String, Object> rootMap = createRootMap(loadBalancerNo, componentNo, instanceNos);

    // ????????//ww w. ja v  a2 s. c o  m
    if (instanceNos.size() == 1) {
        configureInstance(loadBalancerNo, componentNo, instanceNos.get(0), rootMap);
        return;
    }

    // 
    List<Callable<Void>> callables = new ArrayList<Callable<Void>>();
    final Map<String, Object> loggingContext = LoggingUtils.getContext();
    for (final Long instanceNo : instanceNos) {
        Callable<Void> callable = new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                LoggingUtils.setContext(loggingContext);
                try {
                    Map<String, Object> map = new HashMap<String, Object>(rootMap);
                    configureInstance(loadBalancerNo, componentNo, instanceNo, map);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                    throw e;
                } finally {
                    LoggingUtils.removeContext();
                }
                return null;
            }
        };
        callables.add(callable);
    }

    try {
        List<Future<Void>> futures = executorService.invokeAll(callables);

        // ???
        List<Throwable> throwables = new ArrayList<Throwable>();
        for (Future<Void> future : futures) {
            try {
                future.get();
            } catch (ExecutionException e) {
                throwables.add(e.getCause());
            } catch (InterruptedException ignore) {
            }
        }

        // ??
        if (throwables.size() > 0) {
            throw new MultiCauseException(throwables.toArray(new Throwable[throwables.size()]));
        }
    } catch (InterruptedException e) {
    }
}

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

@Override
public boolean exists(final String path) throws IOException {
    LOGGER.debug("exists (path : {})", path);
    Boolean exists = executionHandler(new Callable<Boolean>() {
        @Override//from w  w w.j  ava 2s.  co m
        public Boolean call() throws Exception {

            int replyCode = ftpClient.stat(path);
            String replyText = ftpClient.getReplyString();
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                // this replyText code is set when file doesn't exist on the server
                if (FTPReply.FILE_ACTION_NOT_TAKEN == replyCode)
                    return false;
                else {
                    LOGGER.warn("Unexpected Reply (Code: {}, Text: '{}'", replyCode, replyText);
                }
            }

            String[] replyTextParts = replyText.split("\n");
            if (replyTextParts.length <= 2) {
                if (ftpClient.changeWorkingDirectory(path))
                    ftpClient.changeToParentDirectory();
                else
                    return false;
            }
            return true;
        }
    });
    LOGGER.debug("Returns: {}", exists);
    return exists;
}

From source file:ch.cyberduck.core.onedrive.OneDriveCommonsHttpRequestExecutor.java

protected Upload doUpload(final URL url, final Set<RequestHeader> headers,
        final HttpEntityEnclosingRequestBase request) {
    for (RequestHeader header : headers) {
        if (header.getKey().equals(HTTP.TRANSFER_ENCODING)) {
            continue;
        }/* w  ww  .  j a v  a2 s .c  om*/
        if (header.getKey().equals(HTTP.CONTENT_LEN)) {
            continue;
        }
        request.addHeader(new BasicHeader(header.getKey(), header.getValue()));
    }
    final CountDownLatch entry = new CountDownLatch(1);
    final DelayedHttpEntity entity = new DelayedHttpEntity(entry) {
        @Override
        public long getContentLength() {
            for (RequestHeader header : headers) {
                if (header.getKey().equals(HTTP.CONTENT_LEN)) {
                    return Long.valueOf(header.getValue());
                }
            }
            // Content-Encoding: chunked
            return -1L;
        }
    };
    request.setEntity(entity);
    final DefaultThreadPool executor = new DefaultThreadPool(String.format("http-%s", url), 1);
    final Future<CloseableHttpResponse> future = executor.execute(new Callable<CloseableHttpResponse>() {
        @Override
        public CloseableHttpResponse call() throws Exception {
            return client.execute(request);
        }
    });
    return new Upload() {
        @Override
        public Response getResponse() throws IOException {
            final CloseableHttpResponse response;
            try {
                response = future.get();
            } catch (InterruptedException e) {
                throw new IOException(e);
            } catch (ExecutionException e) {
                throw new IOException(e.getCause());
            } finally {
                executor.shutdown(false);
            }
            return new CommonsHttpResponse(response);
        }

        @Override
        public OutputStream getOutputStream() {
            try {
                // Await execution of HTTP request to make stream available
                entry.await();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return entity.getStream();
        }
    };
}

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

/**
* Gets Azure SQL Database security policy object according to a given Azure
* SQL Database Server and Database./*from  w  ww  .  j a  v a2  s  .  co m*/
*
* @param resourceGroupName Required. The name of the Resource Group to
* which the Azure SQL Database Server belongs.
* @param serverName Required. The name of the Azure SQL Database Server on
* which the Azure SQL Database hosted.
* @param databaseName Required. The name of the Azure SQL Database for
* which the security policy is being retreived.
* @return Represents the response to a get Azure SQL Database security
* policy request
*/
@Override
public Future<DatabaseSecurityPolicyGetResponse> getAsync(final String resourceGroupName,
        final String serverName, final String databaseName) {
    return this.getClient().getExecutorService().submit(new Callable<DatabaseSecurityPolicyGetResponse>() {
        @Override
        public DatabaseSecurityPolicyGetResponse call() throws Exception {
            return get(resourceGroupName, serverName, databaseName);
        }
    });
}

From source file:edu.tum.cs.vis.model.util.algorithm.ACCUM.java

/**
 * Calculate curvature for each vertex of model
 * // w  ww  . j  ava2  s.c  o  m
 * @param curvatures
 *            resulting vertex curvature mapping
 * @param m
 *            model to calculate curvature for
 */
private static void calculateCurvature(final HashMap<Vertex, Curvature> curvatures, final Model m) {

    // Set up an initial coordinate system with min and max curvature as u and v per vertex
    for (int i = 0; i < m.getTriangles().size(); i++) {
        Triangle t = m.getTriangles().get(i);
        for (int j = 0; j < 3; j++) {
            Vertex v = t.getPosition()[j];
            Curvature c = new Curvature();
            curvatures.put(v, c);
            c.setPrincipleDirectionMax(new Vector3f(t.getPosition()[(j + 1) % 3]));
            c.getPrincipleDirectionMax().sub(v);
        }
    }
    for (Iterator<Vertex> it = m.getVertices().iterator(); it.hasNext();) {
        Vertex v = it.next();

        Curvature c = curvatures.get(v);
        if (c == null) {
            // vertex isn't referenced in any triangle
            it.remove();
            continue;
        }

        Vector3f tmp = new Vector3f();
        tmp.cross(c.getPrincipleDirectionMax(), v.getNormalVector());
        tmp.normalize();
        c.setPrincipleDirectionMax(tmp);

        tmp = new Vector3f();
        tmp.cross(v.getNormalVector(), c.getPrincipleDirectionMax());
        c.setPrincipleDirectionMin(tmp);

    }

    // Compute curvature per-face

    List<Callable<Void>> threads = new LinkedList<Callable<Void>>();

    final int interval = 500;

    for (int start = 0; start < m.getTriangles().size(); start += interval) {
        final int st = start;
        threads.add(new Callable<Void>() {

            @Override
            public Void call() throws Exception {
                int end = Math.min(st + interval, m.getTriangles().size());
                for (int i = st; i < end; i++) {
                    calculateCurvatureForTriangle(curvatures, m.getTriangles().get(i));
                }
                return null;
            }

        });
    }

    ThreadPool.executeInPool(threads);

    // Compute principal directions and curvatures at each vertex
    for (int i = 0; i < m.getVertices().size(); i++) {
        Curvature c = curvatures.get(m.getVertices().get(i));
        Vector3f pdirRet[] = new Vector3f[2];
        float kRet[] = new float[2];

        diagonalize_curv(c.getPrincipleDirectionMax(), c.getPrincipleDirectionMin(), c.getCurvatureMax(),
                c.getCurvatureMinMax(), c.getCurvatureMin(), m.getVertices().get(i).getNormalVector(), pdirRet,
                kRet);
        c.setPrincipleDirectionMax(pdirRet[0]);
        c.setPrincipleDirectionMin(pdirRet[1]);
        c.setCurvatureMax(kRet[0]);
        c.setCurvatureMin(kRet[1]);
    }
}

From source file:com.easarrive.quartz.aws.service.impl.PythonWordSegmenterService.java

/**
 * {@inheritDoc}/* ww w . ja v a 2  s. com*/
 */
@Override
public void teachFromDatabase(final String wordSegmenterURL, String dbName, String tableName, String taskName) {

    //?
    List<CronTask> cronTaskList = cronTaskReadMapper.find(dbName, tableName, taskName);
    CronTask dbCronTask = null;

    //?????
    if (cronTaskList != null && cronTaskList.size() > 0) {
        dbCronTask = cronTaskList.get(0);
        if (cronTaskList.size() > 1) {
            for (int index = 1; index < cronTaskList.size(); index++) {
                CronTask deleteCronTask = cronTaskList.get(index);
                Long count = cronTaskWriteMapper.delete(deleteCronTask.getId());
                if (logger.isDebugEnabled()) {
                    logger.debug("Python ????  {}", count);
                }
            }
        }
    }

    //?
    Long tableUpdateTime = null;
    if (dbCronTask != null) {
        tableUpdateTime = dbCronTask.getTableUpdateTime();
        dbCronTask.setLastExecTime(dbCronTask.getExecTime());
        dbCronTask.setExecTime(System.currentTimeMillis());
        dbCronTask.setUpdateTime(System.currentTimeMillis());
    }
    if (tableUpdateTime == null) {
        tableUpdateTime = -1L;
    }

    //
    List<GoodsTags> goodsTagsList = goodsTagsReadMapper.getAll(tableUpdateTime);
    if (goodsTagsList == null || goodsTagsList.size() < 1) {
        if (logger.isInfoEnabled()) {
            logger.info("Python ?");
        }
        return;
    }

    //
    ExecutorService executorService = Executors.newCachedThreadPool();
    List<Future<Map<Integer, Boolean>>> futureList = new ArrayList<Future<Map<Integer, Boolean>>>();
    for (final GoodsTags tags : goodsTagsList) {
        if (tags == null) {
            continue;
        }
        Future<Map<Integer, Boolean>> future = executorService.submit(new Callable<Map<Integer, Boolean>>() {
            @Override
            public Map<Integer, Boolean> call() throws Exception {
                Map<Integer, Boolean> result = new HashMap<Integer, Boolean>();
                result.put(tags.getId(), null);
                if (StringUtil.isEmpty(tags.getTag())) {
                    return result;
                }
                try {
                    String wordSegmenterURLFinal = String.format("%s%s", wordSegmenterURL,
                            URLEncoder.encode(tags.getTag(), Constant.Charset.UTF8));
                    HttpResponse httpResponse = HttpClientUtil.get(wordSegmenterURLFinal, null);
                    int statusCode = httpResponse.getStatusLine().getStatusCode();
                    result.put(tags.getId(), statusCode == 200);
                } catch (Exception e) {
                    result.put(tags.getId(), false);
                }
                return result;
            }
        });
        futureList.add(future);
        if (tableUpdateTime < tags.getAddTime()) {
            tableUpdateTime = tags.getAddTime();
        }
    }

    //?
    for (Future<Map<Integer, Boolean>> future : futureList) {
        try {
            Map<Integer, Boolean> result = future.get();
            if (logger.isInfoEnabled()) {
                logger.info("Python ??  {}", result);
            }
        } catch (InterruptedException e) {
            if (logger.isErrorEnabled()) {
                logger.error(e.getMessage(), e);
            }
        } catch (ExecutionException e) {
            if (logger.isErrorEnabled()) {
                logger.error(e.getMessage(), e);
            }
        }
    }

    //
    if (dbCronTask == null) {
        dbCronTask = new CronTask(0L, dbName, tableName, tableUpdateTime, taskName, System.currentTimeMillis(),
                System.currentTimeMillis(), System.currentTimeMillis(), System.currentTimeMillis(), 0);
        Long id = cronTaskWriteMapper.insert(dbCronTask);
        if (logger.isDebugEnabled()) {
            logger.debug(" Python ?  {}", id);
        }
    } else {
        Long count = cronTaskWriteMapper.update(dbCronTask);
        if (logger.isDebugEnabled()) {
            logger.debug(" Python ??  {}", count);
        }
    }
}

From source file:com.microsoft.windowsazure.management.compute.VirtualMachineExtensionOperationsImpl.java

/**
* The List Resource Extensions operation lists the resource extensions that
* are available to add to a Virtual Machine. In Azure, a process can run
* as a resource extension of a Virtual Machine. For example, Remote
* Desktop Access or the Azure Diagnostics Agent can run as resource
* extensions to the Virtual Machine.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/dn495441.aspx for
* more information)/*  w w  w.  java  2 s . co m*/
*
* @return The List Resource Extensions operation response.
*/
@Override
public Future<VirtualMachineExtensionListResponse> listAsync() {
    return this.getClient().getExecutorService().submit(new Callable<VirtualMachineExtensionListResponse>() {
        @Override
        public VirtualMachineExtensionListResponse call() throws Exception {
            return list();
        }
    });
}

From source file:com.microsoft.windowsazure.management.network.VirtualIPOperationsImpl.java

/**
* The Add Virtual IP operation adds a logical Virtual IP to the deployment.
*
* @param serviceName Required. The name of the hosted service that contains
* the given deployment./*from   w ww .j  a  v a 2  s. com*/
* @param deploymentName Required. The name of the deployment where the
* logical Virtual IP is to be added.
* @param virtualIPName Required. The name of the logical Virtual IP to be
* added.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request, and also includes error information regarding the
* failure.
*/
@Override
public Future<OperationStatusResponse> addAsync(final String serviceName, final String deploymentName,
        final String virtualIPName) {
    return this.getClient().getExecutorService().submit(new Callable<OperationStatusResponse>() {
        @Override
        public OperationStatusResponse call() throws Exception {
            return add(serviceName, deploymentName, virtualIPName);
        }
    });
}

From source file:io.fabric8.elasticsearch.plugin.PluginClient.java

public UpdateResponse updateDocument(String index, String type, String id, String source) {
    return execute(new Callable<UpdateResponse>() {

        @Override/*from w ww  .  j  a  v  a2 s. co m*/
        public UpdateResponse call() throws Exception {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Updating Document: '{}/{}/{}' source: '{}'", index, type, id, source);
            }
            UpdateResponse response = client.prepareUpdate(index, type, id).setDoc(source, XContentType.JSON)
                    .setDocAsUpsert(true).get();

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Document Updated: '{}'", response.status());
            }
            return response;
        }
    });
}