io.netty.handler.codec.http.multipart.HttpDataFactory Java Examples

The following examples show how to use io.netty.handler.codec.http.multipart.HttpDataFactory. 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: NettyMultipartRequestTest.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@link HttpPostRequestEncoder} that encodes the given {@code request} and {@code parts}.
 * @param request the {@link HttpRequest} containing headers and other metadata about the request.
 * @param parts the {@link InMemoryFile}s that will form the parts of the request.
 * @return a {@link HttpPostRequestEncoder} that can encode the {@code request} and {@code parts}.
 * @throws HttpPostRequestEncoder.ErrorDataEncoderException
 * @throws IOException
 */
private HttpPostRequestEncoder createEncoder(HttpRequest request, InMemoryFile[] parts)
    throws HttpPostRequestEncoder.ErrorDataEncoderException, IOException {
  HttpDataFactory httpDataFactory = new DefaultHttpDataFactory(false);
  HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(httpDataFactory, request, true);
  if (parts != null) {
    for (InMemoryFile part : parts) {
      FileUpload fileUpload =
          new MemoryFileUpload(part.name, part.name, "application/octet-stream", "", Charset.forName("UTF-8"),
              part.content.remaining());
      fileUpload.setContent(Unpooled.wrappedBuffer(part.content));
      encoder.addBodyHttpData(fileUpload);
    }
  }
  return encoder;
}
 
Example #2
Source File: HttpPostRequestDecoder.java    From dorado with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param factory
 *            the factory used to create InterfaceHttpData
 * @param request
 *            the request to decode
 * @param charset
 *            the charset to use as default
 * @throws NullPointerException
 *             for request or charset or factory
 * @throws ErrorDataDecoderException
 *             if the default charset was wrong when decoding or other
 *             errors
 */
public HttpPostRequestDecoder(HttpDataFactory factory, HttpRequest request, Charset charset) {
    if (factory == null) {
        throw new NullPointerException("factory");
    }
    if (request == null) {
        throw new NullPointerException("request");
    }
    if (charset == null) {
        throw new NullPointerException("charset");
    }
    // Fill default values
    if (isMultipart(request)) {
        decoder = new HttpPostMultipartRequestDecoder(factory, request, charset);
    } else {
        decoder = new HttpPostStandardRequestDecoder(factory, request, charset);
    }
}
 
Example #3
Source File: HttpPostMultipartRequestDecoder.java    From dorado with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param factory the factory used to create InterfaceHttpData
 * @param request the request to decode
 * @param charset the charset to use as default
 * @throws NullPointerException      for request or charset or factory
 * @throws ErrorDataDecoderException if the default charset was wrong when
 *                                   decoding or other errors
 */
public HttpPostMultipartRequestDecoder(HttpDataFactory factory, HttpRequest request, Charset charset) {
	this.request = checkNotNull(request, "request");
	this.charset = checkNotNull(charset, "charset");
	this.factory = checkNotNull(factory, "factory");
	// Fill default values

	setMultipart(this.request.headers().get(HttpHeaderNames.CONTENT_TYPE));
	if (request instanceof HttpContent) {
		// Offer automatically if the given request is als type of HttpContent
		// See #1089
		offer((HttpContent) request);
	} else {
		undecodedChunk = buffer();
		parseBody();
	}
}
 
Example #4
Source File: NettyMessageProcessorTest.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * 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.
 * @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)
    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);
  return encoder;
}
 
