Java Code Examples for io.netty.handler.codec.http.HttpResponseStatus#OK

The following examples show how to use io.netty.handler.codec.http.HttpResponseStatus#OK . 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: HttpChannelImpl.java    From InChat with Apache License 2.0 6 votes vote down vote up
@Override
public void getState(Channel channel, SendServerVO serverVO) {
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    response.headers().set(HttpConstant.CONTENT_TYPE, HttpConstant.APPLICATION_JSON);
    if (serverVO.getToken() == "") {
        notFindUri(channel);
    }
    Boolean state = WebSocketCacheMap.hasToken(serverVO.getToken());
    StateVo stateVo = new StateVo(serverVO.getToken(), state);
    ResultVO<StateVo> resultVO = new ResultVO<>(HttpResponseStatus.OK.code(), stateVo);
    Gson gson = new Gson();
    ByteBuf buf = Unpooled.copiedBuffer(gson.toJson(resultVO), CharsetUtil.UTF_8);
    response.content().writeBytes(buf);
    channel.writeAndFlush(response);
    close(channel);
}
 
Example 2
Source File: HttpCacheRequestHandler.java    From timely with Apache License 2.0 6 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, CacheRequest v) throws Exception {
    byte[] buf;
    try {
        buf = JsonUtil.getObjectMapper().writeValueAsBytes(cache.getCacheStatus());
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        this.sendHttpError(ctx, new TimelyException(HttpResponseStatus.INTERNAL_SERVER_ERROR.code(),
                "Error getting cache status", "Error getting cache status", e));
        return;
    }
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
            Unpooled.copiedBuffer(buf));
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, Constants.JSON_TYPE);
    response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
    sendResponse(ctx, response);
}
 
Example 3
Source File: MesosClientTest.java    From mesos-rxjava with Apache License 2.0 6 votes vote down vote up
@Test
public void testVerifyResponseOk_ensuresContentTypeOfResponseMatchesReceiveCodec() throws Exception {
    final Func1<HttpClientResponse<ByteBuf>, Observable<ByteBuf>> f = MesosClient.verifyResponseOk(
        "Subscribe",
        new AtomicReference<>(),
        StringMessageCodec.UTF8_STRING.mediaType()
    );

    final DefaultHttpResponse nettyResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    nettyResponse.headers().add("Content-Type", "text/html");
    final HttpClientResponse<ByteBuf> response = new HttpClientResponse<>(
        nettyResponse,
        UnicastContentSubject.create(1000, TimeUnit.MILLISECONDS)
    );

    try {
        f.call(response);
    } catch (MesosException e) {
        final String expected = String.format(
            "Response had Content-Type \"%s\" expected \"%s\"",
            "text/html",
            StringMessageCodec.UTF8_STRING.mediaType()
        );
        assertThat(e.getContext().getMessage()).isEqualTo(expected);
    }
}
 
Example 4
Source File: StreamServerGroupHandler.java    From IpCamera with Eclipse Public License 2.0 6 votes vote down vote up
private void sendFile(ChannelHandlerContext ctx, String fileUri, String contentType) throws IOException {
    logger.debug("file is :{}", fileUri);
    File file = new File(fileUri);
    ChunkedFile chunkedFile = new ChunkedFile(file);
    ByteBuf footerBbuf = Unpooled.copiedBuffer("\r\n", 0, 2, StandardCharsets.UTF_8);
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    response.headers().add(HttpHeaderNames.CONTENT_TYPE, contentType);
    response.headers().set(HttpHeaderNames.CACHE_CONTROL, HttpHeaderValues.NO_CACHE);
    response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
    response.headers().add(HttpHeaderNames.CONTENT_LENGTH, chunkedFile.length());
    response.headers().add("Access-Control-Allow-Origin", "*");
    response.headers().add("Access-Control-Expose-Headers", "*");
    ctx.channel().write(response);
    ctx.channel().write(chunkedFile);
    ctx.channel().writeAndFlush(footerBbuf);
}
 
Example 5
Source File: HttpBlobHandler.java    From crate with Apache License 2.0 6 votes vote down vote up
private void fullContentResponse(HttpRequest request, String index, final String digest) throws IOException {
    BlobShard blobShard = localBlobShard(index, digest);
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK);
    Netty4CorsHandler.setCorsResponseHeaders(request, response, corsConfig);
    final RandomAccessFile raf = blobShard.blobContainer().getRandomAccessFile(digest);
    try {
        HttpUtil.setContentLength(response, raf.length());
        setDefaultGetHeaders(response);
        LOGGER.trace("HttpResponse: {}", response);
        Channel channel = ctx.channel();
        channel.write(response);
        ChannelFuture writeFuture = transferFile(digest, raf, 0, raf.length());
        if (!HttpUtil.isKeepAlive(request)) {
            writeFuture.addListener(ChannelFutureListener.CLOSE);
        }
    } catch (Throwable t) {
        /*
         * Make sure RandomAccessFile is closed when exception is raised.
         * In case of success, the ChannelFutureListener in "transferFile" will take care
         * that the resources are released.
         */
        raf.close();
        throw t;
    }
}
 
