Package io.netty.handler.codec.http

Examples of io.netty.handler.codec.http.DefaultFullHttpResponse


      case "/json":
    byte[] json = MAPPER.writeValueAsBytes(new Message("Hello, World!"));
    writeResponse(ctx, request, Unpooled.wrappedBuffer(json), TYPE_JSON, String.valueOf(json.length));
    return;
      }
      FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND, Unpooled.EMPTY_BUFFER, false);
      ctx.write(response).addListener(ChannelFutureListener.CLOSE);
  }
    }
View Full Code Here


    private void writeResponse(ChannelHandlerContext ctx, HttpRequest request, ByteBuf buf, CharSequence contentType, CharSequence contentLength) {
  // Decide whether to close the connection or not.
  boolean keepAlive = HttpHeaders.isKeepAlive(request);
  // Build the response object.
  FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf, false);
  HttpHeaders headers = response.headers();
  headers.set(CONTENT_TYPE_ENTITY, contentType);
  headers.set(SERVER_ENTITY, SERVER_NAME);
  headers.set(DATE_ENTITY, date);
  headers.set(CONTENT_LENGTH_ENTITY, contentLength);
View Full Code Here

        }
       
        HttpResponse response = null;
       
        if (buffer != null) {
            response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(code), buffer);
            // We just need to reset the readerIndex this time
            if (buffer.readerIndex() == buffer.writerIndex()) {
                buffer.setIndex(0, buffer.writerIndex());
            }
            // TODO How to enable the chunk transport
            int len = buffer.readableBytes();
            // set content-length
            response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, len);
            LOG.trace("Content-Length: {}", len);
        } else {
            response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(code));
        }
       
        TypeConverter tc = message.getExchange().getContext().getTypeConverter();

        // append headers
View Full Code Here

        httpResponse.withBody("somebody");
        httpResponse.withHeaders(new Header("headerName1", "headerValue1"), new Header("headerName2", "headerValue2_1", "headerValue2_2"));
        httpResponse.withCookies(new Cookie("cookieName1", "cookieValue1"), new Cookie("cookieName2", "cookieValue2"));

        // when
        DefaultFullHttpResponse defaultFullHttpResponse = new MockServerToNettyResponseMapper().mapMockServerResponseToNettyResponse(httpResponse);

        // then
        assertEquals(HttpStatusCode.OK_200.code(), defaultFullHttpResponse.getStatus().code());
        assertEquals("somebody", defaultFullHttpResponse.content().toString(Charsets.UTF_8));
        assertEquals("headerValue1", defaultFullHttpResponse.headers().get("headerName1"));
        assertThat(defaultFullHttpResponse.headers().getAll("headerName2"), containsInAnyOrder("headerValue2_1", "headerValue2_2"));
        assertEquals(Arrays.asList(
                "cookieName1=cookieValue1",
                "cookieName2=cookieValue2"
        ), defaultFullHttpResponse.headers().getAll("Set-Cookie"));
    }
View Full Code Here

        httpResponse.withBody((byte[]) null);
        httpResponse.withHeaders((Header[]) null);
        httpResponse.withCookies((Cookie[]) null);

        // when
        DefaultFullHttpResponse defaultFullHttpResponse = new MockServerToNettyResponseMapper().mapMockServerResponseToNettyResponse(httpResponse);

        // then
        assertEquals(HttpStatusCode.OK_200.code(), defaultFullHttpResponse.getStatus().code());
        assertEquals("", defaultFullHttpResponse.content().toString(Charsets.UTF_8));
        assertTrue(defaultFullHttpResponse.headers().isEmpty());
    }
View Full Code Here

    }

    @Test
    public void shouldMapNullResponseToNettyResponse() {
        // when
        DefaultFullHttpResponse defaultFullHttpResponse = new MockServerToNettyResponseMapper().mapMockServerResponseToNettyResponse(null);

        // then
        assertEquals(HttpStatusCode.NOT_FOUND_404.code(), defaultFullHttpResponse.getStatus().code());
        assertEquals("", defaultFullHttpResponse.content().toString(Charsets.UTF_8));
        assertTrue(defaultFullHttpResponse.headers().isEmpty());
    }
View Full Code Here

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) {
            if (msg instanceof HttpRequest) {
                HttpRequest req = (HttpRequest) msg;

                FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(req.getUri().getBytes(StringUtils.UTF_8)));
                response.headers().set(CONTENT_TYPE, "text/plain");
                response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
                ctx.write(response).addListener(ChannelFutureListener.CLOSE);
            }
        }
View Full Code Here

    }

    private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
        // Allow only GET methods.
        if (req.getMethod() != GET) {
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
            return;
        }

        // Handshake
        WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
View Full Code Here

      if (method.equals(HttpMethod.POST ) )
      {
         ctx.fireChannelRead(ReferenceCountUtil.retain(((FullHttpRequest) msg).content()));
         // add a new response
         responses.put(new ResponseHolder(System.currentTimeMillis() + responseTime,
               new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK)));
         ReferenceCountUtil.release(msg);
         return;
      }
      super.channelRead(ctx, msg);
   }
View Full Code Here

    public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
        if (msg instanceof FullHttpRequest) {
            final FullHttpRequest req = (FullHttpRequest) msg;

            if (is100ContinueExpected(req)) {
                ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
            }

            if (req.getMethod() != GET && req.getMethod() != POST) {
                sendError(ctx, METHOD_NOT_ALLOWED, METHOD_NOT_ALLOWED.toString());
                return;
            }

            final Triplet<String, Map<String,Object>, Optional<String>> requestArguments;
            try {
                requestArguments = getGremlinScript(req);
            } catch (IllegalArgumentException iae) {
                sendError(ctx, BAD_REQUEST, iae.getMessage());
                return;
            }

            final String acceptString = Optional.ofNullable(req.headers().get("Accept")).orElse("application/json");
            final String accept = acceptString.equals("*/*") ? "application/json" : acceptString;
            final MessageTextSerializer serializer = (MessageTextSerializer) serializers.get(accept);
            if (null == serializer) {
                sendError(ctx, BAD_REQUEST, String.format("no serializer for requested Accept header: %s", accept));
                return;
            }

            try {
                logger.debug("Processing request containing script [{}] and bindings of [{}]", requestArguments.getValue0(), requestArguments.getValue1());
                final Timer.Context timerContext = evalOpTimer.time();
                final Object result = gremlinExecutor.eval(requestArguments.getValue0(), requestArguments.getValue2(), requestArguments.getValue1()).get();
                timerContext.stop();

                final ResponseMessage responseMessage = ResponseMessage.build(UUID.randomUUID())
                        .code(ResponseStatusCode.SUCCESS)
                        .result(IteratorUtil.convertToList(result)).create();

                final FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(
                        serializer.serializeResponseAsString(responseMessage).getBytes(UTF8)));
                response.headers().set(CONTENT_TYPE, accept);
                response.headers().set(CONTENT_LENGTH, response.content().readableBytes());

                // handle cors business
                final String origin = req.headers().get(ORIGIN);
                if (origin != null)
                    response.headers().set(ACCESS_CONTROL_ALLOW_ORIGIN, origin);
           
                if (!isKeepAlive(req)) {
                    ctx.write(response).addListener(ChannelFutureListener.CLOSE);
                } else {
                    response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
                    ctx.write(response);
                }
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
View Full Code Here

TOP

Related Classes of io.netty.handler.codec.http.DefaultFullHttpResponse

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.