List of usage examples for io.netty.channel ChannelFutureListener CLOSE
ChannelFutureListener CLOSE
To view the source code for io.netty.channel ChannelFutureListener CLOSE.
Click Source Link
From source file:com.mapple.http.HttpHelloWorldServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; if (HttpUtil.is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); }//from www . j a v a2 s. c o m QueryStringDecoder decoder = new QueryStringDecoder(req.uri()); List<String> close = decoder.parameters().get("close"); int pos = -1; if (close != null && close.size() > 0) { pos = Integer.valueOf(close.get(0)); } StringBuilder body = new StringBuilder(); ConcurrentSet<Channel> proxyList = ForwardLoginHandler.INSTANCE.proxyList(); int i = 0; AttributeKey<ForwardLogin> Session = AttributeKey.valueOf("Session"); Iterator<Channel> it = proxyList.iterator(); while (it.hasNext()) { Channel ch = it.next(); ForwardLogin p = ch.attr(Session).get(); body.append(i + 1); body.append(" "); body.append(p.getUserName()); body.append(" "); body.append( p.getProvince() + (p.getCity() == null ? "" : p.getCity()) + "[" + p.getProvince2() + "]"); body.append(" "); body.append(p.getRemoteAddr() + ":" + p.getRemotePort()); body.append(" "); body.append(p.getCarrier()); body.append(" "); if (ch instanceof SocketChannel) { body.append("TCP"); } else { body.append("UDT"); } if (i++ == pos) { body.append(" [CLOSED]"); ch.writeAndFlush(new ForwardForceClose()); } body.append("\n"); } String data = body.toString(); if (data.isEmpty()) { data = "?"; } // boolean keepAlive = HttpUtil.isKeepAlive(req); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(data.getBytes(CharsetUtil.UTF_8))); response.headers().set(CONTENT_TYPE, "text/plain; charset=utf-8"); response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes()); // if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); // } else { // response.headers().set(CONNECTION, KEEP_ALIVE); // ctx.write(response); // } } }
From source file:com.mastfrog.acteur.Acteur.java
License:Open Source License
/** * Set a ChannelFutureListener which will be called after headers are * written and flushed to the socket; prefer * <code>setResponseWriter()</code> to this method unless you are not using * chunked encoding and want to stream your response (in which case, be sure * to setChunked(false) or you will have encoding errors). * * @param listener/* w w w .j a va 2s.c om*/ */ public final void setResponseBodyWriter(final ChannelFutureListener listener) { if (listener == ChannelFutureListener.CLOSE || listener == ChannelFutureListener.CLOSE_ON_FAILURE) { getResponse().setBodyWriter(listener); return; } final Page p = Page.get(); final Application app = p.getApplication(); class WL implements ChannelFutureListener, Callable<Void> { private ChannelFuture future; private Callable<Void> wrapper = app.getRequestScope().wrap(this); @Override public void operationComplete(ChannelFuture future) throws Exception { this.future = future; wrapper.call(); } @Override public Void call() throws Exception { listener.operationComplete(future); return null; } @Override public String toString() { return "Scope wrapper for " + listener; } } getResponse().setBodyWriter(new WL()); }
From source file:com.mastfrog.acteur.Application.java
License:Open Source License
protected void send404(RequestID id, Event<?> event, Channel channel) { HttpResponse response = createNotFoundResponse(event); onBeforeRespond(id, event, response.getStatus()); ChannelFutureListener closer = !ResponseImpl.isKeepAlive(event) ? ChannelFutureListener.CLOSE : null; ChannelFuture fut = channel.writeAndFlush(response); if (closer != null) { fut.addListener(closer);//from w ww . j ava 2 s . c o m } }
From source file:com.mastfrog.acteur.auth.AuthenticateBasicActeur.java
License:Open Source License
@Benchmark(value = "failedAuthentication", publish = Kind.CALL_COUNT) private void unauthorized(Realm realm, HttpEvent evt, AuthenticationDecorator decorator, Page page, Response response) {/*from w w w.ja v a 2s . c o m*/ decorator.onAuthenticationFailed(null, page, response); add(Headers.WWW_AUTHENTICATE, realm); setState(new RespondWith(HttpResponseStatus.UNAUTHORIZED)); setResponseBodyWriter(ChannelFutureListener.CLOSE); }
From source file:com.mastfrog.acteur.CheckIfNoneMatchHeader.java
@Inject CheckIfNoneMatchHeader(HttpEvent event, Page page) throws Exception { Checks.notNull("event", event); Checks.notNull("page", page); String etag = event.getHeader(Headers.IF_NONE_MATCH); String pageEtag = page.getResponseHeaders().getETag(); if (etag != null && pageEtag != null) { if (etag.equals(pageEtag)) { setState(new RespondWith(HttpResponseStatus.NOT_MODIFIED)); // XXX workaround for peculiar problem with FileResource = // not modified responses are leaving a hanging connection setResponseBodyWriter(ChannelFutureListener.CLOSE); return; }// w w w.j a va 2s . c o m } setState(new ConsumedState()); }
From source file:com.mastfrog.acteur.ResponseImpl.java
License:Open Source License
public HttpResponse toResponse(Event<?> evt, Charset charset) { if (!canHaveBody(getResponseCode()) && (message != null || listener != null)) { if (listener != ChannelFutureListener.CLOSE) { System.err.println(evt + " attempts to attach a body to " + getResponseCode() + " which cannot have one: " + message + " - " + listener); }//from w w w. j a v a 2 s. c o m } String msg = getMessage(); HttpResponse resp; if (msg != null) { ByteBuf buf = Unpooled.copiedBuffer(msg, charset); long size = buf.readableBytes(); add(Headers.CONTENT_LENGTH, size); DefaultFullHttpResponse r = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, getResponseCode(), buf); resp = r; } else { resp = new HackHttpResponse(getResponseCode(), this.status == NOT_MODIFIED ? false : chunked); } for (Entry<?> e : headers) { // Remove things which cause problems for non-modified responses - // browsers will hold the connection open regardless if (this.status == NOT_MODIFIED) { if (e.decorator == Headers.CONTENT_LENGTH) { continue; } else if (HttpHeaders.Names.CONTENT_ENCODING.equals(e.decorator.name())) { continue; } else if ("Transfer-Encoding".equals(e.decorator.name())) { continue; } } e.write(resp); } return resp; }
From source file:com.mastfrog.acteur.ResponseImpl.java
License:Open Source License
ChannelFuture sendMessage(Event<?> evt, ChannelFuture future, HttpMessage resp) { if (listener != null) { future = future.addListener(listener); return future; } else if (!isKeepAlive(evt)) { future = future.addListener(ChannelFutureListener.CLOSE); }//from w w w .ja v a 2 s. c o m return future; }
From source file:com.mastfrog.tinymavenproxy.GetActeur.java
License:Open Source License
@Inject GetActeur(HttpEvent req, Deferral def, Config config, FileFinder finder, Closables clos, Downloader dl, @Named(ACCESS_LOGGER) Logger accessLog, RequestID id) throws FileNotFoundException { if ("true".equals(req.getParameter("browse")) || "true".equals(req.getParameter("index"))) { reject();/*from w w w. j ava 2 s . c o m*/ return; } Path path = req.getPath(); if (path.size() == 0) { reject(); return; } if (path.toString().contains("..")) { setState(new RespondWith(Err.badRequest("Relative paths not allowed"))); return; } File file = finder.find(path); if (file != null) { try (Log<?> log = accessLog.info("fetch")) { log.add("path", path).add("id", id).add("cached", true); add(Headers.LAST_MODIFIED, new DateTime(file.lastModified())); setState(new RespondWith(HttpResponseStatus.OK)); add(Headers.CONTENT_TYPE, findMimeType(path)); if (req.getMethod() != HEAD) { setResponseBodyWriter(new FileWriter(file, clos)); } } } else { if (dl.isFailedPath(path)) { setState(new RespondWith(404)); setResponseBodyWriter(ChannelFutureListener.CLOSE); return; } setChunked(true); final Resumer r = def.defer(); ChannelFutureListener l = dl.download(path, id, new DownloadReceiverImpl(r)); req.getChannel().closeFuture().addListener(l); next(); } }
From source file:com.miko.s4netty.handler.WorkerProviderHandler.java
License:Open Source License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; if (is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); }// w w w. j a v a 2s .co m boolean keepAlive = isKeepAlive(req); logger.debug("channelRead keepAlive= " + keepAlive); Gson gson = new Gson(); List<CarDTO> carList = simpleCarService.getAll(); Map<String, List<CarDTO>> byMake = simpleCarService.getAll().stream() .collect(Collectors.groupingBy(CarDTO::getMake)); System.out.println("byMake = " + byMake); System.out.println("byMake Skoda= " + byMake.get("Skoda").iterator().next().getModel()); JsonElement element = gson.toJsonTree(carList, new TypeToken<List<CarDTO>>() { }.getType()); JsonArray jsonArray = element.getAsJsonArray(); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(jsonArray.toString().getBytes())); response.headers().set(CONTENT_TYPE, "application/json"); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); //ignoring KeepAlive ctx.write(response).addListener(ChannelFutureListener.CLOSE); } }
From source file:com.mpush.common.message.BaseMessage.java
License:Apache License
public void close() { send(ChannelFutureListener.CLOSE); }