Esempio n. 1
0
  /**
   * build SETUP request
   *
   * @return
   */
  private HttpRequest buildSetupRequest(String uri) {
    HttpRequest request = new DefaultFullHttpRequest(RtspVersions.RTSP_1_0, RtspMethods.SETUP, uri);
    request.headers().set(RtspHeaderNames.CSEQ, "3");
    request.headers().add(RtspHeaderNames.TRANSPORT, "RTP/AVP;unicast;client_port=4588-4589");

    return request;
  }
Esempio n. 2
0
    @Override
    public void messageReceived(ChannelHandlerContext ctx, HttpObject httpObject) {
      if (log.isDebugEnabled()) {
        log.debug("Received HTTP message {}", httpObject);
      }
      if (httpObject instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) httpObject;
        SocketChannel channel = (SocketChannel) ctx.channel();
        curRequest = new NettyHttpRequest(req, channel);

        curResponse =
            new NettyHttpResponse(
                new DefaultHttpResponse(req.getProtocolVersion(), HttpResponseStatus.OK),
                channel,
                curRequest.isKeepAlive(),
                NettyHttpServer.this);
        stub.onRequest(curRequest, curResponse);

      } else if (httpObject instanceof HttpContent) {
        if ((curRequest == null) || (curResponse == null)) {
          log.error("Received an HTTP chunk without a request first");
          return;
        }
        NettyHttpChunk chunk = new NettyHttpChunk((HttpContent) httpObject);
        if (chunk.hasData() && !curRequest.hasContentLength() && !curRequest.isChunked()) {
          returnError(ctx, HttpResponseStatus.BAD_REQUEST);
        } else {
          stub.onData(curRequest, curResponse, chunk);
        }

      } else {
        throw new AssertionError();
      }
    }
Esempio n. 3
0
  /**
   * build PAUSE request
   *
   * @return
   */
  private HttpRequest buildPauseRequest(String uri) {
    HttpRequest request = new DefaultFullHttpRequest(RtspVersions.RTSP_1_0, RtspMethods.PAUSE, uri);
    request.headers().set(RtspHeaderNames.CSEQ, "5");
    request.headers().set(RtspHeaderNames.SESSION, "1234567");

    return request;
  }
