示例#1
0
 default void end(RoutingContext context, HttpResponseStatus statusCode) {
   context
       .response()
       .setStatusCode(statusCode.code())
       .setStatusMessage(statusCode.reasonPhrase())
       .end();
 }
示例#2
0
  default <T extends Throwable> void error(
      RoutingContext context, HttpResponseStatus code, String message, T object) {
    HttpServerResponse response = context.response().setStatusCode(code.code());
    response.putHeader("X-API-Gateway-Error", "true");

    if (message == null) {
      response.setStatusMessage(code.reasonPhrase());
    } else {
      response.setStatusMessage(message);
    }

    if (object != null) {
      JsonObject errorResponse =
          new JsonObject()
              .put("errorType", object.getClass().getSimpleName())
              .put("message", object.getMessage());

      response
          .setChunked(true)
          .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
          .end(errorResponse.toString(), "UTF-8");
    } else {
      response.end();
    }
  }
    @Override
    public void postCall(HttpRequest request, HttpResponseStatus status, HandlerInfo handlerInfo) {
      HTTPMonitoringEvent httpMonitoringEvent =
          (HTTPMonitoringEvent) handlerInfo.getAttribute(MONITORING_EVENT);
      httpMonitoringEvent.setResponseTime(
          TimeUnit.NANOSECONDS.toMillis(
              System.nanoTime() - httpMonitoringEvent.getStartNanoTime()));
      httpMonitoringEvent.setResponseHttpStatusCode(status.code());

      Object[] meta =
          new Object[] {
            httpMonitoringEvent.getTimestamp(), SERVER_HOST_ADDRESS, SERVER_HOSTNAME, MICROSERVICE
          };
      Object[] payload = new Object[11];
      payload[0] = httpMonitoringEvent.getServiceClass();
      payload[1] = httpMonitoringEvent.getServiceName();
      payload[2] = httpMonitoringEvent.getServiceMethod();
      payload[3] = httpMonitoringEvent.getRequestUri();
      payload[4] = httpMonitoringEvent.getServiceContext();
      payload[5] = httpMonitoringEvent.getHttpMethod();
      payload[6] = httpMonitoringEvent.getContentType();
      payload[7] = httpMonitoringEvent.getRequestSizeBytes();
      payload[8] = httpMonitoringEvent.getReferrer();
      payload[9] = httpMonitoringEvent.getResponseHttpStatusCode();
      payload[10] = httpMonitoringEvent.getResponseTime();
      Event event =
          new Event(
              HTTP_MONITORING_STREAM_ID, httpMonitoringEvent.getTimestamp(), meta, null, payload);
      dataPublisher.publish(event);
    }
 protected void internalReceive(HttpResponseStatus status, HttpHeaders headers, ByteBuf content) {
   try {
     if (status.code() > 399) {
       byte[] b = new byte[content.readableBytes()];
       content.readBytes(b);
       onErrorResponse(status, headers, new String(b, CharsetUtil.UTF_8));
       return;
     }
     if (type == ByteBuf.class) {
       _doReceive(status, headers, type.cast(content));
     } else if (type == String.class || type == CharSequence.class) {
       byte[] b = new byte[content.readableBytes()];
       content.readBytes(b);
       _doReceive(status, headers, type.cast(new String(b, CharsetUtil.UTF_8)));
     } else if (type == byte[].class) {
       byte[] b = new byte[content.readableBytes()];
       content.readBytes(b);
       _doReceive(status, headers, type.cast(b));
     } else {
       ObjectMapper mapper = new ObjectMapper();
       byte[] b = new byte[content.readableBytes()];
       content.readBytes(b);
       try {
         Object o = mapper.readValue(b, type);
         _doReceive(status, headers, type.cast(o));
       } catch (Exception ex) {
         Exceptions.chuck(ex);
       }
     }
   } finally {
     latch.countDown();
   }
 }
  @Override
  public void sendError(int status, String message) throws IOException {
    if (committed) {
      throw new IllegalStateException();
    }

    final HttpResponseStatus responseStatus;
    if (message != null) {
      responseStatus = new HttpResponseStatus(status, message);
      setStatus(status);
    } else {
      responseStatus = HttpResponseStatus.valueOf(status);
      setStatus(status);
    }
    io.netty.handler.codec.http.HttpResponse response = null;
    if (message != null) {
      ByteBuf byteBuf = ctx.alloc().buffer();
      byteBuf.writeBytes(message.getBytes());

      response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, responseStatus, byteBuf);
    } else {
      response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, responseStatus);
    }
    if (keepAlive) {
      // Add keep alive and content length if needed
      response.headers().add(Names.CONNECTION, Values.KEEP_ALIVE);
      if (message == null) response.headers().add(Names.CONTENT_LENGTH, 0);
      else response.headers().add(Names.CONTENT_LENGTH, message.getBytes().length);
    }
    ctx.writeAndFlush(response);
    committed = true;
  }
