Example #1
0
  public void sendError() {
    if (request == null
        || status == null
        || shortDescription == null
        || detailedDescription == null
        || version == null
        || status == null) throw new IllegalStateException();

    StringBuffer sb = new StringBuffer();
    sb.append("Error ").append(status.code()).append(": ").append(shortDescription);
    sb.append("\n\n");
    sb.append(detailedDescription);
    sb.append("\n\n");
    sb.append("Request:\n").append(request.getUri());
    sb.append("\n\n");
    sb.append("Request Submitted:\n").append(FdsnwsDate.toString(new Date()));
    sb.append("\n\n");
    sb.append("Service version:\n").append(version);
    String html = sb.toString();

    FullHttpResponse response =
        new DefaultFullHttpResponse(
            request.getProtocolVersion(),
            status,
            Unpooled.copiedBuffer(html, Charset.forName("UTF-8")));
    response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, html.length());
    response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=UTF-8");

    if (HttpHeaders.isKeepAlive(request)) {
      response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }
    ctx.writeAndFlush(response);
  }
Example #2
0
  /**
   * A fallback converter that allows us to easily call Java beans and use the raw Netty {@link
   * HttpRequest} as parameter types.
   */
  @FallbackConverter
  public static Object convertToHttpRequest(
      Class<?> type, Exchange exchange, Object value, TypeConverterRegistry registry) {
    // if we want to covert to HttpRequest
    if (value != null && HttpRequest.class.isAssignableFrom(type)) {

      // okay we may need to cheat a bit when we want to grab the HttpRequest as its stored on the
      // NettyHttpMessage
      // so if the message instance is a NettyHttpMessage and its body is the value, then we can
      // grab the
      // HttpRequest from the NettyHttpMessage
      NettyHttpMessage msg;
      if (exchange.hasOut()) {
        msg = exchange.getOut(NettyHttpMessage.class);
      } else {
        msg = exchange.getIn(NettyHttpMessage.class);
      }
      if (msg != null && msg.getBody() == value) {
        // ensure the http request content is reset so we can read all the content out-of-the-box
        FullHttpRequest request = msg.getHttpRequest();
        request.content().resetReaderIndex();
        return request;
      }
    }

    return null;
  }
  private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
    // Handle a bad request.
    if (!req.getDecoderResult().isSuccess()) {
      sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
      req.release();
      return;
    }

    // Allow only GET methods.
    if (req.getMethod() != GET) {
      sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
      req.release();
      return;
    }

    // Handshake
    WebSocketServerHandshakerFactory wsFactory =
        new WebSocketServerHandshakerFactory(
            getWebSocketLocation(req), null, false, Integer.MAX_VALUE);
    handshaker = wsFactory.newHandshaker(req);
    if (handshaker == null) {
      WebSocketServerHandshakerFactory.sendUnsupportedWebSocketVersionResponse(ctx.channel());
    } else {
      handshaker.handshake(ctx.channel(), req);
    }
    req.release();
  }
  @Override
  protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {

    FullHttpRequest req = (FullHttpRequest) msg;
    String upgrade = req.headers().get(HttpHeaders.Names.UPGRADE);
    if (HttpHeaders.Values.WEBSOCKET.equalsIgnoreCase(upgrade)) {
      WebSocketServerHandshakerFactory wsFactory =
          new WebSocketServerHandshakerFactory(req.getUri(), null, false);
      WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req);
      if (handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedWebSocketVersionResponse(ctx.channel());
      } else {
        ChannelFuture future = handshaker.handshake(ctx.channel(), req);
        future.addListener(
            f -> {
              this.configurator.switchToWebSockets(ctx.pipeline());
            });
      }
    } else {
      ReferenceCountUtil.retain(msg);
      this.configurator.switchToPlainHttp(ctx.pipeline());
      ChannelHandlerContext agg = ctx.pipeline().context(HttpObjectAggregator.class);
      agg.fireChannelRead(msg);
    }
  }