Esempio n. 4
0
 /**
  * build TEARDOWN request
  *
  * @return
  */
 private HttpRequest buildTeardownRequest(String uri) {
   HttpRequest request =
       new DefaultFullHttpRequest(RtspVersions.RTSP_1_0, RtspMethods.TEARDOWN, uri);
   request.headers().set(RtspHeaderNames.CSEQ, "6");
   request.headers().set(RtspHeaderNames.SESSION, "1234567");
   return request;
 }
  public static HttpRequest createSendDataRequest(String host, String cookie, ChannelBuffer data) {
    HttpRequest request = createRequestTemplate(host, cookie, CLIENT_SEND_REQUEST_URI);
    request.setHeader(HttpHeaders.Names.CONTENT_LENGTH, Long.toString(data.readableBytes()));
    request.setContent(data);

    return request;
  }
  private boolean exitAfterSpecialCases(
      final HttpResponse response, final Channel channel, final NettyResponseFuture<?> future)
      throws Exception {

    HttpRequest httpRequest = future.getNettyRequest().getHttpRequest();
    ProxyServer proxyServer = future.getProxyServer();
    int statusCode = response.getStatus().code();
    Request request = future.getCurrentRequest();
    Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm();

    if (statusCode == UNAUTHORIZED_401) {
      return exitAfterHandling401(
          channel, future, response, request, statusCode, realm, proxyServer, httpRequest);

    } else if (statusCode == PROXY_AUTHENTICATION_REQUIRED_407) {
      return exitAfterHandling407(
          channel, future, response, request, statusCode, proxyServer, httpRequest);

    } else if (statusCode == CONTINUE_100) {
      return exitAfterHandling100(channel, future, statusCode);

    } else if (REDIRECT_STATUSES.contains(statusCode)) {
      return exitAfterHandlingRedirect(channel, future, response, request, statusCode, realm);

    } else if (httpRequest.getMethod() == HttpMethod.CONNECT && statusCode == OK_200) {
      return exitAfterHandlingConnect(
          channel, future, request, proxyServer, statusCode, httpRequest);
    }
    return false;
  }
  private void writeResponse(Channel channel, HttpRequest request, String message, String client) {
    String contentType = "text/plain";
    if (client != null && (client.equals("web") || client.equals("bluej"))) {
      // convert to HTML
      message = message.replaceAll("\n", "<br>\n");
      contentType = "text/html";
    }
    // Convert the response content to a ChannelBuffer.
    ByteBuf buf = copiedBuffer(message, CharsetUtil.UTF_8);

    // Decide whether to close the connection or not.
    boolean close =
        HttpHeaders.Values.CLOSE.equalsIgnoreCase(request.headers().get(CONNECTION))
            || request.getProtocolVersion().equals(HttpVersion.HTTP_1_0)
                && !HttpHeaders.Values.KEEP_ALIVE.equalsIgnoreCase(
                    request.headers().get(CONNECTION));

    // Build the response object.
    FullHttpResponse response =
        new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);
    response.headers().set(CONTENT_TYPE, contentType + "; charset=UTF-8");

    if (!close) {
      // There's no need to add 'Content-Length' header
      // if this is the last response.
      response.headers().set(CONTENT_LENGTH, buf.readableBytes());
    }

    // Write the response.
    ChannelFuture future = channel.writeAndFlush(response);
    // Close the connection after the write operation is done if necessary.
    if (close) {
      future.addListener(ChannelFutureListener.CLOSE);
    }
  }
  /**
   * Flush the response contents to the output channel
   *
   * @param channel Channel to be used
   */
  private void writeResponse(Channel channel) {
    // Convert the response content to a ChannelBuffer.
    ByteBuf buf = copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8);
    responseContent.setLength(0);

    // Decide whether to close the connection or not.
    boolean close =
        HttpHeaders.Values.CLOSE.equalsIgnoreCase(request.headers().get(CONNECTION))
            || request.getProtocolVersion().equals(HttpVersion.HTTP_1_0)
                && !HttpHeaders.Values.KEEP_ALIVE.equalsIgnoreCase(
                    request.headers().get(CONNECTION));

    // Build the response object.
    FullHttpResponse response =
        new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);
    response.headers().set(CONTENT_TYPE, "application/json; charset=UTF-8");

    if (!close) {
      // There's no need to add 'Content-Length' header
      // if this is the last response.
      response.headers().set(CONTENT_LENGTH, buf.readableBytes());
    }

    try {
      // Write the response.
      ChannelFuture future = channel.writeAndFlush(response);
      // Close the connection after the write operation is done if necessary.
      if (close) {
        future.addListener(ChannelFutureListener.CLOSE);
      }
    } catch (Exception e) {
      logger.error("{}", e);
    }
  }
Esempio n. 9
0
  public void run() {
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    String host = uri.getHost() == null ? "localhost" : uri.getHost();
    int port = uri.getPort();
    if (port == -1) {
      if (scheme.equalsIgnoreCase("http")) {
        port = 80;
      } else if (scheme.equalsIgnoreCase("https")) {
        port = 443;
      }
    }

    if (!scheme.equalsIgnoreCase("http") && !scheme.equalsIgnoreCase("https")) {
      logger.error("Only HTTP(S) is supported.");
      return;
    }

    boolean ssl = scheme.equalsIgnoreCase("https");

    // Configure the client.
    ClientBootstrap bootstrap =
        new ClientBootstrap(new NioClientSocketChannelFactory(Executors.newCachedThreadPool()));

    // Set up the event pipeline factory.
    bootstrap.setPipelineFactory(new HttpSnoopClientPipelineFactory(ssl));

    // Start the connection attempt.
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));

    // Wait until the connection attempt succeeds or fails.
    Channel channel = future.awaitUninterruptibly().getChannel();
    if (!future.isSuccess()) {
      future.getCause().printStackTrace();
      bootstrap.releaseExternalResources();
      return;
    }

    // Prepare the HTTP request.
    HttpRequest request =
        new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());
    request.setHeader(HttpHeaders.Names.HOST, host);
    request.setHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
    request.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);

    // Set some example cookies.
    CookieEncoder httpCookieEncoder = new CookieEncoder(false);
    httpCookieEncoder.addCookie("my-cookie", "foo");
    httpCookieEncoder.addCookie("another-cookie", "bar");
    request.setHeader(HttpHeaders.Names.COOKIE, httpCookieEncoder.encode());

    // Send the HTTP request.
    channel.write(request);

    // Wait for the server to close the connection.
    channel.getCloseFuture().awaitUninterruptibly();

    // Shut down executor threads to exit.
    bootstrap.releaseExternalResources();
  }
