List of usage examples for io.netty.channel ChannelHandlerContext flush
@Override ChannelHandlerContext flush();
From source file:org.bridje.http.impl.HttpServerChannelHandler.java
License:Apache License
private void sendBadRequest(ChannelHandlerContext ctx) { LOG.log(Level.WARNING, "Bad Request Received...."); DefaultHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST); response.headers().set(SERVER, server.getServerName()); response.headers().set(CONTENT_TYPE, "text/html"); response.headers().set(CONTENT_LENGTH, 0); response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); ctx.write(response);//from ww w.j a v a 2 s .com ctx.flush(); closeAll(); }
From source file:org.code_house.ebus.netty.codec.OutboundEBusHandler.java
License:Apache License
@Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { if (masterHeader != null && masterData != null) { // passive get int destination = masterHeader.getDestination(); if (device.getSlave().getAddress() == destination) { Command command = new DefaultCommand(masterHeader.getPrimary(), masterHeader.getSecondary()); Optional<CommandCodec> mapper = codecRegistry.find(command); if (mapper.isPresent()) { try { PropertyValue value = mapper.get().master().decode(masterData.getData()); if (value == null) { ctx.write(new Rejection()); } else { // ok, we received data and mapper was able to parse it, try to set value PropertyValue returnValue = device.set(command, value); if (returnValue == null) { ctx.write(new Rejection()); }//from w ww .j av a 2 s . co m ByteBuffer reply = mapper.get().slave().encode(returnValue); // data should not exceed 16 bytes, so we're safe here ctx.write(new SlaveHeader((short) reply.capacity())); ctx.write(new SlaveData(reply, (byte) 0, (byte) 0)); } } catch (UnsupportedCommandException | CommandCodecException e) { logger.error("Could not answer slave command", e); } } else { logger.warn("Received slave command {}, but could not find mapping for it. Ignoring", command); ctx.write(new Rejection()); } } if (device.getMaster().getAddress() == destination) { Command command = new DefaultCommand(masterHeader.getPrimary(), masterHeader.getSecondary()); Optional<CommandCodec> mapper = codecRegistry.find(command); if (mapper.isPresent()) { try { PropertyValue value = mapper.get().master().decode(masterData.getData()); if (value != null && device.receive(command, value)) { ctx.write(new Confirmation()); // ok, we received data and mapper is able to parse it } else { ctx.write(new Rejection()); } } catch (UnsupportedCommandException | CommandCodecException e) { logger.error("Could not handle master command", e); } } else { logger.warn("Received master command {}, but could not find mapping for it. Ignoring", command); } } ctx.flush(); } masterHeader = null; masterData = null; ctx.fireChannelReadComplete(); }
From source file:org.code_house.ebus.netty.codec.OutboundEBusHandler.java
License:Apache License
@Override public void flush(ChannelHandlerContext ctx) throws Exception { if (ctx.channel().isWritable() && accessGranted) { ToSend toSend = entries.pollFirst(); ctx.write(toSend.toSend, toSend.promise); ctx.write(Unpooled.buffer().writeByte(Constants.SYN)); accessGranted = false;/* ww w . ja v a2 s. co m*/ writeInProgress = false; } ctx.flush(); }
From source file:org.dcache.xrootd.stream.ChunkedResponseWriteHandler.java
License:Open Source License
@Override public void flush(ChannelHandlerContext ctx) throws Exception { if (!doFlush(ctx)) { // Make sure to flush at least once. ctx.flush(); }/*from w w w. j ava 2 s.co m*/ }
From source file:org.dcache.xrootd.stream.ChunkedResponseWriteHandler.java
License:Open Source License
private boolean doFlush(final ChannelHandlerContext ctx) throws Exception { final Channel channel = ctx.channel(); if (!channel.isActive()) { discard(null);/* w w w. j a v a 2s . com*/ return false; } boolean flushed = false; while (channel.isWritable()) { if (currentWrite == null) { currentWrite = queue.poll(); } if (currentWrite == null) { break; } final PendingWrite currentWrite = this.currentWrite; final ChunkedResponse pendingMessage = currentWrite.msg; boolean endOfInput; Object message = null; try { message = pendingMessage.nextChunk(ctx.alloc()); endOfInput = pendingMessage.isEndOfInput(); } catch (final Throwable t) { this.currentWrite = null; if (message != null) { ReferenceCountUtil.release(message); } currentWrite.fail(t); break; } if (message == null) { // If message is null write an empty ByteBuf. // See https://github.com/netty/netty/issues/1671 message = Unpooled.EMPTY_BUFFER; } final int amount = amount(message); ChannelFuture f = ctx.write(message); if (endOfInput) { this.currentWrite = null; // Register a listener which will close the input once the write is complete. // This is needed because the Chunk may have some resource bound that can not // be closed before its not written. // // See https://github.com/netty/netty/issues/303 f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { currentWrite.fail(future.cause()); } else { currentWrite.progress(amount); currentWrite.success(); } } }); } else { f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { currentWrite.fail(future.cause()); } else { currentWrite.progress(amount); } } }); } // Always need to flush ctx.flush(); flushed = true; if (!channel.isActive()) { discard(new ClosedChannelException()); break; } } return flushed; }
From source file:org.eclipse.neoscada.protocol.iec60870.apci.MessageChannel.java
License:Open Source License
private void processInformationTransfer(final ChannelHandlerContext ctx, final Object msg) { final List<Object> out = new LinkedList<>(); logger.trace("Passing to manager: {}", msg); final ByteBuf errorData = this.manager.receiveMessage((InformationTransfer) msg, out); if (errorData != null) { logger.debug("Write error reply"); writeMessageToChannel(ctx, errorData, null); ctx.flush(); }// w w w. j a v a 2 s . c o m for (final Object newMsg : out) { logger.trace("Passing message: {}", newMsg); ctx.fireChannelRead(newMsg); } }
From source file:org.eclipse.neoscada.protocol.iec60870.apci.MessageChannel.java
License:Open Source License
protected synchronized void handleAck(final ChannelHandlerContext ctx, final int receiveSequenceNumber) { logger.trace("Received ACK up to: {}", receiveSequenceNumber); // handle ack this.ackBuffer.gotAck(receiveSequenceNumber); // now try to flush messages from the buffer sendFromBuffer();// ww w . j av a 2s . c o m // try to send from sources sendFromSources(); ctx.flush(); }
From source file:org.eclipse.neoscada.protocol.iec60870.apci.MessageChannel.java
License:Open Source License
private synchronized void handleMessageSourceUpdates(final ChannelHandlerContext ctx) { if (this.ackBuffer.isFull()) { logger.trace("Received notify token but buffer is full"); return;/*from w ww .ja v a2s . c o m*/ } /* * we can directly send from the sources since either is the message buffer * not empty, but then also the ackBuffer full. Which it is not at this point. * * Or the ackBuffer has room, so there won't be any message in the message buffer left. */ sendFromSources(); // we have to flush manually ctx.flush(); }
From source file:org.ensembl.gti.seqstore.server.RequestResponseServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { log.trace("Reading message"); ByteBuf in = (ByteBuf) msg;// w ww .j a v a 2s . c o m int l = in.readInt(); log.trace("Reading message of length " + l); ByteBuf x = in.readBytes(l); Response response = null; try { Request request = Request.parseFrom(x.array()); log.debug("Received " + request.getOperation()); String responseMsg; switch (request.getOperation()) { case START_SESSION: log.debug("Creating new session for " + request.getClientId()); Long id = seqStore.startSession(request.getClientId()); responseMsg = id.toString(); break; case ABORT_SESSION: log.debug("Aborting session " + request.getSessionId() + " for " + request.getClientId()); seqStore.clearSession(request.getSessionId()); responseMsg = "Aborted session " + request.getSessionId(); break; case STORE_GENOME: log.debug("Storing " + request.getGeneCount() + " genes"); long genomeId = seqStore.storeGenome(request.getSessionId(), new GenomeDelegate(request.getGenome())); responseMsg = String.valueOf(genomeId); break; case STORE_GENOME_SEQUENCE: log.info("Storing " + request.getGenomeSequenceCount() + " genome sequences"); int n = 0; for (GenomeSequence g : request.getGenomeSequenceList()) { seqStore.storeGenomeSequence(request.getSessionId(), new GenomeSequenceDelegate(g)); n++; } responseMsg = "Stored " + n + " genome sequences"; break; case STORE_GENE: log.debug("Storing " + request.getGeneCount() + " genes"); n = 0; for (Gene g : request.getGeneList()) { seqStore.storeGene(request.getSessionId(), new GeneDelegate(g)); n++; } responseMsg = "Stored " + n + " genes"; break; default: responseMsg = "Unknown operation " + request.getOperation(); response = Response.newBuilder().setStatus(Status.DATA_ERROR).setMessage(responseMsg).build(); throw new UnsupportedOperationException(responseMsg); } response = Response.newBuilder().setStatus(Status.OK).setMessage(responseMsg).build(); } catch (SeqStoreException e) { log.error("Error processing request", e); response = Response.newBuilder().setStatus(Status.DATA_ERROR).setMessage(e.getMessage()).build(); } catch (Throwable e) { log.error("Error processing request", e); response = Response.newBuilder().setStatus(Status.SERVER_ERROR).setMessage(e.getMessage()).build(); } finally { byte[] ra = response.toByteArray(); ctx.write(Unpooled.copyInt(ra.length)); ctx.write(Unpooled.copiedBuffer(ra)); ctx.flush(); if (x != null) x.release(); if (in != null) in.release(); } }
From source file:org.fengbaoxp.netty.official.EchoServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf in = (ByteBuf) msg;//from w w w .j ava 2 s. co m StringBuilder smsg = new StringBuilder(); while (in.isReadable()) { smsg.append((char) in.readByte()); } logger.info(smsg.toString()); final ByteBuf out = ctx.alloc().buffer(); out.writeBytes(smsg.toString().getBytes()); ctx.write(out); ctx.flush(); }