Search in sources :

Example 1 with HttpMethod

use of io.netty.handler.codec.http.HttpMethod in project elasticsearch by elastic.

the class Netty4HttpServerTransport method buildCorsConfig.

// package private for testing
static Netty4CorsConfig buildCorsConfig(Settings settings) {
    if (SETTING_CORS_ENABLED.get(settings) == false) {
        return Netty4CorsConfigBuilder.forOrigins().disable().build();
    }
    String origin = SETTING_CORS_ALLOW_ORIGIN.get(settings);
    final Netty4CorsConfigBuilder builder;
    if (Strings.isNullOrEmpty(origin)) {
        builder = Netty4CorsConfigBuilder.forOrigins();
    } else if (origin.equals(ANY_ORIGIN)) {
        builder = Netty4CorsConfigBuilder.forAnyOrigin();
    } else {
        Pattern p = RestUtils.checkCorsSettingForRegex(origin);
        if (p == null) {
            builder = Netty4CorsConfigBuilder.forOrigins(RestUtils.corsSettingAsArray(origin));
        } else {
            builder = Netty4CorsConfigBuilder.forPattern(p);
        }
    }
    if (SETTING_CORS_ALLOW_CREDENTIALS.get(settings)) {
        builder.allowCredentials();
    }
    String[] strMethods = Strings.tokenizeToStringArray(SETTING_CORS_ALLOW_METHODS.get(settings), ",");
    HttpMethod[] methods = Arrays.asList(strMethods).stream().map(HttpMethod::valueOf).toArray(size -> new HttpMethod[size]);
    return builder.allowedRequestMethods(methods).maxAge(SETTING_CORS_MAX_AGE.get(settings)).allowedRequestHeaders(Strings.tokenizeToStringArray(SETTING_CORS_ALLOW_HEADERS.get(settings), ",")).shortCircuit().build();
}
Also used : Pattern(java.util.regex.Pattern) Netty4CorsConfigBuilder(org.elasticsearch.http.netty4.cors.Netty4CorsConfigBuilder) HttpMethod(io.netty.handler.codec.http.HttpMethod)

Example 2 with HttpMethod

use of io.netty.handler.codec.http.HttpMethod in project vert.x by eclipse.

the class HttpServerRequestImpl method setExpectMultipart.

@Override
public HttpServerRequest setExpectMultipart(boolean expect) {
    synchronized (conn) {
        checkEnded();
        if (expect) {
            if (decoder == null) {
                String contentType = request.headers().get(HttpHeaders.Names.CONTENT_TYPE);
                if (contentType != null) {
                    HttpMethod method = request.getMethod();
                    String lowerCaseContentType = contentType.toLowerCase();
                    boolean isURLEncoded = lowerCaseContentType.startsWith(HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED);
                    if ((lowerCaseContentType.startsWith(HttpHeaders.Values.MULTIPART_FORM_DATA) || isURLEncoded) && (method.equals(HttpMethod.POST) || method.equals(HttpMethod.PUT) || method.equals(HttpMethod.PATCH) || method.equals(HttpMethod.DELETE))) {
                        decoder = new HttpPostRequestDecoder(new NettyFileUploadDataFactory(conn.vertx(), this, () -> uploadHandler), request);
                    }
                }
            }
        } else {
            decoder = null;
        }
        return this;
    }
}
Also used : HttpPostRequestDecoder(io.netty.handler.codec.http.multipart.HttpPostRequestDecoder) HttpMethod(io.netty.handler.codec.http.HttpMethod)

Example 3 with HttpMethod

use of io.netty.handler.codec.http.HttpMethod in project hadoop by apache.

the class WebHdfsHandler method handle.

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 if (PutOpParam.Op.CREATE.name().equalsIgnoreCase(op) && method == OPTIONS) {
        allowCORSOnCreate(ctx);
    } else {
        throw new IllegalArgumentException("Invalid operation " + op);
    }
}
Also used : HttpMethod(io.netty.handler.codec.http.HttpMethod)

