Tabnine Logo
ChannelHandlerContext.write
Code IndexAdd Tabnine to your IDE (free)

How to use
write
method
in
io.netty.channel.ChannelHandlerContext

Best Java code snippets using io.netty.channel.ChannelHandlerContext.write (Showing top 20 results out of 3,753)

Refine searchRefine arrow

  • ChannelHandlerContext.channel
origin: ReactiveX/RxNetty

  @Override
  public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    /*Both these handlers always run in the same executor, so it's safe to access this variable.*/
    bytesWriteInterceptor.messageReceived = false; /*reset flag for this write*/
    ctx.write(msg, promise);
    if (!bytesWriteInterceptor.messageReceived) {
      bytesWriteInterceptor.requestMoreIfWritable(ctx.channel());
    }
  }
}
origin: jooby-project/jooby

private void send(final ByteBuf buffer) throws Exception {
 DefaultFullHttpResponse rsp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, buffer);
 headers.remove(HttpHeaderNames.TRANSFER_ENCODING)
   .set(HttpHeaderNames.CONTENT_LENGTH, buffer.readableBytes());
 ChannelPromise promise;
 if (keepAlive) {
  promise = ctx.voidPromise();
  headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
 } else {
  promise = ctx.newPromise();
 }
 // dump headers
 rsp.headers().set(headers);
 Attribute<Boolean> async = ctx.channel().attr(NettyRequest.ASYNC);
 boolean flush = async != null && async.get() == Boolean.TRUE;
 final ChannelFuture future;
 if (flush) {
  future = ctx.writeAndFlush(rsp, promise);
 } else {
  future = ctx.write(rsp, promise);
 }
 if (!keepAlive) {
  future.addListener(CLOSE);
 }
 committed = true;
}
origin: ReactiveX/RxNetty

@Override
public void write(ChannelHandlerContext ctx, final Object msg, ChannelPromise promise) throws Exception {
  ctx.write(msg, promise);
  messageReceived = true;
  requestMoreIfWritable(ctx.channel());
}
origin: jersey/jersey

JerseyChunkedInput jerseyChunkedInput = new JerseyChunkedInput(ctx.channel());
  ctx.write(new HttpChunkedInput(jerseyChunkedInput)).addListener(FLUSH_FUTURE);
} else {
  ctx.write(new HttpChunkedInput(jerseyChunkedInput)).addListener(FLUSH_FUTURE);
origin: andsel/moquette

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
  MessageMetrics metrics = ctx.channel().attr(ATTR_KEY_METRICS).get();
  metrics.incrementWrote(1);
  ctx.write(msg, promise).addListener(CLOSE_ON_FAILURE);
}
origin: blynkkk/blynk-server