Example #5
0
  private static FullHttpRequest createHttpRequest(int spdyVersion, SpdyHeaderBlock requestFrame)
      throws Exception {
    // Create the first line of the request from the name/value pairs
    HttpMethod method = SpdyHeaders.getMethod(spdyVersion, requestFrame);
    String url = SpdyHeaders.getUrl(spdyVersion, requestFrame);
    HttpVersion httpVersion = SpdyHeaders.getVersion(spdyVersion, requestFrame);
    SpdyHeaders.removeMethod(spdyVersion, requestFrame);
    SpdyHeaders.removeUrl(spdyVersion, requestFrame);
    SpdyHeaders.removeVersion(spdyVersion, requestFrame);

    FullHttpRequest req = new DefaultFullHttpRequest(httpVersion, method, url);

    // Remove the scheme header
    SpdyHeaders.removeScheme(spdyVersion, requestFrame);

    if (spdyVersion >= 3) {
      // Replace the SPDY host header with the HTTP host header
      String host = SpdyHeaders.getHost(requestFrame);
      SpdyHeaders.removeHost(requestFrame);
      HttpHeaders.setHost(req, host);
    }

    for (Map.Entry<String, String> e : requestFrame.headers().entries()) {
      req.headers().add(e.getKey(), e.getValue());
    }

    // The Connection and Keep-Alive headers are no longer valid
    HttpHeaders.setKeepAlive(req, true);

    // Transfer-Encoding header is not valid
    req.headers().remove(HttpHeaders.Names.TRANSFER_ENCODING);

    return req;
  }
 @Test
 public void clientRequestMultipleEmptyDataFrames() throws Exception {
   final String text = "";
   final ByteBuf content = Unpooled.copiedBuffer(text.getBytes());
   final FullHttpRequest request =
       new DefaultFullHttpRequest(
           HttpVersion.HTTP_1_1, HttpMethod.GET, "/some/path/resource2", content, true);
   try {
     HttpHeaders httpHeaders = request.headers();
     httpHeaders.set(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 3);
     httpHeaders.set(HttpHeaders.Names.CONTENT_LENGTH, text.length());
     final Http2Headers http2Headers =
         new DefaultHttp2Headers().method(as("GET")).path(as("/some/path/resource2"));
     runInChannel(
         clientChannel,
         new Http2Runnable() {
           @Override
           public void run() {
             frameWriter.writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient());
             frameWriter.writeData(ctxClient(), 3, content.retain(), 0, false, newPromiseClient());
             frameWriter.writeData(ctxClient(), 3, content.retain(), 0, false, newPromiseClient());
             frameWriter.writeData(ctxClient(), 3, content.retain(), 0, true, newPromiseClient());
             ctxClient().flush();
           }
         });
     awaitRequests();
     ArgumentCaptor<FullHttpMessage> requestCaptor =
         ArgumentCaptor.forClass(FullHttpMessage.class);
     verify(serverListener).messageReceived(requestCaptor.capture());
     capturedRequests = requestCaptor.getAllValues();
     assertEquals(request, capturedRequests.get(0));
   } finally {
     request.release();
   }
 }
 @Test(expected = MethodNotAllowedException.class)
 public void shouldThrowMethodNotAllowed() {
   FullHttpRequest httpRequest =
       new DefaultFullHttpRequest(
           HttpVersion.HTTP_1_1, HttpMethod.OPTIONS, "/foo/foo23.json?value=ignored");
   httpRequest.headers().add("Host", "testing-host");
   Request request = new Request(httpRequest, null);
   resolver.resolve(request);
 }
 @Override
 public FullHttpMessage copyIfNeeded(FullHttpMessage msg) {
   if (msg instanceof FullHttpRequest) {
     FullHttpRequest copy = ((FullHttpRequest) msg).copy(null);
     copy.headers().remove(HttpHeaderNames.EXPECT);
     return copy;
   }
   return null;
 }
 @Test
 public void shouldResolveAliasFooPostRoute() {
   FullHttpRequest httpRequest =
       new DefaultFullHttpRequest(
           HttpVersion.HTTP_1_1, HttpMethod.POST, "/yada/yada.json?value=ignored");
   httpRequest.headers().add("Host", "testing-host");
   Request request = new Request(httpRequest, null);
   Action action = resolver.resolve(request);
   assertNotNull(action);
   assertEquals(HttpMethod.POST, action.getRoute().getMethod());
   assertEquals("/foo", action.getRoute().getPattern());
 }
 private static String getRequestText(FullHttpRequest request) {
   if (request.method() == io.netty.handler.codec.http.HttpMethod.POST) {
     return request.content().toString(Charsets.ISO_8859_1);
   } else {
     int index = request.uri().indexOf('?');
     if (index == -1) {
       return "";
     } else {
       return request.uri().substring(index + 1);
     }
   }
 }
 @Test
 public void shouldResolveAliasCrudRouteForDelete() {
   FullHttpRequest httpRequest =
       new DefaultFullHttpRequest(
           HttpVersion.HTTP_1_1, HttpMethod.DELETE, "/blah/foo/foo23.json?value=ignored");
   httpRequest.headers().add("Host", "testing-host");
   Request request = new Request(httpRequest, null);
   Action action = resolver.resolve(request);
   assertNotNull(action);
   assertEquals(HttpMethod.DELETE, action.getRoute().getMethod());
   assertEquals("/foo/{fooId}", action.getRoute().getPattern());
 }
 @Override
 protected void doPost(ChannelHandlerContext ctx, HttpRequest httpReq) {
   postCount++;
   processTime();
   FullHttpRequest req = (FullHttpRequest) httpReq;
   ByteBuf byteBuf = req.content();
   byte[] data = new byte[byteBuf.readableBytes()];
   byteBuf.readBytes(data);
   byteBuf.release();
   Payload payload = JSONSerializer.INSTANCE.fromBytes(data, Payload.class);
   writeJSON(ctx, httpReq, payload);
 }
