Search in sources :

Example 6 with ContainerRequest

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

the class JerseyHttp2ServerHandler method createContainerRequest.

/**
     * Create Jersey {@link ContainerRequest} based on Netty {@link HttpRequest}.
     *
     * @param ctx          Netty channel context.
     * @param http2Headers Netty Http/2 headers.
     * @return created Jersey Container Request.
     */
private ContainerRequest createContainerRequest(ChannelHandlerContext ctx, Http2HeadersFrame http2Headers) {
    String path = http2Headers.headers().path().toString();
    String s = path.startsWith("/") ? path.substring(1) : path;
    URI requestUri = URI.create(baseUri + ContainerUtils.encodeUnsafeCharacters(s));
    ContainerRequest requestContext = new ContainerRequest(baseUri, requestUri, http2Headers.headers().method().toString(), getSecurityContext(), new PropertiesDelegate() {

        private final Map<String, Object> properties = new HashMap<>();

        @Override
        public Object getProperty(String name) {
            return properties.get(name);
        }

        @Override
        public Collection<String> getPropertyNames() {
            return properties.keySet();
        }

        @Override
        public void setProperty(String name, Object object) {
            properties.put(name, object);
        }

        @Override
        public void removeProperty(String name) {
            properties.remove(name);
        }
    });
    // request entity handling.
    if (!http2Headers.isEndStream()) {
        ctx.channel().closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() {

            @Override
            public void operationComplete(Future<? super Void> future) throws Exception {
                isList.add(NettyInputStream.END_OF_INPUT_ERROR);
            }
        });
        requestContext.setEntityStream(new NettyInputStream(isList));
    } else {
        requestContext.setEntityStream(new InputStream() {

            @Override
            public int read() throws IOException {
                return -1;
            }
        });
    }
    // copying headers from netty request to jersey container request context.
    for (CharSequence name : http2Headers.headers().names()) {
        requestContext.headers(name.toString(), mapToString(http2Headers.headers().getAll(name)));
    }
    return requestContext;
}
Also used : HashMap(java.util.HashMap) NettyInputStream(org.glassfish.jersey.netty.connector.internal.NettyInputStream) ByteBufInputStream(io.netty.buffer.ByteBufInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) NettyInputStream(org.glassfish.jersey.netty.connector.internal.NettyInputStream) URI(java.net.URI) IOException(java.io.IOException) Collection(java.util.Collection) Future(io.netty.util.concurrent.Future) ContainerRequest(org.glassfish.jersey.server.ContainerRequest) PropertiesDelegate(org.glassfish.jersey.internal.PropertiesDelegate)

Example 7 with ContainerRequest

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

the class JerseyServerHandler method createContainerRequest.

/**
     * Create Jersey {@link ContainerRequest} based on Netty {@link HttpRequest}.
     *
     * @param ctx Netty channel context.
     * @param req Netty Http request.
     * @return created Jersey Container Request.
     */
private ContainerRequest createContainerRequest(ChannelHandlerContext ctx, HttpRequest req) {
    String s = req.uri().startsWith("/") ? req.uri().substring(1) : req.uri();
    URI requestUri = URI.create(baseUri + ContainerUtils.encodeUnsafeCharacters(s));
    ContainerRequest requestContext = new ContainerRequest(baseUri, requestUri, req.method().name(), getSecurityContext(), new PropertiesDelegate() {

        private final Map<String, Object> properties = new HashMap<>();

        @Override
        public Object getProperty(String name) {
            return properties.get(name);
        }

        @Override
        public Collection<String> getPropertyNames() {
            return properties.keySet();
        }

        @Override
        public void setProperty(String name, Object object) {
            properties.put(name, object);
        }

        @Override
        public void removeProperty(String name) {
            properties.remove(name);
        }
    });
    // request entity handling.
    if ((req.headers().contains(HttpHeaderNames.CONTENT_LENGTH) && HttpUtil.getContentLength(req) > 0) || HttpUtil.isTransferEncodingChunked(req)) {
        ctx.channel().closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() {

            @Override
            public void operationComplete(Future<? super Void> future) throws Exception {
                isList.add(NettyInputStream.END_OF_INPUT_ERROR);
            }
        });
        requestContext.setEntityStream(new NettyInputStream(isList));
    } else {
        requestContext.setEntityStream(new InputStream() {

            @Override
            public int read() throws IOException {
                return -1;
            }
        });
    }
    // copying headers from netty request to jersey container request context.
    for (String name : req.headers().names()) {
        requestContext.headers(name, req.headers().getAll(name));
    }
    return requestContext;
}
Also used : HashMap(java.util.HashMap) ByteBufInputStream(io.netty.buffer.ByteBufInputStream) NettyInputStream(org.glassfish.jersey.netty.connector.internal.NettyInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) NettyInputStream(org.glassfish.jersey.netty.connector.internal.NettyInputStream) URI(java.net.URI) IOException(java.io.IOException) Collection(java.util.Collection) Future(io.netty.util.concurrent.Future) ContainerRequest(org.glassfish.jersey.server.ContainerRequest) PropertiesDelegate(org.glassfish.jersey.internal.PropertiesDelegate)

