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.github.jarlakxen.embedphantomjs.executor.PhantomJSFileExecutor.java

public ListenableFuture<String> execute(final File sourceFile, final String... args) {
    final String cmd = this.phantomReference.getBinaryPath() + " " + sourceFile.getAbsolutePath() + " "
            + StringUtils.join(args, " ");
    try {/*from  www  .  j a  v  a  2  s  .  co  m*/
        final Process process = Runtime.getRuntime().exec(cmd);
        LOGGER.info("Command to execute: " + cmd);

        final ListenableFuture<String> action = processExecutorService.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                LOGGER.info("Command to execute: " + cmd);
                String output = IOUtils.toString(process.getInputStream());
                process.waitFor();
                LOGGER.debug("Command " + cmd + " output:" + output);
                return output;
            }
        });

        timeoutExecutorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    action.get(executionTimeout.getTimeout(), executionTimeout.getUnit());
                } catch (Exception e) {
                    action.cancel(false);
                    process.destroy();
                }
            }
        });

        return action;

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.microsoft.azure.management.resources.FeaturesImpl.java

/**
* Get all features under the subscription.
*
* @param resourceProviderNamespace Required. Namespace of the resource
* provider.//from www . ja v a  2 s. c  o m
* @param featureName Required. Previewed feature name in the resource
* provider.
* @return Previewed feature information.
*/
@Override
public Future<FeatureResponse> getAsync(final String resourceProviderNamespace, final String featureName) {
    return this.getClient().getExecutorService().submit(new Callable<FeatureResponse>() {
        @Override
        public FeatureResponse call() throws Exception {
            return get(resourceProviderNamespace, featureName);
        }
    });
}

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

/**
* Returns information about a dropped Azure SQL Database that can be
* restored.//w w  w  . j av  a  2  s  .co m
*
* @param serverName Required. The name of the Azure SQL Database Server on
* which the database was hosted.
* @param entityId Required. The entity ID of the restorable dropped Azure
* SQL Database to be obtained.
* @return Contains the response to the Get Restorable Dropped Database
* request.
*/
@Override
public Future<RestorableDroppedDatabaseGetResponse> getAsync(final String serverName, final String entityId) {
    return this.getClient().getExecutorService().submit(new Callable<RestorableDroppedDatabaseGetResponse>() {
        @Override
        public RestorableDroppedDatabaseGetResponse call() throws Exception {
            return get(serverName, entityId);
        }
    });
}

From source file:disko.flow.analyzers.hgdb.HGDBSaver.java

