org.glassfish.jersey.internal.MapPropertiesDelegate Java Examples

The following examples show how to use org.glassfish.jersey.internal.MapPropertiesDelegate. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JRestlessHandlerContainer.java    From jrestless with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new {@link ContainerRequest} for the given input.
 *
 * @param request
 * @param containerResponseWriter
 * @param securityContext
 * @return
 */
@Nonnull
protected ContainerRequest createContainerRequest(@Nonnull RequestT request,
		@Nonnull ContainerResponseWriter containerResponseWriter, @Nonnull SecurityContext securityContext) {
	requireNonNull(request, "request may not be null");
	URI baseUri = request.getBaseUri();
	URI requestUri = requireNonNull(request.getRequestUri(), "request.getRequestUri() may not be null");
	String httpMethod = requireNonNull(request.getHttpMethod(), "request.getHttpMethod() may not be null");
	InputStream entityStream = requireNonNull(request.getEntityStream(),
			"request.getEntityStream() may not be null");
	Map<String, List<String>> headers = requireNonNull(request.getHeaders(),
			"request.getHeaderParams() may not be null");
	requireNonNull(containerResponseWriter, "containerResponseWriter may not be null");
	requireNonNull(securityContext, "securityContext may not be null");

	ContainerRequest requestContext = new ContainerRequest(baseUri, requestUri, httpMethod, securityContext,
			new MapPropertiesDelegate());
	requestContext.setEntityStream(entityStream);
	requestContext.getHeaders().putAll(headers);
	requestContext.setWriter(containerResponseWriter);

	return requestContext;
}
 
Example #2
Source File: NettyRestHandlerContainer.java    From tajo with Apache License 2.0 6 votes vote down vote up
protected void messageReceived(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
  URI baseUri = getBaseUri(ctx, request);
  URI requestUri = baseUri.resolve(request.getUri());
  ByteBuf responseContent = PooledByteBufAllocator.DEFAULT.buffer();
  FullHttpResponse response = 
      new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, responseContent);
  
  NettyRestResponseWriter responseWriter = new NettyRestResponseWriter(ctx, response);
  ContainerRequest containerRequest = new ContainerRequest(baseUri, requestUri, 
      request.getMethod().name(), getSecurityContext(), new MapPropertiesDelegate());
  containerRequest.setEntityStream(new ByteBufInputStream(request.content()));
  
  HttpHeaders httpHeaders = request.headers();
  for (String headerName: httpHeaders.names()) {
    List<String> headerValues = httpHeaders.getAll(headerName);
    containerRequest.headers(headerName, headerValues);
  }
  containerRequest.setWriter(responseWriter);
  try {
    applicationHandler.handle(containerRequest);
  } finally {
    responseWriter.releaseConnection();
  }
}
 
Example #3
Source File: RxBodyWriterTest.java    From rx-jersey with MIT License 5 votes vote down vote up
private OutputStream testWriteTo(String methodName, MediaType mediaType, Object entity, OutputStream outputStream) throws NoSuchMethodException, IOException {

        final MessageBodyFactory messageBodyFactory = injectionManager.getInstance(MessageBodyFactory.class);

        final Method textMethod = TestResource.class.getMethod(methodName);
        final Type genericReturnType = textMethod.getGenericReturnType();
        final Annotation[] annotations = textMethod.getDeclaredAnnotations();

        final MultivaluedHashMap<String, Object> headers = new MultivaluedHashMap<>(
                Collections.singletonMap(HttpHeaders.CONTENT_TYPE, Collections.singletonList(mediaType))
        );

        return messageBodyFactory.writeTo(entity, entity.getClass(), genericReturnType, annotations, mediaType, headers,
                new MapPropertiesDelegate(), outputStream, Collections.emptyList());
    }
 
Example #4
Source File: StructuredEventFilterTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private ContainerRequest createRequestContext(MultivaluedMap<String, String> headersMap) {
    MapPropertiesDelegate propertiesDelegate = new MapPropertiesDelegate();
    ContainerRequest requestContext =
            new ContainerRequest(URI.create("http://localhost"), URI.create("/test/endpoint"), "PUT", securityContext, propertiesDelegate);
    requestContext.headers(headersMap);
    return requestContext;
}
 
