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);
    }
  }
示例#3
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 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;
 }
示例#5
0
  protected ServerResponse invokeOnTarget(
      HttpRequest request, HttpResponse response, Object target) {
    if (validator != null) {
      violationsContainer = new ViolationsContainer<Object>(validator.validate(target));
      request.setAttribute(ViolationsContainer.class.getName(), violationsContainer);
      request.setAttribute(GeneralValidator.class.getName(), validator);
    }

    PostMatchContainerRequestContext requestContext =
        new PostMatchContainerRequestContext(request, this);
    for (ContainerRequestFilter filter : requestFilters) {
      try {
        filter.filter(requestContext);
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
      ServerResponse serverResponse = (ServerResponse) requestContext.getResponseAbortedWith();
      if (serverResponse != null) {
        return prepareResponse(serverResponse);
      }
    }

    Object rtn = null;
    try {
      rtn = methodInjector.invoke(request, response, target);
    } catch (WebApplicationException wae) {
      prepareResponse(ServerResponse.convertToServerResponse(wae.getResponse()));
      throw wae;
    }

    if (violationsContainer != null && violationsContainer.size() > 0) {
      throw new ResteasyViolationExceptionExtension(violationsContainer);
    }

    if (request.isSuspended()) {
      AbstractAsynchronousResponse asyncResponse =
          (AbstractAsynchronousResponse) request.getAsynchronousResponse();
      if (asyncResponse == null) return null;
      asyncResponse.setAnnotations(method.getAnnotations());
      asyncResponse.setWriterInterceptors(writerInterceptors);
      asyncResponse.setResponseFilters(responseFilters);
      return null;
    }
    if (rtn == null || method.getReturnType().equals(void.class)) {
      return prepareResponse((ServerResponse) Response.noContent().build());
    }
    if (Response.class.isAssignableFrom(method.getReturnType()) || rtn instanceof Response) {
      return prepareResponse(ServerResponse.convertToServerResponse((Response) rtn));
    }

    Response.ResponseBuilder builder = Response.ok(rtn);
    builder.type(resolveContentType(request, rtn));
    ServerResponse jaxrsResponse = (ServerResponse) builder.build();
    jaxrsResponse.setGenericType(genericReturnType);
    return prepareResponse(jaxrsResponse);
  }
  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 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;
 }
示例#8
0
  protected BuiltResponse invokeOnTarget(
      HttpRequest request, HttpResponse response, Object target) {
    if (validator != null) {
      violationsContainer = new ViolationsContainer<Object>(validator.validate(target));
      request.setAttribute(ViolationsContainer.class.getName(), violationsContainer);
      request.setAttribute(GeneralValidator.class.getName(), validator);
    }

    PostMatchContainerRequestContext requestContext =
        new PostMatchContainerRequestContext(request, this);
    for (ContainerRequestFilter filter : requestFilters) {
      try {
        filter.filter(requestContext);
      } catch (IOException e) {
        throw new ApplicationException(e);
      }
      BuiltResponse serverResponse = (BuiltResponse) requestContext.getResponseAbortedWith();
      if (serverResponse != null) {
        return serverResponse;
      }
    }

    Object rtn = methodInjector.invoke(request, response, target);

    if (violationsContainer != null && violationsContainer.size() > 0) {
      throw new ResteasyViolationExceptionExtension(violationsContainer);
    }

    if (request.getAsyncContext().isSuspended()) {
      request.getAsyncContext().getAsyncResponse().setAnnotations(method.getAnnotations());
      request.getAsyncContext().getAsyncResponse().setWriterInterceptors(writerInterceptors);
      request.getAsyncContext().getAsyncResponse().setResponseFilters(responseFilters);
      request.getAsyncContext().getAsyncResponse().setMethod(this);
      return null;
    }
    if (rtn == null || method.getReturnType().equals(void.class)) {
      BuiltResponse build = (BuiltResponse) Response.noContent().build();
      build.setAnnotations(method.getAnnotations());
      return build;
    }
    if (Response.class.isAssignableFrom(method.getReturnType()) || rtn instanceof Response) {
      BuiltResponse rtn1 = (BuiltResponse) rtn;
      rtn1.setAnnotations(method.getAnnotations());
      return rtn1;
    }

    Response.ResponseBuilder builder = Response.ok(rtn);
    builder.type(resolveContentType(request, rtn));
    BuiltResponse jaxrsResponse = (BuiltResponse) builder.build();
    jaxrsResponse.setGenericType(genericReturnType);
    jaxrsResponse.setAnnotations(method.getAnnotations());
    return jaxrsResponse;
  }
 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;
 }
