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 FullHttpResponse handleJsonServiceMappings(
     FullHttpRequest request, JsonServiceMapping jsonServiceMapping, Matcher matcher)
     throws Exception {
   if (!httpSessionManager.hasReadAccess(request)) {
     return handleNotAuthenticated(request);
   }
   boolean isGetRequest = request.method().name().equals(HttpMethod.GET.name());
   if (!isGetRequest && !httpSessionManager.hasAdminAccess(request)) {
     return handleNotAuthorized();
   }
   String requestText = getRequestText(request);
   String[] args = new String[matcher.groupCount()];
   for (int i = 0; i < args.length; i++) {
     String group = matcher.group(i + 1);
     checkNotNull(group);
     args[i] = group;
   }
   logger.debug(
       "handleJsonRequest(): serviceMethodName={}, args={}, requestText={}",
       jsonServiceMapping.methodName(),
       args,
       requestText);
   Object responseObject;
   try {
     responseObject =
         callMethod(
             jsonServiceMapping.service(), jsonServiceMapping.methodName(), args, requestText);
   } catch (Exception e) {
     return newHttpResponseFromException(e);
   }
   return buildJsonResponse(responseObject);
 }
 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 @Nullable JsonServiceMatcher getJsonServiceMatcher(FullHttpRequest request, String path) {
   for (JsonServiceMapping jsonServiceMapping : jsonServiceMappings) {
     if (!jsonServiceMapping.httpMethod().name().equals(request.method().name())) {
       continue;
     }
     Matcher matcher = jsonServiceMapping.pattern().matcher(path);
     if (matcher.matches()) {
       return ImmutableJsonServiceMatcher.of(jsonServiceMapping, matcher);
     }
   }
   return null;
 }
  @Override
  public void channelRead0(
      ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest)
      throws Exception {

    DecoderResult decoderResult = fullHttpRequest.decoderResult();

    if (!decoderResult.isSuccess()) {
      _sendError(channelHandlerContext, BAD_REQUEST);

      return;
    }

    if (fullHttpRequest.method() == GET) {
      processGetRequest(channelHandlerContext, fullHttpRequest);
    } else if (fullHttpRequest.method() == HEAD) {
      processHeadRequest(channelHandlerContext, fullHttpRequest);
    } else {
      _sendError(channelHandlerContext, BAD_REQUEST);
    }
  }
 private @Nullable FullHttpResponse handleHttpService(
     ChannelHandlerContext ctx, FullHttpRequest request, HttpService httpService)
     throws Exception {
   if (!httpSessionManager.hasReadAccess(request)
       && !(httpService instanceof UnauthenticatedHttpService)) {
     return handleNotAuthenticated(request);
   }
   boolean isGetRequest = request.method().name().equals(HttpMethod.GET.name());
   if (!isGetRequest && !httpSessionManager.hasAdminAccess(request)) {
     return handleNotAuthorized();
   }
   return httpService.handleRequest(ctx, request);
 }
 private void checkAuthent(ChannelHandlerContext ctx) {
   newSession = true;
   if (request.method() == HttpMethod.GET) {
     String logon = Logon();
     logon = logon.replaceAll(REPLACEMENT.XXXERRORMESGXXX.toString(), "");
     responseContent.append(logon);
     clearSession();
     writeResponse(ctx);
     return;
   } else if (request.method() == HttpMethod.POST) {
     getParams();
     if (params == null) {
       String logon = Logon();
       logon =
           logon.replaceAll(
               REPLACEMENT.XXXERRORMESGXXX.toString(),
               Messages.getString("HttpSslHandler.EmptyLogin"));
       responseContent.append(logon);
       clearSession();
       writeResponse(ctx);
       return;
     }
   }
   boolean getMenu = false;
   if (params.containsKey("Logon")) {
     String name = null, password = null;
     List<String> values = null;
     if (!params.isEmpty()) {
       // get values
       if (params.containsKey("name")) {
         values = params.get("name");
         if (values != null) {
           name = values.get(0);
           if (name == null || name.isEmpty()) {
             getMenu = true;
           }
         }
       } else {
         getMenu = true;
       }
       // search the nb param
       if ((!getMenu) && params.containsKey("passwd")) {
         values = params.get("passwd");
         if (values != null) {
           password = values.get(0);
           if (password == null || password.isEmpty()) {
             getMenu = true;
           } else {
             getMenu = false;
           }
         } else {
           getMenu = true;
         }
       } else {
         getMenu = true;
       }
     } else {
       getMenu = true;
     }
     if (!getMenu) {
       logger.debug(
           "Name="
               + name
               + " vs "
               + name.equals(Configuration.configuration.getADMINNAME())
               + " Passwd vs "
               + Arrays.equals(
                   password.getBytes(WaarpStringUtils.UTF8),
                   Configuration.configuration.getSERVERADMINKEY()));
       if (name.equals(Configuration.configuration.getADMINNAME())
           && Arrays.equals(
               password.getBytes(WaarpStringUtils.UTF8),
               Configuration.configuration.getSERVERADMINKEY())) {
         authentHttp
             .getAuth()
             .specialNoSessionAuth(true, Configuration.configuration.getHOST_ID());
         authentHttp.setStatus(70);
       } else {
         getMenu = true;
       }
       if (!authentHttp.isAuthenticated()) {
         authentHttp.setStatus(71);
         logger.debug("Still not authenticated: {}", authentHttp);
         getMenu = true;
       }
     }
   } else {
     getMenu = true;
   }
   if (getMenu) {
     String logon = Logon();
     logon =
         logon.replaceAll(
             REPLACEMENT.XXXERRORMESGXXX.toString(),
             Messages.getString("HttpSslHandler.BadLogin"));
     responseContent.append(logon);
     clearSession();
     writeResponse(ctx);
   } else {
     String index = index();
     responseContent.append(index);
     clearSession();
     admin =
         new DefaultCookie(
             R66SESSION + Configuration.configuration.getHOST_ID(),
             Configuration.configuration.getHOST_ID() + Long.toHexString(random.nextLong()));
     sessions.put(admin.value(), this.authentHttp);
     authentHttp.setStatus(72);
     logger.debug("CreateSession: " + uriRequest + ":{}", admin);
     writeResponse(ctx);
   }
 }
  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);
  }