Example #5
Source File: NettyMultipartRequest.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 * <p/>
 * Prepares the request for reading by decoding all the content added via {@link #addContent(HttpContent)}.
 * @throws RestServiceException if request channel is closed or if the request could not be decoded/prepared.
 */
@Override
public void prepare() throws RestServiceException {
  if (!isOpen()) {
    nettyMetrics.multipartRequestAlreadyClosedError.inc();
    throw new RestServiceException("Request is closed", RestServiceErrorCode.RequestChannelClosed);
  } else if (!readyForRead) {
    // make sure data is held in memory.
    HttpDataFactory httpDataFactory = new DefaultHttpDataFactory(false);
    HttpPostMultipartRequestDecoder postRequestDecoder =
        new HttpPostMultipartRequestDecoder(httpDataFactory, request);
    try {
      HttpContent httpContent = rawRequestContents.poll();
      while (httpContent != null) {
        try {
          // if the request is also an instance of HttpContent, the HttpPostMultipartRequestDecoder does the offer
          // automatically at the time of construction. We should not add it again.
          if (httpContent != request) {
            postRequestDecoder.offer(httpContent);
          }
        } finally {
          ReferenceCountUtil.release(httpContent);
        }
        httpContent = rawRequestContents.poll();
      }
      for (InterfaceHttpData part : postRequestDecoder.getBodyHttpDatas()) {
        processPart(part);
      }
      requestContents.add(LastHttpContent.EMPTY_LAST_CONTENT);
      readyForRead = true;
    } catch (HttpPostRequestDecoder.ErrorDataDecoderException e) {
      nettyMetrics.multipartRequestDecodeError.inc();
      throw new RestServiceException("There was an error decoding the request", e,
          RestServiceErrorCode.MalformedRequest);
    } finally {
      postRequestDecoder.destroy();
    }
  }
}
 
Example #6
Source File: HttpClientFormEncoder.java    From reactor-netty 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
 */
HttpClientFormEncoder(HttpDataFactory factory,
		HttpRequest request,
		boolean multipart,
		Charset charset,
		EncoderMode encoderMode) throws ErrorDataEncoderException {
	super(factory, request, multipart, charset, encoderMode);
	this.newCharset = charset;
	this.request = request;
	this.cleanOnTerminate = true;
	this.progressFlux = Processors.more().multicastNoBackpressure();
	this.newMode = encoderMode;
	this.newFactory = factory;
	this.newMultipart = multipart;
}
 
Example #7
Source File: HttpUploadClient.java    From tools-journey with Apache License 2.0 4 votes vote down vote up
/**
 * Standard post without multipart but already support on Factory (memory management)
 *
 * @return the list of HttpData object (attribute and file) to be reused on next post
 */
private static List<InterfaceHttpData> formpost(
        Bootstrap bootstrap,
        String host, int port, URI uriSimple, File file, HttpDataFactory factory,
        List<Entry<String, String>> headers) throws Exception {
    // XXX /formpost
    // Start the connection attempt.
    ChannelFuture future = bootstrap.connect(SocketUtils.socketAddress(host, port));
    // Wait until the connection attempt succeeds or fails.
    Channel channel = future.sync().channel();

    // Prepare the HTTP request.
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uriSimple.toASCIIString());

    // Use the PostBody encoder
    HttpPostRequestEncoder bodyRequestEncoder =
            new HttpPostRequestEncoder(factory, request, false);  // false => not multipart

    // it is legal to add directly header or cookie into the request until finalize
    for (Entry<String, String> entry : headers) {
        request.headers().set(entry.getKey(), entry.getValue());
    }

    // add Form attribute
    bodyRequestEncoder.addBodyAttribute("getform", "POST");
    bodyRequestEncoder.addBodyAttribute("info", "first value");
    bodyRequestEncoder.addBodyAttribute("secondinfo", "secondvalue ���&");
    bodyRequestEncoder.addBodyAttribute("thirdinfo", textArea);
    bodyRequestEncoder.addBodyAttribute("fourthinfo", textAreaLong);
    bodyRequestEncoder.addBodyFileUpload("myfile", file, "application/x-zip-compressed", false);

    // finalize request
    request = bodyRequestEncoder.finalizeRequest();

    // Create the bodylist to be reused on the last version with Multipart support
    List<InterfaceHttpData> bodylist = bodyRequestEncoder.getBodyListAttributes();

    // send request
    channel.write(request);

    // test if request was chunked and if so, finish the write
    if (bodyRequestEncoder.isChunked()) { // could do either request.isChunked()
        // either do it through ChunkedWriteHandler
        channel.write(bodyRequestEncoder);
    }
    channel.flush();

    // Do not clear here since we will reuse the InterfaceHttpData on the next request
    // for the example (limit action on client side). Take this as a broadcast of the same
    // request on both Post actions.
    //
    // On standard program, it is clearly recommended to clean all files after each request
    // bodyRequestEncoder.cleanFiles();

    // Wait for the server to close the connection.
    channel.closeFuture().sync();
    return bodylist;
}
 