示例#6
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);
  }
 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;
 }
 private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
   FullHttpResponse response =
       new DefaultFullHttpResponse(
           HTTP_1_1,
           status,
           Unpooled.copiedBuffer("失败: " + status.toString() + "\r\n", CharsetUtil.UTF_8));
   response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
   ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
 }
示例#9
0
  @Override
  public void failover(FullHttpRequest request, FullHttpResponse response) {
    Response dumpedResponse = failoverResponse(request);
    response.setProtocolVersion(HttpVersion.valueOf(dumpedResponse.getVersion()));
    response.setStatus(HttpResponseStatus.valueOf(dumpedResponse.getStatusCode()));
    for (Map.Entry<String, String> entry : dumpedResponse.getHeaders().entrySet()) {
      response.headers().add(entry.getKey(), entry.getValue());
    }

    response.content().writeBytes(dumpedResponse.getContent().getBytes());
  }
  private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
    FullHttpResponse response =
        new DefaultFullHttpResponse(
            HttpVersion.HTTP_1_1,
            status,
            Unpooled.copiedBuffer("Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8));
    response.headers().set(HttpHeaderConstants.CONTENT_TYPE, "text/plain; charset=UTF-8");

    // Close the connection as soon as the error message is sent.
    ctx.write(response).addListener(ChannelFutureListener.CLOSE);
  }
  private static void parseHeaders(@NotNull HttpResponse response, @NotNull ByteBuf buffer) {
    StringBuilder builder = new StringBuilder();
    while (buffer.isReadable()) {
      builder.setLength(0);

      String key = null;
      boolean valueExpected = true;
      while (true) {
        int b = buffer.readByte();
        if (b < 0 || b == '\n') {
          break;
        }

        if (b != '\r') {
          if (valueExpected && b == ':') {
            valueExpected = false;

            key = builder.toString();
            builder.setLength(0);
            MessageDecoder.skipWhitespace(buffer);
          } else {
            builder.append((char) b);
          }
        }
      }

      if (builder.length() == 0) {
        // end of headers
        return;
      }

      // skip standard headers
      if (StringUtil.isEmpty(key)
          || StringUtilRt.startsWithIgnoreCase(key, "http")
          || StringUtilRt.startsWithIgnoreCase(key, "X-Accel-")) {
        continue;
      }

      String value = builder.toString();
      if (key.equalsIgnoreCase("status")) {
        int index = value.indexOf(' ');
        if (index == -1) {
          LOG.warn("Cannot parse status: " + value);
          response.setStatus(HttpResponseStatus.OK);
        } else {
          response.setStatus(
              HttpResponseStatus.valueOf(Integer.parseInt(value.substring(0, index))));
        }
      } else if (!(key.startsWith("http") || key.startsWith("HTTP"))) {
        response.headers().add(key, value);
      }
    }
  }
 @Override
 protected void encode(ChannelHandlerContext ctx, HttpResponse response, List<Object> out) {
   DefaultFullHttpResponse defaultFullHttpResponse =
       new DefaultFullHttpResponse(
           HttpVersion.HTTP_1_1,
           HttpResponseStatus.valueOf(
               (response.getStatusCode() != null ? response.getStatusCode() : 200)),
           getBody(response));
   setHeaders(response, defaultFullHttpResponse);
   setCookies(response, defaultFullHttpResponse);
   out.add(defaultFullHttpResponse);
 }
示例#13
0
  private RestException makeException(
      HttpResponseStatus status, String response, List<HttpResponse> errors) {

    if (status == null) {
      return new RestException("Shutdown: " + response);
    }

    for (HttpResponse hr : errors) {
      if (hr.code == status.code()) {
        return new RestException(hr.description);
      }
    }
    return new RestException(response);
  }
示例#14
0
 /**
  * Send an error and close
  *
  * @param ctx
  * @param status
  */
 private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
   responseContent.setLength(0);
   responseContent.append(error(status.toString()));
   FullHttpResponse response =
       new DefaultFullHttpResponse(
           HttpVersion.HTTP_1_1,
           status,
           Unpooled.copiedBuffer(responseContent.toString(), WaarpStringUtils.UTF8));
   response.headers().add(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
   response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html");
   responseContent.setLength(0);
   clearSession();
   // Close the connection as soon as the error message is sent.
   ctx.writeAndFlush(response).addListener(WaarpSslUtility.SSLCLOSE);
 }
示例#15
0
 public static void sendError(
     ChannelHandlerContext ctx, int statusCode, Map<String, String> rspHeaders) {
   HttpResponseStatus status = HttpResponseStatus.valueOf(statusCode);
   logger.warn("send status {}", ctx.channel(), statusCode);
   FullHttpResponse response =
       new DefaultFullHttpResponse(
           HTTP_1_1, status, Unpooled.copiedBuffer(status + "\r\n", CharsetUtil.UTF_8));
   rspHeaders.forEach(
       (k, v) -> {
         response.headers().set(k, v);
       });
   response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
   // Close the connection as soon as the error message is sent.
   ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
 }
  @Override
  public void handleWebRequest(
      ChannelHandlerContext ctx,
      HttpRequest nettyRequest,
      HttpFileUpload upload,
      Set<HttpCookie> cookiesToAdd)
      throws IOException {
    NettyHttpRequest request =
        new NettyHttpRequest(nettyRequest, parentHandler.getWebServer().getLog());
    NettyHttpResponse response = new NettyHttpResponse(ctx, extraHttpContentHeaders);
    response.addCookies(cookiesToAdd);

    DefaultFullHttpResponse res;
    try {
      requestHandler.handle(request, upload, response);

      res =
          new DefaultFullHttpResponse(
              HttpVersion.HTTP_1_1,
              HttpResponseStatus.valueOf(response.getResponseCode()),
              response.getChannelBuffer());

      String contentType = response.getContentType();
      if (contentType != null) {
        addHeader(res, HttpHeaders.Names.CONTENT_TYPE, contentType);
      }

      parentHandler.addHttpResponseHeaders(res, response.getContentHeaders());
      parentHandler.sendHttpResponse(ctx, nettyRequest, res, true, false);

      parentHandler
          .getWebServer()
          .getLog()
          .debug("Dynamic content handler for %s completed", uriPrefix);
    } catch (Throwable e) {
      parentHandler
          .getWebServer()
          .getLog()
          .error(
              String.format(
                  "Error while handling dynamic web server request %s", nettyRequest.getUri()),
              e);

      parentHandler.sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR);
    }
  }