Example 8 with ContainerRequest

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

the class JerseyServerHandler method channelRead.

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        final HttpRequest req = (HttpRequest) msg;
        if (HttpUtil.is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE));
        }
        // clearing the content - possible leftover from previous request processing.
        isList.clear();
        final ContainerRequest requestContext = createContainerRequest(ctx, req);
        requestContext.setWriter(new NettyResponseWriter(ctx, req, container));
        // must be like this, since there is a blocking read from Jersey
        container.getExecutorService().execute(new Runnable() {

            @Override
            public void run() {
                container.getApplicationHandler().handle(requestContext);
            }
        });
    }
    if (msg instanceof HttpContent) {
        HttpContent httpContent = (HttpContent) msg;
        ByteBuf content = httpContent.content();
        if (content.isReadable()) {
            isList.add(new ByteBufInputStream(content));
        }
        if (msg instanceof LastHttpContent) {
            isList.add(NettyInputStream.END_OF_INPUT);
        }
    }
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) ContainerRequest(org.glassfish.jersey.server.ContainerRequest) ByteBufInputStream(io.netty.buffer.ByteBufInputStream) ByteBuf(io.netty.buffer.ByteBuf) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HttpContent(io.netty.handler.codec.http.HttpContent)

Example 9 with ContainerRequest

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

the class HttpMethodOverrideFilter method filter.

@Override
public void filter(final ContainerRequestContext request) {
    if (!request.getMethod().equalsIgnoreCase("POST")) {
        return;
    }
    final String header = getParamValue(Source.HEADER, request.getHeaders(), "X-HTTP-Method-Override");
    final String query = getParamValue(Source.QUERY, request.getUriInfo().getQueryParameters(), "_method");
    final String override;
    if (header == null) {
        override = query;
    } else {
        override = header;
        if (query != null && !query.equals(header)) {
            // inconsistent query and header param values
            throw new BadRequestException();
        }
    }
    if (override != null) {
        request.setMethod(override);
        if (override.equals("GET")) {
            if (request.getMediaType() != null && MediaType.APPLICATION_FORM_URLENCODED_TYPE.getType().equals(request.getMediaType().getType())) {
                final UriBuilder ub = request.getUriInfo().getRequestUriBuilder();
                final Form f = ((ContainerRequest) request).readEntity(Form.class);
                for (final Map.Entry<String, List<String>> param : f.asMap().entrySet()) {
                    ub.queryParam(param.getKey(), param.getValue().toArray());
                }
                request.setRequestUri(request.getUriInfo().getBaseUri(), ub.build());
            }
        }
    }
}
Also used : Form(javax.ws.rs.core.Form) BadRequestException(javax.ws.rs.BadRequestException) ContainerRequest(org.glassfish.jersey.server.ContainerRequest) List(java.util.List) UriBuilder(javax.ws.rs.core.UriBuilder) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Map(java.util.Map)

Example 10 with ContainerRequest

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

the class ParameterInjectionBinder method configure.