Example #8
Source File: HttpUploadClient.java    From netty4.0.27Learn with Apache License 2.0 4 votes vote down vote up
/**
 * Multipart example
 */
private static void formpostmultipart(
        Bootstrap bootstrap, String host, int port, URI uriFile, HttpDataFactory factory,
        List<Entry<String, String>> headers, List<InterfaceHttpData> bodylist) throws Exception {
    // XXX /formpostmultipart
    // Start the connection attempt.
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
    // Wait until the connection attempt succeeds or fails.
    Channel channel = future.sync().channel();

    // Prepare the HTTP request.
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uriFile.toASCIIString());

    // Use the PostBody encoder
    HttpPostRequestEncoder bodyRequestEncoder =
            new HttpPostRequestEncoder(factory, request, true); // true => multipart

    // it is legal to add directly header or cookie into the request until finalize
    for (Entry<String, String> entry : headers) {
        request.headers().set(entry.getKey(), entry.getValue());
    }

    // add Form attribute from previous request in formpost()
    bodyRequestEncoder.setBodyHttpDatas(bodylist);

    // finalize request
    bodyRequestEncoder.finalizeRequest();

    // send request
    channel.write(request);

    // test if request was chunked and if so, finish the write
    if (bodyRequestEncoder.isChunked()) {
        channel.write(bodyRequestEncoder);
    }
    channel.flush();

    // Now no more use of file representation (and list of HttpData)
    bodyRequestEncoder.cleanFiles();

    // Wait for the server to close the connection.
    channel.closeFuture().sync();
}
 
Example #9
Source File: HttpUploadClient.java    From netty4.0.27Learn with Apache License 2.0 4 votes vote down vote up
/**
 * Standard post without multipart but already support on Factory (memory management)
 *
 * @return the list of HttpData object (attribute and file) to be reused on next post
 */
private static List<InterfaceHttpData> formpost(
        Bootstrap bootstrap,
        String host, int port, URI uriSimple, File file, HttpDataFactory factory,
        List<Entry<String, String>> headers) throws Exception {
    // XXX /formpost
    // Start the connection attempt.
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
    // Wait until the connection attempt succeeds or fails.
    Channel channel = future.sync().channel();

    // Prepare the HTTP request.
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uriSimple.toASCIIString());

    // Use the PostBody encoder
    HttpPostRequestEncoder bodyRequestEncoder =
            new HttpPostRequestEncoder(factory, request, false);  // false => not multipart

    // it is legal to add directly header or cookie into the request until finalize
    for (Entry<String, String> entry : headers) {
        request.headers().set(entry.getKey(), entry.getValue());
    }

    // add Form attribute
    bodyRequestEncoder.addBodyAttribute("getform", "POST");
    bodyRequestEncoder.addBodyAttribute("info", "first value");
    bodyRequestEncoder.addBodyAttribute("secondinfo", "secondvalue ���&");
    bodyRequestEncoder.addBodyAttribute("thirdinfo", textArea);
    bodyRequestEncoder.addBodyAttribute("fourthinfo", textAreaLong);
    bodyRequestEncoder.addBodyFileUpload("myfile", file, "application/x-zip-compressed", false);

    // finalize request
    request = bodyRequestEncoder.finalizeRequest();

    // Create the bodylist to be reused on the last version with Multipart support
    List<InterfaceHttpData> bodylist = bodyRequestEncoder.getBodyListAttributes();

    // send request
    channel.write(request);

    // test if request was chunked and if so, finish the write
    if (bodyRequestEncoder.isChunked()) { // could do either request.isChunked()
        // either do it through ChunkedWriteHandler
        channel.write(bodyRequestEncoder);
    }
    channel.flush();

    // Do not clear here since we will reuse the InterfaceHttpData on the next request
    // for the example (limit action on client side). Take this as a broadcast of the same
    // request on both Post actions.
    //
    // On standard program, it is clearly recommended to clean all files after each request
    // bodyRequestEncoder.cleanFiles();

    // Wait for the server to close the connection.
    channel.closeFuture().sync();
    return bodylist;
}
 