Example 4 with HttpMethod

use of io.netty.handler.codec.http.HttpMethod in project asterixdb by apache.

the class ApplicationInstallationHandler method handle.

@Override
public void handle(IServletRequest request, IServletResponse response) {
    String localPath = localPath(request);
    while (localPath.startsWith("/")) {
        localPath = localPath.substring(1);
    }
    final String[] params = localPath.split("&");
    if (params.length != 2 || params[0].isEmpty() || params[1].isEmpty()) {
        response.setStatus(HttpResponseStatus.BAD_REQUEST);
        return;
    }
    final String deployIdString = params[0];
    final String fileName = params[1];
    final String rootDir = ccs.getServerContext().getBaseDir().toString();
    final String deploymentDir = rootDir.endsWith(File.separator) ? rootDir + "applications/" + deployIdString : rootDir + File.separator + "/applications/" + File.separator + deployIdString;
    final HttpMethod method = request.getHttpRequest().method();
    try {
        if (method == HttpMethod.PUT) {
            final ByteBuf content = request.getHttpRequest().content();
            writeToFile(content, deploymentDir, fileName);
        } else if (method == HttpMethod.GET) {
            readFromFile(fileName, deploymentDir, response);
        } else {
            response.setStatus(HttpResponseStatus.METHOD_NOT_ALLOWED);
        }
    } catch (Exception e) {
        LOGGER.log(Level.WARNING, "Unhandled exception ", e);
        response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
    }
}
Also used : ByteBuf(io.netty.buffer.ByteBuf) HttpMethod(io.netty.handler.codec.http.HttpMethod)

Example 5 with HttpMethod

use of io.netty.handler.codec.http.HttpMethod in project camel by apache.

the class DefaultNettyHttpBinding method toNettyRequest.

