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);
}
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);
}
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());
}
}
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"));
}
Aggregations