private static void syncSpecificPins(ChannelHandlerContext ctx, String messageBody,
                   int msgId, Profile profile, DashBoard dash, int deviceId) {
  String[] bodyParts = messageBody.split(StringUtils.BODY_SEPARATOR_STRING);
  if (bodyParts.length < 2 || bodyParts[0].isEmpty()) {
    ctx.writeAndFlush(illegalCommand(msgId), ctx.voidPromise());
    return;
  }
  PinType pinType = PinType.getPinType(bodyParts[0].charAt(0));
  if (StringUtils.isReadOperation(bodyParts[0])) {
    for (int i = 1; i < bodyParts.length; i++) {
      short pin = NumberUtil.parsePin(bodyParts[i]);
      Widget widget = dash.findWidgetByPin(deviceId, pin, pinType);
      if (ctx.channel().isWritable()) {
        if (widget == null) {
          PinStorageValue pinStorageValue =
              profile.pinsStorage.get(new DashPinStorageKey(dash.id, deviceId, pinType, pin));
          if (pinStorageValue != null) {
            for (String value : pinStorageValue.values()) {
              String body = DataStream.makeHardwareBody(pinType, pin, value);
              ctx.write(makeUTF8StringMessage(HARDWARE, msgId, body), ctx.voidPromise());
            }
          }
        } else if (widget instanceof HardwareSyncWidget) {
          ((HardwareSyncWidget) widget).sendHardSync(ctx, msgId, deviceId);
        }
      }
    }
    ctx.flush();
  }
}
origin: alipay/sofa-rpc

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable e)
    throws Exception {
    // handle the case of to big requests.
    if (e.getCause() instanceof TooLongFrameException) {
      DefaultHttpResponse response = new DefaultHttpResponse(HTTP_1_1, REQUEST_ENTITY_TOO_LARGE);
      ctx.write(response).addListener(ChannelFutureListener.CLOSE);
    } else {
      if (ctx.channel().isActive()) { // 连接已断开就不打印了
        logger.warn("Exception caught by request handler", e);
      }
      ctx.close();
    }
  }
}
origin: alipay/sofa-rpc

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable e)
    throws Exception {
    // handle the case of to big requests.
    if (e.getCause() instanceof TooLongFrameException) {
      DefaultHttpResponse response = new DefaultHttpResponse(HTTP_1_1, REQUEST_ENTITY_TOO_LARGE);
      ctx.write(response).addListener(ChannelFutureListener.CLOSE);
    } else {
      if (ctx.channel().isActive()) { // 连接已断开就不打印了
        logger.warn("Exception caught by request handler", e);
      }
      ctx.close();
    }
  }
}
origin: andsel/moquette

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
  BytesMetrics metrics = ctx.channel().attr(ATTR_KEY_METRICS).get();
  metrics.incrementWrote(((ByteBuf) msg).writableBytes());
  ctx.write(msg, promise).addListener(CLOSE_ON_FAILURE);
}
origin: traccar/traccar

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
  if (msg instanceof NetworkMessage) {
    NetworkMessage message = (NetworkMessage) msg;
    if (ctx.channel() instanceof DatagramChannel) {
      InetSocketAddress recipient = (InetSocketAddress) message.getRemoteAddress();
      InetSocketAddress sender = (InetSocketAddress) ctx.channel().localAddress();
      ctx.write(new DatagramPacket((ByteBuf) message.getMessage(), recipient, sender), promise);
    } else {
      ctx.write(message.getMessage(), promise);
    }
  } else {
    ctx.write(msg, promise);
  }
}
origin: openzipkin/brave

 @Override
 public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise prm) throws Exception {
  String uri = ctx.channel().attr(URI_ATTRIBUTE).get();
  if (uri == null) {
   ctx.write(msg, prm);
   return;
  }
  if ("/unsampled".equals(uri)) {
   unsampled.write(ctx, msg, prm);
  } else if ("/traced".equals(uri)) {
   traced.write(ctx, msg, prm);
  } else if ("/traced128".equals(uri)) {
   traced128.write(ctx, msg, prm);
  } else {
   ctx.write(msg, prm);
  }
 }
}
origin: jamesdbloom/mockserver

private void handleWebSocketFrame(final ChannelHandlerContext ctx, WebSocketFrame frame) {
  if (frame instanceof CloseWebSocketFrame) {
    handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
  } else if (frame instanceof TextWebSocketFrame) {
    webSocketClientRegistry.receivedTextWebSocketFrame(((TextWebSocketFrame) frame));
  } else if (frame instanceof PingWebSocketFrame) {
    ctx.write(new PongWebSocketFrame(frame.content().retain()));
  } else {
    throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass().getName()));
  }
}
origin: jooby-project/jooby

