fix channelHandlers has null object (#11357) (#11360)

This commit is contained in:
KamTo Hung 2023-01-22 22:33:20 +08:00 committed by GitHub
parent 33d4288cb8
commit 54bb2765a7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 25 additions and 2 deletions

View File

@ -24,7 +24,9 @@ import org.apache.dubbo.remoting.ChannelHandler;
import java.util.Arrays;
import java.util.Collection;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.stream.Collectors;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR;
@ -41,12 +43,15 @@ public class ChannelHandlerDispatcher implements ChannelHandler {
}
public ChannelHandlerDispatcher(ChannelHandler... handlers) {
// if varargs is used, the type of handlers is ChannelHandler[] and it is not null
// so we should filter the null object
this(handlers == null ? null : Arrays.asList(handlers));
}
public ChannelHandlerDispatcher(Collection<ChannelHandler> handlers) {
if (CollectionUtils.isNotEmpty(handlers)) {
this.channelHandlers.addAll(handlers);
// filter null object
this.channelHandlers.addAll(handlers.stream().filter(Objects::nonNull).collect(Collectors.toSet()));
}
}

View File

@ -19,12 +19,13 @@ package org.apache.dubbo.remoting.transport;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.RemotingException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
class ChannelHandlerDispatcherTest {
@ -57,6 +58,23 @@ class ChannelHandlerDispatcherTest {
}
@Test
void constructorNullObjectTest() {
ChannelHandlerDispatcher channelHandlerDispatcher = new ChannelHandlerDispatcher(null, null);
Assertions.assertEquals(0, channelHandlerDispatcher.getChannelHandlers().size());
ChannelHandlerDispatcher channelHandlerDispatcher1 = new ChannelHandlerDispatcher((MockChannelHandler) null);
Assertions.assertEquals(0, channelHandlerDispatcher1.getChannelHandlers().size());
ChannelHandlerDispatcher channelHandlerDispatcher2 = new ChannelHandlerDispatcher(null, new MockChannelHandler());
Assertions.assertEquals(1, channelHandlerDispatcher2.getChannelHandlers().size());
ChannelHandlerDispatcher channelHandlerDispatcher3 = new ChannelHandlerDispatcher(Collections.singleton(new MockChannelHandler()));
Assertions.assertEquals(1, channelHandlerDispatcher3.getChannelHandlers().size());
Collection<ChannelHandler> mockChannelHandlers = new HashSet<>();
mockChannelHandlers.add(new MockChannelHandler());
mockChannelHandlers.add(null);
ChannelHandlerDispatcher channelHandlerDispatcher4 = new ChannelHandlerDispatcher(mockChannelHandlers);
Assertions.assertEquals(1, channelHandlerDispatcher4.getChannelHandlers().size());
}
}
class MockChannelHandler extends ChannelHandlerAdapter {