use of javax.ws.rs.container.AsyncResponse in project pravega by pravega.
the class StreamMetadataResourceImpl method createStream.
/**
* Implementation of createStream REST API.
*
* @param scopeName The scope name of stream.
* @param createStreamRequest The object conforming to createStream request json.
* @param securityContext The security for API access.
* @param asyncResponse AsyncResponse provides means for asynchronous server side response processing.
*/
@Override
public void createStream(final String scopeName, final CreateStreamRequest createStreamRequest, final SecurityContext securityContext, final AsyncResponse asyncResponse) {
long traceId = LoggerHelpers.traceEnter(log, "createStream");
long requestId = requestIdGenerator.nextLong();
String streamName = createStreamRequest.getStreamName();
try {
NameUtils.validateUserStreamName(streamName);
} catch (IllegalArgumentException | NullPointerException e) {
log.warn(requestId, "Create stream failed due to invalid stream name {}", streamName);
asyncResponse.resume(Response.status(Status.BAD_REQUEST).build());
LoggerHelpers.traceLeave(log, "createStream", traceId);
return;
}
try {
restAuthHelper.authenticateAuthorize(getAuthorizationHeader(), authorizationResource.ofStreamsInScope(scopeName), READ_UPDATE);
} catch (AuthException e) {
log.warn(requestId, "Create stream for {} failed due to authentication failure.", streamName);
asyncResponse.resume(Response.status(Status.fromStatusCode(e.getResponseCode())).build());
LoggerHelpers.traceLeave(log, "createStream", traceId);
return;
}
StreamConfiguration streamConfiguration = ModelHelper.getCreateStreamConfig(createStreamRequest);
controllerService.createStream(scopeName, streamName, streamConfiguration, System.currentTimeMillis(), requestId).thenApply(streamStatus -> {
Response resp = null;
if (streamStatus.getStatus() == CreateStreamStatus.Status.SUCCESS) {
log.info(requestId, "Successfully created stream: {}/{}", scopeName, streamName);
resp = Response.status(Status.CREATED).entity(ModelHelper.encodeStreamResponse(scopeName, streamName, streamConfiguration)).build();
} else if (streamStatus.getStatus() == CreateStreamStatus.Status.STREAM_EXISTS) {
log.warn(requestId, "Stream already exists: {}/{}", scopeName, streamName);
resp = Response.status(Status.CONFLICT).build();
} else if (streamStatus.getStatus() == CreateStreamStatus.Status.SCOPE_NOT_FOUND) {
log.warn(requestId, "Scope not found: {}", scopeName);
resp = Response.status(Status.NOT_FOUND).build();
} else if (streamStatus.getStatus() == CreateStreamStatus.Status.INVALID_STREAM_NAME) {
log.warn(requestId, "Invalid stream name: {}", streamName);
resp = Response.status(Status.BAD_REQUEST).build();
} else {
log.warn(requestId, "createStream failed for : {}/{}", scopeName, streamName);
resp = Response.status(Status.INTERNAL_SERVER_ERROR).build();
}
return resp;
}).exceptionally(exception -> {
log.warn(requestId, "createStream for {}/{} failed: ", scopeName, streamName, exception);
return Response.status(Status.INTERNAL_SERVER_ERROR).build();
}).thenApply(asyncResponse::resume).thenAccept(x -> LoggerHelpers.traceLeave(log, "createStream", traceId));
}
use of javax.ws.rs.container.AsyncResponse in project cxf by apache.
the class JAXRSInvoker method invoke.
@SuppressWarnings("unchecked")
public Object invoke(Exchange exchange, Object request, Object resourceObject) {
final OperationResourceInfo ori = exchange.get(OperationResourceInfo.class);
final ClassResourceInfo cri = ori.getClassResourceInfo();
final Message inMessage = exchange.getInMessage();
final ServerProviderFactory providerFactory = ServerProviderFactory.getInstance(inMessage);
cri.injectContexts(resourceObject, ori, inMessage);
if (cri.isRoot()) {
ProviderInfo<Application> appProvider = providerFactory.getApplicationProvider();
if (appProvider != null) {
InjectionUtils.injectContexts(appProvider.getProvider(), appProvider, inMessage);
}
}
Method methodToInvoke = getMethodToInvoke(cri, ori, resourceObject);
List<Object> params = null;
if (request instanceof List) {
params = CastUtils.cast((List<?>) request);
} else if (request != null) {
params = new MessageContentsList(request);
}
Object result = null;
ClassLoaderHolder contextLoader = null;
AsyncResponseImpl asyncResponse = null;
try {
if (setServiceLoaderAsContextLoader(inMessage)) {
contextLoader = ClassLoaderUtils.setThreadContextClassloader(resourceObject.getClass().getClassLoader());
}
if (!ori.isSubResourceLocator()) {
asyncResponse = (AsyncResponseImpl) inMessage.get(AsyncResponse.class);
}
result = invoke(exchange, resourceObject, methodToInvoke, params);
if (asyncResponse == null && !ori.isSubResourceLocator()) {
asyncResponse = checkFutureResponse(inMessage, checkResultObject(result));
}
if (asyncResponse != null) {
if (!asyncResponse.suspendContinuationIfNeeded()) {
result = handleAsyncResponse(exchange, asyncResponse);
} else {
providerFactory.clearThreadLocalProxies();
}
}
} catch (Fault ex) {
Object faultResponse;
if (asyncResponse != null) {
faultResponse = handleAsyncFault(exchange, asyncResponse, ex.getCause() == null ? ex : ex.getCause());
} else {
faultResponse = handleFault(ex, inMessage, cri, methodToInvoke);
}
return faultResponse;
} finally {
exchange.put(LAST_SERVICE_OBJECT, resourceObject);
if (contextLoader != null) {
contextLoader.reset();
}
}
ClassResourceInfo subCri = null;
if (ori.isSubResourceLocator()) {
try {
MultivaluedMap<String, String> values = getTemplateValues(inMessage);
String subResourcePath = values.getFirst(URITemplate.FINAL_MATCH_GROUP);
String httpMethod = (String) inMessage.get(Message.HTTP_REQUEST_METHOD);
String contentType = (String) inMessage.get(Message.CONTENT_TYPE);
if (contentType == null) {
contentType = "*/*";
}
List<MediaType> acceptContentType = (List<MediaType>) exchange.get(Message.ACCEPT_CONTENT_TYPE);
result = checkSubResultObject(result, subResourcePath);
final Class<?> subResponseType;
if (result.getClass() == Class.class) {
ResourceContext rc = new ResourceContextImpl(inMessage, ori);
result = rc.getResource((Class<?>) result);
subResponseType = InjectionUtils.getActualType(methodToInvoke.getGenericReturnType());
} else {
subResponseType = methodToInvoke.getReturnType();
}
subCri = cri.getSubResource(subResponseType, ClassHelper.getRealClass(exchange.getBus(), result), result);
if (subCri == null) {
org.apache.cxf.common.i18n.Message errorM = new org.apache.cxf.common.i18n.Message("NO_SUBRESOURCE_FOUND", BUNDLE, subResourcePath);
LOG.severe(errorM.toString());
throw ExceptionUtils.toNotFoundException(null, null);
}
OperationResourceInfo subOri = JAXRSUtils.findTargetMethod(Collections.singletonMap(subCri, values), inMessage, httpMethod, values, contentType, acceptContentType);
exchange.put(OperationResourceInfo.class, subOri);
inMessage.put(URITemplate.TEMPLATE_PARAMETERS, values);
inMessage.put(URITemplate.URI_TEMPLATE, JAXRSUtils.getUriTemplate(inMessage, subCri, ori, subOri));
if (!subOri.isSubResourceLocator() && JAXRSUtils.runContainerRequestFilters(providerFactory, inMessage, false, subOri.getNameBindings())) {
return new MessageContentsList(exchange.get(Response.class));
}
// work out request parameters for the sub-resource class. Here we
// presume InputStream has not been consumed yet by the root resource class.
List<Object> newParams = JAXRSUtils.processParameters(subOri, values, inMessage);
inMessage.setContent(List.class, newParams);
return this.invoke(exchange, newParams, result);
} catch (IOException ex) {
Response resp = JAXRSUtils.convertFaultToResponse(ex, inMessage);
if (resp == null) {
resp = JAXRSUtils.convertFaultToResponse(ex, inMessage);
}
return new MessageContentsList(resp);
} catch (WebApplicationException ex) {
Response excResponse;
if (JAXRSUtils.noResourceMethodForOptions(ex.getResponse(), (String) inMessage.get(Message.HTTP_REQUEST_METHOD))) {
excResponse = JAXRSUtils.createResponse(Collections.singletonList(subCri), null, null, 200, true);
} else {
excResponse = JAXRSUtils.convertFaultToResponse(ex, inMessage);
}
return new MessageContentsList(excResponse);
}
}
setResponseContentTypeIfNeeded(inMessage, result);
return result;
}
use of javax.ws.rs.container.AsyncResponse in project cxf by apache.
the class AsyncResponseImplTest method testCancelBehavesTheSameWhenInvokedMultipleTimes.
/**
* According to the spec, subsequent calls to cancel the same AsyncResponse should
* have the same behavior as the first call.
*/
@Test
public void testCancelBehavesTheSameWhenInvokedMultipleTimes() {
HttpServletRequest req = control.createMock(HttpServletRequest.class);
HttpServletResponse resp = control.createMock(HttpServletResponse.class);
AsyncContext asyncCtx = control.createMock(AsyncContext.class);
Message msg = new MessageImpl();
msg.setExchange(new ExchangeImpl());
msg.put(ContinuationProvider.class.getName(), new Servlet3ContinuationProvider(req, resp, msg));
req.startAsync();
EasyMock.expectLastCall().andReturn(asyncCtx);
control.replay();
AsyncResponse impl = new AsyncResponseImpl(msg);
// cancel the AsyncResponse for the first time
assertTrue("Unexpectedly returned false when canceling the first time", impl.cancel());
// check the state of the AsyncResponse
assertTrue("AsyncResponse was canceled but is reporting that it was not canceled", impl.isCancelled());
boolean isDone = impl.isDone();
boolean isSuspended = impl.isSuspended();
// cancel the AsyncResponse a second time
assertTrue("Unexpectedly returned false when canceling the second time", impl.cancel());
// verify that the state is the same as before the second cancel
assertTrue("AsyncResponse was canceled (twice) but is reporting that it was not canceled", impl.isCancelled());
assertEquals("AsynchResponse.isDone() returned a different response after canceling a second time", isDone, impl.isDone());
assertEquals("AsynchResponse.isSuspended() returned a different response after canceling a second time", isSuspended, impl.isSuspended());
}
use of javax.ws.rs.container.AsyncResponse in project cxf by apache.
the class AsyncResponseImplTest method testCancelDateBehavesTheSameWhenInvokedMultipleTimes.
/**
* Similar to testCancelBehavesTheSameWhenInvokedMultipleTimes, but using the cancel(Date) signature.
*/
@Test
public void testCancelDateBehavesTheSameWhenInvokedMultipleTimes() {
HttpServletRequest req = control.createMock(HttpServletRequest.class);
HttpServletResponse resp = control.createMock(HttpServletResponse.class);
AsyncContext asyncCtx = control.createMock(AsyncContext.class);
Message msg = new MessageImpl();
msg.setExchange(new ExchangeImpl());
msg.put(ContinuationProvider.class.getName(), new Servlet3ContinuationProvider(req, resp, msg));
req.startAsync();
EasyMock.expectLastCall().andReturn(asyncCtx);
control.replay();
AsyncResponse impl = new AsyncResponseImpl(msg);
// cancel the AsyncResponse for the first time
Date d = new Date(System.currentTimeMillis() + 60000);
assertTrue("Unexpectedly returned false when canceling the first time", impl.cancel(d));
// check the state of the AsyncResponse
assertTrue("AsyncResponse was canceled but is reporting that it was not canceled", impl.isCancelled());
boolean isDone = impl.isDone();
boolean isSuspended = impl.isSuspended();
// cancel the AsyncResponse a second time
d = new Date(System.currentTimeMillis() + 120000);
assertTrue("Unexpectedly returned false when canceling the second time", impl.cancel(d));
// verify that the state is the same as before the second cancel
assertTrue("AsyncResponse was canceled (twice) but is reporting that it was not canceled", impl.isCancelled());
assertEquals("AsynchResponse.isDone() returned a different response after canceling a second time", isDone, impl.isDone());
assertEquals("AsynchResponse.isSuspended() returned a different response after canceling a second time", isSuspended, impl.isSuspended());
}
use of javax.ws.rs.container.AsyncResponse in project cxf by apache.
the class AsyncResponseImplTest method testCancelIntBehavesTheSameWhenInvokedMultipleTimes.
/**
* Similar to testCancelBehavesTheSameWhenInvokedMultipleTimes, but using the cancel(int) signature.
*/
@Test
public void testCancelIntBehavesTheSameWhenInvokedMultipleTimes() {
HttpServletRequest req = control.createMock(HttpServletRequest.class);
HttpServletResponse resp = control.createMock(HttpServletResponse.class);
AsyncContext asyncCtx = control.createMock(AsyncContext.class);
Message msg = new MessageImpl();
msg.setExchange(new ExchangeImpl());
msg.put(ContinuationProvider.class.getName(), new Servlet3ContinuationProvider(req, resp, msg));
req.startAsync();
EasyMock.expectLastCall().andReturn(asyncCtx);
control.replay();
AsyncResponse impl = new AsyncResponseImpl(msg);
// cancel the AsyncResponse for the first time
assertTrue("Unexpectedly returned false when canceling the first time", impl.cancel(10));
// check the state of the AsyncResponse
assertTrue("AsyncResponse was canceled but is reporting that it was not canceled", impl.isCancelled());
boolean isDone = impl.isDone();
boolean isSuspended = impl.isSuspended();
// cancel the AsyncResponse a second time
assertTrue("Unexpectedly returned false when canceling the second time", impl.cancel(25));
// verify that the state is the same as before the second cancel
assertTrue("AsyncResponse was canceled (twice) but is reporting that it was not canceled", impl.isCancelled());
assertEquals("AsynchResponse.isDone() returned a different response after canceling a second time", isDone, impl.isDone());
assertEquals("AsynchResponse.isSuspended() returned a different response after canceling a second time", isSuspended, impl.isSuspended());
}
Aggregations