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:org.apache.brooklyn.util.http.HttpTool.java

/**
 * Connects to the given url and returns the connection.
 * Caller should {@code connection.getInputStream().close()} the result of this
 * (especially if they are making heavy use of this method).
 *//* w w w. ja  va 2s  .c o m*/
public static URLConnection connectToUrl(String u) throws Exception {
    final URL url = new URL(u);
    final AtomicReference<Exception> exception = new AtomicReference<Exception>();

    // sometimes openConnection hangs, so run in background
    Future<URLConnection> f = executor.submit(new Callable<URLConnection>() {
        public URLConnection call() {
            try {
                HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String s, SSLSession sslSession) {
                        return true;
                    }
                });
                URLConnection connection = url.openConnection();
                TrustingSslSocketFactory.configure(connection);
                connection.connect();

                connection.getContentLength(); // Make sure the connection is made.
                return connection;
            } catch (Exception e) {
                exception.set(e);
                LOG.debug("Error connecting to url " + url + " (propagating): " + e, e);
            }
            return null;
        }
    });
    try {
        URLConnection result = null;
        try {
            result = f.get(60, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw e;
        } catch (Exception e) {
            LOG.debug("Error connecting to url " + url + ", probably timed out (rethrowing): " + e);
            throw new IllegalStateException(
                    "Connect to URL not complete within 60 seconds, for url " + url + ": " + e);
        }
        if (exception.get() != null) {
            LOG.debug("Error connecting to url " + url + ", thread caller of " + exception,
                    new Throwable("source of rethrown error " + exception));
            throw exception.get();
        } else {
            return result;
        }
    } finally {
        f.cancel(true);
    }
}

From source file:ddf.catalog.test.SecurityPolicyConfigurator.java

private Callable<Boolean> createChecker(final Map<String, Object> policyProperties) {

    final ContextPolicyManager ctxPolicyMgr = services.getService(ContextPolicyManager.class);

    final PolicyManager targetPolicies = new PolicyManager();
    targetPolicies.setPolicies(policyProperties);

    return new Callable<Boolean>() {
        @Override//w w  w.  ja va2 s.c  o  m
        public Boolean call() throws Exception {
            for (ContextPolicy policy : ctxPolicyMgr.getAllContextPolicies()) {
                ContextPolicy targetPolicy = targetPolicies.getContextPolicy(policy.getContextPath());

                if (targetPolicy == null || !targetPolicy.getContextPath().equals(policy.getContextPath())
                        || (targetPolicy.getRealm() != null
                                && !targetPolicy.getRealm().equals(policy.getRealm()))
                        || !targetPolicy.getAuthenticationMethods()
                                .containsAll(policy.getAuthenticationMethods())
                        || !targetPolicy.getAllowedAttributeNames()
                                .containsAll(policy.getAllowedAttributeNames())) {
                    return false;
                }
            }

            return true;
        }
    };
}

From source file:org.jasig.portlet.blackboardvcportlet.dao.impl.BaseJpaDaoTest.java

/**
 * Deletes ALL entities from the database
 *///w ww.  ja va2s.  c om
@After
public final void deleteAllEntities() {
    final EntityManager entityManager = getEntityManager();
    final EntityManagerFactory entityManagerFactory = entityManager.getEntityManagerFactory();
    final Metamodel metamodel = entityManagerFactory.getMetamodel();
    Set<EntityType<?>> entityTypes = new LinkedHashSet<EntityType<?>>(metamodel.getEntities());

    do {
        final Set<EntityType<?>> failedEntitieTypes = new HashSet<EntityType<?>>();

        for (final EntityType<?> entityType : entityTypes) {
            final String entityClassName = entityType.getBindableJavaType().getName();

            try {
                this.executeInTransaction(new Callable<Object>() {
                    @Override
                    public Object call() throws Exception {
                        logger.trace("Purging all: " + entityClassName);

                        final Query query = entityManager
                                .createQuery("SELECT e FROM " + entityClassName + " AS e");
                        final List<?> entities = query.getResultList();
                        logger.trace("Found " + entities.size() + " " + entityClassName + " to delete");
                        for (final Object entity : entities) {
                            entityManager.remove(entity);
                        }

                        return null;
                    }
                });
            } catch (DataIntegrityViolationException e) {
                logger.trace(
                        "Failed to delete " + entityClassName + ". Must be a dependency of another entity");
                failedEntitieTypes.add(entityType);
            }
        }

        entityTypes = failedEntitieTypes;
    } while (!entityTypes.isEmpty());

    //Reset all spring managed mocks after every test
    MockitoFactoryBean.resetAllMocks();
}