示例#17
0
  @Override
  protected ChannelFuture doOnPut(ChannelHandlerContext context, HttpRequest request) {
    NettyTransferService<HttpProtocolInfo>.NettyMoverChannel file = null;
    Exception exception = null;

    try {
      checkContentHeader(request.headers().names(), Collections.singletonList(CONTENT_LENGTH));

      file = open(request, true);

      if (file.getIoMode() != IoMode.WRITE) {
        throw new HttpException(METHOD_NOT_ALLOWED.code(), "Resource is not open for writing");
      }

      if (is100ContinueExpected(request)) {
        context
            .writeAndFlush(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE))
            .addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
      }
      _writeChannel = file;
      file = null;
      return null;
    } catch (HttpException e) {
      exception = e;
      return context.writeAndFlush(
          createErrorResponse(HttpResponseStatus.valueOf(e.getErrorCode()), e.getMessage()));
    } catch (URISyntaxException e) {
      exception = e;
      return context.writeAndFlush(
          createErrorResponse(BAD_REQUEST, "URI is not valid: " + e.getMessage()));
    } catch (IllegalArgumentException e) {
      exception = e;
      return context.writeAndFlush(createErrorResponse(BAD_REQUEST, e.getMessage()));
    } catch (RuntimeException e) {
      exception = e;
      return context.writeAndFlush(createErrorResponse(INTERNAL_SERVER_ERROR, e.getMessage()));
    } finally {
      if (file != null) {
        file.release(exception);
        _files.remove(file);
      }
    }
  }
