Search in sources :

Example 1 with DefaultHttpDataFactory

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

the class RestClient method createRequest.

private static Request createRequest(String targetAddress, String targetUrl, HttpMethod httpMethod, ByteBuf jsonPayload, Collection<FileUpload> fileUploads) throws IOException {
    if (fileUploads.isEmpty()) {
        HttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, httpMethod, targetUrl, jsonPayload);
        httpRequest.headers().set(HttpHeaders.Names.HOST, targetAddress).set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE).add(HttpHeaders.Names.CONTENT_LENGTH, jsonPayload.capacity()).add(HttpHeaders.Names.CONTENT_TYPE, RestConstants.REST_CONTENT_TYPE);
        return new SimpleRequest(httpRequest);
    } else {
        HttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, httpMethod, targetUrl);
        httpRequest.headers().set(HttpHeaders.Names.HOST, targetAddress).set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
        // takes care of splitting the request into multiple parts
        HttpPostRequestEncoder bodyRequestEncoder;
        try {
            // we could use mixed attributes here but we have to ensure that the minimum size is
            // greater than
            // any file as the upload otherwise fails
            DefaultHttpDataFactory httpDataFactory = new DefaultHttpDataFactory(true);
            // the FileUploadHandler explicitly checks for multipart headers
            bodyRequestEncoder = new HttpPostRequestEncoder(httpDataFactory, httpRequest, true);
            Attribute requestAttribute = new MemoryAttribute(FileUploadHandler.HTTP_ATTRIBUTE_REQUEST);
            requestAttribute.setContent(jsonPayload);
            bodyRequestEncoder.addBodyHttpData(requestAttribute);
            int fileIndex = 0;
            for (FileUpload fileUpload : fileUploads) {
                Path path = fileUpload.getFile();
                if (Files.isDirectory(path)) {
                    throw new IllegalArgumentException("Upload of directories is not supported. Dir=" + path);
                }
                File file = path.toFile();
                LOG.trace("Adding file {} to request.", file);
                bodyRequestEncoder.addBodyFileUpload("file_" + fileIndex, file, fileUpload.getContentType(), false);
                fileIndex++;
            }
        } catch (HttpPostRequestEncoder.ErrorDataEncoderException e) {
            throw new IOException("Could not encode request.", e);
        }
        try {
            httpRequest = bodyRequestEncoder.finalizeRequest();
        } catch (HttpPostRequestEncoder.ErrorDataEncoderException e) {
            throw new IOException("Could not finalize request.", e);
        }
        return new MultipartRequest(httpRequest, bodyRequestEncoder);
    }
}
Also used : HttpRequest(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpRequest) DefaultFullHttpRequest(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultFullHttpRequest) Path(java.nio.file.Path) DefaultFullHttpRequest(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultFullHttpRequest) MemoryAttribute(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.multipart.MemoryAttribute) Attribute(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.multipart.Attribute) HttpPostRequestEncoder(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.multipart.HttpPostRequestEncoder) IOException(java.io.IOException) MemoryAttribute(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.multipart.MemoryAttribute) DefaultHttpDataFactory(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.multipart.DefaultHttpDataFactory) File(java.io.File)

Example 2 with DefaultHttpDataFactory

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

the class HttpUploadClient method main.

