Search in sources :

Example 1 with InvocationCallback

use of javax.ws.rs.client.InvocationCallback in project camel by apache.

the class CxfRsProducer method invokeAsyncProxyClient.

protected void invokeAsyncProxyClient(Exchange exchange, final AsyncCallback callback) throws Exception {
    Message inMessage = exchange.getIn();
    Object[] varValues = inMessage.getHeader(CxfConstants.CAMEL_CXF_RS_VAR_VALUES, Object[].class);
    String methodName = inMessage.getHeader(CxfConstants.OPERATION_NAME, String.class);
    Client target;
    JAXRSClientFactoryBean cfb = clientFactoryBeanCache.get(CxfEndpointUtils.getEffectiveAddress(exchange, ((CxfRsEndpoint) getEndpoint()).getAddress()));
    Bus bus = ((CxfRsEndpoint) getEndpoint()).getBus();
    // We need to apply the bus setting from the CxfRsEndpoint which is not use the default bus
    if (bus != null) {
        cfb.setBus(bus);
    }
    if (varValues == null) {
        target = cfb.create();
    } else {
        target = cfb.createWithValues(varValues);
    }
    setupClientHeaders(target, exchange);
    // find out the method which we want to invoke
    JAXRSServiceFactoryBean sfb = cfb.getServiceFactory();
    sfb.getResourceClasses();
    // check the null body first
    Object[] parameters = null;
    if (inMessage.getBody() != null) {
        parameters = inMessage.getBody(Object[].class);
    }
    // get the method
    Method method = findRightMethod(sfb.getResourceClasses(), methodName, getParameterTypes(parameters));
    CxfRsEndpoint cxfRsEndpoint = (CxfRsEndpoint) getEndpoint();
    final CxfProxyInvocationCallback invocationCallback = new CxfProxyInvocationCallback(target, exchange, cxfRsEndpoint, callback);
    WebClient.getConfig(target).getRequestContext().put(InvocationCallback.class.getName(), invocationCallback);
    // handle cookies
    CookieHandler cookieHandler = ((CxfRsEndpoint) getEndpoint()).getCookieHandler();
    loadCookies(exchange, target, cookieHandler);
    method.invoke(target, parameters);
}
Also used : Bus(org.apache.cxf.Bus) Message(org.apache.camel.Message) JAXRSClientFactoryBean(org.apache.cxf.jaxrs.client.JAXRSClientFactoryBean) Method(java.lang.reflect.Method) JAXRSServiceFactoryBean(org.apache.cxf.jaxrs.JAXRSServiceFactoryBean) InvocationCallback(javax.ws.rs.client.InvocationCallback) WebClient(org.apache.cxf.jaxrs.client.WebClient) Client(org.apache.cxf.jaxrs.client.Client) CookieHandler(org.apache.camel.http.common.cookie.CookieHandler)

Example 2 with InvocationCallback

use of javax.ws.rs.client.InvocationCallback in project jersey by jersey.

the class AsyncAgentResource method async.

