Ejemplo n.º 1
0
 public void handle(ChannelHandlerContext ctx, HttpRequest req)
     throws IOException, URISyntaxException {
   String op = params.op();
   HttpMethod method = req.method();
   if (PutOpParam.Op.CREATE.name().equalsIgnoreCase(op) && method == PUT) {
     onCreate(ctx);
   } else if (PostOpParam.Op.APPEND.name().equalsIgnoreCase(op) && method == POST) {
     onAppend(ctx);
   } else if (GetOpParam.Op.OPEN.name().equalsIgnoreCase(op) && method == GET) {
     onOpen(ctx);
   } else if (GetOpParam.Op.GETFILECHECKSUM.name().equalsIgnoreCase(op) && method == GET) {
     onGetFileChecksum(ctx);
   } else {
     throw new IllegalArgumentException("Invalid operation " + op);
   }
 }
Ejemplo n.º 2
0
  @Override
  protected void messageReceived(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
      HttpRequest request = _request = (HttpRequest) msg;
      HttpMethod method = request.method();
      HttpHeaders headers = request.headers();
      QueryStringDecoder query = new QueryStringDecoder(request.uri());

      if (HttpHeaderUtil.is100ContinueExpected(request))
        ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));

      //            if (headers != null) for (Map.Entry<CharSequence, CharSequence> h : headers) {}

      if (method.equals(HttpMethod.GET)) RamdRequest.build(query.path(), query.parameters());
    }

    if (msg instanceof HttpContent) {
      ByteBuf bb = ((HttpContent) msg).content();
      if (bb.isReadable()) {}
      _buf.append("Done.");
      writeResponse((HttpContent) msg, ctx);
    }
  }
Ejemplo n.º 3
0
  @Override
  protected void encodeInitialLine(final ByteBuf buf, final HttpMessage message) throws Exception {
    if (message instanceof HttpRequest) {
      HttpRequest request = (HttpRequest) message;
      ByteBufUtil.writeAscii(buf, request.method().asciiName());
      buf.writeByte(SP);
      buf.writeBytes(request.uri().getBytes(CharsetUtil.UTF_8));
      buf.writeByte(SP);
      ByteBufUtil.writeAscii(buf, request.protocolVersion().text());
      buf.writeBytes(CRLF);
    } else if (message instanceof HttpResponse) {
      HttpResponse response = (HttpResponse) message;
      ByteBufUtil.writeAscii(buf, response.protocolVersion().text());
      buf.writeByte(SP);
      buf.writeBytes(String.valueOf(response.status().code()).getBytes(CharsetUtil.US_ASCII));
      buf.writeByte(SP);
      ByteBufUtil.writeAscii(buf, response.status().reasonPhrase());

      buf.writeBytes(CRLF);
    } else {
      throw new UnsupportedMessageTypeException(
          "Unsupported type " + StringUtil.simpleClassName(message));
    }
  }