public static void main(String[] args) throws Exception {
    String postSimple, postFile, get;
    if (BASE_URL.endsWith("/")) {
        postSimple = BASE_URL + "formpost";
        postFile = BASE_URL + "formpostmultipart";
        get = BASE_URL + "formget";
    } else {
        postSimple = BASE_URL + "/formpost";
        postFile = BASE_URL + "/formpostmultipart";
        get = BASE_URL + "/formget";
    }
    URI uriSimple = new URI(postSimple);
    String scheme = uriSimple.getScheme() == null ? "http" : uriSimple.getScheme();
    String host = uriSimple.getHost() == null ? "127.0.0.1" : uriSimple.getHost();
    int port = uriSimple.getPort();
    if (port == -1) {
        if ("http".equalsIgnoreCase(scheme)) {
            port = 80;
        } else if ("https".equalsIgnoreCase(scheme)) {
            port = 443;
        }
    }
    if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
        System.err.println("Only HTTP(S) is supported.");
        return;
    }
    final boolean ssl = "https".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }
    URI uriFile = new URI(postFile);
    File file = new File(FILE);
    if (!file.canRead()) {
        throw new FileNotFoundException(FILE);
    }
    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    // setup the factory: here using a mixed memory/disk based on size threshold
    // Disk if MINSIZE exceed
    HttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE);
    // should delete file on exit (in normal exit)
    DiskFileUpload.deleteOnExitTemporaryFile = true;
    // system temp directory
    DiskFileUpload.baseDirectory = null;
    // should delete file on exit (in normal exit)
    DiskAttribute.deleteOnExitTemporaryFile = true;
    // system temp directory
    DiskAttribute.baseDirectory = null;
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new HttpUploadClientInitializer(sslCtx));
        // Simple Get form: no factory used (not usable)
        List<Entry<String, String>> headers = formget(b, host, port, get, uriSimple);
        if (headers == null) {
            factory.cleanAllHttpData();
            return;
        }
        // Simple Post form: factory used for big attributes
        List<InterfaceHttpData> bodylist = formpost(b, host, port, uriSimple, file, factory, headers);
        if (bodylist == null) {
            factory.cleanAllHttpData();
            return;
        }
        // Multipart Post form: factory used
        formpostmultipart(b, host, port, uriFile, factory, headers, bodylist);
    } finally {
        // Shut down executor threads to exit.
        group.shutdownGracefully();
        // Really clean all temporary files if they still exist
        factory.cleanAllHttpData();
    }
}
Also used : FileNotFoundException(java.io.FileNotFoundException) URI(java.net.URI) DefaultHttpDataFactory(io.netty.handler.codec.http.multipart.DefaultHttpDataFactory) HttpDataFactory(io.netty.handler.codec.http.multipart.HttpDataFactory) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Entry(java.util.Map.Entry) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) InterfaceHttpData(io.netty.handler.codec.http.multipart.InterfaceHttpData) DefaultHttpDataFactory(io.netty.handler.codec.http.multipart.DefaultHttpDataFactory) Bootstrap(io.netty.bootstrap.Bootstrap) File(java.io.File) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SslContext(io.netty.handler.ssl.SslContext)

Example 3 with DefaultHttpDataFactory

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.multipart.DefaultHttpDataFactory in project riposte by Nike-Inc.

the class RequestInfoImpl method getMultipartParts.

/**
 * {@inheritDoc}
 */
@Override
@Nullable
public synchronized List<InterfaceHttpData> getMultipartParts() {
    if (!isMultipartRequest() || !isCompleteRequestWithAllChunks())
        return null;
    if (multipartData == null) {
        byte[] contentBytes = getRawContentBytes();
        HttpVersion httpVersion = getProtocolVersion();
        HttpMethod httpMethod = getMethod();
        // default them to something if null somehow slips through.
        if (httpVersion == null) {
            httpVersion = HttpVersion.HTTP_1_0;
        }
        if (httpMethod == null) {
            httpMethod = HttpMethod.POST;
        }
        HttpRequest fullHttpRequestForMultipartDecoder = (contentBytes == null) ? new DefaultFullHttpRequest(httpVersion, httpMethod, getUri()) : new DefaultFullHttpRequest(httpVersion, httpMethod, getUri(), Unpooled.wrappedBuffer(contentBytes));
        fullHttpRequestForMultipartDecoder.headers().add(getHeaders());
        multipartData = new HttpPostMultipartRequestDecoder(new DefaultHttpDataFactory(false), fullHttpRequestForMultipartDecoder, getContentCharset());
    }
    return multipartData.getBodyHttpDatas();
}
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) HttpPostMultipartRequestDecoder(io.netty.handler.codec.http.multipart.HttpPostMultipartRequestDecoder) DefaultHttpDataFactory(io.netty.handler.codec.http.multipart.DefaultHttpDataFactory) HttpVersion(io.netty.handler.codec.http.HttpVersion) HttpMethod(io.netty.handler.codec.http.HttpMethod) Nullable(org.jetbrains.annotations.Nullable)

Example 4 with DefaultHttpDataFactory

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.multipart.DefaultHttpDataFactory in project ambry by linkedin.

the class FrontendIntegrationTest method createEncoder.

/**
 * Creates a {@link HttpPostRequestEncoder} that encodes the given {@code request} and {@code blobContent}.
 * @param request the {@link HttpRequest} containing headers and other metadata about the request.
 * @param blobContent the {@link ByteBuffer} that represents the content of the blob.
 * @param usermetadata the {@link ByteBuffer} that represents user metadata
 * @return a {@link HttpPostRequestEncoder} that can encode the {@code request} and {@code blobContent}.
 * @throws HttpPostRequestEncoder.ErrorDataEncoderException
 * @throws IOException
 */
