List of usage examples for io.netty.handler.codec.http HttpResponseStatus CONTINUE
HttpResponseStatus CONTINUE
To view the source code for io.netty.handler.codec.http HttpResponseStatus CONTINUE.
Click Source Link
From source file:io.urmia.st.StorageServerHandler.java
License:Open Source License
private void handlePUT(ChannelHandlerContext ctx, HttpRequest request) /*throws IOException*/ { log.debug("handlePUT: {}", request); final String location = getLocation(request); String uri = request.getUri(); if (location != null) { String existing = BASE + location; String link = BASE + uri; log.debug("ln {} -> {}", link, existing); link(ctx, existing, link);//from w w w .j av a 2 s .c o m return; } boolean isDir = isDirectory(request.headers().get("content-type")); // PUT String p = BASE + uri; log.info("creating {} at: {}", isDir ? "dir" : "file", p); File file = new File(p); if (isDir) { log.info("mkdir at: {}", p); final boolean done = file.mkdirs(); if (done) { access.success(ctx, "MKDIR", uri, requestStartMS); ctx.writeAndFlush(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NO_CONTENT)); } else { access.fail(ctx, "MKDIR", uri, requestStartMS); sendError(ctx, HttpResponseStatus.BAD_REQUEST); } } else { file.getParentFile().mkdirs(); this.uri = uri; // todo: handle 'location' header for 'mln()'. e.i. no content //Path path = file.toPath(); //fileChannel = FileChannel.open(path, CREATE, WRITE); try { fileChannel = new FileOutputStream(file).getChannel(); // todo: should close fis? } catch (FileNotFoundException e) { log.error("exception in opening file channel: {}, err: {}", file, e.getMessage()); writeResponse(ctx, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST, errorBody("UploadError", "invalid path: " + uri)), true); return; } readingChunks = HttpHeaders.isTransferEncodingChunked(request); //log.info("is chunk: {}", readingChunks); ctx.writeAndFlush(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE)); // VoidChannelPromise } }
From source file:me.zhuoran.amoeba.netty.server.HttpServerHandler.java
License:Apache License
protected void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception { AmoebaHttpRequest request = null;// w w w .j av a 2 s . c o m if (msg instanceof HttpRequest) { HttpRequest httpContent = (HttpRequest) msg; if (!httpContent.getDecoderResult().isSuccess()) { sendHttpResponse(ctx, httpContent, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST)); return; } if (httpContent.getMethod() != HttpMethod.GET && httpContent.getMethod() != HttpMethod.POST) { sendHttpResponse(ctx, httpContent, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN)); return; } if (HttpHeaders.is100ContinueExpected(httpContent)) { ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE)); } String uri = HttpRequestHandler.sanitizeUri(httpContent.getUri()); if (!HttpServer.executorNameList.contains(uri)) { DefaultFullHttpResponse response1 = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND); sendHttpResponse(ctx, httpContent, response1); return; } request = new AmoebaHttpRequest(httpContent, ctx.channel().id().asLongText()); } if (msg instanceof HttpContent) { HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); request.setHttpContent(content); request.setContent(content.toString(CharsetUtil.UTF_8)); if (msg instanceof LastHttpContent) { FullHttpResponse response = this.getHttpResponse(request); this.writeResponse(request, response, ctx); } } }
From source file:name.osipov.alexey.server.ServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws IOException { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; if (HttpHeaders.is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE)); return; }//from w ww.j av a 2 s .c o m //String passkey = req.headers().get("passkey"); // in case of large output this buffer will demand memory // writing directly to channel maybe more efficient... ByteBufOutputStream bufstream = new ByteBufOutputStream(Unpooled.buffer()); JsonGenerator json = new JsonFactory().createGenerator(bufstream); json.writeStartObject(); HttpResponseStatus status = HttpResponseStatus.INTERNAL_SERVER_ERROR; switch (req.getUri()) { case "/register": { User u = users.Register(); json.writeNumberField("id", u.getId()); json.writeBinaryField("key", u.getKey().asBinary()); status = HttpResponseStatus.OK; } break; case "/statistics": { String hashed_key_base64 = req.headers().get("key"); byte[] hashed_key = Base64.decodeBase64(hashed_key_base64); long salt = System.currentTimeMillis() / 1000 / 30; User u = users.getBySaltedHash(hashed_key, salt); if (u != null) { u.requestHappen(); json.writeNumberField("id", u.getId()); json.writeNumberField("requests", u.getRequests()); status = HttpResponseStatus.OK; } else status = HttpResponseStatus.UNAUTHORIZED; } break; } json.writeEndObject(); json.close(); FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, bufstream.buffer()); response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain"); response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes()); if (!HttpHeaders.isKeepAlive(req)) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(HttpHeaders.Names.CONNECTION, Values.KEEP_ALIVE); ctx.write(response); } } }
From source file:net.anyflow.menton.http.HttpRequestRouter.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (HttpHeaderValues.WEBSOCKET.toString().equalsIgnoreCase(request.headers().get(HttpHeaderNames.UPGRADE)) && HttpHeaderValues.UPGRADE.toString() .equalsIgnoreCase(request.headers().get(HttpHeaderNames.CONNECTION))) { if (ctx.pipeline().get(WebsocketFrameHandler.class) == null) { logger.error("No WebSocket Handler available."); ctx.channel()//from www .j a v a2 s .c o m .writeAndFlush( new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN)) .addListener(ChannelFutureListener.CLOSE); return; } ctx.fireChannelRead(request.retain()); return; } if (HttpUtil.is100ContinueExpected(request)) { ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE)); return; } HttpResponse response = HttpResponse.createServerDefault(request.headers().get(HttpHeaderNames.COOKIE)); String requestPath = new URI(request.uri()).getPath(); if (isWebResourcePath(requestPath)) { handleWebResourceRequest(ctx, request, response, requestPath); } else { try { processRequest(ctx, request, response); } catch (URISyntaxException e) { response.setStatus(HttpResponseStatus.NOT_FOUND); logger.info("unexcepted URI : {}", request.uri()); } catch (Exception e) { response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR); logger.error("Unknown exception was thrown in business logic handler.\r\n" + e.getMessage(), e); } } }
From source file:org.apache.cxf.transport.http.netty.server.NettyHttpServletHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { HttpRequest request = (HttpRequest) msg; if (HttpHeaders.is100ContinueExpected(request)) { ctx.write(new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE)); }/*from w w w. java 2 s . c o m*/ // find the nettyHttpContextHandler by lookup the request url NettyHttpContextHandler nettyHttpContextHandler = pipelineFactory.getNettyHttpHandler(request.getUri()); if (nettyHttpContextHandler != null) { handleHttpServletRequest(ctx, request, nettyHttpContextHandler); } else { throw new RuntimeException( new Fault(new Message("NO_NETTY_SERVLET_HANDLER_FOUND", LOG, request.getUri()))); } }
From source file:org.ballerinalang.test.service.http.sample.ExpectContinueTestCase.java
License:Open Source License
@Test(description = "Test 100 continue response and for request with expect:100-continue header") public void test100Continue() { HttpClient httpClient = new HttpClient("localhost", servicePort); DefaultHttpRequest httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/continue"); DefaultLastHttpContent reqPayload = new DefaultLastHttpContent( Unpooled.wrappedBuffer(TestUtils.LARGE_ENTITY.getBytes())); httpRequest.headers().set(HttpHeaderNames.CONTENT_LENGTH, TestUtils.LARGE_ENTITY.getBytes().length); httpRequest.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.TEXT_PLAIN); httpRequest.headers().set("X-Status", "Positive"); List<FullHttpResponse> responses = httpClient.sendExpectContinueRequest(httpRequest, reqPayload); Assert.assertFalse(httpClient.waitForChannelClose()); // 100-continue response Assert.assertEquals(responses.get(0).status(), HttpResponseStatus.CONTINUE); Assert.assertEquals(Integer.parseInt(responses.get(0).headers().get(HttpHeaderNames.CONTENT_LENGTH)), 0); // Actual response String responsePayload = TestUtils.getEntityBodyFrom(responses.get(1)); Assert.assertEquals(responses.get(1).status(), HttpResponseStatus.OK); Assert.assertEquals(responsePayload, TestUtils.LARGE_ENTITY); Assert.assertEquals(responsePayload.getBytes().length, TestUtils.LARGE_ENTITY.getBytes().length); Assert.assertEquals(Integer.parseInt(responses.get(1).headers().get(HttpHeaderNames.CONTENT_LENGTH)), TestUtils.LARGE_ENTITY.getBytes().length); }
From source file:org.ballerinalang.test.service.http.sample.ExpectContinueTestCase.java
License:Open Source License
@Test public void test100ContinuePassthrough() { HttpClient httpClient = new HttpClient("localhost", servicePort); DefaultHttpRequest reqHeaders = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/continue/testPassthrough"); DefaultLastHttpContent reqPayload = new DefaultLastHttpContent( Unpooled.wrappedBuffer(TestUtils.LARGE_ENTITY.getBytes())); reqHeaders.headers().set(HttpHeaderNames.CONTENT_LENGTH, TestUtils.LARGE_ENTITY.getBytes().length); reqHeaders.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.TEXT_PLAIN); List<FullHttpResponse> responses = httpClient.sendExpectContinueRequest(reqHeaders, reqPayload); Assert.assertFalse(httpClient.waitForChannelClose()); // 100-continue response Assert.assertEquals(responses.get(0).status(), HttpResponseStatus.CONTINUE); Assert.assertEquals(Integer.parseInt(responses.get(0).headers().get(HttpHeaderNames.CONTENT_LENGTH)), 0); // Actual response String responsePayload = TestUtils.getEntityBodyFrom(responses.get(1)); Assert.assertEquals(responses.get(1).status(), HttpResponseStatus.OK); Assert.assertEquals(responsePayload, TestUtils.LARGE_ENTITY); Assert.assertEquals(responsePayload.getBytes().length, TestUtils.LARGE_ENTITY.getBytes().length); Assert.assertEquals(Integer.parseInt(responses.get(1).headers().get(HttpHeaderNames.CONTENT_LENGTH)), TestUtils.LARGE_ENTITY.getBytes().length); }
From source file:org.ballerinalang.test.util.client.HttpClient.java
License:Open Source License
public List<FullHttpResponse> sendExpectContinueRequest(DefaultHttpRequest httpRequest, DefaultLastHttpContent httpContent) { CountDownLatch latch = new CountDownLatch(1); this.waitForConnectionClosureLatch = new CountDownLatch(1); this.responseHandler.setLatch(latch); this.responseHandler.setWaitForConnectionClosureLatch(this.waitForConnectionClosureLatch); httpRequest.headers().set(HttpHeaderNames.HOST, host + ":" + port); httpRequest.headers().set(HttpHeaderNames.EXPECT, HttpHeaderValues.CONTINUE); this.connectedChannel.writeAndFlush(httpRequest); try {//from w w w. j ava 2 s . c o m latch.await(); } catch (InterruptedException e) { log.warn("Interrupted before receiving the response."); } FullHttpResponse response100Continue = this.responseHandler.getHttpFullResponse(); if (response100Continue.status().equals(HttpResponseStatus.CONTINUE)) { latch = new CountDownLatch(1); this.responseHandler.setLatch(latch); this.connectedChannel.writeAndFlush(httpContent); try { latch.await(); } catch (InterruptedException e) { log.warn("Interrupted before receiving the response."); } } return responseHandler.getHttpFullResponses(); }
From source file:org.dcache.http.KeepAliveHandler.java
License:Open Source License
@Override public void write(ChannelHandlerContext context, Object message, ChannelPromise promise) throws Exception { boolean is100Continue = false; if (message instanceof HttpResponse) { HttpResponse response = (HttpResponse) message; is100Continue = response.getStatus().equals(HttpResponseStatus.CONTINUE); boolean keepAlive = _inflightKeepAlive.getFirst(); /*// w ww .j a va2 s .c om * An upstream handler can request the connection be closed even if * the client make no such request. */ if (keepAlive && !HttpHeaders.isKeepAlive(response)) { _inflightKeepAlive.removeFirst(); _inflightKeepAlive.addFirst(Boolean.FALSE); keepAlive = false; } /* REVISIT: It is not clear from RFC-2616 whether, when the client * issues a request with both the "Expect: 100-continue" and the * "Connection: close" headers, the initial CONTINUE response and * the final response should both include the server's * "Connection: close" header, or just the initial CONTINUE, or * just the final response. * * We choose (somewhat arbitrarily) not to send the * "Connection: close" header with CONTINUE responses. */ if (!is100Continue) { HttpHeaders.setKeepAlive(response, keepAlive); } } ChannelFuture writePromise = context.write(message, promise); /* * Netty (currently) requires that the message(s) for the 100-continue * partial response contain a LastHttpContent message; therefore, an * HTTP PUT request with the "Expect: 100-continue" header will * generate two LastHttpContent messages. */ if (message instanceof LastHttpContent && !is100Continue) { boolean keepAlive = _inflightKeepAlive.remove(); if (!keepAlive) { writePromise.addListener(ChannelFutureListener.CLOSE); } } }
From source file:org.elasticsearch.http.netty4.Netty4HttpServerTransportTests.java
License:Apache License
/** * Test that {@link Netty4HttpServerTransport} supports the "Expect: 100-continue" HTTP header */// w w w .ja v a 2 s . c om public void testExpectContinueHeader() throws Exception { try (Netty4HttpServerTransport transport = new Netty4HttpServerTransport(Settings.EMPTY, networkService, bigArrays, threadPool)) { transport.httpServerAdapter((request, channel, context) -> channel.sendResponse( new BytesRestResponse(OK, BytesRestResponse.TEXT_CONTENT_TYPE, new BytesArray("done")))); transport.start(); InetSocketTransportAddress remoteAddress = (InetSocketTransportAddress) randomFrom( transport.boundAddress().boundAddresses()); try (Netty4HttpClient client = new Netty4HttpClient()) { FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/"); HttpUtil.set100ContinueExpected(request, true); HttpUtil.setContentLength(request, 10); FullHttpResponse response = client.post(remoteAddress.address(), request); assertThat(response.status(), is(HttpResponseStatus.CONTINUE)); request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/", Unpooled.EMPTY_BUFFER); response = client.post(remoteAddress.address(), request); assertThat(response.status(), is(HttpResponseStatus.OK)); assertThat(new String(ByteBufUtil.getBytes(response.content()), StandardCharsets.UTF_8), is("done")); } } }