Java Code Examples for io.netty.handler.codec.http.HttpRequest#getMethod()

The following examples show how to use io.netty.handler.codec.http.HttpRequest#getMethod() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WebHdfsHandler.java    From hadoop with Apache License 2.0 6 votes vote down vote up
public void handle(ChannelHandlerContext ctx, HttpRequest req)
  throws IOException, URISyntaxException {
  String op = params.op();
  HttpMethod method = req.getMethod();
  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);
  }
}
 
Example 2
Source File: WebHdfsHandler.java    From big-c with Apache License 2.0 6 votes vote down vote up
public void handle(ChannelHandlerContext ctx, HttpRequest req)
  throws IOException, URISyntaxException {
  String op = params.op();
  HttpMethod method = req.getMethod();
  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);
  }
}
 
Example 3
Source File: AutobahnServerHandler.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
private void handleHttpRequest(ChannelHandlerContext ctx, HttpRequest req)
        throws Exception {
    // Handle a bad request.
    if (!req.getDecoderResult().isSuccess()) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
        return;
    }

    // Allow only GET methods.
    if (req.getMethod() != GET) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
        return;
    }

    // Handshake
    WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
            getWebSocketLocation(req), null, false, Integer.MAX_VALUE);
    handshaker = wsFactory.newHandshaker(req);
    if (handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
    } else {
        handshaker.handshake(ctx.channel(), req);
    }
}
 
Example 4
Source File: ClientToProxyConnection.java    From g4proxy with Apache License 2.0 5 votes vote down vote up
/**
 * Copy the given {@link HttpRequest} verbatim.
 * 
 * @param original
 * @return
 */
private HttpRequest copy(HttpRequest original) {
    if (original instanceof FullHttpRequest) {
        return ((FullHttpRequest) original).copy();
    } else {
        HttpRequest request = new DefaultHttpRequest(original.getProtocolVersion(),
                original.getMethod(), original.getUri());
        request.headers().set(original.headers());
        return request;
    }
}
 
Example 5
Source File: HttpPostRequestEncoder.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param factory
 *            the factory used to create InterfaceHttpData
 * @param request
 *            the request to encode
 * @param multipart
 *            True if the FORM is a ENCTYPE="multipart/form-data"
 * @param charset
 *            the charset to use as default
 * @param encoderMode
 *            the mode for the encoder to use. See {@link EncoderMode} for the details.
 * @throws NullPointerException
 *             for request or charset or factory
 * @throws ErrorDataEncoderException
 *             if the request is not a POST
 */
public HttpPostRequestEncoder(
        HttpDataFactory factory, HttpRequest request, boolean multipart, Charset charset,
        EncoderMode encoderMode)
        throws ErrorDataEncoderException {
    if (factory == null) {
        throw new NullPointerException("factory");
    }
    if (request == null) {
        throw new NullPointerException("request");
    }
    if (charset == null) {
        throw new NullPointerException("charset");
    }
    if (request.getMethod() != HttpMethod.POST) {
        throw new ErrorDataEncoderException("Cannot create a Encoder if not a POST");
    }
    this.request = request;
    this.charset = charset;
    this.factory = factory;
    // Fill default values
    bodyListDatas = new ArrayList<InterfaceHttpData>();
    // default mode
    isLastChunk = false;
    isLastChunkSent = false;
    isMultipart = multipart;
    multipartHttpDatas = new ArrayList<InterfaceHttpData>();
    this.encoderMode = encoderMode;
    if (isMultipart) {
        initDataMultipart();
    }
}
 
Example 6
Source File: WebSocketService.java    From netty-rest with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RakamHttpRequest request) {
    WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
            getWebSocketLocation(request), null, true);
    handshaker = wsFactory.newHandshaker(request.getRequest());
    if (handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(request.context().channel());
    } else {
        HttpRequest request1 = request.getRequest();
        DefaultFullHttpRequest defaultFullHttpRequest = new DefaultFullHttpRequest(request1.getProtocolVersion(), request1.getMethod(), request1.getUri());
        defaultFullHttpRequest.headers().set(request1.headers());
        handshaker.handshake(request.context().channel(), defaultFullHttpRequest);
        onOpen(new WebSocketRequest(request));
    }
}
 
Example 7
Source File: Tracker.java    From blueflood with Apache License 2.0 5 votes vote down vote up
public void track(HttpRequest request) {
    // check if tenantId is being tracked by JMX TenantTrackerMBean and log the request if it is
    if (request == null) return;

    String tenantId = findTid( request.getUri() );

    if (isTracking(tenantId)) {

        // get headers
        String headers = EMPTY_STRING;
        for (String headerName : request.headers().names()) {
            headers += "\n" + headerName + "\t" + request.headers().get(headerName);
        }

        // get parameters
        String queryParams = getQueryParameters(request);

        // get request content
        String requestContent = EMPTY_STRING;
        if ( request instanceof FullHttpRequest ) {
            FullHttpRequest fullReq = (FullHttpRequest)request;
            requestContent = fullReq.content().toString(Constants.DEFAULT_CHARSET);
            if ((requestContent != null) && (!requestContent.isEmpty())) {
                requestContent = "\nREQUEST_CONTENT:\n" + requestContent;
            }
        }

        // log request
        String logMessage = "[TRACKER] " +
                request.getMethod() + " request for tenantId " + tenantId + ": " + request.getUri() + queryParams + "\n" +
                "HEADERS: " + headers +
                requestContent;

        if (doesMessageContainMetricNames(logMessage)) {
            log.info(logMessage);
        }
    }
}
 