From source file:apiserver.services.cache.controllers.CacheDocumentController.java

/**
 * put document into cache, usable for future manipulations APIs
 *
 * @param uploadedFile uploaded file// w  w  w  . ja v a2s. co m
 * @param tags list of metadata tags
 * @return cache ID
 */
//@ApiOperation(value = "add a document to cache", multiValueResponse = true)
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public WebAsyncTask<String> addDocument(
        @ApiParam(name = "uploadedFile", required = true) @RequestParam(value = "uploadedFile", required = true) MultipartFile uploadedFile,

        @ApiParam(name = "tags", required = false) @RequestParam(required = false) String[] tags)
        throws InterruptedException, TimeoutException, ExecutionException {
    final MultipartFile _file = uploadedFile;
    final String[] _tags = tags;

    Callable<String> callable = new Callable<String>() {
        @Override
        public String call() throws Exception {
            UploadDocumentJob job = new UploadDocumentJob(_file);
            job.setTags(_tags);

            Future<DocumentJob> imageFuture = documentAddGateway.addDocument(job);
            DocumentJob payload = imageFuture.get(defaultTimeout, TimeUnit.MILLISECONDS);

            return payload.getDocument().getId();
        }
    };

    return new WebAsyncTask<String>(10000, callable);
}

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

/**
* Issues a restore request for an Azure SQL Database.
*
* @param sourceServerName Required. The name of the Azure SQL Database
* Server where the source database is, or was, hosted.
* @param parameters Required. Additional parameters for the Create Restore
* Database Operation request.//w w w.  j ava 2 s .  c  o  m
* @return Contains the response to the Create Restore Database Operation
* request.
*/
@Override
public Future<RestoreDatabaseOperationCreateResponse> createAsync(final String sourceServerName,
        final RestoreDatabaseOperationCreateParameters parameters) {
    return this.getClient().getExecutorService().submit(new Callable<RestoreDatabaseOperationCreateResponse>() {
        @Override
        public RestoreDatabaseOperationCreateResponse call() throws Exception {
            return create(sourceServerName, parameters);
        }
    });
}

From source file:com.taobao.datax.plugins.writer.ftpwriter.FtpWriter.java

private void initFtpHelperAndLogin() {
    if ("sftp".equalsIgnoreCase(this.protocol)) {
        this.port = param.getIntValue(ParamKey.PORT, Constant.DEFAULT_SFTP_PORT);
        this.ftpHelper = new SftpHelperImpl();
    } else if ("ftp".equalsIgnoreCase(this.protocol)) {
        this.port = param.getIntValue(ParamKey.PORT, Constant.DEFAULT_FTP_PORT);
        this.ftpHelper = new StandardFtpHelperImpl();
    } else {/*from   w  ww. j  a  v a 2 s  .co m*/
        throw new DataExchangeException(String.format(
                "? ftpsftp ?? , ?????: [%s]", protocol));
    }
    try {
        RetryUtil.executeWithRetry(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                ftpHelper.loginFtpServer(host, username, password, port, timeout);
                return null;
            }
        }, 3, 4000, true);
    } catch (Exception e) {
        String message = String.format(
                "ftp?, host:%s, username:%s, port:%s, errorMessage:%s", host,
                username, port, e.getMessage());
        LOG.error(message);
        throw new DataExchangeException(message, e);
    }
}

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

public boolean renameFile(final String from, final String to) {
    return timeLogAndCatch("Rename file", new Callable<Boolean>() {
        @Override//  ww  w.j av a  2  s  .  co  m
        public Boolean call() throws Exception {
            return preparedClient.rename(from, to);
        }
    });
}

From source file:com.ebay.cloud.cms.sysmgmt.monitor.metrics.MongoMetric.java