@GET
@ManagedAsync
public void async(@Suspended final AsyncResponse async) {
    final long time = System.nanoTime();
    final AgentResponse response = new AgentResponse();
    final CountDownLatch outerLatch = new CountDownLatch(2);
    final Queue<String> errors = new ConcurrentLinkedQueue<>();
    // Obtain visited destinations.
    destination.path("visited").request().header("Rx-User", "Async").async().get(new InvocationCallback<List<Destination>>() {

        @Override
        public void completed(final List<Destination> destinations) {
            response.setVisited(destinations);
            outerLatch.countDown();
        }

        @Override
        public void failed(final Throwable throwable) {
            errors.offer("Visited: " + throwable.getMessage());
            outerLatch.countDown();
        }
    });
    // Obtain recommended destinations. (does not depend on visited ones)
    destination.path("recommended").request().header("Rx-User", "Async").async().get(new InvocationCallback<List<Destination>>() {

        @Override
        public void completed(final List<Destination> recommended) {
            final CountDownLatch innerLatch = new CountDownLatch(recommended.size() * 2);
            // Forecasts. (depend on recommended destinations)
            final Map<String, Forecast> forecasts = Collections.synchronizedMap(new HashMap<>());
            for (final Destination dest : recommended) {
                forecast.resolveTemplate("destination", dest.getDestination()).request().async().get(new InvocationCallback<Forecast>() {

                    @Override
                    public void completed(final Forecast forecast) {
                        forecasts.put(dest.getDestination(), forecast);
                        innerLatch.countDown();
                    }

                    @Override
                    public void failed(final Throwable throwable) {
                        errors.offer("Forecast: " + throwable.getMessage());
                        innerLatch.countDown();
                    }
                });
            }
            // Calculations. (depend on recommended destinations)
            final List<Future<Calculation>> futures = recommended.stream().map(dest -> calculation.resolveTemplate("from", "Moon").resolveTemplate("to", dest.getDestination()).request().async().get(Calculation.class)).collect(Collectors.toList());
            final Map<String, Calculation> calculations = new HashMap<>();
            while (!futures.isEmpty()) {
                final Iterator<Future<Calculation>> iterator = futures.iterator();
                while (iterator.hasNext()) {
                    final Future<Calculation> f = iterator.next();
                    if (f.isDone()) {
                        try {
                            final Calculation calculation = f.get();
                            calculations.put(calculation.getTo(), calculation);
                            innerLatch.countDown();
                        } catch (final Throwable t) {
                            errors.offer("Calculation: " + t.getMessage());
                            innerLatch.countDown();
                        } finally {
                            iterator.remove();
                        }
                    }
                }
            }
            // Have to wait here for dependent requests ...
            try {
                if (!innerLatch.await(10, TimeUnit.SECONDS)) {
                    errors.offer("Inner: Waiting for requests to complete has timed out.");
                }
            } catch (final InterruptedException e) {
                errors.offer("Inner: Waiting for requests to complete has been interrupted.");
            }
            // Recommendations.
            final List<Recommendation> recommendations = new ArrayList<>(recommended.size());
            for (final Destination dest : recommended) {
                final Forecast fore = forecasts.get(dest.getDestination());
                final Calculation calc = calculations.get(dest.getDestination());
                recommendations.add(new Recommendation(dest.getDestination(), fore != null ? fore.getForecast() : "N/A", calc != null ? calc.getPrice() : -1));
            }
            response.setRecommended(recommendations);
            outerLatch.countDown();
        }

        @Override
        public void failed(final Throwable throwable) {
            errors.offer("Recommended: " + throwable.getMessage());
            outerLatch.countDown();
        }
    });
    // ... and have to wait also here for independent requests.
    try {
        if (!outerLatch.await(10, TimeUnit.SECONDS)) {
            errors.offer("Outer: Waiting for requests to complete has timed out.");
        }
    } catch (final InterruptedException e) {
        errors.offer("Outer: Waiting for requests to complete has been interrupted.");
    }
    // Do something with errors.
    // ...
    response.setProcessingTime((System.nanoTime() - time) / 1000000);
    async.resume(response);
}
Also used : Destination(org.glassfish.jersey.examples.rx.domain.Destination) HashMap(java.util.HashMap) CountDownLatch(java.util.concurrent.CountDownLatch) Recommendation(org.glassfish.jersey.examples.rx.domain.Recommendation) InvocationCallback(javax.ws.rs.client.InvocationCallback) Forecast(org.glassfish.jersey.examples.rx.domain.Forecast) Iterator(java.util.Iterator) Future(java.util.concurrent.Future) ArrayList(java.util.ArrayList) List(java.util.List) Calculation(org.glassfish.jersey.examples.rx.domain.Calculation) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) AgentResponse(org.glassfish.jersey.examples.rx.domain.AgentResponse) HashMap(java.util.HashMap) Map(java.util.Map) GET(javax.ws.rs.GET) ManagedAsync(org.glassfish.jersey.server.ManagedAsync)

Example 3 with InvocationCallback

use of javax.ws.rs.client.InvocationCallback in project jersey by jersey.