@Override
public HttpRequest toNettyRequest(Message message, String uri, NettyHttpConfiguration configuration) throws Exception {
    LOG.trace("toNettyRequest: {}", message);
    // the message body may already be a Netty HTTP response
    if (message.getBody() instanceof HttpRequest) {
        return (HttpRequest) message.getBody();
    }
    String uriForRequest = uri;
    if (configuration.isUseRelativePath()) {
        int indexOfPath = uri.indexOf((new URI(uri)).getPath());
        if (indexOfPath > 0) {
            uriForRequest = uri.substring(indexOfPath);
        }
    }
    // just assume GET for now, we will later change that to the actual method to use
    HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uriForRequest);
    Object body = message.getBody();
    if (body != null) {
        // support bodies as native Netty
        ByteBuf buffer;
        if (body instanceof ByteBuf) {
            buffer = (ByteBuf) body;
        } else {
            // try to convert to buffer first
            buffer = message.getBody(ByteBuf.class);
            if (buffer == null) {
                // fallback to byte array as last resort
                byte[] data = message.getMandatoryBody(byte[].class);
                buffer = NettyConverter.toByteBuffer(data);
            }
        }
        if (buffer != null) {
            request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uriForRequest, buffer);
            int len = buffer.readableBytes();
            // set content-length
            request.headers().set(HttpHeaderNames.CONTENT_LENGTH.toString(), len);
            LOG.trace("Content-Length: {}", len);
        } else {
            // we do not support this kind of body
            throw new NoTypeConversionAvailableException(body, ByteBuf.class);
        }
    }
    // update HTTP method accordingly as we know if we have a body or not
    HttpMethod method = NettyHttpHelper.createMethod(message, body != null);
    request.setMethod(method);
    TypeConverter tc = message.getExchange().getContext().getTypeConverter();
    // if we bridge endpoint then we need to skip matching headers with the HTTP_QUERY to avoid sending
    // duplicated headers to the receiver, so use this skipRequestHeaders as the list of headers to skip
    Map<String, Object> skipRequestHeaders = null;
    if (configuration.isBridgeEndpoint()) {
        String queryString = message.getHeader(Exchange.HTTP_QUERY, String.class);
        if (queryString != null) {
            skipRequestHeaders = URISupport.parseQuery(queryString, false, true);
        }
        // Need to remove the Host key as it should be not used
        message.getHeaders().remove("host");
    }
    // must use entrySet to ensure case of keys is preserved
    for (Map.Entry<String, Object> entry : message.getHeaders().entrySet()) {
        String key = entry.getKey();
        Object value = entry.getValue();
        // as then we would duplicate headers on both the endpoint uri, and in HTTP headers as well
        if (skipRequestHeaders != null && skipRequestHeaders.containsKey(key)) {
            continue;
        }
        // use an iterator as there can be multiple values. (must not use a delimiter)
        final Iterator<?> it = ObjectHelper.createIterator(value, null, true);
        while (it.hasNext()) {
            String headerValue = tc.convertTo(String.class, it.next());
            if (headerValue != null && headerFilterStrategy != null && !headerFilterStrategy.applyFilterToCamelHeaders(key, headerValue, message.getExchange())) {
                LOG.trace("HTTP-Header: {}={}", key, headerValue);
                request.headers().add(key, headerValue);
            }
        }
    }
    // set the content type in the response.
    String contentType = MessageHelper.getContentType(message);
    if (contentType != null) {
        // set content-type
        request.headers().set(HttpHeaderNames.CONTENT_TYPE.toString(), contentType);
        LOG.trace("Content-Type: {}", contentType);
    }
    // must include HOST header as required by HTTP 1.1
    // use URI as its faster than URL (no DNS lookup)
    URI u = new URI(uri);
    String hostHeader = u.getHost() + (u.getPort() == 80 ? "" : ":" + u.getPort());
    request.headers().set(HttpHeaderNames.HOST.toString(), hostHeader);
    LOG.trace("Host: {}", hostHeader);
    // configure connection to accordingly to keep alive configuration
    // favor using the header from the message
    String connection = message.getHeader(HttpHeaderNames.CONNECTION.toString(), String.class);
    if (connection == null) {
        // fallback and use the keep alive from the configuration
        if (configuration.isKeepAlive()) {
            connection = HttpHeaderValues.KEEP_ALIVE.toString();
        } else {
            connection = HttpHeaderValues.CLOSE.toString();
        }
    }
    request.headers().set(HttpHeaderNames.CONNECTION.toString(), connection);
    LOG.trace("Connection: {}", connection);
    return request;
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) NoTypeConversionAvailableException(org.apache.camel.NoTypeConversionAvailableException) ByteBuf(io.netty.buffer.ByteBuf) URI(java.net.URI) TypeConverter(org.apache.camel.TypeConverter) Map(java.util.Map) HttpMethod(io.netty.handler.codec.http.HttpMethod)

Aggregations

HttpMethod (io.netty.handler.codec.http.HttpMethod)95 Test (org.junit.Test)51 HttpRequest (io.netty.handler.codec.http.HttpRequest)28 DefaultHttpRequest (io.netty.handler.codec.http.DefaultHttpRequest)25 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)21 URI (java.net.URI)15 IOException (java.io.IOException)13 AtomicReference (java.util.concurrent.atomic.AtomicReference)13 DataProvider (com.tngtech.java.junit.dataprovider.DataProvider)11 HttpVersion (io.netty.handler.codec.http.HttpVersion)11 DefaultHttpClient (org.jocean.http.client.impl.DefaultHttpClient)11 TestChannelCreator (org.jocean.http.client.impl.TestChannelCreator)11 TestChannelPool (org.jocean.http.client.impl.TestChannelPool)11 DefaultSignalClient (org.jocean.http.rosa.impl.DefaultSignalClient)11 HttpTrade (org.jocean.http.server.HttpServerBuilder.HttpTrade)11 Subscription (rx.Subscription)11 Action2 (rx.functions.Action2)11 ByteBuf (io.netty.buffer.ByteBuf)10 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)10 Map (java.util.Map)9