@Override
public void configure() {
    // Param converter providers
    // TODO: Replace by non-di version
    bind(new ParamConverters.AggregatedProvider()).to(ParamConverterProvider.class);
    Provider<ContainerRequest> requestProvider = Injections.getProvider(injectionManager, ContainerRequest.class);
    Provider<AsyncContext> asyncContextProvider = Injections.getProvider(injectionManager, AsyncContext.class);
    Function<Class<? extends Configuration>, Configuration> clientConfigProvider = clientConfigClass -> Injections.getOrCreate(injectionManager, clientConfigClass);
    // Param Converters must be initialized Lazy and created at the time of the call on extractor
    LazyValue<ParamConverterFactory> lazyParamConverterFactory = Values.lazy((Value<ParamConverterFactory>) () -> new ParamConverterFactory(Providers.getProviders(injectionManager, ParamConverterProvider.class), Providers.getCustomProviders(injectionManager, ParamConverterProvider.class)));
    LazyValue<Configuration> lazyConfiguration = Values.lazy((Value<Configuration>) () -> injectionManager.getInstance(Configuration.class));
    MultivaluedParameterExtractorFactory paramExtractor = new MultivaluedParameterExtractorFactory(lazyParamConverterFactory);
    bind(paramExtractor).to(MultivaluedParameterExtractorProvider.class);
    // Parameter injection value providers
    AsyncResponseValueSupplierProvider asyncSupplier = new AsyncResponseValueSupplierProvider(asyncContextProvider);
    bindValueSupplier(asyncSupplier);
    CookieParamValueSupplierProvider cookieSupplier = new CookieParamValueSupplierProvider(paramExtractor, requestProvider);
    bindValueSupplier(cookieSupplier);
    EntityParamValueSupplierProvider entitySupplier = new EntityParamValueSupplierProvider(paramExtractor, requestProvider);
    bindValueSupplier(entitySupplier);
    FormParamValueSupplierProvider formSupplier = new FormParamValueSupplierProvider(paramExtractor, requestProvider);
    bindValueSupplier(formSupplier);
    HeaderParamValueSupplierProvider headerSupplier = new HeaderParamValueSupplierProvider(paramExtractor, requestProvider);
    bindValueSupplier(headerSupplier);
    MatrixParamValueSupplierProvider matrixSupplier = new MatrixParamValueSupplierProvider(paramExtractor, requestProvider);
    bindValueSupplier(matrixSupplier);
    PathParamValueSupplierProvider pathSupplier = new PathParamValueSupplierProvider(paramExtractor, requestProvider);
    bindValueSupplier(pathSupplier);
    QueryParamValueSupplierProvider querySupplier = new QueryParamValueSupplierProvider(paramExtractor, requestProvider);
    bindValueSupplier(querySupplier);
    WebTargetValueSupplierProvider webTargetSupplier = new WebTargetValueSupplierProvider(requestProvider, lazyConfiguration, clientConfigProvider);
    bindValueSupplier(webTargetSupplier);
    BeanParamValueSupplierProvider beanSupplier = new BeanParamValueSupplierProvider(paramExtractor, requestProvider, injectionManager);
    bindValueSupplier(beanSupplier);
    // Register InjectionResolvers with param providers
    // TODO: RENAME INJECTION RESOLVER
    bind(new ParamInjectionResolver<>(cookieSupplier, CookieParam.class));
    bind(new ParamInjectionResolver<>(formSupplier, FormParam.class));
    bind(new ParamInjectionResolver<>(headerSupplier, HeaderParam.class));
    bind(new ParamInjectionResolver<>(matrixSupplier, MatrixParam.class));
    bind(new ParamInjectionResolver<>(querySupplier, QueryParam.class));
    bind(new ParamInjectionResolver<>(pathSupplier, PathParam.class));
    bind(new ParamInjectionResolver<>(asyncSupplier, Suspended.class));
    bind(new ParamInjectionResolver<>(webTargetSupplier, Uri.class));
    bind(new ParamInjectionResolver<>(beanSupplier, BeanParam.class));
    // Delegated value supplier for Context InjectionResolver which is implemented directly in DI provider
    ContextInjectionResolver contextInjectionResolver = injectionManager.getInstance(ContextInjectionResolver.class);
    bind(new DelegatedInjectionValueSupplierProvider(contextInjectionResolver, injectionManager::createForeignDescriptor)).to(ValueSupplierProvider.class);
}
Also used : FormParam(javax.ws.rs.FormParam) ContextInjectionResolver(org.glassfish.jersey.internal.inject.ContextInjectionResolver) PathParam(javax.ws.rs.PathParam) Provider(javax.inject.Provider) Configuration(javax.ws.rs.core.Configuration) AsyncContext(org.glassfish.jersey.server.internal.process.AsyncContext) AbstractBinder(org.glassfish.jersey.internal.inject.AbstractBinder) Providers(org.glassfish.jersey.internal.inject.Providers) ContainerRequest(org.glassfish.jersey.server.ContainerRequest) Function(java.util.function.Function) Suspended(javax.ws.rs.container.Suspended) InjectionManager(org.glassfish.jersey.internal.inject.InjectionManager) Uri(org.glassfish.jersey.server.Uri) BeanParam(javax.ws.rs.BeanParam) QueryParam(javax.ws.rs.QueryParam) Value(org.glassfish.jersey.internal.util.collection.Value) MatrixParam(javax.ws.rs.MatrixParam) LazyValue(org.glassfish.jersey.internal.util.collection.LazyValue) ValueSupplierProvider(org.glassfish.jersey.server.spi.internal.ValueSupplierProvider) HeaderParam(javax.ws.rs.HeaderParam) ParamConverterProvider(javax.ws.rs.ext.ParamConverterProvider) CookieParam(javax.ws.rs.CookieParam) Injections(org.glassfish.jersey.internal.inject.Injections) Values(org.glassfish.jersey.internal.util.collection.Values) HeaderParam(javax.ws.rs.HeaderParam) MatrixParam(javax.ws.rs.MatrixParam) Configuration(javax.ws.rs.core.Configuration) AsyncContext(org.glassfish.jersey.server.internal.process.AsyncContext) Uri(org.glassfish.jersey.server.Uri) ParamConverterProvider(javax.ws.rs.ext.ParamConverterProvider) ContainerRequest(org.glassfish.jersey.server.ContainerRequest) PathParam(javax.ws.rs.PathParam) Suspended(javax.ws.rs.container.Suspended) ContextInjectionResolver(org.glassfish.jersey.internal.inject.ContextInjectionResolver) BeanParam(javax.ws.rs.BeanParam) CookieParam(javax.ws.rs.CookieParam) QueryParam(javax.ws.rs.QueryParam) FormParam(javax.ws.rs.FormParam)

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