/**
     * @see
     *     com.linkedin.databus.client.netty.AbstractHttpResponseProcessorDecorator#startResponse(org.jboss.netty.handler.codec.http.HttpResponse)
     */
    @Override
    public void startResponse(HttpResponse response) throws Exception {
      // check for errors in the response
      _serverErrorClass = response.getHeader(DatabusHttpHeaders.DATABUS_ERROR_CAUSE_CLASS_HEADER);
      _serverErrorMessage =
          response.getHeader(DatabusHttpHeaders.DATABUS_ERROR_CAUSE_MESSAGE_HEADER);
      if (null == _serverErrorClass) {
        _serverErrorClass = response.getHeader(DatabusHttpHeaders.DATABUS_ERROR_CLASS_HEADER);
        _serverErrorMessage = response.getHeader(DatabusHttpHeaders.DATABUS_ERROR_MESSAGE_HEADER);
      }
      if (null != _serverErrorClass) {
        if (null != _parent) {
          _parent
              .getLog()
              .error(
                  "server error detected class="
                      + _serverErrorClass
                      + " message="
                      + _serverErrorMessage);
        }
      }

      super.startResponse(response);
      if (null != _parent) _parent.addConnectionTracking(response);
    }
 HttpClientResponse(ClientConnection conn, HttpResponse response, Thread th) {
   this.conn = conn;
   this.statusCode = response.getStatus().getCode();
   this.statusMessage = response.getStatus().getReasonPhrase();
   this.response = response;
   this.th = th;
 }
  public static HttpResponse buildHttpServletResponse(HttpResponseExchange forwardResponse)
      throws IOException {

    if (null == forwardResponse) {
      return new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.REQUEST_TIMEOUT);
    }
    HttpResponse response =
        new DefaultHttpResponse(
            HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(forwardResponse.getResponseCode()));

    List<String[]> headers = forwardResponse.getHeaders();
    for (String[] header : headers) {
      if (header[0].equalsIgnoreCase(HttpHeaders.Names.SET_COOKIE)
          || header[0].equalsIgnoreCase(HttpHeaders.Names.SET_COOKIE2)) {
        List<SetCookieHeaderValue> cookies = SetCookieHeaderValue.parse(header[1]);
        for (SetCookieHeaderValue cookie : cookies) {
          response.addHeader(header[0], cookie.toString());
        }
      } else {
        response.addHeader(header[0], header[1]);
      }
    }
    byte[] content = forwardResponse.getBody();
    if (null != content) {
      ChannelBuffer bufer = ChannelBuffers.wrappedBuffer(content);
      response.setContent(bufer);
    }

    return response;
  }
  private static void sendStatus(
      HttpResponse response,
      @Nullable HttpRequest request,
      Channel channel,
      @Nullable String description) {
    response.setHeader(CONTENT_TYPE, "text/html");
    if (request == null || request.getMethod() != HttpMethod.HEAD) {
      String message = response.getStatus().toString();

      StringBuilder builder = new StringBuilder();
      builder
          .append("<!doctype html><title>")
          .append(message)
          .append("</title>")
          .append("<h1 style=\"text-align: center\">")
          .append(message)
          .append("</h1>");
      if (description != null) {
        builder.append("<p>").append(description).append("</p>");
      }
      builder
          .append("<hr/><p style=\"text-align: center\">")
          .append(StringUtil.notNullize(getServerHeaderValue(), ""))
          .append("</p>");

      response.setContent(ChannelBuffers.copiedBuffer(builder, CharsetUtil.UTF_8));
    }
    send(response, channel, request);
  }
  private void handleHttpRequest(ChannelHandlerContext ctx, HttpRequest req) throws Exception {
    // Allow only GET methods.
    if (req.getMethod() != GET) {
      sendHttpResponse(ctx, req, new DefaultHttpResponse(HTTP_1_1, FORBIDDEN));
      return;
    }

    // Send the demo page and favicon.ico
    if (req.getUri().equals("/")) {
      HttpResponse res = new DefaultHttpResponse(HTTP_1_1, OK);

      ChannelBuffer content = WebSocketServerIndexPage.getContent(getWebSocketLocation(req));

      res.setHeader(CONTENT_TYPE, "text/html; charset=UTF-8");
      setContentLength(res, content.readableBytes());

      res.setContent(content);
      sendHttpResponse(ctx, req, res);
      return;
    } else if (req.getUri().equals("/favicon.ico")) {
      HttpResponse res = new DefaultHttpResponse(HTTP_1_1, NOT_FOUND);
      sendHttpResponse(ctx, req, res);
      return;
    }

    // Handshake
    WebSocketServerHandshakerFactory wsFactory =
        new WebSocketServerHandshakerFactory(this.getWebSocketLocation(req), null, false);
    this.handshaker = wsFactory.newHandshaker(ctx, req);
    if (this.handshaker == null) {
      wsFactory.sendUnsupportedWebSocketVersionResponse(ctx);
    } else {
      this.handshaker.executeOpeningHandshake(ctx, req);
    }
  }
