List of usage examples for io.netty.channel ChannelHandlerContext executor
EventExecutor executor();
From source file:io.werval.server.netty.WervalHttpHandler.java
License:Apache License
private ChannelFuture writeOutcome(ChannelHandlerContext nettyContext, Outcome outcome) { // == Build the Netty Response ResponseHeader responseHeader = outcome.responseHeader(); // Netty Version & Status HttpVersion responseVersion = HttpVersion.valueOf(responseHeader.version().toString()); HttpResponseStatus responseStatus = HttpResponseStatus.valueOf(responseHeader.status().code()); // Netty Headers & Body output final HttpResponse nettyResponse; final ChannelFuture writeFuture; if (outcome instanceof ChunkedInputOutcome) { ChunkedInputOutcome chunkedOutcome = (ChunkedInputOutcome) outcome; nettyResponse = new DefaultHttpResponse(responseVersion, responseStatus); // Headers applyResponseHeader(responseHeader, nettyResponse); nettyResponse.headers().set(TRANSFER_ENCODING, CHUNKED); nettyResponse.headers().set(TRAILER, X_WERVAL_CONTENT_LENGTH); // Body/*from www .j ava 2 s. c om*/ nettyContext.write(nettyResponse); writeFuture = nettyContext.writeAndFlush(new HttpChunkedBodyEncoder( new ChunkedStream(chunkedOutcome.inputStream(), chunkedOutcome.chunkSize()))); } else if (outcome instanceof InputStreamOutcome) { InputStreamOutcome streamOutcome = (InputStreamOutcome) outcome; nettyResponse = new DefaultFullHttpResponse(responseVersion, responseStatus); // Headers applyResponseHeader(responseHeader, nettyResponse); nettyResponse.headers().set(CONTENT_LENGTH, streamOutcome.contentLength()); // Body try (InputStream bodyInputStream = streamOutcome.bodyInputStream()) { ((ByteBufHolder) nettyResponse).content().writeBytes(bodyInputStream, new BigDecimal(streamOutcome.contentLength()).intValueExact()); } catch (IOException ex) { throw new UncheckedIOException(ex); } writeFuture = nettyContext.writeAndFlush(nettyResponse); } else if (outcome instanceof SimpleOutcome) { SimpleOutcome simpleOutcome = (SimpleOutcome) outcome; byte[] body = simpleOutcome.body().asBytes(); nettyResponse = new DefaultFullHttpResponse(responseVersion, responseStatus); // Headers applyResponseHeader(responseHeader, nettyResponse); nettyResponse.headers().set(CONTENT_LENGTH, body.length); // Body ((ByteBufHolder) nettyResponse).content().writeBytes(body); writeFuture = nettyContext.writeAndFlush(nettyResponse); } else { LOG.warn("{} Unhandled Outcome type '{}', no response body.", requestIdentity, outcome.getClass()); nettyResponse = new DefaultFullHttpResponse(responseVersion, responseStatus); applyResponseHeader(responseHeader, nettyResponse); writeFuture = nettyContext.writeAndFlush(nettyResponse); } if (LOG.isTraceEnabled()) { LOG.trace("{} Sent a HttpResponse:\n{}", requestIdentity, nettyResponse.toString()); } // Close the connection as soon as the response is sent if not keep alive if (!outcome.responseHeader().isKeepAlive() || nettyContext.executor().isShuttingDown()) { writeFuture.addListener(ChannelFutureListener.CLOSE); } // Done! return writeFuture; }
From source file:net.anyflow.lannister.server.ScheduledExecutor.java
License:Apache License
@Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { int $sysPublisherInterval = Settings.SELF.getInt("annister.sys.intervalSeconds", 2); ctx.executor().scheduleAtFixedRate(new $SysPublisher(), 0, $sysPublisherInterval, TimeUnit.SECONDS); int sessionExpiratorInterval = Settings.SELF .getInt("lannister.sessionExpirationHandlerExecutionIntervalSeconds", 0); ctx.executor().scheduleAtFixedRate(new SessionExpirator(), 0, sessionExpiratorInterval, TimeUnit.SECONDS); }
From source file:net.anyflow.lannister.session.MessageSender.java
License:Apache License
private void completeInboundMessageStatuses() { ChannelHandlerContext ctx = Session.NEXUS.channelHandlerContext(session.clientId()); if (ctx == null) { return;//from www . j a v a2 s. com } ctx.executor().submit(() -> { Date now = new Date(); Stream<InboundMessageStatus> statuses = Topic.NEXUS.map().values().stream() .map(t -> t.inboundMessageStatuses()).flatMap(t -> t.values().stream()); statuses.forEach(s -> { long intervalSeconds = (now.getTime() - s.updateTime().getTime()) * 1000; if (intervalSeconds < RESPONSE_TIMEOUT_SECONDS) { return; } Topic topic = Topic.NEXUS.get(s.clientId(), s.messageId(), Topics.ClientType.PUBLISHER); Message message = topic.messages().get(s.messageId()); switch (s.status()) { case RECEIVED: case PUBRECED: if (message.qos() == MqttQoS.AT_LEAST_ONCE) { session.send(MessageFactory.puback(message.id())).addListener(f -> { // [MQTT-2.3.1-6] topic.removeInboundMessageStatus(session.clientId(), message.id()); logger.debug("Inbound message status REMOVED [clientId={}, messageId={}]", session.clientId(), message.id()); }); } else { session.send(MessageFactory.pubrec(message.id())) // [MQTT-2.3.1-6] .addListener(f -> topic.setInboundMessageStatus(session.clientId(), message.id(), InboundMessageStatus.Status.PUBRECED)); } break; default: logger.error("Invalid Outbound Message Status [status={}, clientId={}, topic={}, messageId={}]", s.status(), session.clientId(), message.topicName(), message.id()); break; } }); }); }
From source file:net.anyflow.lannister.session.MessageSender.java
License:Apache License
private void completeOutboundMessageStatuses() { ChannelHandlerContext ctx = Session.NEXUS.channelHandlerContext(session.clientId()); if (ctx == null) { return;/* w ww .j a v a2s. c o m*/ } ctx.executor().submit(() -> { Date now = new Date(); Stream<OutboundMessageStatus> statuses = Topic.NEXUS.map().values().parallelStream() .filter(t -> t.subscribers().containsKey(session.clientId())) .map(t -> t.subscribers().get(session.clientId())).map(s -> s.outboundMessageStatuses()) .flatMap(s -> s.values().stream()); statuses.forEach(s -> { long intervalSeconds = (now.getTime() - s.updateTime().getTime()) * 1000; if (intervalSeconds < RESPONSE_TIMEOUT_SECONDS) { return; } Topic topic = Topic.NEXUS.get(s.clientId(), s.messageId(), Topics.ClientType.SUBSCRIBER); Message message = topic.messages().get(s.inboundMessageKey()); message.setQos(s.qos()); message.setId(s.messageId()); // [MQTT-2.3.1-4] message.setRetain(false); // [MQTT-3.3.1-9] switch (s.status()) { case TO_PUBLISH: case PUBLISHED: send(MessageFactory.publish(message, s.status() == OutboundMessageStatus.Status.PUBLISHED)) // [MQTT-3.3.1-1] .addListener(f -> { Statistics.SELF.add(Statistics.Criterion.MESSAGES_PUBLISH_SENT, 1); }); break; case PUBRECED: send(MessageFactory.pubrel(message.id())); break; default: logger.error("Invalid Outbound Message Status [status={}, clientId={}, topic={}, messageId={}]", s.status(), session.clientId(), message.topicName(), message.id()); break; } }); }); }
From source file:net.petercashel.nettyCore.server.ServerConnectionHandler.java
License:Apache License
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { try {// w w w . j a v a 2 s. c om if (!(serverCore.clientConnectionMap.containsKey(ctx.channel().remoteAddress()))) { ChannelUserHolder chUser = (new ChannelUserHolder()); chUser.c = ctx.channel(); serverCore.clientConnectionMap.put(ctx.channel().remoteAddress(), chUser); } } catch (NullPointerException e) { // Delibrately null on shutdown. ctx.close(); ctx.executor().shutdownGracefully(); } }
From source file:net.petercashel.nettyCore.serverUDS.ServerUDSConnectionHandler.java
License:Apache License
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { try {/* w w w. ja v a2 s . c o m*/ if (!(serverCoreUDS.clientConnectionMap.containsKey(ctx.channel()))) { serverCoreUDS.clientConnectionMap.put(ctx.channel(), ctx.channel()); } } catch (NullPointerException e) { // Delibrately null on shutdown. ctx.close(); ctx.executor().shutdownGracefully(); } }
From source file:net.tenorite.net.TetrinetServerHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, String message) throws Exception { if (finished) { received.add(Inbound.of(message)); flush();//from w w w.j a v a 2s .c o m return; } finished = true; Optional<String[]> decoded = decode(message).map(s -> s.split(" ")); if (decoded.isPresent()) { String[] initialization = decoded.get(); Tempo tempo = TETRIFASTER.equalsIgnoreCase(initialization[0]) ? Tempo.FAST : Tempo.NORMAL; String name = initialization[1]; clientsRegistry.registerClient(tempo, name, clientChannel(tempo, ctx)) .whenCompleteAsync((result, failure) -> { if (failure != null) { if (failure instanceof CompletionException) { failure = failure.getCause(); } if (failure instanceof ClientRegistrationException) { ClientRegistrationException cre = (ClientRegistrationException) failure; switch (cre.getType()) { case INVALID_NAME: ctx.writeAndFlush(("noconnecting invalid nickname")); break; case NAME_ALREADY_IN_USE: ctx.writeAndFlush(("noconnecting nickname already in use")); break; } } else { ctx.writeAndFlush(("noconnecting an error occured")); ctx.close(); } } else { client = result.getClient(); ctx.channel().closeFuture() .addListener(f -> client.tell(PoisonPill.getInstance(), noSender())); flush(); } }, ctx.executor()); } else { ctx.writeAndFlush(("noconnecting invalid initialization")); } }
From source file:nettyprivateprotocolclientdemo.HeartBeatReqHandler.java
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { NettyMessage message = (NettyMessage) msg; if (message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_RESP.value()) { heartBeat = ctx.executor().scheduleAtFixedRate(new HeartBeatReqHandler.HeartBeatTask(ctx), 0, 5000, TimeUnit.MILLISECONDS); } else if (message.getHeader() != null && message.getHeader().getType() == MessageType.HEARTBEAT_RESP.value()) { System.out.println("Client receive server heart beat message : ---> " + message); } else {//from w w w . j a va 2 s . c o m ctx.fireChannelRead(msg); } }
From source file:org.apache.tinkerpop.gremlin.server.handler.IteratorHandler.java
License:Apache License
@Override public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) throws Exception { if (msg instanceof Pair) { try {/*from ww w. java2 s . c o m*/ final Pair pair = (Pair) msg; final Iterator itty = (Iterator) pair.getValue1(); final RequestMessage requestMessage = (RequestMessage) pair.getValue0(); // the batch size can be overriden by the request final int resultIterationBatchSize = (Integer) requestMessage.optionalArgs(Tokens.ARGS_BATCH_SIZE) .orElse(settings.resultIterationBatchSize); // timer for the total serialization time final StopWatch stopWatch = new StopWatch(); final EventExecutorGroup executorService = ctx.executor(); final Future<?> iteration = executorService.submit((Callable<Void>) () -> { logger.debug("Preparing to iterate results from - {} - in thread [{}]", requestMessage, Thread.currentThread().getName()); stopWatch.start(); List<Object> aggregate = new ArrayList<>(resultIterationBatchSize); while (itty.hasNext()) { aggregate.add(itty.next()); // send back a page of results if batch size is met or if it's the end of the results being // iterated if (aggregate.size() == resultIterationBatchSize || !itty.hasNext()) { final ResponseStatusCode code = itty.hasNext() ? ResponseStatusCode.PARTIAL_CONTENT : ResponseStatusCode.SUCCESS; ctx.writeAndFlush( ResponseMessage.build(requestMessage).code(code).result(aggregate).create()); aggregate = new ArrayList<>(resultIterationBatchSize); } stopWatch.split(); if (stopWatch.getSplitTime() > settings.serializedResponseTimeout) throw new TimeoutException( "Serialization of the entire response exceeded the serializeResponseTimeout setting"); stopWatch.unsplit(); } return null; }); iteration.addListener(f -> { stopWatch.stop(); if (!f.isSuccess()) { final String errorMessage = String.format( "Response iteration and serialization exceeded the configured threshold for request [%s] - %s", msg, f.cause().getMessage()); logger.warn(errorMessage); ctx.writeAndFlush( ResponseMessage.build(requestMessage).code(ResponseStatusCode.SERVER_ERROR_TIMEOUT) .statusMessage(errorMessage).create()); } }); } finally { ReferenceCountUtil.release(msg); } } else { ctx.write(msg, promise); } }
From source file:org.artJava.protocol.client.handlers.HeartBeatReqHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { Message message = (Message) msg;//from ww w . ja v a 2 s. co m // ????? if (message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_RESP.value()) { heartBeat = ctx.executor().scheduleAtFixedRate(new HeartBeatReqHandler.HeartBeatTask(ctx), 0, 50000, TimeUnit.MILLISECONDS); } else if (message.getHeader() != null && message.getHeader().getType() == MessageType.HEARTBEAT_RESP.value()) { System.out.println("Client receive server heart beat message : ---> " + message); } else ctx.fireChannelRead(msg); }