Esempio n. 10
0
  /**
   * build PLAY request
   *
   * @return
   */
  private HttpRequest buildPlayRequest(String uri) {
    HttpRequest request = new DefaultFullHttpRequest(RtspVersions.RTSP_1_0, RtspMethods.PLAY, uri);
    request.headers().set(RtspHeaderNames.CSEQ, "4");
    request.headers().set(RtspHeaderNames.SESSION, "1234567");
    request.headers().add(RtspHeaderNames.RANGE, "npt=10-15");

    return request;
  }
Esempio n. 11
0
  public static void newHttpClientBootstrap(String url, ChannelHandler handler) throws Exception {
    URI uri = new URI(url);
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    int port = uri.getPort();
    if (port == -1) {
      if ("http".equalsIgnoreCase(scheme)) {
        port = 80;
      } else if ("https".equalsIgnoreCase(scheme)) {
        port = 443;
      }
    }

    if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
      System.err.println("Only HTTP(S) is supported.");
      return;
    }

    // Configure SSL context if necessary.
    final boolean ssl = "https".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
      sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } else {
      sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
      Bootstrap b = new Bootstrap();
      b.group(group)
          .channel(NioSocketChannel.class)
          .handler(new HttpDownloadertInitializer(sslCtx, handler));
      // Make the connection attempt.
      Channel ch = b.connect(host, port).sync().channel();
      // Prepare the HTTP request.
      HttpRequest request =
          new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());
      HttpHeaders headers = request.headers();
      headers.set(HttpHeaders.Names.HOST, host);
      headers.set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
      headers.set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
      // Set some example cookies.
      headers.set(
          HttpHeaders.Names.COOKIE,
          ClientCookieEncoder.encode(new DefaultCookie("my-cookie", "foo")));
      ch.writeAndFlush(request);
      // Wait for the server to close the connection.
      ch.closeFuture().sync();
      Thread.sleep(1000);
    } finally {
      // Shut down executor threads to exit.
      group.shutdownGracefully();
    }
  }
Esempio n. 12
0
 private HttpRequest buildAnnounceRequest(String uri) {
   HttpRequest request =
       new DefaultFullHttpRequest(RtspVersions.RTSP_1_0, RtspMethods.ANNOUNCE, uri);
   request.headers().set(RtspHeaderNames.CSEQ, "1");
   request.headers().set(RtspHeaderNames.SESSION, "1234567");
   request.headers().add(RtspHeaderNames.CONTENT_TYPE, "application/sdp");
   request.headers().add(RtspHeaderNames.CONTENT_LENGTH, "123");
   //        request.setContent(null);
   return request;
 }
Esempio n. 13
0
  @Override
  protected void channelRead0(ChannelHandlerContext ctx, FullHttpMessage msg)
      throws Exception { // 1
    // Request header 처리
    if (msg instanceof HttpRequest) { // 2
      this.request = (HttpRequest) msg; // 3

      if (HttpHeaders.is100ContinueExpected(request)) {
        send100Continue(ctx);
      }

      HttpHeaders headers = request.headers(); // 4
      if (!headers.isEmpty()) {
        for (Map.Entry<String, String> h : headers) {
          String key = h.getKey();
          if (usingHeader.contains(key)) { // 5
            reqData.put(key, h.getValue()); // 6
          }
        }
      }

      reqData.put("REQUEST_URI", request.getUri()); // 7
      reqData.put("REQUEST_METHOD", request.getMethod().name()); // 8
    }

    if (msg instanceof HttpContent) { // 9
      HttpContent httpContent = (HttpContent) msg; // 10

      ByteBuf content = httpContent.content(); // 11

      if (msg instanceof LastHttpContent) { // 12
        System.out.println("LastHttpContent message received!!" + request.getUri());

        LastHttpContent trailer = (LastHttpContent) msg;

        readPostData(); // 13

        ApiRequest service = ServiceDispatcher.dispatch(reqData); // 14

        try {
          service.executeService(); // 15

          apiResult = service.getApiResult(); // 16
        } finally {
          reqData.clear();
        }

        if (!writeResponse(trailer, ctx)) { // 17
          ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
        }
        reset();
      }
    }
  }
