private static ContainerRequest ensureValidRequest(final ContainerRequest request)
        throws IllegalStateException {
      if (request.getMethod().equals("GET")) {
        throw new IllegalStateException(LocalizationMessages.FORM_PARAM_METHOD_ERROR());
      }

      if (!MediaTypes.typeEqual(
          MediaType.APPLICATION_FORM_URLENCODED_TYPE, request.getMediaType())) {
        throw new IllegalStateException(LocalizationMessages.FORM_PARAM_CONTENT_TYPE_ERROR());
      }
      return request;
    }
  /**
   * Invokes a request and returns the {@link Future response future}.
   *
   * @param request request data.
   * @param outputStream response output stream.
   * @return response future.
   */
  public Future<ContainerResponse> apply(
      final ContainerRequest request, final OutputStream outputStream) {
    final FutureResponseWriter responseFuture =
        new FutureResponseWriter(request.getMethod(), outputStream);

    request.setSecurityContext(DEFAULT_SECURITY_CONTEXT);
    request.setWriter(responseFuture);

    handle(request);

    return responseFuture;
  }
 private static Form getCachedForm(final ContainerRequest request, boolean decode) {
   return (Form)
       request.getProperty(
           decode
               ? InternalServerProperties.FORM_DECODED_PROPERTY
               : InternalServerProperties.FORM_PROPERTY);
 }
 private void cacheForm(final ContainerRequest request, final Form form) {
   request.setProperty(
       decode
           ? InternalServerProperties.FORM_DECODED_PROPERTY
           : InternalServerProperties.FORM_PROPERTY,
       form);
 }
  @Override
  public ContainerResponse apply(final ContainerRequest requestContext) {
    final Object resource = routingContextFactory.get().peekMatchedResource();

    final ProcessingContext processingCtx = invocationContextFactory.get();
    if (method.isSuspendDeclared()) {
      processingCtx.setSuspendTimeout(method.getSuspendTimeout(), method.getSuspendTimeoutUnit());
    }
    requestContext.setProperty(ReaderInterceptorExecutor.INTERCEPTORS, getReaderInterceptors());
    requestContext.setProperty(WriterInterceptorExecutor.INTERCEPTORS, getWriterInterceptors());
    final Response response = dispatcher.dispatch(resource, requestContext);

    if (method.isSuspendDeclared()) {
      processingCtx.setResponse(resource);
      processingCtx.trySuspend();
    }

    final ContainerResponse responseContext = new ContainerResponse(requestContext, response);
    final Invocable invocable = method.getInvocable();
    responseContext.setEntityAnnotations(invocable.getHandlingMethod().getDeclaredAnnotations());

    if (responseContext.hasEntity()
        && !(responseContext.getEntityType() instanceof ParameterizedType)) {
      Type invocableType = invocable.getResponseType();
      if (invocableType != null
          && Void.TYPE != invocableType
          && Void.class != invocableType
          && invocableType != Response.class) {
        responseContext.setEntityType(invocableType);
      }
    }

    return responseContext;
  }