Example #10
Source File: HttpUploadClient.java    From netty4.0.27Learn with Apache License 2.0 4 votes vote down vote up
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 = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } 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
    HttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE); // Disk if MINSIZE exceed

    DiskFileUpload.deleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit)
    DiskFileUpload.baseDirectory = null; // system temp directory
    DiskAttribute.deleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit)
    DiskAttribute.baseDirectory = null; // system temp directory

    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new HttpUploadClientIntializer(sslCtx));

        // Simple Get form: no factory used (not usable)
        List<Entry<String, String>> headers = formget(b, host, port, get, uriSimple);
        if (headers == null) {
            factory.cleanAllHttpDatas();
            return;
        }

        // Simple Post form: factory used for big attributes
        List<InterfaceHttpData> bodylist = formpost(b, host, port, uriSimple, file, factory, headers);
        if (bodylist == null) {
            factory.cleanAllHttpDatas();
            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.cleanAllHttpDatas();
    }
}
 
Example #11
Source File: HttpClientOperations.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("FutureReturnValueIgnored")
void _subscribe(CoreSubscriber<? super Void> s) {
	HttpDataFactory df = DEFAULT_FACTORY;

	try {
		HttpClientFormEncoder encoder = new HttpClientFormEncoder(df,
				parent.nettyRequest,
				false,
				HttpConstants.DEFAULT_CHARSET,
				HttpPostRequestEncoder.EncoderMode.RFC1738);

		formCallback.accept(parent, encoder);

		encoder = encoder.applyChanges(parent.nettyRequest);
		df = encoder.newFactory;

		if (!encoder.isMultipart()) {
			parent.requestHeaders.remove(HttpHeaderNames.TRANSFER_ENCODING);
		}

		// Returned value is deliberately ignored
		parent.addHandlerFirst(NettyPipeline.ChunkedWriter, new ChunkedWriteHandler());

		boolean chunked = HttpUtil.isTransferEncodingChunked(parent.nettyRequest);

		HttpRequest r = encoder.finalizeRequest();

		if (!chunked) {
			HttpUtil.setTransferEncodingChunked(r, false);
			HttpUtil.setContentLength(r, encoder.length());
		}

		ChannelFuture f = parent.channel()
		                        .writeAndFlush(r);

		Flux<Long> tail = encoder.progressFlux.onBackpressureLatest();

		if (encoder.cleanOnTerminate) {
			tail = tail.doOnCancel(encoder)
			           .doAfterTerminate(encoder);
		}

		if (encoder.isChunked()) {
			if (progressCallback != null) {
				progressCallback.accept(tail);
			}
			//"FutureReturnValueIgnored" this is deliberate
			parent.channel()
			      .writeAndFlush(encoder);
		}
		else {
			if (progressCallback != null) {
				progressCallback.accept(FutureMono.from(f)
				                                  .cast(Long.class)
				                                  .switchIfEmpty(Mono.just(encoder.length()))
				                                  .flux());
			}
		}
		s.onComplete();


	}
	catch (Throwable e) {
		Exceptions.throwIfJvmFatal(e);
		df.cleanRequestHttpData(parent.nettyRequest);
		s.onError(Exceptions.unwrap(e));
	}
}
 