@Override
public void end() {
 if (ctx != null) {
  Attribute<NettyWebSocket> ws = ctx.channel().attr(NettyWebSocket.KEY);
  if (ws != null && ws.get() != null) {
   status = HttpResponseStatus.SWITCHING_PROTOCOLS;
   ws.get().hankshake();
   ctx = null;
   committed = true;
   return;
  }
  if (!committed) {
   DefaultHttpResponse rsp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status);
   headers.set(HttpHeaderNames.CONTENT_LENGTH, 0);
   // dump headers
   rsp.headers().set(headers);
   if (keepAlive) {
    ctx.write(rsp, ctx.voidPromise());
   } else {
    ctx.write(rsp).addListener(CLOSE);
   }
   ctx.flush();
   committed = true;
  }
  ctx = null;
 }
}
origin: apache/incubator-shardingsphere

  private void writeMoreResults(final PostgreSQLQueryCommandPacket queryCommandPacket) throws SQLException {
    if (!context.channel().isActive()) {
      return;
    }
    int count = 0;
    int proxyFrontendFlushThreshold = GlobalRegistry.getInstance().getShardingProperties().<Integer>getValue(ShardingPropertiesConstant.PROXY_FRONTEND_FLUSH_THRESHOLD);
    while (queryCommandPacket.next()) {
      count++;
      while (!context.channel().isWritable() && context.channel().isActive()) {
        context.flush();
        synchronized (frontendHandler) {
          try {
            frontendHandler.wait();
          } catch (final InterruptedException ignored) {
          }
        }
      }
      DatabasePacket resultValue = queryCommandPacket.getResultValue();
      context.write(resultValue);
      if (proxyFrontendFlushThreshold == count) {
        context.flush();
        count = 0;
      }
    }
  }
}
origin: apache/incubator-shardingsphere

  private void writeMoreResults(final QueryCommandPacket queryCommandPacket, final int headPacketsCount) throws SQLException {
    if (!context.channel().isActive()) {
      return;
    }
    currentSequenceId = headPacketsCount;
    int count = 0;
    int proxyFrontendFlushThreshold = GlobalRegistry.getInstance().getShardingProperties().<Integer>getValue(ShardingPropertiesConstant.PROXY_FRONTEND_FLUSH_THRESHOLD);
    while (queryCommandPacket.next()) {
      count++;
      while (!context.channel().isWritable() && context.channel().isActive()) {
        context.flush();
        synchronized (frontendHandler) {
          try {
            frontendHandler.wait();
          } catch (final InterruptedException ignored) {
          }
        }
      }
      DatabasePacket resultValue = queryCommandPacket.getResultValue();
      currentSequenceId = resultValue.getSequenceId();
      context.write(resultValue);
      if (proxyFrontendFlushThreshold == count) {
        context.flush();
        count = 0;
      }
    }
    context.write(new EofPacket(++currentSequenceId));
  }
}
origin: apache/incubator-shardingsphere

  private void writeMoreResults(final QueryCommandPacket queryCommandPacket, final int headPacketsCount) throws SQLException {
    if (!context.channel().isActive()) {
      return;
    }
    currentSequenceId = headPacketsCount;
    int count = 0;
    int proxyFrontendFlushThreshold = GlobalRegistry.getInstance().getShardingProperties().<Integer>getValue(ShardingPropertiesConstant.PROXY_FRONTEND_FLUSH_THRESHOLD);
    while (queryCommandPacket.next()) {
      count++;
      while (!context.channel().isWritable() && context.channel().isActive()) {
        context.flush();
        synchronized (frontendHandler) {
          try {
            frontendHandler.wait();
          } catch (final InterruptedException ignored) {
          }
        }
      }
      DatabasePacket resultValue = queryCommandPacket.getResultValue();
      currentSequenceId = resultValue.getSequenceId();
      context.write(resultValue);
      if (proxyFrontendFlushThreshold == count) {
        context.flush();
        count = 0;
      }
    }
    context.write(new EofPacket(++currentSequenceId));
  }
}
origin: redisson/redisson

@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
  Channel channel = ctx.channel();
  Integer key = channel.hashCode();
  PerChannel perChannel = channelQueues.remove(key);
          perChannel.queueSize -= size;
          queuesSize.addAndGet(-size);
          ctx.write(toSend.toSend, toSend.promise);