public void process(final AnalysisContext<TextDocument> context, Ports ports) throws InterruptedException {
    HGHandle docHandle = context.getGraph().getHandle(context.getDocument());
    if (docHandle == null)
        docHandle = context.getGraph().add(context.getDocument());
    if (context.getTopScope() == null)
        context.pushScoping(docHandle);//from w w w.  ja v a  2s .c  o m

    InputPort<SentenceAnn> sentenceInput = ports.getInput(SentenceAnalyzer.SENTENCE_CHANNEL);
    InputPort<SentenceInterpretation> parseInput = ports.getInput(ToRelOccProcessor.SENTENCE_INTERPRETATIONS);

    if (parseInput == null)
        parseInput = ports.getInput(ParseSelectAnalyzer.SELECTED_PARSE_CHANNEL);

    final int[] C = new int[] { 0 };

    for (SentenceAnn sentence = sentenceInput.take(); !sentenceInput.isEOS(sentence); sentence = sentenceInput
            .take()) {

        final SentenceInterpretation si = parseInput.take();
        /*         if (si == null)
                    log.error("SI is null");
                 else if (si.getParse() == null)
                    log.error("SI.getParse is null");
                 else if (si.getParse().getSentence() == null)
                    log.error("SI.getParse().getSEntence is null");
                 else if (si.getParse().getSentence().getSentence() == null)
                    log.error("SI.getParse().getSEntence().getSentence() is null");
                 else 
                    log.debug("Sentence to save " + si.getParse().getSentence().getSentence()); */

        if (parseInput.isEOS(si))
            throw new DataFlowException("HGDBSave: missing parse on " + sentence.getSentence());
        else if (!si.getSentence().equals(sentence.getSentence()))
            throw new DataFlowException("HGDBSave: out of sync for sentence <<" + sentence.getSentence()
                    + ">>, received interpretation for <<" + si.getSentence() + ">>");
        else if (si.getRelOccs().isEmpty()) {
            log.warn("No parses found for sentence " + sentence.getSentence());
            continue;
        }

        final SentenceAnn S = sentence;

        try {
            context.getGraph().getTransactionManager().transact(new Callable<Object>() {
                public Object call() {
                    context.pushScoping(context.add(S));
                    try {
                        for (RelOccurrence occ : si.getRelOccs()) {
                            int[] positions = occ.getPositions();
                            for (int i = 0; i < positions.length; i++)
                                positions[i] += S.getInterval().getStart();

                            //
                            // Don't end RelOccurrence instances for now because 
                            // they only pollute the data set and are not used for
                            // anything. 
                            // context.add(occ);

                            HGHandle[] targets = HGUtils.toHandleArray(occ);
                            HGHandle synRelHandle = hg.findOne(context.getGraph(),
                                    hg.and(hg.type(SynRel.class), hg.link(targets)));
                            C[0] = C[0] + 1;
                            if (synRelHandle == null)
                                synRelHandle = context.getGraph().add(new SynRel(targets));
                            context.addInScope(synRelHandle);
                        }
                    } finally {
                        context.popScope();
                    }
                    return null;
                }
            });
        } catch (Throwable t) {
            log.error("While saving relations for '" + sentence.getSentence() + "'", t);
        } finally {
            log.debug("Total synrel lookup: " + C[0]);
        }
    }
    log.debug("HGDB Saver ended");
    System.out.println("HGDB Saver ended");
}

From source file:com.msopentech.odatajclient.engine.communication.request.streamed.AbstractODataStreamedRequestImpl.java

/**
 * {@inheritDoc }//from  www . j a  v  a 2 s.c  om
 */
@Override
@SuppressWarnings("unchecked")
public T execute() {
    streamManager = getStreamManager();

    ((HttpEntityEnclosingRequestBase) request)
            .setEntity(URIUtils.buildInputStreamEntity(odataClient, streamManager.getBody()));

    futureWrapper.setWrapped(odataClient.getConfiguration().getExecutor().submit(new Callable<HttpResponse>() {

        @Override
        public HttpResponse call() throws Exception {
            return doExecute();
        }
    }));

    // returns the stream manager object
    return (T) streamManager;
}

From source file:com.wolvereness.overmapped.asm.ByteClass.java

public Callable<Pair<ZipEntry, byte[]>> callable(final Map<Signature, Signature> signatures,
        final Map<String, String> classMaps, final Map<String, ByteClass> classes,
        final Map<Signature, Integer> flags, final boolean correctEnums) {
    return new Callable<Pair<ZipEntry, byte[]>>() {
        @Override// w ww. j a  v a 2  s.com
        public Pair<ZipEntry, byte[]> call() throws Exception {
            return ByteClass.this.call(signatures, classMaps, classes, flags, correctEnums);
        }
    };
}

From source file:com.microsoft.azure.management.websites.SourceControlOperationsImpl.java

/**
* Get user source control//from w w  w .j av a 2s .c o  m
*
* @param name Required. The name of the source control (GitHub, Bitbucket,
* CodePlex or Dropbox)
* @return The get source control operation response.
*/
@Override
public Future<SourceControlGetResponse> getAsync(final String name) {
    return this.getClient().getExecutorService().submit(new Callable<SourceControlGetResponse>() {
        @Override
        public SourceControlGetResponse call() throws Exception {
            return get(name);
        }
    });
}

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

