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.rest.BrooklynRestApiLauncherTest.java

private static void checkRestCatalogApplications(Server server) throws Exception {
    final String rootUrl = "http://localhost:" + ((NetworkConnector) server.getConnectors()[0]).getLocalPort();
    int code = Asserts.succeedsEventually(new Callable<Integer>() {
        @Override//from w w w  .j a  va  2  s.  c  om
        public Integer call() throws Exception {
            int code = HttpTool.getHttpStatusCode(rootUrl + "/v1/catalog/applications");
            if (code == HttpStatus.SC_FORBIDDEN) {
                throw new RuntimeException("Retry request");
            } else {
                return code;
            }
        }
    });
    HttpAsserts.assertHealthyStatusCode(code);
    HttpAsserts.assertContentContainsText(rootUrl + "/v1/catalog/applications",
            SampleNoOpApplication.class.getSimpleName());
}

From source file:com.github.jrialland.ajpclient.servlet.TestWrongHost.java

/**
 * tries to make a request to an unknown host, verifies that the request
 * fails (the library does not hangs) and that we have a 502 error
 * //  www. j a va  2 s .c o  m
 * @throws Exception
 */
@Test
public void testWrongTargetHost() throws Exception {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("GET");
    request.setRequestURI("/dizzy.mp4");
    final MockHttpServletResponse response = new MockHttpServletResponse();

    final Future<Integer> statusFuture = Executors.newSingleThreadExecutor().submit(new Callable<Integer>() {
        @Override
        public Integer call() throws Exception {
            AjpServletProxy.forHost("unknownhost.inexistentdomain.com", 8415).forward(request, response);
            return response.getStatus();
        }
    });

    final long start = System.currentTimeMillis();

    // should finish in less that seconds
    final int status = statusFuture.get(10, TimeUnit.SECONDS);

    Assert.assertTrue(System.currentTimeMillis() - start < 8000);

    Assert.assertEquals(HttpServletResponse.SC_BAD_GATEWAY, status);
}

From source file:org.fishwife.jrugged.httpclient.ServiceWrappedHttpClientDecorator.java

public HttpResponse execute(final HttpHost host, final HttpRequest req, final HttpContext ctx)
        throws IOException, ClientProtocolException {
    try {//from   w ww .  j a v  a2 s  . c om
        return wrapper.invoke(new Callable<HttpResponse>() {
            public HttpResponse call() throws Exception {
                return backend.execute(host, req, ctx);
            }
        });
    } catch (IOException ioe) {
        throw (ioe);
    } catch (RuntimeException re) {
        throw (re);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.t2framework.commons.util.LazyLoadingReference.java

 public T get() throws IllegalStateException {
   while (true) {
      WeakReference<Future<T>> ref = reference.get();
      boolean valid = true;
      if (ref == null) {
         FutureTask<T> f = new FutureTask<T>(new Callable<T>() {
            @Override/*  w  ww. ja  v a 2 s. c  o m*/
            public T call() throws Exception {
               return factory.create();
            }
         });
         ref = new WeakReference<Future<T>>(f);
         if (valid = reference.compareAndSet(null, ref)) {
            f.run();
         }
      }
      if (valid) {
         try {
            Future<T> f = ref.get();
            if (f != null) {
               return f.get();
            } else {
               reference.compareAndSet(ref, null);
            }
         } catch (CancellationException e) {
            reference.compareAndSet(ref, null);
         } catch (ExecutionException e) {
            throw new IllegalStateException(e.getCause());
         } catch (Exception e) {
            throw new IllegalStateException(e);
         }
      }
   }
}

From source file:com.spotify.helios.system.CliHostListTest.java

@Before
public void initialize() throws Exception {
    startDefaultMaster();/*w  ww. j  a  va 2s  . co  m*/

    // Wait for master to come up
    Polling.await(LONG_WAIT_SECONDS, SECONDS, new Callable<String>() {
        @Override
        public String call() throws Exception {
            final String output = cli("masters");
            return output.contains(masterName()) ? output : null;
        }
    });

    hostname1 = testHost() + "a";
    hostname2 = testHost() + "b";

    startDefaultAgent(hostname1);
    final AgentMain agent2 = startDefaultAgent(hostname2);

    // Wait for both agents to come up
    awaitHostRegistered(hostname1, LONG_WAIT_SECONDS, SECONDS);
    awaitHostStatus(hostname2, UP, LONG_WAIT_SECONDS, SECONDS);

    // Stop agent2
    agent2.stopAsync().awaitTerminated();
}

From source file:com.barchart.netty.rest.client.TestRequestHandler.java

public void sync() throws Exception {
    CallableTest.waitFor(new Callable<Boolean>() {
        @Override/*w w w  . j a  va2  s  . c  o m*/
        public Boolean call() throws Exception {
            return method != null;
        }
    }, 5000);
}

From source file:com.javacreed.examples.cache.part2.FictitiousLongRunningTask.java

public long computeLongTask(final String key) throws Exception {
    return cache.getValue(key, new Callable<Long>() {
        @Override/*from   ww w  .j a  v  a 2 s  . c  o  m*/
        public Long call() throws Exception {
            FictitiousLongRunningTask.LOGGER.debug("Computing Fictitious Long Running Task: {}", key);
            Thread.sleep(10000); // 10 seconds
            return System.currentTimeMillis();
        }
    });
}

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

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

        @Override//  www.  ja v  a2s .co  m
        public ResponseEntity<Void> call() throws Exception {
            HttpHeaders headers = new HttpHeaders();
            headers.setETag("\"123456\"");
            return new ResponseEntity<Void>(headers, HttpStatus.OK);
        }
    };

}