Ejemplo n.º 4
0
  @Override
  public void messageReceived(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    if (msg instanceof HttpRequest) {
      HttpRequest request = this.request = (HttpRequest) msg;
      URI uri = new URI(request.uri());
      if (!uri.getPath().startsWith("/form")) {
        // Write Menu
        writeMenu(ctx);
        return;
      }
      responseContent.setLength(0);
      responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
      responseContent.append("===================================\r\n");

      responseContent.append("VERSION: " + request.protocolVersion().text() + "\r\n");

      responseContent.append("REQUEST_URI: " + request.uri() + "\r\n\r\n");
      responseContent.append("\r\n\r\n");

      // new getMethod
      for (Entry<CharSequence, CharSequence> entry : request.headers()) {
        responseContent.append("HEADER: " + entry.getKey() + '=' + entry.getValue() + "\r\n");
      }
      responseContent.append("\r\n\r\n");

      // new getMethod
      Set<Cookie> cookies;
      String value = request.headers().getAndConvert(HttpHeaderNames.COOKIE);
      if (value == null) {
        cookies = Collections.emptySet();
      } else {
        cookies = ServerCookieDecoder.STRICT.decode(value);
      }
      for (Cookie cookie : cookies) {
        responseContent.append("COOKIE: " + cookie + "\r\n");
      }
      responseContent.append("\r\n\r\n");

      QueryStringDecoder decoderQuery = new QueryStringDecoder(request.uri());
      Map<String, List<String>> uriAttributes = decoderQuery.parameters();
      for (Entry<String, List<String>> attr : uriAttributes.entrySet()) {
        for (String attrVal : attr.getValue()) {
          responseContent.append("URI: " + attr.getKey() + '=' + attrVal + "\r\n");
        }
      }
      responseContent.append("\r\n\r\n");

      // if GET Method: should not try to create a HttpPostRequestDecoder
      if (request.method().equals(HttpMethod.GET)) {
        // GET Method: should not try to create a HttpPostRequestDecoder
        // So stop here
        responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n");
        // Not now: LastHttpContent will be sent writeResponse(ctx.channel());
        return;
      }
      try {
        decoder = new HttpPostRequestDecoder(factory, request);
      } catch (ErrorDataDecoderException e1) {
        e1.printStackTrace();
        responseContent.append(e1.getMessage());
        writeResponse(ctx.channel());
        ctx.channel().close();
        return;
      }

      readingChunks = HttpHeaderUtil.isTransferEncodingChunked(request);
      responseContent.append("Is Chunked: " + readingChunks + "\r\n");
      responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n");
      if (readingChunks) {
        // Chunk version
        responseContent.append("Chunks: ");
        readingChunks = true;
      }
    }

    // check if the decoder was constructed before
    // if not it handles the form get
    if (decoder != null) {
      if (msg instanceof HttpContent) {
        // New chunk is received
        HttpContent chunk = (HttpContent) msg;
        try {
          decoder.offer(chunk);
        } catch (ErrorDataDecoderException e1) {
          e1.printStackTrace();
          responseContent.append(e1.getMessage());
          writeResponse(ctx.channel());
          ctx.channel().close();
          return;
        }
        responseContent.append('o');
        // example of reading chunk by chunk (minimize memory usage due to
        // Factory)
        readHttpDataChunkByChunk();
        // example of reading only if at the end
        if (chunk instanceof LastHttpContent) {
          writeResponse(ctx.channel());
          readingChunks = false;

          reset();
        }
      }
    } else {
      writeResponse(ctx.channel());
    }
  }
  @Override
  public void invoke(
      ServiceInvocationContext ctx, Executor blockingTaskExecutor, Promise<Object> promise)
      throws Exception {

    final HttpRequest req = ctx.originalRequest();
    if (req.method() != HttpMethod.GET) {
      respond(
          ctx,
          promise,
          HttpResponseStatus.METHOD_NOT_ALLOWED,
          0,
          ERROR_MIME_TYPE,
          Unpooled.wrappedBuffer(CONTENT_METHOD_NOT_ALLOWED));
      return;
    }

    final String path = normalizePath(ctx.mappedPath());
    if (path == null) {
      respond(
          ctx,
          promise,
          HttpResponseStatus.NOT_FOUND,
          0,
          ERROR_MIME_TYPE,
          Unpooled.wrappedBuffer(CONTENT_NOT_FOUND));
      return;
    }

    Entry entry = getEntry(path);
    long lastModifiedMillis;
    if ((lastModifiedMillis = entry.lastModifiedMillis()) == 0) {
      boolean found = false;
      if (path.charAt(path.length() - 1) == '/') {
        // Try index.html if it was a directory access.
        entry = getEntry(path + "index.html");
        if ((lastModifiedMillis = entry.lastModifiedMillis()) != 0) {
          found = true;
        }
      }

      if (!found) {
        respond(
            ctx,
            promise,
            HttpResponseStatus.NOT_FOUND,
            0,
            ERROR_MIME_TYPE,
            Unpooled.wrappedBuffer(CONTENT_NOT_FOUND));
        return;
      }
    }

    long ifModifiedSinceMillis = Long.MIN_VALUE;
    try {
      ifModifiedSinceMillis =
          req.headers().getTimeMillis(HttpHeaderNames.IF_MODIFIED_SINCE, Long.MIN_VALUE);
    } catch (Exception e) {
      // Ignore the ParseException, which is raised on malformed date.
      //noinspection ConstantConditions
      if (!(e instanceof ParseException)) {
        throw e;
      }
    }

    // HTTP-date does not have subsecond-precision; add 999ms to it.
    if (ifModifiedSinceMillis > Long.MAX_VALUE - 999) {
      ifModifiedSinceMillis = Long.MAX_VALUE;
    } else {
      ifModifiedSinceMillis += 999;
    }

    if (lastModifiedMillis < ifModifiedSinceMillis) {
      respond(
          ctx,
          promise,
          HttpResponseStatus.NOT_MODIFIED,
          lastModifiedMillis,
          entry.mimeType(),
          Unpooled.EMPTY_BUFFER);
      return;
    }

    respond(
        ctx,
        promise,
        HttpResponseStatus.OK,
        lastModifiedMillis,
        entry.mimeType(),
        entry.readContent(ctx.alloc()));
  }
