List of usage examples for io.netty.handler.codec.http HttpMethod POST
HttpMethod POST
To view the source code for io.netty.handler.codec.http HttpMethod POST.
Click Source Link
From source file:com.linkedin.proxy.netty.MysqlQueryDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, FullHttpRequest msg, List<Object> out) throws Exception { MysqlQuery result = new MysqlQuery(); try {//from w w w . j a v a 2 s . co m HttpMethod met = msg.getMethod(); String uri = msg.getUri(); int s = 0; int e = uri.length(); if (uri.charAt(0) == '/') s = 1; if (uri.charAt(e - 1) == '/') e--; String parts[] = uri.substring(s, e).split("/"); result.setDbName(parts[0]); result.setTableName(parts[1]); result.setKeyColName(parts[2]); result.setValueColName(parts[3]); if (met.equals(HttpMethod.PUT)) { /* * If HttpRequest method is PUT, I interpret it as a WRITE query. * MysqlQuery instance's value is set as the value in the HttpRequest. */ result.setKey(parts[4]); byte[] tempData = new byte[msg.content().readableBytes()]; msg.content().readBytes(tempData); result.setValue(tempData); result.setType(QueryType.WRITE); } else if (met.equals(HttpMethod.GET)) { /* * If HttpRequest method is GET, I interpret it as a READ query. * Once the query is processed, the result value (if any) is written to MysqlQuery.value. */ result.setKey(parts[4]); result.setType(QueryType.READ); } else if (met.equals(HttpMethod.DELETE)) { /* * If HttpRequest method is DELETE, I interpret it as a DELETE query. */ result.setKey(parts[4]); result.setType(QueryType.DELETE); } else if (met.equals(HttpMethod.POST)) { /* * If HttpRequest method is POST, I interpret it as a CREATE TABLE query. * I store size of the value column in MysqlQuery.Value. * I store byte array of the string representation. */ result.setValue(parts[4].getBytes()); result.setType(QueryType.CREATE); } else { result.setType(QueryType.INVALID); _LOG.error("Unhandled HttpMethod: " + met); _LOG.error("Type=" + QueryType.INVALID); } } catch (Exception e) { _LOG.error("Exception occured during HttpRequest processing", e); result.setType(QueryType.INVALID); _LOG.error("Type=" + QueryType.INVALID); } out.add(result); }
From source file:com.linkedin.r2.transport.http.client.TestNettyRequestAdapter.java
License:Apache License
@Test public void testRestToNettyRequest() throws Exception { RestRequestBuilder restRequestBuilder = new RestRequestBuilder(new URI(ANY_URI)); restRequestBuilder.setMethod("POST"); restRequestBuilder.setEntity(ByteString.copyString(ANY_ENTITY, Charset.defaultCharset())); restRequestBuilder.setHeader("Content-Length", Integer.toString(restRequestBuilder.getEntity().length())); restRequestBuilder.setHeader("Content-Type", "application/json"); restRequestBuilder.setCookies(Collections.singletonList(ANY_COOKIE)); RestRequest restRequest = restRequestBuilder.build(); HttpRequest nettyRequest = NettyRequestAdapter.toNettyRequest(restRequest); Assert.assertEquals(nettyRequest.uri(), "/foo/bar?q=baz"); Assert.assertEquals(nettyRequest.method(), HttpMethod.POST); Assert.assertEquals(nettyRequest.protocolVersion(), HttpVersion.HTTP_1_1); Assert.assertEquals(nettyRequest.headers().get("Content-Length"), Integer.toString(restRequestBuilder.getEntity().length())); Assert.assertEquals(nettyRequest.headers().get("Content-Type"), "application/json"); Assert.assertEquals(nettyRequest.headers().get("Cookie"), ANY_COOKIE); }
From source file:com.linkedin.r2.transport.http.client.TestNettyRequestAdapter.java
License:Apache License
@Test public void testStreamToNettyRequest() throws Exception { StreamRequestBuilder streamRequestBuilder = new StreamRequestBuilder(new URI(ANY_URI)); streamRequestBuilder.setMethod("POST"); streamRequestBuilder.setHeader("Content-Length", Integer.toString(ANY_ENTITY.length())); streamRequestBuilder.setHeader("Content-Type", "application/json"); streamRequestBuilder.setCookies(Collections.singletonList("anyCookie")); StreamRequest streamRequest = streamRequestBuilder .build(EntityStreams.newEntityStream(new ByteStringWriter(ByteString.copy(ANY_ENTITY.getBytes())))); HttpRequest nettyRequest = NettyRequestAdapter.toNettyRequest(streamRequest); Assert.assertEquals(nettyRequest.uri(), "/foo/bar?q=baz"); Assert.assertEquals(nettyRequest.method(), HttpMethod.POST); Assert.assertEquals(nettyRequest.protocolVersion(), HttpVersion.HTTP_1_1); Assert.assertNull(nettyRequest.headers().get("Content-Length")); Assert.assertEquals(nettyRequest.headers().get("Content-Type"), "application/json"); Assert.assertEquals(nettyRequest.headers().get("Cookie"), ANY_COOKIE); }
From source file:com.litgh.RouterTest.java
License:Open Source License
public void testRouterAPI() { Router router = new Router(); final Map<String, Boolean> test = new HashMap<String, Boolean>(); router.GET("/GET", new Handler() { public void handle(HttpRequest req, FullHttpResponse resp, List<Param> params) { test.put("GET", true); }//from w w w . j a v a2s . co m }); router.POST("/POST", new Handler() { public void handle(HttpRequest req, FullHttpResponse resp, List<Param> params) { test.put("POST", true); } }); router.PUT("/PUT", new Handler() { public void handle(HttpRequest req, FullHttpResponse resp, List<Param> params) { test.put("PUT", true); } }); router.DELETE("/DELETE", new Handler() { public void handle(HttpRequest req, FullHttpResponse resp, List<Param> params) { test.put("DELETE", true); } }); router.HEAD("/HEAD", new Handler() { public void handle(HttpRequest req, FullHttpResponse resp, List<Param> params) { test.put("HEAD", true); } }); router.PATCH("/PATCH", new Handler() { public void handle(HttpRequest req, FullHttpResponse resp, List<Param> params) { test.put("PATCH", true); } }); HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/GET"); FullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); router.serverHttp(req, resp); req.setMethod(HttpMethod.POST); req.setUri("/POST"); router.serverHttp(req, resp); req.setMethod(HttpMethod.PUT); req.setUri("/PUT"); router.serverHttp(req, resp); req.setMethod(HttpMethod.DELETE); req.setUri("/DELETE"); router.serverHttp(req, resp); req.setMethod(HttpMethod.HEAD); req.setUri("/HEAD"); router.serverHttp(req, resp); req.setMethod(HttpMethod.PATCH); req.setUri("/PATCH"); router.serverHttp(req, resp); assertEquals("routing GET failed", Boolean.TRUE, test.get("GET")); assertEquals("routing POST failed", Boolean.TRUE, test.get("POST")); assertEquals("routing PUT failed", Boolean.TRUE, test.get("PUT")); assertEquals("routing DELETE failed", Boolean.TRUE, test.get("DELETE")); assertEquals("routing HEAD failed", Boolean.TRUE, test.get("HEAD")); assertEquals("routing PATCH failed", Boolean.TRUE, test.get("PATCH")); }
From source file:com.lunex.inputprocessor.testdemo.HttpSnoopClient.java
License:Apache License
public static void main(String[] args) throws Exception { URI uri = new URI(URL); String scheme = uri.getScheme() == null ? "http" : uri.getScheme(); String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost(); int port = uri.getPort(); if (port == -1) { if ("http".equalsIgnoreCase(scheme)) { port = 80;/*w ww. ja v a 2 s . co m*/ } else if ("https".equalsIgnoreCase(scheme)) { port = 443; } } if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) { System.err.println("Only HTTP(S) is supported."); return; } // Configure SSL context if necessary. final boolean ssl = "https".equalsIgnoreCase(scheme); final SslContext sslCtx; if (ssl) { sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE); } else { sslCtx = null; } // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new HttpSnoopClientInitializer(sslCtx)); // Make the connection attempt. Channel ch = b.connect(host, port).sync().channel(); // Prepare the HTTP request. HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uri.getRawPath()); request.headers().set(HttpHeaders.Names.HOST, host); request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); // Set some example cookies. request.headers().set(HttpHeaders.Names.COOKIE, ClientCookieEncoder .encode(new DefaultCookie("my-cookie", "foo"), new DefaultCookie("another-cookie", "bar"))); String json = "{\"foo\":\"bar\"}"; request.headers().set("json", json); // Send the HTTP request. ch.writeAndFlush(request); // Wait for the server to close the connection. ch.closeFuture().sync(); } finally { // Shut down executor threads to exit. group.shutdownGracefully(); } }
From source file:com.mesosphere.mesos.rx.java.test.simulation.MesosServerSimulation.java
License:Apache License
/** * Create a {@code MesosServerSimulation} that will use {@code events} as the event stream to return to a * a client when {@code isSubscribePredicate} evaluates to {@code true} * <p>/*from ww w . j ava2 s. c om*/ * The simulation server must be started using {@link #start()} before requests can be serviced by the server. * * @param events The event stream to be returned by the server upon {@code isSubscribePredicate} * evaluating to {@code true} For each {@link Event} sent to {@code events}, the event * will be sent by the server. * @param sendCodec The {@link MessageCodec} to use to encode {@link Event}s sent by the server * @param receiveCodec The {@link MessageCodec} to use to decode {@link Call}s received by the server * @param isSubscribePredicate The predicate used to determine if a {@link Call} is a "Subscribe" call */ public MesosServerSimulation(@NotNull final Observable<Event> events, @NotNull final MessageCodec<Event> sendCodec, @NotNull final MessageCodec<Call> receiveCodec, @NotNull final Predicate<Call> isSubscribePredicate) { this.callsReceived = Collections.synchronizedList(new ArrayList<>()); this.started = new AtomicBoolean(false); this.eventsCompletedLatch = new CountDownLatch(1); this.subscribedLatch = new CountDownLatch(1); this.sem = new Semaphore(0); this.server = RxNetty.createHttpServer(0, (request, response) -> { response.getHeaders().setHeader("Accept", receiveCodec.mediaType()); if (!"/api/v1/scheduler".equals(request.getUri())) { response.setStatus(HttpResponseStatus.NOT_FOUND); response.getHeaders().setHeader("Content-Length", "0"); return response.close(); } if (!HttpMethod.POST.equals(request.getHttpMethod()) || !receiveCodec.mediaType().equals(request.getHeaders().getHeader("Content-Type")) || request.getHeaders().getContentLength() <= 0) { response.setStatus(HttpResponseStatus.BAD_REQUEST); response.getHeaders().setHeader("Content-Length", "0"); return response.close(); } return request.getContent().flatMap(buf -> { final ByteBufInputStream in = new ByteBufInputStream(buf); final Call call = receiveCodec.decode(in); if (callsReceived.add(call)) { sem.release(); } LOGGER.debug(RECEIVE_MARKER, "Call: {}", receiveCodec.show(call)); if (isSubscribePredicate.test(call)) { if (subscribedLatch.getCount() == 0) { final String message = "Only one event stream can be open per server"; response.setStatus(HttpResponseStatus.CONFLICT); response.getHeaders().set("Content-Type", "test/plain;charset=utf-8"); response.writeString(message); return response.close(); } LOGGER.debug("Responding with event stream from source: {}", events); response.getHeaders().setTransferEncodingChunked(); response.getHeaders().set("Content-Type", sendCodec.mediaType()); response.getHeaders().add("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate"); response.getHeaders().add("Pragma", "no-cache"); final Subject<Void, Void> subject = PublishSubject.create(); final MultipleAssignmentSubscription subscription = new MultipleAssignmentSubscription(); final Subscription actionSubscription = events .doOnSubscribe(() -> LOGGER.debug("Event stream subscription active")) .doOnNext(e -> LOGGER.debug(SEND_MARKER, "Event: {}", sendCodec.show(e))) .doOnError((t) -> LOGGER.error("Error while creating response", t)) .doOnCompleted(() -> { eventsCompletedLatch.countDown(); LOGGER.debug("Sending events complete"); if (!response.isCloseIssued()) { response.close(true); } }).map(sendCodec::encode).map(RecordIOUtils::createChunk).subscribe(bytes -> { if (!response.getChannel().isOpen()) { subscription.unsubscribe(); return; } try { LOGGER.trace(SEND_MARKER, "bytes: {}", Arrays.toString(bytes)); response.writeBytesAndFlush(bytes); } catch (Exception e) { subject.onError(e); } }); subscription.set(actionSubscription); subscribedLatch.countDown(); return subject; } else { response.setStatus(HttpResponseStatus.ACCEPTED); return response.close(); } }); }); }
From source file:com.netty.file.HttpUploadClient.java
License:Apache License
/** * 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 */// w w w . j a v a 2s . co m 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.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; }
From source file:com.netty.fileTest.http.upload.HttpUploadClient.java
License:Apache License
public static void main(String[] args) throws Exception { String postFile;//from w w w. j a v a 2 s .c om // postFile = BASE_URL + "formpost"; postFile = BASE_URL + "formpostmultipart"; URI uriFile = new URI(postFile); File file = new File(FILE); if (!file.canRead()) { throw new FileNotFoundException(FILE); } // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group).channel(NioSocketChannel.class).handler(new HttpUploadClientIntializer(null)); 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 { ChannelFuture future = bootstrap.connect(new InetSocketAddress("127.0.0.1", 8080)); // 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, false); // add Form attribute 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() channel.write(bodyRequestEncoder); } channel.flush(); channel.closeFuture().sync(); } finally { // Shut down executor threads to exit. group.shutdownGracefully(); // Really clean all temporary files if they still exist factory.cleanAllHttpDatas(); } }
From source file:com.nextcont.ecm.fileengine.http.nettyServer.HttpUploadServerHandler.java
License:Apache License
private void doHttpRequest(ChannelHandlerContext ctx, HttpRequest httpRequest) throws URISyntaxException { HttpRequest request = this.request = httpRequest; HttpMethod httpMethod = request.getMethod(); if (httpMethod.equals(HttpMethod.GET)) { doGet(ctx, request);//from ww w . java2 s .co m } else if (httpMethod.equals(HttpMethod.POST)) { doPost(ctx, request); } else { responseContent.setLength(0); responseContent.append(httpMethod.name()).append(" method not support!"); writeResponse(ctx.channel()); logger.error(responseContent.toString()); } }
From source file:com.nike.cerberus.endpoints.authentication.AuthenticateIamPrincipal.java
License:Apache License
@Override public Matcher requestMatcher() { return Matcher.match("/v2/auth/iam-principal", HttpMethod.POST); }