Example #13
0
 @Override
 protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
   FullHttpRequest request = this.request = msg;
   QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri());
   uriRequest = queryStringDecoder.path();
   logger.debug("Msg: " + uriRequest);
   if (uriRequest.contains("gre/")
       || uriRequest.contains("img/")
       || uriRequest.contains("res/")
       || uriRequest.contains("favicon.ico")) {
     HttpWriteCacheEnable.writeFile(
         request,
         ctx,
         Configuration.configuration.getHttpBasePath() + uriRequest,
         R66SESSION + Configuration.configuration.getHOST_ID());
     ctx.flush();
     return;
   }
   checkSession(ctx.channel());
   if (!authentHttp.isAuthenticated()) {
     logger.debug("Not Authent: " + uriRequest + ":{}", authentHttp);
     checkAuthent(ctx);
     return;
   }
   String find = uriRequest;
   if (uriRequest.charAt(0) == '/') {
     find = uriRequest.substring(1);
   }
   find = find.substring(0, find.indexOf("."));
   REQUEST req = REQUEST.index;
   try {
     req = REQUEST.valueOf(find);
   } catch (IllegalArgumentException e1) {
     req = REQUEST.index;
     logger.debug("NotFound: " + find + ":" + uriRequest);
   }
   switch (req) {
     case index:
       responseContent.append(index());
       break;
     case Logon:
       responseContent.append(index());
       break;
     case System:
       responseContent.append(System());
       break;
     default:
       responseContent.append(index());
       break;
   }
   writeResponse(ctx);
 }
 @Test
 public void clientRequestStreamDependencyInHttpMessageFlow() throws Exception {
   setServerLatch(2);
   final String text = "hello world big time data!";
   final ByteBuf content = Unpooled.copiedBuffer(text.getBytes());
   final String text2 = "hello world big time data...number 2!!";
   final ByteBuf content2 = Unpooled.copiedBuffer(text2.getBytes());
   final FullHttpRequest request =
       new DefaultFullHttpRequest(
           HttpVersion.HTTP_1_1, HttpMethod.PUT, "/some/path/resource", content, true);
   final FullHttpMessage request2 =
       new DefaultFullHttpRequest(
           HttpVersion.HTTP_1_1, HttpMethod.PUT, "/some/path/resource2", content2, true);
   try {
     HttpHeaders httpHeaders = request.headers();
     httpHeaders.set(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 3);
     httpHeaders.set(HttpHeaders.Names.CONTENT_LENGTH, text.length());
     HttpHeaders httpHeaders2 = request2.headers();
     httpHeaders2.set(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 5);
     httpHeaders2.set(HttpUtil.ExtensionHeaderNames.STREAM_DEPENDENCY_ID.text(), 3);
     httpHeaders2.set(HttpUtil.ExtensionHeaderNames.STREAM_WEIGHT.text(), 123);
     httpHeaders2.set(HttpHeaders.Names.CONTENT_LENGTH, text2.length());
     final Http2Headers http2Headers =
         new DefaultHttp2Headers().method(as("PUT")).path(as("/some/path/resource"));
     final Http2Headers http2Headers2 =
         new DefaultHttp2Headers().method(as("PUT")).path(as("/some/path/resource2"));
     runInChannel(
         clientChannel,
         new Http2Runnable() {
           @Override
           public void run() {
             frameWriter.writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient());
             frameWriter.writeHeaders(ctxClient(), 5, http2Headers2, 0, false, newPromiseClient());
             frameWriter.writePriority(ctxClient(), 5, 3, (short) 123, true, newPromiseClient());
             frameWriter.writeData(ctxClient(), 3, content.retain(), 0, true, newPromiseClient());
             frameWriter.writeData(ctxClient(), 5, content2.retain(), 0, true, newPromiseClient());
             ctxClient().flush();
           }
         });
     awaitRequests();
     ArgumentCaptor<FullHttpMessage> httpObjectCaptor =
         ArgumentCaptor.forClass(FullHttpMessage.class);
     verify(serverListener, times(2)).messageReceived(httpObjectCaptor.capture());
     capturedRequests = httpObjectCaptor.getAllValues();
     assertEquals(request, capturedRequests.get(0));
     assertEquals(request2, capturedRequests.get(1));
   } finally {
     request.release();
     request2.release();
   }
 }
