Example usage for io.netty.handler.codec.http DefaultFullHttpRequest DefaultFullHttpRequest

List of usage examples for io.netty.handler.codec.http DefaultFullHttpRequest DefaultFullHttpRequest

Introduction

In this page you can find the example usage for io.netty.handler.codec.http DefaultFullHttpRequest DefaultFullHttpRequest.

Prototype

public DefaultFullHttpRequest(HttpVersion httpVersion, HttpMethod method, String uri, boolean validateHeaders) 

Source Link

Usage

From source file:c5db.control.ClientHttpProtostuffEncoder.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, Message msg, List<Object> out) throws Exception {
    Class<?> messageType = msg.getClass();

    LowCopyProtobufOutput outputSerializer = new LowCopyProtobufOutput();
    msg.cachedSchema().writeTo(outputSerializer, msg);
    List<ByteBuffer> serializedBuffers = outputSerializer.buffer.finish();
    ByteBuf requestContent = Unpooled.wrappedBuffer(serializedBuffers.toArray(new ByteBuffer[] {}));

    DefaultFullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.POST,
            "foo", requestContent);

    httpRequest.headers().set(HttpProtostuffConstants.PROTOSTUFF_HEADER_NAME, messageType.getName());
    httpRequest.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/octet-stream");
    httpRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, requestContent.readableBytes());

    out.add(httpRequest);/*from  w  w  w . j  a v a2s .  c  om*/
}

From source file:com.ahanda.techops.noty.clientTest.ClientHandler.java

License:Apache License

private void getEvents(Channel ch, FullHttpResponse resp) {
    StringWriter estr = new StringWriter();
    getEvents.write(estr);/* w w w. j av  a  2  s  .  c o  m*/
    String contentStr = estr.toString();

    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/events/get",
            ch.alloc().buffer().writeBytes(contentStr.getBytes()));

    request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
    request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json");

    request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes());
    // Set some example cookies.
    request.headers().set(HttpHeaders.Names.COOKIE, ClientCookieEncoder.encode(sessCookies));

    l.info("getevents bytes {}", request.content().readableBytes());

    // Send the HTTP request.
    ch.writeAndFlush(request);
}

From source file:com.ahanda.techops.noty.clientTest.ClientHandler.java

License:Apache License

public void login(Channel ch, JSONObject credential) {
    StringWriter estr = new StringWriter();
    credential.write(estr);/*from  w  ww . jav  a  2  s.  c om*/
    String contentStr = estr.toString();
    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/login",
            ch.alloc().buffer().writeBytes(contentStr.getBytes()));

    request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
    request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json");
    if (sessCookies != null)
        request.headers().set(HttpHeaders.Names.COOKIE, ClientCookieEncoder.encode(sessCookies));

    request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes());

    l.info("login request {}", request);

    // Send the HTTP request.
    ch.writeAndFlush(request);
}

From source file:com.ahanda.techops.noty.clientTest.ClientHandler.java

License:Apache License

public void logout(Channel ch) {
    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.DELETE, "/logout",
            Unpooled.buffer(0));/*from ww  w . java  2  s.  com*/

    request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
    request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json");

    request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, 0);

    l.info("readable bytes {}", request.content().readableBytes());

    // Send the HTTP request.
    ch.writeAndFlush(request);
}

From source file:com.ahanda.techops.noty.clientTest.ClientHandler.java

License:Apache License

public void pubEvent(Channel ch, JSONObject e, FullHttpResponse resp) {
    // Prepare the HTTP request.
    JSONArray es = new JSONArray();
    es.put(e);//from  w w  w .j a va  2 s . c  o  m

    StringWriter estr = new StringWriter();
    es.write(estr);
    String contentStr = estr.toString();
    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/events",
            ch.alloc().buffer().writeBytes(contentStr.getBytes()));

    request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
    request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json");

    request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes());
    // Set some example cookies.
    request.headers().set(HttpHeaders.Names.COOKIE, ClientCookieEncoder.encode(sessCookies));

    l.info("PUB Event request {}", request);

    // Send the HTTP request.
    ch.writeAndFlush(request);
}

From source file:com.andrewkroh.cisco.xmlservices.DefaultXmlPushService.java

License:Apache License

/**
 * Builds a HTTP POST request containing the marshaled CiscoIPPhoneExecute
 * object in the body./*www  .  j a  v a 2  s . co  m*/
 *
 * <p/>
 * The phones require authentication in order to execute the commands. The
 * specified {@code username} and {@code password} will be included in the
 * request using HTTP Basic Authentication.
 *
 * @param hostname
 *            hostname of the server where the request will be sent
 * @param username
 *            username for authentiation to the phone
 * @param password
 *            password for authentication to the phone
 * @param command
 *            command to execute, this will be marshaled to XML
 * @param baseCallbackUrl
 *            optional base URL to the callback resource, any URLs in the
 *            outgoing command will have $BASEURL replaced with this value.
 *            {@code callbackUrl} cannot not end with '/'.
 * @return a fully-populated HTTP request
 */
