public ResourceInvoker getInvoker(HttpRequest request) throws Failure {
   logger.debug("PathInfo: " + request.getUri().getPath());
   if (!request.isInitial()) {
     throw new InternalServerErrorException(
         request.getUri().getPath()
             + " is not initial request.  Its suspended and retried.  Aborting.");
   }
   ResourceInvoker invoker = registry.getResourceInvoker(request);
   if (invoker == null) {
     throw new NotFoundException(
         "Unable to find JAX-RS resource associated with path: " + request.getUri().getPath());
   }
   return invoker;
 }
示例#2
0
  public BuiltResponse invoke(HttpRequest request, HttpResponse response, Object target) {
    request.setAttribute(ResourceMethod.class.getName(), this);
    incrementMethodCount(request.getHttpMethod());
    ResteasyUriInfo uriInfo = (ResteasyUriInfo) request.getUri();
    uriInfo.pushCurrentResource(target);
    try {
      BuiltResponse jaxrsResponse = invokeOnTarget(request, response, target);

      if (jaxrsResponse != null && jaxrsResponse.getEntity() != null) {
        // if the content type isn't set, then set it to be either most desired type from the Accept
        // header
        // or the first media type in the @Produces annotation
        // See RESTEASY-144
        Object type = jaxrsResponse.getMetadata().getFirst(HttpHeaderNames.CONTENT_TYPE);
        if (type == null)
          jaxrsResponse
              .getMetadata()
              .putSingle(
                  HttpHeaderNames.CONTENT_TYPE,
                  resolveContentType(request, jaxrsResponse.getEntity()));
      }
      return jaxrsResponse;

    } finally {
      uriInfo.popCurrentResource();
    }
  }
 public HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
   ResteasyRequestWrapper requestWrapper =
       RequestUtil.getRequestWrapper(request, request.getMethod(), prefix);
   try {
     // NOTE: if invoker isn't found, RESTEasy throw NoReourceFoundFailure
     HttpRequest httpRequest = requestWrapper.getHttpRequest();
     if (!httpRequest.isInitial()) {
       String message =
           httpRequest.getUri().getPath()
               + " is not initial request.  Its suspended and retried.  Aborting.";
       logger.error(message);
       requestWrapper.setError(500, message);
     } else {
       Response response = dispatcher.preprocess(httpRequest);
       if (response != null) {
         requestWrapper.setAbortedResponse(response);
       } else {
         requestWrapper.setInvoker(getInvoker(httpRequest));
       }
     }
     return new HandlerExecutionChain(requestWrapper, interceptors);
   } catch (NotFoundException e) {
     if (throwNotFound) {
       throw e;
     }
     logger.error("Resource Not Found: " + e.getMessage(), e);
   } catch (Failure e) {
     logger.error("ResourceFailure: " + e.getMessage(), e);
     throw e;
   }
   return null;
 }
  public void handleException(HttpRequest request, HttpResponse response, Throwable e) {
    // See if there is an ExceptionMapper for the exact class of the exception instance being thrown
    if (executeExactExceptionMapper(request, response, e)) return;

    // These are wrapper exceptions so they need to be processed first as they map e.getCause()
    if (e instanceof ApplicationException) {
      handleApplicationException(request, response, (ApplicationException) e);
      return;
    } else if (e instanceof WriterException) {
      handleWriterException(request, response, (WriterException) e);
      return;
    } else if (e instanceof ReaderException) {
      handleReaderException(request, response, (ReaderException) e);
      return;
    }

    // First try and handle it with a mapper
    if (executeExceptionMapper(request, response, e)) {
      return;
    }
    // Otherwise do specific things
    else if (e instanceof WebApplicationException) {
      handleWebApplicationException(request, response, (WebApplicationException) e);
    } else if (e instanceof Failure) {
      handleFailure(request, response, (Failure) e);
    } else {
      logger.error(
          "Unknown exception while executing "
              + request.getHttpMethod()
              + " "
              + request.getUri().getPath(),
          e);
      throw new UnhandledException(e);
    }
  }
 public static MockHttpRequest deepCopy(HttpRequest request) throws IOException {
   MockHttpRequest mock = new MockHttpRequest();
   mock.uri = request.getUri();
   mock.httpHeaders = (ResteasyHttpHeaders) request.getHttpHeaders();
   mock.httpMethod = request.getHttpMethod();
   byte[] bytes = ReadFromStream.readFromStream(1024, request.getInputStream());
   mock.inputStream = new ByteArrayInputStream(bytes);
   return mock;
 }
 public BuiltResponse invoke(HttpRequest request, HttpResponse response, Object target) {
   request.setAttribute(ResourceMethodInvoker.class.getName(), this);
   incrementMethodCount(request.getHttpMethod());
   ResteasyUriInfo uriInfo = (ResteasyUriInfo) request.getUri();
   if (method.getPath() != null) {
     uriInfo.pushMatchedURI(uriInfo.getMatchingPath());
   }
   uriInfo.pushCurrentResource(target);
   BuiltResponse rtn = invokeOnTarget(request, response, target);
   return rtn;
 }
  public void pushContextObjects(HttpRequest request, HttpResponse response) {
    Map contextDataMap = ResteasyProviderFactory.getContextDataMap();
    contextDataMap.put(HttpRequest.class, request);
    contextDataMap.put(HttpResponse.class, response);
    contextDataMap.put(HttpHeaders.class, request.getHttpHeaders());
    contextDataMap.put(UriInfo.class, request.getUri());
    contextDataMap.put(Request.class, new RequestImpl(request));
    contextDataMap.put(ResteasyAsynchronousContext.class, request.getAsyncContext());

    contextDataMap.putAll(defaultContextObjects);
  }
  public ServerResponse preProcess(HttpRequest request, ResourceMethod method)
      throws Failure, WebApplicationException {
    ServerResponse response = null;
    Long requestId = RequestLogger.getInstance().getLogger().getRequestId();
    logger.info("Request Interceptor: Processing request #%d", requestId);

    List<NameValuePair> params = URLEncodedUtils.parse(request.getUri().getRequestUri(), "UTF-8");

    // Handle paging parameters.
    processPaging(request, params, requestId);
    return response;
  }