示例#18
0
 @Override
 public int statusCode() {
   return status.code();
 }
示例#19
0
    @Override
    public final boolean trySend(HttpResponse message) {
      try {
        final HttpRequestWrapper nettyRequest = (HttpRequestWrapper) message.getRequest();
        final FullHttpRequest req = nettyRequest.req;
        final ChannelHandlerContext ctx = nettyRequest.ctx;

        final HttpResponseStatus status = HttpResponseStatus.valueOf(message.getStatus());

        if (message.getStatus() >= 400 && message.getStatus() < 600) {
          sendHttpResponse(
              ctx, req, new DefaultFullHttpResponse(req.getProtocolVersion(), status), false);
          close();
          return true;
        }

        if (message.getRedirectPath() != null) {
          sendHttpRedirect(ctx, req, message.getRedirectPath());
          close();
          return true;
        }

        FullHttpResponse res;
        if (message.getStringBody() != null)
          res =
              new DefaultFullHttpResponse(
                  req.getProtocolVersion(),
                  status,
                  Unpooled.wrappedBuffer(message.getStringBody().getBytes()));
        else if (message.getByteBufferBody() != null)
          res =
              new DefaultFullHttpResponse(
                  req.getProtocolVersion(),
                  status,
                  Unpooled.wrappedBuffer(message.getByteBufferBody()));
        else res = new DefaultFullHttpResponse(req.getProtocolVersion(), status);

        if (message.getCookies() != null) {
          final ServerCookieEncoder enc = ServerCookieEncoder.STRICT;
          for (final Cookie c : message.getCookies())
            HttpHeaders.setHeader(res, COOKIE, enc.encode(getNettyCookie(c)));
        }
        if (message.getHeaders() != null) {
          for (final Map.Entry<String, String> h : message.getHeaders().entries())
            HttpHeaders.setHeader(res, h.getKey(), h.getValue());
        }

        if (message.getContentType() != null) {
          String ct = message.getContentType();
          if (message.getCharacterEncoding() != null)
            ct = ct + "; charset=" + message.getCharacterEncoding().name();
          HttpHeaders.setHeader(res, CONTENT_TYPE, ct);
        }

        final boolean sseStarted = message.shouldStartActor();
        if (trackSession(sseStarted)) {
          final String sessionId = UUID.randomUUID().toString();
          res.headers()
              .add(SET_COOKIE, ServerCookieEncoder.STRICT.encode(SESSION_COOKIE_KEY, sessionId));
          startSession(sessionId, actorContext);
        }
        if (!sseStarted) {
          final String stringBody = message.getStringBody();
          long contentLength = 0L;
          if (stringBody != null) contentLength = stringBody.getBytes().length;
          else {
            final ByteBuffer byteBufferBody = message.getByteBufferBody();
            if (byteBufferBody != null) contentLength = byteBufferBody.remaining();
          }
          res.headers().add(CONTENT_LENGTH, contentLength);
        }

        final HttpStreamActorAdapter httpStreamActorAdapter;
        if (sseStarted)
          // This will copy the request content, which must still be referenceable, doing before the
          // request handler
          // unallocates it (unfortunately it is explicitly reference-counted in Netty)
          httpStreamActorAdapter = new HttpStreamActorAdapter(ctx, req);
        else httpStreamActorAdapter = null;

        sendHttpResponse(ctx, req, res, false);

        if (sseStarted) {
          if (httpResponseEncoderName != null) {
            ctx.pipeline().remove(httpResponseEncoderName);
          } else {
            final ChannelPipeline pl = ctx.pipeline();
            final List<String> handlerKeysToBeRemoved = new ArrayList<>();
            for (final Map.Entry<String, ChannelHandler> e : pl) {
              if (e.getValue() instanceof HttpResponseEncoder)
                handlerKeysToBeRemoved.add(e.getKey());
            }
            for (final String k : handlerKeysToBeRemoved) pl.remove(k);
          }

          try {
            message.getFrom().send(new HttpStreamOpened(httpStreamActorAdapter.ref(), message));
          } catch (SuspendExecution e) {
            throw new AssertionError(e);
          }
        }

        return true;
      } finally {
        if (actor != null) actor.unwatch();
      }
    }
 public DefaultHttpResponse getDefaultHttpResponse() {
   DefaultHttpResponse res =
       new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.valueOf(getStatus()));
   transformResponseHeaders(res);
   return res;
 }
 @Override
 public void setStatusCode(int code) {
   response.setStatus(HttpResponseStatus.valueOf(code));
 }
 private static boolean isResponseWithCode(HttpResponse response, HttpResponseStatus status) {
   return HttpVersion.HTTP_1_1.equals(response.getProtocolVersion())
       && status.equals(response.getStatus());
 }