@Test
public void testCreateWithSession() throws Exception {
    this.execute(new Callable<Object>() {
        @Override/*w w w. j a v a2s . c o m*/
        public Object call() {
            final BlackboardSessionResponse sessionResponse = new BlackboardSessionResponse();
            sessionResponse.setSessionId(1);
            sessionResponse.setSessionName("Test Session");
            sessionResponse.setStartTime(1364566500000l);
            sessionResponse.setEndTime(1364567400000l);
            sessionResponse.setCreatorId("admin@example.com");
            sessionResponse.setBoundaryTime(30);
            sessionResponse.setAccessType(2);
            sessionResponse.setRecordings(false);
            sessionResponse.setChairList("admin@example.com,dalquist@example.com");
            sessionResponse.setNonChairList("levett@example.com");
            sessionResponse.setOpenChair(false);
            sessionResponse.setPermissionsOn(true);
            sessionResponse.setMustBeSupervised(true);
            sessionResponse.setRecordingModeType(3);
            sessionResponse.setMaxTalkers(6);
            sessionResponse.setMaxCameras(6);
            sessionResponse.setRaiseHandOnEnter(false);
            sessionResponse.setReserveSeats(0);
            sessionResponse.setSecureSignOn(false);
            sessionResponse.setVersionId(111);
            sessionResponse.setAllowInSessionInvites(true);
            sessionResponse.setHideParticipantNames(true);

            final Session session = sessionDao.createSession(sessionResponse, "http://www.example.com/session");
            assertNotNull(session);

            return null;
        }
    });

    //Create rec 2
    this.execute(new Callable<Object>() {
        @Override
        public Object call() {
            final BlackboardRecordingLongResponse recordingLongResponse = new BlackboardRecordingLongResponse();

            recordingLongResponse.setCreationDate(1364566600000l);
            recordingLongResponse.setRecordingId(1);
            recordingLongResponse.setRecordingSize(12345);
            recordingLongResponse.setRecordingURL("http://www.example.com/recording/1");
            recordingLongResponse.setRoomEndDate(1364567400000l);
            recordingLongResponse.setRoomName("Test Room");
            recordingLongResponse.setRoomStartDate(1364566500000l);
            recordingLongResponse.setSecureSignOn(false);
            recordingLongResponse.setSessionId(1);

            final SessionRecording recording = sessionRecordingDao
                    .createOrUpdateRecording(recordingLongResponse);
            assertNotNull(recording);
            assertEquals("2013-03-29T14:16:40.000Z", recording.getCreationDate().toString());
            assertEquals(false, recording.isSecureSignOn());

            return null;
        }
    });

    //Update rec 1
    this.execute(new Callable<Object>() {
        @Override
        public Object call() {
            final BlackboardRecordingLongResponse recordingLongResponse = new BlackboardRecordingLongResponse();

            recordingLongResponse.setCreationDate(1364566600000l);
            recordingLongResponse.setRecordingId(1);
            recordingLongResponse.setRecordingSize(12345);
            recordingLongResponse.setRecordingURL("http://www.example.com/recording/1");
            recordingLongResponse.setRoomEndDate(1364567400000l);
            recordingLongResponse.setRoomName("Test Room");
            recordingLongResponse.setRoomStartDate(1364566500000l);
            recordingLongResponse.setSecureSignOn(true);
            recordingLongResponse.setSessionId(1);

            final SessionRecording recording = sessionRecordingDao
                    .createOrUpdateRecording(recordingLongResponse);
            assertNotNull(recording);
            assertEquals("2013-03-29T14:16:40.000Z", recording.getCreationDate().toString());
            assertEquals(true, recording.isSecureSignOn());

            return null;
        }
    });

    //Create rec 2
    this.execute(new Callable<Object>() {
        @Override
        public Object call() {
            final BlackboardRecordingLongResponse recordingLongResponse = new BlackboardRecordingLongResponse();

            recordingLongResponse.setCreationDate(1364566600000l);
            recordingLongResponse.setRecordingId(2);
            recordingLongResponse.setRecordingSize(12345);
            recordingLongResponse.setRecordingURL("http://www.example.com/recording/2");
            recordingLongResponse.setRoomEndDate(1364567400000l);
            recordingLongResponse.setRoomName("Test Room");
            recordingLongResponse.setRoomStartDate(1364566500000l);
            recordingLongResponse.setSecureSignOn(true);
            recordingLongResponse.setSessionId(1);

            final SessionRecording recording = sessionRecordingDao
                    .createOrUpdateRecording(recordingLongResponse);
            assertNotNull(recording);
            assertEquals("2013-03-29T14:16:40.000Z", recording.getCreationDate().toString());
            assertEquals(true, recording.isSecureSignOn());

            return null;
        }
    });

    //Create rec 3
    this.execute(new Callable<Object>() {
        @Override
        public Object call() {
            final BlackboardRecordingLongResponse recordingLongResponse = new BlackboardRecordingLongResponse();

            recordingLongResponse.setCreationDate(1364566600000l);
            recordingLongResponse.setRecordingId(3);
            recordingLongResponse.setRecordingSize(12345);
            recordingLongResponse.setRecordingURL("http://www.example.com/recording/3");
            recordingLongResponse.setRoomEndDate(1364567400000l);
            recordingLongResponse.setRoomName("Test Room");
            recordingLongResponse.setRoomStartDate(1364566500000l);
            recordingLongResponse.setSecureSignOn(true);
            recordingLongResponse.setSessionId(1);

            final SessionRecording recording = sessionRecordingDao
                    .createOrUpdateRecording(recordingLongResponse);
            assertNotNull(recording);
            assertEquals("2013-03-29T14:16:40.000Z", recording.getCreationDate().toString());
            assertEquals(true, recording.isSecureSignOn());

            return null;
        }
    });

    //Verify 3 rec
    this.execute(new Callable<Object>() {
        @Override
        public Object call() {
            final Set<SessionRecording> allRecordings = sessionRecordingDao.getAllRecordings();
            assertEquals(3, allRecordings.size());

            return null;
        }
    });

    //Delete rec 1 & 3
    this.execute(new Callable<Object>() {
        @Override
        public Object call() {

            SessionRecording rec = sessionRecordingDao.getSessionRecording(1);
            sessionRecordingDao.deleteRecording(rec);

            rec = sessionRecordingDao.getSessionRecording(3);
            sessionRecordingDao.deleteRecording(rec);

            return null;
        }
    });

    //Verify 1 rec
    this.execute(new Callable<Object>() {
        @Override
        public Object call() {
            final Set<SessionRecording> allRecordings = sessionRecordingDao.getAllRecordings();
            assertEquals(1, allRecordings.size());

            return null;
        }
    });
}