Example #15
0
 private void getParams() {
   if (request.method() == HttpMethod.GET) {
     params = null;
   } else if (request.method() == HttpMethod.POST) {
     ByteBuf content = request.content();
     if (content.isReadable()) {
       String param = content.toString(WaarpStringUtils.UTF8);
       QueryStringDecoder queryStringDecoder2 = new QueryStringDecoder("/?" + param);
       params = queryStringDecoder2.parameters();
     } else {
       params = null;
     }
   }
 }
 @Test
 public void shouldSendAllowedMethodsForGetRoute() {
   FullHttpRequest httpRequest =
       new DefaultFullHttpRequest(
           HttpVersion.HTTP_1_1, HttpMethod.OPTIONS, "/foo/bar/bar23.json?value=ignored");
   httpRequest.headers().add("Host", "testing-host");
   Request request = new Request(httpRequest, null);
   try {
     resolver.resolve(request);
   } catch (MethodNotAllowedException e) {
     List<HttpMethod> allowed = e.getAllowedMethods();
     assertEquals(1, allowed.size());
     assertTrue(allowed.contains(HttpMethod.GET));
   }
 }
Example #17
0
 @Override
 public void write(final ChannelHandlerContext ctx, final Object msg, ChannelPromise promise)
     throws Exception {
   if (msg instanceof ByteBuf) {
     ByteBuf buf = (ByteBuf) msg;
     FullHttpRequest httpRequest =
         new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "", buf);
     httpRequest
         .headers()
         .add(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(buf.readableBytes()));
     ctx.write(httpRequest, promise);
   } else {
     ctx.write(msg, promise);
   }
 }
 /**
  * Method to easily create a request.
  *
  * @param httpMethod the {@link HttpMethod} desired.
  * @param uri string representation of the desired URI.
  * @param headers any associated headers as a {@link HttpHeaders} object. Can be null.
  * @param content the content that accompanies the request. Can be null.
  * @return A {@link FullHttpRequest} object that defines the request required by the input.
  */
 private FullHttpRequest buildRequest(
     HttpMethod httpMethod, String uri, HttpHeaders headers, ByteBuffer content) {
   ByteBuf contentBuf;
   if (content != null) {
     contentBuf = Unpooled.wrappedBuffer(content);
   } else {
     contentBuf = Unpooled.buffer(0);
   }
   FullHttpRequest httpRequest =
       new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, httpMethod, uri, contentBuf);
   if (headers != null) {
     httpRequest.headers().set(headers);
   }
   return httpRequest;
 }
 private static String getContentType(final FullHttpRequest request) {
   final String contentType = request.headers().get(CONTENT_TYPE);
   if (contentType == null) {
     return Transports.CONTENT_TYPE_PLAIN;
   }
   return contentType;
 }