Esempio n. 14
0
  @Override
  public Context process(final HttpObject request, final Context context) {
    if (request instanceof HttpRequest) {
      final HttpRequest httpRequest = (HttpRequest) request;
      final QueryStringDecoder queryStringDecoder = new QueryStringDecoder(httpRequest.getUri());
      context.getQueryParams().putAll(queryStringDecoder.parameters());
      context.getCookies().putAll(readCookie(httpRequest));
    }

    return context;
  }
  private static HttpRequest createRequestTemplate(String host, String tunnelId, String uri) {
    HttpRequest request =
        new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, createCompleteUri(host, uri));
    request.setHeader(HttpHeaders.Names.HOST, host);
    request.setHeader(HttpHeaders.Names.USER_AGENT, USER_AGENT);
    if (tunnelId != null) {
      request.setHeader(HttpHeaders.Names.COOKIE, tunnelId);
    }

    return request;
  }
 @Test
 public void ifNoneMatchHeader() throws Exception {
   final SockJsConfig config = config();
   final String path = config.prefix() + "/iframe.html";
   final HttpRequest httpRequest = createHttpRequest(path);
   httpRequest.headers().set(HttpHeaders.Names.IF_NONE_MATCH, "*");
   final FullHttpResponse response = Iframe.response(config, httpRequest);
   assertThat(
       response.headers().get(HttpHeaders.Names.SET_COOKIE), equalTo("JSESSIONID=dummy; path=/"));
   assertThat(response.getStatus().code(), is(HttpResponseStatus.NOT_MODIFIED.code()));
 }