origin: openzipkin/brave

 @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise prm) {
  Span span = ctx.channel().attr(NettyHttpTracing.SPAN_ATTRIBUTE).get();
  if (span == null || !(msg instanceof HttpResponse)) {
   ctx.write(msg, prm);
   return;
  }

  HttpResponse response = (HttpResponse) msg;

  // Guard re-scoping the same span
  SpanInScope spanInScope = ctx.channel().attr(NettyHttpTracing.SPAN_IN_SCOPE_ATTRIBUTE).get();
  if (spanInScope == null) spanInScope = tracer.withSpanInScope(span);
  try {
   ctx.write(msg, prm);
   parser.response(adapter, response, null, span.customizer());
  } catch (RuntimeException | Error e) {
   span.error(e);
   throw e;
  } finally {
   spanInScope.close(); // clear scope before reporting
   span.finish();
  }
 }
}
origin: wildfly/wildfly

@Override
public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
  promise = promise.unvoid();
  // Avoid NotYetConnectedException
  if (!ctx.channel().isActive()) {
    ctx.close(promise);
    return;
  }
  // If the user has already sent a GO_AWAY frame they may be attempting to do a graceful shutdown which requires
  // sending multiple GO_AWAY frames. We should only send a GO_AWAY here if one has not already been sent. If
  // a GO_AWAY has been sent we send a empty buffer just so we can wait to close until all other data has been
  // flushed to the OS.
  // https://github.com/netty/netty/issues/5307
  final ChannelFuture future = connection().goAwaySent() ? ctx.write(EMPTY_BUFFER) : goAway(ctx, null);
  ctx.flush();
  doGracefulShutdown(ctx, future, promise);
}
origin: traccar/traccar

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
  NetworkMessage networkMessage = (NetworkMessage) msg;
  if (networkMessage.getMessage() instanceof Command) {
    Command command = (Command) networkMessage.getMessage();
    Object encodedCommand = encodeCommand(ctx.channel(), command);
    StringBuilder s = new StringBuilder();
    s.append("[").append(ctx.channel().id().asShortText()).append("] ");
    s.append("id: ").append(getUniqueId(command.getDeviceId())).append(", ");
    s.append("command type: ").append(command.getType()).append(" ");
    if (encodedCommand != null) {
      s.append("sent");
    } else {
      s.append("not sent");
    }
    LOGGER.info(s.toString());
    ctx.write(new NetworkMessage(encodedCommand, networkMessage.getRemoteAddress()), promise);
  } else {
    super.write(ctx, msg, promise);
  }
}
io.netty.channelChannelHandlerContextwrite

Popular methods of ChannelHandlerContext

  • channel
    Return the Channel which is bound to the ChannelHandlerContext.
  • close
  • writeAndFlush
  • flush
  • fireChannelRead
  • pipeline
    Return the assigned ChannelPipeline
  • alloc
    Return the assigned ByteBufAllocator which will be used to allocate ByteBufs.
  • executor
    Returns the EventExecutor which is used to execute an arbitrary task.
  • fireExceptionCaught
  • fireUserEventTriggered
  • newPromise
  • fireChannelActive
  • newPromise,
  • fireChannelActive,
  • fireChannelInactive,
  • voidPromise,
  • read,
  • fireChannelReadComplete,
  • name,
  • attr,
  • disconnect

Popular in Java

  • Updating database using SQL prepared statement
  • compareTo (BigDecimal)
  • putExtra (Intent)
  • runOnUiThread (Activity)
  • EOFException (java.io)
    Thrown when a program encounters the end of a file or stream during an input operation.
  • FileWriter (java.io)
    A specialized Writer that writes to a file in the file system. All write requests made by calling me
  • HttpURLConnection (java.net)
    An URLConnection for HTTP (RFC 2616 [http://tools.ietf.org/html/rfc2616]) used to send and receive d
  • URI (java.net)
    A Uniform Resource Identifier that identifies an abstract or physical resource, as specified by RFC
  • Handler (java.util.logging)
    A Handler object accepts a logging request and exports the desired messages to a target, for example
  • JPanel (javax.swing)
  • Top 17 Plugins for Android Studio
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimAtomGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyStudentsTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now