Search in sources :

Example 11 with ContainerRequest

use of org.glassfish.jersey.server.ContainerRequest in project jersey by jersey.

the class RoutingStage method apply.

/**
     * {@inheritDoc}
     * <p/>
     * Routing stage navigates through the nested {@link Router routing hierarchy}
     * using a depth-first transformation strategy until a request-to-response
     * inflector is {@link org.glassfish.jersey.process.internal.Inflecting found on
     * a leaf stage node}, in which case the request routing is terminated and an
     * {@link org.glassfish.jersey.process.Inflector inflector} (if found) is pushed
     * to the {@link RoutingContext routing context}.
     */
@Override
public Continuation<RequestProcessingContext> apply(final RequestProcessingContext context) {
    final ContainerRequest request = context.request();
    context.triggerEvent(RequestEvent.Type.MATCHING_START);
    final TracingLogger tracingLogger = TracingLogger.getInstance(request);
    final long timestamp = tracingLogger.timestamp(ServerTraceEvent.MATCH_SUMMARY);
    try {
        final RoutingResult result = _apply(context, routingRoot);
        Stage<RequestProcessingContext> nextStage = null;
        if (result.endpoint != null) {
            context.routingContext().setEndpoint(result.endpoint);
            nextStage = getDefaultNext();
        }
        return Continuation.of(result.context, nextStage);
    } finally {
        tracingLogger.logDuration(ServerTraceEvent.MATCH_SUMMARY, timestamp);
    }
}
Also used : RequestProcessingContext(org.glassfish.jersey.server.internal.process.RequestProcessingContext) ContainerRequest(org.glassfish.jersey.server.ContainerRequest) TracingLogger(org.glassfish.jersey.message.internal.TracingLogger)

Example 12 with ContainerRequest

use of org.glassfish.jersey.server.ContainerRequest in project jersey by jersey.

the class MethodSelectingRouter method getMethodRouter.

private List<Router> getMethodRouter(final RequestProcessingContext context) {
    final ContainerRequest request = context.request();
    final List<ConsumesProducesAcceptor> acceptors = consumesProducesAcceptors.get(request.getMethod());
    if (acceptors == null) {
        throw new NotAllowedException(Response.status(Status.METHOD_NOT_ALLOWED).allow(consumesProducesAcceptors.keySet()).build());
    }
    final List<ConsumesProducesAcceptor> satisfyingAcceptors = new LinkedList<>();
    final Set<ResourceMethod> differentInvokableMethods = Collections.newSetFromMap(new IdentityHashMap<>());
    for (ConsumesProducesAcceptor cpi : acceptors) {
        if (cpi.isConsumable(request)) {
            satisfyingAcceptors.add(cpi);
            differentInvokableMethods.add(cpi.methodRouting.method);
        }
    }
    if (satisfyingAcceptors.isEmpty()) {
        throw new NotSupportedException();
    }
    final List<AcceptableMediaType> acceptableMediaTypes = request.getQualifiedAcceptableMediaTypes();
    final MediaType requestContentType = request.getMediaType();
    final MediaType effectiveContentType = requestContentType == null ? MediaType.WILDCARD_TYPE : requestContentType;
    final MethodSelector methodSelector = selectMethod(acceptableMediaTypes, satisfyingAcceptors, effectiveContentType, differentInvokableMethods.size() == 1);
    if (methodSelector.selected != null) {
        final RequestSpecificConsumesProducesAcceptor selected = methodSelector.selected;
        if (methodSelector.sameFitnessAcceptors != null) {
            reportMethodSelectionAmbiguity(acceptableMediaTypes, methodSelector.selected, methodSelector.sameFitnessAcceptors);
        }
        context.push(new Function<ContainerResponse, ContainerResponse>() {

            @Override
            public ContainerResponse apply(final ContainerResponse responseContext) {
                // - either there is an entity, or we are responding to a HEAD request
                if (responseContext.getMediaType() == null && ((responseContext.hasEntity() || HttpMethod.HEAD.equals(request.getMethod())))) {
                    MediaType effectiveResponseType = determineResponseMediaType(responseContext.getEntityClass(), responseContext.getEntityType(), methodSelector.selected, acceptableMediaTypes);
                    if (MediaTypes.isWildcard(effectiveResponseType)) {
                        if (effectiveResponseType.isWildcardType() || "application".equalsIgnoreCase(effectiveResponseType.getType())) {
                            effectiveResponseType = MediaType.APPLICATION_OCTET_STREAM_TYPE;
                        } else {
                            throw new NotAcceptableException();
                        }
                    }
                    responseContext.setMediaType(effectiveResponseType);
                }
                return responseContext;
            }
        });
        return selected.methodRouting.routers;
    }
    throw new NotAcceptableException();
}
Also used : NotAllowedException(javax.ws.rs.NotAllowedException) ContainerResponse(org.glassfish.jersey.server.ContainerResponse) LinkedList(java.util.LinkedList) NotAcceptableException(javax.ws.rs.NotAcceptableException) AcceptableMediaType(org.glassfish.jersey.message.internal.AcceptableMediaType) MediaType(javax.ws.rs.core.MediaType) AcceptableMediaType(org.glassfish.jersey.message.internal.AcceptableMediaType) ContainerRequest(org.glassfish.jersey.server.ContainerRequest) NotSupportedException(javax.ws.rs.NotSupportedException) ResourceMethod(org.glassfish.jersey.server.model.ResourceMethod)

