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:io.druid.tests.indexer.AbstractIndexerTest.java

protected void unloadAndKillData(final String dataSource) throws Exception {
    Interval interval = new Interval("2013-01-01T00:00:00.000Z/2013-12-01T00:00:00.000Z");
    coordinator.unloadSegmentsForDataSource(dataSource, interval);
    RetryUtil.retryUntilFalse(new Callable<Boolean>() {
        @Override/*from   ww  w  .  j  a  v  a 2 s .co m*/
        public Boolean call() throws Exception {
            return coordinator.areSegmentsLoaded(dataSource);
        }
    }, "Segment Unloading");
    coordinator.deleteSegmentsDataSource(dataSource, interval);
    RetryUtil.retryUntilTrue(new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            return (indexer.getPendingTasks().size() + indexer.getRunningTasks().size()
                    + indexer.getWaitingTasks().size()) == 0;
        }
    }, "Waiting for Tasks Completion");
}

From source file:Main.java

public TimedFutureTask(final Callable<Object> callable, final int timeoutMS) {
    timedCallable = (new Callable<Object>() {
        @Override/*from   w w  w.  j a v a 2  s . co  m*/
        public Object call() throws Exception {
            cancelTimer = new Timer();
            cancelTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    f.cancel(true);
                }
            }, timeoutMS);
            final Object res = callable.call();
            cancelTimer.cancel();
            return res;
        }
    });
}

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

@Test
public void testEmptyQueries() throws Exception {
    this.execute(new Callable<Object>() {
        @Override//from  www. j  ava2  s. c om
        public Object call() {
            final ServerConfiguration serverConfiguration = serverConfigurationDao.getServerConfiguration();
            assertNull(serverConfiguration);

            return null;
        }
    });
    this.execute(new Callable<Object>() {
        @Override
        public Object call() {
            serverConfigurationDao.deleteServerConfiguration();
            return null;
        }
    });
}

From source file:br.com.caelum.vraptor.ioc.spring.SpringProviderRegisteringComponentsTest.java

