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.mediaservices.MediaServiceManagementIntegrationTestBase.java

protected static void createMediaServiceManagementClient() throws Exception {
    Configuration config = createConfiguration();
    config.setProperty(ApacheConfigurationProperties.PROPERTY_RETRY_HANDLER,
            new DefaultHttpRequestRetryHandler());
    mediaServicesManagementClient = MediaServicesManagementService.create(config);
    addClient((ServiceClient<?>) mediaServicesManagementClient, new Callable<Void>() {
        @Override//from  ww  w.j a  v  a  2 s . co m
        public Void call() throws Exception {
            createMediaServiceManagementClient();
            return null;
        }
    });
}

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

@Test
public void testCreateNoSession() throws Exception {
    this.execute(new Callable<Object>() {
        @Override/*from w ww.  jav a2s  .  co  m*/
        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);

            try {
                sessionRecordingDao.createOrUpdateRecording(recordingLongResponse);
                fail("Should have failed with IllegalArgumentException");
            } catch (IllegalArgumentException e) {
                //Expected
            }

            return null;
        }
    });
}

From source file:org.fcrepo.camel.indexing.triplestore.integration.TestUtils.java

/**
 * get a count of the items in the triplestore, corresponding to a given subject.
 *//*ww  w .jav  a2s.  co m*/
public static Callable<Integer> triplestoreCount(final String fusekiBase, final String subject)
        throws Exception {
    final String query = "SELECT (COUNT(*) AS ?n) WHERE { <" + subject + "> ?o ?p . }";
    final String url = fusekiBase + "/query?query=" + URLEncoder.encode(query, "UTF-8") + "&output=json";
    final ObjectMapper mapper = new ObjectMapper();
    return new Callable<Integer>() {
        public Integer call() throws Exception {
            return Integer.valueOf(mapper.readTree(httpGet(url)).get("results").get("bindings").get(0).get("n")
                    .get("value").asText(), 10);
        }
    };
}

From source file:org.dasein.cloud.utils.requester.DaseinParallelRequestExecutor.java

public List<T> execute() throws DaseinRequestException {
    final HttpClientBuilder clientBuilder = setProxyIfRequired(httpClientBuilder);

    final CloseableHttpClient httpClient = clientBuilder.build();

    List<T> results = new ArrayList<T>();
    List<Callable<T>> tasks = new ArrayList<Callable<T>>();
    for (final HttpUriRequest httpUriRequest : httpUriRequests) {
        tasks.add(new Callable<T>() {
            @Override/*from   www  .j a va 2 s.com*/
            public T call() throws Exception {
                return execute(httpClient, httpUriRequest);
            }
        });
    }

    try {
        try {
            ExecutorService executorService = Executors.newFixedThreadPool(httpUriRequests.size());
            List<Future<T>> futures = executorService.invokeAll(tasks);
            for (Future<T> future : futures) {
                T result = future.get();
                results.add(result);
            }
            return results;
        } finally {
            httpClient.close();
        }
    } catch (Exception e) {
        throw new DaseinRequestException(e.getMessage(), e);
    }
}

From source file:com.microsoft.windowsazure.core.apache.HttpResponseInterceptorAdapterTest.java

@Test
public void responseFilterShouldWork() throws Exception {
    ServiceResponseFilter filterFirst = new ServiceResponseFilter() {
        @Override//from  www .j  a  v a2 s  .c o m
        public void filter(ServiceRequestContext request, ServiceResponseContext response) {
            response.setHeader("header1", "value1");
        }
    };

    ServiceResponseFilter filterLast = new ServiceResponseFilter() {
        @Override
        public void filter(ServiceRequestContext request, ServiceResponseContext response) {
            response.setHeader("header1", "value2");
        }
    };

    class DummyClient extends ServiceClient<DummyClient> {
        public URI baseUri;

        public DummyClient() {
            super(HttpClientBuilder.create(), null);
        }

        @Override
        protected DummyClient newInstance(HttpClientBuilder httpClientBuilder,
                ExecutorService executorService) {
            return new DummyClient();
        }
    }

    DummyClient client = new DummyClient();
    client.baseUri = new URI("http://www.microsoft.com");

    addClient((ServiceClient<?>) client, new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            return null;
        }
    });
    setupTest();

    client.withResponseFilterFirst(filterFirst);
    client.withResponseFilterFirst(filterLast);

    HttpGet request = new HttpGet(client.baseUri);
    HttpResponse response = null;
    try {
        response = client.getHttpClient().execute(request);
    } finally {
        assertEquals(response.getFirstHeader("header1").getValue(), "value1");
        resetTest();
    }
}

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

public boolean createDirectory(final String directory) {
    return timeLogAndCatch("Create directory", new Callable<Boolean>() {
        @Override//w  ww.  ja va 2  s . c  o  m
        public Boolean call() throws Exception {
            return preparedClient.makeDirectory(directory);
        }
    });
}