Esempio n. 17
0
  public FileChunk get() throws IOException {
    if (useLocalFile) {
      startTime = System.currentTimeMillis();
      finishTime = System.currentTimeMillis();
      state = TajoProtos.FetcherState.FETCH_FINISHED;
      return fileChunk;
    }

    this.startTime = System.currentTimeMillis();
    this.state = TajoProtos.FetcherState.FETCH_FETCHING;
    ChannelFuture future = null;
    try {
      future =
          bootstrap
              .clone()
              .connect(new InetSocketAddress(host, port))
              .addListener(ChannelFutureListener.CLOSE_ON_FAILURE);

      // Wait until the connection attempt succeeds or fails.
      Channel channel = future.awaitUninterruptibly().channel();
      if (!future.isSuccess()) {
        state = TajoProtos.FetcherState.FETCH_FAILED;
        throw new IOException(future.cause());
      }

      String query = uri.getPath() + (uri.getRawQuery() != null ? "?" + uri.getRawQuery() : "");
      // Prepare the HTTP request.
      HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, query);
      request.headers().set(HttpHeaders.Names.HOST, host);
      request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
      request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);

      LOG.info("Status: " + getState() + ", URI:" + uri);
      // Send the HTTP request.
      channel.writeAndFlush(request);

      // Wait for the server to close the connection. throw exception if failed
      channel.closeFuture().syncUninterruptibly();

      fileChunk.setLength(fileChunk.getFile().length());
      return fileChunk;
    } finally {
      if (future != null && future.channel().isOpen()) {
        // Close the channel to exit.
        future.channel().close().awaitUninterruptibly();
      }

      this.finishTime = System.currentTimeMillis();
      LOG.info(
          "Fetcher finished:" + (finishTime - startTime) + " ms, " + getState() + ", URI:" + uri);
    }
  }
  private static boolean isRequestTo(HttpRequest request, String uri) {
    URI decodedUri;
    try {
      decodedUri = new URI(request.getUri());
    } catch (URISyntaxException e) {
      return false;
    }

    return HttpVersion.HTTP_1_1.equals(request.getProtocolVersion())
        && USER_AGENT.equals(request.getHeader(HttpHeaders.Names.USER_AGENT))
        && HttpMethod.POST.equals(request.getMethod())
        && uri.equals(decodedUri.getPath());
  }
 @Override
 public @Nullable FullHttpResponse handleRequest(ChannelHandlerContext ctx, HttpRequest request)
     throws Exception {
   QueryStringDecoder decoder = new QueryStringDecoder(request.uri());
   List<String> agentIds = decoder.parameters().get("agent-id");
   if (agentIds == null) {
     agentIds = ImmutableList.of("");
   }
   String agentId = agentIds.get(0);
   List<String> traceIds = decoder.parameters().get("trace-id");
   checkNotNull(traceIds, "Missing trace id in query string: %s", request.uri());
   String traceId = traceIds.get(0);
   // check-live-traces is an optimization so glowroot server only has to check with remote
   // agents when necessary
   List<String> checkLiveTracesParams = decoder.parameters().get("check-live-traces");
   boolean checkLiveTraces = false;
   if (checkLiveTracesParams != null && !checkLiveTracesParams.isEmpty()) {
     checkLiveTraces = Boolean.parseBoolean(checkLiveTracesParams.get(0));
   }
   logger.debug(
       "handleRequest(): agentId={}, traceId={}, checkLiveTraces={}",
       agentId,
       traceId,
       checkLiveTraces);
   TraceExport traceExport = traceCommonService.getExport(agentId, traceId, checkLiveTraces);
   if (traceExport == null) {
     logger.warn("no trace found for id: {}", traceId);
     return new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND);
   }
   ChunkedInput<HttpContent> in = getExportChunkedInput(traceExport);
   HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
   response.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
   response.headers().set(HttpHeaderNames.CONTENT_TYPE, MediaType.ZIP.toString());
   response
       .headers()
       .set("Content-Disposition", "attachment; filename=" + traceExport.fileName() + ".zip");
   boolean keepAlive = HttpUtil.isKeepAlive(request);
   if (keepAlive && !request.protocolVersion().isKeepAliveDefault()) {
     response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
   }
   HttpServices.preventCaching(response);
   ctx.write(response);
   ChannelFuture future = ctx.write(in);
   HttpServices.addErrorListener(future);
   if (!keepAlive) {
     HttpServices.addCloseListener(future);
   }
   // return null to indicate streaming
   return null;
 }
  @Test
  public void testPerformOpeningHandshake() {
    Channel channelMock = EasyMock.createMock(Channel.class);

    DefaultChannelPipeline pipeline = createPipeline(channelMock);
    EasyMock.expect(channelMock.pipeline()).andReturn(pipeline);

    // capture the http response in order to verify the headers
    Capture<HttpResponse> res = new Capture<HttpResponse>();
    EasyMock.expect(channelMock.write(capture(res)))
        .andReturn(new DefaultChannelFuture(channelMock, true));

    replay(channelMock);

    HttpRequest req = new DefaultHttpRequest(HTTP_1_1, HttpMethod.GET, "/chat");
    req.setHeader(Names.HOST, "server.example.com");
    req.setHeader(Names.UPGRADE, WEBSOCKET.toLowerCase());
    req.setHeader(Names.CONNECTION, "Upgrade");
    req.setHeader(Names.SEC_WEBSOCKET_KEY, "dGhlIHNhbXBsZSBub25jZQ==");
    req.setHeader(Names.SEC_WEBSOCKET_ORIGIN, "http://example.com");
    req.setHeader(Names.SEC_WEBSOCKET_PROTOCOL, "chat, superchat");
    req.setHeader(Names.SEC_WEBSOCKET_VERSION, "13");
    WebSocketServerHandshaker13 handsaker =
        new WebSocketServerHandshaker13("ws://example.com/chat", "chat", false, Integer.MAX_VALUE);
    handsaker.handshake(channelMock, req);

    Assert.assertEquals(
        "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", res.getValue().getHeader(Names.SEC_WEBSOCKET_ACCEPT));
    Assert.assertEquals("chat", res.getValue().getHeader(Names.SEC_WEBSOCKET_PROTOCOL));
  }