示例#23
0
  @Override
  protected ChannelFuture doOnContent(ChannelHandlerContext context, HttpContent content) {
    if (_writeChannel != null) {
      try {
        ByteBuf data = content.content();
        while (data.isReadable()) {
          data.readBytes(_writeChannel, data.readableBytes());
        }
        if (content instanceof LastHttpContent) {
          checkContentHeader(
              ((LastHttpContent) content).trailingHeaders().names(),
              Collections.singletonList(CONTENT_LENGTH));

          context.channel().config().setAutoRead(false);

          NettyTransferService<HttpProtocolInfo>.NettyMoverChannel writeChannel = _writeChannel;
          _writeChannel = null;
          _files.remove(writeChannel);

          long size = writeChannel.size();
          URI location = writeChannel.getProtocolInfo().getLocation();

          ChannelPromise promise = context.newPromise();
          Futures.addCallback(
              writeChannel.release(),
              new FutureCallback<Void>() {
                @Override
                public void onSuccess(Void result) {
                  try {
                    context.writeAndFlush(new HttpPutResponse(size, location), promise);
                  } catch (IOException e) {
                    context.writeAndFlush(
                        createErrorResponse(INTERNAL_SERVER_ERROR, e.getMessage()), promise);
                  }
                  context.channel().config().setAutoRead(true);
                }

                @Override
                public void onFailure(Throwable t) {
                  if (t instanceof FileCorruptedCacheException) {
                    context.writeAndFlush(
                        createErrorResponse(BAD_REQUEST, t.getMessage()), promise);
                  } else if (t instanceof CacheException) {
                    context.writeAndFlush(
                        createErrorResponse(INTERNAL_SERVER_ERROR, t.getMessage()), promise);
                  } else {
                    context.writeAndFlush(
                        createErrorResponse(INTERNAL_SERVER_ERROR, t.toString()), promise);
                  }
                  context.channel().config().setAutoRead(true);
                }
              },
              MoreExecutors.directExecutor());
          return promise;
        }
      } catch (IOException e) {
        _writeChannel.release(e);
        _files.remove(_writeChannel);
        _writeChannel = null;
        return context.writeAndFlush(createErrorResponse(INTERNAL_SERVER_ERROR, e.getMessage()));
      } catch (HttpException e) {
        _writeChannel.release(e);
        _files.remove(_writeChannel);
        _writeChannel = null;
        return context.writeAndFlush(
            createErrorResponse(HttpResponseStatus.valueOf(e.getErrorCode()), e.getMessage()));
      }
    }
    return null;
  }
 @Override
 public void setStatus(int sc) {
   response.setStatus(HttpResponseStatus.valueOf(sc));
 }
 @Override
 public void sendError(int sc) throws IOException {
   checkNotCommitted();
   response.setStatus(HttpResponseStatus.valueOf(sc));
 }
示例#26
0
 @Override
 public void statusCode(final int code) {
   this.status = HttpResponseStatus.valueOf(code);
 }