index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/ResponseTest.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.exchange; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.HEARTBEAT_EVENT; class ResponseTest { @Test void test() { Response response = new Response(); response.setStatus(Response.OK); response.setId(1); response.setVersion("1.0.0"); response.setResult("test"); response.setEvent(HEARTBEAT_EVENT); response.setErrorMessage("errorMsg"); Assertions.assertTrue(response.isEvent()); Assertions.assertTrue(response.isHeartbeat()); Assertions.assertEquals(response.getVersion(), "1.0.0"); Assertions.assertEquals(response.getId(), 1); Assertions.assertEquals(response.getResult(), HEARTBEAT_EVENT); Assertions.assertEquals(response.getErrorMessage(), "errorMsg"); } }
7,400
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/MultiMessageTest.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.exchange.support; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * {@link MultiMessage} */ class MultiMessageTest { @Test void test() { MultiMessage multiMessage = MultiMessage.create(); Assertions.assertTrue(multiMessage instanceof Iterable); multiMessage.addMessage("test1"); multiMessage.addMessages(Arrays.asList("test2", "test3")); Assertions.assertEquals(multiMessage.size(), 3); Assertions.assertFalse(multiMessage.isEmpty()); Assertions.assertEquals(multiMessage.get(0), "test1"); Assertions.assertEquals(multiMessage.get(1), "test2"); Assertions.assertEquals(multiMessage.get(2), "test3"); Collection messages = multiMessage.getMessages(); Assertions.assertTrue(messages.contains("test1")); Assertions.assertTrue(messages.contains("test2")); Assertions.assertTrue(messages.contains("test3")); Iterator iterator = messages.iterator(); Assertions.assertTrue(iterator.hasNext()); Assertions.assertEquals(iterator.next(), "test1"); Assertions.assertEquals(iterator.next(), "test2"); Assertions.assertEquals(iterator.next(), "test3"); Collection removedCollection = multiMessage.removeMessages(); Assertions.assertArrayEquals(removedCollection.toArray(), messages.toArray()); messages = multiMessage.getMessages(); Assertions.assertTrue(messages.isEmpty()); MultiMessage multiMessage1 = MultiMessage.createFromCollection(Arrays.asList("test1", "test2")); MultiMessage multiMessage2 = MultiMessage.createFromArray("test1", "test2"); Assertions.assertArrayEquals( multiMessage1.getMessages().toArray(), multiMessage2.getMessages().toArray()); } }
7,401
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/ExchangeHandlerDispatcherTest.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.exchange.support; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.exchange.ExchangeChannel; import org.apache.dubbo.remoting.telnet.support.TelnetHandlerAdapter; import java.lang.reflect.Field; import org.junit.jupiter.api.Test; import org.mockito.Mockito; class ExchangeHandlerDispatcherTest { @Test void test() throws Exception { ExchangeHandlerDispatcher exchangeHandlerDispatcher = new ExchangeHandlerDispatcher(); ChannelHandler channelHandler = Mockito.mock(ChannelHandler.class); Replier replier = Mockito.mock(Replier.class); TelnetHandlerAdapter telnetHandlerAdapter = Mockito.mock(TelnetHandlerAdapter.class); exchangeHandlerDispatcher.addChannelHandler(channelHandler); exchangeHandlerDispatcher.addReplier(ExchangeHandlerDispatcherTest.class, replier); Field telnetHandlerField = exchangeHandlerDispatcher.getClass().getDeclaredField("telnetHandler"); telnetHandlerField.setAccessible(true); telnetHandlerField.set(exchangeHandlerDispatcher, telnetHandlerAdapter); Channel channel = Mockito.mock(Channel.class); ExchangeChannel exchangeChannel = Mockito.mock(ExchangeChannel.class); exchangeHandlerDispatcher.connected(channel); exchangeHandlerDispatcher.disconnected(channel); exchangeHandlerDispatcher.sent(channel, null); exchangeHandlerDispatcher.received(channel, null); exchangeHandlerDispatcher.caught(channel, null); ExchangeHandlerDispatcherTest obj = new ExchangeHandlerDispatcherTest(); exchangeHandlerDispatcher.reply(exchangeChannel, obj); exchangeHandlerDispatcher.telnet(channel, null); Mockito.verify(channelHandler, Mockito.times(1)).connected(channel); Mockito.verify(channelHandler, Mockito.times(1)).disconnected(channel); Mockito.verify(channelHandler, Mockito.times(1)).sent(channel, null); Mockito.verify(channelHandler, Mockito.times(1)).received(channel, null); Mockito.verify(channelHandler, Mockito.times(1)).caught(channel, null); Mockito.verify(replier, Mockito.times(1)).reply(exchangeChannel, obj); Mockito.verify(telnetHandlerAdapter, Mockito.times(1)).telnet(channel, null); exchangeHandlerDispatcher.removeChannelHandler(channelHandler); exchangeHandlerDispatcher.removeReplier(ExchangeHandlerDispatcherTest.class); } }
7,402
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/DefaultFutureTest.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.exchange.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.threadpool.ThreadlessExecutor; import org.apache.dubbo.common.threadpool.manager.ExecutorRepository; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.TimeoutException; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.handler.MockedChannel; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; class DefaultFutureTest { private static final AtomicInteger index = new AtomicInteger(); @Test void newFuture() { DefaultFuture future = defaultFuture(3000); Assertions.assertNotNull(future, "new future return null"); } @Test void isDone() { DefaultFuture future = defaultFuture(3000); Assertions.assertTrue(!future.isDone(), "init future is finished!"); // cancel a future future.cancel(); Assertions.assertTrue(future.isDone(), "cancel a future failed!"); } /** * for example, it will print like this: * before a future is create , time is : 2018-06-21 15:06:17 * after a future is timeout , time is : 2018-06-21 15:06:22 * <p> * The exception info print like: * Sending request timeout in client-side by scan timer. * start time: 2018-06-21 15:13:02.215, end time: 2018-06-21 15:13:07.231... */ @Test @Disabled public void timeoutNotSend() throws Exception { final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); System.out.println( "before a future is create , time is : " + LocalDateTime.now().format(formatter)); // timeout after 5 seconds. DefaultFuture f = defaultFuture(5000); while (!f.isDone()) { // spin Thread.sleep(100); } System.out.println( "after a future is timeout , time is : " + LocalDateTime.now().format(formatter)); // get operate will throw a timeout exception, because the future is timeout. try { f.get(); } catch (Exception e) { Assertions.assertTrue( e.getCause() instanceof TimeoutException, "catch exception is not timeout exception!"); System.out.println(e.getMessage()); } } /** * for example, it will print like this: * before a future is created, time is : 2023-09-03 18:20:14.535 * after a future is timeout, time is : 2023-09-03 18:20:14.669 * <p> * The exception info print like: * Sending request timeout in client-side by scan timer. * start time: 2023-09-03 18:20:14.544, end time: 2023-09-03 18:20:14.598... */ @Test public void clientTimeoutSend() throws Exception { final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"); System.out.println( "before a future is create , time is : " + LocalDateTime.now().format(formatter)); // timeout after 5 milliseconds. Channel channel = new MockedChannel(); Request request = new Request(10); DefaultFuture f = DefaultFuture.newFuture(channel, request, 5, null); System.gc(); // events such as Full GC will increase the time required to send messages. // mark the future is sent DefaultFuture.sent(channel, request); while (!f.isDone()) { // spin Thread.sleep(100); } System.out.println( "after a future is timeout , time is : " + LocalDateTime.now().format(formatter)); // get operate will throw a timeout exception, because the future is timeout. try { f.get(); } catch (Exception e) { Assertions.assertTrue( e.getCause() instanceof TimeoutException, "catch exception is not timeout exception!"); System.out.println(e.getMessage()); Assertions.assertTrue(e.getMessage() .startsWith( e.getCause().getClass().getCanonicalName() + ": Sending request timeout in client-side")); } } /** * for example, it will print like this: * before a future is create , time is : 2018-06-21 15:11:31 * after a future is timeout , time is : 2018-06-21 15:11:36 * <p> * The exception info print like: * Waiting server-side response timeout by scan timer. * start time: 2018-06-21 15:12:38.337, end time: 2018-06-21 15:12:43.354... */ @Test @Disabled public void timeoutSend() throws Exception { final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); System.out.println( "before a future is create , time is : " + LocalDateTime.now().format(formatter)); // timeout after 5 seconds. Channel channel = new MockedChannel(); Request request = new Request(10); DefaultFuture f = DefaultFuture.newFuture(channel, request, 5000, null); // mark the future is sent DefaultFuture.sent(channel, request); while (!f.isDone()) { // spin Thread.sleep(100); } System.out.println( "after a future is timeout , time is : " + LocalDateTime.now().format(formatter)); // get operate will throw a timeout exception, because the future is timeout. try { f.get(); } catch (Exception e) { Assertions.assertTrue( e.getCause() instanceof TimeoutException, "catch exception is not timeout exception!"); System.out.println(e.getMessage()); } } /** * for example, it will print like this: * before a future is created , time is : 2021-01-22 10:55:03 * null * after a future is timeout , time is : 2021-01-22 10:55:05 */ @Test void interruptSend() throws Exception { final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); System.out.println( "before a future is create , time is : " + LocalDateTime.now().format(formatter)); // timeout after 1 seconds. Channel channel = new MockedChannel(); int channelId = 10; Request request = new Request(channelId); ThreadlessExecutor executor = new ThreadlessExecutor(); DefaultFuture f = DefaultFuture.newFuture(channel, request, 1000, executor); // mark the future is sent DefaultFuture.sent(channel, request); // get operate will throw a interrupted exception, because the thread is interrupted. try { new InterruptThread(Thread.currentThread()).start(); while (!f.isDone()) { executor.waitAndDrain(Long.MAX_VALUE); } f.get(); } catch (Exception e) { Assertions.assertTrue(e instanceof InterruptedException, "catch exception is not interrupted exception!"); System.out.println(e.getMessage()); } finally { executor.shutdown(); } // waiting timeout check task finished Thread.sleep(1500); System.out.println( "after a future is timeout , time is : " + LocalDateTime.now().format(formatter)); DefaultFuture future = DefaultFuture.getFuture(channelId); // waiting future should be removed by time out check task Assertions.assertNull(future); } @Test void testClose1() { Channel channel = new MockedChannel(); Request request = new Request(123); ExecutorService executor = ExtensionLoader.getExtensionLoader(ExecutorRepository.class) .getDefaultExtension() .createExecutorIfAbsent(URL.valueOf("dubbo://127.0.0.1:23456")); DefaultFuture.newFuture(channel, request, 1000, executor); DefaultFuture.closeChannel(channel, 0); Assertions.assertFalse(executor.isTerminated()); } @Test void testClose2() { Channel channel = new MockedChannel(); Request request = new Request(123); ThreadlessExecutor threadlessExecutor = new ThreadlessExecutor(); DefaultFuture.newFuture(channel, request, 1000, threadlessExecutor); DefaultFuture.closeChannel(channel, 0); Assertions.assertTrue(threadlessExecutor.isTerminated()); } /** * mock a default future */ private DefaultFuture defaultFuture(int timeout) { Channel channel = new MockedChannel(); Request request = new Request(index.getAndIncrement()); return DefaultFuture.newFuture(channel, request, timeout, null); } /** * mock a thread interrupt another thread which is waiting waitAndDrain() to return. */ static class InterruptThread extends Thread { private Thread parent; public InterruptThread(Thread parent) { this.parent = parent; } @Override public void run() { super.run(); try { // interrupt waiting thread before timeout Thread.sleep(500); parent.interrupt(); } catch (InterruptedException e) { System.out.println(e.getMessage()); } } } }
7,403
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeServerTest.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.exchange.support.header; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.url.component.ServiceConfigURL; 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 java.net.InetSocketAddress; import java.util.Arrays; import java.util.Collection; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; /** * {@link HeaderExchangeServer} */ class HeaderExchangeServerTest { @Test void test() throws InterruptedException, RemotingException { RemotingServer server = Mockito.mock(RemotingServer.class); URL url = new ServiceConfigURL("dubbo", "127.0.0.1", 20881); Mockito.when(server.getUrl()).thenReturn(url); Mockito.when(server.canHandleIdle()).thenReturn(false); HeaderExchangeServer headerExchangeServer = new HeaderExchangeServer(server); Assertions.assertEquals(headerExchangeServer.getServer(), server); Assertions.assertEquals(headerExchangeServer.getUrl(), url); // test getChannels() and getExchangeChannels() Channel channel1 = Mockito.mock(Channel.class); Channel channel2 = Mockito.mock(Channel.class); Channel exchangeChannel1 = new HeaderExchangeChannel(channel1); Channel exchangeChannel2 = new HeaderExchangeChannel(channel2); Mockito.when(channel1.getAttribute(HeaderExchangeChannel.class.getName() + ".CHANNEL")) .thenReturn(exchangeChannel1); Mockito.when(channel2.getAttribute(HeaderExchangeChannel.class.getName() + ".CHANNEL")) .thenReturn(exchangeChannel2); Collection<Channel> exChannels = Arrays.asList(exchangeChannel1, exchangeChannel2); Mockito.when(server.getChannels()).thenReturn(Arrays.asList(channel1, channel2)); Assertions.assertEquals(headerExchangeServer.getChannels(), exChannels); Assertions.assertEquals(headerExchangeServer.getExchangeChannels(), exChannels); // test getChannel(InetSocketAddress) and getExchangeChannel(InetSocketAddress) InetSocketAddress address1 = Mockito.mock(InetSocketAddress.class); InetSocketAddress address2 = Mockito.mock(InetSocketAddress.class); Mockito.when(server.getChannel(Mockito.eq(address1))).thenReturn(channel1); Mockito.when(server.getChannel(Mockito.eq(address2))).thenReturn(channel2); Assertions.assertEquals(headerExchangeServer.getChannel(address1), exchangeChannel1); Assertions.assertEquals(headerExchangeServer.getChannel(address2), exchangeChannel2); Assertions.assertEquals(headerExchangeServer.getExchangeChannel(address1), exchangeChannel1); Assertions.assertEquals(headerExchangeServer.getExchangeChannel(address2), exchangeChannel2); // test send(Object message) and send(Object message, boolean sent) headerExchangeServer.send("test"); Mockito.verify(server, Mockito.times(1)).send("test"); headerExchangeServer.send("test", true); Mockito.verify(server, Mockito.times(1)).send("test", true); // test reset(URL url) url = url.addParameter(Constants.HEARTBEAT_KEY, 3000).addParameter(Constants.HEARTBEAT_TIMEOUT_KEY, 3000 * 3); headerExchangeServer.reset(url); // test close(int timeout) Mockito.when(exchangeChannel1.isConnected()).thenReturn(true); headerExchangeServer.close(1000); Mockito.verify(server, Mockito.times(1)).startClose(); Thread.sleep(1000); Mockito.verify(server, Mockito.times(1)).close(1000); Assertions.assertThrows(RemotingException.class, () -> headerExchangeServer.send("test")); Assertions.assertThrows(RemotingException.class, () -> headerExchangeServer.send("test", true)); } }
7,404
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/ReconnectTimerTaskTest.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.exchange.support.header; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.timer.HashedWheelTimer; import java.util.Collections; 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.DUBBO_VERSION_KEY; import static org.apache.dubbo.remoting.Constants.HEARTBEAT_CHECK_TICK; class ReconnectTimerTaskTest { private URL url = URL.valueOf("dubbo://localhost:20880"); private MockChannel channel; private ReconnectTimerTask reconnectTimerTask; private HashedWheelTimer reconnectTimer; private boolean isConnected = false; @BeforeEach public void setup() throws Exception { long tickDuration = 1000; reconnectTimer = new HashedWheelTimer(tickDuration / HEARTBEAT_CHECK_TICK, TimeUnit.MILLISECONDS); channel = new MockChannel() { @Override public URL getUrl() { return url; } @Override public boolean isConnected() { return isConnected; } }; reconnectTimerTask = new ReconnectTimerTask( () -> Collections.singleton(channel), reconnectTimer, tickDuration / HEARTBEAT_CHECK_TICK, (int) tickDuration); } @AfterEach public void teardown() { reconnectTimerTask.cancel(); } @Test void testReconnect() throws Exception { long now = System.currentTimeMillis(); url = url.addParameter(DUBBO_VERSION_KEY, "2.1.1"); channel.setAttribute(HeartbeatHandler.KEY_READ_TIMESTAMP, now - 1000); channel.setAttribute(HeartbeatHandler.KEY_WRITE_TIMESTAMP, now - 1000); Thread.sleep(2000L); Assertions.assertTrue(channel.getReconnectCount() > 0); isConnected = true; Thread.sleep(2000L); Assertions.assertTrue(channel.getReconnectCount() > 1); } }
7,405
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartBeatTaskTest.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.exchange.support.header; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.timer.HashedWheelTimer; import org.apache.dubbo.remoting.exchange.Request; import java.util.Collections; import java.util.List; 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.DUBBO_VERSION_KEY; import static org.apache.dubbo.remoting.Constants.HEARTBEAT_CHECK_TICK; class HeartBeatTaskTest { private URL url = URL.valueOf("dubbo://localhost:20880"); private MockChannel channel; private HeartbeatTimerTask heartbeatTimerTask; private HashedWheelTimer heartbeatTimer; @BeforeEach public void setup() throws Exception { long tickDuration = 1000; heartbeatTimer = new HashedWheelTimer(tickDuration / HEARTBEAT_CHECK_TICK, TimeUnit.MILLISECONDS); channel = new MockChannel() { @Override public URL getUrl() { return url; } }; heartbeatTimerTask = new HeartbeatTimerTask( () -> Collections.singleton(channel), heartbeatTimer, tickDuration / HEARTBEAT_CHECK_TICK, (int) tickDuration); } @AfterEach public void teardown() { heartbeatTimerTask.cancel(); } @Test void testHeartBeat() throws Exception { long now = System.currentTimeMillis(); url = url.addParameter(DUBBO_VERSION_KEY, "2.1.1"); channel.setAttribute(HeartbeatHandler.KEY_READ_TIMESTAMP, now); channel.setAttribute(HeartbeatHandler.KEY_WRITE_TIMESTAMP, now); Thread.sleep(2000L); List<Object> objects = channel.getSentObjects(); Assertions.assertTrue(objects.size() > 0); Object obj = objects.get(0); Assertions.assertTrue(obj instanceof Request); Request request = (Request) obj; Assertions.assertTrue(request.isHeartbeat()); } }
7,406
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeClientTest.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.exchange.support.header; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.Client; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; public class HeaderExchangeClientTest { @Test void testReconnect() { HeaderExchangeClient headerExchangeClient = new HeaderExchangeClient(Mockito.mock(Client.class), false); Assertions.assertTrue(headerExchangeClient.shouldReconnect(URL.valueOf("localhost"))); Assertions.assertTrue(headerExchangeClient.shouldReconnect(URL.valueOf("localhost?reconnect=true"))); Assertions.assertTrue(headerExchangeClient.shouldReconnect(URL.valueOf("localhost?reconnect=tRue"))); Assertions.assertTrue(headerExchangeClient.shouldReconnect(URL.valueOf("localhost?reconnect=30000"))); Assertions.assertTrue(headerExchangeClient.shouldReconnect(URL.valueOf("localhost?reconnect=0"))); Assertions.assertTrue(headerExchangeClient.shouldReconnect(URL.valueOf("localhost?reconnect=-1"))); Assertions.assertFalse(headerExchangeClient.shouldReconnect(URL.valueOf("localhost?reconnect=false"))); Assertions.assertFalse(headerExchangeClient.shouldReconnect(URL.valueOf("localhost?reconnect=FALSE"))); } }
7,407
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeChannelTest.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.exchange.support.header; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.support.DefaultFuture; import java.util.List; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; class HeaderExchangeChannelTest { private HeaderExchangeChannel header; private MockChannel channel; private URL url = URL.valueOf("dubbo://localhost:20880"); private static final String CHANNEL_KEY = HeaderExchangeChannel.class.getName() + ".CHANNEL"; @BeforeEach public void setup() { channel = new MockChannel() { @Override public URL getUrl() { return url; } }; header = new HeaderExchangeChannel(channel); } @Test void getOrAddChannelTest00() { channel.setAttribute("CHANNEL_KEY", "attribute"); HeaderExchangeChannel ret = HeaderExchangeChannel.getOrAddChannel(channel); Assertions.assertNotNull(ret); } @Test void getOrAddChannelTest01() { channel = new MockChannel() { @Override public URL getUrl() { return url; } @Override public boolean isConnected() { return true; } }; Assertions.assertNull(channel.getAttribute(CHANNEL_KEY)); HeaderExchangeChannel ret = HeaderExchangeChannel.getOrAddChannel(channel); Assertions.assertNotNull(ret); Assertions.assertNotNull(channel.getAttribute(CHANNEL_KEY)); Assertions.assertEquals(channel.getAttribute(CHANNEL_KEY).getClass(), HeaderExchangeChannel.class); } @Test void getOrAddChannelTest02() { channel = null; HeaderExchangeChannel ret = HeaderExchangeChannel.getOrAddChannel(channel); Assertions.assertNull(ret); } @Test void removeChannelIfDisconnectedTest() { Assertions.assertNull(channel.getAttribute(CHANNEL_KEY)); channel.setAttribute(CHANNEL_KEY, header); channel.close(); HeaderExchangeChannel.removeChannelIfDisconnected(channel); Assertions.assertNull(channel.getAttribute(CHANNEL_KEY)); } @Test void sendTest00() { boolean sent = true; String message = "this is a test message"; try { header.close(1); header.send(message, sent); } catch (Exception e) { Assertions.assertTrue(e instanceof RemotingException); } } @Test void sendTest01() throws RemotingException { boolean sent = true; String message = "this is a test message"; header.send(message, sent); List<Object> objects = channel.getSentObjects(); Assertions.assertEquals(objects.get(0), "this is a test message"); } @Test void sendTest02() throws RemotingException { boolean sent = true; int message = 1; header.send(message, sent); List<Object> objects = channel.getSentObjects(); Assertions.assertEquals(objects.get(0).getClass(), Request.class); Request request = (Request) objects.get(0); Assertions.assertEquals(request.getVersion(), "2.0.2"); } @Test void sendTest04() throws RemotingException { String message = "this is a test message"; header.send(message); List<Object> objects = channel.getSentObjects(); Assertions.assertEquals(objects.get(0), "this is a test message"); } @Test void requestTest01() throws RemotingException { Assertions.assertThrows(RemotingException.class, () -> { header.close(1000); Object requestObject = new Object(); header.request(requestObject); }); } @Test void requestTest02() throws RemotingException { Channel channel = Mockito.mock(MockChannel.class); header = new HeaderExchangeChannel(channel); when(channel.getUrl()).thenReturn(url); Object requestObject = new Object(); header.request(requestObject); ArgumentCaptor<Request> argumentCaptor = ArgumentCaptor.forClass(Request.class); verify(channel, times(1)).send(argumentCaptor.capture()); Assertions.assertEquals(argumentCaptor.getValue().getData(), requestObject); } @Test void requestTest03() throws RemotingException { Assertions.assertThrows(RemotingException.class, () -> { channel = new MockChannel() { @Override public void send(Object req) throws RemotingException { throw new RemotingException(channel.getLocalAddress(), channel.getRemoteAddress(), "throw error"); } }; header = new HeaderExchangeChannel(channel); Object requestObject = new Object(); header.request(requestObject, 1000); }); } @Test void isClosedTest() { Assertions.assertFalse(header.isClosed()); } @Test void closeTest() { Assertions.assertFalse(channel.isClosed()); header.close(); Assertions.assertTrue(channel.isClosed()); } @Test void closeWithTimeoutTest02() { Assertions.assertFalse(channel.isClosed()); Request request = new Request(); DefaultFuture.newFuture(channel, request, 100, null); header.close(100); // return directly header.close(1000); } @Test void startCloseTest() { try { boolean isClosing = channel.isClosing(); Assertions.assertFalse(isClosing); header.startClose(); isClosing = channel.isClosing(); Assertions.assertTrue(isClosing); } catch (Exception e) { e.printStackTrace(); } } @Test void getLocalAddressTest() { Assertions.assertNull(header.getLocalAddress()); } @Test void getRemoteAddressTest() { Assertions.assertNull(header.getRemoteAddress()); } @Test void getUrlTest() { Assertions.assertEquals(header.getUrl(), URL.valueOf("dubbo://localhost:20880")); } @Test void isConnectedTest() { Assertions.assertFalse(header.isConnected()); } @Test void getChannelHandlerTest() { Assertions.assertNull(header.getChannelHandler()); } @Test void getExchangeHandlerTest() { Assertions.assertNull(header.getExchangeHandler()); } @Test void getAttributeAndSetAttributeTest() { header.setAttribute("test", "test"); Assertions.assertEquals(header.getAttribute("test"), "test"); Assertions.assertTrue(header.hasAttribute("test")); } @Test void removeAttributeTest() { header.setAttribute("test", "test"); Assertions.assertEquals(header.getAttribute("test"), "test"); header.removeAttribute("test"); Assertions.assertFalse(header.hasAttribute("test")); } @Test void hasAttributeTest() { Assertions.assertFalse(header.hasAttribute("test")); header.setAttribute("test", "test"); Assertions.assertTrue(header.hasAttribute("test")); } @Test void hashCodeTest() { final int prime = 31; int result = 1; result = prime * result + ((channel == null) ? 0 : channel.hashCode()); Assertions.assertEquals(header.hashCode(), result); } @Test void equalsTest() { Assertions.assertThrows(IllegalArgumentException.class, () -> { Assertions.assertEquals(header, new HeaderExchangeChannel(channel)); header = new HeaderExchangeChannel(null); Assertions.assertNotEquals(header, new HeaderExchangeChannel(channel)); }); } @Test void toStringTest() { Assertions.assertEquals(header.toString(), channel.toString()); } }
7,408
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/MockChannel.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.exchange.support.header; import org.apache.dubbo.common.Parameters; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Client; import org.apache.dubbo.remoting.RemotingException; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class MockChannel implements Channel, Client { private Map<String, Object> attributes = new HashMap<String, Object>(); private volatile boolean closed = false; private volatile boolean closing = false; private volatile int reconnectCount = 0; private List<Object> sentObjects = new ArrayList<Object>(); @Override public InetSocketAddress getRemoteAddress() { return null; } @Override public boolean isConnected() { return false; } @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) { attributes.put(key, value); } @Override public void removeAttribute(String key) { attributes.remove(key); } @Override public URL getUrl() { return null; } @Override public ChannelHandler getChannelHandler() { return null; } @Override public InetSocketAddress getLocalAddress() { return null; } @Override public void send(Object message) throws RemotingException { sentObjects.add(message); } @Override public void send(Object message, boolean sent) throws RemotingException { sentObjects.add(message); } @Override public void close() { closed = true; } @Override public void close(int timeout) { closed = true; } @Override public void startClose() { closing = true; } @Override public boolean isClosed() { return closed; } public List<Object> getSentObjects() { return Collections.unmodifiableList(sentObjects); } public boolean isClosing() { return closing; } @Override public void reset(URL url) {} @Override public void reconnect() throws RemotingException { reconnectCount++; } @Override public void reset(Parameters parameters) {} public int getReconnectCount() { return reconnectCount; } }
7,409
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/CloseTimerTaskTest.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.exchange.support.header; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.timer.HashedWheelTimer; import org.apache.dubbo.remoting.Channel; import java.util.Collections; 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.DUBBO_VERSION_KEY; import static org.apache.dubbo.remoting.Constants.HEARTBEAT_CHECK_TICK; /** * {@link CloseTimerTask} */ class CloseTimerTaskTest { private URL url = URL.valueOf("dubbo://localhost:20880"); private MockChannel channel; private CloseTimerTask closeTimerTask; private HashedWheelTimer closeTimer; @BeforeEach public void setup() throws Exception { long tickDuration = 1000; closeTimer = new HashedWheelTimer(tickDuration / HEARTBEAT_CHECK_TICK, TimeUnit.MILLISECONDS); channel = new MockChannel() { @Override public URL getUrl() { return url; } }; AbstractTimerTask.ChannelProvider cp = () -> Collections.<Channel>singletonList(channel); closeTimerTask = new CloseTimerTask(cp, closeTimer, tickDuration / HEARTBEAT_CHECK_TICK, (int) tickDuration); } @AfterEach public void teardown() { closeTimerTask.cancel(); } @Test void testClose() throws Exception { long now = System.currentTimeMillis(); url = url.addParameter(DUBBO_VERSION_KEY, "2.1.1"); channel.setAttribute(HeartbeatHandler.KEY_READ_TIMESTAMP, now - 1000); channel.setAttribute(HeartbeatHandler.KEY_WRITE_TIMESTAMP, now - 1000); closeTimer.newTimeout(closeTimerTask, 250, TimeUnit.MILLISECONDS); Thread.sleep(2000L); Assertions.assertTrue(channel.isClosed()); } }
7,410
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/DecodeHandlerTest.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; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Decodeable; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.Response; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; /** * {@link DecodeHandler} */ class DecodeHandlerTest { @Test void test() throws Exception { ChannelHandler handler = Mockito.mock(ChannelHandler.class); Channel channel = Mockito.mock(Channel.class); DecodeHandler decodeHandler = new DecodeHandler(handler); MockData mockData = new MockData(); decodeHandler.received(channel, mockData); Assertions.assertTrue(mockData.isDecoded()); MockData mockRequestData = new MockData(); Request request = new Request(1); request.setData(mockRequestData); decodeHandler.received(channel, request); Assertions.assertTrue(mockRequestData.isDecoded()); MockData mockResponseData = new MockData(); Response response = new Response(1); response.setResult(mockResponseData); decodeHandler.received(channel, response); Assertions.assertTrue(mockResponseData.isDecoded()); mockData.setThrowEx(true); decodeHandler.received(channel, mockData); } class MockData implements Decodeable { private boolean isDecoded = false; private boolean throwEx = false; @Override public void decode() throws Exception { if (throwEx) { throw new RuntimeException(); } isDecoded = true; } public boolean isDecoded() { return isDecoded; } public void setThrowEx(boolean throwEx) { this.throwEx = throwEx; } } }
7,411
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/ChannelHandlerDispatcherTest.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; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; class ChannelHandlerDispatcherTest { @Test void test() { ChannelHandlerDispatcher channelHandlerDispatcher = new ChannelHandlerDispatcher(); MockChannelHandler channelHandler1 = new MockChannelHandler(); MockChannelHandler channelHandler2 = new MockChannelHandler(); channelHandlerDispatcher.addChannelHandler(channelHandler1); channelHandlerDispatcher.addChannelHandler(channelHandler2); Collection<ChannelHandler> channelHandlers = channelHandlerDispatcher.getChannelHandlers(); Assertions.assertTrue(channelHandlers.contains(channelHandler1)); Assertions.assertTrue(channelHandlers.contains(channelHandler2)); Channel channel = Mockito.mock(Channel.class); channelHandlerDispatcher.sent(channel, "test"); channelHandlerDispatcher.connected(channel); channelHandlerDispatcher.disconnected(channel); channelHandlerDispatcher.caught(channel, null); channelHandlerDispatcher.received(channel, "test"); Assertions.assertEquals(MockChannelHandler.getSentCount(), 2); Assertions.assertEquals(MockChannelHandler.getConnectedCount(), 2); Assertions.assertEquals(MockChannelHandler.getDisconnectedCount(), 2); Assertions.assertEquals(MockChannelHandler.getCaughtCount(), 2); Assertions.assertEquals(MockChannelHandler.getReceivedCount(), 2); channelHandlerDispatcher = channelHandlerDispatcher.removeChannelHandler(channelHandler1); Assertions.assertFalse(channelHandlerDispatcher.getChannelHandlers().contains(channelHandler1)); } @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 { private static int sentCount = 0; private static int connectedCount = 0; private static int disconnectedCount = 0; private static int receivedCount = 0; private static int caughtCount = 0; @Override public void connected(Channel channel) throws RemotingException { connectedCount++; super.connected(channel); } @Override public void disconnected(Channel channel) throws RemotingException { disconnectedCount++; super.disconnected(channel); } @Override public void sent(Channel channel, Object message) throws RemotingException { sentCount++; super.sent(channel, message); } @Override public void received(Channel channel, Object message) throws RemotingException { receivedCount++; super.received(channel, message); } @Override public void caught(Channel channel, Throwable exception) throws RemotingException { caughtCount++; super.caught(channel, exception); } public static int getSentCount() { return sentCount; } public static int getConnectedCount() { return connectedCount; } public static int getDisconnectedCount() { return disconnectedCount; } public static int getReceivedCount() { return receivedCount; } public static int getCaughtCount() { return caughtCount; } }
7,412
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/MultiMessageHandlerTest.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; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.exchange.support.MultiMessage; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; /** * {@link MultiMessageHandler} */ class MultiMessageHandlerTest { @Test void test() throws Exception { ChannelHandler handler = Mockito.mock(ChannelHandler.class); Channel channel = Mockito.mock(Channel.class); MultiMessageHandler multiMessageHandler = new MultiMessageHandler(handler); MultiMessage multiMessage = MultiMessage.createFromArray("test1", "test2"); multiMessageHandler.received(channel, multiMessage); // verify ArgumentCaptor<Channel> channelArgumentCaptor = ArgumentCaptor.forClass(Channel.class); ArgumentCaptor<Object> objectArgumentCaptor = ArgumentCaptor.forClass(Object.class); Mockito.verify(handler, Mockito.times(2)) .received(channelArgumentCaptor.capture(), objectArgumentCaptor.capture()); Assertions.assertEquals(objectArgumentCaptor.getAllValues().get(0), "test1"); Assertions.assertEquals(objectArgumentCaptor.getAllValues().get(1), "test2"); Assertions.assertEquals(channelArgumentCaptor.getValue(), channel); Object obj = new Object(); multiMessageHandler.received(channel, obj); // verify Mockito.verify(handler, Mockito.times(3)) .received(channelArgumentCaptor.capture(), objectArgumentCaptor.capture()); Assertions.assertEquals(objectArgumentCaptor.getValue(), obj); Assertions.assertEquals(channelArgumentCaptor.getValue(), channel); RuntimeException runtimeException = new RuntimeException(); Mockito.doThrow(runtimeException).when(handler).received(Mockito.any(), Mockito.any()); multiMessageHandler.received(channel, multiMessage); // verify ArgumentCaptor<Throwable> throwableArgumentCaptor = ArgumentCaptor.forClass(Throwable.class); Mockito.verify(handler, Mockito.times(2)) .caught(channelArgumentCaptor.capture(), throwableArgumentCaptor.capture()); Assertions.assertEquals(throwableArgumentCaptor.getAllValues().get(0), runtimeException); Assertions.assertEquals(throwableArgumentCaptor.getAllValues().get(1), runtimeException); Assertions.assertEquals(channelArgumentCaptor.getValue(), channel); } }
7,413
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/AbstractCodecTest.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; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.buffer.ChannelBuffer; import java.io.IOException; import java.net.InetSocketAddress; import org.junit.jupiter.api.Test; import org.mockito.internal.verification.VerificationModeFactory; import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; class AbstractCodecTest { @Test void testCheckPayloadDefault8M() throws Exception { Channel channel = mock(Channel.class); given(channel.getUrl()).willReturn(URL.valueOf("dubbo://1.1.1.1")); AbstractCodec.checkPayload(channel, 1 * 1024 * 1024); try { AbstractCodec.checkPayload(channel, 15 * 1024 * 1024); } catch (IOException expected) { assertThat( expected.getMessage(), allOf( containsString("Data length too large: "), containsString("max payload: " + 8 * 1024 * 1024))); } verify(channel, VerificationModeFactory.atLeastOnce()).getUrl(); } @Test void testCheckProviderPayload() throws Exception { Channel channel = mock(Channel.class); given(channel.getUrl()).willReturn(URL.valueOf("dubbo://1.1.1.1")); AbstractCodec.checkPayload(channel, 1024 * 1024 + 1, 1024 * 1024); try { AbstractCodec.checkPayload(channel, 1024 * 1024, 1024 * 1024); } catch (IOException expected) { assertThat( expected.getMessage(), allOf(containsString("Data length too large: "), containsString("max payload: " + 1024 * 1024))); } try { AbstractCodec.checkPayload(channel, 0, 15 * 1024 * 1024); } catch (IOException expected) { assertThat( expected.getMessage(), allOf( containsString("Data length too large: "), containsString("max payload: " + 8 * 1024 * 1024))); } verify(channel, VerificationModeFactory.atLeastOnce()).getUrl(); } @Test void tesCheckPayloadMinusPayloadNoLimit() throws Exception { Channel channel = mock(Channel.class); given(channel.getUrl()).willReturn(URL.valueOf("dubbo://1.1.1.1?payload=-1")); AbstractCodec.checkPayload(channel, 15 * 1024 * 1024); verify(channel, VerificationModeFactory.atLeastOnce()).getUrl(); } @Test void testIsClientSide() { AbstractCodec codec = getAbstractCodec(); Channel channel = mock(Channel.class); given(channel.getRemoteAddress()).willReturn(new InetSocketAddress("172.24.157.13", 9103)); given(channel.getUrl()).willReturn(URL.valueOf("dubbo://172.24.157.13:9103")); assertThat(codec.isClientSide(channel), is(true)); assertThat(codec.isServerSide(channel), is(false)); given(channel.getRemoteAddress()).willReturn(new InetSocketAddress("172.24.157.14", 9103)); given(channel.getUrl()).willReturn(URL.valueOf("dubbo://172.24.157.13:9103")); assertThat(codec.isClientSide(channel), is(false)); assertThat(codec.isServerSide(channel), is(true)); } private AbstractCodec getAbstractCodec() { AbstractCodec codec = new AbstractCodec() { @Override public void encode(Channel channel, ChannelBuffer buffer, Object message) {} @Override public Object decode(Channel channel, ChannelBuffer buffer) { return null; } }; return codec; } }
7,414
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/CodecSupportTest.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; import org.apache.dubbo.common.serialize.ObjectOutput; import org.apache.dubbo.common.serialize.Serialization; import org.apache.dubbo.common.serialize.support.DefaultSerializationSelector; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class CodecSupportTest { @Test void testHeartbeat() throws Exception { Byte proto = CodecSupport.getIDByName(DefaultSerializationSelector.getDefaultRemotingSerialization()); Serialization serialization = CodecSupport.getSerializationById(proto); byte[] nullBytes = CodecSupport.getNullBytesOf(serialization); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutput out = serialization.serialize(null, baos); out.writeObject(null); out.flushBuffer(); InputStream is = new ByteArrayInputStream(baos.toByteArray()); baos.close(); byte[] payload = CodecSupport.getPayload(is); Assertions.assertArrayEquals(nullBytes, payload); Assertions.assertTrue(CodecSupport.isHeartBeat(payload, proto)); } }
7,415
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/dispatcher/ChannelEventRunnableTest.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.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import java.util.Arrays; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; /** * {@link ChannelEventRunnable} */ class ChannelEventRunnableTest { @Test void test() throws Exception { ChannelEventRunnable.ChannelState[] values = ChannelEventRunnable.ChannelState.values(); Assertions.assertEquals(Arrays.toString(values), "[CONNECTED, DISCONNECTED, SENT, RECEIVED, CAUGHT]"); Channel channel = Mockito.mock(Channel.class); ChannelHandler handler = Mockito.mock(ChannelHandler.class); ChannelEventRunnable connectRunnable = new ChannelEventRunnable(channel, handler, ChannelEventRunnable.ChannelState.CONNECTED); ChannelEventRunnable disconnectRunnable = new ChannelEventRunnable(channel, handler, ChannelEventRunnable.ChannelState.DISCONNECTED); ChannelEventRunnable sentRunnable = new ChannelEventRunnable(channel, handler, ChannelEventRunnable.ChannelState.SENT); ChannelEventRunnable receivedRunnable = new ChannelEventRunnable(channel, handler, ChannelEventRunnable.ChannelState.RECEIVED, ""); ChannelEventRunnable caughtRunnable = new ChannelEventRunnable( channel, handler, ChannelEventRunnable.ChannelState.CAUGHT, new RuntimeException()); connectRunnable.run(); disconnectRunnable.run(); sentRunnable.run(); receivedRunnable.run(); caughtRunnable.run(); ArgumentCaptor<Channel> channelArgumentCaptor = ArgumentCaptor.forClass(Channel.class); ArgumentCaptor<Throwable> throwableArgumentCaptor = ArgumentCaptor.forClass(Throwable.class); ArgumentCaptor<Object> objectArgumentCaptor = ArgumentCaptor.forClass(Object.class); Mockito.verify(handler, Mockito.times(1)).connected(channelArgumentCaptor.capture()); Mockito.verify(handler, Mockito.times(1)).disconnected(channelArgumentCaptor.capture()); Mockito.verify(handler, Mockito.times(1)).sent(channelArgumentCaptor.capture(), Mockito.any()); Mockito.verify(handler, Mockito.times(1)) .received(channelArgumentCaptor.capture(), objectArgumentCaptor.capture()); Mockito.verify(handler, Mockito.times(1)) .caught(channelArgumentCaptor.capture(), throwableArgumentCaptor.capture()); } }
7,416
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/DeprecatedTelnetCodec.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.codec; 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.serialize.ObjectOutput; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.Codec; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.transport.CodecSupport; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.InetSocketAddress; import java.nio.charset.Charset; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_EXCEED_PAYLOAD_LIMIT; import static org.apache.dubbo.remoting.Constants.CHARSET_KEY; public class DeprecatedTelnetCodec implements Codec { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DeprecatedTelnetCodec.class); private static final String HISTORY_LIST_KEY = "telnet.history.list"; private static final String HISTORY_INDEX_KEY = "telnet.history.index"; private static final byte[] UP = new byte[] {27, 91, 65}; private static final byte[] DOWN = new byte[] {27, 91, 66}; private static final List<?> ENTER = Arrays.asList( new Object[] {new byte[] {'\r', '\n'} /* Windows Enter */, new byte[] {'\n'} /* Linux Enter */}); private static final List<?> EXIT = Arrays.asList(new Object[] { new byte[] {3} /* Windows Ctrl+C */, new byte[] {-1, -12, -1, -3, 6} /* Linux Ctrl+C */, new byte[] {-1, -19, -1, -3, 6} /* Linux Pause */ }); static void checkPayload(Channel channel, long size) throws IOException { int payload = Constants.DEFAULT_PAYLOAD; if (channel != null && channel.getUrl() != null) { payload = channel.getUrl().getPositiveParameter(Constants.PAYLOAD_KEY, Constants.DEFAULT_PAYLOAD); } if (size > payload) { IOException e = new IOException( "Data length too large: " + size + ", max payload: " + payload + ", channel: " + channel); logger.error(TRANSPORT_EXCEED_PAYLOAD_LIMIT, "", "", e.getMessage(), e); throw e; } } private static Charset getCharset(Channel channel) { if (channel != null) { Object attribute = channel.getAttribute(CHARSET_KEY); if (attribute instanceof String) { try { return Charset.forName((String) attribute); } catch (Throwable t) { logger.warn(t.getMessage(), t); } } else if (attribute instanceof Charset) { return (Charset) attribute; } URL url = channel.getUrl(); if (url != null) { String parameter = url.getParameter(CHARSET_KEY); if (StringUtils.isNotEmpty(parameter)) { try { return Charset.forName(parameter); } catch (Throwable t) { logger.warn(t.getMessage(), t); } } } } try { return Charset.forName("GBK"); } catch (Throwable t) { logger.warn(t.getMessage(), t); } return Charset.defaultCharset(); } private static String toString(byte[] message, Charset charset) throws UnsupportedEncodingException { byte[] copy = new byte[message.length]; int index = 0; for (int i = 0; i < message.length; i++) { byte b = message[i]; if (b == '\b') { // backspace if (index > 0) { index--; } if (i > 2 && message[i - 2] < 0) { // double byte char if (index > 0) { index--; } } } else if (b == 27) { // escape if (i < message.length - 4 && message[i + 4] == 126) { i = i + 4; } else if (i < message.length - 3 && message[i + 3] == 126) { i = i + 3; } else if (i < message.length - 2) { i = i + 2; } } else if (b == -1 && i < message.length - 2 && (message[i + 1] == -3 || message[i + 1] == -5)) { // handshake i = i + 2; } else { copy[index++] = message[i]; } } if (index == 0) { return ""; } return new String(copy, 0, index, charset.name()).trim(); } private static boolean isEquals(byte[] message, byte[] command) throws IOException { return message.length == command.length && endsWith(message, command); } private static boolean endsWith(byte[] message, byte[] command) throws IOException { if (message.length < command.length) { return false; } int offset = message.length - command.length; for (int i = command.length - 1; i >= 0; i--) { if (message[offset + i] != command[i]) { return false; } } return true; } protected boolean isClientSide(Channel channel) { String side = (String) channel.getAttribute(SIDE_KEY); if ("client".equals(side)) { return true; } else if ("server".equals(side)) { return false; } else { InetSocketAddress address = channel.getRemoteAddress(); URL url = channel.getUrl(); boolean client = url.getPort() == address.getPort() && NetUtils.filterLocalHost(url.getIp()) .equals(NetUtils.filterLocalHost( address.getAddress().getHostAddress())); channel.setAttribute(SIDE_KEY, client ? "client" : "server"); return client; } } public void encode(Channel channel, OutputStream output, Object message) throws IOException { if (message instanceof String) { if (isClientSide(channel)) { message = message + "\r\n"; } byte[] msgData = ((String) message).getBytes(getCharset(channel).name()); output.write(msgData); output.flush(); } else { ObjectOutput objectOutput = CodecSupport.getSerialization(channel.getUrl()).serialize(channel.getUrl(), output); objectOutput.writeObject(message); objectOutput.flushBuffer(); } } public Object decode(Channel channel, InputStream is) throws IOException { int readable = is.available(); byte[] message = new byte[readable]; is.read(message); return decode(channel, is, readable, message); } @SuppressWarnings("unchecked") protected Object decode(Channel channel, InputStream is, int readable, byte[] message) throws IOException { if (isClientSide(channel)) { return toString(message, getCharset(channel)); } checkPayload(channel, readable); if (message == null || message.length == 0) { return NEED_MORE_INPUT; } if (message[message.length - 1] == '\b') { // Windows backspace echo try { boolean doublechar = message.length >= 3 && message[message.length - 3] < 0; // double byte char channel.send(new String( doublechar ? new byte[] {32, 32, 8, 8} : new byte[] {32, 8}, getCharset(channel).name())); } catch (RemotingException e) { throw new IOException(StringUtils.toString(e)); } return NEED_MORE_INPUT; } for (Object command : EXIT) { if (isEquals(message, (byte[]) command)) { if (logger.isInfoEnabled()) { logger.info(new Exception( "Close channel " + channel + " on exit command: " + Arrays.toString((byte[]) command))); } channel.close(); return null; } } boolean up = endsWith(message, UP); boolean down = endsWith(message, DOWN); if (up || down) { LinkedList<String> history = (LinkedList<String>) channel.getAttribute(HISTORY_LIST_KEY); if (history == null || history.size() == 0) { return NEED_MORE_INPUT; } Integer index = (Integer) channel.getAttribute(HISTORY_INDEX_KEY); Integer old = index; if (index == null) { index = history.size() - 1; } else { if (up) { index = index - 1; if (index < 0) { index = history.size() - 1; } } else { index = index + 1; if (index > history.size() - 1) { index = 0; } } } if (old == null || !old.equals(index)) { channel.setAttribute(HISTORY_INDEX_KEY, index); String value = history.get(index); if (old != null && old >= 0 && old < history.size()) { String ov = history.get(old); StringBuilder buf = new StringBuilder(); for (int i = 0; i < ov.length(); i++) { buf.append('\b'); } for (int i = 0; i < ov.length(); i++) { buf.append(' '); } for (int i = 0; i < ov.length(); i++) { buf.append('\b'); } value = buf.toString() + value; } try { channel.send(value); } catch (RemotingException e) { throw new IOException(StringUtils.toString(e)); } } return NEED_MORE_INPUT; } for (Object command : EXIT) { if (isEquals(message, (byte[]) command)) { if (logger.isInfoEnabled()) { logger.info(new Exception("Close channel " + channel + " on exit command " + command)); } channel.close(); return null; } } byte[] enter = null; for (Object command : ENTER) { if (endsWith(message, (byte[]) command)) { enter = (byte[]) command; break; } } if (enter == null) { return NEED_MORE_INPUT; } LinkedList<String> history = (LinkedList<String>) channel.getAttribute(HISTORY_LIST_KEY); Integer index = (Integer) channel.getAttribute(HISTORY_INDEX_KEY); channel.removeAttribute(HISTORY_INDEX_KEY); if (history != null && history.size() > 0 && index != null && index >= 0 && index < history.size()) { String value = history.get(index); if (value != null) { byte[] b1 = value.getBytes(); if (message != null && message.length > 0) { byte[] b2 = new byte[b1.length + message.length]; System.arraycopy(b1, 0, b2, 0, b1.length); System.arraycopy(message, 0, b2, b1.length, message.length); message = b2; } else { message = b1; } } } String result = toString(message, getCharset(channel)); if (result != null && result.trim().length() > 0) { if (history == null) { history = new LinkedList<String>(); channel.setAttribute(HISTORY_LIST_KEY, history); } if (history.size() == 0) { history.addLast(result); } else if (!result.equals(history.getLast())) { history.remove(result); history.addLast(result); if (history.size() > 10) { history.removeFirst(); } } } return result; } }
7,417
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/CodecAdapterTest.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.codec; import org.apache.dubbo.remoting.transport.codec.CodecAdapter; import org.junit.jupiter.api.BeforeEach; class CodecAdapterTest extends ExchangeCodecTest { @BeforeEach public void setUp() throws Exception { codec = new CodecAdapter(new DeprecatedExchangeCodec()); } }
7,418
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/AbstractMockChannel.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.codec; import org.apache.dubbo.common.URL; 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 java.net.InetSocketAddress; import java.util.HashMap; import java.util.Map; public class AbstractMockChannel implements Channel { public static final String LOCAL_ADDRESS = "local"; public static final String REMOTE_ADDRESS = "remote"; public static final String ERROR_WHEN_SEND = "error_when_send"; InetSocketAddress localAddress; InetSocketAddress remoteAddress; private URL remoteUrl; private ChannelHandler handler; private boolean isClosed; private volatile boolean closing; private Map<String, Object> attributes = new HashMap<String, Object>(1); private volatile Object receivedMessage = null; public AbstractMockChannel() {} public AbstractMockChannel(URL remoteUrl) { this.remoteUrl = remoteUrl; this.remoteAddress = NetUtils.toAddress(remoteUrl.getParameter(REMOTE_ADDRESS)); this.localAddress = NetUtils.toAddress(remoteUrl.getParameter(LOCAL_ADDRESS)); } public AbstractMockChannel(ChannelHandler handler) { this.handler = handler; } @Override public URL getUrl() { return remoteUrl; } @Override public ChannelHandler getChannelHandler() { return handler; } @Override public InetSocketAddress getLocalAddress() { return localAddress; } @Override public void send(Object message) throws RemotingException { if (remoteUrl.getParameter(ERROR_WHEN_SEND, Boolean.FALSE)) { receivedMessage = null; throw new RemotingException(localAddress, remoteAddress, "mock error"); } else { receivedMessage = message; } } @Override public void send(Object message, boolean sent) throws RemotingException { send(message); } @Override public void close() { close(0); } @Override public void close(int timeout) { isClosed = true; } @Override public void startClose() { closing = true; } @Override public boolean isClosed() { return isClosed; } @Override public InetSocketAddress getRemoteAddress() { return remoteAddress; } @Override public boolean isConnected() { return isClosed; } @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) { attributes.put(key, value); } @Override public void removeAttribute(String key) { attributes.remove(key); } public Object getReceivedMessage() { return receivedMessage; } }
7,419
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/TelnetCodecTest.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.codec; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.Codec2; import org.apache.dubbo.remoting.buffer.ChannelBuffer; import org.apache.dubbo.remoting.buffer.ChannelBuffers; import org.apache.dubbo.remoting.telnet.codec.TelnetCodec; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class TelnetCodecTest { protected Codec2 codec; byte[] UP = new byte[] {27, 91, 65}; byte[] DOWN = new byte[] {27, 91, 66}; // ====================================================== URL url = URL.valueOf("dubbo://10.20.30.40:20880"); /** * @throws java.lang.Exception */ @BeforeEach public void setUp() throws Exception { codec = new TelnetCodec(); } protected AbstractMockChannel getServerSideChannel(URL url) { url = url.addParameter(AbstractMockChannel.LOCAL_ADDRESS, url.getAddress()) .addParameter(AbstractMockChannel.REMOTE_ADDRESS, "127.0.0.1:12345"); AbstractMockChannel channel = new AbstractMockChannel(url); return channel; } protected AbstractMockChannel getClientSideChannel(URL url) { url = url.addParameter(AbstractMockChannel.LOCAL_ADDRESS, "127.0.0.1:12345") .addParameter(AbstractMockChannel.REMOTE_ADDRESS, url.getAddress()); AbstractMockChannel channel = new AbstractMockChannel(url); return channel; } protected byte[] join(byte[] in1, byte[] in2) { byte[] ret = new byte[in1.length + in2.length]; System.arraycopy(in1, 0, ret, 0, in1.length); System.arraycopy(in2, 0, ret, in1.length, in2.length); return ret; } protected byte[] objectToByte(Object obj) { byte[] bytes; if (obj instanceof String) { bytes = ((String) obj).getBytes(); } else if (obj instanceof byte[]) { bytes = (byte[]) obj; } else { try { // object to bytearray ByteArrayOutputStream bo = new ByteArrayOutputStream(); ObjectOutputStream oo = new ObjectOutputStream(bo); oo.writeObject(obj); bytes = bo.toByteArray(); bo.close(); oo.close(); } catch (Exception e) { throw new RuntimeException(e); } } return bytes; } protected Object byteToObject(byte[] objBytes) throws Exception { if (objBytes == null || objBytes.length == 0) { return null; } ByteArrayInputStream bi = new ByteArrayInputStream(objBytes); ObjectInputStream oi = new ObjectInputStream(bi); return oi.readObject(); } protected void testDecode_assertEquals(byte[] request, Object ret) throws IOException { testDecode_assertEquals(request, ret, true); } protected void testDecode_assertEquals(byte[] request, Object ret, boolean isServerside) throws IOException { // init channel Channel channel = isServerside ? getServerSideChannel(url) : getClientSideChannel(url); // init request string ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(request); // decode Object obj = codec.decode(channel, buffer); Assertions.assertEquals(ret, obj); } protected void testEecode_assertEquals(Object request, byte[] ret, boolean isServerside) throws IOException { // init channel Channel channel = isServerside ? getServerSideChannel(url) : getClientSideChannel(url); ChannelBuffer buffer = ChannelBuffers.dynamicBuffer(1024); codec.encode(channel, buffer, request); byte[] data = new byte[buffer.readableBytes()]; buffer.readBytes(data); Assertions.assertEquals(ret.length, data.length); for (int i = 0; i < ret.length; i++) { if (ret[i] != data[i]) { Assertions.fail(); } } } protected void testDecode_assertEquals(Object request, Object ret) throws IOException { testDecode_assertEquals(request, ret, null); } private void testDecode_assertEquals(Object request, Object ret, Object channelReceive) throws IOException { testDecode_assertEquals(null, request, ret, channelReceive); } private void testDecode_assertEquals( AbstractMockChannel channel, Object request, Object expectRet, Object channelReceive) throws IOException { // init channel if (channel == null) { channel = getServerSideChannel(url); } byte[] buf = objectToByte(request); ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(buf); // decode Object obj = codec.decode(channel, buffer); Assertions.assertEquals(expectRet, obj); Assertions.assertEquals(channelReceive, channel.getReceivedMessage()); } private void testDecode_PersonWithEnterByte(byte[] enterBytes, boolean isNeedMore) throws IOException { // init channel Channel channel = getServerSideChannel(url); // init request string Person request = new Person(); byte[] newBuf = join(objectToByte(request), enterBytes); ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(newBuf); // decode Object obj = codec.decode(channel, buffer); if (isNeedMore) { Assertions.assertEquals(Codec2.DecodeResult.NEED_MORE_INPUT, obj); } else { Assertions.assertTrue(obj instanceof String, "return must string "); } } private void testDecode_WithExitByte(byte[] exitbytes, boolean isChannelClose) throws IOException { // init channel Channel channel = getServerSideChannel(url); ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(exitbytes); // decode codec.decode(channel, buffer); Assertions.assertEquals(isChannelClose, channel.isClosed()); } @Test void testDecode_String_ClientSide() throws IOException { testDecode_assertEquals("aaa".getBytes(), "aaa", false); } @Test void testDecode_BlankMessage() throws IOException { testDecode_assertEquals(new byte[] {}, Codec2.DecodeResult.NEED_MORE_INPUT); } @Test void testDecode_String_NoEnter() throws IOException { testDecode_assertEquals("aaa", Codec2.DecodeResult.NEED_MORE_INPUT); } @Test void testDecode_String_WithEnter() throws IOException { testDecode_assertEquals("aaa\n", "aaa"); } @Test void testDecode_String_MiddleWithEnter() throws IOException { testDecode_assertEquals("aaa\r\naaa", Codec2.DecodeResult.NEED_MORE_INPUT); } @Test void testDecode_Person_ObjectOnly() throws IOException { testDecode_assertEquals(new Person(), Codec2.DecodeResult.NEED_MORE_INPUT); } @Test void testDecode_Person_WithEnter() throws IOException { testDecode_PersonWithEnterByte(new byte[] {'\r', '\n'}, false); // windows end testDecode_PersonWithEnterByte(new byte[] {'\n', '\r'}, true); testDecode_PersonWithEnterByte(new byte[] {'\n'}, false); // linux end testDecode_PersonWithEnterByte(new byte[] {'\r'}, true); testDecode_PersonWithEnterByte(new byte[] {'\r', 100}, true); } @Test void testDecode_WithExitByte() throws IOException { HashMap<byte[], Boolean> exitBytes = new HashMap<byte[], Boolean>(); exitBytes.put(new byte[] {3}, true); /* Windows Ctrl+C */ exitBytes.put(new byte[] {1, 3}, false); // must equal the bytes exitBytes.put(new byte[] {-1, -12, -1, -3, 6}, true); /* Linux Ctrl+C */ exitBytes.put(new byte[] {1, -1, -12, -1, -3, 6}, false); // must equal the bytes exitBytes.put(new byte[] {-1, -19, -1, -3, 6}, true); /* Linux Pause */ for (Map.Entry<byte[], Boolean> entry : exitBytes.entrySet()) { testDecode_WithExitByte(entry.getKey(), entry.getValue()); } } @Test void testDecode_Backspace() throws IOException { // 32 8 first add space and then add backspace. testDecode_assertEquals(new byte[] {'\b'}, Codec2.DecodeResult.NEED_MORE_INPUT, new String(new byte[] {32, 8})); // test chinese byte[] chineseBytes = "中".getBytes(); byte[] request = join(chineseBytes, new byte[] {'\b'}); testDecode_assertEquals(request, Codec2.DecodeResult.NEED_MORE_INPUT, new String(new byte[] {32, 32, 8, 8})); // There may be some problem handling chinese (negative number recognition). Ignoring this problem, the // backspace key is only meaningfully input in a real telnet program. testDecode_assertEquals( new byte[] {'a', 'x', -1, 'x', '\b'}, Codec2.DecodeResult.NEED_MORE_INPUT, new String(new byte[] {32, 32, 8, 8})); } @Test void testDecode_Backspace_WithError() throws IOException { Assertions.assertThrows(IOException.class, () -> { url = url.addParameter(AbstractMockChannel.ERROR_WHEN_SEND, Boolean.TRUE.toString()); testDecode_Backspace(); url = url.removeParameter(AbstractMockChannel.ERROR_WHEN_SEND); }); } @Test void testDecode_History_UP() throws IOException { // init channel AbstractMockChannel channel = getServerSideChannel(url); testDecode_assertEquals(channel, UP, Codec2.DecodeResult.NEED_MORE_INPUT, null); String request1 = "aaa\n"; Object expected1 = "aaa"; // init history testDecode_assertEquals(channel, request1, expected1, null); testDecode_assertEquals(channel, UP, Codec2.DecodeResult.NEED_MORE_INPUT, expected1); } @Test void testDecode_UPorDOWN_WithError() throws IOException { Assertions.assertThrows(IOException.class, () -> { url = url.addParameter(AbstractMockChannel.ERROR_WHEN_SEND, Boolean.TRUE.toString()); // init channel AbstractMockChannel channel = getServerSideChannel(url); testDecode_assertEquals(channel, UP, Codec2.DecodeResult.NEED_MORE_INPUT, null); String request1 = "aaa\n"; Object expected1 = "aaa"; // init history testDecode_assertEquals(channel, request1, expected1, null); testDecode_assertEquals(channel, UP, Codec2.DecodeResult.NEED_MORE_INPUT, expected1); url = url.removeParameter(AbstractMockChannel.ERROR_WHEN_SEND); }); } // ============================================================================================================================= @Test void testEncode_String_ClientSide() throws IOException { testEecode_assertEquals("aaa", "aaa\r\n".getBytes(), false); } /*@Test public void testDecode_History_UP_DOWN_MULTI() throws IOException{ AbstractMockChannel channel = getServerSideChannel(url); String request1 = "aaa\n"; Object expected1 = request1.replace("\n", ""); //init history testDecode_assertEquals(channel, request1, expected1, null); String request2 = "bbb\n"; Object expected2 = request2.replace("\n", ""); //init history testDecode_assertEquals(channel, request2, expected2, null); String request3 = "ccc\n"; Object expected3= request3.replace("\n", ""); //init history testDecode_assertEquals(channel, request3, expected3, null); byte[] UP = new byte[] {27, 91, 65}; byte[] DOWN = new byte[] {27, 91, 66}; //history[aaa,bbb,ccc] testDecode_assertEquals(channel, UP, Codec.NEED_MORE_INPUT, expected3); testDecode_assertEquals(channel, DOWN, Codec.NEED_MORE_INPUT, expected3); testDecode_assertEquals(channel, UP, Codec.NEED_MORE_INPUT, expected2); testDecode_assertEquals(channel, UP, Codec.NEED_MORE_INPUT, expected1); testDecode_assertEquals(channel, UP, Codec.NEED_MORE_INPUT, expected1); testDecode_assertEquals(channel, UP, Codec.NEED_MORE_INPUT, expected1); testDecode_assertEquals(channel, DOWN, Codec.NEED_MORE_INPUT, expected2); testDecode_assertEquals(channel, DOWN, Codec.NEED_MORE_INPUT, expected3); testDecode_assertEquals(channel, DOWN, Codec.NEED_MORE_INPUT, expected3); testDecode_assertEquals(channel, DOWN, Codec.NEED_MORE_INPUT, expected3); testDecode_assertEquals(channel, UP, Codec.NEED_MORE_INPUT, expected2); }*/ // ====================================================== public static class Person implements Serializable { private static final long serialVersionUID = 3362088148941547337L; public String name; public String sex; @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((sex == null) ? 0 : sex.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Person other = (Person) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (sex == null) { if (other.sex != null) return false; } else if (!sex.equals(other.sex)) return false; return true; } } }
7,420
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/DeprecatedExchangeCodec.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.codec; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.io.Bytes; import org.apache.dubbo.common.io.StreamUtils; import org.apache.dubbo.common.io.UnsafeByteArrayInputStream; import org.apache.dubbo.common.io.UnsafeByteArrayOutputStream; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; import org.apache.dubbo.common.serialize.Serialization; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.Codec; 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.CodecSupport; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_RESPONSE; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_SKIP_UNUSED_STREAM; final class DeprecatedExchangeCodec extends DeprecatedTelnetCodec implements Codec { // header length. protected static final int HEADER_LENGTH = 16; // magic header. protected static final short MAGIC = (short) 0xdabb; protected static final byte MAGIC_HIGH = Bytes.short2bytes(MAGIC)[0]; protected static final byte MAGIC_LOW = Bytes.short2bytes(MAGIC)[1]; // message flag. protected static final byte FLAG_REQUEST = (byte) 0x80; protected static final byte FLAG_TWOWAY = (byte) 0x40; protected static final byte FLAG_EVENT = (byte) 0x20; protected static final int SERIALIZATION_MASK = 0x1f; private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DeprecatedExchangeCodec.class); public Short getMagicCode() { return MAGIC; } public void encode(Channel channel, OutputStream os, Object msg) throws IOException { if (msg instanceof Request) { encodeRequest(channel, os, (Request) msg); } else if (msg instanceof Response) { encodeResponse(channel, os, (Response) msg); } else { super.encode(channel, os, msg); } } public Object decode(Channel channel, InputStream is) throws IOException { int readable = is.available(); byte[] header = new byte[Math.min(readable, HEADER_LENGTH)]; is.read(header); return decode(channel, is, readable, header); } protected Object decode(Channel channel, InputStream is, int readable, byte[] header) throws IOException { // check magic number. if (readable > 0 && header[0] != MAGIC_HIGH || readable > 1 && header[1] != MAGIC_LOW) { int length = header.length; if (header.length < readable) { header = Bytes.copyOf(header, readable); is.read(header, length, readable - length); } for (int i = 1; i < header.length - 1; i++) { if (header[i] == MAGIC_HIGH && header[i + 1] == MAGIC_LOW) { UnsafeByteArrayInputStream bis = ((UnsafeByteArrayInputStream) is); bis.position(bis.position() - header.length + i); header = Bytes.copyOf(header, i); break; } } return super.decode(channel, is, readable, header); } // check length. if (readable < HEADER_LENGTH) { return NEED_MORE_INPUT; } // get data length. int len = Bytes.bytes2int(header, 12); checkPayload(channel, len); int tt = len + HEADER_LENGTH; if (readable < tt) { return NEED_MORE_INPUT; } // limit input stream. if (readable != tt) is = StreamUtils.limitedInputStream(is, len); try { return decodeBody(channel, is, header); } finally { if (is.available() > 0) { try { if (logger.isWarnEnabled()) { logger.warn(TRANSPORT_SKIP_UNUSED_STREAM, "", "", "Skip input stream " + is.available()); } StreamUtils.skipUnusedStream(is); } catch (IOException e) { logger.warn(TRANSPORT_SKIP_UNUSED_STREAM, "", "", e.getMessage(), e); } } } } protected Object decodeBody(Channel channel, InputStream is, byte[] header) throws IOException { byte flag = header[2], proto = (byte) (flag & SERIALIZATION_MASK); // get request id. long id = Bytes.bytes2long(header, 4); if ((flag & FLAG_REQUEST) == 0) { // decode response. Response res = new Response(id); if ((flag & FLAG_EVENT) != 0) { res.setEvent(true); } // get status. byte status = header[3]; res.setStatus(status); try { ObjectInput in = CodecSupport.deserialize(channel.getUrl(), is, proto); if (status == Response.OK) { Object data; if (res.isHeartbeat()) { data = decodeHeartbeatData(channel, in); } else if (res.isEvent()) { data = decodeEventData(channel, in); } else { data = decodeResponseData(channel, in, getRequestData(id)); } res.setResult(data); } else { res.setErrorMessage(in.readUTF()); } } catch (Throwable t) { res.setStatus(Response.CLIENT_ERROR); res.setErrorMessage(StringUtils.toString(t)); } return res; } else { // decode request. Request req = new Request(id); req.setVersion(Version.getProtocolVersion()); req.setTwoWay((flag & FLAG_TWOWAY) != 0); if ((flag & FLAG_EVENT) != 0) { req.setEvent(true); } try { ObjectInput in = CodecSupport.deserialize(channel.getUrl(), is, proto); Object data; if (req.isHeartbeat()) { data = decodeHeartbeatData(channel, in); } else if (req.isEvent()) { data = decodeEventData(channel, in); } else { data = decodeRequestData(channel, in); } req.setData(data); } catch (Throwable t) { // bad request req.setBroken(true); req.setData(t); } return req; } } protected Object getRequestData(long id) { DefaultFuture future = DefaultFuture.getFuture(id); if (future == null) return null; Request req = future.getRequest(); if (req == null) return null; return req.getData(); } protected void encodeRequest(Channel channel, OutputStream os, Request req) throws IOException { Serialization serialization = CodecSupport.getSerialization(channel.getUrl()); // header. byte[] header = new byte[HEADER_LENGTH]; // set magic number. Bytes.short2bytes(MAGIC, header); // set request and serialization flag. header[2] = (byte) (FLAG_REQUEST | serialization.getContentTypeId()); if (req.isTwoWay()) header[2] |= FLAG_TWOWAY; if (req.isEvent()) header[2] |= FLAG_EVENT; // set request id. Bytes.long2bytes(req.getId(), header, 4); // encode request data. UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(1024); ObjectOutput out = serialization.serialize(channel.getUrl(), bos); if (req.isEvent()) { encodeEventData(channel, out, req.getData()); } else { encodeRequestData(channel, out, req.getData()); } out.flushBuffer(); bos.flush(); bos.close(); byte[] data = bos.toByteArray(); checkPayload(channel, data.length); Bytes.int2bytes(data.length, header, 12); // write os.write(header); // write header. os.write(data); // write data. } protected void encodeResponse(Channel channel, OutputStream os, Response res) throws IOException { try { Serialization serialization = CodecSupport.getSerialization(channel.getUrl()); // header. byte[] header = new byte[HEADER_LENGTH]; // set magic number. Bytes.short2bytes(MAGIC, header); // set request and serialization flag. header[2] = serialization.getContentTypeId(); if (res.isHeartbeat()) header[2] |= FLAG_EVENT; // set response status. byte status = res.getStatus(); header[3] = status; // set request id. Bytes.long2bytes(res.getId(), header, 4); UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(1024); ObjectOutput out = serialization.serialize(channel.getUrl(), bos); // encode response data or error message. if (status == Response.OK) { if (res.isHeartbeat()) { encodeHeartbeatData(channel, out, res.getResult()); } else { encodeResponseData(channel, out, res.getResult()); } } else out.writeUTF(res.getErrorMessage()); out.flushBuffer(); bos.flush(); bos.close(); byte[] data = bos.toByteArray(); checkPayload(channel, data.length); Bytes.int2bytes(data.length, header, 12); // write os.write(header); // write header. os.write(data); // write data. } catch (Throwable t) { // send error message to Consumer, otherwise, Consumer will wait until timeout. if (!res.isEvent() && res.getStatus() != Response.BAD_RESPONSE) { try { // FIXME log error info in Codec and put all error handle logic in IoHanndler? logger.warn( TRANSPORT_FAILED_RESPONSE, "", "", "Fail to encode response: " + res + ", send bad_response info instead, cause: " + t.getMessage(), t); Response r = new Response(res.getId(), res.getVersion()); if (t instanceof IOException) { r.setStatus(Response.SERIALIZATION_ERROR); } else { r.setStatus(Response.BAD_RESPONSE); } r.setErrorMessage("Failed to send response: " + res + ", cause: " + StringUtils.toString(t)); channel.send(r); return; } catch (RemotingException e) { logger.warn( TRANSPORT_FAILED_RESPONSE, "", "", "Failed to send bad_response info back: " + res + ", cause: " + e.getMessage(), e); } } // Rethrow exception if (t instanceof IOException) { throw (IOException) t; } else if (t instanceof RuntimeException) { throw (RuntimeException) t; } else if (t instanceof Error) { throw (Error) t; } else { throw new RuntimeException(t.getMessage(), t); } } } protected Object decodeData(ObjectInput in) throws IOException { return decodeRequestData(in); } @Deprecated protected Object decodeHeartbeatData(ObjectInput in) throws IOException { try { return in.readObject(); } catch (ClassNotFoundException e) { throw new IOException(StringUtils.toString("Read object failed.", e)); } } protected Object decodeRequestData(ObjectInput in) throws IOException { try { return in.readObject(); } catch (ClassNotFoundException e) { throw new IOException(StringUtils.toString("Read object failed.", e)); } } protected Object decodeResponseData(ObjectInput in) throws IOException { try { return in.readObject(); } catch (ClassNotFoundException e) { throw new IOException(StringUtils.toString("Read object failed.", e)); } } protected void encodeData(ObjectOutput out, Object data) throws IOException { encodeRequestData(out, data); } private void encodeEventData(ObjectOutput out, Object data) throws IOException { out.writeObject(data); } @Deprecated protected void encodeHeartbeatData(ObjectOutput out, Object data) throws IOException { encodeEventData(out, data); } protected void encodeRequestData(ObjectOutput out, Object data) throws IOException { out.writeObject(data); } protected void encodeResponseData(ObjectOutput out, Object data) throws IOException { out.writeObject(data); } protected Object decodeData(Channel channel, ObjectInput in) throws IOException { return decodeRequestData(channel, in); } protected Object decodeEventData(Channel channel, ObjectInput in) throws IOException { try { return in.readObject(); } catch (ClassNotFoundException e) { throw new IOException(StringUtils.toString("Read object failed.", e)); } } @Deprecated protected Object decodeHeartbeatData(Channel channel, ObjectInput in) throws IOException { try { return in.readObject(); } catch (ClassNotFoundException e) { throw new IOException(StringUtils.toString("Read object failed.", e)); } } protected Object decodeRequestData(Channel channel, ObjectInput in) throws IOException { return decodeRequestData(in); } protected Object decodeResponseData(Channel channel, ObjectInput in) throws IOException { return decodeResponseData(in); } protected Object decodeResponseData(Channel channel, ObjectInput in, Object requestData) throws IOException { return decodeResponseData(channel, in); } protected void encodeData(Channel channel, ObjectOutput out, Object data) throws IOException { encodeRequestData(channel, out, data); } private void encodeEventData(Channel channel, ObjectOutput out, Object data) throws IOException { encodeEventData(out, data); } @Deprecated protected void encodeHeartbeatData(Channel channel, ObjectOutput out, Object data) throws IOException { encodeHeartbeatData(out, data); } protected void encodeRequestData(Channel channel, ObjectOutput out, Object data) throws IOException { encodeRequestData(out, data); } protected void encodeResponseData(Channel channel, ObjectOutput out, Object data) throws IOException { encodeResponseData(out, data); } }
7,421
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/ExchangeCodecTest.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.codec; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.io.Bytes; import org.apache.dubbo.common.io.UnsafeByteArrayOutputStream; import org.apache.dubbo.common.serialize.ObjectOutput; import org.apache.dubbo.common.serialize.Serialization; import org.apache.dubbo.common.serialize.support.DefaultSerializationSelector; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.buffer.ChannelBuffer; import org.apache.dubbo.remoting.buffer.ChannelBuffers; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.Response; import org.apache.dubbo.remoting.exchange.codec.ExchangeCodec; import org.apache.dubbo.remoting.exchange.support.DefaultFuture; import org.apache.dubbo.remoting.telnet.codec.TelnetCodec; import org.apache.dubbo.rpc.model.FrameworkModel; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.apache.dubbo.common.constants.CommonConstants.READONLY_EVENT; /** * * byte 16 * 0-1 magic code * 2 flag * 8 - 1-request/0-response * 7 - two way * 6 - heartbeat * 1-5 serialization id * 3 status * 20 ok * 90 error? * 4-11 id (long) * 12 -15 datalength */ class ExchangeCodecTest extends TelnetCodecTest { // magic header. private static final short MAGIC = (short) 0xdabb; private static final byte MAGIC_HIGH = (byte) Bytes.short2bytes(MAGIC)[0]; private static final byte MAGIC_LOW = (byte) Bytes.short2bytes(MAGIC)[1]; Serialization serialization = getSerialization(DefaultSerializationSelector.getDefaultRemotingSerialization()); private static final byte SERIALIZATION_BYTE = FrameworkModel.defaultModel() .getExtension(Serialization.class, DefaultSerializationSelector.getDefaultRemotingSerialization()) .getContentTypeId(); private static Serialization getSerialization(String name) { Serialization serialization = ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(name); return serialization; } private Object decode(byte[] request) throws IOException { ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(request); AbstractMockChannel channel = getServerSideChannel(url); // decode Object obj = codec.decode(channel, buffer); return obj; } private byte[] getRequestBytes(Object obj, byte[] header) throws IOException { // encode request data. UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(1024); ObjectOutput out = serialization.serialize(url, bos); out.writeObject(obj); out.flushBuffer(); bos.flush(); bos.close(); byte[] data = bos.toByteArray(); byte[] len = Bytes.int2bytes(data.length); System.arraycopy(len, 0, header, 12, 4); byte[] request = join(header, data); return request; } private byte[] getReadonlyEventRequestBytes(Object obj, byte[] header) throws IOException { // encode request data. UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(1024); ObjectOutput out = serialization.serialize(url, bos); out.writeObject(obj); out.flushBuffer(); bos.flush(); bos.close(); byte[] data = bos.toByteArray(); // byte[] len = Bytes.int2bytes(data.length); System.arraycopy(data, 0, header, 12, data.length); byte[] request = join(header, data); return request; } private byte[] assemblyDataProtocol(byte[] header) { Person request = new Person(); byte[] newbuf = join(header, objectToByte(request)); return newbuf; } // =================================================================================== @BeforeEach public void setUp() throws Exception { codec = new ExchangeCodec(); } @Test void test_Decode_Error_MagicNum() throws IOException { HashMap<byte[], Object> inputBytes = new HashMap<byte[], Object>(); inputBytes.put(new byte[] {0}, TelnetCodec.DecodeResult.NEED_MORE_INPUT); inputBytes.put(new byte[] {MAGIC_HIGH, 0}, TelnetCodec.DecodeResult.NEED_MORE_INPUT); inputBytes.put(new byte[] {0, MAGIC_LOW}, TelnetCodec.DecodeResult.NEED_MORE_INPUT); for (Map.Entry<byte[], Object> entry : inputBytes.entrySet()) { testDecode_assertEquals(assemblyDataProtocol(entry.getKey()), entry.getValue()); } } @Test void test_Decode_Error_Length() throws IOException { DefaultFuture future = DefaultFuture.newFuture(Mockito.mock(Channel.class), new Request(0), 100000, null); byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, SERIALIZATION_BYTE, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; Person person = new Person(); byte[] request = getRequestBytes(person, header); Channel channel = getServerSideChannel(url); byte[] baddata = new byte[] {1, 2}; ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(join(request, baddata)); Response obj = (Response) codec.decode(channel, buffer); Assertions.assertEquals(person, obj.getResult()); // only decode necessary bytes Assertions.assertEquals(request.length, buffer.readerIndex()); future.cancel(); } @Test void test_Decode_Error_Response_Object() throws IOException { // 00000010-response/oneway/hearbeat=true |20-stats=ok|id=0|length=0 byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, SERIALIZATION_BYTE, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; Person person = new Person(); byte[] request = getRequestBytes(person, header); // bad object byte[] badbytes = new byte[] {-1, -2, -3, -4, -3, -4, -3, -4, -3, -4, -3, -4}; System.arraycopy(badbytes, 0, request, 21, badbytes.length); Response obj = (Response) decode(request); Assertions.assertEquals(90, obj.getStatus()); } @Test void testInvalidSerializaitonId() throws Exception { byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, (byte) 0x8F, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; Object obj = decode(header); Assertions.assertTrue(obj instanceof Request); Request request = (Request) obj; Assertions.assertTrue(request.isBroken()); Assertions.assertTrue(request.getData() instanceof IOException); header = new byte[] {MAGIC_HIGH, MAGIC_LOW, (byte) 0x1F, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; obj = decode(header); Assertions.assertTrue(obj instanceof Response); Response response = (Response) obj; Assertions.assertEquals(response.getStatus(), Response.CLIENT_ERROR); Assertions.assertTrue(response.getErrorMessage().contains("IOException")); } @Test void test_Decode_Check_Payload() throws IOException { byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; byte[] request = assemblyDataProtocol(header); try { Channel channel = getServerSideChannel(url); ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(request); Object obj = codec.decode(channel, buffer); Assertions.assertTrue(obj instanceof Response); Assertions.assertTrue(((Response) obj) .getErrorMessage() .startsWith("Data length too large: " + Bytes.bytes2int(new byte[] {1, 1, 1, 1}))); } catch (IOException expected) { Assertions.assertTrue(expected.getMessage() .startsWith("Data length too large: " + Bytes.bytes2int(new byte[] {1, 1, 1, 1}))); } } @Test void test_Decode_Header_Need_Readmore() throws IOException { byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, 0, 0, 0, 0, 0, 0, 0, 0, 0}; testDecode_assertEquals(header, TelnetCodec.DecodeResult.NEED_MORE_INPUT); } @Test void test_Decode_Body_Need_Readmore() throws IOException { byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 'a', 'a'}; testDecode_assertEquals(header, TelnetCodec.DecodeResult.NEED_MORE_INPUT); } @Test void test_Decode_MigicCodec_Contain_ExchangeHeader() throws IOException { byte[] header = new byte[] {0, 0, MAGIC_HIGH, MAGIC_LOW, 0, 0, 0, 0, 0, 0, 0, 0, 0}; Channel channel = getServerSideChannel(url); ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(header); Object obj = codec.decode(channel, buffer); Assertions.assertEquals(TelnetCodec.DecodeResult.NEED_MORE_INPUT, obj); // If the telnet data and request data are in the same data packet, we should guarantee that the receipt of // request data won't be affected by the factor that telnet does not have an end characters. Assertions.assertEquals(2, buffer.readerIndex()); } @Test void test_Decode_Return_Response_Person() throws IOException { DefaultFuture future = DefaultFuture.newFuture(Mockito.mock(Channel.class), new Request(0), 100000, null); // 00000010-response/oneway/hearbeat=false/hessian |20-stats=ok|id=0|length=0 byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, SERIALIZATION_BYTE, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; Person person = new Person(); byte[] request = getRequestBytes(person, header); Response obj = (Response) decode(request); Assertions.assertEquals(20, obj.getStatus()); Assertions.assertEquals(person, obj.getResult()); System.out.println(obj); future.cancel(); } @Test // The status input has a problem, and the read information is wrong when the serialization is serialized. public void test_Decode_Return_Response_Error() throws IOException { byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, SERIALIZATION_BYTE, 90, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; String errorString = "encode request data error "; byte[] request = getRequestBytes(errorString, header); Response obj = (Response) decode(request); Assertions.assertEquals(90, obj.getStatus()); Assertions.assertEquals(errorString, obj.getErrorMessage()); } @Test @Disabled("Event should not be object.") void test_Decode_Return_Request_Event_Object() throws IOException { // |10011111|20-stats=ok|id=0|length=0 byte[] header = new byte[] { MAGIC_HIGH, MAGIC_LOW, (byte) (SERIALIZATION_BYTE | (byte) 0xe0), 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; Person person = new Person(); byte[] request = getRequestBytes(person, header); System.setProperty("deserialization.event.size", "100"); Request obj = (Request) decode(request); Assertions.assertEquals(person, obj.getData()); Assertions.assertTrue(obj.isTwoWay()); Assertions.assertTrue(obj.isEvent()); Assertions.assertEquals(Version.getProtocolVersion(), obj.getVersion()); System.out.println(obj); System.clearProperty("deserialization.event.size"); } @Test void test_Decode_Return_Request_Event_String() throws IOException { // |10011111|20-stats=ok|id=0|length=0 byte[] header = new byte[] { MAGIC_HIGH, MAGIC_LOW, (byte) (SERIALIZATION_BYTE | (byte) 0xe0), 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; String event = READONLY_EVENT; byte[] request = getRequestBytes(event, header); Request obj = (Request) decode(request); Assertions.assertEquals(event, obj.getData()); Assertions.assertTrue(obj.isTwoWay()); Assertions.assertTrue(obj.isEvent()); Assertions.assertEquals(Version.getProtocolVersion(), obj.getVersion()); System.out.println(obj); } @Test void test_Decode_Return_Request_Heartbeat_Object() throws IOException { // |10011111|20-stats=ok|id=0|length=0 byte[] header = new byte[] { MAGIC_HIGH, MAGIC_LOW, (byte) (SERIALIZATION_BYTE | (byte) 0xe0), 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; byte[] request = getRequestBytes(null, header); Request obj = (Request) decode(request); Assertions.assertNull(obj.getData()); Assertions.assertTrue(obj.isTwoWay()); Assertions.assertTrue(obj.isHeartbeat()); Assertions.assertEquals(Version.getProtocolVersion(), obj.getVersion()); System.out.println(obj); } @Test @Disabled("Event should not be object.") void test_Decode_Return_Request_Object() throws IOException { // |10011111|20-stats=ok|id=0|length=0 byte[] header = new byte[] { MAGIC_HIGH, MAGIC_LOW, (byte) (SERIALIZATION_BYTE | (byte) 0xe0), 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; Person person = new Person(); byte[] request = getRequestBytes(person, header); System.setProperty("deserialization.event.size", "100"); Request obj = (Request) decode(request); Assertions.assertEquals(person, obj.getData()); Assertions.assertTrue(obj.isTwoWay()); Assertions.assertFalse(obj.isHeartbeat()); Assertions.assertEquals(Version.getProtocolVersion(), obj.getVersion()); System.out.println(obj); System.clearProperty("deserialization.event.size"); } @Test void test_Decode_Error_Request_Object() throws IOException { // 00000010-response/oneway/hearbeat=true |20-stats=ok|id=0|length=0 byte[] header = new byte[] { MAGIC_HIGH, MAGIC_LOW, (byte) (SERIALIZATION_BYTE | (byte) 0xe0), 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; Person person = new Person(); byte[] request = getRequestBytes(person, header); // bad object byte[] badbytes = new byte[] {-1, -2, -3, -4, -3, -4, -3, -4, -3, -4, -3, -4}; System.arraycopy(badbytes, 0, request, 21, badbytes.length); Request obj = (Request) decode(request); Assertions.assertTrue(obj.isBroken()); Assertions.assertTrue(obj.getData() instanceof Throwable); } @Test void test_Header_Response_NoSerializationFlag() throws IOException { DefaultFuture future = DefaultFuture.newFuture(Mockito.mock(Channel.class), new Request(0), 100000, null); // 00000010-response/oneway/hearbeat=false/noset |20-stats=ok|id=0|length=0 byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, SERIALIZATION_BYTE, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; Person person = new Person(); byte[] request = getRequestBytes(person, header); Response obj = (Response) decode(request); Assertions.assertEquals(20, obj.getStatus()); Assertions.assertEquals(person, obj.getResult()); System.out.println(obj); future.cancel(); } @Test void test_Header_Response_Heartbeat() throws IOException { DefaultFuture future = DefaultFuture.newFuture(Mockito.mock(Channel.class), new Request(0), 100000, null); // 00000010-response/oneway/hearbeat=true |20-stats=ok|id=0|length=0 byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, SERIALIZATION_BYTE, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; Person person = new Person(); byte[] request = getRequestBytes(person, header); Response obj = (Response) decode(request); Assertions.assertEquals(20, obj.getStatus()); Assertions.assertEquals(person, obj.getResult()); System.out.println(obj); future.cancel(); } @Test void test_Encode_Request() throws IOException { ChannelBuffer encodeBuffer = ChannelBuffers.dynamicBuffer(2014); Channel channel = getClientSideChannel(url); Request request = new Request(); Person person = new Person(); request.setData(person); codec.encode(channel, encodeBuffer, request); // encode resault check need decode byte[] data = new byte[encodeBuffer.writerIndex()]; encodeBuffer.readBytes(data); ChannelBuffer decodeBuffer = ChannelBuffers.wrappedBuffer(data); Request obj = (Request) codec.decode(channel, decodeBuffer); Assertions.assertEquals(request.isBroken(), obj.isBroken()); Assertions.assertEquals(request.isHeartbeat(), obj.isHeartbeat()); Assertions.assertEquals(request.isTwoWay(), obj.isTwoWay()); Assertions.assertEquals(person, obj.getData()); } @Test @Disabled("Event should not be object.") void test_Encode_Response() throws IOException { DefaultFuture future = DefaultFuture.newFuture(Mockito.mock(Channel.class), new Request(1001), 100000, null); ChannelBuffer encodeBuffer = ChannelBuffers.dynamicBuffer(1024); Channel channel = getClientSideChannel(url); Response response = new Response(); response.setHeartbeat(true); response.setId(1001L); response.setStatus((byte) 20); response.setVersion("11"); Person person = new Person(); response.setResult(person); codec.encode(channel, encodeBuffer, response); byte[] data = new byte[encodeBuffer.writerIndex()]; encodeBuffer.readBytes(data); // encode resault check need decode ChannelBuffer decodeBuffer = ChannelBuffers.wrappedBuffer(data); Response obj = (Response) codec.decode(channel, decodeBuffer); Assertions.assertEquals(response.getId(), obj.getId()); Assertions.assertEquals(response.getStatus(), obj.getStatus()); Assertions.assertEquals(response.isHeartbeat(), obj.isHeartbeat()); Assertions.assertEquals(person, obj.getResult()); // encode response verson ?? // Assertions.assertEquals(response.getProtocolVersion(), obj.getVersion()); future.cancel(); } @Test void test_Encode_Error_Response() throws IOException { ChannelBuffer encodeBuffer = ChannelBuffers.dynamicBuffer(1024); Channel channel = getClientSideChannel(url); Response response = new Response(); response.setHeartbeat(true); response.setId(1001L); response.setStatus((byte) 10); response.setVersion("11"); String badString = "bad"; response.setErrorMessage(badString); Person person = new Person(); response.setResult(person); codec.encode(channel, encodeBuffer, response); byte[] data = new byte[encodeBuffer.writerIndex()]; encodeBuffer.readBytes(data); // encode resault check need decode ChannelBuffer decodeBuffer = ChannelBuffers.wrappedBuffer(data); Response obj = (Response) codec.decode(channel, decodeBuffer); Assertions.assertEquals(response.getId(), obj.getId()); Assertions.assertEquals(response.getStatus(), obj.getStatus()); Assertions.assertEquals(response.isHeartbeat(), obj.isHeartbeat()); Assertions.assertEquals(badString, obj.getErrorMessage()); Assertions.assertNull(obj.getResult()); // Assertions.assertEquals(response.getProtocolVersion(), obj.getVersion()); } @Test void testMessageLengthGreaterThanMessageActualLength() throws Exception { Channel channel = getClientSideChannel(url); Request request = new Request(1L); request.setVersion(Version.getProtocolVersion()); Date date = new Date(); request.setData(date); ChannelBuffer encodeBuffer = ChannelBuffers.dynamicBuffer(1024); codec.encode(channel, encodeBuffer, request); byte[] bytes = new byte[encodeBuffer.writerIndex()]; encodeBuffer.readBytes(bytes); int len = Bytes.bytes2int(bytes, 12); ByteArrayOutputStream out = new ByteArrayOutputStream(1024); out.write(bytes, 0, 12); /* * The fill length can not be less than 256, because by default, hessian reads 256 bytes from the stream each time. * Refer Hessian2Input.readBuffer for more details */ int padding = 512; out.write(Bytes.int2bytes(len + padding)); out.write(bytes, 16, bytes.length - 16); for (int i = 0; i < padding; i++) { out.write(1); } out.write(bytes); /* request|1111...|request */ ChannelBuffer decodeBuffer = ChannelBuffers.wrappedBuffer(out.toByteArray()); Request decodedRequest = (Request) codec.decode(channel, decodeBuffer); Assertions.assertEquals(date, decodedRequest.getData()); Assertions.assertEquals(bytes.length + padding, decodeBuffer.readerIndex()); decodedRequest = (Request) codec.decode(channel, decodeBuffer); Assertions.assertEquals(date, decodedRequest.getData()); } @Test void testMessageLengthExceedPayloadLimitWhenEncode() throws Exception { Request request = new Request(1L); request.setData("hello"); ChannelBuffer encodeBuffer = ChannelBuffers.dynamicBuffer(512); AbstractMockChannel channel = getClientSideChannel(url.addParameter(Constants.PAYLOAD_KEY, 4)); try { codec.encode(channel, encodeBuffer, request); Assertions.fail(); } catch (IOException e) { Assertions.assertTrue(e.getMessage().startsWith("Data length too large: ")); Assertions.assertTrue(e.getMessage() .contains("max payload: 4, channel: org.apache.dubbo.remoting.codec.AbstractMockChannel")); } Response response = new Response(1L); response.setResult("hello"); encodeBuffer = ChannelBuffers.dynamicBuffer(512); channel = getServerSideChannel(url.addParameter(Constants.PAYLOAD_KEY, 4)); codec.encode(channel, encodeBuffer, response); Assertions.assertTrue(channel.getReceivedMessage() instanceof Response); Response receiveMessage = (Response) channel.getReceivedMessage(); Assertions.assertEquals(Response.SERIALIZATION_ERROR, receiveMessage.getStatus()); Assertions.assertTrue(receiveMessage.getErrorMessage().contains("Data length too large: ")); } }
7,422
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/utils/PayloadDropperTest.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.utils; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.Response; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class PayloadDropperTest { @Test void test() { Request request = new Request(1); request.setData(new Object()); Request requestWithoutData = (Request) PayloadDropper.getRequestWithoutData(request); Assertions.assertEquals(requestWithoutData.getId(), request.getId()); Assertions.assertNull(requestWithoutData.getData()); Response response = new Response(1); response.setResult(new Object()); Response responseWithoutData = (Response) PayloadDropper.getRequestWithoutData(response); Assertions.assertEquals(responseWithoutData.getId(), response.getId()); Assertions.assertNull(responseWithoutData.getResult()); Object object = new Object(); Assertions.assertEquals(object, PayloadDropper.getRequestWithoutData(object)); } }
7,423
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/utils/UrlUtilsTest.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.utils; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.Constants; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class UrlUtilsTest { @Test void testGetIdleTimeout() { URL url1 = URL.valueOf("dubbo://127.0.0.1:12345?heartbeat=10000"); URL url2 = URL.valueOf("dubbo://127.0.0.1:12345?heartbeat=10000&heartbeat.timeout=50000"); URL url3 = URL.valueOf("dubbo://127.0.0.1:12345?heartbeat=10000&heartbeat.timeout=10000"); Assertions.assertEquals(UrlUtils.getIdleTimeout(url1), 30000); Assertions.assertEquals(UrlUtils.getIdleTimeout(url2), 50000); Assertions.assertThrows(RuntimeException.class, () -> UrlUtils.getIdleTimeout(url3)); } @Test void testGetHeartbeat() { URL url = URL.valueOf("dubbo://127.0.0.1:12345?heartbeat=10000"); Assertions.assertEquals(UrlUtils.getHeartbeat(url), 10000); } @Test void testConfiguredHeartbeat() { System.setProperty(Constants.HEARTBEAT_CONFIG_KEY, "200"); URL url = URL.valueOf("dubbo://127.0.0.1:12345"); Assertions.assertEquals(200, UrlUtils.getHeartbeat(url)); System.clearProperty(Constants.HEARTBEAT_CONFIG_KEY); } @Test void testGetCloseTimeout() { URL url1 = URL.valueOf("dubbo://127.0.0.1:12345?heartbeat=10000"); URL url2 = URL.valueOf("dubbo://127.0.0.1:12345?heartbeat=10000&heartbeat.timeout=50000"); URL url3 = URL.valueOf("dubbo://127.0.0.1:12345?heartbeat=10000&heartbeat.timeout=10000"); URL url4 = URL.valueOf("dubbo://127.0.0.1:12345?close.timeout=30000&heartbeat=10000&heartbeat.timeout=10000"); URL url5 = URL.valueOf("dubbo://127.0.0.1:12345?close.timeout=40000&heartbeat=10000&heartbeat.timeout=50000"); URL url6 = URL.valueOf("dubbo://127.0.0.1:12345?close.timeout=10000&heartbeat=10000&heartbeat.timeout=10000"); Assertions.assertEquals(30000, UrlUtils.getCloseTimeout(url1)); Assertions.assertEquals(50000, UrlUtils.getCloseTimeout(url2)); Assertions.assertThrows(RuntimeException.class, () -> UrlUtils.getCloseTimeout(url3)); Assertions.assertThrows(RuntimeException.class, () -> UrlUtils.getCloseTimeout(url4)); Assertions.assertEquals(40000, UrlUtils.getCloseTimeout(url5)); Assertions.assertThrows(RuntimeException.class, () -> UrlUtils.getCloseTimeout(url6)); } @Test void testConfiguredClose() { System.setProperty(Constants.CLOSE_TIMEOUT_CONFIG_KEY, "180000"); URL url = URL.valueOf("dubbo://127.0.0.1:12345"); Assertions.assertEquals(180000, UrlUtils.getCloseTimeout(url)); System.clearProperty(Constants.HEARTBEAT_CONFIG_KEY); } }
7,424
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/api/EmptyProtocol.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.api; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.api.pu.ChannelOperator; import org.apache.dubbo.remoting.api.ssl.ContextOperator; public class EmptyProtocol 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() {} }
7,425
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/TelnetUtilsTest.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.telnet; import org.apache.dubbo.remoting.telnet.support.TelnetUtils; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class TelnetUtilsTest { /** * abc - abc - abc * 1 - 2 - 3 * x - y - z */ @Test void testToList() { List<List<String>> table = new LinkedList<>(); table.add(Arrays.asList("abc", "abc", "abc")); table.add(Arrays.asList("1", "2", "3")); table.add(Arrays.asList("x", "y", "z")); String toList = TelnetUtils.toList(table); Assertions.assertTrue(toList.contains("abc - abc - abc")); Assertions.assertTrue(toList.contains("1 - 2 - 3")); Assertions.assertTrue(toList.contains("x - y - z")); } /** * +-----+-----+-----+ * | A | B | C | * +-----+-----+-----+ * | abc | abc | abc | * | 1 | 2 | 3 | * | x | y | z | * +-----+-----+-----+ */ @Test void testToTable() { List<List<String>> table = new LinkedList<>(); table.add(Arrays.asList("abc", "abc", "abc")); table.add(Arrays.asList("1", "2", "3")); table.add(Arrays.asList("x", "y", "z")); String toTable = TelnetUtils.toTable(new String[] {"A", "B", "C"}, table); Assertions.assertTrue(toTable.contains("| A | B | C |")); Assertions.assertTrue(toTable.contains("| abc | abc | abc |")); Assertions.assertTrue(toTable.contains("| 1 | 2 | 3 |")); Assertions.assertTrue(toTable.contains("| x | y | z |")); } }
7,426
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/support/StatusTelnetHandlerTest.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.telnet.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.telnet.support.command.StatusTelnetHandler; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; class StatusTelnetHandlerTest { @Test void test() { Channel channel = Mockito.mock(Channel.class); Mockito.when(channel.getUrl()).thenReturn(URL.valueOf("dubbo://127.0.0.1:12345")); StatusTelnetHandler statusTelnetHandler = new StatusTelnetHandler(); Assertions.assertNotNull(statusTelnetHandler.telnet(channel, "")); Assertions.assertNotNull(statusTelnetHandler.telnet(channel, "-l")); String errorPrompt = "Unsupported parameter "; Assertions.assertTrue(statusTelnetHandler.telnet(channel, "other").contains(errorPrompt)); Mockito.when(channel.getUrl()).thenReturn(URL.valueOf("dubbo://127.0.0.1:12345?status=load,memory")); Assertions.assertNotNull(statusTelnetHandler.telnet(channel, "")); Assertions.assertNotNull(statusTelnetHandler.telnet(channel, "-l")); } }
7,427
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/support/TelnetHandlerAdapterTest.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.telnet.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; class TelnetHandlerAdapterTest { @Test void testTelnet() throws RemotingException { Channel channel = Mockito.mock(Channel.class); Map<String, String> param = new HashMap<>(); param.put("telnet", "status"); URL url = new URL("p1", "127.0.0.1", 12345, "path1", param); Mockito.when(channel.getUrl()).thenReturn(url); TelnetHandlerAdapter telnetHandlerAdapter = new TelnetHandlerAdapter(FrameworkModel.defaultModel()); String message = "--no-prompt status "; String expectedResult = "OK\r\n"; Assertions.assertEquals(expectedResult, telnetHandlerAdapter.telnet(channel, message)); message = "--no-prompt status test"; expectedResult = "Unsupported parameter test for status.\r\n"; Assertions.assertEquals(expectedResult, telnetHandlerAdapter.telnet(channel, message)); message = "--no-prompt test"; expectedResult = "Unsupported command: test\r\n"; Assertions.assertEquals(expectedResult, telnetHandlerAdapter.telnet(channel, message)); message = "--no-prompt help"; expectedResult = "Command: help disabled for security reasons, please enable support by listing the commands through 'telnet'\r\n"; Assertions.assertEquals(expectedResult, telnetHandlerAdapter.telnet(channel, message)); message = "--no-prompt"; expectedResult = StringUtils.EMPTY_STRING; Assertions.assertEquals(expectedResult, telnetHandlerAdapter.telnet(channel, message)); message = "help"; expectedResult = "Command: help disabled for security reasons, please enable support by listing the commands through 'telnet'\r\ndubbo>"; Assertions.assertEquals(expectedResult, telnetHandlerAdapter.telnet(channel, message)); } }
7,428
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/support/ClearTelnetHandlerTest.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.telnet.support; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.telnet.support.command.ClearTelnetHandler; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; class ClearTelnetHandlerTest { @Test void test() { StringBuilder buf = new StringBuilder(); for (int i = 0; i < 50; i++) { buf.append("\r\n"); } ClearTelnetHandler telnetHandler = new ClearTelnetHandler(); Assertions.assertEquals(buf.toString(), telnetHandler.telnet(Mockito.mock(Channel.class), "50")); // Illegal Input Assertions.assertTrue( telnetHandler.telnet(Mockito.mock(Channel.class), "Illegal").contains("Illegal")); for (int i = 0; i < 50; i++) { buf.append("\r\n"); } Assertions.assertEquals(buf.toString(), telnetHandler.telnet(Mockito.mock(Channel.class), "")); } }
7,429
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/support/HelpTelnetHandlerTest.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.telnet.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.telnet.support.command.HelpTelnetHandler; import org.apache.dubbo.rpc.model.FrameworkModel; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; class HelpTelnetHandlerTest { @Test void test() { Channel channel = Mockito.mock(Channel.class); Mockito.when(channel.getUrl()).thenReturn(URL.valueOf("dubbo://127.0.0.1:12345")); HelpTelnetHandler helpTelnetHandler = new HelpTelnetHandler(FrameworkModel.defaultModel()); // default output String prompt = "Please input \"help [command]\" show detail.\r\n"; Assertions.assertTrue(helpTelnetHandler.telnet(channel, "").contains(prompt)); // "help" command output String demoOutput = "Command:\r\n" + " help [command]\r\n" + "Summary:\r\n" + " Show help.\r\n" + "Detail:\r\n" + " Show help."; Assertions.assertEquals(helpTelnetHandler.telnet(channel, "help"), demoOutput); } }
7,430
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/support/ExitTelnetHandlerTest.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.telnet.support; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.telnet.support.command.ExitTelnetHandler; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; class ExitTelnetHandlerTest { @Test void test() { Channel channel = Mockito.mock(Channel.class); ExitTelnetHandler exitTelnetHandler = new ExitTelnetHandler(); exitTelnetHandler.telnet(channel, null); verify(channel, times(1)).close(); } }
7,431
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/ChannelBufferFactoryTest.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; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * {@link DirectChannelBufferFactory} * {@link HeapChannelBufferFactory} */ class ChannelBufferFactoryTest { @Test void test() { ChannelBufferFactory directChannelBufferFactory = DirectChannelBufferFactory.getInstance(); ChannelBufferFactory heapChannelBufferFactory = HeapChannelBufferFactory.getInstance(); ChannelBuffer directBuffer1 = directChannelBufferFactory.getBuffer(16); ChannelBuffer directBuffer2 = directChannelBufferFactory.getBuffer(ByteBuffer.allocate(16)); ChannelBuffer directBuffer3 = directChannelBufferFactory.getBuffer(new byte[] {1}, 0, 1); Assertions.assertTrue(directBuffer1.isDirect()); Assertions.assertTrue(directBuffer2.isDirect()); Assertions.assertTrue(directBuffer3.isDirect()); ChannelBuffer heapBuffer1 = heapChannelBufferFactory.getBuffer(16); ChannelBuffer heapBuffer2 = heapChannelBufferFactory.getBuffer(ByteBuffer.allocate(16)); ChannelBuffer heapBuffer3 = heapChannelBufferFactory.getBuffer(new byte[] {1}, 0, 1); Assertions.assertTrue(heapBuffer1.hasArray()); Assertions.assertTrue(heapBuffer2.hasArray()); Assertions.assertTrue(heapBuffer3.hasArray()); } }
7,432
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/ChannelBufferStreamTest.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 org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; class ChannelBufferStreamTest { @Test void testChannelBufferOutputStreamWithNull() { assertThrows(NullPointerException.class, () -> new ChannelBufferOutputStream(null)); } @Test void testChannelBufferInputStreamWithNull() { assertThrows(NullPointerException.class, () -> new ChannelBufferInputStream(null)); } @Test void testChannelBufferInputStreamWithNullAndLength() { assertThrows(NullPointerException.class, () -> new ChannelBufferInputStream(null, 0)); } @Test void testChannelBufferInputStreamWithBadLength() { assertThrows(IllegalArgumentException.class, () -> new ChannelBufferInputStream(mock(ChannelBuffer.class), -1)); } @Test void testChannelBufferInputStreamWithOutOfBounds() { assertThrows(IndexOutOfBoundsException.class, () -> { ChannelBuffer buf = mock(ChannelBuffer.class); new ChannelBufferInputStream(buf, buf.capacity() + 1); }); } @Test void testChannelBufferWriteOutAndReadIn() { ChannelBuffer buf = ChannelBuffers.dynamicBuffer(); testChannelBufferOutputStream(buf); testChannelBufferInputStream(buf); } public void testChannelBufferOutputStream(final ChannelBuffer buf) { try (ChannelBufferOutputStream out = new ChannelBufferOutputStream(buf)) { assertSame(buf, out.buffer()); write(out); } catch (IOException ioe) { // ignored } } private void write(final ChannelBufferOutputStream out) throws IOException { out.write(new byte[0]); out.write(new byte[] {1, 2, 3, 4}); out.write(new byte[] {1, 3, 3, 4}, 0, 0); } public void testChannelBufferInputStream(final ChannelBuffer buf) { try (ChannelBufferInputStream in = new ChannelBufferInputStream(buf)) { assertTrue(in.markSupported()); in.mark(Integer.MAX_VALUE); assertEquals(buf.writerIndex(), in.skip(Long.MAX_VALUE)); assertFalse(buf.readable()); in.reset(); assertEquals(0, buf.readerIndex()); assertEquals(4, in.skip(4)); assertEquals(4, buf.readerIndex()); in.reset(); readBytes(in); assertEquals(buf.readerIndex(), in.readBytes()); } catch (IOException ioe) { // ignored } } private void readBytes(ChannelBufferInputStream in) throws IOException { byte[] tmp = new byte[13]; in.read(tmp); assertEquals(1, tmp[0]); assertEquals(2, tmp[1]); assertEquals(3, tmp[2]); assertEquals(4, tmp[3]); assertEquals(-1, in.read()); assertEquals(-1, in.read(tmp)); } }
7,433
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/DirectChannelBufferTest.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 org.junit.jupiter.api.Assertions; class DirectChannelBufferTest extends AbstractChannelBufferTest { private ChannelBuffer buffer; @Override protected ChannelBuffer newBuffer(int capacity) { buffer = ChannelBuffers.directBuffer(capacity); Assertions.assertEquals(0, buffer.writerIndex()); return buffer; } @Override protected ChannelBuffer[] components() { return new ChannelBuffer[] {buffer}; } }
7,434
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/DynamicChannelBufferTest.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.util.Random; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class DynamicChannelBufferTest extends AbstractChannelBufferTest { private ChannelBuffer buffer; @Override protected ChannelBuffer newBuffer(int length) { buffer = ChannelBuffers.dynamicBuffer(length); assertEquals(0, buffer.readerIndex()); assertEquals(0, buffer.writerIndex()); assertEquals(length, buffer.capacity()); return buffer; } @Override protected ChannelBuffer[] components() { return new ChannelBuffer[] {buffer}; } @Test void shouldNotFailOnInitialIndexUpdate() { new DynamicChannelBuffer(10).setIndex(0, 10); } @Test void shouldNotFailOnInitialIndexUpdate2() { new DynamicChannelBuffer(10).writerIndex(10); } @Test void shouldNotFailOnInitialIndexUpdate3() { ChannelBuffer buf = new DynamicChannelBuffer(10); buf.writerIndex(10); buf.readerIndex(10); } @Test void ensureWritableBytes() { ChannelBuffer buf = new DynamicChannelBuffer(16); buf.ensureWritableBytes(30); Assertions.assertEquals(buf.capacity(), 32); Random random = new Random(); byte[] bytes = new byte[126]; random.nextBytes(bytes); buf.writeBytes(bytes); Assertions.assertEquals(buf.capacity(), 128); } }
7,435
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/AbstractChannelBufferTest.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.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Random; 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.remoting.buffer.ChannelBuffers.directBuffer; import static org.apache.dubbo.remoting.buffer.ChannelBuffers.wrappedBuffer; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; public abstract class AbstractChannelBufferTest { private static final int CAPACITY = 4096; // Must be even private static final int BLOCK_SIZE = 128; private long seed; private Random random; private ChannelBuffer buffer; protected abstract ChannelBuffer newBuffer(int capacity); protected abstract ChannelBuffer[] components(); protected boolean discardReadBytesDoesNotMoveWritableBytes() { return true; } @BeforeEach public void init() { buffer = newBuffer(CAPACITY); seed = System.currentTimeMillis(); random = new Random(seed); } @AfterEach public void dispose() { buffer = null; } @Test void initialState() { assertEquals(CAPACITY, buffer.capacity()); assertEquals(0, buffer.readerIndex()); } @Test void readerIndexBoundaryCheck1() { Assertions.assertThrows(IndexOutOfBoundsException.class, () -> { try { buffer.writerIndex(0); } catch (IndexOutOfBoundsException e) { fail(); } buffer.readerIndex(-1); }); } @Test void readerIndexBoundaryCheck2() { Assertions.assertThrows(IndexOutOfBoundsException.class, () -> { try { buffer.writerIndex(buffer.capacity()); } catch (IndexOutOfBoundsException e) { fail(); } buffer.readerIndex(buffer.capacity() + 1); }); } @Test void readerIndexBoundaryCheck3() { Assertions.assertThrows(IndexOutOfBoundsException.class, () -> { try { buffer.writerIndex(CAPACITY / 2); } catch (IndexOutOfBoundsException e) { fail(); } buffer.readerIndex(CAPACITY * 3 / 2); }); } @Test void readerIndexBoundaryCheck4() { buffer.writerIndex(0); buffer.readerIndex(0); buffer.writerIndex(buffer.capacity()); buffer.readerIndex(buffer.capacity()); } @Test void writerIndexBoundaryCheck1() { Assertions.assertThrows(IndexOutOfBoundsException.class, () -> { buffer.writerIndex(-1); }); } @Test void writerIndexBoundaryCheck2() { Assertions.assertThrows(IndexOutOfBoundsException.class, () -> { try { buffer.writerIndex(CAPACITY); buffer.readerIndex(CAPACITY); } catch (IndexOutOfBoundsException e) { fail(); } buffer.writerIndex(buffer.capacity() + 1); }); } @Test void writerIndexBoundaryCheck3() { Assertions.assertThrows(IndexOutOfBoundsException.class, () -> { try { buffer.writerIndex(CAPACITY); buffer.readerIndex(CAPACITY / 2); } catch (IndexOutOfBoundsException e) { fail(); } buffer.writerIndex(CAPACITY / 4); }); } @Test void writerIndexBoundaryCheck4() { buffer.writerIndex(0); buffer.readerIndex(0); buffer.writerIndex(CAPACITY); } @Test void getByteBoundaryCheck1() { Assertions.assertThrows(IndexOutOfBoundsException.class, () -> buffer.getByte(-1)); } @Test void getByteBoundaryCheck2() { Assertions.assertThrows(IndexOutOfBoundsException.class, () -> buffer.getByte(buffer.capacity())); } @Test void getByteArrayBoundaryCheck1() { Assertions.assertThrows(IndexOutOfBoundsException.class, () -> buffer.getBytes(-1, new byte[0])); } @Test void getByteArrayBoundaryCheck2() { Assertions.assertThrows(IndexOutOfBoundsException.class, () -> buffer.getBytes(-1, new byte[0], 0, 0)); } @Test void getByteBufferBoundaryCheck() { Assertions.assertThrows(IndexOutOfBoundsException.class, () -> buffer.getBytes(-1, ByteBuffer.allocate(0))); } @Test void copyBoundaryCheck1() { Assertions.assertThrows(IndexOutOfBoundsException.class, () -> buffer.copy(-1, 0)); } @Test void copyBoundaryCheck2() { Assertions.assertThrows(IndexOutOfBoundsException.class, () -> buffer.copy(0, buffer.capacity() + 1)); } @Test void copyBoundaryCheck3() { Assertions.assertThrows(IndexOutOfBoundsException.class, () -> buffer.copy(buffer.capacity() + 1, 0)); } @Test void copyBoundaryCheck4() { Assertions.assertThrows(IndexOutOfBoundsException.class, () -> buffer.copy(buffer.capacity(), 1)); } @Test void setIndexBoundaryCheck1() { Assertions.assertThrows(IndexOutOfBoundsException.class, () -> buffer.setIndex(-1, CAPACITY)); } @Test void setIndexBoundaryCheck2() { Assertions.assertThrows(IndexOutOfBoundsException.class, () -> buffer.setIndex(CAPACITY / 2, CAPACITY / 4)); } @Test void setIndexBoundaryCheck3() { Assertions.assertThrows(IndexOutOfBoundsException.class, () -> buffer.setIndex(0, CAPACITY + 1)); } @Test void getByteBufferState() { ByteBuffer dst = ByteBuffer.allocate(4); dst.position(1); dst.limit(3); buffer.setByte(0, (byte) 1); buffer.setByte(1, (byte) 2); buffer.setByte(2, (byte) 3); buffer.setByte(3, (byte) 4); buffer.getBytes(1, dst); assertEquals(3, dst.position()); assertEquals(3, dst.limit()); dst.clear(); assertEquals(0, dst.get(0)); assertEquals(2, dst.get(1)); assertEquals(3, dst.get(2)); assertEquals(0, dst.get(3)); } @Test void getDirectByteBufferBoundaryCheck() { Assertions.assertThrows( IndexOutOfBoundsException.class, () -> buffer.getBytes(-1, ByteBuffer.allocateDirect(0))); } @Test void getDirectByteBufferState() { ByteBuffer dst = ByteBuffer.allocateDirect(4); dst.position(1); dst.limit(3); buffer.setByte(0, (byte) 1); buffer.setByte(1, (byte) 2); buffer.setByte(2, (byte) 3); buffer.setByte(3, (byte) 4); buffer.getBytes(1, dst); assertEquals(3, dst.position()); assertEquals(3, dst.limit()); dst.clear(); assertEquals(0, dst.get(0)); assertEquals(2, dst.get(1)); assertEquals(3, dst.get(2)); assertEquals(0, dst.get(3)); } @Test void testRandomByteAccess() { for (int i = 0; i < buffer.capacity(); i++) { byte value = (byte) random.nextInt(); buffer.setByte(i, value); } random.setSeed(seed); for (int i = 0; i < buffer.capacity(); i++) { byte value = (byte) random.nextInt(); assertEquals(value, buffer.getByte(i)); } } @Test void testSequentialByteAccess() { buffer.writerIndex(0); for (int i = 0; i < buffer.capacity(); i++) { byte value = (byte) random.nextInt(); assertEquals(i, buffer.writerIndex()); assertTrue(buffer.writable()); buffer.writeByte(value); } assertEquals(0, buffer.readerIndex()); assertEquals(buffer.capacity(), buffer.writerIndex()); assertFalse(buffer.writable()); random.setSeed(seed); for (int i = 0; i < buffer.capacity(); i++) { byte value = (byte) random.nextInt(); assertEquals(i, buffer.readerIndex()); assertTrue(buffer.readable()); assertEquals(value, buffer.readByte()); } assertEquals(buffer.capacity(), buffer.readerIndex()); assertEquals(buffer.capacity(), buffer.writerIndex()); assertFalse(buffer.readable()); assertFalse(buffer.writable()); } @Test void testByteArrayTransfer() { byte[] value = new byte[BLOCK_SIZE * 2]; for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(value); buffer.setBytes(i, value, random.nextInt(BLOCK_SIZE), BLOCK_SIZE); } random.setSeed(seed); byte[] expectedValue = new byte[BLOCK_SIZE * 2]; for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(expectedValue); int valueOffset = random.nextInt(BLOCK_SIZE); buffer.getBytes(i, value, valueOffset, BLOCK_SIZE); for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j++) { assertEquals(expectedValue[j], value[j]); } } } @Test void testRandomByteArrayTransfer1() { byte[] value = new byte[BLOCK_SIZE]; for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(value); buffer.setBytes(i, value); } random.setSeed(seed); byte[] expectedValueContent = new byte[BLOCK_SIZE]; ChannelBuffer expectedValue = wrappedBuffer(expectedValueContent); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(expectedValueContent); buffer.getBytes(i, value); for (int j = 0; j < BLOCK_SIZE; j++) { assertEquals(expectedValue.getByte(j), value[j]); } } } @Test void testRandomByteArrayTransfer2() { byte[] value = new byte[BLOCK_SIZE * 2]; for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(value); buffer.setBytes(i, value, random.nextInt(BLOCK_SIZE), BLOCK_SIZE); } random.setSeed(seed); byte[] expectedValueContent = new byte[BLOCK_SIZE * 2]; ChannelBuffer expectedValue = wrappedBuffer(expectedValueContent); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(expectedValueContent); int valueOffset = random.nextInt(BLOCK_SIZE); buffer.getBytes(i, value, valueOffset, BLOCK_SIZE); for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j++) { assertEquals(expectedValue.getByte(j), value[j]); } } } @Test void testRandomHeapBufferTransfer1() { byte[] valueContent = new byte[BLOCK_SIZE]; ChannelBuffer value = wrappedBuffer(valueContent); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(valueContent); value.setIndex(0, BLOCK_SIZE); buffer.setBytes(i, value); assertEquals(BLOCK_SIZE, value.readerIndex()); assertEquals(BLOCK_SIZE, value.writerIndex()); } random.setSeed(seed); byte[] expectedValueContent = new byte[BLOCK_SIZE]; ChannelBuffer expectedValue = wrappedBuffer(expectedValueContent); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(expectedValueContent); value.clear(); buffer.getBytes(i, value); assertEquals(0, value.readerIndex()); assertEquals(BLOCK_SIZE, value.writerIndex()); for (int j = 0; j < BLOCK_SIZE; j++) { assertEquals(expectedValue.getByte(j), value.getByte(j)); } } } @Test void testRandomHeapBufferTransfer2() { byte[] valueContent = new byte[BLOCK_SIZE * 2]; ChannelBuffer value = wrappedBuffer(valueContent); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(valueContent); buffer.setBytes(i, value, random.nextInt(BLOCK_SIZE), BLOCK_SIZE); } random.setSeed(seed); byte[] expectedValueContent = new byte[BLOCK_SIZE * 2]; ChannelBuffer expectedValue = wrappedBuffer(expectedValueContent); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(expectedValueContent); int valueOffset = random.nextInt(BLOCK_SIZE); buffer.getBytes(i, value, valueOffset, BLOCK_SIZE); for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j++) { assertEquals(expectedValue.getByte(j), value.getByte(j)); } } } @Test void testRandomDirectBufferTransfer() { byte[] tmp = new byte[BLOCK_SIZE * 2]; ChannelBuffer value = directBuffer(BLOCK_SIZE * 2); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(tmp); value.setBytes(0, tmp, 0, value.capacity()); buffer.setBytes(i, value, random.nextInt(BLOCK_SIZE), BLOCK_SIZE); } random.setSeed(seed); ChannelBuffer expectedValue = directBuffer(BLOCK_SIZE * 2); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(tmp); expectedValue.setBytes(0, tmp, 0, expectedValue.capacity()); int valueOffset = random.nextInt(BLOCK_SIZE); buffer.getBytes(i, value, valueOffset, BLOCK_SIZE); for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j++) { assertEquals(expectedValue.getByte(j), value.getByte(j)); } } } @Test void testRandomByteBufferTransfer() { ByteBuffer value = ByteBuffer.allocate(BLOCK_SIZE * 2); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(value.array()); value.clear().position(random.nextInt(BLOCK_SIZE)); value.limit(value.position() + BLOCK_SIZE); buffer.setBytes(i, value); } random.setSeed(seed); ByteBuffer expectedValue = ByteBuffer.allocate(BLOCK_SIZE * 2); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(expectedValue.array()); int valueOffset = random.nextInt(BLOCK_SIZE); value.clear().position(valueOffset).limit(valueOffset + BLOCK_SIZE); buffer.getBytes(i, value); assertEquals(valueOffset + BLOCK_SIZE, value.position()); for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j++) { assertEquals(expectedValue.get(j), value.get(j)); } } } @Test void testSequentialByteArrayTransfer1() { byte[] value = new byte[BLOCK_SIZE]; buffer.writerIndex(0); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(value); assertEquals(0, buffer.readerIndex()); assertEquals(i, buffer.writerIndex()); buffer.writeBytes(value); } random.setSeed(seed); byte[] expectedValue = new byte[BLOCK_SIZE]; for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(expectedValue); assertEquals(i, buffer.readerIndex()); assertEquals(CAPACITY, buffer.writerIndex()); buffer.readBytes(value); for (int j = 0; j < BLOCK_SIZE; j++) { assertEquals(expectedValue[j], value[j]); } } } @Test void testSequentialByteArrayTransfer2() { byte[] value = new byte[BLOCK_SIZE * 2]; buffer.writerIndex(0); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(value); assertEquals(0, buffer.readerIndex()); assertEquals(i, buffer.writerIndex()); int readerIndex = random.nextInt(BLOCK_SIZE); buffer.writeBytes(value, readerIndex, BLOCK_SIZE); } random.setSeed(seed); byte[] expectedValue = new byte[BLOCK_SIZE * 2]; for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(expectedValue); int valueOffset = random.nextInt(BLOCK_SIZE); assertEquals(i, buffer.readerIndex()); assertEquals(CAPACITY, buffer.writerIndex()); buffer.readBytes(value, valueOffset, BLOCK_SIZE); for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j++) { assertEquals(expectedValue[j], value[j]); } } } @Test void testSequentialHeapBufferTransfer1() { byte[] valueContent = new byte[BLOCK_SIZE * 2]; ChannelBuffer value = wrappedBuffer(valueContent); buffer.writerIndex(0); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(valueContent); assertEquals(0, buffer.readerIndex()); assertEquals(i, buffer.writerIndex()); buffer.writeBytes(value, random.nextInt(BLOCK_SIZE), BLOCK_SIZE); assertEquals(0, value.readerIndex()); assertEquals(valueContent.length, value.writerIndex()); } random.setSeed(seed); byte[] expectedValueContent = new byte[BLOCK_SIZE * 2]; ChannelBuffer expectedValue = wrappedBuffer(expectedValueContent); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(expectedValueContent); int valueOffset = random.nextInt(BLOCK_SIZE); assertEquals(i, buffer.readerIndex()); assertEquals(CAPACITY, buffer.writerIndex()); buffer.readBytes(value, valueOffset, BLOCK_SIZE); for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j++) { assertEquals(expectedValue.getByte(j), value.getByte(j)); } assertEquals(0, value.readerIndex()); assertEquals(valueContent.length, value.writerIndex()); } } @Test void testSequentialHeapBufferTransfer2() { byte[] valueContent = new byte[BLOCK_SIZE * 2]; ChannelBuffer value = wrappedBuffer(valueContent); buffer.writerIndex(0); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(valueContent); assertEquals(0, buffer.readerIndex()); assertEquals(i, buffer.writerIndex()); int readerIndex = random.nextInt(BLOCK_SIZE); value.readerIndex(readerIndex); value.writerIndex(readerIndex + BLOCK_SIZE); buffer.writeBytes(value); assertEquals(readerIndex + BLOCK_SIZE, value.writerIndex()); assertEquals(value.writerIndex(), value.readerIndex()); } random.setSeed(seed); byte[] expectedValueContent = new byte[BLOCK_SIZE * 2]; ChannelBuffer expectedValue = wrappedBuffer(expectedValueContent); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(expectedValueContent); int valueOffset = random.nextInt(BLOCK_SIZE); assertEquals(i, buffer.readerIndex()); assertEquals(CAPACITY, buffer.writerIndex()); value.readerIndex(valueOffset); value.writerIndex(valueOffset); buffer.readBytes(value, BLOCK_SIZE); for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j++) { assertEquals(expectedValue.getByte(j), value.getByte(j)); } assertEquals(valueOffset, value.readerIndex()); assertEquals(valueOffset + BLOCK_SIZE, value.writerIndex()); } } @Test void testSequentialDirectBufferTransfer1() { byte[] valueContent = new byte[BLOCK_SIZE * 2]; ChannelBuffer value = directBuffer(BLOCK_SIZE * 2); buffer.writerIndex(0); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(valueContent); value.setBytes(0, valueContent); assertEquals(0, buffer.readerIndex()); assertEquals(i, buffer.writerIndex()); buffer.writeBytes(value, random.nextInt(BLOCK_SIZE), BLOCK_SIZE); assertEquals(0, value.readerIndex()); assertEquals(0, value.writerIndex()); } random.setSeed(seed); byte[] expectedValueContent = new byte[BLOCK_SIZE * 2]; ChannelBuffer expectedValue = wrappedBuffer(expectedValueContent); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(expectedValueContent); int valueOffset = random.nextInt(BLOCK_SIZE); value.setBytes(0, valueContent); assertEquals(i, buffer.readerIndex()); assertEquals(CAPACITY, buffer.writerIndex()); buffer.readBytes(value, valueOffset, BLOCK_SIZE); for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j++) { assertEquals(expectedValue.getByte(j), value.getByte(j)); } assertEquals(0, value.readerIndex()); assertEquals(0, value.writerIndex()); } } @Test void testSequentialDirectBufferTransfer2() { byte[] valueContent = new byte[BLOCK_SIZE * 2]; ChannelBuffer value = directBuffer(BLOCK_SIZE * 2); buffer.writerIndex(0); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(valueContent); value.setBytes(0, valueContent); assertEquals(0, buffer.readerIndex()); assertEquals(i, buffer.writerIndex()); int readerIndex = random.nextInt(BLOCK_SIZE); value.readerIndex(0); value.writerIndex(readerIndex + BLOCK_SIZE); value.readerIndex(readerIndex); buffer.writeBytes(value); assertEquals(readerIndex + BLOCK_SIZE, value.writerIndex()); assertEquals(value.writerIndex(), value.readerIndex()); } random.setSeed(seed); byte[] expectedValueContent = new byte[BLOCK_SIZE * 2]; ChannelBuffer expectedValue = wrappedBuffer(expectedValueContent); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(expectedValueContent); value.setBytes(0, valueContent); int valueOffset = random.nextInt(BLOCK_SIZE); assertEquals(i, buffer.readerIndex()); assertEquals(CAPACITY, buffer.writerIndex()); value.readerIndex(valueOffset); value.writerIndex(valueOffset); buffer.readBytes(value, BLOCK_SIZE); for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j++) { assertEquals(expectedValue.getByte(j), value.getByte(j)); } assertEquals(valueOffset, value.readerIndex()); assertEquals(valueOffset + BLOCK_SIZE, value.writerIndex()); } } @Test void testSequentialByteBufferBackedHeapBufferTransfer1() { byte[] valueContent = new byte[BLOCK_SIZE * 2]; ChannelBuffer value = wrappedBuffer(ByteBuffer.allocate(BLOCK_SIZE * 2)); value.writerIndex(0); buffer.writerIndex(0); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(valueContent); value.setBytes(0, valueContent); assertEquals(0, buffer.readerIndex()); assertEquals(i, buffer.writerIndex()); buffer.writeBytes(value, random.nextInt(BLOCK_SIZE), BLOCK_SIZE); assertEquals(0, value.readerIndex()); assertEquals(0, value.writerIndex()); } random.setSeed(seed); byte[] expectedValueContent = new byte[BLOCK_SIZE * 2]; ChannelBuffer expectedValue = wrappedBuffer(expectedValueContent); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(expectedValueContent); int valueOffset = random.nextInt(BLOCK_SIZE); value.setBytes(0, valueContent); assertEquals(i, buffer.readerIndex()); assertEquals(CAPACITY, buffer.writerIndex()); buffer.readBytes(value, valueOffset, BLOCK_SIZE); for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j++) { assertEquals(expectedValue.getByte(j), value.getByte(j)); } assertEquals(0, value.readerIndex()); assertEquals(0, value.writerIndex()); } } @Test void testSequentialByteBufferBackedHeapBufferTransfer2() { byte[] valueContent = new byte[BLOCK_SIZE * 2]; ChannelBuffer value = wrappedBuffer(ByteBuffer.allocate(BLOCK_SIZE * 2)); value.writerIndex(0); buffer.writerIndex(0); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(valueContent); value.setBytes(0, valueContent); assertEquals(0, buffer.readerIndex()); assertEquals(i, buffer.writerIndex()); int readerIndex = random.nextInt(BLOCK_SIZE); value.readerIndex(0); value.writerIndex(readerIndex + BLOCK_SIZE); value.readerIndex(readerIndex); buffer.writeBytes(value); assertEquals(readerIndex + BLOCK_SIZE, value.writerIndex()); assertEquals(value.writerIndex(), value.readerIndex()); } random.setSeed(seed); byte[] expectedValueContent = new byte[BLOCK_SIZE * 2]; ChannelBuffer expectedValue = wrappedBuffer(expectedValueContent); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(expectedValueContent); value.setBytes(0, valueContent); int valueOffset = random.nextInt(BLOCK_SIZE); assertEquals(i, buffer.readerIndex()); assertEquals(CAPACITY, buffer.writerIndex()); value.readerIndex(valueOffset); value.writerIndex(valueOffset); buffer.readBytes(value, BLOCK_SIZE); for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j++) { assertEquals(expectedValue.getByte(j), value.getByte(j)); } assertEquals(valueOffset, value.readerIndex()); assertEquals(valueOffset + BLOCK_SIZE, value.writerIndex()); } } @Test void testSequentialByteBufferTransfer() { buffer.writerIndex(0); ByteBuffer value = ByteBuffer.allocate(BLOCK_SIZE * 2); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(value.array()); value.clear().position(random.nextInt(BLOCK_SIZE)); value.limit(value.position() + BLOCK_SIZE); buffer.writeBytes(value); } random.setSeed(seed); ByteBuffer expectedValue = ByteBuffer.allocate(BLOCK_SIZE * 2); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(expectedValue.array()); int valueOffset = random.nextInt(BLOCK_SIZE); value.clear().position(valueOffset).limit(valueOffset + BLOCK_SIZE); buffer.readBytes(value); assertEquals(valueOffset + BLOCK_SIZE, value.position()); for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j++) { assertEquals(expectedValue.get(j), value.get(j)); } } } @Test void testSequentialCopiedBufferTransfer1() { buffer.writerIndex(0); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { byte[] value = new byte[BLOCK_SIZE]; random.nextBytes(value); assertEquals(0, buffer.readerIndex()); assertEquals(i, buffer.writerIndex()); buffer.writeBytes(value); } random.setSeed(seed); byte[] expectedValue = new byte[BLOCK_SIZE]; for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(expectedValue); assertEquals(i, buffer.readerIndex()); assertEquals(CAPACITY, buffer.writerIndex()); ChannelBuffer actualValue = buffer.readBytes(BLOCK_SIZE); assertEquals(wrappedBuffer(expectedValue), actualValue); // Make sure if it is a copied buffer. actualValue.setByte(0, (byte) (actualValue.getByte(0) + 1)); assertFalse(buffer.getByte(i) == actualValue.getByte(0)); } } @Test void testStreamTransfer1() throws Exception { byte[] expected = new byte[buffer.capacity()]; random.nextBytes(expected); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { ByteArrayInputStream in = new ByteArrayInputStream(expected, i, BLOCK_SIZE); assertEquals(BLOCK_SIZE, buffer.setBytes(i, in, BLOCK_SIZE)); assertEquals(-1, buffer.setBytes(i, in, 0)); } ByteArrayOutputStream out = new ByteArrayOutputStream(); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { buffer.getBytes(i, out, BLOCK_SIZE); } assertTrue(Arrays.equals(expected, out.toByteArray())); } @Test void testStreamTransfer2() throws Exception { byte[] expected = new byte[buffer.capacity()]; random.nextBytes(expected); buffer.clear(); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { ByteArrayInputStream in = new ByteArrayInputStream(expected, i, BLOCK_SIZE); assertEquals(i, buffer.writerIndex()); buffer.writeBytes(in, BLOCK_SIZE); assertEquals(i + BLOCK_SIZE, buffer.writerIndex()); } ByteArrayOutputStream out = new ByteArrayOutputStream(); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { assertEquals(i, buffer.readerIndex()); buffer.readBytes(out, BLOCK_SIZE); assertEquals(i + BLOCK_SIZE, buffer.readerIndex()); } assertTrue(Arrays.equals(expected, out.toByteArray())); } @Test void testCopy() { for (int i = 0; i < buffer.capacity(); i++) { byte value = (byte) random.nextInt(); buffer.setByte(i, value); } final int readerIndex = CAPACITY / 3; final int writerIndex = CAPACITY * 2 / 3; buffer.setIndex(readerIndex, writerIndex); // Make sure all properties are copied. ChannelBuffer copy = buffer.copy(); assertEquals(0, copy.readerIndex()); assertEquals(buffer.readableBytes(), copy.writerIndex()); assertEquals(buffer.readableBytes(), copy.capacity()); for (int i = 0; i < copy.capacity(); i++) { assertEquals(buffer.getByte(i + readerIndex), copy.getByte(i)); } // Make sure the buffer content is independent from each other. buffer.setByte(readerIndex, (byte) (buffer.getByte(readerIndex) + 1)); assertTrue(buffer.getByte(readerIndex) != copy.getByte(0)); copy.setByte(1, (byte) (copy.getByte(1) + 1)); assertTrue(buffer.getByte(readerIndex + 1) != copy.getByte(1)); } @Test void testToByteBuffer1() { byte[] value = new byte[buffer.capacity()]; random.nextBytes(value); buffer.clear(); buffer.writeBytes(value); assertEquals(ByteBuffer.wrap(value), buffer.toByteBuffer()); } @Test void testToByteBuffer2() { byte[] value = new byte[buffer.capacity()]; random.nextBytes(value); buffer.clear(); buffer.writeBytes(value); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { assertEquals(ByteBuffer.wrap(value, i, BLOCK_SIZE), buffer.toByteBuffer(i, BLOCK_SIZE)); } } @Test void testSkipBytes1() { buffer.setIndex(CAPACITY / 4, CAPACITY / 2); buffer.skipBytes(CAPACITY / 4); assertEquals(CAPACITY / 4 * 2, buffer.readerIndex()); try { buffer.skipBytes(CAPACITY / 4 + 1); fail(); } catch (IndexOutOfBoundsException e) { // Expected } // Should remain unchanged. assertEquals(CAPACITY / 4 * 2, buffer.readerIndex()); } }
7,436
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/ChannelBuffersTest.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; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.apache.dubbo.remoting.buffer.ChannelBuffers.DEFAULT_CAPACITY; import static org.apache.dubbo.remoting.buffer.ChannelBuffers.EMPTY_BUFFER; /** * {@link ChannelBuffers} */ class ChannelBuffersTest { @Test void testDynamicBuffer() { ChannelBuffer channelBuffer = ChannelBuffers.dynamicBuffer(); Assertions.assertTrue(channelBuffer instanceof DynamicChannelBuffer); Assertions.assertEquals(channelBuffer.capacity(), DEFAULT_CAPACITY); channelBuffer = ChannelBuffers.dynamicBuffer(32, DirectChannelBufferFactory.getInstance()); Assertions.assertTrue(channelBuffer instanceof DynamicChannelBuffer); Assertions.assertTrue(channelBuffer.isDirect()); Assertions.assertEquals(channelBuffer.capacity(), 32); } @Test void testPrefixEquals() { ChannelBuffer bufA = ChannelBuffers.wrappedBuffer("abcedfaf".getBytes()); ChannelBuffer bufB = ChannelBuffers.wrappedBuffer("abcedfaa".getBytes()); Assertions.assertTrue(ChannelBuffers.equals(bufA, bufB)); Assertions.assertTrue(ChannelBuffers.prefixEquals(bufA, bufB, 7)); Assertions.assertFalse(ChannelBuffers.prefixEquals(bufA, bufB, 8)); } @Test void testBuffer() { ChannelBuffer channelBuffer = ChannelBuffers.buffer(DEFAULT_CAPACITY); Assertions.assertTrue(channelBuffer instanceof HeapChannelBuffer); channelBuffer = ChannelBuffers.buffer(0); Assertions.assertEquals(channelBuffer, EMPTY_BUFFER); } @Test void testWrappedBuffer() { byte[] bytes = new byte[16]; ChannelBuffer channelBuffer = ChannelBuffers.wrappedBuffer(bytes, 0, 15); Assertions.assertTrue(channelBuffer instanceof HeapChannelBuffer); Assertions.assertEquals(channelBuffer.capacity(), 15); channelBuffer = ChannelBuffers.wrappedBuffer(new byte[] {}); Assertions.assertEquals(channelBuffer, EMPTY_BUFFER); ByteBuffer byteBuffer = ByteBuffer.allocate(16); channelBuffer = ChannelBuffers.wrappedBuffer(byteBuffer); Assertions.assertTrue(channelBuffer instanceof HeapChannelBuffer); byteBuffer = ByteBuffer.allocateDirect(16); channelBuffer = ChannelBuffers.wrappedBuffer(byteBuffer); Assertions.assertTrue(channelBuffer instanceof ByteBufferBackedChannelBuffer); byteBuffer.position(byteBuffer.limit()); channelBuffer = ChannelBuffers.wrappedBuffer(byteBuffer); Assertions.assertEquals(channelBuffer, EMPTY_BUFFER); } @Test void testDirectBuffer() { ChannelBuffer channelBuffer = ChannelBuffers.directBuffer(0); Assertions.assertEquals(channelBuffer, EMPTY_BUFFER); channelBuffer = ChannelBuffers.directBuffer(16); Assertions.assertTrue(channelBuffer instanceof ByteBufferBackedChannelBuffer); } @Test void testEqualsHashCodeCompareMethod() { ChannelBuffer buffer1 = ChannelBuffers.buffer(4); byte[] bytes1 = new byte[] {1, 2, 3, 4}; buffer1.writeBytes(bytes1); ChannelBuffer buffer2 = ChannelBuffers.buffer(4); byte[] bytes2 = new byte[] {1, 2, 3, 4}; buffer2.writeBytes(bytes2); ChannelBuffer buffer3 = ChannelBuffers.buffer(3); byte[] bytes3 = new byte[] {1, 2, 3}; buffer3.writeBytes(bytes3); ChannelBuffer buffer4 = ChannelBuffers.buffer(4); byte[] bytes4 = new byte[] {1, 2, 3, 5}; buffer4.writeBytes(bytes4); Assertions.assertTrue(ChannelBuffers.equals(buffer1, buffer2)); Assertions.assertFalse(ChannelBuffers.equals(buffer1, buffer3)); Assertions.assertFalse(ChannelBuffers.equals(buffer1, buffer4)); Assertions.assertTrue(ChannelBuffers.compare(buffer1, buffer2) == 0); Assertions.assertTrue(ChannelBuffers.compare(buffer1, buffer3) > 0); Assertions.assertTrue(ChannelBuffers.compare(buffer1, buffer4) < 0); Assertions.assertEquals(ChannelBuffers.hasCode(buffer1), ChannelBuffers.hasCode(buffer2)); Assertions.assertNotEquals(ChannelBuffers.hasCode(buffer1), ChannelBuffers.hasCode(buffer3)); Assertions.assertNotEquals(ChannelBuffers.hasCode(buffer1), ChannelBuffers.hasCode(buffer4)); } }
7,437
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/HeapChannelBufferTest.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 org.hamcrest.MatcherAssert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; class HeapChannelBufferTest extends AbstractChannelBufferTest { private ChannelBuffer buffer; @Override protected ChannelBuffer newBuffer(int capacity) { buffer = ChannelBuffers.buffer(capacity); Assertions.assertEquals(0, buffer.writerIndex()); return buffer; } @Override protected ChannelBuffer[] components() { return new ChannelBuffer[] {buffer}; } @Test void testEqualsAndHashcode() { HeapChannelBuffer b1 = new HeapChannelBuffer("hello-world".getBytes()); HeapChannelBuffer b2 = new HeapChannelBuffer("hello-world".getBytes()); MatcherAssert.assertThat(b1.equals(b2), is(true)); MatcherAssert.assertThat(b1.hashCode(), is(b2.hashCode())); b1 = new HeapChannelBuffer("hello-world".getBytes()); b2 = new HeapChannelBuffer("hello-worldd".getBytes()); MatcherAssert.assertThat(b1.equals(b2), is(false)); MatcherAssert.assertThat(b1.hashCode(), not(b2.hashCode())); } }
7,438
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/ByteBufferBackedChannelBufferTest.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; class ByteBufferBackedChannelBufferTest extends AbstractChannelBufferTest { private ChannelBuffer buffer; @Override protected ChannelBuffer newBuffer(int capacity) { buffer = new ByteBufferBackedChannelBuffer(ByteBuffer.allocate(capacity)); return buffer; } @Override protected ChannelBuffer[] components() { return new ChannelBuffer[] {buffer}; } }
7,439
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Transporter.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; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; /** * Transporter. (SPI, Singleton, ThreadSafe) * <p> * <a href="http://en.wikipedia.org/wiki/Transport_Layer">Transport Layer</a> * <a href="http://en.wikipedia.org/wiki/Client%E2%80%93server_model">Client/Server</a> * * @see org.apache.dubbo.remoting.Transporters */ @SPI(value = "netty", scope = ExtensionScope.FRAMEWORK) public interface Transporter { /** * Bind a server. * * @param url server url * @param handler * @return server * @throws RemotingException * @see org.apache.dubbo.remoting.Transporters#bind(URL, ChannelHandler...) */ @Adaptive({Constants.SERVER_KEY, Constants.TRANSPORTER_KEY}) RemotingServer bind(URL url, ChannelHandler handler) throws RemotingException; /** * Connect to a server. * * @param url server url * @param handler * @return client * @throws RemotingException * @see org.apache.dubbo.remoting.Transporters#connect(URL, ChannelHandler...) */ @Adaptive({Constants.CLIENT_KEY, Constants.TRANSPORTER_KEY}) Client connect(URL url, ChannelHandler handler) throws RemotingException; }
7,440
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Decodeable.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; public interface Decodeable { void decode() throws Exception; }
7,441
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Client.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; import org.apache.dubbo.common.Resetable; /** * Remoting Client. (API/SPI, Prototype, ThreadSafe) * <p> * <a href="http://en.wikipedia.org/wiki/Client%E2%80%93server_model">Client/Server</a> * * @see org.apache.dubbo.remoting.Transporter#connect(org.apache.dubbo.common.URL, ChannelHandler) */ public interface Client extends Endpoint, Channel, Resetable, IdleSensible { /** * reconnect. */ void reconnect() throws RemotingException; @Deprecated void reset(org.apache.dubbo.common.Parameters parameters); }
7,442
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Transporters.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; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.transport.ChannelHandlerAdapter; import org.apache.dubbo.remoting.transport.ChannelHandlerDispatcher; /** * Transporter facade. (API, Static, ThreadSafe) */ public class Transporters { private Transporters() {} public static RemotingServer bind(String url, ChannelHandler... handler) throws RemotingException { return bind(URL.valueOf(url), handler); } public static RemotingServer bind(URL url, ChannelHandler... handlers) throws RemotingException { if (url == null) { throw new IllegalArgumentException("url == null"); } if (handlers == null || handlers.length == 0) { throw new IllegalArgumentException("handlers == null"); } ChannelHandler handler; if (handlers.length == 1) { handler = handlers[0]; } else { handler = new ChannelHandlerDispatcher(handlers); } return getTransporter(url).bind(url, handler); } public static Client connect(String url, ChannelHandler... handler) throws RemotingException { return connect(URL.valueOf(url), handler); } public static Client connect(URL url, ChannelHandler... handlers) throws RemotingException { if (url == null) { throw new IllegalArgumentException("url == null"); } ChannelHandler handler; if (handlers == null || handlers.length == 0) { handler = new ChannelHandlerAdapter(); } else if (handlers.length == 1) { handler = handlers[0]; } else { handler = new ChannelHandlerDispatcher(handlers); } return getTransporter(url).connect(url, handler); } public static Transporter getTransporter(URL url) { return url.getOrDefaultFrameworkModel() .getExtensionLoader(Transporter.class) .getAdaptiveExtension(); } }
7,443
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/RemotingServer.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; import org.apache.dubbo.common.Resetable; import java.net.InetSocketAddress; import java.util.Collection; /** * Remoting Server. (API/SPI, Prototype, ThreadSafe) * <p> * <a href="http://en.wikipedia.org/wiki/Client%E2%80%93server_model">Client/Server</a> * * @see org.apache.dubbo.remoting.Transporter#bind(org.apache.dubbo.common.URL, ChannelHandler) */ public interface RemotingServer extends Endpoint, Resetable, IdleSensible { /** * is bound. * * @return bound */ boolean isBound(); /** * get channels. * * @return channels */ Collection<Channel> getChannels(); /** * get channel. * * @param remoteAddress * @return channel */ Channel getChannel(InetSocketAddress remoteAddress); @Deprecated void reset(org.apache.dubbo.common.Parameters parameters); }
7,444
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Codec2.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; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.remoting.buffer.ChannelBuffer; import java.io.IOException; @SPI(scope = ExtensionScope.FRAMEWORK) public interface Codec2 { @Adaptive({Constants.CODEC_KEY}) void encode(Channel channel, ChannelBuffer buffer, Object message) throws IOException; @Adaptive({Constants.CODEC_KEY}) Object decode(Channel channel, ChannelBuffer buffer) throws IOException; enum DecodeResult { NEED_MORE_INPUT, SKIP_SOME_INPUT } }
7,445
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/ExecutionException.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; import java.net.InetSocketAddress; /** * ReceiveException * * @export */ public class ExecutionException extends RemotingException { private static final long serialVersionUID = -2531085236111056860L; private final Object request; public ExecutionException(Object request, Channel channel, String message, Throwable cause) { super(channel, message, cause); this.request = request; } public ExecutionException(Object request, Channel channel, String msg) { super(channel, msg); this.request = request; } public ExecutionException(Object request, Channel channel, Throwable cause) { super(channel, cause); this.request = request; } public ExecutionException( Object request, InetSocketAddress localAddress, InetSocketAddress remoteAddress, String message, Throwable cause) { super(localAddress, remoteAddress, message, cause); this.request = request; } public ExecutionException( Object request, InetSocketAddress localAddress, InetSocketAddress remoteAddress, String message) { super(localAddress, remoteAddress, message); this.request = request; } public ExecutionException( Object request, InetSocketAddress localAddress, InetSocketAddress remoteAddress, Throwable cause) { super(localAddress, remoteAddress, cause); this.request = request; } public Object getRequest() { return request; } }
7,446
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/IdleSensible.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; /** * Indicate whether the implementation (for both server and client) has the ability to sense and handle idle connection. * If the server has the ability to handle idle connection, it should close the connection when it happens, and if * the client has the ability to handle idle connection, it should send the heartbeat to the server. */ public interface IdleSensible { /** * Whether the implementation can sense and handle the idle connection. By default, it's false, the implementation * relies on dedicated timer to take care of idle connection. * * @return whether it has the ability to handle idle connection */ default boolean canHandleIdle() { return false; } }
7,447
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Channel.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; import java.net.InetSocketAddress; /** * Channel. (API/SPI, Prototype, ThreadSafe) * * @see org.apache.dubbo.remoting.Client * @see RemotingServer#getChannels() * @see RemotingServer#getChannel(InetSocketAddress) */ public interface Channel extends Endpoint { /** * get remote address. * * @return remote address. */ InetSocketAddress getRemoteAddress(); /** * is connected. * * @return connected */ boolean isConnected(); /** * has attribute. * * @param key key. * @return has or has not. */ boolean hasAttribute(String key); /** * get attribute. * * @param key key. * @return value. */ Object getAttribute(String key); /** * set attribute. * * @param key key. * @param value value. */ void setAttribute(String key, Object value); /** * remove attribute. * * @param key key. */ void removeAttribute(String key); }
7,448
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/RemotingException.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; import java.net.InetSocketAddress; /** * RemotingException. (API, Prototype, ThreadSafe) * * @export * @see org.apache.dubbo.remoting.exchange.support.DefaultFuture#get() * @see org.apache.dubbo.remoting.Channel#send(Object, boolean) * @see org.apache.dubbo.remoting.exchange.ExchangeChannel#request(Object) * @see org.apache.dubbo.remoting.exchange.ExchangeChannel#request(Object, int) * @see org.apache.dubbo.remoting.Transporter#bind(org.apache.dubbo.common.URL, ChannelHandler) * @see org.apache.dubbo.remoting.Transporter#connect(org.apache.dubbo.common.URL, ChannelHandler) */ public class RemotingException extends Exception { private static final long serialVersionUID = -3160452149606778709L; private InetSocketAddress localAddress; private InetSocketAddress remoteAddress; public RemotingException(Channel channel, String msg) { this( channel == null ? null : channel.getLocalAddress(), channel == null ? null : channel.getRemoteAddress(), msg); } public RemotingException(InetSocketAddress localAddress, InetSocketAddress remoteAddress, String message) { super(message); this.localAddress = localAddress; this.remoteAddress = remoteAddress; } public RemotingException(Channel channel, Throwable cause) { this( channel == null ? null : channel.getLocalAddress(), channel == null ? null : channel.getRemoteAddress(), cause); } public RemotingException(InetSocketAddress localAddress, InetSocketAddress remoteAddress, Throwable cause) { super(cause); this.localAddress = localAddress; this.remoteAddress = remoteAddress; } public RemotingException(Channel channel, String message, Throwable cause) { this( channel == null ? null : channel.getLocalAddress(), channel == null ? null : channel.getRemoteAddress(), message, cause); } public RemotingException( InetSocketAddress localAddress, InetSocketAddress remoteAddress, String message, Throwable cause) { super(message, cause); this.localAddress = localAddress; this.remoteAddress = remoteAddress; } public InetSocketAddress getLocalAddress() { return localAddress; } public InetSocketAddress getRemoteAddress() { return remoteAddress; } }
7,449
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/RemotingScopeModelInitializer.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; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.zookeeper.ZookeeperTransporter; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; import org.apache.dubbo.rpc.model.ScopeModelInitializer; import java.util.List; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_DESTROY_ZOOKEEPER; /** * Scope model initializer for remoting-api */ public class RemotingScopeModelInitializer implements ScopeModelInitializer { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(RemotingScopeModelInitializer.class); @Override public void initializeFrameworkModel(FrameworkModel frameworkModel) {} @Override public void initializeApplicationModel(ApplicationModel applicationModel) { applicationModel.addDestroyListener(m -> { // destroy zookeeper clients if any try { List<ZookeeperTransporter> transporters = applicationModel .getExtensionLoader(ZookeeperTransporter.class) .getLoadedExtensionInstances(); for (ZookeeperTransporter zkTransporter : transporters) { zkTransporter.destroy(); } } catch (Exception e) { logger.error( TRANSPORT_FAILED_DESTROY_ZOOKEEPER, "", "", "Error encountered while destroying ZookeeperTransporter: " + e.getMessage(), e); } }); } @Override public void initializeModuleModel(ModuleModel moduleModel) {} }
7,450
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Endpoint.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; import org.apache.dubbo.common.URL; import java.net.InetSocketAddress; /** * Endpoint. (API/SPI, Prototype, ThreadSafe) * * * @see org.apache.dubbo.remoting.Channel * @see org.apache.dubbo.remoting.Client * @see RemotingServer */ public interface Endpoint { /** * get url. * * @return url */ URL getUrl(); /** * get channel handler. * * @return channel handler */ ChannelHandler getChannelHandler(); /** * get local address. * * @return local address. */ InetSocketAddress getLocalAddress(); /** * send message. * * @param message * @throws RemotingException */ void send(Object message) throws RemotingException; /** * send message. * * @param message * @param sent already sent to socket? */ void send(Object message, boolean sent) throws RemotingException; /** * close the channel. */ void close(); /** * Graceful close the channel. */ void close(int timeout); void startClose(); /** * is closed. * * @return closed */ boolean isClosed(); }
7,451
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/TimeoutException.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; import java.net.InetSocketAddress; /** * TimeoutException. (API, Prototype, ThreadSafe) * * @export * @see org.apache.dubbo.remoting.exchange.support.DefaultFuture#get() */ public class TimeoutException extends RemotingException { public static final int CLIENT_SIDE = 0; public static final int SERVER_SIDE = 1; private static final long serialVersionUID = 3122966731958222692L; private final int phase; public TimeoutException(boolean serverSide, Channel channel, String message) { super(channel, message); this.phase = serverSide ? SERVER_SIDE : CLIENT_SIDE; } public TimeoutException( boolean serverSide, InetSocketAddress localAddress, InetSocketAddress remoteAddress, String message) { super(localAddress, remoteAddress, message); this.phase = serverSide ? SERVER_SIDE : CLIENT_SIDE; } public int getPhase() { return phase; } public boolean isServerSide() { return phase == 1; } public boolean isClientSide() { return phase == 0; } }
7,452
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Dispatcher.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; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.remoting.transport.dispatcher.all.AllDispatcher; /** * ChannelHandlerWrapper (SPI, Singleton, ThreadSafe) */ @SPI(value = AllDispatcher.NAME, scope = ExtensionScope.FRAMEWORK) public interface Dispatcher { /** * dispatch the message to threadpool. * * @param handler * @param url * @return channel handler */ @Adaptive({Constants.DISPATCHER_KEY, "dispather", "channel.handler"}) // The last two parameters are reserved for compatibility with the old configuration ChannelHandler dispatch(ChannelHandler handler, URL url); }
7,453
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/ChannelHandler.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; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; /** * ChannelHandler. (API, Prototype, ThreadSafe) * * @see org.apache.dubbo.remoting.Transporter#bind(org.apache.dubbo.common.URL, ChannelHandler) * @see org.apache.dubbo.remoting.Transporter#connect(org.apache.dubbo.common.URL, ChannelHandler) */ @SPI(scope = ExtensionScope.FRAMEWORK) public interface ChannelHandler { /** * on channel connected. * * @param channel channel. */ void connected(Channel channel) throws RemotingException; /** * on channel disconnected. * * @param channel channel. */ void disconnected(Channel channel) throws RemotingException; /** * on message sent. * * @param channel channel. * @param message message. */ void sent(Channel channel, Object message) throws RemotingException; /** * on message received. * * @param channel channel. * @param message message. */ void received(Channel channel, Object message) throws RemotingException; /** * on exception caught. * * @param channel channel. * @param exception exception. */ void caught(Channel channel, Throwable exception) throws RemotingException; }
7,454
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Codec.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; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * Codec. (SPI, Singleton, ThreadSafe) */ @Deprecated @SPI(scope = ExtensionScope.FRAMEWORK) public interface Codec { /** * Need more input poison. * * @see #decode(Channel, InputStream) */ Object NEED_MORE_INPUT = new Object(); /** * Encode message. * * @param channel channel. * @param output output stream. * @param message message. */ @Adaptive({Constants.CODEC_KEY}) void encode(Channel channel, OutputStream output, Object message) throws IOException; /** * Decode message. * * @param channel channel. * @param input input stream. * @return message or <code>NEED_MORE_INPUT</code> poison. * @see #NEED_MORE_INPUT */ @Adaptive({Constants.CODEC_KEY}) Object decode(Channel channel, InputStream input) throws IOException; }
7,455
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Constants.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; public interface Constants { String BUFFER_KEY = "buffer"; /** * default buffer size is 8k. */ int DEFAULT_BUFFER_SIZE = 8 * 1024; int MAX_BUFFER_SIZE = 16 * 1024; int MIN_BUFFER_SIZE = 1 * 1024; String IDLE_TIMEOUT_KEY = "idle.timeout"; int DEFAULT_IDLE_TIMEOUT = 600 * 1000; /** * max size of channel. default value is zero that means unlimited. */ String ACCEPTS_KEY = "accepts"; int DEFAULT_ACCEPTS = 0; String CONNECT_QUEUE_CAPACITY = "connect.queue.capacity"; String CONNECT_QUEUE_WARNING_SIZE = "connect.queue.warning.size"; int DEFAULT_CONNECT_QUEUE_WARNING_SIZE = 1000; String CHARSET_KEY = "charset"; String DEFAULT_CHARSET = "UTF-8"; /** * Every heartbeat duration / HEARTBEAT_CHECK_TICK, check if a heartbeat should be sent. Every heartbeat timeout * duration / HEARTBEAT_CHECK_TICK, check if a connection should be closed on server side, and if reconnect on * client side */ int HEARTBEAT_CHECK_TICK = 3; /** * the least heartbeat during is 1000 ms. */ long LEAST_HEARTBEAT_DURATION = 1000; /** * the least reconnect during is 60000 ms. */ long LEAST_RECONNECT_DURATION = 60000; String LEAST_RECONNECT_DURATION_KEY = "dubbo.application.least-reconnect-duration"; /** * ticks per wheel. */ int TICKS_PER_WHEEL = 128; String PAYLOAD_KEY = "payload"; /** * 8M */ int DEFAULT_PAYLOAD = 8 * 1024 * 1024; String CONNECT_TIMEOUT_KEY = "connect.timeout"; int DEFAULT_CONNECT_TIMEOUT = 3000; String SERIALIZATION_KEY = "serialization"; /** * Prefer serialization */ String PREFER_SERIALIZATION_KEY = "prefer.serialization"; String DEFAULT_REMOTING_SERIALIZATION_PROPERTY_KEY = "DUBBO_DEFAULT_SERIALIZATION"; String CODEC_KEY = "codec"; String CODEC_VERSION_KEY = "codec.version"; String SERVER_KEY = "server"; String IS_PU_SERVER_KEY = "ispuserver"; String CLIENT_KEY = "client"; String DEFAULT_REMOTING_CLIENT = "netty"; String TRANSPORTER_KEY = "transporter"; String DEFAULT_TRANSPORTER = "netty"; String EXCHANGER_KEY = "exchanger"; String DEFAULT_EXCHANGER = "header"; String DISPACTHER_KEY = "dispacther"; int DEFAULT_IO_THREADS = Math.min(Runtime.getRuntime().availableProcessors() + 1, 32); String EVENT_LOOP_BOSS_POOL_NAME = "NettyServerBoss"; String EVENT_LOOP_WORKER_POOL_NAME = "NettyServerWorker"; String NETTY_EPOLL_ENABLE_KEY = "netty.epoll.enable"; String BIND_IP_KEY = "bind.ip"; String BIND_PORT_KEY = "bind.port"; String BIND_RETRY_TIMES = "bind.retry.times"; String BIND_RETRY_INTERVAL = "bind.retry.interval"; String SENT_KEY = "sent"; String DISPATCHER_KEY = "dispatcher"; String CHANNEL_ATTRIBUTE_READONLY_KEY = "channel.readonly"; String CHANNEL_READONLYEVENT_SENT_KEY = "channel.readonly.sent"; String CHANNEL_SEND_READONLYEVENT_KEY = "channel.readonly.send"; String RECONNECT_KEY = "reconnect"; int DEFAULT_RECONNECT_PERIOD = 2000; String CHANNEL_SHUTDOWN_TIMEOUT_KEY = "channel.shutdown.timeout"; String SEND_RECONNECT_KEY = "send.reconnect"; String CHECK_KEY = "check"; String PROMPT_KEY = "prompt"; String DEFAULT_PROMPT = "dubbo>"; String TELNET_KEY = "telnet"; String HEARTBEAT_KEY = "heartbeat"; String HEARTBEAT_CONFIG_KEY = "dubbo.protocol.default-heartbeat"; String CLOSE_TIMEOUT_CONFIG_KEY = "dubbo.protocol.default-close-timeout"; int DEFAULT_HEARTBEAT = 60 * 1000; String HEARTBEAT_TIMEOUT_KEY = "heartbeat.timeout"; String CLOSE_TIMEOUT_KEY = "close.timeout"; String CONNECTIONS_KEY = "connections"; int DEFAULT_BACKLOG = 1024; String CONNECTION = "Connection"; String KEEP_ALIVE = "keep-alive"; String KEEP_ALIVE_HEADER = "Keep-Alive"; String OK_HTTP = "ok-http"; String URL_CONNECTION = "url-connection"; String APACHE_HTTP_CLIENT = "apache-http-client"; String CONTENT_LENGTH_KEY = "content-length"; String USE_SECURE_RANDOM_ID = "dubbo.application.use-secure-random-request-id"; String CONNECTION_HANDLER_NAME = "connectionHandler"; }
7,456
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/ExchangeChannel.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.exchange; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.RemotingException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; /** * ExchangeChannel. (API/SPI, Prototype, ThreadSafe) */ public interface ExchangeChannel extends Channel { /** * send request. * * @param request * @return response future * @throws RemotingException */ @Deprecated CompletableFuture<Object> request(Object request) throws RemotingException; /** * send request. * * @param request * @param timeout * @return response future * @throws RemotingException */ @Deprecated CompletableFuture<Object> request(Object request, int timeout) throws RemotingException; /** * send request. * * @param request * @return response future * @throws RemotingException */ CompletableFuture<Object> request(Object request, ExecutorService executor) throws RemotingException; /** * send request. * * @param request * @param timeout * @return response future * @throws RemotingException */ CompletableFuture<Object> request(Object request, int timeout, ExecutorService executor) throws RemotingException; /** * get message handler. * * @return message handler */ ExchangeHandler getExchangeHandler(); /** * graceful close. * * @param timeout */ @Override void close(int timeout); }
7,457
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/PortUnificationExchanger.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.exchange; 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.ConcurrentHashMapUtils; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.RemotingServer; import org.apache.dubbo.remoting.api.connection.AbstractConnectionClient; import org.apache.dubbo.remoting.api.pu.AbstractPortUnificationServer; import org.apache.dubbo.remoting.api.pu.PortUnificationTransporter; import java.util.ArrayList; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_ERROR_CLOSE_SERVER; public class PortUnificationExchanger { private static final ErrorTypeAwareLogger log = LoggerFactory.getErrorTypeAwareLogger(PortUnificationExchanger.class); private static final ConcurrentMap<String, RemotingServer> servers = new ConcurrentHashMap<>(); public static RemotingServer bind(URL url, ChannelHandler handler) { ConcurrentHashMapUtils.computeIfAbsent(servers, url.getAddress(), addr -> { final AbstractPortUnificationServer server; try { server = getTransporter(url).bind(url, handler); } catch (RemotingException e) { throw new RuntimeException(e); } // server.bind(); return server; }); servers.computeIfPresent(url.getAddress(), (addr, server) -> { ((AbstractPortUnificationServer) server).addSupportedProtocol(url, handler); return server; }); return servers.get(url.getAddress()); } public static AbstractConnectionClient connect(URL url, ChannelHandler handler) { final AbstractConnectionClient connectionClient; try { connectionClient = getTransporter(url).connect(url, handler); } catch (RemotingException e) { throw new RuntimeException(e); } return connectionClient; } public static void close() { final ArrayList<RemotingServer> toClose = new ArrayList<>(servers.values()); servers.clear(); for (RemotingServer server : toClose) { try { server.close(); } catch (Throwable throwable) { log.error(PROTOCOL_ERROR_CLOSE_SERVER, "", "", "Close all port unification server failed", throwable); } } } // for test public static ConcurrentMap<String, RemotingServer> getServers() { return servers; } public static PortUnificationTransporter getTransporter(URL url) { return url.getOrDefaultFrameworkModel() .getExtensionLoader(PortUnificationTransporter.class) .getAdaptiveExtension(); } }
7,458
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Response.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.exchange; import static org.apache.dubbo.common.constants.CommonConstants.HEARTBEAT_EVENT; /** * Response */ public class Response { /** * ok. */ public static final byte OK = 20; /** * serialization error */ public static final byte SERIALIZATION_ERROR = 25; /** * client side timeout. */ public static final byte CLIENT_TIMEOUT = 30; /** * server side timeout. */ public static final byte SERVER_TIMEOUT = 31; /** * channel inactive, directly return the unfinished requests. */ public static final byte CHANNEL_INACTIVE = 35; /** * request format error. */ public static final byte BAD_REQUEST = 40; /** * response format error. */ public static final byte BAD_RESPONSE = 50; /** * service not found. */ public static final byte SERVICE_NOT_FOUND = 60; /** * service error. */ public static final byte SERVICE_ERROR = 70; /** * internal server error. */ public static final byte SERVER_ERROR = 80; /** * internal server error. */ public static final byte CLIENT_ERROR = 90; /** * server side threadpool exhausted and quick return. */ public static final byte SERVER_THREADPOOL_EXHAUSTED_ERROR = 100; private long mId = 0; private String mVersion; private byte mStatus = OK; private boolean mEvent = false; private String mErrorMsg; private Object mResult; public Response() {} public Response(long id) { mId = id; } public Response(long id, String version) { mId = id; mVersion = version; } public long getId() { return mId; } public void setId(long id) { mId = id; } public String getVersion() { return mVersion; } public void setVersion(String version) { mVersion = version; } public byte getStatus() { return mStatus; } public void setStatus(byte status) { mStatus = status; } public boolean isEvent() { return mEvent; } public void setEvent(String event) { mEvent = true; mResult = event; } public void setEvent(boolean mEvent) { this.mEvent = mEvent; } public boolean isHeartbeat() { return mEvent && HEARTBEAT_EVENT == mResult; } @Deprecated public void setHeartbeat(boolean isHeartbeat) { if (isHeartbeat) { setEvent(HEARTBEAT_EVENT); } } public Object getResult() { return mResult; } public void setResult(Object msg) { mResult = msg; } public String getErrorMessage() { return mErrorMsg; } public void setErrorMessage(String msg) { mErrorMsg = msg; } @Override public String toString() { return "Response [id=" + mId + ", version=" + mVersion + ", status=" + mStatus + ", event=" + mEvent + ", error=" + mErrorMsg + ", result=" + (mResult == this ? "this" : mResult) + "]"; } }
7,459
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Exchanger.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.exchange; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.support.header.HeaderExchanger; /** * Exchanger. (SPI, Singleton, ThreadSafe) * <p> * <a href="http://en.wikipedia.org/wiki/Message_Exchange_Pattern">Message Exchange Pattern</a> * <a href="http://en.wikipedia.org/wiki/Request-response">Request-Response</a> */ @SPI(value = HeaderExchanger.NAME, scope = ExtensionScope.FRAMEWORK) public interface Exchanger { /** * bind. * * @param url * @param handler * @return message server */ @Adaptive({Constants.EXCHANGER_KEY}) ExchangeServer bind(URL url, ExchangeHandler handler) throws RemotingException; /** * connect. * * @param url * @param handler * @return message channel */ @Adaptive({Constants.EXCHANGER_KEY}) ExchangeClient connect(URL url, ExchangeHandler handler) throws RemotingException; }
7,460
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/ExchangeServer.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.exchange; import org.apache.dubbo.remoting.RemotingServer; import java.net.InetSocketAddress; import java.util.Collection; /** * ExchangeServer. (API/SPI, Prototype, ThreadSafe) */ public interface ExchangeServer extends RemotingServer { /** * get channels. * * @return channels */ Collection<ExchangeChannel> getExchangeChannels(); /** * get channel. * * @param remoteAddress * @return channel */ ExchangeChannel getExchangeChannel(InetSocketAddress remoteAddress); }
7,461
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Exchangers.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.exchange; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.support.ExchangeHandlerDispatcher; import org.apache.dubbo.remoting.exchange.support.Replier; import org.apache.dubbo.remoting.transport.ChannelHandlerAdapter; /** * Exchanger facade. (API, Static, ThreadSafe) */ public class Exchangers { private Exchangers() {} public static ExchangeServer bind(String url, Replier<?> replier) throws RemotingException { return bind(URL.valueOf(url), replier); } public static ExchangeServer bind(URL url, Replier<?> replier) throws RemotingException { return bind(url, new ChannelHandlerAdapter(), replier); } public static ExchangeServer bind(String url, ChannelHandler handler, Replier<?> replier) throws RemotingException { return bind(URL.valueOf(url), handler, replier); } public static ExchangeServer bind(URL url, ChannelHandler handler, Replier<?> replier) throws RemotingException { return bind(url, new ExchangeHandlerDispatcher(url.getOrDefaultFrameworkModel(), replier, handler)); } public static ExchangeServer bind(String url, ExchangeHandler handler) throws RemotingException { return bind(URL.valueOf(url), handler); } public static ExchangeServer bind(URL url, ExchangeHandler handler) throws RemotingException { if (url == null) { throw new IllegalArgumentException("url == null"); } if (handler == null) { throw new IllegalArgumentException("handler == null"); } url = url.addParameterIfAbsent(Constants.CODEC_KEY, "exchange"); return getExchanger(url).bind(url, handler); } public static ExchangeClient connect(String url) throws RemotingException { return connect(URL.valueOf(url)); } public static ExchangeClient connect(URL url) throws RemotingException { return connect(url, new ChannelHandlerAdapter(), null); } public static ExchangeClient connect(String url, Replier<?> replier) throws RemotingException { return connect(URL.valueOf(url), new ChannelHandlerAdapter(), replier); } public static ExchangeClient connect(URL url, Replier<?> replier) throws RemotingException { return connect(url, new ChannelHandlerAdapter(), replier); } public static ExchangeClient connect(String url, ChannelHandler handler, Replier<?> replier) throws RemotingException { return connect(URL.valueOf(url), handler, replier); } public static ExchangeClient connect(URL url, ChannelHandler handler, Replier<?> replier) throws RemotingException { return connect(url, new ExchangeHandlerDispatcher(url.getOrDefaultFrameworkModel(), replier, handler)); } public static ExchangeClient connect(String url, ExchangeHandler handler) throws RemotingException { return connect(URL.valueOf(url), handler); } public static ExchangeClient connect(URL url, ExchangeHandler handler) throws RemotingException { if (url == null) { throw new IllegalArgumentException("url == null"); } if (handler == null) { throw new IllegalArgumentException("handler == null"); } return getExchanger(url).connect(url, handler); } public static Exchanger getExchanger(URL url) { String type = url.getParameter(Constants.EXCHANGER_KEY, Constants.DEFAULT_EXCHANGER); return url.getOrDefaultFrameworkModel() .getExtensionLoader(Exchanger.class) .getExtension(type); } }
7,462
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/HeartBeatRequest.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.exchange; public class HeartBeatRequest extends Request { private byte proto; public HeartBeatRequest(long id) { super(id); } public byte getProto() { return proto; } public void setProto(byte proto) { this.proto = proto; } }
7,463
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/ExchangeClient.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.exchange; import org.apache.dubbo.remoting.Client; /** * ExchangeClient. (API/SPI, Prototype, ThreadSafe) * * */ public interface ExchangeClient extends Client, ExchangeChannel {}
7,464
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/ExchangeHandler.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.exchange; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.telnet.TelnetHandler; import java.util.concurrent.CompletableFuture; /** * ExchangeHandler. (API, Prototype, ThreadSafe) */ public interface ExchangeHandler extends ChannelHandler, TelnetHandler { /** * reply. * * @param channel * @param request * @return response * @throws RemotingException */ CompletableFuture<Object> reply(ExchangeChannel channel, Object request) throws RemotingException; }
7,465
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/HeartBeatResponse.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.exchange; public class HeartBeatResponse extends Response { private byte proto; public HeartBeatResponse(long id, String version) { super(id, version); } public byte getProto() { return proto; } public void setProto(byte proto) { this.proto = proto; } }
7,466
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Request.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.exchange; import org.apache.dubbo.common.utils.StringUtils; import java.security.SecureRandom; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicLong; import static org.apache.dubbo.common.constants.CommonConstants.HEARTBEAT_EVENT; import static org.apache.dubbo.remoting.Constants.USE_SECURE_RANDOM_ID; /** * Request. */ public class Request { private static final AtomicLong INVOKE_ID; private final long mId; private String mVersion; private boolean mTwoWay = true; private boolean mEvent = false; private boolean mBroken = false; private int mPayload; private Object mData; public Request() { mId = newId(); } public Request(long id) { mId = id; } static { long startID = ThreadLocalRandom.current().nextLong(); if (Boolean.parseBoolean(System.getProperty(USE_SECURE_RANDOM_ID, "false"))) { try { SecureRandom rand = new SecureRandom(SecureRandom.getSeed(20)); startID = rand.nextLong(); } catch (Throwable ignore) { } } INVOKE_ID = new AtomicLong(startID); } private static long newId() { // getAndIncrement() When it grows to MAX_VALUE, it will grow to MIN_VALUE, and the negative can be used as ID return INVOKE_ID.getAndIncrement(); } private static String safeToString(Object data) { if (data == null) { return null; } try { return data.toString(); } catch (Exception e) { return "<Fail toString of " + data.getClass() + ", cause: " + StringUtils.toString(e) + ">"; } } public long getId() { return mId; } public String getVersion() { return mVersion; } public void setVersion(String version) { mVersion = version; } public boolean isTwoWay() { return mTwoWay; } public void setTwoWay(boolean twoWay) { mTwoWay = twoWay; } public boolean isEvent() { return mEvent; } public void setEvent(String event) { this.mEvent = true; this.mData = event; } public void setEvent(boolean mEvent) { this.mEvent = mEvent; } public boolean isBroken() { return mBroken; } public void setBroken(boolean mBroken) { this.mBroken = mBroken; } public int getPayload() { return mPayload; } public void setPayload(int mPayload) { this.mPayload = mPayload; } public Object getData() { return mData; } public void setData(Object msg) { mData = msg; } public boolean isHeartbeat() { return mEvent && HEARTBEAT_EVENT == mData; } public void setHeartbeat(boolean isHeartbeat) { if (isHeartbeat) { setEvent(HEARTBEAT_EVENT); } } public Request copy() { Request copy = new Request(mId); copy.mVersion = this.mVersion; copy.mTwoWay = this.mTwoWay; copy.mEvent = this.mEvent; copy.mBroken = this.mBroken; copy.mPayload = this.mPayload; copy.mData = this.mData; return copy; } public Request copyWithoutData() { Request copy = new Request(mId); copy.mVersion = this.mVersion; copy.mTwoWay = this.mTwoWay; copy.mEvent = this.mEvent; copy.mBroken = this.mBroken; copy.mPayload = this.mPayload; return copy; } @Override public String toString() { return "Request [id=" + mId + ", version=" + mVersion + ", twoWay=" + mTwoWay + ", event=" + mEvent + ", broken=" + mBroken + ", mPayload=" + mPayload + ", data=" + (mData == this ? "this" : safeToString(mData)) + "]"; } }
7,467
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/codec/ExchangeCodec.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.exchange.codec; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.io.Bytes; import org.apache.dubbo.common.io.StreamUtils; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.serialize.Cleanable; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; import org.apache.dubbo.common.serialize.Serialization; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.buffer.ChannelBuffer; import org.apache.dubbo.remoting.buffer.ChannelBufferInputStream; import org.apache.dubbo.remoting.buffer.ChannelBufferOutputStream; import org.apache.dubbo.remoting.exchange.HeartBeatRequest; 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.telnet.codec.TelnetCodec; import org.apache.dubbo.remoting.transport.CodecSupport; import org.apache.dubbo.remoting.transport.ExceedPayloadLimitException; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.Date; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_TIMEOUT_SERVER; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_EXCEED_PAYLOAD_LIMIT; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_RESPONSE; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_SKIP_UNUSED_STREAM; /** * ExchangeCodec. */ public class ExchangeCodec extends TelnetCodec { // header length. protected static final int HEADER_LENGTH = 16; // magic header. protected static final short MAGIC = (short) 0xdabb; protected static final byte MAGIC_HIGH = Bytes.short2bytes(MAGIC)[0]; protected static final byte MAGIC_LOW = Bytes.short2bytes(MAGIC)[1]; // message flag. protected static final byte FLAG_REQUEST = (byte) 0x80; protected static final byte FLAG_TWOWAY = (byte) 0x40; protected static final byte FLAG_EVENT = (byte) 0x20; protected static final int SERIALIZATION_MASK = 0x1f; private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ExchangeCodec.class); public Short getMagicCode() { return MAGIC; } @Override public void encode(Channel channel, ChannelBuffer buffer, Object msg) throws IOException { if (msg instanceof Request) { encodeRequest(channel, buffer, (Request) msg); } else if (msg instanceof Response) { encodeResponse(channel, buffer, (Response) msg); } else { super.encode(channel, buffer, msg); } } @Override public Object decode(Channel channel, ChannelBuffer buffer) throws IOException { int readable = buffer.readableBytes(); byte[] header = new byte[Math.min(readable, HEADER_LENGTH)]; buffer.readBytes(header); return decode(channel, buffer, readable, header); } @Override protected Object decode(Channel channel, ChannelBuffer buffer, int readable, byte[] header) throws IOException { // check magic number. if (readable > 0 && header[0] != MAGIC_HIGH || readable > 1 && header[1] != MAGIC_LOW) { int length = header.length; if (header.length < readable) { header = Bytes.copyOf(header, readable); buffer.readBytes(header, length, readable - length); } for (int i = 1; i < header.length - 1; i++) { if (header[i] == MAGIC_HIGH && header[i + 1] == MAGIC_LOW) { buffer.readerIndex(buffer.readerIndex() - header.length + i); header = Bytes.copyOf(header, i); break; } } return super.decode(channel, buffer, readable, header); } // check length. if (readable < HEADER_LENGTH) { return DecodeResult.NEED_MORE_INPUT; } // get data length. int len = Bytes.bytes2int(header, 12); // When receiving response, how to exceed the length, then directly construct a response to the client. // see more detail from https://github.com/apache/dubbo/issues/7021. Object obj = finishRespWhenOverPayload(channel, len, header); if (null != obj) { return obj; } int tt = len + HEADER_LENGTH; if (readable < tt) { return DecodeResult.NEED_MORE_INPUT; } // limit input stream. ChannelBufferInputStream is = new ChannelBufferInputStream(buffer, len); try { return decodeBody(channel, is, header); } finally { if (is.available() > 0) { try { if (logger.isWarnEnabled()) { logger.warn(TRANSPORT_SKIP_UNUSED_STREAM, "", "", "Skip input stream " + is.available()); } StreamUtils.skipUnusedStream(is); } catch (IOException e) { logger.warn(TRANSPORT_SKIP_UNUSED_STREAM, "", "", e.getMessage(), e); } } } } protected Object decodeBody(Channel channel, InputStream is, byte[] header) throws IOException { byte flag = header[2], proto = (byte) (flag & SERIALIZATION_MASK); // get request id. long id = Bytes.bytes2long(header, 4); if ((flag & FLAG_REQUEST) == 0) { // decode response. Response res = new Response(id); if ((flag & FLAG_EVENT) != 0) { res.setEvent(true); } // get status. byte status = header[3]; res.setStatus(status); try { if (status == Response.OK) { Object data; if (res.isEvent()) { byte[] eventPayload = CodecSupport.getPayload(is); if (CodecSupport.isHeartBeat(eventPayload, proto)) { // heart beat response data is always null; data = null; } else { data = decodeEventData( channel, CodecSupport.deserialize( channel.getUrl(), new ByteArrayInputStream(eventPayload), proto), eventPayload); } } else { data = decodeResponseData( channel, CodecSupport.deserialize(channel.getUrl(), is, proto), getRequestData(channel, res, id)); } res.setResult(data); } else { res.setErrorMessage(CodecSupport.deserialize(channel.getUrl(), is, proto) .readUTF()); } } catch (Throwable t) { res.setStatus(Response.CLIENT_ERROR); res.setErrorMessage(StringUtils.toString(t)); } return res; } else { // decode request. Request req; try { Object data; if ((flag & FLAG_EVENT) != 0) { byte[] eventPayload = CodecSupport.getPayload(is); if (CodecSupport.isHeartBeat(eventPayload, proto)) { // heart beat response data is always null; req = new HeartBeatRequest(id); ((HeartBeatRequest) req).setProto(proto); data = null; } else { req = new Request(id); data = decodeEventData( channel, CodecSupport.deserialize( channel.getUrl(), new ByteArrayInputStream(eventPayload), proto), eventPayload); } req.setEvent(true); } else { req = new Request(id); data = decodeRequestData(channel, CodecSupport.deserialize(channel.getUrl(), is, proto)); } req.setData(data); } catch (Throwable t) { // bad request req = new Request(id); req.setBroken(true); req.setData(t); } req.setVersion(Version.getProtocolVersion()); req.setTwoWay((flag & FLAG_TWOWAY) != 0); return req; } } protected Object getRequestData(Channel channel, Response response, long id) { DefaultFuture future = DefaultFuture.getFuture(id); if (future != null) { Request req = future.getRequest(); if (req != null) { return req.getData(); } } logger.warn( PROTOCOL_TIMEOUT_SERVER, "", "", "The timeout response finally returned at " + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date())) + ", response status is " + response.getStatus() + ", response id is " + response.getId() + (channel == null ? "" : ", channel: " + channel.getLocalAddress() + " -> " + channel.getRemoteAddress()) + ", please check provider side for detailed result."); throw new IllegalArgumentException("Failed to find any request match the response, response id: " + id); } protected void encodeRequest(Channel channel, ChannelBuffer buffer, Request req) throws IOException { Serialization serialization = getSerialization(channel, req); // header. byte[] header = new byte[HEADER_LENGTH]; // set magic number. Bytes.short2bytes(MAGIC, header); // set request and serialization flag. header[2] = (byte) (FLAG_REQUEST | serialization.getContentTypeId()); if (req.isTwoWay()) { header[2] |= FLAG_TWOWAY; } if (req.isEvent()) { header[2] |= FLAG_EVENT; } // set request id. Bytes.long2bytes(req.getId(), header, 4); // encode request data. int savedWriteIndex = buffer.writerIndex(); buffer.writerIndex(savedWriteIndex + HEADER_LENGTH); ChannelBufferOutputStream bos = new ChannelBufferOutputStream(buffer); if (req.isHeartbeat()) { // heartbeat request data is always null bos.write(CodecSupport.getNullBytesOf(serialization)); } else { ObjectOutput out = serialization.serialize(channel.getUrl(), bos); if (req.isEvent()) { encodeEventData(channel, out, req.getData()); } else { encodeRequestData(channel, out, req.getData(), req.getVersion()); } out.flushBuffer(); if (out instanceof Cleanable) { ((Cleanable) out).cleanup(); } } bos.flush(); bos.close(); int len = bos.writtenBytes(); checkPayload(channel, req.getPayload(), len); Bytes.int2bytes(len, header, 12); // write buffer.writerIndex(savedWriteIndex); buffer.writeBytes(header); // write header. buffer.writerIndex(savedWriteIndex + HEADER_LENGTH + len); } protected void encodeResponse(Channel channel, ChannelBuffer buffer, Response res) throws IOException { int savedWriteIndex = buffer.writerIndex(); try { Serialization serialization = getSerialization(channel, res); // header. byte[] header = new byte[HEADER_LENGTH]; // set magic number. Bytes.short2bytes(MAGIC, header); // set request and serialization flag. header[2] = serialization.getContentTypeId(); if (res.isHeartbeat()) { header[2] |= FLAG_EVENT; } // set response status. byte status = res.getStatus(); header[3] = status; // set request id. Bytes.long2bytes(res.getId(), header, 4); buffer.writerIndex(savedWriteIndex + HEADER_LENGTH); ChannelBufferOutputStream bos = new ChannelBufferOutputStream(buffer); // encode response data or error message. if (status == Response.OK) { if (res.isHeartbeat()) { // heartbeat response data is always null bos.write(CodecSupport.getNullBytesOf(serialization)); } else { ObjectOutput out = serialization.serialize(channel.getUrl(), bos); if (res.isEvent()) { encodeEventData(channel, out, res.getResult()); } else { encodeResponseData(channel, out, res.getResult(), res.getVersion()); } out.flushBuffer(); if (out instanceof Cleanable) { ((Cleanable) out).cleanup(); } } } else { ObjectOutput out = serialization.serialize(channel.getUrl(), bos); out.writeUTF(res.getErrorMessage()); out.flushBuffer(); if (out instanceof Cleanable) { ((Cleanable) out).cleanup(); } } bos.flush(); bos.close(); int len = bos.writtenBytes(); checkPayload(channel, len); Bytes.int2bytes(len, header, 12); // write buffer.writerIndex(savedWriteIndex); buffer.writeBytes(header); // write header. buffer.writerIndex(savedWriteIndex + HEADER_LENGTH + len); } catch (Throwable t) { // clear buffer buffer.writerIndex(savedWriteIndex); // send error message to Consumer, otherwise, Consumer will wait till timeout. if (!res.isEvent() && res.getStatus() != Response.BAD_RESPONSE) { Response r = new Response(res.getId(), res.getVersion()); r.setStatus(Response.BAD_RESPONSE); if (t instanceof ExceedPayloadLimitException) { logger.warn(TRANSPORT_EXCEED_PAYLOAD_LIMIT, "", "", t.getMessage(), t); try { r.setErrorMessage(t.getMessage()); r.setStatus(Response.SERIALIZATION_ERROR); channel.send(r); return; } catch (RemotingException e) { logger.warn( TRANSPORT_FAILED_RESPONSE, "", "", "Failed to send bad_response info back: " + t.getMessage() + ", cause: " + e.getMessage(), e); } } else { // FIXME log error message in Codec and handle in caught() of IoHanndler? logger.warn( TRANSPORT_FAILED_RESPONSE, "", "", "Fail to encode response: " + res + ", send bad_response info instead, cause: " + t.getMessage(), t); try { r.setErrorMessage("Failed to send response: " + res + ", cause: " + StringUtils.toString(t)); channel.send(r); return; } catch (RemotingException e) { logger.warn( TRANSPORT_FAILED_RESPONSE, "", "", "Failed to send bad_response info back: " + res + ", cause: " + e.getMessage(), e); } } } // Rethrow exception if (t instanceof IOException) { throw (IOException) t; } else if (t instanceof RuntimeException) { throw (RuntimeException) t; } else if (t instanceof Error) { throw (Error) t; } else { throw new RuntimeException(t.getMessage(), t); } } } @Override protected Object decodeData(ObjectInput in) throws IOException { return decodeRequestData(in); } protected Object decodeRequestData(ObjectInput in) throws IOException { try { return in.readObject(); } catch (ClassNotFoundException e) { throw new IOException(StringUtils.toString("Read object failed.", e)); } } protected Object decodeResponseData(ObjectInput in) throws IOException { try { return in.readObject(); } catch (ClassNotFoundException e) { throw new IOException(StringUtils.toString("Read object failed.", e)); } } @Override protected void encodeData(ObjectOutput out, Object data) throws IOException { encodeRequestData(out, data); } private void encodeEventData(ObjectOutput out, Object data) throws IOException { out.writeEvent((String) data); } @Deprecated protected void encodeHeartbeatData(ObjectOutput out, Object data) throws IOException { encodeEventData(out, data); } protected void encodeRequestData(ObjectOutput out, Object data) throws IOException { out.writeObject(data); } protected void encodeResponseData(ObjectOutput out, Object data) throws IOException { out.writeObject(data); } @Override protected Object decodeData(Channel channel, ObjectInput in) throws IOException { return decodeRequestData(channel, in); } protected Object decodeEventData(Channel channel, ObjectInput in, byte[] eventBytes) throws IOException { try { if (eventBytes != null) { int dataLen = eventBytes.length; int threshold = ConfigurationUtils.getSystemConfiguration( channel.getUrl().getScopeModel()) .getInt("deserialization.event.size", 15); if (dataLen > threshold) { throw new IllegalArgumentException("Event data too long, actual size " + threshold + ", threshold " + threshold + " rejected for security consideration."); } } return in.readEvent(); } catch (IOException | ClassNotFoundException e) { throw new IOException(StringUtils.toString("Decode dubbo protocol event failed.", e)); } } protected Object decodeRequestData(Channel channel, ObjectInput in) throws IOException { return decodeRequestData(in); } protected Object decodeResponseData(Channel channel, ObjectInput in) throws IOException { return decodeResponseData(in); } protected Object decodeResponseData(Channel channel, ObjectInput in, Object requestData) throws IOException { return decodeResponseData(channel, in); } @Override protected void encodeData(Channel channel, ObjectOutput out, Object data) throws IOException { encodeRequestData(channel, out, data); } private void encodeEventData(Channel channel, ObjectOutput out, Object data) throws IOException { encodeEventData(out, data); } @Deprecated protected void encodeHeartbeatData(Channel channel, ObjectOutput out, Object data) throws IOException { encodeHeartbeatData(out, data); } protected void encodeRequestData(Channel channel, ObjectOutput out, Object data) throws IOException { encodeRequestData(out, data); } protected void encodeResponseData(Channel channel, ObjectOutput out, Object data) throws IOException { encodeResponseData(out, data); } protected void encodeRequestData(Channel channel, ObjectOutput out, Object data, String version) throws IOException { encodeRequestData(out, data); } protected void encodeResponseData(Channel channel, ObjectOutput out, Object data, String version) throws IOException { encodeResponseData(out, data); } private Object finishRespWhenOverPayload(Channel channel, long size, byte[] header) { byte flag = header[2]; if ((flag & FLAG_REQUEST) == 0) { int payload = getPayload(channel); boolean overPayload = isOverPayload(payload, size); if (overPayload) { long reqId = Bytes.bytes2long(header, 4); Response res = new Response(reqId); if ((flag & FLAG_EVENT) != 0) { res.setEvent(true); } res.setStatus(Response.CLIENT_ERROR); String errorMsg = "Data length too large: " + size + ", max payload: " + payload + ", channel: " + channel; logger.error(TRANSPORT_EXCEED_PAYLOAD_LIMIT, "", "", errorMsg); res.setErrorMessage(errorMsg); return res; } } return null; } }
7,468
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/MultiMessage.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.exchange.support; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * @see org.apache.dubbo.remoting.transport.MultiMessageHandler */ public final class MultiMessage implements Iterable { private final List messages = new ArrayList(); private MultiMessage() {} public static MultiMessage createFromCollection(Collection collection) { MultiMessage result = new MultiMessage(); result.addMessages(collection); return result; } public static MultiMessage createFromArray(Object... args) { return createFromCollection(Arrays.asList(args)); } public static MultiMessage create() { return new MultiMessage(); } public void addMessage(Object msg) { messages.add(msg); } public void addMessages(Collection collection) { messages.addAll(collection); } public Collection getMessages() { return Collections.unmodifiableCollection(messages); } public int size() { return messages.size(); } public Object get(int index) { return messages.get(index); } public boolean isEmpty() { return messages.isEmpty(); } public Collection removeMessages() { Collection result = Collections.unmodifiableCollection(messages); messages.clear(); return result; } @Override public Iterator iterator() { return messages.iterator(); } }
7,469
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/ExchangeHandlerAdapter.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.exchange.support; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.ExchangeChannel; import org.apache.dubbo.remoting.exchange.ExchangeHandler; import org.apache.dubbo.remoting.telnet.support.TelnetHandlerAdapter; import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.concurrent.CompletableFuture; /** * ExchangeHandlerAdapter */ public abstract class ExchangeHandlerAdapter extends TelnetHandlerAdapter implements ExchangeHandler { public ExchangeHandlerAdapter(FrameworkModel frameworkModel) { super(frameworkModel); } @Override public CompletableFuture<Object> reply(ExchangeChannel channel, Object msg) throws RemotingException { return null; } }
7,470
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/DefaultFuture.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.exchange.support; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.resource.GlobalResourceInitializer; import org.apache.dubbo.common.serialize.SerializationException; import org.apache.dubbo.common.threadpool.ThreadlessExecutor; import org.apache.dubbo.common.timer.HashedWheelTimer; import org.apache.dubbo.common.timer.Timeout; import org.apache.dubbo.common.timer.Timer; import org.apache.dubbo.common.timer.TimerTask; import org.apache.dubbo.common.utils.NamedThreadFactory; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.TimeoutException; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.Response; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; 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.PROTOCOL_TIMEOUT_SERVER; /** * DefaultFuture. */ public class DefaultFuture extends CompletableFuture<Object> { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DefaultFuture.class); /** * in-flight channels */ private static final Map<Long, Channel> CHANNELS = new ConcurrentHashMap<>(); /** * in-flight requests */ private static final Map<Long, DefaultFuture> FUTURES = new ConcurrentHashMap<>(); private static final GlobalResourceInitializer<Timer> TIME_OUT_TIMER = new GlobalResourceInitializer<>( () -> new HashedWheelTimer(new NamedThreadFactory("dubbo-future-timeout", true), 30, TimeUnit.MILLISECONDS), DefaultFuture::destroy); // invoke id. private final Long id; private final Channel channel; private final Request request; private final int timeout; private final long start = System.currentTimeMillis(); private volatile long sent; private Timeout timeoutCheckTask; private ExecutorService executor; public ExecutorService getExecutor() { return executor; } public void setExecutor(ExecutorService executor) { this.executor = executor; } private DefaultFuture(Channel channel, Request request, int timeout) { this.channel = channel; this.request = request; this.id = request.getId(); this.timeout = timeout > 0 ? timeout : channel.getUrl().getPositiveParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT); // put into waiting map. FUTURES.put(id, this); CHANNELS.put(id, channel); } /** * check time out of the future */ private static void timeoutCheck(DefaultFuture future) { TimeoutCheckTask task = new TimeoutCheckTask(future.getId()); future.timeoutCheckTask = TIME_OUT_TIMER.get().newTimeout(task, future.getTimeout(), TimeUnit.MILLISECONDS); } public static void destroy() { TIME_OUT_TIMER.remove(Timer::stop); FUTURES.clear(); CHANNELS.clear(); } /** * init a DefaultFuture * 1.init a DefaultFuture * 2.timeout check * * @param channel channel * @param request the request * @param timeout timeout * @return a new DefaultFuture */ public static DefaultFuture newFuture(Channel channel, Request request, int timeout, ExecutorService executor) { final DefaultFuture future = new DefaultFuture(channel, request, timeout); future.setExecutor(executor); // timeout check timeoutCheck(future); return future; } public static DefaultFuture getFuture(long id) { return FUTURES.get(id); } public static boolean hasFuture(Channel channel) { return CHANNELS.containsValue(channel); } public static void sent(Channel channel, Request request) { DefaultFuture future = FUTURES.get(request.getId()); if (future != null) { future.doSent(); } } /** * close a channel when a channel is inactive * directly return the unfinished requests. * * @param channel channel to close */ public static void closeChannel(Channel channel, long timeout) { long deadline = timeout > 0 ? System.currentTimeMillis() + timeout : 0; for (Map.Entry<Long, Channel> entry : CHANNELS.entrySet()) { if (channel.equals(entry.getValue())) { DefaultFuture future = getFuture(entry.getKey()); if (future != null && !future.isDone()) { long restTime = deadline - System.currentTimeMillis(); if (restTime > 0) { try { future.get(restTime, TimeUnit.MILLISECONDS); } catch (java.util.concurrent.TimeoutException ignore) { logger.warn( PROTOCOL_TIMEOUT_SERVER, "", "", "Trying to close channel " + channel + ", but response is not received in " + timeout + "ms, and the request id is " + future.id); } catch (Throwable ignore) { } } if (!future.isDone()) { respInactive(channel, future); } } } } } private static void respInactive(Channel channel, DefaultFuture future) { Response disconnectResponse = new Response(future.getId()); disconnectResponse.setStatus(Response.CHANNEL_INACTIVE); disconnectResponse.setErrorMessage("Channel " + channel + " is inactive. Directly return the unFinished request : " + (logger.isDebugEnabled() ? future.getRequest() : future.getRequest().copyWithoutData())); DefaultFuture.received(channel, disconnectResponse); } public static void received(Channel channel, Response response) { received(channel, response, false); } public static void received(Channel channel, Response response, boolean timeout) { try { DefaultFuture future = FUTURES.remove(response.getId()); if (future != null) { Timeout t = future.timeoutCheckTask; if (!timeout) { // decrease Time t.cancel(); } future.doReceived(response); shutdownExecutorIfNeeded(future); } else { logger.warn( PROTOCOL_TIMEOUT_SERVER, "", "", "The timeout response finally returned at " + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date())) + ", response status is " + response.getStatus() + (channel == null ? "" : ", channel: " + channel.getLocalAddress() + " -> " + channel.getRemoteAddress()) + ", please check provider side for detailed result."); } } finally { CHANNELS.remove(response.getId()); } } @Override public boolean cancel(boolean mayInterruptIfRunning) { Response errorResult = new Response(id); errorResult.setStatus(Response.CLIENT_ERROR); errorResult.setErrorMessage("request future has been canceled."); this.doReceived(errorResult); DefaultFuture future = FUTURES.remove(id); shutdownExecutorIfNeeded(future); CHANNELS.remove(id); timeoutCheckTask.cancel(); return true; } private static void shutdownExecutorIfNeeded(DefaultFuture future) { ExecutorService executor = future.getExecutor(); if (executor instanceof ThreadlessExecutor && !executor.isShutdown()) { executor.shutdownNow(); } } public void cancel() { this.cancel(true); } private void doReceived(Response res) { if (res == null) { throw new IllegalStateException("response cannot be null"); } if (res.getStatus() == Response.OK) { this.complete(res.getResult()); } else if (res.getStatus() == Response.CLIENT_TIMEOUT || res.getStatus() == Response.SERVER_TIMEOUT) { this.completeExceptionally( new TimeoutException(res.getStatus() == Response.SERVER_TIMEOUT, channel, res.getErrorMessage())); } else if (res.getStatus() == Response.SERIALIZATION_ERROR) { this.completeExceptionally(new SerializationException(res.getErrorMessage())); } else { this.completeExceptionally(new RemotingException(channel, res.getErrorMessage())); } } private long getId() { return id; } private Channel getChannel() { return channel; } private boolean isSent() { return sent > 0; } public Request getRequest() { return request; } private int getTimeout() { return timeout; } private void doSent() { sent = System.currentTimeMillis(); } private String getTimeoutMessage(boolean scan) { long nowTimestamp = System.currentTimeMillis(); return (sent > 0 && sent - start < timeout ? "Waiting server-side response timeout" : "Sending request timeout in client-side") + (scan ? " by scan timer" : "") + ". start time: " + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date(start))) + ", end time: " + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date(nowTimestamp))) + "," + (sent > 0 ? " client elapsed: " + (sent - start) + " ms, server elapsed: " + (nowTimestamp - sent) : " elapsed: " + (nowTimestamp - start)) + " ms, timeout: " + timeout + " ms, request: " + (logger.isDebugEnabled() ? request : request.copyWithoutData()) + ", channel: " + channel.getLocalAddress() + " -> " + channel.getRemoteAddress(); } private static class TimeoutCheckTask implements TimerTask { private final Long requestID; TimeoutCheckTask(Long requestID) { this.requestID = requestID; } @Override public void run(Timeout timeout) { DefaultFuture future = DefaultFuture.getFuture(requestID); if (future == null || future.isDone()) { return; } ExecutorService executor = future.getExecutor(); if (executor != null && !executor.isShutdown()) { executor.execute(() -> notifyTimeout(future)); } else { notifyTimeout(future); } } private void notifyTimeout(DefaultFuture future) { // create exception response. Response timeoutResponse = new Response(future.getId()); // set timeout status. timeoutResponse.setStatus(future.isSent() ? Response.SERVER_TIMEOUT : Response.CLIENT_TIMEOUT); timeoutResponse.setErrorMessage(future.getTimeoutMessage(true)); // handle response. DefaultFuture.received(future.getChannel(), timeoutResponse, true); } } }
7,471
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/ExchangeServerDelegate.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.exchange.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.ExchangeChannel; import org.apache.dubbo.remoting.exchange.ExchangeServer; import java.net.InetSocketAddress; import java.util.Collection; /** * ExchangeServerDelegate */ public class ExchangeServerDelegate implements ExchangeServer { private transient ExchangeServer server; public ExchangeServerDelegate() {} public ExchangeServerDelegate(ExchangeServer server) { setServer(server); } public ExchangeServer getServer() { return server; } public void setServer(ExchangeServer server) { this.server = server; } @Override public boolean isBound() { return server.isBound(); } @Override public void reset(URL url) { server.reset(url); } @Override @Deprecated public void reset(org.apache.dubbo.common.Parameters parameters) { reset(getUrl().addParameters(parameters.getParameters())); } @Override public Collection<Channel> getChannels() { return server.getChannels(); } @Override public Channel getChannel(InetSocketAddress remoteAddress) { return server.getChannel(remoteAddress); } @Override public URL getUrl() { return server.getUrl(); } @Override public ChannelHandler getChannelHandler() { return server.getChannelHandler(); } @Override public InetSocketAddress getLocalAddress() { return server.getLocalAddress(); } @Override public void send(Object message) throws RemotingException { server.send(message); } @Override public void send(Object message, boolean sent) throws RemotingException { server.send(message, sent); } @Override public void close() { server.close(); } @Override public boolean isClosed() { return server.isClosed(); } @Override public Collection<ExchangeChannel> getExchangeChannels() { return server.getExchangeChannels(); } @Override public ExchangeChannel getExchangeChannel(InetSocketAddress remoteAddress) { return server.getExchangeChannel(remoteAddress); } @Override public void close(int timeout) { server.close(timeout); } @Override public void startClose() { server.startClose(); } }
7,472
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/ExchangeHandlerDispatcher.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.exchange.support; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.ExchangeChannel; import org.apache.dubbo.remoting.exchange.ExchangeHandler; import org.apache.dubbo.remoting.telnet.TelnetHandler; import org.apache.dubbo.remoting.telnet.support.TelnetHandlerAdapter; import org.apache.dubbo.remoting.transport.ChannelHandlerDispatcher; import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.concurrent.CompletableFuture; /** * ExchangeHandlerDispatcher */ public class ExchangeHandlerDispatcher implements ExchangeHandler { private final ReplierDispatcher replierDispatcher; private final ChannelHandlerDispatcher handlerDispatcher; private final TelnetHandler telnetHandler; public ExchangeHandlerDispatcher() { this(FrameworkModel.defaultModel(), null, (ChannelHandler) null); } public ExchangeHandlerDispatcher(Replier<?> replier) { this(FrameworkModel.defaultModel(), replier, (ChannelHandler) null); } public ExchangeHandlerDispatcher(ChannelHandler... handlers) { this(FrameworkModel.defaultModel(), null, handlers); } public ExchangeHandlerDispatcher(FrameworkModel frameworkModel, Replier<?> replier, ChannelHandler... handlers) { replierDispatcher = new ReplierDispatcher(replier); handlerDispatcher = new ChannelHandlerDispatcher(handlers); telnetHandler = new TelnetHandlerAdapter(frameworkModel); } public ExchangeHandlerDispatcher addChannelHandler(ChannelHandler handler) { handlerDispatcher.addChannelHandler(handler); return this; } public ExchangeHandlerDispatcher removeChannelHandler(ChannelHandler handler) { handlerDispatcher.removeChannelHandler(handler); return this; } public <T> ExchangeHandlerDispatcher addReplier(Class<T> type, Replier<T> replier) { replierDispatcher.addReplier(type, replier); return this; } public <T> ExchangeHandlerDispatcher removeReplier(Class<T> type) { replierDispatcher.removeReplier(type); return this; } @Override @SuppressWarnings({"unchecked", "rawtypes"}) public CompletableFuture<Object> reply(ExchangeChannel channel, Object request) throws RemotingException { return CompletableFuture.completedFuture(((Replier) replierDispatcher).reply(channel, request)); } @Override public void connected(Channel channel) { handlerDispatcher.connected(channel); } @Override public void disconnected(Channel channel) { handlerDispatcher.disconnected(channel); } @Override public void sent(Channel channel, Object message) { handlerDispatcher.sent(channel, message); } @Override public void received(Channel channel, Object message) { handlerDispatcher.received(channel, message); } @Override public void caught(Channel channel, Throwable exception) { handlerDispatcher.caught(channel, exception); } @Override public String telnet(Channel channel, String message) throws RemotingException { return telnetHandler.telnet(channel, message); } }
7,473
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/ReplierDispatcher.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.exchange.support; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.ExchangeChannel; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * ReplierDispatcher */ public class ReplierDispatcher implements Replier<Object> { private final Replier<?> defaultReplier; private final Map<Class<?>, Replier<?>> repliers = new ConcurrentHashMap<Class<?>, Replier<?>>(); public ReplierDispatcher() { this(null, null); } public ReplierDispatcher(Replier<?> defaultReplier) { this(defaultReplier, null); } public ReplierDispatcher(Replier<?> defaultReplier, Map<Class<?>, Replier<?>> repliers) { this.defaultReplier = defaultReplier; if (CollectionUtils.isNotEmptyMap(repliers)) { this.repliers.putAll(repliers); } } public <T> ReplierDispatcher addReplier(Class<T> type, Replier<T> replier) { repliers.put(type, replier); return this; } public <T> ReplierDispatcher removeReplier(Class<T> type) { repliers.remove(type); return this; } private Replier<?> getReplier(Class<?> type) { for (Map.Entry<Class<?>, Replier<?>> entry : repliers.entrySet()) { if (entry.getKey().isAssignableFrom(type)) { return entry.getValue(); } } if (defaultReplier != null) { return defaultReplier; } throw new IllegalStateException("Replier not found, Unsupported message object: " + type); } @Override @SuppressWarnings({"unchecked", "rawtypes"}) public Object reply(ExchangeChannel channel, Object request) throws RemotingException { return ((Replier) getReplier(request.getClass())).reply(channel, request); } }
7,474
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/Replier.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.exchange.support; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.ExchangeChannel; /** * Replier. (API, Prototype, ThreadSafe) */ public interface Replier<T> { /** * reply. * * @param channel * @param request * @return response * @throws RemotingException */ Object reply(ExchangeChannel channel, T request) throws RemotingException; }
7,475
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/AbstractTimerTask.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.exchange.support.header; import org.apache.dubbo.common.timer.HashedWheelTimer; import org.apache.dubbo.common.timer.Timeout; import org.apache.dubbo.common.timer.TimerTask; import org.apache.dubbo.remoting.Channel; import java.util.Collection; import java.util.concurrent.TimeUnit; /** * AbstractTimerTask */ public abstract class AbstractTimerTask implements TimerTask { private final ChannelProvider channelProvider; private final HashedWheelTimer hashedWheelTimer; private final Long tick; protected volatile boolean cancel = false; private volatile Timeout timeout; AbstractTimerTask(ChannelProvider channelProvider, HashedWheelTimer hashedWheelTimer, Long tick) { if (channelProvider == null || hashedWheelTimer == null || tick == null) { throw new IllegalArgumentException(); } this.channelProvider = channelProvider; this.hashedWheelTimer = hashedWheelTimer; this.tick = tick; start(); } static Long lastRead(Channel channel) { return (Long) channel.getAttribute(HeartbeatHandler.KEY_READ_TIMESTAMP); } static Long lastWrite(Channel channel) { return (Long) channel.getAttribute(HeartbeatHandler.KEY_WRITE_TIMESTAMP); } static Long now() { return System.currentTimeMillis(); } private void start() { this.timeout = hashedWheelTimer.newTimeout(this, tick, TimeUnit.MILLISECONDS); } public synchronized void cancel() { this.cancel = true; this.timeout.cancel(); } private synchronized void reput(Timeout timeout) { if (timeout == null) { throw new IllegalArgumentException(); } if (cancel) { return; } if (hashedWheelTimer.isStop() || timeout.isCancelled()) { return; } this.timeout = hashedWheelTimer.newTimeout(timeout.task(), tick, TimeUnit.MILLISECONDS); } @Override public synchronized void run(Timeout timeout) throws Exception { Collection<Channel> channels = channelProvider.getChannels(); for (Channel channel : channels) { if (!channel.isClosed()) { doTask(channel); } } reput(timeout); } protected abstract void doTask(Channel channel); interface ChannelProvider { Collection<Channel> getChannels(); } }
7,476
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeClient.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.exchange.support.header; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.resource.GlobalResourceInitializer; import org.apache.dubbo.common.timer.HashedWheelTimer; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.common.utils.NamedThreadFactory; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Client; 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.ExchangeClient; import org.apache.dubbo.remoting.exchange.ExchangeHandler; import java.net.InetSocketAddress; import java.util.Collections; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import static org.apache.dubbo.remoting.Constants.HEARTBEAT_CHECK_TICK; import static org.apache.dubbo.remoting.Constants.LEAST_HEARTBEAT_DURATION; import static org.apache.dubbo.remoting.Constants.LEAST_RECONNECT_DURATION; import static org.apache.dubbo.remoting.Constants.LEAST_RECONNECT_DURATION_KEY; import static org.apache.dubbo.remoting.Constants.TICKS_PER_WHEEL; import static org.apache.dubbo.remoting.utils.UrlUtils.getHeartbeat; import static org.apache.dubbo.remoting.utils.UrlUtils.getIdleTimeout; /** * DefaultMessageClient */ public class HeaderExchangeClient implements ExchangeClient { private final Client client; private final ExchangeChannel channel; public static GlobalResourceInitializer<HashedWheelTimer> IDLE_CHECK_TIMER = new GlobalResourceInitializer<>( () -> new HashedWheelTimer( new NamedThreadFactory("dubbo-client-heartbeat-reconnect", true), 1, TimeUnit.SECONDS, TICKS_PER_WHEEL), HashedWheelTimer::stop); private ReconnectTimerTask reconnectTimerTask; private HeartbeatTimerTask heartBeatTimerTask; private final int idleTimeout; public HeaderExchangeClient(Client client, boolean startTimer) { Assert.notNull(client, "Client can't be null"); this.client = client; this.channel = new HeaderExchangeChannel(client); if (startTimer) { URL url = client.getUrl(); idleTimeout = getIdleTimeout(url); startReconnectTask(url); startHeartBeatTask(url); } else { idleTimeout = 0; } } @Override public CompletableFuture<Object> request(Object request) throws RemotingException { return channel.request(request); } @Override public URL getUrl() { return channel.getUrl(); } @Override public InetSocketAddress getRemoteAddress() { return channel.getRemoteAddress(); } @Override public CompletableFuture<Object> request(Object request, int timeout) throws RemotingException { return channel.request(request, timeout); } @Override public CompletableFuture<Object> request(Object request, ExecutorService executor) throws RemotingException { return channel.request(request, executor); } @Override public CompletableFuture<Object> request(Object request, int timeout, ExecutorService executor) throws RemotingException { return channel.request(request, timeout, executor); } @Override public ChannelHandler getChannelHandler() { return channel.getChannelHandler(); } @Override public boolean isConnected() { if (channel.isConnected()) { if (idleTimeout <= 0) { return true; } Long lastRead = (Long) channel.getAttribute(HeartbeatHandler.KEY_READ_TIMESTAMP); Long now = System.currentTimeMillis(); return lastRead == null || now - lastRead < idleTimeout; } return false; } @Override public InetSocketAddress getLocalAddress() { return channel.getLocalAddress(); } @Override public ExchangeHandler getExchangeHandler() { return channel.getExchangeHandler(); } @Override public void send(Object message) throws RemotingException { channel.send(message); } @Override public void send(Object message, boolean sent) throws RemotingException { channel.send(message, sent); } @Override public boolean isClosed() { return channel.isClosed(); } @Override public synchronized void close() { doClose(); channel.close(); } @Override public void close(int timeout) { // Mark the client into the closure process startClose(); doClose(); channel.close(timeout); } @Override public void startClose() { channel.startClose(); } @Override public void reset(URL url) { client.reset(url); // FIXME, should cancel and restart timer tasks if parameters in the new URL are different? } @Override @Deprecated public void reset(org.apache.dubbo.common.Parameters parameters) { reset(getUrl().addParameters(parameters.getParameters())); } @Override public synchronized void reconnect() throws RemotingException { client.reconnect(); } @Override public Object getAttribute(String key) { return channel.getAttribute(key); } @Override public void setAttribute(String key, Object value) { channel.setAttribute(key, value); } @Override public void removeAttribute(String key) { channel.removeAttribute(key); } @Override public boolean hasAttribute(String key) { return channel.hasAttribute(key); } private void startHeartBeatTask(URL url) { if (!client.canHandleIdle()) { int heartbeat = getHeartbeat(url); long heartbeatTick = calculateLeastDuration(heartbeat); heartBeatTimerTask = new HeartbeatTimerTask( () -> Collections.singleton(this), IDLE_CHECK_TIMER.get(), heartbeatTick, heartbeat); } } private void startReconnectTask(URL url) { if (shouldReconnect(url)) { long heartbeatTimeoutTick = calculateLeastDuration(idleTimeout); reconnectTimerTask = new ReconnectTimerTask( () -> Collections.singleton(this), IDLE_CHECK_TIMER.get(), calculateReconnectDuration(url, heartbeatTimeoutTick), idleTimeout); } } private void doClose() { if (heartBeatTimerTask != null) { heartBeatTimerTask.cancel(); heartBeatTimerTask = null; } if (reconnectTimerTask != null) { reconnectTimerTask.cancel(); reconnectTimerTask = null; } } /** * Each interval cannot be less than 1000ms. */ private long calculateLeastDuration(int time) { if (time / HEARTBEAT_CHECK_TICK <= 0) { return LEAST_HEARTBEAT_DURATION; } else { return time / HEARTBEAT_CHECK_TICK; } } private long calculateReconnectDuration(URL url, long tick) { long leastReconnectDuration = url.getParameter(LEAST_RECONNECT_DURATION_KEY, LEAST_RECONNECT_DURATION); return Math.max(leastReconnectDuration, tick); } protected boolean shouldReconnect(URL url) { return !Boolean.FALSE.toString().equalsIgnoreCase(url.getParameter(Constants.RECONNECT_KEY)); } @Override public String toString() { return "HeaderExchangeClient [channel=" + channel + "]"; } }
7,477
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatTimerTask.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.exchange.support.header; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.timer.HashedWheelTimer; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.exchange.Request; import static org.apache.dubbo.common.constants.CommonConstants.HEARTBEAT_EVENT; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_RESPONSE; /** * HeartbeatTimerTask */ public class HeartbeatTimerTask extends AbstractTimerTask { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(HeartbeatTimerTask.class); private final int heartbeat; HeartbeatTimerTask( ChannelProvider channelProvider, HashedWheelTimer hashedWheelTimer, Long heartbeatTick, int heartbeat) { super(channelProvider, hashedWheelTimer, heartbeatTick); this.heartbeat = heartbeat; } @Override protected void doTask(Channel channel) { try { Long lastRead = lastRead(channel); Long lastWrite = lastWrite(channel); Long now = now(); if ((lastRead != null && now - lastRead > heartbeat) || (lastWrite != null && now - lastWrite > heartbeat)) { Request req = new Request(); req.setVersion(Version.getProtocolVersion()); req.setTwoWay(true); req.setEvent(HEARTBEAT_EVENT); channel.send(req); if (logger.isDebugEnabled()) { logger.debug("Send heartbeat to remote channel " + channel.getRemoteAddress() + ", cause: The channel has no data-transmission exceeds a heartbeat period: " + heartbeat + "ms"); } } } catch (Throwable t) { logger.warn( TRANSPORT_FAILED_RESPONSE, "", "", "Exception when heartbeat to remote channel " + channel.getRemoteAddress(), t); } } }
7,478
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandler.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.exchange.support.header; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; 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.exchange.HeartBeatRequest; import org.apache.dubbo.remoting.exchange.HeartBeatResponse; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.Response; import org.apache.dubbo.remoting.transport.AbstractChannelHandlerDelegate; import static org.apache.dubbo.common.constants.CommonConstants.HEARTBEAT_EVENT; public class HeartbeatHandler extends AbstractChannelHandlerDelegate { private static final Logger logger = LoggerFactory.getLogger(HeartbeatHandler.class); public static final String KEY_READ_TIMESTAMP = "READ_TIMESTAMP"; public static final String KEY_WRITE_TIMESTAMP = "WRITE_TIMESTAMP"; public HeartbeatHandler(ChannelHandler handler) { super(handler); } @Override public void connected(Channel channel) throws RemotingException { setReadTimestamp(channel); setWriteTimestamp(channel); handler.connected(channel); } @Override public void disconnected(Channel channel) throws RemotingException { clearReadTimestamp(channel); clearWriteTimestamp(channel); handler.disconnected(channel); } @Override public void sent(Channel channel, Object message) throws RemotingException { setWriteTimestamp(channel); handler.sent(channel, message); } @Override public void received(Channel channel, Object message) throws RemotingException { setReadTimestamp(channel); if (isHeartbeatRequest(message)) { HeartBeatRequest req = (HeartBeatRequest) message; if (req.isTwoWay()) { HeartBeatResponse res; res = new HeartBeatResponse(req.getId(), req.getVersion()); res.setEvent(HEARTBEAT_EVENT); res.setProto(req.getProto()); channel.send(res); if (logger.isDebugEnabled()) { int heartbeat = channel.getUrl().getParameter(Constants.HEARTBEAT_KEY, 0); logger.debug("Received heartbeat from remote channel " + channel.getRemoteAddress() + ", cause: The channel has no data-transmission exceeds a heartbeat period" + (heartbeat > 0 ? ": " + heartbeat + "ms" : "")); } } return; } if (isHeartbeatResponse(message)) { if (logger.isDebugEnabled()) { logger.debug("Receive heartbeat response in thread " + Thread.currentThread().getName()); } return; } handler.received(channel, message); } private void setReadTimestamp(Channel channel) { channel.setAttribute(KEY_READ_TIMESTAMP, System.currentTimeMillis()); } private void setWriteTimestamp(Channel channel) { channel.setAttribute(KEY_WRITE_TIMESTAMP, System.currentTimeMillis()); } private void clearReadTimestamp(Channel channel) { channel.removeAttribute(KEY_READ_TIMESTAMP); } private void clearWriteTimestamp(Channel channel) { channel.removeAttribute(KEY_WRITE_TIMESTAMP); } private boolean isHeartbeatRequest(Object message) { return message instanceof HeartBeatRequest && ((Request) message).isHeartbeat(); } private boolean isHeartbeatResponse(Object message) { return message instanceof Response && ((Response) message).isHeartbeat(); } }
7,479
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.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.exchange.support.header; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.ConfigurationUtils; 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.common.utils.StringUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.ExecutionException; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.ExchangeChannel; import org.apache.dubbo.remoting.exchange.ExchangeHandler; 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.exchange.support.MultiMessage; import org.apache.dubbo.remoting.transport.ChannelHandlerDelegate; import java.net.InetSocketAddress; import java.util.concurrent.CompletionStage; import static org.apache.dubbo.common.constants.CommonConstants.READONLY_EVENT; import static org.apache.dubbo.common.constants.CommonConstants.WRITEABLE_EVENT; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_RESPONSE; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_UNSUPPORTED_MESSAGE; /** * ExchangeReceiver */ public class HeaderExchangeHandler implements ChannelHandlerDelegate { protected static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(HeaderExchangeHandler.class); private final ExchangeHandler handler; public HeaderExchangeHandler(ExchangeHandler handler) { if (handler == null) { throw new IllegalArgumentException("handler == null"); } this.handler = handler; } static void handleResponse(Channel channel, Response response) throws RemotingException { if (response != null && !response.isHeartbeat()) { DefaultFuture.received(channel, response); } } private static boolean isClientSide(Channel channel) { InetSocketAddress address = channel.getRemoteAddress(); URL url = channel.getUrl(); return url.getPort() == address.getPort() && NetUtils.filterLocalHost(url.getIp()) .equals(NetUtils.filterLocalHost(address.getAddress().getHostAddress())); } void handlerEvent(Channel channel, Request req) throws RemotingException { if (req.getData() != null && req.getData().equals(READONLY_EVENT)) { channel.setAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); logger.info("ChannelReadOnly set true for channel: " + channel); } if (req.getData() != null && req.getData().equals(WRITEABLE_EVENT)) { channel.removeAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY); logger.info("ChannelReadOnly set false for channel: " + channel); } } void handleRequest(final ExchangeChannel channel, Request req) throws RemotingException { Response res = new Response(req.getId(), req.getVersion()); if (req.isBroken()) { Object data = req.getData(); String msg; if (data == null) { msg = null; } else if (data instanceof Throwable) { msg = StringUtils.toString((Throwable) data); } else { msg = data.toString(); } res.setErrorMessage("Fail to decode request due to: " + msg); res.setStatus(Response.BAD_REQUEST); channel.send(res); return; } // find handler by message class. Object msg = req.getData(); try { CompletionStage<Object> future = handler.reply(channel, msg); future.whenComplete((appResult, t) -> { try { if (t == null) { res.setStatus(Response.OK); res.setResult(appResult); } else { res.setStatus(Response.SERVICE_ERROR); res.setErrorMessage(StringUtils.toString(t)); } channel.send(res); } catch (RemotingException e) { logger.warn( TRANSPORT_FAILED_RESPONSE, "", "", "Send result to consumer failed, channel is " + channel + ", msg is " + e); } }); } catch (Throwable e) { res.setStatus(Response.SERVICE_ERROR); res.setErrorMessage(StringUtils.toString(e)); channel.send(res); } } @Override public void connected(Channel channel) throws RemotingException { ExchangeChannel exchangeChannel = HeaderExchangeChannel.getOrAddChannel(channel); handler.connected(exchangeChannel); channel.setAttribute( Constants.CHANNEL_SHUTDOWN_TIMEOUT_KEY, ConfigurationUtils.getServerShutdownTimeout(channel.getUrl().getOrDefaultApplicationModel())); } @Override public void disconnected(Channel channel) throws RemotingException { ExchangeChannel exchangeChannel = HeaderExchangeChannel.getOrAddChannel(channel); try { handler.disconnected(exchangeChannel); } finally { int shutdownTimeout = 0; Object timeoutObj = channel.getAttribute(Constants.CHANNEL_SHUTDOWN_TIMEOUT_KEY); if (timeoutObj instanceof Integer) { shutdownTimeout = (Integer) timeoutObj; } DefaultFuture.closeChannel(channel, ConfigurationUtils.reCalShutdownTime(shutdownTimeout)); HeaderExchangeChannel.removeChannel(channel); } } @Override public void sent(Channel channel, Object message) throws RemotingException { Throwable exception = null; try { ExchangeChannel exchangeChannel = HeaderExchangeChannel.getOrAddChannel(channel); handler.sent(exchangeChannel, message); } catch (Throwable t) { exception = t; HeaderExchangeChannel.removeChannelIfDisconnected(channel); } if (message instanceof Request) { Request request = (Request) message; DefaultFuture.sent(channel, request); } if (message instanceof MultiMessage) { MultiMessage multiMessage = (MultiMessage) message; for (Object single : multiMessage) { if (single instanceof Request) { DefaultFuture.sent(channel, ((Request) single)); } } } if (exception != null) { if (exception instanceof RuntimeException) { throw (RuntimeException) exception; } else if (exception instanceof RemotingException) { throw (RemotingException) exception; } else { throw new RemotingException( channel.getLocalAddress(), channel.getRemoteAddress(), exception.getMessage(), exception); } } } @Override public void received(Channel channel, Object message) throws RemotingException { final ExchangeChannel exchangeChannel = HeaderExchangeChannel.getOrAddChannel(channel); if (message instanceof Request) { // handle request. Request request = (Request) message; if (request.isEvent()) { handlerEvent(channel, request); } else { if (request.isTwoWay()) { handleRequest(exchangeChannel, request); } else { handler.received(exchangeChannel, request.getData()); } } } else if (message instanceof Response) { handleResponse(channel, (Response) message); } else if (message instanceof String) { if (isClientSide(channel)) { Exception e = new Exception("Dubbo client can not supported string message: " + message + " in channel: " + channel + ", url: " + channel.getUrl()); logger.error(TRANSPORT_UNSUPPORTED_MESSAGE, "", "", e.getMessage(), e); } else { String echo = handler.telnet(channel, (String) message); if (StringUtils.isNotEmpty(echo)) { channel.send(echo); } } } else { handler.received(exchangeChannel, message); } } @Override public void caught(Channel channel, Throwable exception) throws RemotingException { if (exception instanceof ExecutionException) { ExecutionException e = (ExecutionException) exception; Object msg = e.getRequest(); if (msg instanceof Request) { Request req = (Request) msg; if (req.isTwoWay() && !req.isHeartbeat()) { Response res = new Response(req.getId(), req.getVersion()); res.setStatus(Response.SERVER_ERROR); res.setErrorMessage(StringUtils.toString(e)); channel.send(res); return; } } } ExchangeChannel exchangeChannel = HeaderExchangeChannel.getOrAddChannel(channel); try { handler.caught(exchangeChannel, exception); } finally { HeaderExchangeChannel.removeChannelIfDisconnected(channel); } } @Override public ChannelHandler getHandler() { if (handler instanceof ChannelHandlerDelegate) { return ((ChannelHandlerDelegate) handler).getHandler(); } else { return handler; } } }
7,480
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/CloseTimerTask.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.exchange.support.header; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.timer.HashedWheelTimer; import org.apache.dubbo.remoting.Channel; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_RESPONSE; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE; /** * CloseTimerTask */ public class CloseTimerTask extends AbstractTimerTask { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(CloseTimerTask.class); private final int closeTimeout; public CloseTimerTask( ChannelProvider channelProvider, HashedWheelTimer hashedWheelTimer, Long tick, int closeTimeout) { super(channelProvider, hashedWheelTimer, tick); this.closeTimeout = closeTimeout; } @Override protected void doTask(Channel channel) { try { Long lastRead = lastRead(channel); Long lastWrite = lastWrite(channel); Long now = now(); // check ping & pong at server if ((lastRead != null && now - lastRead > closeTimeout) || (lastWrite != null && now - lastWrite > closeTimeout)) { logger.warn( PROTOCOL_FAILED_RESPONSE, "", "", "Close channel " + channel + ", because idleCheck timeout: " + closeTimeout + "ms"); channel.close(); } } catch (Throwable t) { logger.warn( TRANSPORT_FAILED_CLOSE, "", "", "Exception when close remote channel " + channel.getRemoteAddress(), t); } } }
7,481
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/ReconnectTimerTask.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.exchange.support.header; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.timer.HashedWheelTimer; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.Client; import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_RECONNECT; /** * ReconnectTimerTask */ public class ReconnectTimerTask extends AbstractTimerTask { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ReconnectTimerTask.class); private final int idleTimeout; public ReconnectTimerTask( ChannelProvider channelProvider, HashedWheelTimer hashedWheelTimer, Long heartbeatTimeoutTick, int idleTimeout) { super(channelProvider, hashedWheelTimer, heartbeatTimeoutTick); this.idleTimeout = idleTimeout; } @Override protected void doTask(Channel channel) { try { Long lastRead = lastRead(channel); Long now = now(); // Rely on reconnect timer to reconnect when AbstractClient.doConnect fails to init the connection if (!channel.isConnected()) { try { logger.info("Initial connection to " + channel); ((Client) channel).reconnect(); } catch (Exception e) { logger.error(TRANSPORT_FAILED_RECONNECT, "", "", "Fail to connect to" + channel, e); } // check pong at client } else if (lastRead != null && now - lastRead > idleTimeout) { logger.warn( TRANSPORT_FAILED_RECONNECT, "", "", "Reconnect to channel " + channel + ", because heartbeat read idle time out: " + idleTimeout + "ms"); try { ((Client) channel).reconnect(); } catch (Exception e) { logger.error(TRANSPORT_FAILED_RECONNECT, "", "", channel + "reconnect failed during idle time.", e); } } } catch (Throwable t) { logger.warn( INTERNAL_ERROR, "unknown error in remoting module", "", "Exception when reconnect to remote channel " + channel.getRemoteAddress(), t); } } }
7,482
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.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.exchange.support.header; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.ExchangeChannel; import org.apache.dubbo.remoting.exchange.ExchangeHandler; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.Response; import org.apache.dubbo.remoting.exchange.support.DefaultFuture; import java.net.InetSocketAddress; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; 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.TRANSPORT_FAILED_CLOSE; /** * ExchangeReceiver */ final class HeaderExchangeChannel implements ExchangeChannel { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(HeaderExchangeChannel.class); private static final String CHANNEL_KEY = HeaderExchangeChannel.class.getName() + ".CHANNEL"; private final Channel channel; private final int shutdownTimeout; private volatile boolean closed = false; HeaderExchangeChannel(Channel channel) { if (channel == null) { throw new IllegalArgumentException("channel == null"); } this.channel = channel; this.shutdownTimeout = Optional.ofNullable(channel.getUrl()) .map(URL::getOrDefaultApplicationModel) .map(ConfigurationUtils::getServerShutdownTimeout) .orElse(DEFAULT_TIMEOUT); } static HeaderExchangeChannel getOrAddChannel(Channel ch) { if (ch == null) { return null; } HeaderExchangeChannel ret = (HeaderExchangeChannel) ch.getAttribute(CHANNEL_KEY); if (ret == null) { ret = new HeaderExchangeChannel(ch); if (ch.isConnected()) { ch.setAttribute(CHANNEL_KEY, ret); } } return ret; } static void removeChannelIfDisconnected(Channel ch) { if (ch != null && !ch.isConnected()) { ch.removeAttribute(CHANNEL_KEY); } } static void removeChannel(Channel ch) { if (ch != null) { ch.removeAttribute(CHANNEL_KEY); } } @Override public void send(Object message) throws RemotingException { send(message, false); } @Override public void send(Object message, boolean sent) throws RemotingException { if (closed) { throw new RemotingException( this.getLocalAddress(), null, "Failed to send message " + message + ", cause: The channel " + this + " is closed!"); } if (message instanceof Request || message instanceof Response || message instanceof String) { channel.send(message, sent); } else { Request request = new Request(); request.setVersion(Version.getProtocolVersion()); request.setTwoWay(false); request.setData(message); channel.send(request, sent); } } @Override public CompletableFuture<Object> request(Object request) throws RemotingException { return request(request, null); } @Override public CompletableFuture<Object> request(Object request, int timeout) throws RemotingException { return request(request, timeout, null); } @Override public CompletableFuture<Object> request(Object request, ExecutorService executor) throws RemotingException { return request(request, channel.getUrl().getPositiveParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT), executor); } @Override public CompletableFuture<Object> request(Object request, int timeout, ExecutorService executor) throws RemotingException { if (closed) { throw new RemotingException( this.getLocalAddress(), null, "Failed to send request " + request + ", cause: The channel " + this + " is closed!"); } Request req; if (request instanceof Request) { req = (Request) request; } else { // create request. req = new Request(); req.setVersion(Version.getProtocolVersion()); req.setTwoWay(true); req.setData(request); } DefaultFuture future = DefaultFuture.newFuture(channel, req, timeout, executor); try { channel.send(req); } catch (RemotingException e) { future.cancel(); throw e; } return future; } @Override public boolean isClosed() { return closed; } @Override public void close() { if (closed) { return; } closed = true; try { // graceful close DefaultFuture.closeChannel(channel, ConfigurationUtils.reCalShutdownTime(shutdownTimeout)); } catch (Exception e) { logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } try { channel.close(); } catch (Exception e) { logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } } // graceful close @Override public void close(int timeout) { if (closed) { return; } if (timeout > 0) { long start = System.currentTimeMillis(); while (DefaultFuture.hasFuture(channel) && System.currentTimeMillis() - start < timeout) { try { Thread.sleep(10); } catch (InterruptedException e) { logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } } } close(); } @Override public void startClose() { channel.startClose(); } @Override public InetSocketAddress getLocalAddress() { return channel.getLocalAddress(); } @Override public InetSocketAddress getRemoteAddress() { return channel.getRemoteAddress(); } @Override public URL getUrl() { return channel.getUrl(); } @Override public boolean isConnected() { return channel.isConnected(); } @Override public ChannelHandler getChannelHandler() { return channel.getChannelHandler(); } @Override public ExchangeHandler getExchangeHandler() { return (ExchangeHandler) channel.getChannelHandler(); } @Override public Object getAttribute(String key) { return channel.getAttribute(key); } @Override public void setAttribute(String key, Object value) { channel.setAttribute(key, value); } @Override public void removeAttribute(String key) { channel.removeAttribute(key); } @Override public boolean hasAttribute(String key) { return channel.hasAttribute(key); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + channel.hashCode(); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } HeaderExchangeChannel other = (HeaderExchangeChannel) obj; return channel.equals(other.channel); } @Override public String toString() { return channel.toString(); } }
7,483
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeServer.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.exchange.support.header; 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.common.resource.GlobalResourceInitializer; import org.apache.dubbo.common.timer.HashedWheelTimer; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.NamedThreadFactory; 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.RemotingServer; import org.apache.dubbo.remoting.exchange.ExchangeChannel; import org.apache.dubbo.remoting.exchange.ExchangeServer; import org.apache.dubbo.remoting.exchange.Request; import java.net.InetSocketAddress; import java.nio.channels.ClosedChannelException; import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import static java.util.Collections.unmodifiableCollection; import static org.apache.dubbo.common.constants.CommonConstants.READONLY_EVENT; import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_RESPONSE; import static org.apache.dubbo.remoting.Constants.HEARTBEAT_CHECK_TICK; import static org.apache.dubbo.remoting.Constants.LEAST_HEARTBEAT_DURATION; import static org.apache.dubbo.remoting.Constants.TICKS_PER_WHEEL; import static org.apache.dubbo.remoting.utils.UrlUtils.getCloseTimeout; /** * ExchangeServerImpl */ public class HeaderExchangeServer implements ExchangeServer { protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); private final RemotingServer server; private final AtomicBoolean closed = new AtomicBoolean(false); public static GlobalResourceInitializer<HashedWheelTimer> IDLE_CHECK_TIMER = new GlobalResourceInitializer<>( () -> new HashedWheelTimer( new NamedThreadFactory("dubbo-server-idleCheck", true), 1, TimeUnit.SECONDS, TICKS_PER_WHEEL), HashedWheelTimer::stop); private CloseTimerTask closeTimer; public HeaderExchangeServer(RemotingServer server) { Assert.notNull(server, "server == null"); this.server = server; startIdleCheckTask(getUrl()); } public RemotingServer getServer() { return server; } @Override public boolean isClosed() { return server.isClosed(); } private boolean isRunning() { // If there are any client connections, // our server should be running. return getChannels().stream().anyMatch(Channel::isConnected); } @Override public void close() { if (!closed.compareAndSet(false, true)) { return; } doClose(); server.close(); } @Override public void close(final int timeout) { if (!closed.compareAndSet(false, true)) { return; } startClose(); if (timeout > 0) { final long start = System.currentTimeMillis(); if (getUrl().getParameter(Constants.CHANNEL_SEND_READONLYEVENT_KEY, true)) { sendChannelReadOnlyEvent(); } while (HeaderExchangeServer.this.isRunning() && System.currentTimeMillis() - start < (long) timeout) { try { Thread.sleep(10); } catch (InterruptedException e) { logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } } } doClose(); server.close(timeout); } @Override public void startClose() { server.startClose(); } private void sendChannelReadOnlyEvent() { Request request = new Request(); request.setEvent(READONLY_EVENT); request.setTwoWay(false); request.setVersion(Version.getProtocolVersion()); Collection<Channel> channels = getChannels(); for (Channel channel : channels) { try { if (channel.isConnected()) { channel.send(request, getUrl().getParameter(Constants.CHANNEL_READONLYEVENT_SENT_KEY, true)); } } catch (RemotingException e) { if (closed.get() && e.getCause() instanceof ClosedChannelException) { // ignore ClosedChannelException which means the connection has been closed. continue; } logger.warn(TRANSPORT_FAILED_RESPONSE, "", "", "send cannot write message error.", e); } } } private void doClose() { cancelCloseTask(); } private void cancelCloseTask() { if (closeTimer != null) { closeTimer.cancel(); } } @Override public Collection<ExchangeChannel> getExchangeChannels() { Collection<ExchangeChannel> exchangeChannels = new ArrayList<ExchangeChannel>(); Collection<Channel> channels = server.getChannels(); if (CollectionUtils.isNotEmpty(channels)) { for (Channel channel : channels) { exchangeChannels.add(HeaderExchangeChannel.getOrAddChannel(channel)); } } return exchangeChannels; } @Override public ExchangeChannel getExchangeChannel(InetSocketAddress remoteAddress) { Channel channel = server.getChannel(remoteAddress); return HeaderExchangeChannel.getOrAddChannel(channel); } @Override @SuppressWarnings({"unchecked", "rawtypes"}) public Collection<Channel> getChannels() { return (Collection) getExchangeChannels(); } @Override public Channel getChannel(InetSocketAddress remoteAddress) { return getExchangeChannel(remoteAddress); } @Override public boolean isBound() { return server.isBound(); } @Override public InetSocketAddress getLocalAddress() { return server.getLocalAddress(); } @Override public URL getUrl() { return server.getUrl(); } @Override public ChannelHandler getChannelHandler() { return server.getChannelHandler(); } @Override public void reset(URL url) { server.reset(url); try { int currCloseTimeout = getCloseTimeout(getUrl()); int closeTimeout = getCloseTimeout(url); if (closeTimeout != currCloseTimeout) { cancelCloseTask(); startIdleCheckTask(url); } } catch (Throwable t) { logger.error(INTERNAL_ERROR, "unknown error in remoting module", "", t.getMessage(), t); } } @Override @Deprecated public void reset(org.apache.dubbo.common.Parameters parameters) { reset(getUrl().addParameters(parameters.getParameters())); } @Override public void send(Object message) throws RemotingException { if (closed.get()) { throw new RemotingException( this.getLocalAddress(), null, "Failed to send message " + message + ", cause: The server " + getLocalAddress() + " is closed!"); } server.send(message); } @Override public void send(Object message, boolean sent) throws RemotingException { if (closed.get()) { throw new RemotingException( this.getLocalAddress(), null, "Failed to send message " + message + ", cause: The server " + getLocalAddress() + " is closed!"); } server.send(message, sent); } /** * Each interval cannot be less than 1000ms. */ private long calculateLeastDuration(int time) { if (time / HEARTBEAT_CHECK_TICK <= 0) { return LEAST_HEARTBEAT_DURATION; } else { return time / HEARTBEAT_CHECK_TICK; } } private void startIdleCheckTask(URL url) { if (!server.canHandleIdle()) { AbstractTimerTask.ChannelProvider cp = () -> unmodifiableCollection(HeaderExchangeServer.this.getChannels()); int closeTimeout = getCloseTimeout(url); long closeTimeoutTick = calculateLeastDuration(closeTimeout); this.closeTimer = new CloseTimerTask(cp, IDLE_CHECK_TIMER.get(), closeTimeoutTick, closeTimeout); } } }
7,484
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchanger.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.exchange.support.header; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.Transporters; import org.apache.dubbo.remoting.exchange.ExchangeClient; import org.apache.dubbo.remoting.exchange.ExchangeHandler; import org.apache.dubbo.remoting.exchange.ExchangeServer; import org.apache.dubbo.remoting.exchange.Exchanger; import org.apache.dubbo.remoting.exchange.PortUnificationExchanger; import org.apache.dubbo.remoting.transport.DecodeHandler; import static org.apache.dubbo.remoting.Constants.IS_PU_SERVER_KEY; /** * DefaultMessenger * * */ public class HeaderExchanger implements Exchanger { public static final String NAME = "header"; @Override public ExchangeClient connect(URL url, ExchangeHandler handler) throws RemotingException { return new HeaderExchangeClient( Transporters.connect(url, new DecodeHandler(new HeaderExchangeHandler(handler))), true); } @Override public ExchangeServer bind(URL url, ExchangeHandler handler) throws RemotingException { ExchangeServer server; boolean isPuServerKey = url.getParameter(IS_PU_SERVER_KEY, false); if (isPuServerKey) { server = new HeaderExchangeServer( PortUnificationExchanger.bind(url, new DecodeHandler(new HeaderExchangeHandler(handler)))); } else { server = new HeaderExchangeServer( Transporters.bind(url, new DecodeHandler(new HeaderExchangeHandler(handler)))); } return server; } }
7,485
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ChannelDelegate.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; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import java.net.InetSocketAddress; /** * ChannelDelegate */ public class ChannelDelegate implements Channel { private transient Channel channel; public ChannelDelegate() {} public ChannelDelegate(Channel channel) { setChannel(channel); } public Channel getChannel() { return channel; } public void setChannel(Channel channel) { if (channel == null) { throw new IllegalArgumentException("channel == null"); } this.channel = channel; } @Override public URL getUrl() { return channel.getUrl(); } @Override public InetSocketAddress getRemoteAddress() { return channel.getRemoteAddress(); } @Override public ChannelHandler getChannelHandler() { return channel.getChannelHandler(); } @Override public boolean isConnected() { return channel.isConnected(); } @Override public InetSocketAddress getLocalAddress() { return channel.getLocalAddress(); } @Override public boolean hasAttribute(String key) { return channel.hasAttribute(key); } @Override public void send(Object message) throws RemotingException { channel.send(message); } @Override public Object getAttribute(String key) { return channel.getAttribute(key); } @Override public void setAttribute(String key, Object value) { channel.setAttribute(key, value); } @Override public void send(Object message, boolean sent) throws RemotingException { channel.send(message, sent); } @Override public void removeAttribute(String key) { channel.removeAttribute(key); } @Override public void close() { channel.close(); } @Override public void close(int timeout) { channel.close(timeout); } @Override public void startClose() { channel.startClose(); } @Override public boolean isClosed() { return channel.isClosed(); } }
7,486
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ChannelHandlerDispatcher.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; 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.remoting.Channel; 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; /** * ChannelListenerDispatcher */ public class ChannelHandlerDispatcher implements ChannelHandler { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ChannelHandlerDispatcher.class); private final Collection<ChannelHandler> channelHandlers = new CopyOnWriteArraySet<>(); public ChannelHandlerDispatcher() {} 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)) { // filter null object this.channelHandlers.addAll( handlers.stream().filter(Objects::nonNull).collect(Collectors.toSet())); } } public Collection<ChannelHandler> getChannelHandlers() { return channelHandlers; } public ChannelHandlerDispatcher addChannelHandler(ChannelHandler handler) { this.channelHandlers.add(handler); return this; } public ChannelHandlerDispatcher removeChannelHandler(ChannelHandler handler) { this.channelHandlers.remove(handler); return this; } @Override public void connected(Channel channel) { for (ChannelHandler listener : channelHandlers) { try { listener.connected(channel); } catch (Throwable t) { logger.error(INTERNAL_ERROR, "unknown error in remoting module", "", t.getMessage(), t); } } } @Override public void disconnected(Channel channel) { for (ChannelHandler listener : channelHandlers) { try { listener.disconnected(channel); } catch (Throwable t) { logger.error(INTERNAL_ERROR, "unknown error in remoting module", "", t.getMessage(), t); } } } @Override public void sent(Channel channel, Object message) { for (ChannelHandler listener : channelHandlers) { try { listener.sent(channel, message); } catch (Throwable t) { logger.error(INTERNAL_ERROR, "unknown error in remoting module", "", t.getMessage(), t); } } } @Override public void received(Channel channel, Object message) { for (ChannelHandler listener : channelHandlers) { try { listener.received(channel, message); } catch (Throwable t) { logger.error(INTERNAL_ERROR, "unknown error in remoting module", "", t.getMessage(), t); } } } @Override public void caught(Channel channel, Throwable exception) { for (ChannelHandler listener : channelHandlers) { try { listener.caught(channel, exception); } catch (Throwable t) { logger.error(INTERNAL_ERROR, "unknown error in remoting module", "", t.getMessage(), t); } } } }
7,487
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractCodec.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; 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.serialize.Serialization; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.Codec2; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.Response; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ScopeModelAware; import java.io.IOException; import java.net.InetSocketAddress; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_EXCEED_PAYLOAD_LIMIT; /** * AbstractCodec */ public abstract class AbstractCodec implements Codec2, ScopeModelAware { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractCodec.class); private static final String CLIENT_SIDE = "client"; private static final String SERVER_SIDE = "server"; protected FrameworkModel frameworkModel; @Override public void setFrameworkModel(FrameworkModel frameworkModel) { this.frameworkModel = frameworkModel; } protected static void checkPayload(Channel channel, long size) throws IOException { int payload = getPayload(channel); boolean overPayload = isOverPayload(payload, size); if (overPayload) { ExceedPayloadLimitException e = new ExceedPayloadLimitException( "Data length too large: " + size + ", max payload: " + payload + ", channel: " + channel); logger.error(TRANSPORT_EXCEED_PAYLOAD_LIMIT, "", "", e.getMessage(), e); throw e; } } protected static void checkPayload(Channel channel, int payload, long size) throws IOException { if (payload <= 0) { payload = getPayload(channel); } boolean overPayload = isOverPayload(payload, size); if (overPayload) { ExceedPayloadLimitException e = new ExceedPayloadLimitException( "Data length too large: " + size + ", max payload: " + payload + ", channel: " + channel); logger.error(TRANSPORT_EXCEED_PAYLOAD_LIMIT, "", "", e.getMessage(), e); throw e; } } protected static int getPayload(Channel channel) { if (channel != null && channel.getUrl() != null) { return channel.getUrl().getParameter(Constants.PAYLOAD_KEY, Constants.DEFAULT_PAYLOAD); } return Constants.DEFAULT_PAYLOAD; } protected static boolean isOverPayload(int payload, long size) { return payload > 0 && size > payload; } protected Serialization getSerialization(Channel channel, Request req) { return CodecSupport.getSerialization(channel.getUrl()); } protected Serialization getSerialization(Channel channel, Response res) { return CodecSupport.getSerialization(channel.getUrl()); } protected Serialization getSerialization(Channel channel) { return CodecSupport.getSerialization(channel.getUrl()); } protected boolean isClientSide(Channel channel) { String side = (String) channel.getAttribute(SIDE_KEY); if (CLIENT_SIDE.equals(side)) { return true; } else if (SERVER_SIDE.equals(side)) { return false; } else { InetSocketAddress address = channel.getRemoteAddress(); URL url = channel.getUrl(); boolean isClient = url.getPort() == address.getPort() && NetUtils.filterLocalHost(url.getIp()) .equals(NetUtils.filterLocalHost( address.getAddress().getHostAddress())); channel.setAttribute(SIDE_KEY, isClient ? CLIENT_SIDE : SERVER_SIDE); return isClient; } } protected boolean isServerSide(Channel channel) { return !isClientSide(channel); } }
7,488
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractChannelHandlerDelegate.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; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; public abstract class AbstractChannelHandlerDelegate implements ChannelHandlerDelegate { protected ChannelHandler handler; protected AbstractChannelHandlerDelegate(ChannelHandler handler) { Assert.notNull(handler, "handler == null"); this.handler = handler; } @Override public ChannelHandler getHandler() { if (handler instanceof ChannelHandlerDelegate) { return ((ChannelHandlerDelegate) handler).getHandler(); } return handler; } @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); } }
7,489
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ClientDelegate.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; 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 java.net.InetSocketAddress; /** * ClientDelegate */ public class ClientDelegate implements Client { private transient Client client; public ClientDelegate() {} public ClientDelegate(Client client) { setClient(client); } public Client getClient() { return client; } public void setClient(Client client) { if (client == null) { throw new IllegalArgumentException("client == null"); } this.client = client; } @Override public void reset(URL url) { client.reset(url); } @Override @Deprecated public void reset(org.apache.dubbo.common.Parameters parameters) { reset(getUrl().addParameters(parameters.getParameters())); } @Override public URL getUrl() { return client.getUrl(); } @Override public InetSocketAddress getRemoteAddress() { return client.getRemoteAddress(); } @Override public void reconnect() throws RemotingException { client.reconnect(); } @Override public ChannelHandler getChannelHandler() { return client.getChannelHandler(); } @Override public boolean isConnected() { return client.isConnected(); } @Override public InetSocketAddress getLocalAddress() { return client.getLocalAddress(); } @Override public boolean hasAttribute(String key) { return client.hasAttribute(key); } @Override public void send(Object message) throws RemotingException { client.send(message); } @Override public Object getAttribute(String key) { return client.getAttribute(key); } @Override public void setAttribute(String key, Object value) { client.setAttribute(key, value); } @Override public void send(Object message, boolean sent) throws RemotingException { client.send(message, sent); } @Override public void removeAttribute(String key) { client.removeAttribute(key); } @Override public void close() { client.close(); } @Override public void close(int timeout) { client.close(timeout); } @Override public void startClose() { client.startClose(); } @Override public boolean isClosed() { return client.isClosed(); } }
7,490
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ServerDelegate.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; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.RemotingServer; import java.net.InetSocketAddress; import java.util.Collection; /** * ServerDelegate * * */ public class ServerDelegate implements RemotingServer { private transient RemotingServer server; public ServerDelegate() {} public ServerDelegate(RemotingServer server) { setServer(server); } public RemotingServer getServer() { return server; } public void setServer(RemotingServer server) { this.server = server; } @Override public boolean isBound() { return server.isBound(); } @Override public void reset(URL url) { server.reset(url); } @Override @Deprecated public void reset(org.apache.dubbo.common.Parameters parameters) { reset(getUrl().addParameters(parameters.getParameters())); } @Override public Collection<Channel> getChannels() { return server.getChannels(); } @Override public Channel getChannel(InetSocketAddress remoteAddress) { return server.getChannel(remoteAddress); } @Override public URL getUrl() { return server.getUrl(); } @Override public ChannelHandler getChannelHandler() { return server.getChannelHandler(); } @Override public InetSocketAddress getLocalAddress() { return server.getLocalAddress(); } @Override public void send(Object message) throws RemotingException { server.send(message); } @Override public void send(Object message, boolean sent) throws RemotingException { server.send(message, sent); } @Override public void close() { server.close(); } @Override public void close(int timeout) { server.close(timeout); } @Override public void startClose() { server.startClose(); } @Override public boolean isClosed() { return server.isClosed(); } }
7,491
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractClient.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; 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.common.threadpool.manager.ExecutorRepository; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Client; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.transport.dispatcher.ChannelHandlers; import java.net.InetSocketAddress; import java.util.concurrent.ExecutorService; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_CLIENT_THREADPOOL; import static org.apache.dubbo.common.constants.CommonConstants.LAZY_CONNECT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CONNECT_PROVIDER; import static org.apache.dubbo.config.Constants.CLIENT_THREAD_POOL_NAME; /** * AbstractClient */ public abstract class AbstractClient extends AbstractEndpoint implements Client { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractClient.class); private final Lock connectLock = new ReentrantLock(); private final boolean needReconnect; protected volatile ExecutorService executor; public AbstractClient(URL url, ChannelHandler handler) throws RemotingException { super(url, handler); // set default needReconnect true when channel is not connected needReconnect = url.getParameter(Constants.SEND_RECONNECT_KEY, true); initExecutor(url); try { doOpen(); } catch (Throwable t) { close(); throw new RemotingException( url.toInetSocketAddress(), null, "Failed to start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress() + " connect to the server " + getRemoteAddress() + ", cause: " + t.getMessage(), t); } try { // connect. connect(); if (logger.isInfoEnabled()) { logger.info("Start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress() + " connect to the server " + getRemoteAddress()); } } catch (RemotingException t) { // If lazy connect client fails to establish a connection, the client instance will still be created, // and the reconnection will be initiated by ReconnectTask, so there is no need to throw an exception if (url.getParameter(LAZY_CONNECT_KEY, false)) { logger.warn( TRANSPORT_FAILED_CONNECT_PROVIDER, "", "", "Failed to start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress() + " connect to the server " + getRemoteAddress() + " (the connection request is initiated by lazy connect client, ignore and retry later!), cause: " + t.getMessage(), t); return; } if (url.getParameter(Constants.CHECK_KEY, true)) { close(); throw t; } else { logger.warn( TRANSPORT_FAILED_CONNECT_PROVIDER, "", "", "Failed to start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress() + " connect to the server " + getRemoteAddress() + " (check == false, ignore and retry later!), cause: " + t.getMessage(), t); } } catch (Throwable t) { close(); throw new RemotingException( url.toInetSocketAddress(), null, "Failed to start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress() + " connect to the server " + getRemoteAddress() + ", cause: " + t.getMessage(), t); } } private void initExecutor(URL url) { ExecutorRepository executorRepository = ExecutorRepository.getInstance(url.getOrDefaultApplicationModel()); /** * Consumer's executor is shared globally, provider ip doesn't need to be part of the thread name. * * Instance of url is InstanceAddressURL, so addParameter actually adds parameters into ServiceInstance, * which means params are shared among different services. Since client is shared among services this is currently not a problem. */ url = url.addParameter(THREAD_NAME_KEY, CLIENT_THREAD_POOL_NAME) .addParameterIfAbsent(THREADPOOL_KEY, DEFAULT_CLIENT_THREADPOOL); executor = executorRepository.createExecutorIfAbsent(url); } protected static ChannelHandler wrapChannelHandler(URL url, ChannelHandler handler) { return ChannelHandlers.wrap(handler, url); } public InetSocketAddress getConnectAddress() { return new InetSocketAddress(NetUtils.filterLocalHost(getUrl().getHost()), getUrl().getPort()); } @Override public InetSocketAddress getRemoteAddress() { Channel channel = getChannel(); if (channel == null) { return getUrl().toInetSocketAddress(); } return channel.getRemoteAddress(); } @Override public InetSocketAddress getLocalAddress() { Channel channel = getChannel(); if (channel == null) { return InetSocketAddress.createUnresolved(NetUtils.getLocalHost(), 0); } return channel.getLocalAddress(); } @Override public boolean isConnected() { Channel channel = getChannel(); if (channel == null) { return false; } return channel.isConnected(); } @Override public Object getAttribute(String key) { Channel channel = getChannel(); if (channel == null) { return null; } return channel.getAttribute(key); } @Override public void setAttribute(String key, Object value) { Channel channel = getChannel(); if (channel == null) { return; } channel.setAttribute(key, value); } @Override public void removeAttribute(String key) { Channel channel = getChannel(); if (channel == null) { return; } channel.removeAttribute(key); } @Override public boolean hasAttribute(String key) { Channel channel = getChannel(); if (channel == null) { return false; } return channel.hasAttribute(key); } @Override public void send(Object message, boolean sent) throws RemotingException { if (needReconnect && !isConnected()) { connect(); } Channel channel = getChannel(); // TODO Can the value returned by getChannel() be null? need improvement. if (channel == null || !channel.isConnected()) { throw new RemotingException(this, "message can not send, because channel is closed . url:" + getUrl()); } channel.send(message, sent); } protected void connect() throws RemotingException { connectLock.lock(); try { if (isConnected()) { return; } if (isClosed() || isClosing()) { logger.warn( TRANSPORT_FAILED_CONNECT_PROVIDER, "", "", "No need to connect to server " + getRemoteAddress() + " from " + getClass().getSimpleName() + " " + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion() + ", cause: client status is closed or closing."); return; } doConnect(); if (!isConnected()) { throw new RemotingException( this, "Failed to connect to server " + getRemoteAddress() + " from " + getClass().getSimpleName() + " " + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion() + ", cause: Connect wait timeout: " + getConnectTimeout() + "ms."); } else { if (logger.isInfoEnabled()) { logger.info("Successfully connect to server " + getRemoteAddress() + " from " + getClass().getSimpleName() + " " + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion() + ", channel is " + this.getChannel()); } } } catch (RemotingException e) { throw e; } catch (Throwable e) { throw new RemotingException( this, "Failed to connect to server " + getRemoteAddress() + " from " + getClass().getSimpleName() + " " + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion() + ", cause: " + e.getMessage(), e); } finally { connectLock.unlock(); } } public void disconnect() { connectLock.lock(); try { try { Channel channel = getChannel(); if (channel != null) { channel.close(); } } catch (Throwable e) { logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } try { doDisConnect(); } catch (Throwable e) { logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } } finally { connectLock.unlock(); } } @Override public void reconnect() throws RemotingException { connectLock.lock(); try { disconnect(); connect(); } finally { connectLock.unlock(); } } @Override public void close() { if (isClosed()) { logger.warn( TRANSPORT_FAILED_CONNECT_PROVIDER, "", "", "No need to close connection to server " + getRemoteAddress() + " from " + getClass().getSimpleName() + " " + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion() + ", cause: the client status is closed."); return; } connectLock.lock(); try { if (isClosed()) { logger.warn( TRANSPORT_FAILED_CONNECT_PROVIDER, "", "", "No need to close connection to server " + getRemoteAddress() + " from " + getClass().getSimpleName() + " " + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion() + ", cause: the client status is closed."); return; } try { super.close(); } catch (Throwable e) { logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } try { disconnect(); } catch (Throwable e) { logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } try { doClose(); } catch (Throwable e) { logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } } finally { connectLock.unlock(); } } @Override public void close(int timeout) { close(); } @Override public String toString() { return getClass().getName() + " [" + getLocalAddress() + " -> " + getRemoteAddress() + "]"; } /** * Open client. * * @throws Throwable */ protected abstract void doOpen() throws Throwable; /** * Close client. * * @throws Throwable */ protected abstract void doClose() throws Throwable; /** * Connect to server. * * @throws Throwable */ protected abstract void doConnect() throws Throwable; /** * disConnect to server. * * @throws Throwable */ protected abstract void doDisConnect() throws Throwable; /** * Get the connected channel. * * @return channel */ protected abstract Channel getChannel(); }
7,492
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractPeer.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; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.Endpoint; import org.apache.dubbo.remoting.RemotingException; /** * AbstractPeer */ public abstract class AbstractPeer implements Endpoint, ChannelHandler { private final ChannelHandler handler; private volatile URL url; // closing closed means the process is being closed and close is finished private volatile boolean closing; private volatile boolean closed; public AbstractPeer(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 send(Object message) throws RemotingException { send(message, url.getParameter(Constants.SENT_KEY, false)); } @Override public void close() { closed = true; } @Override public void close(int timeout) { close(); } @Override public void startClose() { if (isClosed()) { return; } closing = true; } @Override public URL getUrl() { return url; } protected void setUrl(URL url) { if (url == null) { throw new IllegalArgumentException("url == null"); } this.url = url; } @Override public ChannelHandler getChannelHandler() { if (handler instanceof ChannelHandlerDelegate) { return ((ChannelHandlerDelegate) handler).getHandler(); } else { return handler; } } /** * @return ChannelHandler */ @Deprecated public ChannelHandler getHandler() { return getDelegateHandler(); } /** * Return the final handler (which may have been wrapped). This method should be distinguished with getChannelHandler() method * * @return ChannelHandler */ public ChannelHandler getDelegateHandler() { return handler; } @Override public boolean isClosed() { return closed; } public boolean isClosing() { return closing && !closed; } @Override public void connected(Channel ch) throws RemotingException { if (closed) { return; } handler.connected(ch); } @Override public void disconnected(Channel ch) throws RemotingException { handler.disconnected(ch); } @Override public void sent(Channel ch, Object msg) throws RemotingException { if (closed) { return; } handler.sent(ch, msg); } @Override public void received(Channel ch, Object msg) throws RemotingException { if (closed) { return; } handler.received(ch, msg); } @Override public void caught(Channel ch, Throwable ex) throws RemotingException { handler.caught(ch, ex); } }
7,493
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ChannelHandlerDelegate.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; import org.apache.dubbo.remoting.ChannelHandler; public interface ChannelHandlerDelegate extends ChannelHandler { ChannelHandler getHandler(); }
7,494
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/MultiMessageHandler.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; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.support.MultiMessage; import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR; /** * @see MultiMessage */ public class MultiMessageHandler extends AbstractChannelHandlerDelegate { protected static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MultiMessageHandler.class); public MultiMessageHandler(ChannelHandler handler) { super(handler); } @SuppressWarnings("unchecked") @Override public void received(Channel channel, Object message) throws RemotingException { if (message instanceof MultiMessage) { MultiMessage list = (MultiMessage) message; for (Object obj : list) { try { handler.received(channel, obj); } catch (Throwable t) { logger.error( INTERNAL_ERROR, "unknown error in remoting module", "", "MultiMessageHandler received fail.", t); try { handler.caught(channel, t); } catch (Throwable t1) { logger.error( INTERNAL_ERROR, "unknown error in remoting module", "", "MultiMessageHandler caught fail.", t1); } } } } else { handler.received(channel, message); } } }
7,495
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/DecodeHandler.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; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Decodeable; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.Response; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_DECODE; public class DecodeHandler extends AbstractChannelHandlerDelegate { private static final ErrorTypeAwareLogger log = LoggerFactory.getErrorTypeAwareLogger(DecodeHandler.class); public DecodeHandler(ChannelHandler handler) { super(handler); } @Override public void received(Channel channel, Object message) throws RemotingException { if (message instanceof Decodeable) { decode(message); } if (message instanceof Request) { decode(((Request) message).getData()); } if (message instanceof Response) { decode(((Response) message).getResult()); } handler.received(channel, message); } private void decode(Object message) { if (!(message instanceof Decodeable)) { return; } try { ((Decodeable) message).decode(); if (log.isDebugEnabled()) { log.debug("Decode decodeable message " + message.getClass().getName()); } } catch (Throwable e) { if (log.isWarnEnabled()) { log.warn(TRANSPORT_FAILED_DECODE, "", "", "Call Decodeable.decode failed: " + e.getMessage(), e); } } } }
7,496
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractServer.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; 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.threadpool.manager.ExecutorRepository; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.common.utils.ExecutorUtil; 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.RemotingServer; import java.net.InetSocketAddress; import java.util.Collection; import java.util.Set; import java.util.concurrent.ExecutorService; 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.LoggerCodeConstants.INTERNAL_ERROR; import static org.apache.dubbo.config.Constants.SERVER_THREAD_POOL_NAME; import static org.apache.dubbo.remoting.Constants.ACCEPTS_KEY; import static org.apache.dubbo.remoting.Constants.DEFAULT_ACCEPTS; /** * AbstractServer */ public abstract class AbstractServer extends AbstractEndpoint implements RemotingServer { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractServer.class); private Set<ExecutorService> executors = new ConcurrentHashSet<>(); private InetSocketAddress localAddress; private InetSocketAddress bindAddress; private int accepts; private ExecutorRepository executorRepository; public AbstractServer(URL url, ChannelHandler handler) throws RemotingException { super(url, handler); executorRepository = ExecutorRepository.getInstance(url.getOrDefaultApplicationModel()); localAddress = getUrl().toInetSocketAddress(); String bindIp = getUrl().getParameter(Constants.BIND_IP_KEY, getUrl().getHost()); int bindPort = getUrl().getParameter(Constants.BIND_PORT_KEY, getUrl().getPort()); if (url.getParameter(ANYHOST_KEY, false) || NetUtils.isInvalidLocalHost(bindIp)) { bindIp = ANYHOST_VALUE; } bindAddress = new InetSocketAddress(bindIp, bindPort); this.accepts = url.getParameter(ACCEPTS_KEY, DEFAULT_ACCEPTS); try { doOpen(); if (logger.isInfoEnabled()) { logger.info("Start " + getClass().getSimpleName() + " bind " + getBindAddress() + ", export " + getLocalAddress()); } } catch (Throwable t) { throw new RemotingException( url.toInetSocketAddress(), null, "Failed to bind " + getClass().getSimpleName() + " on " + bindAddress + ", cause: " + t.getMessage(), t); } executors.add( executorRepository.createExecutorIfAbsent(ExecutorUtil.setThreadName(url, SERVER_THREAD_POOL_NAME))); } protected abstract void doOpen() throws Throwable; protected abstract void doClose() throws Throwable; protected abstract int getChannelsSize(); @Override public void reset(URL url) { if (url == null) { return; } try { if (url.hasParameter(ACCEPTS_KEY)) { int a = url.getParameter(ACCEPTS_KEY, 0); if (a > 0) { this.accepts = a; } } } catch (Throwable t) { logger.error(INTERNAL_ERROR, "unknown error in remoting module", "", t.getMessage(), t); } ExecutorService executor = executorRepository.createExecutorIfAbsent(ExecutorUtil.setThreadName(url, SERVER_THREAD_POOL_NAME)); executors.add(executor); executorRepository.updateThreadpool(url, executor); super.setUrl(getUrl().addParameters(url.getParameters())); } @Override public void send(Object message, boolean sent) throws RemotingException { Collection<Channel> channels = getChannels(); for (Channel channel : channels) { if (channel.isConnected()) { channel.send(message, sent); } } } @Override public void close() { if (logger.isInfoEnabled()) { logger.info("Close " + getClass().getSimpleName() + " bind " + getBindAddress() + ", export " + getLocalAddress()); } for (ExecutorService executor : executors) { ExecutorUtil.shutdownNow(executor, 100); } try { super.close(); } catch (Throwable e) { logger.warn(INTERNAL_ERROR, "unknown error in remoting module", "", e.getMessage(), e); } try { doClose(); } catch (Throwable e) { logger.warn(INTERNAL_ERROR, "unknown error in remoting module", "", e.getMessage(), e); } } @Override public void close(int timeout) { for (ExecutorService executor : executors) { ExecutorUtil.gracefulShutdown(executor, timeout); } close(); } @Override public InetSocketAddress getLocalAddress() { return localAddress; } public InetSocketAddress getBindAddress() { return bindAddress; } public int getAccepts() { return accepts; } @Override public void connected(Channel ch) throws RemotingException { // If the server has entered the shutdown process, reject any new connection if (this.isClosing() || this.isClosed()) { logger.warn( INTERNAL_ERROR, "unknown error in remoting module", "", "Close new channel " + ch + ", cause: server is closing or has been closed. For example, receive a new connect request while in shutdown process."); ch.close(); return; } if (accepts > 0 && getChannelsSize() > accepts) { logger.error( INTERNAL_ERROR, "unknown error in remoting module", "", "Close channel " + ch + ", cause: The server " + ch.getLocalAddress() + " connections greater than max config " + accepts); ch.close(); return; } super.connected(ch); } @Override public void disconnected(Channel ch) throws RemotingException { if (getChannelsSize() == 0) { logger.warn( INTERNAL_ERROR, "unknown error in remoting module", "", "All clients has disconnected from " + ch.getLocalAddress() + ". You can graceful shutdown now."); } super.disconnected(ch); } }
7,497
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractChannel.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; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.utils.PayloadDropper; /** * AbstractChannel */ public abstract class AbstractChannel extends AbstractPeer implements Channel { public AbstractChannel(URL url, ChannelHandler handler) { super(url, handler); } @Override public void send(Object message, boolean sent) throws RemotingException { if (isClosed()) { throw new RemotingException( this, "Failed to send message " + (message == null ? "" : message.getClass().getName()) + ":" + PayloadDropper.getRequestWithoutData(message) + ", cause: Channel closed. channel: " + getLocalAddress() + " -> " + getRemoteAddress()); } } @Override public String toString() { return getLocalAddress() + " -> " + getRemoteAddress(); } @Override protected void setUrl(URL url) { super.setUrl(url); } }
7,498
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ExceedPayloadLimitException.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; import java.io.IOException; public class ExceedPayloadLimitException extends IOException { private static final long serialVersionUID = -1112322085391551410L; public ExceedPayloadLimitException(String message) { super(message); } }
7,499