private static HttpRequest buildRequest(String hostname, String username, String password,
        CiscoIPPhoneExecute command, String baseCallbackUrl) {
    Preconditions.checkNotNull(username, "Username cannot be null.");
    Preconditions.checkNotNull(password, "Password cannot be null.");
    Preconditions.checkNotNull(command, "CiscoIPPhoneExecute object cannot be null.");

    if (baseCallbackUrl != null) {
        replaceBaseUrlPlaceholder(command, baseCallbackUrl);
    }

    // Marshal object to XML and escape the XML:
    String objectAsXml = XmlMarshaller.marshalToXml(command);
    String urlEncodedXml = urlEncode(objectAsXml);

    // Build the content of the POST body:
    StringBuilder postContent = new StringBuilder();
    postContent.append("XML=");
    postContent.append(urlEncodedXml);

    // Encode the POST body to bytes:
    byte[] encodedPostContent = postContent.toString().getBytes(ENCODING);
    ByteBuf postContentByteBuf = Unpooled.wrappedBuffer(encodedPostContent);

    // Encode credentials:
    String encodedCredentials = base64EncodeCredentials(username, password);

    // Build the HTTP request:
    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            CISCO_CGI_EXECUTE_PATH, postContentByteBuf);
    request.headers().set(HttpHeaders.Names.HOST, hostname);
    request.headers().set(HttpHeaders.Names.AUTHORIZATION, encodedCredentials);
    request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
    request.headers().set(HttpHeaders.Names.CONTENT_TYPE, HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED);
    request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, encodedPostContent.length);

    return request;
}

From source file:com.codeabovelab.dm.platform.http.async.NettyRequest.java

License:Apache License

private FullHttpRequest createFullHttpRequest(HttpHeaders headers) {
    io.netty.handler.codec.http.HttpMethod nettyMethod = io.netty.handler.codec.http.HttpMethod
            .valueOf(this.method.name());

    FullHttpRequest nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, nettyMethod,
            this.uri.toString(), this.body.buffer());

    io.netty.handler.codec.http.HttpHeaders nettyHeaders = nettyRequest.headers();
    nettyHeaders.set(HttpHeaders.HOST, this.uri.getHost());
    nettyHeaders.set(HttpHeaders.CONNECTION, "close");

    for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
        nettyHeaders.add(entry.getKey(), entry.getValue());
    }/*from   w  w w . j  a v a2s .  c  o m*/

    return nettyRequest;
}

From source file:com.couchbase.client.core.endpoint.config.ConfigHandler.java

License:Apache License

@Override
protected HttpRequest encodeRequest(final ChannelHandlerContext ctx, final ConfigRequest msg) throws Exception {
    HttpMethod httpMethod = HttpMethod.GET;
    if (msg instanceof FlushRequest || msg instanceof InsertBucketRequest
            || msg instanceof UpdateBucketRequest) {
        httpMethod = HttpMethod.POST;/*from   w  w w  . j  a v a  2s  .co  m*/
    } else if (msg instanceof RemoveBucketRequest) {
        httpMethod = HttpMethod.DELETE;
    }

    ByteBuf content;
    if (msg instanceof InsertBucketRequest) {
        content = Unpooled.copiedBuffer(((InsertBucketRequest) msg).payload(), CharsetUtil.UTF_8);
    } else if (msg instanceof UpdateBucketRequest) {
        content = Unpooled.copiedBuffer(((UpdateBucketRequest) msg).payload(), CharsetUtil.UTF_8);
    } else {
        content = Unpooled.EMPTY_BUFFER;
    }

    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, httpMethod, msg.path(), content);
    request.headers().set(HttpHeaders.Names.USER_AGENT, env().userAgent());
    if (msg instanceof InsertBucketRequest || msg instanceof UpdateBucketRequest) {
        request.headers().set(HttpHeaders.Names.ACCEPT, "*/*");
        request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded");
    }
    request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, content.readableBytes());
    request.headers().set(HttpHeaders.Names.HOST, remoteHttpHost(ctx));

    addHttpBasicAuth(ctx, request, msg.bucket(), msg.password());
    return request;
}

From source file:com.couchbase.client.core.endpoint.search.SearchHandler.java

License:Apache License