private HttpPostRequestEncoder createEncoder(HttpRequest request, ByteBuffer blobContent, ByteBuffer usermetadata) throws HttpPostRequestEncoder.ErrorDataEncoderException, IOException {
    HttpDataFactory httpDataFactory = new DefaultHttpDataFactory(false);
    HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(httpDataFactory, request, true);
    FileUpload fileUpload = new MemoryFileUpload(RestUtils.MultipartPost.BLOB_PART, RestUtils.MultipartPost.BLOB_PART, "application/octet-stream", "", Charset.forName("UTF-8"), blobContent.remaining());
    fileUpload.setContent(Unpooled.wrappedBuffer(blobContent));
    encoder.addBodyHttpData(fileUpload);
    fileUpload = new MemoryFileUpload(RestUtils.MultipartPost.USER_METADATA_PART, RestUtils.MultipartPost.USER_METADATA_PART, "application/octet-stream", "", Charset.forName("UTF-8"), usermetadata.remaining());
    fileUpload.setContent(Unpooled.wrappedBuffer(usermetadata));
    encoder.addBodyHttpData(fileUpload);
    return encoder;
}
Also used : HttpPostRequestEncoder(io.netty.handler.codec.http.multipart.HttpPostRequestEncoder) DefaultHttpDataFactory(io.netty.handler.codec.http.multipart.DefaultHttpDataFactory) MemoryFileUpload(io.netty.handler.codec.http.multipart.MemoryFileUpload) MemoryFileUpload(io.netty.handler.codec.http.multipart.MemoryFileUpload) FileUpload(io.netty.handler.codec.http.multipart.FileUpload) HttpDataFactory(io.netty.handler.codec.http.multipart.HttpDataFactory) DefaultHttpDataFactory(io.netty.handler.codec.http.multipart.DefaultHttpDataFactory)

Example 5 with DefaultHttpDataFactory

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.multipart.DefaultHttpDataFactory in project jocean-http by isdom.

the class HttpPostRequestEncoderTestCase method testGetBodyListAttributes.

@Test
public final void testGetBodyListAttributes() throws Exception {
    final HttpDataFactory factory = new DefaultHttpDataFactory(false);
    final HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/");
    // Use the PostBody encoder
    final HttpPostRequestEncoder postRequestEncoder = // true => multipart
    new HttpPostRequestEncoder(factory, request, true);
    final MemoryFileUpload f1 = new MemoryFileUpload("m1", "m1", "application/json", null, null, 100);
    final DiskFileUpload f2 = new DiskFileUpload("d1", "d1", "application/json", null, null, 100);
    final DiskFileUpload f3 = new DiskFileUpload("d2", "d2", "application/json", null, null, 100);
    postRequestEncoder.addBodyHttpData(f1);
    postRequestEncoder.addBodyHttpData(f2);
    postRequestEncoder.addBodyHttpData(f3);
    final List<InterfaceHttpData> attrs = postRequestEncoder.getBodyListAttributes();
    final InterfaceHttpData[] datas = new InterfaceHttpData[] { f1, f2, f3 };
    for (int idx = 0; idx < datas.length; idx++) {
        assertEquals(datas[idx], attrs.toArray(new InterfaceHttpData[0])[idx]);
    }
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) DiskFileUpload(io.netty.handler.codec.http.multipart.DiskFileUpload) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) InterfaceHttpData(io.netty.handler.codec.http.multipart.InterfaceHttpData) HttpPostRequestEncoder(io.netty.handler.codec.http.multipart.HttpPostRequestEncoder) DefaultHttpDataFactory(io.netty.handler.codec.http.multipart.DefaultHttpDataFactory) MemoryFileUpload(io.netty.handler.codec.http.multipart.MemoryFileUpload) DefaultHttpDataFactory(io.netty.handler.codec.http.multipart.DefaultHttpDataFactory) HttpDataFactory(io.netty.handler.codec.http.multipart.HttpDataFactory) Test(org.junit.Test)

Aggregations

DefaultHttpDataFactory (io.netty.handler.codec.http.multipart.DefaultHttpDataFactory)10 HttpDataFactory (io.netty.handler.codec.http.multipart.HttpDataFactory)8 HttpPostRequestEncoder (io.netty.handler.codec.http.multipart.HttpPostRequestEncoder)6 MemoryFileUpload (io.netty.handler.codec.http.multipart.MemoryFileUpload)5 FileUpload (io.netty.handler.codec.http.multipart.FileUpload)4 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)2 HttpRequest (io.netty.handler.codec.http.HttpRequest)2 InterfaceHttpData (io.netty.handler.codec.http.multipart.InterfaceHttpData)2 File (java.io.File)2 DefaultHttpRequest (com.github.dreamhead.moco.model.DefaultHttpRequest)1 Bootstrap (io.netty.bootstrap.Bootstrap)1 EventLoopGroup (io.netty.channel.EventLoopGroup)1 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)1 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)1 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)1 DefaultHttpRequest (io.netty.handler.codec.http.DefaultHttpRequest)1 HttpMethod (io.netty.handler.codec.http.HttpMethod)1 HttpVersion (io.netty.handler.codec.http.HttpVersion)1 DiskFileUpload (io.netty.handler.codec.http.multipart.DiskFileUpload)1 HttpPostMultipartRequestDecoder (io.netty.handler.codec.http.multipart.HttpPostMultipartRequestDecoder)1