Example #5
Source File: Router.java    From minnal with Apache License 2.0 5 votes vote down vote up
/**
	 * Creates the container request from the http request
	 *  
	 * @param httpRequest
	 * @return
	 */
	protected ContainerRequest createContainerRequest(MessageContext context) {
		Application<ApplicationConfiguration> application = context.getApplication();
		FullHttpRequest httpRequest = context.getRequest();
		URI baseUri = URI.create(context.getBaseUri().resolve(application.getPath()) + "/");
		URI requestUri = HttpUtil.createURI(httpRequest.getUri());
		ContainerRequest containerRequest = new ContainerRequest(baseUri, requestUri, httpRequest.getMethod().name(), null, new MapPropertiesDelegate());
//		containerRequest.setProperty(REQUEST_PROPERTY_REMOTE_ADDR, context.getRequest().channel().remoteAddress());
		containerRequest.setEntityStream(new ByteBufInputStream(httpRequest.content()));
		
        for (Map.Entry<String, String> headerEntry : httpRequest.headers()) {
        	containerRequest.getHeaders().add(headerEntry.getKey(), headerEntry.getValue());
        }
        return containerRequest;
	}
 
Example #6
Source File: HttpHandlerContainer.java    From metrics with Apache License 2.0 4 votes vote down vote up
@Override
public void handle(final HttpExchange exchange) throws IOException {
    /**
     * This is a URI that contains the path, query and fragment components.
     */
    URI exchangeUri = exchange.getRequestURI();

    /**
     * The base path specified by the HTTP context of the HTTP handler. It
     * is in decoded form.
     */
    String decodedBasePath = exchange.getHttpContext().getPath();

    // Ensure that the base path ends with a '/'
    if (!decodedBasePath.endsWith("/")) {
        if (decodedBasePath.equals(exchangeUri.getPath())) {
            /**
             * This is an edge case where the request path does not end in a
             * '/' and is equal to the context path of the HTTP handler.
             * Both the request path and base path need to end in a '/'
             * Currently the request path is modified.
             *
             * TODO support redirection in accordance with resource configuration feature.
             */
            exchangeUri = UriBuilder.fromUri(exchangeUri)
                    .path("/").build();
        }
        decodedBasePath += "/";
    }

    /*
     * The following is madness, there is no easy way to get the complete
     * URI of the HTTP request!!
     *
     * TODO this is missing the user information component, how can this be obtained?
     */
    final boolean isSecure = exchange instanceof HttpsExchange;
    final String scheme = isSecure ? "https" : "http";

    final URI baseUri = getBaseUri(exchange, decodedBasePath, scheme);
    final URI requestUri = getRequestUri(exchange, baseUri);

    final ResponseWriter responseWriter = new ResponseWriter(exchange);
    final ContainerRequest requestContext = new ContainerRequest(baseUri, requestUri,
            exchange.getRequestMethod(), getSecurityContext(exchange.getPrincipal(), isSecure),
            new MapPropertiesDelegate());
    requestContext.setEntityStream(exchange.getRequestBody());
    requestContext.getHeaders().putAll(exchange.getRequestHeaders());
    requestContext.setWriter(responseWriter);
    try {
        appHandler.handle(requestContext);
    } catch (Exception e) {
        LOGGER.log(Level.WARNING, "Error handling request: ", e);
    } finally {
        // if the response was not committed yet by the JerseyApplication
        // then commit it and log warning
        responseWriter.closeAndLogWarning();
    }
}
 
Example #7
Source File: DefaultJerseyStreamingHttpRouter.java    From servicetalk with Apache License 2.0 4 votes vote down vote up
private void handle0(final HttpServiceContext serviceCtx, final StreamingHttpRequest req,
                     final StreamingHttpResponseFactory factory,
                     final Subscriber<? super StreamingHttpResponse> subscriber,
                     final DelayedCancellable delayedCancellable) {

    final CharSequence baseUri = baseUriFunction.apply(serviceCtx, req);
    final CharSequence path = ensureNoLeadingSlash(req.rawPath());

    // Jersey needs URI-unsafe query chars to be encoded
    @Nullable
    final String encodedQuery = req.rawQuery().isEmpty() ? null : encodeUnsafeCharacters(req.rawQuery());

    final StringBuilder requestUriBuilder =
            new StringBuilder(baseUri.length() + path.length() +
                    (encodedQuery != null ? 1 + encodedQuery.length() : 0))
                    .append(baseUri)
                    .append(path);

    if (encodedQuery != null) {
        requestUriBuilder.append('?').append(encodedQuery);
    }

    final ContainerRequest containerRequest = new ContainerRequest(
            URI.create(baseUri.toString()),
            URI.create(requestUriBuilder.toString()),
            req.method().name(),
            UNAUTHENTICATED_SECURITY_CONTEXT,
            new MapPropertiesDelegate());

    req.headers().forEach(h ->
            containerRequest.getHeaders().add(h.getKey().toString(), h.getValue().toString()));

    final BufferPublisherInputStream entityStream = new BufferPublisherInputStream(req.payloadBody(),
            publisherInputStreamQueueCapacity);
    containerRequest.setEntityStream(entityStream);
    initRequestProperties(entityStream, containerRequest);

    final DefaultContainerResponseWriter responseWriter = new DefaultContainerResponseWriter(containerRequest,
            req.version(), serviceCtx, factory, subscriber);

    containerRequest.setWriter(responseWriter);

    containerRequest.setRequestScopedInitializer(injectionManager -> {
        injectionManager.<Ref<ConnectionContext>>getInstance(CONNECTION_CONTEXT_REF_TYPE).set(serviceCtx);
        injectionManager.<Ref<StreamingHttpRequest>>getInstance(HTTP_REQUEST_REF_TYPE).set(req);
    });

    delayedCancellable.delayedCancellable(responseWriter::dispose);

    applicationHandler.handle(containerRequest);
}
 
