Beispiel #1
0
 @Test
 public void testGetCookie() throws Exception {
   DefaultHttpRequest nettyRequest =
       new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "");
   String cookie1Name = "PREF";
   String cookie1Value = "ID=a95756377b78e75e:FF=0:TM=1392709628:LM=1392709628:S=a5mOVvTB7DBkexgi";
   String cookie1Domain = ".google.com";
   String cookie1Path = "/";
   String cookie1Header =
       cookie1Name
           + '='
           + cookie1Value
           + "; expires=Thu, 18-Feb-2016 07:47:08 GMT; path="
           + cookie1Path
           + "; domain="
           + cookie1Domain;
   nettyRequest.headers().add(HttpHeaders.Names.COOKIE, cookie1Header);
   HttpServerRequest<ByteBuf> request =
       new HttpServerRequest<ByteBuf>(nettyRequest, PublishSubject.<ByteBuf>create());
   Map<String, Set<Cookie>> cookies = request.getCookies();
   Assert.assertEquals("Unexpected number of cookies.", 1, cookies.size());
   Set<Cookie> cookies1 = cookies.get(cookie1Name);
   Assert.assertNotNull("No cookie found with name: " + cookie1Name, cookies1);
   Assert.assertEquals(
       "Unexpected number of cookies with name: " + cookie1Name, 1, cookies1.size());
   Cookie cookie = cookies1.iterator().next();
   Assert.assertEquals("Unexpected cookie name.", cookie1Name, cookie.getName());
   Assert.assertEquals("Unexpected cookie path.", cookie1Path, cookie.getPath());
 }
    public HttpResponse clientToProxyRequest(HttpObject httpObject) {
      if (httpObject instanceof DefaultHttpRequest) {

        DefaultHttpRequest fullreq = (DefaultHttpRequest) httpObject;
        Content c = null;
        // only return if content exist & at least one quality is
        // available
        if ((c = content.get(fullreq.getUri())) != null && c.getQualities().size() > 0) {

          LOGGER.debug("Cached resource found {}", c.getUri());

          HttpResponse response =
              new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.TEMPORARY_REDIRECT);
          Collections.shuffle(c.getQualities());

          String redirectUri =
              UriBuilder.fromPath(
                      "http://" + config.getFrontalHostName() + ":" + config.getFrontalPort())
                  .path("api")
                  .path("content")
                  .path(c.getId())
                  .path(c.getQualities().get(0))
                  .build()
                  .toString();
          response.headers().add("Location", redirectUri);
          LOGGER.debug("Redirecting it to ", redirectUri);
          return response;
        }
      }
      return null;
    }
 // Build the HTTP request based on the given parameters
 private HttpRequest buildRequest(
     String path, String method, List<HttpParam> parametersQuery, List<HttpParam> parametersForm) {
   String queryString = String.format("?api_key=%s:%s", username, password);
   for (HttpParam hp : parametersQuery) {
     if (hp.value != null && !hp.value.isEmpty()) {
       queryString += "&" + hp.name + "=" + hp.value;
     }
   }
   DefaultHttpRequest request =
       new DefaultHttpRequest(
           HttpVersion.HTTP_1_1,
           HttpMethod.valueOf(method),
           baseUri.getPath() + "ari" + path + queryString);
   // System.out.println(request.getUri());
   request.headers().set(HttpHeaders.Names.HOST, "localhost");
   request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
   return request;
 }
 protected boolean filter() throws Exception {
   if (!request.decoderResult().isSuccess()) {
     if (logger.isDebugEnabled()) {
       logger.debug("bad request");
     }
     sendError(ctx, BAD_REQUEST);
     return false;
   }
   requestFile = new File(cdnServer.getHomeDir(), request.uri());
   if (cdnServer.requestFilter != null) {
     filterCtx = new FilterContext(requestFile);
     filterCtx.request = request;
     cdnServer.requestFilter.filter(filterCtx);
     if (filterCtx.errorCode != FilterContext.CODE_OK) {
       if (logger.isDebugEnabled()) {
         logger.debug("requestFilter {} reject ", cdnServer.requestFilter);
       }
       sendError(ctx, filterCtx.errorCode, filterCtx.responseMap);
       return false;
     }
   }
   return true;
 }
  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;
  }