Exemple #6
0
  public static void serve404(
      NotFound e, ChannelHandlerContext ctx, Request request, HttpRequest nettyRequest) {
    Logger.trace("serve404: begin");
    HttpResponse nettyResponse =
        new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);
    nettyResponse.setHeader(SERVER, signature);

    nettyResponse.setHeader(CONTENT_TYPE, "text/html");
    Map<String, Object> binding = getBindingForErrors(e, false);

    String format = Request.current().format;
    if (format == null) {
      format = "txt";
    }
    nettyResponse.setHeader(
        CONTENT_TYPE, (MimeTypes.getContentType("404." + format, "text/plain")));

    String errorHtml = TemplateLoader.load("errors/404." + format).render(binding);
    try {
      ChannelBuffer buf = ChannelBuffers.copiedBuffer(errorHtml.getBytes("utf-8"));
      nettyResponse.setContent(buf);
      ChannelFuture writeFuture = ctx.getChannel().write(nettyResponse);
      writeFuture.addListener(ChannelFutureListener.CLOSE);
    } catch (UnsupportedEncodingException fex) {
      Logger.error(fex, "(utf-8 ?)");
    }
    Logger.trace("serve404: end");
  }
Exemple #7
0
  protected static void addToResponse(Response response, HttpResponse nettyResponse) {
    Map<String, Http.Header> headers = response.headers;
    for (Map.Entry<String, Http.Header> entry : headers.entrySet()) {
      Http.Header hd = entry.getValue();
      for (String value : hd.values) {
        nettyResponse.setHeader(entry.getKey(), value);
      }
    }
    Map<String, Http.Cookie> cookies = response.cookies;

    for (Http.Cookie cookie : cookies.values()) {
      CookieEncoder encoder = new CookieEncoder(true);
      Cookie c = new DefaultCookie(cookie.name, cookie.value);
      c.setSecure(cookie.secure);
      c.setPath(cookie.path);
      if (cookie.domain != null) {
        c.setDomain(cookie.domain);
      }
      if (cookie.maxAge != null) {
        c.setMaxAge(cookie.maxAge);
      }
      c.setHttpOnly(cookie.httpOnly);
      encoder.addCookie(c);
      nettyResponse.addHeader(SET_COOKIE, encoder.encode());
    }

    if (!response.headers.containsKey(CACHE_CONTROL)) {
      nettyResponse.setHeader(CACHE_CONTROL, "no-cache");
    }
  }