Example 8
Source File: Tracker.java    From blueflood with Apache License 2.0 5 votes vote down vote up
public void trackResponse(HttpRequest request, FullHttpResponse response) {
    // check if tenantId is being tracked by JMX TenantTrackerMBean and log the response if it is
    // HttpRequest is needed for original request uri and tenantId
    if (request == null) return;
    if (response == null) return;

    String tenantId = findTid( request.getUri() );
    if (isTracking(tenantId)) {
        HttpResponseStatus status = response.getStatus();
        String messageBody = response.content().toString(Constants.DEFAULT_CHARSET);

        // get parameters
        String queryParams = getQueryParameters(request);

        // get headers
        String headers = "";
        for (String headerName : response.headers().names()) {
            headers += "\n" + headerName + "\t" + response.headers().get(headerName);
        }

        // get response content
        String responseContent = "";
        if ((messageBody != null) && (!messageBody.isEmpty())) {
            responseContent = "\nRESPONSE_CONTENT:\n" + messageBody;
        }

        String logMessage = "[TRACKER] " +
                "Response for tenantId " + tenantId + " " + request.getMethod() + " request " + request.getUri() + queryParams +
                "\nRESPONSE_STATUS: " + status.code() +
                "\nRESPONSE HEADERS: " + headers +
                responseContent;

        log.info(logMessage);
    }

}
 
Example 9
Source File: HttpReqDispatcher.java    From jframe with Apache License 2.0 4 votes vote down vote up
/**
 * request regular expression
 */
// public final static Pattern Req_Regx = Pattern
// .compile("\\/(.*?)\\/(.*?)(?:\\/(.*))?");

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;
        if (LOG.isDebugEnabled()) {
            LOG.debug("Dispatch req path {} method {}", req.getUri(), req.getMethod().name());
        }

        // pay client req
        final String reqUrl = req.getUri();
        Map<String, WeakReference<String>> cache = _cache;

        WeakReference<String> wr = cache.get(reqUrl);
        String clazz = wr != null && wr.get() != null ? wr.get() : null;
        if (clazz != null) {
            // if (reqUrl.startsWith("/common/image/download")) {
            // ctx.pipeline().addLast("http aggregator",
            // new HttpObjectAggregator(65536));
            // ctx.pipeline().addLast("http chunk",
            // new ChunkedWriteHandler());
            // }

            ctx.pipeline().addLast((ChannelHandler) getClass().getClassLoader().loadClass(clazz).newInstance());
        } else {
            List<Dispatcher> list = _dispatcher;
            boolean notFound = true;
            for (Dispatcher d : list) {
                if (d.getMethod().contains(req.getMethod().name()) && Pattern.matches(d.getUrl(), reqUrl)) {
                    // if (d.getId().equals("img.down")) {
                    // ctx.pipeline().remove("http compressor");
                    // ctx.pipeline().addLast("http aggregator",
                    // new HttpObjectAggregator(65536)); //
                    // ctx.pipeline().addLast("http chunk",
                    // new ChunkedWriteHandler());
                    // }
                    ctx.pipeline().addLast(
                            (ChannelHandler) getClass().getClassLoader().loadClass(d.getClazz()).newInstance());
                    cache.put(reqUrl, new WeakReference<String>(d.getClazz()));
                    notFound = false;
                    break;
                }
            }
            if (notFound) {
                // ctx.pipeline().addLast(VoidHandler);
                // cache.put(reqUrl, new
                // WeakReference<String>(VoidHandler.getClass().getName()));
                // LOG.error("Not found reqUrl->{}", reqUrl);
                throw new Exception("HttpReqDispatcher not match uri->" + reqUrl + " method->" + req.getMethod());
            }
        }
    }
    ReferenceCountUtil.retain(msg);
    ctx.fireChannelRead(msg);
}
 
Example 10
Source File: HTTPSProxyAuthConduitTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
public void requestReceivedFromClient(FlowContext flowContext,
                                      HttpRequest httpRequest) {
    if (httpRequest.getMethod() != HttpMethod.CONNECT) {
        count.incrementAndGet();
    }
}
 
Example 11
Source File: HTTPSProxyConduitTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
public void requestReceivedFromClient(FlowContext flowContext,
                                      HttpRequest httpRequest) {
    if (httpRequest.getMethod() != HttpMethod.CONNECT) {
        count.incrementAndGet();
    }
}
 
Example 12
Source File: ClientToProxyConnection.java    From g4proxy with Apache License 2.0 3 votes vote down vote up
/**
 * Returns true if the specified request is a request to an origin server, rather than to a proxy server. If this
 * request is being MITM'd, this method always returns false. The format of requests to a proxy server are defined
 * in RFC 7230, section 5.3.2 (all other requests are considered requests to an origin server):
 <pre>
     When making a request to a proxy, other than a CONNECT or server-wide
     OPTIONS request (as detailed below), a client MUST send the target
     URI in absolute-form as the request-target.
     [...]
     An example absolute-form of request-line would be:
     GET http://www.example.org/pub/WWW/TheProject.html HTTP/1.1
     To allow for transition to the absolute-form for all requests in some
     future version of HTTP, a server MUST accept the absolute-form in
     requests, even though HTTP/1.1 clients will only send them in
     requests to proxies.
 </pre>
 *
 * @param httpRequest the request to evaluate
 * @return true if the specified request is a request to an origin server, otherwise false
 */
private boolean isRequestToOriginServer(HttpRequest httpRequest) {
    // while MITMing, all HTTPS requests are requests to the origin server, since the client does not know
    // the request is being MITM'd by the proxy
    if (httpRequest.getMethod() == HttpMethod.CONNECT || isMitming()) {
        return false;
    }

    // direct requests to the proxy have the path only without a scheme
    String uri = httpRequest.getUri();
    return !HTTP_SCHEME.matcher(uri).matches();
}