Search in sources :

Example 11 with HttpMethod

use of org.apache.flink.shaded.netty4.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 12 with HttpMethod

use of org.apache.flink.shaded.netty4.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)

Example 13 with HttpMethod

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpMethod in project camel by apache.

the class NettyHttpHelper method createMethod.

/**
     * Creates the {@link HttpMethod} to use to call the remote server, often either its GET or POST.
     *
     * @param message  the Camel message
     * @return the created method
     */
public static HttpMethod createMethod(Message message, boolean hasPayload) {
    // use header first
    HttpMethod m = message.getHeader(Exchange.HTTP_METHOD, HttpMethod.class);
    if (m != null) {
        return m;
    }
    String name = message.getHeader(Exchange.HTTP_METHOD, String.class);
    if (name != null) {
        return HttpMethod.valueOf(name);
    }
    if (hasPayload) {
        // use POST if we have payload
        return HttpMethod.POST;
    } else {
        // fallback to GET
        return HttpMethod.GET;
    }
}
Also used : HttpMethod(io.netty.handler.codec.http.HttpMethod)

Example 14 with HttpMethod

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpMethod in project ratpack by ratpack.

the class WebSocketEngine method connect.

@SuppressWarnings("deprecation")
public static <T> void connect(final Context context, String path, int maxLength, final WebSocketHandler<T> handler) {
    PublicAddress publicAddress = context.get(PublicAddress.class);
    URI address = publicAddress.get(context);
    URI httpPath = address.resolve(path);
    URI wsPath;
    try {
        wsPath = new URI("ws", httpPath.getUserInfo(), httpPath.getHost(), httpPath.getPort(), httpPath.getPath(), httpPath.getQuery(), httpPath.getFragment());
    } catch (URISyntaxException e) {
        throw uncheck(e);
    }
    WebSocketServerHandshakerFactory factory = new WebSocketServerHandshakerFactory(wsPath.toString(), null, false, maxLength);
    Request request = context.getRequest();
    HttpMethod method = valueOf(request.getMethod().getName());
    FullHttpRequest nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, method, request.getUri());
    nettyRequest.headers().add(SEC_WEBSOCKET_VERSION, request.getHeaders().get(SEC_WEBSOCKET_VERSION));
    nettyRequest.headers().add(SEC_WEBSOCKET_KEY, request.getHeaders().get(SEC_WEBSOCKET_KEY));
    final WebSocketServerHandshaker handshaker = factory.newHandshaker(nettyRequest);
    final DirectChannelAccess directChannelAccess = context.getDirectChannelAccess();
    final Channel channel = directChannelAccess.getChannel();
    if (!channel.config().isAutoRead()) {
        channel.config().setAutoRead(true);
    }
    handshaker.handshake(channel, nettyRequest).addListener(new HandshakeFutureListener<>(context, handshaker, handler));
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) DirectChannelAccess(ratpack.handling.direct.DirectChannelAccess) Channel(io.netty.channel.Channel) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) Request(ratpack.http.Request) PublicAddress(ratpack.server.PublicAddress) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) HttpMethod(io.netty.handler.codec.http.HttpMethod)

Example 15 with HttpMethod

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpMethod in project BRFS by zhangnianli.

the class Test method main.

public static void main(String[] args) throws Exception {
    // Runtime.getRuntime().addShutdownHook(new Thread() {
    // @Override
    // public void run() {
    // System.out.println("shutdown thread run...");
    // }
    // });
    // 
    // Thread.sleep(60000);
    Map<HttpMethod, String> map = new HashMap<HttpMethod, String>();
    map.put(HttpMethod.valueOf("CLOSE"), "1234");
    System.out.println(map.get(HttpMethod.valueOf("CLOSE")));
    System.out.println("--" + URLDecoder.decode("/mem/data/brfs/t3", "UTF-8"));
    File f = new File("/root/temp/a.txt");
    System.out.println(f.getParent());
    System.out.println(f.getName());
}
Also used : HashMap(java.util.HashMap) File(java.io.File) HttpMethod(io.netty.handler.codec.http.HttpMethod)

Aggregations

HttpMethod (io.netty.handler.codec.http.HttpMethod)83 Test (org.junit.Test)44 HttpRequest (io.netty.handler.codec.http.HttpRequest)24 DefaultHttpRequest (io.netty.handler.codec.http.DefaultHttpRequest)23 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)20 URI (java.net.URI)15 IOException (java.io.IOException)14 AtomicReference (java.util.concurrent.atomic.AtomicReference)13 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 HttpVersion (io.netty.handler.codec.http.HttpVersion)10 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)9 Map (java.util.Map)9 DataProvider (com.tngtech.java.junit.dataprovider.DataProvider)8