the class JerseyInvocationTest method failedCallbackTest.

@Test
public void failedCallbackTest() throws InterruptedException {
    final Invocation.Builder builder = ClientBuilder.newClient().target("http://localhost:888/").request();
    for (int i = 0; i < 1; i++) {
        final CountDownLatch latch = new CountDownLatch(1);
        final AtomicInteger ai = new AtomicInteger(0);
        final InvocationCallback<String> callback = new InvocationCallback<String>() {

            @Override
            public void completed(final String arg0) {
                try {
                    ai.set(ai.get() + 1);
                } finally {
                    latch.countDown();
                }
            }

            @Override
            public void failed(final Throwable throwable) {
                try {
                    int result = 10;
                    if (throwable instanceof ProcessingException) {
                        result += 100;
                    }
                    final Throwable ioe = throwable.getCause();
                    if (ioe instanceof IOException) {
                        result += 1000;
                    }
                    ai.set(ai.get() + result);
                } finally {
                    latch.countDown();
                }
            }
        };
        final Invocation invocation = builder.buildGet();
        final Future<String> future = invocation.submit(callback);
        try {
            future.get();
            fail("future.get() should have failed.");
        } catch (final ExecutionException e) {
            final Throwable pe = e.getCause();
            assertTrue("Execution exception cause is not a ProcessingException: " + pe.toString(), pe instanceof ProcessingException);
            final Throwable ioe = pe.getCause();
            assertTrue("Execution exception cause is not an IOException: " + ioe.toString(), ioe instanceof IOException);
        } catch (final InterruptedException e) {
            throw new RuntimeException(e);
        }
        latch.await(1, TimeUnit.SECONDS);
        assertEquals(1110, ai.get());
    }
}
Also used : Invocation(javax.ws.rs.client.Invocation) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) InvocationCallback(javax.ws.rs.client.InvocationCallback) ExecutionException(java.util.concurrent.ExecutionException) ProcessingException(javax.ws.rs.ProcessingException) Test(org.junit.Test)

Example 4 with InvocationCallback

use of javax.ws.rs.client.InvocationCallback in project jersey by jersey.

the class JerseyInvocationTest method _submitWithGenericType.

private void _submitWithGenericType(final GenericType type) throws Exception {
    final Invocation.Builder builder = ClientBuilder.newClient().register(TerminatingFilter.class).target("http://localhost/").request();
    final AtomicReference<String> reference = new AtomicReference<String>();
    final CountDownLatch latch = new CountDownLatch(1);
    final InvocationCallback callback = new InvocationCallback<Object>() {

        @Override
        public void completed(final Object obj) {
            reference.set(obj.toString());
            latch.countDown();
        }

        @Override
        public void failed(final Throwable throwable) {
            latch.countDown();
        }
    };
    //noinspection unchecked
    ((JerseyInvocation) builder.buildGet()).submit(type, (InvocationCallback<String>) callback);
    latch.await();
    assertThat(reference.get(), is("ENTITY"));
}
Also used : Invocation(javax.ws.rs.client.Invocation) InvocationCallback(javax.ws.rs.client.InvocationCallback) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch)

Aggregations

InvocationCallback (javax.ws.rs.client.InvocationCallback)4 CountDownLatch (java.util.concurrent.CountDownLatch)3 Invocation (javax.ws.rs.client.Invocation)2 IOException (java.io.IOException)1 Method (java.lang.reflect.Method)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 Iterator (java.util.Iterator)1 List (java.util.List)1 Map (java.util.Map)1 ConcurrentLinkedQueue (java.util.concurrent.ConcurrentLinkedQueue)1 ExecutionException (java.util.concurrent.ExecutionException)1 Future (java.util.concurrent.Future)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 AtomicReference (java.util.concurrent.atomic.AtomicReference)1 GET (javax.ws.rs.GET)1 ProcessingException (javax.ws.rs.ProcessingException)1 Message (org.apache.camel.Message)1 CookieHandler (org.apache.camel.http.common.cookie.CookieHandler)1 Bus (org.apache.cxf.Bus)1