Example 6
Source File: HttpRootController.java    From happor with MIT License 5 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
		throws Exception {
	// TODO Auto-generated method stub
	if (msg instanceof FullHttpRequest) {
		request = (FullHttpRequest) msg;
		response = new DefaultFullHttpResponse(
				request.getProtocolVersion(), HttpResponseStatus.OK);
		
		HapporContext happorContext = server.getContext(request);
		if (happorContext == null) {
			logger.error("cannot find path for URI: " + request.getUri());
			response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
			ctx.channel().writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
			return;
		}
		
		HttpController lastController = null;
		
		Map<String, ControllerRegistry> controllers = happorContext.getControllers();
		for (Map.Entry<String, ControllerRegistry> entry : controllers.entrySet()) {
			ControllerRegistry registry = entry.getValue();
			String method = registry.getMethod();
			String uriPattern = registry.getUriPattern();
			UriParser uriParser = new UriParser(request.getUri());
			
			if (isMethodMatch(method) && isUriMatch(uriParser, uriPattern)) {
				HttpController controller = happorContext.getController(registry.getClazz());
				controller.setPrev(lastController);
				controller.setServer(server);
				controller.setUriParser(uriParser);
				boolean isEnd = controller.input(ctx, request, response);
				if (isEnd) {
					break;
				}
				lastController = controller;
			}
		}
	}
}
 
Example 7
Source File: NettyHttpUtil.java    From netty-cookbook with Apache License 2.0 5 votes vote down vote up
public static FullHttpResponse theHttpContent(String str, String contentType) {
	ByteBuf byteBuf = Unpooled.copiedBuffer(str.getBytes());	
	FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK ,byteBuf);
	response.headers().set(CONTENT_TYPE, contentType);
	response.headers().set(CONTENT_LENGTH, byteBuf.readableBytes());
	response.headers().set(CONNECTION, HEADER_CONNECTION_CLOSE);		
	return response;
}
 
Example 8
Source File: GoogleHomeHandler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private void writeResult(ChannelHandlerContext ctx, FullHttpRequest req, Request googleRequest, Response res) {
   String json = Transformers.GSON.toJson(res);
   logger.trace("[{}] resulted in response [{}]", googleRequest, json);
   FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
   response.content().writeBytes(json.getBytes(StandardCharsets.UTF_8));
   httpSender.sendHttpResponse(ctx, req, response);
}
 
Example 9
Source File: UploadHandler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public void sendResponse(FullHttpRequest req, ChannelHandlerContext ctx) throws Exception {
   long startTime = System.nanoTime();

   HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(req);
   try {
      String place = null;
      int num = 0;
      while(decoder.hasNext()) {
         num++;

         InterfaceHttpData httpData = decoder.next();
         if(httpData.getHttpDataType() == HttpDataType.Attribute && httpData.getName().equalsIgnoreCase("place")) {
            place = ((Attribute) httpData).getValue();
         } else if(httpData.getHttpDataType() == HttpDataType.FileUpload) {
            String camProtAddr = URLDecoder.decode(httpData.getName(), "UTF-8");
            Device d = findCamera(camProtAddr);
            if(d == null) {
               UPLOAD_UNKNOWN.inc();
               logger.warn("ignoring preview upload for non-existent camera {}", camProtAddr);
               continue;
            }
            write(place, d, (FileUpload) httpData);
         }
      }
      HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
      ChannelFuture future = ctx.writeAndFlush(response);
      if(!HttpHeaders.isKeepAlive(req)) {
         future.addListener(ChannelFutureListener.CLOSE);
      }

      UPLOAD_NUM.update(num);
      UPLOAD_SUCCESS.update(System.nanoTime() - startTime, TimeUnit.NANOSECONDS);
   } catch (Exception ex) {
      UPLOAD_FAIL.update(System.nanoTime() - startTime, TimeUnit.NANOSECONDS);
   } finally {
      decoder.cleanFiles();
   }
}
 
Example 10
Source File: NettyHttpUtil.java    From netty-cookbook with Apache License 2.0 5 votes vote down vote up
public static FullHttpResponse theHttpContent(String str) {
	ByteBuf byteBuf = Unpooled.copiedBuffer(str.getBytes());
	FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK ,byteBuf);
	response.headers().set(CONTENT_TYPE, ContentTypePool.TEXT_UTF8);
	response.headers().set(CONTENT_LENGTH, byteBuf.readableBytes());
	response.headers().set(CONNECTION, HEADER_CONNECTION_CLOSE);
	return response;
}
 