Example 13 with ContainerRequest

use of org.glassfish.jersey.server.ContainerRequest in project jersey by jersey.

the class InMemoryConnector method apply.

/**
     * {@inheritDoc}
     * <p/>
     * Transforms client-side request to server-side and invokes it on provided application ({@link ApplicationHandler}
     * instance).
     *
     * @param clientRequest client side request to be invoked.
     */
@Override
public ClientResponse apply(final ClientRequest clientRequest) {
    PropertiesDelegate propertiesDelegate = new MapPropertiesDelegate();
    final ContainerRequest containerRequest = new ContainerRequest(baseUri, clientRequest.getUri(), clientRequest.getMethod(), null, propertiesDelegate);
    containerRequest.getHeaders().putAll(clientRequest.getStringHeaders());
    final ByteArrayOutputStream clientOutput = new ByteArrayOutputStream();
    if (clientRequest.getEntity() != null) {
        clientRequest.setStreamProvider(new OutboundMessageContext.StreamProvider() {

            @Override
            public OutputStream getOutputStream(int contentLength) throws IOException {
                final MultivaluedMap<String, Object> clientHeaders = clientRequest.getHeaders();
                if (contentLength != -1 && !clientHeaders.containsKey(HttpHeaders.CONTENT_LENGTH)) {
                    containerRequest.getHeaders().putSingle(HttpHeaders.CONTENT_LENGTH, String.valueOf(contentLength));
                }
                return clientOutput;
            }
        });
        clientRequest.enableBuffering();
        try {
            clientRequest.writeEntity();
        } catch (IOException e) {
            final String msg = "Error while writing entity to the output stream.";
            LOGGER.log(Level.SEVERE, msg, e);
            throw new ProcessingException(msg, e);
        }
    }
    containerRequest.setEntityStream(new ByteArrayInputStream(clientOutput.toByteArray()));
    boolean followRedirects = ClientProperties.getValue(clientRequest.getConfiguration().getProperties(), ClientProperties.FOLLOW_REDIRECTS, true);
    final InMemoryResponseWriter inMemoryResponseWriter = new InMemoryResponseWriter();
    containerRequest.setWriter(inMemoryResponseWriter);
    containerRequest.setSecurityContext(new SecurityContext() {

        @Override
        public Principal getUserPrincipal() {
            return null;
        }

        @Override
        public boolean isUserInRole(String role) {
            return false;
        }

        @Override
        public boolean isSecure() {
            return false;
        }

        @Override
        public String getAuthenticationScheme() {
            return null;
        }
    });
    appHandler.handle(containerRequest);
    return tryFollowRedirects(followRedirects, createClientResponse(clientRequest, inMemoryResponseWriter), new ClientRequest(clientRequest));
}
Also used : ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) OutboundMessageContext(org.glassfish.jersey.message.internal.OutboundMessageContext) MapPropertiesDelegate(org.glassfish.jersey.internal.MapPropertiesDelegate) ByteArrayInputStream(java.io.ByteArrayInputStream) SecurityContext(javax.ws.rs.core.SecurityContext) ContainerRequest(org.glassfish.jersey.server.ContainerRequest) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) MapPropertiesDelegate(org.glassfish.jersey.internal.MapPropertiesDelegate) PropertiesDelegate(org.glassfish.jersey.internal.PropertiesDelegate) Principal(java.security.Principal) ClientRequest(org.glassfish.jersey.client.ClientRequest) ProcessingException(javax.ws.rs.ProcessingException)