示例#10
0
 private SecurityContext basicAuthentication(HttpRequest request, HttpResponse response)
     throws IOException {
   List<String> headers = request.getHttpHeaders().getRequestHeader(HttpHeaderNames.AUTHORIZATION);
   if (!headers.isEmpty()) {
     String auth = headers.get(0);
     if (auth.length() > 5) {
       String type = auth.substring(0, 5);
       type = type.toLowerCase();
       if ("basic".equals(type)) {
         String cookie = auth.substring(6);
         cookie = new String(Base64.decodeBase64(cookie.getBytes()));
         String[] split = cookie.split(":");
         Principal user = null;
         try {
           user = domain.authenticate(split[0], split[1]);
           return new NettySecurityContext(user, domain, "BASIC", true);
         } catch (SecurityException e) {
           response.sendError(HttpResponseCodes.SC_UNAUTHORIZED);
           return null;
         }
       } else {
         response.sendError(HttpResponseCodes.SC_UNAUTHORIZED);
         return null;
       }
     }
   }
   return null;
 }
 private static String getWebSocketLocation(ChannelPipeline cp, HttpRequest req, String path) {
   String protocol = "ws";
   if (cp.get(SslHandler.class) != null) {
     // SSL in use so use Secure WebSockets
     protocol = "wss";
   }
   return protocol + "://" + req.getHttpHeaders().getHeaderString(HttpHeaders.Names.HOST) + path;
 }
示例#12
0
 protected Response getResponse(
     HttpRequest request, HttpResponse response, ResourceInvoker invoker) {
   Response jaxrsResponse = null;
   try {
     jaxrsResponse = invoker.invoke(request, response);
     if (request.getAsyncContext().isSuspended()) {
       /**
        * Callback by the initial calling thread. This callback will probably do nothing in an
        * asynchronous environment but will be used to simulate AsynchronousResponse in vanilla
        * Servlet containers that do not support asychronous HTTP.
        */
       request.getAsyncContext().getAsyncResponse().initialRequestThreadFinished();
       jaxrsResponse = null; // we're handing response asynchronously
     }
   } catch (Exception e) {
     handleInvokerException(request, response, e);
   }
   return jaxrsResponse;
 }
示例#13
0
  public void build(HttpResponse response) {
    String origin = request.getHttpHeaders().getRequestHeaders().getFirst(ORIGIN_HEADER);
    if (origin == null) {
      logger.debug("No origin returning");
      return;
    }

    if (!preflight
        && (allowedOrigins == null
            || (!allowedOrigins.contains(origin)
                && !allowedOrigins.contains(ACCESS_CONTROL_ALLOW_ORIGIN_WILDCARD)))) {
      logger.debug("!preflight and no origin");
      return;
    }

    logger.debug("build CORS headers and return");

    response.getOutputHeaders().add(ACCESS_CONTROL_ALLOW_ORIGIN, origin);

    if (preflight) {
      if (allowedMethods != null) {
        response
            .getOutputHeaders()
            .add(ACCESS_CONTROL_ALLOW_METHODS, CollectionUtil.join(allowedMethods));
      } else {
        response.getOutputHeaders().add(ACCESS_CONTROL_ALLOW_METHODS, DEFAULT_ALLOW_METHODS);
      }
    }

    if (!preflight && exposedHeaders != null) {
      response
          .getOutputHeaders()
          .add(ACCESS_CONTROL_EXPOSE_HEADERS, CollectionUtil.join(exposedHeaders));
    }

    response.getOutputHeaders().add(ACCESS_CONTROL_ALLOW_CREDENTIALS, Boolean.toString(auth));

    if (preflight) {
      if (auth) {
        response
            .getOutputHeaders()
            .add(
                ACCESS_CONTROL_ALLOW_HEADERS,
                String.format("%s, %s", DEFAULT_ALLOW_HEADERS, AUTHORIZATION_HEADER));
      } else {
        response.getOutputHeaders().add(ACCESS_CONTROL_ALLOW_HEADERS, DEFAULT_ALLOW_HEADERS);
      }
    }

    if (preflight) {
      response.getOutputHeaders().add(ACCESS_CONTROL_MAX_AGE, DEFAULT_MAX_AGE);
    }
  }
  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;
  }