Ejemplo n.º 6
0
  @SuppressWarnings("deprecation")
  private SpdySynStreamFrame createSynStreamFrame(HttpMessage httpMessage) throws Exception {
    // Get the Stream-ID, Associated-To-Stream-ID, Priority, URL, and scheme from the headers
    final HttpHeaders httpHeaders = httpMessage.headers();
    int streamID = httpHeaders.getInt(Names.STREAM_ID);
    int associatedToStreamId = httpHeaders.getInt(Names.ASSOCIATED_TO_STREAM_ID, 0);
    byte priority = (byte) httpHeaders.getInt(Names.PRIORITY, 0);
    String URL = httpHeaders.get(Names.URL);
    String scheme = httpHeaders.get(Names.SCHEME);
    httpHeaders.remove(Names.STREAM_ID);
    httpHeaders.remove(Names.ASSOCIATED_TO_STREAM_ID);
    httpHeaders.remove(Names.PRIORITY);
    httpHeaders.remove(Names.URL);
    httpHeaders.remove(Names.SCHEME);

    // The Connection, Keep-Alive, Proxy-Connection, and Transfer-Encoding
    // headers are not valid and MUST not be sent.
    httpHeaders.remove(HttpHeaders.Names.CONNECTION);
    httpHeaders.remove(HttpHeaders.Names.KEEP_ALIVE);
    httpHeaders.remove(HttpHeaders.Names.PROXY_CONNECTION);
    httpHeaders.remove(HttpHeaders.Names.TRANSFER_ENCODING);

    SpdySynStreamFrame spdySynStreamFrame =
        new DefaultSpdySynStreamFrame(streamID, associatedToStreamId, priority);

    // Unfold the first line of the message into name/value pairs
    SpdyHeaders frameHeaders = spdySynStreamFrame.headers();
    if (httpMessage instanceof FullHttpRequest) {
      HttpRequest httpRequest = (HttpRequest) httpMessage;
      frameHeaders.set(METHOD, httpRequest.method());
      frameHeaders.set(PATH, httpRequest.uri());
      frameHeaders.set(VERSION, httpMessage.protocolVersion());
    }
    if (httpMessage instanceof HttpResponse) {
      HttpResponse httpResponse = (HttpResponse) httpMessage;
      frameHeaders.set(STATUS, httpResponse.status());
      frameHeaders.set(PATH, URL);
      frameHeaders.set(VERSION, httpMessage.protocolVersion());
      spdySynStreamFrame.setUnidirectional(true);
    }

    // Replace the HTTP host header with the SPDY host header
    if (spdyVersion >= 3) {
      CharSequence host = httpHeaders.getUnconverted(HttpHeaders.Names.HOST);
      httpHeaders.remove(HttpHeaders.Names.HOST);
      frameHeaders.set(HOST, host);
    }

    // Set the SPDY scheme header
    if (scheme == null) {
      scheme = "https";
    }
    frameHeaders.set(SCHEME, scheme);

    // Transfer the remaining HTTP headers
    for (Map.Entry<String, String> entry : httpHeaders) {
      frameHeaders.add(entry.getKey(), entry.getValue());
    }
    currentStreamId = spdySynStreamFrame.streamId();
    spdySynStreamFrame.setLast(isLast(httpMessage));

    return spdySynStreamFrame;
  }
    private void handleHttpRequest(ChannelHandlerContext ctx, HttpRequest req) throws Exception {
        if (req.method() != HttpMethod.GET) {
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_0, HttpResponseStatus.FORBIDDEN));
            ctx.close();
            return;
        } else {
            
            ByteBuf content = null;
            SentimentAndCensor twitterAnalysis = new SentimentAndCensor();
            int req_length = req.uri().length();
            String params = req.uri().substring(1, req_length);
            // Response to health check
            if (params.equals("heartbeat")) {
                content = Unpooled.wrappedBuffer("Health Check".getBytes());
            } else if (params.contains("key") && params.contains("message")) {
                TimeZone timeZone = TimeZone.getTimeZone("GMT-4:00");
                Calendar calendar = Calendar.getInstance(timeZone);
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
                simpleDateFormat.setTimeZone(timeZone);
                String data_string = simpleDateFormat.format(calendar.getTime()); // Retrive
                // the
                // time
                // of
                // local
                // timezone.
                
                QueryStringDecoder queryStringDecoder = new QueryStringDecoder(req.uri());
                String key = queryStringDecoder.parameters().get("key").get(0);
                String message = queryStringDecoder.parameters().get("message").get(0);
                Decoder decoder = new Decoder();
                String execute_data = decoder.Response(key, message);
                String line1 = teamId + "," + AWS_Account_Id + "\n";
                String result_line = line1 + data_string + "\n" + execute_data + "\n";
                content = Unpooled.wrappedBuffer(result_line.getBytes());
            } else if (params.contains("userid") && params.contains("tweet_time")) {
                // store two parameters into key(userid) and value(tweet_time)
                QueryStringDecoder queryStringDecoder = new QueryStringDecoder(req.uri());
                String key = queryStringDecoder.parameters().get("userid").get(0);
                String message = queryStringDecoder.parameters().get("tweet_time").get(0);
                
                // String decoder_result = twitterAnalysis.Response(key,
                // message);
                // result store the response string
                ArrayList<String> resultSet = selectFromSQLq2(key, message);
                
                String result = teamId + "," + AWS_Account_Id;
                for (int i = 0; i < resultSet.size(); i++) {
                    result = result + "\n" + resultSet.get(i);
                }
                result = result.trim() + "\n";
                content = Unpooled.wrappedBuffer(result.getBytes());
                
            } else if (params.contains("start_date") && params.contains("end_date") && params.contains("userid")
                       && params.contains("n")) {
                
                QueryStringDecoder queryStringDecoder = new QueryStringDecoder(req.uri());
                String start_date = queryStringDecoder.parameters().get("start_date").get(0);
                String end_date = queryStringDecoder.parameters().get("end_date").get(0);
                String userid = queryStringDecoder.parameters().get("userid").get(0);
                String n = queryStringDecoder.parameters().get("n").get(0);
                
                ArrayList<String> resultPositve = selectFromSQLq3_p(start_date, end_date, userid, n);
                ArrayList<String> resultNegetive = selectFromSQLq3_n(start_date, end_date, userid, n);
                
                String result = teamId + "," + AWS_Account_Id;
                
                result = result + "\n" + "Positive Tweets";
                for (int i = 0; i < resultPositve.size(); i++) {
                    result = result + "\n" + resultPositve.get(i);
                }
                
                result = result + "\n\n" + "Negative Tweets";
                for (int i = 0; i < resultNegetive.size(); i++) {
                    result = result + "\n" + resultNegetive.get(i);
                }
                
                result = result.trim() + "\n";
                
                //System.out.println(result);
                
                content = Unpooled.wrappedBuffer(result.getBytes());
                
            } else if (params.contains("hashtag") && params.contains("n")) {
                QueryStringDecoder queryStringDecoder = new QueryStringDecoder(req.uri());
                String hashtag = queryStringDecoder.parameters().get("hashtag").get(0);
                String n = queryStringDecoder.parameters().get("n").get(0);
                
                ArrayList<String> resultSet = selectFromSQLq4(hashtag, n);
                
                String result = teamId + "," + AWS_Account_Id;
                for (int i = 0; i < resultSet.size(); i++) {
                    result = result + "\n" + resultSet.get(i);
                }
                result = result.trim() + "\n";
                content = Unpooled.wrappedBuffer(result.getBytes());
                
            }else if(params.contains("userid_min") && params.contains("userid_max")){
                QueryStringDecoder queryStringDecoder = new QueryStringDecoder(req.uri());
                String min  = queryStringDecoder.parameters().get("userid_min").get(0);
                String max = queryStringDecoder.parameters().get("userid_max").get(0);
                
                // ArrayList<Integer> resultSet = selectFromSQLq5(max, min);
                int count = selectFromSQLq5(min, max);
                
                String result = teamId + "," + AWS_Account_Id + "\n";
                // int count = 0;
                // for (int i = 0; i < resultSet.size(); i++) {
                //     count += resultSet.get(i);
                // }

                result += count;

                result = result.trim() + "\n";
                content = Unpooled.wrappedBuffer(result.getBytes());
                
            } else {
                sendHttpResponse(ctx, req,
                                 new DefaultFullHttpResponse(HttpVersion.HTTP_1_0, HttpResponseStatus.FORBIDDEN));
                ctx.close();
                return;
            }
            FullHttpResponse res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_0, HttpResponseStatus.OK, content);
            res.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
            sendHttpResponse(ctx, req, res);
        }
        
    }