Esempio n. 21
0
 @URLPattern("/hello/[a-zA-Z]{3,3}[A-Za-z0-9]*")
 public FullHttpResponse parameterized(HttpRequest req) {
   return new DefaultFullHttpResponse(
       HTTP_1_1,
       OK,
       Unpooled.wrappedBuffer(("Hello " + req.uri().replaceAll("/hello/", "")).getBytes()));
 }
  private boolean handleConnectOKAndExit(
      int statusCode,
      Realm realm,
      final Request request,
      HttpRequest httpRequest,
      HttpResponse response,
      final NettyResponseFuture<?> future,
      ProxyServer proxyServer,
      final Channel channel)
      throws IOException {
    if (statusCode == OK.code() && httpRequest.getMethod() == HttpMethod.CONNECT) {

      LOGGER.debug("Connected to {}:{}", proxyServer.getHost(), proxyServer.getPort());

      if (future.isKeepAlive()) {
        future.attachChannel(channel, true);
      }

      try {
        LOGGER.debug("Connecting to proxy {} for scheme {}", proxyServer, request.getUrl());
        channels.upgradeProtocol(channel.pipeline(), request.getURI().getScheme());
      } catch (Throwable ex) {
        channels.abort(future, ex);
      }
      future.setReuseChannel(true);
      future.setConnectAllowed(false);
      requestSender.sendNextRequest(new RequestBuilder(future.getRequest()).build(), future);
      return true;
    }

    return false;
  }
  /**
   * Handle the web socket handshake for the web socket specification <a href=
   * "http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17">HyBi versions 13-17</a>.
   * Versions 13-17 share the same wire protocol.
   *
   * <p>Browser request to the server:
   *
   * <pre>
   * GET /chat HTTP/1.1
   * Host: server.example.com
   * Upgrade: websocket
   * Connection: Upgrade
   * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
   * Sec-WebSocket-Origin: http://example.com
   * Sec-WebSocket-Protocol: chat, superchat
   * Sec-WebSocket-Version: 13
   * </pre>
   *
   * <p>Server response:
   *
   * <pre>
   * HTTP/1.1 101 Switching Protocols
   * Upgrade: websocket
   * Connection: Upgrade
   * Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
   * Sec-WebSocket-Protocol: chat
   * </pre>
   *
   * @param channel Channel
   * @param req HTTP request
   */
  @Override
  public ChannelFuture handshake(Channel channel, HttpRequest req) {

    if (logger.isDebugEnabled()) {
      logger.debug(String.format("Channel %s WS Version 13 server handshake", channel.getId()));
    }

    HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.SWITCHING_PROTOCOLS);

    String key = req.getHeader(Names.SEC_WEBSOCKET_KEY);
    if (key == null) {
      throw new WebSocketHandshakeException("not a WebSocket request: missing key");
    }
    String acceptSeed = key + WEBSOCKET_13_ACCEPT_GUID;
    byte[] sha1 = WebSocketUtil.sha1(acceptSeed.getBytes(CharsetUtil.US_ASCII));
    String accept = WebSocketUtil.base64(sha1);

    if (logger.isDebugEnabled()) {
      logger.debug(
          String.format("WS Version 13 Server Handshake key: %s. Response: %s.", key, accept));
    }

    res.setStatus(HttpResponseStatus.SWITCHING_PROTOCOLS);
    res.addHeader(Names.UPGRADE, WEBSOCKET.toLowerCase());
    res.addHeader(Names.CONNECTION, Names.UPGRADE);
    res.addHeader(Names.SEC_WEBSOCKET_ACCEPT, accept);
    String protocol = req.getHeader(Names.SEC_WEBSOCKET_PROTOCOL);
    if (protocol != null) {
      res.addHeader(Names.SEC_WEBSOCKET_PROTOCOL, selectSubprotocol(protocol));
    }

    ChannelFuture future = channel.write(res);

    // Upgrade the connection and send the handshake response.
    ChannelPipeline p = channel.getPipeline();
    if (p.get(HttpChunkAggregator.class) != null) {
      p.remove(HttpChunkAggregator.class);
    }

    p.replace(
        HttpRequestDecoder.class,
        "wsdecoder",
        new WebSocket13FrameDecoder(true, allowExtensions, this.getMaxFramePayloadLength()));
    p.replace(HttpResponseEncoder.class, "wsencoder", new WebSocket13FrameEncoder(false));

    return future;
  }