示例#15
0
 protected void handlePreflightRequest() {
   if (request.getHttpMethod().equalsIgnoreCase("OPTIONS")) {
     logger.debug("Cors admin pre-flight");
     Response response =
         Cors.add(request, Response.ok())
             .preflight()
             .allowedMethods("GET", "PUT", "POST", "DELETE")
             .auth()
             .build();
     throw new NoLogWebApplicationException(response);
   }
 }
示例#16
0
  protected void writeJaxrsResponse(
      HttpRequest request, HttpResponse response, Response jaxrsResponse) throws WriterException {
    Object type = jaxrsResponse.getMetadata().getFirst(HttpHeaderNames.CONTENT_TYPE);
    if (type == null && jaxrsResponse.getEntity() != null) {
      ResourceMethod method = (ResourceMethod) request.getAttribute(ResourceMethod.class.getName());
      if (method != null) {
        jaxrsResponse
            .getMetadata()
            .putSingle(
                HttpHeaderNames.CONTENT_TYPE,
                method.resolveContentType(request, jaxrsResponse.getEntity()));
      } else {
        MediaType contentType =
            resolveContentTypeByAccept(
                request.getHttpHeaders().getAcceptableMediaTypes(), jaxrsResponse.getEntity());
        jaxrsResponse.getMetadata().putSingle(HttpHeaderNames.CONTENT_TYPE, contentType);
      }
    }

    ServerResponseWriter.writeResponse(
        (BuiltResponse) jaxrsResponse, request, response, providerFactory);
  }
示例#17
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;
  }
示例#18
0
  public MediaType resolveContentType(HttpRequest in, Object entity) {
    MediaType chosen = (MediaType) in.getAttribute(Segment.RESTEASY_CHOSEN_ACCEPT);
    if (chosen != null && !chosen.equals(MediaType.WILDCARD_TYPE)) {
      return chosen;
    }

    List<MediaType> accepts = in.getHttpHeaders().getAcceptableMediaTypes();

    if (accepts == null || accepts.size() == 0) {
      if (produces == null) return MediaType.WILDCARD_TYPE;
      else return produces[0];
    }

    if (produces == null || produces.length == 0) {
      return resolveContentTypeByAccept(accepts, entity);
    }

    for (MediaType accept : accepts) {
      for (MediaType type : produces) {
        if (type.isCompatible(accept)) return type;
      }
    }
    return MediaType.WILDCARD_TYPE;
  }
示例#19
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);
      }
    }
  }
