List of usage examples for io.netty.handler.codec.http HttpResponseStatus HttpResponseStatus
public HttpResponseStatus(int code, String reasonPhrase)
From source file:co.freeside.betamax.proxy.BetamaxFilters.java
License:Apache License
private Optional<? extends FullHttpResponse> onRequestIntercepted() throws IOException { if (tape == null) { return Optional.of(new DefaultFullHttpResponse(HTTP_1_1, new HttpResponseStatus(403, "No tape"))); } else if (tape.isReadable() && tape.seek(request)) { LOG.warning(String.format("Playing back from tape %s", tape.getName())); Response recordedResponse = tape.play(request); FullHttpResponse response = playRecordedResponse(recordedResponse); setViaHeader(response);// w w w . jav a 2 s . co m setBetamaxHeader(response, "PLAY"); return Optional.of(response); } else { LOG.warning(String.format("no matching request found on %s", tape.getName())); return Optional.absent(); } }
From source file:com.addthis.hydra.query.loadbalance.HttpQueryCallHandler.java
License:Apache License
/** * special handler for query//ww w . j a v a2 s .co m */ public static ChannelFuture handleQuery(ChannelHandler queryToQueryResultsEncoder, KVPairs kv, HttpRequest request, ChannelHandlerContext ctx, EventExecutor executor) throws Exception { String job = kv.getValue("job"); String path = kv.getValue("path", kv.getValue("q", "")); Query query = new Query(job, new String[] { path }, new String[] { kv.getValue("ops"), kv.getValue("rops") }); query.setTraced(kv.getIntValue("trace", 0) == 1); query.setParameterIfNotYetSet("hosts", kv.getValue("hosts")); query.setParameterIfNotYetSet("gate", kv.getValue("gate")); query.setParameterIfNotYetSet("originalrequest", kv.getValue("originalrequest")); SocketAddress remoteIP = ctx.channel().remoteAddress(); if (remoteIP instanceof InetSocketAddress) { // only log implementations with known methods query.setParameterIfNotYetSet("remoteip", ((InetSocketAddress) remoteIP).getAddress().getHostAddress()); } query.setParameterIfNotYetSet("allocator", kv.getValue("allocator")); query.setParameterIfNotYetSet("allowPartial", kv.getValue("allowPartial")); String filename = kv.getValue("filename", "query"); String format = kv.getValue("format", "json"); String gdriveAccessToken = kv.getValue("accesstoken"); int timeout = Math.min(kv.getIntValue("timeout", maxQueryTime), maxQueryTime); query.setParameterIfNotYetSet("timeout", timeout); query.setParameter("sender", kv.getValue("sender")); if (log.isDebugEnabled()) { log.debug(new StringMapHelper().put("type", "query.starting").put("query.path", query.getPaths()[0]) .put("query.hosts", query.getParameter("hosts")).put("query.ops", query.getOps()) .put("trace", query.isTraced()).put("sources", query.getParameter("sources")) .put("time", System.currentTimeMillis()).put("job.id", query.getJob()) .put("query.id", query.uuid()).put("sender", query.getParameter("sender")).put("format", format) .put("filename", filename).put("originalrequest", query.getParameter("originalrequest")) .put("timeout", query.getParameter("timeout")).put("requestIP", query.getParameter("remoteip")) .put("allocator", query.getParameter("allocator")) .put("allowPartial", query.getParameter("allowPartial")).createKVPairs().toString()); } // support legacy async query semantics query = LegacyHandler.handleQuery(query, kv, request, ctx); if (query == null) { return ctx.newSucceededFuture(); } if (query.getJob() == null) { sendError(ctx, new HttpResponseStatus(500, "missing job")); return ctx.newSucceededFuture(); } switch (format) { case "json": ctx.pipeline().addLast(executor, "format", new JsonBundleEncoder()); break; case "html": ctx.pipeline().addLast(executor, "format", new HtmlBundleEncoder()); break; case "gdrive": ctx.pipeline().addLast(executor, "stringer", stringer); ctx.pipeline().addLast(executor, "format", GoogleDriveBundleEncoder.create(filename, gdriveAccessToken)); break; default: ctx.pipeline().addLast(executor, "format", DelimitedBundleEncoder.create(filename, format)); break; } ctx.pipeline().addLast(executor, "mqm", queryToQueryResultsEncoder); return ctx.pipeline().write(query, new DefaultChannelProgressivePromise(ctx.channel(), executor)); }
From source file:com.addthis.hydra.query.loadbalance.NextQueryTask.java
License:Apache License
@Override public void run() { QueryRequest request;// w w w . j a va2s. c om try { request = queryQueue.takeQuery(); } catch (InterruptedException ignored) { log.info("Frame reader thread interrupted -- halting query processing"); return; } try { final ChannelFuture queryFuture = HttpQueryCallHandler.handleQuery(request.querySource, request.kv, request.request, request.ctx, executor); queryFuture.addListener(this); queryFuture.channel().closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (queryFuture.cancel(false)) { log.warn("cancelling query due to closed output channel"); } } }); } catch (Exception e) { log.warn("Exception caught before mesh query master added to pipeline", e); if (request.ctx.channel().isActive()) { HttpUtils.sendError(request.ctx, new HttpResponseStatus(500, e.getMessage())); } } }
From source file:com.addthis.hydra.query.loadbalance.NextQueryTask.java
License:Apache License
private static void sendDetailedError(ChannelHandlerContext ctx, Throwable cause) { if (cause == null) { cause = new RuntimeException("query failed for unknown reasons"); }/*from w w w.j av a 2 s. co m*/ String reasonPhrase = cause.getMessage(); HttpResponseStatus responseStatus; try { responseStatus = new HttpResponseStatus(500, reasonPhrase); } catch (NullPointerException | IllegalArgumentException ignored) { reasonPhrase = cause.getClass().getSimpleName(); responseStatus = new HttpResponseStatus(500, reasonPhrase); } String detailPhrase = logAndFormatErrorDetail(cause); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, responseStatus, Unpooled.copiedBuffer(detailPhrase + "\r\n", CharsetUtil.UTF_8)); response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); log.trace("issuing error of {}", responseStatus); // Close the connection as soon as the error message is sent. ctx.channel().writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
From source file:com.addthis.hydra.query.tracker.DetailedStatusHandler.java
License:Apache License
private void onFailure(Throwable cause) { if (ctx.channel().isActive()) { HttpUtils.sendError(ctx, new HttpResponseStatus(500, cause.getMessage())); }/*from w w w . j a va 2s . com*/ }
From source file:com.addthis.hydra.query.web.HttpQueryCallHandler.java
License:Apache License
/** * special handler for query/*w w w. jav a 2s. co m*/ */ public static ChannelFuture handleQuery(ChannelHandler queryToQueryResultsEncoder, KVPairs kv, HttpRequest request, ChannelHandlerContext ctx, EventExecutor executor) throws Exception { String job = kv.getValue("job"); // support either job=id/dir or job=id&dir=dir for convenience (and don't punish doing both) String dir = kv.getValue("dir"); if ((dir != null) && !job.endsWith(dir)) { String[] jobs = job.split(","); String[] dirs = dir.split(","); job = Arrays.stream(jobs).flatMap(subJob -> Arrays.stream(dirs).map(subDir -> subJob + '/' + subDir)) .collect(Collectors.joining(",")); } String path = kv.getValue("path", kv.getValue("q", "")); Query query = new Query(job, new String[] { path }, new String[] { kv.getValue("ops"), kv.getValue("rops") }); query.setTraced(kv.getIntValue("trace", 0) == 1); query.setParameterIfNotYetSet("hosts", kv.getValue("hosts")); query.setParameterIfNotYetSet("gate", kv.getValue("gate")); query.setParameterIfNotYetSet("originalrequest", kv.getValue("originalrequest")); SocketAddress remoteIP = ctx.channel().remoteAddress(); if (remoteIP instanceof InetSocketAddress) { // only log implementations with known methods query.setParameterIfNotYetSet("remoteip", ((InetSocketAddress) remoteIP).getAddress().getHostAddress()); } query.setParameterIfNotYetSet("allocator", kv.getValue("allocator")); query.setParameterIfNotYetSet("allowPartial", kv.getValue("allowPartial")); query.setParameterIfNotYetSet("tasks", kv.getValue("tasks")); String filename = kv.getValue("filename", "query"); String format = kv.getValue("format", "json"); String gdriveAccessToken = kv.getValue("accesstoken"); int timeout = Math.min(kv.getIntValue("timeout", maxQueryTime), maxQueryTime); query.setParameterIfNotYetSet("timeout", timeout); query.setParameter("sender", kv.getValue("sender")); query.setParameter("injectSource", kv.getValue("injectSource")); if (log.isDebugEnabled()) { log.debug(new StringMapHelper().put("type", "query.starting").put("query.path", query.getPaths()[0]) .put("query.hosts", query.getParameter("hosts")).put("query.ops", query.getOps()) .put("trace", query.isTraced()).put("sources", query.getParameter("sources")) .put("time", System.currentTimeMillis()).put("job.id", query.getJob()) .put("query.id", query.uuid()).put("sender", query.getParameter("sender")).put("format", format) .put("filename", filename).put("originalrequest", query.getParameter("originalrequest")) .put("timeout", query.getParameter("timeout")).put("requestIP", query.getParameter("remoteip")) .put("allocator", query.getParameter("allocator")) .put("allowPartial", query.getParameter("allowPartial")) .put("tasks", query.getParameter("tasks")).createKVPairs().toString()); } // support legacy async query semantics query = LegacyHandler.handleQuery(query, kv, request, ctx); if (query == null) { return ctx.newSucceededFuture(); } if (query.getJob() == null) { sendError(ctx, new HttpResponseStatus(500, "missing job")); return ctx.newSucceededFuture(); } switch (format) { case "json": ctx.pipeline().addLast(executor, "format", new JsonBundleEncoder()); break; case "html": ctx.pipeline().addLast(executor, "format", new HtmlBundleEncoder()); break; case "gdrive": ctx.pipeline().addLast(executor, "stringer", stringer); ctx.pipeline().addLast(executor, "format", GoogleDriveBundleEncoder.create(filename, gdriveAccessToken)); break; case "csv2": case "psv2": case "tsv2": ctx.pipeline().addLast(executor, "format", DelimitedEscapedBundleEncoder.create(filename, format)); break; default: ctx.pipeline().addLast(executor, "format", DelimitedBundleEncoder.create(filename, format)); break; } ctx.pipeline().addLast(executor, "mqm", queryToQueryResultsEncoder); return ctx.pipeline().write(query, new DefaultChannelProgressivePromise(ctx.channel(), executor)); }
From source file:com.addthis.hydra.query.web.HttpQueryHandler.java
License:Apache License
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { log.warn("Exception caught while serving http query endpoint", cause); if (ctx.channel().isActive()) { sendError(ctx, new HttpResponseStatus(500, cause.getMessage())); }/*from w ww .j av a 2 s .co m*/ }
From source file:com.chenyang.proxy.http.HttpUserAgentTunnelHandler.java
License:Apache License
@Override public void channelRead(final ChannelHandlerContext uaChannelCtx, Object msg) throws Exception { if (msg instanceof HttpRequest) { // Channel uaChannel = uaChannelCtx.channel(); // connect remote Bootstrap bootstrap = new Bootstrap(); bootstrap.group(uaChannelCtx.channel().eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option(ChannelOption.AUTO_READ, false) .handler(new HttpTunnelChannelInitializer(uaChannelCtx.channel())); final HttpRemote apnProxyRemote = uaChannelCtx.channel().attr(HttpConnectionAttribute.ATTRIBUTE_KEY) .get().getRemote();/*from w ww . ja v a2 s.c o m*/ bootstrap .connect(apnProxyRemote.getInetSocketAddress(), new InetSocketAddress(NetworkUtils.getCyclicLocalIp().getHostAddress(), 0)) .addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future1) throws Exception { if (future1.isSuccess()) { HttpResponse proxyConnectSuccessResponse = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, new HttpResponseStatus(200, "Connection established")); uaChannelCtx.writeAndFlush(proxyConnectSuccessResponse) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future2) throws Exception { // remove handlers uaChannelCtx.pipeline().remove("codec"); uaChannelCtx.pipeline().remove(HttpPreHandler.HANDLER_NAME); uaChannelCtx.pipeline() .remove(HttpUserAgentTunnelHandler.HANDLER_NAME); uaChannelCtx.pipeline() .addLast(new HttpRelayHandler( "UA --> " + apnProxyRemote.getRemoteAddr(), future1.channel())); } }); } else { if (uaChannelCtx.channel().isActive()) { uaChannelCtx.channel().writeAndFlush(Unpooled.EMPTY_BUFFER) .addListener(ChannelFutureListener.CLOSE); } } } }); } ReferenceCountUtil.release(msg); }
From source file:com.couchbase.client.core.endpoint.config.ConfigHandlerTest.java
License:Apache License
@Test public void shouldDecodeSuccessBucketConfigResponse() throws Exception { HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1, new HttpResponseStatus(200, "OK")); HttpContent responseChunk1 = new DefaultHttpContent(Unpooled.copiedBuffer("foo", CHARSET)); HttpContent responseChunk2 = new DefaultLastHttpContent(Unpooled.copiedBuffer("bar", CHARSET)); BucketConfigRequest requestMock = mock(BucketConfigRequest.class); requestQueue.add(requestMock);/* www . j av a2s . co m*/ channel.writeInbound(responseHeader, responseChunk1, responseChunk2); channel.readInbound(); assertEquals(1, eventSink.responseEvents().size()); BucketConfigResponse event = (BucketConfigResponse) eventSink.responseEvents().get(0).getMessage(); assertEquals(ResponseStatus.SUCCESS, event.status()); assertEquals("foobar", event.config()); assertTrue(requestQueue.isEmpty()); }
From source file:com.couchbase.client.core.endpoint.config.ConfigHandlerTest.java
License:Apache License
@Test public void shouldDecodeAuthFailureBucketConfigResponse() throws Exception { HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1, new HttpResponseStatus(401, "Unauthorized")); HttpContent responseChunk = LastHttpContent.EMPTY_LAST_CONTENT; BucketConfigRequest requestMock = mock(BucketConfigRequest.class); requestQueue.add(requestMock);//www .java2 s. c om channel.writeInbound(responseHeader, responseChunk); assertEquals(1, eventSink.responseEvents().size()); BucketConfigResponse event = (BucketConfigResponse) eventSink.responseEvents().get(0).getMessage(); assertEquals(ResponseStatus.FAILURE, event.status()); assertEquals("Unauthorized", event.config()); assertTrue(requestQueue.isEmpty()); }