public DefaultHttpResponse getEmptyHttpResponse() {
   DefaultFullHttpResponse res =
       new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.valueOf(getStatus()));
   res.headers().add(Names.CONTENT_LENGTH, EMPTY_CONTENT_LENGTH);
   transformResponseHeaders(res);
   return res;
 }
Ejemplo n.º 2
0
  private void send(final ByteBuf buffer) throws Exception {
    DefaultFullHttpResponse rsp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, buffer);

    if (!headers.contains(HttpHeaderNames.CONTENT_LENGTH)) {
      headers
          .remove(HttpHeaderNames.TRANSFER_ENCODING)
          .set(HttpHeaderNames.CONTENT_LENGTH, buffer.readableBytes());
    }

    if (keepAlive) {
      headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }

    // dump headers
    rsp.headers().set(headers);

    Attribute<Boolean> async = ctx.attr(NettyRequest.ASYNC);
    boolean isAsync = async != null && async.get() == Boolean.TRUE;
    if (isAsync) {
      // we need flush, from async
      keepAlive(ctx.writeAndFlush(rsp));
    } else {
      keepAlive(ctx.write(rsp));
    }

    committed = true;
  }
 /*
  * Create an HTTP 400 bad request response.
  */
 public static FullHttpResponse badRequest(String msg) {
   DefaultFullHttpResponse resp = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST);
   resp.content().writeBytes(msg.getBytes());
   resp.headers().set(CONTENT_TYPE, "text/plain");
   resp.headers().set(CONTENT_LENGTH, resp.content().readableBytes());
   return resp;
 }
Ejemplo n.º 4
0
  private void respondAsLeader(ChannelHandlerContext ctx, Routed routed, ActorGateway jobManager) {
    DefaultFullHttpResponse response;

    try {
      // we only pass the first element in the list to the handlers.
      Map<String, String> queryParams = new HashMap<>();
      for (String key : routed.queryParams().keySet()) {
        queryParams.put(key, routed.queryParam(key));
      }

      InetSocketAddress address = (InetSocketAddress) ctx.channel().localAddress();
      queryParams.put(WEB_MONITOR_ADDRESS_KEY, address.getHostName() + ":" + address.getPort());

      String result = handler.handleRequest(routed.pathParams(), queryParams, jobManager);
      byte[] bytes = result.getBytes(ENCODING);

      response =
          new DefaultFullHttpResponse(
              HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(bytes));

      response.headers().set(HttpHeaders.Names.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
      response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json");
    } catch (NotFoundException e) {
      // this should result in a 404 error code (not found)
      ByteBuf message =
          e.getMessage() == null
              ? Unpooled.buffer(0)
              : Unpooled.wrappedBuffer(e.getMessage().getBytes(ENCODING));
      response =
          new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND, message);
      response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
      LOG.warn("Error while handling request", e);
    } catch (Exception e) {
      byte[] bytes = ExceptionUtils.stringifyException(e).getBytes(ENCODING);
      response =
          new DefaultFullHttpResponse(
              HttpVersion.HTTP_1_1,
              HttpResponseStatus.INTERNAL_SERVER_ERROR,
              Unpooled.wrappedBuffer(bytes));
      response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
      LOG.warn("Error while handling request", e);
    }

    response.headers().set(HttpHeaders.Names.CONTENT_ENCODING, "utf-8");
    response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());
    KeepAliveWrite.flush(ctx, routed.request(), response);
  }