Exemple #8
0
 @Override
 public NettyHttpResponse chunked() {
   response.setHeader(Names.TRANSFER_ENCODING, Values.CHUNKED);
   response.setChunked(true);
   ctx.getChannel().write(response);
   return this;
 }
  @Override
  public void populateCamelHeaders(
      HttpResponse response,
      Map<String, Object> headers,
      Exchange exchange,
      NettyHttpConfiguration configuration)
      throws Exception {
    LOG.trace("populateCamelHeaders: {}", response);

    headers.put(Exchange.HTTP_RESPONSE_CODE, response.getStatus().getCode());
    headers.put(Exchange.HTTP_RESPONSE_TEXT, response.getStatus().getReasonPhrase());

    for (String name : response.headers().names()) {
      // mapping the content-type
      if (name.toLowerCase().equals("content-type")) {
        name = Exchange.CONTENT_TYPE;
      }
      // add the headers one by one, and use the header filter strategy
      List<String> values = response.headers().getAll(name);
      Iterator<?> it = ObjectHelper.createIterator(values);
      while (it.hasNext()) {
        Object extracted = it.next();
        LOG.trace("HTTP-header: {}", extracted);
        if (headerFilterStrategy != null
            && !headerFilterStrategy.applyFilterToExternalHeaders(name, extracted, exchange)) {
          NettyHttpHelper.appendHeader(headers, name, extracted);
        }
      }
    }
  }
  /**
   * Writes the specified TaskResult data to the channel output. Only the raw output data is written
   * and rest of the TaskResult fields are ignored
   *
   * @param ctx the ChannelHandlerContext
   * @param event the ChannelEvent
   * @throws Exception in case of any errors
   */
  private void writeCommandExecutionResponse(
      ChannelHandlerContext ctx, ChannelEvent event, HttpResponse response) throws Exception {
    // Don't write anything if the response is null
    if (response == null) {
      // write empty response
      event
          .getChannel()
          .write(new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NO_CONTENT))
          .addListener(ChannelFutureListener.CLOSE);
      return;
    }
    org.jboss.netty.handler.codec.http.HttpResponse httpResponse =
        new DefaultHttpResponse(
            HttpVersion.HTTP_1_1,
            HttpResponseStatus.valueOf(response.getStatusLine().getStatusCode()));
    // write headers
    for (Header header : response.getAllHeaders()) {
      if (!RoutingHttpChannelHandler.REMOVE_HEADERS.contains(header.getName())) {
        httpResponse.setHeader(header.getName(), header.getValue());
      }
    }

    // write entity
    HttpEntity responseEntity = response.getEntity();
    byte[] responseData = EntityUtils.toByteArray(responseEntity);
    httpResponse.setContent(ChannelBuffers.copiedBuffer(responseData));
    // write response
    event.getChannel().write(httpResponse).addListener(ChannelFutureListener.CLOSE);
  }
  public void sendResponse(final MessageEvent e) {
    // Build the response object.
    final HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);

    final ByteArrayOutputStream bos = receivedData;
    try {
      bos.write(" successfully received by server".getBytes("UTF-8"));
    } catch (final UnsupportedEncodingException e1) {
      e1.printStackTrace();
    } catch (final IOException e1) {
      e1.printStackTrace();
    }
    final ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(bos.toByteArray());
    response.setContent(buffer);
    // response.setContent(arg0)
    // response.setContent(ChannelBuffers.copiedBuffer(buf.toString(),
    // CharsetUtil.UTF_8));
    response.setHeader(CONTENT_TYPE, "application/octet-stream");

    final ChannelFuture future = e.getChannel().write(response);

    // Close the non-keep-alive connection after the write operation is
    // done.
    // if (!keepAlive) {
    future.addListener(ChannelFutureListener.CLOSE);
    // }
  }
 public NettyHttpResponse header(String name, String value) {
   if (value == null) {
     response.removeHeader(name);
   } else {
     response.addHeader(name, value);
   }
   return this;
 }
  private void sendError(ChannelHandlerContext ctx, String message, HttpResponseStatus status) {
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
    response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
    response.setContent(ChannelBuffers.copiedBuffer(message, CharsetUtil.UTF_8));

    // Close the connection as soon as the error message is sent.
    ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
  }
 public static void sendOptionsResponse(
     String allowHeaders, HttpRequest request, ChannelHandlerContext context) {
   HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
   response.setHeader(ACCESS_CONTROL_ALLOW_ORIGIN, "*");
   response.setHeader(ACCESS_CONTROL_ALLOW_METHODS, allowHeaders);
   response.setHeader(ALLOW, allowHeaders);
   send(response, request, context);
 }
 @Override
 public void addHeader(String name, String value) {
   if (name.equalsIgnoreCase("content-type") && response.containsHeader("Content-Type")) {
     setHeader(name, value);
   } else {
     response.addHeader(name, value);
   }
 }
 public static void send(
     String contentType,
     CharSequence content,
     HttpRequest request,
     ChannelHandlerContext context) {
   HttpResponse response = create(contentType);
   response.setContent(ChannelBuffers.copiedBuffer(content, CharsetUtil.UTF_8));
   send(response, request, context);
 }
  private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status);
    response.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=UTF-8");
    response.setContent(
        ChannelBuffers.copiedBuffer(
            "Failure: " + status.toString() + "\r\n", Charset.forName("UTF-8")));

    // Close the connection as soon as the error message is sent.
    ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
  }
 public Deferred<HttpResponse> process(ChannelHandlerContext context, HttpRequest request) {
   HttpResponse response =
       new DefaultHttpResponse(request.getProtocolVersion(), HttpResponseStatus.OK);
   response.setHeader("content-type", "text/html");
   response.setContent(
       ChannelBuffers.copiedBuffer("Accepted ShutDown Request", Charset.defaultCharset()));
   Deferred<HttpResponse> deferred = new Deferred<HttpResponse>();
   deferred.callback(response);
   shutdown();
   super.doShutdown(context.getChannel());
   return deferred;
 }
  private void sendHttpResponse(ChannelHandlerContext ctx, HttpRequest req, HttpResponse res) {
    // Generate an error page if response status code is not OK (200).
    if (res.getStatus().getCode() != 200) {
      res.setContent(ChannelBuffers.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8));
      setContentLength(res, res.getContent().readableBytes());
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.getChannel().write(res);
    if (!isKeepAlive(req) || res.getStatus().getCode() != 200) {
      f.addListener(ChannelFutureListener.CLOSE);
    }
  }