From source file:net.eusashead.hateoas.conditional.interceptor.AsyncTestController.java

@RequestMapping(method = RequestMethod.DELETE)
public Callable<ResponseEntity<Void>> delete() {
    return new Callable<ResponseEntity<Void>>() {

        @Override//from   w  w  w  .ja va2 s .co  m
        public ResponseEntity<Void> call() throws Exception {
            return new ResponseEntity<Void>(HttpStatus.NO_CONTENT);
        }
    };
}

From source file:eu.eubrazilcc.lvl.core.ConcurrencyTest.java

@Test
public void test() {
    System.out.println("ConcurrencyTest.test()");
    try {//from   ww  w.  j ava  2  s .  c o  m
        final String success = "OK";

        // test uninitialized task runner         
        try {
            TASK_RUNNER.submit(new Callable<String>() {
                @Override
                public String call() throws Exception {
                    return success;
                }
            });
            fail("Should have thrown an IllegalStateException because task runner is uninitialized");
        } catch (IllegalStateException e) {
            assertThat(e.getMessage(), containsString("Task runner uninitialized"));
        }

        // test run task
        TASK_RUNNER.preload();
        final ListenableFuture<String> future = TASK_RUNNER.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return success;
            }
        });
        assertThat("task future is not null", future, notNullValue());
        final String result = future.get(20, SECONDS);
        assertThat("task result is not null", result, notNullValue());
        assertThat("task result is not empty", isNotBlank(result));
        assertThat("task result coincides with expected", result, equalTo(success));

        // test uninitialized task scheduler
        try {
            TASK_SCHEDULER.scheduleAtFixedRate(new Runnable() {
                @Override
                public void run() {
                    System.out.println(" >> Scheluded job runs");
                }
            }, 0, 20, SECONDS);
            fail("Should have thrown an IllegalStateException because task runner is uninitialized");
        } catch (IllegalStateException e) {
            assertThat(e.getMessage(), containsString("Task scheduler uninitialized"));
        }

        // test schedule task
        TASK_SCHEDULER.preload();
        final ListenableScheduledFuture<?> future2 = TASK_SCHEDULER.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                System.out.println(" >> Scheluded job runs");
            }
        }, 0, 20, SECONDS);
        assertThat("scheduled task future is not null", future2, notNullValue());
        future2.addListener(new Runnable() {
            @Override
            public void run() {
                isCompleted = true;
            }
        }, directExecutor());
        Thread.sleep(2000);
        assertThat("scheduled task result coincides with expected", isCompleted, equalTo(isCompleted));
    } catch (Exception e) {
        e.printStackTrace(System.err);
        fail("ConcurrencyTest.test() failed: " + e.getMessage());
    } finally {
        System.out.println("ConcurrencyTest.test() has finished");
    }
}

From source file:com.eclectide.intellij.whatthecommit.WhatTheCommitAction.java

public String loadCommitMessage(final String url) {
    final FutureTask<String> downloadTask = new FutureTask<String>(new Callable<String>() {
        public String call() {
            final HttpClient client = new HttpClient();
            final GetMethod getMethod = new GetMethod(url);
            try {
                final int statusCode = client.executeMethod(getMethod);
                if (statusCode != HttpStatus.SC_OK)
                    throw new RuntimeException("Connection error (HTTP status = " + statusCode + ")");
                return getMethod.getResponseBodyAsString();
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage(), e);
            }/*from  w  w w .  jav a 2 s  . c o  m*/
        }
    });

    ApplicationManager.getApplication().executeOnPooledThread(downloadTask);

    try {
        return downloadTask.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    } catch (TimeoutException e) {
        // ignore
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }

    if (!downloadTask.isDone()) {
        downloadTask.cancel(true);
        throw new RuntimeException("Connection timed out");
    }

    return "";
}

From source file:org.honeysoft.akka.actor.BusinessActorTest.java

@Test
public void shouldBeValidWhenNoOneIsNull() throws Exception {
    //GIVEN//from ww w.  ja va  2s. co m
    final ConcurrentMap<String, Object> threadSafeMap = new ConcurrentHashMap<String, Object>(1);
    field("logger").ofType(Logger.class).in(businessService).postDecorateWith(new TestLogger(threadSafeMap));

    //WHEN
    String testString = "test-string";
    businessActorRef.tell(testString);

    //THEN
    Awaitility.waitAtMost(Duration.FIVE_SECONDS).until(new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            return !threadSafeMap.isEmpty();
        }
    });

    Assertions.assertThat(threadSafeMap).hasSize(1);
    Assertions.assertThat(threadSafeMap.values().iterator().next()).isEqualTo(testString);
}