下面列出了java.nio.channels.NotYetConnectedException#io.netty.channel.Channel 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
protected void processResponseFrame(Channel channel, ModbusFrame respFrame) {
super.processResponseFrame(channel, respFrame);
int respTransactionIdentifier = respFrame.getHeader().getTransactionIdentifier();
ModbusFrame reqFrame = ModebusFrameCacheFactory.getInstance().getRequestCache()
.get(respTransactionIdentifier - this.getTransactionIdentifierOffset());
boolean isErr = false;
if (reqFrame != null) {
if (reqFrame.getFunction() instanceof AbstractFunction) {
AbstractFunction reqFunc = (AbstractFunction) reqFrame.getFunction();
ModbusFunction respFunc = respFrame.getFunction();
processResponseFrame(channel, reqFunc, respFunc);
} else {
isErr = true;
}
} else {
isErr = true;
}
if (isErr) {
logger.error(String.format("req is null:%s;%s", channel.remoteAddress(), respFrame));
}
}
@Test
public void cancelExecuteFuture_channelAcquired_submitsRunnable() {
EventLoop mockEventLoop = mock(EventLoop.class);
Channel mockChannel = mock(Channel.class);
when(mockChannel.eventLoop()).thenReturn(mockEventLoop);
when(mockChannelPool.acquire(any(Promise.class))).thenAnswer((Answer<Promise>) invocationOnMock -> {
Promise p = invocationOnMock.getArgumentAt(0, Promise.class);
p.setSuccess(mockChannel);
return p;
});
CompletableFuture<Void> executeFuture = nettyRequestExecutor.execute();
executeFuture.cancel(true);
verify(mockEventLoop).submit(any(Runnable.class));
}
public NioUdtMessageConnectorChannel(final Channel parent, final SocketChannelUDT channelUDT) {
super(parent, channelUDT, OP_READ);
try {
channelUDT.configureBlocking(false);
switch (channelUDT.socketUDT().status()) {
case INIT:
case OPENED:
config = new DefaultUdtChannelConfig(this, channelUDT, true);
break;
default:
config = new DefaultUdtChannelConfig(this, channelUDT, false);
break;
}
} catch (final Exception e) {
try {
channelUDT.close();
} catch (final Exception e2) {
if (logger.isWarnEnabled()) {
logger.warn("Failed to close channel.", e2);
}
}
throw new ChannelException("Failed to configure channel.", e);
}
}
public HashMap<String, HashMap<Channel, ClientChannelInfo>> getGroupChannelTable() {
HashMap<String /* group name */, HashMap<Channel, ClientChannelInfo>> newGroupChannelTable =
new HashMap<String, HashMap<Channel, ClientChannelInfo>>();
try {
if (this.groupChannelLock.tryLock(LockTimeoutMillis, TimeUnit.MILLISECONDS)){
try {
newGroupChannelTable.putAll(groupChannelTable);
} finally {
groupChannelLock.unlock();
}
}
} catch (InterruptedException e) {
log.error("",e);
}
return newGroupChannelTable;
}
@Test(
alwaysRun = true,
dependsOnMethods = {"testRegisterModelHttpError"})
public void testRegisterModelInvalidPath() throws InterruptedException {
Channel channel = TestUtils.connect(true, configManager);
Assert.assertNotNull(channel);
HttpRequest req =
new DefaultFullHttpRequest(
HttpVersion.HTTP_1_1,
HttpMethod.POST,
"/models?url=..%2Ffake.mar&synchronous=false");
channel.writeAndFlush(req).sync();
channel.closeFuture().sync();
ErrorResponse resp = JsonUtils.GSON.fromJson(TestUtils.getResult(), ErrorResponse.class);
Assert.assertEquals(resp.getCode(), HttpResponseStatus.NOT_FOUND.code());
Assert.assertEquals(resp.getMessage(), "Relative path is not allowed in url: ../fake.mar");
}
@Override
public void masterDisconntected(Channel channel) {
super.masterDisconntected(channel);
redisKeeperServer.getKeeperMonitor().getReplicationStoreStats().refreshReplDownSince(System.currentTimeMillis());
long interval = System.currentTimeMillis() - connectedTime;
long scheduleTime = masterConnectRetryDelaySeconds * 1000 - interval;
if (scheduleTime < 0) {
scheduleTime = 0;
}
logger.info("[masterDisconntected][reconnect after {} ms]", scheduleTime);
scheduled.schedule(new AbstractExceptionLogTask() {
@Override
public void doRun() {
connectWithMaster();
}
}, scheduleTime, TimeUnit.MILLISECONDS);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
LOG.log(Level.SEVERE, "UNEXPECTED_EXCEPCTION_IN_NETTY_SERVLET_HANDLER", cause);
interceptOnRequestFailed(ctx, cause);
Channel ch = ctx.channel();
if (cause instanceof IllegalArgumentException) {
ch.close();
} else {
if (cause instanceof TooLongFrameException) {
sendError(ctx, HttpResponseStatus.BAD_REQUEST);
return;
}
if (ch.isActive()) {
sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR);
}
}
ctx.close();
}
@Override
public void sendCancelRequest(@Nonnull Object feature, @Nonnull MixedWeight mixed)
throws Exception {
assert (initialized);
float weight = mixed.getWeight();
float covar = mixed.getCovar();
int deltaUpdates = mixed.getDeltaUpdates();
MixMessage msg = new MixMessage(event, feature, weight, covar, deltaUpdates, true);
assert (groupID != null);
msg.setGroupID(groupID);
// TODO REVIEWME consider mix server faults (what if mix server dead? Do not send cancel request?)
NodeInfo server = router.selectNode(msg);
Channel ch = channelMap.get(server);
if (!ch.isActive()) {// reconnect
SocketAddress remoteAddr = server.getSocketAddress();
ch.connect(remoteAddr).sync();
}
ch.writeAndFlush(msg); // send asynchronously in the background
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
Channel ch = ctx.channel();
if (msg instanceof JResponsePayload) {
try {
processor.handleResponse(NettyChannel.attachChannel(ch), (JResponsePayload) msg);
} catch (Throwable t) {
logger.error("An exception was caught: {}, on {} #channelRead().", StackTraceUtil.stackTrace(t), ch);
}
} else {
logger.warn("Unexpected message type received: {}, channel: {}.", msg.getClass(), ch);
ReferenceCountUtil.release(msg);
}
}
NettyTransportFactory(ProtocolNegotiator protocolNegotiator,
ChannelFactory<? extends Channel> channelFactory,
Map<ChannelOption<?>, ?> channelOptions, ObjectPool<? extends EventLoopGroup> groupPool,
boolean autoFlowControl, int flowControlWindow, int maxMessageSize, int maxHeaderListSize,
long keepAliveTimeNanos, long keepAliveTimeoutNanos, boolean keepAliveWithoutCalls,
TransportTracer.Factory transportTracerFactory, LocalSocketPicker localSocketPicker,
boolean useGetForSafeMethods) {
this.protocolNegotiator = checkNotNull(protocolNegotiator, "protocolNegotiator");
this.channelFactory = channelFactory;
this.channelOptions = new HashMap<ChannelOption<?>, Object>(channelOptions);
this.groupPool = groupPool;
this.group = groupPool.getObject();
this.autoFlowControl = autoFlowControl;
this.flowControlWindow = flowControlWindow;
this.maxMessageSize = maxMessageSize;
this.maxHeaderListSize = maxHeaderListSize;
this.keepAliveTimeNanos = new AtomicBackoff("keepalive time nanos", keepAliveTimeNanos);
this.keepAliveTimeoutNanos = keepAliveTimeoutNanos;
this.keepAliveWithoutCalls = keepAliveWithoutCalls;
this.transportTracerFactory = transportTracerFactory;
this.localSocketPicker =
localSocketPicker != null ? localSocketPicker : new LocalSocketPicker();
this.useGetForSafeMethods = useGetForSafeMethods;
}
private void testLoadingMemoryError() throws InterruptedException {
Channel channel = connect(true);
Assert.assertNotNull(channel);
result = null;
latch = new CountDownLatch(1);
HttpRequest req =
new DefaultFullHttpRequest(
HttpVersion.HTTP_1_1,
HttpMethod.POST,
"/models?url=loading-memory-error&model_name=memory_error&runtime=python&initial_workers=1&synchronous=true");
channel.writeAndFlush(req);
latch.await();
Assert.assertEquals(httpStatus, HttpResponseStatus.INSUFFICIENT_STORAGE);
channel.close();
}
@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
final Channel channel = ctx.channel();
final byte[] message = (byte[]) msg;
if (LOG.isLoggable(Level.FINEST)) {
LOG.log(Level.FINEST, "MessageEvent: local: {0} remote: {1} :: {2}", new Object[]{
channel.localAddress(), channel.remoteAddress(), message});
}
if (message.length > 0) {
// send to the dispatch stage
this.stage.onNext(this.getTransportEvent(message, channel));
}
}
@Override
protected void channelRead0(ChannelHandlerContext context, Packet packet) throws Exception {
Channel channel = context.channel();
if(this.proxySession == null || !this.proxySession.isInboundConnected()) {
channel.close();
return;
}
switch(this.state) {
case LOGIN:
if(packet.getOpcode() == LoginSuccessPacket.opcode) {
this.state = ProxyState.INIT;
this.proxySession.setRedirecting(true);
context.channel().attr(StatefulPacketCodecProviderPair.attributeKey).get().setState(PlayStateCodecProvider.instance);
} else if(packet.getOpcode() == LoginDisconnectPacket.opcode) {
this.proxySession.disconnect(new PlayDisconnectPacket((((LoginDisconnectPacket) packet)).getJson()));
channel.close();
} else {
this.proxySession.disconnectIfInitializing("Error: Protocol Mismatch");
channel.close();
}
break;
case INIT:
if(packet.getOpcode() == 0x08) {
this.state = ProxyState.CONNECTED;
this.proxySession.setOutboundChannel(this.server, channel);
}
case CONNECTED:
this.proxySession.outboundReceived(channel, packet);
if(packet.getOpcode() == PlayDisconnectPacket.opcode) {
this.state = ProxyState.DISCONNECTED;
}
break;
default:
break;
}
}
public void write() {
Channel originChannel = this.nettyConnection.channel();
if (originChannel.isActive()) {
io.netty.handler.codec.http.HttpRequest httpRequest = makeRequest(request);
originChannel.writeAndFlush(httpRequest)
.addListener(subscribeToRequestBody());
} else {
responseFromOriginFlux.error(new TransportLostException(originChannel.remoteAddress(), nettyConnection.getOrigin()));
}
}
public BungeeChannelInitializer(ChannelInitializer<Channel> oldInit) {
this.original = oldInit;
try {
this.method = ChannelInitializer.class.getDeclaredMethod("initChannel", Channel.class);
this.method.setAccessible(true);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
/**
* Iterates through every open NetworkManager and adds my ChannelDuplexHandler subclass into the pipeline
* This allows you to listen for outgoing packets and modify them before they are sent
*
* The List of NetworkManager instances is converted to an array to avoid ConcurrentModificationExceptions
* NullPointerExceptions, IllegalArgumentExceptions, and NoSuchElementException only occur if there is a massive amount of ping requests being sent to the server.
* NullPointerExceptions are thrown when the pipeline has yet to be created.
* Since ping responses are handled on separate threads IllegalArgumentExceptions are thrown when this method is invoked at the same time on two different threads
* This means the null check will be passed and this method will attempt to create a duplicate handler which throws this exception
* NoSuchElementExceptions have a similar cause. They are caused when the "packet_handler" has yet to be added.
* The best solution I could find is simply ignoring these exceptions
*/
public void injectOpenConnections() {
try {
Field field = ReflectUtils.getFirstFieldByType(NetworkManager.class, Channel.class);
field.setAccessible(true);
for(Object manager : networkManagers.toArray()) {
Channel channel = (Channel) field.get(manager);
if(channel.pipeline().context("pingapi_handler") == null && (channel.pipeline().context("packet_handler") != null)) {
channel.pipeline().addBefore("packet_handler", "pingapi_handler", new DuplexHandler());
}
}
} catch(IllegalAccessException e) {
e.printStackTrace();
} catch(NullPointerException | IllegalArgumentException | NoSuchElementException ignored) {}
}
public ReverseShadowSocksProxy(Channel clientChannel,
Callback finish,
ShadowSocksConfiguration shadowSocksConfiguration,
NioEventLoopGroup eventLoopGroup,
ShadowsocksRequestResolver requestResolver) {
super(clientChannel, finish, shadowSocksConfiguration, eventLoopGroup, requestResolver);
}
/**
* Flush Message
* | 'H' | int32 len
* <p>
* Flush forces the backend to deliver any data pending in it's output buffers.
*/
private void handleFlush(Channel channel) {
try {
// If we have deferred any executions we need to trigger a sync now because the client is expecting data
// (That we've been holding back, as we don't eager react to `execute` requests. (We do that to optimize batch inserts))
// The sync will also trigger a flush eventually if there are deferred executions.
if (session.hasDeferredExecutions()) {
session.sync();
} else {
channel.flush();
}
} catch (Throwable t) {
Messages.sendErrorResponse(channel, t);
}
}
@Override
public String getDestinationId() {
if (this.channelHandlerContext != null) {
final Channel channel = this.channelHandlerContext.channel();
if (channel != null) {
return NettyUtils.getEndPoint(channel.remoteAddress());
}
}
return "Unknown";
}
@RequestMapping("installCert")
public FullHttpResponse installCert(Channel channel, FullHttpRequest request) throws Exception {
Map<String, Object> data = new HashMap<>();
boolean status;
if (OsUtil.isUnix() || OsUtil.isWindowsXP()) {
if (!AppUtil.checkIsInstalledCert()) {
ExtensionCertUtil.buildCert(AppUtil.SSL_PATH, AppUtil.SUBJECT);
}
Desktop.getDesktop().open(new File(AppUtil.SSL_PATH));
status = true;
} else {
//再检测一次,确保不重复安装
if (!AppUtil.checkIsInstalledCert()) {
if (ExtensionCertUtil.existsCert(AppUtil.SUBJECT)) {
//存在无用证书需要卸载
ExtensionCertUtil.uninstallCert(AppUtil.SUBJECT);
}
//生成新的证书
ExtensionCertUtil.buildCert(AppUtil.SSL_PATH, AppUtil.SUBJECT);
//安装
ExtensionCertUtil.installCert(new File(AppUtil.CERT_PATH));
//检测是否安装成功,可能点了取消就没安装成功
status = AppUtil.checkIsInstalledCert();
} else {
status = true;
}
}
data.put("status", status);
if (status && !PDownProxyServer.isStart) {
new Thread(() -> {
try {
AppUtil.startProxyServer();
} catch (IOException e) {
LOGGER.error("Start proxy server error", e);
}
}).start();
}
return HttpHandlerUtil.buildJson(data);
}
H2ParentConnectionContext(final Channel channel, final BufferAllocator allocator, final Executor executor,
final FlushStrategy flushStrategy, @Nullable final Long idleTimeoutMs,
final HttpExecutionStrategy executionStrategy,
final KeepAliveManager keepAliveManager) {
super(channel, executor);
this.executionContext = new DefaultHttpExecutionContext(allocator, fromNettyEventLoop(channel.eventLoop()),
executor, executionStrategy);
this.flushStrategyHolder = new FlushStrategyHolder(flushStrategy);
this.idleTimeoutMs = idleTimeoutMs;
this.keepAliveManager = keepAliveManager;
// Just in case the channel abruptly closes, we should complete the onClosing Completable.
onClose().subscribe(onClosing::onComplete);
}
@Test
public void failedConnectionAcquireNotifiesPromise() throws InterruptedException {
IOException exception = new IOException();
ChannelPool connectionPool = mock(ChannelPool.class);
when(connectionPool.acquire()).thenReturn(new FailedFuture<>(loopGroup.next(), exception));
ChannelPool pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup.next(), null);
Future<Channel> acquirePromise = pool.acquire().await();
assertThat(acquirePromise.isSuccess()).isFalse();
assertThat(acquirePromise.cause()).isEqualTo(exception);
}
private static boolean attachPublishEventOnChannel(RegisterMeta meta, Channel channel) {
Attribute<ConcurrentSet<RegisterMeta>> attr = channel.attr(C_PUBLISH_KEY);
ConcurrentSet<RegisterMeta> registerMetaSet = attr.get();
if (registerMetaSet == null) {
ConcurrentSet<RegisterMeta> newRegisterMetaSet = new ConcurrentSet<>();
registerMetaSet = attr.setIfAbsent(newRegisterMetaSet);
if (registerMetaSet == null) {
registerMetaSet = newRegisterMetaSet;
}
}
return registerMetaSet.add(meta);
}
public Channel getChannelByModelName(final String name) {
if (CollectionUtils.isNotEmpty(clients)) {
final Optional<Channel> first = clients.stream().filter(channel ->
Objects.equals(channel.remoteAddress().toString(), name))
.findFirst();
return first.orElse(null);
}
return null;
}
private static void verifyApplicationLevelProtocol(Channel channel, String expectedApplicationProtocol) {
SslHandler handler = channel.pipeline().get(SslHandler.class);
assertNotNull(handler);
String appProto = handler.applicationProtocol();
assertEquals(appProto, expectedApplicationProtocol);
SSLEngine engine = handler.engine();
if (engine instanceof Java9SslEngine) {
// Also verify the Java9 exposed method.
Java9SslEngine java9SslEngine = (Java9SslEngine) engine;
assertEquals(expectedApplicationProtocol == null ? StringUtil.EMPTY_STRING : expectedApplicationProtocol,
java9SslEngine.getApplicationProtocol());
}
}
/**
* B - S
* @param channel
* @param mqttMessage
*/
public void processUnSubBack(Channel channel, MqttMessage mqttMessage) {
int messageId;
if (mqttMessage instanceof MqttUnsubAckMessage) {
MqttUnsubAckMessage mqttUnsubAckMessage = (MqttUnsubAckMessage) mqttMessage;
messageId = mqttUnsubAckMessage.variableHeader().messageId();
} else {
MqttMessageIdVariableHeader o = (MqttMessageIdVariableHeader) mqttMessage.variableHeader();
messageId = o.messageId();
NettyLog.error("not UnsubAckMessage:{}", messageId);
}
this.consumerProcess.processUnSubBack(messageId);
}
@Override
protected ChannelFactory<? extends Channel> connectionFactory(EventLoopGroup elg, boolean isDomainSocket) {
if (isDomainSocket) {
throw new UnsupportedOperationException();
}
if (isPreferNative()) {
return () -> loopResources().onChannel(DatagramChannel.class, elg);
}
else {
return () -> new NioDatagramChannel(family());
}
}
/**
* Returns the correct Channel that wraps the given filedescriptor or {@code null} if not supported.
*
* @param group the {@link EventLoopGroup} for which the class is needed
* @param address the filedescriptor to wrap.
* @return the class that should be used for bootstrapping
*/
@Nullable
public static Channel socketChannel(EventLoopGroup group, FileDescriptorSocketAddress address) {
if (useEpoll(group)) {
return new EpollSocketChannel(address.getValue());
}
if (useKQueue(group)) {
return new KQueueSocketChannel(address.getValue());
}
return null;
}
public ListenableFuture<FullHttpResponse> execute() throws URISyntaxException {
Preconditions.checkState(request != null);
final SettableFuture<FullHttpResponse> error = SettableFuture.create();
final SettableFuture<FullHttpResponse> response = SettableFuture.create();
final ListenableFuture<ChannelFuture> connectFuture =
connect(XUrl.inetSocket(uri), client.bootstrap(), buildRetryLoop());
Futures.addCallback(
connectFuture,
new FutureCallback<ChannelFuture>() {
@Override
public void onSuccess(ChannelFuture result) {
try {
Channel channel = result.await().channel();
channel.writeAndFlush(request);
HttpResponseHandler responseHandler =
(HttpResponseHandler) channel.pipeline().get("responseHandler");
response.setFuture(responseHandler.response());
} catch (InterruptedException e) {
response.cancel(true);
error.setException(e);
}
}
@Override
public void onFailure(Throwable t) {
response.cancel(true);
error.setException(t);
}
},
MoreExecutors.directExecutor());
if (response.isCancelled()) {
return error;
} else {
return response;
}
}
@Nullable
protected String getIp(Channel channel) {
SocketAddress address = channel.remoteAddress();
if(address instanceof InetSocketAddress) {
return ((InetSocketAddress) address).getAddress().getHostAddress();
}
else {
logger.warn("Non inet socket address from client: {}", address);
return null;
}
}