Search in sources :

Example 21 with AsyncResponse

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));
}
Also used : ApiV1(io.pravega.controller.server.rest.v1.ApiV1) READ(io.pravega.auth.AuthHandler.Permissions.READ) StreamsList(io.pravega.controller.server.rest.generated.model.StreamsList) SecurityContext(javax.ws.rs.core.SecurityContext) LoggerFactory(org.slf4j.LoggerFactory) ReaderGroupManagerImpl(io.pravega.client.admin.impl.ReaderGroupManagerImpl) Random(java.util.Random) ReaderGroup(io.pravega.client.stream.ReaderGroup) StreamConfiguration(io.pravega.client.stream.StreamConfiguration) ReaderGroupNotFoundException(io.pravega.client.stream.ReaderGroupNotFoundException) TagLogger(io.pravega.common.tracing.TagLogger) RESTAuthHelper(io.pravega.shared.rest.security.RESTAuthHelper) LocalController(io.pravega.controller.server.eventProcessor.LocalController) StoreException(io.pravega.controller.store.stream.StoreException) ClientFactoryImpl(io.pravega.client.stream.impl.ClientFactoryImpl) ReaderGroupManager(io.pravega.client.admin.ReaderGroupManager) Stream(io.pravega.client.stream.Stream) ReaderGroupProperty(io.pravega.controller.server.rest.generated.model.ReaderGroupProperty) INTERNAL_NAME_PREFIX(io.pravega.shared.NameUtils.INTERNAL_NAME_PREFIX) DeleteScopeStatus(io.pravega.controller.stream.api.grpc.v1.Controller.DeleteScopeStatus) CreateStreamStatus(io.pravega.controller.stream.api.grpc.v1.Controller.CreateStreamStatus) AuthorizationResource(io.pravega.shared.security.auth.AuthorizationResource) Context(javax.ws.rs.core.Context) AsyncResponse(javax.ws.rs.container.AsyncResponse) CreateScopeRequest(io.pravega.controller.server.rest.generated.model.CreateScopeRequest) Collectors(java.util.stream.Collectors) CreateStreamRequest(io.pravega.controller.server.rest.generated.model.CreateStreamRequest) READER_GROUP_STREAM_PREFIX(io.pravega.shared.NameUtils.READER_GROUP_STREAM_PREFIX) List(java.util.List) Principal(java.security.Principal) HttpHeaders(javax.ws.rs.core.HttpHeaders) StreamState(io.pravega.controller.server.rest.generated.model.StreamState) Response(javax.ws.rs.core.Response) ScopesList(io.pravega.controller.server.rest.generated.model.ScopesList) Futures(io.pravega.common.concurrent.Futures) AuthException(io.pravega.auth.AuthException) CreateScopeStatus(io.pravega.controller.stream.api.grpc.v1.Controller.CreateScopeStatus) ConnectionFactory(io.pravega.client.connection.impl.ConnectionFactory) CompletableFuture(java.util.concurrent.CompletableFuture) UpdateStreamRequest(io.pravega.controller.server.rest.generated.model.UpdateStreamRequest) ArrayList(java.util.ArrayList) READ_UPDATE(io.pravega.auth.AuthHandler.Permissions.READ_UPDATE) ScaleMetadata(io.pravega.controller.store.stream.ScaleMetadata) DeleteStreamStatus(io.pravega.controller.stream.api.grpc.v1.Controller.DeleteStreamStatus) Status(javax.ws.rs.core.Response.Status) AuthorizationResourceImpl(io.pravega.shared.security.auth.AuthorizationResourceImpl) LoggerHelpers(io.pravega.common.LoggerHelpers) ControllerService(io.pravega.controller.server.ControllerService) NameUtils(io.pravega.shared.NameUtils) Iterator(java.util.Iterator) ScopeProperty(io.pravega.controller.server.rest.generated.model.ScopeProperty) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) ModelHelper(io.pravega.controller.server.rest.ModelHelper) ReaderGroupsList(io.pravega.controller.server.rest.generated.model.ReaderGroupsList) AuthHandlerManager(io.pravega.shared.rest.security.AuthHandlerManager) ReaderGroupsListReaderGroups(io.pravega.controller.server.rest.generated.model.ReaderGroupsListReaderGroups) UpdateStreamStatus(io.pravega.controller.stream.api.grpc.v1.Controller.UpdateStreamStatus) ClientConfig(io.pravega.client.ClientConfig) AsyncResponse(javax.ws.rs.container.AsyncResponse) Response(javax.ws.rs.core.Response) StreamConfiguration(io.pravega.client.stream.StreamConfiguration) AuthException(io.pravega.auth.AuthException)