Exemple #20
0
 /* 此函数封装一个响应信息
  * 当需要发送信息给用户时,此函数将被调用
  * @param       [res]                   响应对象
  * @param       [setCookie]             是否需要强制浏览器设置cookie
  * @param       [sessionId]             当setCookie为真时使用,服务器产生的sessionId
  * @param       [content]               服务器响应内容
  * @param       [contentLength]         服务器响应内容长度
  */
 private void buildResponse(
     HttpResponse res,
     boolean setCookie,
     String sessionId,
     ChannelBuffer content,
     int contentLength) {
   if (setCookie == true) {
     res.setHeader(SET_COOKIE, sessionId);
   }
   res.setHeader(CONTENT_TYPE, "text/html; charset=UTF-8");
   setContentLength(res, content.readableBytes());
   res.setContent(content);
 }
Exemple #21
0
 /*
  * 私有函数,服务器发送响应给用户时将被调用调用
  * @param       [ctx]       channelHandler中的上下文
  * @param       [req]       消息请求
  * @param       [res]       消息响应
  */
 private void sendHttpResponse(ChannelHandlerContext ctx, HttpRequest req, HttpResponse res) {
   if (res.getStatus().getCode() != 200) {
     // 将响应信息以UTF_8编码格式写回
     ChannelBuffer content =
         ChannelBuffers.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
     int contentLength = res.getContent().readableBytes();
     buildResponse(res, false, null, content, contentLength);
   }
   ChannelFuture f = ctx.getChannel().write(res);
   if (!isKeepAlive(req) || res.getStatus().getCode() != 200) {
     f.addListener(ChannelFutureListener.CLOSE);
   }
 }
  /**
   * Process server response:
   *
   * <pre>
   * HTTP/1.1 101 WebSocket Protocol Handshake
   * Upgrade: WebSocket
   * Connection: Upgrade
   * Sec-WebSocket-Origin: http://example.com
   * Sec-WebSocket-Location: ws://example.com/demo
   * Sec-WebSocket-Protocol: sample
   *
   * 8jKS'y:G*Co,Wxa-
   * </pre>
   *
   * @param ctx Channel context
   * @param response HTTP response returned from the server for the request sent by
   *     beginOpeningHandshake00().
   * @throws WebSocketHandshakeException
   */
  @Override
  public void endOpeningHandshake(ChannelHandlerContext ctx, HttpResponse response)
      throws WebSocketHandshakeException {
    final HttpResponseStatus status = new HttpResponseStatus(101, "WebSocket Protocol Handshake");

    if (!response.getStatus().equals(status)) {
      throw new WebSocketHandshakeException(
          "Invalid handshake response status: " + response.getStatus());
    }

    String upgrade = response.getHeader(Names.UPGRADE);
    if (upgrade == null || !upgrade.equals(Values.WEBSOCKET)) {
      throw new WebSocketHandshakeException(
          "Invalid handshake response upgrade: " + response.getHeader(Names.UPGRADE));
    }

    String connection = response.getHeader(Names.CONNECTION);
    if (connection == null || !connection.equals(Values.UPGRADE)) {
      throw new WebSocketHandshakeException(
          "Invalid handshake response connection: " + response.getHeader(Names.CONNECTION));
    }

    byte[] challenge = response.getContent().array();
    if (!Arrays.equals(challenge, expectedChallengeResponseBytes)) {
      throw new WebSocketHandshakeException("Invalid challenge");
    }

    String protocol = response.getHeader(Names.SEC_WEBSOCKET_PROTOCOL);
    this.setSubProtocolResponse(protocol);

    ctx.getPipeline().replace("decoder", "ws-decoder", new WebSocket00FrameDecoder());

    this.setOpenningHandshakeCompleted(true);
    return;
  }
 protected void addConnectionTracking(HttpResponse response) throws Exception {
   boolean debugEnabled = _log.isDebugEnabled();
   _hostHdr = response.getHeader(DatabusHttpHeaders.DBUS_SERVER_HOST_HDR);
   _svcHdr = response.getHeader(DatabusHttpHeaders.DBUS_SERVER_SERVICE_HDR);
   if (debugEnabled) {
     if (null != _hostHdr) {
       _log.debug("Received response for databus server host: " + _hostHdr);
     }
     if (null != _svcHdr) {
       _log.debug("Received response for databus server host: " + _svcHdr);
     }
   }
   return;
 }
  private void sendResponse(
      ChannelHandlerContext channel,
      HttpRequest request,
      String messageBody,
      HttpResponseStatus status) {

    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status);

    if (messageBody != null && !messageBody.isEmpty()) {
      response.setContent(ChannelBuffers.copiedBuffer(messageBody, Constants.DEFAULT_CHARSET));
    }

    Tracker.getInstance().trackResponse(request, response);
    HttpResponder.respond(channel, request, response);
  }
 protected boolean isContentAlwaysEmpty(HttpMessage msg) {
   if (msg instanceof HttpResponse) {
     HttpResponse res = (HttpResponse) msg;
     int code = res.getStatus().getCode();
     if (code < 200) {
       return true;
     }
     switch (code) {
       case 204:
       case 205:
       case 304:
         return true;
     }
   }
   return false;
 }
 private void writeHead() {
   if (!headWritten) {
     HttpResponseStatus status =
         statusMessage == null
             ? HttpResponseStatus.valueOf(statusCode)
             : new HttpResponseStatus(statusCode, statusMessage);
     response.setStatus(status);
     if (chunked) {
       response.setHeader(Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED);
     } else if (contentLength == 0) {
       response.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "0");
     }
     writeFuture = conn.write(response);
     headWritten = true;
   }
 }