示例#9
0
  /**
   * Interrogates the request and sets the principal for the request.
   *
   * @throws WebApplicationException when no auths result in a valid principal
   * @throws Failure when there is an unkown failure in the code
   * @return the Server Response
   */
  public ServerResponse preProcess(HttpRequest request, ResourceMethod method)
      throws Failure, WebApplicationException {

    SecurityHole securityHole = AuthUtil.checkForSecurityHoleAnnotation(method.getMethod());

    Principal principal = null;

    if (log.isDebugEnabled()) {
      log.debug("Authentication check for " + request.getUri().getPath());
    }

    // Check for anonymous calls, and let them through
    if (securityHole != null && securityHole.anon()) {
      log.debug("Request is anonymous, adding NoAuth Principal");
      principal = new NoAuthPrincipal();
    } else {
      // This method is not anonymous, so attempt to
      // establish the identity.
      for (AuthProvider provider : providers) {
        principal = provider.getPrincipal(request);

        if (principal != null) {
          break;
        }
      }
    }

    // At this point, there is no provider that has given a valid principal,
    // so we use the NoAuthPrincipal here if it is set.
    if (principal == null) {
      if (securityHole != null && securityHole.noAuth()) {
        log.debug("No auth allowed for resource; setting NoAuth principal");
        principal = new NoAuthPrincipal();
      } else {
        throw new UnauthorizedException("Invalid credentials.");
      }
    }

    // Expose the principal for Resteasy to inject via @Context
    ResteasyProviderFactory.pushContext(Principal.class, principal);

    if (principal instanceof ConsumerPrincipal) {
      // HACK: We need to do this after the principal has been pushed,
      // lest our security settings start getting upset when we try to
      // update a consumer without any roles:
      ConsumerPrincipal p = (ConsumerPrincipal) principal;
      consumerCurator.updateLastCheckin(p.getConsumer());
    }

    return null;
  }