示例#20
0
  public Response build() {
    String origin = request.getHttpHeaders().getRequestHeaders().getFirst(ORIGIN_HEADER);
    if (origin == null) {
      return builder.build();
    }

    if (!preflight
        && (allowedOrigins == null
            || (!allowedOrigins.contains(origin)
                && !allowedOrigins.contains(ACCESS_CONTROL_ALLOW_ORIGIN_WILDCARD)))) {
      return builder.build();
    }

    builder.header(ACCESS_CONTROL_ALLOW_ORIGIN, origin);

    if (preflight) {
      if (allowedMethods != null) {
        builder.header(ACCESS_CONTROL_ALLOW_METHODS, CollectionUtil.join(allowedMethods));
      } else {
        builder.header(ACCESS_CONTROL_ALLOW_METHODS, DEFAULT_ALLOW_METHODS);
      }
    }

    if (!preflight && exposedHeaders != null) {
      builder.header(ACCESS_CONTROL_EXPOSE_HEADERS, CollectionUtil.join(exposedHeaders));
    }

    builder.header(ACCESS_CONTROL_ALLOW_CREDENTIALS, Boolean.toString(auth));

    if (preflight) {
      if (auth) {
        builder.header(
            ACCESS_CONTROL_ALLOW_HEADERS,
            String.format("%s, %s", DEFAULT_ALLOW_HEADERS, AUTHORIZATION_HEADER));
      } else {
        builder.header(ACCESS_CONTROL_ALLOW_HEADERS, DEFAULT_ALLOW_HEADERS);
      }
    }

    if (preflight) {
      builder.header(ACCESS_CONTROL_MAX_AGE, DEFAULT_MAX_AGE);
    }

    return builder.build();
  }