Example #12
Source File: HttpUploadClient.java    From tools-journey with Apache License 2.0 4 votes vote down vote up
/**
 * Multipart example
 */
private static void formpostmultipart(
        Bootstrap bootstrap, String host, int port, URI uriFile, HttpDataFactory factory,
        Iterable<Entry<String, String>> headers, List<InterfaceHttpData> bodylist) throws Exception {
    // XXX /formpostmultipart
    // Start the connection attempt.
    ChannelFuture future = bootstrap.connect(SocketUtils.socketAddress(host, port));
    // Wait until the connection attempt succeeds or fails.
    Channel channel = future.sync().channel();

    // Prepare the HTTP request.
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uriFile.toASCIIString());

    // Use the PostBody encoder
    HttpPostRequestEncoder bodyRequestEncoder =
            new HttpPostRequestEncoder(factory, request, true); // true => multipart

    // it is legal to add directly header or cookie into the request until finalize
    for (Entry<String, String> entry : headers) {
        request.headers().set(entry.getKey(), entry.getValue());
    }

    // add Form attribute from previous request in formpost()
    bodyRequestEncoder.setBodyHttpDatas(bodylist);

    // finalize request
    bodyRequestEncoder.finalizeRequest();

    // send request
    channel.write(request);

    // test if request was chunked and if so, finish the write
    if (bodyRequestEncoder.isChunked()) {
        channel.write(bodyRequestEncoder);
    }
    channel.flush();

    // Now no more use of file representation (and list of HttpData)
    bodyRequestEncoder.cleanFiles();

    // Wait for the server to close the connection.
    channel.closeFuture().sync();
}
 
Example #13
Source File: HttpUploadClient.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
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
    HttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE); // Disk if MINSIZE exceed

    DiskFileUpload.deleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit)
    DiskFileUpload.baseDirectory = null; // system temp directory
    DiskAttribute.deleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit)
    DiskAttribute.baseDirectory = null; // system temp directory

    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();
    }
}
 
Example #14
Source File: HttpUploadClient.java    From tools-journey with Apache License 2.0 4 votes vote down vote up
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
    HttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE); // Disk if MINSIZE exceed

    DiskFileUpload.deleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit)
    DiskFileUpload.baseDirectory = null; // system temp directory
    DiskAttribute.deleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit)
    DiskAttribute.baseDirectory = null; // system temp directory

    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();
    }
}
 
Example #15
Source File: ServletContext.java    From spring-boot-protocol with Apache License 2.0 4 votes vote down vote up
@Override
protected Map<Charset, HttpDataFactory> initialValue() throws Exception {
    return new LinkedHashMap<>(5);
}
 
Example #16
Source File: HttpUploadClient.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
/**
 * Multipart example
 */
private static void formpostmultipart(
        Bootstrap bootstrap, String host, int port, URI uriFile, HttpDataFactory factory,
        Iterable<Entry<String, String>> headers, List<InterfaceHttpData> bodylist) throws Exception {
    // XXX /formpostmultipart
    // Start the connection attempt.
    ChannelFuture future = bootstrap.connect(SocketUtils.socketAddress(host, port));
    // Wait until the connection attempt succeeds or fails.
    Channel channel = future.sync().channel();

    // Prepare the HTTP request.
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uriFile.toASCIIString());

    // Use the PostBody encoder
    HttpPostRequestEncoder bodyRequestEncoder =
            new HttpPostRequestEncoder(factory, request, true); // true => multipart

    // it is legal to add directly header or cookie into the request until finalize
    for (Entry<String, String> entry : headers) {
        request.headers().set(entry.getKey(), entry.getValue());
    }

    // add Form attribute from previous request in formpost()
    bodyRequestEncoder.setBodyHttpDatas(bodylist);

    // finalize request
    bodyRequestEncoder.finalizeRequest();

    // send request
    channel.write(request);

    // test if request was chunked and if so, finish the write
    if (bodyRequestEncoder.isChunked()) {
        channel.write(bodyRequestEncoder);
    }
    channel.flush();

    // Now no more use of file representation (and list of HttpData)
    bodyRequestEncoder.cleanFiles();

    // Wait for the server to close the connection.
    channel.closeFuture().sync();
}
 
