List of usage examples for io.netty.buffer Unpooled wrappedBuffer
public static ByteBuf wrappedBuffer(ByteBuffer... buffers)
From source file:com.beeswax.hexbid.handler.BidHandlerTest.java
License:Apache License
@Test public void processRequestTest_InvalidProto() { final FullHttpRequest request = Mockito.mock(FullHttpRequest.class); Mockito.when(request.content()).thenReturn(Unpooled.wrappedBuffer("Invalid proto".getBytes())); final ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class); final BidHandler handler = new BidHandler(); final FullHttpResponse response = handler.processRequest(ctx, request); Assert.assertEquals(HttpResponseStatus.BAD_REQUEST, response.status()); Assert.assertEquals("Bad request", response.content().toString(Charset.forName("UTF-8"))); }
From source file:com.beeswax.hexbid.handler.BidHandlerTest.java
License:Apache License
@Test public void processRequestTest_FlatPriceStrategy() { final BidAgentRequest.Builder requestBuilder = BidAgentRequest.newBuilder(); final Adcandidate.Builder adcandidateBuilder = Adcandidate.newBuilder(); final Bidding.Builder biddingBuilder = Bidding.newBuilder(); final CustomStrategy.Builder strategyBuilder = CustomStrategy.newBuilder(); strategyBuilder.setName(FlatPriceStrategy.STRATEGY_NAME); final Params.Builder params = Params.newBuilder(); params.setKey("flat_price_micros_usd"); params.setValue("866"); strategyBuilder.addCustomParams(params); biddingBuilder.setCustomStrategy(strategyBuilder.buildPartial()); adcandidateBuilder.setBidding(biddingBuilder.buildPartial()); adcandidateBuilder.setLineItemId(111); adcandidateBuilder.addCreativeIds(33); requestBuilder.addAdcandidates(adcandidateBuilder.buildPartial()); final ByteBuf requestByteBuf = Unpooled.wrappedBuffer(requestBuilder.build().toByteArray()); final FullHttpRequest request = Mockito.mock(FullHttpRequest.class); Mockito.when(request.content()).thenReturn(requestByteBuf); final ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class); final BidHandler handler = new BidHandler(); final FullHttpResponse bytebufRsponse = handler.processRequest(ctx, request); try {/* w ww. j a v a 2 s .co m*/ final BidAgentResponse protoResponse = (BidAgentResponse) BidProtobufParser .parseProtoBytebuf(bytebufRsponse.content(), BidAgentResponse.newBuilder()); Assert.assertEquals(1, protoResponse.getBidsCount()); Assert.assertEquals(33, protoResponse.getBids(0).getCreative().getId()); Assert.assertEquals(111, protoResponse.getBids(0).getLineItemId()); Assert.assertEquals(866, protoResponse.getBids(0).getBidPriceMicros()); } catch (InvalidProtocolBufferException e) { Assert.fail(e.getMessage()); } }
From source file:com.beeswax.hexbid.handler.BidHandlerTest.java
License:Apache License
@Test public void processRequestTest_RandomPriceStrategy() { final BidAgentRequest.Builder requestBuilder = BidAgentRequest.newBuilder(); final Adcandidate.Builder adcandidateBuilder = Adcandidate.newBuilder(); final Bidding.Builder biddingBuilder = Bidding.newBuilder(); final CustomStrategy.Builder strategyBuilder = CustomStrategy.newBuilder(); strategyBuilder.setName(RandomPriceStrategy.STRATEGY_NAME); final Params.Builder params = Params.newBuilder(); params.setKey("max_price_micros_usd"); params.setValue("1200"); strategyBuilder.addCustomParams(params); biddingBuilder.setCustomStrategy(strategyBuilder.buildPartial()); adcandidateBuilder.setBidding(biddingBuilder.buildPartial()); adcandidateBuilder.setLineItemId(34); adcandidateBuilder.addCreativeIds(13814); requestBuilder.addAdcandidates(adcandidateBuilder.buildPartial()); final ByteBuf requestByteBuf = Unpooled.wrappedBuffer(requestBuilder.build().toByteArray()); final FullHttpRequest request = Mockito.mock(FullHttpRequest.class); Mockito.when(request.content()).thenReturn(requestByteBuf); final ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class); final BidHandler handler = new BidHandler(); final FullHttpResponse bytebufRsponse = handler.processRequest(ctx, request); try {/*from w w w . ja va 2 s .c om*/ final BidAgentResponse protoResponse = (BidAgentResponse) BidProtobufParser .parseProtoBytebuf(bytebufRsponse.content(), BidAgentResponse.newBuilder()); Assert.assertEquals(1, protoResponse.getBidsCount()); Assert.assertEquals(13814, protoResponse.getBids(0).getCreative().getId()); Assert.assertEquals(34, protoResponse.getBids(0).getLineItemId()); Assert.assertTrue( protoResponse.getBids(0).getBidPriceMicros() <= protoResponse.getBids(0).getBidPriceMicros()); Assert.assertTrue(protoResponse.getBids(0).getBidPriceMicros() > 0); } catch (InvalidProtocolBufferException e) { Assert.fail(e.getMessage()); } }
From source file:com.beeswax.hexbid.handler.BidHandlerTest.java
License:Apache License
@Test public void processRequestTest_RetargetingStrategy() { final BidAgentRequest.Builder requestBuilder = BidAgentRequest.newBuilder(); final Adcandidate.Builder adcandidateBuilder = Adcandidate.newBuilder(); final Bidding.Builder biddingBuilder = Bidding.newBuilder(); final CustomStrategy.Builder strategyBuilder = CustomStrategy.newBuilder(); strategyBuilder.setName(RetargetingStrategy.STRATEGY_NAME); final Params.Builder params = Params.newBuilder(); params.setKey("base_price_micros_usd"); params.setValue("100"); strategyBuilder.addCustomParams(params); params.setKey("param_2"); params.setValue("999"); strategyBuilder.addCustomParams(params); biddingBuilder.setCustomStrategy(strategyBuilder.buildPartial()); adcandidateBuilder.setBidding(biddingBuilder.buildPartial()); adcandidateBuilder.setLineItemId(999); adcandidateBuilder.addCreativeIds(888); requestBuilder.addAdcandidates(adcandidateBuilder.buildPartial()); final UserExtensions userExt = UserExtensions.newBuilder().setUserId("BITO.123456").buildPartial(); final User user = User.newBuilder().setExt(userExt).buildPartial(); requestBuilder.setBidRequest(BidRequest.newBuilder().setUser(user).buildPartial()); final ByteBuf requestByteBuf = Unpooled.wrappedBuffer(requestBuilder.buildPartial().toByteArray()); final FullHttpRequest request = Mockito.mock(FullHttpRequest.class); Mockito.when(request.content()).thenReturn(requestByteBuf); final ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class); final BidHandler handler = new BidHandler(); final FullHttpResponse bytebufRsponse = handler.processRequest(ctx, request); try {// w w w . ja va 2s .c o m final BidAgentResponse protoResponse = (BidAgentResponse) BidProtobufParser .parseProtoBytebuf(bytebufRsponse.content(), BidAgentResponse.newBuilder()); Assert.assertEquals(1, protoResponse.getBidsCount()); Assert.assertEquals(888, protoResponse.getBids(0).getCreative().getId()); Assert.assertEquals(999, protoResponse.getBids(0).getLineItemId()); Assert.assertEquals(1100, protoResponse.getBids(0).getBidPriceMicros()); } catch (InvalidProtocolBufferException e) { Assert.fail(e.getMessage()); } }
From source file:com.beeswax.hexbid.handler.DefaultHandler.java
License:Apache License
public FullHttpResponse processRequest(ChannelHandlerContext ctx, FullHttpRequest request) { final QueryStringDecoder queryDecoder = new QueryStringDecoder(request.uri()); LOGGER.debug("Responding with 404: not found path {}", queryDecoder.path()); return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND, Unpooled.wrappedBuffer(CONTENT_MESSAGE.getBytes())); }
From source file:com.beeswax.hexbid.handler.HealthHandler.java
License:Apache License
public FullHttpResponse processRequest(ChannelHandlerContext ctx, FullHttpRequest request) { LOGGER.debug("/health request"); return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(CONTENT_MESSAGE.getBytes())); }
From source file:com.beeswax.hexbid.handler.VarHandler.java
License:Apache License
public FullHttpResponse processRequest(ChannelHandlerContext ctx, FullHttpRequest request) { LOGGER.debug("/var request"); return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(CONTENT_MESSAGE.getBytes())); }
From source file:com.bloom.zerofs.rest.HealthCheckHandler.java
License:Open Source License
@Override public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception { logger.trace("Reading on channel {}", ctx.channel()); boolean forwardObj = false; if (obj instanceof HttpRequest) { if (request == null && ((HttpRequest) obj).getUri().equals(healthCheckUri)) { nettyMetrics.healthCheckRequestRate.mark(); startTimeInMs = System.currentTimeMillis(); logger.trace("Handling health check request while in state " + restServerState.isServiceUp()); request = (HttpRequest) obj; if (restServerState.isServiceUp()) { response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(GOOD)); HttpHeaders.setKeepAlive(response, HttpHeaders.isKeepAlive(request)); HttpHeaders.setContentLength(response, GOOD.length); } else { response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.SERVICE_UNAVAILABLE, Unpooled.wrappedBuffer(BAD)); HttpHeaders.setKeepAlive(response, false); HttpHeaders.setContentLength(response, BAD.length); }//from ww w . ja va2 s .com nettyMetrics.healthCheckRequestProcessingTimeInMs .update(System.currentTimeMillis() - startTimeInMs); } else { // Rest server could be down even if not for health check request. We intentionally don't take any action in this // handler for such cases and leave it to the downstream handlers to handle it forwardObj = true; } } if (obj instanceof LastHttpContent) { if (response != null) { // response was created when we received the request with health check uri ChannelFuture future = ctx.writeAndFlush(response); if (!HttpHeaders.isKeepAlive(response)) { future.addListener(ChannelFutureListener.CLOSE); } request = null; response = null; nettyMetrics.healthCheckRequestRoundTripTimeInMs.update(System.currentTimeMillis() - startTimeInMs); } else { // request was not for health check uri forwardObj = true; } } else if (request == null) { // http Content which is not LastHttpContent is not intended for this handler forwardObj = true; } if (forwardObj) { super.channelRead(ctx, obj); } else { ReferenceCountUtil.release(obj); } }
From source file:com.bloom.zerofs.rest.NettyResponseChannel.java
License:Open Source License
/** * Provided a cause, returns an error response with the right status and error message. * @param cause the cause of the error.//from w ww .j a v a 2s. c o m * @return a {@link FullHttpResponse} with the error message that can be sent to the client. */ private FullHttpResponse getErrorResponse(Throwable cause) { HttpResponseStatus status; StringBuilder errReason = new StringBuilder(); if (cause instanceof RestServiceException) { RestServiceErrorCode restServiceErrorCode = ((RestServiceException) cause).getErrorCode(); errorResponseStatus = ResponseStatus.getResponseStatus(restServiceErrorCode); status = getHttpResponseStatus(errorResponseStatus); if (status == HttpResponseStatus.BAD_REQUEST) { errReason.append(" [").append(Utils.getRootCause(cause).getMessage()).append("]"); } } else { nettyMetrics.internalServerErrorCount.inc(); status = HttpResponseStatus.INTERNAL_SERVER_ERROR; errorResponseStatus = ResponseStatus.InternalServerError; } String fullMsg = "Failure: " + status + errReason; logger.trace("Constructed error response for the client - [{}]", fullMsg); FullHttpResponse response; if (request != null && !request.getRestMethod().equals(RestMethod.HEAD)) { response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, Unpooled.wrappedBuffer(fullMsg.getBytes())); } else { // for HEAD, we cannot send the actual body but we need to return what the length would have been if this was GET. // https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html (Section 9.4) response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status); } HttpHeaders.setDate(response, new GregorianCalendar().getTime()); HttpHeaders.setContentLength(response, fullMsg.length()); HttpHeaders.setHeader(response, HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=UTF-8"); boolean keepAlive = !forceClose && HttpHeaders.isKeepAlive(responseMetadata) && request != null && !request.getRestMethod().equals(RestMethod.POST) && !CLOSE_CONNECTION_ERROR_STATUSES.contains(status); HttpHeaders.setKeepAlive(response, keepAlive); return response; }
From source file:com.butor.netty.handler.codec.ftp.cmd.CommandUtil.java
License:Apache License
public static void send(String response, ChannelHandlerContext ctx) { String line = response + "\r\n"; byte[] data = line.getBytes(CharsetUtil.US_ASCII); ctx.channel().writeAndFlush(Unpooled.wrappedBuffer(data)); }