private Map<String, Object> listDatabases(final MongoClient client) {
    try {/* w w w.  ja  v  a2 s .co  m*/
        Future<Map<String, Object>> future = executor.submit(new Callable<Map<String, Object>>() {
            @Override
            public Map<String, Object> call() {
                Map<String, Object> resultMap = new HashMap<String, Object>();
                List<String> databaseNames = client.getDatabaseNames();
                for (String databaseName : databaseNames) {
                    DB db = client.getDB(databaseName);
                    if (db != null) {
                        CommandResult cr = db.getStats();
                        if (cr != null) {
                            Object dataSize = cr.get("dataSize");
                            resultMap.put(databaseName, dataSize);
                        }
                    }
                }
                return resultMap;
            }
        });
        return future.get(listWaitPeroid, TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        return Collections.emptyMap();
    }
}

From source file:org.apache.cxf.dosgi.systests.common.AbstractListenerHookServiceListenerTest.java

public void testBasicInvocation() throws Exception {

    Thread.currentThread().setContextClassLoader(ClientProxyFactoryBean.class.getClassLoader());

    Server server1 = null;/*from   ww w  . j av a  2 s .  co m*/
    Server server2 = null;
    ServiceTracker tracker = null;
    try {
        server1 = startServer(ADDRESS1, GreeterService.class, new GreeterServiceImpl());

        server2 = startServer(ADDRESS2, GreeterService.class, new GreeterServiceImpl());
        tracker = new ServiceTracker(bundleContext, GreeterService.class.getName(), null) {
            @Override
            public Object addingService(final ServiceReference reference) {
                Object result = super.addingService(reference);

                FutureTask<Map<GreetingPhrase, String>> future = new FutureTask<Map<GreetingPhrase, String>>(
                        new Callable<Map<GreetingPhrase, String>>() {
                            public Map<GreetingPhrase, String> call() {
                                return useService(reference);
                            }
                        });
                future.run();
                synchronized (mutex1) {
                    synchronized (mutex2) {
                        if (task1 == null) {
                            task1 = future;
                            mutex1.notify();
                        } else if (task2 == null) {
                            task2 = future;
                            mutex2.notify();
                        }
                    }
                }
                return result;
            }
        };
        tracker.open();
        // sleep for a bit
        Thread.sleep(2000);

        installDswIfNeeded();

        verifyGreeterResponse(task1, mutex1);
        verifyGreeterResponse(task2, mutex2);
    } finally {
        if (tracker != null) {
            tracker.close();
        }

        if (server1 != null) {
            server1.getDestination().shutdown();
            server1.stop();
        }

        if (server2 != null) {
            server2.getDestination().shutdown();
            server2.stop();
        }

    }
}

From source file:com.ebay.pulsar.analytics.security.spring.PermissionControlCache.java

private PermissionControlCache() {
    permissionControl = new UserPermissionControl();
    userService = new UserService();
    cache = CacheBuilder.newBuilder().maximumSize(SIZE_CACHE).expireAfterWrite(TIME_EXPIRE, TimeUnit.MINUTES)
            .refreshAfterWrite(TIME_REFRESH, TimeUnit.MINUTES).build(new CacheLoader<String, PulsarSession>() {
                @Override/*from  ww w  . j  a  v a 2  s .  co m*/
                public PulsarSession load(String userName) throws Exception {
                    return loadFromUnderlying(userName);
                }

                @Override
                public Map<String, PulsarSession> loadAll(Iterable<? extends String> keys) {
                    Map<String, PulsarSession> m = Maps.newHashMap();
                    for (String key : keys) {
                        try {
                            PulsarSession ps = load(key);
                            m.put(key, ps);
                        } catch (Exception e) {
                        }
                        ;
                    }
                    return m;
                }

                @Override
                public ListenableFuture<PulsarSession> reload(final String userName, PulsarSession prev) {
                    // asynchronous!
                    ListenableFutureTask<PulsarSession> task = ListenableFutureTask
                            .create(new Callable<PulsarSession>() {
                                public PulsarSession call() {
                                    return loadFromUnderlying(userName);
                                }
                            });
                    EXECUTOR.submit(task);
                    return task;
                }
            });
}