Beispiel #6
0
 private ContainerRequest createContainerRequest(
     URI baseUri,
     URI requestUri,
     String method,
     String content,
     Map<String, String> headers,
     SecurityContext securityContext,
     PropertiesDelegate propertiesDelegate) {
   URI uri = URI.create(baseUri.getPath() + "/");
   ContainerRequest containerRequest =
       new ContainerRequest(uri, requestUri, method, securityContext, propertiesDelegate);
   containerRequest.setEntityStream(new ByteArrayInputStream(content.getBytes()));
   for (Map.Entry<String, String> headerEntry : headers.entrySet()) {
     containerRequest.getHeaders().add(headerEntry.getKey(), headerEntry.getValue());
   }
   return containerRequest;
 }
    private Form getFormParameters(ContainerRequest request) {
      if (MediaTypes.typeEqual(
          MediaType.APPLICATION_FORM_URLENCODED_TYPE, request.getMediaType())) {
        request.bufferEntity();
        Form form;
        if (decode) {
          form = request.readEntity(Form.class);
        } else {
          Annotation[] annotations = new Annotation[1];
          annotations[0] = encodedAnnotation;
          form = request.readEntity(Form.class, annotations);
        }

        return (form == null ? new Form() : form);
      } else {
        return new Form();
      }
    }
    @Override
    public Object provide() {
      final ContainerRequest requestContext = getContainerRequest();

      final Class<?> rawType = parameter.getRawType();

      Object value;
      if ((Request.class.isAssignableFrom(rawType)
              || ContainerRequestContext.class.isAssignableFrom(rawType))
          && rawType.isInstance(requestContext)) {
        value = requestContext;
      } else {
        value = requestContext.readEntity(rawType, parameter.getType(), parameter.getAnnotations());
        if (rawType.isPrimitive() && value == null) {
          throw new BadRequestException(
              Response.status(Response.Status.BAD_REQUEST)
                  .entity(LocalizationMessages.ERROR_PRIMITIVE_TYPE_NULL())
                  .build());
        }
      }
      return value;
    }
 @Override
 public void cancelled() {
   synchronized (stateUpdateLock) {
     if (done) {
       return;
     }
     done = timeoutCancelled = true;
   }
   try {
     requestContext.getResponseWriter().cancel();
   } finally {
     release();
   }
 }
Beispiel #10
0
 public ContainerResponse call(ContainerRequest containerRequest) {
   ByteBuffer byteBuf = ByteBuffer.allocate(BUFFER_CAPACITY);
   ContainerResponse response;
   try {
     response = handler.apply(containerRequest, new ByteBufferOutputStream(byteBuf)).get();
   } catch (Exception e) {
     logger.debug("Failed while handling the request - " + containerRequest, e);
     response = new ContainerResponse(containerRequest, Response.serverError().build());
   }
   ContainerResponseWriter responseWriter = containerRequest.getResponseWriter();
   OutputStream os = responseWriter.writeResponseStatusAndHeaders(response.getLength(), response);
   response.setEntityStream(os);
   return response;
 }
  /**
   * Suspend the container response writer.
   *
   * <p>This method is always executed from within a synchronized block.
   *
   * @param time suspend timeout value.
   * @param unit suspend timeout time unit.
   */
  private void suspendWriter(final long time, final TimeUnit unit) {
    requestContext
        .getResponseWriter()
        .suspend(
            time,
            unit,
            new ContainerResponseWriter.TimeoutHandler() {

              @Override
              public void onTimeout(ContainerResponseWriter responseWriter) {
                synchronized (stateUpdateLock) {
                  if (timeoutCancelled || done) {
                    return;
                  }
                  done = true;
                }
                writeTimeoutResponse(invocationContext);
              }
            });
    suspended = true;
  }
    private Form switchUrlEncoding(final ContainerRequest request, final Form otherForm) {
      final Set<Map.Entry<String, List<String>>> entries = otherForm.asMap().entrySet();

      MultivaluedMap<String, String> formMap = new NullableMultivaluedHashMap<>();
      for (Map.Entry<String, List<String>> entry : entries) {
        final String charsetName =
            ReaderWriter.getCharset(
                    MediaType.valueOf(request.getHeaderString(HttpHeaders.CONTENT_TYPE)))
                .name();

        String key;
        try {
          key =
              decode
                  ? URLDecoder.decode(entry.getKey(), charsetName)
                  : URLEncoder.encode(entry.getKey(), charsetName);

          for (String value : entry.getValue()) {
            if (value != null) {
              formMap.add(
                  key,
                  decode
                      ? URLDecoder.decode(value, charsetName)
                      : URLEncoder.encode(value, charsetName));
            } else {
              formMap.add(key, null);
            }
          }

        } catch (UnsupportedEncodingException uee) {
          throw new ProcessingException(
              LocalizationMessages.ERROR_UNSUPPORTED_ENCODING(charsetName, extractor.getName()),
              uee);
        }
      }
      return new Form(formMap);
    }
 @Override
 public void suspendTimeoutChanged(long time, TimeUnit unit) {
   requestContext.getResponseWriter().setSuspendTimeout(time, unit);
 }