@Override
 public @Nullable FullHttpResponse handleRequest(ChannelHandlerContext ctx, HttpRequest request)
     throws Exception {
   QueryStringDecoder decoder = new QueryStringDecoder(request.uri());
   List<String> agentIds = decoder.parameters().get("agent-id");
   if (agentIds == null) {
     agentIds = ImmutableList.of("");
   }
   String agentId = agentIds.get(0);
   List<String> traceIds = decoder.parameters().get("trace-id");
   checkNotNull(traceIds, "Missing trace id in query string: %s", request.uri());
   String traceId = traceIds.get(0);
   // check-live-traces is an optimization so glowroot server only has to check with remote
   // agents when necessary
   List<String> checkLiveTracesParams = decoder.parameters().get("check-live-traces");
   boolean checkLiveTraces = false;
   if (checkLiveTracesParams != null && !checkLiveTracesParams.isEmpty()) {
     checkLiveTraces = Boolean.parseBoolean(checkLiveTracesParams.get(0));
   }
   logger.debug(
       "handleRequest(): agentId={}, traceId={}, checkLiveTraces={}",
       agentId,
       traceId,
       checkLiveTraces);
   TraceExport traceExport = traceCommonService.getExport(agentId, traceId, checkLiveTraces);
   if (traceExport == null) {
     logger.warn("no trace found for id: {}", traceId);
     return new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND);
   }
   ChunkedInput<HttpContent> in = getExportChunkedInput(traceExport);
   HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
   response.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
   response.headers().set(HttpHeaderNames.CONTENT_TYPE, MediaType.ZIP.toString());
   response
       .headers()
       .set("Content-Disposition", "attachment; filename=" + traceExport.fileName() + ".zip");
   boolean keepAlive = HttpUtil.isKeepAlive(request);
   if (keepAlive && !request.protocolVersion().isKeepAliveDefault()) {
     response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
   }
   HttpServices.preventCaching(response);
   ctx.write(response);
   ChannelFuture future = ctx.write(in);
   HttpServices.addErrorListener(future);
   if (!keepAlive) {
     HttpServices.addCloseListener(future);
   }
   // return null to indicate streaming
   return null;
 }
Esempio n. 2
0
 @URLPattern("/hello/[a-zA-Z]{3,3}[A-Za-z0-9]*")
 public FullHttpResponse parameterized(HttpRequest req) {
   return new DefaultFullHttpResponse(
       HTTP_1_1,
       OK,
       Unpooled.wrappedBuffer(("Hello " + req.uri().replaceAll("/hello/", "")).getBytes()));
 }
Esempio n. 3
0
  @Override
  public void channelRead0(final ChannelHandlerContext ctx, final HttpRequest req)
      throws Exception {
    Preconditions.checkArgument(req.uri().startsWith(WEBHDFS_PREFIX));
    QueryStringDecoder queryString = new QueryStringDecoder(req.uri());
    params = new ParameterParser(queryString, conf);
    DataNodeUGIProvider ugiProvider = new DataNodeUGIProvider(params);
    ugi = ugiProvider.ugi();
    path = params.path();

    injectToken();
    ugi.doAs(
        new PrivilegedExceptionAction<Void>() {
          @Override
          public Void run() throws Exception {
            handle(ctx, req);
            return null;
          }
        });
  }
Esempio n. 4
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);
    }
  }
Esempio n. 5
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));
    }
  }
  @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());
    }
  }
Esempio n. 7
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);
        }
        
    }