Example #20
0
 private void checkSession(Channel channel) {
   String cookieString = request.headers().get(HttpHeaderNames.COOKIE);
   if (cookieString != null) {
     Set<Cookie> cookies = ServerCookieDecoder.LAX.decode(cookieString);
     if (!cookies.isEmpty()) {
       for (Cookie elt : cookies) {
         if (elt.name().equalsIgnoreCase(R66SESSION + Configuration.configuration.getHOST_ID())) {
           logger.debug("Found session: " + elt);
           admin = elt;
           R66Session session = sessions.get(admin.value());
           if (session != null) {
             authentHttp = session;
             authentHttp.setStatus(73);
           } else {
             admin = null;
             continue;
           }
         } else if (elt.name().equalsIgnoreCase(I18NEXT)) {
           logger.debug("Found i18next: " + elt);
           lang = elt.value();
         }
       }
     }
   }
   if (admin == null) {
     logger.debug("NoSession: " + uriRequest + ":{}", admin);
   }
 }
  private SyncFile _getSyncFile(FullHttpRequest fullHttpRequest) {
    String[] pathArray = StringUtils.split(fullHttpRequest.uri(), "/");

    if (pathArray.length != 4) {
      return null;
    }

    String lanServerUuid = pathArray[0];
    long repositoryId = GetterUtil.getLong(pathArray[1]);
    long typePK = GetterUtil.getLong(pathArray[2]);
    long versionId = GetterUtil.getLong(pathArray[3]);

    if (lanServerUuid.isEmpty() || (repositoryId == 0) || (typePK == 0) || (versionId == 0)) {

      return null;
    }

    List<SyncAccount> syncAccounts = SyncAccountService.findSyncAccounts(lanServerUuid);

    for (SyncAccount syncAccount : syncAccounts) {
      SyncFile syncFile =
          SyncFileService.fetchSyncFile(
              repositoryId, syncAccount.getSyncAccountId(), typePK, versionId);

      if ((syncFile != null) && (syncFile.getState() == SyncFile.STATE_SYNCED)) {

        return syncFile;
      }
    }

    return null;
  }
 private FullHttpResponse handleJsonServiceMappings(
     FullHttpRequest request, JsonServiceMapping jsonServiceMapping, Matcher matcher)
     throws Exception {
   if (!httpSessionManager.hasReadAccess(request)) {
     return handleNotAuthenticated(request);
   }
   boolean isGetRequest = request.method().name().equals(HttpMethod.GET.name());
   if (!isGetRequest && !httpSessionManager.hasAdminAccess(request)) {
     return handleNotAuthorized();
   }
   String requestText = getRequestText(request);
   String[] args = new String[matcher.groupCount()];
   for (int i = 0; i < args.length; i++) {
     String group = matcher.group(i + 1);
     checkNotNull(group);
     args[i] = group;
   }
   logger.debug(
       "handleJsonRequest(): serviceMethodName={}, args={}, requestText={}",
       jsonServiceMapping.methodName(),
       args,
       requestText);
   Object responseObject;
   try {
     responseObject =
         callMethod(
             jsonServiceMapping.service(), jsonServiceMapping.methodName(), args, requestText);
   } catch (Exception e) {
     return newHttpResponseFromException(e);
   }
   return buildJsonResponse(responseObject);
 }
 @SuppressWarnings("argument.type.incompatible")
 private void sendFullResponse(
     ChannelHandlerContext ctx, FullHttpRequest request, FullHttpResponse response)
     throws Exception {
   boolean keepAlive = HttpUtil.isKeepAlive(request);
   if (httpSessionManager.getSessionId(request) != null
       && httpSessionManager.getAuthenticatedUser(request) == null
       && !response.headers().contains("Set-Cookie")) {
     httpSessionManager.deleteSessionCookie(response);
   }
   response.headers().add("Glowroot-Layout-Version", layoutService.getLayoutVersion());
   if (response.headers().contains("Glowroot-Port-Changed")) {
     // current connection is the only open channel on the old port, keepAlive=false will add
     // the listener below to close the channel after the response completes
     //
     // remove the hacky header, no need to send it back to client
     response.headers().remove("Glowroot-Port-Changed");
     response.headers().add("Connection", "close");
     keepAlive = false;
   }
   response.headers().add(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
   if (keepAlive && !request.protocolVersion().isKeepAliveDefault()) {
     response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
   }
   ChannelFuture f = ctx.write(response);
   if (!keepAlive) {
     f.addListener(ChannelFutureListener.CLOSE);
   }
 }
 @Test
 public void clientRequestMultipleHeaders() throws Exception {
   // writeHeaders will implicitly add an END_HEADERS tag each time and so this test does not
   // follow the HTTP
   // message flow. We currently accept this message flow and just add the second headers to the
   // trailing headers.
   final String text = "";
   final ByteBuf content = Unpooled.copiedBuffer(text.getBytes());
   final FullHttpRequest request =
       new DefaultFullHttpRequest(
           HttpVersion.HTTP_1_1, HttpMethod.GET, "/some/path/resource2", content, true);
   try {
     HttpHeaders httpHeaders = request.headers();
     httpHeaders.set(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 3);
     httpHeaders.set(HttpHeaders.Names.CONTENT_LENGTH, text.length());
     HttpHeaders trailingHeaders = request.trailingHeaders();
     trailingHeaders.set("FoO", "goo");
     trailingHeaders.set("foO2", "goo2");
     trailingHeaders.add("fOo2", "goo3");
     final Http2Headers http2Headers =
         new DefaultHttp2Headers().method(as("GET")).path(as("/some/path/resource2"));
     final Http2Headers http2Headers2 =
         new DefaultHttp2Headers()
             .set(as("foo"), as("goo"))
             .set(as("foo2"), as("goo2"))
             .add(as("foo2"), as("goo3"));
     runInChannel(
         clientChannel,
         new Http2Runnable() {
           @Override
           public void run() {
             frameWriter.writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient());
             frameWriter.writeHeaders(ctxClient(), 3, http2Headers2, 0, false, newPromiseClient());
             frameWriter.writeData(ctxClient(), 3, content.retain(), 0, true, newPromiseClient());
             ctxClient().flush();
           }
         });
     awaitRequests();
     ArgumentCaptor<FullHttpMessage> requestCaptor =
         ArgumentCaptor.forClass(FullHttpMessage.class);
     verify(serverListener).messageReceived(requestCaptor.capture());
     capturedRequests = requestCaptor.getAllValues();
     assertEquals(request, capturedRequests.get(0));
   } finally {
     request.release();
   }
 }
 private static String getWebSocketLocation(FullHttpRequest req) {
   String location = req.headers().get(HOST) + WEBSOCKET_PATH;
   if (WebSocketServer.SSL) {
     return "wss://" + location;
   } else {
     return "ws://" + location;
   }
 }
  private static void testPerformOpeningHandshake0(boolean subProtocol) {
    EmbeddedChannel ch =
        new EmbeddedChannel(
            new HttpObjectAggregator(42), new HttpRequestDecoder(), new HttpResponseEncoder());

    FullHttpRequest req =
        ReferenceCountUtil.releaseLater(
            new DefaultFullHttpRequest(
                HTTP_1_1,
                HttpMethod.GET,
                "/chat",
                Unpooled.copiedBuffer("^n:ds[4U", CharsetUtil.US_ASCII)));

    req.headers().set(HttpHeaderNames.HOST, "server.example.com");
    req.headers().set(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET);
    req.headers().set(HttpHeaderNames.CONNECTION, "Upgrade");
    req.headers().set(HttpHeaderNames.ORIGIN, "http://example.com");
    req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_KEY1, "4 @1  46546xW%0l 1 5");
    req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_KEY2, "12998 5 Y3 1  .P00");
    req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, "chat, superchat");

    if (subProtocol) {
      new WebSocketServerHandshaker00("ws://example.com/chat", "chat", Integer.MAX_VALUE)
          .handshake(ch, req);
    } else {
      new WebSocketServerHandshaker00("ws://example.com/chat", null, Integer.MAX_VALUE)
          .handshake(ch, req);
    }

    EmbeddedChannel ch2 = new EmbeddedChannel(new HttpResponseDecoder());
    ch2.writeInbound(ch.readOutbound());
    HttpResponse res = ch2.readInbound();

    Assert.assertEquals(
        "ws://example.com/chat", res.headers().get(HttpHeaderNames.SEC_WEBSOCKET_LOCATION));

    if (subProtocol) {
      Assert.assertEquals("chat", res.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL));
    } else {
      Assert.assertNull(res.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL));
    }
    LastHttpContent content = ch2.readInbound();

    Assert.assertEquals("8jKS'y:G*Co,Wxa-", content.content().toString(CharsetUtil.US_ASCII));
    content.release();
  }