Exemple #27
0
 private NettyHttpResponse content(ChannelBuffer content) {
   if (response.isChunked()) {
     throw new UnsupportedOperationException();
   }
   responseBuffer.writeBytes(content);
   return this;
 }
Exemple #28
0
  protected static void writeResponse(
      ChannelHandlerContext ctx,
      Response response,
      HttpResponse nettyResponse,
      HttpRequest nettyRequest) {
    Logger.trace("writeResponse: begin");
    byte[] content = null;

    final boolean keepAlive = isKeepAlive(nettyRequest);
    if (nettyRequest.getMethod().equals(HttpMethod.HEAD)) {
      content = new byte[0];
    } else {
      content = response.out.toByteArray();
    }

    ChannelBuffer buf = ChannelBuffers.copiedBuffer(content);
    nettyResponse.setContent(buf);

    if (keepAlive) {
      // Add 'Content-Length' header only for a keep-alive connection.
      Logger.trace("writeResponse: content length [" + response.out.size() + "]");
      setContentLength(nettyResponse, response.out.size());
    }

    ChannelFuture f = ctx.getChannel().write(nettyResponse);

    // Decide whether to close the connection or not.
    if (!keepAlive) {
      // Close the connection when the whole content is written out.
      f.addListener(ChannelFutureListener.CLOSE);
    }
    Logger.trace("writeResponse: end");
  }
 public static boolean addKeepAliveIfNeed(HttpResponse response, HttpRequest request) {
   if (isKeepAlive(request)) {
     response.setHeader(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
     return true;
   }
   return false;
 }
 @Override
 public void messageReceived(ChannelHandlerContext context, MessageEvent e) throws Exception {
   if (e.getMessage() instanceof HttpRequest) {
     HttpRequest message = (HttpRequest) e.getMessage();
     HttpResponse response;
     if (new QueryStringDecoder(message.getUri()).getPath().equals(START_TIME_PATH)) {
       response = new DefaultHttpResponse(HTTP_1_1, OK);
       response.setHeader("Access-Control-Allow-Origin", "*");
       response.setContent(
           ChannelBuffers.copiedBuffer(getApplicationStartTime(), CharsetUtil.US_ASCII));
     } else {
       response = new DefaultHttpResponse(HTTP_1_1, NOT_FOUND);
     }
     context.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
   }
 }