@Override public void exceptionCaught(ChannelHandlerContext context, Throwable cause) { LOG.error(cause.getMessage(), cause); if (context.channel().isOpen()) { context.channel().close(); } }
@Override public final boolean trySend(WebDataMessage message) { if (!message.isBinary()) ctx.writeAndFlush(new TextWebSocketFrame(message.getStringBody())); else ctx.writeAndFlush( new BinaryWebSocketFrame(Unpooled.wrappedBuffer(message.getByteBufferBody()))); return true; }
@Override protected final void die(Throwable cause) { super.die(cause); if (ctx.channel().isOpen()) ctx.close(); // Ensure to release server references userActor = null; ctx = null; }
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { // Check for closing frame if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); return; } if (frame instanceof PingWebSocketFrame) { ctx.channel().writeAndFlush(new PongWebSocketFrame(frame.content().retain())); return; } if (frame instanceof ContinuationWebSocketFrame) return; if (frame instanceof TextWebSocketFrame) webSocketActor.onMessage(((TextWebSocketFrame) frame).text()); else webSocketActor.onMessage(frame.content().nioBuffer()); }
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (!isIgnorableException(cause)) { cause.printStackTrace(); if (ctx.channel().isActive()) { sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR); } } }
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (!(msg instanceof FullHttpRequest)) { Action<Object> subscriber = channelSubscriptions.get(ctx.channel()); if (subscriber != null) { subscriber.execute(msg); return; } } super.channelRead(ctx, msg); }
private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) { FullHttpResponse response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, status, Unpooled.copiedBuffer("Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8)); response.headers().set(HttpHeaderConstants.CONTENT_TYPE, "text/plain; charset=UTF-8"); // Close the connection as soon as the error message is sent. ctx.write(response).addListener(ChannelFutureListener.CLOSE); }
@Override public final boolean trySend(WebDataMessage res) { final ByteBuf buf; final String stringBody = res.getStringBody(); if (stringBody != null) { byte[] bs = stringBody.getBytes(encoding); buf = Unpooled.wrappedBuffer(bs); } else { buf = Unpooled.wrappedBuffer(res.getByteBufferBody()); } ctx.writeAndFlush(buf); return true; }
private void processGet(ChannelHandlerContext context, FullHttpRequest request) { try { File file = getRequestedFile(request.getUri()); RandomAccessFile raf = new RandomAccessFile(file, "r"); long fileLength = raf.length(); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); HttpHeaders.setContentLength(response, fileLength); setContentTypeHeader(response, file); context.write(response); context.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength)); // Write the end marker. ChannelFuture future = context.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); future.addListener(ChannelFutureListener.CLOSE); } catch (IOException | URISyntaxException e) { context.writeAndFlush(getBadRequest(e.getMessage())); } }
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (cause instanceof ReadTimeoutException) { LOG.warn(cause.getMessage(), cause); } else { LOG.error("Fetch failed :", cause); } // this fetching will be retry IOUtils.cleanup(LOG, fc, raf); finishTime = System.currentTimeMillis(); state = TajoProtos.FetcherState.FETCH_FAILED; ctx.close(); }
private static void writeHttpResponse( ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res, Boolean close) { if (!omitDateHeader && !res.headers().contains(DefaultHttpHeaders.Names.DATE)) DefaultHttpHeaders.addDateHeader(res, DefaultHttpHeaders.Names.DATE, new Date()); // Send the response and close the connection if necessary. if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200 || close == null || close) { res.headers().set(CONNECTION, HttpHeaders.Values.CLOSE); ctx.writeAndFlush(res).addListener(ChannelFutureListener.CLOSE); } else { res.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); write(ctx, res); } }
@Override protected void channelRead0(ChannelHandlerContext context, FullHttpRequest request) throws Exception { if (request.getMethod().equals(HttpMethod.HEAD)) { processHead(context, request); } else if (request.getMethod().equals(HttpMethod.GET)) { processGet(context, request); } else { // error String msg = "Not supported method: " + request.getMethod(); LOG.error(msg); context.writeAndFlush(getBadRequest(msg)); } }
/** {@inheritDoc} */ @Override public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; trackingType = setTrackingType(request); } if (msg instanceof HttpContent) { // New chunk is received HttpContent chunk = (HttpContent) msg; requestContent.append(chunk.content().toString(Charset.defaultCharset())); if (chunk instanceof LastHttpContent) { // All chunks have been received ResultTO resultTO = submitPayload(requestContent.toString()); responseContent.append(gson.toJson(resultTO)); writeResponse(ctx.channel()); reset(); } } }
private void processHead(ChannelHandlerContext context, FullHttpRequest request) { HttpHeaders headers = request.headers(); FullHttpResponse response = null; if (headers.contains(Names.CONTENT_LENGTH)) { try { File file = getRequestedFile(request.getUri()); response = new DefaultFullHttpResponse( HTTP_1_1, request.getDecoderResult().isSuccess() ? OK : BAD_REQUEST); HttpHeaders.setContentLength(response, file.length()); } catch (FileNotFoundException | URISyntaxException e) { response = getBadRequest(e.getMessage()); } } context.writeAndFlush(response); }
public void messageReceived(ChannelHandlerContext ctx, Object o) throws Exception { if (o instanceof HttpRequest) { // DefaultHttpRequest ) { queue.add((HttpRequest) o); } else if (o instanceof LastHttpContent) { HttpRequest req = queue.remove(); req.getMethod(); req.getUri(); req.headers(); LastHttpContent content = (LastHttpContent) o; ByteBuf buf = content.content(); if (buf.readableBytes() > 0) { Gson gson = GsonFactory.createBuilder().create(); Reader in = new InputStreamReader(new ByteBufInputStream(buf), "utf-8"); Object v = gson.fromJson(in, Class.forName("com.logbook.logbook.resources.logs.LogEntryDTO")); System.out.println("v = " + v); } System.out.println( req.getMethod() + " " + req.getUri() + " -- " + buf.readableBytes() + " bytes"); HttpResponse r = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); r.headers().add("Content-Length", "0"); ctx.write(r); } else { System.out.println("o = " + o + " : " + o.getClass()); } }
@Override public final boolean trySend(HttpResponse message) { try { final HttpRequestWrapper nettyRequest = (HttpRequestWrapper) message.getRequest(); final FullHttpRequest req = nettyRequest.req; final ChannelHandlerContext ctx = nettyRequest.ctx; final HttpResponseStatus status = HttpResponseStatus.valueOf(message.getStatus()); if (message.getStatus() >= 400 && message.getStatus() < 600) { sendHttpResponse( ctx, req, new DefaultFullHttpResponse(req.getProtocolVersion(), status), false); close(); return true; } if (message.getRedirectPath() != null) { sendHttpRedirect(ctx, req, message.getRedirectPath()); close(); return true; } FullHttpResponse res; if (message.getStringBody() != null) res = new DefaultFullHttpResponse( req.getProtocolVersion(), status, Unpooled.wrappedBuffer(message.getStringBody().getBytes())); else if (message.getByteBufferBody() != null) res = new DefaultFullHttpResponse( req.getProtocolVersion(), status, Unpooled.wrappedBuffer(message.getByteBufferBody())); else res = new DefaultFullHttpResponse(req.getProtocolVersion(), status); if (message.getCookies() != null) { final ServerCookieEncoder enc = ServerCookieEncoder.STRICT; for (final Cookie c : message.getCookies()) HttpHeaders.setHeader(res, COOKIE, enc.encode(getNettyCookie(c))); } if (message.getHeaders() != null) { for (final Map.Entry<String, String> h : message.getHeaders().entries()) HttpHeaders.setHeader(res, h.getKey(), h.getValue()); } if (message.getContentType() != null) { String ct = message.getContentType(); if (message.getCharacterEncoding() != null) ct = ct + "; charset=" + message.getCharacterEncoding().name(); HttpHeaders.setHeader(res, CONTENT_TYPE, ct); } final boolean sseStarted = message.shouldStartActor(); if (trackSession(sseStarted)) { final String sessionId = UUID.randomUUID().toString(); res.headers() .add(SET_COOKIE, ServerCookieEncoder.STRICT.encode(SESSION_COOKIE_KEY, sessionId)); startSession(sessionId, actorContext); } if (!sseStarted) { final String stringBody = message.getStringBody(); long contentLength = 0L; if (stringBody != null) contentLength = stringBody.getBytes().length; else { final ByteBuffer byteBufferBody = message.getByteBufferBody(); if (byteBufferBody != null) contentLength = byteBufferBody.remaining(); } res.headers().add(CONTENT_LENGTH, contentLength); } final HttpStreamActorAdapter httpStreamActorAdapter; if (sseStarted) // This will copy the request content, which must still be referenceable, doing before the // request handler // unallocates it (unfortunately it is explicitly reference-counted in Netty) httpStreamActorAdapter = new HttpStreamActorAdapter(ctx, req); else httpStreamActorAdapter = null; sendHttpResponse(ctx, req, res, false); if (sseStarted) { if (httpResponseEncoderName != null) { ctx.pipeline().remove(httpResponseEncoderName); } else { final ChannelPipeline pl = ctx.pipeline(); final List<String> handlerKeysToBeRemoved = new ArrayList<>(); for (final Map.Entry<String, ChannelHandler> e : pl) { if (e.getValue() instanceof HttpResponseEncoder) handlerKeysToBeRemoved.add(e.getKey()); } for (final String k : handlerKeysToBeRemoved) pl.remove(k); } try { message.getFrom().send(new HttpStreamOpened(httpStreamActorAdapter.ref(), message)); } catch (SuspendExecution e) { throw new AssertionError(e); } } return true; } finally { if (actor != null) actor.unwatch(); } }
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { logger.warn(responseContent.toString(), cause); ctx.channel().close(); }
public void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest nettyRequest) throws Exception { if (!nettyRequest.getDecoderResult().isSuccess()) { sendError(ctx, HttpResponseStatus.BAD_REQUEST); return; } final long startTime = System.nanoTime(); final Request request = new DefaultRequest( new NettyHeadersBackedHeaders(nettyRequest.headers()), nettyRequest.getMethod().name(), nettyRequest.getUri(), nettyRequest.content()); final Channel channel = ctx.channel(); final DefaultMutableStatus responseStatus = new DefaultMutableStatus(); final HttpHeaders httpHeaders = new DefaultHttpHeaders(false); final MutableHeaders responseHeaders = new NettyHeadersBackedMutableHeaders(httpHeaders); FileHttpTransmitter fileHttpTransmitter = new DefaultFileHttpTransmitter( nettyRequest, httpHeaders, channel, compressResponses, addResponseTimeHeader ? startTime : -1); final DefaultEventController<RequestOutcome> requestOutcomeEventController = new DefaultEventController<>(); // We own the lifecycle nettyRequest.content().retain(); final Response response = new DefaultResponse( responseStatus, responseHeaders, fileHttpTransmitter, ctx.alloc(), new Action<ByteBuf>() { @Override public void execute(final ByteBuf byteBuf) throws Exception { final HttpResponse nettyResponse = new CustomHttpResponse(responseStatus.getResponseStatus(), httpHeaders); nettyRequest.content().release(); responseHeaders.set(HttpHeaderConstants.CONTENT_LENGTH, byteBuf.writerIndex()); boolean shouldClose = true; if (channel.isOpen()) { if (isKeepAlive(nettyRequest)) { responseHeaders.set( HttpHeaderConstants.CONNECTION, HttpHeaderConstants.KEEP_ALIVE); shouldClose = false; } long stopTime = System.nanoTime(); if (addResponseTimeHeader) { responseHeaders.set( "X-Response-Time", NumberUtil.toMillisDiffString(startTime, stopTime)); } execController.getExecution().complete(); channel.writeAndFlush(nettyResponse); channel.write(new DefaultHttpContent(byteBuf)); ChannelFuture future = channel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); if (requestOutcomeEventController.isHasListeners()) { Headers headers = new DelegatingHeaders(responseHeaders); Status status = new DefaultStatus(responseStatus.getCode(), responseStatus.getMessage()); SentResponse sentResponse = new DefaultSentResponse(headers, status); RequestOutcome requestOutcome = new DefaultRequestOutcome( request, sentResponse, System.currentTimeMillis()); requestOutcomeEventController.fire(requestOutcome); } if (shouldClose) { future.addListener(ChannelFutureListener.CLOSE); } } } }); InetSocketAddress socketAddress = (InetSocketAddress) channel.localAddress(); final BindAddress bindAddress = new InetSocketAddressBackedBindAddress(socketAddress); Action<Action<Object>> subscribeHandler = new Action<Action<Object>>() { @Override public void execute(Action<Object> thing) throws Exception { channelSubscriptions.put(channel, thing); channel .closeFuture() .addListener( new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { channelSubscriptions.remove(channel); } }); } }; final DirectChannelAccess directChannelAccess = new DefaultDirectChannelAccess(channel, subscribeHandler); execController.start( new Action<Execution>() { @Override public void execute(Execution execution) throws Exception { DefaultContext.RequestConstants requestConstants = new DefaultContext.RequestConstants( applicationConstants, bindAddress, request, response, directChannelAccess, requestOutcomeEventController.getRegistry(), execution); new DefaultContext(requestConstants, registry, handlers, 0, return404).next(); } }); }
public void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest nettyRequest) throws Exception { if (!nettyRequest.getDecoderResult().isSuccess()) { sendError(ctx, HttpResponseStatus.BAD_REQUEST); return; } final long startTime = addResponseTimeHeader ? System.nanoTime() : 0; final Request request = new DefaultRequest( new NettyHeadersBackedHeaders(nettyRequest.headers()), nettyRequest.getMethod().name(), nettyRequest.getUri(), nettyRequest.content()); final Channel channel = ctx.channel(); final DefaultMutableStatus responseStatus = new DefaultMutableStatus(); final HttpHeaders nettyHeaders = new DefaultHttpHeaders(false); final MutableHeaders responseHeaders = new NettyHeadersBackedMutableHeaders(nettyHeaders); final MimeTypes mimeTypes = registry.get(MimeTypes.class); final DefaultEventController<RequestOutcome> requestOutcomeEventController = new DefaultEventController<>(); final AtomicBoolean transmitted = new AtomicBoolean(false); final ResponseTransmitter responseTransmitter = new DefaultResponseTransmitter( transmitted, channel, nettyRequest, request, nettyHeaders, responseStatus, requestOutcomeEventController, startTime); final Action<Action<? super ResponseTransmitter>> responseTransmitterWrapper = Actions.wrap(responseTransmitter); final FileHttpTransmitter fileHttpTransmitter = new DefaultFileHttpTransmitter( nettyHeaders, mimeTypes, compressResponses, compressionMinSize, compressionMimeTypeWhiteList, compressionMimeTypeBlackList, responseTransmitterWrapper); StreamTransmitter streamTransmitter = new DefaultStreamTransmitter(nettyRequest, nettyHeaders, channel); final Response response = new DefaultResponse( responseStatus, responseHeaders, fileHttpTransmitter, streamTransmitter, ctx.alloc(), new Action<ByteBuf>() { @Override public void execute(final ByteBuf byteBuf) throws Exception { responseTransmitterWrapper.execute( new Action<ResponseTransmitter>() { @Override public void execute(ResponseTransmitter responseTransmitter) throws Exception { nettyHeaders.set(HttpHeaders.Names.CONTENT_LENGTH, byteBuf.writerIndex()); responseTransmitter.transmit(new DefaultHttpContent(byteBuf)); } }); } }); InetSocketAddress socketAddress = (InetSocketAddress) channel.localAddress(); final BindAddress bindAddress = new InetSocketAddressBackedBindAddress(socketAddress); Action<Action<Object>> subscribeHandler = new Action<Action<Object>>() { @Override public void execute(Action<Object> thing) throws Exception { transmitted.set(true); channelSubscriptions.put(channel, thing); channel .closeFuture() .addListener( new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { channelSubscriptions.remove(channel); } }); } }; final DirectChannelAccess directChannelAccess = new DefaultDirectChannelAccess(channel, subscribeHandler); final DefaultContext.RequestConstants requestConstants = new DefaultContext.RequestConstants( applicationConstants, bindAddress, request, response, directChannelAccess, requestOutcomeEventController.getRegistry()); DefaultContext.start( execController.getControl(), requestConstants, registry, handlers, return404, new Action<Execution>() { @Override public void execute(Execution execution) throws Exception { if (!transmitted.get()) { Handler lastHandler = requestConstants.handler; StringBuilder description = new StringBuilder(); description .append("No response sent for ") .append(request.getMethod().getName()) .append(" request to ") .append(request.getUri()) .append(" (last handler: "); if (lastHandler instanceof DescribingHandler) { ((DescribingHandler) lastHandler).describeTo(description); } else { DescribingHandlers.describeTo(lastHandler, description); } description.append(")"); String message = description.toString(); LOGGER.warn(message); response.status(500); if (launchConfig.isDevelopment()) { response.send(message); } else { response.send(); } } } }); }
private static ChannelFuture write(ChannelHandlerContext ctx, Object res) { return ctx.writeAndFlush(res); // : ctx.write(res); }
@Override public final void close() { if (ctx.channel().isOpen()) ctx.close(); if (actor != null) actor.die(null); }
@Override public final void channelReadComplete(ChannelHandlerContext ctx) { ctx.flush(); }
@Override public final void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { if (ctx.channel().isOpen()) ctx.close(); log.error("Exception caught", cause); }
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws SuspendExecution { // Handle a bad request. if (!req.getDecoderResult().isSuccess()) { sendHttpResponse( ctx, req, new DefaultFullHttpResponse(req.getProtocolVersion(), BAD_REQUEST), false); return; } final String uri = req.getUri(); final Context actorCtx = selector.get(ctx, req); assert actorCtx != null; final ReentrantLock lock = actorCtx.getLock(); assert lock != null; lock.lock(); try { final ActorRef<? extends WebMessage> userActorRef = actorCtx.getRef(); ActorImpl internalActor = (ActorImpl) actorCtx.getAttachments().get(ACTOR_KEY); if (userActorRef != null) { if (actorCtx.handlesWithWebSocket(uri)) { if (internalActor == null || !(internalActor instanceof WebSocketActorAdapter)) { //noinspection unchecked webSocketActor = new WebSocketActorAdapter(ctx, (ActorRef<? super WebMessage>) userActorRef); addActorToContextAndUnlock(actorCtx, webSocketActor, lock); } // Handshake final WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(uri, null, true); handshaker = wsFactory.newHandshaker(req); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } else { @SuppressWarnings("unchecked") final ActorRef<WebMessage> userActorRef0 = (ActorRef<WebMessage>) webSocketActor.userActor; handshaker .handshake(ctx.channel(), req) .addListener( new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(ChannelFuture future) throws Exception { FiberUtil.runInFiber( new SuspendableRunnable() { @Override public void run() throws SuspendExecution, InterruptedException { userActorRef0.send( new WebSocketOpened(WebActorHandler.this.webSocketActor.ref())); } }); } }); } return; } else if (actorCtx.handlesWithHttp(uri)) { if (internalActor == null || !(internalActor instanceof HttpActorAdapter)) { //noinspection unchecked internalActor = new HttpActorAdapter( (ActorRef<HttpRequest>) userActorRef, actorCtx, httpResponseEncoderName); addActorToContextAndUnlock(actorCtx, internalActor, lock); } //noinspection unchecked ((HttpActorAdapter) internalActor).service(ctx, req); return; } } } finally { if (lock.isHeldByCurrentStrand() && lock.isLocked()) lock.unlock(); } sendHttpResponse( ctx, req, new DefaultFullHttpResponse(req.getProtocolVersion(), NOT_FOUND), false); }