示例#10
0
  protected void handleFailure(HttpRequest request, HttpResponse response, Failure failure) {
    if (failure.isLoggable())
      logger.error(
          "Failed executing " + request.getHttpMethod() + " " + request.getUri().getPath(),
          failure);
    else
      logger.debug(
          "Failed executing " + request.getHttpMethod() + " " + request.getUri().getPath(),
          failure);

    if (failure.getResponse() != null) {
      writeFailure(request, response, failure.getResponse());
    } else {
      try {
        if (failure.getMessage() != null) {
          response.sendError(failure.getErrorCode(), failure.getMessage());
        } else {
          response.sendError(failure.getErrorCode());
        }
      } catch (IOException e1) {
        throw new UnhandledException(e1);
      }
    }
  }
  public static ChannelFuture handshake(
      final ChannelHandlerContext ctx,
      final HttpRequest request,
      final String websocketPath,
      final ChannelHandler handler) {

    final String connHead = request.getHttpHeaders().getHeaderString(HttpHeaders.Names.CONNECTION);
    final String upHead = request.getHttpHeaders().getHeaderString(HttpHeaders.Names.UPGRADE);
    final String sockHead =
        request.getHttpHeaders().getHeaderString(HttpHeaders.Names.SEC_WEBSOCKET_VERSION);
    final String keyHead =
        request.getHttpHeaders().getHeaderString(HttpHeaders.Names.SEC_WEBSOCKET_KEY);

    try {
      DefaultHttpRequest req =
          new DefaultHttpRequest(
              HttpVersion.HTTP_1_0, HttpMethod.GET, request.getUri().getAbsolutePath().toString());
      req.setHeader(HttpHeaders.Names.SEC_WEBSOCKET_VERSION, sockHead);
      req.setHeader(HttpHeaders.Names.SEC_WEBSOCKET_KEY, keyHead);

      final Channel channel = ctx.channel();

      final String location = getWebSocketLocation(channel.pipeline(), request, websocketPath);
      final WebSocketServerHandshakerFactory wsFactory =
          new WebSocketServerHandshakerFactory(location, null, false);

      final WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req);

      if (handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedWebSocketVersionResponse(channel);
        return null;

      } else if (!connHead.toLowerCase().contains(HttpHeaders.Values.UPGRADE.toLowerCase())
          || !upHead.toLowerCase().contains(HttpHeaders.Values.WEBSOCKET.toLowerCase())) {
        // Not a valid socket open request
        logger.info("Invalid request: " + request.getUri());
        return null;

      } else {
        // We need to remove the RESTEasy stuff otherwise the Netty logic to write the handshake to
        // the channel
        // will never make it back to the client
        channel.pipeline().remove("resteasyEncoder");
        channel.pipeline().remove("resteasyDecoder");

        final ChannelFuture handshakeFuture = handshaker.handshake(channel, req);

        handshakeFuture.addListener(
            new ChannelFutureListener() {
              @Override
              public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                  ctx.fireExceptionCaught(future.cause());
                } else {
                  final ChannelPipeline pipeline = future.channel().pipeline();
                  pipeline.replace(pipeline.last(), "customSocketHandler", handler);
                  pipeline.addBefore(
                      "customSocketHandler", "socketHandler", new WebSocketProtocolHandler());
                }
              }
            });

        WebSocketProtocolHandler.setHandshaker(ctx, handshaker);
        return handshakeFuture;

        // channel.pipeline().addBefore("timeout", "WS403Responder",
        //    WebSocketProtocolHandler.forbiddenHttpRequestResponder());
      }

    } catch (Exception e) {
      logger.error("Error trying to upgrade the channel to a socket", e);
    }

    return null;
  }