index
int64 0
0
| repo_id
stringlengths 9
205
| file_path
stringlengths 31
246
| content
stringlengths 1
12.2M
| __index_level_0__
int64 0
10k
|
---|---|---|---|---|
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
|
Create_ds/dubbo/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<Byte, Serialization>();
private static Map<Byte, String> ID_SERIALIZATIONNAME_MAP = new HashMap<Byte, String>();
private static Map<String, Byte> SERIALIZATIONNAME_ID_MAP = new HashMap<String, Byte>();
// 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.");
}
}
| 7,500 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/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;
/**
* AbstractEndpoint
*/
public abstract class AbstractEndpoint extends AbstractPeer implements Resetable {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractEndpoint.class);
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 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;
}
}
| 7,501 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/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 {}
}
| 7,502 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/codec/CodecAdapter.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.codec;
import org.apache.dubbo.common.io.UnsafeByteArrayInputStream;
import org.apache.dubbo.common.io.UnsafeByteArrayOutputStream;
import org.apache.dubbo.common.utils.Assert;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.Codec;
import org.apache.dubbo.remoting.Codec2;
import org.apache.dubbo.remoting.buffer.ChannelBuffer;
import java.io.IOException;
public class CodecAdapter implements Codec2 {
private Codec codec;
public CodecAdapter(Codec codec) {
Assert.notNull(codec, "codec == null");
this.codec = codec;
}
@Override
public void encode(Channel channel, ChannelBuffer buffer, Object message) throws IOException {
UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream(1024);
codec.encode(channel, os, message);
buffer.writeBytes(os.toByteArray());
}
@Override
public Object decode(Channel channel, ChannelBuffer buffer) throws IOException {
byte[] bytes = new byte[buffer.readableBytes()];
int savedReaderIndex = buffer.readerIndex();
buffer.readBytes(bytes);
UnsafeByteArrayInputStream is = new UnsafeByteArrayInputStream(bytes);
Object result = codec.decode(channel, is);
buffer.readerIndex(savedReaderIndex + is.position());
return result == Codec.NEED_MORE_INPUT ? DecodeResult.NEED_MORE_INPUT : result;
}
public Codec getCodec() {
return codec;
}
}
| 7,503 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/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));
}
}
}
| 7,504 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/ChannelEventRunnable.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.dispatcher;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.threadlocal.InternalThreadLocalMap;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.ChannelHandler;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR;
public class ChannelEventRunnable implements Runnable {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(ChannelEventRunnable.class);
private final ChannelHandler handler;
private final Channel channel;
private final ChannelState state;
private final Throwable exception;
private final Object message;
public ChannelEventRunnable(Channel channel, ChannelHandler handler, ChannelState state) {
this(channel, handler, state, null);
}
public ChannelEventRunnable(Channel channel, ChannelHandler handler, ChannelState state, Object message) {
this(channel, handler, state, message, null);
}
public ChannelEventRunnable(Channel channel, ChannelHandler handler, ChannelState state, Throwable t) {
this(channel, handler, state, null, t);
}
public ChannelEventRunnable(
Channel channel, ChannelHandler handler, ChannelState state, Object message, Throwable exception) {
this.channel = channel;
this.handler = handler;
this.state = state;
this.message = message;
this.exception = exception;
}
@Override
public void run() {
InternalThreadLocalMap internalThreadLocalMap = InternalThreadLocalMap.getAndRemove();
try {
if (state == ChannelState.RECEIVED) {
try {
handler.received(channel, message);
} catch (Exception e) {
logger.warn(
INTERNAL_ERROR,
"unknown error in remoting module",
"",
"ChannelEventRunnable handle " + state + " operation error, channel is " + channel
+ ", message is " + message,
e);
}
} else {
switch (state) {
case CONNECTED:
try {
handler.connected(channel);
} catch (Exception e) {
logger.warn(
INTERNAL_ERROR,
"unknown error in remoting module",
"",
"ChannelEventRunnable handle " + state + " operation error, channel is " + channel,
e);
}
break;
case DISCONNECTED:
try {
handler.disconnected(channel);
} catch (Exception e) {
logger.warn(
INTERNAL_ERROR,
"unknown error in remoting module",
"",
"ChannelEventRunnable handle " + state + " operation error, channel is " + channel,
e);
}
break;
case SENT:
try {
handler.sent(channel, message);
} catch (Exception e) {
logger.warn(
INTERNAL_ERROR,
"unknown error in remoting module",
"",
"ChannelEventRunnable handle " + state + " operation error, channel is " + channel
+ ", message is " + message,
e);
}
break;
case CAUGHT:
try {
handler.caught(channel, exception);
} catch (Exception e) {
logger.warn(
INTERNAL_ERROR,
"unknown error in remoting module",
"",
"ChannelEventRunnable handle " + state + " operation error, channel is " + channel
+ ", message is: " + message + ", exception is " + exception,
e);
}
break;
default:
logger.warn(
INTERNAL_ERROR,
"unknown error in remoting module",
"",
"unknown state: " + state + ", message is " + message);
}
}
} finally {
InternalThreadLocalMap.set(internalThreadLocalMap);
}
}
/**
* ChannelState
*/
public enum ChannelState {
/**
* CONNECTED
*/
CONNECTED,
/**
* DISCONNECTED
*/
DISCONNECTED,
/**
* SENT
*/
SENT,
/**
* RECEIVED
*/
RECEIVED,
/**
* CAUGHT
*/
CAUGHT
}
}
| 7,505 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/WrappedChannelHandler.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.dispatcher;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.resource.GlobalResourcesRepository;
import org.apache.dubbo.common.threadpool.manager.ExecutorRepository;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.exchange.Request;
import org.apache.dubbo.remoting.exchange.Response;
import org.apache.dubbo.remoting.exchange.support.DefaultFuture;
import org.apache.dubbo.remoting.transport.ChannelHandlerDelegate;
import org.apache.dubbo.rpc.executor.ExecutorSupport;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
public class WrappedChannelHandler implements ChannelHandlerDelegate {
protected static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(WrappedChannelHandler.class);
protected final ChannelHandler handler;
protected final URL url;
protected final ExecutorSupport executorSupport;
public WrappedChannelHandler(ChannelHandler handler, URL url) {
this.handler = handler;
this.url = url;
this.executorSupport = ExecutorRepository.getInstance(url.getOrDefaultApplicationModel())
.getExecutorSupport(url);
}
public void close() {}
@Override
public void connected(Channel channel) throws RemotingException {
handler.connected(channel);
}
@Override
public void disconnected(Channel channel) throws RemotingException {
handler.disconnected(channel);
}
@Override
public void sent(Channel channel, Object message) throws RemotingException {
handler.sent(channel, message);
}
@Override
public void received(Channel channel, Object message) throws RemotingException {
handler.received(channel, message);
}
@Override
public void caught(Channel channel, Throwable exception) throws RemotingException {
handler.caught(channel, exception);
}
protected void sendFeedback(Channel channel, Request request, Throwable t) throws RemotingException {
if (!request.isTwoWay()) {
return;
}
String msg = "Server side(" + url.getIp() + "," + url.getPort() + ") thread pool is exhausted, detail msg:"
+ t.getMessage();
Response response = new Response(request.getId(), request.getVersion());
response.setStatus(Response.SERVER_THREADPOOL_EXHAUSTED_ERROR);
response.setErrorMessage(msg);
channel.send(response);
}
@Override
public ChannelHandler getHandler() {
if (handler instanceof ChannelHandlerDelegate) {
return ((ChannelHandlerDelegate) handler).getHandler();
} else {
return handler;
}
}
public URL getUrl() {
return url;
}
/**
* Currently, this method is mainly customized to facilitate the thread model on consumer side.
* 1. Use ThreadlessExecutor, aka., delegate callback directly to the thread initiating the call.
* 2. Use shared executor to execute the callback.
*
* @param msg
* @return
*/
public ExecutorService getPreferredExecutorService(Object msg) {
if (msg instanceof Response) {
Response response = (Response) msg;
DefaultFuture responseFuture = DefaultFuture.getFuture(response.getId());
// a typical scenario is the response returned after timeout, the timeout response may have completed the
// future
if (responseFuture == null) {
return getSharedExecutorService();
} else {
ExecutorService executor = responseFuture.getExecutor();
if (executor == null || executor.isShutdown()) {
executor = getSharedExecutorService(msg);
}
return executor;
}
} else {
return getSharedExecutorService(msg);
}
}
/**
* @param msg msg is the network message body, executorSupport.getExecutor needs it, and gets important information from it to get executor
* @return
*/
public ExecutorService getSharedExecutorService(Object msg) {
Executor executor = executorSupport.getExecutor(msg);
return executor != null ? (ExecutorService) executor : getSharedExecutorService();
}
/**
* get the shared executor for current Server or Client
*
* @return
*/
public ExecutorService getSharedExecutorService() {
// Application may be destroyed before channel disconnected, avoid create new application model
// see https://github.com/apache/dubbo/issues/9127
if (url.getApplicationModel() == null || url.getApplicationModel().isDestroyed()) {
return GlobalResourcesRepository.getGlobalExecutorService();
}
// note: url.getOrDefaultApplicationModel() may create new application model
ApplicationModel applicationModel = url.getOrDefaultApplicationModel();
ExecutorRepository executorRepository = ExecutorRepository.getInstance(applicationModel);
ExecutorService executor = executorRepository.getExecutor(url);
if (executor == null) {
executor = executorRepository.createExecutorIfAbsent(url);
}
return executor;
}
@Deprecated
public ExecutorService getExecutorService() {
return getSharedExecutorService();
}
}
| 7,506 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/ChannelHandlers.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.dispatcher;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.Dispatcher;
import org.apache.dubbo.remoting.exchange.support.header.HeartbeatHandler;
import org.apache.dubbo.remoting.transport.MultiMessageHandler;
public class ChannelHandlers {
private static ChannelHandlers INSTANCE = new ChannelHandlers();
protected ChannelHandlers() {}
public static ChannelHandler wrap(ChannelHandler handler, URL url) {
return ChannelHandlers.getInstance().wrapInternal(handler, url);
}
public static ChannelHandlers getInstance() {
return INSTANCE;
}
static void setTestingChannelHandlers(ChannelHandlers instance) {
INSTANCE = instance;
}
protected ChannelHandler wrapInternal(ChannelHandler handler, URL url) {
return new MultiMessageHandler(new HeartbeatHandler(url.getOrDefaultFrameworkModel()
.getExtensionLoader(Dispatcher.class)
.getAdaptiveExtension()
.dispatch(handler, url)));
}
}
| 7,507 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/direct/DirectChannelHandler.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.dispatcher.direct;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.threadpool.ThreadlessExecutor;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.ExecutionException;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.transport.dispatcher.ChannelEventRunnable;
import org.apache.dubbo.remoting.transport.dispatcher.ChannelEventRunnable.ChannelState;
import org.apache.dubbo.remoting.transport.dispatcher.WrappedChannelHandler;
import java.util.concurrent.ExecutorService;
public class DirectChannelHandler extends WrappedChannelHandler {
public DirectChannelHandler(ChannelHandler handler, URL url) {
super(handler, url);
}
@Override
public void received(Channel channel, Object message) throws RemotingException {
ExecutorService executor = getPreferredExecutorService(message);
if (executor instanceof ThreadlessExecutor) {
try {
executor.execute(new ChannelEventRunnable(channel, handler, ChannelState.RECEIVED, message));
} catch (Throwable t) {
throw new ExecutionException(message, channel, getClass() + " error when process received event .", t);
}
} else {
handler.received(channel, message);
}
}
}
| 7,508 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/direct/DirectDispatcher.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.dispatcher.direct;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.Dispatcher;
/**
* Direct dispatcher
*/
public class DirectDispatcher implements Dispatcher {
public static final String NAME = "direct";
@Override
public ChannelHandler dispatch(ChannelHandler handler, URL url) {
return new DirectChannelHandler(handler, url);
}
}
| 7,509 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedDispatcher.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.dispatcher.connection;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.Dispatcher;
/**
* connect disconnect ensure the order
*/
public class ConnectionOrderedDispatcher implements Dispatcher {
public static final String NAME = "connection";
@Override
public ChannelHandler dispatch(ChannelHandler handler, URL url) {
return new ConnectionOrderedChannelHandler(handler, url);
}
}
| 7,510 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedChannelHandler.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.dispatcher.connection;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.threadpool.support.AbortPolicyWithReport;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.ExecutionException;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.exchange.Request;
import org.apache.dubbo.remoting.transport.dispatcher.ChannelEventRunnable;
import org.apache.dubbo.remoting.transport.dispatcher.ChannelEventRunnable.ChannelState;
import org.apache.dubbo.remoting.transport.dispatcher.WrappedChannelHandler;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREAD_NAME;
import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_CONNECTION_LIMIT_EXCEED;
import static org.apache.dubbo.remoting.Constants.CONNECT_QUEUE_CAPACITY;
import static org.apache.dubbo.remoting.Constants.CONNECT_QUEUE_WARNING_SIZE;
import static org.apache.dubbo.remoting.Constants.DEFAULT_CONNECT_QUEUE_WARNING_SIZE;
public class ConnectionOrderedChannelHandler extends WrappedChannelHandler {
protected final ThreadPoolExecutor connectionExecutor;
private final int queueWarningLimit;
public ConnectionOrderedChannelHandler(ChannelHandler handler, URL url) {
super(handler, url);
String threadName = url.getParameter(THREAD_NAME_KEY, DEFAULT_THREAD_NAME);
connectionExecutor = new ThreadPoolExecutor(
1,
1,
0L,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(url.getPositiveParameter(CONNECT_QUEUE_CAPACITY, Integer.MAX_VALUE)),
new NamedThreadFactory(threadName, true),
new AbortPolicyWithReport(threadName, url)); // FIXME There's no place to release connectionExecutor!
queueWarningLimit = url.getParameter(CONNECT_QUEUE_WARNING_SIZE, DEFAULT_CONNECT_QUEUE_WARNING_SIZE);
}
@Override
public void connected(Channel channel) throws RemotingException {
try {
checkQueueLength();
connectionExecutor.execute(new ChannelEventRunnable(channel, handler, ChannelState.CONNECTED));
} catch (Throwable t) {
throw new ExecutionException(
"connect event", channel, getClass() + " error when process connected event .", t);
}
}
@Override
public void disconnected(Channel channel) throws RemotingException {
try {
checkQueueLength();
connectionExecutor.execute(new ChannelEventRunnable(channel, handler, ChannelState.DISCONNECTED));
} catch (Throwable t) {
throw new ExecutionException(
"disconnected event", channel, getClass() + " error when process disconnected event .", t);
}
}
@Override
public void received(Channel channel, Object message) throws RemotingException {
ExecutorService executor = getPreferredExecutorService(message);
try {
executor.execute(new ChannelEventRunnable(channel, handler, ChannelState.RECEIVED, message));
} catch (Throwable t) {
if (message instanceof Request && t instanceof RejectedExecutionException) {
sendFeedback(channel, (Request) message, t);
return;
}
throw new ExecutionException(message, channel, getClass() + " error when process received event .", t);
}
}
@Override
public void caught(Channel channel, Throwable exception) throws RemotingException {
ExecutorService executor = getSharedExecutorService();
try {
executor.execute(new ChannelEventRunnable(channel, handler, ChannelState.CAUGHT, exception));
} catch (Throwable t) {
throw new ExecutionException("caught event", channel, getClass() + " error when process caught event .", t);
}
}
private void checkQueueLength() {
if (connectionExecutor.getQueue().size() > queueWarningLimit) {
logger.warn(
TRANSPORT_CONNECTION_LIMIT_EXCEED,
"",
"",
"connectionordered channel handler queue size: "
+ connectionExecutor.getQueue().size() + " exceed the warning limit number :"
+ queueWarningLimit);
}
}
}
| 7,511 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/all/AllChannelHandler.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.dispatcher.all;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.ExecutionException;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.exchange.Request;
import org.apache.dubbo.remoting.transport.dispatcher.ChannelEventRunnable;
import org.apache.dubbo.remoting.transport.dispatcher.ChannelEventRunnable.ChannelState;
import org.apache.dubbo.remoting.transport.dispatcher.WrappedChannelHandler;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
public class AllChannelHandler extends WrappedChannelHandler {
public AllChannelHandler(ChannelHandler handler, URL url) {
super(handler, url);
}
@Override
public void connected(Channel channel) throws RemotingException {
ExecutorService executor = getSharedExecutorService();
try {
executor.execute(new ChannelEventRunnable(channel, handler, ChannelState.CONNECTED));
} catch (Throwable t) {
throw new ExecutionException(
"connect event", channel, getClass() + " error when process connected event .", t);
}
}
@Override
public void disconnected(Channel channel) throws RemotingException {
ExecutorService executor = getSharedExecutorService();
try {
executor.execute(new ChannelEventRunnable(channel, handler, ChannelState.DISCONNECTED));
} catch (Throwable t) {
throw new ExecutionException(
"disconnect event", channel, getClass() + " error when process disconnected event .", t);
}
}
@Override
public void received(Channel channel, Object message) throws RemotingException {
ExecutorService executor = getPreferredExecutorService(message);
try {
executor.execute(new ChannelEventRunnable(channel, handler, ChannelState.RECEIVED, message));
} catch (Throwable t) {
if (message instanceof Request && t instanceof RejectedExecutionException) {
sendFeedback(channel, (Request) message, t);
return;
}
throw new ExecutionException(message, channel, getClass() + " error when process received event .", t);
}
}
@Override
public void caught(Channel channel, Throwable exception) throws RemotingException {
ExecutorService executor = getSharedExecutorService();
try {
executor.execute(new ChannelEventRunnable(channel, handler, ChannelState.CAUGHT, exception));
} catch (Throwable t) {
throw new ExecutionException("caught event", channel, getClass() + " error when process caught event .", t);
}
}
}
| 7,512 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/all/AllDispatcher.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.dispatcher.all;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.Dispatcher;
/**
* default thread pool configure
*/
public class AllDispatcher implements Dispatcher {
public static final String NAME = "all";
@Override
public ChannelHandler dispatch(ChannelHandler handler, URL url) {
return new AllChannelHandler(handler, url);
}
}
| 7,513 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/message/MessageOnlyChannelHandler.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.dispatcher.message;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.ExecutionException;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.exchange.Request;
import org.apache.dubbo.remoting.transport.dispatcher.ChannelEventRunnable;
import org.apache.dubbo.remoting.transport.dispatcher.ChannelEventRunnable.ChannelState;
import org.apache.dubbo.remoting.transport.dispatcher.WrappedChannelHandler;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
public class MessageOnlyChannelHandler extends WrappedChannelHandler {
public MessageOnlyChannelHandler(ChannelHandler handler, URL url) {
super(handler, url);
}
@Override
public void received(Channel channel, Object message) throws RemotingException {
ExecutorService executor = getPreferredExecutorService(message);
try {
executor.execute(new ChannelEventRunnable(channel, handler, ChannelState.RECEIVED, message));
} catch (Throwable t) {
if (message instanceof Request && t instanceof RejectedExecutionException) {
sendFeedback(channel, (Request) message, t);
return;
}
throw new ExecutionException(message, channel, getClass() + " error when process received event .", t);
}
}
}
| 7,514 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/message/MessageOnlyDispatcher.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.dispatcher.message;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.Dispatcher;
/**
* Only message receive uses the thread pool.
*/
public class MessageOnlyDispatcher implements Dispatcher {
public static final String NAME = "message";
@Override
public ChannelHandler dispatch(ChannelHandler handler, URL url) {
return new MessageOnlyChannelHandler(handler, url);
}
}
| 7,515 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/execution/ExecutionDispatcher.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.dispatcher.execution;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.Dispatcher;
/**
* In addition to sending all the use thread pool processing
*/
public class ExecutionDispatcher implements Dispatcher {
public static final String NAME = "execution";
@Override
public ChannelHandler dispatch(ChannelHandler handler, URL url) {
return new ExecutionChannelHandler(handler, url);
}
}
| 7,516 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/execution/ExecutionChannelHandler.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.dispatcher.execution;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.threadpool.ThreadlessExecutor;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.ExecutionException;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.exchange.Request;
import org.apache.dubbo.remoting.transport.dispatcher.ChannelEventRunnable;
import org.apache.dubbo.remoting.transport.dispatcher.ChannelEventRunnable.ChannelState;
import org.apache.dubbo.remoting.transport.dispatcher.WrappedChannelHandler;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
/**
* Only request message will be dispatched to thread pool. Other messages like response, connect, disconnect,
* heartbeat will be directly executed by I/O thread.
*/
public class ExecutionChannelHandler extends WrappedChannelHandler {
public ExecutionChannelHandler(ChannelHandler handler, URL url) {
super(handler, url);
}
@Override
public void received(Channel channel, Object message) throws RemotingException {
ExecutorService executor = getPreferredExecutorService(message);
if (message instanceof Request) {
try {
executor.execute(new ChannelEventRunnable(channel, handler, ChannelState.RECEIVED, message));
} catch (Throwable t) {
// FIXME: when the thread pool is full, SERVER_THREADPOOL_EXHAUSTED_ERROR cannot return properly,
// therefore the consumer side has to wait until gets timeout. This is a temporary solution to prevent
// this scenario from happening, but a better solution should be considered later.
if (t instanceof RejectedExecutionException) {
sendFeedback(channel, (Request) message, t);
}
throw new ExecutionException(message, channel, getClass() + " error when process received event.", t);
}
} else if (executor instanceof ThreadlessExecutor) {
executor.execute(new ChannelEventRunnable(channel, handler, ChannelState.RECEIVED, message));
} else {
handler.received(channel, message);
}
}
}
| 7,517 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/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.serialize.support.DefaultSerializationSelector;
import org.apache.dubbo.common.utils.StringUtils;
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 = System.getProperty(Constants.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 = System.getProperty(Constants.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();
}
}
| 7,518 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/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;
}
}
| 7,519 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/zookeeper/ZookeeperTransporter.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.zookeeper;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.rpc.model.ApplicationModel;
@SPI(scope = ExtensionScope.APPLICATION)
public interface ZookeeperTransporter {
String CURATOR_5 = "curator5";
String CURATOR = "curator";
ZookeeperClient connect(URL url);
void destroy();
static ZookeeperTransporter getExtension(ApplicationModel applicationModel) {
ExtensionLoader<ZookeeperTransporter> extensionLoader =
applicationModel.getExtensionLoader(ZookeeperTransporter.class);
return isHighVersionCurator() ? extensionLoader.getExtension(CURATOR_5) : extensionLoader.getExtension(CURATOR);
}
static boolean isHighVersionCurator() {
try {
Class.forName("org.apache.curator.framework.recipes.cache.CuratorCache");
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
}
| 7,520 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/zookeeper/ZookeeperClient.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.zookeeper;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.ConfigItem;
import java.util.List;
import java.util.concurrent.Executor;
/**
* Common abstraction of Zookeeper client.
*/
public interface ZookeeperClient {
/**
* Create ZNode in Zookeeper.
*
* @param path path to ZNode
* @param ephemeral specify create mode of ZNode creation. true - EPHEMERAL, false - PERSISTENT.
* @param faultTolerant specify fault tolerance of ZNode creation.
* true - ignore exception and recreate if is ephemeral, false - throw exception.
*/
void create(String path, boolean ephemeral, boolean faultTolerant);
/**
* Delete ZNode.
*
* @param path path to ZNode
*/
void delete(String path);
List<String> getChildren(String path);
List<String> addChildListener(String path, ChildListener listener);
/**
* Attach data listener to current Zookeeper client.
*
* @param path directory. All children of path will be listened.
* @param listener The data listener object.
*/
void addDataListener(String path, DataListener listener);
/**
* Attach data listener to current Zookeeper client. The listener will be executed using the given executor.
*
* @param path directory. All children of path will be listened.
* @param listener The data listener object.
* @param executor the executor that will execute the listener.
*/
void addDataListener(String path, DataListener listener, Executor executor);
/**
* Detach data listener.
*
* @param path directory. All listener of children of the path will be detached.
* @param listener The data listener object.
*/
void removeDataListener(String path, DataListener listener);
void removeChildListener(String path, ChildListener listener);
void addStateListener(StateListener listener);
void removeStateListener(StateListener listener);
/**
* Check the Zookeeper client whether connected to server or not.
*
* @return true if connected
*/
boolean isConnected();
/**
* Close connection to Zookeeper server (cluster).
*/
void close();
URL getUrl();
/**
* Create or update ZNode in Zookeeper with content specified.
*
* @param path path to ZNode
* @param content the content of ZNode
* @param ephemeral specify create mode of ZNode creation. true - EPHEMERAL, false - PERSISTENT.
*/
void createOrUpdate(String path, String content, boolean ephemeral);
/**
* CAS version to Create or update ZNode in Zookeeper with content specified.
*
* @param path path to ZNode
* @param content the content of ZNode
* @param ephemeral specify create mode of ZNode creation. true - EPHEMERAL, false - PERSISTENT.
* @param ticket origin content version, if current version is not the specified version, throw exception
*/
void createOrUpdate(String path, String content, boolean ephemeral, Integer ticket);
/**
* Obtain the content of a ZNode.
*
* @param path path to ZNode
* @return content of ZNode
*/
String getContent(String path);
ConfigItem getConfigItem(String path);
boolean checkExists(String path);
}
| 7,521 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/zookeeper/AbstractZookeeperTransporter.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.zookeeper;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.RemotingConstants;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import org.apache.dubbo.common.utils.StringUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
/**
* AbstractZookeeperTransporter is abstract implements of ZookeeperTransporter.
* <p>
* If you want to extend this, implements createZookeeperClient.
*/
public abstract class AbstractZookeeperTransporter implements ZookeeperTransporter {
private static final Logger logger = LoggerFactory.getLogger(ZookeeperTransporter.class);
private final Map<String, ZookeeperClient> zookeeperClientMap = new ConcurrentHashMap<>();
/**
* share connect for registry, metadata, etc..
* <p>
* Make sure the connection is connected.
*
* @param url
* @return
*/
@Override
public ZookeeperClient connect(URL url) {
ZookeeperClient zookeeperClient;
// address format: {[username:password@]address}
List<String> addressList = getURLBackupAddress(url);
// The field define the zookeeper server , including protocol, host, port, username, password
if ((zookeeperClient = fetchAndUpdateZookeeperClientCache(addressList)) != null
&& zookeeperClient.isConnected()) {
logger.info("find valid zookeeper client from the cache for address: " + url);
return zookeeperClient;
}
// avoid creating too many connections, so add lock
synchronized (zookeeperClientMap) {
if ((zookeeperClient = fetchAndUpdateZookeeperClientCache(addressList)) != null
&& zookeeperClient.isConnected()) {
logger.info("find valid zookeeper client from the cache for address: " + url);
return zookeeperClient;
}
zookeeperClient = createZookeeperClient(url);
logger.info("No valid zookeeper client found from cache, therefore create a new client for url. " + url);
writeToClientMap(addressList, zookeeperClient);
}
return zookeeperClient;
}
/**
* @param url the url that will create zookeeper connection .
* The url in AbstractZookeeperTransporter#connect parameter is rewritten by this one.
* such as: zookeeper://127.0.0.1:2181/org.apache.dubbo.remoting.zookeeper.ZookeeperTransporter
* @return
*/
protected abstract ZookeeperClient createZookeeperClient(URL url);
/**
* get the ZookeeperClient from cache, the ZookeeperClient must be connected.
* <p>
* It is not private method for unit test.
*
* @param addressList
* @return
*/
public ZookeeperClient fetchAndUpdateZookeeperClientCache(List<String> addressList) {
ZookeeperClient zookeeperClient = null;
for (String address : addressList) {
if ((zookeeperClient = zookeeperClientMap.get(address)) != null && zookeeperClient.isConnected()) {
break;
}
}
// mapping new backup address
if (zookeeperClient != null && zookeeperClient.isConnected()) {
writeToClientMap(addressList, zookeeperClient);
}
return zookeeperClient;
}
/**
* get all zookeeper urls (such as zookeeper://127.0.0.1:2181?backup=127.0.0.1:8989,127.0.0.1:9999)
*
* @param url such as zookeeper://127.0.0.1:2181?backup=127.0.0.1:8989,127.0.0.1:9999
* @return such as 127.0.0.1:2181,127.0.0.1:8989,127.0.0.1:9999
*/
public List<String> getURLBackupAddress(URL url) {
List<String> addressList = new ArrayList<>();
addressList.add(url.getAddress());
addressList.addAll(url.getParameter(RemotingConstants.BACKUP_KEY, Collections.emptyList()));
String authPrefix = null;
if (StringUtils.isNotEmpty(url.getUsername())) {
StringBuilder buf = new StringBuilder();
buf.append(url.getUsername());
if (StringUtils.isNotEmpty(url.getPassword())) {
buf.append(':');
buf.append(url.getPassword());
}
buf.append('@');
authPrefix = buf.toString();
}
if (StringUtils.isNotEmpty(authPrefix)) {
List<String> authedAddressList = new ArrayList<>(addressList.size());
for (String addr : addressList) {
authedAddressList.add(authPrefix + addr);
}
return authedAddressList;
}
return addressList;
}
/**
* write address-ZookeeperClient relationship to Map
*
* @param addressList
* @param zookeeperClient
*/
void writeToClientMap(List<String> addressList, ZookeeperClient zookeeperClient) {
for (String address : addressList) {
zookeeperClientMap.put(address, zookeeperClient);
}
}
/**
* redefine the url for zookeeper. just keep protocol, username, password, host, port, and individual parameter.
*
* @param url
* @return
*/
URL toClientURL(URL url) {
Map<String, String> parameterMap = new HashMap<>();
// for CuratorZookeeperClient
if (url.getParameter(TIMEOUT_KEY) != null) {
parameterMap.put(TIMEOUT_KEY, url.getParameter(TIMEOUT_KEY));
}
if (url.getParameter(RemotingConstants.BACKUP_KEY) != null) {
parameterMap.put(RemotingConstants.BACKUP_KEY, url.getParameter(RemotingConstants.BACKUP_KEY));
}
return new ServiceConfigURL(
url.getProtocol(),
url.getUsername(),
url.getPassword(),
url.getHost(),
url.getPort(),
ZookeeperTransporter.class.getName(),
parameterMap);
}
/**
* for unit test
*
* @return
*/
public Map<String, ZookeeperClient> getZookeeperClientMap() {
return zookeeperClientMap;
}
@Override
public void destroy() {
// only destroy zk clients here
for (ZookeeperClient client : zookeeperClientMap.values()) {
client.close();
}
zookeeperClientMap.clear();
}
}
| 7,522 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/zookeeper/AbstractZookeeperClient.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.zookeeper;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.ConfigItem;
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.common.utils.ConcurrentHashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.Executor;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ZOOKEEPER_EXCEPTION;
public abstract class AbstractZookeeperClient<TargetDataListener, TargetChildListener> implements ZookeeperClient {
protected static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(AbstractZookeeperClient.class);
// may hang up to wait name resolution up to 10s
protected int DEFAULT_CONNECTION_TIMEOUT_MS = 30 * 1000;
protected int DEFAULT_SESSION_TIMEOUT_MS = 60 * 1000;
private final URL url;
private final Set<StateListener> stateListeners = new CopyOnWriteArraySet<>();
private final ConcurrentMap<String, ConcurrentMap<ChildListener, TargetChildListener>> childListeners =
new ConcurrentHashMap<>();
private final ConcurrentMap<String, ConcurrentMap<DataListener, TargetDataListener>> listeners =
new ConcurrentHashMap<>();
private volatile boolean closed = false;
private final Set<String> persistentExistNodePath = new ConcurrentHashSet<>();
public AbstractZookeeperClient(URL url) {
this.url = url;
}
@Override
public URL getUrl() {
return url;
}
@Override
public void delete(String path) {
// never mind if ephemeral
persistentExistNodePath.remove(path);
deletePath(path);
}
@Override
public void create(String path, boolean ephemeral, boolean faultTolerant) {
if (!ephemeral) {
if (persistentExistNodePath.contains(path)) {
return;
}
if (checkExists(path)) {
persistentExistNodePath.add(path);
return;
}
}
int i = path.lastIndexOf('/');
if (i > 0) {
create(path.substring(0, i), false, true);
}
if (ephemeral) {
createEphemeral(path, faultTolerant);
} else {
createPersistent(path, faultTolerant);
persistentExistNodePath.add(path);
}
}
@Override
public void addStateListener(StateListener listener) {
stateListeners.add(listener);
}
@Override
public void removeStateListener(StateListener listener) {
stateListeners.remove(listener);
}
public Set<StateListener> getSessionListeners() {
return stateListeners;
}
@Override
public List<String> addChildListener(String path, final ChildListener listener) {
ConcurrentMap<ChildListener, TargetChildListener> listeners =
ConcurrentHashMapUtils.computeIfAbsent(childListeners, path, k -> new ConcurrentHashMap<>());
TargetChildListener targetListener =
ConcurrentHashMapUtils.computeIfAbsent(listeners, listener, k -> createTargetChildListener(path, k));
return addTargetChildListener(path, targetListener);
}
@Override
public void addDataListener(String path, DataListener listener) {
this.addDataListener(path, listener, null);
}
@Override
public void addDataListener(String path, DataListener listener, Executor executor) {
ConcurrentMap<DataListener, TargetDataListener> dataListenerMap =
ConcurrentHashMapUtils.computeIfAbsent(listeners, path, k -> new ConcurrentHashMap<>());
TargetDataListener targetListener = ConcurrentHashMapUtils.computeIfAbsent(
dataListenerMap, listener, k -> createTargetDataListener(path, k));
addTargetDataListener(path, targetListener, executor);
}
@Override
public void removeDataListener(String path, DataListener listener) {
ConcurrentMap<DataListener, TargetDataListener> dataListenerMap = listeners.get(path);
if (dataListenerMap != null) {
TargetDataListener targetListener = dataListenerMap.remove(listener);
if (targetListener != null) {
removeTargetDataListener(path, targetListener);
}
}
}
@Override
public void removeChildListener(String path, ChildListener listener) {
ConcurrentMap<ChildListener, TargetChildListener> listeners = childListeners.get(path);
if (listeners != null) {
TargetChildListener targetListener = listeners.remove(listener);
if (targetListener != null) {
removeTargetChildListener(path, targetListener);
}
}
}
protected void stateChanged(int state) {
for (StateListener sessionListener : getSessionListeners()) {
sessionListener.stateChanged(state);
}
}
@Override
public void close() {
if (closed) {
return;
}
closed = true;
try {
doClose();
} catch (Exception e) {
logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", e.getMessage(), e);
}
}
@Override
public void createOrUpdate(String path, String content, boolean ephemeral) {
int i = path.lastIndexOf('/');
if (i > 0) {
create(path.substring(0, i), false, true);
}
if (ephemeral) {
createOrUpdateEphemeral(path, content);
} else {
createOrUpdatePersistent(path, content);
}
}
@Override
public void createOrUpdate(String path, String content, boolean ephemeral, Integer version) {
int i = path.lastIndexOf('/');
if (i > 0) {
create(path.substring(0, i), false, true);
}
if (ephemeral) {
createOrUpdateEphemeral(path, content, version);
} else {
createOrUpdatePersistent(path, content, version);
}
}
@Override
public String getContent(String path) {
if (!checkExists(path)) {
return null;
}
return doGetContent(path);
}
@Override
public ConfigItem getConfigItem(String path) {
return doGetConfigItem(path);
}
protected void doClose() {
// Break circular reference of zk client
stateListeners.clear();
}
protected abstract void createPersistent(String path, boolean faultTolerant);
protected abstract void createEphemeral(String path, boolean faultTolerant);
protected abstract void createPersistent(String path, String data, boolean faultTolerant);
protected abstract void createEphemeral(String path, String data, boolean faultTolerant);
protected abstract void update(String path, String data, int version);
protected abstract void update(String path, String data);
protected abstract void createOrUpdatePersistent(String path, String data);
protected abstract void createOrUpdateEphemeral(String path, String data);
protected abstract void createOrUpdatePersistent(String path, String data, Integer version);
protected abstract void createOrUpdateEphemeral(String path, String data, Integer version);
@Override
public abstract boolean checkExists(String path);
protected abstract TargetChildListener createTargetChildListener(String path, ChildListener listener);
protected abstract List<String> addTargetChildListener(String path, TargetChildListener listener);
protected abstract TargetDataListener createTargetDataListener(String path, DataListener listener);
protected abstract void addTargetDataListener(String path, TargetDataListener listener);
protected abstract void addTargetDataListener(String path, TargetDataListener listener, Executor executor);
protected abstract void removeTargetDataListener(String path, TargetDataListener listener);
protected abstract void removeTargetChildListener(String path, TargetChildListener listener);
protected abstract String doGetContent(String path);
protected abstract ConfigItem doGetConfigItem(String path);
/**
* we invoke the zookeeper client to delete the node
*
* @param path the node path
*/
protected abstract void deletePath(String path);
}
| 7,523 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/zookeeper/EventType.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.zookeeper;
/**
* 2019-02-26
*/
public enum EventType {
None(-1),
NodeCreated(1),
NodeDeleted(2),
NodeDataChanged(3),
NodeChildrenChanged(4),
CONNECTION_SUSPENDED(11),
CONNECTION_RECONNECTED(12),
CONNECTION_LOST(12),
INITIALIZED(10);
private final int intValue; // Integer representation of value
// for sending over wire
EventType(int intValue) {
this.intValue = intValue;
}
public int getIntValue() {
return intValue;
}
}
| 7,524 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/zookeeper/DataListener.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.zookeeper;
/**
* 2019-02-26
*/
public interface DataListener {
void dataChanged(String path, Object value, EventType eventType);
}
| 7,525 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/zookeeper/ChildListener.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.zookeeper;
import java.util.List;
public interface ChildListener {
void childChanged(String path, List<String> children);
}
| 7,526 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/zookeeper/StateListener.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.zookeeper;
public interface StateListener {
int SESSION_LOST = 0;
int CONNECTED = 1;
int RECONNECTED = 2;
int SUSPENDED = 3;
int NEW_SESSION_CREATED = 4;
void stateChanged(int connected);
}
| 7,527 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/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();
}
| 7,528 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/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() {}
}
| 7,529 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/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;
/**
* Determine incoming bytes belong to the specific protocol.
*
*/
public interface ProtocolDetector {
Result detect(ChannelBuffer in);
enum Result {
RECOGNIZED,
UNRECOGNIZED,
NEED_MORE_DATA
}
}
| 7,530 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api
|
Create_ds/dubbo/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();
}
| 7,531 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api
|
Create_ds/dubbo/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.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 {
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) -> {
if (conn == null) {
String transport = url.getParameter(Constants.TRANSPORTER_KEY, "netty4");
ConnectionManager manager = frameworkModel
.getExtensionLoader(ConnectionManager.class)
.getExtension(transport);
final AbstractConnectionClient connectionClient = manager.connect(url, handler);
connectionClient.addCloseListener(() -> connections.remove(address, connectionClient));
return connectionClient;
} else {
conn.retain();
return conn;
}
});
}
@Override
public void forEachConnection(Consumer<AbstractConnectionClient> connectionConsumer) {
connections.values().forEach(connectionConsumer);
}
}
| 7,532 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api
|
Create_ds/dubbo/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);
}
}
| 7,533 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api
|
Create_ds/dubbo/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.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
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 {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(AbstractConnectionClient.class);
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);
}
public final void increase() {
COUNTER_UPDATER.set(this, 1L);
}
/**
* Increments the reference count by 1.
*/
public final AbstractConnectionClient retain() {
long oldCount = COUNTER_UPDATER.getAndIncrement(this);
if (oldCount <= 0) {
COUNTER_UPDATER.getAndDecrement(this);
throw new AssertionError("This instance has been destroyed");
}
return this;
}
/**
* Decreases the reference count by 1 and calls {@link this#destroy} if the reference count reaches 0.
*/
public final boolean release() {
long remainingCount = COUNTER_UPDATER.decrementAndGet(this);
if (remainingCount == 0) {
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();
/**
* create connecting promise.
*/
public abstract void createConnectingPromise();
/**
* add the listener of close connection event.
*
* @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 Object getChannel(Boolean generalizable);
/**
* Get counter
*/
public long getCounter() {
return COUNTER_UPDATER.get(this);
}
}
| 7,534 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api
|
Create_ds/dubbo/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);
}
| 7,535 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api
|
Create_ds/dubbo/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);
}
| 7,536 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api
|
Create_ds/dubbo/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;
}
| 7,537 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api
|
Create_ds/dubbo/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;
}
}
| 7,538 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api
|
Create_ds/dubbo/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.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.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public abstract class AbstractPortUnificationServer extends AbstractServer {
private final List<WireProtocol> protocols;
/*
protocol name --> URL object
wire protocol will get url object to config server pipeline for channel
*/
private final Map<String, URL> supportedUrls = new ConcurrentHashMap<>();
/*
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 final Map<String, ChannelHandler> supportedHandlers = new ConcurrentHashMap<>();
public AbstractPortUnificationServer(URL url, ChannelHandler handler) throws RemotingException {
super(url, handler);
this.protocols = url.getOrDefaultFrameworkModel()
.getExtensionLoader(WireProtocol.class)
.getActivateExtension(url, new String[0]);
}
public List<WireProtocol> getProtocols() {
return protocols;
}
/*
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;
}
}
| 7,539 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api
|
Create_ds/dubbo/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 java.util.List;
public interface ChannelOperator {
void configChannelHandler(List<ChannelHandler> handlerList);
}
| 7,540 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api
|
Create_ds/dubbo/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;
}
}
| 7,541 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api
|
Create_ds/dubbo/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 {}
}
| 7,542 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/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;
/**
* TelnetHandler
*/
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface TelnetHandler {
/**
* telnet.
*
* @param channel
* @param message
*/
String telnet(Channel channel, String message) throws RemotingException;
}
| 7,543 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet
|
Create_ds/dubbo/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.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;
/**
* TelnetCodec
*/
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();
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<String>();
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;
}
}
| 7,544 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet
|
Create_ds/dubbo/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 "";
}
| 7,545 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet
|
Create_ds/dubbo/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;
/**
* TelnetUtils
*/
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 remaing = cell.length();
while (remaing > 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() - remaing, cell.length() - remaing + 1);
remaing--;
}
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();
}
}
| 7,546 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet
|
Create_ds/dubbo/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;
}
}
| 7,547 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support
|
Create_ds/dubbo/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;
/**
* ExitTelnetHandler
*/
@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;
}
}
| 7,548 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support
|
Create_ds/dubbo/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;
/**
* ClearTelnetHandler
*/
@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();
}
}
| 7,549 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support
|
Create_ds/dubbo/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;
/**
* HelpTelnetHandler
*/
@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<String>>();
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>();
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);
}
}
| 7,550 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support
|
Create_ds/dubbo/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;
/**
* StatusTelnetHandler
*/
@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<List<String>>();
Map<String, Status> statuses = new HashMap<String, Status>();
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<String>();
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<String>();
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<String, Status>();
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());
}
}
| 7,551 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support
|
Create_ds/dubbo/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;
/**
* LogTelnetHandler
*/
@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();
}
}
| 7,552 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ChannelBuffers.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.buffer;
import java.nio.ByteBuffer;
public final class ChannelBuffers {
public static final ChannelBuffer EMPTY_BUFFER = new HeapChannelBuffer(0);
public static final int DEFAULT_CAPACITY = 256;
private ChannelBuffers() {}
public static ChannelBuffer dynamicBuffer() {
return dynamicBuffer(DEFAULT_CAPACITY);
}
public static ChannelBuffer dynamicBuffer(int capacity) {
return new DynamicChannelBuffer(capacity);
}
public static ChannelBuffer dynamicBuffer(int capacity, ChannelBufferFactory factory) {
return new DynamicChannelBuffer(capacity, factory);
}
public static ChannelBuffer buffer(int capacity) {
if (capacity < 0) {
throw new IllegalArgumentException("capacity can not be negative");
}
if (capacity == 0) {
return EMPTY_BUFFER;
}
return new HeapChannelBuffer(capacity);
}
public static ChannelBuffer wrappedBuffer(byte[] array, int offset, int length) {
if (array == null) {
throw new NullPointerException("array == null");
}
byte[] dest = new byte[length];
System.arraycopy(array, offset, dest, 0, length);
return wrappedBuffer(dest);
}
public static ChannelBuffer wrappedBuffer(byte[] array) {
if (array == null) {
throw new NullPointerException("array == null");
}
if (array.length == 0) {
return EMPTY_BUFFER;
}
return new HeapChannelBuffer(array);
}
public static ChannelBuffer wrappedBuffer(ByteBuffer buffer) {
if (!buffer.hasRemaining()) {
return EMPTY_BUFFER;
}
if (buffer.hasArray()) {
return wrappedBuffer(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining());
} else {
return new ByteBufferBackedChannelBuffer(buffer);
}
}
public static ChannelBuffer directBuffer(int capacity) {
if (capacity == 0) {
return EMPTY_BUFFER;
}
ChannelBuffer buffer = new ByteBufferBackedChannelBuffer(ByteBuffer.allocateDirect(capacity));
buffer.clear();
return buffer;
}
public static boolean equals(ChannelBuffer bufferA, ChannelBuffer bufferB) {
final int aLen = bufferA.readableBytes();
if (aLen != bufferB.readableBytes()) {
return false;
}
final int byteCount = aLen & 7;
int aIndex = bufferA.readerIndex();
int bIndex = bufferB.readerIndex();
for (int i = byteCount; i > 0; i--) {
if (bufferA.getByte(aIndex) != bufferB.getByte(bIndex)) {
return false;
}
aIndex++;
bIndex++;
}
return true;
}
// prefix
public static boolean prefixEquals(ChannelBuffer bufferA, ChannelBuffer bufferB, int count) {
final int aLen = bufferA.readableBytes();
final int bLen = bufferB.readableBytes();
if (aLen < count || bLen < count) {
return false;
}
int aIndex = bufferA.readerIndex();
int bIndex = bufferB.readerIndex();
for (int i = count; i > 0; i--) {
if (bufferA.getByte(aIndex) != bufferB.getByte(bIndex)) {
return false;
}
aIndex++;
bIndex++;
}
return true;
}
public static int hasCode(ChannelBuffer buffer) {
final int aLen = buffer.readableBytes();
final int byteCount = aLen & 7;
int hashCode = 1;
int arrayIndex = buffer.readerIndex();
for (int i = byteCount; i > 0; i--) {
hashCode = 31 * hashCode + buffer.getByte(arrayIndex++);
}
if (hashCode == 0) {
hashCode = 1;
}
return hashCode;
}
public static int compare(ChannelBuffer bufferA, ChannelBuffer bufferB) {
final int aLen = bufferA.readableBytes();
final int bLen = bufferB.readableBytes();
final int minLength = Math.min(aLen, bLen);
int aIndex = bufferA.readerIndex();
int bIndex = bufferB.readerIndex();
for (int i = minLength; i > 0; i--) {
byte va = bufferA.getByte(aIndex);
byte vb = bufferB.getByte(bIndex);
if (va > vb) {
return 1;
} else if (va < vb) {
return -1;
}
aIndex++;
bIndex++;
}
return aLen - bLen;
}
}
| 7,553 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/HeapChannelBufferFactory.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.buffer;
import java.nio.ByteBuffer;
public class HeapChannelBufferFactory implements ChannelBufferFactory {
private static final HeapChannelBufferFactory INSTANCE = new HeapChannelBufferFactory();
public HeapChannelBufferFactory() {
super();
}
public static ChannelBufferFactory getInstance() {
return INSTANCE;
}
@Override
public ChannelBuffer getBuffer(int capacity) {
return ChannelBuffers.buffer(capacity);
}
@Override
public ChannelBuffer getBuffer(byte[] array, int offset, int length) {
return ChannelBuffers.wrappedBuffer(array, offset, length);
}
@Override
public ChannelBuffer getBuffer(ByteBuffer nioBuffer) {
if (nioBuffer.hasArray()) {
return ChannelBuffers.wrappedBuffer(nioBuffer);
}
ChannelBuffer buf = getBuffer(nioBuffer.remaining());
int pos = nioBuffer.position();
buf.writeBytes(nioBuffer);
nioBuffer.position(pos);
return buf;
}
}
| 7,554 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/DynamicChannelBuffer.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.buffer;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
public class DynamicChannelBuffer extends AbstractChannelBuffer {
private final ChannelBufferFactory factory;
private ChannelBuffer buffer;
public DynamicChannelBuffer(int estimatedLength) {
this(estimatedLength, HeapChannelBufferFactory.getInstance());
}
public DynamicChannelBuffer(int estimatedLength, ChannelBufferFactory factory) {
if (estimatedLength < 0) {
throw new IllegalArgumentException("estimatedLength: " + estimatedLength);
}
if (factory == null) {
throw new NullPointerException("factory");
}
this.factory = factory;
this.buffer = factory.getBuffer(estimatedLength);
}
@Override
public void ensureWritableBytes(int minWritableBytes) {
if (minWritableBytes <= writableBytes()) {
return;
}
int newCapacity = capacity() == 0 ? 1 : capacity();
int minNewCapacity = writerIndex() + minWritableBytes;
while (newCapacity < minNewCapacity) {
newCapacity <<= 1;
}
ChannelBuffer newBuffer = factory().getBuffer(newCapacity);
newBuffer.writeBytes(buffer, 0, writerIndex());
buffer = newBuffer;
}
@Override
public int capacity() {
return buffer.capacity();
}
@Override
public ChannelBuffer copy(int index, int length) {
DynamicChannelBuffer copiedBuffer = new DynamicChannelBuffer(Math.max(length, 64), factory());
copiedBuffer.buffer = buffer.copy(index, length);
copiedBuffer.setIndex(0, length);
return copiedBuffer;
}
@Override
public ChannelBufferFactory factory() {
return factory;
}
@Override
public byte getByte(int index) {
return buffer.getByte(index);
}
@Override
public void getBytes(int index, byte[] dst, int dstIndex, int length) {
buffer.getBytes(index, dst, dstIndex, length);
}
@Override
public void getBytes(int index, ByteBuffer dst) {
buffer.getBytes(index, dst);
}
@Override
public void getBytes(int index, ChannelBuffer dst, int dstIndex, int length) {
buffer.getBytes(index, dst, dstIndex, length);
}
@Override
public void getBytes(int index, OutputStream dst, int length) throws IOException {
buffer.getBytes(index, dst, length);
}
@Override
public boolean isDirect() {
return buffer.isDirect();
}
@Override
public void setByte(int index, int value) {
buffer.setByte(index, value);
}
@Override
public void setBytes(int index, byte[] src, int srcIndex, int length) {
buffer.setBytes(index, src, srcIndex, length);
}
@Override
public void setBytes(int index, ByteBuffer src) {
buffer.setBytes(index, src);
}
@Override
public void setBytes(int index, ChannelBuffer src, int srcIndex, int length) {
buffer.setBytes(index, src, srcIndex, length);
}
@Override
public int setBytes(int index, InputStream src, int length) throws IOException {
return buffer.setBytes(index, src, length);
}
@Override
public ByteBuffer toByteBuffer(int index, int length) {
return buffer.toByteBuffer(index, length);
}
@Override
public void writeByte(int value) {
ensureWritableBytes(1);
super.writeByte(value);
}
@Override
public void writeBytes(byte[] src, int srcIndex, int length) {
ensureWritableBytes(length);
super.writeBytes(src, srcIndex, length);
}
@Override
public void writeBytes(ChannelBuffer src, int srcIndex, int length) {
ensureWritableBytes(length);
super.writeBytes(src, srcIndex, length);
}
@Override
public void writeBytes(ByteBuffer src) {
ensureWritableBytes(src.remaining());
super.writeBytes(src);
}
@Override
public int writeBytes(InputStream in, int length) throws IOException {
ensureWritableBytes(length);
return super.writeBytes(in, length);
}
@Override
public byte[] array() {
return buffer.array();
}
@Override
public boolean hasArray() {
return buffer.hasArray();
}
@Override
public int arrayOffset() {
return buffer.arrayOffset();
}
@Override
public void release() {
buffer.release();
}
}
| 7,555 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/DirectChannelBufferFactory.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.buffer;
import java.nio.ByteBuffer;
public class DirectChannelBufferFactory implements ChannelBufferFactory {
private static final DirectChannelBufferFactory INSTANCE = new DirectChannelBufferFactory();
public DirectChannelBufferFactory() {
super();
}
public static ChannelBufferFactory getInstance() {
return INSTANCE;
}
@Override
public ChannelBuffer getBuffer(int capacity) {
if (capacity < 0) {
throw new IllegalArgumentException("capacity: " + capacity);
}
if (capacity == 0) {
return ChannelBuffers.EMPTY_BUFFER;
}
return ChannelBuffers.directBuffer(capacity);
}
@Override
public ChannelBuffer getBuffer(byte[] array, int offset, int length) {
if (array == null) {
throw new NullPointerException("array");
}
if (offset < 0) {
throw new IndexOutOfBoundsException("offset: " + offset);
}
if (length == 0) {
return ChannelBuffers.EMPTY_BUFFER;
}
if (offset + length > array.length) {
throw new IndexOutOfBoundsException("length: " + length);
}
ChannelBuffer buf = getBuffer(length);
buf.writeBytes(array, offset, length);
return buf;
}
@Override
public ChannelBuffer getBuffer(ByteBuffer nioBuffer) {
if (!nioBuffer.isReadOnly() && nioBuffer.isDirect()) {
return ChannelBuffers.wrappedBuffer(nioBuffer);
}
ChannelBuffer buf = getBuffer(nioBuffer.remaining());
int pos = nioBuffer.position();
buf.writeBytes(nioBuffer);
nioBuffer.position(pos);
return buf;
}
}
| 7,556 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ChannelBufferInputStream.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.buffer;
import java.io.IOException;
import java.io.InputStream;
public class ChannelBufferInputStream extends InputStream {
private final ChannelBuffer buffer;
private final int startIndex;
private final int endIndex;
public ChannelBufferInputStream(ChannelBuffer buffer) {
this(buffer, buffer.readableBytes());
}
public ChannelBufferInputStream(ChannelBuffer buffer, int length) {
if (buffer == null) {
throw new NullPointerException("buffer");
}
if (length < 0) {
throw new IllegalArgumentException("length: " + length);
}
if (length > buffer.readableBytes()) {
throw new IndexOutOfBoundsException();
}
this.buffer = buffer;
startIndex = buffer.readerIndex();
endIndex = startIndex + length;
buffer.markReaderIndex();
}
public int readBytes() {
return buffer.readerIndex() - startIndex;
}
@Override
public int available() throws IOException {
return endIndex - buffer.readerIndex();
}
@Override
public synchronized void mark(int readLimit) {
buffer.markReaderIndex();
}
@Override
public boolean markSupported() {
return true;
}
@Override
public int read() throws IOException {
if (!buffer.readable()) {
return -1;
}
return buffer.readByte() & 0xff;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
int available = available();
if (available == 0) {
return -1;
}
len = Math.min(available, len);
buffer.readBytes(b, off, len);
return len;
}
@Override
public synchronized void reset() throws IOException {
buffer.resetReaderIndex();
}
@Override
public long skip(long n) throws IOException {
if (n > Integer.MAX_VALUE) {
return skipBytes(Integer.MAX_VALUE);
} else {
return skipBytes((int) n);
}
}
private int skipBytes(int n) throws IOException {
int nBytes = Math.min(available(), n);
buffer.skipBytes(nBytes);
return nBytes;
}
}
| 7,557 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/AbstractChannelBuffer.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.buffer;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
public abstract class AbstractChannelBuffer implements ChannelBuffer {
private int readerIndex;
private int writerIndex;
private int markedReaderIndex;
private int markedWriterIndex;
@Override
public int readerIndex() {
return readerIndex;
}
@Override
public void readerIndex(int readerIndex) {
if (readerIndex < 0 || readerIndex > writerIndex) {
throw new IndexOutOfBoundsException();
}
this.readerIndex = readerIndex;
}
@Override
public int writerIndex() {
return writerIndex;
}
@Override
public void writerIndex(int writerIndex) {
if (writerIndex < readerIndex || writerIndex > capacity()) {
throw new IndexOutOfBoundsException();
}
this.writerIndex = writerIndex;
}
@Override
public void setIndex(int readerIndex, int writerIndex) {
if (readerIndex < 0 || readerIndex > writerIndex || writerIndex > capacity()) {
throw new IndexOutOfBoundsException();
}
this.readerIndex = readerIndex;
this.writerIndex = writerIndex;
}
@Override
public void clear() {
readerIndex = writerIndex = 0;
}
@Override
public boolean readable() {
return readableBytes() > 0;
}
@Override
public boolean writable() {
return writableBytes() > 0;
}
@Override
public int readableBytes() {
return writerIndex - readerIndex;
}
@Override
public int writableBytes() {
return capacity() - writerIndex;
}
@Override
public void markReaderIndex() {
markedReaderIndex = readerIndex;
}
@Override
public void resetReaderIndex() {
readerIndex(markedReaderIndex);
}
@Override
public void markWriterIndex() {
markedWriterIndex = writerIndex;
}
@Override
public void resetWriterIndex() {
writerIndex = markedWriterIndex;
}
@Override
public void discardReadBytes() {
if (readerIndex == 0) {
return;
}
setBytes(0, this, readerIndex, writerIndex - readerIndex);
writerIndex -= readerIndex;
markedReaderIndex = Math.max(markedReaderIndex - readerIndex, 0);
markedWriterIndex = Math.max(markedWriterIndex - readerIndex, 0);
readerIndex = 0;
}
@Override
public void ensureWritableBytes(int writableBytes) {
if (writableBytes > writableBytes()) {
throw new IndexOutOfBoundsException();
}
}
@Override
public void getBytes(int index, byte[] dst) {
getBytes(index, dst, 0, dst.length);
}
@Override
public void getBytes(int index, ChannelBuffer dst) {
getBytes(index, dst, dst.writableBytes());
}
@Override
public void getBytes(int index, ChannelBuffer dst, int length) {
if (length > dst.writableBytes()) {
throw new IndexOutOfBoundsException();
}
getBytes(index, dst, dst.writerIndex(), length);
dst.writerIndex(dst.writerIndex() + length);
}
@Override
public void setBytes(int index, byte[] src) {
setBytes(index, src, 0, src.length);
}
@Override
public void setBytes(int index, ChannelBuffer src) {
setBytes(index, src, src.readableBytes());
}
@Override
public void setBytes(int index, ChannelBuffer src, int length) {
if (length > src.readableBytes()) {
throw new IndexOutOfBoundsException();
}
setBytes(index, src, src.readerIndex(), length);
src.readerIndex(src.readerIndex() + length);
}
@Override
public byte readByte() {
if (readerIndex == writerIndex) {
throw new IndexOutOfBoundsException();
}
return getByte(readerIndex++);
}
@Override
public ChannelBuffer readBytes(int length) {
checkReadableBytes(length);
if (length == 0) {
return ChannelBuffers.EMPTY_BUFFER;
}
ChannelBuffer buf = factory().getBuffer(length);
buf.writeBytes(this, readerIndex, length);
readerIndex += length;
return buf;
}
@Override
public void readBytes(byte[] dst, int dstIndex, int length) {
checkReadableBytes(length);
getBytes(readerIndex, dst, dstIndex, length);
readerIndex += length;
}
@Override
public void readBytes(byte[] dst) {
readBytes(dst, 0, dst.length);
}
@Override
public void readBytes(ChannelBuffer dst) {
readBytes(dst, dst.writableBytes());
}
@Override
public void readBytes(ChannelBuffer dst, int length) {
if (length > dst.writableBytes()) {
throw new IndexOutOfBoundsException();
}
readBytes(dst, dst.writerIndex(), length);
dst.writerIndex(dst.writerIndex() + length);
}
@Override
public void readBytes(ChannelBuffer dst, int dstIndex, int length) {
checkReadableBytes(length);
getBytes(readerIndex, dst, dstIndex, length);
readerIndex += length;
}
@Override
public void readBytes(ByteBuffer dst) {
int length = dst.remaining();
checkReadableBytes(length);
getBytes(readerIndex, dst);
readerIndex += length;
}
@Override
public void readBytes(OutputStream out, int length) throws IOException {
checkReadableBytes(length);
getBytes(readerIndex, out, length);
readerIndex += length;
}
@Override
public void skipBytes(int length) {
int newReaderIndex = readerIndex + length;
if (newReaderIndex > writerIndex) {
throw new IndexOutOfBoundsException();
}
readerIndex = newReaderIndex;
}
@Override
public void writeByte(int value) {
setByte(writerIndex++, value);
}
@Override
public void writeBytes(byte[] src, int srcIndex, int length) {
setBytes(writerIndex, src, srcIndex, length);
writerIndex += length;
}
@Override
public void writeBytes(byte[] src) {
writeBytes(src, 0, src.length);
}
@Override
public void writeBytes(ChannelBuffer src) {
writeBytes(src, src.readableBytes());
}
@Override
public void writeBytes(ChannelBuffer src, int length) {
if (length > src.readableBytes()) {
throw new IndexOutOfBoundsException();
}
writeBytes(src, src.readerIndex(), length);
src.readerIndex(src.readerIndex() + length);
}
@Override
public void writeBytes(ChannelBuffer src, int srcIndex, int length) {
setBytes(writerIndex, src, srcIndex, length);
writerIndex += length;
}
@Override
public void writeBytes(ByteBuffer src) {
int length = src.remaining();
setBytes(writerIndex, src);
writerIndex += length;
}
@Override
public int writeBytes(InputStream in, int length) throws IOException {
int writtenBytes = setBytes(writerIndex, in, length);
if (writtenBytes > 0) {
writerIndex += writtenBytes;
}
return writtenBytes;
}
@Override
public ChannelBuffer copy() {
return copy(readerIndex, readableBytes());
}
@Override
public ByteBuffer toByteBuffer() {
return toByteBuffer(readerIndex, readableBytes());
}
@Override
public boolean equals(Object o) {
return o instanceof ChannelBuffer && ChannelBuffers.equals(this, (ChannelBuffer) o);
}
@Override
public int hashCode() {
return ChannelBuffers.hasCode(this);
}
@Override
public int compareTo(ChannelBuffer that) {
return ChannelBuffers.compare(this, that);
}
@Override
public String toString() {
return getClass().getSimpleName() + '(' + "ridx="
+ readerIndex + ", " + "widx="
+ writerIndex + ", " + "cap="
+ capacity() + ')';
}
protected void checkReadableBytes(int minimumReadableBytes) {
if (readableBytes() < minimumReadableBytes) {
throw new IndexOutOfBoundsException();
}
}
}
| 7,558 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ChannelBufferOutputStream.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.buffer;
import java.io.IOException;
import java.io.OutputStream;
public class ChannelBufferOutputStream extends OutputStream {
private final ChannelBuffer buffer;
private final int startIndex;
public ChannelBufferOutputStream(ChannelBuffer buffer) {
if (buffer == null) {
throw new NullPointerException("buffer");
}
this.buffer = buffer;
startIndex = buffer.writerIndex();
}
public int writtenBytes() {
return buffer.writerIndex() - startIndex;
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
if (len == 0) {
return;
}
buffer.writeBytes(b, off, len);
}
@Override
public void write(byte[] b) throws IOException {
buffer.writeBytes(b);
}
@Override
public void write(int b) throws IOException {
buffer.writeByte((byte) b);
}
public ChannelBuffer buffer() {
return buffer;
}
}
| 7,559 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ByteBufferBackedChannelBuffer.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.buffer;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
public class ByteBufferBackedChannelBuffer extends AbstractChannelBuffer {
private final ByteBuffer buffer;
private final int capacity;
public ByteBufferBackedChannelBuffer(ByteBuffer buffer) {
if (buffer == null) {
throw new NullPointerException("buffer");
}
this.buffer = buffer.slice();
capacity = buffer.remaining();
writerIndex(capacity);
}
public ByteBufferBackedChannelBuffer(ByteBufferBackedChannelBuffer buffer) {
this.buffer = buffer.buffer;
capacity = buffer.capacity;
setIndex(buffer.readerIndex(), buffer.writerIndex());
}
@Override
public ChannelBufferFactory factory() {
if (buffer.isDirect()) {
return DirectChannelBufferFactory.getInstance();
} else {
return HeapChannelBufferFactory.getInstance();
}
}
@Override
public int capacity() {
return capacity;
}
@Override
public ChannelBuffer copy(int index, int length) {
ByteBuffer src;
try {
src = (ByteBuffer) buffer.duplicate().position(index).limit(index + length);
} catch (IllegalArgumentException e) {
throw new IndexOutOfBoundsException();
}
ByteBuffer dst = buffer.isDirect() ? ByteBuffer.allocateDirect(length) : ByteBuffer.allocate(length);
dst.put(src);
dst.clear();
return new ByteBufferBackedChannelBuffer(dst);
}
@Override
public byte getByte(int index) {
return buffer.get(index);
}
@Override
public void getBytes(int index, byte[] dst, int dstIndex, int length) {
ByteBuffer data = buffer.duplicate();
try {
data.limit(index + length).position(index);
} catch (IllegalArgumentException e) {
throw new IndexOutOfBoundsException();
}
data.get(dst, dstIndex, length);
}
@Override
public void getBytes(int index, ByteBuffer dst) {
ByteBuffer data = buffer.duplicate();
int bytesToCopy = Math.min(capacity() - index, dst.remaining());
try {
data.limit(index + bytesToCopy).position(index);
} catch (IllegalArgumentException e) {
throw new IndexOutOfBoundsException();
}
dst.put(data);
}
@Override
public void getBytes(int index, ChannelBuffer dst, int dstIndex, int length) {
if (dst instanceof ByteBufferBackedChannelBuffer) {
ByteBufferBackedChannelBuffer bbdst = (ByteBufferBackedChannelBuffer) dst;
ByteBuffer data = bbdst.buffer.duplicate();
data.limit(dstIndex + length).position(dstIndex);
getBytes(index, data);
} else if (buffer.hasArray()) {
dst.setBytes(dstIndex, buffer.array(), index + buffer.arrayOffset(), length);
} else {
dst.setBytes(dstIndex, this, index, length);
}
}
@Override
public void getBytes(int index, OutputStream out, int length) throws IOException {
if (length == 0) {
return;
}
if (buffer.hasArray()) {
out.write(buffer.array(), index + buffer.arrayOffset(), length);
} else {
byte[] tmp = new byte[length];
((ByteBuffer) buffer.duplicate().position(index)).get(tmp);
out.write(tmp);
}
}
@Override
public boolean isDirect() {
return buffer.isDirect();
}
@Override
public void setByte(int index, int value) {
buffer.put(index, (byte) value);
}
@Override
public void setBytes(int index, byte[] src, int srcIndex, int length) {
ByteBuffer data = buffer.duplicate();
data.limit(index + length).position(index);
data.put(src, srcIndex, length);
}
@Override
public void setBytes(int index, ByteBuffer src) {
ByteBuffer data = buffer.duplicate();
data.limit(index + src.remaining()).position(index);
data.put(src);
}
@Override
public void setBytes(int index, ChannelBuffer src, int srcIndex, int length) {
if (src instanceof ByteBufferBackedChannelBuffer) {
ByteBufferBackedChannelBuffer bbsrc = (ByteBufferBackedChannelBuffer) src;
ByteBuffer data = bbsrc.buffer.duplicate();
data.limit(srcIndex + length).position(srcIndex);
setBytes(index, data);
} else if (buffer.hasArray()) {
src.getBytes(srcIndex, buffer.array(), index + buffer.arrayOffset(), length);
} else {
src.getBytes(srcIndex, this, index, length);
}
}
@Override
public ByteBuffer toByteBuffer(int index, int length) {
if (index == 0 && length == capacity()) {
return buffer.duplicate();
} else {
return ((ByteBuffer) buffer.duplicate().position(index).limit(index + length)).slice();
}
}
@Override
public int setBytes(int index, InputStream in, int length) throws IOException {
int readBytes = 0;
if (buffer.hasArray()) {
index += buffer.arrayOffset();
do {
int localReadBytes = in.read(buffer.array(), index, length);
if (localReadBytes < 0) {
if (readBytes == 0) {
return -1;
} else {
break;
}
}
readBytes += localReadBytes;
index += localReadBytes;
length -= localReadBytes;
} while (length > 0);
} else {
byte[] tmp = new byte[length];
int i = 0;
do {
int localReadBytes = in.read(tmp, i, tmp.length - i);
if (localReadBytes < 0) {
if (readBytes == 0) {
return -1;
} else {
break;
}
}
readBytes += localReadBytes;
i += readBytes;
} while (i < tmp.length);
((ByteBuffer) buffer.duplicate().position(index)).put(tmp);
}
return readBytes;
}
@Override
public byte[] array() {
return buffer.array();
}
@Override
public boolean hasArray() {
return buffer.hasArray();
}
@Override
public int arrayOffset() {
return buffer.arrayOffset();
}
}
| 7,560 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ChannelBufferFactory.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.buffer;
import java.nio.ByteBuffer;
public interface ChannelBufferFactory {
ChannelBuffer getBuffer(int capacity);
ChannelBuffer getBuffer(byte[] array, int offset, int length);
ChannelBuffer getBuffer(ByteBuffer nioBuffer);
}
| 7,561 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/HeapChannelBuffer.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.buffer;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.GatheringByteChannel;
import java.nio.channels.ScatteringByteChannel;
public class HeapChannelBuffer extends AbstractChannelBuffer {
/**
* The underlying heap byte array that this buffer is wrapping.
*/
protected final byte[] array;
/**
* Creates a new heap buffer with a newly allocated byte array.
*
* @param length the length of the new byte array
*/
public HeapChannelBuffer(int length) {
this(new byte[length], 0, 0);
}
/**
* Creates a new heap buffer with an existing byte array.
*
* @param array the byte array to wrap
*/
public HeapChannelBuffer(byte[] array) {
this(array, 0, array.length);
}
/**
* Creates a new heap buffer with an existing byte array.
*
* @param array the byte array to wrap
* @param readerIndex the initial reader index of this buffer
* @param writerIndex the initial writer index of this buffer
*/
protected HeapChannelBuffer(byte[] array, int readerIndex, int writerIndex) {
if (array == null) {
throw new NullPointerException("array");
}
this.array = array;
setIndex(readerIndex, writerIndex);
}
@Override
public boolean isDirect() {
return false;
}
@Override
public int capacity() {
return array.length;
}
@Override
public boolean hasArray() {
return true;
}
@Override
public byte[] array() {
return array;
}
@Override
public int arrayOffset() {
return 0;
}
@Override
public byte getByte(int index) {
return array[index];
}
@Override
public void getBytes(int index, ChannelBuffer dst, int dstIndex, int length) {
if (dst instanceof HeapChannelBuffer) {
getBytes(index, ((HeapChannelBuffer) dst).array, dstIndex, length);
} else {
dst.setBytes(dstIndex, array, index, length);
}
}
@Override
public void getBytes(int index, byte[] dst, int dstIndex, int length) {
System.arraycopy(array, index, dst, dstIndex, length);
}
@Override
public void getBytes(int index, ByteBuffer dst) {
dst.put(array, index, Math.min(capacity() - index, dst.remaining()));
}
@Override
public void getBytes(int index, OutputStream out, int length) throws IOException {
out.write(array, index, length);
}
public int getBytes(int index, GatheringByteChannel out, int length) throws IOException {
return out.write(ByteBuffer.wrap(array, index, length));
}
@Override
public void setByte(int index, int value) {
array[index] = (byte) value;
}
@Override
public void setBytes(int index, ChannelBuffer src, int srcIndex, int length) {
if (src instanceof HeapChannelBuffer) {
setBytes(index, ((HeapChannelBuffer) src).array, srcIndex, length);
} else {
src.getBytes(srcIndex, array, index, length);
}
}
@Override
public void setBytes(int index, byte[] src, int srcIndex, int length) {
System.arraycopy(src, srcIndex, array, index, length);
}
@Override
public void setBytes(int index, ByteBuffer src) {
src.get(array, index, src.remaining());
}
@Override
public int setBytes(int index, InputStream in, int length) throws IOException {
int readBytes = 0;
do {
int localReadBytes = in.read(array, index, length);
if (localReadBytes < 0) {
if (readBytes == 0) {
return -1;
} else {
break;
}
}
readBytes += localReadBytes;
index += localReadBytes;
length -= localReadBytes;
} while (length > 0);
return readBytes;
}
public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException {
ByteBuffer buf = ByteBuffer.wrap(array, index, length);
int readBytes = 0;
do {
int localReadBytes;
try {
localReadBytes = in.read(buf);
} catch (ClosedChannelException e) {
localReadBytes = -1;
}
if (localReadBytes < 0) {
if (readBytes == 0) {
return -1;
} else {
break;
}
} else if (localReadBytes == 0) {
break;
}
readBytes += localReadBytes;
} while (readBytes < length);
return readBytes;
}
@Override
public ChannelBuffer copy(int index, int length) {
if (index < 0 || length < 0 || index + length > array.length) {
throw new IndexOutOfBoundsException();
}
byte[] copiedArray = new byte[length];
System.arraycopy(array, index, copiedArray, 0, length);
return new HeapChannelBuffer(copiedArray);
}
@Override
public ChannelBufferFactory factory() {
return HeapChannelBufferFactory.getInstance();
}
@Override
public ByteBuffer toByteBuffer(int index, int length) {
return ByteBuffer.wrap(array, index, length);
}
}
| 7,562 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ChannelBuffer.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.buffer;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
/**
* A random and sequential accessible sequence of zero or more bytes (octets).
* This interface provides an abstract view for one or more primitive byte
* arrays ({@code byte[]}) and {@linkplain ByteBuffer NIO buffers}.
* <p/>
* <h3>Creation of a buffer</h3>
* <p/>
* It is recommended to create a new buffer using the helper methods in {@link
* ChannelBuffers} rather than calling an individual implementation's
* constructor.
* <p/>
* <h3>Random Access Indexing</h3>
* <p/>
* Just like an ordinary primitive byte array, {@link ChannelBuffer} uses <a
* href="http://en.wikipedia.org/wiki/Index_(information_technology)#Array_element_identifier">zero-based
* indexing</a>. It means the index of the first byte is always {@code 0} and
* the index of the last byte is always {@link #capacity() capacity - 1}. For
* example, to iterate all bytes of a buffer, you can do the following,
* regardless of its internal implementation:
* <p/>
* <pre>
* {@link ChannelBuffer} buffer = ...;
* for (int i = 0; i < buffer.capacity(); i ++</strong>) {
* byte b = buffer.getByte(i);
* System.out.println((char) b);
* }
* </pre>
* <p/>
* <h3>Sequential Access Indexing</h3>
* <p/>
* {@link ChannelBuffer} provides two pointer variables to support sequential
* read and write operations - {@link #readerIndex() readerIndex} for a read
* operation and {@link #writerIndex() writerIndex} for a write operation
* respectively. The following diagram shows how a buffer is segmented into
* three areas by the two pointers:
* <p/>
* <pre>
* +-------------------+------------------+------------------+
* | discardable bytes | readable bytes | writable bytes |
* | | (CONTENT) | |
* +-------------------+------------------+------------------+
* | | | |
* 0 <= readerIndex <= writerIndex <= capacity
* </pre>
* <p/>
* <h4>Readable bytes (the actual content)</h4>
* <p/>
* This segment is where the actual data is stored. Any operation whose name
* starts with {@code read} or {@code skip} will get or skip the data at the
* current {@link #readerIndex() readerIndex} and increase it by the number of
* read bytes. If the argument of the read operation is also a {@link
* ChannelBuffer} and no destination index is specified, the specified buffer's
* {@link #readerIndex() readerIndex} is increased together.
* <p/>
* If there's not enough content left, {@link IndexOutOfBoundsException} is
* raised. The default value of newly allocated, wrapped or copied buffer's
* {@link #readerIndex() readerIndex} is {@code 0}.
* <p/>
* <pre>
* // Iterates the readable bytes of a buffer.
* {@link ChannelBuffer} buffer = ...;
* while (buffer.readable()) {
* System.out.println(buffer.readByte());
* }
* </pre>
* <p/>
* <h4>Writable bytes</h4>
* <p/>
* This segment is a undefined space which needs to be filled. Any operation
* whose name ends with {@code write} will write the data at the current {@link
* #writerIndex() writerIndex} and increase it by the number of written bytes.
* If the argument of the write operation is also a {@link ChannelBuffer}, and
* no source index is specified, the specified buffer's {@link #readerIndex()
* readerIndex} is increased together.
* <p/>
* If there's not enough writable bytes left, {@link IndexOutOfBoundsException}
* is raised. The default value of newly allocated buffer's {@link
* #writerIndex() writerIndex} is {@code 0}. The default value of wrapped or
* copied buffer's {@link #writerIndex() writerIndex} is the {@link #capacity()
* capacity} of the buffer.
* <p/>
* <pre>
* // Fills the writable bytes of a buffer with random integers.
* {@link ChannelBuffer} buffer = ...;
* while (buffer.writableBytes() >= 4) {
* buffer.writeInt(random.nextInt());
* }
* </pre>
* <p/>
* <h4>Discardable bytes</h4>
* <p/>
* This segment contains the bytes which were read already by a read operation.
* Initially, the size of this segment is {@code 0}, but its size increases up
* to the {@link #writerIndex() writerIndex} as read operations are executed.
* The read bytes can be discarded by calling {@link #discardReadBytes()} to
* reclaim unused area as depicted by the following diagram:
* <p/>
* <pre>
* BEFORE discardReadBytes()
*
* +-------------------+------------------+------------------+
* | discardable bytes | readable bytes | writable bytes |
* +-------------------+------------------+------------------+
* | | | |
* 0 <= readerIndex <= writerIndex <= capacity
*
*
* AFTER discardReadBytes()
*
* +------------------+--------------------------------------+
* | readable bytes | writable bytes (got more space) |
* +------------------+--------------------------------------+
* | | |
* readerIndex (0) <= writerIndex (decreased) <= capacity
* </pre>
* <p/>
* Please note that there is no guarantee about the content of writable bytes
* after calling {@link #discardReadBytes()}. The writable bytes will not be
* moved in most cases and could even be filled with completely different data
* depending on the underlying buffer implementation.
* <p/>
* <h4>Clearing the buffer indexes</h4>
* <p/>
* You can set both {@link #readerIndex() readerIndex} and {@link #writerIndex()
* writerIndex} to {@code 0} by calling {@link #clear()}. It does not clear the
* buffer content (e.g. filling with {@code 0}) but just clears the two
* pointers. Please also note that the semantic of this operation is different
* from {@link ByteBuffer#clear()}.
* <p/>
* <pre>
* BEFORE clear()
*
* +-------------------+------------------+------------------+
* | discardable bytes | readable bytes | writable bytes |
* +-------------------+------------------+------------------+
* | | | |
* 0 <= readerIndex <= writerIndex <= capacity
*
*
* AFTER clear()
*
* +---------------------------------------------------------+
* | writable bytes (got more space) |
* +---------------------------------------------------------+
* | |
* 0 = readerIndex = writerIndex <= capacity
* </pre>
* <p/>
* <h3>Mark and reset</h3>
* <p/>
* There are two marker indexes in every buffer. One is for storing {@link
* #readerIndex() readerIndex} and the other is for storing {@link
* #writerIndex() writerIndex}. You can always reposition one of the two
* indexes by calling a reset method. It works in a similar fashion to the mark
* and reset methods in {@link InputStream} except that there's no {@code
* readlimit}.
* <p/>
* <h3>Conversion to existing JDK types</h3>
* <p/>
* <h4>Byte array</h4>
* <p/>
* If a {@link ChannelBuffer} is backed by a byte array (i.e. {@code byte[]}),
* you can access it directly via the {@link #array()} method. To determine if
* a buffer is backed by a byte array, {@link #hasArray()} should be used.
* <p/>
* <h4>NIO Buffers</h4>
* <p/>
* Various {@link #toByteBuffer()} methods convert a {@link ChannelBuffer} into
* one or more NIO buffers. These methods avoid buffer allocation and memory
* copy whenever possible, but there's no guarantee that memory copy will not be
* involved.
* <p/>
* <h4>I/O Streams</h4>
* <p/>
* Please refer to {@link ChannelBufferInputStream} and {@link
* ChannelBufferOutputStream}.
*
*
*/
public interface ChannelBuffer extends Comparable<ChannelBuffer> {
/**
* Returns the number of bytes (octets) this buffer can contain.
*/
int capacity();
/**
* Sets the {@code readerIndex} and {@code writerIndex} of this buffer to
* {@code 0}. This method is identical to {@link #setIndex(int, int)
* setIndex(0, 0)}.
* <p/>
* Please note that the behavior of this method is different from that of
* NIO buffer, which sets the {@code limit} to the {@code capacity} of the
* buffer.
*/
void clear();
/**
* Returns a copy of this buffer's readable bytes. Modifying the content of
* the returned buffer or this buffer does not affect each other at all.
* This method is identical to {@code buf.copy(buf.readerIndex(),
* buf.readableBytes())}. This method does not modify {@code readerIndex} or
* {@code writerIndex} of this buffer.
*/
ChannelBuffer copy();
/**
* Returns a copy of this buffer's sub-region. Modifying the content of the
* returned buffer or this buffer does not affect each other at all. This
* method does not modify {@code readerIndex} or {@code writerIndex} of this
* buffer.
*/
ChannelBuffer copy(int index, int length);
/**
* Discards the bytes between the 0th index and {@code readerIndex}. It
* moves the bytes between {@code readerIndex} and {@code writerIndex} to
* the 0th index, and sets {@code readerIndex} and {@code writerIndex} to
* {@code 0} and {@code oldWriterIndex - oldReaderIndex} respectively.
* <p/>
* Please refer to the class documentation for more detailed explanation.
*/
void discardReadBytes();
/**
* Makes sure the number of {@linkplain #writableBytes() the writable bytes}
* is equal to or greater than the specified value. If there is enough
* writable bytes in this buffer, this method returns with no side effect.
* Otherwise: <ul> <li>a non-dynamic buffer will throw an {@link
* IndexOutOfBoundsException}.</li> <li>a dynamic buffer will expand its
* capacity so that the number of the {@link #writableBytes() writable
* bytes} becomes equal to or greater than the specified value. The
* expansion involves the reallocation of the internal buffer and
* consequently memory copy.</li> </ul>
*
* @param writableBytes the expected minimum number of writable bytes
* @throws IndexOutOfBoundsException if {@linkplain #writableBytes() the
* writable bytes} of this buffer is less
* than the specified value and if this
* buffer is not a dynamic buffer
*/
void ensureWritableBytes(int writableBytes);
/**
* Determines if the content of the specified buffer is identical to the
* content of this array. 'Identical' here means: <ul> <li>the size of the
* contents of the two buffers are same and</li> <li>every single byte of
* the content of the two buffers are same.</li> </ul> Please note that it
* does not compare {@link #readerIndex()} nor {@link #writerIndex()}. This
* method also returns {@code false} for {@code null} and an object which is
* not an instance of {@link ChannelBuffer} type.
*/
@Override
boolean equals(Object o);
/**
* Returns the factory which creates a {@link ChannelBuffer} whose type and
* default {@link java.nio.ByteOrder} are same with this buffer.
*/
ChannelBufferFactory factory();
/**
* Gets a byte at the specified absolute {@code index} in this buffer. This
* method does not modify {@code readerIndex} or {@code writerIndex} of this
* buffer.
*
* @throws IndexOutOfBoundsException if the specified {@code index} is less
* than {@code 0} or {@code index + 1} is
* greater than {@code this.capacity}
*/
byte getByte(int index);
/**
* Transfers this buffer's data to the specified destination starting at the
* specified absolute {@code index}. This method does not modify {@code
* readerIndex} or {@code writerIndex} of this buffer
*
* @throws IndexOutOfBoundsException if the specified {@code index} is less
* than {@code 0} or if {@code index +
* dst.length} is greater than {@code
* this.capacity}
*/
void getBytes(int index, byte[] dst);
/**
* Transfers this buffer's data to the specified destination starting at the
* specified absolute {@code index}. This method does not modify {@code
* readerIndex} or {@code writerIndex} of this buffer.
*
* @param dstIndex the first index of the destination
* @param length the number of bytes to transfer
* @throws IndexOutOfBoundsException if the specified {@code index} is less
* than {@code 0}, if the specified {@code
* dstIndex} is less than {@code 0}, if
* {@code index + length} is greater than
* {@code this.capacity}, or if {@code
* dstIndex + length} is greater than
* {@code dst.length}
*/
void getBytes(int index, byte[] dst, int dstIndex, int length);
/**
* Transfers this buffer's data to the specified destination starting at the
* specified absolute {@code index} until the destination's position reaches
* its limit. This method does not modify {@code readerIndex} or {@code
* writerIndex} of this buffer while the destination's {@code position} will
* be increased.
*
* @throws IndexOutOfBoundsException if the specified {@code index} is less
* than {@code 0} or if {@code index +
* dst.remaining()} is greater than {@code
* this.capacity}
*/
void getBytes(int index, ByteBuffer dst);
/**
* Transfers this buffer's data to the specified destination starting at the
* specified absolute {@code index} until the destination becomes
* non-writable. This method is basically same with {@link #getBytes(int,
* ChannelBuffer, int, int)}, except that this method increases the {@code
* writerIndex} of the destination by the number of the transferred bytes
* while {@link #getBytes(int, ChannelBuffer, int, int)} does not. This
* method does not modify {@code readerIndex} or {@code writerIndex} of the
* source buffer (i.e. {@code this}).
*
* @throws IndexOutOfBoundsException if the specified {@code index} is less
* than {@code 0} or if {@code index +
* dst.writableBytes} is greater than
* {@code this.capacity}
*/
void getBytes(int index, ChannelBuffer dst);
/**
* Transfers this buffer's data to the specified destination starting at the
* specified absolute {@code index}. This method is basically same with
* {@link #getBytes(int, ChannelBuffer, int, int)}, except that this method
* increases the {@code writerIndex} of the destination by the number of the
* transferred bytes while {@link #getBytes(int, ChannelBuffer, int, int)}
* does not. This method does not modify {@code readerIndex} or {@code
* writerIndex} of the source buffer (i.e. {@code this}).
*
* @param length the number of bytes to transfer
* @throws IndexOutOfBoundsException if the specified {@code index} is less
* than {@code 0}, if {@code index +
* length} is greater than {@code
* this.capacity}, or if {@code length} is
* greater than {@code dst.writableBytes}
*/
void getBytes(int index, ChannelBuffer dst, int length);
/**
* Transfers this buffer's data to the specified destination starting at the
* specified absolute {@code index}. This method does not modify {@code
* readerIndex} or {@code writerIndex} of both the source (i.e. {@code
* this}) and the destination.
*
* @param dstIndex the first index of the destination
* @param length the number of bytes to transfer
* @throws IndexOutOfBoundsException if the specified {@code index} is less
* than {@code 0}, if the specified {@code
* dstIndex} is less than {@code 0}, if
* {@code index + length} is greater than
* {@code this.capacity}, or if {@code
* dstIndex + length} is greater than
* {@code dst.capacity}
*/
void getBytes(int index, ChannelBuffer dst, int dstIndex, int length);
/**
* Transfers this buffer's data to the specified stream starting at the
* specified absolute {@code index}. This method does not modify {@code
* readerIndex} or {@code writerIndex} of this buffer.
*
* @param length the number of bytes to transfer
* @throws IndexOutOfBoundsException if the specified {@code index} is less
* than {@code 0} or if {@code index +
* length} is greater than {@code
* this.capacity}
* @throws IOException if the specified stream threw an
* exception during I/O
*/
void getBytes(int index, OutputStream dst, int length) throws IOException;
/**
* Returns {@code true} if and only if this buffer is backed by an NIO
* direct buffer.
*/
boolean isDirect();
/**
* Marks the current {@code readerIndex} in this buffer. You can reposition
* the current {@code readerIndex} to the marked {@code readerIndex} by
* calling {@link #resetReaderIndex()}. The initial value of the marked
* {@code readerIndex} is {@code 0}.
*/
void markReaderIndex();
/**
* Marks the current {@code writerIndex} in this buffer. You can reposition
* the current {@code writerIndex} to the marked {@code writerIndex} by
* calling {@link #resetWriterIndex()}. The initial value of the marked
* {@code writerIndex} is {@code 0}.
*/
void markWriterIndex();
/**
* Returns {@code true} if and only if {@code (this.writerIndex -
* this.readerIndex)} is greater than {@code 0}.
*/
boolean readable();
/**
* Returns the number of readable bytes which is equal to {@code
* (this.writerIndex - this.readerIndex)}.
*/
int readableBytes();
/**
* Gets a byte at the current {@code readerIndex} and increases the {@code
* readerIndex} by {@code 1} in this buffer.
*
* @throws IndexOutOfBoundsException if {@code this.readableBytes} is less
* than {@code 1}
*/
byte readByte();
/**
* Transfers this buffer's data to the specified destination starting at the
* current {@code readerIndex} and increases the {@code readerIndex} by the
* number of the transferred bytes (= {@code dst.length}).
*
* @throws IndexOutOfBoundsException if {@code dst.length} is greater than
* {@code this.readableBytes}
*/
void readBytes(byte[] dst);
/**
* Transfers this buffer's data to the specified destination starting at the
* current {@code readerIndex} and increases the {@code readerIndex} by the
* number of the transferred bytes (= {@code length}).
*
* @param dstIndex the first index of the destination
* @param length the number of bytes to transfer
* @throws IndexOutOfBoundsException if the specified {@code dstIndex} is
* less than {@code 0}, if {@code length}
* is greater than {@code this.readableBytes},
* or if {@code dstIndex + length} is
* greater than {@code dst.length}
*/
void readBytes(byte[] dst, int dstIndex, int length);
/**
* Transfers this buffer's data to the specified destination starting at the
* current {@code readerIndex} until the destination's position reaches its
* limit, and increases the {@code readerIndex} by the number of the
* transferred bytes.
*
* @throws IndexOutOfBoundsException if {@code dst.remaining()} is greater
* than {@code this.readableBytes}
*/
void readBytes(ByteBuffer dst);
/**
* Transfers this buffer's data to the specified destination starting at the
* current {@code readerIndex} until the destination becomes non-writable,
* and increases the {@code readerIndex} by the number of the transferred
* bytes. This method is basically same with {@link
* #readBytes(ChannelBuffer, int, int)}, except that this method increases
* the {@code writerIndex} of the destination by the number of the
* transferred bytes while {@link #readBytes(ChannelBuffer, int, int)} does
* not.
*
* @throws IndexOutOfBoundsException if {@code dst.writableBytes} is greater
* than {@code this.readableBytes}
*/
void readBytes(ChannelBuffer dst);
/**
* Transfers this buffer's data to the specified destination starting at the
* current {@code readerIndex} and increases the {@code readerIndex} by the
* number of the transferred bytes (= {@code length}). This method is
* basically same with {@link #readBytes(ChannelBuffer, int, int)}, except
* that this method increases the {@code writerIndex} of the destination by
* the number of the transferred bytes (= {@code length}) while {@link
* #readBytes(ChannelBuffer, int, int)} does not.
*
* @throws IndexOutOfBoundsException if {@code length} is greater than
* {@code this.readableBytes} or if {@code
* length} is greater than {@code
* dst.writableBytes}
*/
void readBytes(ChannelBuffer dst, int length);
/**
* Transfers this buffer's data to the specified destination starting at the
* current {@code readerIndex} and increases the {@code readerIndex} by the
* number of the transferred bytes (= {@code length}).
*
* @param dstIndex the first index of the destination
* @param length the number of bytes to transfer
* @throws IndexOutOfBoundsException if the specified {@code dstIndex} is
* less than {@code 0}, if {@code length}
* is greater than {@code this.readableBytes},
* or if {@code dstIndex + length} is
* greater than {@code dst.capacity}
*/
void readBytes(ChannelBuffer dst, int dstIndex, int length);
/**
* Transfers this buffer's data to a newly created buffer starting at the
* current {@code readerIndex} and increases the {@code readerIndex} by the
* number of the transferred bytes (= {@code length}). The returned buffer's
* {@code readerIndex} and {@code writerIndex} are {@code 0} and {@code
* length} respectively.
*
* @param length the number of bytes to transfer
* @return the newly created buffer which contains the transferred bytes
* @throws IndexOutOfBoundsException if {@code length} is greater than
* {@code this.readableBytes}
*/
ChannelBuffer readBytes(int length);
/**
* Repositions the current {@code readerIndex} to the marked {@code
* readerIndex} in this buffer.
*
* @throws IndexOutOfBoundsException if the current {@code writerIndex} is
* less than the marked {@code
* readerIndex}
*/
void resetReaderIndex();
/**
* Marks the current {@code writerIndex} in this buffer. You can reposition
* the current {@code writerIndex} to the marked {@code writerIndex} by
* calling {@link #resetWriterIndex()}. The initial value of the marked
* {@code writerIndex} is {@code 0}.
*/
void resetWriterIndex();
/**
* Returns the {@code readerIndex} of this buffer.
*/
int readerIndex();
/**
* Sets the {@code readerIndex} of this buffer.
*
* @throws IndexOutOfBoundsException if the specified {@code readerIndex} is
* less than {@code 0} or greater than
* {@code this.writerIndex}
*/
void readerIndex(int readerIndex);
/**
* Transfers this buffer's data to the specified stream starting at the
* current {@code readerIndex}.
*
* @param length the number of bytes to transfer
* @throws IndexOutOfBoundsException if {@code length} is greater than
* {@code this.readableBytes}
* @throws IOException if the specified stream threw an
* exception during I/O
*/
void readBytes(OutputStream dst, int length) throws IOException;
/**
* Sets the specified byte at the specified absolute {@code index} in this
* buffer. The 24 high-order bits of the specified value are ignored. This
* method does not modify {@code readerIndex} or {@code writerIndex} of this
* buffer.
*
* @throws IndexOutOfBoundsException if the specified {@code index} is less
* than {@code 0} or {@code index + 1} is
* greater than {@code this.capacity}
*/
void setByte(int index, int value);
/**
* Transfers the specified source array's data to this buffer starting at
* the specified absolute {@code index}. This method does not modify {@code
* readerIndex} or {@code writerIndex} of this buffer.
*
* @throws IndexOutOfBoundsException if the specified {@code index} is less
* than {@code 0} or if {@code index +
* src.length} is greater than {@code
* this.capacity}
*/
void setBytes(int index, byte[] src);
/**
* Transfers the specified source array's data to this buffer starting at
* the specified absolute {@code index}. This method does not modify {@code
* readerIndex} or {@code writerIndex} of this buffer.
*
* @throws IndexOutOfBoundsException if the specified {@code index} is less
* than {@code 0}, if the specified {@code
* srcIndex} is less than {@code 0}, if
* {@code index + length} is greater than
* {@code this.capacity}, or if {@code
* srcIndex + length} is greater than
* {@code src.length}
*/
void setBytes(int index, byte[] src, int srcIndex, int length);
/**
* Transfers the specified source buffer's data to this buffer starting at
* the specified absolute {@code index} until the source buffer's position
* reaches its limit. This method does not modify {@code readerIndex} or
* {@code writerIndex} of this buffer.
*
* @throws IndexOutOfBoundsException if the specified {@code index} is less
* than {@code 0} or if {@code index +
* src.remaining()} is greater than {@code
* this.capacity}
*/
void setBytes(int index, ByteBuffer src);
/**
* Transfers the specified source buffer's data to this buffer starting at
* the specified absolute {@code index} until the source buffer becomes
* unreadable. This method is basically same with {@link #setBytes(int,
* ChannelBuffer, int, int)}, except that this method increases the {@code
* readerIndex} of the source buffer by the number of the transferred bytes
* while {@link #setBytes(int, ChannelBuffer, int, int)} does not. This
* method does not modify {@code readerIndex} or {@code writerIndex} of the
* source buffer (i.e. {@code this}).
*
* @throws IndexOutOfBoundsException if the specified {@code index} is less
* than {@code 0} or if {@code index +
* src.readableBytes} is greater than
* {@code this.capacity}
*/
void setBytes(int index, ChannelBuffer src);
/**
* Transfers the specified source buffer's data to this buffer starting at
* the specified absolute {@code index}. This method is basically same with
* {@link #setBytes(int, ChannelBuffer, int, int)}, except that this method
* increases the {@code readerIndex} of the source buffer by the number of
* the transferred bytes while {@link #setBytes(int, ChannelBuffer, int,
* int)} does not. This method does not modify {@code readerIndex} or {@code
* writerIndex} of the source buffer (i.e. {@code this}).
*
* @param length the number of bytes to transfer
* @throws IndexOutOfBoundsException if the specified {@code index} is less
* than {@code 0}, if {@code index +
* length} is greater than {@code
* this.capacity}, or if {@code length} is
* greater than {@code src.readableBytes}
*/
void setBytes(int index, ChannelBuffer src, int length);
/**
* Transfers the specified source buffer's data to this buffer starting at
* the specified absolute {@code index}. This method does not modify {@code
* readerIndex} or {@code writerIndex} of both the source (i.e. {@code
* this}) and the destination.
*
* @param srcIndex the first index of the source
* @param length the number of bytes to transfer
* @throws IndexOutOfBoundsException if the specified {@code index} is less
* than {@code 0}, if the specified {@code
* srcIndex} is less than {@code 0}, if
* {@code index + length} is greater than
* {@code this.capacity}, or if {@code
* srcIndex + length} is greater than
* {@code src.capacity}
*/
void setBytes(int index, ChannelBuffer src, int srcIndex, int length);
/**
* Transfers the content of the specified source stream to this buffer
* starting at the specified absolute {@code index}. This method does not
* modify {@code readerIndex} or {@code writerIndex} of this buffer.
*
* @param length the number of bytes to transfer
* @return the actual number of bytes read in from the specified channel.
* {@code -1} if the specified channel is closed.
* @throws IndexOutOfBoundsException if the specified {@code index} is less
* than {@code 0} or if {@code index +
* length} is greater than {@code
* this.capacity}
* @throws IOException if the specified stream threw an
* exception during I/O
*/
int setBytes(int index, InputStream src, int length) throws IOException;
/**
* Sets the {@code readerIndex} and {@code writerIndex} of this buffer in
* one shot. This method is useful when you have to worry about the
* invocation order of {@link #readerIndex(int)} and {@link
* #writerIndex(int)} methods. For example, the following code will fail:
* <p/>
* <pre>
* // Create a buffer whose readerIndex, writerIndex and capacity are
* // 0, 0 and 8 respectively.
* {@link ChannelBuffer} buf = {@link ChannelBuffers}.buffer(8);
*
* // IndexOutOfBoundsException is thrown because the specified
* // readerIndex (2) cannot be greater than the current writerIndex (0).
* buf.readerIndex(2);
* buf.writerIndex(4);
* </pre>
* <p/>
* The following code will also fail:
* <p/>
* <pre>
* // Create a buffer whose readerIndex, writerIndex and capacity are
* // 0, 8 and 8 respectively.
* {@link ChannelBuffer} buf = {@link ChannelBuffers}.wrappedBuffer(new
* byte[8]);
*
* // readerIndex becomes 8.
* buf.readLong();
*
* // IndexOutOfBoundsException is thrown because the specified
* // writerIndex (4) cannot be less than the current readerIndex (8).
* buf.writerIndex(4);
* buf.readerIndex(2);
* </pre>
* <p/>
* By contrast, {@link #setIndex(int, int)} guarantees that it never throws
* an {@link IndexOutOfBoundsException} as long as the specified indexes
* meet basic constraints, regardless what the current index values of the
* buffer are:
* <p/>
* <pre>
* // No matter what the current state of the buffer is, the following
* // call always succeeds as long as the capacity of the buffer is not
* // less than 4.
* buf.setIndex(2, 4);
* </pre>
*
* @throws IndexOutOfBoundsException if the specified {@code readerIndex} is
* less than 0, if the specified {@code
* writerIndex} is less than the specified
* {@code readerIndex} or if the specified
* {@code writerIndex} is greater than
* {@code this.capacity}
*/
void setIndex(int readerIndex, int writerIndex);
/**
* Increases the current {@code readerIndex} by the specified {@code length}
* in this buffer.
*
* @throws IndexOutOfBoundsException if {@code length} is greater than
* {@code this.readableBytes}
*/
void skipBytes(int length);
/**
* Converts this buffer's readable bytes into a NIO buffer. The returned
* buffer might or might not share the content with this buffer, while they
* have separate indexes and marks. This method is identical to {@code
* buf.toByteBuffer(buf.readerIndex(), buf.readableBytes())}. This method
* does not modify {@code readerIndex} or {@code writerIndex} of this
* buffer.
*/
ByteBuffer toByteBuffer();
/**
* Converts this buffer's sub-region into a NIO buffer. The returned buffer
* might or might not share the content with this buffer, while they have
* separate indexes and marks. This method does not modify {@code
* readerIndex} or {@code writerIndex} of this buffer.
*/
ByteBuffer toByteBuffer(int index, int length);
/**
* Returns {@code true} if and only if {@code (this.capacity -
* this.writerIndex)} is greater than {@code 0}.
*/
boolean writable();
/**
* Returns the number of writable bytes which is equal to {@code
* (this.capacity - this.writerIndex)}.
*/
int writableBytes();
/**
* Sets the specified byte at the current {@code writerIndex} and increases
* the {@code writerIndex} by {@code 1} in this buffer. The 24 high-order
* bits of the specified value are ignored.
*
* @throws IndexOutOfBoundsException if {@code this.writableBytes} is less
* than {@code 1}
*/
void writeByte(int value);
/**
* Transfers the specified source array's data to this buffer starting at
* the current {@code writerIndex} and increases the {@code writerIndex} by
* the number of the transferred bytes (= {@code src.length}).
*
* @throws IndexOutOfBoundsException if {@code src.length} is greater than
* {@code this.writableBytes}
*/
void writeBytes(byte[] src);
/**
* Transfers the specified source array's data to this buffer starting at
* the current {@code writerIndex} and increases the {@code writerIndex} by
* the number of the transferred bytes (= {@code length}).
*
* @param index the first index of the source
* @param length the number of bytes to transfer
* @throws IndexOutOfBoundsException if the specified {@code srcIndex} is
* less than {@code 0}, if {@code srcIndex
* + length} is greater than {@code
* src.length}, or if {@code length} is
* greater than {@code this.writableBytes}
*/
void writeBytes(byte[] src, int index, int length);
/**
* Transfers the specified source buffer's data to this buffer starting at
* the current {@code writerIndex} until the source buffer's position
* reaches its limit, and increases the {@code writerIndex} by the number of
* the transferred bytes.
*
* @throws IndexOutOfBoundsException if {@code src.remaining()} is greater
* than {@code this.writableBytes}
*/
void writeBytes(ByteBuffer src);
/**
* Transfers the specified source buffer's data to this buffer starting at
* the current {@code writerIndex} until the source buffer becomes
* unreadable, and increases the {@code writerIndex} by the number of the
* transferred bytes. This method is basically same with {@link
* #writeBytes(ChannelBuffer, int, int)}, except that this method increases
* the {@code readerIndex} of the source buffer by the number of the
* transferred bytes while {@link #writeBytes(ChannelBuffer, int, int)} does
* not.
*
* @throws IndexOutOfBoundsException if {@code src.readableBytes} is greater
* than {@code this.writableBytes}
*/
void writeBytes(ChannelBuffer src);
/**
* Transfers the specified source buffer's data to this buffer starting at
* the current {@code writerIndex} and increases the {@code writerIndex} by
* the number of the transferred bytes (= {@code length}). This method is
* basically same with {@link #writeBytes(ChannelBuffer, int, int)}, except
* that this method increases the {@code readerIndex} of the source buffer
* by the number of the transferred bytes (= {@code length}) while {@link
* #writeBytes(ChannelBuffer, int, int)} does not.
*
* @param length the number of bytes to transfer
* @throws IndexOutOfBoundsException if {@code length} is greater than
* {@code this.writableBytes} or if {@code
* length} is greater then {@code
* src.readableBytes}
*/
void writeBytes(ChannelBuffer src, int length);
/**
* Transfers the specified source buffer's data to this buffer starting at
* the current {@code writerIndex} and increases the {@code writerIndex} by
* the number of the transferred bytes (= {@code length}).
*
* @param srcIndex the first index of the source
* @param length the number of bytes to transfer
* @throws IndexOutOfBoundsException if the specified {@code srcIndex} is
* less than {@code 0}, if {@code srcIndex
* + length} is greater than {@code
* src.capacity}, or if {@code length} is
* greater than {@code this.writableBytes}
*/
void writeBytes(ChannelBuffer src, int srcIndex, int length);
/**
* Transfers the content of the specified stream to this buffer starting at
* the current {@code writerIndex} and increases the {@code writerIndex} by
* the number of the transferred bytes.
*
* @param length the number of bytes to transfer
* @return the actual number of bytes read in from the specified stream
* @throws IndexOutOfBoundsException if {@code length} is greater than
* {@code this.writableBytes}
* @throws IOException if the specified stream threw an
* exception during I/O
*/
int writeBytes(InputStream src, int length) throws IOException;
/**
* Returns the {@code writerIndex} of this buffer.
*/
int writerIndex();
/**
* Sets the {@code writerIndex} of this buffer.
*
* @throws IndexOutOfBoundsException if the specified {@code writerIndex} is
* less than {@code this.readerIndex} or
* greater than {@code this.capacity}
*/
void writerIndex(int writerIndex);
/**
* Returns the backing byte array of this buffer.
*
* @throws UnsupportedOperationException if there is no accessible backing byte
* array
*/
byte[] array();
/**
* Returns {@code true} if and only if this buffer has a backing byte array.
* If this method returns true, you can safely call {@link #array()} and
* {@link #arrayOffset()}.
*/
boolean hasArray();
/**
* Returns the offset of the first byte within the backing byte array of
* this buffer.
*
* @throws UnsupportedOperationException if there is no accessible backing byte
* array
*/
int arrayOffset();
/**
* If this buffer is backed by an NIO direct buffer,
* in some scenarios it may be necessary to manually release.
*/
default void release() {}
}
| 7,563 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyClientToServerTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty4;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.exchange.ExchangeChannel;
import org.apache.dubbo.remoting.exchange.ExchangeServer;
import org.apache.dubbo.remoting.exchange.Exchangers;
import org.apache.dubbo.remoting.exchange.support.Replier;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
/**
* Netty4ClientToServerTest
*/
class NettyClientToServerTest extends ClientToServerTest {
protected ExchangeServer newServer(int port, Replier<?> receiver) throws RemotingException {
// add heartbeat cycle to avoid unstable ut.
URL url = URL.valueOf("exchange://localhost:" + port + "?server=netty4");
ApplicationModel applicationModel = ApplicationModel.defaultModel();
ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
ConfigManager configManager = new ConfigManager(applicationModel);
configManager.setApplication(applicationConfig);
configManager.getApplication();
applicationModel.setConfigManager(configManager);
url = url.addParameter(Constants.HEARTBEAT_KEY, 600 * 1000)
.putAttribute(CommonConstants.SCOPE_MODEL, applicationModel);
url = url.setScopeModel(applicationModel);
// ModuleModel moduleModel = applicationModel.getDefaultModule();
ModuleModel moduleModel = applicationModel.getDefaultModule();
url = url.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel);
return Exchangers.bind(url, receiver);
}
protected ExchangeChannel newClient(int port) throws RemotingException {
// add heartbeat cycle to avoid unstable ut.
URL url = URL.valueOf("exchange://localhost:" + port + "?client=netty4&timeout=300000");
url = url.addParameter(Constants.HEARTBEAT_KEY, 600 * 1000);
ApplicationModel applicationModel = ApplicationModel.defaultModel();
ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
ConfigManager configManager = new ConfigManager(applicationModel);
configManager.setApplication(applicationConfig);
configManager.getApplication();
applicationModel.setConfigManager(configManager);
url = url.setScopeModel(applicationModel);
ModuleModel moduleModel = applicationModel.getDefaultModule();
url = url.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel);
return Exchangers.connect(url);
}
}
| 7,564 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientsTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty4;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.remoting.Transporter;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.fail;
class ClientsTest {
@Test
void testGetTransportEmpty() {
try {
ExtensionLoader.getExtensionLoader(Transporter.class).getExtension("");
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected.getMessage(), containsString("Extension name == null"));
}
}
@Test
void testGetTransportNull() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
String name = null;
ExtensionLoader.getExtensionLoader(Transporter.class).getExtension(name);
});
}
@Test
void testGetTransport3() {
String name = "netty4";
assertEquals(
NettyTransporter.class,
ExtensionLoader.getExtensionLoader(Transporter.class)
.getExtension(name)
.getClass());
}
@Test
void testGetTransportWrong() {
Assertions.assertThrows(IllegalStateException.class, () -> {
String name = "nety";
assertNull(ExtensionLoader.getExtensionLoader(Transporter.class)
.getExtension(name)
.getClass());
});
}
}
| 7,565 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ReplierDispatcherTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty4;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.exchange.ExchangeChannel;
import org.apache.dubbo.remoting.exchange.ExchangeServer;
import org.apache.dubbo.remoting.exchange.Exchangers;
import org.apache.dubbo.remoting.exchange.support.ReplierDispatcher;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
import static org.junit.jupiter.api.Assertions.fail;
/**
* ReplierDispatcherTest
*/
class ReplierDispatcherTest {
private ExchangeServer exchangeServer;
private ConcurrentHashMap<String, ExchangeChannel> clients = new ConcurrentHashMap<>();
private int port;
@BeforeEach
public void startServer() throws RemotingException {
port = NetUtils.getAvailablePort();
ReplierDispatcher dispatcher = new ReplierDispatcher();
dispatcher.addReplier(RpcMessage.class, new RpcMessageHandler());
dispatcher.addReplier(Data.class, (channel, msg) -> new StringMessage("hello world"));
URL url = URL.valueOf(
"exchange://localhost:" + port + "?" + CommonConstants.TIMEOUT_KEY + "=60000&threadpool=cached");
ApplicationModel applicationModel = ApplicationModel.defaultModel();
ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
ConfigManager configManager = new ConfigManager(applicationModel);
configManager.setApplication(applicationConfig);
configManager.getApplication();
applicationModel.setConfigManager(configManager);
url = url.setScopeModel(applicationModel);
ModuleModel moduleModel = applicationModel.getDefaultModule();
url = url.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel);
exchangeServer = Exchangers.bind(url, dispatcher);
}
@Test
void testDataPackage() throws Exception {
ExchangeChannel client = Exchangers.connect(
URL.valueOf("exchange://localhost:" + port + "?" + CommonConstants.TIMEOUT_KEY + "=60000"));
Random random = new Random();
for (int i = 5; i < 100; i++) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < i * 100; j++)
sb.append('(').append(random.nextLong()).append(')');
Data d = new Data();
d.setData(sb.toString());
Assertions.assertEquals(client.request(d).get().toString(), "hello world");
}
clients.put(Thread.currentThread().getName(), client);
}
@Test
void testMultiThread() throws Exception {
int tc = 10;
ExecutorService exec = Executors.newFixedThreadPool(tc);
List<Future<?>> futureList = new LinkedList<>();
for (int i = 0; i < tc; i++)
futureList.add(exec.submit(() -> {
try {
clientExchangeInfo(port);
} catch (Exception e) {
fail(e);
}
}));
for (Future<?> future : futureList) {
future.get();
}
exec.shutdown();
exec.awaitTermination(10, TimeUnit.SECONDS);
}
void clientExchangeInfo(int port) throws Exception {
ExchangeChannel client = Exchangers.connect(
URL.valueOf("exchange://localhost:" + port + "?" + CommonConstants.TIMEOUT_KEY + "=60000"));
clients.put(Thread.currentThread().getName(), client);
MockResult result = (MockResult) client.request(new RpcMessage(
DemoService.class.getName(), "plus", new Class<?>[] {int.class, int.class}, new Object[] {55, 25
}))
.get();
Assertions.assertEquals(result.getResult(), 80);
for (int i = 0; i < 100; i++) {
client.request(new RpcMessage(
DemoService.class.getName(), "sayHello", new Class<?>[] {String.class}, new Object[] {"qianlei" + i
}));
}
for (int i = 0; i < 100; i++) {
CompletableFuture<Object> future = client.request(new Data());
Assertions.assertEquals(future.get().toString(), "hello world");
}
}
@AfterEach
public void tearDown() {
try {
if (exchangeServer != null) exchangeServer.close();
} finally {
if (clients.size() != 0)
clients.forEach((key, value) -> {
value.close();
clients.remove(key);
});
}
}
static class Data implements Serializable {
private static final long serialVersionUID = -4666580993978548778L;
private String mData = "";
public Data() {}
public String getData() {
return mData;
}
public void setData(String data) {
mData = data;
}
}
static class StringMessage implements Serializable {
private static final long serialVersionUID = 7193122183120113947L;
private String mText;
StringMessage(String msg) {
mText = msg;
}
public String toString() {
return mText;
}
}
}
| 7,566 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientReconnectTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty4;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.utils.DubboAppender;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.Client;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.RemotingServer;
import org.apache.dubbo.remoting.exchange.Exchangers;
import org.apache.dubbo.remoting.exchange.support.ExchangeHandlerAdapter;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
import static org.apache.dubbo.remoting.Constants.LEAST_RECONNECT_DURATION_KEY;
/**
* Client reconnect test
*/
class ClientReconnectTest {
public static void main(String[] args) {
System.out.println(3 % 1);
}
@BeforeEach
public void clear() {
DubboAppender.clear();
}
@Test
void testReconnect() throws RemotingException, InterruptedException {
{
int port = NetUtils.getAvailablePort();
Client client = startClient(port, 200);
Assertions.assertFalse(client.isConnected());
RemotingServer server = startServer(port);
for (int i = 0; i < 100 && !client.isConnected(); i++) {
Thread.sleep(20);
}
Assertions.assertTrue(client.isConnected());
client.close(2000);
server.close(2000);
}
{
int port = NetUtils.getAvailablePort();
Client client = startClient(port, 20000);
Assertions.assertFalse(client.isConnected());
RemotingServer server = startServer(port);
for (int i = 0; i < 5; i++) {
Thread.sleep(200);
}
Assertions.assertFalse(client.isConnected());
client.close(2000);
server.close(2000);
}
}
public Client startClient(int port, int heartbeat) throws RemotingException {
URL url = URL.valueOf("exchange://127.0.0.1:" + port + "/client.reconnect.test?client=netty4&check=false&"
+ Constants.HEARTBEAT_KEY + "=" + heartbeat + "&" + LEAST_RECONNECT_DURATION_KEY + "=0");
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
ConfigManager configManager = new ConfigManager(applicationModel);
configManager.setApplication(applicationConfig);
configManager.getApplication();
applicationModel.setConfigManager(configManager);
url = url.putAttribute(CommonConstants.SCOPE_MODEL, applicationModel);
return Exchangers.connect(url);
}
public RemotingServer startServer(int port) throws RemotingException {
URL url = URL.valueOf("exchange://127.0.0.1:" + port + "/client.reconnect.test?server=netty4");
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
ConfigManager configManager = new ConfigManager(applicationModel);
configManager.setApplication(applicationConfig);
configManager.getApplication();
applicationModel.setConfigManager(configManager);
ModuleModel moduleModel = applicationModel.getDefaultModule();
url = url.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel);
return Exchangers.bind(url, new HandlerAdapter());
}
static class HandlerAdapter extends ExchangeHandlerAdapter {
public HandlerAdapter() {
super(FrameworkModel.defaultModel());
}
@Override
public void connected(Channel channel) throws RemotingException {}
@Override
public void disconnected(Channel channel) throws RemotingException {}
@Override
public void caught(Channel channel, Throwable exception) throws RemotingException {}
}
}
| 7,567 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientToServerTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty4;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.exchange.ExchangeChannel;
import org.apache.dubbo.remoting.exchange.ExchangeServer;
import org.apache.dubbo.remoting.exchange.support.Replier;
import java.util.concurrent.CompletableFuture;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* ClientToServer
*/
public abstract class ClientToServerTest {
protected ExchangeServer server;
protected ExchangeChannel client;
protected WorldHandler handler = new WorldHandler();
protected abstract ExchangeServer newServer(int port, Replier<?> receiver) throws RemotingException;
protected abstract ExchangeChannel newClient(int port) throws RemotingException;
@BeforeEach
protected void setUp() throws Exception {
int port = NetUtils.getAvailablePort();
server = newServer(port, handler);
client = newClient(port);
}
@AfterEach
protected void tearDown() {
try {
if (server != null) server.close();
} finally {
if (client != null) client.close();
}
}
@Test
void testFuture() throws Exception {
CompletableFuture<Object> future = client.request(new World("world"));
Hello result = (Hello) future.get();
Assertions.assertEquals("hello,world", result.getName());
}
}
| 7,568 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/World.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty4;
import java.io.Serializable;
/**
* Data
*/
public class World implements Serializable {
private static final long serialVersionUID = 8563900571013747774L;
private String name;
public World() {}
public World(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| 7,569 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyCodecAdapterTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty4;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.Codec2;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToByteEncoder;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
/**
* {@link NettyCodecAdapter}
*/
class NettyCodecAdapterTest {
@Test
void test() {
Codec2 codec2 = Mockito.mock(Codec2.class);
URL url = Mockito.mock(URL.class);
ChannelHandler handler = Mockito.mock(ChannelHandler.class);
NettyCodecAdapter nettyCodecAdapter = new NettyCodecAdapter(codec2, url, handler);
io.netty.channel.ChannelHandler decoder = nettyCodecAdapter.getDecoder();
io.netty.channel.ChannelHandler encoder = nettyCodecAdapter.getEncoder();
Assertions.assertTrue(decoder instanceof ByteToMessageDecoder);
Assertions.assertTrue(encoder instanceof MessageToByteEncoder);
}
}
| 7,570 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/Hello.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty4;
import java.io.Serializable;
/**
* Result
*/
public class Hello implements Serializable {
private static final long serialVersionUID = 753429849957096150L;
private String name;
public Hello() {}
public Hello(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| 7,571 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyEventLoopFactoryTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty4;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.Epoll;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollServerSocketChannel;
import io.netty.channel.epoll.EpollSocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.OS_LINUX_PREFIX;
import static org.apache.dubbo.common.constants.CommonConstants.OS_NAME_KEY;
import static org.apache.dubbo.remoting.Constants.NETTY_EPOLL_ENABLE_KEY;
/**
* {@link NettyEventLoopFactory}
*/
class NettyEventLoopFactoryTest {
@BeforeEach
public void setUp() {
System.setProperty(NETTY_EPOLL_ENABLE_KEY, "true");
}
@AfterEach
public void reset() {
System.clearProperty(NETTY_EPOLL_ENABLE_KEY);
}
@Test
void eventLoopGroup() {
if (isEpoll()) {
EventLoopGroup eventLoopGroup = NettyEventLoopFactory.eventLoopGroup(1, "test");
Assertions.assertTrue(eventLoopGroup instanceof EpollEventLoopGroup);
Class<? extends SocketChannel> socketChannelClass = NettyEventLoopFactory.socketChannelClass();
Assertions.assertEquals(socketChannelClass, EpollSocketChannel.class);
Class<? extends ServerSocketChannel> serverSocketChannelClass =
NettyEventLoopFactory.serverSocketChannelClass();
Assertions.assertEquals(serverSocketChannelClass, EpollServerSocketChannel.class);
} else {
EventLoopGroup eventLoopGroup = NettyEventLoopFactory.eventLoopGroup(1, "test");
Assertions.assertTrue(eventLoopGroup instanceof NioEventLoopGroup);
Class<? extends SocketChannel> socketChannelClass = NettyEventLoopFactory.socketChannelClass();
Assertions.assertEquals(socketChannelClass, NioSocketChannel.class);
Class<? extends ServerSocketChannel> serverSocketChannelClass =
NettyEventLoopFactory.serverSocketChannelClass();
Assertions.assertEquals(serverSocketChannelClass, NioServerSocketChannel.class);
}
}
private boolean isEpoll() {
String osName = System.getProperty(OS_NAME_KEY);
return osName.toLowerCase().contains(OS_LINUX_PREFIX) && Epoll.isAvailable();
}
}
| 7,572 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/RpcMessage.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty4;
import java.io.Serializable;
/**
* RpcMessage.
*/
public class RpcMessage implements Serializable {
private static final long serialVersionUID = -5148079121106659095L;
private String mClassName;
private String mMethodDesc;
private Class<?>[] mParameterTypes;
private Object[] mArguments;
public RpcMessage(String cn, String desc, Class<?>[] parameterTypes, Object[] args) {
mClassName = cn;
mMethodDesc = desc;
mParameterTypes = parameterTypes;
mArguments = args;
}
public String getClassName() {
return mClassName;
}
public String getMethodDesc() {
return mMethodDesc;
}
public Class<?>[] getParameterTypes() {
return mParameterTypes;
}
public Object[] getArguments() {
return mArguments;
}
}
| 7,573 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/WorldHandler.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty4;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.exchange.ExchangeChannel;
import org.apache.dubbo.remoting.exchange.support.Replier;
/**
* DataHandler
*/
public class WorldHandler implements Replier<World> {
public Class<World> interest() {
return World.class;
}
public Object reply(ExchangeChannel channel, World msg) throws RemotingException {
return new Hello("hello," + msg.getName());
}
}
| 7,574 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/DemoServiceImpl.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty4;
/**
* <code>TestServiceImpl</code>
*/
public class DemoServiceImpl implements DemoService {
public void sayHello(String name) {
System.out.println("hello " + name);
}
public int plus(int a, int b) {
return a + b;
}
}
| 7,575 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyClientHandlerTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty4;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.exchange.Request;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.handler.timeout.IdleStateEvent;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class NettyClientHandlerTest {
@Test
void test() throws Exception {
URL url = new ServiceConfigURL("dubbo", "127.0.0.1", 20901);
ChannelHandler handler = Mockito.mock(ChannelHandler.class);
ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class);
Channel channel = Mockito.mock(Channel.class);
Mockito.when(ctx.channel()).thenReturn(channel);
Mockito.when(channel.isActive()).thenReturn(true);
Mockito.when(channel.eventLoop()).thenReturn(new NioEventLoopGroup().next());
Mockito.when(channel.alloc()).thenReturn(PooledByteBufAllocator.DEFAULT);
ChannelPromise future = mock(ChannelPromise.class);
when(channel.writeAndFlush(any())).thenReturn(future);
when(future.cause()).thenReturn(null);
when(channel.newPromise()).thenReturn(future);
when(future.addListener(Mockito.any())).thenReturn(future);
NettyClientHandler nettyClientHandler = new NettyClientHandler(url, handler);
nettyClientHandler.channelActive(ctx);
ArgumentCaptor<NettyChannel> captor = ArgumentCaptor.forClass(NettyChannel.class);
Mockito.verify(handler, Mockito.times(1)).connected(captor.capture());
nettyClientHandler.channelInactive(ctx);
captor = ArgumentCaptor.forClass(NettyChannel.class);
Mockito.verify(handler, Mockito.times(1)).disconnected(captor.capture());
Throwable throwable = Mockito.mock(Throwable.class);
nettyClientHandler.exceptionCaught(ctx, throwable);
captor = ArgumentCaptor.forClass(NettyChannel.class);
ArgumentCaptor<Throwable> throwableArgumentCaptor = ArgumentCaptor.forClass(Throwable.class);
Mockito.verify(handler, Mockito.times(1)).caught(captor.capture(), throwableArgumentCaptor.capture());
nettyClientHandler.channelRead(ctx, "test");
captor = ArgumentCaptor.forClass(NettyChannel.class);
ArgumentCaptor<Object> objectArgumentCaptor = ArgumentCaptor.forClass(Object.class);
Mockito.verify(handler, Mockito.times(1)).received(captor.capture(), objectArgumentCaptor.capture());
nettyClientHandler.userEventTriggered(ctx, IdleStateEvent.READER_IDLE_STATE_EVENT);
ArgumentCaptor<Request> requestArgumentCaptor = ArgumentCaptor.forClass(Request.class);
Thread.sleep(500);
Mockito.verify(channel, Mockito.times(1)).writeAndFlush(requestArgumentCaptor.capture());
}
}
| 7,576 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/RpcMessageHandler.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty4;
import org.apache.dubbo.common.bytecode.NoSuchMethodException;
import org.apache.dubbo.common.bytecode.Wrapper;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.exchange.ExchangeChannel;
import org.apache.dubbo.remoting.exchange.support.Replier;
import java.lang.reflect.InvocationTargetException;
/**
* RpcMessageHandler.
*/
public class RpcMessageHandler implements Replier<RpcMessage> {
private static final ServiceProvider DEFAULT_PROVIDER = new ServiceProvider() {
public Object getImplementation(String service) {
String impl = service + "Impl";
try {
Class<?> cl = Thread.currentThread().getContextClassLoader().loadClass(impl);
return cl.getDeclaredConstructor().newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
};
private ServiceProvider mProvider;
public RpcMessageHandler() {
this(DEFAULT_PROVIDER);
}
public RpcMessageHandler(ServiceProvider prov) {
mProvider = prov;
}
public Class<RpcMessage> interest() {
return RpcMessage.class;
}
public Object reply(ExchangeChannel channel, RpcMessage msg) throws RemotingException {
String desc = msg.getMethodDesc();
Object[] args = msg.getArguments();
Object impl = mProvider.getImplementation(msg.getClassName());
Wrapper wrap = Wrapper.getWrapper(impl.getClass());
try {
return new MockResult(wrap.invokeMethod(impl, desc, msg.getParameterTypes(), args));
} catch (NoSuchMethodException e) {
throw new RemotingException(channel, "Service method not found.");
} catch (InvocationTargetException e) {
return new MockResult(e.getTargetException());
}
}
public interface ServiceProvider {
Object getImplementation(String service);
}
}
| 7,577 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/PortUnificationExchangerTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty4;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.api.connection.AbstractConnectionClient;
import org.apache.dubbo.remoting.api.pu.DefaultPuHandler;
import org.apache.dubbo.remoting.exchange.PortUnificationExchanger;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
class PortUnificationExchangerTest {
private static URL url;
@BeforeAll
public static void init() throws RemotingException {
int port = NetUtils.getAvailablePort();
url = URL.valueOf("empty://127.0.0.1:" + port + "?foo=bar");
ApplicationModel applicationModel = ApplicationModel.defaultModel();
ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
ConfigManager configManager = new ConfigManager(applicationModel);
configManager.setApplication(applicationConfig);
configManager.getApplication();
applicationModel.setConfigManager(configManager);
url = url.setScopeModel(applicationModel);
ModuleModel moduleModel = applicationModel.getDefaultModule();
url = url.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel);
}
@Test
void test() {
PortUnificationExchanger.bind(url, new DefaultPuHandler());
PortUnificationExchanger.bind(url, new DefaultPuHandler());
Assertions.assertEquals(PortUnificationExchanger.getServers().size(), 1);
PortUnificationExchanger.close();
Assertions.assertEquals(PortUnificationExchanger.getServers().size(), 0);
}
@Test
void testConnection() {
PortUnificationExchanger.bind(url, new DefaultPuHandler());
PortUnificationExchanger.bind(url, new DefaultPuHandler());
Assertions.assertEquals(1, PortUnificationExchanger.getServers().size());
PortUnificationExchanger.connect(url, new DefaultPuHandler());
AbstractConnectionClient connectionClient = PortUnificationExchanger.connect(url, new DefaultPuHandler());
Assertions.assertTrue(connectionClient.isAvailable());
connectionClient.close();
PortUnificationExchanger.close();
Assertions.assertEquals(0, PortUnificationExchanger.getServers().size());
}
}
| 7,578 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/DefaultCodec.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty4;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.Codec2;
import org.apache.dubbo.remoting.buffer.ChannelBuffer;
import java.io.IOException;
public class DefaultCodec implements Codec2 {
@Override
public void encode(Channel channel, ChannelBuffer buffer, Object message) throws IOException {}
@Override
public Object decode(Channel channel, ChannelBuffer buffer) throws IOException {
return null;
}
}
| 7,579 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyTransporterTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty4;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.RemotingServer;
import org.apache.dubbo.remoting.transport.ChannelHandlerAdapter;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.concurrent.CountDownLatch;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
class NettyTransporterTest {
@Test
void shouldAbleToBindNetty4() throws Exception {
int port = NetUtils.getAvailablePort();
URL url = new ServiceConfigURL(
"telnet", "localhost", port, new String[] {Constants.BIND_PORT_KEY, String.valueOf(port)});
ApplicationModel applicationModel = ApplicationModel.defaultModel();
ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
ConfigManager configManager = new ConfigManager(applicationModel);
configManager.setApplication(applicationConfig);
configManager.getApplication();
applicationModel.setConfigManager(configManager);
url = url.setScopeModel(applicationModel);
ModuleModel moduleModel = applicationModel.getDefaultModule();
url = url.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel);
RemotingServer server = new NettyTransporter().bind(url, new ChannelHandlerAdapter());
assertThat(server.isBound(), is(true));
}
@Test
void shouldConnectToNetty4Server() throws Exception {
final CountDownLatch lock = new CountDownLatch(1);
int port = NetUtils.getAvailablePort();
URL url = new ServiceConfigURL(
"telnet", "localhost", port, new String[] {Constants.BIND_PORT_KEY, String.valueOf(port)});
ApplicationModel applicationModel = ApplicationModel.defaultModel();
ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
ConfigManager configManager = new ConfigManager(applicationModel);
configManager.setApplication(applicationConfig);
configManager.getApplication();
applicationModel.setConfigManager(configManager);
url = url.setScopeModel(applicationModel);
ModuleModel moduleModel = applicationModel.getDefaultModule();
url = url.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel);
new NettyTransporter().bind(url, new ChannelHandlerAdapter() {
@Override
public void connected(Channel channel) {
lock.countDown();
}
});
new NettyTransporter().connect(url, new ChannelHandlerAdapter() {
@Override
public void sent(Channel channel, Object message) throws RemotingException {
channel.send(message);
channel.close();
}
});
lock.await();
}
}
| 7,580 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/DemoService.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty4;
/**
* <code>TestService</code>
*/
public interface DemoService {
void sayHello(String name);
int plus(int a, int b);
}
| 7,581 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/MockResult.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty4;
import java.io.Serializable;
/**
* AppResponse.
*/
public class MockResult implements Serializable {
private static final long serialVersionUID = -3630485157441794463L;
private final Object mResult;
public MockResult(Object result) {
mResult = result;
}
public Object getResult() {
return mResult;
}
}
| 7,582 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/PortUnificationServerTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty4;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.remoting.api.pu.DefaultPuHandler;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
class PortUnificationServerTest {
@Test
void testBind() throws Throwable {
int port = NetUtils.getAvailablePort();
URL url = URL.valueOf("empty://127.0.0.1:" + port + "?foo=bar");
ApplicationModel applicationModel = ApplicationModel.defaultModel();
ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
ConfigManager configManager = new ConfigManager(applicationModel);
configManager.setApplication(applicationConfig);
configManager.getApplication();
applicationModel.setConfigManager(configManager);
url = url.setScopeModel(applicationModel);
ModuleModel moduleModel = applicationModel.getDefaultModule();
url = url.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel);
// abstract endpoint need to get codec of url(which is in triple package)
final NettyPortUnificationServer server = new NettyPortUnificationServer(url, new DefaultPuHandler());
server.bind();
Assertions.assertTrue(server.isBound());
server.close();
}
}
| 7,583 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyChannelTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty4;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.RemotingException;
import java.net.InetSocketAddress;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelPromise;
import io.netty.channel.EventLoop;
import io.netty.util.concurrent.GenericFutureListener;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
class NettyChannelTest {
private Channel channel = Mockito.mock(Channel.class);
private URL url = new ServiceConfigURL("dubbo", "127.0.0.1", 8080);
private ChannelHandler channelHandler = Mockito.mock(ChannelHandler.class);
@Test
void test() throws Exception {
Channel channel = Mockito.mock(Channel.class);
Mockito.when(channel.isActive()).thenReturn(true);
URL url = URL.valueOf("test://127.0.0.1/test");
ChannelHandler channelHandler = Mockito.mock(ChannelHandler.class);
NettyChannel nettyChannel = NettyChannel.getOrAddChannel(channel, url, channelHandler);
Assertions.assertEquals(nettyChannel.getChannelHandler(), channelHandler);
Assertions.assertTrue(nettyChannel.isActive());
NettyChannel.removeChannel(channel);
Assertions.assertFalse(nettyChannel.isActive());
nettyChannel = NettyChannel.getOrAddChannel(channel, url, channelHandler);
Mockito.when(channel.isActive()).thenReturn(false);
NettyChannel.removeChannelIfDisconnected(channel);
Assertions.assertFalse(nettyChannel.isActive());
nettyChannel = NettyChannel.getOrAddChannel(channel, url, channelHandler);
Assertions.assertFalse(nettyChannel.isConnected());
nettyChannel = NettyChannel.getOrAddChannel(channel, url, channelHandler);
nettyChannel.markActive(true);
Assertions.assertTrue(nettyChannel.isActive());
}
@Test
void testAddress() {
NettyChannel nettyChannel = NettyChannel.getOrAddChannel(channel, url, channelHandler);
InetSocketAddress localAddress = InetSocketAddress.createUnresolved("127.0.0.1", 8888);
InetSocketAddress remoteAddress = InetSocketAddress.createUnresolved("127.0.0.1", 9999);
Mockito.when(channel.localAddress()).thenReturn(localAddress);
Mockito.when(channel.remoteAddress()).thenReturn(remoteAddress);
Assertions.assertEquals(nettyChannel.getLocalAddress(), localAddress);
Assertions.assertEquals(nettyChannel.getRemoteAddress(), remoteAddress);
}
@Test
void testSend() throws Exception {
Mockito.when(channel.eventLoop()).thenReturn(Mockito.mock(EventLoop.class));
Mockito.when(channel.alloc()).thenReturn(PooledByteBufAllocator.DEFAULT);
NettyChannel nettyChannel = NettyChannel.getOrAddChannel(channel, url, channelHandler);
ChannelPromise future = Mockito.mock(ChannelPromise.class);
Mockito.when(future.await(1000)).thenReturn(true);
Mockito.when(future.cause()).thenReturn(null);
Mockito.when(channel.writeAndFlush(Mockito.any())).thenReturn(future);
Mockito.when(channel.newPromise()).thenReturn(future);
Mockito.when(future.addListener(Mockito.any())).thenReturn(future);
nettyChannel.send("msg", true);
NettyChannel finalNettyChannel = nettyChannel;
Exception exception = Mockito.mock(Exception.class);
Mockito.when(exception.getMessage()).thenReturn("future cause");
Mockito.when(future.cause()).thenReturn(exception);
Assertions.assertThrows(
RemotingException.class,
() -> {
finalNettyChannel.send("msg", true);
},
"future cause");
Mockito.when(future.await(1000)).thenReturn(false);
Mockito.when(future.cause()).thenReturn(null);
Assertions.assertThrows(
RemotingException.class,
() -> {
finalNettyChannel.send("msg", true);
},
"in timeout(1000ms) limit");
ChannelPromise channelPromise = Mockito.mock(ChannelPromise.class);
Mockito.when(channel.newPromise()).thenReturn(channelPromise);
Mockito.when(channelPromise.await(1000)).thenReturn(true);
Mockito.when(channelPromise.cause()).thenReturn(null);
Mockito.when(channelPromise.addListener(Mockito.any())).thenReturn(channelPromise);
finalNettyChannel.send("msg", true);
ArgumentCaptor<GenericFutureListener> listenerArgumentCaptor =
ArgumentCaptor.forClass(GenericFutureListener.class);
Mockito.verify(channelPromise, Mockito.times(1)).addListener(listenerArgumentCaptor.capture());
}
@Test
void testAttribute() {
NettyChannel nettyChannel = NettyChannel.getOrAddChannel(channel, url, channelHandler);
nettyChannel.setAttribute("k1", "v1");
Assertions.assertTrue(nettyChannel.hasAttribute("k1"));
Assertions.assertEquals(nettyChannel.getAttribute("k1"), "v1");
nettyChannel.removeAttribute("k1");
Assertions.assertFalse(nettyChannel.hasAttribute("k1"));
}
@Test
void testEquals() {
Channel channel2 = Mockito.mock(Channel.class);
NettyChannel nettyChannel = NettyChannel.getOrAddChannel(channel, url, channelHandler);
NettyChannel nettyChannel2 = NettyChannel.getOrAddChannel(channel2, url, channelHandler);
Assertions.assertEquals(nettyChannel, nettyChannel);
Assertions.assertNotEquals(nettyChannel, nettyChannel2);
}
}
| 7,584 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyBackedChannelBufferTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty4;
import org.apache.dubbo.remoting.buffer.ChannelBuffer;
import io.netty.buffer.Unpooled;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class NettyBackedChannelBufferTest {
private static final int CAPACITY = 4096;
private ChannelBuffer buffer;
@BeforeEach
public void init() {
buffer = new NettyBackedChannelBuffer(Unpooled.buffer(CAPACITY, CAPACITY * 2));
}
@AfterEach
public void dispose() {
buffer = null;
}
@Test
void testBufferTransfer() {
byte[] tmp1 = {1, 2};
byte[] tmp2 = {3, 4};
ChannelBuffer source = new NettyBackedChannelBuffer(Unpooled.buffer(2, 4));
source.writeBytes(tmp1);
buffer.writeBytes(tmp2);
assertEquals(2, buffer.readableBytes());
source.setBytes(0, tmp1, 0, 2);
buffer.setBytes(0, source, 0, 2);
assertEquals(2, buffer.readableBytes());
byte[] actual = new byte[2];
buffer.getBytes(0, actual);
assertEquals(1, actual[0]);
assertEquals(2, actual[1]);
}
}
| 7,585 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ConnectionTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty4;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.remoting.api.connection.AbstractConnectionClient;
import org.apache.dubbo.remoting.api.connection.ConnectionManager;
import org.apache.dubbo.remoting.api.connection.MultiplexProtocolConnectionManager;
import org.apache.dubbo.remoting.api.pu.DefaultPuHandler;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
public class ConnectionTest {
private static URL url;
private static NettyPortUnificationServer server;
private static ConnectionManager connectionManager;
@BeforeAll
public static void init() throws Throwable {
int port = NetUtils.getAvailablePort();
url = URL.valueOf("empty://127.0.0.1:" + port + "?foo=bar");
ApplicationModel applicationModel = ApplicationModel.defaultModel();
ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
ConfigManager configManager = new ConfigManager(applicationModel);
configManager.setApplication(applicationConfig);
configManager.getApplication();
applicationModel.setConfigManager(configManager);
url = url.setScopeModel(applicationModel);
ModuleModel moduleModel = applicationModel.getDefaultModule();
url = url.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel);
server = new NettyPortUnificationServer(url, new DefaultPuHandler());
server.bind();
connectionManager = url.getOrDefaultFrameworkModel()
.getExtensionLoader(ConnectionManager.class)
.getExtension(MultiplexProtocolConnectionManager.NAME);
}
@AfterAll
public static void close() {
try {
server.close();
} catch (Throwable e) {
// ignored
}
}
@Test
void testGetChannel() {
final AbstractConnectionClient connectionClient = connectionManager.connect(url, new DefaultPuHandler());
Assertions.assertNotNull(connectionClient);
connectionClient.close();
}
@Test
void testRefCnt0() throws InterruptedException {
final AbstractConnectionClient connectionClient = connectionManager.connect(url, new DefaultPuHandler());
CountDownLatch latch = new CountDownLatch(1);
Assertions.assertNotNull(connectionClient);
connectionClient.addCloseListener(latch::countDown);
connectionClient.release();
latch.await();
Assertions.assertEquals(0, latch.getCount());
}
@Test
void testRefCnt1() {
DefaultPuHandler handler = new DefaultPuHandler();
final AbstractConnectionClient connectionClient = connectionManager.connect(url, handler);
CountDownLatch latch = new CountDownLatch(1);
Assertions.assertNotNull(connectionClient);
connectionManager.connect(url, handler);
connectionClient.addCloseListener(latch::countDown);
connectionClient.release();
Assertions.assertEquals(1, latch.getCount());
connectionClient.close();
}
@Test
void testRefCnt2() throws InterruptedException {
final AbstractConnectionClient connectionClient = connectionManager.connect(url, new DefaultPuHandler());
CountDownLatch latch = new CountDownLatch(1);
connectionClient.retain();
connectionClient.addCloseListener(latch::countDown);
connectionClient.release();
connectionClient.release();
latch.await();
Assertions.assertEquals(0, latch.getCount());
}
@Test
void connectSyncTest() throws Throwable {
int port = NetUtils.getAvailablePort();
URL url = URL.valueOf("empty://127.0.0.1:" + port + "?foo=bar");
NettyPortUnificationServer nettyPortUnificationServer =
new NettyPortUnificationServer(url, new DefaultPuHandler());
nettyPortUnificationServer.bind();
final AbstractConnectionClient connectionClient = connectionManager.connect(url, new DefaultPuHandler());
Assertions.assertTrue(connectionClient.isAvailable());
nettyPortUnificationServer.close();
Assertions.assertFalse(connectionClient.isAvailable());
nettyPortUnificationServer.bind();
// auto reconnect
Assertions.assertTrue(connectionClient.isAvailable());
connectionClient.close();
Assertions.assertFalse(connectionClient.isAvailable());
nettyPortUnificationServer.close();
}
@Test
void testMultiConnect() throws Throwable {
ExecutorService service = Executors.newFixedThreadPool(10);
final CountDownLatch latch = new CountDownLatch(10);
AtomicInteger failedCount = new AtomicInteger(0);
final AbstractConnectionClient connectionClient = connectionManager.connect(url, new DefaultPuHandler());
Runnable runnable = () -> {
try {
Assertions.assertTrue(connectionClient.isAvailable());
} catch (Exception e) {
// ignore
e.printStackTrace();
failedCount.incrementAndGet();
} finally {
latch.countDown();
}
};
for (int i = 0; i < 10; i++) {
service.execute(runnable);
}
latch.await();
Assertions.assertEquals(0, failedCount.get());
service.shutdown();
connectionClient.destroy();
}
}
| 7,586 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/api/MultiplexProtocolConnectionManagerTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty4.api;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.remoting.api.connection.AbstractConnectionClient;
import org.apache.dubbo.remoting.api.connection.ConnectionManager;
import org.apache.dubbo.remoting.api.connection.MultiplexProtocolConnectionManager;
import org.apache.dubbo.remoting.api.pu.DefaultPuHandler;
import org.apache.dubbo.remoting.transport.netty4.NettyPortUnificationServer;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.function.Consumer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
public class MultiplexProtocolConnectionManagerTest {
private static URL url1;
private static URL url2;
private static NettyPortUnificationServer server;
private static ConnectionManager connectionManager;
@BeforeAll
public static void init() throws Throwable {
ApplicationModel applicationModel = ApplicationModel.defaultModel();
ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
ConfigManager configManager = new ConfigManager(applicationModel);
configManager.setApplication(applicationConfig);
configManager.getApplication();
applicationModel.setConfigManager(configManager);
url1 = URL.valueOf("empty://127.0.0.1:8080?foo=bar");
url2 = URL.valueOf("tri://127.0.0.1:8081?foo=bar");
url1 = url1.setScopeModel(applicationModel);
ModuleModel moduleModel = applicationModel.getDefaultModule();
url1 = url1.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel);
url2 = url2.setScopeModel(applicationModel);
url2 = url2.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel);
server = new NettyPortUnificationServer(url1, new DefaultPuHandler());
server.bind();
connectionManager = url1.getOrDefaultFrameworkModel()
.getExtensionLoader(ConnectionManager.class)
.getExtension(MultiplexProtocolConnectionManager.NAME);
}
@AfterAll
public static void close() {
try {
server.close();
} catch (Throwable e) {
// ignored
}
}
@Test
public void testConnect() throws Exception {
final AbstractConnectionClient connectionClient = connectionManager.connect(url1, new DefaultPuHandler());
Assertions.assertNotNull(connectionClient);
Field protocolsField = connectionManager.getClass().getDeclaredField("protocols");
protocolsField.setAccessible(true);
Map protocolMap = (Map) protocolsField.get(connectionManager);
Assertions.assertNotNull(protocolMap.get(url1.getProtocol()));
connectionClient.close();
}
@Test
public void testForEachConnection() throws Throwable {
DefaultPuHandler handler = new DefaultPuHandler();
NettyPortUnificationServer server2 = new NettyPortUnificationServer(url2, handler);
server2.bind();
final AbstractConnectionClient connect1 = connectionManager.connect(url1, handler);
final AbstractConnectionClient connect2 = connectionManager.connect(url2, handler);
Consumer<AbstractConnectionClient> consumer = connection -> {
String protocol = connection.getUrl().getProtocol();
Assertions.assertTrue(protocol.equals("empty") || protocol.equals("tri"));
};
connectionManager.forEachConnection(consumer);
// close connections to avoid impacts on other test cases.
connect1.close();
connect2.close();
try {
server2.close();
} catch (Throwable e) {
// ignored
}
}
}
| 7,587 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/api/EmptyWireProtocol.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty4.api;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.api.ProtocolDetector;
import org.apache.dubbo.remoting.api.WireProtocol;
import org.apache.dubbo.remoting.api.pu.ChannelOperator;
import org.apache.dubbo.remoting.api.ssl.ContextOperator;
public class EmptyWireProtocol implements WireProtocol {
@Override
public ProtocolDetector detector() {
return null;
}
@Override
public void configServerProtocolHandler(URL url, ChannelOperator operator) {}
@Override
public void configClientPipeline(URL url, ChannelOperator operator, ContextOperator contextOperator) {}
@Override
public void close() {}
}
| 7,588 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/api/SingleProtocolConnectionManagerTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty4.api;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.api.connection.AbstractConnectionClient;
import org.apache.dubbo.remoting.api.connection.ConnectionManager;
import org.apache.dubbo.remoting.api.connection.SingleProtocolConnectionManager;
import org.apache.dubbo.remoting.api.pu.DefaultPuHandler;
import org.apache.dubbo.remoting.transport.netty4.NettyConnectionClient;
import org.apache.dubbo.remoting.transport.netty4.NettyPortUnificationServer;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.function.Consumer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
public class SingleProtocolConnectionManagerTest {
private static URL url;
private static NettyPortUnificationServer server;
private static ConnectionManager connectionManager;
@BeforeAll
public static void init() throws Throwable {
int port = NetUtils.getAvailablePort();
url = URL.valueOf("empty://127.0.0.1:" + port + "?foo=bar");
ApplicationModel applicationModel = ApplicationModel.defaultModel();
ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
ConfigManager configManager = new ConfigManager(applicationModel);
configManager.setApplication(applicationConfig);
configManager.getApplication();
applicationModel.setConfigManager(configManager);
url = url.setScopeModel(applicationModel);
ModuleModel moduleModel = applicationModel.getDefaultModule();
url = url.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel);
server = new NettyPortUnificationServer(url, new DefaultPuHandler());
server.bind();
connectionManager = url.getOrDefaultFrameworkModel()
.getExtensionLoader(ConnectionManager.class)
.getExtension(SingleProtocolConnectionManager.NAME);
}
@AfterAll
public static void close() {
try {
server.close();
} catch (Throwable e) {
// ignored
}
}
@Test
public void testConnect() throws Exception {
final NettyConnectionClient connectionClient =
(NettyConnectionClient) connectionManager.connect(url, new DefaultPuHandler());
Assertions.assertNotNull(connectionClient);
Field protocolsField = connectionManager.getClass().getDeclaredField("connections");
protocolsField.setAccessible(true);
Map protocolMap = (Map) protocolsField.get(connectionManager);
Assertions.assertNotNull(protocolMap.get(url.getAddress()));
connectionClient.close();
// Test whether closePromise's listener removes entry
connectionClient.getClosePromise().await();
while (protocolMap.containsKey(url.getAddress())) {}
Assertions.assertNull(protocolMap.get(url.getAddress()));
}
@Test
public void testForEachConnection() throws RemotingException {
AbstractConnectionClient connectionClient = connectionManager.connect(url, new DefaultPuHandler());
{
Consumer<AbstractConnectionClient> consumer1 = connection ->
Assertions.assertEquals("empty", connection.getUrl().getProtocol());
connectionManager.forEachConnection(consumer1);
}
{
Consumer<AbstractConnectionClient> consumer2 = connection ->
Assertions.assertNotEquals("not-empty", connection.getUrl().getProtocol());
connectionManager.forEachConnection(consumer2);
}
connectionClient.close();
}
}
| 7,589 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyPortUnificationTransporter.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty4;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.api.connection.AbstractConnectionClient;
import org.apache.dubbo.remoting.api.connection.ConnectionManager;
import org.apache.dubbo.remoting.api.connection.MultiplexProtocolConnectionManager;
import org.apache.dubbo.remoting.api.pu.AbstractPortUnificationServer;
import org.apache.dubbo.remoting.api.pu.PortUnificationTransporter;
public class NettyPortUnificationTransporter implements PortUnificationTransporter {
public static final String NAME = "netty4";
@Override
public AbstractPortUnificationServer bind(URL url, ChannelHandler handler) throws RemotingException {
return new NettyPortUnificationServer(url, handler);
}
@Override
public AbstractConnectionClient connect(URL url, ChannelHandler handler) throws RemotingException {
ConnectionManager manager = url.getOrDefaultFrameworkModel()
.getExtensionLoader(ConnectionManager.class)
.getExtension(MultiplexProtocolConnectionManager.NAME);
return manager.connect(url, handler);
}
}
| 7,590 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClient.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty4;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.Version;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.resource.GlobalResourceInitializer;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.transport.AbstractClient;
import org.apache.dubbo.remoting.transport.netty4.ssl.SslClientTlsHandler;
import org.apache.dubbo.remoting.transport.netty4.ssl.SslContexts;
import org.apache.dubbo.remoting.utils.UrlUtils;
import java.net.InetSocketAddress;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.proxy.Socks5ProxyHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.EventExecutorGroup;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_CLIENT_CONNECT_TIMEOUT;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CONNECT_PROVIDER;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_DISCONNECT_PROVIDER;
import static org.apache.dubbo.remoting.Constants.DEFAULT_CONNECT_TIMEOUT;
import static org.apache.dubbo.remoting.transport.netty4.NettyEventLoopFactory.eventLoopGroup;
import static org.apache.dubbo.remoting.transport.netty4.NettyEventLoopFactory.socketChannelClass;
/**
* NettyClient.
*/
public class NettyClient extends AbstractClient {
private static final String SOCKS_PROXY_HOST = "socksProxyHost";
private static final String SOCKS_PROXY_PORT = "socksProxyPort";
private static final String DEFAULT_SOCKS_PROXY_PORT = "1080";
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(NettyClient.class);
/**
* netty client bootstrap
*/
private static final GlobalResourceInitializer<EventLoopGroup> EVENT_LOOP_GROUP = new GlobalResourceInitializer<>(
() -> eventLoopGroup(Constants.DEFAULT_IO_THREADS, "NettyClientWorker"),
EventExecutorGroup::shutdownGracefully);
private Bootstrap bootstrap;
/**
* current channel. Each successful invocation of {@link NettyClient#doConnect()} will
* replace this with new channel and close old channel.
* <b>volatile, please copy reference to use.</b>
*/
private volatile Channel channel;
/**
* The constructor of NettyClient.
* It wil init and start netty.
*/
public NettyClient(final URL url, final ChannelHandler handler) throws RemotingException {
// you can customize name and type of client thread pool by THREAD_NAME_KEY and THREADPOOL_KEY in
// CommonConstants.
// the handler will be wrapped: MultiMessageHandler->HeartbeatHandler->handler
super(url, wrapChannelHandler(url, handler));
}
/**
* Init bootstrap
*
* @throws Throwable
*/
@Override
protected void doOpen() throws Throwable {
final NettyClientHandler nettyClientHandler = createNettyClientHandler();
bootstrap = new Bootstrap();
initBootstrap(nettyClientHandler);
}
protected NettyClientHandler createNettyClientHandler() {
return new NettyClientHandler(getUrl(), this);
}
protected void initBootstrap(NettyClientHandler nettyClientHandler) {
bootstrap
.group(EVENT_LOOP_GROUP.get())
.option(ChannelOption.SO_KEEPALIVE, true)
.option(ChannelOption.TCP_NODELAY, true)
.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
// .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getTimeout())
.channel(socketChannelClass());
bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, Math.max(DEFAULT_CONNECT_TIMEOUT, getConnectTimeout()));
SslContext sslContext = SslContexts.buildClientSslContext(getUrl());
bootstrap.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
int heartbeatInterval = UrlUtils.getHeartbeat(getUrl());
if (sslContext != null) {
ch.pipeline().addLast("negotiation", new SslClientTlsHandler(sslContext));
}
NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this);
ch.pipeline() // .addLast("logging",new LoggingHandler(LogLevel.INFO))//for debug
.addLast("decoder", adapter.getDecoder())
.addLast("encoder", adapter.getEncoder())
.addLast("client-idle-handler", new IdleStateHandler(heartbeatInterval, 0, 0, MILLISECONDS))
.addLast("handler", nettyClientHandler);
String socksProxyHost =
ConfigurationUtils.getProperty(getUrl().getOrDefaultApplicationModel(), SOCKS_PROXY_HOST);
if (socksProxyHost != null && !isFilteredAddress(getUrl().getHost())) {
int socksProxyPort = Integer.parseInt(ConfigurationUtils.getProperty(
getUrl().getOrDefaultApplicationModel(), SOCKS_PROXY_PORT, DEFAULT_SOCKS_PROXY_PORT));
Socks5ProxyHandler socks5ProxyHandler =
new Socks5ProxyHandler(new InetSocketAddress(socksProxyHost, socksProxyPort));
ch.pipeline().addFirst(socks5ProxyHandler);
}
}
});
}
private boolean isFilteredAddress(String host) {
// filter local address
return StringUtils.isEquals(NetUtils.getLocalHost(), host) || NetUtils.isLocalHost(host);
}
@Override
protected void doConnect() throws Throwable {
try {
String ipv6Address = NetUtils.getLocalHostV6();
InetSocketAddress connectAddress;
// first try ipv6 address
if (ipv6Address != null && getUrl().getParameter(CommonConstants.IPV6_KEY) != null) {
connectAddress =
new InetSocketAddress(getUrl().getParameter(CommonConstants.IPV6_KEY), getUrl().getPort());
try {
doConnect(connectAddress);
return;
} catch (Throwable throwable) {
// ignore
}
}
connectAddress = getConnectAddress();
doConnect(connectAddress);
} finally {
// just add new valid channel to NettyChannel's cache
if (!isConnected()) {
// future.cancel(true);
}
}
}
private void doConnect(InetSocketAddress serverAddress) throws RemotingException {
long start = System.currentTimeMillis();
ChannelFuture future = bootstrap.connect(serverAddress);
try {
boolean ret = future.awaitUninterruptibly(getConnectTimeout(), MILLISECONDS);
if (ret && future.isSuccess()) {
Channel newChannel = future.channel();
try {
// Close old channel
// copy reference
Channel oldChannel = NettyClient.this.channel;
if (oldChannel != null) {
try {
if (logger.isInfoEnabled()) {
logger.info("Close old netty channel " + oldChannel + " on create new netty channel "
+ newChannel);
}
oldChannel.close();
} finally {
NettyChannel.removeChannelIfDisconnected(oldChannel);
}
}
} finally {
if (NettyClient.this.isClosed()) {
try {
if (logger.isInfoEnabled()) {
logger.info("Close new netty channel " + newChannel + ", because the client closed.");
}
newChannel.close();
} finally {
NettyClient.this.channel = null;
NettyChannel.removeChannelIfDisconnected(newChannel);
}
} else {
NettyClient.this.channel = newChannel;
}
}
} else if (future.cause() != null) {
Throwable cause = future.cause();
// 6-1 Failed to connect to provider server by other reason.
RemotingException remotingException = new RemotingException(
this,
"client(url: " + getUrl() + ") failed to connect to server " + serverAddress
+ ", error message is:" + cause.getMessage(),
cause);
logger.error(
TRANSPORT_FAILED_CONNECT_PROVIDER,
"network disconnected",
"",
"Failed to connect to provider server by other reason.",
cause);
throw remotingException;
} else {
// 6-2 Client-side timeout
RemotingException remotingException = new RemotingException(
this,
"client(url: " + getUrl() + ") failed to connect to server "
+ serverAddress + " client-side timeout "
+ getConnectTimeout() + "ms (elapsed: " + (System.currentTimeMillis() - start)
+ "ms) from netty client "
+ NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion());
logger.error(
TRANSPORT_CLIENT_CONNECT_TIMEOUT,
"provider crash",
"",
"Client-side timeout.",
remotingException);
throw remotingException;
}
} finally {
// just add new valid channel to NettyChannel's cache
if (!isConnected()) {
// future.cancel(true);
}
}
}
@Override
protected void doDisConnect() throws Throwable {
try {
NettyChannel.removeChannelIfDisconnected(channel);
} catch (Throwable t) {
logger.warn(TRANSPORT_FAILED_DISCONNECT_PROVIDER, "", "", t.getMessage());
}
}
@Override
protected void doClose() throws Throwable {
// can't shut down nioEventLoopGroup because the method will be invoked when closing one channel but not a
// client,
// but when and how to close the nioEventLoopGroup ?
// nioEventLoopGroup.shutdownGracefully();
}
@Override
protected org.apache.dubbo.remoting.Channel getChannel() {
Channel c = channel;
if (c == null) {
return null;
}
return NettyChannel.getOrAddChannel(c, getUrl(), this);
}
Channel getNettyChannel() {
return channel;
}
@Override
public boolean canHandleIdle() {
return true;
}
protected EventLoopGroup getEventLoopGroup() {
return EVENT_LOOP_GROUP.get();
}
protected Bootstrap getBootstrap() {
return bootstrap;
}
}
| 7,591 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyTransporter.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty4;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.Client;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.RemotingServer;
import org.apache.dubbo.remoting.Transporter;
/**
* Default extension of {@link Transporter} using netty4.x.
*/
public class NettyTransporter implements Transporter {
public static final String NAME = "netty";
@Override
public RemotingServer bind(URL url, ChannelHandler handler) throws RemotingException {
return new NettyServer(url, handler);
}
@Override
public Client connect(URL url, ChannelHandler handler) throws RemotingException {
return new NettyClient(url, handler);
}
}
| 7,592 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyConnectionHandler.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty4;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.remoting.api.connection.ConnectionHandler;
import java.util.concurrent.TimeUnit;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.EventLoop;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_RECONNECT;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_UNEXPECTED_EXCEPTION;
@ChannelHandler.Sharable
public class NettyConnectionHandler extends ChannelInboundHandlerAdapter implements ConnectionHandler {
private static final ErrorTypeAwareLogger LOGGER =
LoggerFactory.getErrorTypeAwareLogger(NettyConnectionHandler.class);
private static final AttributeKey<Boolean> GO_AWAY_KEY = AttributeKey.valueOf("dubbo_channel_goaway");
private final NettyConnectionClient connectionClient;
public NettyConnectionHandler(NettyConnectionClient connectionClient) {
this.connectionClient = connectionClient;
}
@Override
public void onGoAway(Object channel) {
if (!(channel instanceof Channel)) {
return;
}
Channel nettyChannel = ((Channel) channel);
final Attribute<Boolean> attr = nettyChannel.attr(GO_AWAY_KEY);
if (Boolean.TRUE.equals(attr.get())) {
return;
}
attr.set(true);
if (connectionClient != null) {
connectionClient.onGoaway(nettyChannel);
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(String.format("Channel %s go away ,schedule reconnect", nettyChannel));
}
reconnect(nettyChannel);
}
@Override
public void reconnect(Object channel) {
if (!(channel instanceof Channel)) {
return;
}
Channel nettyChannel = ((Channel) channel);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(String.format("Connection %s is reconnecting, attempt=%d", connectionClient, 1));
}
final EventLoop eventLoop = nettyChannel.eventLoop();
if (connectionClient.isClosed()) {
LOGGER.info("The client has been closed and will not reconnect. ");
return;
}
eventLoop.schedule(
() -> {
try {
connectionClient.doConnect();
} catch (Throwable e) {
LOGGER.error(
TRANSPORT_FAILED_RECONNECT,
"",
"",
"Fail to connect to " + connectionClient.getChannel(),
e);
}
},
1,
TimeUnit.SECONDS);
}
@Override
public void channelActive(ChannelHandlerContext ctx) {
ctx.fireChannelActive();
NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), connectionClient.getUrl(), connectionClient);
if (!connectionClient.isClosed()) {
connectionClient.onConnected(ctx.channel());
if (LOGGER.isInfoEnabled()) {
LOGGER.info("The connection of " + channel.getLocalAddress() + " -> " + channel.getRemoteAddress()
+ " is established.");
}
} else {
ctx.close();
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
LOGGER.warn(TRANSPORT_UNEXPECTED_EXCEPTION, "", "", String.format("Channel error:%s", ctx.channel()), cause);
ctx.close();
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
super.channelInactive(ctx);
final Attribute<Boolean> goawayAttr = ctx.channel().attr(GO_AWAY_KEY);
if (!Boolean.TRUE.equals(goawayAttr.get())) {
reconnect(ctx.channel());
}
}
}
| 7,593 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyConnectionManager.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty4;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.api.connection.AbstractConnectionClient;
import org.apache.dubbo.remoting.api.connection.ConnectionManager;
import java.util.function.Consumer;
public class NettyConnectionManager implements ConnectionManager {
public static final String NAME = "netty4";
@Override
public AbstractConnectionClient connect(URL url, ChannelHandler handler) {
try {
return new NettyConnectionClient(url, handler);
} catch (RemotingException e) {
throw new RuntimeException(e);
}
}
@Override
public void forEachConnection(Consumer<AbstractConnectionClient> connectionConsumer) {
// Do nothing.
}
}
| 7,594 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClientHandler.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty4;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.Version;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.exchange.Request;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.timeout.IdleStateEvent;
import static org.apache.dubbo.common.constants.CommonConstants.HEARTBEAT_EVENT;
/**
* NettyClientHandler
*/
@io.netty.channel.ChannelHandler.Sharable
public class NettyClientHandler extends ChannelDuplexHandler {
private static final Logger logger = LoggerFactory.getLogger(NettyClientHandler.class);
private final URL url;
private final ChannelHandler handler;
public NettyClientHandler(URL url, ChannelHandler handler) {
if (url == null) {
throw new IllegalArgumentException("url == null");
}
if (handler == null) {
throw new IllegalArgumentException("handler == null");
}
this.url = url;
this.handler = handler;
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler);
handler.connected(channel);
if (logger.isInfoEnabled()) {
logger.info("The connection of " + channel.getLocalAddress() + " -> " + channel.getRemoteAddress()
+ " is established.");
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler);
try {
handler.disconnected(channel);
} finally {
NettyChannel.removeChannel(ctx.channel());
}
if (logger.isInfoEnabled()) {
logger.info("The connection of " + channel.getLocalAddress() + " -> " + channel.getRemoteAddress()
+ " is disconnected.");
}
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler);
handler.received(channel, msg);
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
super.write(ctx, msg, promise);
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
// send heartbeat when read idle.
if (evt instanceof IdleStateEvent) {
try {
NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler);
if (logger.isDebugEnabled()) {
logger.debug("IdleStateEvent triggered, send heartbeat to channel " + channel);
}
Request req = new Request();
req.setVersion(Version.getProtocolVersion());
req.setTwoWay(true);
req.setEvent(HEARTBEAT_EVENT);
channel.send(req);
} finally {
NettyChannel.removeChannelIfDisconnected(ctx.channel());
}
} else {
super.userEventTriggered(ctx, evt);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler);
try {
handler.caught(channel, cause);
} finally {
NettyChannel.removeChannelIfDisconnected(ctx.channel());
}
}
}
| 7,595 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyEventLoopFactory.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty4;
import org.apache.dubbo.common.resource.GlobalResourceInitializer;
import org.apache.dubbo.remoting.Constants;
import java.util.concurrent.ThreadFactory;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.Epoll;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollServerSocketChannel;
import io.netty.channel.epoll.EpollSocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.concurrent.DefaultThreadFactory;
import static org.apache.dubbo.common.constants.CommonConstants.OS_LINUX_PREFIX;
import static org.apache.dubbo.common.constants.CommonConstants.OS_NAME_KEY;
import static org.apache.dubbo.remoting.Constants.NETTY_EPOLL_ENABLE_KEY;
public class NettyEventLoopFactory {
/**
* netty client bootstrap
*/
public static final GlobalResourceInitializer<EventLoopGroup> NIO_EVENT_LOOP_GROUP =
new GlobalResourceInitializer<>(
() -> eventLoopGroup(Constants.DEFAULT_IO_THREADS, "NettyClientWorker"),
eventLoopGroup -> eventLoopGroup.shutdownGracefully());
public static EventLoopGroup eventLoopGroup(int threads, String threadFactoryName) {
ThreadFactory threadFactory = new DefaultThreadFactory(threadFactoryName, true);
return shouldEpoll()
? new EpollEventLoopGroup(threads, threadFactory)
: new NioEventLoopGroup(threads, threadFactory);
}
public static Class<? extends SocketChannel> socketChannelClass() {
return shouldEpoll() ? EpollSocketChannel.class : NioSocketChannel.class;
}
public static Class<? extends ServerSocketChannel> serverSocketChannelClass() {
return shouldEpoll() ? EpollServerSocketChannel.class : NioServerSocketChannel.class;
}
private static boolean shouldEpoll() {
if (Boolean.parseBoolean(System.getProperty(NETTY_EPOLL_ENABLE_KEY, "false"))) {
String osName = System.getProperty(OS_NAME_KEY);
return osName.toLowerCase().contains(OS_LINUX_PREFIX) && Epoll.isAvailable();
}
return false;
}
}
| 7,596 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyPortUnificationServerHandler.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty4;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.io.Bytes;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.ssl.CertManager;
import org.apache.dubbo.common.ssl.ProviderCert;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.api.ProtocolDetector;
import org.apache.dubbo.remoting.api.WireProtocol;
import org.apache.dubbo.remoting.buffer.ChannelBuffer;
import org.apache.dubbo.remoting.transport.netty4.ssl.SslContexts;
import javax.net.ssl.SSLSession;
import java.util.List;
import java.util.Map;
import java.util.Set;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.ssl.SslHandshakeCompletionEvent;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR;
public class NettyPortUnificationServerHandler extends ByteToMessageDecoder {
private static final ErrorTypeAwareLogger LOGGER =
LoggerFactory.getErrorTypeAwareLogger(NettyPortUnificationServerHandler.class);
private final URL url;
private final ChannelHandler handler;
private final boolean detectSsl;
private final List<WireProtocol> protocols;
private final Map<String, URL> urlMapper;
private final Map<String, ChannelHandler> handlerMapper;
public NettyPortUnificationServerHandler(
URL url,
boolean detectSsl,
List<WireProtocol> protocols,
ChannelHandler handler,
Map<String, URL> urlMapper,
Map<String, ChannelHandler> handlerMapper) {
this.url = url;
this.protocols = protocols;
this.detectSsl = detectSsl;
this.handler = handler;
this.urlMapper = urlMapper;
this.handlerMapper = handlerMapper;
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
LOGGER.error(
INTERNAL_ERROR,
"unknown error in remoting module",
"",
"Unexpected exception from downstream before protocol detected.",
cause);
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof SslHandshakeCompletionEvent) {
SslHandshakeCompletionEvent handshakeEvent = (SslHandshakeCompletionEvent) evt;
if (handshakeEvent.isSuccess()) {
SSLSession session =
ctx.pipeline().get(SslHandler.class).engine().getSession();
LOGGER.info("TLS negotiation succeed with session: " + session);
} else {
LOGGER.error(
INTERNAL_ERROR,
"",
"",
"TLS negotiation failed when trying to accept new connection.",
handshakeEvent.cause());
ctx.close();
}
}
super.userEventTriggered(ctx, evt);
}
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler);
// Will use the first five bytes to detect a protocol.
// size of telnet command ls is 2 bytes
if (in.readableBytes() < 2) {
return;
}
CertManager certManager =
url.getOrDefaultFrameworkModel().getBeanFactory().getBean(CertManager.class);
ProviderCert providerConnectionConfig =
certManager.getProviderConnectionConfig(url, ctx.channel().remoteAddress());
if (providerConnectionConfig != null && isSsl(in)) {
enableSsl(ctx, providerConnectionConfig);
} else {
for (final WireProtocol protocol : protocols) {
in.markReaderIndex();
ChannelBuffer buf = new NettyBackedChannelBuffer(in);
final ProtocolDetector.Result result = protocol.detector().detect(buf);
in.resetReaderIndex();
switch (result) {
case UNRECOGNIZED:
continue;
case RECOGNIZED:
String protocolName = url.getOrDefaultFrameworkModel()
.getExtensionLoader(WireProtocol.class)
.getExtensionName(protocol);
ChannelHandler localHandler = this.handlerMapper.getOrDefault(protocolName, handler);
URL localURL = this.urlMapper.getOrDefault(protocolName, url);
channel.setUrl(localURL);
NettyConfigOperator operator = new NettyConfigOperator(channel, localHandler);
protocol.configServerProtocolHandler(url, operator);
ctx.pipeline().remove(this);
case NEED_MORE_DATA:
return;
default:
return;
}
}
byte[] preface = new byte[in.readableBytes()];
in.readBytes(preface);
Set<String> supported = url.getApplicationModel()
.getExtensionLoader(WireProtocol.class)
.getSupportedExtensions();
LOGGER.error(
INTERNAL_ERROR,
"unknown error in remoting module",
"",
String.format(
"Can not recognize protocol from downstream=%s . " + "preface=%s protocols=%s",
ctx.channel().remoteAddress(), Bytes.bytes2hex(preface), supported));
// Unknown protocol; discard everything and close the connection.
in.clear();
ctx.close();
}
}
private void enableSsl(ChannelHandlerContext ctx, ProviderCert providerConnectionConfig) {
ChannelPipeline p = ctx.pipeline();
SslContext sslContext = SslContexts.buildServerSslContext(providerConnectionConfig);
p.addLast("ssl", sslContext.newHandler(ctx.alloc()));
p.addLast(
"unificationA",
new NettyPortUnificationServerHandler(url, false, protocols, handler, urlMapper, handlerMapper));
p.remove(this);
}
private boolean isSsl(ByteBuf buf) {
// at least 5 bytes to determine if data is encrypted
if (detectSsl && buf.readableBytes() >= 5) {
return SslHandler.isEncrypted(buf);
}
return false;
}
}
| 7,597 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyConfigOperator.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty4;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.Codec;
import org.apache.dubbo.remoting.Codec2;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.remoting.api.pu.ChannelHandlerPretender;
import org.apache.dubbo.remoting.api.pu.ChannelOperator;
import org.apache.dubbo.remoting.api.pu.DefaultCodec;
import org.apache.dubbo.remoting.transport.codec.CodecAdapter;
import java.util.List;
public class NettyConfigOperator implements ChannelOperator {
private final Channel channel;
private ChannelHandler handler;
public NettyConfigOperator(NettyChannel channel, ChannelHandler handler) {
this.channel = channel;
this.handler = handler;
}
@Override
public void configChannelHandler(List<ChannelHandler> handlerList) {
URL url = channel.getUrl();
Codec2 codec2;
String codecName = url.getParameter(Constants.CODEC_KEY);
if (StringUtils.isEmpty(codecName)) {
// codec extension name must stay the same with protocol name
codecName = url.getProtocol();
}
if (url.getOrDefaultFrameworkModel().getExtensionLoader(Codec2.class).hasExtension(codecName)) {
codec2 = url.getOrDefaultFrameworkModel()
.getExtensionLoader(Codec2.class)
.getExtension(codecName);
} else if (url.getOrDefaultFrameworkModel()
.getExtensionLoader(Codec.class)
.hasExtension(codecName)) {
codec2 = new CodecAdapter(url.getOrDefaultFrameworkModel()
.getExtensionLoader(Codec.class)
.getExtension(codecName));
} else {
codec2 = url.getOrDefaultFrameworkModel()
.getExtensionLoader(Codec2.class)
.getExtension("default");
}
if (!(codec2 instanceof DefaultCodec)) {
((NettyChannel) channel).setCodec(codec2);
NettyCodecAdapter codec = new NettyCodecAdapter(codec2, channel.getUrl(), handler);
((NettyChannel) channel)
.getNioChannel()
.pipeline()
.addLast(codec.getDecoder())
.addLast(codec.getEncoder());
}
for (ChannelHandler handler : handlerList) {
if (handler instanceof ChannelHandlerPretender) {
Object realHandler = ((ChannelHandlerPretender) handler).getRealHandler();
if (realHandler instanceof io.netty.channel.ChannelHandler) {
((NettyChannel) channel).getNioChannel().pipeline().addLast((io.netty.channel.ChannelHandler)
realHandler);
}
}
}
// todo distinguish between client and server channel
if (isClientSide(channel)) {
// todo config client channel handler
} else {
NettyServerHandler sh = new NettyServerHandler(channel.getUrl(), handler);
((NettyChannel) channel).getNioChannel().pipeline().addLast(sh);
}
}
private boolean isClientSide(Channel channel) {
return channel.getUrl().getSide("").equalsIgnoreCase(CommonConstants.CONSUMER);
}
}
| 7,598 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyPortUnificationServer.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty4;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.api.WireProtocol;
import org.apache.dubbo.remoting.api.pu.AbstractPortUnificationServer;
import org.apache.dubbo.remoting.transport.dispatcher.ChannelHandlers;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.util.concurrent.Future;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE;
import static org.apache.dubbo.common.constants.CommonConstants.IO_THREADS_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE;
import static org.apache.dubbo.remoting.Constants.EVENT_LOOP_BOSS_POOL_NAME;
import static org.apache.dubbo.remoting.Constants.EVENT_LOOP_WORKER_POOL_NAME;
/**
* PortUnificationServer.
*/
public class NettyPortUnificationServer extends AbstractPortUnificationServer {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(NettyPortUnificationServer.class);
private final int serverShutdownTimeoutMills;
/**
* netty server bootstrap.
*/
private ServerBootstrap bootstrap;
/**
* the boss channel that receive connections and dispatch these to worker channel.
*/
private io.netty.channel.Channel channel;
private EventLoopGroup bossGroup;
private EventLoopGroup workerGroup;
private final Map<String, Channel> dubboChannels = new ConcurrentHashMap<>();
public NettyPortUnificationServer(URL url, ChannelHandler handler) throws RemotingException {
super(url, ChannelHandlers.wrap(handler, url));
// you can customize name and type of client thread pool by THREAD_NAME_KEY and THREADPOOL_KEY in
// CommonConstants.
// the handler will be wrapped: MultiMessageHandler->HeartbeatHandler->handler
// read config before destroy
serverShutdownTimeoutMills = ConfigurationUtils.getServerShutdownTimeout(getUrl().getOrDefaultModuleModel());
}
@Override
public void addSupportedProtocol(URL url, ChannelHandler handler) {
super.addSupportedProtocol(url, ChannelHandlers.wrap(handler, url));
}
@Override
public void close() {
if (channel != null) {
doClose();
}
}
public void bind() throws Throwable {
if (channel == null) {
doOpen();
}
}
@Override
public void doOpen() throws Throwable {
bootstrap = new ServerBootstrap();
bossGroup = NettyEventLoopFactory.eventLoopGroup(1, EVENT_LOOP_BOSS_POOL_NAME);
workerGroup = NettyEventLoopFactory.eventLoopGroup(
getUrl().getPositiveParameter(IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS),
EVENT_LOOP_WORKER_POOL_NAME);
bootstrap
.group(bossGroup, workerGroup)
.channel(NettyEventLoopFactory.serverSocketChannelClass())
.option(ChannelOption.SO_REUSEADDR, Boolean.TRUE)
.childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE)
.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
// Do not add idle state handler here, because it should be added in the protocol handler.
final ChannelPipeline p = ch.pipeline();
NettyChannelHandler nettyChannelHandler =
new NettyChannelHandler(dubboChannels, getUrl(), NettyPortUnificationServer.this);
NettyPortUnificationServerHandler puHandler = new NettyPortUnificationServerHandler(
getUrl(),
true,
getProtocols(),
NettyPortUnificationServer.this,
getSupportedUrls(),
getSupportedHandlers());
p.addLast("channel-handler", nettyChannelHandler);
p.addLast("negotiation-protocol", puHandler);
}
});
// bind
String bindIp = getUrl().getParameter(Constants.BIND_IP_KEY, getUrl().getHost());
int bindPort = getUrl().getParameter(Constants.BIND_PORT_KEY, getUrl().getPort());
if (getUrl().getParameter(ANYHOST_KEY, false) || NetUtils.isInvalidLocalHost(bindIp)) {
bindIp = ANYHOST_VALUE;
}
InetSocketAddress bindAddress = new InetSocketAddress(bindIp, bindPort);
try {
ChannelFuture channelFuture = bootstrap.bind(bindAddress);
channelFuture.syncUninterruptibly();
channel = channelFuture.channel();
} catch (Throwable t) {
closeBootstrap();
throw t;
}
}
private void closeBootstrap() {
try {
if (bootstrap != null) {
long timeout = ConfigurationUtils.reCalShutdownTime(serverShutdownTimeoutMills);
long quietPeriod = Math.min(2000L, timeout);
Future<?> bossGroupShutdownFuture = bossGroup.shutdownGracefully(quietPeriod, timeout, MILLISECONDS);
Future<?> workerGroupShutdownFuture =
workerGroup.shutdownGracefully(quietPeriod, timeout, MILLISECONDS);
bossGroupShutdownFuture.awaitUninterruptibly(timeout, MILLISECONDS);
workerGroupShutdownFuture.awaitUninterruptibly(timeout, MILLISECONDS);
}
} catch (Throwable e) {
logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e);
}
}
@Override
public void doClose() {
try {
if (channel != null) {
// unbind.
channel.close();
channel = null;
}
} catch (Throwable e) {
logger.warn(TRANSPORT_FAILED_CLOSE, "", "", "Interrupted while shutting down", e);
}
try {
Collection<Channel> channels = getChannels();
if (CollectionUtils.isNotEmpty(channels)) {
for (Channel channel : channels) {
try {
channel.close();
} catch (Throwable e) {
logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e);
}
}
}
} catch (Throwable e) {
logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e);
}
for (WireProtocol protocol : getProtocols()) {
protocol.close();
}
closeBootstrap();
}
@Override
protected int getChannelsSize() {
return dubboChannels.size();
}
public boolean isBound() {
return channel.isActive();
}
@Override
public Collection<Channel> getChannels() {
Collection<Channel> chs = new ArrayList<>(this.dubboChannels.size());
chs.addAll(this.dubboChannels.values());
return chs;
}
@Override
public Channel getChannel(InetSocketAddress remoteAddress) {
return dubboChannels.get(NetUtils.toAddressString(remoteAddress));
}
public InetSocketAddress getLocalAddress() {
return (InetSocketAddress) channel.localAddress();
}
@Override
public boolean canHandleIdle() {
return true;
}
}
| 7,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.