Ejemplo n.º 5
0
  private void onGetFileChecksum(ChannelHandlerContext ctx) throws IOException {
    MD5MD5CRC32FileChecksum checksum = null;
    final String nnId = params.namenodeId();
    DFSClient dfsclient = newDfsClient(nnId, conf);
    try {
      checksum = dfsclient.getFileChecksum(path, Long.MAX_VALUE);
      dfsclient.close();
      dfsclient = null;
    } finally {
      IOUtils.cleanup(LOG, dfsclient);
    }
    final byte[] js = JsonUtil.toJsonString(checksum).getBytes(Charsets.UTF_8);
    DefaultFullHttpResponse resp =
        new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(js));

    resp.headers().set(CONTENT_TYPE, APPLICATION_JSON_UTF8);
    resp.headers().set(CONTENT_LENGTH, js.length);
    resp.headers().set(CONNECTION, CLOSE);
    ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE);
  }
 /**
  * Respond to errors occurring on a Reactor by redirecting them to the client via an HTTP 500
  * error response.
  *
  * @param channel the channel on which to send an HTTP response
  * @return a consumer to handle HTTP requests
  */
 public static Consumer<Throwable> errorHandler(
     NetChannel<FullHttpRequest, FullHttpResponse> channel) {
   return ev -> {
     DefaultFullHttpResponse resp =
         new DefaultFullHttpResponse(
             HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR);
     resp.content().writeBytes(ev.getMessage().getBytes());
     resp.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
     resp.headers().set(HttpHeaders.Names.CONTENT_LENGTH, resp.content().readableBytes());
     channel.send(resp);
   };
 }
  /*
   * Create an HTTP 200 response that contains the data of the thumbnailed image.
   */
  public static FullHttpResponse serveImage(Path path) throws IOException {
    DefaultFullHttpResponse resp = new DefaultFullHttpResponse(HTTP_1_1, OK);

    RandomAccessFile f = new RandomAccessFile(path.toString(), "r");
    resp.headers().set(CONTENT_TYPE, "image/jpeg");
    resp.headers().set(CONTENT_LENGTH, f.length());

    byte[] bytes = Files.readAllBytes(path);
    resp.content().writeBytes(bytes);

    return resp;
  }
 private void setCookies(HttpResponse response, DefaultFullHttpResponse httpServletResponse) {
   if (response.getCookies() != null) {
     List<Cookie> cookieValues = new ArrayList<Cookie>();
     for (org.mockserver.model.Cookie cookie : response.getCookies()) {
       cookieValues.add(
           new DefaultCookie(cookie.getName().getValue(), cookie.getValue().getValue()));
     }
     if (!cookieValues.isEmpty()) {
       httpServletResponse.headers().add(SET_COOKIE, ServerCookieEncoder.LAX.encode(cookieValues));
     }
   }
 }
  private void setHeaders(HttpResponse response, DefaultFullHttpResponse httpServletResponse) {
    if (response.getHeaders() != null) {
      for (Header header : response.getHeaders()) {
        for (NottableString value : header.getValues()) {
          httpServletResponse.headers().add(header.getName().getValue(), value.getValue());
        }
      }
    }

    if (Strings.isNullOrEmpty(response.getFirstHeader(CONTENT_TYPE))) {
      if (response.getBody() != null && !Strings.isNullOrEmpty(response.getBody().toString())) {
        Charset bodyCharset = response.getBody().getCharset(null);
        String bodyContentType = response.getBody().getContentType();
        if (bodyCharset != null) {
          httpServletResponse
              .headers()
              .set(CONTENT_TYPE, bodyContentType + "; charset=" + bodyCharset.name().toLowerCase());
        } else if (bodyContentType != null) {
          httpServletResponse.headers().set(CONTENT_TYPE, bodyContentType);
        }
      }
    }
  }
  protected FullHttpResponse newHandshakeResponse(FullHttpRequest var1, HttpHeaders var2) {
    DefaultFullHttpResponse var3 =
        new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.SWITCHING_PROTOCOLS);
    if (var2 != null) {
      var3.headers().add(var2);
    }

    String var4 = var1.headers().get("Sec-WebSocket-Key");
    if (var4 == null) {
      throw new WebSocketHandshakeException("not a WebSocket request: missing key");
    } else {
      String var5 = var4 + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
      byte[] var6 = WebSocketUtil.sha1(var5.getBytes(CharsetUtil.US_ASCII));
      String var7 = WebSocketUtil.base64(var6);
      if (logger.isDebugEnabled()) {
        logger.debug("WebSocket version 13 server handshake key: {}, response: {}", var4, var7);
      }

      var3.headers().add((String) "Upgrade", (Object) "WebSocket".toLowerCase());
      var3.headers().add((String) "Connection", (Object) "Upgrade");
      var3.headers().add((String) "Sec-WebSocket-Accept", (Object) var7);
      String var8 = var1.headers().get("Sec-WebSocket-Protocol");
      if (var8 != null) {
        String var9 = this.selectSubprotocol(var8);
        if (var9 == null) {
          if (logger.isDebugEnabled()) {
            logger.debug("Requested subprotocol(s) not supported: {}", (Object) var8);
          }
        } else {
          var3.headers().add((String) "Sec-WebSocket-Protocol", (Object) var9);
        }
      }

      return var3;
    }
  }