@Override
protected HttpRequest encodeRequest(ChannelHandlerContext ctx, SearchRequest msg) throws Exception {
    HttpMethod httpMethod = HttpMethod.GET;
    if (msg instanceof UpsertSearchIndexRequest) {
        httpMethod = HttpMethod.PUT;//w w  w.  j av  a 2  s.  c o m
    } else if (msg instanceof RemoveSearchIndexRequest) {
        httpMethod = HttpMethod.DELETE;
    } else if (msg instanceof SearchQueryRequest) {
        httpMethod = HttpMethod.POST;
    }

    ByteBuf content;
    if (msg instanceof UpsertSearchIndexRequest) {
        content = Unpooled.copiedBuffer(((UpsertSearchIndexRequest) msg).payload(), CharsetUtil.UTF_8);
    } else if (msg instanceof SearchQueryRequest) {
        content = Unpooled.copiedBuffer(((SearchQueryRequest) msg).payload(), CharsetUtil.UTF_8);
    } else {
        content = Unpooled.EMPTY_BUFFER;
    }

    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, httpMethod, msg.path(), content);
    request.headers().set(HttpHeaders.Names.USER_AGENT, env().userAgent());
    if (msg instanceof UpsertSearchIndexRequest || msg instanceof SearchQueryRequest) {
        request.headers().set(HttpHeaders.Names.ACCEPT, "*/*");
        request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json");
    }
    request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, content.readableBytes());
    request.headers().set(HttpHeaders.Names.HOST, remoteHttpHost(ctx));

    addHttpBasicAuth(ctx, request, msg.bucket(), msg.password());
    return request;
}

From source file:com.couchbase.client.core.endpoint.view.ViewHandler.java

License:Apache License

@Override
protected HttpRequest encodeRequest(final ChannelHandlerContext ctx, final ViewRequest msg) throws Exception {
    if (msg instanceof KeepAliveRequest) {
        FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.HEAD, "/",
                Unpooled.EMPTY_BUFFER);/*from  ww w .j av a  2  s .  c  om*/
        request.headers().set(HttpHeaders.Names.USER_AGENT, env().userAgent());
        request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, 0);
        return request;
    }

    StringBuilder path = new StringBuilder();

    HttpMethod method = HttpMethod.GET;
    ByteBuf content = null;
    if (msg instanceof ViewQueryRequest) {
        ViewQueryRequest queryMsg = (ViewQueryRequest) msg;
        path.append("/").append(msg.bucket()).append("/_design/");
        path.append(queryMsg.development() ? "dev_" + queryMsg.design() : queryMsg.design());
        if (queryMsg.spatial()) {
            path.append("/_spatial/");
        } else {
            path.append("/_view/");
        }
        path.append(queryMsg.view());

        int queryLength = queryMsg.query() == null ? 0 : queryMsg.query().length();
        int keysLength = queryMsg.keys() == null ? 0 : queryMsg.keys().length();
        boolean hasQuery = queryLength > 0;
        boolean hasKeys = keysLength > 0;

        if (hasQuery || hasKeys) {
            if (queryLength + keysLength < MAX_GET_LENGTH) {
                //the query is short enough for GET
                //it has query, query+keys or keys only
                if (hasQuery) {
                    path.append("?").append(queryMsg.query());
                    if (hasKeys) {
                        path.append("&keys=").append(encodeKeysGet(queryMsg.keys()));
                    }
                } else {
                    //it surely has keys if not query
                    path.append("?keys=").append(encodeKeysGet(queryMsg.keys()));
                }
            } else {
                //the query is too long for GET, use the keys as JSON body
                if (hasQuery) {
                    path.append("?").append(queryMsg.query());
                }
                String keysContent = encodeKeysPost(queryMsg.keys());

                //switch to POST
                method = HttpMethod.POST;
                //body is "keys" but in JSON
                content = ctx.alloc().buffer(keysContent.length());
                content.writeBytes(keysContent.getBytes(CHARSET));
            }
        }
    } else if (msg instanceof GetDesignDocumentRequest) {
        GetDesignDocumentRequest queryMsg = (GetDesignDocumentRequest) msg;
        path.append("/").append(msg.bucket()).append("/_design/");
        path.append(queryMsg.development() ? "dev_" + queryMsg.name() : queryMsg.name());
    } else if (msg instanceof UpsertDesignDocumentRequest) {
        method = HttpMethod.PUT;
        UpsertDesignDocumentRequest queryMsg = (UpsertDesignDocumentRequest) msg;
        path.append("/").append(msg.bucket()).append("/_design/");
        path.append(queryMsg.development() ? "dev_" + queryMsg.name() : queryMsg.name());
        content = Unpooled.copiedBuffer(queryMsg.body(), CHARSET);
    } else if (msg instanceof RemoveDesignDocumentRequest) {
        method = HttpMethod.DELETE;
        RemoveDesignDocumentRequest queryMsg = (RemoveDesignDocumentRequest) msg;
        path.append("/").append(msg.bucket()).append("/_design/");
        path.append(queryMsg.development() ? "dev_" + queryMsg.name() : queryMsg.name());
    } else {
        throw new IllegalArgumentException("Unknown incoming ViewRequest type " + msg.getClass());
    }

    if (content == null) {
        content = Unpooled.buffer(0);
    }
    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, method, path.toString(),
            content);
    request.headers().set(HttpHeaders.Names.USER_AGENT, env().userAgent());
    request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, content.readableBytes());
    request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json");
    request.headers().set(HttpHeaders.Names.HOST, remoteHttpHost(ctx));
    addHttpBasicAuth(ctx, request, msg.bucket(), msg.password());

    return request;
}