repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/codec/CodecAdapter.java
dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/codec/CodecAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.codec; import org.apache.dubbo.common.io.UnsafeByteArrayInputStream; import org.apache.dubbo.common.io.UnsafeByteArrayOutputStream; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.Codec; import org.apache.dubbo.remoting.Codec2; import org.apache.dubbo.remoting.buffer.ChannelBuffer; import java.io.IOException; public class CodecAdapter implements Codec2 { private Codec codec; public CodecAdapter(Codec codec) { Assert.notNull(codec, "codec == null"); this.codec = codec; } @Override public void encode(Channel channel, ChannelBuffer buffer, Object message) throws IOException { UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream(1024); codec.encode(channel, os, message); buffer.writeBytes(os.toByteArray()); } @Override public Object decode(Channel channel, ChannelBuffer buffer) throws IOException { byte[] bytes = new byte[buffer.readableBytes()]; int savedReaderIndex = buffer.readerIndex(); buffer.readBytes(bytes); UnsafeByteArrayInputStream is = new UnsafeByteArrayInputStream(bytes); Object result = codec.decode(channel, is); buffer.readerIndex(savedReaderIndex + is.position()); return result == Codec.NEED_MORE_INPUT ? DecodeResult.NEED_MORE_INPUT : result; } public Codec getCodec() { return codec; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/ChannelHandlers.java
dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/ChannelHandlers.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.dispatcher; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Dispatcher; import org.apache.dubbo.remoting.exchange.support.header.HeartbeatHandler; import org.apache.dubbo.remoting.transport.MultiMessageHandler; public class ChannelHandlers { private static ChannelHandlers INSTANCE = new ChannelHandlers(); protected ChannelHandlers() {} public static ChannelHandler wrap(ChannelHandler handler, URL url) { return ChannelHandlers.getInstance().wrapInternal(handler, url); } public static ChannelHandlers getInstance() { return INSTANCE; } static void setTestingChannelHandlers(ChannelHandlers instance) { INSTANCE = instance; } protected ChannelHandler wrapInternal(ChannelHandler handler, URL url) { return new MultiMessageHandler(new HeartbeatHandler(url.getOrDefaultFrameworkModel() .getExtensionLoader(Dispatcher.class) .getAdaptiveExtension() .dispatch(handler, url))); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/WrappedChannelHandler.java
dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/WrappedChannelHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.dispatcher; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.resource.GlobalResourcesRepository; import org.apache.dubbo.common.threadpool.manager.ExecutorRepository; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.Response; import org.apache.dubbo.remoting.exchange.support.DefaultFuture; import org.apache.dubbo.remoting.transport.ChannelHandlerDelegate; import org.apache.dubbo.rpc.executor.ExecutorSupport; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; public class WrappedChannelHandler implements ChannelHandlerDelegate { protected static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(WrappedChannelHandler.class); protected final ChannelHandler handler; protected final URL url; protected final ExecutorSupport executorSupport; public WrappedChannelHandler(ChannelHandler handler, URL url) { this.handler = handler; this.url = url; this.executorSupport = ExecutorRepository.getInstance(url.getOrDefaultApplicationModel()) .getExecutorSupport(url); } public void close() {} @Override public void connected(Channel channel) throws RemotingException { handler.connected(channel); } @Override public void disconnected(Channel channel) throws RemotingException { handler.disconnected(channel); } @Override public void sent(Channel channel, Object message) throws RemotingException { handler.sent(channel, message); } @Override public void received(Channel channel, Object message) throws RemotingException { handler.received(channel, message); } @Override public void caught(Channel channel, Throwable exception) throws RemotingException { handler.caught(channel, exception); } protected void sendFeedback(Channel channel, Request request, Throwable t) throws RemotingException { if (!request.isTwoWay()) { return; } String msg = "Server side(" + url.getIp() + "," + url.getPort() + ") thread pool is exhausted, detail msg:" + t.getMessage(); Response response = new Response(request.getId(), request.getVersion()); response.setStatus(Response.SERVER_THREADPOOL_EXHAUSTED_ERROR); response.setErrorMessage(msg); channel.send(response); } @Override public ChannelHandler getHandler() { if (handler instanceof ChannelHandlerDelegate) { return ((ChannelHandlerDelegate) handler).getHandler(); } else { return handler; } } public URL getUrl() { return url; } /** * Currently, this method is mainly customized to facilitate the thread model on consumer side. * 1. Use ThreadlessExecutor, aka., delegate callback directly to the thread initiating the call. * 2. Use shared executor to execute the callback. * * @param msg * @return */ public ExecutorService getPreferredExecutorService(Object msg) { if (msg instanceof Response) { Response response = (Response) msg; DefaultFuture responseFuture = DefaultFuture.getFuture(response.getId()); // a typical scenario is the response returned after timeout, the timeout response may have completed the // future if (responseFuture == null) { return getSharedExecutorService(); } else { ExecutorService executor = responseFuture.getExecutor(); if (executor == null || executor.isShutdown()) { executor = getSharedExecutorService(msg); } return executor; } } else { return getSharedExecutorService(msg); } } /** * @param msg msg is the network message body, executorSupport.getExecutor needs it, and gets important information from it to get executor * @return */ public ExecutorService getSharedExecutorService(Object msg) { Executor executor = executorSupport.getExecutor(msg); return executor != null ? (ExecutorService) executor : getSharedExecutorService(); } /** * get the shared executor for current Server or Client * * @return */ public ExecutorService getSharedExecutorService() { // Application may be destroyed before channel disconnected, avoid create new application model // see https://github.com/apache/dubbo/issues/9127 if (url.getApplicationModel() == null || url.getApplicationModel().isDestroyed()) { return GlobalResourcesRepository.getGlobalExecutorService(); } // note: url.getOrDefaultApplicationModel() may create new application model ApplicationModel applicationModel = url.getOrDefaultApplicationModel(); ExecutorRepository executorRepository = ExecutorRepository.getInstance(applicationModel); ExecutorService executor = executorRepository.getExecutor(url); if (executor == null) { executor = executorRepository.createExecutorIfAbsent(url); } return executor; } @Deprecated public ExecutorService getExecutorService() { return getSharedExecutorService(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/ChannelEventRunnable.java
dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/ChannelEventRunnable.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.dispatcher; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.threadlocal.InternalThreadLocalMap; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR; public class ChannelEventRunnable implements Runnable { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ChannelEventRunnable.class); private final ChannelHandler handler; private final Channel channel; private final ChannelState state; private final Throwable exception; private final Object message; public ChannelEventRunnable(Channel channel, ChannelHandler handler, ChannelState state) { this(channel, handler, state, null); } public ChannelEventRunnable(Channel channel, ChannelHandler handler, ChannelState state, Object message) { this(channel, handler, state, message, null); } public ChannelEventRunnable(Channel channel, ChannelHandler handler, ChannelState state, Throwable t) { this(channel, handler, state, null, t); } public ChannelEventRunnable( Channel channel, ChannelHandler handler, ChannelState state, Object message, Throwable exception) { this.channel = channel; this.handler = handler; this.state = state; this.message = message; this.exception = exception; } @Override public void run() { InternalThreadLocalMap internalThreadLocalMap = InternalThreadLocalMap.getAndRemove(); try { if (state == ChannelState.RECEIVED) { try { handler.received(channel, message); } catch (Exception e) { logger.warn( INTERNAL_ERROR, "unknown error in remoting module", "", "ChannelEventRunnable handle " + state + " operation error, channel is " + channel + ", message is " + message, e); } } else { switch (state) { case CONNECTED: try { handler.connected(channel); } catch (Exception e) { logger.warn( INTERNAL_ERROR, "unknown error in remoting module", "", "ChannelEventRunnable handle " + state + " operation error, channel is " + channel, e); } break; case DISCONNECTED: try { handler.disconnected(channel); } catch (Exception e) { logger.warn( INTERNAL_ERROR, "unknown error in remoting module", "", "ChannelEventRunnable handle " + state + " operation error, channel is " + channel, e); } break; case SENT: try { handler.sent(channel, message); } catch (Exception e) { logger.warn( INTERNAL_ERROR, "unknown error in remoting module", "", "ChannelEventRunnable handle " + state + " operation error, channel is " + channel + ", message is " + message, e); } break; case CAUGHT: try { handler.caught(channel, exception); } catch (Exception e) { logger.warn( INTERNAL_ERROR, "unknown error in remoting module", "", "ChannelEventRunnable handle " + state + " operation error, channel is " + channel + ", message is: " + message + ", exception is " + exception, e); } break; default: logger.warn( INTERNAL_ERROR, "unknown error in remoting module", "", "unknown state: " + state + ", message is " + message); } } } finally { InternalThreadLocalMap.set(internalThreadLocalMap); } } /** * ChannelState */ public enum ChannelState { /** * CONNECTED */ CONNECTED, /** * DISCONNECTED */ DISCONNECTED, /** * SENT */ SENT, /** * RECEIVED */ RECEIVED, /** * CAUGHT */ CAUGHT } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/execution/ExecutionChannelHandler.java
dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/execution/ExecutionChannelHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.dispatcher.execution; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.threadpool.ThreadlessExecutor; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.ExecutionException; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.transport.dispatcher.ChannelEventRunnable; import org.apache.dubbo.remoting.transport.dispatcher.ChannelEventRunnable.ChannelState; import org.apache.dubbo.remoting.transport.dispatcher.WrappedChannelHandler; import java.util.concurrent.ExecutorService; import java.util.concurrent.RejectedExecutionException; /** * Only request message will be dispatched to thread pool. Other messages like response, connect, disconnect, * heartbeat will be directly executed by I/O thread. */ public class ExecutionChannelHandler extends WrappedChannelHandler { public ExecutionChannelHandler(ChannelHandler handler, URL url) { super(handler, url); } @Override public void received(Channel channel, Object message) throws RemotingException { ExecutorService executor = getPreferredExecutorService(message); if (message instanceof Request) { try { executor.execute(new ChannelEventRunnable(channel, handler, ChannelState.RECEIVED, message)); } catch (Throwable t) { // FIXME: when the thread pool is full, SERVER_THREADPOOL_EXHAUSTED_ERROR cannot return properly, // therefore the consumer side has to wait until gets timeout. This is a temporary solution to prevent // this scenario from happening, but a better solution should be considered later. if (t instanceof RejectedExecutionException) { sendFeedback(channel, (Request) message, t); } throw new ExecutionException(message, channel, getClass() + " error when process received event.", t); } } else if (executor instanceof ThreadlessExecutor) { executor.execute(new ChannelEventRunnable(channel, handler, ChannelState.RECEIVED, message)); } else { handler.received(channel, message); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/execution/ExecutionDispatcher.java
dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/execution/ExecutionDispatcher.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.dispatcher.execution; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Dispatcher; /** * In addition to sending all the use thread pool processing */ public class ExecutionDispatcher implements Dispatcher { public static final String NAME = "execution"; @Override public ChannelHandler dispatch(ChannelHandler handler, URL url) { return new ExecutionChannelHandler(handler, url); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedChannelHandler.java
dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedChannelHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.dispatcher.connection; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.threadpool.support.AbortPolicyWithReport; import org.apache.dubbo.common.utils.NamedThreadFactory; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.ExecutionException; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.transport.dispatcher.ChannelEventRunnable; import org.apache.dubbo.remoting.transport.dispatcher.ChannelEventRunnable.ChannelState; import org.apache.dubbo.remoting.transport.dispatcher.WrappedChannelHandler; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREAD_NAME; import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_CONNECTION_LIMIT_EXCEED; import static org.apache.dubbo.remoting.Constants.CONNECT_QUEUE_CAPACITY; import static org.apache.dubbo.remoting.Constants.CONNECT_QUEUE_WARNING_SIZE; import static org.apache.dubbo.remoting.Constants.DEFAULT_CONNECT_QUEUE_WARNING_SIZE; public class ConnectionOrderedChannelHandler extends WrappedChannelHandler { protected final ThreadPoolExecutor connectionExecutor; private final int queueWarningLimit; public ConnectionOrderedChannelHandler(ChannelHandler handler, URL url) { super(handler, url); String threadName = url.getParameter(THREAD_NAME_KEY, DEFAULT_THREAD_NAME); connectionExecutor = new ThreadPoolExecutor( 1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(url.getPositiveParameter(CONNECT_QUEUE_CAPACITY, Integer.MAX_VALUE)), new NamedThreadFactory(threadName, true), new AbortPolicyWithReport(threadName, url)); // FIXME There's no place to release connectionExecutor! queueWarningLimit = url.getParameter(CONNECT_QUEUE_WARNING_SIZE, DEFAULT_CONNECT_QUEUE_WARNING_SIZE); } @Override public void connected(Channel channel) throws RemotingException { try { checkQueueLength(); connectionExecutor.execute(new ChannelEventRunnable(channel, handler, ChannelState.CONNECTED)); } catch (Throwable t) { throw new ExecutionException( "connect event", channel, getClass() + " error when process connected event .", t); } } @Override public void disconnected(Channel channel) throws RemotingException { try { checkQueueLength(); connectionExecutor.execute(new ChannelEventRunnable(channel, handler, ChannelState.DISCONNECTED)); } catch (Throwable t) { throw new ExecutionException( "disconnected event", channel, getClass() + " error when process disconnected event .", t); } } @Override public void received(Channel channel, Object message) throws RemotingException { ExecutorService executor = getPreferredExecutorService(message); try { executor.execute(new ChannelEventRunnable(channel, handler, ChannelState.RECEIVED, message)); } catch (Throwable t) { if (message instanceof Request && t instanceof RejectedExecutionException) { sendFeedback(channel, (Request) message, t); return; } throw new ExecutionException(message, channel, getClass() + " error when process received event .", t); } } @Override public void caught(Channel channel, Throwable exception) throws RemotingException { ExecutorService executor = getSharedExecutorService(); try { executor.execute(new ChannelEventRunnable(channel, handler, ChannelState.CAUGHT, exception)); } catch (Throwable t) { throw new ExecutionException("caught event", channel, getClass() + " error when process caught event .", t); } } private void checkQueueLength() { if (connectionExecutor.getQueue().size() > queueWarningLimit) { logger.warn( TRANSPORT_CONNECTION_LIMIT_EXCEED, "", "", "connectionordered channel handler queue size: " + connectionExecutor.getQueue().size() + " exceed the warning limit number :" + queueWarningLimit); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedDispatcher.java
dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedDispatcher.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.dispatcher.connection; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Dispatcher; /** * connect disconnect ensure the order */ public class ConnectionOrderedDispatcher implements Dispatcher { public static final String NAME = "connection"; @Override public ChannelHandler dispatch(ChannelHandler handler, URL url) { return new ConnectionOrderedChannelHandler(handler, url); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/message/MessageOnlyChannelHandler.java
dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/message/MessageOnlyChannelHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.dispatcher.message; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.ExecutionException; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.transport.dispatcher.ChannelEventRunnable; import org.apache.dubbo.remoting.transport.dispatcher.ChannelEventRunnable.ChannelState; import org.apache.dubbo.remoting.transport.dispatcher.WrappedChannelHandler; import java.util.concurrent.ExecutorService; import java.util.concurrent.RejectedExecutionException; public class MessageOnlyChannelHandler extends WrappedChannelHandler { public MessageOnlyChannelHandler(ChannelHandler handler, URL url) { super(handler, url); } @Override public void received(Channel channel, Object message) throws RemotingException { ExecutorService executor = getPreferredExecutorService(message); try { executor.execute(new ChannelEventRunnable(channel, handler, ChannelState.RECEIVED, message)); } catch (Throwable t) { if (message instanceof Request && t instanceof RejectedExecutionException) { sendFeedback(channel, (Request) message, t); return; } throw new ExecutionException(message, channel, getClass() + " error when process received event .", t); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/message/MessageOnlyDispatcher.java
dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/message/MessageOnlyDispatcher.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.dispatcher.message; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Dispatcher; /** * Only message receive uses the thread pool. */ public class MessageOnlyDispatcher implements Dispatcher { public static final String NAME = "message"; @Override public ChannelHandler dispatch(ChannelHandler handler, URL url) { return new MessageOnlyChannelHandler(handler, url); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/all/AllDispatcher.java
dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/all/AllDispatcher.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.dispatcher.all; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Dispatcher; /** * default thread pool configure */ public class AllDispatcher implements Dispatcher { public static final String NAME = "all"; @Override public ChannelHandler dispatch(ChannelHandler handler, URL url) { return new AllChannelHandler(handler, url); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/all/AllChannelHandler.java
dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/all/AllChannelHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.dispatcher.all; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.ExecutionException; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.transport.dispatcher.ChannelEventRunnable; import org.apache.dubbo.remoting.transport.dispatcher.ChannelEventRunnable.ChannelState; import org.apache.dubbo.remoting.transport.dispatcher.WrappedChannelHandler; import java.util.concurrent.ExecutorService; import java.util.concurrent.RejectedExecutionException; public class AllChannelHandler extends WrappedChannelHandler { public AllChannelHandler(ChannelHandler handler, URL url) { super(handler, url); } @Override public void connected(Channel channel) throws RemotingException { ExecutorService executor = getSharedExecutorService(); try { executor.execute(new ChannelEventRunnable(channel, handler, ChannelState.CONNECTED)); } catch (Throwable t) { throw new ExecutionException( "connect event", channel, getClass() + " error when process connected event .", t); } } @Override public void disconnected(Channel channel) throws RemotingException { ExecutorService executor = getSharedExecutorService(); try { executor.execute(new ChannelEventRunnable(channel, handler, ChannelState.DISCONNECTED)); } catch (Throwable t) { throw new ExecutionException( "disconnect event", channel, getClass() + " error when process disconnected event .", t); } } @Override public void received(Channel channel, Object message) throws RemotingException { ExecutorService executor = getPreferredExecutorService(message); try { executor.execute(new ChannelEventRunnable(channel, handler, ChannelState.RECEIVED, message)); } catch (Throwable t) { if (message instanceof Request && t instanceof RejectedExecutionException) { sendFeedback(channel, (Request) message, t); return; } throw new ExecutionException(message, channel, getClass() + " error when process received event .", t); } } @Override public void caught(Channel channel, Throwable exception) throws RemotingException { ExecutorService executor = getSharedExecutorService(); try { executor.execute(new ChannelEventRunnable(channel, handler, ChannelState.CAUGHT, exception)); } catch (Throwable t) { throw new ExecutionException("caught event", channel, getClass() + " error when process caught event .", t); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/direct/DirectDispatcher.java
dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/direct/DirectDispatcher.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.dispatcher.direct; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Dispatcher; /** * Direct dispatcher */ public class DirectDispatcher implements Dispatcher { public static final String NAME = "direct"; @Override public ChannelHandler dispatch(ChannelHandler handler, URL url) { return new DirectChannelHandler(handler, url); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/direct/DirectChannelHandler.java
dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/direct/DirectChannelHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.dispatcher.direct; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.threadpool.ThreadlessExecutor; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.ExecutionException; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.transport.dispatcher.ChannelEventRunnable; import org.apache.dubbo.remoting.transport.dispatcher.ChannelEventRunnable.ChannelState; import org.apache.dubbo.remoting.transport.dispatcher.WrappedChannelHandler; import java.util.concurrent.ExecutorService; public class DirectChannelHandler extends WrappedChannelHandler { public DirectChannelHandler(ChannelHandler handler, URL url) { super(handler, url); } @Override public void received(Channel channel, Object message) throws RemotingException { ExecutorService executor = getPreferredExecutorService(message); if (executor instanceof ThreadlessExecutor) { try { executor.execute(new ChannelEventRunnable(channel, handler, ChannelState.RECEIVED, message)); } catch (Throwable t) { throw new ExecutionException(message, channel, getClass() + " error when process received event .", t); } } else { handler.received(channel, message); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ChannelBufferFactory.java
dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ChannelBufferFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.buffer; import java.nio.ByteBuffer; public interface ChannelBufferFactory { ChannelBuffer getBuffer(int capacity); ChannelBuffer getBuffer(byte[] array, int offset, int length); ChannelBuffer getBuffer(ByteBuffer nioBuffer); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/DynamicChannelBuffer.java
dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/DynamicChannelBuffer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.buffer; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; public class DynamicChannelBuffer extends AbstractChannelBuffer { private final ChannelBufferFactory factory; private ChannelBuffer buffer; public DynamicChannelBuffer(int estimatedLength) { this(estimatedLength, HeapChannelBufferFactory.getInstance()); } public DynamicChannelBuffer(int estimatedLength, ChannelBufferFactory factory) { if (estimatedLength < 0) { throw new IllegalArgumentException("estimatedLength: " + estimatedLength); } if (factory == null) { throw new NullPointerException("factory"); } this.factory = factory; this.buffer = factory.getBuffer(estimatedLength); } @Override public void ensureWritableBytes(int minWritableBytes) { if (minWritableBytes <= writableBytes()) { return; } int newCapacity = capacity() == 0 ? 1 : capacity(); int minNewCapacity = writerIndex() + minWritableBytes; while (newCapacity < minNewCapacity) { newCapacity <<= 1; } ChannelBuffer newBuffer = factory().getBuffer(newCapacity); newBuffer.writeBytes(buffer, 0, writerIndex()); buffer = newBuffer; } @Override public int capacity() { return buffer.capacity(); } @Override public ChannelBuffer copy(int index, int length) { DynamicChannelBuffer copiedBuffer = new DynamicChannelBuffer(Math.max(length, 64), factory()); copiedBuffer.buffer = buffer.copy(index, length); copiedBuffer.setIndex(0, length); return copiedBuffer; } @Override public ChannelBufferFactory factory() { return factory; } @Override public byte getByte(int index) { return buffer.getByte(index); } @Override public void getBytes(int index, byte[] dst, int dstIndex, int length) { buffer.getBytes(index, dst, dstIndex, length); } @Override public void getBytes(int index, ByteBuffer dst) { buffer.getBytes(index, dst); } @Override public void getBytes(int index, ChannelBuffer dst, int dstIndex, int length) { buffer.getBytes(index, dst, dstIndex, length); } @Override public void getBytes(int index, OutputStream dst, int length) throws IOException { buffer.getBytes(index, dst, length); } @Override public boolean isDirect() { return buffer.isDirect(); } @Override public void setByte(int index, int value) { buffer.setByte(index, value); } @Override public void setBytes(int index, byte[] src, int srcIndex, int length) { buffer.setBytes(index, src, srcIndex, length); } @Override public void setBytes(int index, ByteBuffer src) { buffer.setBytes(index, src); } @Override public void setBytes(int index, ChannelBuffer src, int srcIndex, int length) { buffer.setBytes(index, src, srcIndex, length); } @Override public int setBytes(int index, InputStream src, int length) throws IOException { return buffer.setBytes(index, src, length); } @Override public ByteBuffer toByteBuffer(int index, int length) { return buffer.toByteBuffer(index, length); } @Override public void writeByte(int value) { ensureWritableBytes(1); super.writeByte(value); } @Override public void writeBytes(byte[] src, int srcIndex, int length) { ensureWritableBytes(length); super.writeBytes(src, srcIndex, length); } @Override public void writeBytes(ChannelBuffer src, int srcIndex, int length) { ensureWritableBytes(length); super.writeBytes(src, srcIndex, length); } @Override public void writeBytes(ByteBuffer src) { ensureWritableBytes(src.remaining()); super.writeBytes(src); } @Override public int writeBytes(InputStream in, int length) throws IOException { ensureWritableBytes(length); return super.writeBytes(in, length); } @Override public byte[] array() { return buffer.array(); } @Override public boolean hasArray() { return buffer.hasArray(); } @Override public int arrayOffset() { return buffer.arrayOffset(); } @Override public void release() { buffer.release(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ChannelBufferInputStream.java
dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ChannelBufferInputStream.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.buffer; import java.io.IOException; import java.io.InputStream; public class ChannelBufferInputStream extends InputStream { private final ChannelBuffer buffer; private final int startIndex; private final int endIndex; public ChannelBufferInputStream(ChannelBuffer buffer) { this(buffer, buffer.readableBytes()); } public ChannelBufferInputStream(ChannelBuffer buffer, int length) { if (buffer == null) { throw new NullPointerException("buffer"); } if (length < 0) { throw new IllegalArgumentException("length: " + length); } if (length > buffer.readableBytes()) { throw new IndexOutOfBoundsException(); } this.buffer = buffer; startIndex = buffer.readerIndex(); endIndex = startIndex + length; buffer.markReaderIndex(); } public int readBytes() { return buffer.readerIndex() - startIndex; } @Override public int available() throws IOException { return endIndex - buffer.readerIndex(); } @Override public synchronized void mark(int readLimit) { buffer.markReaderIndex(); } @Override public boolean markSupported() { return true; } @Override public int read() throws IOException { if (!buffer.readable()) { return -1; } return buffer.readByte() & 0xff; } @Override public int read(byte[] b, int off, int len) throws IOException { int available = available(); if (available == 0) { return -1; } len = Math.min(available, len); buffer.readBytes(b, off, len); return len; } @Override public synchronized void reset() throws IOException { buffer.resetReaderIndex(); } @Override public long skip(long n) throws IOException { if (n > Integer.MAX_VALUE) { return skipBytes(Integer.MAX_VALUE); } else { return skipBytes((int) n); } } private int skipBytes(int n) throws IOException { int nBytes = Math.min(available(), n); buffer.skipBytes(nBytes); return nBytes; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/HeapChannelBufferFactory.java
dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/HeapChannelBufferFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.buffer; import java.nio.ByteBuffer; public class HeapChannelBufferFactory implements ChannelBufferFactory { private static final HeapChannelBufferFactory INSTANCE = new HeapChannelBufferFactory(); public HeapChannelBufferFactory() { super(); } public static ChannelBufferFactory getInstance() { return INSTANCE; } @Override public ChannelBuffer getBuffer(int capacity) { return ChannelBuffers.buffer(capacity); } @Override public ChannelBuffer getBuffer(byte[] array, int offset, int length) { return ChannelBuffers.wrappedBuffer(array, offset, length); } @Override public ChannelBuffer getBuffer(ByteBuffer nioBuffer) { if (nioBuffer.hasArray()) { return ChannelBuffers.wrappedBuffer(nioBuffer); } ChannelBuffer buf = getBuffer(nioBuffer.remaining()); int pos = nioBuffer.position(); buf.writeBytes(nioBuffer); nioBuffer.position(pos); return buf; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/AbstractChannelBuffer.java
dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/AbstractChannelBuffer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.buffer; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; public abstract class AbstractChannelBuffer implements ChannelBuffer { private int readerIndex; private int writerIndex; private int markedReaderIndex; private int markedWriterIndex; @Override public int readerIndex() { return readerIndex; } @Override public void readerIndex(int readerIndex) { if (readerIndex < 0 || readerIndex > writerIndex) { throw new IndexOutOfBoundsException(); } this.readerIndex = readerIndex; } @Override public int writerIndex() { return writerIndex; } @Override public void writerIndex(int writerIndex) { if (writerIndex < readerIndex || writerIndex > capacity()) { throw new IndexOutOfBoundsException(); } this.writerIndex = writerIndex; } @Override public void setIndex(int readerIndex, int writerIndex) { if (readerIndex < 0 || readerIndex > writerIndex || writerIndex > capacity()) { throw new IndexOutOfBoundsException(); } this.readerIndex = readerIndex; this.writerIndex = writerIndex; } @Override public void clear() { readerIndex = writerIndex = 0; } @Override public boolean readable() { return readableBytes() > 0; } @Override public boolean writable() { return writableBytes() > 0; } @Override public int readableBytes() { return writerIndex - readerIndex; } @Override public int writableBytes() { return capacity() - writerIndex; } @Override public void markReaderIndex() { markedReaderIndex = readerIndex; } @Override public void resetReaderIndex() { readerIndex(markedReaderIndex); } @Override public void markWriterIndex() { markedWriterIndex = writerIndex; } @Override public void resetWriterIndex() { writerIndex = markedWriterIndex; } @Override public void discardReadBytes() { if (readerIndex == 0) { return; } setBytes(0, this, readerIndex, writerIndex - readerIndex); writerIndex -= readerIndex; markedReaderIndex = Math.max(markedReaderIndex - readerIndex, 0); markedWriterIndex = Math.max(markedWriterIndex - readerIndex, 0); readerIndex = 0; } @Override public void ensureWritableBytes(int writableBytes) { if (writableBytes > writableBytes()) { throw new IndexOutOfBoundsException(); } } @Override public void getBytes(int index, byte[] dst) { getBytes(index, dst, 0, dst.length); } @Override public void getBytes(int index, ChannelBuffer dst) { getBytes(index, dst, dst.writableBytes()); } @Override public void getBytes(int index, ChannelBuffer dst, int length) { if (length > dst.writableBytes()) { throw new IndexOutOfBoundsException(); } getBytes(index, dst, dst.writerIndex(), length); dst.writerIndex(dst.writerIndex() + length); } @Override public void setBytes(int index, byte[] src) { setBytes(index, src, 0, src.length); } @Override public void setBytes(int index, ChannelBuffer src) { setBytes(index, src, src.readableBytes()); } @Override public void setBytes(int index, ChannelBuffer src, int length) { if (length > src.readableBytes()) { throw new IndexOutOfBoundsException(); } setBytes(index, src, src.readerIndex(), length); src.readerIndex(src.readerIndex() + length); } @Override public byte readByte() { if (readerIndex == writerIndex) { throw new IndexOutOfBoundsException(); } return getByte(readerIndex++); } @Override public ChannelBuffer readBytes(int length) { checkReadableBytes(length); if (length == 0) { return ChannelBuffers.EMPTY_BUFFER; } ChannelBuffer buf = factory().getBuffer(length); buf.writeBytes(this, readerIndex, length); readerIndex += length; return buf; } @Override public void readBytes(byte[] dst, int dstIndex, int length) { checkReadableBytes(length); getBytes(readerIndex, dst, dstIndex, length); readerIndex += length; } @Override public void readBytes(byte[] dst) { readBytes(dst, 0, dst.length); } @Override public void readBytes(ChannelBuffer dst) { readBytes(dst, dst.writableBytes()); } @Override public void readBytes(ChannelBuffer dst, int length) { if (length > dst.writableBytes()) { throw new IndexOutOfBoundsException(); } readBytes(dst, dst.writerIndex(), length); dst.writerIndex(dst.writerIndex() + length); } @Override public void readBytes(ChannelBuffer dst, int dstIndex, int length) { checkReadableBytes(length); getBytes(readerIndex, dst, dstIndex, length); readerIndex += length; } @Override public void readBytes(ByteBuffer dst) { int length = dst.remaining(); checkReadableBytes(length); getBytes(readerIndex, dst); readerIndex += length; } @Override public void readBytes(OutputStream out, int length) throws IOException { checkReadableBytes(length); getBytes(readerIndex, out, length); readerIndex += length; } @Override public void skipBytes(int length) { int newReaderIndex = readerIndex + length; if (newReaderIndex > writerIndex) { throw new IndexOutOfBoundsException(); } readerIndex = newReaderIndex; } @Override public void writeByte(int value) { setByte(writerIndex++, value); } @Override public void writeBytes(byte[] src, int srcIndex, int length) { setBytes(writerIndex, src, srcIndex, length); writerIndex += length; } @Override public void writeBytes(byte[] src) { writeBytes(src, 0, src.length); } @Override public void writeBytes(ChannelBuffer src) { writeBytes(src, src.readableBytes()); } @Override public void writeBytes(ChannelBuffer src, int length) { if (length > src.readableBytes()) { throw new IndexOutOfBoundsException(); } writeBytes(src, src.readerIndex(), length); src.readerIndex(src.readerIndex() + length); } @Override public void writeBytes(ChannelBuffer src, int srcIndex, int length) { setBytes(writerIndex, src, srcIndex, length); writerIndex += length; } @Override public void writeBytes(ByteBuffer src) { int length = src.remaining(); setBytes(writerIndex, src); writerIndex += length; } @Override public int writeBytes(InputStream in, int length) throws IOException { int writtenBytes = setBytes(writerIndex, in, length); if (writtenBytes > 0) { writerIndex += writtenBytes; } return writtenBytes; } @Override public ChannelBuffer copy() { return copy(readerIndex, readableBytes()); } @Override public ByteBuffer toByteBuffer() { return toByteBuffer(readerIndex, readableBytes()); } @Override public boolean equals(Object o) { return o instanceof ChannelBuffer && ChannelBuffers.equals(this, (ChannelBuffer) o); } @Override public int hashCode() { return ChannelBuffers.hasCode(this); } @Override public int compareTo(ChannelBuffer that) { return ChannelBuffers.compare(this, that); } @Override public String toString() { return getClass().getSimpleName() + '(' + "ridx=" + readerIndex + ", " + "widx=" + writerIndex + ", " + "cap=" + capacity() + ')'; } protected void checkReadableBytes(int minimumReadableBytes) { if (readableBytes() < minimumReadableBytes) { throw new IndexOutOfBoundsException(); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ChannelBufferOutputStream.java
dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ChannelBufferOutputStream.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.buffer; import java.io.IOException; import java.io.OutputStream; public class ChannelBufferOutputStream extends OutputStream { private final ChannelBuffer buffer; private final int startIndex; public ChannelBufferOutputStream(ChannelBuffer buffer) { if (buffer == null) { throw new NullPointerException("buffer"); } this.buffer = buffer; startIndex = buffer.writerIndex(); } public int writtenBytes() { return buffer.writerIndex() - startIndex; } @Override public void write(byte[] b, int off, int len) throws IOException { if (len == 0) { return; } buffer.writeBytes(b, off, len); } @Override public void write(byte[] b) throws IOException { buffer.writeBytes(b); } @Override public void write(int b) throws IOException { buffer.writeByte((byte) b); } public ChannelBuffer buffer() { return buffer; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ChannelBuffer.java
dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ChannelBuffer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.buffer; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; /** * A random and sequential accessible sequence of zero or more bytes (octets). * This interface provides an abstract view for one or more primitive byte * arrays ({@code byte[]}) and {@linkplain ByteBuffer NIO buffers}. * <p/> * <h3>Creation of a buffer</h3> * <p/> * It is recommended to create a new buffer using the helper methods in {@link * ChannelBuffers} rather than calling an individual implementation's * constructor. * <p/> * <h3>Random Access Indexing</h3> * <p/> * Just like an ordinary primitive byte array, {@link ChannelBuffer} uses <a * href="http://en.wikipedia.org/wiki/Index_(information_technology)#Array_element_identifier">zero-based * indexing</a>. It means the index of the first byte is always {@code 0} and * the index of the last byte is always {@link #capacity() capacity - 1}. For * example, to iterate all bytes of a buffer, you can do the following, * regardless of its internal implementation: * <p/> * <pre> * {@link ChannelBuffer} buffer = ...; * for (int i = 0; i &lt; buffer.capacity(); i ++</strong>) { * byte b = buffer.getByte(i); * System.out.println((char) b); * } * </pre> * <p/> * <h3>Sequential Access Indexing</h3> * <p/> * {@link ChannelBuffer} provides two pointer variables to support sequential * read and write operations - {@link #readerIndex() readerIndex} for a read * operation and {@link #writerIndex() writerIndex} for a write operation * respectively. The following diagram shows how a buffer is segmented into * three areas by the two pointers: * <p/> * <pre> * +-------------------+------------------+------------------+ * | discardable bytes | readable bytes | writable bytes | * | | (CONTENT) | | * +-------------------+------------------+------------------+ * | | | | * 0 <= readerIndex <= writerIndex <= capacity * </pre> * <p/> * <h4>Readable bytes (the actual content)</h4> * <p/> * This segment is where the actual data is stored. Any operation whose name * starts with {@code read} or {@code skip} will get or skip the data at the * current {@link #readerIndex() readerIndex} and increase it by the number of * read bytes. If the argument of the read operation is also a {@link * ChannelBuffer} and no destination index is specified, the specified buffer's * {@link #readerIndex() readerIndex} is increased together. * <p/> * If there's not enough content left, {@link IndexOutOfBoundsException} is * raised. The default value of newly allocated, wrapped or copied buffer's * {@link #readerIndex() readerIndex} is {@code 0}. * <p/> * <pre> * // Iterates the readable bytes of a buffer. * {@link ChannelBuffer} buffer = ...; * while (buffer.readable()) { * System.out.println(buffer.readByte()); * } * </pre> * <p/> * <h4>Writable bytes</h4> * <p/> * This segment is a undefined space which needs to be filled. Any operation * whose name ends with {@code write} will write the data at the current {@link * #writerIndex() writerIndex} and increase it by the number of written bytes. * If the argument of the write operation is also a {@link ChannelBuffer}, and * no source index is specified, the specified buffer's {@link #readerIndex() * readerIndex} is increased together. * <p/> * If there's not enough writable bytes left, {@link IndexOutOfBoundsException} * is raised. The default value of newly allocated buffer's {@link * #writerIndex() writerIndex} is {@code 0}. The default value of wrapped or * copied buffer's {@link #writerIndex() writerIndex} is the {@link #capacity() * capacity} of the buffer. * <p/> * <pre> * // Fills the writable bytes of a buffer with random integers. * {@link ChannelBuffer} buffer = ...; * while (buffer.writableBytes() >= 4) { * buffer.writeInt(random.nextInt()); * } * </pre> * <p/> * <h4>Discardable bytes</h4> * <p/> * This segment contains the bytes which were read already by a read operation. * Initially, the size of this segment is {@code 0}, but its size increases up * to the {@link #writerIndex() writerIndex} as read operations are executed. * The read bytes can be discarded by calling {@link #discardReadBytes()} to * reclaim unused area as depicted by the following diagram: * <p/> * <pre> * BEFORE discardReadBytes() * * +-------------------+------------------+------------------+ * | discardable bytes | readable bytes | writable bytes | * +-------------------+------------------+------------------+ * | | | | * 0 <= readerIndex <= writerIndex <= capacity * * * AFTER discardReadBytes() * * +------------------+--------------------------------------+ * | readable bytes | writable bytes (got more space) | * +------------------+--------------------------------------+ * | | | * readerIndex (0) <= writerIndex (decreased) <= capacity * </pre> * <p/> * Please note that there is no guarantee about the content of writable bytes * after calling {@link #discardReadBytes()}. The writable bytes will not be * moved in most cases and could even be filled with completely different data * depending on the underlying buffer implementation. * <p/> * <h4>Clearing the buffer indexes</h4> * <p/> * You can set both {@link #readerIndex() readerIndex} and {@link #writerIndex() * writerIndex} to {@code 0} by calling {@link #clear()}. It does not clear the * buffer content (e.g. filling with {@code 0}) but just clears the two * pointers. Please also note that the semantic of this operation is different * from {@link ByteBuffer#clear()}. * <p/> * <pre> * BEFORE clear() * * +-------------------+------------------+------------------+ * | discardable bytes | readable bytes | writable bytes | * +-------------------+------------------+------------------+ * | | | | * 0 <= readerIndex <= writerIndex <= capacity * * * AFTER clear() * * +---------------------------------------------------------+ * | writable bytes (got more space) | * +---------------------------------------------------------+ * | | * 0 = readerIndex = writerIndex <= capacity * </pre> * <p/> * <h3>Mark and reset</h3> * <p/> * There are two marker indexes in every buffer. One is for storing {@link * #readerIndex() readerIndex} and the other is for storing {@link * #writerIndex() writerIndex}. You can always reposition one of the two * indexes by calling a reset method. It works in a similar fashion to the mark * and reset methods in {@link InputStream} except that there's no {@code * readlimit}. * <p/> * <h3>Conversion to existing JDK types</h3> * <p/> * <h4>Byte array</h4> * <p/> * If a {@link ChannelBuffer} is backed by a byte array (i.e. {@code byte[]}), * you can access it directly via the {@link #array()} method. To determine if * a buffer is backed by a byte array, {@link #hasArray()} should be used. * <p/> * <h4>NIO Buffers</h4> * <p/> * Various {@link #toByteBuffer()} methods convert a {@link ChannelBuffer} into * one or more NIO buffers. These methods avoid buffer allocation and memory * copy whenever possible, but there's no guarantee that memory copy will not be * involved. * <p/> * <h4>I/O Streams</h4> * <p/> * Please refer to {@link ChannelBufferInputStream} and {@link * ChannelBufferOutputStream}. * * */ public interface ChannelBuffer extends Comparable<ChannelBuffer> { /** * Returns the number of bytes (octets) this buffer can contain. */ int capacity(); /** * Sets the {@code readerIndex} and {@code writerIndex} of this buffer to * {@code 0}. This method is identical to {@link #setIndex(int, int) * setIndex(0, 0)}. * <p/> * Please note that the behavior of this method is different from that of * NIO buffer, which sets the {@code limit} to the {@code capacity} of the * buffer. */ void clear(); /** * Returns a copy of this buffer's readable bytes. Modifying the content of * the returned buffer or this buffer does not affect each other at all. * This method is identical to {@code buf.copy(buf.readerIndex(), * buf.readableBytes())}. This method does not modify {@code readerIndex} or * {@code writerIndex} of this buffer. */ ChannelBuffer copy(); /** * Returns a copy of this buffer's sub-region. Modifying the content of the * returned buffer or this buffer does not affect each other at all. This * method does not modify {@code readerIndex} or {@code writerIndex} of this * buffer. */ ChannelBuffer copy(int index, int length); /** * Discards the bytes between the 0th index and {@code readerIndex}. It * moves the bytes between {@code readerIndex} and {@code writerIndex} to * the 0th index, and sets {@code readerIndex} and {@code writerIndex} to * {@code 0} and {@code oldWriterIndex - oldReaderIndex} respectively. * <p/> * Please refer to the class documentation for more detailed explanation. */ void discardReadBytes(); /** * Makes sure the number of {@linkplain #writableBytes() the writable bytes} * is equal to or greater than the specified value. If there is enough * writable bytes in this buffer, this method returns with no side effect. * Otherwise: <ul> <li>a non-dynamic buffer will throw an {@link * IndexOutOfBoundsException}.</li> <li>a dynamic buffer will expand its * capacity so that the number of the {@link #writableBytes() writable * bytes} becomes equal to or greater than the specified value. The * expansion involves the reallocation of the internal buffer and * consequently memory copy.</li> </ul> * * @param writableBytes the expected minimum number of writable bytes * @throws IndexOutOfBoundsException if {@linkplain #writableBytes() the * writable bytes} of this buffer is less * than the specified value and if this * buffer is not a dynamic buffer */ void ensureWritableBytes(int writableBytes); /** * Determines if the content of the specified buffer is identical to the * content of this array. 'Identical' here means: <ul> <li>the size of the * contents of the two buffers are same and</li> <li>every single byte of * the content of the two buffers are same.</li> </ul> Please note that it * does not compare {@link #readerIndex()} nor {@link #writerIndex()}. This * method also returns {@code false} for {@code null} and an object which is * not an instance of {@link ChannelBuffer} type. */ @Override boolean equals(Object o); /** * Returns the factory which creates a {@link ChannelBuffer} whose type and * default {@link java.nio.ByteOrder} are same with this buffer. */ ChannelBufferFactory factory(); /** * Gets a byte at the specified absolute {@code index} in this buffer. This * method does not modify {@code readerIndex} or {@code writerIndex} of this * buffer. * * @throws IndexOutOfBoundsException if the specified {@code index} is less * than {@code 0} or {@code index + 1} is * greater than {@code this.capacity} */ byte getByte(int index); /** * Transfers this buffer's data to the specified destination starting at the * specified absolute {@code index}. This method does not modify {@code * readerIndex} or {@code writerIndex} of this buffer * * @throws IndexOutOfBoundsException if the specified {@code index} is less * than {@code 0} or if {@code index + * dst.length} is greater than {@code * this.capacity} */ void getBytes(int index, byte[] dst); /** * Transfers this buffer's data to the specified destination starting at the * specified absolute {@code index}. This method does not modify {@code * readerIndex} or {@code writerIndex} of this buffer. * * @param dstIndex the first index of the destination * @param length the number of bytes to transfer * @throws IndexOutOfBoundsException if the specified {@code index} is less * than {@code 0}, if the specified {@code * dstIndex} is less than {@code 0}, if * {@code index + length} is greater than * {@code this.capacity}, or if {@code * dstIndex + length} is greater than * {@code dst.length} */ void getBytes(int index, byte[] dst, int dstIndex, int length); /** * Transfers this buffer's data to the specified destination starting at the * specified absolute {@code index} until the destination's position reaches * its limit. This method does not modify {@code readerIndex} or {@code * writerIndex} of this buffer while the destination's {@code position} will * be increased. * * @throws IndexOutOfBoundsException if the specified {@code index} is less * than {@code 0} or if {@code index + * dst.remaining()} is greater than {@code * this.capacity} */ void getBytes(int index, ByteBuffer dst); /** * Transfers this buffer's data to the specified destination starting at the * specified absolute {@code index} until the destination becomes * non-writable. This method is basically same with {@link #getBytes(int, * ChannelBuffer, int, int)}, except that this method increases the {@code * writerIndex} of the destination by the number of the transferred bytes * while {@link #getBytes(int, ChannelBuffer, int, int)} does not. This * method does not modify {@code readerIndex} or {@code writerIndex} of the * source buffer (i.e. {@code this}). * * @throws IndexOutOfBoundsException if the specified {@code index} is less * than {@code 0} or if {@code index + * dst.writableBytes} is greater than * {@code this.capacity} */ void getBytes(int index, ChannelBuffer dst); /** * Transfers this buffer's data to the specified destination starting at the * specified absolute {@code index}. This method is basically same with * {@link #getBytes(int, ChannelBuffer, int, int)}, except that this method * increases the {@code writerIndex} of the destination by the number of the * transferred bytes while {@link #getBytes(int, ChannelBuffer, int, int)} * does not. This method does not modify {@code readerIndex} or {@code * writerIndex} of the source buffer (i.e. {@code this}). * * @param length the number of bytes to transfer * @throws IndexOutOfBoundsException if the specified {@code index} is less * than {@code 0}, if {@code index + * length} is greater than {@code * this.capacity}, or if {@code length} is * greater than {@code dst.writableBytes} */ void getBytes(int index, ChannelBuffer dst, int length); /** * Transfers this buffer's data to the specified destination starting at the * specified absolute {@code index}. This method does not modify {@code * readerIndex} or {@code writerIndex} of both the source (i.e. {@code * this}) and the destination. * * @param dstIndex the first index of the destination * @param length the number of bytes to transfer * @throws IndexOutOfBoundsException if the specified {@code index} is less * than {@code 0}, if the specified {@code * dstIndex} is less than {@code 0}, if * {@code index + length} is greater than * {@code this.capacity}, or if {@code * dstIndex + length} is greater than * {@code dst.capacity} */ void getBytes(int index, ChannelBuffer dst, int dstIndex, int length); /** * Transfers this buffer's data to the specified stream starting at the * specified absolute {@code index}. This method does not modify {@code * readerIndex} or {@code writerIndex} of this buffer. * * @param length the number of bytes to transfer * @throws IndexOutOfBoundsException if the specified {@code index} is less * than {@code 0} or if {@code index + * length} is greater than {@code * this.capacity} * @throws IOException if the specified stream threw an * exception during I/O */ void getBytes(int index, OutputStream dst, int length) throws IOException; /** * Returns {@code true} if and only if this buffer is backed by an NIO * direct buffer. */ boolean isDirect(); /** * Marks the current {@code readerIndex} in this buffer. You can reposition * the current {@code readerIndex} to the marked {@code readerIndex} by * calling {@link #resetReaderIndex()}. The initial value of the marked * {@code readerIndex} is {@code 0}. */ void markReaderIndex(); /** * Marks the current {@code writerIndex} in this buffer. You can reposition * the current {@code writerIndex} to the marked {@code writerIndex} by * calling {@link #resetWriterIndex()}. The initial value of the marked * {@code writerIndex} is {@code 0}. */ void markWriterIndex(); /** * Returns {@code true} if and only if {@code (this.writerIndex - * this.readerIndex)} is greater than {@code 0}. */ boolean readable(); /** * Returns the number of readable bytes which is equal to {@code * (this.writerIndex - this.readerIndex)}. */ int readableBytes(); /** * Gets a byte at the current {@code readerIndex} and increases the {@code * readerIndex} by {@code 1} in this buffer. * * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less * than {@code 1} */ byte readByte(); /** * Transfers this buffer's data to the specified destination starting at the * current {@code readerIndex} and increases the {@code readerIndex} by the * number of the transferred bytes (= {@code dst.length}). * * @throws IndexOutOfBoundsException if {@code dst.length} is greater than * {@code this.readableBytes} */ void readBytes(byte[] dst); /** * Transfers this buffer's data to the specified destination starting at the * current {@code readerIndex} and increases the {@code readerIndex} by the * number of the transferred bytes (= {@code length}). * * @param dstIndex the first index of the destination * @param length the number of bytes to transfer * @throws IndexOutOfBoundsException if the specified {@code dstIndex} is * less than {@code 0}, if {@code length} * is greater than {@code this.readableBytes}, * or if {@code dstIndex + length} is * greater than {@code dst.length} */ void readBytes(byte[] dst, int dstIndex, int length); /** * Transfers this buffer's data to the specified destination starting at the * current {@code readerIndex} until the destination's position reaches its * limit, and increases the {@code readerIndex} by the number of the * transferred bytes. * * @throws IndexOutOfBoundsException if {@code dst.remaining()} is greater * than {@code this.readableBytes} */ void readBytes(ByteBuffer dst); /** * Transfers this buffer's data to the specified destination starting at the * current {@code readerIndex} until the destination becomes non-writable, * and increases the {@code readerIndex} by the number of the transferred * bytes. This method is basically same with {@link * #readBytes(ChannelBuffer, int, int)}, except that this method increases * the {@code writerIndex} of the destination by the number of the * transferred bytes while {@link #readBytes(ChannelBuffer, int, int)} does * not. * * @throws IndexOutOfBoundsException if {@code dst.writableBytes} is greater * than {@code this.readableBytes} */ void readBytes(ChannelBuffer dst); /** * Transfers this buffer's data to the specified destination starting at the * current {@code readerIndex} and increases the {@code readerIndex} by the * number of the transferred bytes (= {@code length}). This method is * basically same with {@link #readBytes(ChannelBuffer, int, int)}, except * that this method increases the {@code writerIndex} of the destination by * the number of the transferred bytes (= {@code length}) while {@link * #readBytes(ChannelBuffer, int, int)} does not. * * @throws IndexOutOfBoundsException if {@code length} is greater than * {@code this.readableBytes} or if {@code * length} is greater than {@code * dst.writableBytes} */ void readBytes(ChannelBuffer dst, int length); /** * Transfers this buffer's data to the specified destination starting at the * current {@code readerIndex} and increases the {@code readerIndex} by the * number of the transferred bytes (= {@code length}). * * @param dstIndex the first index of the destination * @param length the number of bytes to transfer * @throws IndexOutOfBoundsException if the specified {@code dstIndex} is * less than {@code 0}, if {@code length} * is greater than {@code this.readableBytes}, * or if {@code dstIndex + length} is * greater than {@code dst.capacity} */ void readBytes(ChannelBuffer dst, int dstIndex, int length); /** * Transfers this buffer's data to a newly created buffer starting at the * current {@code readerIndex} and increases the {@code readerIndex} by the * number of the transferred bytes (= {@code length}). The returned buffer's * {@code readerIndex} and {@code writerIndex} are {@code 0} and {@code * length} respectively. * * @param length the number of bytes to transfer * @return the newly created buffer which contains the transferred bytes * @throws IndexOutOfBoundsException if {@code length} is greater than * {@code this.readableBytes} */ ChannelBuffer readBytes(int length); /** * Repositions the current {@code readerIndex} to the marked {@code * readerIndex} in this buffer. * * @throws IndexOutOfBoundsException if the current {@code writerIndex} is * less than the marked {@code * readerIndex} */ void resetReaderIndex(); /** * Marks the current {@code writerIndex} in this buffer. You can reposition * the current {@code writerIndex} to the marked {@code writerIndex} by * calling {@link #resetWriterIndex()}. The initial value of the marked * {@code writerIndex} is {@code 0}. */ void resetWriterIndex(); /** * Returns the {@code readerIndex} of this buffer. */ int readerIndex(); /** * Sets the {@code readerIndex} of this buffer. * * @throws IndexOutOfBoundsException if the specified {@code readerIndex} is * less than {@code 0} or greater than * {@code this.writerIndex} */ void readerIndex(int readerIndex); /** * Transfers this buffer's data to the specified stream starting at the * current {@code readerIndex}. * * @param length the number of bytes to transfer * @throws IndexOutOfBoundsException if {@code length} is greater than * {@code this.readableBytes} * @throws IOException if the specified stream threw an * exception during I/O */ void readBytes(OutputStream dst, int length) throws IOException; /** * Sets the specified byte at the specified absolute {@code index} in this * buffer. The 24 high-order bits of the specified value are ignored. This * method does not modify {@code readerIndex} or {@code writerIndex} of this * buffer. * * @throws IndexOutOfBoundsException if the specified {@code index} is less * than {@code 0} or {@code index + 1} is * greater than {@code this.capacity} */ void setByte(int index, int value); /** * Transfers the specified source array's data to this buffer starting at * the specified absolute {@code index}. This method does not modify {@code * readerIndex} or {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException if the specified {@code index} is less * than {@code 0} or if {@code index + * src.length} is greater than {@code * this.capacity} */ void setBytes(int index, byte[] src); /** * Transfers the specified source array's data to this buffer starting at * the specified absolute {@code index}. This method does not modify {@code * readerIndex} or {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException if the specified {@code index} is less * than {@code 0}, if the specified {@code * srcIndex} is less than {@code 0}, if * {@code index + length} is greater than * {@code this.capacity}, or if {@code * srcIndex + length} is greater than * {@code src.length} */ void setBytes(int index, byte[] src, int srcIndex, int length); /** * Transfers the specified source buffer's data to this buffer starting at * the specified absolute {@code index} until the source buffer's position * reaches its limit. This method does not modify {@code readerIndex} or * {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException if the specified {@code index} is less * than {@code 0} or if {@code index + * src.remaining()} is greater than {@code * this.capacity} */ void setBytes(int index, ByteBuffer src); /** * Transfers the specified source buffer's data to this buffer starting at * the specified absolute {@code index} until the source buffer becomes * unreadable. This method is basically same with {@link #setBytes(int, * ChannelBuffer, int, int)}, except that this method increases the {@code * readerIndex} of the source buffer by the number of the transferred bytes * while {@link #setBytes(int, ChannelBuffer, int, int)} does not. This * method does not modify {@code readerIndex} or {@code writerIndex} of the * source buffer (i.e. {@code this}). * * @throws IndexOutOfBoundsException if the specified {@code index} is less * than {@code 0} or if {@code index + * src.readableBytes} is greater than * {@code this.capacity} */ void setBytes(int index, ChannelBuffer src); /** * Transfers the specified source buffer's data to this buffer starting at * the specified absolute {@code index}. This method is basically same with * {@link #setBytes(int, ChannelBuffer, int, int)}, except that this method * increases the {@code readerIndex} of the source buffer by the number of * the transferred bytes while {@link #setBytes(int, ChannelBuffer, int, * int)} does not. This method does not modify {@code readerIndex} or {@code * writerIndex} of the source buffer (i.e. {@code this}). * * @param length the number of bytes to transfer * @throws IndexOutOfBoundsException if the specified {@code index} is less * than {@code 0}, if {@code index + * length} is greater than {@code * this.capacity}, or if {@code length} is * greater than {@code src.readableBytes} */ void setBytes(int index, ChannelBuffer src, int length); /** * Transfers the specified source buffer's data to this buffer starting at * the specified absolute {@code index}. This method does not modify {@code * readerIndex} or {@code writerIndex} of both the source (i.e. {@code * this}) and the destination. * * @param srcIndex the first index of the source * @param length the number of bytes to transfer * @throws IndexOutOfBoundsException if the specified {@code index} is less * than {@code 0}, if the specified {@code * srcIndex} is less than {@code 0}, if * {@code index + length} is greater than * {@code this.capacity}, or if {@code * srcIndex + length} is greater than * {@code src.capacity} */ void setBytes(int index, ChannelBuffer src, int srcIndex, int length); /** * Transfers the content of the specified source stream to this buffer * starting at the specified absolute {@code index}. This method does not * modify {@code readerIndex} or {@code writerIndex} of this buffer. * * @param length the number of bytes to transfer
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
true
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/DirectChannelBufferFactory.java
dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/DirectChannelBufferFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.buffer; import java.nio.ByteBuffer; public class DirectChannelBufferFactory implements ChannelBufferFactory { private static final DirectChannelBufferFactory INSTANCE = new DirectChannelBufferFactory(); public DirectChannelBufferFactory() { super(); } public static ChannelBufferFactory getInstance() { return INSTANCE; } @Override public ChannelBuffer getBuffer(int capacity) { if (capacity < 0) { throw new IllegalArgumentException("capacity: " + capacity); } if (capacity == 0) { return ChannelBuffers.EMPTY_BUFFER; } return ChannelBuffers.directBuffer(capacity); } @Override public ChannelBuffer getBuffer(byte[] array, int offset, int length) { if (array == null) { throw new NullPointerException("array"); } if (offset < 0) { throw new IndexOutOfBoundsException("offset: " + offset); } if (length == 0) { return ChannelBuffers.EMPTY_BUFFER; } if (offset + length > array.length) { throw new IndexOutOfBoundsException("length: " + length); } ChannelBuffer buf = getBuffer(length); buf.writeBytes(array, offset, length); return buf; } @Override public ChannelBuffer getBuffer(ByteBuffer nioBuffer) { if (!nioBuffer.isReadOnly() && nioBuffer.isDirect()) { return ChannelBuffers.wrappedBuffer(nioBuffer); } ChannelBuffer buf = getBuffer(nioBuffer.remaining()); int pos = nioBuffer.position(); buf.writeBytes(nioBuffer); nioBuffer.position(pos); return buf; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/HeapChannelBuffer.java
dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/HeapChannelBuffer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.buffer; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.channels.ClosedChannelException; import java.nio.channels.GatheringByteChannel; import java.nio.channels.ScatteringByteChannel; public class HeapChannelBuffer extends AbstractChannelBuffer { /** * The underlying heap byte array that this buffer is wrapping. */ protected final byte[] array; /** * Creates a new heap buffer with a newly allocated byte array. * * @param length the length of the new byte array */ public HeapChannelBuffer(int length) { this(new byte[length], 0, 0); } /** * Creates a new heap buffer with an existing byte array. * * @param array the byte array to wrap */ public HeapChannelBuffer(byte[] array) { this(array, 0, array.length); } /** * Creates a new heap buffer with an existing byte array. * * @param array the byte array to wrap * @param readerIndex the initial reader index of this buffer * @param writerIndex the initial writer index of this buffer */ protected HeapChannelBuffer(byte[] array, int readerIndex, int writerIndex) { if (array == null) { throw new NullPointerException("array"); } this.array = array; setIndex(readerIndex, writerIndex); } @Override public boolean isDirect() { return false; } @Override public int capacity() { return array.length; } @Override public boolean hasArray() { return true; } @Override public byte[] array() { return array; } @Override public int arrayOffset() { return 0; } @Override public byte getByte(int index) { return array[index]; } @Override public void getBytes(int index, ChannelBuffer dst, int dstIndex, int length) { if (dst instanceof HeapChannelBuffer) { getBytes(index, ((HeapChannelBuffer) dst).array, dstIndex, length); } else { dst.setBytes(dstIndex, array, index, length); } } @Override public void getBytes(int index, byte[] dst, int dstIndex, int length) { System.arraycopy(array, index, dst, dstIndex, length); } @Override public void getBytes(int index, ByteBuffer dst) { dst.put(array, index, Math.min(capacity() - index, dst.remaining())); } @Override public void getBytes(int index, OutputStream out, int length) throws IOException { out.write(array, index, length); } public int getBytes(int index, GatheringByteChannel out, int length) throws IOException { return out.write(ByteBuffer.wrap(array, index, length)); } @Override public void setByte(int index, int value) { array[index] = (byte) value; } @Override public void setBytes(int index, ChannelBuffer src, int srcIndex, int length) { if (src instanceof HeapChannelBuffer) { setBytes(index, ((HeapChannelBuffer) src).array, srcIndex, length); } else { src.getBytes(srcIndex, array, index, length); } } @Override public void setBytes(int index, byte[] src, int srcIndex, int length) { System.arraycopy(src, srcIndex, array, index, length); } @Override public void setBytes(int index, ByteBuffer src) { src.get(array, index, src.remaining()); } @Override public int setBytes(int index, InputStream in, int length) throws IOException { int readBytes = 0; do { int localReadBytes = in.read(array, index, length); if (localReadBytes < 0) { if (readBytes == 0) { return -1; } else { break; } } readBytes += localReadBytes; index += localReadBytes; length -= localReadBytes; } while (length > 0); return readBytes; } public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException { ByteBuffer buf = ByteBuffer.wrap(array, index, length); int readBytes = 0; do { int localReadBytes; try { localReadBytes = in.read(buf); } catch (ClosedChannelException e) { localReadBytes = -1; } if (localReadBytes < 0) { if (readBytes == 0) { return -1; } else { break; } } else if (localReadBytes == 0) { break; } readBytes += localReadBytes; } while (readBytes < length); return readBytes; } @Override public ChannelBuffer copy(int index, int length) { if (index < 0 || length < 0 || index + length > array.length) { throw new IndexOutOfBoundsException(); } byte[] copiedArray = new byte[length]; System.arraycopy(array, index, copiedArray, 0, length); return new HeapChannelBuffer(copiedArray); } @Override public ChannelBufferFactory factory() { return HeapChannelBufferFactory.getInstance(); } @Override public ByteBuffer toByteBuffer(int index, int length) { return ByteBuffer.wrap(array, index, length); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ChannelBuffers.java
dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ChannelBuffers.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.buffer; import java.nio.ByteBuffer; public final class ChannelBuffers { public static final ChannelBuffer EMPTY_BUFFER = new HeapChannelBuffer(0); public static final int DEFAULT_CAPACITY = 256; private ChannelBuffers() {} public static ChannelBuffer dynamicBuffer() { return dynamicBuffer(DEFAULT_CAPACITY); } public static ChannelBuffer dynamicBuffer(int capacity) { return new DynamicChannelBuffer(capacity); } public static ChannelBuffer dynamicBuffer(int capacity, ChannelBufferFactory factory) { return new DynamicChannelBuffer(capacity, factory); } public static ChannelBuffer buffer(int capacity) { if (capacity < 0) { throw new IllegalArgumentException("capacity can not be negative"); } if (capacity == 0) { return EMPTY_BUFFER; } return new HeapChannelBuffer(capacity); } public static ChannelBuffer wrappedBuffer(byte[] array, int offset, int length) { if (array == null) { throw new NullPointerException("array == null"); } byte[] dest = new byte[length]; System.arraycopy(array, offset, dest, 0, length); return wrappedBuffer(dest); } public static ChannelBuffer wrappedBuffer(byte[] array) { if (array == null) { throw new NullPointerException("array == null"); } if (array.length == 0) { return EMPTY_BUFFER; } return new HeapChannelBuffer(array); } public static ChannelBuffer wrappedBuffer(ByteBuffer buffer) { if (!buffer.hasRemaining()) { return EMPTY_BUFFER; } if (buffer.hasArray()) { return wrappedBuffer(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining()); } else { return new ByteBufferBackedChannelBuffer(buffer); } } public static ChannelBuffer directBuffer(int capacity) { if (capacity == 0) { return EMPTY_BUFFER; } ChannelBuffer buffer = new ByteBufferBackedChannelBuffer(ByteBuffer.allocateDirect(capacity)); buffer.clear(); return buffer; } public static boolean equals(ChannelBuffer bufferA, ChannelBuffer bufferB) { final int aLen = bufferA.readableBytes(); if (aLen != bufferB.readableBytes()) { return false; } final int byteCount = aLen & 7; int aIndex = bufferA.readerIndex(); int bIndex = bufferB.readerIndex(); for (int i = byteCount; i > 0; i--) { if (bufferA.getByte(aIndex) != bufferB.getByte(bIndex)) { return false; } aIndex++; bIndex++; } return true; } // prefix public static boolean prefixEquals(ChannelBuffer bufferA, ChannelBuffer bufferB, int count) { final int aLen = bufferA.readableBytes(); final int bLen = bufferB.readableBytes(); if (aLen < count || bLen < count) { return false; } int aIndex = bufferA.readerIndex(); int bIndex = bufferB.readerIndex(); for (int i = count; i > 0; i--) { if (bufferA.getByte(aIndex) != bufferB.getByte(bIndex)) { return false; } aIndex++; bIndex++; } return true; } public static int hasCode(ChannelBuffer buffer) { final int aLen = buffer.readableBytes(); final int byteCount = aLen & 7; int hashCode = 1; int arrayIndex = buffer.readerIndex(); for (int i = byteCount; i > 0; i--) { hashCode = 31 * hashCode + buffer.getByte(arrayIndex++); } if (hashCode == 0) { hashCode = 1; } return hashCode; } public static int compare(ChannelBuffer bufferA, ChannelBuffer bufferB) { final int aLen = bufferA.readableBytes(); final int bLen = bufferB.readableBytes(); final int minLength = Math.min(aLen, bLen); int aIndex = bufferA.readerIndex(); int bIndex = bufferB.readerIndex(); for (int i = minLength; i > 0; i--) { byte va = bufferA.getByte(aIndex); byte vb = bufferB.getByte(bIndex); if (va > vb) { return 1; } else if (va < vb) { return -1; } aIndex++; bIndex++; } return aLen - bLen; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ByteBufferBackedChannelBuffer.java
dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ByteBufferBackedChannelBuffer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.buffer; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; public class ByteBufferBackedChannelBuffer extends AbstractChannelBuffer { private final ByteBuffer buffer; private final int capacity; public ByteBufferBackedChannelBuffer(ByteBuffer buffer) { if (buffer == null) { throw new NullPointerException("buffer"); } this.buffer = buffer.slice(); capacity = buffer.remaining(); writerIndex(capacity); } public ByteBufferBackedChannelBuffer(ByteBufferBackedChannelBuffer buffer) { this.buffer = buffer.buffer; capacity = buffer.capacity; setIndex(buffer.readerIndex(), buffer.writerIndex()); } @Override public ChannelBufferFactory factory() { if (buffer.isDirect()) { return DirectChannelBufferFactory.getInstance(); } else { return HeapChannelBufferFactory.getInstance(); } } @Override public int capacity() { return capacity; } @Override public ChannelBuffer copy(int index, int length) { ByteBuffer src; try { src = (ByteBuffer) buffer.duplicate().position(index).limit(index + length); } catch (IllegalArgumentException e) { throw new IndexOutOfBoundsException(); } ByteBuffer dst = buffer.isDirect() ? ByteBuffer.allocateDirect(length) : ByteBuffer.allocate(length); dst.put(src); dst.clear(); return new ByteBufferBackedChannelBuffer(dst); } @Override public byte getByte(int index) { return buffer.get(index); } @Override public void getBytes(int index, byte[] dst, int dstIndex, int length) { ByteBuffer data = buffer.duplicate(); try { data.limit(index + length).position(index); } catch (IllegalArgumentException e) { throw new IndexOutOfBoundsException(); } data.get(dst, dstIndex, length); } @Override public void getBytes(int index, ByteBuffer dst) { ByteBuffer data = buffer.duplicate(); int bytesToCopy = Math.min(capacity() - index, dst.remaining()); try { data.limit(index + bytesToCopy).position(index); } catch (IllegalArgumentException e) { throw new IndexOutOfBoundsException(); } dst.put(data); } @Override public void getBytes(int index, ChannelBuffer dst, int dstIndex, int length) { if (dst instanceof ByteBufferBackedChannelBuffer) { ByteBufferBackedChannelBuffer bbdst = (ByteBufferBackedChannelBuffer) dst; ByteBuffer data = bbdst.buffer.duplicate(); data.limit(dstIndex + length).position(dstIndex); getBytes(index, data); } else if (buffer.hasArray()) { dst.setBytes(dstIndex, buffer.array(), index + buffer.arrayOffset(), length); } else { dst.setBytes(dstIndex, this, index, length); } } @Override public void getBytes(int index, OutputStream out, int length) throws IOException { if (length == 0) { return; } if (buffer.hasArray()) { out.write(buffer.array(), index + buffer.arrayOffset(), length); } else { byte[] tmp = new byte[length]; ((ByteBuffer) buffer.duplicate().position(index)).get(tmp); out.write(tmp); } } @Override public boolean isDirect() { return buffer.isDirect(); } @Override public void setByte(int index, int value) { buffer.put(index, (byte) value); } @Override public void setBytes(int index, byte[] src, int srcIndex, int length) { ByteBuffer data = buffer.duplicate(); data.limit(index + length).position(index); data.put(src, srcIndex, length); } @Override public void setBytes(int index, ByteBuffer src) { ByteBuffer data = buffer.duplicate(); data.limit(index + src.remaining()).position(index); data.put(src); } @Override public void setBytes(int index, ChannelBuffer src, int srcIndex, int length) { if (src instanceof ByteBufferBackedChannelBuffer) { ByteBufferBackedChannelBuffer bbsrc = (ByteBufferBackedChannelBuffer) src; ByteBuffer data = bbsrc.buffer.duplicate(); data.limit(srcIndex + length).position(srcIndex); setBytes(index, data); } else if (buffer.hasArray()) { src.getBytes(srcIndex, buffer.array(), index + buffer.arrayOffset(), length); } else { src.getBytes(srcIndex, this, index, length); } } @Override public ByteBuffer toByteBuffer(int index, int length) { if (index == 0 && length == capacity()) { return buffer.duplicate(); } else { return ((ByteBuffer) buffer.duplicate().position(index).limit(index + length)).slice(); } } @Override public int setBytes(int index, InputStream in, int length) throws IOException { int readBytes = 0; if (buffer.hasArray()) { index += buffer.arrayOffset(); do { int localReadBytes = in.read(buffer.array(), index, length); if (localReadBytes < 0) { if (readBytes == 0) { return -1; } else { break; } } readBytes += localReadBytes; index += localReadBytes; length -= localReadBytes; } while (length > 0); } else { byte[] tmp = new byte[length]; int i = 0; do { int localReadBytes = in.read(tmp, i, tmp.length - i); if (localReadBytes < 0) { if (readBytes == 0) { return -1; } else { break; } } readBytes += localReadBytes; i += readBytes; } while (i < tmp.length); ((ByteBuffer) buffer.duplicate().position(index)).put(tmp); } return readBytes; } @Override public byte[] array() { return buffer.array(); } @Override public boolean hasArray() { return buffer.hasArray(); } @Override public int arrayOffset() { return buffer.arrayOffset(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ReplierDispatcherTest.java
dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ReplierDispatcherTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.ExchangeChannel; import org.apache.dubbo.remoting.exchange.ExchangeServer; import org.apache.dubbo.remoting.exchange.Exchangers; import org.apache.dubbo.remoting.exchange.support.ReplierDispatcher; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; import java.io.Serializable; import java.util.LinkedList; import java.util.List; import java.util.Random; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT; import static org.junit.jupiter.api.Assertions.fail; class ReplierDispatcherTest { private ExchangeServer exchangeServer; private ConcurrentHashMap<String, ExchangeChannel> clients = new ConcurrentHashMap<>(); private int port; @BeforeEach public void startServer() throws RemotingException { FrameworkModel.destroyAll(); port = NetUtils.getAvailablePort(); ReplierDispatcher dispatcher = new ReplierDispatcher(); dispatcher.addReplier(RpcMessage.class, new RpcMessageHandler()); dispatcher.addReplier(Data.class, (channel, msg) -> new StringMessage("hello world")); URL url = URL.valueOf( "exchange://localhost:" + port + "?" + CommonConstants.TIMEOUT_KEY + "=60000&threadpool=cached"); ApplicationModel applicationModel = ApplicationModel.defaultModel(); ApplicationConfig applicationConfig = new ApplicationConfig("provider-app"); applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT); applicationModel.getApplicationConfigManager().setApplication(applicationConfig); ConfigManager configManager = new ConfigManager(applicationModel); configManager.setApplication(applicationConfig); configManager.getApplication(); applicationModel.setConfigManager(configManager); url = url.setScopeModel(applicationModel); ModuleModel moduleModel = applicationModel.getDefaultModule(); url = url.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel); exchangeServer = Exchangers.bind(url, dispatcher); } @Test void testDataPackage() throws Exception { ExchangeChannel client = Exchangers.connect( URL.valueOf("exchange://localhost:" + port + "?" + CommonConstants.TIMEOUT_KEY + "=60000")); Random random = new Random(); for (int i = 5; i < 100; i++) { StringBuilder sb = new StringBuilder(); for (int j = 0; j < i * 100; j++) sb.append('(').append(random.nextLong()).append(')'); Data d = new Data(); d.setData(sb.toString()); Assertions.assertEquals(client.request(d).get().toString(), "hello world"); } clients.put(Thread.currentThread().getName(), client); } @Test void testMultiThread() throws Exception { int tc = 10; ExecutorService exec = Executors.newFixedThreadPool(tc); List<Future<?>> futureList = new LinkedList<>(); for (int i = 0; i < tc; i++) futureList.add(exec.submit(() -> { try { clientExchangeInfo(port); } catch (Exception e) { fail(e); } })); for (Future<?> future : futureList) { future.get(); } exec.shutdown(); exec.awaitTermination(10, TimeUnit.SECONDS); } void clientExchangeInfo(int port) throws Exception { ExchangeChannel client = Exchangers.connect( URL.valueOf("exchange://localhost:" + port + "?" + CommonConstants.TIMEOUT_KEY + "=60000")); clients.put(Thread.currentThread().getName(), client); MockResult result = (MockResult) client.request(new RpcMessage( DemoService.class.getName(), "plus", new Class<?>[] {int.class, int.class}, new Object[] {55, 25 })) .get(); Assertions.assertEquals(result.getResult(), 80); for (int i = 0; i < 100; i++) { client.request(new RpcMessage( DemoService.class.getName(), "sayHello", new Class<?>[] {String.class}, new Object[] {"qianlei" + i })); } for (int i = 0; i < 100; i++) { CompletableFuture<Object> future = client.request(new Data()); Assertions.assertEquals(future.get().toString(), "hello world"); } } @AfterEach public void tearDown() { try { if (exchangeServer != null) exchangeServer.close(); } finally { if (clients.size() != 0) clients.forEach((key, value) -> { value.close(); clients.remove(key); }); } } static class Data implements Serializable { private static final long serialVersionUID = -4666580993978548778L; private String mData = ""; public Data() {} public String getData() { return mData; } public void setData(String data) { mData = data; } } static class StringMessage implements Serializable { private static final long serialVersionUID = 7193122183120113947L; private String mText; StringMessage(String msg) { mText = msg; } public String toString() { return mText; } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyCodecAdapterTest.java
dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyCodecAdapterTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Codec2; import org.apache.dubbo.remoting.Constants; import java.io.IOException; import java.nio.charset.StandardCharsets; import io.netty.buffer.AbstractByteBufAllocator; import io.netty.buffer.ByteBuf; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.handler.codec.ByteToMessageDecoder; import io.netty.handler.codec.DecoderException; import io.netty.handler.codec.MessageToByteEncoder; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; /** * {@link NettyCodecAdapter} */ class NettyCodecAdapterTest { @Test void test() { Codec2 codec2 = Mockito.mock(Codec2.class); URL url = Mockito.mock(URL.class); ChannelHandler handler = Mockito.mock(ChannelHandler.class); NettyCodecAdapter nettyCodecAdapter = new NettyCodecAdapter(codec2, url, handler); io.netty.channel.ChannelHandler decoder = nettyCodecAdapter.getDecoder(); io.netty.channel.ChannelHandler encoder = nettyCodecAdapter.getEncoder(); Assertions.assertTrue(decoder instanceof ByteToMessageDecoder); Assertions.assertTrue(encoder instanceof MessageToByteEncoder); } @Test void testDecodeException() throws IOException { Codec2 codec2 = Mockito.mock(Codec2.class); doThrow(new IOException("testDecodeIllegalPacket")).when(codec2).decode(any(), any()); URL url = Mockito.mock(URL.class); doReturn("default").when(url).getParameter(eq(Constants.CODEC_KEY)); ChannelHandler handler = Mockito.mock(ChannelHandler.class); NettyCodecAdapter nettyCodecAdapter = new NettyCodecAdapter(codec2, url, handler); io.netty.channel.ChannelHandler decoder = nettyCodecAdapter.getDecoder(); EmbeddedChannel embeddedChannel = new EmbeddedChannel(); embeddedChannel.pipeline().addLast(decoder); // simulate illegal data packet ByteBuf input = AbstractByteBufAllocator.DEFAULT.buffer(); input.writeBytes("testDecodeIllegalPacket".getBytes(StandardCharsets.UTF_8)); DecoderException decoderException = Assertions.assertThrows(DecoderException.class, () -> { embeddedChannel.writeInbound(input); }); Assertions.assertTrue(decoderException.getCause() instanceof IOException); Assertions.assertEquals(0, input.refCnt()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientsTest.java
dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.remoting.Transporter; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.fail; class ClientsTest { @Test void testGetTransportEmpty() { try { ExtensionLoader.getExtensionLoader(Transporter.class).getExtension(""); fail(); } catch (IllegalArgumentException expected) { assertThat(expected.getMessage(), containsString("Extension name == null")); } } @Test void testGetTransportNull() { Assertions.assertThrows(IllegalArgumentException.class, () -> { String name = null; ExtensionLoader.getExtensionLoader(Transporter.class).getExtension(name); }); } @Test void testGetTransport3() { String name = "netty4"; assertEquals( NettyTransporter.class, ExtensionLoader.getExtensionLoader(Transporter.class) .getExtension(name) .getClass()); } @Test void testGetTransportWrong() { Assertions.assertThrows(IllegalStateException.class, () -> { String name = "nety"; assertNull(ExtensionLoader.getExtensionLoader(Transporter.class) .getExtension(name) .getClass()); }); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyChannelTest.java
dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyChannelTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import java.net.InetSocketAddress; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.Channel; import io.netty.channel.ChannelPromise; import io.netty.channel.EventLoop; import io.netty.util.concurrent.GenericFutureListener; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; class NettyChannelTest { private Channel channel = Mockito.mock(Channel.class); private URL url = new ServiceConfigURL("dubbo", "127.0.0.1", 8080); private ChannelHandler channelHandler = Mockito.mock(ChannelHandler.class); @Test void test() throws Exception { Channel channel = Mockito.mock(Channel.class); Mockito.when(channel.isActive()).thenReturn(true); URL url = URL.valueOf("test://127.0.0.1/test"); ChannelHandler channelHandler = Mockito.mock(ChannelHandler.class); NettyChannel nettyChannel = NettyChannel.getOrAddChannel(channel, url, channelHandler); Assertions.assertEquals(nettyChannel.getChannelHandler(), channelHandler); Assertions.assertTrue(nettyChannel.isActive()); NettyChannel.removeChannel(channel); Assertions.assertFalse(nettyChannel.isActive()); nettyChannel = NettyChannel.getOrAddChannel(channel, url, channelHandler); Mockito.when(channel.isActive()).thenReturn(false); NettyChannel.removeChannelIfDisconnected(channel); Assertions.assertFalse(nettyChannel.isActive()); nettyChannel = NettyChannel.getOrAddChannel(channel, url, channelHandler); Assertions.assertFalse(nettyChannel.isConnected()); nettyChannel = NettyChannel.getOrAddChannel(channel, url, channelHandler); nettyChannel.markActive(true); Assertions.assertTrue(nettyChannel.isActive()); } @Test void testAddress() { NettyChannel nettyChannel = NettyChannel.getOrAddChannel(channel, url, channelHandler); InetSocketAddress localAddress = InetSocketAddress.createUnresolved("127.0.0.1", 8888); InetSocketAddress remoteAddress = InetSocketAddress.createUnresolved("127.0.0.1", 9999); Mockito.when(channel.localAddress()).thenReturn(localAddress); Mockito.when(channel.remoteAddress()).thenReturn(remoteAddress); Assertions.assertEquals(nettyChannel.getLocalAddress(), localAddress); Assertions.assertEquals(nettyChannel.getRemoteAddress(), remoteAddress); } @Test void testSend() throws Exception { Mockito.when(channel.eventLoop()).thenReturn(Mockito.mock(EventLoop.class)); Mockito.when(channel.alloc()).thenReturn(PooledByteBufAllocator.DEFAULT); NettyChannel nettyChannel = NettyChannel.getOrAddChannel(channel, url, channelHandler); ChannelPromise future = Mockito.mock(ChannelPromise.class); Mockito.when(future.await(1000)).thenReturn(true); Mockito.when(future.cause()).thenReturn(null); Mockito.when(channel.writeAndFlush(Mockito.any())).thenReturn(future); Mockito.when(channel.newPromise()).thenReturn(future); Mockito.when(future.addListener(Mockito.any())).thenReturn(future); nettyChannel.send("msg", true); NettyChannel finalNettyChannel = nettyChannel; Exception exception = Mockito.mock(Exception.class); Mockito.when(exception.getMessage()).thenReturn("future cause"); Mockito.when(future.cause()).thenReturn(exception); Assertions.assertThrows( RemotingException.class, () -> { finalNettyChannel.send("msg", true); }, "future cause"); Mockito.when(future.await(1000)).thenReturn(false); Mockito.when(future.cause()).thenReturn(null); Assertions.assertThrows( RemotingException.class, () -> { finalNettyChannel.send("msg", true); }, "in timeout(1000ms) limit"); ChannelPromise channelPromise = Mockito.mock(ChannelPromise.class); Mockito.when(channel.newPromise()).thenReturn(channelPromise); Mockito.when(channelPromise.await(1000)).thenReturn(true); Mockito.when(channelPromise.cause()).thenReturn(null); Mockito.when(channelPromise.addListener(Mockito.any())).thenReturn(channelPromise); finalNettyChannel.send("msg", true); ArgumentCaptor<GenericFutureListener> listenerArgumentCaptor = ArgumentCaptor.forClass(GenericFutureListener.class); Mockito.verify(channelPromise, Mockito.times(1)).addListener(listenerArgumentCaptor.capture()); } @Test void testAttribute() { NettyChannel nettyChannel = NettyChannel.getOrAddChannel(channel, url, channelHandler); nettyChannel.setAttribute("k1", "v1"); Assertions.assertTrue(nettyChannel.hasAttribute("k1")); Assertions.assertEquals(nettyChannel.getAttribute("k1"), "v1"); nettyChannel.removeAttribute("k1"); Assertions.assertFalse(nettyChannel.hasAttribute("k1")); } @Test void testEquals() { Channel channel2 = Mockito.mock(Channel.class); NettyChannel nettyChannel = NettyChannel.getOrAddChannel(channel, url, channelHandler); NettyChannel nettyChannel2 = NettyChannel.getOrAddChannel(channel2, url, channelHandler); Assertions.assertEquals(nettyChannel, nettyChannel); Assertions.assertNotEquals(nettyChannel, nettyChannel2); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/MockResult.java
dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/MockResult.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import java.io.Serializable; /** * AppResponse. */ public class MockResult implements Serializable { private static final long serialVersionUID = -3630485157441794463L; private final Object mResult; public MockResult(Object result) { mResult = result; } public Object getResult() { return mResult; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/World.java
dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/World.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import java.io.Serializable; /** * Data */ public class World implements Serializable { private static final long serialVersionUID = 8563900571013747774L; private String name; public World() {} public World(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/PortUnificationServerTest.java
dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/PortUnificationServerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.remoting.api.pu.DefaultPuHandler; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ModuleModel; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT; import static org.apache.dubbo.common.constants.CommonConstants.EXT_PROTOCOL; class PortUnificationServerTest { @Test void testBind() throws Throwable { int port = NetUtils.getAvailablePort(); URL url = URL.valueOf("empty://127.0.0.1:" + port + "?foo=bar&" + EXT_PROTOCOL + "=tri"); ApplicationModel applicationModel = ApplicationModel.defaultModel(); ApplicationConfig applicationConfig = new ApplicationConfig("provider-app"); applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT); applicationModel.getApplicationConfigManager().setApplication(applicationConfig); ConfigManager configManager = new ConfigManager(applicationModel); configManager.setApplication(applicationConfig); configManager.getApplication(); applicationModel.setConfigManager(configManager); url = url.setScopeModel(applicationModel); ModuleModel moduleModel = applicationModel.getDefaultModule(); url = url.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel); // abstract endpoint need to get codec of url(which is in triple package) final NettyPortUnificationServer server = new NettyPortUnificationServer(url, new DefaultPuHandler()); server.bind(); Assertions.assertTrue(server.isBound()); Assertions.assertEquals(2, server.getProtocols().size()); server.close(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/DefaultCodec.java
dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/DefaultCodec.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.Codec2; import org.apache.dubbo.remoting.buffer.ChannelBuffer; import java.io.IOException; public class DefaultCodec implements Codec2 { @Override public void encode(Channel channel, ChannelBuffer buffer, Object message) throws IOException {} @Override public Object decode(Channel channel, ChannelBuffer buffer) throws IOException { return null; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/DemoServiceImpl.java
dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/DemoServiceImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <code>TestServiceImpl</code> */ public class DemoServiceImpl implements DemoService { private static final Logger logger = LoggerFactory.getLogger(DemoServiceImpl.class); public void sayHello(String name) { logger.info("hello {}", name); } public int plus(int a, int b) { return a + b; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/DemoService.java
dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/DemoService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; /** * <code>TestService</code> */ public interface DemoService { void sayHello(String name); int plus(int a, int b); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/WorldHandler.java
dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/WorldHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.ExchangeChannel; import org.apache.dubbo.remoting.exchange.support.Replier; /** * DataHandler */ public class WorldHandler implements Replier<World> { public Class<World> interest() { return World.class; } public Object reply(ExchangeChannel channel, World msg) throws RemotingException { return new Hello("hello," + msg.getName()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyClientToServerTest.java
dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyClientToServerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.ExchangeChannel; import org.apache.dubbo.remoting.exchange.ExchangeServer; import org.apache.dubbo.remoting.exchange.Exchangers; import org.apache.dubbo.remoting.exchange.support.Replier; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ModuleModel; import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT; /** * Netty4ClientToServerTest */ class NettyClientToServerTest extends ClientToServerTest { protected ExchangeServer newServer(int port, Replier<?> receiver) throws RemotingException { // add heartbeat cycle to avoid unstable ut. URL url = URL.valueOf("exchange://localhost:" + port + "?server=netty4"); ApplicationModel applicationModel = ApplicationModel.defaultModel(); ApplicationConfig applicationConfig = new ApplicationConfig("provider-app"); applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT); applicationModel.getApplicationConfigManager().setApplication(applicationConfig); ConfigManager configManager = new ConfigManager(applicationModel); configManager.setApplication(applicationConfig); configManager.getApplication(); applicationModel.setConfigManager(configManager); url = url.addParameter(Constants.HEARTBEAT_KEY, 600 * 1000) .putAttribute(CommonConstants.SCOPE_MODEL, applicationModel); url = url.setScopeModel(applicationModel); // ModuleModel moduleModel = applicationModel.getDefaultModule(); ModuleModel moduleModel = applicationModel.getDefaultModule(); url = url.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel); return Exchangers.bind(url, receiver); } protected ExchangeChannel newClient(int port) throws RemotingException { // add heartbeat cycle to avoid unstable ut. URL url = URL.valueOf("exchange://localhost:" + port + "?client=netty4&timeout=300000"); url = url.addParameter(Constants.HEARTBEAT_KEY, 600 * 1000); ApplicationModel applicationModel = ApplicationModel.defaultModel(); ApplicationConfig applicationConfig = new ApplicationConfig("provider-app"); applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT); applicationModel.getApplicationConfigManager().setApplication(applicationConfig); ConfigManager configManager = new ConfigManager(applicationModel); configManager.setApplication(applicationConfig); configManager.getApplication(); applicationModel.setConfigManager(configManager); url = url.setScopeModel(applicationModel); ModuleModel moduleModel = applicationModel.getDefaultModule(); url = url.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel); return Exchangers.connect(url); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/RpcMessageHandler.java
dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/RpcMessageHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.bytecode.NoSuchMethodException; import org.apache.dubbo.common.bytecode.Wrapper; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.ExchangeChannel; import org.apache.dubbo.remoting.exchange.support.Replier; import java.lang.reflect.InvocationTargetException; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * RpcMessageHandler. */ public class RpcMessageHandler implements Replier<RpcMessage> { private static final ConcurrentMap<String, Object> IMPLEMENT_MAP = new ConcurrentHashMap<>(); private static final ServiceProvider DEFAULT_PROVIDER = new ServiceProvider() { public Object getImplementation(String service) { String impl = service + "Impl"; return ConcurrentHashMapUtils.computeIfAbsent(IMPLEMENT_MAP, impl, (s) -> { try { Class<?> cl = Thread.currentThread().getContextClassLoader().loadClass(s); return cl.getDeclaredConstructor().newInstance(); } catch (Exception e) { e.printStackTrace(); } return null; }); } }; private ServiceProvider mProvider; public RpcMessageHandler() { this(DEFAULT_PROVIDER); } public RpcMessageHandler(ServiceProvider prov) { mProvider = prov; } public Class<RpcMessage> interest() { return RpcMessage.class; } public Object reply(ExchangeChannel channel, RpcMessage msg) throws RemotingException { String desc = msg.getMethodDesc(); Object[] args = msg.getArguments(); Object impl = mProvider.getImplementation(msg.getClassName()); Wrapper wrap = Wrapper.getWrapper(impl.getClass()); try { return new MockResult(wrap.invokeMethod(impl, desc, msg.getParameterTypes(), args)); } catch (NoSuchMethodException e) { throw new RemotingException(channel, "Service method not found."); } catch (InvocationTargetException e) { return new MockResult(e.getTargetException()); } } public interface ServiceProvider { Object getImplementation(String service); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/Hello.java
dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/Hello.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import java.io.Serializable; /** * Result */ public class Hello implements Serializable { private static final long serialVersionUID = 753429849957096150L; private String name; public Hello() {} public Hello(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/PortUnificationExchangerTest.java
dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/PortUnificationExchangerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.api.connection.AbstractConnectionClient; import org.apache.dubbo.remoting.api.pu.DefaultPuHandler; import org.apache.dubbo.remoting.exchange.PortUnificationExchanger; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ModuleModel; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT; class PortUnificationExchangerTest { private static URL url; @BeforeAll public static void init() throws RemotingException { int port = NetUtils.getAvailablePort(); url = URL.valueOf("empty://127.0.0.1:" + port + "?foo=bar"); ApplicationModel applicationModel = ApplicationModel.defaultModel(); ApplicationConfig applicationConfig = new ApplicationConfig("provider-app"); applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT); applicationModel.getApplicationConfigManager().setApplication(applicationConfig); ConfigManager configManager = new ConfigManager(applicationModel); configManager.setApplication(applicationConfig); configManager.getApplication(); applicationModel.setConfigManager(configManager); url = url.setScopeModel(applicationModel); ModuleModel moduleModel = applicationModel.getDefaultModule(); url = url.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel); } @Test void test() { PortUnificationExchanger.bind(url, new DefaultPuHandler()); PortUnificationExchanger.bind(url, new DefaultPuHandler()); Assertions.assertEquals(PortUnificationExchanger.getServers().size(), 1); PortUnificationExchanger.close(); Assertions.assertEquals(PortUnificationExchanger.getServers().size(), 0); } @Test void testConnection() { PortUnificationExchanger.bind(url, new DefaultPuHandler()); PortUnificationExchanger.bind(url, new DefaultPuHandler()); Assertions.assertEquals(1, PortUnificationExchanger.getServers().size()); PortUnificationExchanger.connect(url, new DefaultPuHandler()); AbstractConnectionClient connectionClient = PortUnificationExchanger.connect(url, new DefaultPuHandler()); Assertions.assertTrue(connectionClient.isAvailable()); connectionClient.close(); PortUnificationExchanger.close(); Assertions.assertEquals(0, PortUnificationExchanger.getServers().size()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/RpcMessage.java
dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/RpcMessage.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import java.io.Serializable; /** * RpcMessage. */ public class RpcMessage implements Serializable { private static final long serialVersionUID = -5148079121106659095L; private String mClassName; private String mMethodDesc; private Class<?>[] mParameterTypes; private Object[] mArguments; public RpcMessage(String cn, String desc, Class<?>[] parameterTypes, Object[] args) { mClassName = cn; mMethodDesc = desc; mParameterTypes = parameterTypes; mArguments = args; } public String getClassName() { return mClassName; } public String getMethodDesc() { return mMethodDesc; } public Class<?>[] getParameterTypes() { return mParameterTypes; } public Object[] getArguments() { return mArguments; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyTransporterTest.java
dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyTransporterTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.RemotingServer; import org.apache.dubbo.remoting.transport.ChannelHandlerAdapter; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ModuleModel; import java.util.concurrent.CountDownLatch; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; class NettyTransporterTest { @Test void shouldAbleToBindNetty4() throws Exception { int port = NetUtils.getAvailablePort(); URL url = new ServiceConfigURL( "telnet", "localhost", port, new String[] {Constants.BIND_PORT_KEY, String.valueOf(port)}); ApplicationModel applicationModel = ApplicationModel.defaultModel(); ApplicationConfig applicationConfig = new ApplicationConfig("provider-app"); applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT); applicationModel.getApplicationConfigManager().setApplication(applicationConfig); ConfigManager configManager = new ConfigManager(applicationModel); configManager.setApplication(applicationConfig); configManager.getApplication(); applicationModel.setConfigManager(configManager); url = url.setScopeModel(applicationModel); ModuleModel moduleModel = applicationModel.getDefaultModule(); url = url.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel); RemotingServer server = new NettyTransporter().bind(url, new ChannelHandlerAdapter()); assertThat(server.isBound(), is(true)); Assertions.assertNotEquals(port, NetUtils.getAvailablePort(port)); } @Test void shouldConnectToNetty4Server() throws Exception { final CountDownLatch lock = new CountDownLatch(1); int port = NetUtils.getAvailablePort(); URL url = new ServiceConfigURL( "telnet", "localhost", port, new String[] {Constants.BIND_PORT_KEY, String.valueOf(port)}); ApplicationModel applicationModel = ApplicationModel.defaultModel(); ApplicationConfig applicationConfig = new ApplicationConfig("provider-app"); applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT); applicationModel.getApplicationConfigManager().setApplication(applicationConfig); ConfigManager configManager = new ConfigManager(applicationModel); configManager.setApplication(applicationConfig); configManager.getApplication(); applicationModel.setConfigManager(configManager); url = url.setScopeModel(applicationModel); ModuleModel moduleModel = applicationModel.getDefaultModule(); url = url.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel); new NettyTransporter().bind(url, new ChannelHandlerAdapter() { @Override public void connected(Channel channel) { lock.countDown(); } }); new NettyTransporter().connect(url, new ChannelHandlerAdapter() { @Override public void sent(Channel channel, Object message) throws RemotingException { channel.send(message); channel.close(); } }); lock.await(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyBackedChannelBufferTest.java
dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyBackedChannelBufferTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.remoting.buffer.ChannelBuffer; import io.netty.buffer.Unpooled; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class NettyBackedChannelBufferTest { private static final int CAPACITY = 4096; private ChannelBuffer buffer; @BeforeEach public void init() { buffer = new NettyBackedChannelBuffer(Unpooled.buffer(CAPACITY, CAPACITY * 2)); } @AfterEach public void dispose() { buffer = null; } @Test void testBufferTransfer() { byte[] tmp1 = {1, 2}; byte[] tmp2 = {3, 4}; ChannelBuffer source = new NettyBackedChannelBuffer(Unpooled.buffer(2, 4)); source.writeBytes(tmp1); buffer.writeBytes(tmp2); assertEquals(2, buffer.readableBytes()); source.setBytes(0, tmp1, 0, 2); buffer.setBytes(0, source, 0, 2); assertEquals(2, buffer.readableBytes()); byte[] actual = new byte[2]; buffer.getBytes(0, actual); assertEquals(1, actual[0]); assertEquals(2, actual[1]); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyClientHandlerTest.java
dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyClientHandlerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.exchange.Request; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.handler.timeout.IdleStateEvent; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class NettyClientHandlerTest { @Test void test() throws Exception { URL url = new ServiceConfigURL("dubbo", "127.0.0.1", 20901); ChannelHandler handler = Mockito.mock(ChannelHandler.class); ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class); Channel channel = Mockito.mock(Channel.class); Mockito.when(ctx.channel()).thenReturn(channel); Mockito.when(channel.isActive()).thenReturn(true); Mockito.when(channel.eventLoop()).thenReturn(new NioEventLoopGroup().next()); Mockito.when(channel.alloc()).thenReturn(PooledByteBufAllocator.DEFAULT); ChannelPromise future = mock(ChannelPromise.class); when(channel.writeAndFlush(any())).thenReturn(future); when(future.cause()).thenReturn(null); when(channel.newPromise()).thenReturn(future); when(future.addListener(Mockito.any())).thenReturn(future); NettyClientHandler nettyClientHandler = new NettyClientHandler(url, handler); nettyClientHandler.channelActive(ctx); ArgumentCaptor<NettyChannel> captor = ArgumentCaptor.forClass(NettyChannel.class); Mockito.verify(handler, Mockito.times(1)).connected(captor.capture()); nettyClientHandler.channelInactive(ctx); captor = ArgumentCaptor.forClass(NettyChannel.class); Mockito.verify(handler, Mockito.times(1)).disconnected(captor.capture()); Throwable throwable = Mockito.mock(Throwable.class); nettyClientHandler.exceptionCaught(ctx, throwable); captor = ArgumentCaptor.forClass(NettyChannel.class); ArgumentCaptor<Throwable> throwableArgumentCaptor = ArgumentCaptor.forClass(Throwable.class); Mockito.verify(handler, Mockito.times(1)).caught(captor.capture(), throwableArgumentCaptor.capture()); nettyClientHandler.channelRead(ctx, "test"); captor = ArgumentCaptor.forClass(NettyChannel.class); ArgumentCaptor<Object> objectArgumentCaptor = ArgumentCaptor.forClass(Object.class); Mockito.verify(handler, Mockito.times(1)).received(captor.capture(), objectArgumentCaptor.capture()); nettyClientHandler.userEventTriggered(ctx, IdleStateEvent.READER_IDLE_STATE_EVENT); ArgumentCaptor<Request> requestArgumentCaptor = ArgumentCaptor.forClass(Request.class); Thread.sleep(500); Mockito.verify(channel, Mockito.times(1)).writeAndFlush(requestArgumentCaptor.capture()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyEventLoopFactoryTest.java
dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyEventLoopFactoryTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.utils.SystemPropertyConfigUtils; import io.netty.channel.EventLoopGroup; import io.netty.channel.epoll.Epoll; import io.netty.channel.epoll.EpollEventLoopGroup; import io.netty.channel.epoll.EpollServerSocketChannel; import io.netty.channel.epoll.EpollSocketChannel; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.ServerSocketChannel; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.OS_LINUX_PREFIX; import static org.apache.dubbo.common.constants.CommonConstants.SystemProperty.SYSTEM_OS_NAME; import static org.apache.dubbo.common.constants.CommonConstants.ThirdPartyProperty.NETTY_EPOLL_ENABLE_KEY; /** * {@link NettyEventLoopFactory} */ class NettyEventLoopFactoryTest { @BeforeEach public void setUp() { SystemPropertyConfigUtils.setSystemProperty(NETTY_EPOLL_ENABLE_KEY, "true"); } @AfterEach public void reset() { SystemPropertyConfigUtils.clearSystemProperty(NETTY_EPOLL_ENABLE_KEY); } @Test void eventLoopGroup() { if (isEpoll()) { EventLoopGroup eventLoopGroup = NettyEventLoopFactory.eventLoopGroup(1, "test"); Assertions.assertTrue(eventLoopGroup instanceof EpollEventLoopGroup); Class<? extends SocketChannel> socketChannelClass = NettyEventLoopFactory.socketChannelClass(); Assertions.assertEquals(socketChannelClass, EpollSocketChannel.class); Class<? extends ServerSocketChannel> serverSocketChannelClass = NettyEventLoopFactory.serverSocketChannelClass(); Assertions.assertEquals(serverSocketChannelClass, EpollServerSocketChannel.class); } else { EventLoopGroup eventLoopGroup = NettyEventLoopFactory.eventLoopGroup(1, "test"); Assertions.assertTrue(eventLoopGroup instanceof NioEventLoopGroup); Class<? extends SocketChannel> socketChannelClass = NettyEventLoopFactory.socketChannelClass(); Assertions.assertEquals(socketChannelClass, NioSocketChannel.class); Class<? extends ServerSocketChannel> serverSocketChannelClass = NettyEventLoopFactory.serverSocketChannelClass(); Assertions.assertEquals(serverSocketChannelClass, NioServerSocketChannel.class); } } private boolean isEpoll() { String osName = SystemPropertyConfigUtils.getSystemProperty(SYSTEM_OS_NAME); return osName.toLowerCase().contains(OS_LINUX_PREFIX) && Epoll.isAvailable(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientReconnectTest.java
dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientReconnectTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.DubboAppender; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.Client; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.RemotingServer; import org.apache.dubbo.remoting.exchange.Exchangers; import org.apache.dubbo.remoting.exchange.support.ExchangeHandlerAdapter; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT; import static org.apache.dubbo.remoting.Constants.LEAST_RECONNECT_DURATION_KEY; /** * Client reconnect test */ class ClientReconnectTest { private static final Logger logger = LoggerFactory.getLogger(ClientReconnectTest.class); public static void main(String[] args) { logger.info(String.valueOf(3 % 1)); } @BeforeEach public void clear() { DubboAppender.clear(); } @Test void testReconnect() throws RemotingException, InterruptedException { { int port = NetUtils.getAvailablePort(); Client client = startClient(port, 200); Assertions.assertFalse(client.isConnected()); RemotingServer server = startServer(port); for (int i = 0; i < 100 && !client.isConnected(); i++) { Thread.sleep(20); } Assertions.assertTrue(client.isConnected()); client.close(2000); server.close(2000); } { int port = NetUtils.getAvailablePort(); Client client = startClient(port, 20000); Assertions.assertFalse(client.isConnected()); RemotingServer server = startServer(port); for (int i = 0; i < 5; i++) { Thread.sleep(200); } Assertions.assertFalse(client.isConnected()); client.close(2000); server.close(2000); } } public Client startClient(int port, int heartbeat) throws RemotingException { URL url = URL.valueOf("exchange://127.0.0.1:" + port + "/client.reconnect.test?client=netty4&check=false&" + Constants.HEARTBEAT_KEY + "=" + heartbeat + "&" + LEAST_RECONNECT_DURATION_KEY + "=0"); FrameworkModel frameworkModel = new FrameworkModel(); ApplicationModel applicationModel = frameworkModel.newApplication(); ApplicationConfig applicationConfig = new ApplicationConfig("provider-app"); applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT); ConfigManager configManager = new ConfigManager(applicationModel); configManager.setApplication(applicationConfig); configManager.getApplication(); applicationModel.setConfigManager(configManager); url = url.putAttribute(CommonConstants.SCOPE_MODEL, applicationModel); return Exchangers.connect(url); } public RemotingServer startServer(int port) throws RemotingException { URL url = URL.valueOf("exchange://127.0.0.1:" + port + "/client.reconnect.test?server=netty4"); FrameworkModel frameworkModel = new FrameworkModel(); ApplicationModel applicationModel = frameworkModel.newApplication(); ApplicationConfig applicationConfig = new ApplicationConfig("provider-app"); applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT); ConfigManager configManager = new ConfigManager(applicationModel); configManager.setApplication(applicationConfig); configManager.getApplication(); applicationModel.setConfigManager(configManager); ModuleModel moduleModel = applicationModel.getDefaultModule(); url = url.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel); return Exchangers.bind(url, new HandlerAdapter()); } static class HandlerAdapter extends ExchangeHandlerAdapter { public HandlerAdapter() { super(FrameworkModel.defaultModel()); } @Override public void connected(Channel channel) throws RemotingException {} @Override public void disconnected(Channel channel) throws RemotingException {} @Override public void caught(Channel channel, Throwable exception) throws RemotingException {} } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ConnectionTest.java
dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ConnectionTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.remoting.api.connection.AbstractConnectionClient; import org.apache.dubbo.remoting.api.connection.ConnectionManager; import org.apache.dubbo.remoting.api.connection.MultiplexProtocolConnectionManager; import org.apache.dubbo.remoting.api.pu.DefaultPuHandler; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ModuleModel; import java.time.Duration; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT; import static org.awaitility.Awaitility.await; public class ConnectionTest { private static URL url; private static NettyPortUnificationServer server; private static ConnectionManager connectionManager; @BeforeAll public static void init() throws Throwable { int port = NetUtils.getAvailablePort(); url = URL.valueOf("empty://127.0.0.1:" + port + "?foo=bar"); ApplicationModel applicationModel = ApplicationModel.defaultModel(); ApplicationConfig applicationConfig = new ApplicationConfig("provider-app"); applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT); applicationModel.getApplicationConfigManager().setApplication(applicationConfig); ConfigManager configManager = new ConfigManager(applicationModel); configManager.setApplication(applicationConfig); configManager.getApplication(); applicationModel.setConfigManager(configManager); url = url.setScopeModel(applicationModel); ModuleModel moduleModel = applicationModel.getDefaultModule(); url = url.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel); server = new NettyPortUnificationServer(url, new DefaultPuHandler()); server.bind(); connectionManager = url.getOrDefaultFrameworkModel() .getExtensionLoader(ConnectionManager.class) .getExtension(MultiplexProtocolConnectionManager.NAME); } @AfterAll public static void close() { try { server.close(); } catch (Throwable e) { // ignored } } @Test void testGetChannel() { final AbstractConnectionClient connectionClient = connectionManager.connect(url, new DefaultPuHandler()); Assertions.assertNotNull(connectionClient); connectionClient.close(); } @Test void testRefCnt0() throws InterruptedException { final AbstractConnectionClient connectionClient = connectionManager.connect(url, new DefaultPuHandler()); CountDownLatch latch = new CountDownLatch(1); Assertions.assertNotNull(connectionClient); connectionClient.addCloseListener(latch::countDown); connectionClient.release(); latch.await(); Assertions.assertEquals(0, latch.getCount()); } @Test void testRefCnt1() { DefaultPuHandler handler = new DefaultPuHandler(); final AbstractConnectionClient connectionClient = connectionManager.connect(url, handler); CountDownLatch latch = new CountDownLatch(1); Assertions.assertNotNull(connectionClient); connectionManager.connect(url, handler); connectionClient.addCloseListener(latch::countDown); connectionClient.release(); Assertions.assertEquals(1, latch.getCount()); connectionClient.close(); } @Test void testRefCnt2() throws InterruptedException { final AbstractConnectionClient connectionClient = connectionManager.connect(url, new DefaultPuHandler()); CountDownLatch latch = new CountDownLatch(1); connectionClient.retain(); connectionClient.addCloseListener(latch::countDown); connectionClient.release(); connectionClient.release(); latch.await(); Assertions.assertEquals(0, latch.getCount()); } @Test void connectSyncTest() throws Throwable { int port = NetUtils.getAvailablePort(); URL url = URL.valueOf("empty://127.0.0.1:" + port + "?foo=bar"); NettyPortUnificationServer nettyPortUnificationServer = new NettyPortUnificationServer(url, new DefaultPuHandler()); nettyPortUnificationServer.bind(); final AbstractConnectionClient connectionClient = connectionManager.connect(url, new DefaultPuHandler()); Assertions.assertTrue(connectionClient.isAvailable()); nettyPortUnificationServer.close(); Assertions.assertFalse(connectionClient.isAvailable()); nettyPortUnificationServer.bind(); // auto reconnect await().atMost(Duration.ofSeconds(100)).until(() -> connectionClient.isAvailable()); Assertions.assertTrue(connectionClient.isAvailable()); connectionClient.close(); Assertions.assertFalse(connectionClient.isAvailable()); nettyPortUnificationServer.close(); } @Test void testMultiConnect() throws Throwable { ExecutorService service = Executors.newFixedThreadPool(10); final CountDownLatch latch = new CountDownLatch(10); AtomicInteger failedCount = new AtomicInteger(0); final AbstractConnectionClient connectionClient = connectionManager.connect(url, new DefaultPuHandler()); Runnable runnable = () -> { try { Assertions.assertTrue(connectionClient.isAvailable()); } catch (Exception e) { // ignore e.printStackTrace(); failedCount.incrementAndGet(); } finally { latch.countDown(); } }; for (int i = 0; i < 10; i++) { service.execute(runnable); } latch.await(); Assertions.assertEquals(0, failedCount.get()); service.shutdown(); connectionClient.destroy(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientToServerTest.java
dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientToServerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.ExchangeChannel; import org.apache.dubbo.remoting.exchange.ExchangeServer; import org.apache.dubbo.remoting.exchange.support.Replier; import java.util.concurrent.CompletableFuture; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * ClientToServer */ public abstract class ClientToServerTest { protected ExchangeServer server; protected ExchangeChannel client; protected WorldHandler handler = new WorldHandler(); protected abstract ExchangeServer newServer(int port, Replier<?> receiver) throws RemotingException; protected abstract ExchangeChannel newClient(int port) throws RemotingException; @BeforeEach protected void setUp() throws Exception { int port = NetUtils.getAvailablePort(); server = newServer(port, handler); client = newClient(port); } @AfterEach protected void tearDown() { try { if (server != null) server.close(); } finally { if (client != null) client.close(); } } @Test void testFuture() throws Exception { CompletableFuture<Object> future = client.request(new World("world")); Hello result = (Hello) future.get(); Assertions.assertEquals("hello,world", result.getName()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/api/EmptyWireProtocol.java
dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/api/EmptyWireProtocol.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4.api; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.remoting.api.ProtocolDetector; import org.apache.dubbo.remoting.api.WireProtocol; import org.apache.dubbo.remoting.api.pu.ChannelOperator; import org.apache.dubbo.remoting.api.ssl.ContextOperator; @Activate public class EmptyWireProtocol implements WireProtocol { @Override public ProtocolDetector detector() { return null; } @Override public void configServerProtocolHandler(URL url, ChannelOperator operator) {} @Override public void configClientPipeline(URL url, ChannelOperator operator, ContextOperator contextOperator) {} @Override public void close() {} }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/api/MultiplexProtocolConnectionManagerTest.java
dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/api/MultiplexProtocolConnectionManagerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4.api; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.remoting.api.connection.AbstractConnectionClient; import org.apache.dubbo.remoting.api.connection.ConnectionManager; import org.apache.dubbo.remoting.api.connection.MultiplexProtocolConnectionManager; import org.apache.dubbo.remoting.api.pu.DefaultPuHandler; import org.apache.dubbo.remoting.transport.netty4.NettyPortUnificationServer; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ModuleModel; import java.lang.reflect.Field; import java.util.Map; import java.util.function.Consumer; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT; public class MultiplexProtocolConnectionManagerTest { private static URL url1; private static URL url2; private static NettyPortUnificationServer server; private static ConnectionManager connectionManager; @BeforeAll public static void init() throws Throwable { ApplicationModel applicationModel = ApplicationModel.defaultModel(); ApplicationConfig applicationConfig = new ApplicationConfig("provider-app"); applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT); applicationModel.getApplicationConfigManager().setApplication(applicationConfig); ConfigManager configManager = new ConfigManager(applicationModel); configManager.setApplication(applicationConfig); configManager.getApplication(); applicationModel.setConfigManager(configManager); url1 = URL.valueOf("empty://127.0.0.1:8080?foo=bar"); url2 = URL.valueOf("tri://127.0.0.1:8081?foo=bar"); url1 = url1.setScopeModel(applicationModel); ModuleModel moduleModel = applicationModel.getDefaultModule(); url1 = url1.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel); url2 = url2.setScopeModel(applicationModel); url2 = url2.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel); server = new NettyPortUnificationServer(url1, new DefaultPuHandler()); server.bind(); connectionManager = url1.getOrDefaultFrameworkModel() .getExtensionLoader(ConnectionManager.class) .getExtension(MultiplexProtocolConnectionManager.NAME); } @AfterAll public static void close() { try { server.close(); } catch (Throwable e) { // ignored } } @Test public void testConnect() throws Exception { final AbstractConnectionClient connectionClient = connectionManager.connect(url1, new DefaultPuHandler()); Assertions.assertNotNull(connectionClient); Field protocolsField = connectionManager.getClass().getDeclaredField("protocols"); protocolsField.setAccessible(true); Map protocolMap = (Map) protocolsField.get(connectionManager); Assertions.assertNotNull(protocolMap.get(url1.getProtocol())); connectionClient.close(); } @Test public void testForEachConnection() throws Throwable { DefaultPuHandler handler = new DefaultPuHandler(); NettyPortUnificationServer server2 = new NettyPortUnificationServer(url2, handler); server2.bind(); final AbstractConnectionClient connect1 = connectionManager.connect(url1, handler); final AbstractConnectionClient connect2 = connectionManager.connect(url2, handler); Consumer<AbstractConnectionClient> consumer = connection -> { String protocol = connection.getUrl().getProtocol(); Assertions.assertTrue(protocol.equals("empty") || protocol.equals("tri")); }; connectionManager.forEachConnection(consumer); // close connections to avoid impacts on other test cases. connect1.close(); connect2.close(); try { server2.close(); } catch (Throwable e) { // ignored } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/api/SingleProtocolConnectionManagerTest.java
dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/api/SingleProtocolConnectionManagerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4.api; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.api.connection.AbstractConnectionClient; import org.apache.dubbo.remoting.api.connection.ConnectionManager; import org.apache.dubbo.remoting.api.connection.SingleProtocolConnectionManager; import org.apache.dubbo.remoting.api.pu.DefaultPuHandler; import org.apache.dubbo.remoting.transport.netty4.NettyConnectionClient; import org.apache.dubbo.remoting.transport.netty4.NettyPortUnificationServer; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ModuleModel; import java.lang.reflect.Field; import java.util.Map; import java.util.function.Consumer; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT; public class SingleProtocolConnectionManagerTest { private static URL url; private static NettyPortUnificationServer server; private static ConnectionManager connectionManager; @BeforeAll public static void init() throws Throwable { int port = NetUtils.getAvailablePort(); url = URL.valueOf("empty://127.0.0.1:" + port + "?foo=bar"); ApplicationModel applicationModel = ApplicationModel.defaultModel(); ApplicationConfig applicationConfig = new ApplicationConfig("provider-app"); applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT); applicationModel.getApplicationConfigManager().setApplication(applicationConfig); ConfigManager configManager = new ConfigManager(applicationModel); configManager.setApplication(applicationConfig); configManager.getApplication(); applicationModel.setConfigManager(configManager); url = url.setScopeModel(applicationModel); ModuleModel moduleModel = applicationModel.getDefaultModule(); url = url.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel); server = new NettyPortUnificationServer(url, new DefaultPuHandler()); server.bind(); connectionManager = url.getOrDefaultFrameworkModel() .getExtensionLoader(ConnectionManager.class) .getExtension(SingleProtocolConnectionManager.NAME); } @AfterAll public static void close() { try { server.close(); } catch (Throwable e) { // ignored } } @Test public void testConnect() throws Exception { final NettyConnectionClient connectionClient = (NettyConnectionClient) connectionManager.connect(url, new DefaultPuHandler()); Assertions.assertNotNull(connectionClient); Field protocolsField = connectionManager.getClass().getDeclaredField("connections"); protocolsField.setAccessible(true); Map protocolMap = (Map) protocolsField.get(connectionManager); Assertions.assertNotNull(protocolMap.get(url.getAddress())); connectionClient.close(); // Test whether closePromise's listener removes entry connectionClient.getClosePromise().await(); while (protocolMap.containsKey(url.getAddress())) {} Assertions.assertNull(protocolMap.get(url.getAddress())); } @Test public void testForEachConnection() throws RemotingException { AbstractConnectionClient connectionClient = connectionManager.connect(url, new DefaultPuHandler()); { Consumer<AbstractConnectionClient> consumer1 = connection -> Assertions.assertEquals("empty", connection.getUrl().getProtocol()); connectionManager.forEachConnection(consumer1); } { Consumer<AbstractConnectionClient> consumer2 = connection -> Assertions.assertNotEquals("not-empty", connection.getUrl().getProtocol()); connectionManager.forEachConnection(consumer2); } connectionClient.close(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyBackedChannelBuffer.java
dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyBackedChannelBuffer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.remoting.buffer.ChannelBuffer; import org.apache.dubbo.remoting.buffer.ChannelBufferFactory; import org.apache.dubbo.remoting.buffer.ChannelBuffers; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import io.netty.buffer.ByteBuf; import io.netty.util.ReferenceCountUtil; public class NettyBackedChannelBuffer implements ChannelBuffer { private final ByteBuf buffer; public NettyBackedChannelBuffer(ByteBuf buffer) { Assert.notNull(buffer, "buffer == null"); this.buffer = buffer; } @Override public int capacity() { return buffer.capacity(); } @Override public ChannelBuffer copy(int index, int length) { return new NettyBackedChannelBuffer(buffer.copy(index, length)); } // has nothing use @Override public ChannelBufferFactory factory() { return null; } @Override public byte getByte(int index) { return buffer.getByte(index); } @Override public void getBytes(int index, byte[] dst, int dstIndex, int length) { buffer.getBytes(index, dst, dstIndex, length); } @Override public void getBytes(int index, ByteBuffer dst) { buffer.getBytes(index, dst); } @Override public void getBytes(int index, ChannelBuffer dst, int dstIndex, int length) { // careful byte[] data = new byte[length]; buffer.getBytes(index, data, 0, length); dst.setBytes(dstIndex, data, 0, length); } @Override public void getBytes(int index, OutputStream dst, int length) throws IOException { buffer.getBytes(index, dst, length); } @Override public boolean isDirect() { return buffer.isDirect(); } @Override public void setByte(int index, int value) { buffer.setByte(index, value); } @Override public void setBytes(int index, byte[] src, int srcIndex, int length) { buffer.setBytes(index, src, srcIndex, length); } @Override public void setBytes(int index, ByteBuffer src) { buffer.setBytes(index, src); } @Override public void setBytes(int index, ChannelBuffer src, int srcIndex, int length) { if (length > src.readableBytes()) { throw new IndexOutOfBoundsException(); } // careful byte[] data = new byte[length]; src.getBytes(srcIndex, data, 0, length); setBytes(index, data, 0, length); } @Override public int setBytes(int index, InputStream src, int length) throws IOException { return buffer.setBytes(index, src, length); } @Override public ByteBuffer toByteBuffer(int index, int length) { return buffer.nioBuffer(index, length); } @Override public byte[] array() { return buffer.array(); } @Override public boolean hasArray() { return buffer.hasArray(); } @Override public int arrayOffset() { return buffer.arrayOffset(); } // AbstractChannelBuffer @Override public void clear() { buffer.clear(); } @Override public ChannelBuffer copy() { return new NettyBackedChannelBuffer(buffer.copy()); } @Override public void discardReadBytes() { buffer.discardReadBytes(); } @Override public void ensureWritableBytes(int writableBytes) { buffer.ensureWritable(writableBytes); } @Override public void getBytes(int index, byte[] dst) { buffer.getBytes(index, dst); } @Override public void getBytes(int index, ChannelBuffer dst) { // careful getBytes(index, dst, dst.writableBytes()); } @Override public void getBytes(int index, ChannelBuffer dst, int length) { // careful if (length > dst.writableBytes()) { throw new IndexOutOfBoundsException(); } getBytes(index, dst, dst.writerIndex(), length); dst.writerIndex(dst.writerIndex() + length); } @Override public void markReaderIndex() { buffer.markReaderIndex(); } @Override public void markWriterIndex() { buffer.markWriterIndex(); } @Override public boolean readable() { return buffer.isReadable(); } @Override public int readableBytes() { return buffer.readableBytes(); } @Override public byte readByte() { return buffer.readByte(); } @Override public void readBytes(byte[] dst) { buffer.readBytes(dst); } @Override public void readBytes(byte[] dst, int dstIndex, int length) { buffer.readBytes(dst, dstIndex, length); } @Override public void readBytes(ByteBuffer dst) { buffer.readBytes(dst); } @Override public void readBytes(ChannelBuffer dst) { // careful readBytes(dst, dst.writableBytes()); } @Override public void readBytes(ChannelBuffer dst, int length) { // careful if (length > dst.writableBytes()) { throw new IndexOutOfBoundsException(); } readBytes(dst, dst.writerIndex(), length); dst.writerIndex(dst.writerIndex() + length); } @Override public void readBytes(ChannelBuffer dst, int dstIndex, int length) { // careful if (readableBytes() < length) { throw new IndexOutOfBoundsException(); } byte[] data = new byte[length]; buffer.readBytes(data, 0, length); dst.setBytes(dstIndex, data, 0, length); } @Override public ChannelBuffer readBytes(int length) { return new NettyBackedChannelBuffer(buffer.readBytes(length)); } @Override public void resetReaderIndex() { buffer.resetReaderIndex(); } @Override public void resetWriterIndex() { buffer.resetWriterIndex(); } @Override public int readerIndex() { return buffer.readerIndex(); } @Override public void readerIndex(int readerIndex) { buffer.readerIndex(readerIndex); } @Override public void readBytes(OutputStream dst, int length) throws IOException { buffer.readBytes(dst, length); } @Override public void setBytes(int index, byte[] src) { buffer.setBytes(index, src); } @Override public void setBytes(int index, ChannelBuffer src) { // careful setBytes(index, src, src.readableBytes()); } @Override public void setBytes(int index, ChannelBuffer src, int length) { // careful if (length > src.readableBytes()) { throw new IndexOutOfBoundsException(); } setBytes(index, src, src.readerIndex(), length); src.readerIndex(src.readerIndex() + length); } @Override public void setIndex(int readerIndex, int writerIndex) { buffer.setIndex(readerIndex, writerIndex); } @Override public void skipBytes(int length) { buffer.skipBytes(length); } @Override public ByteBuffer toByteBuffer() { return buffer.nioBuffer(); } @Override public boolean writable() { return buffer.isWritable(); } @Override public int writableBytes() { return buffer.writableBytes(); } @Override public void writeByte(int value) { buffer.writeByte(value); } @Override public void writeBytes(byte[] src) { buffer.writeBytes(src); } @Override public void writeBytes(byte[] src, int index, int length) { buffer.writeBytes(src, index, length); } @Override public void writeBytes(ByteBuffer src) { buffer.writeBytes(src); } @Override public void writeBytes(ChannelBuffer src) { // careful writeBytes(src, src.readableBytes()); } @Override public void writeBytes(ChannelBuffer src, int length) { // careful if (length > src.readableBytes()) { throw new IndexOutOfBoundsException(); } writeBytes(src, src.readerIndex(), length); src.readerIndex(src.readerIndex() + length); } @Override public void writeBytes(ChannelBuffer src, int srcIndex, int length) { // careful byte[] data = new byte[length]; src.getBytes(srcIndex, data, 0, length); writeBytes(data, 0, length); } @Override public int writeBytes(InputStream src, int length) throws IOException { return buffer.writeBytes(src, length); } @Override public int writerIndex() { return buffer.writerIndex(); } @Override public void writerIndex(int writerIndex) { buffer.ensureWritable(writerIndex); buffer.writerIndex(writerIndex); } @Override public int compareTo(ChannelBuffer o) { return ChannelBuffers.compare(this, o); } public void release() { ReferenceCountUtil.safeRelease(buffer); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyCodecAdapter.java
dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyCodecAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.Codec2; import org.apache.dubbo.remoting.buffer.ChannelBuffer; import org.apache.dubbo.remoting.exchange.support.MultiMessage; import java.io.IOException; import java.util.List; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageDecoder; import io.netty.handler.codec.MessageToByteEncoder; /** * NettyCodecAdapter. */ public final class NettyCodecAdapter { private final ChannelHandler encoder = new InternalEncoder(); private final ChannelHandler decoder = new InternalDecoder(); private final Codec2 codec; private final URL url; private final org.apache.dubbo.remoting.ChannelHandler handler; public NettyCodecAdapter(Codec2 codec, URL url, org.apache.dubbo.remoting.ChannelHandler handler) { this.codec = codec; this.url = url; this.handler = handler; } public ChannelHandler getEncoder() { return encoder; } public ChannelHandler getDecoder() { return decoder; } private class InternalEncoder extends MessageToByteEncoder { @Override protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception { boolean encoded = false; if (msg instanceof ByteBuf) { out.writeBytes(((ByteBuf) msg)); encoded = true; } else if (msg instanceof MultiMessage) { for (Object singleMessage : ((MultiMessage) msg)) { if (singleMessage instanceof ByteBuf) { ByteBuf buf = (ByteBuf) singleMessage; out.writeBytes(buf); encoded = true; buf.release(); } } } if (!encoded) { ChannelBuffer buffer = new NettyBackedChannelBuffer(out); Channel ch = ctx.channel(); NettyChannel channel = NettyChannel.getOrAddChannel(ch, url, handler); codec.encode(channel, buffer, msg); } } } private class InternalDecoder extends ByteToMessageDecoder { @Override protected void decode(ChannelHandlerContext ctx, ByteBuf input, List<Object> out) throws Exception { ChannelBuffer message = new NettyBackedChannelBuffer(input); try { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); // decode object. do { int saveReaderIndex = message.readerIndex(); Object msg = codec.decode(channel, message); if (msg == Codec2.DecodeResult.NEED_MORE_INPUT) { message.readerIndex(saveReaderIndex); break; } else { // is it possible to go here ? if (saveReaderIndex == message.readerIndex()) { throw new IOException("Decode without read data."); } if (msg != null) { out.add(msg); } } } while (message.readable()); } catch (Throwable t) { message.skipBytes(message.readableBytes()); throw t; } } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyEventLoopFactory.java
dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyEventLoopFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.resource.GlobalResourceInitializer; import org.apache.dubbo.common.utils.SystemPropertyConfigUtils; import org.apache.dubbo.remoting.Constants; import java.util.concurrent.ThreadFactory; import io.netty.channel.EventLoopGroup; import io.netty.channel.epoll.Epoll; import io.netty.channel.epoll.EpollEventLoopGroup; import io.netty.channel.epoll.EpollServerSocketChannel; import io.netty.channel.epoll.EpollSocketChannel; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.ServerSocketChannel; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.util.concurrent.DefaultThreadFactory; import static org.apache.dubbo.common.constants.CommonConstants.OS_LINUX_PREFIX; import static org.apache.dubbo.common.constants.CommonConstants.SystemProperty.SYSTEM_OS_NAME; import static org.apache.dubbo.common.constants.CommonConstants.ThirdPartyProperty.NETTY_EPOLL_ENABLE_KEY; public class NettyEventLoopFactory { /** * netty client bootstrap */ public static final GlobalResourceInitializer<EventLoopGroup> NIO_EVENT_LOOP_GROUP = new GlobalResourceInitializer<>( () -> eventLoopGroup(Constants.DEFAULT_IO_THREADS, "NettyClientWorker"), eventLoopGroup -> eventLoopGroup.shutdownGracefully()); public static EventLoopGroup eventLoopGroup(int threads, String threadFactoryName) { ThreadFactory threadFactory = new DefaultThreadFactory(threadFactoryName, true); if (shouldEpoll()) { return new EpollEventLoopGroup(threads, threadFactory); } else { return new NioEventLoopGroup(threads, threadFactory); } } public static Class<? extends SocketChannel> socketChannelClass() { return shouldEpoll() ? EpollSocketChannel.class : NioSocketChannel.class; } public static Class<? extends ServerSocketChannel> serverSocketChannelClass() { return shouldEpoll() ? EpollServerSocketChannel.class : NioServerSocketChannel.class; } private static boolean shouldEpoll() { if (Boolean.parseBoolean(SystemPropertyConfigUtils.getSystemProperty(NETTY_EPOLL_ENABLE_KEY, "false"))) { String osName = SystemPropertyConfigUtils.getSystemProperty(SYSTEM_OS_NAME); return osName.toLowerCase().contains(OS_LINUX_PREFIX) && Epoll.isAvailable(); } return false; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettySslContextOperator.java
dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettySslContextOperator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.remoting.api.ssl.ContextOperator; import io.netty.handler.ssl.SslContext; public class NettySslContextOperator implements ContextOperator { @Override public SslContext buildContext() { return null; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyConnectionHandler.java
dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyConnectionHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.api.connection.ConnectionHandler; import java.util.concurrent.TimeUnit; import io.netty.channel.Channel; import io.netty.channel.ChannelHandler.Sharable; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.util.Attribute; import io.netty.util.AttributeKey; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_UNEXPECTED_EXCEPTION; @Sharable public class NettyConnectionHandler extends ChannelInboundHandlerAdapter implements ConnectionHandler { private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(NettyConnectionHandler.class); private static final AttributeKey<Boolean> GO_AWAY_KEY = AttributeKey.valueOf("dubbo_channel_goaway"); private final AbstractNettyConnectionClient connectionClient; public NettyConnectionHandler(AbstractNettyConnectionClient connectionClient) { this.connectionClient = connectionClient; } @Override public void onGoAway(Object channel) { if (!(channel instanceof Channel)) { return; } Channel nettyChannel = ((Channel) channel); Attribute<Boolean> attr = nettyChannel.attr(GO_AWAY_KEY); if (Boolean.TRUE.equals(attr.get())) { return; } attr.set(true); if (connectionClient != null) { connectionClient.onGoaway(nettyChannel); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Channel {} go away ,schedule reconnect", nettyChannel); } reconnect(nettyChannel); } @Override public void reconnect(Object channel) { if (!(channel instanceof Channel)) { return; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Connection:{} is reconnecting, attempt={}", connectionClient, 1); } if (connectionClient.isClosed()) { LOGGER.info("The connection {} has been closed and will not reconnect", connectionClient); return; } connectionClient.scheduleReconnect(1, TimeUnit.SECONDS); } @Override public void channelActive(ChannelHandlerContext ctx) { ctx.fireChannelActive(); Channel ch = ctx.channel(); NettyChannel channel = NettyChannel.getOrAddChannel(ch, connectionClient.getUrl(), connectionClient); if (!connectionClient.isClosed()) { connectionClient.onConnected(ch); if (LOGGER.isInfoEnabled() && channel != null) { LOGGER.info( "The connection {} of {} -> {} is established.", ch, channel.getLocalAddressKey(), channel.getRemoteAddressKey()); } } else { ctx.close(); } } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { super.channelInactive(ctx); Channel ch = ctx.channel(); NettyChannel channel = NettyChannel.getOrAddChannel(ch, connectionClient.getUrl(), connectionClient); try { Attribute<Boolean> goawayAttr = ch.attr(GO_AWAY_KEY); if (!Boolean.TRUE.equals(goawayAttr.get())) { reconnect(ch); } if (LOGGER.isInfoEnabled() && channel != null) { LOGGER.info( "The connection {} of {} -> {} is disconnected.", ch, channel.getLocalAddressKey(), channel.getRemoteAddressKey()); } } finally { NettyChannel.removeChannel(ch); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { LOGGER.warn(TRANSPORT_UNEXPECTED_EXCEPTION, "", "", String.format("Channel error:%s", ctx.channel()), cause); ctx.close(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyConnectionClient.java
dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyConnectionClient.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.api.WireProtocol; import org.apache.dubbo.remoting.transport.netty4.http2.Http2ClientSettingsHandler; import org.apache.dubbo.remoting.transport.netty4.ssl.SslClientTlsHandler; import org.apache.dubbo.remoting.transport.netty4.ssl.SslContexts; import org.apache.dubbo.remoting.utils.UrlUtils; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.http2.Http2FrameCodec; import io.netty.handler.ssl.SslContext; import io.netty.handler.timeout.IdleStateHandler; import io.netty.util.concurrent.DefaultPromise; import io.netty.util.concurrent.GlobalEventExecutor; import io.netty.util.concurrent.Promise; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_CLIENT_CONNECT_TIMEOUT; import static org.apache.dubbo.remoting.transport.netty4.NettyEventLoopFactory.socketChannelClass; public final class NettyConnectionClient extends AbstractNettyConnectionClient { private Bootstrap bootstrap; private AtomicReference<Promise<Void>> channelInitializedPromiseRef; private AtomicReference<Promise<Void>> connectionPrefaceReceivedPromiseRef; public NettyConnectionClient(URL url, ChannelHandler handler) throws RemotingException { super(url, handler); } @Override protected void initConnectionClient() { protocol = getUrl().getOrDefaultFrameworkModel() .getExtensionLoader(WireProtocol.class) .getExtension(getUrl().getProtocol()); super.initConnectionClient(); } protected void initBootstrap() { channelInitializedPromiseRef = new AtomicReference<>(); Bootstrap bootstrap = new Bootstrap(); bootstrap .group(NettyEventLoopFactory.NIO_EVENT_LOOP_GROUP.get()) .option(ChannelOption.SO_KEEPALIVE, true) .option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .remoteAddress(getConnectAddress()) .channel(socketChannelClass()); NettyConnectionHandler connectionHandler = new NettyConnectionHandler(this); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getConnectTimeout()); SslContext sslContext = SslContexts.buildClientSslContext(getUrl()); bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { NettyChannel nettyChannel = NettyChannel.getOrAddChannel(ch, getUrl(), getChannelHandler()); ChannelPipeline pipeline = ch.pipeline(); NettySslContextOperator nettySslContextOperator = new NettySslContextOperator(); if (sslContext != null) { pipeline.addLast("negotiation", new SslClientTlsHandler(sslContext)); } // pipeline.addLast("logging", new LoggingHandler(LogLevel.INFO)); //for debug int heartbeat = UrlUtils.getHeartbeat(getUrl()); pipeline.addLast("client-idle-handler", new IdleStateHandler(heartbeat, 0, 0, MILLISECONDS)); pipeline.addLast(Constants.CONNECTION_HANDLER_NAME, connectionHandler); NettyConfigOperator operator = new NettyConfigOperator(nettyChannel, getChannelHandler()); protocol.configClientPipeline(getUrl(), operator, nettySslContextOperator); ChannelHandlerContext http2FrameCodecHandlerCtx = pipeline.context(Http2FrameCodec.class); if (http2FrameCodecHandlerCtx == null) { // set connection preface received promise to null. connectionPrefaceReceivedPromiseRef = null; } else { // create connection preface received promise if necessary. if (connectionPrefaceReceivedPromiseRef == null) { connectionPrefaceReceivedPromiseRef = new AtomicReference<>(); } connectionPrefaceReceivedPromiseRef.compareAndSet( null, new DefaultPromise<>(GlobalEventExecutor.INSTANCE)); pipeline.addAfter( http2FrameCodecHandlerCtx.name(), "client-connection-preface-handler", new Http2ClientSettingsHandler(connectionPrefaceReceivedPromiseRef)); } // set null but do not close this client, it will be reconnecting in the future ch.closeFuture().addListener(channelFuture -> clearNettyChannel()); // TODO support Socks5 // set channel initialized promise to success if necessary. Promise<Void> channelInitializedPromise = channelInitializedPromiseRef.get(); if (channelInitializedPromise != null) { channelInitializedPromise.trySuccess(null); } } }); this.bootstrap = bootstrap; } @Override protected ChannelFuture performConnect() { // ChannelInitializer#initChannel will be invoked by Netty client work thread. return bootstrap.connect(); } @Override protected void doConnect() throws RemotingException { long start = System.currentTimeMillis(); // re-create channel initialized promise if necessary. channelInitializedPromiseRef.compareAndSet(null, new DefaultPromise<>(GlobalEventExecutor.INSTANCE)); super.doConnect(); waitConnectionPreface(start); } /** * Wait connection preface * <br> * Http2 client should set max header list size of http2 encoder based on server connection preface before * sending first data frame, otherwise the http2 server might send back GO_AWAY frame and disconnect the connection * immediately if the size of client Headers frame is bigger than the MAX_HEADER_LIST_SIZE of server settings.<br> * @see <a href="https://httpwg.org/specs/rfc7540.html#ConnectionHeader">HTTP/2 Connection Preface</a><br> * In HTTP/2, each endpoint is required to send a connection preface as a final confirmation of the protocol * in use and to establish the initial settings for the HTTP/2 connection. The client and server each send a * different connection preface. The client connection preface starts with a sequence of 24 octets, * which in hex notation is:<br> * 0x505249202a20485454502f322e300d0a0d0a534d0d0a0d0a<br> * That is, the connection preface starts with the string PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n<br> * This sequence MUST be followed by a SETTINGS frame (Section 6.5), which MAY be empty. * The server connection preface consists of a potentially empty SETTINGS frame (Section 6.5) that MUST be * the first frame the server sends in the HTTP/2 connection. * * @param start start time of doConnect in milliseconds. */ private void waitConnectionPreface(long start) throws RemotingException { // await channel initialization to ensure connection preface received promise had been created when necessary. Promise<Void> channelInitializedPromise = channelInitializedPromiseRef.get(); long retainedTimeout = getConnectTimeout() - System.currentTimeMillis() + start; boolean ret = channelInitializedPromise.awaitUninterruptibly(retainedTimeout, TimeUnit.MILLISECONDS); // destroy channel initialized promise after used. channelInitializedPromiseRef.set(null); if (!ret || !channelInitializedPromise.isSuccess()) { // 6-2 Client-side channel initialization timeout RemotingException remotingException = new RemotingException( this, "client(url: " + getUrl() + ") failed to connect to server " + getConnectAddress() + " client-side channel initialization timeout " + getConnectTimeout() + "ms (elapsed: " + (System.currentTimeMillis() - start) + "ms) from netty client " + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion()); logger.error( TRANSPORT_CLIENT_CONNECT_TIMEOUT, "provider crash", "", "Client-side channel initialization timeout", remotingException); throw remotingException; } // await if connection preface received promise is not null. if (connectionPrefaceReceivedPromiseRef == null) { return; } Promise<Void> connectionPrefaceReceivedPromise = connectionPrefaceReceivedPromiseRef.get(); retainedTimeout = getConnectTimeout() - System.currentTimeMillis() + start; ret = connectionPrefaceReceivedPromise.awaitUninterruptibly(retainedTimeout, TimeUnit.MILLISECONDS); // destroy connection preface received promise after used. connectionPrefaceReceivedPromiseRef.set(null); if (!ret || !connectionPrefaceReceivedPromise.isSuccess()) { // 6-2 Client-side connection preface timeout RemotingException remotingException = new RemotingException( this, "client(url: " + getUrl() + ") failed to connect to server " + getConnectAddress() + " client-side connection preface timeout " + getConnectTimeout() + "ms (elapsed: " + (System.currentTimeMillis() - start) + "ms) from netty client " + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion()); logger.error( TRANSPORT_CLIENT_CONNECT_TIMEOUT, "provider crash", "", "Client-side connection preface timeout", remotingException); throw remotingException; } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyPortUnificationServer.java
dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyPortUnificationServer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.api.WireProtocol; import org.apache.dubbo.remoting.api.pu.AbstractPortUnificationServer; import org.apache.dubbo.remoting.transport.dispatcher.ChannelHandlers; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.ChannelPipeline; import io.netty.channel.EventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.util.concurrent.Future; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.IO_THREADS_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE; import static org.apache.dubbo.remoting.Constants.EVENT_LOOP_BOSS_POOL_NAME; import static org.apache.dubbo.remoting.Constants.EVENT_LOOP_WORKER_POOL_NAME; /** * PortUnificationServer. */ public class NettyPortUnificationServer extends AbstractPortUnificationServer { private int serverShutdownTimeoutMills; /** * netty server bootstrap. */ private ServerBootstrap bootstrap; /** * the boss channel that receive connections and dispatch these to worker channel. */ private io.netty.channel.Channel channel; private EventLoopGroup bossGroup; private EventLoopGroup workerGroup; private Map<String, Channel> dubboChannels; public NettyPortUnificationServer(URL url, ChannelHandler handler) throws RemotingException { super(url, ChannelHandlers.wrap(handler, url)); } @Override public void addSupportedProtocol(URL url, ChannelHandler handler) { super.addSupportedProtocol(url, ChannelHandlers.wrap(handler, url)); } @Override public void close() { if (channel != null) { doClose(); } } public void bind() throws Throwable { if (channel == null) { doOpen(); } } @Override public void doOpen0() { bootstrap = new ServerBootstrap(); // initialize dubboChannels and serverShutdownTimeoutMills before potential usage to avoid NPE. dubboChannels = new ConcurrentHashMap<>(); // you can customize name and type of client thread pool by THREAD_NAME_KEY and THREADPOOL_KEY in // CommonConstants. // the handler will be wrapped: MultiMessageHandler->HeartbeatHandler->handler // read config before destroy serverShutdownTimeoutMills = ConfigurationUtils.getServerShutdownTimeout(getUrl().getOrDefaultModuleModel()); bossGroup = NettyEventLoopFactory.eventLoopGroup(1, EVENT_LOOP_BOSS_POOL_NAME); workerGroup = NettyEventLoopFactory.eventLoopGroup( getUrl().getPositiveParameter(IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS), EVENT_LOOP_WORKER_POOL_NAME); bootstrap .group(bossGroup, workerGroup) .channel(NettyEventLoopFactory.serverSocketChannelClass()) .option(ChannelOption.SO_REUSEADDR, Boolean.TRUE) .childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE) .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { // Do not add idle state handler here, because it should be added in the protocol handler. final ChannelPipeline p = ch.pipeline(); NettyChannelHandler nettyChannelHandler = new NettyChannelHandler(dubboChannels, getUrl(), NettyPortUnificationServer.this); NettyPortUnificationServerHandler puHandler = new NettyPortUnificationServerHandler( getUrl(), true, getProtocols(), NettyPortUnificationServer.this, getSupportedUrls(), getSupportedHandlers()); p.addLast("channel-handler", nettyChannelHandler); p.addLast("negotiation-protocol", puHandler); } }); // bind String bindIp = getUrl().getParameter(Constants.BIND_IP_KEY, getUrl().getHost()); int bindPort = getUrl().getParameter(Constants.BIND_PORT_KEY, getUrl().getPort()); if (getUrl().getParameter(ANYHOST_KEY, false) || NetUtils.isInvalidLocalHost(bindIp)) { bindIp = ANYHOST_VALUE; } InetSocketAddress bindAddress = new InetSocketAddress(bindIp, bindPort); try { ChannelFuture channelFuture = bootstrap.bind(bindAddress); channelFuture.syncUninterruptibly(); channel = channelFuture.channel(); } catch (Throwable t) { closeBootstrap(); throw t; } } private void closeBootstrap() { try { if (bootstrap != null) { long timeout = ConfigurationUtils.reCalShutdownTime(serverShutdownTimeoutMills); long quietPeriod = Math.min(2000L, timeout); Future<?> bossGroupShutdownFuture = bossGroup.shutdownGracefully(quietPeriod, timeout, MILLISECONDS); Future<?> workerGroupShutdownFuture = workerGroup.shutdownGracefully(quietPeriod, timeout, MILLISECONDS); bossGroupShutdownFuture.awaitUninterruptibly(timeout, MILLISECONDS); workerGroupShutdownFuture.awaitUninterruptibly(timeout, MILLISECONDS); } } catch (Throwable e) { logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } } @Override public void doClose() { try { if (channel != null) { // unbind. channel.close(); channel = null; } } catch (Throwable e) { logger.warn(TRANSPORT_FAILED_CLOSE, "", "", "Interrupted while shutting down", e); } try { Collection<Channel> channels = getChannels(); if (CollectionUtils.isNotEmpty(channels)) { for (Channel channel : channels) { try { channel.close(); } catch (Throwable e) { logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } } } } catch (Throwable e) { logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } for (WireProtocol protocol : getProtocols().values()) { protocol.close(); } closeBootstrap(); } @Override protected int getChannelsSize() { return dubboChannels.size(); } public boolean isBound() { return channel.isActive(); } @Override public Collection<Channel> getChannels() { Collection<Channel> chs = new ArrayList<>(this.dubboChannels.size()); chs.addAll(this.dubboChannels.values()); return chs; } @Override public Channel getChannel(InetSocketAddress remoteAddress) { return dubboChannels.get(NetUtils.toAddressString(remoteAddress)); } public InetSocketAddress getLocalAddress() { return (InetSocketAddress) channel.localAddress(); } @Override public boolean canHandleIdle() { return true; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java
dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.metrics.event.MetricsEventBus; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.registry.event.NettyEvent; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.transport.AbstractServer; import org.apache.dubbo.remoting.transport.dispatcher.ChannelHandlers; import org.apache.dubbo.remoting.transport.netty4.ssl.SslServerTlsHandler; import org.apache.dubbo.remoting.utils.UrlUtils; import org.apache.dubbo.rpc.model.ApplicationModel; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.handler.timeout.IdleStateHandler; import io.netty.util.concurrent.Future; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.apache.dubbo.common.constants.CommonConstants.IO_THREADS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.KEEP_ALIVE_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE; import static org.apache.dubbo.remoting.Constants.EVENT_LOOP_BOSS_POOL_NAME; import static org.apache.dubbo.remoting.Constants.EVENT_LOOP_WORKER_POOL_NAME; /** * NettyServer. */ public class NettyServer extends AbstractServer { /** * the cache for alive worker channel. * <ip:port, dubbo channel> */ private Map<String, Channel> channels; /** * netty server bootstrap. */ private ServerBootstrap bootstrap; /** * the boss channel that receive connections and dispatch these to worker channel. */ private io.netty.channel.Channel channel; private EventLoopGroup bossGroup; private EventLoopGroup workerGroup; private int serverShutdownTimeoutMills; public NettyServer(URL url, ChannelHandler handler) throws RemotingException { // you can customize name and type of client thread pool by THREAD_NAME_KEY and THREAD_POOL_KEY in // CommonConstants. // the handler will be wrapped: MultiMessageHandler->HeartbeatHandler->handler super(url, ChannelHandlers.wrap(handler, url)); } /** * Init and start netty server * * @throws Throwable */ @Override protected void doOpen() throws Throwable { bootstrap = new ServerBootstrap(); // initialize serverShutdownTimeoutMills before potential usage to avoid NPE. // read config before destroy serverShutdownTimeoutMills = ConfigurationUtils.getServerShutdownTimeout(getUrl().getOrDefaultModuleModel()); bossGroup = createBossGroup(); workerGroup = createWorkerGroup(); final NettyServerHandler nettyServerHandler = createNettyServerHandler(); channels = nettyServerHandler.getChannels(); initServerBootstrap(nettyServerHandler); // bind try { ChannelFuture channelFuture = bootstrap.bind(getBindAddress()); channelFuture.syncUninterruptibly(); channel = channelFuture.channel(); } catch (Throwable t) { closeBootstrap(); throw t; } // metrics if (isSupportMetrics()) { ApplicationModel applicationModel = ApplicationModel.defaultModel(); MetricsEventBus.post(NettyEvent.toNettyEvent(applicationModel), () -> { Map<String, Long> dataMap = new HashMap<>(); dataMap.put( MetricsKey.NETTY_ALLOCATOR_HEAP_MEMORY_USED.getName(), PooledByteBufAllocator.DEFAULT.metric().usedHeapMemory()); dataMap.put( MetricsKey.NETTY_ALLOCATOR_DIRECT_MEMORY_USED.getName(), PooledByteBufAllocator.DEFAULT.metric().usedDirectMemory()); dataMap.put(MetricsKey.NETTY_ALLOCATOR_HEAP_ARENAS_NUM.getName(), (long) PooledByteBufAllocator.DEFAULT.numHeapArenas()); dataMap.put(MetricsKey.NETTY_ALLOCATOR_DIRECT_ARENAS_NUM.getName(), (long) PooledByteBufAllocator.DEFAULT.numDirectArenas()); dataMap.put(MetricsKey.NETTY_ALLOCATOR_NORMAL_CACHE_SIZE.getName(), (long) PooledByteBufAllocator.DEFAULT.normalCacheSize()); dataMap.put(MetricsKey.NETTY_ALLOCATOR_SMALL_CACHE_SIZE.getName(), (long) PooledByteBufAllocator.DEFAULT.smallCacheSize()); dataMap.put(MetricsKey.NETTY_ALLOCATOR_THREAD_LOCAL_CACHES_NUM.getName(), (long) PooledByteBufAllocator.DEFAULT.numThreadLocalCaches()); dataMap.put(MetricsKey.NETTY_ALLOCATOR_CHUNK_SIZE.getName(), (long) PooledByteBufAllocator.DEFAULT.chunkSize()); return dataMap; }); } } private boolean isSupportMetrics() { return ClassUtils.isPresent("io.netty.buffer.PooledByteBufAllocatorMetric", NettyServer.class.getClassLoader()); } protected EventLoopGroup createBossGroup() { return NettyEventLoopFactory.eventLoopGroup(1, EVENT_LOOP_BOSS_POOL_NAME); } protected EventLoopGroup createWorkerGroup() { return NettyEventLoopFactory.eventLoopGroup( getUrl().getPositiveParameter(IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS), EVENT_LOOP_WORKER_POOL_NAME); } protected NettyServerHandler createNettyServerHandler() { return new NettyServerHandler(getUrl(), this); } protected void initServerBootstrap(NettyServerHandler nettyServerHandler) { boolean keepalive = getUrl().getParameter(KEEP_ALIVE_KEY, Boolean.FALSE); bootstrap .group(bossGroup, workerGroup) .channel(NettyEventLoopFactory.serverSocketChannelClass()) .option(ChannelOption.SO_REUSEADDR, Boolean.TRUE) .childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE) .childOption(ChannelOption.SO_KEEPALIVE, keepalive) .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { int closeTimeout = UrlUtils.getCloseTimeout(getUrl()); NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyServer.this); ch.pipeline().addLast("negotiation", new SslServerTlsHandler(getUrl())); ch.pipeline() .addLast("decoder", adapter.getDecoder()) .addLast("encoder", adapter.getEncoder()) .addLast("server-idle-handler", new IdleStateHandler(0, 0, closeTimeout, MILLISECONDS)) .addLast("handler", nettyServerHandler); } }); } @Override protected void doClose() { try { if (channel != null) { // unbind. channel.close(); } } catch (Throwable e) { logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } try { Collection<Channel> channels = getChannels(); if (CollectionUtils.isNotEmpty(channels)) { for (Channel channel : channels) { try { channel.close(); } catch (Throwable e) { logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } } } } catch (Throwable e) { logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } closeBootstrap(); try { if (channels != null) { channels.clear(); } } catch (Throwable e) { logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } } private void closeBootstrap() { try { if (bootstrap != null) { long timeout = ConfigurationUtils.reCalShutdownTime(serverShutdownTimeoutMills); long quietPeriod = Math.min(2000L, timeout); Future<?> bossGroupShutdownFuture = bossGroup.shutdownGracefully(quietPeriod, timeout, MILLISECONDS); Future<?> workerGroupShutdownFuture = workerGroup.shutdownGracefully(quietPeriod, timeout, MILLISECONDS); bossGroupShutdownFuture.syncUninterruptibly(); workerGroupShutdownFuture.syncUninterruptibly(); } } catch (Throwable e) { logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } } @Override protected int getChannelsSize() { return channels.size(); } @Override public Collection<Channel> getChannels() { return new ArrayList<>(channels.values()); } @Override public Channel getChannel(InetSocketAddress remoteAddress) { return channels.get(NetUtils.toAddressString(remoteAddress)); } @Override public boolean canHandleIdle() { return true; } @Override public boolean isBound() { return channel.isActive(); } protected EventLoopGroup getBossGroup() { return bossGroup; } protected EventLoopGroup getWorkerGroup() { return workerGroup; } protected ServerBootstrap getServerBootstrap() { return bootstrap; } protected io.netty.channel.Channel getBossChannel() { return channel; } protected Map<String, Channel> getServerChannels() { return channels; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/AbstractNettyConnectionClient.java
dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/AbstractNettyConnectionClient.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.api.connection.AbstractConnectionClient; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.util.AttributeKey; import io.netty.util.concurrent.DefaultPromise; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GlobalEventExecutor; import io.netty.util.concurrent.Promise; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_CLIENT_CONNECT_TIMEOUT; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CONNECT_PROVIDER; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_RECONNECT; public abstract class AbstractNettyConnectionClient extends AbstractConnectionClient { private AtomicReference<Promise<Object>> connectingPromiseRef; private AtomicReference<io.netty.channel.Channel> channelRef; private Promise<Void> connectedPromise; private Promise<Void> disconnectedPromise; private Promise<Void> closePromise; private AtomicBoolean isReconnecting; private ConnectionListener connectionListener; public static final AttributeKey<AbstractConnectionClient> CONNECTION = AttributeKey.valueOf("connection"); public AbstractNettyConnectionClient(URL url, ChannelHandler handler) throws RemotingException { super(url, handler); } @Override protected void doOpen() throws Throwable { initConnectionClient(); initBootstrap(); } @Override protected void initConnectionClient() { remote = getConnectAddress(); init = new AtomicBoolean(false); connectingPromiseRef = new AtomicReference<>(); channelRef = new AtomicReference<>(); connectedPromise = new DefaultPromise<>(GlobalEventExecutor.INSTANCE); disconnectedPromise = new DefaultPromise<>(GlobalEventExecutor.INSTANCE); closePromise = new DefaultPromise<>(GlobalEventExecutor.INSTANCE); isReconnecting = new AtomicBoolean(false); connectionListener = new ConnectionListener(); increase(); } protected abstract void initBootstrap() throws Exception; @Override protected void doClose() { // AbstractPeer close can set closed true. if (isClosed()) { if (logger.isDebugEnabled()) { logger.debug("Connection:{} freed", this); } performClose(); closePromise.setSuccess(null); } } protected void performClose() { io.netty.channel.Channel current = getNettyChannel(); if (current != null) { current.close(); } clearNettyChannel(); } @Override protected void doConnect() throws RemotingException { if (!isReconnecting.compareAndSet(false, true)) { return; } if (isClosed()) { if (logger.isDebugEnabled()) { logger.debug("Connection:{} aborted to reconnect cause connection closed", this); } return; } if (logger.isDebugEnabled()) { logger.debug("Connection:{} attempting to reconnect to server {}", this, getConnectAddress()); } init.compareAndSet(false, true); long start = System.currentTimeMillis(); Promise<Object> connectingPromise = getOrCreateConnectingPromise(); Future<Void> connectPromise = performConnect(); connectPromise.addListener(connectionListener); boolean ret = connectingPromise.awaitUninterruptibly(getConnectTimeout(), TimeUnit.MILLISECONDS); // destroy connectingPromise after used synchronized (this) { connectingPromiseRef.set(null); } if (connectPromise.cause() != null) { Throwable cause = connectPromise.cause(); // 6-1 Failed to connect to provider server by other reason. RemotingException remotingException = new RemotingException( this, "client(url: " + getUrl() + ") failed to connect to server " + getConnectAddress() + ", error message is:" + cause.getMessage(), cause); logger.error( TRANSPORT_FAILED_CONNECT_PROVIDER, "network disconnected", "", "Failed to connect to provider server by other reason", cause); throw remotingException; } else if (!ret || !connectPromise.isSuccess()) { // 6-2 Client-side timeout RemotingException remotingException = new RemotingException( this, "client(url: " + getUrl() + ") failed to connect to server " + getConnectAddress() + " client-side timeout " + getConnectTimeout() + "ms (elapsed: " + (System.currentTimeMillis() - start) + "ms) from netty client " + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion()); logger.error( TRANSPORT_CLIENT_CONNECT_TIMEOUT, "provider crash", "", "Client-side timeout", remotingException); throw remotingException; } } protected abstract ChannelFuture performConnect(); @Override protected void doDisConnect() { NettyChannel.removeChannelIfDisconnected(getNettyChannel()); } protected void scheduleReconnect(long reconnectDuration, TimeUnit unit) { connectivityExecutor.schedule( () -> { try { doConnect(); } catch (RemotingException e) { logger.error( TRANSPORT_FAILED_RECONNECT, "", "", "Failed to connect to server: " + getConnectAddress()); } }, reconnectDuration, unit); } @Override public void onConnected(Object channel) { if (!(channel instanceof io.netty.channel.Channel)) { return; } io.netty.channel.Channel nettyChannel = ((io.netty.channel.Channel) channel); if (isClosed()) { nettyChannel.close(); if (logger.isDebugEnabled()) { logger.debug("Connection:{} is closed, ignoring connected event", this); } return; } // Close the existing channel before setting a new channel io.netty.channel.Channel current = getNettyChannel(); if (current != null) { current.close(); } channelRef.set(nettyChannel); // This indicates that the connection is available. Promise<Object> connectingPromise = connectingPromiseRef.get(); if (connectingPromise != null) { connectingPromise.trySuccess(CONNECTED_OBJECT); } nettyChannel.attr(CONNECTION).set(this); // Notify the connection is available. connectedPromise.trySuccess(null); if (logger.isDebugEnabled()) { logger.debug("Connection:{} connected", this); } } @Override public void onGoaway(Object channel) { if (!(channel instanceof io.netty.channel.Channel)) { return; } io.netty.channel.Channel nettyChannel = (io.netty.channel.Channel) channel; if (channelRef.compareAndSet(nettyChannel, null)) { // Ensure the channel is closed if (nettyChannel.isOpen()) { nettyChannel.close(); } NettyChannel.removeChannelIfDisconnected(nettyChannel); if (logger.isDebugEnabled()) { logger.debug("Connection:{} goaway", this); } } } @Override protected Channel getChannel() { io.netty.channel.Channel c = getNettyChannel(); if (c == null) { return null; } return NettyChannel.getOrAddChannel(c, getUrl(), this); } private io.netty.channel.Channel getNettyChannel() { return channelRef.get(); } protected void clearNettyChannel() { channelRef.set(null); } @Override @SuppressWarnings("unchecked") public <T> T getChannel(Boolean generalizable) { return Boolean.TRUE.equals(generalizable) ? (T) getNettyChannel() : (T) getChannel(); } @Override public boolean isAvailable() { if (isClosed()) { return false; } io.netty.channel.Channel nettyChannel = getNettyChannel(); if (nettyChannel != null && nettyChannel.isActive()) { return true; } if (init.compareAndSet(false, true)) { try { doConnect(); } catch (RemotingException e) { logger.error(TRANSPORT_FAILED_RECONNECT, "", "", "Failed to connect to server: " + getConnectAddress()); } } getOrCreateConnectingPromise().awaitUninterruptibly(getConnectTimeout(), TimeUnit.MILLISECONDS); // destroy connectingPromise after used synchronized (this) { connectingPromiseRef.set(null); } nettyChannel = getNettyChannel(); return nettyChannel != null && nettyChannel.isActive(); } private Promise<Object> getOrCreateConnectingPromise() { connectingPromiseRef.compareAndSet(null, new DefaultPromise<>(GlobalEventExecutor.INSTANCE)); return connectingPromiseRef.get(); } public Promise<Void> getClosePromise() { return closePromise; } public static AbstractConnectionClient getConnectionClientFromChannel(io.netty.channel.Channel channel) { return channel.attr(CONNECTION).get(); } public ChannelFuture write(Object request) throws RemotingException { if (!isAvailable()) { throw new RemotingException( null, null, "Failed to send request " + request + ", cause: The channel to " + remote + " is closed!"); } return getNettyChannel().writeAndFlush(request); } @Override public void addConnectedListener(Runnable func) { connectedPromise.addListener(future -> func.run()); } @Override public void addDisconnectedListener(Runnable func) { disconnectedPromise.addListener(future -> func.run()); } @Override public void addCloseListener(Runnable func) { closePromise.addListener(future -> func.run()); } @Override public void destroy() { close(); } @Override public String toString() { return super.toString() + " (Ref=" + getCounter() + ",local=" + Optional.ofNullable(getChannel()) .map(Channel::getLocalAddress) .orElse(null) + ",remote=" + getRemoteAddress(); } class ConnectionListener implements ChannelFutureListener { @Override public void operationComplete(ChannelFuture future) { if (!isReconnecting.compareAndSet(true, false)) { return; } if (future.isSuccess()) { return; } AbstractNettyConnectionClient connectionClient = AbstractNettyConnectionClient.this; if (connectionClient.isClosed() || connectionClient.getCounter() == 0) { if (logger.isDebugEnabled()) { logger.debug( "Connection:{} aborted to reconnect. {}", connectionClient, future.cause().getMessage()); } return; } if (logger.isDebugEnabled()) { logger.debug( "Connection:{} is reconnecting, attempt=0 cause={}", connectionClient, future.cause().getMessage()); } // Notify the connection is unavailable. disconnectedPromise.trySuccess(null); scheduleReconnect(reconnectDuration, TimeUnit.MILLISECONDS); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyPortUnificationServerHandler.java
dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyPortUnificationServerHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.io.Bytes; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.ssl.AuthPolicy; import org.apache.dubbo.common.ssl.CertManager; import org.apache.dubbo.common.ssl.ProviderCert; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.api.ProtocolDetector; import org.apache.dubbo.remoting.api.WireProtocol; import org.apache.dubbo.remoting.buffer.ChannelBuffer; import org.apache.dubbo.remoting.transport.netty4.ssl.SslContexts; import javax.net.ssl.SSLSession; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPipeline; import io.netty.handler.codec.ByteToMessageDecoder; import io.netty.handler.ssl.ApplicationProtocolNames; import io.netty.handler.ssl.ApplicationProtocolNegotiationHandler; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslHandler; import io.netty.handler.ssl.SslHandshakeCompletionEvent; import io.netty.util.AttributeKey; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_SSL_CONNECT_INSECURE; import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR; public class NettyPortUnificationServerHandler extends ByteToMessageDecoder { private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(NettyPortUnificationServerHandler.class); private final URL url; private final ChannelHandler handler; private final boolean detectSsl; private final Map<String, WireProtocol> protocols; private final Map<String, URL> urlMapper; private final Map<String, ChannelHandler> handlerMapper; private static final AttributeKey<SSLSession> SSL_SESSION_KEY = AttributeKey.valueOf(Constants.SSL_SESSION_KEY); public NettyPortUnificationServerHandler( URL url, boolean detectSsl, Map<String, WireProtocol> protocols, ChannelHandler handler, Map<String, URL> urlMapper, Map<String, ChannelHandler> handlerMapper) { this.url = url; this.protocols = protocols; this.detectSsl = detectSsl; this.handler = handler; this.urlMapper = urlMapper; this.handlerMapper = handlerMapper; } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { LOGGER.error( INTERNAL_ERROR, "unknown error in remoting module", "", "Unexpected exception from downstream before protocol detected.", cause); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof SslHandshakeCompletionEvent) { SslHandshakeCompletionEvent handshakeEvent = (SslHandshakeCompletionEvent) evt; if (handshakeEvent.isSuccess()) { SSLSession session = ctx.pipeline().get(SslHandler.class).engine().getSession(); LOGGER.info("TLS negotiation succeed with session: " + session); ctx.channel().attr(SSL_SESSION_KEY).set(session); } else { LOGGER.error( INTERNAL_ERROR, "", "", "TLS negotiation failed when trying to accept new connection.", handshakeEvent.cause()); ctx.close(); } } super.userEventTriggered(ctx, evt); } @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); // Will use the first five bytes to detect a protocol. // size of telnet command ls is 2 bytes if (in.readableBytes() < 2) { return; } CertManager certManager = url.getOrDefaultFrameworkModel().getBeanFactory().getBean(CertManager.class); ProviderCert providerConnectionConfig = certManager.getProviderConnectionConfig(url, ctx.channel().remoteAddress()); if (providerConnectionConfig != null && canDetectSsl(in)) { if (isSsl(in)) { enableSsl(ctx, providerConnectionConfig); } else { // check server should load TLS or not if (providerConnectionConfig.getAuthPolicy() != AuthPolicy.NONE) { byte[] preface = new byte[in.readableBytes()]; in.readBytes(preface); LOGGER.error( CONFIG_SSL_CONNECT_INSECURE, "client request server without TLS", "", String.format( "Downstream=%s request without TLS preface, but server require it. " + "preface=%s", ctx.channel().remoteAddress(), Bytes.bytes2hex(preface))); // Untrusted connection; discard everything and close the connection. in.clear(); ctx.close(); } } } else { detectProtocol(ctx, url, channel, in); } } private void enableSsl(ChannelHandlerContext ctx, ProviderCert providerConnectionConfig) { ChannelPipeline p = ctx.pipeline(); SslContext sslContext = SslContexts.buildServerSslContext(providerConnectionConfig); p.addLast("ssl", sslContext.newHandler(ctx.alloc())); p.addLast( "unificationA", new NettyPortUnificationServerHandler(url, false, protocols, handler, urlMapper, handlerMapper)); p.addLast("ALPN", new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_1_1) { @Override protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception { if (!ApplicationProtocolNames.HTTP_2.equals(protocol)) { return; } NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); ByteBuf in = ctx.alloc().buffer(); detectProtocol(ctx, url, channel, in); } }); p.remove(this); } private boolean canDetectSsl(ByteBuf buf) { // at least 5 bytes to determine if data is encrypted return detectSsl && buf.readableBytes() >= 5; } private boolean isSsl(ByteBuf buf) { // at least 5 bytes to determine if data is encrypted if (detectSsl && buf.readableBytes() >= 5) { return SslHandler.isEncrypted(buf); } return false; } private void detectProtocol(ChannelHandlerContext ctx, URL url, NettyChannel channel, ByteBuf in) { Set<String> supportedProtocolNames = new HashSet<>(protocols.keySet()); supportedProtocolNames.retainAll(urlMapper.keySet()); for (final String name : supportedProtocolNames) { WireProtocol protocol = protocols.get(name); in.markReaderIndex(); ChannelBuffer buf = new NettyBackedChannelBuffer(in); final ProtocolDetector.Result result = protocol.detector().detect(buf); in.resetReaderIndex(); switch (result.flag()) { case UNRECOGNIZED: continue; case RECOGNIZED: ChannelHandler localHandler = this.handlerMapper.getOrDefault(name, handler); URL localURL = this.urlMapper.getOrDefault(name, url); channel.setUrl(localURL); NettyConfigOperator operator = new NettyConfigOperator(channel, localHandler); operator.setDetectResult(result); protocol.configServerProtocolHandler(url, operator); ctx.pipeline().remove(this); case NEED_MORE_DATA: return; default: return; } } byte[] preface = new byte[in.readableBytes()]; in.readBytes(preface); Set<String> supported = url.getApplicationModel().getSupportedExtensions(WireProtocol.class); LOGGER.error( INTERNAL_ERROR, "unknown error in remoting module", "", String.format( "Can not recognize protocol from downstream=%s . " + "preface=%s protocols=%s", ctx.channel().remoteAddress(), Bytes.bytes2hex(preface), supported)); // Unknown protocol; discard everything and close the connection. in.clear(); ctx.close(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyConfigOperator.java
dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyConfigOperator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Codec; import org.apache.dubbo.remoting.Codec2; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.api.ProtocolDetector; import org.apache.dubbo.remoting.api.pu.ChannelHandlerPretender; import org.apache.dubbo.remoting.api.pu.ChannelOperator; import org.apache.dubbo.remoting.api.pu.DefaultCodec; import org.apache.dubbo.remoting.transport.codec.CodecAdapter; import java.util.Collection; import java.util.List; public class NettyConfigOperator implements ChannelOperator { private final Channel channel; private ChannelHandler handler; private ProtocolDetector.Result detectResult; public NettyConfigOperator(NettyChannel channel, ChannelHandler handler) { this.channel = channel; this.handler = handler; } @Override public void configChannelHandler(List<ChannelHandler> handlerList) { URL url = channel.getUrl(); Codec2 codec2; String codecName = url.getParameter(Constants.CODEC_KEY); if (StringUtils.isEmpty(codecName)) { // codec extension name must stay the same with protocol name codecName = url.getProtocol(); } if (url.getOrDefaultFrameworkModel().getExtensionLoader(Codec2.class).hasExtension(codecName)) { codec2 = url.getOrDefaultFrameworkModel() .getExtensionLoader(Codec2.class) .getExtension(codecName); } else if (url.getOrDefaultFrameworkModel() .getExtensionLoader(Codec.class) .hasExtension(codecName)) { codec2 = new CodecAdapter(url.getOrDefaultFrameworkModel() .getExtensionLoader(Codec.class) .getExtension(codecName)); } else { codec2 = url.getOrDefaultFrameworkModel() .getExtensionLoader(Codec2.class) .getExtension("default"); } if (!(codec2 instanceof DefaultCodec)) { ((NettyChannel) channel).setCodec(codec2); NettyCodecAdapter codec = new NettyCodecAdapter(codec2, channel.getUrl(), handler); ((NettyChannel) channel) .getNioChannel() .pipeline() .addLast(codec.getDecoder()) .addLast(codec.getEncoder()); } for (ChannelHandler handler : handlerList) { if (handler instanceof ChannelHandlerPretender) { Object realHandler = ((ChannelHandlerPretender) handler).getRealHandler(); addRealHandler(realHandler); } } // todo distinguish between client and server channel if (isClientSide(channel)) { // todo config client channel handler } else { NettyServerHandler sh = new NettyServerHandler(channel.getUrl(), handler); ((NettyChannel) channel).getNioChannel().pipeline().addLast(sh); } } private void addRealHandler(Object realHandler) { if (realHandler instanceof Collection) { Collection realHandlers = (Collection) realHandler; for (Object handler : realHandlers) { addChannelHandler(handler); } } else { addChannelHandler(realHandler); } } private void addChannelHandler(Object channelHandler) { if (!(channelHandler instanceof io.netty.channel.ChannelHandler)) { return; } ((NettyChannel) channel).getNioChannel().pipeline().addLast((io.netty.channel.ChannelHandler) channelHandler); } public void setDetectResult(ProtocolDetector.Result detectResult) { this.detectResult = detectResult; } @Override public ProtocolDetector.Result detectResult() { return detectResult; } private boolean isClientSide(Channel channel) { return channel.getUrl().getSide("").equalsIgnoreCase(CommonConstants.CONSUMER); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/ChannelAddressAccessor.java
dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/ChannelAddressAccessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import java.net.InetSocketAddress; import io.netty.channel.Channel; @SPI(scope = ExtensionScope.FRAMEWORK) public interface ChannelAddressAccessor { String getProtocol(); InetSocketAddress getRemoteAddress(Channel channel); InetSocketAddress getLocalAddress(Channel channel); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyConnectionManager.java
dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyConnectionManager.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.api.connection.AbstractConnectionClient; import org.apache.dubbo.remoting.api.connection.ConnectionManager; import java.util.function.Consumer; public class NettyConnectionManager implements ConnectionManager { public static final String NAME = "netty4"; @Override public AbstractConnectionClient connect(URL url, ChannelHandler handler) { try { return new NettyConnectionClient(url, handler); } catch (RemotingException e) { throw new RuntimeException(e); } } @Override public void forEachConnection(Consumer<AbstractConnectionClient> connectionConsumer) { // Do nothing. } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClient.java
dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClient.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.resource.GlobalResourceInitializer; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.transport.AbstractClient; import org.apache.dubbo.remoting.transport.netty4.ssl.SslClientTlsHandler; import org.apache.dubbo.remoting.transport.netty4.ssl.SslContexts; import org.apache.dubbo.remoting.utils.UrlUtils; import java.net.InetSocketAddress; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.handler.proxy.Socks5ProxyHandler; import io.netty.handler.ssl.SslContext; import io.netty.handler.timeout.IdleStateHandler; import io.netty.util.concurrent.EventExecutorGroup; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_CLIENT_CONNECT_TIMEOUT; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CONNECT_PROVIDER; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_DISCONNECT_PROVIDER; import static org.apache.dubbo.remoting.Constants.DEFAULT_CONNECT_TIMEOUT; import static org.apache.dubbo.remoting.transport.netty4.NettyEventLoopFactory.eventLoopGroup; import static org.apache.dubbo.remoting.transport.netty4.NettyEventLoopFactory.socketChannelClass; /** * NettyClient. */ public class NettyClient extends AbstractClient { private static final String SOCKS_PROXY_HOST = "socksProxyHost"; private static final String SOCKS_PROXY_PORT = "socksProxyPort"; private static final String DEFAULT_SOCKS_PROXY_PORT = "1080"; /** * netty client bootstrap */ private static final GlobalResourceInitializer<EventLoopGroup> EVENT_LOOP_GROUP = new GlobalResourceInitializer<>( () -> eventLoopGroup(Constants.DEFAULT_IO_THREADS, "NettyClientWorker"), EventExecutorGroup::shutdownGracefully); private Bootstrap bootstrap; /** * current channel. Each successful invocation of {@link NettyClient#doConnect()} will * replace this with new channel and close old channel. * <b>volatile, please copy reference to use.</b> */ private volatile Channel channel; /** * The constructor of NettyClient. * It wil init and start netty. */ public NettyClient(final URL url, final ChannelHandler handler) throws RemotingException { // you can customize name and type of client thread pool by THREAD_NAME_KEY and THREADPOOL_KEY in // CommonConstants. // the handler will be wrapped: MultiMessageHandler->HeartbeatHandler->handler super(url, wrapChannelHandler(url, handler)); } /** * Init bootstrap * * @throws Throwable */ @Override protected void doOpen() throws Throwable { final NettyClientHandler nettyClientHandler = createNettyClientHandler(); bootstrap = new Bootstrap(); initBootstrap(nettyClientHandler); } protected NettyClientHandler createNettyClientHandler() { return new NettyClientHandler(getUrl(), this); } protected void initBootstrap(NettyClientHandler nettyClientHandler) { bootstrap .group(EVENT_LOOP_GROUP.get()) .option(ChannelOption.SO_KEEPALIVE, true) .option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) // .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getTimeout()) .channel(socketChannelClass()); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, Math.max(DEFAULT_CONNECT_TIMEOUT, getConnectTimeout())); SslContext sslContext = SslContexts.buildClientSslContext(getUrl()); bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { int heartbeatInterval = UrlUtils.getHeartbeat(getUrl()); if (sslContext != null) { ch.pipeline().addLast("negotiation", new SslClientTlsHandler(sslContext)); } NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this); ch.pipeline() // .addLast("logging",new LoggingHandler(LogLevel.INFO))//for debug .addLast("decoder", adapter.getDecoder()) .addLast("encoder", adapter.getEncoder()) .addLast("client-idle-handler", new IdleStateHandler(heartbeatInterval, 0, 0, MILLISECONDS)) .addLast("handler", nettyClientHandler); String socksProxyHost = ConfigurationUtils.getProperty(getUrl().getOrDefaultApplicationModel(), SOCKS_PROXY_HOST); if (socksProxyHost != null && !isFilteredAddress(getUrl().getHost())) { int socksProxyPort = Integer.parseInt(ConfigurationUtils.getProperty( getUrl().getOrDefaultApplicationModel(), SOCKS_PROXY_PORT, DEFAULT_SOCKS_PROXY_PORT)); Socks5ProxyHandler socks5ProxyHandler = new Socks5ProxyHandler(new InetSocketAddress(socksProxyHost, socksProxyPort)); ch.pipeline().addFirst(socks5ProxyHandler); } } }); } private boolean isFilteredAddress(String host) { // filter local address return StringUtils.isEquals(NetUtils.getLocalHost(), host) || NetUtils.isLocalHost(host); } @Override protected void doConnect() throws Throwable { try { String ipv6Address = NetUtils.getLocalHostV6(); InetSocketAddress connectAddress; // first try ipv6 address if (ipv6Address != null && getUrl().getParameter(CommonConstants.IPV6_KEY) != null) { connectAddress = new InetSocketAddress(getUrl().getParameter(CommonConstants.IPV6_KEY), getUrl().getPort()); try { doConnect(connectAddress); return; } catch (Throwable throwable) { // ignore } } connectAddress = getConnectAddress(); doConnect(connectAddress); } finally { // just add new valid channel to NettyChannel's cache if (!isConnected()) { // future.cancel(true); } } } private void doConnect(InetSocketAddress serverAddress) throws RemotingException { long start = System.currentTimeMillis(); ChannelFuture future = bootstrap.connect(serverAddress); try { boolean ret = future.awaitUninterruptibly(getConnectTimeout(), MILLISECONDS); if (ret && future.isSuccess()) { Channel newChannel = future.channel(); try { // Close old channel // copy reference Channel oldChannel = NettyClient.this.channel; if (oldChannel != null) { try { if (logger.isInfoEnabled()) { logger.info("Close old netty channel " + oldChannel + " on create new netty channel " + newChannel); } oldChannel.close(); } finally { NettyChannel.removeChannelIfDisconnected(oldChannel); } } } finally { if (NettyClient.this.isClosed()) { try { if (logger.isInfoEnabled()) { logger.info("Close new netty channel " + newChannel + ", because the client closed."); } newChannel.close(); } finally { NettyClient.this.channel = null; NettyChannel.removeChannelIfDisconnected(newChannel); } } else { NettyClient.this.channel = newChannel; } } } else if (future.cause() != null) { Throwable cause = future.cause(); // 6-1 Failed to connect to provider server by other reason. RemotingException remotingException = new RemotingException( this, "client(url: " + getUrl() + ") failed to connect to server " + serverAddress + ", error message is:" + cause.getMessage(), cause); logger.error( TRANSPORT_FAILED_CONNECT_PROVIDER, "network disconnected", "", "Failed to connect to provider server by other reason.", cause); throw remotingException; } else { // 6-2 Client-side timeout RemotingException remotingException = new RemotingException( this, "client(url: " + getUrl() + ") failed to connect to server " + serverAddress + " client-side timeout " + getConnectTimeout() + "ms (elapsed: " + (System.currentTimeMillis() - start) + "ms) from netty client " + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion()); logger.error( TRANSPORT_CLIENT_CONNECT_TIMEOUT, "provider crash", "", "Client-side timeout.", remotingException); throw remotingException; } } finally { // just add new valid channel to NettyChannel's cache if (!isConnected()) { // future.cancel(true); } } } @Override protected void doDisConnect() throws Throwable { try { NettyChannel.removeChannelIfDisconnected(channel); } catch (Throwable t) { logger.warn(TRANSPORT_FAILED_DISCONNECT_PROVIDER, "", "", t.getMessage()); } } @Override protected void doClose() throws Throwable { // can't shut down nioEventLoopGroup because the method will be invoked when closing one channel but not a // client, // but when and how to close the nioEventLoopGroup ? // nioEventLoopGroup.shutdownGracefully(); } @Override protected org.apache.dubbo.remoting.Channel getChannel() { Channel c = channel; if (c == null) { return null; } return NettyChannel.getOrAddChannel(c, getUrl(), this); } Channel getNettyChannel() { return channel; } @Override public boolean canHandleIdle() { return true; } protected EventLoopGroup getEventLoopGroup() { return EVENT_LOOP_GROUP.get(); } protected Bootstrap getBootstrap() { return bootstrap; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyPortUnificationTransporter.java
dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyPortUnificationTransporter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.api.connection.AbstractConnectionClient; import org.apache.dubbo.remoting.api.connection.ConnectionManager; import org.apache.dubbo.remoting.api.connection.MultiplexProtocolConnectionManager; import org.apache.dubbo.remoting.api.pu.AbstractPortUnificationServer; import org.apache.dubbo.remoting.api.pu.PortUnificationTransporter; public class NettyPortUnificationTransporter implements PortUnificationTransporter { public static final String NAME = "netty4"; @Override public AbstractPortUnificationServer bind(URL url, ChannelHandler handler) throws RemotingException { return new NettyPortUnificationServer(url, handler); } @Override public AbstractConnectionClient connect(URL url, ChannelHandler handler) throws RemotingException { ConnectionManager manager = url.getOrDefaultFrameworkModel() .getExtensionLoader(ConnectionManager.class) .getExtension(MultiplexProtocolConnectionManager.NAME); return manager.connect(url, handler); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServerHandler.java
dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServerHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Constants; import javax.net.ssl.SSLSession; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import io.netty.handler.ssl.SslHandshakeCompletionEvent; import io.netty.handler.timeout.IdleStateEvent; import io.netty.util.AttributeKey; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_UNEXPECTED_EXCEPTION; /** * NettyServerHandler. */ @io.netty.channel.ChannelHandler.Sharable public class NettyServerHandler extends ChannelDuplexHandler { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(NettyServerHandler.class); /** * the cache for alive worker channel. * <ip:port, dubbo channel> */ private final Map<String, Channel> channels = new ConcurrentHashMap<>(); private static final AttributeKey<SSLSession> SSL_SESSION_KEY = AttributeKey.valueOf(Constants.SSL_SESSION_KEY); private final URL url; private final ChannelHandler handler; public NettyServerHandler(URL url, ChannelHandler handler) { if (url == null) { throw new IllegalArgumentException("url == null"); } if (handler == null) { throw new IllegalArgumentException("handler == null"); } this.url = url; this.handler = handler; } public Map<String, Channel> getChannels() { return channels; } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { io.netty.channel.Channel ch = ctx.channel(); NettyChannel channel = NettyChannel.getOrAddChannel(ch, url, handler); if (channel != null) { channels.put(NetUtils.toAddressString(channel.getRemoteAddress()), channel); } handler.connected(channel); if (logger.isInfoEnabled() && channel != null) { logger.info( "The connection {} of {} -> {} is established.", ch, channel.getRemoteAddressKey(), channel.getLocalAddressKey()); } } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { io.netty.channel.Channel ch = ctx.channel(); NettyChannel channel = NettyChannel.getOrAddChannel(ch, url, handler); try { channels.remove(NetUtils.toAddressString(channel.getRemoteAddress())); handler.disconnected(channel); } finally { NettyChannel.removeChannel(ch); } if (logger.isInfoEnabled()) { logger.info( "The connection {} of {} -> {} is disconnected.", ch, channel.getRemoteAddressKey(), channel.getLocalAddressKey()); } } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); handler.received(channel, msg); // trigger qos handler ctx.fireChannelRead(msg); } @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { super.write(ctx, msg, promise); NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); handler.sent(channel, msg); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { // server will close channel when server don't receive any heartbeat from client util timeout. if (evt instanceof IdleStateEvent) { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); try { logger.info("IdleStateEvent triggered, close channel " + channel); channel.close(); } finally { NettyChannel.removeChannelIfDisconnected(ctx.channel()); } } super.userEventTriggered(ctx, evt); if (evt instanceof SslHandshakeCompletionEvent) { SslHandshakeCompletionEvent handshakeEvent = (SslHandshakeCompletionEvent) evt; if (handshakeEvent.isSuccess()) { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); channel.setAttribute( Constants.SSL_SESSION_KEY, ctx.channel().attr(SSL_SESSION_KEY).get()); } } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { io.netty.channel.Channel ch = ctx.channel(); NettyChannel channel = NettyChannel.getOrAddChannel(ch, url, handler); try { handler.caught(channel, cause); } finally { NettyChannel.removeChannelIfDisconnected(ch); } if (logger.isWarnEnabled()) { logger.warn( TRANSPORT_UNEXPECTED_EXCEPTION, "", "", channel == null ? String.format("The connection %s has exception.", ch) : String.format( "The connection %s of %s -> %s has exception.", ch, channel.getRemoteAddressKey(), channel.getLocalAddressKey()), cause); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClientHandler.java
dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClientHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.exchange.Request; import io.netty.channel.Channel; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import io.netty.handler.timeout.IdleStateEvent; import static org.apache.dubbo.common.constants.CommonConstants.HEARTBEAT_EVENT; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_UNEXPECTED_EXCEPTION; @io.netty.channel.ChannelHandler.Sharable public class NettyClientHandler extends ChannelDuplexHandler { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(NettyClientHandler.class); private final URL url; private final ChannelHandler handler; public NettyClientHandler(URL url, ChannelHandler handler) { if (url == null) { throw new IllegalArgumentException("url == null"); } if (handler == null) { throw new IllegalArgumentException("handler == null"); } this.url = url; this.handler = handler; } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { Channel ch = ctx.channel(); NettyChannel channel = NettyChannel.getOrAddChannel(ch, url, handler); handler.connected(channel); if (logger.isInfoEnabled()) { logger.info( "The connection {} of {} -> {} is established.", ch, channel.getLocalAddressKey(), channel.getRemoteAddressKey()); } } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { Channel ch = ctx.channel(); NettyChannel channel = NettyChannel.getOrAddChannel(ch, url, handler); try { handler.disconnected(channel); } finally { NettyChannel.removeChannel(ch); } if (logger.isInfoEnabled()) { logger.info( "The connection {} of {} -> {} is disconnected.", ch, channel.getLocalAddressKey(), channel.getRemoteAddressKey()); } } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); handler.received(channel, msg); } @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { super.write(ctx, msg, promise); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { // send heartbeat when read idle. if (evt instanceof IdleStateEvent) { try { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); if (logger.isDebugEnabled()) { logger.debug("IdleStateEvent triggered, send heartbeat to channel " + channel); } Request req = new Request(); req.setVersion(Version.getProtocolVersion()); req.setTwoWay(true); req.setEvent(HEARTBEAT_EVENT); channel.send(req); } finally { NettyChannel.removeChannelIfDisconnected(ctx.channel()); } } else { super.userEventTriggered(ctx, evt); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { Channel ch = ctx.channel(); NettyChannel channel = NettyChannel.getOrAddChannel(ch, url, handler); try { handler.caught(channel, cause); } finally { NettyChannel.removeChannelIfDisconnected(ch); } if (logger.isWarnEnabled()) { logger.warn( TRANSPORT_UNEXPECTED_EXCEPTION, "", "", channel == null ? String.format("The connection %s has exception.", ch) : String.format( "The connection %s of %s -> %s has exception.", ch, channel.getLocalAddressKey(), channel.getRemoteAddressKey()), cause); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyChannelHandler.java
dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyChannelHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import java.net.InetSocketAddress; import java.util.Map; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; public class NettyChannelHandler extends ChannelInboundHandlerAdapter { private static final Logger logger = LoggerFactory.getLogger(NettyChannelHandler.class); private final Map<String, Channel> dubboChannels; private final URL url; private final ChannelHandler handler; public NettyChannelHandler(Map<String, Channel> dubboChannels, URL url, ChannelHandler handler) { this.dubboChannels = dubboChannels; this.url = url; this.handler = handler; } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { super.channelActive(ctx); io.netty.channel.Channel ch = ctx.channel(); NettyChannel channel = NettyChannel.getOrAddChannel(ch, url, handler); if (channel != null) { dubboChannels.put(NetUtils.toAddressString((InetSocketAddress) ch.remoteAddress()), channel); handler.connected(channel); if (logger.isInfoEnabled()) { logger.info( "The connection {} of {} -> {} is established.", ch, channel.getRemoteAddressKey(), channel.getLocalAddressKey()); } } } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { super.channelInactive(ctx); io.netty.channel.Channel ch = ctx.channel(); NettyChannel channel = NettyChannel.getOrAddChannel(ch, url, handler); try { dubboChannels.remove(NetUtils.toAddressString((InetSocketAddress) ch.remoteAddress())); if (channel != null) { handler.disconnected(channel); if (logger.isInfoEnabled()) { logger.info( "The connection {} of {} -> {} is disconnected.", ch, channel.getRemoteAddressKey(), channel.getLocalAddressKey()); } } } finally { NettyChannel.removeChannel(ch); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyTransporter.java
dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyTransporter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Client; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.RemotingServer; import org.apache.dubbo.remoting.Transporter; /** * Default extension of {@link Transporter} using netty4.x. */ public class NettyTransporter implements Transporter { public static final String NAME = "netty"; @Override public RemotingServer bind(URL url, ChannelHandler handler) throws RemotingException { return new NettyServer(url, handler); } @Override public Client connect(URL url, ChannelHandler handler) throws RemotingException { return new NettyClient(url, handler); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/AddressUtils.java
dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/AddressUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.rpc.model.FrameworkModel; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.List; import io.netty.channel.Channel; import static org.apache.dubbo.common.utils.NetUtils.toAddressString; public final class AddressUtils { private static final List<ChannelAddressAccessor> ACCESSORS = FrameworkModel.defaultModel().getActivateExtensions(ChannelAddressAccessor.class); private static final String LOCAL_ADDRESS_KEY = "NETTY_LOCAL_ADDRESS_KEY"; private static final String REMOTE_ADDRESS_KEY = "NETTY_REMOTE_ADDRESS_KEY"; private static final String PROTOCOL_KEY = "NETTY_PROTOCOL_KEY"; private AddressUtils() {} public static InetSocketAddress getRemoteAddress(Channel channel) { InetSocketAddress address; for (int i = 0, size = ACCESSORS.size(); i < size; i++) { address = ACCESSORS.get(i).getRemoteAddress(channel); if (address != null) { return address; } } return (InetSocketAddress) channel.remoteAddress(); } public static InetSocketAddress getLocalAddress(Channel channel) { InetSocketAddress address; for (int i = 0, size = ACCESSORS.size(); i < size; i++) { address = ACCESSORS.get(i).getLocalAddress(channel); if (address != null) { return address; } } return (InetSocketAddress) channel.localAddress(); } static void initAddressIfNecessary(NettyChannel nettyChannel) { Channel channel = nettyChannel.getNioChannel(); SocketAddress address = channel.localAddress(); if (address instanceof InetSocketAddress) { return; } for (int i = 0, size = ACCESSORS.size(); i < size; i++) { ChannelAddressAccessor accessor = ACCESSORS.get(i); InetSocketAddress localAddress = accessor.getLocalAddress(channel); if (localAddress != null) { nettyChannel.setAttribute(LOCAL_ADDRESS_KEY, localAddress); nettyChannel.setAttribute(REMOTE_ADDRESS_KEY, accessor.getRemoteAddress(channel)); nettyChannel.setAttribute(PROTOCOL_KEY, accessor.getProtocol()); break; } } } static InetSocketAddress getLocalAddress(NettyChannel channel) { InetSocketAddress address = (InetSocketAddress) channel.getAttribute(LOCAL_ADDRESS_KEY); return address == null ? (InetSocketAddress) (channel.getNioChannel().localAddress()) : address; } static InetSocketAddress getRemoteAddress(NettyChannel channel) { InetSocketAddress address = (InetSocketAddress) channel.getAttribute(REMOTE_ADDRESS_KEY); return address == null ? (InetSocketAddress) (channel.getNioChannel().remoteAddress()) : address; } static String getLocalAddressKey(NettyChannel channel) { InetSocketAddress address = getLocalAddress(channel); if (address == null) { return "UNKNOWN"; } String protocol = (String) channel.getAttribute(PROTOCOL_KEY); return protocol == null ? toAddressString(address) : protocol + ' ' + toAddressString(address); } static String getRemoteAddressKey(NettyChannel channel) { InetSocketAddress address = getRemoteAddress(channel); if (address == null) { return "UNKNOWN"; } String protocol = (String) channel.getAttribute(PROTOCOL_KEY); return protocol == null ? toAddressString(address) : protocol + ' ' + toAddressString(address); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/Netty4BatchWriteQueue.java
dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/Netty4BatchWriteQueue.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.BatchExecutorQueue; import org.apache.dubbo.remoting.exchange.support.MultiMessage; import java.util.LinkedList; import java.util.Queue; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelPromise; import io.netty.channel.EventLoop; /** * netty4 batch write queue */ public class Netty4BatchWriteQueue extends BatchExecutorQueue<Netty4BatchWriteQueue.MessageTuple> { private final Channel channel; private final EventLoop eventLoop; private final Queue<ChannelPromise> promises = new LinkedList<>(); private final MultiMessage multiMessage = MultiMessage.create(); private Netty4BatchWriteQueue(Channel channel) { this.channel = channel; this.eventLoop = channel.eventLoop(); } public ChannelFuture enqueue(Object message) { return enqueue(message, channel.newPromise()); } public ChannelFuture enqueue(Object message, ChannelPromise channelPromise) { MessageTuple messageTuple = new MessageTuple(message, channelPromise); super.enqueue(messageTuple, eventLoop); return messageTuple.channelPromise; } @Override protected void prepare(MessageTuple item) { multiMessage.addMessage(item.originMessage); promises.add(item.channelPromise); } @Override protected void flush(MessageTuple item) { prepare(item); Object finalMessage = multiMessage; if (multiMessage.size() == 1) { finalMessage = multiMessage.get(0); } channel.writeAndFlush(finalMessage).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { ChannelPromise cp; while ((cp = promises.poll()) != null) { if (future.isSuccess()) { cp.setSuccess(); } else { cp.setFailure(future.cause()); } } } }); this.multiMessage.removeMessages(); } public static Netty4BatchWriteQueue createWriteQueue(Channel channel) { return new Netty4BatchWriteQueue(channel); } static class MessageTuple { private final Object originMessage; private final ChannelPromise channelPromise; public MessageTuple(Object originMessage, ChannelPromise channelPromise) { this.originMessage = originMessage; this.channelPromise = channelPromise; } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyChannel.java
dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyChannel.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Codec; import org.apache.dubbo.remoting.Codec2; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.buffer.ChannelBuffer; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.Response; import org.apache.dubbo.remoting.transport.AbstractChannel; import org.apache.dubbo.remoting.transport.codec.CodecAdapter; import org.apache.dubbo.remoting.utils.PayloadDropper; import org.apache.dubbo.rpc.model.FrameworkModel; import java.net.InetSocketAddress; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicBoolean; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.handler.codec.EncoderException; import io.netty.util.ReferenceCountUtil; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_ENCODE_IN_IO_THREAD; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.ENCODE_IN_IO_THREAD_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE; import static org.apache.dubbo.rpc.model.ScopeModelUtil.getFrameworkModel; /** * NettyChannel maintains the cache of channel. */ final class NettyChannel extends AbstractChannel { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(NettyChannel.class); /** * the cache for netty channel and dubbo channel */ private static final ConcurrentMap<Channel, NettyChannel> CHANNEL_MAP = new ConcurrentHashMap<>(); /** * netty channel */ private final Channel channel; private final Map<String, Object> attributes = new ConcurrentHashMap<>(); private final AtomicBoolean active = new AtomicBoolean(false); private final Netty4BatchWriteQueue writeQueue; private final boolean encodeInIOThread; private Codec2 codec; /** * The constructor of NettyChannel. * It is private so NettyChannel usually create by {@link NettyChannel#getOrAddChannel(Channel, URL, ChannelHandler)} * * @param channel netty channel * @param url dubbo url * @param handler dubbo handler that contain netty handler */ private NettyChannel(Channel channel, URL url, ChannelHandler handler) { super(url, handler); if (channel == null) { throw new IllegalArgumentException("netty channel == null;"); } this.channel = channel; this.writeQueue = Netty4BatchWriteQueue.createWriteQueue(channel); this.codec = getChannelCodec(url); this.encodeInIOThread = getUrl().getParameter(ENCODE_IN_IO_THREAD_KEY, DEFAULT_ENCODE_IN_IO_THREAD); AddressUtils.initAddressIfNecessary(this); } /** * Get dubbo channel by netty channel through channel cache. * Put netty channel into it if dubbo channel don't exist in the cache. * * @param ch netty channel * @param url dubbo url * @param handler dubbo handler that contain netty's handler */ static NettyChannel getOrAddChannel(Channel ch, URL url, ChannelHandler handler) { if (ch == null) { return null; } NettyChannel ret = CHANNEL_MAP.get(ch); if (ret == null) { NettyChannel nettyChannel = new NettyChannel(ch, url, handler); if (ch.isActive()) { nettyChannel.markActive(true); ret = CHANNEL_MAP.putIfAbsent(ch, nettyChannel); } if (ret == null) { ret = nettyChannel; } } else { ret.markActive(true); } return ret; } /** * Remove the inactive channel. * * @param ch netty channel */ static void removeChannelIfDisconnected(Channel ch) { if (ch != null && !ch.isActive()) { NettyChannel nettyChannel = CHANNEL_MAP.remove(ch); if (nettyChannel != null) { nettyChannel.markActive(false); } } } static void removeChannel(Channel ch) { if (ch != null) { NettyChannel nettyChannel = CHANNEL_MAP.remove(ch); if (nettyChannel != null) { nettyChannel.markActive(false); } } } @Override public InetSocketAddress getLocalAddress() { return AddressUtils.getLocalAddress(this); } @Override public InetSocketAddress getRemoteAddress() { return AddressUtils.getRemoteAddress(this); } public String getLocalAddressKey() { return AddressUtils.getLocalAddressKey(this); } public String getRemoteAddressKey() { return AddressUtils.getRemoteAddressKey(this); } @Override public boolean isConnected() { return !isClosed() && active.get(); } public boolean isActive() { return active.get(); } public void markActive(boolean isActive) { active.set(isActive); } /** * Send message by netty and whether to wait the completion of the sending. * * @param message message that need send. * @param sent whether to ack async-sent * @throws RemotingException throw RemotingException if wait until timeout or any exception thrown by method body that surrounded by try-catch. */ @Override public void send(Object message, boolean sent) throws RemotingException { // whether the channel is closed super.send(message, sent); boolean success = true; int timeout = 0; ByteBuf buf = null; try { Object outputMessage = message; if (!encodeInIOThread) { buf = channel.alloc().buffer(); ChannelBuffer buffer = new NettyBackedChannelBuffer(buf); codec.encode(this, buffer, message); outputMessage = buf; } ChannelFuture future = writeQueue.enqueue(outputMessage).addListener((ChannelFutureListener) f -> { if (!(message instanceof Request)) { return; } ChannelHandler handler = getChannelHandler(); if (f.isSuccess()) { handler.sent(NettyChannel.this, message); } else { Throwable t = f.cause(); if (t == null) { return; } Response response = buildErrorResponse((Request) message, t); handler.received(NettyChannel.this, response); } }); if (sent) { // wait timeout ms timeout = getUrl().getPositiveParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT); success = future.await(timeout); } Throwable cause = future.cause(); if (cause != null) { throw cause; } } catch (Throwable e) { removeChannelIfDisconnected(channel); if (buf != null) { // Release the ByteBuf if an exception occurs ReferenceCountUtil.safeRelease(buf); } throw new RemotingException( this, "Failed to send message " + PayloadDropper.getRequestWithoutData(message) + " to " + getRemoteAddress() + ", cause: " + e.getMessage(), e); } if (!success) { throw new RemotingException( this, "Failed to send message " + PayloadDropper.getRequestWithoutData(message) + " to " + getRemoteAddress() + "in timeout(" + timeout + "ms) limit"); } } @Override public void close() { try { super.close(); } catch (Exception e) { logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } try { removeChannelIfDisconnected(channel); } catch (Exception e) { logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } try { attributes.clear(); } catch (Exception e) { logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } try { if (logger.isInfoEnabled()) { logger.info("Close netty channel " + channel); } channel.close(); } catch (Exception e) { logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } } @Override public boolean hasAttribute(String key) { return attributes.containsKey(key); } @Override public Object getAttribute(String key) { return attributes.get(key); } @Override public void setAttribute(String key, Object value) { // The null value is not allowed in the ConcurrentHashMap. if (value == null) { attributes.remove(key); } else { attributes.put(key, value); } } @Override public void removeAttribute(String key) { attributes.remove(key); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((channel == null) ? 0 : channel.hashCode()); return result; } @Override protected void setUrl(URL url) { super.setUrl(url); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } // FIXME: a hack to make org.apache.dubbo.remoting.exchange.support.DefaultFuture.closeChannel work if (obj instanceof NettyClient) { NettyClient client = (NettyClient) obj; return channel.equals(client.getNettyChannel()); } return getClass() == obj.getClass() && Objects.equals(channel, ((NettyChannel) obj).channel); } @Override public String toString() { return "NettyChannel [channel=" + channel + "]"; } public Channel getNioChannel() { return channel; } /** * build a bad request's response * * @param request the request * @param t the throwable. In most cases, serialization fails. * @return the response */ private static Response buildErrorResponse(Request request, Throwable t) { Response response = new Response(request.getId(), request.getVersion()); if (t instanceof EncoderException) { response.setStatus(Response.SERIALIZATION_ERROR); } else { response.setStatus(Response.BAD_REQUEST); } response.setErrorMessage(StringUtils.toString(t)); return response; } @SuppressWarnings("deprecation") private static Codec2 getChannelCodec(URL url) { String codecName = url.getParameter(Constants.CODEC_KEY); if (StringUtils.isEmpty(codecName)) { // codec extension name must stay the same with protocol name codecName = url.getProtocol(); } FrameworkModel frameworkModel = getFrameworkModel(url.getScopeModel()); if (frameworkModel.getExtensionLoader(Codec2.class).hasExtension(codecName)) { return frameworkModel.getExtensionLoader(Codec2.class).getExtension(codecName); } else if (frameworkModel.getExtensionLoader(Codec.class).hasExtension(codecName)) { return new CodecAdapter( frameworkModel.getExtensionLoader(Codec.class).getExtension(codecName)); } else { return frameworkModel.getExtensionLoader(Codec2.class).getExtension("default"); } } public void setCodec(Codec2 codec) { this.codec = codec; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/logging/FormattingTuple.java
dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/logging/FormattingTuple.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4.logging; import org.apache.dubbo.common.utils.ArrayUtils; /** * Holds the results of formatting done by {@link MessageFormatter}. */ class FormattingTuple { static final FormattingTuple NULL = new FormattingTuple(null); private final String message; private final Throwable throwable; private final Object[] argArray; FormattingTuple(String message) { this(message, null, null); } FormattingTuple(String message, Object[] argArray, Throwable throwable) { this.message = message; this.throwable = throwable; if (throwable == null) { this.argArray = argArray; } else { this.argArray = trimmedCopy(argArray); } } static Object[] trimmedCopy(Object[] argArray) { if (ArrayUtils.isEmpty(argArray)) { throw new IllegalStateException("non-sensical empty or null argument array"); } final int trimmedLen = argArray.length - 1; Object[] trimmed = new Object[trimmedLen]; System.arraycopy(argArray, 0, trimmed, 0, trimmedLen); return trimmed; } public String getMessage() { return message; } public Object[] getArgArray() { return argArray; } public Throwable getThrowable() { return throwable; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/logging/MessageFormatter.java
dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/logging/MessageFormatter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4.logging; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ArrayUtils; import java.text.MessageFormat; import java.util.HashMap; import java.util.Map; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_UNSUPPORTED_MESSAGE; // contributors: lizongbo: proposed special treatment of array parameter values // Joern Huxhorn: pointed out double[] omission, suggested deep array copy /** * Formats messages according to very simple substitution rules. Substitutions * can be made 1, 2 or more arguments. * <p/> * <p/> * For example, * <p/> * <pre> * MessageFormatter.format(&quot;Hi {}.&quot;, &quot;there&quot;) * </pre> * <p/> * will return the string "Hi there.". * <p/> * The {} pair is called the <em>formatting anchor</em>. It serves to designate * the location where arguments need to be substituted within the message * pattern. * <p/> * In case your message contains the '{' or the '}' character, you do not have * to do anything special unless the '}' character immediately follows '{'. For * example, * <p/> * <pre> * MessageFormatter.format(&quot;Set {1,2,3} is not equal to {}.&quot;, &quot;1,2&quot;); * </pre> * <p/> * will return the string "Set {1,2,3} is not equal to 1,2.". * <p/> * <p/> * If for whatever reason you need to place the string "{}" in the message * without its <em>formatting anchor</em> meaning, then you need to escape the * '{' character with '\', that is the backslash character. Only the '{' * character should be escaped. There is no need to escape the '}' character. * For example, * <p/> * <pre> * MessageFormatter.format(&quot;Set \\{} is not equal to {}.&quot;, &quot;1,2&quot;); * </pre> * <p/> * will return the string "Set {} is not equal to 1,2.". * <p/> * <p/> * The escaping behavior just described can be overridden by escaping the escape * character '\'. Calling * <p/> * <pre> * MessageFormatter.format(&quot;File name is C:\\\\{}.&quot;, &quot;file.zip&quot;); * </pre> * <p/> * will return the string "File name is C:\file.zip". * <p/> * <p/> * The formatting conventions are different than those of {@link MessageFormat} * which ships with the Java platform. This is justified by the fact that * SLF4J's implementation is 10 times faster than that of {@link MessageFormat}. * This local performance difference is both measurable and significant in the * larger context of the complete logging processing chain. * <p/> * <p/> * See also {@link #format(String, Object)}, * {@link #format(String, Object, Object)} and * {@link #arrayFormat(String, Object[])} methods for more details. */ final class MessageFormatter { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MessageFormatter.class); static final char DELIM_START = '{'; static final char DELIM_STOP = '}'; static final String DELIM_STR = "{}"; private static final char ESCAPE_CHAR = '\\'; /** * Performs single argument substitution for the 'messagePattern' passed as * parameter. * <p/> * For example, * <p/> * <pre> * MessageFormatter.format(&quot;Hi {}.&quot;, &quot;there&quot;); * </pre> * <p/> * will return the string "Hi there.". * <p/> * * @param messagePattern The message pattern which will be parsed and formatted * @param arg The argument to be substituted in place of the formatting anchor * @return The formatted message */ static FormattingTuple format(String messagePattern, Object arg) { return arrayFormat(messagePattern, new Object[] {arg}); } /** * Performs a two argument substitution for the 'messagePattern' passed as * parameter. * <p/> * For example, * <p/> * <pre> * MessageFormatter.format(&quot;Hi {}. My name is {}.&quot;, &quot;Alice&quot;, &quot;Bob&quot;); * </pre> * <p/> * will return the string "Hi Alice. My name is Bob.". * * @param messagePattern The message pattern which will be parsed and formatted * @param argA The argument to be substituted in place of the first formatting * anchor * @param argB The argument to be substituted in place of the second formatting * anchor * @return The formatted message */ static FormattingTuple format(final String messagePattern, Object argA, Object argB) { return arrayFormat(messagePattern, new Object[] {argA, argB}); } static Throwable getThrowableCandidate(Object[] argArray) { if (ArrayUtils.isEmpty(argArray)) { return null; } final Object lastEntry = argArray[argArray.length - 1]; if (lastEntry instanceof Throwable) { return (Throwable) lastEntry; } return null; } /** * Same principle as the {@link #format(String, Object)} and * {@link #format(String, Object, Object)} methods except that any number of * arguments can be passed in an array. * * @param messagePattern The message pattern which will be parsed and formatted * @param argArray An array of arguments to be substituted in place of formatting * anchors * @return The formatted message */ static FormattingTuple arrayFormat(final String messagePattern, final Object[] argArray) { Throwable throwableCandidate = getThrowableCandidate(argArray); if (messagePattern == null) { return new FormattingTuple(null, argArray, throwableCandidate); } if (argArray == null) { return new FormattingTuple(messagePattern); } int i = 0; int j; StringBuffer sbuf = new StringBuffer(messagePattern.length() + 50); int l; for (l = 0; l < argArray.length; l++) { j = messagePattern.indexOf(DELIM_STR, i); if (j == -1) { // no more variables if (i == 0) { // this is a simple string return new FormattingTuple(messagePattern, argArray, throwableCandidate); } else { // add the tail string which contains no variables and return // the result. sbuf.append(messagePattern.substring(i)); return new FormattingTuple(sbuf.toString(), argArray, throwableCandidate); } } else { if (isEscapedDelimeter(messagePattern, j)) { if (!isDoubleEscaped(messagePattern, j)) { l--; // DELIM_START was escaped, thus should not be incremented sbuf.append(messagePattern, i, j - 1); sbuf.append(DELIM_START); i = j + 1; } else { // The escape character preceding the delimiter start is // itself escaped: "abc x:\\{}" // we have to consume one backward slash sbuf.append(messagePattern, i, j - 1); deeplyAppendParameter(sbuf, argArray[l], new HashMap<Object[], Void>()); i = j + 2; } } else { // normal case sbuf.append(messagePattern, i, j); deeplyAppendParameter(sbuf, argArray[l], new HashMap<Object[], Void>()); i = j + 2; } } } // append the characters following the last {} pair. sbuf.append(messagePattern.substring(i)); if (l < argArray.length - 1) { return new FormattingTuple(sbuf.toString(), argArray, throwableCandidate); } else { return new FormattingTuple(sbuf.toString(), argArray, null); } } static boolean isEscapedDelimeter(String messagePattern, int delimeterStartIndex) { if (delimeterStartIndex == 0) { return false; } return messagePattern.charAt(delimeterStartIndex - 1) == ESCAPE_CHAR; } static boolean isDoubleEscaped(String messagePattern, int delimeterStartIndex) { return delimeterStartIndex >= 2 && messagePattern.charAt(delimeterStartIndex - 2) == ESCAPE_CHAR; } // special treatment of array values was suggested by 'lizongbo' private static void deeplyAppendParameter(StringBuffer sbuf, Object o, Map<Object[], Void> seenMap) { if (o == null) { sbuf.append("null"); return; } if (!o.getClass().isArray()) { safeObjectAppend(sbuf, o); } else { // check for primitive array types because they // unfortunately cannot be cast to Object[] if (o instanceof boolean[]) { booleanArrayAppend(sbuf, (boolean[]) o); } else if (o instanceof byte[]) { byteArrayAppend(sbuf, (byte[]) o); } else if (o instanceof char[]) { charArrayAppend(sbuf, (char[]) o); } else if (o instanceof short[]) { shortArrayAppend(sbuf, (short[]) o); } else if (o instanceof int[]) { intArrayAppend(sbuf, (int[]) o); } else if (o instanceof long[]) { longArrayAppend(sbuf, (long[]) o); } else if (o instanceof float[]) { floatArrayAppend(sbuf, (float[]) o); } else if (o instanceof double[]) { doubleArrayAppend(sbuf, (double[]) o); } else { objectArrayAppend(sbuf, (Object[]) o, seenMap); } } } private static void safeObjectAppend(StringBuffer sbuf, Object o) { try { String oAsString = o.toString(); sbuf.append(oAsString); } catch (Throwable t) { System.err.println("SLF4J: Failed toString() invocation on an object of type [" + o.getClass().getName() + ']'); logger.error(TRANSPORT_UNSUPPORTED_MESSAGE, "", "", t.getMessage(), t); sbuf.append("[FAILED toString()]"); } } private static void objectArrayAppend(StringBuffer sbuf, Object[] a, Map<Object[], Void> seenMap) { sbuf.append('['); if (!seenMap.containsKey(a)) { seenMap.put(a, null); final int len = a.length; for (int i = 0; i < len; i++) { deeplyAppendParameter(sbuf, a[i], seenMap); if (i != len - 1) { sbuf.append(", "); } } // allow repeats in siblings seenMap.remove(a); } else { sbuf.append("..."); } sbuf.append(']'); } private static void booleanArrayAppend(StringBuffer sbuf, boolean[] a) { sbuf.append('['); final int len = a.length; for (int i = 0; i < len; i++) { sbuf.append(a[i]); if (i != len - 1) { sbuf.append(", "); } } sbuf.append(']'); } private static void byteArrayAppend(StringBuffer sbuf, byte[] a) { sbuf.append('['); final int len = a.length; for (int i = 0; i < len; i++) { sbuf.append(a[i]); if (i != len - 1) { sbuf.append(", "); } } sbuf.append(']'); } private static void charArrayAppend(StringBuffer sbuf, char[] a) { sbuf.append('['); final int len = a.length; for (int i = 0; i < len; i++) { sbuf.append(a[i]); if (i != len - 1) { sbuf.append(", "); } } sbuf.append(']'); } private static void shortArrayAppend(StringBuffer sbuf, short[] a) { sbuf.append('['); final int len = a.length; for (int i = 0; i < len; i++) { sbuf.append(a[i]); if (i != len - 1) { sbuf.append(", "); } } sbuf.append(']'); } private static void intArrayAppend(StringBuffer sbuf, int[] a) { sbuf.append('['); final int len = a.length; for (int i = 0; i < len; i++) { sbuf.append(a[i]); if (i != len - 1) { sbuf.append(", "); } } sbuf.append(']'); } private static void longArrayAppend(StringBuffer sbuf, long[] a) { sbuf.append('['); final int len = a.length; for (int i = 0; i < len; i++) { sbuf.append(a[i]); if (i != len - 1) { sbuf.append(", "); } } sbuf.append(']'); } private static void floatArrayAppend(StringBuffer sbuf, float[] a) { sbuf.append('['); final int len = a.length; for (int i = 0; i < len; i++) { sbuf.append(a[i]); if (i != len - 1) { sbuf.append(", "); } } sbuf.append(']'); } private static void doubleArrayAppend(StringBuffer sbuf, double[] a) { sbuf.append('['); final int len = a.length; for (int i = 0; i < len; i++) { sbuf.append(a[i]); if (i != len - 1) { sbuf.append(", "); } } sbuf.append(']'); } private MessageFormatter() {} }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/http2/Http2ClientSettingsHandler.java
dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/http2/Http2ClientSettingsHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4.http2; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import java.util.concurrent.atomic.AtomicReference; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http2.Http2SettingsFrame; import io.netty.util.concurrent.Promise; public class Http2ClientSettingsHandler extends SimpleChannelInboundHandler<Http2SettingsFrame> { private static final Logger logger = LoggerFactory.getLogger(Http2ClientSettingsHandler.class); private final AtomicReference<Promise<Void>> connectionPrefaceReceivedPromiseRef; public Http2ClientSettingsHandler(AtomicReference<Promise<Void>> connectionPrefaceReceivedPromiseRef) { this.connectionPrefaceReceivedPromiseRef = connectionPrefaceReceivedPromiseRef; } @Override protected void channelRead0(ChannelHandlerContext ctx, Http2SettingsFrame msg) throws Exception { if (logger.isDebugEnabled()) { logger.debug("Receive server Http2 Settings frame of " + ctx.channel().localAddress() + " -> " + ctx.channel().remoteAddress()); } // connectionPrefaceReceivedPromise will be set null after first used. Promise<Void> connectionPrefaceReceivedPromise = connectionPrefaceReceivedPromiseRef.get(); if (connectionPrefaceReceivedPromise == null) { ctx.fireChannelRead(msg); } else { // Notify the connection preface is received when first inbound http2 settings frame is arrived. connectionPrefaceReceivedPromise.trySuccess(null); ctx.pipeline().remove(this); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/aot/Netty4ReflectionTypeDescriberRegistrar.java
dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/aot/Netty4ReflectionTypeDescriberRegistrar.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4.aot; import org.apache.dubbo.aot.api.MemberCategory; import org.apache.dubbo.aot.api.ReflectionTypeDescriberRegistrar; import org.apache.dubbo.aot.api.TypeDescriber; import org.apache.dubbo.remoting.transport.netty4.NettyChannelHandler; import org.apache.dubbo.remoting.transport.netty4.NettyClientHandler; import org.apache.dubbo.remoting.transport.netty4.NettyConnectionHandler; import org.apache.dubbo.remoting.transport.netty4.NettyPortUnificationServerHandler; import org.apache.dubbo.remoting.transport.netty4.NettyServerHandler; import org.apache.dubbo.remoting.transport.netty4.ssl.SslClientTlsHandler; import org.apache.dubbo.remoting.transport.netty4.ssl.SslServerTlsHandler; import java.nio.channels.spi.SelectorProvider; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class Netty4ReflectionTypeDescriberRegistrar implements ReflectionTypeDescriberRegistrar { @Override public List<TypeDescriber> getTypeDescribers() { List<TypeDescriber> typeDescribers = new ArrayList<>(); typeDescribers.add(buildTypeDescriberWithPublicMethod(NettyServerHandler.class)); typeDescribers.add(buildTypeDescriberWithPublicMethod(SslServerTlsHandler.class)); typeDescribers.add(buildTypeDescriberWithPublicMethod(NettyClientHandler.class)); typeDescribers.add(buildTypeDescriberWithPublicMethod(SslClientTlsHandler.class)); typeDescribers.add(buildTypeDescriberWithPublicMethod(SelectorProvider.class)); typeDescribers.add(buildTypeDescriberWithPublicMethod(NettyPortUnificationServerHandler.class)); typeDescribers.add(buildTypeDescriberWithPublicMethod(NettyChannelHandler.class)); typeDescribers.add(buildTypeDescriberWithPublicMethod(NettyConnectionHandler.class)); return typeDescribers; } private TypeDescriber buildTypeDescriberWithPublicMethod(Class<?> cl) { Set<MemberCategory> memberCategories = new HashSet<>(); memberCategories.add(MemberCategory.INVOKE_PUBLIC_METHODS); return new TypeDescriber( cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/ssl/SslContexts.java
dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/ssl/SslContexts.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4.ssl; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.ssl.AuthPolicy; import org.apache.dubbo.common.ssl.Cert; import org.apache.dubbo.common.ssl.CertManager; import org.apache.dubbo.common.ssl.ProviderCert; import javax.net.ssl.SSLException; import java.io.IOException; import java.io.InputStream; import java.security.Provider; import java.security.Security; import io.netty.handler.codec.http2.Http2SecurityUtil; import io.netty.handler.ssl.ApplicationProtocolConfig; import io.netty.handler.ssl.ApplicationProtocolNames; import io.netty.handler.ssl.ClientAuth; import io.netty.handler.ssl.OpenSsl; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.SslProvider; import io.netty.handler.ssl.SupportedCipherSuiteFilter; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE_STREAM; public class SslContexts { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(SslContexts.class); public static SslContext buildServerSslContext(ProviderCert providerConnectionConfig) { SslContextBuilder sslClientContextBuilder; InputStream serverKeyCertChainPathStream = null; InputStream serverPrivateKeyPathStream = null; InputStream serverTrustCertStream = null; try { serverKeyCertChainPathStream = providerConnectionConfig.getKeyCertChainInputStream(); serverPrivateKeyPathStream = providerConnectionConfig.getPrivateKeyInputStream(); serverTrustCertStream = providerConnectionConfig.getTrustCertInputStream(); String password = providerConnectionConfig.getPassword(); if (password != null) { sslClientContextBuilder = SslContextBuilder.forServer(serverKeyCertChainPathStream, serverPrivateKeyPathStream, password); } else { sslClientContextBuilder = SslContextBuilder.forServer(serverKeyCertChainPathStream, serverPrivateKeyPathStream); } if (serverTrustCertStream != null) { sslClientContextBuilder.trustManager(serverTrustCertStream); if (providerConnectionConfig.getAuthPolicy() == AuthPolicy.CLIENT_AUTH) { sslClientContextBuilder.clientAuth(ClientAuth.REQUIRE); } else { sslClientContextBuilder.clientAuth(ClientAuth.OPTIONAL); } } } catch (Exception e) { throw new IllegalArgumentException("Could not find certificate file or the certificate is invalid.", e); } finally { safeCloseStream(serverTrustCertStream); safeCloseStream(serverKeyCertChainPathStream); safeCloseStream(serverPrivateKeyPathStream); } try { return sslClientContextBuilder .sslProvider(findSslProvider()) .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) .applicationProtocolConfig(new ApplicationProtocolConfig( ApplicationProtocolConfig.Protocol.ALPN, ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE, ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1)) .build(); } catch (SSLException e) { throw new IllegalStateException("Build SslSession failed.", e); } } public static SslContext buildClientSslContext(URL url) { CertManager certManager = url.getOrDefaultFrameworkModel().getBeanFactory().getBean(CertManager.class); Cert consumerConnectionConfig = certManager.getConsumerConnectionConfig(url); if (consumerConnectionConfig == null) { return null; } SslContextBuilder builder = SslContextBuilder.forClient(); InputStream clientTrustCertCollectionPath = null; InputStream clientCertChainFilePath = null; InputStream clientPrivateKeyFilePath = null; try { clientTrustCertCollectionPath = consumerConnectionConfig.getTrustCertInputStream(); if (clientTrustCertCollectionPath != null) { builder.trustManager(clientTrustCertCollectionPath); } clientCertChainFilePath = consumerConnectionConfig.getKeyCertChainInputStream(); clientPrivateKeyFilePath = consumerConnectionConfig.getPrivateKeyInputStream(); if (clientCertChainFilePath != null && clientPrivateKeyFilePath != null) { String password = consumerConnectionConfig.getPassword(); if (password != null) { builder.keyManager(clientCertChainFilePath, clientPrivateKeyFilePath, password); } else { builder.keyManager(clientCertChainFilePath, clientPrivateKeyFilePath); } } } catch (Exception e) { throw new IllegalArgumentException("Could not find certificate file or find invalid certificate.", e); } finally { safeCloseStream(clientTrustCertCollectionPath); safeCloseStream(clientCertChainFilePath); safeCloseStream(clientPrivateKeyFilePath); } try { return builder.sslProvider(findSslProvider()).build(); } catch (SSLException e) { throw new IllegalStateException("Build SslSession failed.", e); } } /** * Returns OpenSSL if available, otherwise returns the JDK provider. */ private static SslProvider findSslProvider() { if (OpenSsl.isAvailable()) { logger.debug("Using OPENSSL provider."); return SslProvider.OPENSSL; } if (checkJdkProvider()) { logger.debug("Using JDK provider."); return SslProvider.JDK; } throw new IllegalStateException( "Could not find any valid TLS provider, please check your dependency or deployment environment, " + "usually netty-tcnative, Conscrypt, or Jetty NPN/ALPN is needed."); } private static boolean checkJdkProvider() { Provider[] jdkProviders = Security.getProviders("SSLContext.TLS"); return (jdkProviders != null && jdkProviders.length > 0); } private static void safeCloseStream(InputStream stream) { if (stream == null) { return; } try { stream.close(); } catch (IOException e) { logger.warn(TRANSPORT_FAILED_CLOSE_STREAM, "", "", "Failed to close a stream.", e); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/ssl/SslClientTlsHandler.java
dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/ssl/SslClientTlsHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4.ssl; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.Constants; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLSession; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslHandler; import io.netty.handler.ssl.SslHandshakeCompletionEvent; import io.netty.util.AttributeKey; import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR; public class SslClientTlsHandler extends ChannelInboundHandlerAdapter { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(SslClientTlsHandler.class); private static final AttributeKey<SSLSession> SSL_SESSION_KEY = AttributeKey.valueOf(Constants.SSL_SESSION_KEY); private final SslContext sslContext; public SslClientTlsHandler(URL url) { this(SslContexts.buildClientSslContext(url)); } public SslClientTlsHandler(SslContext sslContext) { this.sslContext = sslContext; } @Override public void handlerAdded(ChannelHandlerContext ctx) { SSLEngine sslEngine = sslContext.newEngine(ctx.alloc()); ctx.pipeline().addAfter(ctx.name(), null, new SslHandler(sslEngine, false)); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof SslHandshakeCompletionEvent) { SslHandshakeCompletionEvent handshakeEvent = (SslHandshakeCompletionEvent) evt; if (handshakeEvent.isSuccess()) { SSLSession session = ctx.pipeline().get(SslHandler.class).engine().getSession(); logger.info("TLS negotiation succeed with: " + session.getPeerHost()); ctx.pipeline().remove(this); ctx.channel().attr(SSL_SESSION_KEY).set(session); } else { logger.error( INTERNAL_ERROR, "unknown error in remoting module", "", "TLS negotiation failed when trying to accept new connection.", handshakeEvent.cause()); ctx.fireExceptionCaught(handshakeEvent.cause()); } } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/ssl/SslServerTlsHandler.java
dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/ssl/SslServerTlsHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.remoting.transport.netty4.ssl; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.ssl.AuthPolicy; import org.apache.dubbo.common.ssl.CertManager; import org.apache.dubbo.common.ssl.ProviderCert; import org.apache.dubbo.remoting.Constants; import javax.net.ssl.SSLSession; import java.util.List; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPipeline; import io.netty.handler.codec.ByteToMessageDecoder; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslHandler; import io.netty.handler.ssl.SslHandshakeCompletionEvent; import io.netty.util.AttributeKey; import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR; public class SslServerTlsHandler extends ByteToMessageDecoder { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(SslServerTlsHandler.class); private final URL url; private final boolean sslDetected; private static final AttributeKey<SSLSession> SSL_SESSION_KEY = AttributeKey.valueOf(Constants.SSL_SESSION_KEY); public SslServerTlsHandler(URL url) { this.url = url; this.sslDetected = false; } public SslServerTlsHandler(URL url, boolean sslDetected) { this.url = url; this.sslDetected = sslDetected; } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { logger.error( INTERNAL_ERROR, "unknown error in remoting module", "", "TLS negotiation failed when trying to accept new connection.", cause); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof SslHandshakeCompletionEvent) { SslHandshakeCompletionEvent handshakeEvent = (SslHandshakeCompletionEvent) evt; if (handshakeEvent.isSuccess()) { SSLSession session = ctx.pipeline().get(SslHandler.class).engine().getSession(); logger.info("TLS negotiation succeed with: " + session.getPeerHost()); // Remove after handshake success. ctx.pipeline().remove(this); ctx.channel().attr(SSL_SESSION_KEY).set(session); } else { logger.error( INTERNAL_ERROR, "", "", "TLS negotiation failed when trying to accept new connection.", handshakeEvent.cause()); ctx.close(); } } super.userEventTriggered(ctx, evt); } @Override protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception { // Will use the first five bytes to detect a protocol. if (byteBuf.readableBytes() < 5) { return; } if (sslDetected) { return; } CertManager certManager = url.getOrDefaultFrameworkModel().getBeanFactory().getBean(CertManager.class); ProviderCert providerConnectionConfig = certManager.getProviderConnectionConfig( url, channelHandlerContext.channel().remoteAddress()); if (providerConnectionConfig == null) { channelHandlerContext.pipeline().remove(this); return; } if (isSsl(byteBuf)) { SslContext sslContext = SslContexts.buildServerSslContext(providerConnectionConfig); enableSsl(channelHandlerContext, sslContext); return; } if (providerConnectionConfig.getAuthPolicy() == AuthPolicy.NONE) { channelHandlerContext.pipeline().remove(this); return; } logger.error(INTERNAL_ERROR, "", "", "TLS negotiation failed when trying to accept new connection."); channelHandlerContext.close(); } private boolean isSsl(ByteBuf buf) { return SslHandler.isEncrypted(buf); } private void enableSsl(ChannelHandlerContext ctx, SslContext sslContext) { ChannelPipeline p = ctx.pipeline(); ctx.pipeline().addAfter(ctx.name(), null, sslContext.newHandler(ctx.alloc())); p.addLast("unificationA", new SslServerTlsHandler(url, true)); p.remove(this); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-multicast/src/test/java/org/apache/dubbo/registry/multicast/MulticastRegistryFactoryTest.java
dubbo-registry/dubbo-registry-multicast/src/test/java/org/apache/dubbo/registry/multicast/MulticastRegistryFactoryTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.multicast; import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.Registry; import org.junit.jupiter.api.Test; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; class MulticastRegistryFactoryTest { @Test void shouldCreateRegistry() { Registry registry = new MulticastRegistryFactory().createRegistry(URL.valueOf("multicast://239.255.255.255/")); assertThat(registry, not(nullValue())); assertThat(registry.isAvailable(), is(true)); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-multicast/src/test/java/org/apache/dubbo/registry/multicast/MulticastRegistryTest.java
dubbo-registry/dubbo-registry-multicast/src/test/java/org/apache/dubbo/registry/multicast/MulticastRegistryTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.multicast; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.registry.NotifyListener; import java.net.InetAddress; import java.net.MulticastSocket; import java.net.UnknownHostException; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; class MulticastRegistryTest { private String service = "org.apache.dubbo.test.injvmServie"; private URL registryUrl = URL.valueOf("multicast://239.239.239.239/"); private URL serviceUrl = URL.valueOf("dubbo://" + NetUtils.getLocalHost() + "/" + service + "?methods=test1,test2"); private URL adminUrl = URL.valueOf("dubbo://" + NetUtils.getLocalHost() + "/*"); private URL consumerUrl = URL.valueOf("subscribe://" + NetUtils.getLocalHost() + "/" + service + "?arg1=1&arg2=2"); private MulticastRegistry registry = new MulticastRegistry(registryUrl); @BeforeEach void setUp() { registry.register(serviceUrl); } /** * Test method for {@link org.apache.dubbo.registry.multicast.MulticastRegistry#MulticastRegistry(URL)}. */ @Test void testUrlError() { Assertions.assertThrows(UnknownHostException.class, () -> { try { URL errorUrl = URL.valueOf("multicast://mullticast.local/"); new MulticastRegistry(errorUrl); } catch (IllegalStateException e) { throw e.getCause(); } }); } /** * Test method for {@link org.apache.dubbo.registry.multicast.MulticastRegistry#MulticastRegistry(URL)}. */ @Test void testAnyHost() { Assertions.assertThrows(IllegalStateException.class, () -> { URL errorUrl = URL.valueOf("multicast://0.0.0.0/"); new MulticastRegistry(errorUrl); }); } /** * Test method for {@link org.apache.dubbo.registry.multicast.MulticastRegistry#MulticastRegistry(URL)}. */ @Test void testGetCustomPort() { int port = NetUtils.getAvailablePort(20880 + new Random().nextInt(10000)); URL customPortUrl = URL.valueOf("multicast://239.239.239.239:" + port); MulticastRegistry multicastRegistry = new MulticastRegistry(customPortUrl); assertThat(multicastRegistry.getUrl().getPort(), is(port)); } /** * Test method for {@link org.apache.dubbo.registry.multicast.MulticastRegistry#getRegistered()}. */ @Test void testRegister() { Set<URL> registered; // clear first registered = registry.getRegistered(); for (URL url : registered) { registry.unregister(url); } for (int i = 0; i < 2; i++) { registry.register(serviceUrl); registered = registry.getRegistered(); assertTrue(registered.contains(serviceUrl)); } // confirm only 1 register success registered = registry.getRegistered(); assertEquals(1, registered.size()); } /** * Test method for {@link org.apache.dubbo.registry.multicast.MulticastRegistry#unregister(URL)}. */ @Test void testUnregister() { Set<URL> registered; // register first registry.register(serviceUrl); registered = registry.getRegistered(); assertTrue(registered.contains(serviceUrl)); // then unregister registered = registry.getRegistered(); registry.unregister(serviceUrl); assertFalse(registered.contains(serviceUrl)); } /** * Test method for * {@link org.apache.dubbo.registry.multicast.MulticastRegistry#subscribe(URL url, org.apache.dubbo.registry.NotifyListener)} * . */ @Test void testSubscribe() { // verify listener final URL[] notifyUrl = new URL[1]; for (int i = 0; i < 10; i++) { registry.register(serviceUrl); registry.subscribe(consumerUrl, urls -> { notifyUrl[0] = urls.get(0); Map<URL, Set<NotifyListener>> subscribed = registry.getSubscribed(); assertEquals(consumerUrl, subscribed.keySet().iterator().next()); }); if (!EMPTY_PROTOCOL.equalsIgnoreCase(notifyUrl[0].getProtocol())) { break; } } assertEquals(serviceUrl.toFullString(), notifyUrl[0].toFullString()); } /** * Test method for {@link org.apache.dubbo.registry.multicast.MulticastRegistry#unsubscribe(URL, NotifyListener)} */ @Test void testUnsubscribe() { // subscribe first registry.subscribe(consumerUrl, new NotifyListener() { @Override public void notify(List<URL> urls) { // do nothing } }); // then unsubscribe registry.unsubscribe(consumerUrl, new NotifyListener() { @Override public void notify(List<URL> urls) { Map<URL, Set<NotifyListener>> subscribed = registry.getSubscribed(); Set<NotifyListener> listeners = subscribed.get(consumerUrl); assertTrue(listeners.isEmpty()); Map<URL, Set<URL>> received = registry.getReceived(); assertTrue(received.get(consumerUrl).isEmpty()); } }); } /** * Test method for {@link MulticastRegistry#isAvailable()} */ @Test void testAvailability() { int port = NetUtils.getAvailablePort(20880 + new Random().nextInt(10000)); MulticastRegistry registry = new MulticastRegistry(URL.valueOf("multicast://224.5.6.8:" + port)); assertTrue(registry.isAvailable()); } /** * Test method for {@link MulticastRegistry#destroy()} */ @Test void testDestroy() { MulticastSocket socket = registry.getMulticastSocket(); assertFalse(socket.isClosed()); // then destroy, the multicast socket will be closed registry.destroy(); socket = registry.getMulticastSocket(); assertTrue(socket.isClosed()); } /** * Test method for {@link org.apache.dubbo.registry.multicast.MulticastRegistry#MulticastRegistry(URL)} */ @Test void testDefaultPort() { MulticastRegistry multicastRegistry = new MulticastRegistry(URL.valueOf("multicast://224.5.6.7")); try { MulticastSocket multicastSocket = multicastRegistry.getMulticastSocket(); Assertions.assertEquals(1234, multicastSocket.getLocalPort()); } finally { multicastRegistry.destroy(); } } /** * Test method for {@link org.apache.dubbo.registry.multicast.MulticastRegistry#MulticastRegistry(URL)} */ @Test void testCustomedPort() { int port = NetUtils.getAvailablePort(20880 + new Random().nextInt(10000)); MulticastRegistry multicastRegistry = new MulticastRegistry(URL.valueOf("multicast://224.5.6.7:" + port)); try { MulticastSocket multicastSocket = multicastRegistry.getMulticastSocket(); assertEquals(port, multicastSocket.getLocalPort()); } finally { multicastRegistry.destroy(); } } @Test void testMulticastAddress() { InetAddress multicastAddress = null; MulticastSocket multicastSocket = null; try { // ipv4 multicast address multicastAddress = InetAddress.getByName("224.55.66.77"); multicastSocket = new MulticastSocket(2345); multicastSocket.setLoopbackMode(false); NetUtils.setInterface(multicastSocket, false); multicastSocket.joinGroup(multicastAddress); } catch (Exception e) { Assertions.fail(e); } finally { if (multicastSocket != null) { multicastSocket.close(); } } // multicast ipv6 address, try { multicastAddress = InetAddress.getByName("ff01::1"); multicastSocket = new MulticastSocket(); multicastSocket.setLoopbackMode(false); NetUtils.setInterface(multicastSocket, true); multicastSocket.joinGroup(multicastAddress); } catch (Throwable t) { t.printStackTrace(); } finally { if (multicastSocket != null) { multicastSocket.close(); } } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistry.java
dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistry.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.multicast; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.common.utils.ExecutorUtil; import org.apache.dubbo.common.utils.NamedThreadFactory; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.UrlUtils; import org.apache.dubbo.registry.NotifyListener; import org.apache.dubbo.registry.support.FailbackRegistry; import org.apache.dubbo.rpc.model.ApplicationModel; import java.io.IOException; import java.net.DatagramPacket; import java.net.Inet4Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.MulticastSocket; import java.net.Socket; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_SOCKET_EXCEPTION; import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.OVERRIDE_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.ROUTE_PROTOCOL; import static org.apache.dubbo.registry.Constants.CONSUMER_PROTOCOL; import static org.apache.dubbo.registry.Constants.DEFAULT_SESSION_TIMEOUT; import static org.apache.dubbo.registry.Constants.REGISTER; import static org.apache.dubbo.registry.Constants.REGISTER_KEY; import static org.apache.dubbo.registry.Constants.SESSION_TIMEOUT_KEY; import static org.apache.dubbo.registry.Constants.SUBSCRIBE; import static org.apache.dubbo.registry.Constants.UNREGISTER; import static org.apache.dubbo.registry.Constants.UNSUBSCRIBE; public class MulticastRegistry extends FailbackRegistry { // logging output private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MulticastRegistry.class); private static final int DEFAULT_MULTICAST_PORT = 1234; private final InetAddress multicastAddress; private final MulticastSocket multicastSocket; private final int multicastPort; private final ConcurrentMap<URL, Set<URL>> received = new ConcurrentHashMap<>(); private final ScheduledExecutorService cleanExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("DubboMulticastRegistryCleanTimer", true)); private final ScheduledFuture<?> cleanFuture; private final int cleanPeriod; private final ApplicationModel applicationModel; private volatile boolean admin = false; public MulticastRegistry(URL url, ApplicationModel applicationModel) { super(url); this.applicationModel = applicationModel; if (url.isAnyHost()) { throw new IllegalStateException("registry address == null"); } try { multicastAddress = InetAddress.getByName(url.getHost()); checkMulticastAddress(multicastAddress); multicastPort = url.getPort() <= 0 ? DEFAULT_MULTICAST_PORT : url.getPort(); multicastSocket = new MulticastSocket(multicastPort); NetUtils.joinMulticastGroup(multicastSocket, multicastAddress); Thread thread = new Thread( () -> { byte[] buf = new byte[2048]; DatagramPacket recv = new DatagramPacket(buf, buf.length); while (!multicastSocket.isClosed()) { try { multicastSocket.receive(recv); String msg = new String(recv.getData()).trim(); int i = msg.indexOf('\n'); if (i > 0) { msg = msg.substring(0, i).trim(); } receive(msg, (InetSocketAddress) recv.getSocketAddress()); Arrays.fill(buf, (byte) 0); } catch (Throwable e) { if (!multicastSocket.isClosed()) { logger.error(REGISTRY_SOCKET_EXCEPTION, "", "", e.getMessage(), e); } } } }, "DubboMulticastRegistryReceiver"); thread.setDaemon(true); thread.start(); } catch (IOException e) { throw new IllegalStateException(e.getMessage(), e); } this.cleanPeriod = url.getParameter(SESSION_TIMEOUT_KEY, DEFAULT_SESSION_TIMEOUT); if (url.getParameter("clean", true)) { this.cleanFuture = cleanExecutor.scheduleWithFixedDelay( () -> { try { clean(); // Remove the expired } catch (Throwable t) { // Defensive fault tolerance logger.error( REGISTRY_SOCKET_EXCEPTION, "", "", "Unexpected exception occur at clean expired provider, cause: " + t.getMessage(), t); } }, cleanPeriod, cleanPeriod, TimeUnit.MILLISECONDS); } else { this.cleanFuture = null; } } public MulticastRegistry(URL url) { this(url, url.getOrDefaultApplicationModel()); } private void checkMulticastAddress(InetAddress multicastAddress) { if (!multicastAddress.isMulticastAddress()) { String message = "Invalid multicast address " + multicastAddress; if (multicastAddress instanceof Inet4Address) { throw new IllegalArgumentException( message + ", " + "ipv4 multicast address scope: 224.0.0.0 - 239.255.255.255."); } else { throw new IllegalArgumentException( message + ", " + "ipv6 multicast address must start with ff, " + "for example: ff01::1"); } } } /** * Remove the expired providers, only when "clean" parameter is true. */ private void clean() { if (admin) { for (Set<URL> providers : new HashSet<Set<URL>>(received.values())) { for (URL url : new HashSet<URL>(providers)) { if (isExpired(url)) { if (logger.isWarnEnabled()) { logger.warn(REGISTRY_SOCKET_EXCEPTION, "", "", "Clean expired provider " + url); } doUnregister(url); } } } } } private boolean isExpired(URL url) { if (!url.getParameter(DYNAMIC_KEY, true) || url.getPort() <= 0 || CONSUMER_PROTOCOL.equals(url.getProtocol()) || ROUTE_PROTOCOL.equals(url.getProtocol()) || OVERRIDE_PROTOCOL.equals(url.getProtocol())) { return false; } try (Socket socket = new Socket(url.getHost(), url.getPort())) { } catch (Throwable e) { try { Thread.sleep(100); } catch (Throwable e2) { } try (Socket socket2 = new Socket(url.getHost(), url.getPort())) { } catch (Throwable e2) { return true; } } return false; } private void receive(String msg, InetSocketAddress remoteAddress) { if (logger.isInfoEnabled()) { logger.info("Receive multicast message: " + msg + " from " + remoteAddress); } if (applicationModel.isDestroyed()) { logger.info("The applicationModel is destroyed, skip"); return; } if (msg.startsWith(REGISTER)) { URL url = URL.valueOf(msg.substring(REGISTER.length()).trim()); registered(url); } else if (msg.startsWith(UNREGISTER)) { URL url = URL.valueOf(msg.substring(UNREGISTER.length()).trim()); unregistered(url); } else if (msg.startsWith(SUBSCRIBE)) { URL url = URL.valueOf(msg.substring(SUBSCRIBE.length()).trim()); Set<URL> urls = getRegistered(); if (CollectionUtils.isNotEmpty(urls)) { for (URL u : urls) { if (UrlUtils.isMatch(url, u)) { String host = remoteAddress != null && remoteAddress.getAddress() != null ? remoteAddress.getAddress().getHostAddress() : url.getIp(); if (url.getParameter("unicast", true) // Whether the consumer's machine has only one process && !NetUtils.getLocalHost() .equals(host)) { // Multiple processes in the same machine cannot be unicast // with unicast or there will be only one process receiving // information unicast(REGISTER + " " + u.toFullString(), host); } else { multicast(REGISTER + " " + u.toFullString()); } } } } } /* else if (msg.startsWith(UNSUBSCRIBE)) { }*/ } private void multicast(String msg) { if (logger.isInfoEnabled()) { logger.info("Send multicast message: " + msg + " to " + multicastAddress + ":" + multicastPort); } try { byte[] data = (msg + "\n").getBytes(StandardCharsets.UTF_8); DatagramPacket hi = new DatagramPacket(data, data.length, multicastAddress, multicastPort); multicastSocket.send(hi); } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } private void unicast(String msg, String host) { if (logger.isInfoEnabled()) { logger.info("Send unicast message: " + msg + " to " + host + ":" + multicastPort); } try { byte[] data = (msg + "\n").getBytes(StandardCharsets.UTF_8); DatagramPacket hi = new DatagramPacket(data, data.length, InetAddress.getByName(host), multicastPort); multicastSocket.send(hi); } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } @Override public void doRegister(URL url) { multicast(REGISTER + " " + url.toFullString()); } @Override public void doUnregister(URL url) { multicast(UNREGISTER + " " + url.toFullString()); } @Override public void doSubscribe(URL url, final NotifyListener listener) { if (ANY_VALUE.equals(url.getServiceInterface())) { admin = true; } multicast(SUBSCRIBE + " " + url.toFullString()); synchronized (listener) { try { listener.wait(url.getParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT)); } catch (InterruptedException e) { } } } @Override public void doUnsubscribe(URL url, NotifyListener listener) { if (!ANY_VALUE.equals(url.getServiceInterface()) && url.getParameter(REGISTER_KEY, true)) { unregister(url); } multicast(UNSUBSCRIBE + " " + url.toFullString()); } @Override public boolean isAvailable() { try { return multicastSocket != null; } catch (Throwable t) { return false; } } /** * Remove the expired providers(if clean is true), leave the multicast group and close the multicast socket. */ @Override public void destroy() { super.destroy(); try { ExecutorUtil.cancelScheduledFuture(cleanFuture); } catch (Throwable t) { logger.warn(REGISTRY_SOCKET_EXCEPTION, "", "", t.getMessage(), t); } try { multicastSocket.leaveGroup(multicastAddress); multicastSocket.close(); } catch (Throwable t) { logger.warn(REGISTRY_SOCKET_EXCEPTION, "", "", t.getMessage(), t); } ExecutorUtil.gracefulShutdown(cleanExecutor, cleanPeriod); } protected void registered(URL url) { for (Map.Entry<URL, Set<NotifyListener>> entry : getSubscribed().entrySet()) { URL key = entry.getKey(); if (UrlUtils.isMatch(key, url)) { Set<URL> urls = ConcurrentHashMapUtils.computeIfAbsent(received, key, k -> new ConcurrentHashSet<>()); urls.add(url); List<URL> list = toList(urls); for (final NotifyListener listener : entry.getValue()) { notify(key, listener, list); synchronized (listener) { listener.notify(); } } } } } protected void unregistered(URL url) { for (Map.Entry<URL, Set<NotifyListener>> entry : getSubscribed().entrySet()) { URL key = entry.getKey(); if (UrlUtils.isMatch(key, url)) { Set<URL> urls = received.get(key); if (urls != null) { urls.remove(url); } if (urls == null || urls.isEmpty()) { if (urls == null) { urls = new ConcurrentHashSet<>(); } URL empty = url.setProtocol(EMPTY_PROTOCOL); urls.add(empty); } List<URL> list = toList(urls); for (NotifyListener listener : entry.getValue()) { notify(key, listener, list); } } } } protected void subscribed(URL url, NotifyListener listener) { List<URL> urls = lookup(url); notify(url, listener, urls); } private List<URL> toList(Set<URL> urls) { List<URL> list = new ArrayList<>(); if (CollectionUtils.isNotEmpty(urls)) { list.addAll(urls); } return list; } @Override public void register(URL url) { super.register(url); registered(url); } @Override public void unregister(URL url) { super.unregister(url); unregistered(url); } @Override public void subscribe(URL url, NotifyListener listener) { super.subscribe(url, listener); subscribed(url, listener); } @Override public void unsubscribe(URL url, NotifyListener listener) { super.unsubscribe(url, listener); received.remove(url); } @Override public List<URL> lookup(URL url) { List<URL> urls = new ArrayList<>(); Map<String, List<URL>> notifiedUrls = getNotified().get(url); if (notifiedUrls != null && notifiedUrls.size() > 0) { for (List<URL> values : notifiedUrls.values()) { urls.addAll(values); } } if (urls.isEmpty()) { List<URL> cacheUrls = getCacheUrls(url); if (CollectionUtils.isNotEmpty(cacheUrls)) { urls.addAll(cacheUrls); } } if (urls.isEmpty()) { for (URL u : getRegistered()) { if (UrlUtils.isMatch(url, u)) { urls.add(u); } } } if (ANY_VALUE.equals(url.getServiceInterface())) { for (URL u : getSubscribed().keySet()) { if (UrlUtils.isMatch(url, u)) { urls.add(u); } } } return urls; } public MulticastSocket getMulticastSocket() { return multicastSocket; } public Map<URL, Set<URL>> getReceived() { return received; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastServiceDiscovery.java
dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastServiceDiscovery.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.multicast; import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.client.AbstractServiceDiscovery; import org.apache.dubbo.registry.client.ServiceInstance; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Collections; import java.util.List; import java.util.Set; /** * TODO: make multicast protocol support Service Discovery */ public class MulticastServiceDiscovery extends AbstractServiceDiscovery { public MulticastServiceDiscovery(ApplicationModel applicationModel, URL registryURL) { super(applicationModel, registryURL); } public MulticastServiceDiscovery(String serviceName, URL registryURL) { super(serviceName, registryURL); } @Override public void doDestroy() throws Exception {} @Override public void doRegister(ServiceInstance serviceInstance) throws RuntimeException {} @Override public void doUpdate(ServiceInstance oldServiceInstance, ServiceInstance newServiceInstance) throws RuntimeException {} @Override public void doUnregister(ServiceInstance serviceInstance) throws RuntimeException { this.serviceInstance = null; } @Override public Set<String> getServices() { return Collections.singleton("Unsupported Operation"); } @Override public List<ServiceInstance> getInstances(String serviceName) throws NullPointerException { return null; } @Override public URL getUrl() { return registryURL; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastServiceDiscoveryFactory.java
dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastServiceDiscoveryFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.multicast; import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.client.AbstractServiceDiscoveryFactory; import org.apache.dubbo.registry.client.ServiceDiscovery; public class MulticastServiceDiscoveryFactory extends AbstractServiceDiscoveryFactory { @Override protected ServiceDiscovery createDiscovery(URL registryURL) { return new MulticastServiceDiscovery(applicationModel, registryURL); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistryFactory.java
dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistryFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.multicast; import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.support.AbstractRegistryFactory; /** * MulticastRegistryLocator * */ public class MulticastRegistryFactory extends AbstractRegistryFactory { @Override public Registry createRegistry(URL url) { return new MulticastRegistry(url, applicationModel); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/MockCacheableRegistryImpl.java
dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/MockCacheableRegistryImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.url.component.ServiceAddressURL; import org.apache.dubbo.common.url.component.URLAddress; import org.apache.dubbo.common.url.component.URLParam; import org.apache.dubbo.common.utils.UrlUtils; import org.apache.dubbo.registry.support.CacheableFailbackRegistry; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.Semaphore; public class MockCacheableRegistryImpl extends CacheableFailbackRegistry { private final List<String> children = new ArrayList<>(); NotifyListener listener; public MockCacheableRegistryImpl(URL url) { super(url); } @Override public int getDelay() { return 0; } @Override protected boolean isMatch(URL subscribeUrl, URL providerUrl) { return UrlUtils.isMatch(subscribeUrl, providerUrl); } @Override public void doRegister(URL url) {} @Override public void doUnregister(URL url) {} @Override public void doSubscribe(URL url, NotifyListener listener) { List<URL> res = toUrlsWithoutEmpty(url, children); Semaphore semaphore = getSemaphore(); while (semaphore.availablePermits() != 1) { try { Thread.sleep(100); } catch (InterruptedException e) { // ignore } } listener.notify(res); this.listener = listener; } @Override public void doUnsubscribe(URL url, NotifyListener listener) { super.doUnsubscribe(url, listener); } @Override public boolean isAvailable() { return false; } public void addChildren(URL url) { children.add(URL.encode(url.toFullString())); } public void removeChildren(URL url) { children.remove(URL.encode(url.toFullString())); if (listener != null) { listener.notify(toUrlsWithEmpty(getUrl(), "providers", children)); } } public List<String> getChildren() { return children; } public void clearChildren() { children.clear(); if (listener != null) { listener.notify(toUrlsWithEmpty(getUrl(), "providers", children)); } } public Map<URL, Map<String, ServiceAddressURL>> getStringUrls() { return stringUrls; } public Map<String, URLAddress> getStringAddress() { return stringAddress; } public Map<String, URLParam> getStringParam() { return stringParam; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/ListenerRegistryWrapperTest.java
dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/ListenerRegistryWrapperTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.registry.integration.DemoService; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.registry.Constants.REGISTER_IP_KEY; import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; class ListenerRegistryWrapperTest { @Test void testSubscribe() { Map<String, String> parameters = new HashMap<>(); parameters.put(INTERFACE_KEY, DemoService.class.getName()); parameters.put("registry", "zookeeper"); parameters.put("register", "true"); parameters.put(REGISTER_IP_KEY, "172.23.236.180"); parameters.put("registry.listeners", "listener-one"); Map<String, Object> attributes = new HashMap<>(); ServiceConfigURL serviceConfigURL = new ServiceConfigURL( "registry", "127.0.0.1", 2181, "org.apache.dubbo.registry.RegistryService", parameters); Map<String, String> refer = new HashMap<>(); attributes.put(REFER_KEY, refer); attributes.put("key1", "value1"); URL url = serviceConfigURL.addAttributes(attributes); RegistryFactory registryFactory = mock(RegistryFactory.class); Registry registry = mock(Registry.class); NotifyListener notifyListener = mock(NotifyListener.class); when(registryFactory.getRegistry(url)).thenReturn(registry); RegistryFactoryWrapper registryFactoryWrapper = new RegistryFactoryWrapper(registryFactory); Registry registryWrapper = registryFactoryWrapper.getRegistry(url); Assertions.assertTrue(registryWrapper instanceof ListenerRegistryWrapper); URL subscribeUrl = new ServiceConfigURL("dubbo", "127.0.0.1", 20881, DemoService.class.getName(), parameters); RegistryServiceListener listener = Mockito.mock(RegistryServiceListener.class); RegistryServiceListener1.delegate = listener; registryWrapper.subscribe(subscribeUrl, notifyListener); verify(listener, times(1)).onSubscribe(subscribeUrl, registry); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/RegistryServiceListener2.java
dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/RegistryServiceListener2.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; @Activate(order = 2, value = "listener-two") public class RegistryServiceListener2 implements RegistryServiceListener { static RegistryServiceListener delegate; @Override public void onRegister(URL url, Registry registry) { delegate.onRegister(url, registry); } @Override public void onUnregister(URL url, Registry registry) { delegate.onUnregister(url, registry); } @Override public void onSubscribe(URL url, Registry registry) { delegate.onSubscribe(url, registry); } @Override public void onUnsubscribe(URL url, Registry registry) { delegate.onUnsubscribe(url, registry); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/CacheableFailbackRegistryTest.java
dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/CacheableFailbackRegistryTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLStrParser; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.ENABLE_EMPTY_PROTECTION_KEY; import static org.junit.jupiter.api.Assertions.assertEquals; class CacheableFailbackRegistryTest { static String service; static URL serviceUrl; static URL registryUrl; static String urlStr; static String urlStr2; static String urlStr3; MockCacheableRegistryImpl registry; @BeforeAll static void setProperty() { System.setProperty("dubbo.application.url.cache.task.interval", "0"); System.setProperty("dubbo.application.url.cache.clear.waiting", "0"); FrameworkModel.destroyAll(); } @BeforeEach public void setUp() throws Exception { service = "org.apache.dubbo.test.DemoService"; serviceUrl = URL.valueOf("dubbo://127.0.0.1/org.apache.dubbo.test.DemoService?category=providers"); registryUrl = URL.valueOf("http://1.2.3.4:9090/registry?check=false&file=N/A"); urlStr = "dubbo%3A%2F%2F172.19.4.113%3A20880%2Forg.apache.dubbo.demo.DemoService%3Fside%3Dprovider%26timeout%3D3000"; urlStr2 = "dubbo%3A%2F%2F172.19.4.114%3A20880%2Forg.apache.dubbo.demo.DemoService%3Fside%3Dprovider%26timeout%3D3000"; urlStr3 = "dubbo%3A%2F%2F172.19.4.115%3A20880%2Forg.apache.dubbo.demo.DemoService%3Fside%3Dprovider%26timeout%3D3000"; } @AfterEach public void tearDown() { registry.getStringUrls().clear(); registry.getStringAddress().clear(); registry.getStringParam().clear(); } @Test void testFullURLCache() { final AtomicReference<Integer> resCount = new AtomicReference<>(0); registry = new MockCacheableRegistryImpl(registryUrl); URL url = URLStrParser.parseEncodedStr(urlStr); NotifyListener listener = urls -> resCount.set(urls.size()); registry.addChildren(url); registry.subscribe(serviceUrl, listener); assertEquals(1, registry.getStringUrls().get(serviceUrl).size()); assertEquals(1, resCount.get()); registry.addChildren(url); registry.subscribe(serviceUrl, listener); assertEquals(1, registry.getStringUrls().get(serviceUrl).size()); assertEquals(1, resCount.get()); URL url1 = url.addParameter("k1", "v1"); registry.addChildren(url1); registry.subscribe(serviceUrl, listener); assertEquals(2, registry.getStringUrls().get(serviceUrl).size()); assertEquals(2, resCount.get()); URL url2 = url1.setHost("192.168.1.1"); registry.addChildren(url2); registry.subscribe(serviceUrl, listener); assertEquals(3, registry.getStringUrls().get(serviceUrl).size()); assertEquals(3, resCount.get()); } @Test void testURLAddressCache() { final AtomicReference<Integer> resCount = new AtomicReference<>(0); registry = new MockCacheableRegistryImpl(registryUrl); URL url = URLStrParser.parseEncodedStr(urlStr); NotifyListener listener = urls -> resCount.set(urls.size()); registry.addChildren(url); registry.subscribe(serviceUrl, listener); assertEquals(1, registry.getStringAddress().size()); assertEquals(1, resCount.get()); URL url1 = url.addParameter("k1", "v1"); registry.addChildren(url1); registry.subscribe(serviceUrl, listener); assertEquals(1, registry.getStringAddress().size()); assertEquals(2, resCount.get()); URL url2 = url1.setHost("192.168.1.1"); registry.addChildren(url2); registry.subscribe(serviceUrl, listener); assertEquals(2, registry.getStringAddress().size()); assertEquals(3, resCount.get()); } @Test void testURLParamCache() { final AtomicReference<Integer> resCount = new AtomicReference<>(0); registry = new MockCacheableRegistryImpl(registryUrl); URL url = URLStrParser.parseEncodedStr(urlStr); NotifyListener listener = urls -> resCount.set(urls.size()); registry.addChildren(url); registry.subscribe(serviceUrl, listener); assertEquals(1, registry.getStringParam().size()); assertEquals(1, resCount.get()); URL url1 = url.addParameter("k1", "v1"); registry.addChildren(url1); registry.subscribe(serviceUrl, listener); assertEquals(2, registry.getStringParam().size()); assertEquals(2, resCount.get()); URL url2 = url1.setHost("192.168.1.1"); registry.addChildren(url2); registry.subscribe(serviceUrl, listener); assertEquals(2, registry.getStringParam().size()); assertEquals(3, resCount.get()); } @Test void testRemove() { final AtomicReference<Integer> resCount = new AtomicReference<>(0); registry = new MockCacheableRegistryImpl(registryUrl); URL url = URLStrParser.parseEncodedStr(urlStr); NotifyListener listener = urls -> resCount.set(urls.size()); registry.addChildren(url); registry.subscribe(serviceUrl, listener); assertEquals(1, registry.getStringUrls().get(serviceUrl).size()); assertEquals(1, registry.getStringAddress().size()); assertEquals(1, registry.getStringParam().size()); assertEquals(1, resCount.get()); registry.clearChildren(); URL url1 = url.addParameter("k1", "v1"); registry.addChildren(url1); registry.subscribe(serviceUrl, listener); assertEquals(1, registry.getStringUrls().get(serviceUrl).size()); assertEquals(1, resCount.get()); // After RemovalTask assertEquals(1, registry.getStringParam().size()); // StringAddress will be deleted because the related stringUrls cache has been deleted. assertEquals(0, registry.getStringAddress().size()); registry.clearChildren(); URL url2 = url1.setHost("192.168.1.1"); registry.addChildren(url2); registry.subscribe(serviceUrl, listener); assertEquals(1, registry.getStringUrls().get(serviceUrl).size()); assertEquals(1, resCount.get()); // After RemovalTask assertEquals(1, registry.getStringAddress().size()); // StringParam will be deleted because the related stringUrls cache has been deleted. assertEquals(0, registry.getStringParam().size()); } @Test void testEmptyProtection() { final AtomicReference<Integer> resCount = new AtomicReference<>(0); final AtomicReference<List<URL>> currentUrls = new AtomicReference<>(); final List<URL> EMPTY_LIST = new ArrayList<>(); registry = new MockCacheableRegistryImpl(registryUrl.addParameter(ENABLE_EMPTY_PROTECTION_KEY, true)); URL url = URLStrParser.parseEncodedStr(urlStr); URL url2 = URLStrParser.parseEncodedStr(urlStr2); URL url3 = URLStrParser.parseEncodedStr(urlStr3); NotifyListener listener = urls -> { if (CollectionUtils.isEmpty(urls)) { // do nothing } else if (urls.size() == 1 && urls.get(0).getProtocol().equals(EMPTY_PROTOCOL)) { resCount.set(0); currentUrls.set(EMPTY_LIST); } else { resCount.set(urls.size()); currentUrls.set(urls); } }; registry.addChildren(url); registry.addChildren(url2); registry.addChildren(url3); registry.subscribe(serviceUrl, listener); assertEquals(3, resCount.get()); registry.removeChildren(url); assertEquals(2, resCount.get()); registry.clearChildren(); assertEquals(2, resCount.get()); URL emptyRegistryURL = registryUrl.addParameter(ENABLE_EMPTY_PROTECTION_KEY, false); MockCacheableRegistryImpl emptyRegistry = new MockCacheableRegistryImpl(emptyRegistryURL); emptyRegistry.addChildren(url); emptyRegistry.addChildren(url2); emptyRegistry.subscribe(serviceUrl, listener); assertEquals(2, resCount.get()); emptyRegistry.clearChildren(); assertEquals(0, currentUrls.get().size()); assertEquals(EMPTY_LIST, currentUrls.get()); } @Test void testNoEmptyProtection() { final AtomicReference<Integer> resCount = new AtomicReference<>(0); final AtomicReference<List<URL>> currentUrls = new AtomicReference<>(); final List<URL> EMPTY_LIST = new ArrayList<>(); registry = new MockCacheableRegistryImpl(registryUrl); URL url = URLStrParser.parseEncodedStr(urlStr); URL url2 = URLStrParser.parseEncodedStr(urlStr2); URL url3 = URLStrParser.parseEncodedStr(urlStr3); NotifyListener listener = urls -> { if (CollectionUtils.isEmpty(urls)) { // do nothing } else if (urls.size() == 1 && urls.get(0).getProtocol().equals(EMPTY_PROTOCOL)) { resCount.set(0); currentUrls.set(EMPTY_LIST); } else { resCount.set(urls.size()); currentUrls.set(urls); } }; registry.addChildren(url); registry.addChildren(url2); registry.addChildren(url3); registry.subscribe(serviceUrl, listener); assertEquals(3, resCount.get()); registry.removeChildren(url); assertEquals(2, resCount.get()); registry.clearChildren(); assertEquals(0, resCount.get()); URL emptyRegistryURL = registryUrl.addParameter(ENABLE_EMPTY_PROTECTION_KEY, true); MockCacheableRegistryImpl emptyRegistry = new MockCacheableRegistryImpl(emptyRegistryURL); emptyRegistry.addChildren(url); emptyRegistry.addChildren(url2); emptyRegistry.subscribe(serviceUrl, listener); assertEquals(2, resCount.get()); emptyRegistry.clearChildren(); assertEquals(2, currentUrls.get().size()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/RegistryServiceListener1.java
dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/RegistryServiceListener1.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; @Activate(order = 1, value = "listener-one") public class RegistryServiceListener1 implements RegistryServiceListener { static RegistryServiceListener delegate; @Override public void onRegister(URL url, Registry registry) { delegate.onRegister(url, registry); } @Override public void onUnregister(URL url, Registry registry) { delegate.onUnregister(url, registry); } @Override public void onSubscribe(URL url, Registry registry) { delegate.onSubscribe(url, registry); } @Override public void onUnsubscribe(URL url, Registry registry) { delegate.onUnsubscribe(url, registry); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/PerformanceUtils.java
dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/PerformanceUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.SystemPropertyConfigUtils; import java.net.NetworkInterface; import java.net.SocketException; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; public class PerformanceUtils { private static final int WIDTH = 64; public static String getProperty(String key, String defaultValue) { String value = System.getProperty(key); if (value == null || value.trim().length() == 0 || value.startsWith("$")) { return defaultValue; } return value.trim(); } public static int getIntProperty(String key, int defaultValue) { String value = System.getProperty(key); if (value == null || value.trim().length() == 0 || value.startsWith("$")) { return defaultValue; } return Integer.parseInt(value.trim()); } public static boolean getBooleanProperty(String key, boolean defaultValue) { String value = System.getProperty(key); if (value == null || value.trim().length() == 0 || value.startsWith("$")) { return defaultValue; } return Boolean.parseBoolean(value.trim()); } public static List<String> getEnvironment() { List<String> environment = new ArrayList<String>(); environment.add("OS: " + SystemPropertyConfigUtils.getSystemProperty(CommonConstants.SystemProperty.SYSTEM_OS_NAME) + " " + SystemPropertyConfigUtils.getSystemProperty(CommonConstants.SystemProperty.SYSTEM_OS_VERSION) + " " + SystemPropertyConfigUtils.getSystemProperty(CommonConstants.SystemProperty.OS_ARCH, "")); environment.add("CPU: " + Runtime.getRuntime().availableProcessors() + " cores"); environment.add("JVM: " + SystemPropertyConfigUtils.getSystemProperty(CommonConstants.SystemProperty.JAVA_VM_NAME) + " " + SystemPropertyConfigUtils.getSystemProperty(CommonConstants.SystemProperty.JAVA_RUNTIME_VERSION)); environment.add("Memory: " + DecimalFormat.getIntegerInstance().format(Runtime.getRuntime().totalMemory()) + " bytes (Max: " + DecimalFormat.getIntegerInstance().format(Runtime.getRuntime().maxMemory()) + " bytes)"); NetworkInterface ni = PerformanceUtils.getNetworkInterface(); if (ni != null) { environment.add("Network: " + ni.getDisplayName()); } return environment; } public static void printSeparator() { StringBuilder pad = new StringBuilder(); for (int i = 0; i < WIDTH; i++) { pad.append('-'); } } public static void printBorder() { StringBuilder pad = new StringBuilder(); for (int i = 0; i < WIDTH; i++) { pad.append('='); } } public static void printBody(String msg) { StringBuilder pad = new StringBuilder(); int len = WIDTH - msg.length() - 1; if (len > 0) { for (int i = 0; i < len; i++) { pad.append(' '); } } } public static void printHeader(String msg) { StringBuilder pad = new StringBuilder(); int len = WIDTH - msg.length(); if (len > 0) { int half = len / 2; for (int i = 0; i < half; i++) { pad.append(' '); } } } public static NetworkInterface getNetworkInterface() { try { Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); if (interfaces != null) { while (interfaces.hasMoreElements()) { try { return interfaces.nextElement(); } catch (Throwable e) { } } } } catch (SocketException e) { } return null; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/RegistryFactoryWrapperTest.java
dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/RegistryFactoryWrapperTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.junit.jupiter.api.Test; import org.mockito.Mockito; class RegistryFactoryWrapperTest { private RegistryFactory registryFactory = ExtensionLoader.getExtensionLoader(RegistryFactory.class).getAdaptiveExtension(); @Test void test() throws Exception { RegistryServiceListener listener1 = Mockito.mock(RegistryServiceListener.class); RegistryServiceListener1.delegate = listener1; RegistryServiceListener listener2 = Mockito.mock(RegistryServiceListener.class); RegistryServiceListener2.delegate = listener2; Registry registry = registryFactory.getRegistry( URL.valueOf("simple://localhost:8080/registry-service?registry.listeners=listener-one,listener-two")); URL url = URL.valueOf("dubbo://localhost:8081/simple.service"); registry.register(url); Mockito.verify(listener1, Mockito.times(1)).onRegister(url, SimpleRegistryFactory.registry); Mockito.verify(listener2, Mockito.times(1)).onRegister(url, SimpleRegistryFactory.registry); registry.unregister(url); Mockito.verify(listener1, Mockito.times(1)).onUnregister(url, SimpleRegistryFactory.registry); Mockito.verify(listener2, Mockito.times(1)).onUnregister(url, SimpleRegistryFactory.registry); registry.subscribe(url, Mockito.mock(NotifyListener.class)); Mockito.verify(listener1, Mockito.times(1)).onSubscribe(url, SimpleRegistryFactory.registry); Mockito.verify(listener2, Mockito.times(1)).onSubscribe(url, SimpleRegistryFactory.registry); registry.unsubscribe(url, Mockito.mock(NotifyListener.class)); Mockito.verify(listener1, Mockito.times(1)).onUnsubscribe(url, SimpleRegistryFactory.registry); Mockito.verify(listener2, Mockito.times(1)).onUnsubscribe(url, SimpleRegistryFactory.registry); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/MockLogger.java
dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/MockLogger.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry; import org.apache.dubbo.common.logger.Logger; import java.util.HashSet; import java.util.Set; public class MockLogger implements Logger { public Set<String> printedLogs = new HashSet<>(); public boolean checkLogHappened(String msgPrefix) { for (String printedLog : printedLogs) { if (printedLog.contains(msgPrefix)) { return true; } } return false; } @Override public void trace(String msg) {} @Override public void trace(String msg, Object... arguments) {} @Override public void trace(Throwable e) {} @Override public void trace(String msg, Throwable e) {} @Override public void debug(String msg) {} @Override public void debug(String msg, Object... arguments) {} @Override public void debug(Throwable e) {} @Override public void debug(String msg, Throwable e) {} @Override public void info(String msg) {} @Override public void info(String msg, Object... arguments) {} @Override public void info(Throwable e) {} @Override public void info(String msg, Throwable e) {} @Override public void warn(String msg) {} @Override public void warn(String msg, Object... arguments) {} @Override public void warn(Throwable e) {} @Override public void warn(String msg, Throwable e) { printedLogs.add(msg); } @Override public void error(String msg) {} @Override public void error(String msg, Object... arguments) {} @Override public void error(Throwable e) {} @Override public void error(String msg, Throwable e) {} @Override public boolean isTraceEnabled() { return false; } @Override public boolean isDebugEnabled() { return false; } @Override public boolean isInfoEnabled() { return false; } @Override public boolean isWarnEnabled() { return false; } @Override public boolean isErrorEnabled() { return false; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/SimpleRegistryFactory.java
dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/SimpleRegistryFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry; import org.apache.dubbo.common.URL; import org.mockito.Mockito; public class SimpleRegistryFactory implements RegistryFactory { static Registry registry = Mockito.mock(Registry.class); @Override public Registry getRegistry(URL url) { return registry; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/PerformanceRegistryTest.java
dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/PerformanceRegistryTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.NetUtils; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_UNDEFINED_ARGUMENT; /** * RegistryPerformanceTest */ class PerformanceRegistryTest { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(PerformanceRegistryTest.class); @Test void testRegistry() { // read server info from property if (PerformanceUtils.getProperty("server", null) == null) { logger.warn(CONFIG_UNDEFINED_ARGUMENT, "", "", "Please set -Dserver=127.0.0.1:9090"); return; } final int base = PerformanceUtils.getIntProperty("base", 0); final int concurrent = PerformanceUtils.getIntProperty("concurrent", 100); int r = PerformanceUtils.getIntProperty("runs", 1000); final int runs = r > 0 ? r : Integer.MAX_VALUE; final Registry registry = ExtensionLoader.getExtensionLoader(RegistryFactory.class) .getAdaptiveExtension() .getRegistry(URL.valueOf( "remote://admin:hello1234@" + PerformanceUtils.getProperty("server", "10.20.153.28:9090"))); for (int i = 0; i < concurrent; i++) { final int t = i; new Thread(new Runnable() { public void run() { for (int j = 0; j < runs; j++) { registry.register( URL.valueOf("remote://" + NetUtils.getLocalHost() + ":8080/demoService" + t + "_" + j + "?version=1.0.0&application=demo&dubbo=2.0&interface=" + "org.apache.dubbo.demo.DemoService" + (base + t) + "_" + (base + j))); } } }) .start(); } synchronized (PerformanceRegistryTest.class) { while (true) { try { PerformanceRegistryTest.class.wait(); } catch (InterruptedException e) { } } } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/ZKTools.java
dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/ZKTools.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry; import org.apache.dubbo.common.utils.NamedThreadFactory; import org.apache.dubbo.common.utils.StringUtils; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.framework.api.CuratorListener; import org.apache.curator.framework.recipes.cache.ChildData; import org.apache.curator.framework.recipes.cache.PathChildrenCache; import org.apache.curator.framework.recipes.cache.TreeCache; import org.apache.curator.framework.recipes.cache.TreeCacheEvent; import org.apache.curator.framework.recipes.cache.TreeCacheListener; import org.apache.curator.retry.ExponentialBackoffRetry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ZKTools { private static final Logger logger = LoggerFactory.getLogger(ZKTools.class); private static CuratorFramework client; private static ExecutorService executor = Executors.newFixedThreadPool(1, new NamedThreadFactory("ZKTools-test", true)); public static void main(String[] args) throws Exception { client = CuratorFrameworkFactory.newClient( "127.0.0.1:2181", 60 * 1000, 60 * 1000, new ExponentialBackoffRetry(1000, 3)); client.start(); client.getCuratorListenable() .addListener( new CuratorListener() { @Override public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception { logger.info("event notification: {}", event.getPath()); logger.info(String.valueOf(event)); } }, executor); // testMigrationRule(); testAppMigrationRule(); // tesConditionRule(); // testStartupConfig(); // testProviderConfig(); // testPathCache(); // testTreeCache(); // testCuratorListener(); // Thread.sleep(100000); } public static void testMigrationRule() { String serviceStr = "key: demo-consumer\n" + "interfaces:\n" + " - serviceKey: org.apache.dubbo.demo.DemoService:1.0.0\n" + " threshold: 1.0\n" + " step: FORCE_APPLICATION"; try { String servicePath = "/dubbo/config/DUBBO_SERVICEDISCOVERY_MIGRATION/demo-consumer.migration"; if (client.checkExists().forPath(servicePath) == null) { client.create().creatingParentsIfNeeded().forPath(servicePath); } setData(servicePath, serviceStr); } catch (Exception e) { e.printStackTrace(); } } public static void testAppMigrationRule() { String serviceStr = "key: demo-consumer\n" + "applications:\n" + " - name: demo-provider\n" + " step: FORCE_APPLICATION\n" + " threshold: 0.8\n" + "interfaces:\n" + " - serviceKey: org.apache.dubbo.demo.DemoService\n" + " threshold: 1.0\n" + " step: FORCE_APPLICATION"; try { String servicePath = "/dubbo/config/DUBBO_SERVICEDISCOVERY_MIGRATION/demo-consumer.migration"; if (client.checkExists().forPath(servicePath) == null) { client.create().creatingParentsIfNeeded().forPath(servicePath); } setData(servicePath, serviceStr); } catch (Exception e) { e.printStackTrace(); } } public static void testStartupConfig() { String str = "dubbo.registry.address=zookeeper://127.0.0.1:2181\n" + "dubbo.registry.group=dubboregistrygroup1\n" + "dubbo.metadata-report.address=zookeeper://127.0.0.1:2181\n" + "dubbo.protocol.port=20990\n" + "dubbo.service.org.apache.dubbo.demo.DemoService.timeout=9999\n"; try { String path = "/dubboregistrygroup1/config/dubbo/dubbo.properties"; if (client.checkExists().forPath(path) == null) { client.create().creatingParentsIfNeeded().forPath(path); } setData(path, str); } catch (Exception e) { e.printStackTrace(); } } public static void testProviderConfig() { String str = "---\n" + "apiVersion: v2.7\n" + "scope: service\n" + "key: dd-test/org.apache.dubbo.demo.DemoService:1.0.4\n" + "enabled: true\n" + "configs:\n" + "- addresses: ['0.0.0.0:20880']\n" + " side: provider\n" + " parameters:\n" + " timeout: 6000\n" + "..."; try { String path = "/dubbo/config/dd-test*org.apache.dubbo.demo.DemoService:1.0.4/configurators"; if (client.checkExists().forPath(path) == null) { client.create().creatingParentsIfNeeded().inBackground().forPath(path); } setData(path, str); String pathaa = "/dubboregistrygroup1/config/aaa/dubbo.properties"; if (client.checkExists().forPath(pathaa) == null) { client.create().creatingParentsIfNeeded().forPath(pathaa); } setData(pathaa, "aaaa"); String pathaaa = "/dubboregistrygroup1/config/aaa"; if (client.checkExists().forPath(pathaaa) == null) { client.create().creatingParentsIfNeeded().inBackground().forPath(pathaaa); } setData(pathaaa, "aaaa"); } catch (Exception e) { e.printStackTrace(); } } public static void testConsumerConfig() { String serviceStr = "---\n" + "scope: service\n" + "key: org.apache.dubbo.demo.DemoService\n" + "configs:\n" + " - addresses: [30.5.121.156]\n" + " side: consumer\n" + " rules:\n" + " cluster:\n" + " loadbalance: random\n" + " cluster: failfast\n" + " config:\n" + " timeout: 9999\n" + " weight: 222\n" + "..."; String appStr = "---\n" + "scope: application\n" + "key: demo-consumer\n" + "configs:\n" + " - addresses: [30.5.121.156]\n" + " services: [org.apache.dubbo.demo.DemoService]\n" + " side: consumer\n" + " rules:\n" + " cluster:\n" + " loadbalance: random\n" + " cluster: failfast\n" + " config:\n" + " timeout: 4444\n" + " weight: 222\n" + "..."; try { String servicePath = "/dubbo/config/org.apache.dubbo.demo.DemoService/configurators"; if (client.checkExists().forPath(servicePath) == null) { client.create().creatingParentsIfNeeded().forPath(servicePath); } setData(servicePath, serviceStr); String appPath = "/dubbo/config/demo-consumer/configurators"; if (client.checkExists().forPath(appPath) == null) { client.create().creatingParentsIfNeeded().forPath(appPath); } setData(appPath, appStr); } catch (Exception e) { e.printStackTrace(); } } public static void tesConditionRule() { String serviceStr = "---\n" + "scope: application\n" + "force: true\n" + "runtime: false\n" + "conditions:\n" + " - method!=sayHello =>\n" + " - method=routeMethod1 => 30.5.121.156:20880\n" + "..."; try { String servicePath = "/dubbo/config/demo-consumer/routers"; if (client.checkExists().forPath(servicePath) == null) { client.create().creatingParentsIfNeeded().forPath(servicePath); } setData(servicePath, serviceStr); } catch (Exception e) { e.printStackTrace(); } } public static void setData(String path, String data) throws Exception { client.setData().inBackground().forPath(path, data.getBytes(StandardCharsets.UTF_8)); } public static void testPathCache() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient( "127.0.0.1:2181", 60 * 1000, 60 * 1000, new ExponentialBackoffRetry(1000, 3)); client.start(); PathChildrenCache pathChildrenCache = new PathChildrenCache(client, "/dubbo/config", true); pathChildrenCache.start(true); pathChildrenCache .getListenable() .addListener( (zkClient, event) -> { logger.info(event.getData().getPath()); }, Executors.newFixedThreadPool(1)); List<ChildData> dataList = pathChildrenCache.getCurrentData(); dataList.stream().map(ChildData::getPath).forEach(logger::info); } public static void testTreeCache() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient( "127.0.0.1:2181", 60 * 1000, 60 * 1000, new ExponentialBackoffRetry(1000, 3)); client.start(); CountDownLatch latch = new CountDownLatch(1); TreeCache treeCache = TreeCache.newBuilder(client, "/dubbo/config").setCacheData(true).build(); treeCache.start(); treeCache.getListenable().addListener(new TreeCacheListener() { @Override public void childEvent(CuratorFramework client, TreeCacheEvent event) { TreeCacheEvent.Type type = event.getType(); ChildData data = event.getData(); if (type == TreeCacheEvent.Type.INITIALIZED) { latch.countDown(); } logger.info("{}\n", data.getPath()); if (data.getPath().split("/").length == 5) { byte[] value = data.getData(); String stringValue = new String(value, StandardCharsets.UTF_8); // fire event to all listeners Map<String, Object> added = null; Map<String, Object> changed = null; Map<String, Object> deleted = null; switch (type) { case NODE_ADDED: added = new HashMap<>(1); added.put(pathToKey(data.getPath()), stringValue); added.forEach((k, v) -> logger.info("{} {}", k, v)); break; case NODE_REMOVED: deleted = new HashMap<>(1); deleted.put(pathToKey(data.getPath()), stringValue); deleted.forEach((k, v) -> logger.info("{} {}", k, v)); break; case NODE_UPDATED: changed = new HashMap<>(1); changed.put(pathToKey(data.getPath()), stringValue); changed.forEach((k, v) -> logger.info("{} {}", k, v)); } } } }); latch.await(); /* Map<String, ChildData> dataMap = treeCache.getCurrentChildren("/dubbo/config"); dataMap.forEach((k, v) -> { System.out.println(k); treeCache.getCurrentChildren("/dubbo/config/" + k).forEach((ck, cv) -> { System.out.println(ck); }); });*/ } private static String pathToKey(String path) { if (StringUtils.isEmpty(path)) { return path; } return path.replace("/dubbo/config/", "").replaceAll("/", "."); } public static void testCuratorListener() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient( "127.0.0.1:2181", 60 * 1000, 60 * 1000, new ExponentialBackoffRetry(1000, 3)); client.start(); List<String> children = client.getChildren().forPath("/dubbo/config"); children.forEach(logger::info); /* client.getCuratorListenable().addListener(new CuratorListener() { @Override public void eventReceived(CuratorFramework curatorFramework, CuratorEvent curatorEvent) throws Exception { curatorEvent.get } }); */ /*client.getChildren().usingWatcher(new CuratorWatcher() { @Override public void process(WatchedEvent watchedEvent) throws Exception { System.out.println(watchedEvent.getPath()); client.getChildren().usingWatcher(this).forPath("/dubbo/config"); System.out.println(watchedEvent.getWrapper().getPath()); } }).forPath("/dubbo/config");*/ } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/FailbackRegistryTest.java
dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/FailbackRegistryTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.registry.NotifyListener; import java.util.Arrays; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.registry.Constants.CONSUMER_PROTOCOL; import static org.apache.dubbo.registry.Constants.REGISTRY_RETRY_PERIOD_KEY; import static org.junit.jupiter.api.Assertions.assertEquals; class FailbackRegistryTest { protected final Logger logger = LoggerFactory.getLogger(getClass()); private URL serviceUrl; private URL registryUrl; private MockRegistry registry; private final int FAILED_PERIOD = 200; private final int sleepTime = 100; private final int tryTimes = 5; /** * @throws java.lang.Exception */ @BeforeEach public void setUp() throws Exception { String failedPeriod = String.valueOf(FAILED_PERIOD); serviceUrl = URL.valueOf("remote://127.0.0.1/demoservice?method=get") .addParameter(REGISTRY_RETRY_PERIOD_KEY, failedPeriod); registryUrl = URL.valueOf("http://1.2.3.4:9090/registry?check=false&file=N/A") .addParameter(REGISTRY_RETRY_PERIOD_KEY, failedPeriod); } /** * Test method for retry * * @throws Exception */ @Test void testDoRetry() throws Exception { final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false); // the latest latch just for 3. Because retry method has been removed. final CountDownLatch latch = new CountDownLatch(2); NotifyListener listener = urls -> notified.set(Boolean.TRUE); URL subscribeUrl = serviceUrl.setProtocol(CONSUMER_PROTOCOL).addParameters(CollectionUtils.toStringMap("check", "false")); registry = new MockRegistry(registryUrl, serviceUrl, latch); registry.setBad(true); registry.register(serviceUrl); registry.unregister(serviceUrl); registry.subscribe(subscribeUrl, listener); registry.unsubscribe(subscribeUrl, listener); // Failure can not be called to listener. assertEquals(false, notified.get()); assertEquals(2, latch.getCount()); registry.setBad(false); for (int i = 0; i < 20; i++) { logger.info("failback registry retry, times:" + i); if (latch.getCount() == 0) break; Thread.sleep(sleepTime); } assertEquals(0, latch.getCount()); // The failed subscribe corresponding key will be cleared when unsubscribing assertEquals(false, notified.get()); } @Test void testDoRetryRegister() throws Exception { final CountDownLatch latch = new CountDownLatch( 1); // All of them are called 4 times. A successful attempt to lose 1. subscribe will not be done registry = new MockRegistry(registryUrl, serviceUrl, latch); registry.setBad(true); registry.register(serviceUrl); registry.setBad(false); for (int i = 0; i < tryTimes; i++) { if (latch.getCount() == 0) break; Thread.sleep(sleepTime); } assertEquals(0, latch.getCount()); } @Test void testDoRetrySubscribe() throws Exception { final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false); final CountDownLatch latch = new CountDownLatch( 1); // All of them are called 4 times. A successful attempt to lose 1. subscribe will not be done NotifyListener listener = urls -> notified.set(Boolean.TRUE); registry = new MockRegistry(registryUrl, serviceUrl, latch); registry.setBad(true); registry.subscribe( serviceUrl.setProtocol(CONSUMER_PROTOCOL).addParameters(CollectionUtils.toStringMap("check", "false")), listener); // Failure can not be called to listener. assertEquals(false, notified.get()); assertEquals(1, latch.getCount()); registry.setBad(false); for (int i = 0; i < tryTimes; i++) { if (latch.getCount() == 0) break; Thread.sleep(sleepTime); } assertEquals(0, latch.getCount()); // The failed subscribe corresponding key will be cleared when unsubscribing assertEquals(true, notified.get()); } @Test void testRecover() throws Exception { CountDownLatch countDownLatch = new CountDownLatch(6); final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false); NotifyListener listener = urls -> notified.set(Boolean.TRUE); MockRegistry mockRegistry = new MockRegistry(registryUrl, serviceUrl, countDownLatch); mockRegistry.register(serviceUrl); mockRegistry.subscribe(serviceUrl, listener); Assertions.assertEquals(1, mockRegistry.getRegistered().size()); Assertions.assertEquals(1, mockRegistry.getSubscribed().size()); mockRegistry.recover(); countDownLatch.await(); Assertions.assertEquals(0, mockRegistry.getFailedRegistered().size()); FailbackRegistry.Holder h = new FailbackRegistry.Holder(registryUrl, listener); Assertions.assertNull(mockRegistry.getFailedSubscribed().get(h)); Assertions.assertEquals(countDownLatch.getCount(), 0); } private static class MockRegistry extends FailbackRegistry { private final URL serviceUrl; CountDownLatch latch; private volatile boolean bad = false; /** * @param url * @param serviceUrl */ public MockRegistry(URL url, URL serviceUrl, CountDownLatch latch) { super(url); this.serviceUrl = serviceUrl; this.latch = latch; } /** * @param bad the bad to set */ public void setBad(boolean bad) { this.bad = bad; } @Override public void doRegister(URL url) { if (bad) { throw new RuntimeException("can not invoke!"); } latch.countDown(); } @Override public void doUnregister(URL url) { if (bad) { throw new RuntimeException("can not invoke!"); } latch.countDown(); } @Override public void doSubscribe(URL url, NotifyListener listener) { if (bad) { throw new RuntimeException("can not invoke!"); } super.notify(url, listener, Arrays.asList(new URL[] {serviceUrl})); latch.countDown(); } @Override public void doUnsubscribe(URL url, NotifyListener listener) { if (bad) { throw new RuntimeException("can not invoke!"); } latch.countDown(); } @Override public boolean isAvailable() { return true; } @Override public void removeFailedRegisteredTask(URL url) { if (bad) { throw new RuntimeException("can not invoke!"); } super.removeFailedRegisteredTask(url); latch.countDown(); } @Override public void removeFailedSubscribedTask(URL url, NotifyListener listener) { if (bad) { throw new RuntimeException("can not invoke!"); } super.removeFailedSubscribedTask(url, listener); latch.countDown(); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/AbstractRegistryFactoryTest.java
dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/AbstractRegistryFactoryTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.registry.NotifyListener; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Collection; import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class AbstractRegistryFactoryTest { private AbstractRegistryFactory registryFactory; @BeforeEach public void setup() { registryFactory = new AbstractRegistryFactory() { @Override protected Registry createRegistry(final URL url) { return new Registry() { public URL getUrl() { return url; } @Override public boolean isAvailable() { return false; } @Override public void destroy() {} @Override public void register(URL url) {} @Override public void unregister(URL url) {} @Override public void subscribe(URL url, NotifyListener listener) {} @Override public void unsubscribe(URL url, NotifyListener listener) {} @Override public List<URL> lookup(URL url) { return null; } }; } }; registryFactory.setApplicationModel(ApplicationModel.defaultModel()); } @AfterEach public void teardown() { ApplicationModel.defaultModel().destroy(); } @Test void testRegistryFactoryCache() { URL url = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostAddress() + ":2233"); Registry registry1 = registryFactory.getRegistry(url); Registry registry2 = registryFactory.getRegistry(url); Assertions.assertEquals(registry1, registry2); } /** * Registration center address `dubbo` does not resolve */ // @Test public void testRegistryFactoryIpCache() { Registry registry1 = registryFactory.getRegistry( URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostName() + ":2233")); Registry registry2 = registryFactory.getRegistry( URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostAddress() + ":2233")); Assertions.assertEquals(registry1, registry2); } @Test void testRegistryFactoryGroupCache() { Registry registry1 = registryFactory.getRegistry(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":2233?group=aaa")); Registry registry2 = registryFactory.getRegistry(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":2233?group=bbb")); Assertions.assertNotSame(registry1, registry2); } @Test void testDestroyAllRegistries() { Registry registry1 = registryFactory.getRegistry(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":8888?group=xxx")); Registry registry2 = registryFactory.getRegistry(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":9999?group=yyy")); Registry registry3 = new AbstractRegistry(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":2020?group=yyy")) { @Override public boolean isAvailable() { return true; } }; RegistryManager registryManager = ApplicationModel.defaultModel().getBeanFactory().getBean(RegistryManager.class); Collection<Registry> registries = registryManager.getRegistries(); Assertions.assertTrue(registries.contains(registry1)); Assertions.assertTrue(registries.contains(registry2)); registry3.destroy(); registries = registryManager.getRegistries(); Assertions.assertFalse(registries.contains(registry3)); registryManager.destroyAll(); registries = registryManager.getRegistries(); Assertions.assertFalse(registries.contains(registry1)); Assertions.assertFalse(registries.contains(registry2)); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/AbstractRegistryTest.java
dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/AbstractRegistryTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.registry.NotifyListener; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; class AbstractRegistryTest { private URL testUrl; private URL mockUrl; private NotifyListener listener; private AbstractRegistry abstractRegistry; private boolean notifySuccess; private Map<String, String> parametersConsumer = new LinkedHashMap<>(); @BeforeEach public void init() { URL url = URL.valueOf("dubbo://192.168.0.2:2233"); // sync update cache file url = url.addParameter("save.file", true); testUrl = URL.valueOf("http://192.168.0.3:9090/registry?check=false&file=N/A&interface=com.test"); mockUrl = new ServiceConfigURL("dubbo", "192.168.0.1", 2200); parametersConsumer.put("application", "demo-consumer"); parametersConsumer.put("category", "consumer"); parametersConsumer.put("check", "false"); parametersConsumer.put("dubbo", "2.0.2"); parametersConsumer.put("interface", "org.apache.dubbo.demo.DemoService"); parametersConsumer.put("methods", "sayHello"); parametersConsumer.put("pid", "1676"); parametersConsumer.put("qos.port", "333333"); parametersConsumer.put("side", "consumer"); parametersConsumer.put("timestamp", String.valueOf(System.currentTimeMillis())); // init the object abstractRegistry = new AbstractRegistry(url) { @Override public boolean isAvailable() { return false; } }; // init notify listener listener = urls -> notifySuccess = true; // notify flag notifySuccess = false; } @AfterEach public void after() { abstractRegistry.destroy(); } /** * Test method for * {@link org.apache.dubbo.registry.support.AbstractRegistry#register(URL)}. * */ @Test void testRegister() { // test one url abstractRegistry.register(mockUrl); assert abstractRegistry.getRegistered().contains(mockUrl); // test multiple urls for (URL url : abstractRegistry.getRegistered()) { abstractRegistry.unregister(url); } List<URL> urlList = getList(); for (URL url : urlList) { abstractRegistry.register(url); } MatcherAssert.assertThat(abstractRegistry.getRegistered().size(), Matchers.equalTo(urlList.size())); } @Test void testRegisterIfURLNULL() { Assertions.assertThrows(IllegalArgumentException.class, () -> { abstractRegistry.register(null); Assertions.fail("register url == null"); }); } /** * Test method for * {@link org.apache.dubbo.registry.support.AbstractRegistry#unregister(URL)}. * */ @Test void testUnregister() { // test one unregister URL url = new ServiceConfigURL("dubbo", "192.168.0.1", 2200); abstractRegistry.register(url); abstractRegistry.unregister(url); MatcherAssert.assertThat( false, Matchers.equalTo(abstractRegistry.getRegistered().contains(url))); // test multiple unregisters for (URL u : abstractRegistry.getRegistered()) { abstractRegistry.unregister(u); } List<URL> urlList = getList(); for (URL urlSub : urlList) { abstractRegistry.register(urlSub); } for (URL urlSub : urlList) { abstractRegistry.unregister(urlSub); } MatcherAssert.assertThat( 0, Matchers.equalTo(abstractRegistry.getRegistered().size())); } @Test void testUnregisterIfUrlNull() { Assertions.assertThrows(IllegalArgumentException.class, () -> { abstractRegistry.unregister(null); Assertions.fail("unregister url == null"); }); } /** * test subscribe and unsubscribe */ @Test void testSubscribeAndUnsubscribe() { // test subscribe final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false); NotifyListener listener = urls -> notified.set(Boolean.TRUE); URL url = new ServiceConfigURL("dubbo", "192.168.0.1", 2200); abstractRegistry.subscribe(url, listener); Set<NotifyListener> subscribeListeners = abstractRegistry.getSubscribed().get(url); MatcherAssert.assertThat(true, Matchers.equalTo(subscribeListeners.contains(listener))); // test unsubscribe abstractRegistry.unsubscribe(url, listener); Set<NotifyListener> unsubscribeListeners = abstractRegistry.getSubscribed().get(url); MatcherAssert.assertThat(false, Matchers.equalTo(unsubscribeListeners.contains(listener))); } @Test void testSubscribeIfUrlNull() { Assertions.assertThrows(IllegalArgumentException.class, () -> { final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false); NotifyListener listener = urls -> notified.set(Boolean.TRUE); URL url = new ServiceConfigURL("dubbo", "192.168.0.1", 2200); abstractRegistry.subscribe(null, listener); Assertions.fail("subscribe url == null"); }); } @Test void testSubscribeIfListenerNull() { Assertions.assertThrows(IllegalArgumentException.class, () -> { final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false); NotifyListener listener = urls -> notified.set(Boolean.TRUE); URL url = new ServiceConfigURL("dubbo", "192.168.0.1", 2200); abstractRegistry.subscribe(url, null); Assertions.fail("listener url == null"); }); } @Test void testUnsubscribeIfUrlNull() { Assertions.assertThrows(IllegalArgumentException.class, () -> { final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false); NotifyListener listener = urls -> notified.set(Boolean.TRUE); abstractRegistry.unsubscribe(null, listener); Assertions.fail("unsubscribe url == null"); }); } @Test void testUnsubscribeIfNotifyNull() { Assertions.assertThrows(IllegalArgumentException.class, () -> { final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false); URL url = new ServiceConfigURL("dubbo", "192.168.0.1", 2200); abstractRegistry.unsubscribe(url, null); Assertions.fail("unsubscribe listener == null"); }); } /** * Test method for * {@link org.apache.dubbo.registry.support.AbstractRegistry#subscribe(URL, NotifyListener)}. * */ @Test void testSubscribe() { // check parameters try { abstractRegistry.subscribe(testUrl, null); Assertions.fail(); } catch (Exception e) { Assertions.assertTrue(e instanceof IllegalArgumentException); } // check parameters try { abstractRegistry.subscribe(null, null); Assertions.fail(); } catch (Exception e) { Assertions.assertTrue(e instanceof IllegalArgumentException); } // check if subscribe successfully Assertions.assertNull(abstractRegistry.getSubscribed().get(testUrl)); abstractRegistry.subscribe(testUrl, listener); Assertions.assertNotNull(abstractRegistry.getSubscribed().get(testUrl)); Assertions.assertTrue(abstractRegistry.getSubscribed().get(testUrl).contains(listener)); } /** * Test method for * {@link org.apache.dubbo.registry.support.AbstractRegistry#unsubscribe(URL, NotifyListener)}. * */ @Test void testUnsubscribe() { // check parameters try { abstractRegistry.unsubscribe(testUrl, null); Assertions.fail(); } catch (Exception e) { Assertions.assertTrue(e instanceof IllegalArgumentException); } // check parameters try { abstractRegistry.unsubscribe(null, null); Assertions.fail(); } catch (Exception e) { Assertions.assertTrue(e instanceof IllegalArgumentException); } Assertions.assertNull(abstractRegistry.getSubscribed().get(testUrl)); // check if unsubscribe successfully abstractRegistry.subscribe(testUrl, listener); abstractRegistry.unsubscribe(testUrl, listener); // Since we have subscribed testUrl, here should return a empty set instead of null Assertions.assertNotNull(abstractRegistry.getSubscribed().get(testUrl)); Assertions.assertFalse(abstractRegistry.getSubscribed().get(testUrl).contains(listener)); } /** * Test method for * {@link org.apache.dubbo.registry.support.AbstractRegistry#recover()}. */ @Test void testRecover() throws Exception { // test recover nothing abstractRegistry.recover(); Assertions.assertFalse(abstractRegistry.getRegistered().contains(testUrl)); Assertions.assertNull(abstractRegistry.getSubscribed().get(testUrl)); // test recover abstractRegistry.register(testUrl); abstractRegistry.subscribe(testUrl, listener); abstractRegistry.recover(); // check if recover successfully Assertions.assertTrue(abstractRegistry.getRegistered().contains(testUrl)); Assertions.assertNotNull(abstractRegistry.getSubscribed().get(testUrl)); Assertions.assertTrue(abstractRegistry.getSubscribed().get(testUrl).contains(listener)); } @Test void testRecover2() throws Exception { List<URL> list = getList(); abstractRegistry.recover(); Assertions.assertEquals(0, abstractRegistry.getRegistered().size()); for (URL url : list) { abstractRegistry.register(url); } Assertions.assertEquals(3, abstractRegistry.getRegistered().size()); abstractRegistry.recover(); Assertions.assertEquals(3, abstractRegistry.getRegistered().size()); } /** * Test method for * {@link org.apache.dubbo.registry.support.AbstractRegistry#notify(List)}. */ @Test void testNotify() { final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false); NotifyListener listener1 = urls -> notified.set(Boolean.TRUE); URL url1 = new ServiceConfigURL("dubbo", "192.168.0.1", 2200, parametersConsumer); abstractRegistry.subscribe(url1, listener1); NotifyListener listener2 = urls -> notified.set(Boolean.TRUE); URL url2 = new ServiceConfigURL("dubbo", "192.168.0.2", 2201, parametersConsumer); abstractRegistry.subscribe(url2, listener2); NotifyListener listener3 = urls -> notified.set(Boolean.TRUE); URL url3 = new ServiceConfigURL("dubbo", "192.168.0.3", 2202, parametersConsumer); abstractRegistry.subscribe(url3, listener3); List<URL> urls = new ArrayList<>(); urls.add(url1); urls.add(url2); urls.add(url3); abstractRegistry.notify(url1, listener1, urls); Map<URL, Map<String, List<URL>>> map = abstractRegistry.getNotified(); MatcherAssert.assertThat(true, Matchers.equalTo(map.containsKey(url1))); MatcherAssert.assertThat(false, Matchers.equalTo(map.containsKey(url2))); MatcherAssert.assertThat(false, Matchers.equalTo(map.containsKey(url3))); } /** * test notifyList */ @Test void testNotifyList() { final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false); NotifyListener listener1 = urls -> notified.set(Boolean.TRUE); URL url1 = new ServiceConfigURL("dubbo", "192.168.0.1", 2200, parametersConsumer); abstractRegistry.subscribe(url1, listener1); NotifyListener listener2 = urls -> notified.set(Boolean.TRUE); URL url2 = new ServiceConfigURL("dubbo", "192.168.0.2", 2201, parametersConsumer); abstractRegistry.subscribe(url2, listener2); NotifyListener listener3 = urls -> notified.set(Boolean.TRUE); URL url3 = new ServiceConfigURL("dubbo", "192.168.0.3", 2202, parametersConsumer); abstractRegistry.subscribe(url3, listener3); List<URL> urls = new ArrayList<>(); urls.add(url1); urls.add(url2); urls.add(url3); abstractRegistry.notify(urls); Map<URL, Map<String, List<URL>>> map = abstractRegistry.getNotified(); MatcherAssert.assertThat(true, Matchers.equalTo(map.containsKey(url1))); MatcherAssert.assertThat(true, Matchers.equalTo(map.containsKey(url2))); MatcherAssert.assertThat(true, Matchers.equalTo(map.containsKey(url3))); } @Test void testNotifyIfURLNull() { Assertions.assertThrows(IllegalArgumentException.class, () -> { final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false); NotifyListener listener1 = urls -> notified.set(Boolean.TRUE); URL url1 = new ServiceConfigURL("dubbo", "192.168.0.1", 2200, parametersConsumer); abstractRegistry.subscribe(url1, listener1); NotifyListener listener2 = urls -> notified.set(Boolean.TRUE); URL url2 = new ServiceConfigURL("dubbo", "192.168.0.2", 2201, parametersConsumer); abstractRegistry.subscribe(url2, listener2); NotifyListener listener3 = urls -> notified.set(Boolean.TRUE); URL url3 = new ServiceConfigURL("dubbo", "192.168.0.3", 2202, parametersConsumer); abstractRegistry.subscribe(url3, listener3); List<URL> urls = new ArrayList<>(); urls.add(url1); urls.add(url2); urls.add(url3); abstractRegistry.notify(null, listener1, urls); Assertions.fail("notify url == null"); }); } @Test void testNotifyIfNotifyNull() { Assertions.assertThrows(IllegalArgumentException.class, () -> { final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false); NotifyListener listener1 = urls -> notified.set(Boolean.TRUE); URL url1 = new ServiceConfigURL("dubbo", "192.168.0.1", 2200, parametersConsumer); abstractRegistry.subscribe(url1, listener1); NotifyListener listener2 = urls -> notified.set(Boolean.TRUE); URL url2 = new ServiceConfigURL("dubbo", "192.168.0.2", 2201, parametersConsumer); abstractRegistry.subscribe(url2, listener2); NotifyListener listener3 = urls -> notified.set(Boolean.TRUE); URL url3 = new ServiceConfigURL("dubbo", "192.168.0.3", 2202, parametersConsumer); abstractRegistry.subscribe(url3, listener3); List<URL> urls = new ArrayList<>(); urls.add(url1); urls.add(url2); urls.add(url3); abstractRegistry.notify(url1, null, urls); Assertions.fail("notify listener == null"); }); } /** * Test method for * {@link org.apache.dubbo.registry.support.AbstractRegistry#notify(URL, NotifyListener, List)}. * */ @Test void testNotifyArgs() { // check parameters try { abstractRegistry.notify(null, null, null); Assertions.fail(); } catch (Exception e) { Assertions.assertTrue(e instanceof IllegalArgumentException); } // check parameters try { abstractRegistry.notify(testUrl, null, null); Assertions.fail(); } catch (Exception e) { Assertions.assertTrue(e instanceof IllegalArgumentException); } // check parameters try { abstractRegistry.notify(null, listener, null); Assertions.fail(); } catch (Exception e) { Assertions.assertTrue(e instanceof IllegalArgumentException); } Assertions.assertFalse(notifySuccess); abstractRegistry.notify(testUrl, listener, null); Assertions.assertFalse(notifySuccess); List<URL> urls = new ArrayList<>(); urls.add(testUrl); // check if notify successfully Assertions.assertFalse(notifySuccess); abstractRegistry.notify(testUrl, listener, urls); Assertions.assertTrue(notifySuccess); } @Test void filterEmptyTest() { // check parameters try { AbstractRegistry.filterEmpty(null, null); Assertions.fail(); } catch (Exception e) { Assertions.assertTrue(e instanceof NullPointerException); } // check parameters List<URL> urls = new ArrayList<>(); try { AbstractRegistry.filterEmpty(null, urls); Assertions.fail(); } catch (Exception e) { Assertions.assertTrue(e instanceof NullPointerException); } // check if the output is generated by a fixed way urls.add(testUrl.setProtocol(EMPTY_PROTOCOL)); Assertions.assertEquals(AbstractRegistry.filterEmpty(testUrl, null), urls); List<URL> testUrls = new ArrayList<>(); Assertions.assertEquals(AbstractRegistry.filterEmpty(testUrl, testUrls), urls); // check if the output equals the input urls testUrls.add(testUrl); Assertions.assertEquals(AbstractRegistry.filterEmpty(testUrl, testUrls), testUrls); } @Test void lookupTest() { // loop up before registry try { abstractRegistry.lookup(null); Assertions.fail(); } catch (Exception e) { Assertions.assertTrue(e instanceof NullPointerException); } List<URL> urlList1 = abstractRegistry.lookup(testUrl); Assertions.assertFalse(urlList1.contains(testUrl)); // loop up after registry List<URL> urls = new ArrayList<>(); urls.add(testUrl); abstractRegistry.notify(urls); List<URL> urlList2 = abstractRegistry.lookup(testUrl); Assertions.assertTrue(urlList2.contains(testUrl)); } @Test void destroyTest() { abstractRegistry.register(testUrl); abstractRegistry.subscribe(testUrl, listener); Assertions.assertEquals(1, abstractRegistry.getRegistered().size()); Assertions.assertEquals(1, abstractRegistry.getSubscribed().get(testUrl).size()); // delete listener and register abstractRegistry.destroy(); Assertions.assertEquals(0, abstractRegistry.getRegistered().size()); Assertions.assertEquals(0, abstractRegistry.getSubscribed().get(testUrl).size()); } @Test void allTest() { // test all methods List<URL> urls = new ArrayList<>(); urls.add(testUrl); // register, subscribe, notify, unsubscribe, unregister abstractRegistry.register(testUrl); Assertions.assertTrue(abstractRegistry.getRegistered().contains(testUrl)); abstractRegistry.subscribe(testUrl, listener); Assertions.assertTrue(abstractRegistry.getSubscribed().containsKey(testUrl)); Assertions.assertFalse(notifySuccess); abstractRegistry.notify(urls); Assertions.assertTrue(notifySuccess); abstractRegistry.unsubscribe(testUrl, listener); Assertions.assertFalse(abstractRegistry.getSubscribed().containsKey(listener)); abstractRegistry.unregister(testUrl); Assertions.assertFalse(abstractRegistry.getRegistered().contains(testUrl)); } private List<URL> getList() { List<URL> list = new ArrayList<>(); URL url1 = new ServiceConfigURL("dubbo", "192.168.0.1", 1000); URL url2 = new ServiceConfigURL("dubbo", "192.168.0.2", 1001); URL url3 = new ServiceConfigURL("dubbo", "192.168.0.3", 1002); list.add(url1); list.add(url2); list.add(url3); return list; } @Test void getCacheUrlsTest() { List<URL> urls = new ArrayList<>(); urls.add(testUrl); // check if notify successfully Assertions.assertFalse(notifySuccess); abstractRegistry.notify(testUrl, listener, urls); Assertions.assertTrue(notifySuccess); List<URL> cacheUrl = abstractRegistry.getCacheUrls(testUrl); Assertions.assertEquals(1, cacheUrl.size()); URL nullUrl = URL.valueOf("http://1.2.3.4:9090/registry?check=false&file=N/A&interface=com.testa"); cacheUrl = abstractRegistry.getCacheUrls(nullUrl); Assertions.assertTrue(Objects.isNull(cacheUrl)); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false