repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/MockedChannel.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/MockedChannel.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.handler;
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;
import java.util.HashMap;
import java.util.Map;
public class MockedChannel implements Channel {
private boolean isClosed;
private volatile boolean closing = false;
private URL url;
private ChannelHandler handler;
private Map<String, Object> map = new HashMap<String, Object>();
public MockedChannel() {
super();
}
@Override
public URL getUrl() {
return url;
}
@Override
public ChannelHandler getChannelHandler() {
return this.handler;
}
@Override
public InetSocketAddress getLocalAddress() {
return null;
}
@Override
public void send(Object message) throws RemotingException {}
@Override
public void send(Object message, boolean sent) throws RemotingException {
this.send(message);
}
@Override
public void close() {
isClosed = true;
}
@Override
public void close(int timeout) {
this.close();
}
@Override
public void startClose() {
closing = true;
}
@Override
public boolean isClosed() {
return isClosed;
}
@Override
public InetSocketAddress getRemoteAddress() {
return null;
}
@Override
public boolean isConnected() {
return false;
}
@Override
public boolean hasAttribute(String key) {
return map.containsKey(key);
}
@Override
public Object getAttribute(String key) {
return map.get(key);
}
@Override
public void setAttribute(String key, Object value) {
map.put(key, value);
}
@Override
public void removeAttribute(String key) {
map.remove(key);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/HeaderExchangeHandlerTest.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/HeaderExchangeHandlerTest.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.handler;
import org.apache.dubbo.remoting.Channel;
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.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.header.HeaderExchangeHandler;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.HEARTBEAT_EVENT;
import static org.apache.dubbo.common.constants.CommonConstants.READONLY_EVENT;
// TODO response test
class HeaderExchangeHandlerTest {
@Test
void testReceivedRequestOneway() throws RemotingException {
final Channel mockChannel = new MockedChannel();
final Person requestData = new Person("charles");
Request request = new Request();
request.setTwoWay(false);
request.setData(requestData);
ExchangeHandler exHandler = new MockedExchangeHandler() {
@Override
public void received(Channel channel, Object message) throws RemotingException {
Assertions.assertEquals(requestData, message);
}
};
HeaderExchangeHandler headExHandler = new HeaderExchangeHandler(exHandler);
headExHandler.received(mockChannel, request);
}
@Test
void testReceivedRequestTwoway() throws RemotingException {
final Person requestData = new Person("charles");
final Request request = new Request();
request.setTwoWay(true);
request.setData(requestData);
final AtomicInteger count = new AtomicInteger(0);
final Channel mockChannel = new MockedChannel() {
@Override
public void send(Object message) throws RemotingException {
Response res = (Response) message;
Assertions.assertEquals(request.getId(), res.getId());
Assertions.assertEquals(request.getVersion(), res.getVersion());
Assertions.assertEquals(Response.OK, res.getStatus());
Assertions.assertEquals(requestData, res.getResult());
Assertions.assertNull(res.getErrorMessage());
count.incrementAndGet();
}
};
ExchangeHandler exHandler = new MockedExchangeHandler() {
@Override
public CompletableFuture<Object> reply(ExchangeChannel channel, Object request) throws RemotingException {
return CompletableFuture.completedFuture(request);
}
@Override
public void received(Channel channel, Object message) throws RemotingException {
Assertions.fail();
}
};
HeaderExchangeHandler headerExchangeHandler = new HeaderExchangeHandler(exHandler);
headerExchangeHandler.received(mockChannel, request);
Assertions.assertEquals(1, count.get());
}
@Test
void testReceivedRequestTwowayErrorWithNullHandler() throws RemotingException {
Assertions.assertThrows(IllegalArgumentException.class, () -> new HeaderExchangeHandler(null));
}
@Test
void testReceivedRequestTwowayErrorReply() throws RemotingException {
final Person requestData = new Person("charles");
final Request request = new Request();
request.setTwoWay(true);
request.setData(requestData);
final AtomicInteger count = new AtomicInteger(0);
final Channel mockChannel = new MockedChannel() {
@Override
public void send(Object message) throws RemotingException {
Response res = (Response) message;
Assertions.assertEquals(request.getId(), res.getId());
Assertions.assertEquals(request.getVersion(), res.getVersion());
Assertions.assertEquals(Response.SERVICE_ERROR, res.getStatus());
Assertions.assertNull(res.getResult());
Assertions.assertTrue(res.getErrorMessage().contains(BizException.class.getName()));
count.incrementAndGet();
}
};
ExchangeHandler exHandler = new MockedExchangeHandler() {
@Override
public CompletableFuture<Object> reply(ExchangeChannel channel, Object request) throws RemotingException {
throw new BizException();
}
};
HeaderExchangeHandler headerExchangeHandler = new HeaderExchangeHandler(exHandler);
headerExchangeHandler.received(mockChannel, request);
Assertions.assertEquals(1, count.get());
}
@Test
void testReceivedRequestTwowayErrorRequestBroken() throws RemotingException {
final Request request = new Request();
request.setTwoWay(true);
request.setData(new BizException());
request.setBroken(true);
final AtomicInteger count = new AtomicInteger(0);
final Channel mockChannel = new MockedChannel() {
@Override
public void send(Object message) throws RemotingException {
Response res = (Response) message;
Assertions.assertEquals(request.getId(), res.getId());
Assertions.assertEquals(request.getVersion(), res.getVersion());
Assertions.assertEquals(Response.BAD_REQUEST, res.getStatus());
Assertions.assertNull(res.getResult());
Assertions.assertTrue(res.getErrorMessage().contains(BizException.class.getName()));
count.incrementAndGet();
}
};
HeaderExchangeHandler headerExchangeHandler = new HeaderExchangeHandler(new MockedExchangeHandler());
headerExchangeHandler.received(mockChannel, request);
Assertions.assertEquals(1, count.get());
}
@Test
void testReceivedRequestEventReadonly() throws RemotingException {
final Request request = new Request();
request.setTwoWay(true);
request.setEvent(READONLY_EVENT);
final Channel mockChannel = new MockedChannel();
HeaderExchangeHandler headerExchangeHandler = new HeaderExchangeHandler(new MockedExchangeHandler());
headerExchangeHandler.received(mockChannel, request);
Assertions.assertTrue(mockChannel.hasAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY));
}
@Test
void testReceivedRequestEventOtherDiscard() throws RemotingException {
final Request request = new Request();
request.setTwoWay(true);
request.setEvent("my event");
final Channel mockChannel = new MockedChannel() {
@Override
public void send(Object message) throws RemotingException {
Assertions.fail();
}
};
HeaderExchangeHandler headerExchangeHandler = new HeaderExchangeHandler(new MockedExchangeHandler() {
@Override
public CompletableFuture<Object> reply(ExchangeChannel channel, Object request) throws RemotingException {
Assertions.fail();
throw new RemotingException(channel, "");
}
@Override
public void received(Channel channel, Object message) throws RemotingException {
Assertions.fail();
throw new RemotingException(channel, "");
}
});
headerExchangeHandler.received(mockChannel, request);
}
@Test
void testReceivedResponseHeartbeatEvent() throws Exception {
Channel mockChannel = new MockedChannel();
HeaderExchangeHandler headerExchangeHandler = new HeaderExchangeHandler(new MockedExchangeHandler());
Response response = new Response(1);
response.setStatus(Response.OK);
response.setEvent(true);
response.setResult(HEARTBEAT_EVENT);
headerExchangeHandler.received(mockChannel, response);
}
@Test
void testReceivedResponse() throws Exception {
Request request = new Request(1);
request.setTwoWay(true);
Channel mockChannel = new MockedChannel();
DefaultFuture future = DefaultFuture.newFuture(mockChannel, request, 5000, null);
HeaderExchangeHandler headerExchangeHandler = new HeaderExchangeHandler(new MockedExchangeHandler());
Response response = new Response(1);
response.setStatus(Response.OK);
response.setResult("MOCK_DATA");
headerExchangeHandler.received(mockChannel, response);
Object result = future.get();
Assertions.assertEquals(result.toString(), "MOCK_DATA");
}
private class BizException extends RuntimeException {
private static final long serialVersionUID = 1L;
}
private class MockedExchangeHandler extends MockedChannelHandler implements ExchangeHandler {
public String telnet(Channel channel, String message) throws RemotingException {
throw new UnsupportedOperationException();
}
public CompletableFuture<Object> reply(ExchangeChannel channel, Object request) throws RemotingException {
throw new UnsupportedOperationException();
}
}
private class Person {
private String name;
public Person(String name) {
super();
this.name = name;
}
@Override
public String toString() {
return "Person [name=" + name + "]";
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/HeapChannelBufferTest.java | 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()));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/ChannelBuffersTest.java | 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));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/DirectChannelBufferTest.java | 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};
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/AbstractChannelBufferTest.java | 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.
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | true |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/ChannelBufferFactoryTest.java | 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());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/DynamicChannelBufferTest.java | 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);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/ChannelBufferStreamTest.java | 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));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/ByteBufferBackedChannelBufferTest.java | 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};
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Dispatcher.java | 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);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Client.java | 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);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/ExecutionException.java | 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;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Transporters.java | 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();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/IdleSensible.java | 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;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Channel.java | 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);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/TimeoutException.java | 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;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Codec.java | 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;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Transporter.java | 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;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/ChannelHandler.java | 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;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/RemotingServer.java | 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);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/RemotingException.java | 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;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Decodeable.java | 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;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Codec2.java | 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
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Constants.java | 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;
import java.util.Arrays;
import java.util.List;
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 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 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";
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 PORT_UNIFICATION_NETTY4_SERVER = "netty4";
List<String> REST_SERVER = Arrays.asList("jetty", "tomcat", "netty");
String CONTENT_LENGTH_KEY = "content-length";
String SSL_SESSION_KEY = "ssl-session";
String CONNECTION_HANDLER_NAME = "connectionHandler";
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Endpoint.java | 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();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/HeartBeatRequest.java | 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;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Exchangers.java | 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);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/HeartBeatResponse.java | 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;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/PortUnificationExchanger.java | 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();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/ExchangeClient.java | 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 {}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/ExchangeChannel.java | 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);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Exchanger.java | 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;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Response.java | 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;
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) + "]";
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/ExchangeServer.java | 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);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/ExchangeHandler.java | 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;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Request.java | 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 org.apache.dubbo.common.utils.SystemPropertyConfigUtils;
import java.security.SecureRandom;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicLong;
import static org.apache.dubbo.common.constants.CommonConstants.DubboProperty.DUBBO_USE_SECURE_RANDOM_ID;
import static org.apache.dubbo.common.constants.CommonConstants.HEARTBEAT_EVENT;
/**
* 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(SystemPropertyConfigUtils.getSystemProperty(DUBBO_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)) + "]";
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/codec/ExchangeCodec.java | 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);
int len;
try (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();
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;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/DefaultFuture.java | 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.RejectedExecutionException;
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()) {
try {
executor.execute(() -> notifyTimeout(future));
} catch (RejectedExecutionException e) {
notifyExecutionError(future, e);
throw e;
}
} 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);
}
private void notifyExecutionError(DefaultFuture future, Throwable e) {
// create exception response.
Response errorResponse = new Response(future.getId());
// set error status
errorResponse.setStatus(Response.SERVER_THREADPOOL_EXHAUSTED_ERROR);
// set detailed error message
errorResponse.setErrorMessage("Executor rejected the task for handling timeout notification: "
+ e.getClass().getSimpleName() + " - " + e.getMessage());
// handle response.
DefaultFuture.received(future.getChannel(), errorResponse, true);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/ExchangeServerDelegate.java | 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;
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();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/ReplierDispatcher.java | 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;
public class ReplierDispatcher implements Replier<Object> {
private final Replier<?> defaultReplier;
private final Map<Class<?>, Replier<?>> repliers = new ConcurrentHashMap<>();
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);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/MultiMessage.java | 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();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/ExchangeHandlerDispatcher.java | 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;
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);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/Replier.java | 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;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/ExchangeHandlerAdapter.java | 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;
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;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/AbstractTimerTask.java | 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;
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;
// do not start here because inheritor should set additional timeout parameters before doing task.
}
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();
}
protected 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();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchanger.java | 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;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandler.java | 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();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java | 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<>();
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);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/CloseTimerTask.java | 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;
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;
start();
}
@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);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/ReconnectTimerTask.java | 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;
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;
start();
}
@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);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java | 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 + "]";
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java | 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;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java | 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();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatTimerTask.java | 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;
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;
start();
}
@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);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/TelnetHandler.java | dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/TelnetHandler.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.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.RemotingException;
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface TelnetHandler {
/**
* telnet.
*
* @param channel
* @param message
*/
String telnet(Channel channel, String message) throws RemotingException;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/codec/TelnetCodec.java | dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/codec/TelnetCodec.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.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.utils.CollectionUtils;
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.transport.codec.TransportCodec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_UNSUPPORTED_CHARSET;
import static org.apache.dubbo.remoting.Constants.CHARSET_KEY;
import static org.apache.dubbo.remoting.Constants.DEFAULT_CHARSET;
public class TelnetCodec extends TransportCodec {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(TelnetCodec.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 byte[] {'\r', '\n'} /* Windows Enter */, new byte[] {'\n'} /* Linux Enter */);
private static final List<?> EXIT = Arrays.asList(
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 */);
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(TRANSPORT_UNSUPPORTED_CHARSET, "", "", 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(TRANSPORT_UNSUPPORTED_CHARSET, "", "", t.getMessage(), t);
}
}
}
}
try {
return Charset.forName(DEFAULT_CHARSET);
} catch (Throwable t) {
logger.warn(TRANSPORT_UNSUPPORTED_CHARSET, "", "", 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;
}
@Override
public void encode(Channel channel, ChannelBuffer buffer, Object message) throws IOException {
if (message instanceof String) {
if (isClientSide(channel)) {
message = message + "\r\n";
}
byte[] msgData = ((String) message).getBytes(getCharset(channel).name());
buffer.writeBytes(msgData);
} else {
super.encode(channel, buffer, message);
}
}
@Override
public Object decode(Channel channel, ChannelBuffer buffer) throws IOException {
int readable = buffer.readableBytes();
byte[] message = new byte[readable];
buffer.readBytes(message);
return decode(channel, buffer, readable, message);
}
@SuppressWarnings("unchecked")
protected Object decode(Channel channel, ChannelBuffer buffer, int readable, byte[] message) throws IOException {
if (isClientSide(channel)) {
return toString(message, getCharset(channel));
}
checkPayload(channel, readable);
if (message == null || message.length == 0) {
return DecodeResult.NEED_MORE_INPUT;
}
if (message[message.length - 1] == '\b') { // Windows backspace echo
try {
boolean isDoubleChar = message.length >= 3 && message[message.length - 3] < 0; // double byte char
channel.send(new String(
isDoubleChar ? new byte[] {32, 32, 8, 8} : new byte[] {32, 8},
getCharset(channel).name()));
} catch (RemotingException e) {
throw new IOException(StringUtils.toString(e));
}
return DecodeResult.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 (CollectionUtils.isEmpty(history)) {
return DecodeResult.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 + value;
}
try {
channel.send(value);
} catch (RemotingException e) {
throw new IOException(StringUtils.toString(e));
}
}
return DecodeResult.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 DecodeResult.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 (CollectionUtils.isNotEmpty(history) && index != null && index >= 0 && index < history.size()) {
String value = history.get(index);
if (value != null) {
byte[] b1 = value.getBytes(StandardCharsets.UTF_8);
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;
}
}
String result = toString(message, getCharset(channel));
if (result.trim().length() > 0) {
if (history == null) {
history = new LinkedList<>();
channel.setAttribute(HISTORY_LIST_KEY, history);
}
if (history.isEmpty()) {
history.addLast(result);
} else if (!result.equals(history.getLast())) {
history.remove(result);
history.addLast(result);
if (history.size() > 10) {
history.removeFirst();
}
}
}
return result;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/TelnetUtils.java | dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/TelnetUtils.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 java.util.Arrays;
import java.util.List;
public class TelnetUtils {
public static String toList(List<List<String>> table) {
int[] widths = new int[table.get(0).size()];
for (int j = 0; j < widths.length; j++) {
for (List<String> row : table) {
widths[j] = Math.max(widths[j], row.get(j).length());
}
}
StringBuilder buf = new StringBuilder();
for (List<String> row : table) {
if (buf.length() > 0) {
buf.append("\r\n");
}
for (int j = 0; j < widths.length; j++) {
if (j > 0) {
buf.append(" - ");
}
String value = row.get(j);
buf.append(value);
if (j < widths.length - 1) {
int pad = widths[j] - value.length();
if (pad > 0) {
for (int k = 0; k < pad; k++) {
buf.append(' ');
}
}
}
}
}
return buf.toString();
}
public static String toTable(String[] header, List<List<String>> table) {
return toTable(Arrays.asList(header), table);
}
public static String toTable(List<String> header, List<List<String>> table) {
int totalWidth = 0;
int[] widths = new int[header.size()];
int maxwidth = 70;
int maxcountbefore = 0;
for (int j = 0; j < widths.length; j++) {
widths[j] = Math.max(widths[j], header.get(j).length());
}
for (List<String> row : table) {
int countbefore = 0;
for (int j = 0; j < widths.length; j++) {
widths[j] = Math.max(widths[j], row.get(j).length());
totalWidth = (totalWidth + widths[j]) > maxwidth ? maxwidth : (totalWidth + widths[j]);
if (j < widths.length - 1) {
countbefore = countbefore + widths[j];
}
}
maxcountbefore = Math.max(countbefore, maxcountbefore);
}
widths[widths.length - 1] = Math.min(widths[widths.length - 1], maxwidth - maxcountbefore);
StringBuilder buf = new StringBuilder();
// line
buf.append('+');
for (int j = 0; j < widths.length; j++) {
for (int k = 0; k < widths[j] + 2; k++) {
buf.append('-');
}
buf.append('+');
}
buf.append("\r\n");
// header
buf.append('|');
for (int j = 0; j < widths.length; j++) {
String cell = header.get(j);
buf.append(' ');
buf.append(cell);
int pad = widths[j] - cell.length();
if (pad > 0) {
for (int k = 0; k < pad; k++) {
buf.append(' ');
}
}
buf.append(" |");
}
buf.append("\r\n");
// line
buf.append('+');
for (int j = 0; j < widths.length; j++) {
for (int k = 0; k < widths[j] + 2; k++) {
buf.append('-');
}
buf.append('+');
}
buf.append("\r\n");
// content
for (List<String> row : table) {
StringBuilder rowbuf = new StringBuilder();
rowbuf.append('|');
for (int j = 0; j < widths.length; j++) {
String cell = row.get(j);
rowbuf.append(' ');
int remaining = cell.length();
while (remaining > 0) {
if (rowbuf.length() >= totalWidth) {
buf.append(rowbuf.toString());
rowbuf = new StringBuilder();
// for(int m = 0;m < maxcountbefore && maxcountbefore < totalWidth ;
// m++){
// rowbuf.append(" ");
// }
}
rowbuf.append(cell, cell.length() - remaining, cell.length() - remaining + 1);
remaining--;
}
int pad = widths[j] - cell.length();
if (pad > 0) {
for (int k = 0; k < pad; k++) {
rowbuf.append(' ');
}
}
rowbuf.append(" |");
}
buf.append(rowbuf).append("\r\n");
}
// line
buf.append('+');
for (int j = 0; j < widths.length; j++) {
for (int k = 0; k < widths[j] + 2; k++) {
buf.append('-');
}
buf.append('+');
}
buf.append("\r\n");
return buf.toString();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/TelnetHandlerAdapter.java | dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/TelnetHandlerAdapter.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.extension.ExtensionLoader;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.telnet.TelnetHandler;
import org.apache.dubbo.remoting.transport.ChannelHandlerAdapter;
import org.apache.dubbo.rpc.model.FrameworkModel;
import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN;
import static org.apache.dubbo.remoting.Constants.TELNET_KEY;
public class TelnetHandlerAdapter extends ChannelHandlerAdapter implements TelnetHandler {
private final ExtensionLoader<TelnetHandler> extensionLoader;
public TelnetHandlerAdapter(FrameworkModel frameworkModel) {
extensionLoader = frameworkModel.getExtensionLoader(TelnetHandler.class);
}
@Override
public String telnet(Channel channel, String message) throws RemotingException {
String prompt = channel.getUrl().getParameterAndDecoded(Constants.PROMPT_KEY, Constants.DEFAULT_PROMPT);
boolean noprompt = message.contains("--no-prompt");
message = message.replace("--no-prompt", "");
StringBuilder buf = new StringBuilder();
message = message.trim();
String command;
if (message.length() > 0) {
int i = message.indexOf(' ');
if (i > 0) {
command = message.substring(0, i).trim();
message = message.substring(i + 1).trim();
} else {
command = message;
message = "";
}
} else {
command = "";
}
if (command.length() > 0) {
if (extensionLoader.hasExtension(command)) {
if (commandEnabled(channel.getUrl(), command)) {
try {
String result = extensionLoader.getExtension(command).telnet(channel, message);
if (result == null) {
return null;
}
buf.append(result);
} catch (Throwable t) {
buf.append(t.getMessage());
}
} else {
buf.append("Command: ");
buf.append(command);
buf.append(
" disabled for security reasons, please enable support by listing the commands through 'telnet'");
}
} else {
buf.append("Unsupported command: ");
buf.append(command);
}
}
if (buf.length() > 0) {
buf.append("\r\n");
}
if (StringUtils.isNotEmpty(prompt) && !noprompt) {
buf.append(prompt);
}
return buf.toString();
}
private boolean commandEnabled(URL url, String command) {
String supportCommands = url.getParameter(TELNET_KEY);
if (StringUtils.isEmpty(supportCommands)) {
return false;
}
String[] commands = COMMA_SPLIT_PATTERN.split(supportCommands);
for (String c : commands) {
if (command.equals(c)) {
return true;
}
}
return false;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/Help.java | dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/Help.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 java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Help
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface Help {
String parameter() default "";
String summary();
String detail() default "";
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/ClearTelnetHandler.java | dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/ClearTelnetHandler.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.command;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.telnet.TelnetHandler;
import org.apache.dubbo.remoting.telnet.support.Help;
@Activate
@Help(parameter = "[lines]", summary = "Clear screen.", detail = "Clear screen.")
public class ClearTelnetHandler implements TelnetHandler {
private static final int MAX_LINES = 1000;
@Override
public String telnet(Channel channel, String message) {
int lines = 100;
if (message.length() > 0) {
if (!StringUtils.isNumber(message)) {
return "Illegal lines " + message + ", must be integer.";
}
lines = Math.min(MAX_LINES, Integer.parseInt(message));
}
StringBuilder buf = new StringBuilder();
for (int i = 0; i < lines; i++) {
buf.append("\r\n");
}
return buf.toString();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/StatusTelnetHandler.java | dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/StatusTelnetHandler.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.command;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.status.Status;
import org.apache.dubbo.common.status.StatusChecker;
import org.apache.dubbo.common.status.support.StatusUtils;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.telnet.TelnetHandler;
import org.apache.dubbo.remoting.telnet.support.Help;
import org.apache.dubbo.remoting.telnet.support.TelnetUtils;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN;
import static org.apache.dubbo.config.Constants.STATUS_KEY;
@Activate
@Help(parameter = "[-l]", summary = "Show status.", detail = "Show status.")
public class StatusTelnetHandler implements TelnetHandler {
@Override
public String telnet(Channel channel, String message) {
ApplicationModel applicationModel =
ScopeModelUtil.getApplicationModel(channel.getUrl().getScopeModel());
ExtensionLoader<StatusChecker> extensionLoader = applicationModel.getExtensionLoader(StatusChecker.class);
if ("-l".equals(message)) {
List<StatusChecker> checkers = extensionLoader.getActivateExtension(channel.getUrl(), STATUS_KEY);
String[] header = new String[] {"resource", "status", "message"};
List<List<String>> table = new ArrayList<>();
Map<String, Status> statuses = new HashMap<>();
if (CollectionUtils.isNotEmpty(checkers)) {
for (StatusChecker checker : checkers) {
String name = extensionLoader.getExtensionName(checker);
Status stat;
try {
stat = checker.check();
} catch (Throwable t) {
stat = new Status(Status.Level.ERROR, t.getMessage());
}
statuses.put(name, stat);
if (stat.getLevel() != null && stat.getLevel() != Status.Level.UNKNOWN) {
List<String> row = new ArrayList<>();
row.add(name);
row.add(String.valueOf(stat.getLevel()));
row.add(stat.getMessage() == null ? "" : stat.getMessage());
table.add(row);
}
}
}
Status stat = StatusUtils.getSummaryStatus(statuses);
List<String> row = new ArrayList<>();
row.add("summary");
row.add(String.valueOf(stat.getLevel()));
row.add(stat.getMessage());
table.add(row);
return TelnetUtils.toTable(header, table);
} else if (message.length() > 0) {
return "Unsupported parameter " + message + " for status.";
}
String status = channel.getUrl().getParameter("status");
Map<String, Status> statuses = new HashMap<>();
if (StringUtils.isNotEmpty(status)) {
String[] ss = COMMA_SPLIT_PATTERN.split(status);
for (String s : ss) {
StatusChecker handler = extensionLoader.getExtension(s);
Status stat;
try {
stat = handler.check();
} catch (Throwable t) {
stat = new Status(Status.Level.ERROR, t.getMessage());
}
statuses.put(s, stat);
}
}
Status stat = StatusUtils.getSummaryStatus(statuses);
return String.valueOf(stat.getLevel());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/LogTelnetHandler.java | dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/LogTelnetHandler.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.command;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.logger.Level;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.telnet.TelnetHandler;
import org.apache.dubbo.remoting.telnet.support.Help;
import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Date;
@Activate
@Help(parameter = "level", summary = "Change log level or show log ", detail = "Change log level or show log")
public class LogTelnetHandler implements TelnetHandler {
public static final String SERVICE_KEY = "telnet.log";
@Override
public String telnet(Channel channel, String message) {
long size = 0;
File file = LoggerFactory.getFile();
StringBuilder buf = new StringBuilder();
if (message == null || message.trim().length() == 0) {
buf.append("EXAMPLE: log error / log 100");
} else {
String[] str = message.split(" ");
if (!StringUtils.isNumber(str[0])) {
LoggerFactory.setLevel(Level.valueOf(message.toUpperCase()));
} else {
int showLogLength = Integer.parseInt(str[0]);
if (file != null && file.exists()) {
try {
try (FileInputStream fis = new FileInputStream(file)) {
try (FileChannel filechannel = fis.getChannel()) {
size = filechannel.size();
ByteBuffer bb;
if (size <= showLogLength) {
bb = ByteBuffer.allocate((int) size);
filechannel.read(bb, 0);
} else {
int pos = (int) (size - showLogLength);
bb = ByteBuffer.allocate(showLogLength);
filechannel.read(bb, pos);
}
bb.flip();
String content = new String(bb.array())
.replace("<", "<")
.replace(">", ">")
.replace("\n", "<br/><br/>");
buf.append("\r\ncontent:" + content);
buf.append("\r\nmodified:"
+ (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.format(new Date(file.lastModified()))));
buf.append("\r\nsize:" + size + "\r\n");
}
}
} catch (Exception e) {
buf.append(e.getMessage());
}
} else {
size = 0;
buf.append("\r\nMESSAGE: log file not exists or log appender is console .");
}
}
}
buf.append("\r\nCURRENT LOG LEVEL:" + LoggerFactory.getLevel())
.append("\r\nCURRENT LOG APPENDER:" + (file == null ? "console" : file.getAbsolutePath()));
return buf.toString();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/ExitTelnetHandler.java | dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/ExitTelnetHandler.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.command;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.telnet.TelnetHandler;
import org.apache.dubbo.remoting.telnet.support.Help;
@Activate
@Help(summary = "Exit the telnet.", detail = "Exit the telnet.")
public class ExitTelnetHandler implements TelnetHandler {
@Override
public String telnet(Channel channel, String message) {
channel.close();
return null;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/HelpTelnetHandler.java | dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/HelpTelnetHandler.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.command;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.telnet.TelnetHandler;
import org.apache.dubbo.remoting.telnet.support.Help;
import org.apache.dubbo.remoting.telnet.support.TelnetUtils;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
@Activate
@Help(parameter = "[command]", summary = "Show help.", detail = "Show help.")
public class HelpTelnetHandler implements TelnetHandler {
private final ExtensionLoader<TelnetHandler> extensionLoader;
private static final String MAIN_HELP = "mainHelp";
private static Map<String, String> processedTable = new WeakHashMap<>();
public HelpTelnetHandler(FrameworkModel frameworkModel) {
extensionLoader = frameworkModel.getExtensionLoader(TelnetHandler.class);
}
@Override
public String telnet(Channel channel, String message) {
if (message.length() > 0) {
return processedTable.computeIfAbsent(message, commandName -> generateForOneCommand(commandName));
} else {
return processedTable.computeIfAbsent(MAIN_HELP, commandName -> generateForAllCommand(channel));
}
}
private String generateForOneCommand(String message) {
if (!extensionLoader.hasExtension(message)) {
return "No such command " + message;
}
TelnetHandler handler = extensionLoader.getExtension(message);
Help help = handler.getClass().getAnnotation(Help.class);
StringBuilder buf = new StringBuilder();
buf.append("Command:\r\n ");
buf.append(message + " " + help.parameter().replace("\r\n", " ").replace("\n", " "));
buf.append("\r\nSummary:\r\n ");
buf.append(help.summary().replace("\r\n", " ").replace("\n", " "));
buf.append("\r\nDetail:\r\n ");
buf.append(help.detail().replace("\r\n", " \r\n").replace("\n", " \n"));
return buf.toString();
}
private String generateForAllCommand(Channel channel) {
List<List<String>> table = new ArrayList<>();
List<TelnetHandler> handlers = extensionLoader.getActivateExtension(channel.getUrl(), "telnet");
if (CollectionUtils.isNotEmpty(handlers)) {
for (TelnetHandler handler : handlers) {
Help help = handler.getClass().getAnnotation(Help.class);
List<String> row = new ArrayList<>();
String parameter = " " + extensionLoader.getExtensionName(handler) + " "
+ (help != null ? help.parameter().replace("\r\n", " ").replace("\n", " ") : "");
row.add(parameter.length() > 55 ? parameter.substring(0, 55) + "..." : parameter);
String summary =
help != null ? help.summary().replace("\r\n", " ").replace("\n", " ") : "";
row.add(summary.length() > 55 ? summary.substring(0, 55) + "..." : summary);
table.add(row);
}
}
return "Please input \"help [command]\" show detail.\r\n" + TelnetUtils.toList(table);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/utils/UrlUtils.java | dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/utils/UrlUtils.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.common.constants.CommonConstants;
import org.apache.dubbo.common.serialize.support.DefaultSerializationSelector;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.common.utils.SystemPropertyConfigUtils;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.remoting.transport.CodecSupport;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import static org.apache.dubbo.remoting.Constants.PREFER_SERIALIZATION_KEY;
import static org.apache.dubbo.remoting.Constants.SERIALIZATION_KEY;
public class UrlUtils {
private static final String ALLOWED_SERIALIZATION_KEY = "allowedSerialization";
public static int getCloseTimeout(URL url) {
String configuredCloseTimeout = SystemPropertyConfigUtils.getSystemProperty(
CommonConstants.DubboProperty.DUBBO_CLOSE_TIMEOUT_CONFIG_KEY);
int defaultCloseTimeout = -1;
if (StringUtils.isNotEmpty(configuredCloseTimeout)) {
try {
defaultCloseTimeout = Integer.parseInt(configuredCloseTimeout);
} catch (NumberFormatException e) {
// use default heartbeat
}
}
if (defaultCloseTimeout < 0) {
defaultCloseTimeout = getIdleTimeout(url);
}
int closeTimeout = url.getParameter(Constants.CLOSE_TIMEOUT_KEY, defaultCloseTimeout);
int heartbeat = getHeartbeat(url);
if (closeTimeout < heartbeat * 2) {
throw new IllegalStateException("closeTimeout < heartbeatInterval * 2");
}
return closeTimeout;
}
public static int getIdleTimeout(URL url) {
int heartBeat = getHeartbeat(url);
// idleTimeout should be at least more than twice heartBeat because possible retries of client.
int idleTimeout = url.getParameter(Constants.HEARTBEAT_TIMEOUT_KEY, heartBeat * 3);
if (idleTimeout < heartBeat * 2) {
throw new IllegalStateException("idleTimeout < heartbeatInterval * 2");
}
return idleTimeout;
}
public static int getHeartbeat(URL url) {
String configuredHeartbeat =
SystemPropertyConfigUtils.getSystemProperty(CommonConstants.DubboProperty.DUBBO_HEARTBEAT_CONFIG_KEY);
int defaultHeartbeat = Constants.DEFAULT_HEARTBEAT;
if (StringUtils.isNotEmpty(configuredHeartbeat)) {
try {
defaultHeartbeat = Integer.parseInt(configuredHeartbeat);
} catch (NumberFormatException e) {
// use default heartbeat
}
}
return url.getParameter(Constants.HEARTBEAT_KEY, defaultHeartbeat);
}
/**
* Get the serialization id
*
* @param url url
* @return {@link Byte}
*/
public static Byte serializationId(URL url) {
Byte serializationId;
// Obtain the value from prefer_serialization. Such as.fastjson2,hessian2
List<String> preferSerials = preferSerialization(url);
for (String preferSerial : preferSerials) {
if ((serializationId = CodecSupport.getIDByName(preferSerial)) != null) {
return serializationId;
}
}
// Secondly, obtain the value from serialization
if ((serializationId = CodecSupport.getIDByName(url.getParameter(SERIALIZATION_KEY))) != null) {
return serializationId;
}
// Finally, use the default serialization type
return CodecSupport.getIDByName(DefaultSerializationSelector.getDefaultRemotingSerialization());
}
/**
* Get the serialization or default serialization
*
* @param url url
* @return {@link String}
*/
public static String serializationOrDefault(URL url) {
// noinspection OptionalGetWithoutIsPresent
Optional<String> serializations = allSerializations(url).stream().findFirst();
return serializations.orElseGet(DefaultSerializationSelector::getDefaultRemotingSerialization);
}
/**
* Get the all serializations,ensure insertion order
*
* @param url url
* @return {@link List}<{@link String}>
*/
@SuppressWarnings("unchecked")
public static Collection<String> allSerializations(URL url) {
// preferSerialization -> serialization -> default serialization
Set<String> serializations = new LinkedHashSet<>(preferSerialization(url));
Optional.ofNullable(url.getParameter(SERIALIZATION_KEY))
.filter(StringUtils::isNotBlank)
.ifPresent(serializations::add);
serializations.add(DefaultSerializationSelector.getDefaultRemotingSerialization());
return Collections.unmodifiableSet(serializations);
}
/**
* Prefer Serialization
*
* @param url url
* @return {@link List}<{@link String}>
*/
public static List<String> preferSerialization(URL url) {
String preferSerialization = url.getParameter(PREFER_SERIALIZATION_KEY);
if (StringUtils.isNotBlank(preferSerialization)) {
return Collections.unmodifiableList(StringUtils.splitToList(preferSerialization, ','));
}
return Collections.emptyList();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/utils/PayloadDropper.java | dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/utils/PayloadDropper.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.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.remoting.exchange.Request;
import org.apache.dubbo.remoting.exchange.Response;
public class PayloadDropper {
private static Logger logger = LoggerFactory.getLogger(PayloadDropper.class);
/**
* only log body in debugger mode for size & security consideration.
*
* @param message
* @return
*/
public static Object getRequestWithoutData(Object message) {
if (logger.isDebugEnabled()) {
return message;
}
if (message instanceof Request) {
Request request = (Request) message;
request.setData(null);
return request;
} else if (message instanceof Response) {
Response response = (Response) message;
response.setResult(null);
return response;
}
return message;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/WireProtocol.java | dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/WireProtocol.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.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.remoting.api.pu.ChannelOperator;
import org.apache.dubbo.remoting.api.ssl.ContextOperator;
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface WireProtocol {
ProtocolDetector detector();
void configServerProtocolHandler(URL url, ChannelOperator operator);
void configClientPipeline(URL url, ChannelOperator operator, ContextOperator contextOperator);
void close();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/AbstractWireProtocol.java | dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/AbstractWireProtocol.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 abstract class AbstractWireProtocol implements WireProtocol {
private final ProtocolDetector detector;
public AbstractWireProtocol(ProtocolDetector detector) {
this.detector = detector;
}
@Override
public ProtocolDetector detector() {
return detector;
}
@Override
public void configClientPipeline(URL url, ChannelOperator operator, ContextOperator contextOperator) {}
@Override
public void close() {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/ProtocolDetector.java | dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/ProtocolDetector.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.remoting.buffer.ChannelBuffer;
import java.util.HashMap;
import java.util.Map;
/**
* Determine incoming bytes belong to the specific protocol.
*/
public interface ProtocolDetector {
Result detect(ChannelBuffer in);
class Result {
private final Flag flag;
private final Map<String, String> detectContext = new HashMap<>(4);
private Result(Flag flag) {
this.flag = flag;
}
public void setAttribute(String key, String value) {
this.detectContext.put(key, value);
}
public String getAttribute(String key) {
return this.detectContext.get(key);
}
public void removeAttribute(String key) {
this.detectContext.remove(key);
}
public Flag flag() {
return flag;
}
public static Result recognized() {
return new Result(Flag.RECOGNIZED);
}
public static Result unrecognized() {
return new Result(Flag.UNRECOGNIZED);
}
public static Result needMoreData() {
return new Result(Flag.NEED_MORE_DATA);
}
@Override
public int hashCode() {
return flag.hashCode();
}
@Override
public boolean equals(Object obj) {
return obj instanceof Result && flag == ((Result) obj).flag;
}
}
enum Flag {
RECOGNIZED,
UNRECOGNIZED,
NEED_MORE_DATA
}
default int getByteByIndex(ChannelBuffer buffer, int index) {
return buffer.getByte(buffer.readerIndex() + index);
}
default boolean prefixMatch(char[][] prefixes, ChannelBuffer buffer, int length) {
int[] ints = new int[length];
for (int i = 0; i < length; i++) {
ints[i] = getByteByIndex(buffer, i);
}
// prefix match
for (char[] prefix : prefixes) {
boolean matched = true;
for (int j = 0; j < length; j++) {
if (prefix[j] != ints[j]) {
matched = false;
break;
}
}
if (matched) {
return true;
}
}
return false;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/pu/DefaultPuHandler.java | dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/pu/DefaultPuHandler.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.pu;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.RemotingException;
public class DefaultPuHandler implements ChannelHandler {
@Override
public void connected(Channel channel) throws RemotingException {}
@Override
public void disconnected(Channel channel) throws RemotingException {}
@Override
public void sent(Channel channel, Object message) throws RemotingException {}
@Override
public void received(Channel channel, Object message) throws RemotingException {}
@Override
public void caught(Channel channel, Throwable exception) throws RemotingException {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/pu/PortUnificationTransporter.java | dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/pu/PortUnificationTransporter.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.pu;
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.ChannelHandler;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.api.connection.AbstractConnectionClient;
@SPI(value = "netty4", scope = ExtensionScope.FRAMEWORK)
public interface PortUnificationTransporter {
@Adaptive({Constants.SERVER_KEY, Constants.TRANSPORTER_KEY})
AbstractPortUnificationServer bind(URL url, ChannelHandler handler) throws RemotingException;
@Adaptive({Constants.CLIENT_KEY, Constants.TRANSPORTER_KEY})
AbstractConnectionClient connect(URL url, ChannelHandler handler) throws RemotingException;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/pu/ChannelHandlerPretender.java | dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/pu/ChannelHandlerPretender.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.pu;
import org.apache.dubbo.remoting.transport.ChannelHandlerAdapter;
public class ChannelHandlerPretender extends ChannelHandlerAdapter {
private final Object realHandler;
public ChannelHandlerPretender(Object realHandler) {
this.realHandler = realHandler;
}
public Object getRealHandler() {
return realHandler;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/pu/DefaultCodec.java | dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/pu/DefaultCodec.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.api.pu;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.Codec2;
import org.apache.dubbo.remoting.buffer.ChannelBuffer;
import java.io.IOException;
public class DefaultCodec implements Codec2 {
@Override
public void encode(Channel channel, ChannelBuffer buffer, Object message) throws IOException {}
@Override
public Object decode(Channel channel, ChannelBuffer buffer) throws IOException {
return null;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/pu/ChannelOperator.java | dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/pu/ChannelOperator.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.pu;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.api.ProtocolDetector;
import java.util.List;
public interface ChannelOperator {
void configChannelHandler(List<ChannelHandler> handlerList);
ProtocolDetector.Result detectResult();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/pu/AbstractPortUnificationServer.java | dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/pu/AbstractPortUnificationServer.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.pu;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.api.WireProtocol;
import org.apache.dubbo.remoting.transport.AbstractServer;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;
import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR;
import static org.apache.dubbo.common.constants.CommonConstants.EXT_PROTOCOL;
public abstract class AbstractPortUnificationServer extends AbstractServer {
/**
* extension name -> activate WireProtocol
*/
private volatile Map<String, WireProtocol> protocols;
/*
protocol name --> URL object
wire protocol will get url object to config server pipeline for channel
*/
private Map<String, URL> supportedUrls;
/*
protocol name --> ChannelHandler object
wire protocol will get handler to config server pipeline for channel
(for triple protocol, it's a default handler that do nothing)
*/
private Map<String, ChannelHandler> supportedHandlers;
public AbstractPortUnificationServer(URL url, ChannelHandler handler) throws RemotingException {
super(url, handler);
}
public Map<String, WireProtocol> getProtocols() {
return protocols;
}
@Override
protected final void doOpen() {
// initialize supportedUrls and supportedHandlers before potential usage to avoid NPE.
supportedUrls = new ConcurrentHashMap<>();
supportedHandlers = new ConcurrentHashMap<>();
ExtensionLoader<WireProtocol> loader =
getUrl().getOrDefaultFrameworkModel().getExtensionLoader(WireProtocol.class);
Map<String, WireProtocol> protocols = loader.getActivateExtension(getUrl(), new String[0]).stream()
.collect(Collectors.toConcurrentMap(loader::getExtensionName, Function.identity()));
// load extra protocols
String extraProtocols = getUrl().getParameter(EXT_PROTOCOL);
if (StringUtils.isNotEmpty(extraProtocols)) {
Arrays.stream(extraProtocols.split(COMMA_SEPARATOR)).forEach(p -> {
protocols.put(p, loader.getExtension(p));
});
}
this.protocols = protocols;
doOpen0();
}
protected abstract void doOpen0();
/*
This method registers URL object and corresponding channel handler to pu server.
In PuServerExchanger.bind, this method is called with ConcurrentHashMap.computeIfPresent to register messages to
this supportedUrls and supportedHandlers
*/
public void addSupportedProtocol(URL url, ChannelHandler handler) {
this.supportedUrls.put(url.getProtocol(), url);
this.supportedHandlers.put(url.getProtocol(), handler);
}
protected Map<String, URL> getSupportedUrls() {
// this getter is just used by implementation of this class
return supportedUrls;
}
public Map<String, ChannelHandler> getSupportedHandlers() {
// this getter is just used by implementation of this class
return supportedHandlers;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/connection/ConnectionHandler.java | dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/connection/ConnectionHandler.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.connection;
public interface ConnectionHandler {
/**
* when server close connection gracefully.
*
* @param channel Channel
*/
void onGoAway(Object channel);
/**
* reconnect
*
* @param channel Channel
*/
void reconnect(Object channel);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/connection/AbstractConnectionClient.java | dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/connection/AbstractConnectionClient.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.connection;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.api.WireProtocol;
import org.apache.dubbo.remoting.transport.AbstractClient;
import java.net.InetSocketAddress;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_ERROR_CLOSE_CLIENT;
public abstract class AbstractConnectionClient extends AbstractClient {
protected WireProtocol protocol;
protected InetSocketAddress remote;
protected AtomicBoolean init;
protected static final Object CONNECTED_OBJECT = new Object();
private volatile long counter;
private static final AtomicLongFieldUpdater<AbstractConnectionClient> COUNTER_UPDATER =
AtomicLongFieldUpdater.newUpdater(AbstractConnectionClient.class, "counter");
protected AbstractConnectionClient(URL url, ChannelHandler handler) throws RemotingException {
super(url, handler);
}
protected AbstractConnectionClient() {}
public final void increase() {
COUNTER_UPDATER.set(this, 1L);
}
/**
* Increments the reference count by 1.
*/
public final boolean retain() {
long oldCount = COUNTER_UPDATER.getAndIncrement(this);
if (oldCount <= 0) {
COUNTER_UPDATER.getAndDecrement(this);
logger.info(
"Retain failed, because connection " + remote
+ " has been destroyed but not yet removed, will create a new one instead."
+ " Check logs below to confirm that this connection finally gets removed to make sure there's no potential memory leak!");
return false;
}
return true;
}
/**
* Decreases the reference count by 1 and calls {@link this#destroy} if the reference count reaches 0.
*/
public boolean release() {
long remainingCount = COUNTER_UPDATER.decrementAndGet(this);
if (remainingCount == 0) {
logger.info("Destroying connection to {}, because the reference count reaches 0", remote);
destroy();
return true;
} else if (remainingCount <= -1) {
logger.warn(PROTOCOL_ERROR_CLOSE_CLIENT, "", "", "This instance has been destroyed");
return false;
} else {
return false;
}
}
/**
* init config and attribute.
*/
protected abstract void initConnectionClient();
/**
* connection is available.
*
* @return boolean
*/
public abstract boolean isAvailable();
/**
* add a listener that will be executed when a connection is established.
*
* @param func execute function
*/
public abstract void addConnectedListener(Runnable func);
/**
* Add a listener that will be executed when the connection is disconnected.
*
* @param func execute function
*/
public abstract void addDisconnectedListener(Runnable func);
/**
* add a listener that will be executed when the connection is closed.
*
* @param func execute function
*/
public abstract void addCloseListener(Runnable func);
/**
* when connected, callback.
*
* @param channel Channel
*/
public abstract void onConnected(Object channel);
/**
* when goaway, callback.
*
* @param channel Channel
*/
public abstract void onGoaway(Object channel);
/**
* This method will be invoked when counter reaches 0, override this method to destroy materials related to the specific resource.
*/
public abstract void destroy();
/**
* if generalizable, return NIOChannel
* else return Dubbo Channel
*
* @param generalizable generalizable
* @return Dubbo Channel or NIOChannel such as NettyChannel
*/
public abstract <T> T getChannel(Boolean generalizable);
/**
* Get counter
*/
public long getCounter() {
return COUNTER_UPDATER.get(this);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/connection/MultiplexProtocolConnectionManager.java | dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/connection/MultiplexProtocolConnectionManager.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.connection;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Consumer;
public class MultiplexProtocolConnectionManager implements ConnectionManager {
public static final String NAME = "multiple";
private final ConcurrentMap<String, ConnectionManager> protocols = new ConcurrentHashMap<>(1);
private FrameworkModel frameworkModel;
public MultiplexProtocolConnectionManager(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
@Override
public AbstractConnectionClient connect(URL url, ChannelHandler handler) {
final ConnectionManager manager = ConcurrentHashMapUtils.computeIfAbsent(
protocols, url.getProtocol(), this::createSingleProtocolConnectionManager);
return manager.connect(url, handler);
}
@Override
public void forEachConnection(Consumer<AbstractConnectionClient> connectionConsumer) {
protocols.values().forEach(p -> p.forEachConnection(connectionConsumer));
}
private ConnectionManager createSingleProtocolConnectionManager(String protocol) {
return frameworkModel
.getExtensionLoader(ConnectionManager.class)
.getExtension(SingleProtocolConnectionManager.NAME);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/connection/SingleProtocolConnectionManager.java | dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/connection/SingleProtocolConnectionManager.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.connection;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Consumer;
public class SingleProtocolConnectionManager implements ConnectionManager {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(SingleProtocolConnectionManager.class);
public static final String NAME = "single";
private final ConcurrentMap<String, AbstractConnectionClient> connections = new ConcurrentHashMap<>(16);
private FrameworkModel frameworkModel;
public SingleProtocolConnectionManager(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
@Override
public AbstractConnectionClient connect(URL url, ChannelHandler handler) {
if (url == null) {
throw new IllegalArgumentException("url == null");
}
return connections.compute(url.getAddress(), (address, conn) -> {
String transport = url.getParameter(Constants.TRANSPORTER_KEY, "netty4");
if (conn == null) {
return createAbstractConnectionClient(url, handler, address, transport);
} else {
boolean shouldReuse = conn.retain();
if (!shouldReuse) {
logger.info("Trying to create a new connection for {}.", address);
return createAbstractConnectionClient(url, handler, address, transport);
}
return conn;
}
});
}
private AbstractConnectionClient createAbstractConnectionClient(
URL url, ChannelHandler handler, String address, String transport) {
ConnectionManager manager =
frameworkModel.getExtensionLoader(ConnectionManager.class).getExtension(transport);
final AbstractConnectionClient connectionClient = manager.connect(url, handler);
connectionClient.addCloseListener(() -> {
logger.info(
"Remove closed connection (with reference count==0) for address {}, a new one will be created for upcoming RPC requests routing to this address.",
address);
connections.remove(address, connectionClient);
});
return connectionClient;
}
@Override
public void forEachConnection(Consumer<AbstractConnectionClient> connectionConsumer) {
connections.values().forEach(connectionConsumer);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/connection/ConnectionManager.java | dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/connection/ConnectionManager.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.connection;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.remoting.ChannelHandler;
import java.util.function.Consumer;
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface ConnectionManager {
AbstractConnectionClient connect(URL url, ChannelHandler handler);
void forEachConnection(Consumer<AbstractConnectionClient> connectionConsumer);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/ssl/ContextOperator.java | dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/ssl/ContextOperator.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.ssl;
public interface ContextOperator {
Object buildContext();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ExceedPayloadLimitException.java | 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);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractEndpoint.java | dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractEndpoint.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.Resetable;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.Codec;
import org.apache.dubbo.remoting.Codec2;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.remoting.transport.codec.CodecAdapter;
import org.apache.dubbo.rpc.model.FrameworkModel;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR;
import static org.apache.dubbo.rpc.model.ScopeModelUtil.getFrameworkModel;
public abstract class AbstractEndpoint extends AbstractPeer implements Resetable {
protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
private Codec2 codec;
private int connectTimeout;
public AbstractEndpoint(URL url, ChannelHandler handler) {
super(url, handler);
this.codec = getChannelCodec(url);
this.connectTimeout =
url.getPositiveParameter(Constants.CONNECT_TIMEOUT_KEY, Constants.DEFAULT_CONNECT_TIMEOUT);
}
protected AbstractEndpoint() {}
protected static Codec2 getChannelCodec(URL url) {
String codecName = url.getParameter(Constants.CODEC_KEY);
if (StringUtils.isEmpty(codecName)) {
// codec extension name must stay the same with protocol name
codecName = url.getProtocol();
}
FrameworkModel frameworkModel = getFrameworkModel(url.getScopeModel());
if (frameworkModel.getExtensionLoader(Codec2.class).hasExtension(codecName)) {
return frameworkModel.getExtensionLoader(Codec2.class).getExtension(codecName);
} else if (frameworkModel.getExtensionLoader(Codec.class).hasExtension(codecName)) {
return new CodecAdapter(
frameworkModel.getExtensionLoader(Codec.class).getExtension(codecName));
} else {
return frameworkModel.getExtensionLoader(Codec2.class).getExtension("default");
}
}
@Override
public void reset(URL url) {
if (isClosed()) {
throw new IllegalStateException(
"Failed to reset parameters " + url + ", cause: Channel closed. channel: " + getLocalAddress());
}
try {
if (url.hasParameter(Constants.CONNECT_TIMEOUT_KEY)) {
int t = url.getParameter(Constants.CONNECT_TIMEOUT_KEY, 0);
if (t > 0) {
this.connectTimeout = t;
}
}
} catch (Throwable t) {
logger.error(INTERNAL_ERROR, "", "", t.getMessage(), t);
}
try {
if (url.hasParameter(Constants.CODEC_KEY)) {
this.codec = getChannelCodec(url);
}
} catch (Throwable t) {
logger.error(INTERNAL_ERROR, "unknown error in remoting module", "", t.getMessage(), t);
}
}
@Deprecated
public void reset(org.apache.dubbo.common.Parameters parameters) {
reset(getUrl().addParameters(parameters.getParameters()));
}
protected Codec2 getCodec() {
return codec;
}
protected int getConnectTimeout() {
return connectTimeout;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ChannelHandlerDispatcher.java | 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);
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/DecodeHandler.java | 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);
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/CodecSupport.java | dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/CodecSupport.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.extension.ExtensionLoader;
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.ConcurrentHashMapUtils;
import org.apache.dubbo.remoting.utils.UrlUtils;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_SERIALIZATION;
public class CodecSupport {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(CodecSupport.class);
private static Map<Byte, Serialization> ID_SERIALIZATION_MAP = new HashMap<>();
private static Map<Byte, String> ID_SERIALIZATIONNAME_MAP = new HashMap<>();
private static Map<String, Byte> SERIALIZATIONNAME_ID_MAP = new HashMap<>();
// Cache null object serialize results, for heartbeat request/response serialize use.
private static ConcurrentMap<Byte, byte[]> ID_NULLBYTES_MAP = new ConcurrentHashMap<>();
private static final ThreadLocal<byte[]> TL_BUFFER = ThreadLocal.withInitial(() -> new byte[1024]);
static {
ExtensionLoader<Serialization> extensionLoader =
FrameworkModel.defaultModel().getExtensionLoader(Serialization.class);
Set<String> supportedExtensions = extensionLoader.getSupportedExtensions();
for (String name : supportedExtensions) {
Serialization serialization = extensionLoader.getExtension(name);
byte idByte = serialization.getContentTypeId();
if (ID_SERIALIZATION_MAP.containsKey(idByte)) {
logger.error(
TRANSPORT_FAILED_SERIALIZATION,
"",
"",
"Serialization extension " + serialization.getClass().getName()
+ " has duplicate id to Serialization extension "
+ ID_SERIALIZATION_MAP.get(idByte).getClass().getName()
+ ", ignore this Serialization extension");
continue;
}
ID_SERIALIZATION_MAP.put(idByte, serialization);
ID_SERIALIZATIONNAME_MAP.put(idByte, name);
SERIALIZATIONNAME_ID_MAP.put(name, idByte);
}
}
private CodecSupport() {}
public static Serialization getSerializationById(Byte id) {
return ID_SERIALIZATION_MAP.get(id);
}
public static Byte getIDByName(String name) {
return SERIALIZATIONNAME_ID_MAP.get(name);
}
public static Serialization getSerialization(URL url) {
return url.getOrDefaultFrameworkModel()
.getExtensionLoader(Serialization.class)
.getExtension(UrlUtils.serializationOrDefault(url));
}
public static Serialization getSerialization(Byte id) throws IOException {
Serialization result = getSerializationById(id);
if (result == null) {
throw new IOException("Unrecognized serialize type from consumer: " + id);
}
return result;
}
public static ObjectInput deserialize(URL url, InputStream is, byte proto) throws IOException {
Serialization s = getSerialization(proto);
return s.deserialize(url, is);
}
/**
* Get the null object serialize result byte[] of Serialization from the cache,
* if not, generate it first.
*
* @param s Serialization Instances
* @return serialize result of null object
*/
public static byte[] getNullBytesOf(Serialization s) {
return ConcurrentHashMapUtils.computeIfAbsent(ID_NULLBYTES_MAP, s.getContentTypeId(), k -> {
// Pre-generated Null object bytes
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] nullBytes = new byte[0];
try {
ObjectOutput out = s.serialize(null, baos);
out.writeObject(null);
out.flushBuffer();
nullBytes = baos.toByteArray();
baos.close();
} catch (Exception e) {
logger.warn(
TRANSPORT_FAILED_SERIALIZATION,
"",
"",
"Serialization extension " + s.getClass().getName()
+ " not support serializing null object, return an empty bytes instead.");
}
return nullBytes;
});
}
/**
* Read all payload to byte[]
*
* @param is
* @return
* @throws IOException
*/
public static byte[] getPayload(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = getBuffer(is.available());
int len;
while ((len = is.read(buffer)) > -1) {
baos.write(buffer, 0, len);
}
baos.flush();
return baos.toByteArray();
}
private static byte[] getBuffer(int size) {
byte[] bytes = TL_BUFFER.get();
if (size <= bytes.length) {
return bytes;
}
return new byte[size];
}
/**
* Check if payload is null object serialize result byte[] of serialization
*
* @param payload
* @param proto
* @return
*/
public static boolean isHeartBeat(byte[] payload, byte proto) {
return Arrays.equals(payload, getNullBytesOf(getSerializationById(proto)));
}
public static void checkSerialization(String requestSerializeName, URL url) throws IOException {
Collection<String> all = UrlUtils.allSerializations(url);
checkSerialization(requestSerializeName, all);
}
public static void checkSerialization(String requestSerializeName, Collection<String> allSerializeName)
throws IOException {
for (String serialization : allSerializeName) {
if (serialization.equals(requestSerializeName)) {
return;
}
}
throw new IOException("Unexpected serialization type:" + requestSerializeName
+ " received from network, please check if the peer send the right id.");
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractClient.java | 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.threadpool.manager.ExecutorRepository;
import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository;
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 org.apache.dubbo.rpc.model.FrameworkModel;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
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;
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.utils.UrlUtils.getIdleTimeout;
public abstract class AbstractClient extends AbstractEndpoint implements Client {
private Lock connectLock;
private final boolean needReconnect;
private final FrameworkModel frameworkModel;
protected volatile ExecutorService executor;
protected volatile ScheduledExecutorService connectivityExecutor;
protected long reconnectDuration;
public AbstractClient(URL url, ChannelHandler handler) throws RemotingException {
super(url, handler);
// initialize connectLock before calling connect()
connectLock = new ReentrantLock();
// set default needReconnect true when channel is not connected
needReconnect = url.getParameter(Constants.SEND_RECONNECT_KEY, true);
frameworkModel = url.getOrDefaultFrameworkModel();
initExecutor(url);
reconnectDuration = getReconnectDuration(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);
}
}
protected AbstractClient() {
needReconnect = false;
frameworkModel = null;
}
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);
connectivityExecutor = frameworkModel
.getBeanFactory()
.getBean(FrameworkExecutorRepository.class)
.getConnectivityScheduledExecutor();
}
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();
}
}
private long getReconnectDuration(URL url) {
int idleTimeout = getIdleTimeout(url);
long heartbeatTimeoutTick = calculateLeastDuration(idleTimeout);
return calculateReconnectDuration(url, heartbeatTimeoutTick);
}
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);
}
@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.
*/
protected abstract void doOpen() throws Throwable;
/**
* Close client.
*/
protected abstract void doClose() throws Throwable;
/**
* Connect to server.
*/
protected abstract void doConnect() throws Throwable;
/**
* disConnect to server.
*/
protected abstract void doDisConnect() throws Throwable;
/**
* Get the connected channel.
*/
protected abstract Channel getChannel();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/MultiMessageHandler.java | 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);
}
@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);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractChannelHandlerDelegate.java | 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);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ServerDelegate.java | 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();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ChannelDelegate.java | 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;
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();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractCodec.java | 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;
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);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ChannelHandlerAdapter.java | dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ChannelHandlerAdapter.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;
/**
* ChannelHandlerAdapter.
*/
public class ChannelHandlerAdapter implements ChannelHandler {
@Override
public void connected(Channel channel) throws RemotingException {}
@Override
public void disconnected(Channel channel) throws RemotingException {}
@Override
public void sent(Channel channel, Object message) throws RemotingException {}
@Override
public void received(Channel channel, Object message) throws RemotingException {}
@Override
public void caught(Channel channel, Throwable exception) throws RemotingException {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractChannel.java | 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;
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);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractPeer.java | 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;
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;
}
protected AbstractPeer() {
handler = null;
}
@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);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ChannelHandlerDelegate.java | 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();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractServer.java | 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.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;
public abstract class AbstractServer extends AbstractEndpoint implements RemotingServer {
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("[SERVICE_PUBLISH][METADATA_REGISTER] 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.info(
"All clients has disconnected from " + ch.getLocalAddress() + ". You can graceful shutdown now.");
}
super.disconnected(ch);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ClientDelegate.java | 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;
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();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/codec/TransportCodec.java | dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/codec/TransportCodec.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.codec;
import org.apache.dubbo.common.serialize.Cleanable;
import org.apache.dubbo.common.serialize.ObjectInput;
import org.apache.dubbo.common.serialize.ObjectOutput;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.Channel;
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.transport.AbstractCodec;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Subclasses {@link org.apache.dubbo.remoting.telnet.codec.TelnetCodec} and {@link org.apache.dubbo.remoting.exchange.codec.ExchangeCodec}
* both override all the methods declared in this class.
*/
@Deprecated
public class TransportCodec extends AbstractCodec {
@Override
public void encode(Channel channel, ChannelBuffer buffer, Object message) throws IOException {
OutputStream output = new ChannelBufferOutputStream(buffer);
ObjectOutput objectOutput = getSerialization(channel).serialize(channel.getUrl(), output);
encodeData(channel, objectOutput, message);
objectOutput.flushBuffer();
if (objectOutput instanceof Cleanable) {
((Cleanable) objectOutput).cleanup();
}
}
@Override
public Object decode(Channel channel, ChannelBuffer buffer) throws IOException {
InputStream input = new ChannelBufferInputStream(buffer);
ObjectInput objectInput = getSerialization(channel).deserialize(channel.getUrl(), input);
Object object = decodeData(channel, objectInput);
if (objectInput instanceof Cleanable) {
((Cleanable) objectInput).cleanup();
}
return object;
}
protected void encodeData(Channel channel, ObjectOutput output, Object message) throws IOException {
encodeData(output, message);
}
protected Object decodeData(Channel channel, ObjectInput input) throws IOException {
return decodeData(input);
}
protected void encodeData(ObjectOutput output, Object message) throws IOException {
output.writeObject(message);
}
protected Object decodeData(ObjectInput input) throws IOException {
try {
return input.readObject();
} catch (ClassNotFoundException e) {
throw new IOException("ClassNotFoundException: " + StringUtils.toString(e));
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.