@Override
protected <T> T executeInsideRequest(final WhatToDo<T> execution) {
    Callable<T> task = new Callable<T>() {
        public T call() throws Exception {
            T result = null;//ww w . j  a  v a2s .c  om
            HttpSessionMock session = new HttpSessionMock(context, "session" + ++counter);
            HttpServletRequestMock httpRequest = new HttpServletRequestMock(session,
                    mock(MutableRequest.class, "request" + counter));
            MutableResponse response = mock(MutableResponse.class, "response" + counter);

            RequestInfo request = new RequestInfo(context, null, httpRequest, response);
            VRaptorRequestHolder.setRequestForCurrentThread(request);

            RequestContextListener contextListener = new RequestContextListener();
            contextListener.requestInitialized(new ServletRequestEvent(context, httpRequest));
            result = execution.execute(request, counter);
            contextListener.requestDestroyed(new ServletRequestEvent(context, httpRequest));

            VRaptorRequestHolder.resetRequestForCurrentThread();
            return result;
        }
    };

    Future<T> future = Executors.newSingleThreadExecutor().submit(task);

    try {
        return future.get(60, TimeUnit.SECONDS);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.tesora.dve.mysqlapi.repl.MyReplicationVisitorDispatch.java

public static void executeLDB(ServerDBConnection dbCon, final ChannelHandlerContext channelHandlerContext,
        final byte[] readData) throws SQLException {
    try {/*from w w  w  .  j ava 2  s  .  c o  m*/
        final SSConnection ssCon1 = dbCon.getSSConn();
        Throwable t = ssCon1.executeInContext(new Callable<Throwable>() {
            public Throwable call() {
                try {
                    LoadDataBlockExecutor.executeInsert(channelHandlerContext, ssCon1,
                            LoadDataBlockExecutor.processDataBlock(channelHandlerContext, ssCon1, readData));
                } catch (Throwable e) {
                    return e;
                }
                return null;
            }
        });
        if (t != null && t.getCause() != null) {
            throw new PEException(t);
        }
    } catch (Throwable t) {
        throw new SQLException(t);
    }
}

From source file:org.jboss.spring3_2.example.AsyncRequestMapping.mvc.MemberRestController.java

@RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = "application/json")
public @ResponseBody Callable<Member> lookupMemberById(@PathVariable("id") final Long id) {
    return new Callable<Member>() {
        public Member call() {
            try {
                Thread.sleep(2000);
                System.out.println("Returning from AsyncCall");
            } catch (InterruptedException e) {
                e.printStackTrace();/*from   w ww.j  ava 2s. co  m*/
            }
            return memberDao.findById(id);
        }

    };
}

From source file:com.bbytes.jfilesync.sync.ftp.FTPClientFactory.java

/**
 * Get {@link FTPClient} with initialized connects to server given in properties file
 * @return/*w  w  w.  ja  va  2  s .c  o  m*/
 */
public FTPClient getClientInstance() {

    ExecutorService ftpclientConnThreadPool = Executors.newSingleThreadExecutor();
    Future<FTPClient> future = ftpclientConnThreadPool.submit(new Callable<FTPClient>() {

        FTPClient ftpClient = new FTPClient();

        boolean connected;

        public FTPClient call() throws Exception {

            try {
                while (!connected) {
                    try {
                        ftpClient.connect(host, port);
                        if (!ftpClient.login(username, password)) {
                            ftpClient.logout();
                        }
                        connected = true;
                        return ftpClient;
                    } catch (Exception e) {
                        connected = false;
                    }

                }

                int reply = ftpClient.getReplyCode();
                // FTPReply stores a set of constants for FTP reply codes.
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftpClient.disconnect();
                }

                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
            return ftpClient;
        }
    });

    FTPClient ftpClient = new FTPClient();
    try {
        // wait for 100 secs for acquiring conn else terminate
        ftpClient = future.get(100, TimeUnit.SECONDS);
    } catch (TimeoutException e) {
        log.info("FTP client Conn wait thread terminated!");
    } catch (InterruptedException e) {
        log.error(e.getMessage(), e);
    } catch (ExecutionException e) {
        log.error(e.getMessage(), e);
    }

    ftpclientConnThreadPool.shutdownNow();
    return ftpClient;

}

From source file:com.google.code.jconfig.factory.ConfigurationPluginFactory.java

/**
 * <p>/*  w  ww . java  2 s  .c o  m*/
 *    Returns a plugin instance of type <em>classname</em>.
 * </p>
 * 
 * <p>
 *    If the implementation class use the {@link Cacheable} annotation, it
 *    will be cached for future reuse otherwise a new instance will be
 *    created at every request.
 * </p>
 * 
 * @param classname the full name of an instance of
 *                  {@link IConfigurationPlugin}.
 * @return the plugin instance.
 * @throws PluginInstantiationException
 */
public static IConfigurationPlugin<?> getPlugin(final String classname) throws PluginInstantiationException {

    try {
        if (ClassUtils.getClass(classname).getAnnotation(Cacheable.class) == null) {
            logger.debug("Plugin <" + classname + "> is not cacheable. Creating a new one.");
            return (IConfigurationPlugin<?>) Class.forName(classname).newInstance();
        }
    } catch (Exception e) {
        throw new PluginInstantiationException(e.getMessage(), e);
    }

    // cacheable plugin
    FutureTask<IConfigurationPlugin<?>> theTask = cache.get(classname);
    if (theTask == null) {
        logger.debug("No plugin of class <" + classname + "> available. Creatine a new one.");
        Callable<IConfigurationPlugin<?>> eval = new Callable<IConfigurationPlugin<?>>() {

            public IConfigurationPlugin<?> call() throws Exception {
                IConfigurationPlugin<?> plugin = (IConfigurationPlugin<?>) Class.forName(classname)
                        .newInstance();
                return plugin;
            }
        };

        FutureTask<IConfigurationPlugin<?>> thePluginExec = new FutureTask<IConfigurationPlugin<?>>(eval);
        theTask = cache.putIfAbsent(classname, thePluginExec);
        if (theTask == null) {
            theTask = thePluginExec;
            theTask.run();
        }
        logger.debug("New plugin of class <" + classname + "> ready to be used and cached.");
    } else {
        logger.debug("Plugin of class <" + classname + "> available in cache. Using the cached one.");
    }

    try {
        return theTask.get();
    } catch (Exception e) {
        throw new PluginInstantiationException(e.getMessage(), e);
    } finally {
        logger.debug("plugin cache size: " + cache.size() + " - cache detail: " + cache);
    }
}

From source file:com.echopf.ECHOQuery.java

/**
 * Does Find objects from the remote server.
 * @param sync : if set TRUE, then the main (UI) thread is waited for complete the finding in a background thread. 
 *              (a synchronous communication)
 * @param listKey the key associated with the object list
 * @param clazz the object class/*from www  .  j av a 2 s. co m*/
 * @param callback invoked after the finding is completed
 * @param instanceId the reference ID of the finding target instance
 * @param resourceType the type of this object
 * @param params to control the output objects
 * @throws ECHOException
 */
public static <T extends ECHODataObject<T>> ECHOList<T> doFind(final boolean sync, final String listKey,
        final String resourceType, final FindCallback<T> callback, final String instanceId,
        final JSONObject fParams, final ECHODataObjectFactory<T> factory) throws ECHOException {

    // Get ready a background thread
    final Handler handler = new Handler();
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Callable<ECHOList<T>> communicator = new Callable<ECHOList<T>>() {
        @Override
        public ECHOList<T> call() throws ECHOException {
            ECHOException exception = null;
            ECHOList<T> objList = null;

            try {
                JSONObject response = getRequest(instanceId + "/" + resourceType, fParams);

                /* begin copying data */
                objList = new ECHOList<T>(response.optJSONObject("paginate"));

                JSONArray items = response.optJSONArray(listKey);
                if (items == null)
                    throw new ECHOException(0, "Invalid data type for response-field `" + listKey + "`.");

                for (int i = 0; i < items.length(); i++) {
                    JSONObject item = items.optJSONObject(i);
                    if (item == null)
                        throw new ECHOException(0, "Invalid data type for response-field `" + listKey + "`.");

                    String refid = item.optString("refid");
                    if (refid.isEmpty())
                        continue;

                    T obj = factory.create(instanceId, refid, item);
                    objList.add(obj);
                }
                /* end copying data */

            } catch (ECHOException e) {
                exception = e;
            } catch (Exception e) {
                exception = new ECHOException(e);
            }

            if (sync == false) {
                // Execute a callback method in the main (UI) thread.
                if (callback != null) {
                    final ECHOException fException = exception;
                    final ECHOList<T> fObjList = objList;

                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            callback.done(fObjList, fException);
                        }
                    });
                }

                return null;

            } else {

                if (exception == null)
                    return objList;
                throw exception;

            }
        }
    };

    Future<ECHOList<T>> future = executor.submit(communicator);

    if (sync) {
        try {
            return future.get();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt(); // ignore/reset
        } catch (ExecutionException e) {
            Throwable e2 = e.getCause();

            if (e2 instanceof ECHOException) {
                throw (ECHOException) e2;
            }

            throw new RuntimeException(e2);
        }
    }

    return null;
}

From source file:comsat.sample.actuator.SampleController.java

private Callable<Map<String, String>> helloCallable(final DeferredResult<Map<String, String>> optDeferred)
        throws SuspendExecution {
    return new Callable<Map<String, String>>() {
        @Override//from  ww  w.  j a v  a 2s  .c om
        @Suspendable
        public Map<String, String> call() throws Exception {
            try {
                Fiber.sleep(10);
                Map<String, String> ret = Collections.singletonMap("message",
                        helloWorldService.getHelloMessage());
                if (optDeferred != null)
                    optDeferred.setResult(ret);
                return ret;
            } catch (Throwable t) {
                if (optDeferred != null)
                    optDeferred.setErrorResult(t);
                throw t;
            }
        }
    };
}