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 SyncFile _getSyncFile(FullHttpRequest fullHttpRequest) {
    String[] pathArray = StringUtils.split(fullHttpRequest.uri(), "/");

    if (pathArray.length != 4) {
      return null;
    }

    String lanServerUuid = pathArray[0];
    long repositoryId = GetterUtil.getLong(pathArray[1]);
    long typePK = GetterUtil.getLong(pathArray[2]);
    long versionId = GetterUtil.getLong(pathArray[3]);

    if (lanServerUuid.isEmpty() || (repositoryId == 0) || (typePK == 0) || (versionId == 0)) {

      return null;
    }

    List<SyncAccount> syncAccounts = SyncAccountService.findSyncAccounts(lanServerUuid);

    for (SyncAccount syncAccount : syncAccounts) {
      SyncFile syncFile =
          SyncFileService.fetchSyncFile(
              repositoryId, syncAccount.getSyncAccountId(), typePK, versionId);

      if ((syncFile != null) && (syncFile.getState() == SyncFile.STATE_SYNCED)) {

        return syncFile;
      }
    }

    return null;
  }
 private @Nullable FullHttpResponse handleRequest(
     ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
   logger.debug("handleRequest(): request.uri={}", request.uri());
   QueryStringDecoder decoder = new QueryStringDecoder(request.uri());
   String path = decoder.path();
   logger.debug("handleRequest(): path={}", path);
   FullHttpResponse response = handleIfLoginOrLogoutRequest(path, request);
   if (response != null) {
     return response;
   }
   HttpService httpService = getHttpService(path);
   if (httpService != null) {
     return handleHttpService(ctx, request, httpService);
   }
   JsonServiceMatcher jsonServiceMatcher = getJsonServiceMatcher(request, path);
   if (jsonServiceMatcher != null) {
     return handleJsonServiceMappings(
         request, jsonServiceMatcher.jsonServiceMapping(), jsonServiceMatcher.matcher());
   }
   return handleStaticResource(path, request);
 }
 @Override
 protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
   FullHttpRequest request = this.request = msg;
   QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri());
   uriRequest = queryStringDecoder.path();
   logger.debug("Msg: " + uriRequest);
   if (uriRequest.contains("gre/")
       || uriRequest.contains("img/")
       || uriRequest.contains("res/")
       || uriRequest.contains("favicon.ico")) {
     HttpWriteCacheEnable.writeFile(
         request,
         ctx,
         Configuration.configuration.getHttpBasePath() + uriRequest,
         R66SESSION + Configuration.configuration.getHOST_ID());
     ctx.flush();
     return;
   }
   checkSession(ctx.channel());
   if (!authentHttp.isAuthenticated()) {
     logger.debug("Not Authent: " + uriRequest + ":{}", authentHttp);
     checkAuthent(ctx);
     return;
   }
   String find = uriRequest;
   if (uriRequest.charAt(0) == '/') {
     find = uriRequest.substring(1);
   }
   find = find.substring(0, find.indexOf("."));
   REQUEST req = REQUEST.index;
   try {
     req = REQUEST.valueOf(find);
   } catch (IllegalArgumentException e1) {
     req = REQUEST.index;
     logger.debug("NotFound: " + find + ":" + uriRequest);
   }
   switch (req) {
     case index:
       responseContent.append(index());
       break;
     case Logon:
       responseContent.append(index());
       break;
     case System:
       responseContent.append(System());
       break;
     default:
       responseContent.append(index());
       break;
   }
   writeResponse(ctx);
 }
  protected void processHeadRequest(
      ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest) {

    if (_logger.isTraceEnabled()) {
      Channel channel = channelHandlerContext.channel();

      _logger.trace(
          "Client {}: processing head request {}", channel.remoteAddress(), fullHttpRequest.uri());
    }

    SyncFile syncFile = _getSyncFile(fullHttpRequest);

    if (syncFile == null) {
      _sendError(channelHandlerContext, NOT_FOUND);

      return;
    }

    String lanTokenKey = syncFile.getLanTokenKey();

    if ((lanTokenKey == null) || lanTokenKey.isEmpty()) {
      _sendError(channelHandlerContext, NOT_FOUND);

      return;
    }

    String encryptedToken = null;

    try {
      encryptedToken = LanTokenUtil.createEncryptedToken(lanTokenKey);
    } catch (Exception e) {
      _sendError(channelHandlerContext, NOT_FOUND);

      return;
    }

    HttpResponse httpResponse = new DefaultFullHttpResponse(HTTP_1_1, OK);

    HttpHeaders httpHeaders = httpResponse.headers();

    httpHeaders.set("connectionsCount", _syncTrafficShapingHandler.getConnectionsCount());

    httpHeaders.set("downloadRate", _trafficCounter.lastWrittenBytes());
    httpHeaders.set("encryptedToken", encryptedToken);
    httpHeaders.set("maxConnections", PropsValues.SYNC_LAN_SERVER_MAX_CONNECTIONS);

    channelHandlerContext.writeAndFlush(httpResponse);
  }
 @Override
 public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
   FullHttpRequest request = (FullHttpRequest) msg;
   logger.debug("messageReceived(): request.uri={}", request.uri());
   Channel channel = ctx.channel();
   currentChannel.set(channel);
   try {
     FullHttpResponse response = handleRequest(ctx, request);
     if (response != null) {
       sendFullResponse(ctx, request, response);
     }
   } catch (Exception f) {
     logger.error(f.getMessage(), f);
     FullHttpResponse response = newHttpResponseWithStackTrace(f, INTERNAL_SERVER_ERROR, null);
     sendFullResponse(ctx, request, response);
   } finally {
     currentChannel.remove();
     request.release();
   }
 }
  protected void processGetRequest(
      ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest)
      throws Exception {

    if (_logger.isTraceEnabled()) {
      Channel channel = channelHandlerContext.channel();

      _logger.trace(
          "Client {}: processing get request {}", channel.remoteAddress(), fullHttpRequest.uri());
    }

    HttpHeaders requestHttpHeaders = fullHttpRequest.headers();

    String lanToken = requestHttpHeaders.get("lanToken");

    if (Validator.isBlank(lanToken)) {
      Channel channel = channelHandlerContext.channel();

      _logger.error("Client {}: did not send token", channel.remoteAddress());

      _sendError(channelHandlerContext, NOT_FOUND);

      return;
    }

    if (!LanTokenUtil.containsLanToken(lanToken)) {
      Channel channel = channelHandlerContext.channel();

      _logger.error("Client {}: token not found or expired", channel.remoteAddress());

      _sendError(channelHandlerContext, NOT_FOUND);

      return;
    }

    SyncFile syncFile = _getSyncFile(fullHttpRequest);

    if (syncFile == null) {
      if (_logger.isTraceEnabled()) {
        Channel channel = channelHandlerContext.channel();

        _logger.trace(
            "Client {}: SyncFile not found. uri: {}",
            channel.remoteAddress(),
            fullHttpRequest.uri());
      }

      _sendError(channelHandlerContext, NOT_FOUND);

      return;
    }

    if (_syncTrafficShapingHandler.getConnectionsCount()
        >= PropsValues.SYNC_LAN_SERVER_MAX_CONNECTIONS) {

      _sendError(channelHandlerContext, NOT_FOUND);

      return;
    }

    _syncTrafficShapingHandler.incrementConnectionsCount();

    try {
      sendFile(channelHandlerContext, fullHttpRequest, syncFile);
    } catch (Exception e) {
      _syncTrafficShapingHandler.decrementConnectionsCount();

      throw e;
    }

    LanTokenUtil.removeLanToken(lanToken);
  }