Example #27
0
 private void handleCookies(HttpResponse response) {
   String cookieString = request.headers().get(HttpHeaderNames.COOKIE);
   boolean i18nextFound = false;
   if (cookieString != null) {
     Set<Cookie> cookies = ServerCookieDecoder.LAX.decode(cookieString);
     if (!cookies.isEmpty()) {
       // Reset the sessions if necessary.
       boolean findSession = false;
       for (Cookie cookie : cookies) {
         if (cookie
             .name()
             .equalsIgnoreCase(R66SESSION + Configuration.configuration.getHOST_ID())) {
           if (newSession) {
             findSession = false;
           } else {
             findSession = true;
             response
                 .headers()
                 .add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.LAX.encode(cookie));
           }
         } else if (cookie.name().equalsIgnoreCase(I18NEXT)) {
           i18nextFound = true;
           cookie.setValue(lang);
           response
               .headers()
               .add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.LAX.encode(cookie));
         } else {
           response
               .headers()
               .add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.LAX.encode(cookie));
         }
       }
       if (!i18nextFound) {
         Cookie cookie = new DefaultCookie(I18NEXT, lang);
         response
             .headers()
             .add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.LAX.encode(cookie));
       }
       newSession = false;
       if (!findSession) {
         if (admin != null) {
           response
               .headers()
               .add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.LAX.encode(admin));
           logger.debug("AddSession: " + uriRequest + ":{}", admin);
         }
       }
     }
   } else {
     Cookie cookie = new DefaultCookie(I18NEXT, lang);
     response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.LAX.encode(cookie));
     if (admin != null) {
       logger.debug("AddSession: " + uriRequest + ":{}", admin);
       response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.LAX.encode(admin));
     }
   }
 }
  @Override
  protected void channelRead0(ChannelHandlerContext context, FullHttpRequest request)
      throws Exception {

    if (request.getMethod().equals(HttpMethod.HEAD)) {

      processHead(context, request);

    } else if (request.getMethod().equals(HttpMethod.GET)) {

      processGet(context, request);

    } else {
      // error
      String msg = "Not supported method: " + request.getMethod();
      LOG.error(msg);
      context.writeAndFlush(getBadRequest(msg));
    }
  }
