Exemple #1
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 static String getContent(final FullHttpRequest request) {
   final String contentType = getContentType(request);
   if (Transports.CONTENT_TYPE_FORM.equals(contentType)) {
     final List<String> data = getDataFormParameter(request);
     if (data != null) {
       return data.get(0);
     } else {
       return "";
     }
   }
   return request.content().toString(CharsetUtil.UTF_8);
 }
 @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);
 }
 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);
     }
   }
 }
 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;
     }
   }
 }
  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;
  }
  public void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest nettyRequest)
      throws Exception {
    if (!nettyRequest.getDecoderResult().isSuccess()) {
      sendError(ctx, HttpResponseStatus.BAD_REQUEST);
      return;
    }

    final long startTime = System.nanoTime();

    final Request request =
        new DefaultRequest(
            new NettyHeadersBackedHeaders(nettyRequest.headers()),
            nettyRequest.getMethod().name(),
            nettyRequest.getUri(),
            nettyRequest.content());

    final Channel channel = ctx.channel();

    final DefaultMutableStatus responseStatus = new DefaultMutableStatus();
    final HttpHeaders httpHeaders = new DefaultHttpHeaders(false);
    final MutableHeaders responseHeaders = new NettyHeadersBackedMutableHeaders(httpHeaders);
    FileHttpTransmitter fileHttpTransmitter =
        new DefaultFileHttpTransmitter(
            nettyRequest,
            httpHeaders,
            channel,
            compressResponses,
            addResponseTimeHeader ? startTime : -1);

    final DefaultEventController<RequestOutcome> requestOutcomeEventController =
        new DefaultEventController<>();

    // We own the lifecycle
    nettyRequest.content().retain();

    final Response response =
        new DefaultResponse(
            responseStatus,
            responseHeaders,
            fileHttpTransmitter,
            ctx.alloc(),
            new Action<ByteBuf>() {
              @Override
              public void execute(final ByteBuf byteBuf) throws Exception {
                final HttpResponse nettyResponse =
                    new CustomHttpResponse(responseStatus.getResponseStatus(), httpHeaders);

                nettyRequest.content().release();
                responseHeaders.set(HttpHeaderConstants.CONTENT_LENGTH, byteBuf.writerIndex());
                boolean shouldClose = true;
                if (channel.isOpen()) {
                  if (isKeepAlive(nettyRequest)) {
                    responseHeaders.set(
                        HttpHeaderConstants.CONNECTION, HttpHeaderConstants.KEEP_ALIVE);
                    shouldClose = false;
                  }

                  long stopTime = System.nanoTime();
                  if (addResponseTimeHeader) {
                    responseHeaders.set(
                        "X-Response-Time", NumberUtil.toMillisDiffString(startTime, stopTime));
                  }

                  execController.getExecution().complete();

                  channel.writeAndFlush(nettyResponse);
                  channel.write(new DefaultHttpContent(byteBuf));
                  ChannelFuture future = channel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

                  if (requestOutcomeEventController.isHasListeners()) {
                    Headers headers = new DelegatingHeaders(responseHeaders);
                    Status status =
                        new DefaultStatus(responseStatus.getCode(), responseStatus.getMessage());
                    SentResponse sentResponse = new DefaultSentResponse(headers, status);
                    RequestOutcome requestOutcome =
                        new DefaultRequestOutcome(
                            request, sentResponse, System.currentTimeMillis());
                    requestOutcomeEventController.fire(requestOutcome);
                  }
                  if (shouldClose) {
                    future.addListener(ChannelFutureListener.CLOSE);
                  }
                }
              }
            });

    InetSocketAddress socketAddress = (InetSocketAddress) channel.localAddress();
    final BindAddress bindAddress = new InetSocketAddressBackedBindAddress(socketAddress);

    Action<Action<Object>> subscribeHandler =
        new Action<Action<Object>>() {
          @Override
          public void execute(Action<Object> thing) throws Exception {
            channelSubscriptions.put(channel, thing);
            channel
                .closeFuture()
                .addListener(
                    new ChannelFutureListener() {
                      @Override
                      public void operationComplete(ChannelFuture future) throws Exception {
                        channelSubscriptions.remove(channel);
                      }
                    });
          }
        };

    final DirectChannelAccess directChannelAccess =
        new DefaultDirectChannelAccess(channel, subscribeHandler);

    execController.start(
        new Action<Execution>() {
          @Override
          public void execute(Execution execution) throws Exception {
            DefaultContext.RequestConstants requestConstants =
                new DefaultContext.RequestConstants(
                    applicationConstants,
                    bindAddress,
                    request,
                    response,
                    directChannelAccess,
                    requestOutcomeEventController.getRegistry(),
                    execution);

            new DefaultContext(requestConstants, registry, handlers, 0, return404).next();
          }
        });
  }
 private static List<String> getDataFormParameter(final FullHttpRequest request) {
   final QueryStringDecoder decoder =
       new QueryStringDecoder("?" + request.content().toString(CharsetUtil.UTF_8));
   return decoder.parameters().get("d");
 }
  private void handleRequest(
      ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest) {
    logger.info("Post/Put CategoryField");

    String returnJson = "";

    String messageContent = fullHttpRequest.content().toString(CharsetUtil.UTF_8);

    if (isPost(fullHttpRequest)) {

      CategoryFieldObject categoryField =
          new Gson().fromJson(messageContent, CategoryFieldObject.class);

      if (categoryField != null && categoryField.getCategoryField() != null) {
        CategoryField newCategoryField = categoryField.getCategoryField();

        String category =
            newCategoryField.getId().substring(0, newCategoryField.getId().indexOf("_"));

        CategoryData categoryData = getStorage().getCategory(getDomain().getWebappName(), category);
        boolean updated = false;
        for (CategoryField cf : categoryData.getDefaultFields()) {
          if (cf.getId().equals(categoryField.getCategoryField().getId())) {
            cf.setName(newCategoryField.getName());
            cf.setType(newCategoryField.getType());
            cf.setRequired(newCategoryField.getRequired());
            cf.setRelation(newCategoryField.getRelation());
            updated = true;
          }
        }

        if (!updated) {
          categoryData.getDefaultFields().add(newCategoryField);
          updated = true;
        }

        if (updated) {
          getStorage().setCategory(getDomain().getWebappName(), category, categoryData);
        }

        categoryField = new CategoryFieldObject();
        categoryField.setCategoryField(newCategoryField);

        returnJson = new Gson().toJson(categoryField);
      }
    } else if (isPut(fullHttpRequest)) {
      String categoryFieldId = getParameter("categoryField");
      CategoryFieldObject categoryField =
          new Gson().fromJson(messageContent, CategoryFieldObject.class);

      String category = categoryFieldId.substring(0, categoryFieldId.indexOf("_"));
      String fieldId =
          categoryFieldId.substring(categoryFieldId.indexOf("_") + 1, categoryFieldId.length());

      logger.info(
          "Updating fieldid: "
              + categoryField.getCategoryField().getName()
              + " with: "
              + fieldId
              + " for category: "
              + category);

      CategoryField updatedField = null;
      CategoryData categoryData = getStorage().getCategory(getDomain().getWebappName(), category);
      for (CategoryField cf : categoryData.getDefaultFields()) {
        if (cf.getId().equals(categoryFieldId)) {
          cf.setName(categoryField.getCategoryField().getName());
          cf.setType(categoryField.getCategoryField().getType());
          cf.setRequired(categoryField.getCategoryField().getRequired());
          cf.setRelation(categoryField.getCategoryField().getRelation());
          updatedField = cf;
          break;
        }
      }

      getStorage().setCategory(getDomain().getWebappName(), category, categoryData);

      CategoryFieldObject cfObject = new CategoryFieldObject();
      cfObject.setCategoryField(updatedField);
      returnJson = new Gson().toJson(cfObject);
    } else if (isDelete(fullHttpRequest)) {
      String categoryFieldId = getParameter("categoryField");

      if (categoryFieldId.contains("_")) {
        String category = categoryFieldId.substring(0, categoryFieldId.indexOf("_"));
        String fieldId =
            categoryFieldId.substring(categoryFieldId.indexOf("_") + 1, categoryFieldId.length());

        CategoryData categoryData = getStorage().getCategory(getDomain().getWebappName(), category);

        CategoryField fieldToDelete = null;
        for (CategoryField cf : categoryData.getDefaultFields()) {
          if (cf.getName().equals(fieldId)) {
            fieldToDelete = cf;
            break;
          }
        }

        if (fieldToDelete != null) {
          categoryData.getDefaultFields().remove(fieldToDelete);
        }

        getStorage().setCategory(getDomain().getWebappName(), category, categoryData);
      }
    }

    writeContentsToBuffer(channelHandlerContext, returnJson, "application/json");
  }
  private ChannelFuture handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest request) {
    if (request.method() == HttpMethod.OPTIONS) {
      return HttpHelpers.sendPreflightApproval(ctx);
    }

    HttpRequestInfo CurrRequest = new HttpRequestInfo();

    try {
      CurrRequest.init(Info, request, SVID.makeSVID());
    } catch (URISyntaxException e1) {
      return HttpHelpers.sendError(CurrRequest, ApiErrors.HTTP_DECODE_ERROR);
    }

    URI uri = CurrRequest.RequestURI;

    l.debug(new SVLog("Agent HTTP request", CurrRequest));

    if (!request.decoderResult().isSuccess()) {
      return HttpHelpers.sendError(CurrRequest, ApiErrors.HTTP_DECODE_ERROR);
    }

    if (!authenticate(request, (InetSocketAddress) ctx.channel().remoteAddress())) {
      return HttpHelpers.sendError(CurrRequest, ApiErrors.BAD_AUTH);
    }

    String uriPath = uri.getPath();

    if (uriPath.equals(WEBSOCKET_PATH)) {
      String websockUrl = request.headers().get(HttpHeaderNames.HOST) + WEBSOCKET_PATH;
      WebSocketServerHandshakerFactory wsFactory =
          new WebSocketServerHandshakerFactory(websockUrl, null, false);

      Handshaker = wsFactory.newHandshaker(request);
      if (Handshaker == null) {
        return WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
      } else {
        WebsocketConnected = true;
        return Handshaker.handshake(ctx.channel(), request);
      }
    }

    if (uriPath.startsWith("/api/")) {
      // Invoking an API directly over HTTP

      String messageType = uriPath.substring(5);
      String messageBody = null;
      if (request.method() == HttpMethod.POST && request.content() != null) {
        messageBody = request.content().toString(StandardCharsets.UTF_8);
      }

      ByteBuf reply = null;
      try {
        reply = Dispatcher.dispatch(messageType, messageBody);
      } catch (JsonProcessingException e) {
        return HttpHelpers.sendError(CurrRequest, ApiErrors.JSON_ERROR, e.getMessage());
      } catch (SQLException e) {
        return HttpHelpers.sendError(CurrRequest, ApiErrors.DB_ERROR, e.getMessage());
      } catch (JsonApiException e) {
        return HttpHelpers.sendErrorJson(CurrRequest, e.Error, e.HttpStatus);
      } catch (Exception e) {
        return HttpHelpers.sendError(CurrRequest, ApiErrors.INTERNAL_SERVER_ERROR, e.getMessage());
      }

      HttpResponse response =
          new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, reply);

      if (reply != null) {
        HttpHelpers.setContentTypeHeader(response, "application/json");
        HttpUtil.setContentLength(response, reply.readableBytes());
      }

      response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, "*");

      return ctx.writeAndFlush(response);
    }

    return HttpHelpers.sendError(CurrRequest, ApiErrors.NOT_FOUND);
  }
  public void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest nettyRequest)
      throws Exception {
    if (!nettyRequest.getDecoderResult().isSuccess()) {
      sendError(ctx, HttpResponseStatus.BAD_REQUEST);
      return;
    }

    final long startTime = addResponseTimeHeader ? System.nanoTime() : 0;
    final Request request =
        new DefaultRequest(
            new NettyHeadersBackedHeaders(nettyRequest.headers()),
            nettyRequest.getMethod().name(),
            nettyRequest.getUri(),
            nettyRequest.content());
    final Channel channel = ctx.channel();
    final DefaultMutableStatus responseStatus = new DefaultMutableStatus();
    final HttpHeaders nettyHeaders = new DefaultHttpHeaders(false);
    final MutableHeaders responseHeaders = new NettyHeadersBackedMutableHeaders(nettyHeaders);
    final MimeTypes mimeTypes = registry.get(MimeTypes.class);
    final DefaultEventController<RequestOutcome> requestOutcomeEventController =
        new DefaultEventController<>();
    final AtomicBoolean transmitted = new AtomicBoolean(false);

    final ResponseTransmitter responseTransmitter =
        new DefaultResponseTransmitter(
            transmitted,
            channel,
            nettyRequest,
            request,
            nettyHeaders,
            responseStatus,
            requestOutcomeEventController,
            startTime);
    final Action<Action<? super ResponseTransmitter>> responseTransmitterWrapper =
        Actions.wrap(responseTransmitter);

    final FileHttpTransmitter fileHttpTransmitter =
        new DefaultFileHttpTransmitter(
            nettyHeaders,
            mimeTypes,
            compressResponses,
            compressionMinSize,
            compressionMimeTypeWhiteList,
            compressionMimeTypeBlackList,
            responseTransmitterWrapper);
    StreamTransmitter streamTransmitter =
        new DefaultStreamTransmitter(nettyRequest, nettyHeaders, channel);

    final Response response =
        new DefaultResponse(
            responseStatus,
            responseHeaders,
            fileHttpTransmitter,
            streamTransmitter,
            ctx.alloc(),
            new Action<ByteBuf>() {
              @Override
              public void execute(final ByteBuf byteBuf) throws Exception {
                responseTransmitterWrapper.execute(
                    new Action<ResponseTransmitter>() {
                      @Override
                      public void execute(ResponseTransmitter responseTransmitter)
                          throws Exception {
                        nettyHeaders.set(HttpHeaders.Names.CONTENT_LENGTH, byteBuf.writerIndex());
                        responseTransmitter.transmit(new DefaultHttpContent(byteBuf));
                      }
                    });
              }
            });

    InetSocketAddress socketAddress = (InetSocketAddress) channel.localAddress();
    final BindAddress bindAddress = new InetSocketAddressBackedBindAddress(socketAddress);

    Action<Action<Object>> subscribeHandler =
        new Action<Action<Object>>() {
          @Override
          public void execute(Action<Object> thing) throws Exception {
            transmitted.set(true);
            channelSubscriptions.put(channel, thing);
            channel
                .closeFuture()
                .addListener(
                    new ChannelFutureListener() {
                      @Override
                      public void operationComplete(ChannelFuture future) throws Exception {
                        channelSubscriptions.remove(channel);
                      }
                    });
          }
        };

    final DirectChannelAccess directChannelAccess =
        new DefaultDirectChannelAccess(channel, subscribeHandler);

    final DefaultContext.RequestConstants requestConstants =
        new DefaultContext.RequestConstants(
            applicationConstants,
            bindAddress,
            request,
            response,
            directChannelAccess,
            requestOutcomeEventController.getRegistry());

    DefaultContext.start(
        execController.getControl(),
        requestConstants,
        registry,
        handlers,
        return404,
        new Action<Execution>() {
          @Override
          public void execute(Execution execution) throws Exception {
            if (!transmitted.get()) {
              Handler lastHandler = requestConstants.handler;
              StringBuilder description = new StringBuilder();
              description
                  .append("No response sent for ")
                  .append(request.getMethod().getName())
                  .append(" request to ")
                  .append(request.getUri())
                  .append(" (last handler: ");

              if (lastHandler instanceof DescribingHandler) {
                ((DescribingHandler) lastHandler).describeTo(description);
              } else {
                DescribingHandlers.describeTo(lastHandler, description);
              }

              description.append(")");
              String message = description.toString();
              LOGGER.warn(message);

              response.status(500);

              if (launchConfig.isDevelopment()) {
                response.send(message);
              } else {
                response.send();
              }
            }
          }
        });
  }