Example #17
Source File: HttpUploadClient.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
/**
 * Standard post without multipart but already support on Factory (memory management)
 *
 * @return the list of HttpData object (attribute and file) to be reused on next post
 */
private static List<InterfaceHttpData> formpost(
        Bootstrap bootstrap,
        String host, int port, URI uriSimple, File file, HttpDataFactory factory,
        List<Entry<String, String>> headers) throws Exception {
    // XXX /formpost
    // Start the connection attempt.
    ChannelFuture future = bootstrap.connect(SocketUtils.socketAddress(host, port));
    // Wait until the connection attempt succeeds or fails.
    Channel channel = future.sync().channel();

    // Prepare the HTTP request.
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uriSimple.toASCIIString());

    // Use the PostBody encoder
    HttpPostRequestEncoder bodyRequestEncoder =
            new HttpPostRequestEncoder(factory, request, false);  // false => not multipart

    // it is legal to add directly header or cookie into the request until finalize
    for (Entry<String, String> entry : headers) {
        request.headers().set(entry.getKey(), entry.getValue());
    }

    // add Form attribute
    bodyRequestEncoder.addBodyAttribute("getform", "POST");
    bodyRequestEncoder.addBodyAttribute("info", "first value");
    bodyRequestEncoder.addBodyAttribute("secondinfo", "secondvalue ���&");
    bodyRequestEncoder.addBodyAttribute("thirdinfo", textArea);
    bodyRequestEncoder.addBodyAttribute("fourthinfo", textAreaLong);
    bodyRequestEncoder.addBodyFileUpload("myfile", file, "application/x-zip-compressed", false);

    // finalize request
    request = bodyRequestEncoder.finalizeRequest();

    // Create the bodylist to be reused on the last version with Multipart support
    List<InterfaceHttpData> bodylist = bodyRequestEncoder.getBodyListAttributes();

    // send request
    channel.write(request);

    // test if request was chunked and if so, finish the write
    if (bodyRequestEncoder.isChunked()) { // could do either request.isChunked()
        // either do it through ChunkedWriteHandler
        channel.write(bodyRequestEncoder);
    }
    channel.flush();

    // Do not clear here since we will reuse the InterfaceHttpData on the next request
    // for the example (limit action on client side). Take this as a broadcast of the same
    // request on both Post actions.
    //
    // On standard program, it is clearly recommended to clean all files after each request
    // bodyRequestEncoder.cleanFiles();

    // Wait for the server to close the connection.
    channel.closeFuture().sync();
    return bodylist;
}
 
Example #18
Source File: HttpPostMultipartRequestDecoder.java    From dorado with Apache License 2.0 2 votes vote down vote up
/**
 *
 * @param factory the factory used to create InterfaceHttpData
 * @param request the request to decode
 * @throws NullPointerException      for request or factory
 * @throws ErrorDataDecoderException if the default charset was wrong when
 *                                   decoding or other errors
 */
public HttpPostMultipartRequestDecoder(HttpDataFactory factory, HttpRequest request) {
	this(factory, request, HttpConstants.DEFAULT_CHARSET);
}
 
Example #19
Source File: HttpPostRequestDecoder.java    From dorado with Apache License 2.0 2 votes vote down vote up
/**
 *
 * @param factory
 *            the factory used to create InterfaceHttpData
 * @param request
 *            the request to decode
 * @throws NullPointerException
 *             for request or factory
 * @throws ErrorDataDecoderException
 *             if the default charset was wrong when decoding or other
 *             errors
 */
public HttpPostRequestDecoder(HttpDataFactory factory, HttpRequest request) {
    this(factory, request, HttpConstants.DEFAULT_CHARSET);
}