Example #29
0
 @Override
 public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
   FullHttpResponse res;
   FullHttpRequest req = (FullHttpRequest) msg;
   String url = req.getUri();
   if ("/".equals(req.getUri())) {
     url = "/index.html";
   }
   Path path = Paths.get(root + url);
   if (Files.isReadable(path)) {
     ByteBuf content = Unpooled.copiedBuffer(Files.readAllBytes(path));
     res = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
     if (url.endsWith(".html")) res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
     HttpHeaders.setContentLength(res, content.readableBytes());
   } else {
     res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND);
   }
   sendHttpResponse(ctx, req, res);
 }
  private FullHttpRequest convertToHttpRequest(Invocation invocation) {
    requireNonNull(invocation, "invocation");
    final ServiceInvocationContext ctx = invocation.invocationContext();
    final FullHttpRequest request;
    final Object content = invocation.content();

    if (content instanceof FullHttpRequest) {
      request = (FullHttpRequest) content;
    } else if (content instanceof ByteBuf) {
      request =
          new DefaultFullHttpRequest(
              HttpVersion.HTTP_1_1, HttpMethod.POST, ctx.path(), (ByteBuf) content);
    } else {
      throw new IllegalStateException(
          "content is not a ByteBuf or FullHttpRequest: " + content.getClass().getName());
    }

    HttpHeaders headers = request.headers();

    headers.set(HttpHeaderNames.HOST, ctx.host());
    headers.set(ExtensionHeaderNames.SCHEME.text(), sessionProtocol.uriText());
    headers.set(HttpHeaderNames.USER_AGENT, ARMERIA_USER_AGENT);
    headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);

    ByteBuf contentBuf = request.content();
    if (contentBuf != null && contentBuf.isReadable()) {
      headers.set(HttpHeaderNames.CONTENT_LENGTH, contentBuf.readableBytes());
    }

    invocation.options().get(ClientOption.HTTP_HEADERS).ifPresent(headers::add);
    if (ctx.scheme().serializationFormat() != SerializationFormat.NONE) {
      // we allow a user can set content type and accept headers
      String mimeType = ctx.scheme().serializationFormat().mimeType();
      if (!headers.contains(HttpHeaderNames.CONTENT_TYPE)) {
        headers.set(HttpHeaderNames.CONTENT_TYPE, mimeType);
      }
      if (!headers.contains(HttpHeaderNames.ACCEPT)) {
        headers.set(HttpHeaderNames.ACCEPT, mimeType);
      }
    }

    return request;
  }