Example 14 with ContainerRequest

use of org.glassfish.jersey.server.ContainerRequest in project jersey by jersey.

the class ResourceMethodInvoker method apply.

@Override
@SuppressWarnings("unchecked")
public ContainerResponse apply(final RequestProcessingContext processingContext) {
    final ContainerRequest request = processingContext.request();
    final Object resource = processingContext.routingContext().peekMatchedResource();
    if (method.isSuspendDeclared() || method.isManagedAsyncDeclared()) {
        if (!processingContext.asyncContext().suspend()) {
            throw new ProcessingException(LocalizationMessages.ERROR_SUSPENDING_ASYNC_REQUEST());
        }
    }
    if (method.isManagedAsyncDeclared()) {
        processingContext.asyncContext().invokeManaged(new Producer<Response>() {

            @Override
            public Response call() {
                final Response response = invoke(processingContext, resource);
                if (method.isSuspendDeclared()) {
                    // we ignore any response returned from a method that injects AsyncResponse
                    return null;
                }
                return response;
            }
        });
        // return null on current thread
        return null;
    } else {
        // TODO replace with processing context factory method.
        return new ContainerResponse(request, invoke(processingContext, resource));
    }
}
Also used : Response(javax.ws.rs.core.Response) ContainerResponse(org.glassfish.jersey.server.ContainerResponse) ContainerResponse(org.glassfish.jersey.server.ContainerResponse) ContainerRequest(org.glassfish.jersey.server.ContainerRequest) ProcessingException(javax.ws.rs.ProcessingException)

Example 15 with ContainerRequest

use of org.glassfish.jersey.server.ContainerRequest in project jersey by jersey.

the class JsonProcessingAutoDiscoverableServerTest method _test.

private void _test(final String response, final Boolean globalDisable, final Boolean serverDisable) throws Exception {
    final ResourceConfig resourceConfig = new ResourceConfig(Resource.class, Filter.class);
    if (globalDisable != null) {
        resourceConfig.property(CommonProperties.JSON_PROCESSING_FEATURE_DISABLE, globalDisable);
    }
    if (serverDisable != null) {
        resourceConfig.property(ServerProperties.JSON_PROCESSING_FEATURE_DISABLE, serverDisable);
    }
    final ApplicationHandler app = new ApplicationHandler(resourceConfig);
    final URI baseUri = URI.create("/");
    assertEquals(response, app.apply(new ContainerRequest(baseUri, baseUri, "GET", null, new MapPropertiesDelegate())).get().getEntity());
}
Also used : MapPropertiesDelegate(org.glassfish.jersey.internal.MapPropertiesDelegate) ApplicationHandler(org.glassfish.jersey.server.ApplicationHandler) ContainerRequest(org.glassfish.jersey.server.ContainerRequest) ResourceConfig(org.glassfish.jersey.server.ResourceConfig) URI(java.net.URI)

Aggregations

ContainerRequest (org.glassfish.jersey.server.ContainerRequest)39 ContainerResponse (org.glassfish.jersey.server.ContainerResponse)17 ResourceConfig (org.glassfish.jersey.server.ResourceConfig)14 ContainerRequestContext (javax.ws.rs.container.ContainerRequestContext)10 Response (javax.ws.rs.core.Response)10 IOException (java.io.IOException)8 Resource (org.glassfish.jersey.server.model.Resource)8 URI (java.net.URI)7 ApplicationHandler (org.glassfish.jersey.server.ApplicationHandler)7 Test (org.junit.Test)7 MapPropertiesDelegate (org.glassfish.jersey.internal.MapPropertiesDelegate)6 MediaType (javax.ws.rs.core.MediaType)4 LoggingFeature (org.glassfish.jersey.logging.LoggingFeature)4 ContainerResponseWriter (org.glassfish.jersey.server.spi.ContainerResponseWriter)4 ByteBufInputStream (io.netty.buffer.ByteBufInputStream)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 InputStream (java.io.InputStream)3 PropertiesDelegate (org.glassfish.jersey.internal.PropertiesDelegate)3 RequestContextBuilder (org.glassfish.jersey.server.RequestContextBuilder)3 Future (io.netty.util.concurrent.Future)2