Example #8
Source File: JerseyHandlerFilter.java    From aws-serverless-java-container with Apache License 2.0 4 votes vote down vote up
/**
 * Given a ServletRequest generates the corresponding Jersey ContainerRequest object. The request URI is
 * built from the request's <code>getPathInfo()</code> method. The container request also contains the
 * API Gateway context, stage variables, and Lambda context properties. The original servlet request is
 * also embedded in a property of the container request to allow injection by the
 * {@link AwsProxyServletRequestSupplier}.
 * @param request The incoming servlet request
 * @return A populated ContainerRequest object.
 * @throws RuntimeException if we could not read the servlet request input stream.
 */
// suppressing warnings because I expect headers and query strings to be checked by the underlying
// servlet implementation
@SuppressFBWarnings({ "SERVLET_HEADER", "SERVLET_QUERY_STRING" })
private ContainerRequest servletRequestToContainerRequest(ServletRequest request) {
    Timer.start("JERSEY_SERVLET_REQUEST_TO_CONTAINER");
    HttpServletRequest servletRequest = (HttpServletRequest)request;

    if (baseUri == null) {
        baseUri = getBaseUri(request, "/");
    }

    String requestFullPath = servletRequest.getRequestURI();
    if (LambdaContainerHandler.getContainerConfig().getServiceBasePath() != null && LambdaContainerHandler.getContainerConfig().isStripBasePath()) {
        if (requestFullPath.startsWith(LambdaContainerHandler.getContainerConfig().getServiceBasePath())) {
            requestFullPath = requestFullPath.replaceFirst(LambdaContainerHandler.getContainerConfig().getServiceBasePath(), "");
            if (!requestFullPath.startsWith("/")) {
                requestFullPath = "/" + requestFullPath;
            }
        }
    }
    UriBuilder uriBuilder = UriBuilder.fromUri(baseUri).path(requestFullPath);
    uriBuilder.replaceQuery(servletRequest.getQueryString());

    PropertiesDelegate apiGatewayProperties = new MapPropertiesDelegate();
    apiGatewayProperties.setProperty(API_GATEWAY_CONTEXT_PROPERTY, servletRequest.getAttribute(API_GATEWAY_CONTEXT_PROPERTY));
    apiGatewayProperties.setProperty(API_GATEWAY_STAGE_VARS_PROPERTY, servletRequest.getAttribute(API_GATEWAY_STAGE_VARS_PROPERTY));
    apiGatewayProperties.setProperty(LAMBDA_CONTEXT_PROPERTY, servletRequest.getAttribute(LAMBDA_CONTEXT_PROPERTY));
    apiGatewayProperties.setProperty(JERSEY_SERVLET_REQUEST_PROPERTY, servletRequest);

    ContainerRequest requestContext = new ContainerRequest(
            null, // jersey uses "/" by default
            uriBuilder.build(),
            servletRequest.getMethod().toUpperCase(Locale.ENGLISH),
            (SecurityContext)servletRequest.getAttribute(JAX_SECURITY_CONTEXT_PROPERTY),
            apiGatewayProperties);

    InputStream requestInputStream;
    try {
        requestInputStream = servletRequest.getInputStream();
        if (requestInputStream != null) {
            requestContext.setEntityStream(requestInputStream);
        }
    } catch (IOException e) {
        log.error("Could not read input stream from request", e);
        throw new RuntimeException("Could not read request input stream", e);
    }

    Enumeration<String> headerNames = servletRequest.getHeaderNames();

    while (headerNames.hasMoreElements()) {
        String headerKey = headerNames.nextElement();
        requestContext.getHeaders().addAll(headerKey, Collections.list(servletRequest.getHeaders(headerKey)));
    }

    Timer.stop("JERSEY_SERVLET_REQUEST_TO_CONTAINER");
    return requestContext;
}
 
Example #9
Source File: BaseResourceTest.java    From minnal with Apache License 2.0 4 votes vote down vote up
public ContainerRequest request(String uri, String method, String content, MediaType contentType, Map<String, String> headers) {
    return createContainerRequest(URI.create(""), URI.create(uri), method, content, headers,
            null, new MapPropertiesDelegate());
}