Ejemplo n.º 11
0
  private void messageReceive(ChannelHandlerContext ctx, DefaultFullHttpResponse response) {
    /** send next cmd * */
    switch (state) {
      case PLAY:
        String rtpInfo = response.headers().get("RTP-Info");

        setState(RTSP.PLAYING);
        break;
      case SETUP:
        // session
        String sessionId = response.headers().get("Session");
        if (null != sessionId) {
          Matcher matcher = Pattern.compile("([^;]+)").matcher(sessionId);
          if (matcher.find()) {
            rtspStack.setSession(matcher.group(1));
          } else {
            rtspStack.setSession(sessionId);
          }
        }

        // transport
        InetSocketAddress remoteHost = (InetSocketAddress) ctx.channel().remoteAddress();
        String transport = response.headers().get("Transport");
        RtpSessionExt rtp = rtspStack.getLastRtpSession();
        Matcher matcher = Pattern.compile("([^\\s=;]+)=(([^-;]+)(-([^;]+))?)").matcher(transport);
        while (matcher.find()) {
          String key = matcher.group(1).toLowerCase();
          if ("server_port".equals(key)) {
            rtp.connectRtp(
                new InetSocketAddress(
                    remoteHost.getHostString(), Integer.valueOf(matcher.group(3))));
            rtp.connectRtcp(
                new InetSocketAddress(
                    remoteHost.getHostString(), Integer.valueOf(matcher.group(5))));
          } else if ("ssrc".equals(key)) {
            rtp.setSsrc(Long.parseLong(matcher.group(2).trim(), 16));
          } else if ("interleaved".equals(key)) {
            rtp.setRtpChunk(Integer.valueOf(matcher.group(3)));
            rtp.setRtcpChunk(Integer.valueOf(matcher.group(5)));
          } else {
            logger.warn("ignored [{}={}]", key, matcher.group(2));
          }
        }

        // next action
        boolean finish = setup(sd, mediaIndex++);
        if (finish) {
          sendPlay();
          setState(RTSP.PLAY);
        }

        break;
      case DESCRIBE:
        if (response.getStatus().code() == HttpResponseStatus.UNAUTHORIZED.code()) {
          sendDescribe(buildAuthorizationString(response));
          break;
        }

        String desciptor = response.content().toString(Charset.forName("UTF8"));
        SessionDescriptionImpl sd = new SessionDescriptionImpl();
        StringTokenizer tokenizer = new StringTokenizer(desciptor);
        while (tokenizer.hasMoreChars()) {
          String line = tokenizer.nextToken();

          try {
            SDPParser paser = ParserFactory.createParser(line);
            if (null != paser) {
              SDPField obj = paser.parse();
              sd.addField(obj);
            }
          } catch (ParseException e) {
            logger.warn("fail parse [{}]", line, e);
          }
        }
        this.sd = sd;

        mediaIndex = 0;
        setup(sd, mediaIndex++);

        // 心跳
        rtspStack
            .getChannel()
            .pipeline()
            .addFirst("ping", new IdleStateHandler(30, 15, 13, TimeUnit.SECONDS));

        //
        rtspStack.setSessionDescription(sd);
        break;
      case OPTIONS:
        if (response.getStatus().code() == HttpResponseStatus.UNAUTHORIZED.code()) {
          sendDescribe(buildAuthorizationString(response));
        } else {
          sendDescribe();
        }

        setState(RTSP.DESCRIBE);
        break;
      case PLAYING:
        break;
      default:
        logger.warn("I dont't Known What to do with {}", response);
        break;
    }
  }
 /*
  * Create an HTTP 301 redirect response.
  */
 public static FullHttpResponse redirect() {
   DefaultFullHttpResponse resp = new DefaultFullHttpResponse(HTTP_1_1, MOVED_PERMANENTLY);
   resp.headers().set(CONTENT_LENGTH, 0);
   resp.headers().set(LOCATION, IMG_THUMBNAIL_URI);
   return resp;
 }