List of usage examples for io.netty.handler.codec.http.multipart DefaultHttpDataFactory DefaultHttpDataFactory
public DefaultHttpDataFactory(long minSize)
From source file:HttpUploadClient.java
License:Apache License
public void run() throws Exception { String postSimple, postFile, get; if (baseUri.endsWith("/")) { postSimple = baseUri + "formpost"; postFile = baseUri + "formpostmultipart"; get = baseUri + "formget"; } else {//from w ww. jav a 2 s. co m postSimple = baseUri + "/formpost"; postFile = baseUri + "/formpostmultipart"; get = baseUri + "/formget"; } URI uriSimple; try { uriSimple = new URI(postSimple); } catch (URISyntaxException e) { logger.log(Level.WARNING, "Invalid URI syntax", e); return; } String scheme = uriSimple.getScheme() == null ? "http" : uriSimple.getScheme(); String host = uriSimple.getHost() == null ? "localhost" : 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)) { logger.log(Level.WARNING, "Only HTTP(S) is supported."); return; } boolean ssl = "https".equalsIgnoreCase(scheme); URI uriFile; try { uriFile = new URI(postFile); } catch (URISyntaxException e) { logger.log(Level.WARNING, "Error: ", e); return; } File file = new File(filePath); if (!file.canRead()) { logger.log(Level.WARNING, "A correct path is needed"); return; } // 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(ssl)); // 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(); } }
From source file:ccwihr.client.t1.HttpUploadClient.java
License:Apache License
/** * /*from w ww. j av a 2s.com*/ */ @Override public void run() { System.out.println("Task Running..."); /** * ?? */ Connection conn; try { conn = cpds.getConnection(); SyncEntity se = new SyncEntity("", ""); /** * */ se1.getMore(conn, ""); Statement state = conn.createStatement(); ResultSet rs = state.executeQuery("select * from Departs"); while (rs.next()) { } /** * ? */ // rs.isFirst(); // rs.first(); System.out.println("got data."); // rs.close(); // state.close(); // //?, // conn.close(); /** * ????get? */ // Simple Get form: no factory used (not usable) List<Entry<String, String>> headers = null; try { // headers = formget(b, host, port, GET_URL, uriSimple); HttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE); // Disk if MINSIZE exceed List<InterfaceHttpData> bodylist = formpost(b, host, port, uriSimple, se1, factory, headers); if (bodylist == null) { factory.cleanAllHttpData(); return; } // headers = formpost(b, host, port, GET_URL, uriSimple); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } if (headers == null) { factory.cleanAllHttpData(); return; } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }
From source file:cn.wcl.test.netty.HttpUploadClient.java
License:Apache License
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 {//from www . j a va 2 s . co m 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 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.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(); } }
From source file:com.bay1ts.bay.core.Request.java
License:Apache License
/** * ?Content-Type:application/x-www-form-urlencoded post body ?(htmlform) * * @param name ??form post inputname//from w w w .j av a 2 s . c om * @return value */ public String postBody(String name) { HttpPostRequestDecoder httpPostRequestDecoder = new HttpPostRequestDecoder( new DefaultHttpDataFactory(false), this.fullHttpRequest); InterfaceHttpData data = httpPostRequestDecoder.getBodyHttpData(name); if (data != null && data.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) { Attribute attribute = (Attribute) data; String value = null; try { value = attribute.getValue(); } catch (IOException e) { e.printStackTrace(); } finally { data.release(); } return value; } return null; }
From source file:com.bay1ts.bay.core.Request.java
License:Apache License
public Set<String> postBodyNames() { Set<String> set = new HashSet<>(); HttpPostRequestDecoder httpPostRequestDecoder = new HttpPostRequestDecoder( new DefaultHttpDataFactory(false), this.fullHttpRequest); for (InterfaceHttpData data : httpPostRequestDecoder.getBodyHttpDatas()) { data = httpPostRequestDecoder.next(); set.add(data.getName());/* w w w . ja v a 2 s . com*/ data.release(); // if (data!=null){ // try { // Attribute attribute=(Attribute) data; // set.add(attribute.getName()); // }finally { // data.release(); // } // } } return set; }
From source file:com.bay1ts.bay.core.Request.java
License:Apache License
public Set<String> postBodyValues() { HttpPostRequestDecoder httpPostRequestDecoder = new HttpPostRequestDecoder( new DefaultHttpDataFactory(false), this.fullHttpRequest); Set<String> set = new HashSet<>(); for (; httpPostRequestDecoder.hasNext();) { InterfaceHttpData data = httpPostRequestDecoder.next(); if (data != null) { try { Attribute attribute = (Attribute) data; set.add(attribute.getValue()); } catch (IOException e) { e.printStackTrace();/*from w w w . j a v a 2 s .c om*/ } finally { data.release(); } } } return set; }
From source file:com.github.ambry.frontend.FrontendIntegrationTest.java
License:Open Source License
/** * 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/* w w w . j av a 2 s . c o m*/ */ 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; }
From source file:com.github.ambry.rest.NettyMessageProcessorTest.java
License:Open Source License
/** * 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/*from w w w .j a v a 2 s. co m*/ */ 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; }
From source file:com.github.ambry.rest.NettyMultipartRequest.java
License:Open Source License
/** * {@inheritDoc}//from ww w. j a va 2s . c om * <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); } allArgsReadOnly = Collections.unmodifiableMap(allArgs); 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(); } } }
From source file:com.github.ambry.rest.NettyMultipartRequestTest.java
License:Open Source License
/** * 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//from ww w.ja v a2 s . com */ 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; }