示例#21
0
 public Response redirectAccessCode(
     AccessCodeEntry accessCode,
     UserSessionModel session,
     String state,
     String redirect,
     boolean rememberMe) {
   String code = accessCode.getCode();
   UriBuilder redirectUri = UriBuilder.fromUri(redirect).queryParam(OAuth2Constants.CODE, code);
   log.debugv("redirectAccessCode: state: {0}", state);
   if (state != null) redirectUri.queryParam(OAuth2Constants.STATE, state);
   Response.ResponseBuilder location = Response.status(302).location(redirectUri.build());
   Cookie remember =
       request.getHttpHeaders().getCookies().get(AuthenticationManager.KEYCLOAK_REMEMBER_ME);
   rememberMe = rememberMe || remember != null;
   // refresh the cookies!
   authManager.createLoginCookie(realm, accessCode.getUser(), session, uriInfo, rememberMe);
   if (rememberMe) authManager.createRememberMeCookie(realm, uriInfo);
   return location.build();
 }
  /**
   * Handle Paging Parameters
   *
   * @param params
   */
  private void processPaging(HttpRequest request, List<NameValuePair> params, Long requestId)
      throws WebApplicationException {

    // Grab session header and pull out all common parameters.
    String page = null;
    String sortBy = null;
    String dir = null;
    String top = null;
    String pageSize = null;
    String count = null;
    PagingAttribute attr = null;

    for (NameValuePair nameValuePair : params) {

      if (nameValuePair.getName().equals("page")) page = nameValuePair.getValue();
      else if (nameValuePair.getName().equals("top")) top = nameValuePair.getValue();
      else if (nameValuePair.getName().equals("pageSize")) pageSize = nameValuePair.getValue();
      else if (nameValuePair.getName().equals("sortBy")) sortBy = nameValuePair.getValue();
      else if (nameValuePair.getName().equals("dir")) dir = nameValuePair.getValue();
      else if (nameValuePair.getName().equals("count")) count = nameValuePair.getValue();
    }

    if (page != null) {
      attr = new PagingAttribute();
      int value = new Integer(page).intValue();
      if (value == 0) ++value; // page=0 doesn't exist.
      attr.setPageNumber(value);
      attr.setActive(true);

      if (pageSize != null && !pageSize.isEmpty()) {
        attr.setPageSize(new Integer(pageSize));
      }

      if (count != null && !Boolean.parseBoolean(count)) {
        attr.setType(PagingAttribute.PAGINABLE);
      } else {
        attr.setType(PagingAttribute.COUNT);
      }

      if (sortBy != null && !sortBy.isEmpty()) {
        attr.setSortBy(sortBy);
        if (dir != null) {

          if (dir.toLowerCase().equals("asc") || dir.toLowerCase().equals("desc")) {
            attr.setDir(dir);
          } else {
            logger.info("Request #%s rejected; dir parameter %s is not recognized", requestId, dir);
            throw new CustomWebApplicationException(
                HttpURLConnection.HTTP_BAD_REQUEST,
                "Request #" + requestId + " rejected; dir parameter " + dir + " is not recognized");
          }
        }
      }

    } else if (top != null) {
      attr = new PagingAttribute();
      int value = new Integer(top).intValue();
      attr.setTop(value);
      attr.setType(PagingAttribute.PAGINABLE);
    }

    if (attr != null) {
      PagingContextHolder pagingContextHolder = new PagingContextHolder(attr);
      request.setAttribute(
          Key.get(PagingContextHolder.class, Names.named("pagingContextHolder")).toString(),
          pagingContextHolder);
    }
  }
  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;
  }
 public ServerResponse preProcess(HttpRequest request, ResourceMethodInvoker method)
     throws Failure, WebApplicationException {
   request.setAttribute(InputPart.DEFAULT_CONTENT_TYPE_PROPERTY, TEXT_PLAIN_WITH_CHARSET_UTF_8);
   return null;
 }
  protected BuiltResponse invokeOnTarget(
      HttpRequest request, HttpResponse response, Object target) {
    ResteasyProviderFactory.pushContext(
        ResourceInfo.class, resourceInfo); // we don't pop so writer interceptors can get at this

    PostMatchContainerRequestContext requestContext =
        new PostMatchContainerRequestContext(request, this);
    for (ContainerRequestFilter filter : requestFilters) {
      try {
        filter.filter(requestContext);
      } catch (IOException e) {
        throw new ApplicationException(e);
      }
      BuiltResponse serverResponse = (BuiltResponse) requestContext.getResponseAbortedWith();
      if (serverResponse != null) {
        return serverResponse;
      }
    }

    if (validator != null) {
      if (isValidatable) {
        validator.validate(request, target);
      }
      if (methodIsValidatable) {
        request.setAttribute(GeneralValidator.class.getName(), validator);
      } else if (isValidatable) {
        validator.checkViolations(request);
      }
    }

    Object rtn = null;
    try {
      rtn = methodInjector.invoke(request, response, target);
    } catch (RuntimeException ex) {
      if (request.getAsyncContext().isSuspended()) {
        try {
          request.getAsyncContext().getAsyncResponse().resume(ex);
        } catch (Exception e) {
          logger.error("Error resuming failed async operation", e);
        }
        return null;
      } else {
        throw ex;
      }
    }

    if (request.getAsyncContext().isSuspended() || request.wasForwarded()) {
      return null;
    }
    if (rtn == null || method.getReturnType().equals(void.class)) {
      BuiltResponse build = (BuiltResponse) Response.noContent().build();
      build.addMethodAnnotations(method.getAnnotatedMethod());
      return build;
    }
    if (Response.class.isAssignableFrom(method.getReturnType()) || rtn instanceof Response) {
      if (!(rtn instanceof BuiltResponse)) {
        Response r = (Response) rtn;
        Headers<Object> metadata = new Headers<Object>();
        metadata.putAll(r.getMetadata());
        rtn = new BuiltResponse(r.getStatus(), metadata, r.getEntity(), null);
      }
      BuiltResponse rtn1 = (BuiltResponse) rtn;
      rtn1.addMethodAnnotations(method.getAnnotatedMethod());
      if (rtn1.getGenericType() == null) {
        if (getMethod().getReturnType().equals(Response.class)) {
          rtn1.setGenericType(rtn1.getEntityClass());
        } else {
          rtn1.setGenericType(method.getGenericReturnType());
        }
      }
      return rtn1;
    }

    Response.ResponseBuilder builder = Response.ok(rtn);
    BuiltResponse jaxrsResponse = (BuiltResponse) builder.build();
    if (jaxrsResponse.getGenericType() == null) {
      if (getMethod().getReturnType().equals(Response.class)) {
        jaxrsResponse.setGenericType(jaxrsResponse.getEntityClass());
      } else {
        jaxrsResponse.setGenericType(method.getGenericReturnType());
      }
    }
    jaxrsResponse.addMethodAnnotations(method.getAnnotatedMethod());
    return jaxrsResponse;
  }