Esempio n. 24
0
  public static MultivaluedMap<String, String> extractRequestHeaders(HttpRequest request) {
    Headers<String> requestHeaders = new Headers<String>();

    for (Map.Entry<String, String> header : request.headers()) {
      requestHeaders.add(header.getKey(), header.getValue());
    }
    return requestHeaders;
  }
Esempio n. 25
0
 @Override
 public void channelRead0(final ChannelHandlerContext ctx, HttpRequest req) throws Exception {
   if (req.getUri().equals("/hello")) {
     ctx.executor().schedule(new HelloWorldRunnable(ctx), 10, TimeUnit.SECONDS);
   } else {
     ctx.fireChannelRead(req);
   }
 }
Esempio n. 26
0
  private void writeResponse(Channel channel) {
    // Convert the response content to a ChannelBuffer.
    ByteBuf buf = copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8);
    responseContent.setLength(0);

    // Decide whether to close the connection or not.
    boolean close =
        request.headers().contains(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE, true)
            || request.protocolVersion().equals(HttpVersion.HTTP_1_0)
                && !request
                    .headers()
                    .contains(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE, true);

    // Build the response object.
    FullHttpResponse response =
        new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");

    if (!close) {
      // There's no need to add 'Content-Length' header
      // if this is the last response.
      response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, buf.readableBytes());
    }

    Set<Cookie> cookies;
    String value = request.headers().getAndConvert(HttpHeaderNames.COOKIE);
    if (value == null) {
      cookies = Collections.emptySet();
    } else {
      cookies = ServerCookieDecoder.STRICT.decode(value);
    }
    if (!cookies.isEmpty()) {
      // Reset the cookies if necessary.
      for (Cookie cookie : cookies) {
        response
            .headers()
            .add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie));
      }
    }
    // Write the response.
    ChannelFuture future = channel.writeAndFlush(response);
    // Close the connection after the write operation is done if necessary.
    if (close) {
      future.addListener(ChannelFutureListener.CLOSE);
    }
  }
Esempio n. 27
0
 boolean isKeepAlive() {
   String connHeader = req.headers().get("Connection");
   if (isOlderHttpVersion()) {
     return ((connHeader != null) && "keep-alive".equalsIgnoreCase(connHeader));
   } else {
     return ((connHeader == null) || !"close".equalsIgnoreCase(connHeader));
   }
 }
Esempio n. 28
0
 @Override
 public MultiMap headers() {
   synchronized (getLock()) {
     if (headers == null) {
       headers = new HeadersAdaptor(request.headers());
     }
     return headers;
   }
 }
Esempio n. 29
0
  public static ResteasyUriInfo extractUriInfo(
      HttpRequest request, String contextPath, String protocol) {
    String host = HttpHeaders.getHost(request, "unknown");
    String uri = request.getUri();

    String uriString = protocol + "://" + host + uri;
    URI absoluteURI = URI.create(uriString);
    URI noQuery = UriBuilder.fromUri(uriString).replaceQuery(null).build();
    return new ResteasyUriInfo(uriString, absoluteURI.getRawQuery(), contextPath);
  }
 @Override
 protected void doGet(ChannelHandlerContext ctx, HttpRequest httpReq) {
   getCount++;
   processTime();
   QueryStringDecoder reqDecoder = new QueryStringDecoder(httpReq.getUri());
   String data = reqDecoder.parameters().get("data").get(0);
   Payload payload = JSONSerializer.INSTANCE.fromString(data, Payload.class);
   writeJSON(ctx, httpReq, payload);
   this.writeContent(ctx, httpReq, "do get", "text/plain");
 }