From source file:com.microsoft.windowsazure.management.website.WebSiteManagementIntegrationTestBase.java

protected static void createService() throws Exception {
    // reinitialize configuration from known state
    Configuration config = createConfiguration();
    config.setProperty(ApacheConfigurationProperties.PROPERTY_RETRY_HANDLER,
            new DefaultHttpRequestRetryHandler());

    // add LoggingFilter to any pipeline that is created
    Registry builder = (Registry) config.getBuilder();
    builder.alter(WebSiteManagementClient.class, Client.class, new Alteration<Client>() {
        @Override/*w w  w. j a v a 2 s  . c o m*/
        public Client alter(String profile, Client client, Builder builder, Map<String, Object> properties) {
            client.addFilter(new LoggingFilter());
            return client;
        }
    });

    webSiteManagementClient = WebSiteManagementService.create(config);
    addClient((ServiceClient<?>) webSiteManagementClient, new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            createService();
            return null;
        }
    });
}

From source file:kr.steelheart.site.blog.web.FeedController.java

@RequestMapping(value = {
        "/feed" }, method = RequestMethod.GET, produces = MediaType.APPLICATION_ATOM_XML_VALUE)
@ResponseBody//from  w  w w  .  j a v  a 2  s  .  c  o  m
public Callable<Void> feed(final HttpServletRequest request) {
    return new Callable<Void>() {

        @Override
        public Void call() {
            PageRequest pageable = new PageRequest(0, 20, Direction.DESC, "created");
            Page<Post> posts = postRepository.findAll(QPost.post.publish.isTrue(), pageable);

            String host = "http://" + request.getAttribute("host") + "/";

            Feed feed = new Feed();

            List<SyndPerson> authors = new ArrayList<>();
            Person author = new Person();
            author.setName("Sungha Jun");
            author.setUri(host);
            authors.add(author);

            feed.setId(host);
            feed.setTitle("steelheart*Rocks!");
            feed.setAuthors(authors);
            feed.setCopyright("http://creativecommons.org/licenses/by/3.0/deed.en");

            for (Post post : posts) {
                Date updated = null;
                if (post.getUpdated() == null) {
                    updated = post.getCreated();
                } else {
                    updated = post.getUpdated();
                }

                if (feed.getUpdated() == null || updated.compareTo(feed.getUpdated()) > 0) {
                    feed.setUpdated(updated);
                }
            }

            if (feed.getUpdated() == null) {
                feed.setUpdated(new Date());
            }

            Link link = new Link();
            link.setType(MediaType.TEXT_HTML_VALUE);
            link.setHref(host + "feed");

            List<Link> links = new ArrayList<>();
            links.add(link);

            feed.setAlternateLinks(links);
            feed.setLogo(host + "img/logo@2x.png");

            return null;
        }
    };
}