Example 11
Source File: HttpHandlerUtil.java    From proxyee-down with Apache License 2.0 5 votes vote down vote up
public static FullHttpResponse buildContent(String content, String contentType) {
  FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
  response.headers().set(HttpHeaderNames.CONTENT_TYPE, AsciiString.cached(contentType));
  if (content != null) {
    response.content().writeBytes(content.getBytes(Charset.forName("utf-8")));
  }
  response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
  return response;
}
 
Example 12
Source File: HttpServerHandler.java    From blog with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
	if (msg instanceof HttpRequest) {
		FullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
		httpResponse.content().writeBytes(DataCenter.getData().getBytes());
		httpResponse.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=UTF-8");
		httpResponse.headers().set(HttpHeaders.Names.CONTENT_LENGTH, httpResponse.content().readableBytes());
		ctx.writeAndFlush(httpResponse);
	}
}
 
Example 13
Source File: HttpMetricPutHandler.java    From timely with Apache License 2.0 5 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, MetricRequest m) throws Exception {
    try {
        this.dataStore.store(m.getMetric());
    } catch (TimelyException e) {
        LOG.error(e.getMessage(), e);
        this.sendHttpError(ctx, e);
        return;
    }
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
            Unpooled.EMPTY_BUFFER);
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, Constants.JSON_TYPE);
    response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
    sendResponse(ctx, response);
}
 
Example 14
Source File: RESTHandler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public FullHttpResponse respond(FullHttpRequest req, ChannelHandlerContext ctx) throws Exception {
	ClientMessage request;
	MessageBody response;

	try {
		request = decode(req);
	} catch (Throwable t) {
		LOGGER.debug("Unable to decode request", t);
		return response(HttpResponseStatus.BAD_REQUEST, "plain/text", "Unable to decode request");
	}

	HttpResponseStatus status = HttpResponseStatus.OK;
	try {
	   /* preHandleValidation is typically a NOOP. However
	    * there may be times where a RESTHandler might need
	    * AUTH style checks that require access to the
	    * ChannelHandlerContext.
	    */
	   assertValidRequest(req, ctx);
		response = doHandle(request, ctx);
	} catch (Throwable th) {
		LOGGER.error("Error handling client message", th);
		response = Errors.fromException(th);
		status = overrideErrorResponseStatus(th);
		if(status == null) {
			status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
		}
	}

	ClientMessage message = ClientMessage.builder().withCorrelationId(request.getCorrelationId())
			.withDestination(request.getSource()).withSource(Addresses.toServiceAddress(PlaceService.NAMESPACE))
			.withPayload(response).create();

	return response(status, BridgeHeaders.CONTENT_TYPE_JSON_UTF8, JSON.toJson(message));
}
 
Example 15
Source File: NettyHttpUtil.java    From netty-cookbook with Apache License 2.0 5 votes vote down vote up
public static FullHttpResponse theHttpContent(HttpOutputResource re, String contentType) {
	FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK , re.getByteBuf());
	response.headers().set(CONTENT_TYPE, contentType);
	response.headers().set(CONTENT_LENGTH, re.getLength());
	response.headers().set(CONNECTION, HEADER_CONNECTION_CLOSE);		
	//System.out.println("CONTENT_LENGTH:"+re.getLength());
	//System.out.println();
	return response;
}
 
Example 16
Source File: HttpProcessHandler.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
private static final FullHttpResponse http_200(String result) {
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
            Unpooled.wrappedBuffer(result.getBytes()));
    HttpHeaders httpHeaders = response.headers();
    httpHeaders.set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
    httpHeaders.set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());
    return response;
}
 
Example 17
Source File: GraphQLHttpService.java    From besu with Apache License 2.0 5 votes vote down vote up
private HttpResponseStatus status(final GraphQLResponse response) {

    switch (response.getType()) {
      case UNAUTHORIZED:
        return HttpResponseStatus.UNAUTHORIZED;
      case ERROR:
        return HttpResponseStatus.BAD_REQUEST;
      case SUCCESS:
      case NONE:
      default:
        return HttpResponseStatus.OK;
    }
  }
 
Example 18
Source File: NettyHttpUtil.java    From netty-cookbook with Apache License 2.0 5 votes vote down vote up
public static FullHttpResponse theHttpContent(HttpOutputResource re, String contentType) {
	FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK , re.getByteBuf());
	response.headers().set(CONTENT_TYPE, contentType);
	response.headers().set(CONTENT_LENGTH, re.getLength());
	response.headers().set(CONNECTION, HEADER_CONNECTION_CLOSE);		
	//System.out.println("CONTENT_LENGTH:"+re.getLength());
	//System.out.println();
	return response;
}
 
Example 19
Source File: EthResponseFactory.java    From ethsigner with Apache License 2.0 4 votes vote down vote up
public EthNodeResponse ethNode(final Map<String, String> headers, final String body) {
  return new EthNodeResponse(headers, body, HttpResponseStatus.OK);
}
 
Example 20
Source File: OkResponseHandler.java    From tools-journey with Apache License 2.0 4 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) {
    final FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    response.headers().set("custom-response-header", "Some value");
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}