Example 22 with AsyncResponse

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;
}
Also used : ServerProviderFactory(org.apache.cxf.jaxrs.provider.ServerProviderFactory) ResourceContext(javax.ws.rs.container.ResourceContext) Message(org.apache.cxf.message.Message) MessageContentsList(org.apache.cxf.message.MessageContentsList) WebApplicationException(javax.ws.rs.WebApplicationException) ClassLoaderHolder(org.apache.cxf.common.classloader.ClassLoaderUtils.ClassLoaderHolder) Fault(org.apache.cxf.interceptor.Fault) AsyncResponseImpl(org.apache.cxf.jaxrs.impl.AsyncResponseImpl) MediaType(javax.ws.rs.core.MediaType) MessageContentsList(org.apache.cxf.message.MessageContentsList) List(java.util.List) ResourceContextImpl(org.apache.cxf.jaxrs.impl.ResourceContextImpl) ClassResourceInfo(org.apache.cxf.jaxrs.model.ClassResourceInfo) Method(java.lang.reflect.Method) IOException(java.io.IOException) AsyncResponse(javax.ws.rs.container.AsyncResponse) Response(javax.ws.rs.core.Response) OperationResourceInfo(org.apache.cxf.jaxrs.model.OperationResourceInfo) Application(javax.ws.rs.core.Application)

Example 23 with AsyncResponse

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());
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ContinuationProvider(org.apache.cxf.continuations.ContinuationProvider) Servlet3ContinuationProvider(org.apache.cxf.transport.http.Servlet3ContinuationProvider) Message(org.apache.cxf.message.Message) Servlet3ContinuationProvider(org.apache.cxf.transport.http.Servlet3ContinuationProvider) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext) AsyncResponse(javax.ws.rs.container.AsyncResponse) MessageImpl(org.apache.cxf.message.MessageImpl) ExchangeImpl(org.apache.cxf.message.ExchangeImpl) Test(org.junit.Test)

Example 24 with AsyncResponse

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());
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ContinuationProvider(org.apache.cxf.continuations.ContinuationProvider) Servlet3ContinuationProvider(org.apache.cxf.transport.http.Servlet3ContinuationProvider) Message(org.apache.cxf.message.Message) Servlet3ContinuationProvider(org.apache.cxf.transport.http.Servlet3ContinuationProvider) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext) AsyncResponse(javax.ws.rs.container.AsyncResponse) MessageImpl(org.apache.cxf.message.MessageImpl) ExchangeImpl(org.apache.cxf.message.ExchangeImpl) Date(java.util.Date) Test(org.junit.Test)

Example 25 with AsyncResponse

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());
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ContinuationProvider(org.apache.cxf.continuations.ContinuationProvider) Servlet3ContinuationProvider(org.apache.cxf.transport.http.Servlet3ContinuationProvider) Message(org.apache.cxf.message.Message) Servlet3ContinuationProvider(org.apache.cxf.transport.http.Servlet3ContinuationProvider) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext) AsyncResponse(javax.ws.rs.container.AsyncResponse) MessageImpl(org.apache.cxf.message.MessageImpl) ExchangeImpl(org.apache.cxf.message.ExchangeImpl) Test(org.junit.Test)

Aggregations

AsyncResponse (javax.ws.rs.container.AsyncResponse)58 Response (javax.ws.rs.core.Response)22 Test (org.junit.Test)15 CompletableFuture (java.util.concurrent.CompletableFuture)12 Path (javax.ws.rs.Path)11 List (java.util.List)10 GET (javax.ws.rs.GET)10 WebApplicationException (javax.ws.rs.WebApplicationException)10 Suspended (javax.ws.rs.container.Suspended)10 Status (javax.ws.rs.core.Response.Status)9 ArrayList (java.util.ArrayList)8 Context (javax.ws.rs.core.Context)8 MediaType (javax.ws.rs.core.MediaType)8 LoggerFactory (org.slf4j.LoggerFactory)8 AuthException (io.pravega.auth.AuthException)6 READ (io.pravega.auth.AuthHandler.Permissions.READ)6 READ_UPDATE (io.pravega.auth.AuthHandler.Permissions.READ_UPDATE)6 ClientConfig (io.pravega.client.ClientConfig)6 ReaderGroupManager (io.pravega.client.admin.ReaderGroupManager)6 ReaderGroupManagerImpl (io.pravega.client.admin.impl.ReaderGroupManagerImpl)6