From source file:com.sishuok.chapter3.web.listener.ListenerController.java

@RequestMapping("/listener4")
@ResponseBody//from w  ww  . ja v a2s.c om
public WebAsyncTask<String> listener4() {
    long timeout = 10L * 1000; // 10
    final WebAsyncTask webAsyncTask = new WebAsyncTask(timeout, new Callable() {
        @Override
        public String call() throws Exception {
            Thread.sleep(20L * 1000);
            return "success";
        }
    });

    webAsyncTask.onTimeout(new Callable() {
        @Override
        public Object call() throws Exception {
            System.out.println("====");
            return "error";
        }
    });

    webAsyncTask.onCompletion(new Runnable() {
        @Override
        public void run() {
            System.out.println("===?");
        }
    });

    return webAsyncTask;
}

From source file:com.crossbusiness.resiliency.aspect.AbstractAsyncAspect.java

/**
 * Intercept the given method invocation, submit the actual calling of the method to
 * the correct task executor and return immediately to the caller.
 * @return {@link Future} if the original method returns {@code Future}; {@code null}
 * otherwise./*from   w w w .j  a  va  2  s. co m*/
 */
// @Around("asyncMethodExecution()")
private Object doAsync(final ProceedingJoinPoint point, Async asyncConfig) throws Throwable {
    log.debug(point + " -> " + asyncConfig);

    String qualifier = asyncConfig.value();
    MethodSignature targetMethodSig = (MethodSignature) point.getSignature();
    AsyncTaskExecutor executor = getExecutor(targetMethodSig.getMethod(), qualifier);

    if (executor == null) {
        return point.proceed();
    }

    Callable<Object> callable = new Callable<Object>() {
        public Object call() throws Exception {
            try {
                Object result = point.proceed();
                if (result instanceof Future) {
                    return ((Future<?>) result).get();
                }
            } catch (Throwable ex) {
                ReflectionUtils.rethrowException(ex);
            }
            return null;
        }
    };

    Future<?> result = executor.submit(callable);

    if (Future.class.isAssignableFrom(targetMethodSig.getMethod().getReturnType())) {
        return result;
    } else {
        return null;
    }
}