proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
weibocom_motan
|
motan/motan-core/src/main/java/com/weibo/api/motan/rpc/init/InitializationFactory.java
|
AllSpiInitialization
|
init
|
class AllSpiInitialization implements Initializable {
@Override
// find all initilizable spi and init it.
public synchronized void init() {<FILL_FUNCTION_BODY>}
}
|
if (!inited) {
try {
LoggerUtil.info("AllSpiInitialization init.");
ExtensionLoader<Initializable> extensionLoader = ExtensionLoader.getExtensionLoader(Initializable.class);
List<Initializable> allInit = extensionLoader.getExtensions(null);
if (allInit != null && !allInit.isEmpty()) {
for (Initializable initializable : allInit) {
try {
initializable.init();
LoggerUtil.info(initializable.getClass().getName() + " is init.");
} catch (Exception initErr) {
LoggerUtil.error(initializable.getClass().getName() + " init fail!", initErr);
}
}
}
inited = true;
LoggerUtil.info("AllSpiInitialization init finish.");
} catch (Exception e) {
LoggerUtil.error("Initializable spi init fail!", e);;
}
}
| 54
| 235
| 289
|
<no_super_class>
|
weibocom_motan
|
motan/motan-core/src/main/java/com/weibo/api/motan/runtime/CircularRecorder.java
|
CircularRecorder
|
clear
|
class CircularRecorder<T> {
int size;
AtomicInteger index = new AtomicInteger(0);
Entry<?>[] array;
public CircularRecorder(int size) {
this.size = size;
array = new Entry[size];
}
public void add(T t) {
int i = index.getAndIncrement();
if (i < 0) {
i = -i;
}
array[i % size] = new Entry<>(t, System.currentTimeMillis());
}
// return the latest records map. map key is the record timestamp.
@SuppressWarnings("unchecked")
public Map<String, T> getRecords() {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < size; i++) {
Entry<?> temp = array[i];
if (temp != null) {
map.put(i + ":" + temp.timestamp, (T) temp.value);
}
}
return map;
}
public void clear() {<FILL_FUNCTION_BODY>}
static class Entry<T> {
T value;
long timestamp;
public Entry(T value, long timestamp) {
this.value = value;
this.timestamp = timestamp;
}
}
}
|
for (int i = 0; i < size; i++) {
array[i] = null;
}
index.set(0);
| 349
| 40
| 389
|
<no_super_class>
|
weibocom_motan
|
motan/motan-core/src/main/java/com/weibo/api/motan/runtime/GlobalRuntime.java
|
GlobalRuntime
|
getMergedMeta
|
class GlobalRuntime {
// all runtime registries
private static final ConcurrentHashMap<String, Registry> runtimeRegistries = new ConcurrentHashMap<>();
// all runtime exporters
private static final ConcurrentHashMap<String, Exporter<?>> runtimeExporters = new ConcurrentHashMap<>();
// all runtime clusters
private static final ConcurrentHashMap<String, Cluster<?>> runtimeClusters = new ConcurrentHashMap<>();
// all runtime meshClients
private static final ConcurrentHashMap<String, MeshClient> runtimeMeshClients = new ConcurrentHashMap<>();
// all runtime servers
private static final ConcurrentHashMap<String, Server> runtimeServers = new ConcurrentHashMap<>();
private static final Map<String, String> envMeta;
private static final ConcurrentHashMap<String, String> dynamicMeta = new ConcurrentHashMap<>();
static {
envMeta = Collections.unmodifiableMap(MetaUtil._getOriginMetaInfoFromEnv());
}
// add runtime registry
public static void addRegistry(String id, Registry registry) {
runtimeRegistries.put(id, registry);
}
// remove runtime registry
public static Registry removeRegistry(String id) {
return runtimeRegistries.remove(id);
}
public static Map<String, Registry> getRuntimeRegistries() {
return Collections.unmodifiableMap(runtimeRegistries);
}
// add runtime exporter
public static void addExporter(String id, Exporter<?> exporter) {
runtimeExporters.put(id, exporter);
}
// remove runtime exporter
public static Exporter<?> removeExporter(String id) {
return runtimeExporters.remove(id);
}
public static Map<String, Exporter<?>> getRuntimeExporters() {
return Collections.unmodifiableMap(runtimeExporters);
}
// add runtime cluster
public static void addCluster(String id, Cluster<?> cluster) {
runtimeClusters.put(id, cluster);
}
// remove runtime cluster
public static Cluster<?> removeCluster(String id) {
return runtimeClusters.remove(id);
}
public static Map<String, Cluster<?>> getRuntimeClusters() {
return Collections.unmodifiableMap(runtimeClusters);
}
// add runtime mesh client
public static void addMeshClient(String id, MeshClient meshClient) {
runtimeMeshClients.put(id, meshClient);
}
// remove runtime mesh client
public static MeshClient removeMeshClient(String id) {
return runtimeMeshClients.remove(id);
}
public static Map<String, MeshClient> getRuntimeMeshClients() {
return Collections.unmodifiableMap(runtimeMeshClients);
}
// add runtime server
public static void addServer(String id, Server server) {
runtimeServers.put(id, server);
}
// remove runtime server
public static Server removeServer(String id) {
return runtimeServers.remove(id);
}
public static Map<String, Server> getRuntimeServers() {
return Collections.unmodifiableMap(runtimeServers);
}
// return unmodifiable map of envMeta
public static Map<String, String> getEnvMeta() {
return envMeta;
}
// put dynamicMeta
public static void putDynamicMeta(String key, String value) {
dynamicMeta.put(key, value);
}
// remove dynamicMeta
public static void removeDynamicMeta(String key) {
dynamicMeta.remove(key);
}
public static Map<String, String> getDynamicMeta() {
return dynamicMeta;
}
// return a snapshot of current meta, which is a combination of envMeta and dynamicMeta
public static Map<String, String> getMergedMeta() {<FILL_FUNCTION_BODY>}
}
|
Map<String, String> currentMeta = new HashMap<>();
currentMeta.putAll(envMeta);
currentMeta.putAll(dynamicMeta);
return currentMeta;
| 1,024
| 47
| 1,071
|
<no_super_class>
|
weibocom_motan
|
motan/motan-core/src/main/java/com/weibo/api/motan/serialize/BreezeSerialization.java
|
BreezeSerialization
|
readToMotanException
|
class BreezeSerialization implements Serialization {
public static int DEFAULT_BUFFER_SIZE = 1024;
@Override
public byte[] serialize(Object o) throws IOException {
BreezeBuffer buffer = new BreezeBuffer(DEFAULT_BUFFER_SIZE);
if (o instanceof Throwable) { // compatible with motan1 protocol exception encoding mechanism, handle exception classes individually
Serializer serializer = Breeze.getSerializer(o.getClass());
if (serializer != null) {
if (serializer instanceof CommonSerializer) { // non-customized serializer uses adaptive method
writeException((Throwable) o, buffer);
} else {
BreezeWriter.putMessageType(buffer, serializer.getName());
serializer.writeToBuf(o, buffer);
}
} else {
throw new BreezeException("Breeze unsupported type: " + o.getClass());
}
} else {
BreezeWriter.writeObject(buffer, o);
}
buffer.flip();
return buffer.getBytes();
}
@Override
public <T> T deserialize(byte[] bytes, Class<T> clz) throws IOException {
BreezeBuffer buffer = new BreezeBuffer(bytes);
if (Throwable.class.isAssignableFrom(clz)) { // compatible with motan1 protocol exception encoding mechanism, handle exception classes individually
Serializer serializer = Breeze.getSerializer(clz);
if (serializer instanceof CommonSerializer) {
// non-customized serializer uses adaptive method
throw readToMotanException(buffer, clz);
}
}
return BreezeReader.readObject(buffer, clz);
}
@Override
public byte[] serializeMulti(Object[] objects) throws IOException {
BreezeBuffer buffer = new BreezeBuffer(DEFAULT_BUFFER_SIZE);
for (Object o : objects) {
BreezeWriter.writeObject(buffer, o);
}
buffer.flip();
return buffer.getBytes();
}
@Override
public Object[] deserializeMulti(byte[] bytes, Class<?>[] classes) throws IOException {
Object[] objects = new Object[classes.length];
BreezeBuffer buffer = new BreezeBuffer(bytes);
for (int i = 0; i < classes.length; i++) {
objects[i] = BreezeReader.readObject(buffer, classes[i]);
}
return objects;
}
@Override
public int getSerializationNumber() {
return 8;
}
// adapt motan1 exception
private void writeException(Throwable obj, BreezeBuffer buffer) throws BreezeException {
BreezeWriter.putMessageType(buffer, obj.getClass().getName());
BreezeWriter.writeMessage(buffer, () -> TYPE_STRING.writeMessageField(buffer, 1, obj.getMessage()));
}
private MotanServiceException readToMotanException(BreezeBuffer buffer, Class<?> clz) throws BreezeException {<FILL_FUNCTION_BODY>}
}
|
byte bType = buffer.get();
if (bType >= MESSAGE && bType <= DIRECT_REF_MESSAGE_MAX_TYPE) {
final StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("remote exception class : ")
.append(BreezeReader.readMessageName(buffer, bType))
.append(", error message : ");
BreezeReader.readMessage(buffer, (int index) -> {
switch (index) {
case 1:
stringBuilder.append(TYPE_STRING.read(buffer));
break;
default: //skip unknown field
BreezeReader.readObject(buffer, Object.class);
}
});
return new MotanServiceException(stringBuilder.toString());
}
throw new BreezeException("Breeze not support " + bType + " with receiver type:" + clz);
| 782
| 220
| 1,002
|
<no_super_class>
|
weibocom_motan
|
motan/motan-core/src/main/java/com/weibo/api/motan/serialize/DeserializableObject.java
|
DeserializableObject
|
deserializeMulti
|
class DeserializableObject {
private Serialization serialization;
private byte[] objBytes;
public DeserializableObject(Serialization serialization, byte[] objBytes) {
this.serialization = serialization;
this.objBytes = objBytes;
}
public <T> T deserialize(Class<T> clz) throws IOException {
return serialization.deserialize(objBytes, clz);
}
public Object[] deserializeMulti(Class<?>[] paramTypes) throws IOException {<FILL_FUNCTION_BODY>}
}
|
Object[] ret = null;
if (paramTypes != null && paramTypes.length > 0) {
ret = serialization.deserializeMulti(objBytes, paramTypes);
}
return ret;
| 143
| 55
| 198
|
<no_super_class>
|
weibocom_motan
|
motan/motan-core/src/main/java/com/weibo/api/motan/serialize/FastJsonSerialization.java
|
FastJsonSerialization
|
deserializeMulti
|
class FastJsonSerialization implements Serialization {
@Override
public byte[] serialize(Object data) throws IOException {
SerializeWriter out = new SerializeWriter();
JSONSerializer serializer = new JSONSerializer(out);
serializer.config(SerializerFeature.WriteEnumUsingToString, true);
serializer.config(SerializerFeature.WriteClassName, true);
serializer.write(data);
return out.toBytes("UTF-8");
}
@Override
public <T> T deserialize(byte[] data, Class<T> clz) throws IOException {
return JSON.parseObject(new String(data), clz);
}
@Override
public byte[] serializeMulti(Object[] data) throws IOException {
return serialize(data);
}
@Override
public Object[] deserializeMulti(byte[] data, Class<?>[] classes) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public int getSerializationNumber() {
return 2;
}
}
|
List<Object> list = JSON.parseArray(new String(data), classes);
if (list != null) {
return list.toArray();
}
return null;
| 259
| 49
| 308
|
<no_super_class>
|
weibocom_motan
|
motan/motan-core/src/main/java/com/weibo/api/motan/serialize/Hessian2Serialization.java
|
Hessian2Serialization
|
initDefaultSerializerFactory
|
class Hessian2Serialization implements Serialization {
private static volatile SerializerFactory serializerFactory; // global serializer factory
private static final Boolean canSetDeny; // does the current Hessian version support blacklist setting
static {
canSetDeny = checkCompatibility();
serializerFactory = initDefaultSerializerFactory();
}
@Override
public byte[] serialize(Object data) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Hessian2Output out = new Hessian2Output(bos);
out.setSerializerFactory(serializerFactory);
out.writeObject(data);
out.flush();
return bos.toByteArray();
}
@SuppressWarnings("unchecked")
@Override
public <T> T deserialize(byte[] data, Class<T> clz) throws IOException {
Hessian2Input input = new Hessian2Input(new ByteArrayInputStream(data));
input.setSerializerFactory(serializerFactory);
return (T) input.readObject(clz);
}
@Override
public byte[] serializeMulti(Object[] data) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Hessian2Output out = new Hessian2Output(bos);
out.setSerializerFactory(serializerFactory);
for (Object obj : data) {
out.writeObject(obj);
}
out.flush();
return bos.toByteArray();
}
@Override
public Object[] deserializeMulti(byte[] data, Class<?>[] classes) throws IOException {
Hessian2Input input = new Hessian2Input(new ByteArrayInputStream(data));
input.setSerializerFactory(serializerFactory);
Object[] objects = new Object[classes.length];
for (int i = 0; i < classes.length; i++) {
objects[i] = input.readObject(classes[i]);
}
return objects;
}
@Override
public int getSerializationNumber() {
return 0;
}
public static boolean deny(String pattern) {
if (canSetDeny && StringUtils.isNotBlank(pattern)) {
serializerFactory.getClassFactory().deny(pattern);
return true;
}
return false;
}
public static void setSerializerFactory(SerializerFactory serializerFactory) {
Hessian2Serialization.serializerFactory = serializerFactory;
}
private static Boolean checkCompatibility() {
try {
SerializerFactory.class.getMethod("getClassFactory"); // hessian version >= 4.0.51
return true;
} catch (NoSuchMethodException ignore) {
}
return false;
}
private static SerializerFactory initDefaultSerializerFactory() {<FILL_FUNCTION_BODY>}
}
|
SerializerFactory defaultSerializerFactory = new SerializerFactory();
if (canSetDeny) {
try {
ClassFactory classFactory = defaultSerializerFactory.getClassFactory();
classFactory.setWhitelist(false); // blacklist mode
classFactory.deny("ch.qos.logback.core.*");
classFactory.deny("clojure.*");
classFactory.deny("com.caucho.config.types.*");
classFactory.deny("com.caucho.hessian.test.*");
classFactory.deny("com.caucho.naming.*");
classFactory.deny("com.mchange.v2.c3p0.*");
classFactory.deny("com.mysql.jdbc.util.*");
classFactory.deny("com.rometools.rome.feed.*");
classFactory.deny("com.sun.corba.se.*");
classFactory.deny("com.sun.jndi.*");
classFactory.deny("com.sun.org.apache.bcel.*");
classFactory.deny("com.sun.org.apache.xalan.*");
classFactory.deny("com.sun.org.apache.xml.*");
classFactory.deny("com.sun.org.apache.xpath.*");
classFactory.deny("com.sun.rowset.*");
classFactory.deny("com.sun.xml.internal.bind.v2.*");
classFactory.deny("java.awt.*");
classFactory.deny("java.beans.*");
classFactory.deny("java.lang.ProcessBuilder");
classFactory.deny("java.rmi.server.*");
classFactory.deny("java.security.*");
classFactory.deny("java.util.ServiceLoader*");
classFactory.deny("java.util.StringTokenizer");
classFactory.deny("javassist.*");
classFactory.deny("javax.imageio.*");
classFactory.deny("javax.management.*");
classFactory.deny("javax.media.jai.remote.*");
classFactory.deny("javax.naming.*");
classFactory.deny("javax.script.*");
classFactory.deny("javax.sound.sampled.*");
classFactory.deny("javax.swing.*");
classFactory.deny("javax.xml.transform.*");
classFactory.deny("net.bytebuddy.*");
classFactory.deny("oracle.jdbc.*");
classFactory.deny("org.apache.carbondata.core.scan.*");
classFactory.deny("org.apache.commons.beanutils.*");
classFactory.deny("org.apache.commons.dbcp.*");
classFactory.deny("org.apache.ibatis.executor.*");
classFactory.deny("org.apache.ibatis.javassist.*");
classFactory.deny("org.apache.tomcat.dbcp.*");
classFactory.deny("org.apache.wicket.util.*");
classFactory.deny("org.apache.xalan.*");
classFactory.deny("org.apache.xpath.*");
classFactory.deny("org.aspectj.*");
classFactory.deny("org.codehaus.groovy.runtime.*");
classFactory.deny("org.eclipse.jetty.util.*");
classFactory.deny("org.geotools.filter.*");
classFactory.deny("org.springframework.aop.*");
classFactory.deny("org.springframework.beans.factory.*");
classFactory.deny("org.springframework.expression.*");
classFactory.deny("org.springframework.jndi.*");
classFactory.deny("org.springframework.orm.jpa.*");
classFactory.deny("org.springframework.transaction.*");
classFactory.deny("org.yaml.snakeyaml.tokens.*");
classFactory.deny("sun.print.*");
classFactory.deny("sun.rmi.*");
classFactory.deny("sun.swing.*");
} catch (Exception e) {
LoggerUtil.warn("Hessian2Serialization init deny list failed, please upgrade hessian to version 4.0.66 or later", e);
}
}
return defaultSerializerFactory;
| 714
| 1,092
| 1,806
|
<no_super_class>
|
weibocom_motan
|
motan/motan-core/src/main/java/com/weibo/api/motan/switcher/LocalSwitcherService.java
|
LocalSwitcherService
|
putSwitcher
|
class LocalSwitcherService implements SwitcherService {
private static ConcurrentMap<String, Switcher> switchers = new ConcurrentHashMap<String, Switcher>();
private ConcurrentHashMap<String, List<SwitcherListener>> listenerMap = new ConcurrentHashMap<>();
public static Switcher getSwitcherStatic(String name) {
return switchers.get(name);
}
@Override
public Switcher getSwitcher(String name) {
return switchers.get(name);
}
@Override
public List<Switcher> getAllSwitchers() {
return new ArrayList<Switcher>(switchers.values());
}
public static void putSwitcher(Switcher switcher) {<FILL_FUNCTION_BODY>}
@Override
public void initSwitcher(String switcherName, boolean initialValue) {
setValue(switcherName, initialValue);
}
@Override
public boolean isOpen(String switcherName) {
Switcher switcher = switchers.get(switcherName);
return switcher != null && switcher.isOn();
}
@Override
public boolean isOpen(String switcherName, boolean defaultValue) {
Switcher switcher = switchers.get(switcherName);
if (switcher == null) {
switchers.putIfAbsent(switcherName, new Switcher(switcherName, defaultValue));
switcher = switchers.get(switcherName);
}
return switcher.isOn();
}
@Override
public void setValue(String switcherName, boolean value) {
putSwitcher(new Switcher(switcherName, value));
List<SwitcherListener> listeners = listenerMap.get(switcherName);
if(listeners != null) {
for (SwitcherListener listener : listeners) {
listener.onValueChanged(switcherName, value);
}
}
}
@Override
public void registerListener(String switcherName, SwitcherListener listener) {
List listeners = Collections.synchronizedList(new ArrayList());
List preListeners= listenerMap.putIfAbsent(switcherName, listeners);
if (preListeners == null) {
listeners.add(listener);
} else {
preListeners.add(listener);
}
}
@Override
public void unRegisterListener(String switcherName, SwitcherListener listener) {
List<SwitcherListener> listeners = listenerMap.get(switcherName);
if (listener == null) {
// keep empty listeners
listeners.clear();
} else {
listeners.remove(listener);
}
}
}
|
if (switcher == null) {
throw new MotanFrameworkException("LocalSwitcherService addSwitcher Error: switcher is null");
}
switchers.put(switcher.getName(), switcher);
| 685
| 56
| 741
|
<no_super_class>
|
weibocom_motan
|
motan/motan-core/src/main/java/com/weibo/api/motan/transport/AbstractPoolClient.java
|
AbstractPoolClient
|
returnObject
|
class AbstractPoolClient extends AbstractClient {
private static ThreadPoolExecutor executor = new StandardThreadExecutor(1, 300, 20000,
new DefaultThreadFactory("AbstractPoolClient-initPool-", true));
protected static long defaultMinEvictableIdleTimeMillis = (long) 1000 * 60 * 60;//默认链接空闲时间
protected static long defaultSoftMinEvictableIdleTimeMillis = (long) 1000 * 60 * 10;//
protected static long defaultTimeBetweenEvictionRunsMillis = (long) 1000 * 60 * 10;//默认回收周期
protected GenericObjectPool pool;
protected GenericObjectPool.Config poolConfig;
protected PoolableObjectFactory factory;
public AbstractPoolClient(URL url) {
super(url);
}
protected void initPool() {
poolConfig = new GenericObjectPool.Config();
poolConfig.minIdle =
url.getIntParameter(URLParamType.minClientConnection.getName(), URLParamType.minClientConnection.getIntValue());
poolConfig.maxIdle =
url.getIntParameter(URLParamType.maxClientConnection.getName(), URLParamType.maxClientConnection.getIntValue());
poolConfig.maxActive = poolConfig.maxIdle;
poolConfig.maxWait = url.getIntParameter(URLParamType.requestTimeout.getName(), URLParamType.requestTimeout.getIntValue());
poolConfig.lifo = url.getBooleanParameter(URLParamType.poolLifo.getName(), URLParamType.poolLifo.getBooleanValue());
poolConfig.minEvictableIdleTimeMillis = defaultMinEvictableIdleTimeMillis;
poolConfig.softMinEvictableIdleTimeMillis = defaultSoftMinEvictableIdleTimeMillis;
poolConfig.timeBetweenEvictionRunsMillis = defaultTimeBetweenEvictionRunsMillis;
factory = createChannelFactory();
pool = new GenericObjectPool(factory, poolConfig);
if (url.getBooleanParameter(URLParamType.lazyInit.getName(), URLParamType.lazyInit.getBooleanValue())) {
state = ChannelState.ALIVE;
LoggerUtil.debug("motan client will be lazily initialized. url:" + url.getUri());
return;
}
initConnection(url.getBooleanParameter(URLParamType.asyncInitConnection.getName(), URLParamType.asyncInitConnection.getBooleanValue()));
}
protected void initConnection(boolean async) {
if (async) {
try {
executor.execute(() -> {
createConnections();
LoggerUtil.info("async initPool {}. url:{}", state == ChannelState.ALIVE ? "success" : "fail", getUrl().getUri());
});
return;
} catch (Exception e) {
LoggerUtil.error("async initPool task execute fail!" + this.url.getUri(), e);
}
}
createConnections();
}
private void createConnections() {
for (int i = 0; i < poolConfig.minIdle; i++) {
try {
pool.addObject();
state = ChannelState.ALIVE;// if any channel is successfully created, the ALIVE status will be set
} catch (Exception e) {
LoggerUtil.error("NettyClient init pool create connect Error: url=" + url.getUri(), e);
}
}
if (state == ChannelState.UNINIT) {
state = ChannelState.UNALIVE; // set state to UNALIVE, so that the heartbeat can be triggered if failed to create connections.
}
}
protected abstract BasePoolableObjectFactory createChannelFactory();
protected Channel borrowObject() throws Exception {
Channel nettyChannel = (Channel) pool.borrowObject();
if (nettyChannel != null && nettyChannel.isAvailable()) {
return nettyChannel;
}
invalidateObject(nettyChannel);
String errorMsg = this.getClass().getSimpleName() + " borrowObject Error: url=" + url.getUri();
LoggerUtil.error(errorMsg);
throw new MotanServiceException(errorMsg);
}
protected void invalidateObject(Channel nettyChannel) {
if (nettyChannel == null) {
return;
}
try {
pool.invalidateObject(nettyChannel);
} catch (Exception ie) {
LoggerUtil.error(this.getClass().getSimpleName() + " invalidate client Error: url=" + url.getUri(), ie);
}
}
protected void returnObject(Channel channel) {<FILL_FUNCTION_BODY>}
}
|
if (channel == null) {
return;
}
try {
pool.returnObject(channel);
} catch (Exception ie) {
LoggerUtil.error(this.getClass().getSimpleName() + " return client Error: url=" + url.getUri(), ie);
}
| 1,191
| 81
| 1,272
|
<methods>public void <init>(com.weibo.api.motan.rpc.URL) ,public java.net.InetSocketAddress getLocalAddress() ,public java.net.InetSocketAddress getRemoteAddress() ,public void heartbeat(com.weibo.api.motan.rpc.Request) ,public void setLocalAddress(java.net.InetSocketAddress) ,public void setRemoteAddress(java.net.InetSocketAddress) <variables>protected com.weibo.api.motan.codec.Codec codec,protected java.net.InetSocketAddress localAddress,protected java.net.InetSocketAddress remoteAddress,protected volatile com.weibo.api.motan.common.ChannelState state,protected com.weibo.api.motan.rpc.URL url
|
weibocom_motan
|
motan/motan-core/src/main/java/com/weibo/api/motan/transport/AbstractServer.java
|
AbstractServer
|
getRuntimeInfo
|
class AbstractServer implements Server {
protected InetSocketAddress localAddress;
protected InetSocketAddress remoteAddress;
protected URL url;
protected Codec codec;
protected volatile ChannelState state = ChannelState.UNINIT;
public AbstractServer() {
}
public AbstractServer(URL url) {
this.url = url;
this.codec =
ExtensionLoader.getExtensionLoader(Codec.class).getExtension(
url.getParameter(URLParamType.codec.getName(), URLParamType.codec.getValue()));
}
@Override
public InetSocketAddress getLocalAddress() {
return localAddress;
}
@Override
public InetSocketAddress getRemoteAddress() {
return remoteAddress;
}
public void setLocalAddress(InetSocketAddress localAddress) {
this.localAddress = localAddress;
}
public void setRemoteAddress(InetSocketAddress remoteAddress) {
this.remoteAddress = remoteAddress;
}
@Override
public Collection<Channel> getChannels() {
throw new MotanFrameworkException(this.getClass().getName() + " getChannels() method unSupport " + url);
}
@Override
public Channel getChannel(InetSocketAddress remoteAddress) {
throw new MotanFrameworkException(this.getClass().getName() + " getChannel(InetSocketAddress) method unSupport " + url);
}
public void setUrl(URL url) {
this.url = url;
}
public void setCodec(Codec codec) {
this.codec = codec;
}
@Override
public Map<String, Object> getRuntimeInfo() {<FILL_FUNCTION_BODY>}
}
|
Map<String, Object> infos = new HashMap<>();
infos.put(RuntimeInfoKeys.URL_KEY, url.toFullStr());
infos.put(RuntimeInfoKeys.CODEC_KEY, codec.getClass().getSimpleName());
infos.put(RuntimeInfoKeys.STATE_KEY, state.name());
return infos;
| 438
| 91
| 529
|
<no_super_class>
|
weibocom_motan
|
motan/motan-core/src/main/java/com/weibo/api/motan/transport/AbstractSharedPoolClient.java
|
AbstractSharedPoolClient
|
initConnections
|
class AbstractSharedPoolClient extends AbstractClient {
private static final ThreadPoolExecutor EXECUTOR = new StandardThreadExecutor(1, 300, 20000,
new DefaultThreadFactory("AbstractPoolClient-initPool-", true));
private final AtomicInteger idx = new AtomicInteger();
protected SharedObjectFactory factory;
protected ArrayList<Channel> channels;
protected int connections;
protected volatile boolean poolInit; // Whether the connection pool has been initialized
public AbstractSharedPoolClient(URL url) {
super(url);
connections = url.getIntParameter(URLParamType.minClientConnection.getName(), URLParamType.minClientConnection.getIntValue());
if (connections <= 0) {
connections = URLParamType.minClientConnection.getIntValue();
}
}
protected void initPool() {
factory = createChannelFactory();
channels = new ArrayList<>(connections);
for (int i = 0; i < connections; i++) {
channels.add((Channel) factory.makeObject());
}
if (url.getBooleanParameter(URLParamType.lazyInit.getName(), URLParamType.lazyInit.getBooleanValue())) {
state = ChannelState.ALIVE;
LoggerUtil.debug("motan client will be lazily initialized. url:" + url.getUri());
return;
}
initConnections(url.getBooleanParameter(URLParamType.asyncInitConnection.getName(), URLParamType.asyncInitConnection.getBooleanValue()));
}
protected abstract SharedObjectFactory createChannelFactory();
protected void initConnections(boolean async) {<FILL_FUNCTION_BODY>}
private void createConnections() {
for (Channel channel : channels) {
try {
channel.open();
state = ChannelState.ALIVE;// if any channel is successfully created, the ALIVE status will be set
} catch (Exception e) {
LoggerUtil.error("NettyClient init pool create connect Error: url=" + url.getUri(), e);
}
}
poolInit = true;
if (state == ChannelState.UNINIT) {
state = ChannelState.UNALIVE; // set state to UNALIVE, so that the heartbeat can be triggered if failed to create connections.
}
}
protected Channel getChannel() {
if (!poolInit) {
synchronized (this) {
if (!poolInit) {
createConnections();
}
}
}
int index = MathUtil.getNonNegativeRange24bit(idx.getAndIncrement());
Channel channel;
for (int i = index; i < connections + index; i++) {
channel = channels.get(i % connections);
if (!channel.isAvailable()) {
factory.rebuildObject(channel, i != connections + index - 1);
}
if (channel.isAvailable()) {
return channel;
}
}
String errorMsg = this.getClass().getSimpleName() + " getChannel Error: url=" + url.getUri();
throw new MotanServiceException(errorMsg);
}
protected void closeAllChannels() {
if (!CollectionUtil.isEmpty(channels)) {
for (Channel channel : channels) {
channel.close();
}
}
}
}
|
if (async) {
EXECUTOR.execute(() -> {
createConnections();
LoggerUtil.info("async initPool {}. url:{}", state == ChannelState.ALIVE ? "success" : "fail", getUrl().getUri());
});
} else {
createConnections();
}
| 828
| 83
| 911
|
<methods>public void <init>(com.weibo.api.motan.rpc.URL) ,public java.net.InetSocketAddress getLocalAddress() ,public java.net.InetSocketAddress getRemoteAddress() ,public void heartbeat(com.weibo.api.motan.rpc.Request) ,public void setLocalAddress(java.net.InetSocketAddress) ,public void setRemoteAddress(java.net.InetSocketAddress) <variables>protected com.weibo.api.motan.codec.Codec codec,protected java.net.InetSocketAddress localAddress,protected java.net.InetSocketAddress remoteAddress,protected volatile com.weibo.api.motan.common.ChannelState state,protected com.weibo.api.motan.rpc.URL url
|
weibocom_motan
|
motan/motan-core/src/main/java/com/weibo/api/motan/transport/DefaultMeshClient.java
|
DefaultMeshClient
|
call
|
class DefaultMeshClient implements MeshClient {
static final DefaultMeshClient DEFAULT_MESH_CLIENT; // package-private for test
Referer<MeshClient> innerReferer;
private URL meshUrl;
static {
URL defaultUrl = new URL(MotanConstants.PROTOCOL_MOTAN2,
MotanConstants.MESH_DEFAULT_HOST,
MotanConstants.MESH_DEFAULT_PORT,
MeshClient.class.getName(), getDefaultParams());
DEFAULT_MESH_CLIENT = new DefaultMeshClient(defaultUrl); // only create instance, should be initialized before using
}
// global default client
public static DefaultMeshClient getDefault() {
if (!DEFAULT_MESH_CLIENT.isAvailable()) { // lazy init
DEFAULT_MESH_CLIENT.init();
}
return DEFAULT_MESH_CLIENT;
}
/**
* get default mesh client params map
*
* @return a new map contains default mesh client params
*/
public static Map<String, String> getDefaultParams() {
Map<String, String> params = new HashMap<>();
// default value
params.put(URLParamType.meshMPort.getName(), String.valueOf(MotanConstants.MESH_DEFAULT_MPORT));
params.put(URLParamType.application.getName(), MotanConstants.MESH_CLIENT);
params.put(URLParamType.group.getName(), MotanConstants.MESH_CLIENT);
params.put(URLParamType.module.getName(), MotanConstants.MESH_CLIENT);
params.put(URLParamType.codec.getName(), MotanConstants.PROTOCOL_MOTAN2); // motan2 as default
params.put(URLParamType.protocol.getName(), MotanConstants.PROTOCOL_MOTAN2);
params.put(URLParamType.fusingThreshold.getName(), String.valueOf(Integer.MAX_VALUE)); // no fusing
return params;
}
// build without initializing
public DefaultMeshClient(URL url) {
this.meshUrl = url;
}
@Override
public Class getInterface() {
return MeshClient.class;
}
@Override
public Response call(Request request) {
return innerReferer.call(request);
}
@Override
@SuppressWarnings("unchecked")
public <T> T call(Request request, Class<T> returnType) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public ResponseFuture asyncCall(Request request, Class<?> returnType) {
Response response = innerReferer.call(request);
ResponseFuture result;
if (response instanceof ResponseFuture) {
result = (ResponseFuture) response;
result.setReturnType(returnType);
} else {
result = new DefaultResponseFuture(request, 0, innerReferer.getUrl());
if (response.getException() != null) {
result.onFailure(response);
} else {
result.onSuccess(response);
}
result.setReturnType(returnType);
}
return result;
}
@Override
public synchronized void init() {
ProtocolFilterDecorator decorator = new ProtocolFilterDecorator(new MotanV2Protocol());
innerReferer = decorator.decorateRefererFilter(new InnerMeshReferer<>(MeshClient.class, this.meshUrl), this.meshUrl);
innerReferer.init();
}
@Override
public boolean isAvailable() {
return innerReferer != null && innerReferer.isAvailable();
}
@Override
public String desc() {
return "DefaultMeshClient - url:" + innerReferer.getUrl().toFullStr();
}
@Override
public synchronized void destroy() {
if (innerReferer != null) {
innerReferer.destroy();
}
}
@Override
public URL getUrl() {
return meshUrl;
}
static class InnerMeshReferer<MeshClient> extends DefaultRpcReferer<MeshClient> {
public InnerMeshReferer(Class<MeshClient> clz, URL url) {
super(clz, url, url);
}
@Override
public Response call(Request request) {
if (!isAvailable()) {
throw new MotanFrameworkException("DefaultMeshClient call Error: mesh client is not available, url=" + url.getUri()
+ " " + MotanFrameworkUtil.toString(request));
}
return doCall(request);
}
@Override
protected Response doCall(Request request) {
try {
// group will set by MeshClientRefererInvocationHandler
return client.request(request);
} catch (TransportException exception) {
throw new MotanServiceException("DefaultMeshClient call Error: url=" + url.getUri(), exception);
}
}
}
@Override
public Map<String, Object> getRuntimeInfo() {
Map<String, Object> infos = new HashMap<>();
infos.put(RuntimeInfoKeys.URL_KEY, meshUrl.toFullStr());
infos.put(RuntimeInfoKeys.REFERERS_KEY, innerReferer.getRuntimeInfo());
return infos;
}
}
|
Response response = innerReferer.call(request);
T result = null;
if (response != null) {
if (response.getValue() instanceof DeserializableObject) {
try {
result = ((DeserializableObject) response.getValue()).deserialize(returnType);
} catch (IOException e) {
LoggerUtil.error("deserialize response value fail! deserialize type:" + returnType, e);
throw new MotanFrameworkException("deserialize return value fail! deserialize type:" + returnType, e);
}
} else {
result = (T) response.getValue();
}
}
return result;
| 1,362
| 165
| 1,527
|
<no_super_class>
|
weibocom_motan
|
motan/motan-core/src/main/java/com/weibo/api/motan/transport/DefaultProtectedStrategy.java
|
DefaultProtectedStrategy
|
call
|
class DefaultProtectedStrategy implements ProviderProtectedStrategy, StatisticCallback {
protected ConcurrentMap<String, AtomicInteger> requestCounters = new ConcurrentHashMap<>();
protected ConcurrentMap<String, AtomicInteger> rejectCounters = new ConcurrentHashMap<>();
protected AtomicInteger totalCounter = new AtomicInteger(0);
protected AtomicInteger rejectCounter = new AtomicInteger(0);
protected AtomicInteger methodCounter = new AtomicInteger(1);
public DefaultProtectedStrategy() {
StatsUtil.registryStatisticCallback(this);
}
@Override
public void setMethodCounter(AtomicInteger methodCounter) {
this.methodCounter = methodCounter;
}
@Override
public Response call(Request request, Provider<?> provider) {<FILL_FUNCTION_BODY>}
private Response reject(String method, int requestCounter, int totalCounter, int maxThread, Request request) {
String message = "ThreadProtectedRequestRouter reject request: request_method=" + method + " request_counter=" + requestCounter
+ " total_counter=" + totalCounter + " max_thread=" + maxThread;
MotanServiceException exception = new MotanServiceException(message, MotanErrorMsgConstant.SERVICE_REJECT, false);
DefaultResponse response = MotanFrameworkUtil.buildErrorResponse(request, exception);
LoggerUtil.error(exception.getMessage());
incrCounter(method, rejectCounters);
rejectCounter.incrementAndGet();
return response;
}
private int incrCounter(String requestKey, ConcurrentMap<String, AtomicInteger> counters) {
AtomicInteger counter = counters.get(requestKey);
if (counter == null) {
counter = new AtomicInteger(0);
counters.putIfAbsent(requestKey, counter);
counter = counters.get(requestKey);
}
return counter.incrementAndGet();
}
private int decrCounter(String requestKey, ConcurrentMap<String, AtomicInteger> counters) {
AtomicInteger counter = counters.get(requestKey);
if (counter == null) {
return 0;
}
return counter.decrementAndGet();
}
private int incrTotalCounter() {
return totalCounter.incrementAndGet();
}
private int decrTotalCounter() {
return totalCounter.decrementAndGet();
}
public boolean isAllowRequest(int requestCounter, int totalCounter, int maxThread) {
// 方法总数为1或该方法第一次请求, 直接return true
if (methodCounter.get() == 1 || requestCounter == 1) {
return true;
}
// 不简单判断 requestCount > (maxThread / 2) ,因为假如有2或者3个method对外提供,
// 但是只有一个接口很大调用量,而其他接口很空闲,那么这个时候允许单个method的极限到 maxThread * 3 / 4
if (requestCounter > (maxThread / 2) && totalCounter > (maxThread * 3 / 4)) {
return false;
}
// 如果总体线程数超过 maxThread * 3 / 4个,并且对外的method比较多,那么意味着这个时候整体压力比较大,
// 那么这个时候如果单method超过 maxThread * 1 / 4,那么reject
return !(methodCounter.get() >= 4 && totalCounter > (maxThread * 3 / 4) && requestCounter > (maxThread / 4));
}
@Override
public String statisticCallback() {
int count = rejectCounter.getAndSet(0);
if (count > 0) {
StringBuilder builder = new StringBuilder();
builder.append("type:").append("motan").append(" ")
.append("name:").append("reject_request").append(" ")
.append("total_count:").append(totalCounter.get()).append(" ")
.append("reject_count:").append(count).append(" ");
for (Map.Entry<String, AtomicInteger> entry : rejectCounters.entrySet()) {
String key = entry.getKey();
int cnt = entry.getValue().getAndSet(0);
builder.append(key).append("_reject:").append(cnt).append(" ");
}
return builder.toString();
} else {
return null;
}
}
@Override
public Map<String, Object> getRuntimeInfo() {
Map<String, Object> infos = new HashMap<>();
infos.put("totalCount", totalCounter.get());
infos.put("rejectCount", rejectCounter.get());
Map<String, Object> methodRequestCounts = new HashMap<>();
for (Map.Entry<String, AtomicInteger> entry : requestCounters.entrySet()) {
methodRequestCounts.put(entry.getKey(), entry.getValue().get());
}
infos.put("requestCounts", methodRequestCounts);
Map<String, Object> methodRejectCounts = new HashMap<>();
for (Map.Entry<String, AtomicInteger> entry : rejectCounters.entrySet()) {
methodRejectCounts.put(entry.getKey(), entry.getValue().get());
}
infos.put("rejectCounts", methodRejectCounts);
return infos;
}
}
|
// 支持的最大worker thread数
int maxThread = provider.getUrl().getIntParameter(URLParamType.maxWorkerThread.getName(), URLParamType.maxWorkerThread.getIntValue());
String requestKey = MotanFrameworkUtil.getFullMethodString(request);
try {
int requestCounter = incrCounter(requestKey, requestCounters);
int totalCounter = incrTotalCounter();
if (isAllowRequest(requestCounter, totalCounter, maxThread)) {
return provider.call(request);
} else {
// reject request
return reject(request.getInterfaceName() + "." + request.getMethodName(), requestCounter, totalCounter, maxThread, request);
}
} finally {
decrTotalCounter();
decrCounter(requestKey, requestCounters);
}
| 1,349
| 204
| 1,553
|
<no_super_class>
|
weibocom_motan
|
motan/motan-core/src/main/java/com/weibo/api/motan/transport/ProviderMessageRouter.java
|
ProviderMessageRouter
|
handle
|
class ProviderMessageRouter implements MessageHandler {
private static final boolean STRICT_CHECK_GROUP = Boolean.parseBoolean(MotanGlobalConfigUtil.getConfig(MotanConstants.SERVER_END_STRICT_CHECK_GROUP_KEY, "false"));
protected Map<String, Provider<?>> providers = new HashMap<>();
// framework-level general service providers
protected Map<String, Provider<?>> frameworkProviders = new HashMap<>();
// 所有暴露出去的方法计数
// 比如:messageRouter 里面涉及2个Service: ServiceA 有5个public method,ServiceB
// 有10个public method,那么就是15
protected AtomicInteger methodCounter = new AtomicInteger(0);
protected ProviderProtectedStrategy strategy;
public ProviderMessageRouter() {
strategy = ExtensionLoader.getExtensionLoader(ProviderProtectedStrategy.class).getExtension(URLParamType.providerProtectedStrategy.getValue());
strategy.setMethodCounter(methodCounter);
initFrameworkServiceProvider();
}
public ProviderMessageRouter(URL url) {
String providerProtectedStrategy = url.getParameter(URLParamType.providerProtectedStrategy.getName(), URLParamType.providerProtectedStrategy.getValue());
strategy = ExtensionLoader.getExtensionLoader(ProviderProtectedStrategy.class).getExtension(providerProtectedStrategy);
strategy.setMethodCounter(methodCounter);
initFrameworkServiceProvider();
}
public ProviderMessageRouter(Provider<?> provider) {
this();
addProvider(provider);
}
private void initFrameworkServiceProvider() {
// add MetaServiceProvider
frameworkProviders.put(MetaUtil.SERVICE_NAME, MetaServiceProvider.getInstance());
}
@Override
public Object handle(Channel channel, Object message) {<FILL_FUNCTION_BODY>}
protected Response call(Request request, Provider<?> provider) {
try {
return strategy.call(request, provider);
} catch (Exception e) {
return MotanFrameworkUtil.buildErrorResponse(request, new MotanBizException("provider call process error", e));
}
}
private void processLazyDeserialize(Request request, Method method) {
if (method != null && request.getArguments() != null && request.getArguments().length == 1
&& request.getArguments()[0] instanceof DeserializableObject
&& request instanceof DefaultRequest) {
try {
Object[] args = ((DeserializableObject) request.getArguments()[0]).deserializeMulti(method.getParameterTypes());
((DefaultRequest) request).setArguments(args);
} catch (IOException e) {
throw new MotanFrameworkException("deserialize parameters fail: " + request + ", error:" + e.getMessage());
}
}
}
private void fillParamDesc(Request request, Method method) {
if (method != null && StringUtils.isBlank(request.getParamtersDesc())
&& request instanceof DefaultRequest) {
DefaultRequest dr = (DefaultRequest) request;
dr.setParamtersDesc(ReflectUtil.getMethodParamDesc(method));
dr.setMethodName(method.getName());
}
}
public synchronized void addProvider(Provider<?> provider) {
String serviceKey = MotanFrameworkUtil.getServiceKey(provider.getUrl());
if (providers.containsKey(serviceKey)) {
throw new MotanFrameworkException("provider already exist: " + serviceKey);
}
providers.put(serviceKey, provider);
//兼容模式仅作为特殊情况下的兜底,key重复时直接覆盖
providers.put(provider.getUrl().getPath(), provider);
// 获取该service暴露的方法数:
List<Method> methods = ReflectUtil.getPublicMethod(provider.getInterface());
CompressRpcCodec.putMethodSign(provider, methods);// 对所有接口方法生成方法签名。适配方法签名压缩调用方式。
int publicMethodCount = methods.size();
methodCounter.addAndGet(publicMethodCount);
LoggerUtil.info("RequestRouter addProvider: url=" + provider.getUrl() + " all_public_method_count=" + methodCounter.get());
}
public synchronized void removeProvider(Provider<?> provider) {
String serviceKey = MotanFrameworkUtil.getServiceKey(provider.getUrl());
providers.remove(serviceKey);
providers.remove(provider.getUrl().getPath());
List<Method> methods = ReflectUtil.getPublicMethod(provider.getInterface());
int publicMethodCount = methods.size();
methodCounter.getAndSet(methodCounter.get() - publicMethodCount);
LoggerUtil.info("RequestRouter removeProvider: url=" + provider.getUrl() + " all_public_method_count=" + methodCounter.get());
}
public int getPublicMethodCount() {
return methodCounter.get();
}
@Override
public Map<String, Object> getRuntimeInfo() {
Map<String, Object> infos = new HashMap<>();
infos.put(RuntimeInfoKeys.PROVIDER_SIZE_KEY, providers.size());
infos.put(RuntimeInfoKeys.METHOD_COUNT_KEY, methodCounter.get());
Map<String, Object> strategyInfos = strategy.getRuntimeInfo();
if (!CollectionUtil.isEmpty(strategyInfos)) {
infos.put(RuntimeInfoKeys.PROTECT_STRATEGY_KEY, strategyInfos);
}
return infos;
}
}
|
if (channel == null || message == null) {
throw new MotanFrameworkException("RequestRouter handler(channel, message) params is null");
}
if (!(message instanceof Request)) {
throw new MotanFrameworkException("RequestRouter message type not support: " + message.getClass());
}
Request request = (Request) message;
// check whether request to the framework services.
if (request.getAttachments().containsKey(MotanConstants.FRAMEWORK_SERVICE)) {
if (frameworkProviders.containsKey(request.getInterfaceName())) {
//notice: framework provider should handle lazy deserialize params if params is required
return frameworkProviders.get(request.getInterfaceName()).call(request);
}
//throw specific exception to avoid triggering forced fusing on the client side。
throw new MotanServiceException(MotanErrorMsgConstant.SERVICE_NOT_SUPPORT_ERROR);
}
// biz services
String serviceKey = MotanFrameworkUtil.getServiceKey(request);
Provider<?> provider = providers.get(serviceKey);
// compatibility mode will ignore group, find provider by interface name.
if (provider == null && !STRICT_CHECK_GROUP) {
provider = providers.get(request.getInterfaceName());
}
if (provider == null) {
String errInfo = MotanErrorMsgConstant.PROVIDER_NOT_EXIST_EXCEPTION_PREFIX + serviceKey + ", "
+ MotanFrameworkUtil.toStringWithRemoteIp(request);
LoggerUtil.error(errInfo);
return MotanFrameworkUtil.buildErrorResponse(request, new MotanServiceException(errInfo, MotanErrorMsgConstant.PROVIDER_NOT_EXIST));
}
Method method = provider.lookupMethod(request.getMethodName(), request.getParamtersDesc());
fillParamDesc(request, method);
processLazyDeserialize(request, method);
return call(request, provider);
| 1,400
| 491
| 1,891
|
<no_super_class>
|
weibocom_motan
|
motan/motan-core/src/main/java/com/weibo/api/motan/transport/async/MotanAsyncProcessor.java
|
MotanAsyncProcessor
|
writeAsyncClass
|
class MotanAsyncProcessor extends AbstractProcessor {
protected static String ASYNC = MotanConstants.ASYNC_SUFFIX;
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
}
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
@Override
public Set<String> getSupportedAnnotationTypes() {
HashSet<String> types = new HashSet<>();
types.add(MotanAsync.class.getName());
return types;
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver()) {
return true;
}
for (Element elem : roundEnv.getElementsAnnotatedWith(MotanAsync.class)) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "MotanAsyncProcessor will process " + elem);
try {
writeAsyncClass(elem);
processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "MotanAsyncProcessor done for " + elem);
} catch (Exception e) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING,
"MotanAsyncProcessor process " + elem + " fail. exception:" + e.getMessage());
e.printStackTrace();
}
}
return true;
}
private void writeAsyncClass(Element elem) throws Exception {<FILL_FUNCTION_BODY>}
private void addMethods(TypeElement interfaceClazz, TypeSpec.Builder classBuilder) {
List<? extends Element> elements = interfaceClazz.getEnclosedElements();
if (elements != null && !elements.isEmpty()) {
for (Element e : elements) {
if (ElementKind.METHOD.equals(e.getKind())) {
ExecutableElement method = (ExecutableElement) e;
MethodSpec.Builder methodBuilder =
MethodSpec.methodBuilder(method.getSimpleName().toString() + ASYNC)
.addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT).returns(ResponseFuture.class)
.addTypeVariables(getTypeNames(method.getTypeParameters()));
// add method params
List<? extends VariableElement> vars = method.getParameters();
for (VariableElement var : vars) {
methodBuilder.addParameter(ParameterSpec.builder(TypeName.get(var.asType()), var.getSimpleName().toString())
.build());
}
classBuilder.addMethod(methodBuilder.build());
}
}
}
}
private List<TypeVariableName> getTypeNames(List<? extends TypeParameterElement> types) {
List<TypeVariableName> result = new ArrayList<>();
if (types != null && !types.isEmpty()) {
for (TypeParameterElement type : types) {
result.add(TypeVariableName.get(type));
}
}
return result;
}
private void addSuperInterfaceMethods(List<? extends TypeMirror> superInterfaces, TypeSpec.Builder classBuilder) {
if (superInterfaces != null && !superInterfaces.isEmpty()) {
for (TypeMirror tm : superInterfaces) {
try {
if (tm.getKind().equals(TypeKind.DECLARED)) {
TypeElement de = (TypeElement) ((DeclaredType) tm).asElement();
addMethods(de, classBuilder);
addSuperInterfaceMethods(de.getInterfaces(), classBuilder);
}
} catch (Exception e) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING,
"MotanAsyncProcessor process superinterface " + tm.toString() + " fail. exception:" + e.getMessage());
e.printStackTrace();
}
}
}
}
}
|
if (elem.getKind().isInterface()) {
TypeElement interfaceClazz = (TypeElement) elem;
String className = interfaceClazz.getSimpleName().toString();
TypeSpec.Builder classBuilder =
TypeSpec.interfaceBuilder(className + ASYNC).addModifiers(Modifier.PUBLIC)
.addSuperinterface(TypeName.get(elem.asType()));
// add class generic type
classBuilder.addTypeVariables(getTypeNames(interfaceClazz.getTypeParameters()));
// add direct method
addMethods(interfaceClazz, classBuilder);
// add method form superinterface
addSuperInterfaceMethods(interfaceClazz.getInterfaces(), classBuilder);
// write class
JavaFile javaFile =
JavaFile.builder(processingEnv.getElementUtils().getPackageOf(interfaceClazz).getQualifiedName().toString(),
classBuilder.build()).build();
// use StandardLocation.SOURCE_OUTPUT e.g.:target/generated-sources/annotations/
// you can set configuration <generatedSourcesDirectory> in maven-compiler-plugin to change it
javaFile.writeTo(processingEnv.getFiler());
} else {
processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE,
"MotanAsyncProcessor not process, because " + elem + " not a interface.");
}
| 974
| 337
| 1,311
|
<methods>public Iterable<? extends javax.annotation.processing.Completion> getCompletions(javax.lang.model.element.Element, javax.lang.model.element.AnnotationMirror, javax.lang.model.element.ExecutableElement, java.lang.String) ,public Set<java.lang.String> getSupportedAnnotationTypes() ,public Set<java.lang.String> getSupportedOptions() ,public javax.lang.model.SourceVersion getSupportedSourceVersion() ,public synchronized void init(javax.annotation.processing.ProcessingEnvironment) ,public abstract boolean process(Set<? extends javax.lang.model.element.TypeElement>, javax.annotation.processing.RoundEnvironment) <variables>static final boolean $assertionsDisabled,private boolean initialized,protected javax.annotation.processing.ProcessingEnvironment processingEnv
|
weibocom_motan
|
motan/motan-core/src/main/java/com/weibo/api/motan/transport/support/AbstractEndpointFactory.java
|
AbstractEndpointFactory
|
createServer
|
class AbstractEndpointFactory implements EndpointFactory {
/**
* 维持share channel 的service列表
**/
protected final Map<String, Server> ipPort2ServerShareChannel = new HashMap<>();
protected ConcurrentMap<Server, Set<String>> server2UrlsShareChannel = new ConcurrentHashMap<>();
private EndpointManager heartbeatClientEndpointManager;
public AbstractEndpointFactory() {
heartbeatClientEndpointManager = new HeartbeatClientEndpointManager();
heartbeatClientEndpointManager.init();
}
@Override
public Server createServer(URL url, MessageHandler messageHandler) {<FILL_FUNCTION_BODY>}
@Override
public Client createClient(URL url) {
LoggerUtil.info(this.getClass().getSimpleName() + " create client: url={}", url);
return createClient(url, heartbeatClientEndpointManager);
}
@Override
public void safeReleaseResource(Server server, URL url) {
safeReleaseResource(server, url, ipPort2ServerShareChannel, server2UrlsShareChannel);
}
@Override
public void safeReleaseResource(Client client, URL url) {
destroy(client);
}
private <T extends Endpoint> void safeReleaseResource(T endpoint, URL url, Map<String, T> ipPort2Endpoint,
ConcurrentMap<T, Set<String>> endpoint2Urls) {
boolean shareChannel = url.getBooleanParameter(URLParamType.shareChannel.getName(), URLParamType.shareChannel.getBooleanValue());
if (!shareChannel) {
destroy(endpoint);
return;
}
synchronized (ipPort2Endpoint) {
String ipPort = url.getServerPortStr();
String protocolKey = MotanFrameworkUtil.getProtocolKey(url);
if (endpoint != ipPort2Endpoint.get(ipPort)) {
destroy(endpoint);
return;
}
Set<String> urls = endpoint2Urls.get(endpoint);
urls.remove(protocolKey);
if (urls.isEmpty()) {
destroy(endpoint);
ipPort2Endpoint.remove(ipPort);
endpoint2Urls.remove(endpoint);
}
}
}
private <T> void saveEndpoint2Urls(ConcurrentMap<T, Set<String>> map, T endpoint, String namespace) {
Set<String> sets = map.get(endpoint);
if (sets == null) {
sets = new HashSet<>();
sets.add(namespace);
map.putIfAbsent(endpoint, sets); // 规避并发问题,因为有release逻辑存在,所以这里的sets预先add了namespace
sets = map.get(endpoint);
}
sets.add(namespace);
}
private HeartbeatFactory getHeartbeatFactory(URL url) {
String heartbeatFactoryName = url.getParameter(URLParamType.heartbeatFactory.getName(), URLParamType.heartbeatFactory.getValue());
return getHeartbeatFactory(heartbeatFactoryName);
}
private HeartbeatFactory getHeartbeatFactory(String heartbeatFactoryName) {
return ExtensionLoader.getExtensionLoader(HeartbeatFactory.class).getExtension(heartbeatFactoryName);
}
private Client createClient(URL url, EndpointManager endpointManager) {
Client client = innerCreateClient(url);
endpointManager.addEndpoint(client);
return client;
}
private <T extends Endpoint> void destroy(T endpoint) {
if (endpoint instanceof Client) {
endpoint.close();
heartbeatClientEndpointManager.removeEndpoint(endpoint);
} else { // as Server
endpoint.close();
GlobalRuntime.removeServer(endpoint.getUrl().getServerPortStr());
}
}
public Map<String, Server> getShallServerChannels() {
return Collections.unmodifiableMap(ipPort2ServerShareChannel);
}
public EndpointManager getEndpointManager() {
return heartbeatClientEndpointManager;
}
protected abstract Server innerCreateServer(URL url, MessageHandler messageHandler);
protected abstract Client innerCreateClient(URL url);
}
|
messageHandler = getHeartbeatFactory(url).wrapMessageHandler(messageHandler);
synchronized (ipPort2ServerShareChannel) {
String ipPort = url.getServerPortStr();
String protocolKey = MotanFrameworkUtil.getProtocolKey(url);
boolean shareChannel =
url.getBooleanParameter(URLParamType.shareChannel.getName(), URLParamType.shareChannel.getBooleanValue());
if (!shareChannel) { // 独享一个端口
LoggerUtil.info(this.getClass().getSimpleName() + " create no_share_channel server: url={}", url);
if (url.getPort() == 0) { // create new url for random port,the origin url port will be replaced in exporter
url = url.createCopy();
}
// 如果端口已经被使用了,使用该server bind 会有异常
return innerCreateServer(url, messageHandler);
}
LoggerUtil.info(this.getClass().getSimpleName() + " create share_channel server: url={}", url);
Server server = ipPort2ServerShareChannel.get(ipPort);
if (server != null) {
// can't share service channel
if (!MotanFrameworkUtil.checkIfCanShareServiceChannel(server.getUrl(), url)) {
throw new MotanFrameworkException(
"Service export Error: share channel but some config param is different, protocol or codec or serialize or maxContentLength or maxServerConnection or maxWorkerThread or heartbeatFactory, source="
+ server.getUrl() + " target=" + url, MotanErrorMsgConstant.FRAMEWORK_EXPORT_ERROR);
}
saveEndpoint2Urls(server2UrlsShareChannel, server, protocolKey);
return server;
}
url = url.createCopy();
url.setPath(""); // 共享server端口,由于有多个interfaces存在,所以把path设置为空
server = innerCreateServer(url, messageHandler);
ipPort2ServerShareChannel.put(ipPort, server);
saveEndpoint2Urls(server2UrlsShareChannel, server, protocolKey);
GlobalRuntime.addServer(ipPort, server);
return server;
}
| 1,047
| 551
| 1,598
|
<no_super_class>
|
weibocom_motan
|
motan/motan-core/src/main/java/com/weibo/api/motan/transport/support/DefaultRpcHeartbeatFactory.java
|
HeartMessageHandleWrapper
|
handle
|
class HeartMessageHandleWrapper implements MessageHandler {
private MessageHandler messageHandler;
public HeartMessageHandleWrapper(MessageHandler messageHandler) {
this.messageHandler = messageHandler;
}
@Override
public Object handle(Channel channel, Object message) {<FILL_FUNCTION_BODY>}
@Override
public Map<String, Object> getRuntimeInfo() {
return messageHandler.getRuntimeInfo();
}
}
|
if (isHeartbeatRequest(message)) {
Response response = getDefaultHeartbeatResponse(((Request) message).getRequestId());
response.setRpcProtocolVersion(((Request) message).getRpcProtocolVersion());
return response;
}
return messageHandler.handle(channel, message);
| 111
| 78
| 189
|
<no_super_class>
|
weibocom_motan
|
motan/motan-core/src/main/java/com/weibo/api/motan/transport/support/HeartbeatClientEndpointManager.java
|
HeartbeatClientEndpointManager
|
init
|
class HeartbeatClientEndpointManager implements EndpointManager {
private ConcurrentMap<Client, HeartbeatFactory> endpoints = new ConcurrentHashMap<>();
// 一般这个类创建的实例会比较少,如果共享的话,容易“被影响”,如果某个任务阻塞了
private ScheduledExecutorService executorService = null;
@Override
public void init() {<FILL_FUNCTION_BODY>}
@Override
public void destroy() {
executorService.shutdownNow();
}
@Override
public void addEndpoint(Endpoint endpoint) {
if (!(endpoint instanceof Client)) {
throw new MotanFrameworkException("HeartbeatClientEndpointManager addEndpoint Error: class not support " + endpoint.getClass());
}
Client client = (Client) endpoint;
URL url = endpoint.getUrl();
String heartbeatFactoryName = url.getParameter(URLParamType.heartbeatFactory.getName(), URLParamType.heartbeatFactory.getValue());
HeartbeatFactory heartbeatFactory = ExtensionLoader.getExtensionLoader(HeartbeatFactory.class).getExtension(heartbeatFactoryName);
endpoints.put(client, heartbeatFactory);
}
@Override
public void removeEndpoint(Endpoint endpoint) {
endpoints.remove(endpoint);
}
public Set<Client> getClients() {
return Collections.unmodifiableSet(endpoints.keySet());
}
}
|
executorService = Executors.newScheduledThreadPool(1);
executorService.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
for (Map.Entry<Client, HeartbeatFactory> entry : endpoints.entrySet()) {
Client endpoint = entry.getKey();
try {
// 如果节点是存活状态,那么没必要走心跳
if (endpoint.isAvailable()) {
continue;
}
HeartbeatFactory factory = entry.getValue();
endpoint.heartbeat(factory.createRequest());
} catch (Exception e) {
LoggerUtil.error("HeartbeatEndpointManager send heartbeat Error: url=" + endpoint.getUrl().getUri() + ", " + e.getMessage());
}
}
}
}, MotanConstants.HEARTBEAT_PERIOD, MotanConstants.HEARTBEAT_PERIOD, TimeUnit.MILLISECONDS);
ShutDownHook.registerShutdownHook(new Closable() {
@Override
public void close() {
if (!executorService.isShutdown()) {
executorService.shutdown();
}
}
});
| 360
| 303
| 663
|
<no_super_class>
|
weibocom_motan
|
motan/motan-core/src/main/java/com/weibo/api/motan/util/AsyncUtil.java
|
AsyncUtil
|
createResponseFutureForServerEnd
|
class AsyncUtil {
private static final int DEFAULT_ASYNC_TIMEOUT = 1000; // This variable has no practical meaning on the server side, because the server side does not use Future's getValue method to block waiting for results.
private static ThreadPoolExecutor defaultCallbackExecutor = new StandardThreadExecutor(20, 200,
DEFAULT_MAX_IDLE_TIME, MILLISECONDS, 5000,
new DefaultThreadFactory("defaultResponseCallbackPool-", true), new ThreadPoolExecutor.DiscardPolicy());
public static synchronized void setDefaultCallbackExecutor(ThreadPoolExecutor defaultCallbackExecutor) {
if (defaultCallbackExecutor == null) {
throw new MotanFrameworkException("defaultCallbackExecutor cannot be null");
}
ThreadPoolExecutor temp = AsyncUtil.defaultCallbackExecutor;
AsyncUtil.defaultCallbackExecutor = defaultCallbackExecutor;
temp.shutdown();
}
public static ThreadPoolExecutor getDefaultCallbackExecutor() {
return defaultCallbackExecutor;
}
public static ResponseFuture createResponseFutureForServerEnd() {<FILL_FUNCTION_BODY>}
}
|
Request request = RpcContext.getContext().getRequest();
if (request == null) {
throw new MotanFrameworkException("can not get request from RpcContext");
}
return new DefaultResponseFuture(request, DEFAULT_ASYNC_TIMEOUT, request.getAttachment(URLParamType.host.getName()));
| 271
| 81
| 352
|
<no_super_class>
|
weibocom_motan
|
motan/motan-core/src/main/java/com/weibo/api/motan/util/ByteUtil.java
|
ByteUtil
|
gzip
|
class ByteUtil {
public static List<Byte> toList(byte[] array) {
if (array == null) {
return null;
}
List<Byte> list = new ArrayList<Byte>(array.length);
for (byte value : array) {
list.add(value);
}
return list;
}
public static byte[] toArray(List<Byte> list) {
if (list == null) {
return null;
}
byte[] array = new byte[list.size()];
int index = 0;
for (byte value : list) {
array[index++] = value;
}
return array;
}
/**
* 把long类型的value转为8个byte字节,放到byte数组的off开始的位置,高位在前
*
* @param value
* @param bytes
* @param off
*/
public static void long2bytes(long value, byte[] bytes, int off) {
bytes[off + 7] = (byte) value;
bytes[off + 6] = (byte) (value >>> 8);
bytes[off + 5] = (byte) (value >>> 16);
bytes[off + 4] = (byte) (value >>> 24);
bytes[off + 3] = (byte) (value >>> 32);
bytes[off + 2] = (byte) (value >>> 40);
bytes[off + 1] = (byte) (value >>> 48);
bytes[off] = (byte) (value >>> 56);
}
/**
* 把byte数组中off开始的8个字节,转为long类型,高位在前
*
* @param bytes
* @param off
*/
public static long bytes2long(byte[] bytes, int off) {
return ((bytes[off + 7] & 0xFFL)) + ((bytes[off + 6] & 0xFFL) << 8) + ((bytes[off + 5] & 0xFFL) << 16)
+ ((bytes[off + 4] & 0xFFL) << 24) + ((bytes[off + 3] & 0xFFL) << 32) + ((bytes[off + 2] & 0xFFL) << 40)
+ ((bytes[off + 1] & 0xFFL) << 48) + (((long) bytes[off]) << 56);
}
/**
* 把int类型的value转为4个byte字节,放到byte数组的off开始的位置,高位在前
*
* @param value
* @param bytes
* @param off
*/
public static void int2bytes(int value, byte[] bytes, int off) {
bytes[off + 3] = (byte) value;
bytes[off + 2] = (byte) (value >>> 8);
bytes[off + 1] = (byte) (value >>> 16);
bytes[off] = (byte) (value >>> 24);
}
/**
* 把byte数组中off开始的4个字节,转为int类型,高位在前
*
* @param bytes
* @param off
*/
public static int bytes2int(byte[] bytes, int off) {
return ((bytes[off + 3] & 0xFF)) + ((bytes[off + 2] & 0xFF) << 8) + ((bytes[off + 1] & 0xFF) << 16) + ((bytes[off]) << 24);
}
/**
* 把short类型的value转为2个byte字节,放到byte数组的off开始的位置,高位在前
*
* @param value
* @param bytes
* @param off
*/
public static void short2bytes(short value, byte[] bytes, int off) {
bytes[off + 1] = (byte) value;
bytes[off] = (byte) (value >>> 8);
}
/**
* 把byte数组中off开始的2个字节,转为short类型,高位在前
*
* @param b
* @param off
*/
public static short bytes2short(byte[] b, int off) {
return (short) (((b[off + 1] & 0xFF)) + ((b[off] & 0xFF) << 8));
}
public static byte[] gzip(byte[] data) throws IOException {<FILL_FUNCTION_BODY>}
public static byte[] unGzip(byte[] data) throws IOException {
GZIPInputStream gzip = null;
try {
gzip = new GZIPInputStream(new ByteArrayInputStream(data));
byte[] buf = new byte[2048];
int size = -1;
ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length + 1024);
while ((size = gzip.read(buf, 0, buf.length)) != -1) {
bos.write(buf, 0, size);
}
return bos.toByteArray();
} finally {
if (gzip != null) {
gzip.close();
}
}
}
}
|
ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length);
GZIPOutputStream gzip = null;
try {
gzip = new GZIPOutputStream(bos);
gzip.write(data);
gzip.finish();
return bos.toByteArray();
} finally {
if (gzip != null) {
gzip.close();
}
}
| 1,334
| 104
| 1,438
|
<no_super_class>
|
weibocom_motan
|
motan/motan-core/src/main/java/com/weibo/api/motan/util/CollectionUtil.java
|
CollectionUtil
|
shuffleByteArray
|
class CollectionUtil {
@SuppressWarnings("rawtypes")
public static boolean isEmpty(Collection collection) {
return collection == null || collection.isEmpty();
}
@SuppressWarnings("rawtypes")
public static boolean isEmpty(Map map) {
return map == null || map.isEmpty();
}
public static void shuffleByteArray(byte[] array) {<FILL_FUNCTION_BODY>}
}
|
Random rnd = new Random();
for (int i = array.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
// swap
byte b = array[index];
array[index] = array[i];
array[i] = b;
}
| 114
| 85
| 199
|
<no_super_class>
|
weibocom_motan
|
motan/motan-core/src/main/java/com/weibo/api/motan/util/ExceptionUtil.java
|
ExceptionUtil
|
toMessage
|
class ExceptionUtil {
public static final StackTraceElement[] REMOTE_MOCK_STACK = new StackTraceElement[]{new StackTraceElement("remoteClass",
"remoteMethod", "remoteFile", 1)};
/**
* 判定是否是业务方的逻辑抛出的异常
* <p>
* <pre>
* true: 来自业务方的异常
* false: 来自框架本身的异常
* </pre>
*
* @param e
* @return
*/
@Deprecated
public static boolean isBizException(Exception e) {
return e instanceof MotanBizException;
}
public static boolean isBizException(Throwable t) {
return t instanceof MotanBizException;
}
/**
* 是否框架包装过的异常
*
* @param e
* @return
*/
@Deprecated
public static boolean isMotanException(Exception e) {
return e instanceof MotanAbstractException;
}
public static boolean isMotanException(Throwable t) {
return t instanceof MotanAbstractException;
}
public static String toMessage(Exception e) {<FILL_FUNCTION_BODY>}
public static MotanAbstractException fromMessage(String msg) {
if (StringUtils.isNotBlank(msg)) {
try {
JSONObject jsonObject = JSONObject.parseObject(msg);
int type = jsonObject.getIntValue("errtype");
int errcode = jsonObject.getIntValue("errcode");
String errmsg = jsonObject.getString("errmsg");
MotanAbstractException e = null;
switch (type) {
case 1:
e = new MotanServiceException(errmsg, new MotanErrorMsg(errcode, errcode, errmsg));
break;
case 2:
e = new MotanBizException(errmsg, new MotanErrorMsg(errcode, errcode, errmsg));
break;
default:
e = new MotanFrameworkException(errmsg, new MotanErrorMsg(errcode, errcode, errmsg));
}
return e;
} catch (Exception e) {
LoggerUtil.warn("build exception from msg fail. msg:" + msg);
}
}
return null;
}
/**
* 覆盖给定exception的stack信息,server端产生业务异常时调用此类屏蔽掉server端的异常栈。
*
* @param e
*/
public static void setMockStackTrace(Throwable e) {
if (e != null) {
try {
e.setStackTrace(REMOTE_MOCK_STACK);
} catch (Exception e1) {
LoggerUtil.warn("replace remote exception stack fail!" + e1.getMessage());
}
}
}
}
|
JSONObject jsonObject = new JSONObject();
int type = 1;
int code = 500;
String errmsg = null;
if (e instanceof MotanFrameworkException) {
MotanFrameworkException mfe = (MotanFrameworkException) e;
type = 0;
code = mfe.getErrorCode();
errmsg = mfe.getOriginMessage();
} else if (e instanceof MotanServiceException) {
MotanServiceException mse = (MotanServiceException) e;
type = 1;
code = mse.getErrorCode();
errmsg = mse.getOriginMessage();
} else if (e instanceof MotanBizException) {
MotanBizException mbe = (MotanBizException) e;
type = 2;
code = mbe.getErrorCode();
errmsg = mbe.getOriginMessage();
if(mbe.getCause() != null){
errmsg = errmsg + ", org err:" + mbe.getCause().getMessage();
}
} else {
errmsg = e.getMessage();
}
jsonObject.put("errcode", code);
jsonObject.put("errmsg", errmsg);
jsonObject.put("errtype", type);
return jsonObject.toString();
| 723
| 322
| 1,045
|
<no_super_class>
|
weibocom_motan
|
motan/motan-core/src/main/java/com/weibo/api/motan/util/InternalMetricsFactory.java
|
InternalMetricsFactory
|
getRegistryInstance
|
class InternalMetricsFactory {
private static final ConcurrentMap<String, MetricRegistry> getRegistryCache;
private static final MetricRegistry defaultMetricsRegistry;
static {
getRegistryCache = new ConcurrentHashMap<String, MetricRegistry>();
getRegistryCache.put("default", defaultMetricsRegistry = new MetricRegistry());
}
/**
* 指定名字获取所属的实例。
*
* @param name {@link MetricRegistry} 实例的名字。
* @return {@link MetricRegistry} 实例。
*/
public static MetricRegistry getRegistryInstance(String name) {
MetricRegistry instance = getRegistryCache.get(name);
if (instance == null) {
getRegistryCache.putIfAbsent(name, new MetricRegistry());
instance = getRegistryCache.get(name);
}
return instance;
}
/**
* 指定几个名字的关键词,依据 {@link MetricRegistry} 的名字生成规则获取所属的实例。
*
* @param name 关键字。
* @param names 剩余的关键字。
* @return {@link MetricRegistry} 实例。
*/
public static MetricRegistry getRegistryInstance(String name, String... names) {<FILL_FUNCTION_BODY>}
/**
* 指定类类型和几个名字的关键词,依据 {@link MetricRegistry} 的名字生成规则获取所属的实例。
*
* @param clazz 类的类型。
* @param names 关键字。
* @return {@link MetricRegistry} 实例。
*/
public static MetricRegistry getRegistryInstance(Class<?> clazz, String... names) {
final String key = MetricRegistry.name(clazz, names);
MetricRegistry instance = getRegistryCache.get(key);
if (instance == null) {
getRegistryCache.putIfAbsent(key, new MetricRegistry());
instance = getRegistryCache.get(key);
}
return instance;
}
/**
* 返回默认的 {@link MetricRegistry}。
*/
public static MetricRegistry getDefaultMetricsRegistry() {
return defaultMetricsRegistry;
}
/**
* 返回当前注册的全部 {@link MetricRegistry}s。
*/
public static Map<String, MetricRegistry> allRegistries() {
return Collections.unmodifiableMap(getRegistryCache);
}
}
|
final String key = MetricRegistry.name(name, names);
MetricRegistry instance = getRegistryCache.get(key);
if (instance == null) {
getRegistryCache.putIfAbsent(key, new MetricRegistry());
instance = getRegistryCache.get(key);
}
return instance;
| 630
| 81
| 711
|
<no_super_class>
|
weibocom_motan
|
motan/motan-core/src/main/java/com/weibo/api/motan/util/MathUtil.java
|
MathUtil
|
findGCD
|
class MathUtil {
/**
* 针对int类型字符串进行解析,如果存在格式错误,则返回默认值(defaultValue)
* Parse intStr, return defaultValue when numberFormatException occurs
*
* @param intStr
* @param defaultValue
* @return
*/
public static int parseInt(String intStr, int defaultValue) {
try {
return Integer.parseInt(intStr);
} catch (NumberFormatException e) {
LoggerUtil.debug("ParseInt false, for malformed intStr:" + intStr);
return defaultValue;
}
}
/**
* 针对long类型字符串进行解析,如果存在格式错误,则返回默认值(defaultValue)
* Parse longStr, return defaultValue when numberFormatException occurs
*
* @param longStr
* @param defaultValue
* @return
*/
public static long parseLong(String longStr, long defaultValue) {
try {
return Long.parseLong(longStr);
} catch (NumberFormatException e) {
return defaultValue;
}
}
/**
* 通过二进制位操作将originValue转化为非负数:
* 0和正数返回本身
* 负数通过二进制首位取反转化为正数或0(Integer.MIN_VALUE将转换为0)
* return non-negative int value of originValue
*
* @param originValue
* @return positive int
*/
public static int getNonNegative(int originValue) {
if (originValue >= 0) {
return originValue;
}
return 0x7fffffff & originValue;
}
/**
* 通过二进制位操作将originValue转化为非负数:
* 范围在[0-16777215] 之间
*
* @param originValue
* @return
*/
public static int getNonNegativeRange24bit(int originValue) {
return 0x00ffffff & originValue;
}
public static int findGCD(int[] arr) {<FILL_FUNCTION_BODY>}
}
|
int result = arr[0];
for (int i = 1; i < arr.length; i++) {
result = IntMath.gcd(arr[i], result);
if (result == 1) {
return 1;
}
}
return result;
| 567
| 73
| 640
|
<no_super_class>
|
weibocom_motan
|
motan/motan-core/src/main/java/com/weibo/api/motan/util/MeshProxyUtil.java
|
MeshProxyUtil
|
setInitChecked
|
class MeshProxyUtil {
// config keys
private static final String MODE_KEY = "mode"; // proxy type key
private static final String PORT_KEY = "port"; // mesh transport port for client end
private static final String IP_KEY = "ip"; // mesh management port
private static final String PROTOCOL_KEY = "protocol"; // proxy protocol
// config values
private static final String MODE_SERVER = "server"; // 代理server侧流量
private static final String MODE_CLIENT = "client"; // 代理client侧流量
private static final String MODE_ALL = "all"; // 代理双端流量
private static final String DEFAULT_PORT = "0"; // 默认mesh正向代理端口.为0时,MeshRegistry会使用统一默认端口。
private static final String MESH_REGISTRY_NAME = "weibomesh";
private static final Set<String> NOT_PROCESS_REGISTRY_PROTOCOLS = new HashSet<>(Arrays.asList("local", "direct", MESH_REGISTRY_NAME));
private static Boolean initChecked; // 是否可以进行mesh proxy
private static Map<String, String> proxyConfig;
static {
initCheck();
}
/**
* 如果通过环境变量配置了使用Mesh进行代理,则通过把registry转换为MeshRegistry的方式实现服务的代理
*
* @param originRegistryUrls 原始注册中心urls
* @param serviceUrl 具体的rpc服务。
* @param isServerEnd 是否是服务端使用的场景。环境变量可以控制是对client端流量代理,还是server端流量代理,或者全部代理。
* @return 如果配置了环境变量则进行代理,否则原样返回
*/
public static List<URL> processMeshProxy(List<URL> originRegistryUrls, URL serviceUrl, boolean isServerEnd) {
if (initChecked && needProcess(serviceUrl, isServerEnd)) {
try {
List<URL> newRegistryUrls = new ArrayList<>(originRegistryUrls.size());
for (URL url : originRegistryUrls) {
if (NOT_PROCESS_REGISTRY_PROTOCOLS.contains(url.getProtocol())) {
newRegistryUrls.add(url); // 使用原始注册中心
LoggerUtil.info("mesh proxy ignore url:" + serviceUrl.toSimpleString()
+ ", registry: " + url.toSimpleString());
} else {
URL meshRegistryUrl = buildMeshRegistryUrl(url);
newRegistryUrls.add(meshRegistryUrl);
LoggerUtil.info("build mesh proxy registry for url:" + serviceUrl.toSimpleString()
+ ", origin registry:" + url.toSimpleString()
+ ", mesh registry url:" + meshRegistryUrl.toFullStr());
}
}
return newRegistryUrls;
} catch (Exception e) {
LoggerUtil.error("proxy motan fail", e);
}
}
return originRegistryUrls;
}
private static boolean needProcess(URL serviceUrl, boolean isServerEnd) {
// check proxy mode
String mode = proxyConfig.get(MODE_KEY);
if (StringUtils.isBlank(mode)) {// 必须显示指定,不考虑提供默认值
return false;
}
if (!MODE_ALL.equals(mode) && !MODE_SERVER.equals(mode) && !MODE_CLIENT.equals(mode)) {
return false; // 未识别模式不进行处理
}
if (MODE_CLIENT.equals(mode) && isServerEnd) {// client模式下,server端不进行处理
return false;
}
if (MODE_SERVER.equals(mode) && !isServerEnd) {// server模式下,client端不进行处理
return false;
}
// check protocol
if (!"motan2".equals(serviceUrl.getProtocol()) && !"motan".equals(serviceUrl.getProtocol())) {// only support motan&motan2 protocol
return false;
}
String protocol = proxyConfig.get(PROTOCOL_KEY);
if (StringUtils.isNotBlank(protocol) && !protocol.equals(serviceUrl.getProtocol())) {
return false;
}
return true;
}
/**
* 解析mesh proxy 环境变量中的配置
*
* @param meshProxyString 配置字符串格式 "key:value,key:value", 其中value会进行url decode。 例如:"type:server,mport:8002,port:9981"
* @return 解析后的配置
*/
private static Map<String, String> parseProxyConfig(String meshProxyString) {
Map<String, String> proxyConfig = new HashMap<>();
String[] items = meshProxyString.split(",");
for (String item : items) {
String[] values = item.split(":");
if (StringUtils.isNotBlank(values[0])) {// key not empty
String k = values[0].trim();
String v = "";
if (values.length > 1 && StringUtils.isNotBlank(values[1])) {
v = StringTools.urlDecode(values[1].trim());
}
proxyConfig.put(k, v);
LoggerUtil.info("add mesh proxy param: " + k + ":" + v);
}
}
return proxyConfig;
}
private static URL buildMeshRegistryUrl(URL proxyRegistry) {
URL meshRegistryUrl = new URL(MESH_REGISTRY_NAME,
getValue(proxyConfig, IP_KEY, MotanConstants.MESH_DEFAULT_HOST),
Integer.parseInt(getValue(proxyConfig, PORT_KEY, DEFAULT_PORT)),
RegistryService.class.getName()
);
Map<String, String> params = new HashMap<>(proxyConfig);
// put necessary keys
params.put(URLParamType.dynamic.getName(), "true");
params.put(URLParamType.proxyRegistryUrlString.getName(), StringTools.urlEncode(proxyRegistry.toFullStr()));
meshRegistryUrl.addParameters(params);
return meshRegistryUrl;
}
private static String getValue(Map<String, String> configs, String key, String defaultValue) {
String value = configs.get(key);
return StringUtils.isNotBlank(value) ? value : defaultValue;
}
// 检查是否支持mesh proxy
private static void initCheck() {
// check env set
String meshProxyString = System.getenv(MotanConstants.ENV_MESH_PROXY);
if (StringUtils.isNotBlank(meshProxyString)) {
LoggerUtil.info("find MOTAN_MESH_PROXY env, value:" + meshProxyString);
proxyConfig = parseProxyConfig(meshProxyString);
// check MeshRegistry extension
RegistryFactory meshRegistryFactory = ExtensionLoader.getExtensionLoader(RegistryFactory.class).getExtension(MESH_REGISTRY_NAME, false);
if (meshRegistryFactory != null) {
initChecked = true;
LoggerUtil.info("mesh proxy init check passed");
return;
} else {
LoggerUtil.error("can not proxy motan, because MeshRegistry extension not found, maybe the dependency of 'motan-registry-weibomesh' not set in pom");
}
}
initChecked = false;
}
// ---- only for test ----
protected static void reset() {
proxyConfig = null;
initCheck();
}
protected static Map<String, String> getProxyConfig() {
return proxyConfig;
}
protected static boolean setInitChecked(boolean value) {<FILL_FUNCTION_BODY>}
}
|
boolean oldValue = initChecked;
initChecked = value;
return oldValue;
| 1,964
| 27
| 1,991
|
<no_super_class>
|
weibocom_motan
|
motan/motan-core/src/main/java/com/weibo/api/motan/util/MetaUtil.java
|
MetaUtil
|
getRemoteDynamicMeta
|
class MetaUtil {
public static final String defaultEnvMetaPrefix = "META_";
// Check whether the default prefix is configured from the global configuration, if not, use the default prefix
public static final String ENV_META_PREFIX = MotanGlobalConfigUtil.getConfig(MotanConstants.ENV_META_PREFIX_KEY, defaultEnvMetaPrefix);
public static final String SERVICE_NAME = MetaService.class.getName();
public static final String METHOD_NAME = "getDynamicMeta";
private static final Class<?> RETURN_TYPE = Map.class;
private static int cacheExpireSecond = 3; // default cache expire second
private static final int notSupportExpireSecond = 30; // not support expire second
private static final Cache<String, Map<String, String>> metaCache;
private static final Cache<String, Boolean> notSupportCache;
private static final Set<String> notSupportSerializer = Sets.newHashSet("protobuf", "grpc-pb", "grpc-pb-json");
static {
String expireSecond = MotanGlobalConfigUtil.getConfig(MotanConstants.META_CACHE_EXPIRE_SECOND_KEY);
if (StringUtils.isNotBlank(expireSecond)) {
try {
int tempCacheExpireSecond = Integer.parseInt(expireSecond);
if (tempCacheExpireSecond > 0) {
cacheExpireSecond = tempCacheExpireSecond;
}
} catch (Exception ignore) {
}
}
// init caches
metaCache = CacheBuilder.newBuilder().expireAfterWrite(cacheExpireSecond, TimeUnit.SECONDS).build();
notSupportCache = CacheBuilder.newBuilder().expireAfterWrite(notSupportExpireSecond, TimeUnit.SECONDS).build();
}
// just for GlobalRuntime init envMeta and unit test.
// to get runtime meta info, use GlobalRuntime.getEnvMeta(), GlobalRuntime.getDynamicMeta(), GlobalRuntime.getMergedMeta()(equivalent to MetaUtil.getLocalMeta)
public static HashMap<String, String> _getOriginMetaInfoFromEnv() {
HashMap<String, String> metas = new HashMap<>();
for (String key : System.getenv().keySet()) {
if (key.startsWith(MetaUtil.ENV_META_PREFIX)) { // add all the env variables that start with the prefix to the envMeta
metas.put(key, System.getenv(key));
}
}
return metas;
}
// get local meta information
public static Map<String, String> getLocalMeta() {
return GlobalRuntime.getMergedMeta();
}
// get remote meta information by referer.
// host level, only contains dynamic meta info.
// it's a remote RPC call, an exception will be thrown if it fails.
// if a SERVICE_NOT_SUPPORT_ERROR exception is thrown, should not call this method again.
public static Map<String, String> getRefererDynamicMeta(Referer<?> referer) throws ExecutionException {
return metaCache.get(getCacheKey(referer.getUrl()), () -> getRemoteDynamicMeta(referer));
}
@SuppressWarnings("unchecked")
private static Map<String, String> getRemoteDynamicMeta(Referer<?> referer) throws MotanServiceException, IOException {<FILL_FUNCTION_BODY>}
private static boolean isSupport(URL url) {
// check dynamicMeta config, protocol and serializer
if (url.getBooleanParameter(URLParamType.dynamicMeta.getName(), URLParamType.dynamicMeta.getBooleanValue())
&& !notSupportSerializer.contains(url.getParameter(URLParamType.serialize.getName(), ""))
&& (MotanConstants.PROTOCOL_MOTAN.equals(url.getProtocol()) || MotanConstants.PROTOCOL_MOTAN2.equals(url.getProtocol()))) {
return true;
}
notSupportCache.put(getCacheKey(url), true);
return false;
}
private static String getCacheKey(URL url) {
return url.getHost() + ":" + url.getPort();
}
// get remote static meta information from referer url attachments.
// the static meta is init at server start from env.
public static Map<String, String> getRefererStaticMeta(Referer<?> referer) {
Map<String, String> meta = new HashMap<>();
referer.getUrl().getParameters().forEach((k, v) -> {
if (k.startsWith(defaultEnvMetaPrefix)
|| k.startsWith(ENV_META_PREFIX)) {
meta.put(k, v);
}
});
return meta;
}
public static Request buildMetaServiceRequest() {
DefaultRequest request = new DefaultRequest();
request.setRequestId(RequestIdGenerator.getRequestId());
request.setInterfaceName(SERVICE_NAME);
request.setMethodName(METHOD_NAME);
request.setAttachment(MotanConstants.FRAMEWORK_SERVICE, "y");
return request;
}
// get meta value from meta map by keySuffix.
// Try the environment variable prefix search first, and then use the default prefix search.
// if not found, return null.
public static String getMetaValue(Map<String, String> meta, String keySuffix) {
String value = null;
if (meta != null) {
value = meta.get(ENV_META_PREFIX + keySuffix);
if (value == null) {
value = meta.get(defaultEnvMetaPrefix + keySuffix);
}
}
return value;
}
// only for server end to add meta info to url.
public static void addStaticMeta(URL url) {
if (url != null) {
url.getParameters().putAll(GlobalRuntime.getEnvMeta()); // only add static meta
}
}
public static void clearCache() {
metaCache.invalidateAll();
notSupportCache.invalidateAll();
}
}
|
String key = getCacheKey(referer.getUrl());
// if not support meta service, throws the specified exception.
if (notSupportCache.getIfPresent(key) != null
|| !isSupport(referer.getUrl())) {
throw new MotanServiceException(MotanErrorMsgConstant.SERVICE_NOT_SUPPORT_ERROR);
}
if (!referer.isAvailable()) {
throw new MotanServiceException("referer unavailable");
}
try {
Object value = referer.call(buildMetaServiceRequest()).getValue();
if (value instanceof DeserializableObject) {
value = ((DeserializableObject) value).deserialize(RETURN_TYPE);
}
return (Map<String, String>) value;
} catch (Exception e) {
if (e instanceof MotanServiceException) {
MotanServiceException mse = (MotanServiceException) e;
if (mse.getStatus() == MotanErrorMsgConstant.SERVICE_NOT_SUPPORT_ERROR.getStatus()
|| mse.getOriginMessage().contains("provider")) {
// provider-related exceptions are considered unsupported
notSupportCache.put(key, Boolean.TRUE);
throw new MotanServiceException(MotanErrorMsgConstant.SERVICE_NOT_SUPPORT_ERROR);
}
}
throw e;
}
| 1,533
| 339
| 1,872
|
<no_super_class>
|
weibocom_motan
|
motan/motan-core/src/main/java/com/weibo/api/motan/util/MotanClientUtil.java
|
MotanClientUtil
|
buildRequest
|
class MotanClientUtil {
public static Request buildRequest(String interfaceName, String methodName, Object[] arguments) {
return buildRequest(interfaceName, methodName, arguments, null);
}
public static Request buildRequest(String interfaceName, String methodName, Object[] arguments, Map<String, String> attachments) {
return buildRequest(interfaceName, methodName, null, arguments, attachments);
}
public static Request buildRequest(String interfaceName, String methodName, String paramtersDesc, Object[] arguments, Map<String, String> attachments) {<FILL_FUNCTION_BODY>}
}
|
DefaultRequest request = new DefaultRequest();
request.setRequestId(RequestIdGenerator.getRequestId());
request.setInterfaceName(interfaceName);
request.setMethodName(methodName);
request.setArguments(arguments);
if (StringUtils.isNotEmpty(paramtersDesc)) {
request.setParamtersDesc(paramtersDesc);
}
if (attachments != null) {
request.setAttachments(attachments);
}
return request;
| 151
| 125
| 276
|
<no_super_class>
|
weibocom_motan
|
motan/motan-core/src/main/java/com/weibo/api/motan/util/MotanDigestUtil.java
|
MotanDigestUtil
|
getCrc32
|
class MotanDigestUtil {
private static Logger log = LoggerFactory.getLogger(MotanDigestUtil.class);
private static ThreadLocal<CRC32> crc32Provider = new ThreadLocal<CRC32>() {
@Override
protected CRC32 initialValue() {
return new CRC32();
}
};
public static long getCrc32(String str) {<FILL_FUNCTION_BODY>}
public static long getCrc32(byte[] b) {
CRC32 crc = crc32Provider.get();
crc.reset();
crc.update(b);
return crc.getValue();
}
/*
* 全小写32位MD5
*/
public static String md5LowerCase(String plainText) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(plainText.getBytes());
byte b[] = md.digest();
int i;
StringBuilder buf = new StringBuilder("");
for (byte element : b) {
i = element;
if (i < 0) {
i += 256;
}
if (i < 16) {
buf.append("0");
}
buf.append(Integer.toHexString(i));
}
return buf.toString();
} catch (NoSuchAlgorithmException e) {
log.error("md5 digest error!", e);
}
return null;
}
}
|
try {
return getCrc32(str.getBytes(MotanConstants.DEFAULT_CHARACTER));
} catch (UnsupportedEncodingException e) {
log.warn(String.format("Error: getCrc32, str=%s", str), e);
return -1;
}
| 396
| 79
| 475
|
<no_super_class>
|
weibocom_motan
|
motan/motan-core/src/main/java/com/weibo/api/motan/util/MotanGlobalConfigUtil.java
|
MotanGlobalConfigUtil
|
init
|
class MotanGlobalConfigUtil {
public static final String MOTAN_CONFIG_FILE = "motan.properties";
private static final Map<String, String> DEFAULT_CONFIGS = new HashMap<>();
private static volatile GlobalConfig innerGlobalConfig;
static {
init();
}
public static Map<String, String> getDefaultConfigCopy() {
return new HashMap<>(DEFAULT_CONFIGS);
}
public static String getConfig(String key) {
return innerGlobalConfig.getConfig(key);
}
public static String getConfig(String key, String defaultValue) {
return innerGlobalConfig.getConfig(key, defaultValue);
}
public static void putConfig(String key, String value) {
innerGlobalConfig.putConfig(key, value);
}
public static String remove(String key) {
return innerGlobalConfig.remove(key);
}
public static void putConfigs(Map<String, String> configs, boolean override) {
innerGlobalConfig.putConfigs(configs, override);
}
public static ConcurrentHashMap<String, String> getConfigs() {
return innerGlobalConfig.getConfigs();
}
public static GlobalConfig setInnerGlobalConfig(GlobalConfig newConfig) {
if (newConfig != null) {
GlobalConfig oldConfig = innerGlobalConfig;
innerGlobalConfig = newConfig;
return oldConfig;
}
return null;
}
// load default motan configs from the file named "motan.properties" in resources
private static void init() {<FILL_FUNCTION_BODY>}
}
|
URL url = Thread.currentThread().getContextClassLoader().getResource(MOTAN_CONFIG_FILE);
if (url != null) {
try (InputStream is = url.openStream()) {
LoggerUtil.info("load default motan properties from " + url.getPath());
Properties properties = new Properties();
properties.load(is);
for (String key : properties.stringPropertyNames()) {
String value = properties.getProperty(key);
if (StringUtils.isNotBlank(key) && StringUtils.isNotBlank(value)) {
DEFAULT_CONFIGS.put(key.trim(), value.trim());
}
}
} catch (IOException e) {
LoggerUtil.warn("load default motan properties fail. err:" + e.getMessage(), e);
}
}
LoggerUtil.info("default motan properties:" + DEFAULT_CONFIGS);
innerGlobalConfig = new DefaultGlobalConfig();
| 411
| 233
| 644
|
<no_super_class>
|
weibocom_motan
|
motan/motan-core/src/main/java/com/weibo/api/motan/util/NetUtils.java
|
NetUtils
|
getLocalAddressByNetworkInterface
|
class NetUtils {
private static final Logger logger = LoggerFactory.getLogger(NetUtils.class);
public static final String LOCALHOST = "127.0.0.1";
public static final String ANYHOST = "0.0.0.0";
private static volatile InetAddress LOCAL_ADDRESS = null;
private static final Pattern LOCAL_IP_PATTERN = Pattern.compile("127(\\.\\d{1,3}){3}$");
private static final Pattern ADDRESS_PATTERN = Pattern.compile("^\\d{1,3}(\\.\\d{1,3}){3}\\:\\d{1,5}$");
private static final Pattern IP_PATTERN = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3,5}$");
public static boolean isInvalidLocalHost(String host) {
return host == null || host.length() == 0 || host.equalsIgnoreCase("localhost") || host.equals("0.0.0.0")
|| (LOCAL_IP_PATTERN.matcher(host).matches());
}
public static boolean isValidLocalHost(String host) {
return !isInvalidLocalHost(host);
}
/**
* {@link #getLocalAddress(Map)}
*
* @return
*/
public static InetAddress getLocalAddress() {
return getLocalAddress(null);
}
/**
* <pre>
* 查找策略:首先看是否已经查到ip --> 环境变量中指定的ip --> hostname对应的ip --> 根据连接目标端口得到的本地ip --> 轮询网卡
* </pre>
*
* @return local ip
*/
public static InetAddress getLocalAddress(Map<String, Integer> destHostPorts) {
if (LOCAL_ADDRESS != null) {
return LOCAL_ADDRESS;
}
InetAddress localAddress = null;
String ipPrefix = System.getenv(MotanConstants.ENV_MOTAN_IP_PREFIX);
if (StringUtils.isNotBlank(ipPrefix)) { // 环境变量中如果指定了motan使用的ip前缀,则使用与该前缀匹配的网卡ip作为本机ip。
localAddress = getLocalAddressByNetworkInterface(ipPrefix);
LoggerUtil.info("get local address by ip prefix: " + ipPrefix + ", address:" + localAddress);
}
if (!isValidAddress(localAddress)) {
localAddress = getLocalAddressByHostname();
LoggerUtil.info("get local address by hostname, address:" + localAddress);
}
if (!isValidAddress(localAddress)) {
localAddress = getLocalAddressBySocket(destHostPorts);
LoggerUtil.info("get local address by remote host. address:" + localAddress);
}
if (!isValidAddress(localAddress)) {
localAddress = getLocalAddressByNetworkInterface(null);
LoggerUtil.info("get local address from network interface. address:" + localAddress);
}
if (isValidAddress(localAddress)) {
LOCAL_ADDRESS = localAddress;
}
return localAddress;
}
private static InetAddress getLocalAddressByHostname() {
try {
InetAddress localAddress = InetAddress.getLocalHost();
if (isValidAddress(localAddress)) {
return localAddress;
}
} catch (Throwable e) {
logger.warn("Failed to retrieving local address by hostname:" + e);
}
return null;
}
private static InetAddress getLocalAddressBySocket(Map<String, Integer> destHostPorts) {
if (destHostPorts == null || destHostPorts.size() == 0) {
return null;
}
for (Map.Entry<String, Integer> entry : destHostPorts.entrySet()) {
String host = entry.getKey();
int port = entry.getValue();
try {
try (Socket socket = new Socket()) {
SocketAddress addr = new InetSocketAddress(host, port);
socket.connect(addr, 1000);
LoggerUtil.info("get local address from socket. remote host:" + host + ", port:" + port);
return socket.getLocalAddress();
}
} catch (Exception e) {
LoggerUtil.warn(String.format("Failed to retrieving local address by connecting to dest host:port(%s:%s) false, e=%s", host,
port, e));
}
}
return null;
}
private static InetAddress getLocalAddressByNetworkInterface(String prefix) {<FILL_FUNCTION_BODY>}
public static boolean isValidAddress(String address) {
return ADDRESS_PATTERN.matcher(address).matches();
}
public static boolean isValidAddress(InetAddress address) {
if (address == null || address.isLoopbackAddress()) return false;
String name = address.getHostAddress();
return (name != null && !ANYHOST.equals(name) && !LOCALHOST.equals(name) && IP_PATTERN.matcher(name).matches());
}
//return ip to avoid lookup dns
public static String getHostName(SocketAddress socketAddress) {
if (socketAddress == null) {
return null;
}
if (socketAddress instanceof InetSocketAddress) {
InetAddress addr = ((InetSocketAddress) socketAddress).getAddress();
if (addr != null) {
return addr.getHostAddress();
}
}
return null;
}
}
|
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
if (interfaces != null) {
while (interfaces.hasMoreElements()) {
try {
NetworkInterface network = interfaces.nextElement();
Enumeration<InetAddress> addresses = network.getInetAddresses();
while (addresses.hasMoreElements()) {
try {
InetAddress address = addresses.nextElement();
if (isValidAddress(address)) {
if (StringUtils.isBlank(prefix)) {
return address;
}
if (address.getHostAddress().startsWith(prefix)) {
return address;
}
}
} catch (Throwable e) {
logger.warn("Failed to retrieving ip address, " + e.getMessage(), e);
}
}
} catch (Throwable e) {
logger.warn("Failed to retrieving ip address, " + e.getMessage(), e);
}
}
}
} catch (Throwable e) {
logger.warn("Failed to retrieving ip address, " + e.getMessage(), e);
}
return null;
| 1,450
| 289
| 1,739
|
<no_super_class>
|
weibocom_motan
|
motan/motan-core/src/main/java/com/weibo/api/motan/util/RequestIdGenerator.java
|
RequestIdGenerator
|
getRequestId
|
class RequestIdGenerator {
protected static final AtomicLong offset = new AtomicLong(0);
protected static final int BITS = 20;
protected static final long MAX_COUNT_PER_MILLIS = 1 << BITS;
/**
* 获取 requestId
*
* @return
*/
public static long getRequestId() {<FILL_FUNCTION_BODY>}
public static long getRequestIdFromClient() {
// TODO 上下文 requestid
return 0;
}
}
|
long currentTime = System.currentTimeMillis();
long count = offset.incrementAndGet();
while(count >= MAX_COUNT_PER_MILLIS){
synchronized (RequestIdGenerator.class){
if(offset.get() >= MAX_COUNT_PER_MILLIS){
offset.set(0);
}
}
count = offset.incrementAndGet();
}
return (currentTime << BITS) + count;
| 139
| 116
| 255
|
<no_super_class>
|
weibocom_motan
|
motan/motan-core/src/main/java/com/weibo/api/motan/util/StringTools.java
|
StringTools
|
urlDecode
|
class StringTools {
public static int parseInteger(String intStr) {
if (intStr == null) {
return MotanConstants.DEFAULT_INT_VALUE;
}
try {
return Integer.parseInt(intStr);
} catch (NumberFormatException e) {
return MotanConstants.DEFAULT_INT_VALUE;
}
}
public static String urlEncode(String value) {
if (StringUtils.isEmpty(value)) {
return "";
}
try {
return URLEncoder.encode(value, MotanConstants.DEFAULT_CHARACTER);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
public static String urlDecode(String value) {<FILL_FUNCTION_BODY>}
public static String toQueryString(Map<String, String> ps) {
StringBuilder buf = new StringBuilder();
if (ps != null && ps.size() > 0) {
for (Map.Entry<String, String> entry : new TreeMap<>(ps).entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (key != null && key.length() > 0 && value != null && value.length() > 0) {
if (buf.length() > 0) {
buf.append("&");
}
buf.append(key);
buf.append("=");
buf.append(value);
}
}
}
return buf.toString();
}
// 切分string,去重去空
public static Set<String> splitSet(String str, String regex) {
Set<String> result = new HashSet<>();
if (str != null) {
String[] strings = str.split(regex);
for (String s : strings) {
if (StringUtils.isNotBlank(s)) {
result.add(s.trim());
}
}
}
return result;
}
/**
* join strings,skip blank strings and not trim the strings
*/
public static String joinNotBlank(String separator, String... strings) {
return Arrays.stream(strings).filter(StringUtils::isNotBlank).collect(Collectors.joining(separator));
}
}
|
if (StringUtils.isBlank(value)) {
return "";
}
try {
return URLDecoder.decode(value, MotanConstants.DEFAULT_CHARACTER);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e.getMessage(), e);
}
| 586
| 77
| 663
|
<no_super_class>
|
weibocom_motan
|
motan/motan-core/src/main/java/com/weibo/api/motan/util/UrlUtils.java
|
UrlUtils
|
parseURL
|
class UrlUtils {
public static List<URL> parseURLs(String address, Map<String, String> defaults) {
if (address == null || address.length() == 0) {
return null;
}
String[] addresses = MotanConstants.REGISTRY_SPLIT_PATTERN.split(address);
if (addresses == null || addresses.length == 0) {
return null; // here won't be empty
}
List<URL> registries = new ArrayList<URL>();
for (String addr : addresses) {
registries.add(parseURL(addr, defaults));
}
return registries;
}
public static Map<String, String> parseQueryParams(String rawRefer) {
Map<String, String> map = new HashMap<>();
String refer = StringTools.urlDecode(rawRefer);
String[] kvs = MotanConstants.QUERY_PARAM_PATTERN.split(refer);
for (String kv : kvs) {
if (kv != null && kv.contains(MotanConstants.EQUAL_SIGN_SEPERATOR)) {
String[] kvArr = MotanConstants.EQUAL_SIGN_PATTERN.split(kv);
if (kvArr.length == 2) {
map.put(kvArr[0].trim(), kvArr[1].trim());
}
}
}
return map;
}
private static URL parseURL(String address, Map<String, String> defaults) {<FILL_FUNCTION_BODY>}
public static String urlsToString(List<URL> urls) {
StringBuilder sb = new StringBuilder(128);
if (!CollectionUtil.isEmpty(urls)) {
for (URL url : urls) {
sb.append(StringTools.urlEncode(url.toFullStr())).append(MotanConstants.COMMA_SEPARATOR);
}
if (sb.length() > 0) {
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
}
return null;
}
public static List<URL> stringToURLs(String urlsStr) {
String[] urls = MotanConstants.COMMA_SPLIT_PATTERN.split(urlsStr);
List<URL> result = new ArrayList<>();
for (String u : urls) {
URL url = URL.valueOf(StringTools.urlDecode(u));
if (url != null) {
result.add(url);
}
}
return result;
}
}
|
if (address == null || address.length() == 0) {
return null;
}
String[] addresses = MotanConstants.COMMA_SPLIT_PATTERN.split(address);
String url = addresses[0];
String defaultProtocol = defaults == null ? null : defaults.get("protocol");
if (defaultProtocol == null || defaultProtocol.length() == 0) {
defaultProtocol = URLParamType.protocol.getValue();
}
int defaultPort = StringTools.parseInteger(defaults == null ? null : defaults.get("port"));
String defaultPath = defaults == null ? null : defaults.get("path");
Map<String, String> defaultParameters = defaults == null ? null : new HashMap<String, String>(defaults);
if (defaultParameters != null) {
defaultParameters.remove("protocol");
defaultParameters.remove("host");
defaultParameters.remove("port");
defaultParameters.remove("path");
}
URL u = URL.valueOf(url);
u.addParameters(defaults);
boolean changed = false;
String protocol = u.getProtocol();
String host = u.getHost();
int port = u.getPort();
String path = u.getPath();
Map<String, String> parameters = new HashMap<String, String>(u.getParameters());
if ((protocol == null || protocol.length() == 0) && defaultProtocol != null && defaultProtocol.length() > 0) {
changed = true;
protocol = defaultProtocol;
}
if (port <= 0) {
if (defaultPort > 0) {
changed = true;
port = defaultPort;
} else {
changed = true;
port = MotanConstants.DEFAULT_INT_VALUE;
}
}
if (path == null || path.length() == 0) {
if (defaultPath != null && defaultPath.length() > 0) {
changed = true;
path = defaultPath;
}
}
if (defaultParameters != null && defaultParameters.size() > 0) {
for (Map.Entry<String, String> entry : defaultParameters.entrySet()) {
String key = entry.getKey();
String defaultValue = entry.getValue();
if (defaultValue != null && defaultValue.length() > 0) {
String value = parameters.get(key);
if (value == null || value.length() == 0) {
changed = true;
parameters.put(key, defaultValue);
}
}
}
}
if (changed) {
u = new URL(protocol, host, port, path, parameters);
}
return u;
| 668
| 660
| 1,328
|
<no_super_class>
|
weibocom_motan
|
motan/motan-demo/motan-demo-api/src/main/java/com/weibo/motan/demo/service/model/User.java
|
User
|
toString
|
class User implements Serializable {
private int id;
private String name;
public User() {
}
public User(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "User{" +
"id=" + id +
", name='" + name + '\'' +
'}';
| 168
| 36
| 204
|
<no_super_class>
|
weibocom_motan
|
motan/motan-demo/motan-demo-api/src/main/java/io/grpc/examples/routeguide/Point.java
|
Builder
|
clear
|
class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:routeguide.Point)
io.grpc.examples.routeguide.PointOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return io.grpc.examples.routeguide.RouteGuideProto.internal_static_routeguide_Point_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return io.grpc.examples.routeguide.RouteGuideProto.internal_static_routeguide_Point_fieldAccessorTable
.ensureFieldAccessorsInitialized(
io.grpc.examples.routeguide.Point.class, io.grpc.examples.routeguide.Point.Builder.class);
}
// Construct using io.grpc.examples.routeguide.Point.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
public Builder clear() {<FILL_FUNCTION_BODY>}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return io.grpc.examples.routeguide.RouteGuideProto.internal_static_routeguide_Point_descriptor;
}
public io.grpc.examples.routeguide.Point getDefaultInstanceForType() {
return io.grpc.examples.routeguide.Point.getDefaultInstance();
}
public io.grpc.examples.routeguide.Point build() {
io.grpc.examples.routeguide.Point result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public io.grpc.examples.routeguide.Point buildPartial() {
io.grpc.examples.routeguide.Point result = new io.grpc.examples.routeguide.Point(this);
result.latitude_ = latitude_;
result.longitude_ = longitude_;
onBuilt();
return result;
}
public Builder clone() {
return (Builder) super.clone();
}
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
Object value) {
return (Builder) super.setField(field, value);
}
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
Object value) {
return (Builder) super.addRepeatedField(field, value);
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof io.grpc.examples.routeguide.Point) {
return mergeFrom((io.grpc.examples.routeguide.Point)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(io.grpc.examples.routeguide.Point other) {
if (other == io.grpc.examples.routeguide.Point.getDefaultInstance()) return this;
if (other.getLatitude() != 0) {
setLatitude(other.getLatitude());
}
if (other.getLongitude() != 0) {
setLongitude(other.getLongitude());
}
onChanged();
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
io.grpc.examples.routeguide.Point parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (io.grpc.examples.routeguide.Point) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int latitude_ ;
/**
* <code>optional int32 latitude = 1;</code>
*/
public int getLatitude() {
return latitude_;
}
/**
* <code>optional int32 latitude = 1;</code>
*/
public Builder setLatitude(int value) {
latitude_ = value;
onChanged();
return this;
}
/**
* <code>optional int32 latitude = 1;</code>
*/
public Builder clearLatitude() {
latitude_ = 0;
onChanged();
return this;
}
private int longitude_ ;
/**
* <code>optional int32 longitude = 2;</code>
*/
public int getLongitude() {
return longitude_;
}
/**
* <code>optional int32 longitude = 2;</code>
*/
public Builder setLongitude(int value) {
longitude_ = value;
onChanged();
return this;
}
/**
* <code>optional int32 longitude = 2;</code>
*/
public Builder clearLongitude() {
longitude_ = 0;
onChanged();
return this;
}
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return this;
}
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return this;
}
// @@protoc_insertion_point(builder_scope:routeguide.Point)
}
|
super.clear();
latitude_ = 0;
longitude_ = 0;
return this;
| 1,735
| 32
| 1,767
|
<no_super_class>
|
weibocom_motan
|
motan/motan-demo/motan-demo-api/src/main/java/io/grpc/examples/routeguide/RouteGuideGrpc.java
|
RouteGuideImplBase
|
bindService
|
class RouteGuideImplBase implements io.grpc.BindableService {
/**
* <pre>
* A simple RPC.
* Obtains the feature at a given position.
* A feature with an empty name is returned if there's no feature at the given
* position.
* </pre>
*/
public void getFeature(io.grpc.examples.routeguide.Point request,
io.grpc.stub.StreamObserver<io.grpc.examples.routeguide.Feature> responseObserver) {
asyncUnimplementedUnaryCall(METHOD_GET_FEATURE, responseObserver);
}
/**
* <pre>
* A server-to-client streaming RPC.
* Obtains the Features available within the given Rectangle. Results are
* streamed rather than returned at once (e.g. in a response message with a
* repeated field), as the rectangle may cover a large area and contain a
* huge number of features.
* </pre>
*/
public void listFeatures(io.grpc.examples.routeguide.Rectangle request,
io.grpc.stub.StreamObserver<io.grpc.examples.routeguide.Feature> responseObserver) {
asyncUnimplementedUnaryCall(METHOD_LIST_FEATURES, responseObserver);
}
/**
* <pre>
* A client-to-server streaming RPC.
* Accepts a stream of Points on a route being traversed, returning a
* RouteSummary when traversal is completed.
* </pre>
*/
public io.grpc.stub.StreamObserver<io.grpc.examples.routeguide.Point> recordRoute(
io.grpc.stub.StreamObserver<io.grpc.examples.routeguide.RouteSummary> responseObserver) {
return asyncUnimplementedStreamingCall(METHOD_RECORD_ROUTE, responseObserver);
}
/**
* <pre>
* A Bidirectional streaming RPC.
* Accepts a stream of RouteNotes sent while a route is being traversed,
* while receiving other RouteNotes (e.g. from other users).
* </pre>
*/
public io.grpc.stub.StreamObserver<io.grpc.examples.routeguide.RouteNote> routeChat(
io.grpc.stub.StreamObserver<io.grpc.examples.routeguide.RouteNote> responseObserver) {
return asyncUnimplementedStreamingCall(METHOD_ROUTE_CHAT, responseObserver);
}
@java.lang.Override public io.grpc.ServerServiceDefinition bindService() {<FILL_FUNCTION_BODY>}
}
|
return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor())
.addMethod(
METHOD_GET_FEATURE,
asyncUnaryCall(
new MethodHandlers<
io.grpc.examples.routeguide.Point,
io.grpc.examples.routeguide.Feature>(
this, METHODID_GET_FEATURE)))
.addMethod(
METHOD_LIST_FEATURES,
asyncServerStreamingCall(
new MethodHandlers<
io.grpc.examples.routeguide.Rectangle,
io.grpc.examples.routeguide.Feature>(
this, METHODID_LIST_FEATURES)))
.addMethod(
METHOD_RECORD_ROUTE,
asyncClientStreamingCall(
new MethodHandlers<
io.grpc.examples.routeguide.Point,
io.grpc.examples.routeguide.RouteSummary>(
this, METHODID_RECORD_ROUTE)))
.addMethod(
METHOD_ROUTE_CHAT,
asyncBidiStreamingCall(
new MethodHandlers<
io.grpc.examples.routeguide.RouteNote,
io.grpc.examples.routeguide.RouteNote>(
this, METHODID_ROUTE_CHAT)))
.build();
| 682
| 338
| 1,020
|
<no_super_class>
|
weibocom_motan
|
motan/motan-demo/motan-demo-client/src/main/java/com/weibo/motan/demo/client/AnnotationRpcClientDemo.java
|
AnnotationRpcClientDemo
|
baseRefererConfig
|
class AnnotationRpcClientDemo {
public static void main(String[] args) throws InterruptedException {
ApplicationContext ctx = new ClassPathXmlApplicationContext(new
String[]{"classpath:motan_demo_client_annotation.xml"});
DemoRpcHandler handler = (DemoRpcHandler) ctx.getBean("demoRpcHandler");
handler.test();
System.out.println("motan demo is finish.");
System.exit(0);
}
@Bean(name = "demoMotan")
public ProtocolConfigBean demoMotanProtocolConfig() {
ProtocolConfigBean config = new ProtocolConfigBean();
//Id无需设置
// config.setId("demoMotan");
config.setName("motan");
config.setDefault(true);
config.setMaxContentLength(1048576);
config.setHaStrategy("failover");
config.setLoadbalance("roundrobin");
return config;
}
@Bean(name = "demoMotan2")
public ProtocolConfigBean protocolConfig2() {
ProtocolConfigBean config = new ProtocolConfigBean();
config.setName("motan");
config.setMaxContentLength(1048576);
config.setHaStrategy("failover");
config.setLoadbalance("roundrobin");
return config;
}
@Bean(name = "registry")
public RegistryConfigBean registryConfig() {
RegistryConfigBean config = new RegistryConfigBean();
// config.setRegProtocol("zk");
// config.setAddress("127.0.0.1:2181");
config.setRegProtocol("direct");
config.setAddress("127.0.0.1:8002");
return config;
}
@Bean(name = "motantestClientBasicConfig")
public BasicRefererConfigBean baseRefererConfig() {<FILL_FUNCTION_BODY>}
}
|
BasicRefererConfigBean config = new BasicRefererConfigBean();
config.setProtocol("demoMotan");
config.setGroup("motan-demo-rpc");
config.setModule("motan-demo-rpc");
config.setApplication("myMotanDemo");
config.setRegistry("registry");
config.setCheck(false);
config.setAccessLog(true);
config.setRetries(2);
config.setThrowException(true);
return config;
| 512
| 130
| 642
|
<no_super_class>
|
weibocom_motan
|
motan/motan-demo/motan-demo-client/src/main/java/com/weibo/motan/demo/client/DemoMeshClient.java
|
DemoMeshClient
|
main
|
class DemoMeshClient {
public static void main(String[] args) throws Throwable {<FILL_FUNCTION_BODY>}
// agent yaml配置样例参考:
//motan-agent:
// application: agent-test
//motan-registry:
// direct-registry:
// protocol: direct
// host: localhost
// port: 8002
//motan-refer:
// test-demo:
// registry: direct-registry
// path: com.weibo.motan.demo.service.MotanDemoService
// group: motan-demo-rpc
}
|
//使用MeshClient需要先部署mesh agent(可以参考https://github.com/weibocom/motan-go)。
// 在mesh agent中已经配置好对应的服务。
ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"classpath:demo_mesh_client.xml"});
MotanDemoService service = (MotanDemoService) ctx.getBean("refererWithMeshClient");
System.out.println(service.hello("motan"));
// 直接使用 MeshClient
MeshClient client = (MeshClient) ctx.getBean("testMeshClient");
Request request = MotanClientUtil.buildRequest("com.weibo.motan.demo.service.MotanDemoService",
"hello", new Object[]{"motan"}, null);
// sync call
System.out.println(client.call(request, String.class));
// async call
System.out.println(client.asyncCall(request, String.class).getValue());
System.exit(0);
| 166
| 263
| 429
|
<no_super_class>
|
weibocom_motan
|
motan/motan-demo/motan-demo-client/src/main/java/com/weibo/motan/demo/client/DemoRpcAsyncClient.java
|
DemoRpcAsyncClient
|
main
|
class DemoRpcAsyncClient {
/**
* 使用motan异步调用方法: 1、在声明的service上增加@MotanAsync注解。 如MotanDemoService
* 2、在项目pom.xml中增加build-helper-maven-plugin,用来把自动生成类的目录设置为source path。 参见motan-demo-api模块的pom声明。
* 也可以不使用plugin,手动将target/generated-sources/annotations目录设置为source path。
* 3、在client配置的motan:referer标签中配置interface为自动生成的以Async为后缀的对应service类。
* 参见本模块的motan_demo_async_client.xml
*
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[] {"classpath:motan_demo_async_client.xml"});
MotanDemoServiceAsync service = (MotanDemoServiceAsync) ctx.getBean("motanDemoReferer");
for (int i = 0; i < Integer.MAX_VALUE; i++) {
// sync call
System.out.println(service.hello("motan" + i));
// async call
ResponseFuture future = service.helloAsync("motan async " + i);
System.out.println(future.getValue());
// multi call
ResponseFuture future1 = service.helloAsync("motan async multi-1-" + i);
ResponseFuture future2 = service.helloAsync("motan async multi-2-" + i);
System.out.println(future1.getValue() + ", " + future2.getValue());
// async with listener
ResponseFuture future3 = service.helloAsync("motan async multi-1-" + i);
ResponseFuture future4 = service.helloAsync("motan async multi-2-" + i);
FutureListener listener = new FutureListener() {
@Override
public void operationComplete(Future future) throws Exception {
System.out.println("async call "
+ (future.isSuccess() ? "sucess! value:" + future.getValue() : "fail! exception:"
+ future.getException().getMessage()));
}
};
future3.addListener(listener);
future4.addListener(listener);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("motan demo is finish.");
System.exit(0);
| 220
| 438
| 658
|
<no_super_class>
|
weibocom_motan
|
motan/motan-demo/motan-demo-client/src/main/java/com/weibo/motan/demo/client/DemoRpcClient.java
|
DemoRpcClient
|
main
|
class DemoRpcClient {
public static void main(String[] args) throws InterruptedException {<FILL_FUNCTION_BODY>}
}
|
ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"classpath:motan_demo_client.xml"});
MotanDemoService service = (MotanDemoService) ctx.getBean("motanDemoReferer");
for (int i = 0; i < Integer.MAX_VALUE; i++) {
System.out.println(service.hello("motan" + i));
Thread.sleep(1000);
}
System.out.println("motan demo is finish.");
System.exit(0);
| 40
| 139
| 179
|
<no_super_class>
|
weibocom_motan
|
motan/motan-demo/motan-demo-client/src/main/java/com/weibo/motan/demo/client/DemoRpcHandler.java
|
DemoRpcHandler
|
test
|
class DemoRpcHandler {
@MotanReferer
private MotanDemoService motanDemoService;
public void test() {<FILL_FUNCTION_BODY>}
}
|
for (int i = 0; i < 10; i++) {
System.out.println(motanDemoService.hello("motan handler" + i));
LoggerUtil.info("motan handler" + i);
}
| 52
| 63
| 115
|
<no_super_class>
|
weibocom_motan
|
motan/motan-demo/motan-demo-client/src/main/java/com/weibo/motan/demo/client/GrpcClientDemo.java
|
GrpcClientDemo
|
main
|
class GrpcClientDemo {
public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>}
private static RouteNote newNote(String message, int lat, int lon) {
return RouteNote.newBuilder().setMessage(message).setLocation(Point.newBuilder().setLatitude(lat).setLongitude(lon).build())
.build();
}
}
|
ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[] {"classpath:motan_demo_client_grpc.xml"});
GrpcService service = (GrpcService) ctx.getBean("motanDemoReferer");
// unary
for (int i = 0; i < 2; i++) {
Point request = Point.newBuilder().setLatitude(100 + i).setLongitude(150 + i).build();
System.out.println(service.getFeature(request));
Thread.sleep(1000);
}
// server streaming
Rectangle request =
Rectangle.newBuilder().setLo(Point.newBuilder().setLatitude(400000000).setLongitude(-750000000).build())
.setHi(Point.newBuilder().setLatitude(420000000).setLongitude(-730000000).build()).build();
StreamObserver<Feature> responseObserver = new StreamObserver<Feature>() {
@Override
public void onNext(Feature value) {
System.out.println(value);
}
@Override
public void onError(Throwable t) {
// TODO Auto-generated method stub
}
@Override
public void onCompleted() {
System.out.println("response complete!");
}
};
service.listFeatures(request, responseObserver);
Thread.sleep(2000);
// client streaming
StreamObserver<RouteSummary> routeSummaryObserver = new StreamObserver<RouteSummary>() {
@Override
public void onNext(RouteSummary value) {
System.out.println(value);
}
@Override
public void onError(Throwable t) {
// TODO Auto-generated method stub
}
@Override
public void onCompleted() {
System.out.println("response complete!");
}
};
StreamObserver<Point> requestObserver = service.recordRoute(routeSummaryObserver);
Random random = new Random();
for (int i = 0; i < 5; i++) {
Point point = Point.newBuilder().setLatitude(random.nextInt()).setLongitude(random.nextInt()).build();
requestObserver.onNext(point);
Thread.sleep(200);
}
requestObserver.onCompleted();
Thread.sleep(2000);
// biderict-streaming
StreamObserver<RouteNote> biRequestObserver = service.routeChat(new StreamObserver<RouteNote>() {
public void onNext(RouteNote value) {
System.out.println(value);
}
public void onError(Throwable t) {
t.printStackTrace();
}
public void onCompleted() {
System.out.println("routenote complete");
}
});
try {
RouteNote[] requests =
{newNote("First message", 0, 0), newNote("Second message", 0, 1), newNote("Third message", 1, 0),
newNote("Fourth message", 1, 1)};
for (RouteNote note : requests) {
biRequestObserver.onNext(note);
}
} catch (RuntimeException e) {
biRequestObserver.onError(e);
throw e;
}
biRequestObserver.onCompleted();
Thread.sleep(2000);
System.out.println("motan demo is finish.");
System.exit(0);
| 102
| 905
| 1,007
|
<no_super_class>
|
weibocom_motan
|
motan/motan-demo/motan-demo-client/src/main/java/com/weibo/motan/demo/client/Motan2RpcClient.java
|
Motan2RpcClient
|
main
|
class Motan2RpcClient {
public static void main(String[] args) throws Throwable {<FILL_FUNCTION_BODY>}
public static void print(MotanDemoService service) throws InterruptedException {
for (int i = 0; i < 3; i++) {
try {
System.out.println(service.hello("motan" + i));
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void motan2XmlCommonClientDemo(CommonClient client) throws Throwable {
System.out.println(client.call("hello", new Object[]{"a"}, String.class));
User user = new User(1, "AAA");
System.out.println(user);
user = (User) client.call("rename", new Object[]{user, "BBB"}, User.class);
System.out.println(user);
ResponseFuture future = (ResponseFuture) client.asyncCall("rename", new Object[]{user, "CCC"}, User.class);
user = (User) future.getValue();
System.out.println(user);
ResponseFuture future2 = (ResponseFuture) client.asyncCall("rename", new Object[]{user, "DDD"}, User.class);
future2.addListener(future1 -> System.out.println(future1.getValue()));
Request request = client.buildRequest("rename", new Object[]{user, "EEE"});
request.setAttachment("a", "a");
user = (User) client.call(request, User.class);
System.out.println(user);
// expect throw exception
// client.call("rename", new Object[]{null, "FFF"}, void.class);
}
public static void motan2ApiCommonClientDemo() throws Throwable {
RefererConfig<CommonClient> referer = new RefererConfig<>();
// 设置服务端接口
referer.setInterface(CommonClient.class);
referer.setServiceInterface("com.weibo.motan.demo.service.MotanDemoService");
// 配置服务的group以及版本号
referer.setGroup("motan-demo-rpc");
referer.setVersion("1.0");
referer.setRequestTimeout(1000);
referer.setAsyncInitConnection(false);
// 配置注册中心直连调用
RegistryConfig registry = new RegistryConfig();
registry.setRegProtocol("direct");
registry.setAddress("127.0.0.1:8001");
referer.setRegistry(registry);
// 配置RPC协议
ProtocolConfig protocol = new ProtocolConfig();
protocol.setId("motan2");
protocol.setName("motan2");
referer.setProtocol(protocol);
// 使用服务
CommonClient client = referer.getRef();
System.out.println(client.call("hello", new Object[]{"a"}, String.class));
}
private static void breezeGenericCall(CommonClient client) throws Throwable {
GenericMessage genericMessage = new GenericMessage("com.weibo.motan.demo.service.model.User");
genericMessage.putFields(CommonSerializer.getHash("id"), 1);
genericMessage.putFields(CommonSerializer.getHash("name"), "AAA");
User user = (User) client.call("rename", new Object[]{genericMessage, "BBB"}, User.class);
System.out.println(user);
}
}
|
ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"classpath:motan2_demo_client.xml"});
MotanDemoService service;
// hessian
service = (MotanDemoService) ctx.getBean("motanDemoReferer");
print(service);
// simple serialization
service = (MotanDemoService) ctx.getBean("motanDemoReferer-simple");
print(service);
// breeze serialization
service = (MotanDemoService) ctx.getBean("motanDemoReferer-breeze");
print(service);
// server end async
service = (MotanDemoService) ctx.getBean("motanDemoReferer-asyncServer");
print(service);
// pb serialization
PbParamService pbService = (PbParamService) ctx.getBean("motanDemoReferer-pb");
System.out.println(pbService.getFeature(Point.newBuilder().setLatitude(123).setLongitude(456).build()));
// common client
CommonClient commonClient = (CommonClient) ctx.getBean("motanDemoReferer-common-client");
motan2XmlCommonClientDemo(commonClient);
motan2ApiCommonClientDemo();
breezeGenericCall(commonClient);
System.out.println("motan demo is finish.");
System.exit(0);
| 906
| 361
| 1,267
|
<no_super_class>
|
weibocom_motan
|
motan/motan-demo/motan-demo-client/src/main/java/com/weibo/motan/demo/client/Motan2RpcClientWithMesh.java
|
Motan2RpcClientWithMesh
|
main
|
class Motan2RpcClientWithMesh {
public static void main(String[] args) throws Throwable {<FILL_FUNCTION_BODY>}
}
|
//需要先部署mesh agent。可以参考https://github.com/weibocom/motan-go。agent配置中需要有匹配的注册中心配置
ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"classpath:motan2_demo_client_mesh.xml"});
MotanDemoService service;
service = (MotanDemoService) ctx.getBean("motanDemoReferer");
for (int i = 0; i < 30; i++) {
System.out.println(service.hello("motan" + i));
Thread.sleep(1000);
}
System.out.println("motan demo is finish.");
System.exit(0);
| 44
| 182
| 226
|
<no_super_class>
|
weibocom_motan
|
motan/motan-demo/motan-demo-client/src/main/java/com/weibo/motan/demo/client/MotanApiClientDemo.java
|
MotanApiClientDemo
|
main
|
class MotanApiClientDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
RefererConfig<MotanDemoService> motanDemoServiceReferer = new RefererConfig<MotanDemoService>();
// 设置接口及实现类
motanDemoServiceReferer.setInterface(MotanDemoService.class);
// 配置服务的group以及版本号
motanDemoServiceReferer.setGroup("motan-demo-rpc");
motanDemoServiceReferer.setVersion("1.0");
motanDemoServiceReferer.setRequestTimeout(1000);
motanDemoServiceReferer.setAsyncInitConnection(false);
// 配置注册中心直连调用
RegistryConfig registry = new RegistryConfig();
//use direct registry
registry.setRegProtocol("direct");
registry.setAddress("127.0.0.1:8002");
// use ZooKeeper registry
// registry.setRegProtocol("zk");
// registry.setAddress("127.0.0.1:2181");
motanDemoServiceReferer.setRegistry(registry);
// 配置RPC协议
ProtocolConfig protocol = new ProtocolConfig();
protocol.setId("motan");
protocol.setName("motan");
motanDemoServiceReferer.setProtocol(protocol);
// motanDemoServiceReferer.setDirectUrl("localhost:8002"); // 注册中心直连调用需添加此配置
// 使用服务
MotanDemoService service = motanDemoServiceReferer.getRef();
System.out.println(service.hello("motan"));
System.exit(0);
| 36
| 420
| 456
|
<no_super_class>
|
weibocom_motan
|
motan/motan-demo/motan-demo-client/src/main/java/com/weibo/motan/demo/client/RestfulClient.java
|
RestfulClient
|
main
|
class RestfulClient {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"classpath:motan_demo_client_restful.xml"});
// use restful
RestfulService service1 = (RestfulService) ctx.getBean("restfulReferer");
System.out.println(service1.getUsers(345).get(0).getName());
// use motan
RestfulService service2 = (RestfulService) ctx.getBean("motanReferer");
System.out.println(service2.getUsers(789).get(0).getName());
| 33
| 145
| 178
|
<no_super_class>
|
weibocom_motan
|
motan/motan-demo/motan-demo-client/src/main/java/com/weibo/motan/demo/client/SpringBootRpcClientDemo.java
|
SpringBootRpcClientDemo
|
main
|
class SpringBootRpcClientDemo {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
@Bean
public AnnotationBean motanAnnotationBean() {
AnnotationBean motanAnnotationBean = new AnnotationBean();
motanAnnotationBean.setPackage("com.weibo.motan.demo.client");
return motanAnnotationBean;
}
}
|
System.setProperty("server.port", "8080");
SpringApplication.run(SpringBootRpcClientDemo.class, args);
//start client and curl 'http://localhost:8080/' ,
// will requst to HelloController.home(), add than, request to the rpc server
| 104
| 82
| 186
|
<no_super_class>
|
weibocom_motan
|
motan/motan-demo/motan-demo-client/src/main/java/com/weibo/motan/demo/client/YarClient.java
|
YarClient
|
main
|
class YarClient {
public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>}
}
|
HttpYarClient yarClient = new HttpYarClient();
String result = yarClient.call("http://127.0.0.1:8003/openapi/yarserver/test", "testString", String.class, "yar");
System.out.println(result);
| 36
| 78
| 114
|
<no_super_class>
|
weibocom_motan
|
motan/motan-demo/motan-demo-server/src/main/java/com/weibo/motan/demo/server/AnnotationRpcServerDemo.java
|
AnnotationRpcServerDemo
|
registryConfig
|
class AnnotationRpcServerDemo {
public static void main(String[] args) throws InterruptedException {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(new
String[]{"classpath*:motan_demo_server_annotation.xml"});
MotanSwitcherUtil.setSwitcherValue(MotanConstants.REGISTRY_HEARTBEAT_SWITCHER, true);
System.out.println("server start...");
}
@Bean(name="demoMotan")
public ProtocolConfigBean protocolConfig1() {
ProtocolConfigBean config = new ProtocolConfigBean();
config.setDefault(true);
config.setName("motan");
config.setMaxContentLength(1048576);
return config;
}
@Bean(name = "motan")
public ProtocolConfigBean protocolConfig2() {
ProtocolConfigBean config = new ProtocolConfigBean();
// config.setId("demoMotan2");
config.setName("motan");
config.setMaxContentLength(1048576);
return config;
}
@Bean(name="registryConfig1")
public RegistryConfigBean registryConfig() {<FILL_FUNCTION_BODY>}
@Bean(name="proxy_reg")
public RegistryConfigBean registryProxyConfig() {
RegistryConfigBean config = new RegistryConfigBean();
config.setRegProtocol("weibomesh");
config.setProxyRegistryId("registryConfig1");
return config;
}
@Bean
public BasicServiceConfigBean baseServiceConfig() {
BasicServiceConfigBean config = new BasicServiceConfigBean();
config.setExport("demoMotan:8002");
config.setGroup("motan-demo-rpc");
config.setAccessLog(false);
config.setShareChannel(true);
config.setModule("motan-demo-rpc");
config.setApplication("myMotanDemo");
config.setRegistry("registryConfig1");
return config;
}
}
|
RegistryConfigBean config = new RegistryConfigBean();
// config.setRegProtocol("zk");
// config.setAddress("127.0.0.1:2181");
config.setRegProtocol("local");
return config;
| 536
| 67
| 603
|
<no_super_class>
|
weibocom_motan
|
motan/motan-demo/motan-demo-server/src/main/java/com/weibo/motan/demo/server/DemoRpcServer.java
|
DemoRpcServer
|
main
|
class DemoRpcServer {
public static void main(String[] args) throws InterruptedException {<FILL_FUNCTION_BODY>}
}
|
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[] {"classpath*:motan_demo_server.xml"});
MotanSwitcherUtil.setSwitcherValue(MotanConstants.REGISTRY_HEARTBEAT_SWITCHER, true);
System.out.println("server start...");
| 40
| 82
| 122
|
<no_super_class>
|
weibocom_motan
|
motan/motan-demo/motan-demo-server/src/main/java/com/weibo/motan/demo/server/GrpcServerDemo.java
|
GrpcServerDemo
|
calcDistance
|
class GrpcServerDemo implements GrpcService {
static Collection<Feature> features;
public static void main(String[] args) throws Exception {
features = RouteGuideUtil.parseFeatures(RouteGuideUtil.getDefaultFeaturesFile());
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:motan_demo_server_grpc.xml");
System.out.println("grpc server start...");
Thread.sleep(Long.MAX_VALUE);
}
private final ConcurrentMap<Point, List<RouteNote>> routeNotes =
new ConcurrentHashMap<Point, List<RouteNote>>();
public Feature getFeature(Point request) {
return checkFeature(request);
}
/**
* Gets all features contained within the given bounding {@link Rectangle}.
*
* @param request the bounding rectangle for the requested features.
* @param responseObserver the observer that will receive the features.
*/
public void listFeatures(Rectangle request, StreamObserver<Feature> responseObserver) {
int left = min(request.getLo().getLongitude(), request.getHi().getLongitude());
int right = max(request.getLo().getLongitude(), request.getHi().getLongitude());
int top = max(request.getLo().getLatitude(), request.getHi().getLatitude());
int bottom = min(request.getLo().getLatitude(), request.getHi().getLatitude());
for (Feature feature : features) {
if (!RouteGuideUtil.exists(feature)) {
continue;
}
int lat = feature.getLocation().getLatitude();
int lon = feature.getLocation().getLongitude();
if (lon >= left && lon <= right && lat >= bottom && lat <= top) {
responseObserver.onNext(feature);
}
}
responseObserver.onCompleted();
}
/**
* Gets a stream of points, and responds with statistics about the "trip": number of points,
* number of known features visited, total distance traveled, and total time spent.
*
* @param responseObserver an observer to receive the response summary.
* @return an observer to receive the requested route points.
*/
public StreamObserver<Point> recordRoute(final StreamObserver<RouteSummary> responseObserver) {
return new StreamObserver<Point>() {
int pointCount;
int featureCount;
int distance;
Point previous;
long startTime = System.nanoTime();
public void onNext(Point point) {
pointCount++;
if (RouteGuideUtil.exists(checkFeature(point))) {
featureCount++;
}
// For each point after the first, add the incremental distance from the previous point to
// the total distance value.
if (previous != null) {
distance += calcDistance(previous, point);
}
previous = point;
}
public void onError(Throwable t) {
}
public void onCompleted() {
long seconds = NANOSECONDS.toSeconds(System.nanoTime() - startTime);
responseObserver.onNext(RouteSummary.newBuilder().setPointCount(pointCount)
.setFeatureCount(featureCount).setDistance(distance)
.setElapsedTime((int) seconds).build());
responseObserver.onCompleted();
}
};
}
/**
* Receives a stream of message/location pairs, and responds with a stream of all previous
* messages at each of those locations.
*
* @param responseObserver an observer to receive the stream of previous messages.
* @return an observer to handle requested message/location pairs.
*/
public StreamObserver<RouteNote> routeChat(final StreamObserver<RouteNote> responseObserver) {
return new StreamObserver<RouteNote>() {
public void onNext(RouteNote note) {
List<RouteNote> notes = getOrCreateNotes(note.getLocation());
// Respond with all previous notes at this location.
for (RouteNote prevNote : notes.toArray(new RouteNote[0])) {
responseObserver.onNext(prevNote);
}
// Now add the new note to the list
notes.add(note);
}
public void onError(Throwable t) {
}
public void onCompleted() {
responseObserver.onCompleted();
}
};
}
/**
* Get the notes list for the given location. If missing, create it.
*/
private List<RouteNote> getOrCreateNotes(Point location) {
List<RouteNote> notes = Collections.synchronizedList(new ArrayList<RouteNote>());
List<RouteNote> prevNotes = routeNotes.putIfAbsent(location, notes);
return prevNotes != null ? prevNotes : notes;
}
/**
* Gets the feature at the given point.
*
* @param location the location to check.
* @return The feature object at the point. Note that an empty name indicates no feature.
*/
private Feature checkFeature(Point location) {
for (Feature feature : features) {
if (feature.getLocation().getLatitude() == location.getLatitude()
&& feature.getLocation().getLongitude() == location.getLongitude()) {
return feature;
}
}
// No feature was found, return an unnamed feature.
return Feature.newBuilder().setName("").setLocation(location).build();
}
/**
* Calculate the distance between two points using the "haversine" formula.
* This code was taken from http://www.movable-type.co.uk/scripts/latlong.html.
*
* @param start The starting point
* @param end The end point
* @return The distance between the points in meters
*/
private static double calcDistance(Point start, Point end) {<FILL_FUNCTION_BODY>}
}
|
double lat1 = RouteGuideUtil.getLatitude(start);
double lat2 = RouteGuideUtil.getLatitude(end);
double lon1 = RouteGuideUtil.getLongitude(start);
double lon2 = RouteGuideUtil.getLongitude(end);
int r = 6371000; // metres
double φ1 = toRadians(lat1);
double φ2 = toRadians(lat2);
double Δφ = toRadians(lat2 - lat1);
double Δλ = toRadians(lon2 - lon1);
double a = sin(Δφ / 2) * sin(Δφ / 2) + cos(φ1) * cos(φ2) * sin(Δλ / 2) * sin(Δλ / 2);
double c = 2 * atan2(sqrt(a), sqrt(1 - a));
return r * c;
| 1,500
| 242
| 1,742
|
<no_super_class>
|
weibocom_motan
|
motan/motan-demo/motan-demo-server/src/main/java/com/weibo/motan/demo/server/Motan2Server.java
|
Motan2Server
|
main
|
class Motan2Server {
public static void main(String[] args) throws InterruptedException {<FILL_FUNCTION_BODY>}
}
|
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[] {"classpath*:motan2_demo_server.xml"});
MotanSwitcherUtil.setSwitcherValue(MotanConstants.REGISTRY_HEARTBEAT_SWITCHER, true);
System.out.println("server start...");
| 38
| 83
| 121
|
<no_super_class>
|
weibocom_motan
|
motan/motan-demo/motan-demo-server/src/main/java/com/weibo/motan/demo/server/Motan2ServerWithMesh.java
|
Motan2ServerWithMesh
|
main
|
class Motan2ServerWithMesh {
public static void main(String[] args) throws InterruptedException {<FILL_FUNCTION_BODY>}
}
|
//需要先部署mesh agent。可以参考https://github.com/weibocom/motan-go。agent配置中需要有匹配的注册中心配置
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[]{"classpath*:motan2_demo_server_mesh.xml"});
MotanSwitcherUtil.setSwitcherValue(MotanConstants.REGISTRY_HEARTBEAT_SWITCHER, true);
System.out.println("server start...");
| 41
| 124
| 165
|
<no_super_class>
|
weibocom_motan
|
motan/motan-demo/motan-demo-server/src/main/java/com/weibo/motan/demo/server/MotanApiExportDemo.java
|
MotanApiExportDemo
|
main
|
class MotanApiExportDemo {
public static void main(String[] args) throws InterruptedException {<FILL_FUNCTION_BODY>}
}
|
ServiceConfig<MotanDemoService> motanDemoService = new ServiceConfig<MotanDemoService>();
// 设置接口及实现类
motanDemoService.setInterface(MotanDemoService.class);
motanDemoService.setRef(new MotanDemoServiceImpl());
// 配置服务的group以及版本号
motanDemoService.setGroup("motan-demo-rpc");
motanDemoService.setVersion("1.0");
// 配置注册中心直连调用
RegistryConfig registry = new RegistryConfig();
//use local registry
registry.setRegProtocol("local");
// use ZooKeeper registry
// registry.setRegProtocol("zk");
// registry.setAddress("127.0.0.1:2181");
// registry.setCheck("false"); //是否检查是否注册成功
motanDemoService.setRegistry(registry);
// 配置RPC协议
ProtocolConfig protocol = new ProtocolConfig();
protocol.setId("motan");
protocol.setName("motan");
motanDemoService.setProtocol(protocol);
motanDemoService.setExport("motan:8002");
motanDemoService.export();
MotanSwitcherUtil.setSwitcherValue(MotanConstants.REGISTRY_HEARTBEAT_SWITCHER, true);
System.out.println("server start...");
| 41
| 376
| 417
|
<no_super_class>
|
weibocom_motan
|
motan/motan-demo/motan-demo-server/src/main/java/com/weibo/motan/demo/server/MotanDemoServiceAsyncImpl.java
|
MotanDemoServiceAsyncImpl
|
renameAsync
|
class MotanDemoServiceAsyncImpl implements MotanDemoServiceAsync {
ExecutorService testExecutorService = Executors.newCachedThreadPool();
@Override
public String hello(String name) throws MotanServiceException {
System.out.println(name);
return "Hello " + name + "!";
}
@Override
public User rename(User user, String name) {
Objects.requireNonNull(user);
System.out.println(user.getId() + " rename " + user.getName() + " to " + name);
user.setName(name);
return user;
}
@Override
public ResponseFuture helloAsync(String name) {
System.out.println("in async hello");
final ResponseFuture motanResponseFuture = AsyncUtil.createResponseFutureForServerEnd();
testExecutorService.submit(() -> motanResponseFuture.onSuccess(this.hello(name)));
return motanResponseFuture;
}
@Override
public ResponseFuture renameAsync(User user, String name) {<FILL_FUNCTION_BODY>}
}
|
System.out.println("in async rename");
final ResponseFuture motanResponseFuture = AsyncUtil.createResponseFutureForServerEnd();
testExecutorService.submit(() -> {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
motanResponseFuture.onSuccess(this.rename(user, name));
} catch (Exception e) {
motanResponseFuture.onFailure(e);
}
});
return motanResponseFuture;
| 279
| 141
| 420
|
<no_super_class>
|
weibocom_motan
|
motan/motan-demo/motan-demo-server/src/main/java/com/weibo/motan/demo/server/MotanDemoServiceImpl.java
|
MotanDemoServiceImpl
|
rename
|
class MotanDemoServiceImpl implements MotanDemoService {
@Override
public String hello(String name) {
System.out.println(name);
return "Hello " + name + "!";
}
@Override
public User rename(User user, String name) throws Exception {<FILL_FUNCTION_BODY>}
}
|
Objects.requireNonNull(user);
System.out.println(user.getId() + " rename " + user.getName() + " to " + name);
user.setName(name);
return user;
| 92
| 57
| 149
|
<no_super_class>
|
weibocom_motan
|
motan/motan-demo/motan-demo-server/src/main/java/com/weibo/motan/demo/server/RestfulServerDemo.java
|
RestfulServerDemo
|
main
|
class RestfulServerDemo implements RestfulService {
public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public List<User> getUsers(@CookieParam("uid") int uid) {
return Arrays.asList(new User(uid, "name" + uid));
}
@Override
public String testPrimitiveType() {
return "helloworld!";
}
@Override
public Response add(@FormParam("id") int id, @FormParam("name") String name) {
return Response.ok().cookie(new NewCookie("ck", String.valueOf(id))).entity(new User(id, name)).build();
}
@Override
public void testException() {
throw new UnsupportedOperationException("unsupport");
}
}
|
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:motan_demo_server_restful.xml");
System.out.println("restful server start...");
Thread.sleep(Long.MAX_VALUE);
| 213
| 59
| 272
|
<no_super_class>
|
weibocom_motan
|
motan/motan-demo/motan-demo-server/src/main/java/com/weibo/motan/demo/server/RouteGuideUtil.java
|
RouteGuideUtil
|
parseFeatures
|
class RouteGuideUtil {
private static final double COORD_FACTOR = 1e7;
/**
* Gets the latitude for the given point.
*/
public static double getLatitude(Point location) {
return location.getLatitude() / COORD_FACTOR;
}
/**
* Gets the longitude for the given point.
*/
public static double getLongitude(Point location) {
return location.getLongitude() / COORD_FACTOR;
}
/**
* Gets the default features file from classpath.
*/
public static URL getDefaultFeaturesFile() {
return RouteGuideUtil.class.getResource("/route_guide_db.json");
}
/**
* Parses the JSON input file containing the list of features.
*/
public static List<Feature> parseFeatures(URL file) throws IOException {<FILL_FUNCTION_BODY>}
/**
* Indicates whether the given feature exists (i.e. has a valid name).
*/
public static boolean exists(Feature feature) {
return feature != null && !feature.getName().isEmpty();
}
}
|
InputStream input = file.openStream();
try {
Reader reader = new InputStreamReader(input);
try {
FeatureDatabase.Builder database = FeatureDatabase.newBuilder();
JsonFormat.parser().merge(reader, database);
return database.getFeatureList();
} finally {
reader.close();
}
} finally {
input.close();
}
| 293
| 98
| 391
|
<no_super_class>
|
weibocom_motan
|
motan/motan-demo/motan-demo-server/src/main/java/com/weibo/motan/demo/server/YarServerDemo.java
|
YarServerDemo
|
testMap
|
class YarServerDemo implements YarService {
public String hello(String name) {
System.out.println(name + " invoked rpc service");
return "hello " + name;
}
// local
public static void main(String[] args) throws InterruptedException {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:motan_demo_server_yar.xml");
System.out.println("yar server start...");
Thread.sleep(Long.MAX_VALUE);
}
public void testVoid() {
System.out.println("in void");
}
public String testArgVoid() {
System.out.println("in arg void");
return "in arg void";
}
public String testString(String arg) {
System.out.println("in String");
return arg;
}
public int testInt(int i) {
System.out.println("in int");
return i;
}
public Integer testInteger(Integer integer) {
System.out.println("in Integer");
return integer;
}
public boolean testBoolean(boolean b) {
System.out.println("in boolean");
return b;
}
public long testLong(long l) {
System.out.println("in long");
return l;
}
public float testFloat(Float f) {
return f;
}
public double testDouble(Double d) {
return d;
}
public List<Object> testList(List<Object> list) {
System.out.println("in testlist");
List<Object> retlist = new ArrayList<Object>(list);
Collections.reverse(retlist);
return retlist;
}
public Map<String, Object> testMap(Map<String, Object> map) {<FILL_FUNCTION_BODY>}
}
|
System.out.println("in testmap");
Map<String, Object> retmap = new HashMap<String, Object>(map);
retmap.put("size", map.size());
return retmap;
| 492
| 56
| 548
|
<no_super_class>
|
weibocom_motan
|
motan/motan-demo/motan-demo-server/src/main/java/com/weibo/motan/demo/springboot/SpringBootRpcServerDemo.java
|
SpringBootRpcServerDemo
|
baseServiceConfig
|
class SpringBootRpcServerDemo {
public static void main(String[] args) {
System.setProperty("server.port", "8081");
ConfigurableApplicationContext context = SpringApplication.run(SpringBootRpcServerDemo.class, args);
MotanSwitcherUtil.setSwitcherValue(MotanConstants.REGISTRY_HEARTBEAT_SWITCHER, true);
System.out.println("server start...");
}
@Bean
public AnnotationBean motanAnnotationBean() {
AnnotationBean motanAnnotationBean = new AnnotationBean();
motanAnnotationBean.setPackage("com.weibo.motan.demo.server");
return motanAnnotationBean;
}
@Bean(name = "demoMotan")
public ProtocolConfigBean protocolConfig1() {
ProtocolConfigBean config = new ProtocolConfigBean();
config.setDefault(true);
config.setName("motan");
config.setMaxContentLength(1048576);
return config;
}
@Bean(name = "registryConfig1")
public RegistryConfigBean registryConfig() {
RegistryConfigBean config = new RegistryConfigBean();
config.setRegProtocol("local");
return config;
}
@Bean
public BasicServiceConfigBean baseServiceConfig() {<FILL_FUNCTION_BODY>}
}
|
BasicServiceConfigBean config = new BasicServiceConfigBean();
config.setExport("demoMotan:8002");
config.setGroup("testgroup");
config.setAccessLog(false);
config.setShareChannel(true);
config.setModule("motan-demo-rpc");
config.setApplication("myMotanDemo");
config.setRegistry("registryConfig1");
return config;
| 355
| 110
| 465
|
<no_super_class>
|
weibocom_motan
|
motan/motan-extension/filter-extension/filter-opentracing/src/main/java/com/weibo/api/motan/filter/opentracing/OpenTracingContext.java
|
OpenTracingContext
|
getActiveSpan
|
class OpenTracingContext {
// replace TracerFactory with any tracer implementation
public static TracerFactory tracerFactory = TracerFactory.DEFAULT;
public static final String ACTIVE_SPAN = "ot_active_span";
public static Tracer getTracer() {
return tracerFactory.getTracer();
}
public static Span getActiveSpan() {<FILL_FUNCTION_BODY>}
public static void setActiveSpan(Span span) {
RpcContext.getContext().putAttribute(ACTIVE_SPAN, span);
}
public void setTracerFactory(TracerFactory tracerFactory) {
OpenTracingContext.tracerFactory = tracerFactory;
}
}
|
Object span = RpcContext.getContext().getAttribute(ACTIVE_SPAN);
if (span != null && span instanceof Span) {
return (Span) span;
}
return null;
| 180
| 55
| 235
|
<no_super_class>
|
weibocom_motan
|
motan/motan-extension/filter-extension/filter-opentracing/src/main/java/com/weibo/api/motan/filter/opentracing/OpenTracingFilter.java
|
OpenTracingFilter
|
extractTraceInfo
|
class OpenTracingFilter implements Filter {
@Override
public Response filter(Caller<?> caller, Request request) {
Tracer tracer = getTracer();
if (tracer == null || tracer instanceof NoopTracer) {
return caller.call(request);
}
if (caller instanceof Provider) { // server end
return processProviderTrace(tracer, caller, request);
} else { // client end
return processRefererTrace(tracer, caller, request);
}
}
protected Tracer getTracer(){
return OpenTracingContext.getTracer();
}
/**
* process trace in client end
*
* @param caller
* @param request
* @return
*/
protected Response processRefererTrace(Tracer tracer, Caller<?> caller, Request request) {
String operationName = buildOperationName(request);
SpanBuilder spanBuilder = tracer.buildSpan(operationName);
Span activeSpan = OpenTracingContext.getActiveSpan();
if (activeSpan != null) {
spanBuilder.asChildOf(activeSpan);
}
Span span = spanBuilder.start();
span.setTag("requestId", request.getRequestId());
attachTraceInfo(tracer, span, request);
return process(caller, request, span);
}
protected Response process(Caller<?> caller, Request request, Span span) {
Exception ex = null;
boolean exception = true;
try {
Response response = caller.call(request);
if (response.getException() != null) {
ex = response.getException();
} else {
exception = false;
}
return response;
} catch (RuntimeException e) {
ex = e;
throw e;
} finally {
try {
if (exception) {
span.log("request fail." + (ex == null ? "unknown exception" : ex.getMessage()));
} else {
span.log("request success.");
}
span.finish();
} catch (Exception e) {
LoggerUtil.error("opentracing span finish error!", e);
}
}
}
protected String buildOperationName(Request request) {
return "Motan_" + MotanFrameworkUtil.getGroupMethodString(request);
}
protected void attachTraceInfo(Tracer tracer, Span span, final Request request) {
tracer.inject(span.context(), Format.Builtin.TEXT_MAP, new TextMap() {
@Override
public void put(String key, String value) {
request.setAttachment(key, value);
}
@Override
public Iterator<Entry<String, String>> iterator() {
throw new UnsupportedOperationException("TextMapInjectAdapter should only be used with Tracer.inject()");
}
});
}
/**
* process trace in server end
*
* @param caller
* @param request
* @return
*/
protected Response processProviderTrace(Tracer tracer, Caller<?> caller, Request request) {
Span span = extractTraceInfo(request, tracer);
span.setTag("requestId", request.getRequestId());
OpenTracingContext.setActiveSpan(span);
return process(caller, request, span);
}
protected Span extractTraceInfo(Request request, Tracer tracer) {<FILL_FUNCTION_BODY>}
}
|
String operationName = buildOperationName(request);
SpanBuilder span = tracer.buildSpan(operationName);
try {
SpanContext spanContext = tracer.extract(Format.Builtin.TEXT_MAP, new TextMapExtractAdapter(request.getAttachments()));
if (spanContext != null) {
span.asChildOf(spanContext);
}
} catch (Exception e) {
span.withTag("Error", "extract from request fail, error msg:" + e.getMessage());
}
return span.start();
| 897
| 141
| 1,038
|
<no_super_class>
|
weibocom_motan
|
motan/motan-extension/protocol-extension/motan-protocol-grpc/src/main/java/com/weibo/api/motan/protocol/grpc/GrpcClient.java
|
GrpcClient
|
request
|
class GrpcClient {
private URL url;
private Class<?> interfaceClazz;
private ManagedChannel channel;
private CallOptions callOption = CallOptions.DEFAULT; // TODO 需要配置线程池时使用
@SuppressWarnings("rawtypes")
private HashMap<String, MethodDescriptor> methodDescMap;
public GrpcClient(URL url, Class<?> interfaceClazz) {
this.url = url;
this.interfaceClazz = interfaceClazz;
}
@SuppressWarnings({"unchecked", "rawtypes"})
public <ReqT, RespT> Response request(final Request request) {<FILL_FUNCTION_BODY>}
public boolean init() throws Exception {
methodDescMap = GrpcUtil.getMethodDescriptorByAnnotation(interfaceClazz, url.getParameter(URLParamType.serialize.getName()));
channel = ManagedChannelBuilder.forAddress(url.getHost(), url.getPort()).usePlaintext(true).build();
return true;
}
public void destroy() {
channel.shutdownNow();
}
}
|
MethodDescriptor<ReqT, RespT> methodDesc = methodDescMap.get(request.getMethodName());
if (methodDesc == null) {
throw new MotanServiceException("request method grpc descriptornot found.method:" + request.getMethodName());
}
int timeout =
url.getMethodParameter(request.getMethodName(), request.getParamtersDesc(), URLParamType.requestTimeout.getName(),
URLParamType.requestTimeout.getIntValue());
if (timeout < 0) {
throw new MotanServiceException("request timeout invalid.method timeout:" + timeout);
}
ClientCall<ReqT, RespT> call =
new SimpleForwardingClientCall(channel.newCall(methodDesc, callOption.withDeadlineAfter(timeout, TimeUnit.MILLISECONDS))) {
public void start(Listener responseListener, Metadata headers) {
Map<String, String> attachments = request.getAttachments();
if (attachments != null && !attachments.isEmpty()) {
for (Entry<String, String> entry : attachments.entrySet()) {
headers.put(Metadata.Key.of(entry.getKey(), Metadata.ASCII_STRING_MARSHALLER), entry.getValue());
}
}
super.start(responseListener, headers);
}
};
GrpcResponseFuture<RespT> responseFuture = new GrpcResponseFuture<RespT>(request, timeout, url, call);
MethodType methodType = methodDesc.getType();
switch (methodType) {
case UNARY:
ClientCalls.asyncUnaryCall(call, (ReqT) request.getArguments()[0], responseFuture);
break;
case SERVER_STREAMING:
ClientCalls.asyncServerStreamingCall(call, (ReqT) request.getArguments()[0],
(io.grpc.stub.StreamObserver<RespT>) request.getArguments()[1]);
responseFuture.onCompleted();
break;
case CLIENT_STREAMING:
StreamObserver<ReqT> clientObserver =
ClientCalls.asyncClientStreamingCall(call, (io.grpc.stub.StreamObserver<RespT>) request.getArguments()[0]);
responseFuture.onNext(clientObserver);
responseFuture.onCompleted();
break;
case BIDI_STREAMING:
StreamObserver<ReqT> biObserver =
ClientCalls.asyncBidiStreamingCall(call, (io.grpc.stub.StreamObserver<RespT>) request.getArguments()[0]);
responseFuture.onNext(biObserver);
responseFuture.onCompleted();
break;
default:
throw new MotanServiceException("unknown grpc method type:" + methodType);
}
return responseFuture;
| 283
| 714
| 997
|
<no_super_class>
|
weibocom_motan
|
motan/motan-extension/protocol-extension/motan-protocol-grpc/src/main/java/com/weibo/api/motan/protocol/grpc/GrpcProtocol.java
|
GrpcProtocol
|
createExporter
|
class GrpcProtocol extends AbstractProtocol {
protected ConcurrentHashMap<String, GrpcServer> serverMap = new ConcurrentHashMap<String, GrpcServer>();
@Override
protected <T> Exporter<T> createExporter(Provider<T> provider, URL url) {<FILL_FUNCTION_BODY>}
@Override
protected <T> Referer<T> createReferer(Class<T> clz, URL url, URL serviceUrl) {
return new GrpcReferer<T>(clz, url, serviceUrl);
}
class GrpcExporter<T> extends AbstractExporter<T> {
private GrpcServer server;
public GrpcExporter(Provider<T> provider, URL url, GrpcServer server) {
super(provider, url);
this.server = server;
}
@SuppressWarnings("unchecked")
@Override
public void unexport() {
String protocolKey = MotanFrameworkUtil.getProtocolKey(url);
Exporter<T> exporter = (Exporter<T>) exporterMap.remove(protocolKey);
if (exporter != null) {
exporter.destroy();
}
LoggerUtil.info("GrpcExporter unexport Success: url={}", url);
}
@Override
public void destroy() {
server.safeRelease(url);
LoggerUtil.info("GrpcExporter destory Success: url={}", url);
}
@Override
protected boolean doInit() {
try {
server.init();
server.addExporter(this);
return true;
} catch (Exception e) {
LoggerUtil.error("grpc server init fail!", e);
}
return false;
}
}
class GrpcReferer<T> extends AbstractReferer<T> {
private GrpcClient client;
public GrpcReferer(Class<T> clz, URL url, URL serviceUrl) {
super(clz, url, serviceUrl);
client = new GrpcClient(url, clz);
}
@Override
public void destroy() {
client.destroy();
LoggerUtil.info("GrpcReferer destory Success: url={}", url);
}
@Override
protected Response doCall(Request request) {
return client.request(request);
}
@Override
protected boolean doInit() {
try {
client.init();
return true;
} catch (Exception e) {
LoggerUtil.error("grpc client init fail!", e);
}
return false;
}
}
}
|
String ipPort = url.getServerPortStr();
GrpcServer server = serverMap.get(ipPort);
if (server == null) {
boolean shareChannel =
url.getBooleanParameter(URLParamType.shareChannel.getName(), URLParamType.shareChannel.getBooleanValue());
int workerQueueSize = url.getIntParameter(URLParamType.workerQueueSize.getName(), URLParamType.workerQueueSize.getIntValue());
int minWorkerThread = 0, maxWorkerThread = 0;
if (shareChannel) {
minWorkerThread =
url.getIntParameter(URLParamType.minWorkerThread.getName(), MotanConstants.NETTY_SHARECHANNEL_MIN_WORKDER);
maxWorkerThread =
url.getIntParameter(URLParamType.maxWorkerThread.getName(), MotanConstants.NETTY_SHARECHANNEL_MAX_WORKDER);
} else {
minWorkerThread =
url.getIntParameter(URLParamType.minWorkerThread.getName(), MotanConstants.NETTY_NOT_SHARECHANNEL_MIN_WORKDER);
maxWorkerThread =
url.getIntParameter(URLParamType.maxWorkerThread.getName(), MotanConstants.NETTY_NOT_SHARECHANNEL_MAX_WORKDER);
}
ExecutorService executor =
new StandardThreadExecutor(minWorkerThread, maxWorkerThread, workerQueueSize, new DefaultThreadFactory("GrpcServer-"
+ url.getServerPortStr(), true));
server = new GrpcServer(url.getPort(), shareChannel, executor);
serverMap.putIfAbsent(ipPort, server);
server = serverMap.get(ipPort);
}
return new GrpcExporter<T>(provider, url, server);
| 673
| 453
| 1,126
|
<methods>public non-sealed void <init>() ,public void destroy() ,public Exporter<T> export(Provider<T>, com.weibo.api.motan.rpc.URL) ,public Map<java.lang.String,Exporter<?>> getExporterMap() ,public Referer<T> refer(Class<T>, com.weibo.api.motan.rpc.URL) ,public Referer<T> refer(Class<T>, com.weibo.api.motan.rpc.URL, com.weibo.api.motan.rpc.URL) <variables>protected ConcurrentHashMap<java.lang.String,Exporter<?>> exporterMap
|
weibocom_motan
|
motan/motan-extension/protocol-extension/motan-protocol-grpc/src/main/java/com/weibo/api/motan/protocol/grpc/GrpcResponseFuture.java
|
GrpcResponseFuture
|
onError
|
class GrpcResponseFuture<RespT> extends DefaultResponseFuture implements StreamObserver<RespT> {
private final ClientCall<?, RespT> call;
public GrpcResponseFuture(Request requestObj, int timeout, URL serverUrl, ClientCall<?, RespT> call) {
super(requestObj, timeout, serverUrl);
this.call = call;
}
@Override
public boolean cancel() {
call.cancel("GrpcResponseFuture was cancelled", null);
return super.cancel();
}
private long calculateProcessTime() {
return System.currentTimeMillis() - createTime;
}
@Override
public void onNext(Object value) {
this.result = value;
}
@Override
public void onError(Throwable t) {<FILL_FUNCTION_BODY>}
@Override
public void onCompleted() {
this.processTime = calculateProcessTime();
done();
}
}
|
if (t instanceof Exception) {
this.exception = (Exception) t;
} else {
this.exception = new MotanServiceException("grpc response future has fatal error.", t);
}
done();
| 249
| 57
| 306
|
<methods>public void <init>(com.weibo.api.motan.rpc.Request, int, com.weibo.api.motan.rpc.URL) ,public void <init>(com.weibo.api.motan.rpc.Request, int, java.lang.String) ,public void addFinishCallback(java.lang.Runnable, java.util.concurrent.Executor) ,public void addListener(com.weibo.api.motan.rpc.FutureListener) ,public boolean cancel() ,public Map<java.lang.String,java.lang.String> getAttachments() ,public com.weibo.api.motan.rpc.Callbackable getCallbackHolder() ,public long getCreateTime() ,public java.lang.Exception getException() ,public long getProcessTime() ,public long getRequestId() ,public java.lang.Object getRequestObj() ,public byte getRpcProtocolVersion() ,public int getSerializeNumber() ,public com.weibo.api.motan.common.FutureState getState() ,public int getTimeout() ,public com.weibo.api.motan.rpc.TraceableContext getTraceableContext() ,public java.lang.Object getValue() ,public boolean isCancelled() ,public boolean isDone() ,public boolean isSuccess() ,public void onFailure(com.weibo.api.motan.rpc.Response) ,public void onFailure(java.lang.Exception) ,public void onFinish() ,public void onSuccess(com.weibo.api.motan.rpc.Response) ,public void onSuccess(java.lang.Object) ,public void setAttachment(java.lang.String, java.lang.String) ,public void setProcessTime(long) ,public void setReturnType(Class<?>) ,public void setRpcProtocolVersion(byte) ,public void setSerializeNumber(int) <variables>private Map<java.lang.String,java.lang.String> attachments,private final com.weibo.api.motan.rpc.DefaultCallbackHolder callbackHolder,protected long createTime,protected java.lang.Exception exception,protected List<com.weibo.api.motan.rpc.FutureListener> listeners,protected final java.lang.Object lock,protected long processTime,protected java.lang.String remoteInfo,protected com.weibo.api.motan.rpc.Request request,protected java.lang.Object result,protected Class<?> returnType,protected volatile com.weibo.api.motan.common.FutureState state,protected int timeout,private final com.weibo.api.motan.rpc.TraceableContext traceableContext
|
weibocom_motan
|
motan/motan-extension/protocol-extension/motan-protocol-grpc/src/main/java/com/weibo/api/motan/protocol/grpc/GrpcServer.java
|
GrpcServer
|
addExporter
|
class GrpcServer{
private int port;
private MotanHandlerRegistry registry;
private Server server;
private Map<URL, ServerServiceDefinition> serviceDefinetions;
private boolean init;
private boolean shareChannel;
private ExecutorService executor;
private NettyHttpRequestHandler httpHandler;
public GrpcServer(int port) {
super();
this.port = port;
}
public GrpcServer(int port, boolean shareChannel) {
super();
this.port = port;
this.shareChannel = shareChannel;
}
public GrpcServer(int port, boolean shareChannel, ExecutorService executor) {
super();
this.port = port;
this.shareChannel = shareChannel;
this.executor = executor;
}
@SuppressWarnings("rawtypes")
public void init() throws Exception{
if(!init){
synchronized (this) {
if(!init){
registry = new MotanHandlerRegistry();
serviceDefinetions = new HashMap<URL, ServerServiceDefinition>();
io.grpc.ServerBuilder builder = ServerBuilder.forPort(port);
builder.fallbackHandlerRegistry(registry);
if(executor != null){
builder.executor(executor);
}
if(builder instanceof NettyServerBuilder){
httpHandler = new NettyHttpRequestHandler(executor);
((NettyServerBuilder)builder).protocolNegotiator(new HttpProtocolNegotiator(httpHandler));
}
server = builder.build();
server.start();
init = true;
}
}
}
}
@SuppressWarnings("rawtypes")
public void addExporter(Exporter<?> exporter) throws Exception{<FILL_FUNCTION_BODY>}
/**
* remove service specified by url.
* the server will be closed if all service is remove
* @param url
*/
public void safeRelease(URL url){
synchronized (serviceDefinetions) {
registry.removeService(serviceDefinetions.remove(url));
if(httpHandler != null){
httpHandler.removeProvider(url);
}
if(serviceDefinetions.isEmpty()){
server.shutdown();
if(executor != null){
executor.shutdownNow();
}
}
}
}
}
|
Provider provider = exporter.getProvider();
ServerServiceDefinition serviceDefine = GrpcUtil.getServiceDefByAnnotation(provider.getInterface());
boolean urlShareChannel = exporter.getUrl().getBooleanParameter(URLParamType.shareChannel.getName(),
URLParamType.shareChannel.getBooleanValue());
synchronized (serviceDefinetions) {
if(!(shareChannel && urlShareChannel) && !serviceDefinetions.isEmpty()){
URL url = serviceDefinetions.keySet().iterator().next();
throw new MotanFrameworkException("url:" + exporter.getUrl() + " cannot share channel with url:" + url);
}
registry.addService(serviceDefine, provider);
if(httpHandler != null){
httpHandler.addProvider(provider);
}
serviceDefinetions.put(exporter.getUrl(), serviceDefine);
}
| 610
| 220
| 830
|
<no_super_class>
|
weibocom_motan
|
motan/motan-extension/protocol-extension/motan-protocol-grpc/src/main/java/com/weibo/api/motan/protocol/grpc/GrpcUtil.java
|
GrpcUtil
|
getGrpcClassName
|
class GrpcUtil {
@SuppressWarnings("rawtypes")
private static HashMap<String, HashMap<String, MethodDescriptor>> serviceMap = new HashMap<String, HashMap<String, MethodDescriptor>>();
public static final String JSON_CODEC = "grpc-pb-json";
@SuppressWarnings({"unchecked", "rawtypes"})
public static ServerServiceDefinition getServiceDefByAnnotation(Class<?> clazz) throws Exception {
ServiceDescriptor serviceDesc = getServiceDesc(getGrpcClassName(clazz));
io.grpc.ServerServiceDefinition.Builder builder = io.grpc.ServerServiceDefinition.builder(serviceDesc);
for (MethodDescriptor<?, ?> methodDesc : serviceDesc.getMethods()) {
builder.addMethod(methodDesc, new MotanServerCallHandler());
}
return builder.build();
}
private static String getGrpcClassName(Class<?> clazz) {<FILL_FUNCTION_BODY>}
public static ServiceDescriptor getServiceDesc(String clazzName) throws Exception {
Class<?> clazz = Class.forName(clazzName);
return (ServiceDescriptor) clazz.getMethod("getServiceDescriptor", null).invoke(null, null);
}
@SuppressWarnings("rawtypes")
public static HashMap<String, MethodDescriptor> getMethodDescriptorByAnnotation(Class<?> clazz, String serialization) throws Exception {
String clazzName = getGrpcClassName(clazz);
HashMap<String, MethodDescriptor> result = serviceMap.get(clazzName);
if (result == null) {
synchronized (serviceMap) {
if (!serviceMap.containsKey(clazzName)) {
ServiceDescriptor serviceDesc = getServiceDesc(getGrpcClassName(clazz));
HashMap<String, MethodDescriptor> methodMap = new HashMap<String, MethodDescriptor>();
for (MethodDescriptor<?, ?> methodDesc : serviceDesc.getMethods()) {
Method interfaceMethod = getMethod(methodDesc.getFullMethodName(), clazz);
if(JSON_CODEC.equals(serialization)){
methodDesc = convertJsonDescriptor(methodDesc, interfaceMethod.getParameterTypes()[0], interfaceMethod.getReturnType());
}
methodMap.put(interfaceMethod.getName(), methodDesc);
}
serviceMap.put(clazzName, methodMap);
}
result = serviceMap.get(clazzName);
}
}
return result;
}
public static Method getMethod(String name, Class<?> interfaceClazz) {
int index = name.lastIndexOf("/");
if (index > -1) {
name = name.substring(name.lastIndexOf("/") + 1);
}
Method[] methods = interfaceClazz.getMethods();
for (Method m : methods) {
if (m.getName().equalsIgnoreCase(name)) {
return m;
}
}
throw new MotanFrameworkException("not find grpc method");
}
public static MethodDescriptor convertJsonDescriptor(MethodDescriptor oldDesc, Class req, Class res){
MethodDescriptor.Marshaller reqMarshaller = getJsonMarshaller(req);
MethodDescriptor.Marshaller resMarshaller = getJsonMarshaller(res);
if(reqMarshaller != null && resMarshaller != null){
return MethodDescriptor.create(oldDesc.getType(), oldDesc.getFullMethodName(), reqMarshaller, resMarshaller);
}
return null;
}
public static MethodDescriptor.Marshaller getJsonMarshaller(Class clazz) {
try {
if (MessageLite.class.isAssignableFrom(clazz)) {
Method method = clazz.getDeclaredMethod("getDefaultInstance", null);
Message message = (Message) method.invoke(null, null);
return jsonMarshaller(message);
}
} catch (Exception ignore) {
}
return null;
}
public static <T extends Message> MethodDescriptor.Marshaller<T> jsonMarshaller(final T defaultInstance) {
final JsonFormat.Printer printer = JsonFormat.printer().preservingProtoFieldNames();
final JsonFormat.Parser parser = JsonFormat.parser();
final Charset charset = Charset.forName("UTF-8");
return new MethodDescriptor.Marshaller<T>() {
@Override
public InputStream stream(T value) {
try {
return new ByteArrayInputStream(printer.print(value).getBytes(charset));
} catch (InvalidProtocolBufferException e) {
throw Status.INTERNAL
.withCause(e)
.withDescription("Unable to print json proto")
.asRuntimeException();
}
}
@SuppressWarnings("unchecked")
@Override
public T parse(InputStream stream) {
Message.Builder builder = defaultInstance.newBuilderForType();
Reader reader = new InputStreamReader(stream, charset);
T proto;
try {
parser.merge(reader, builder);
proto = (T) builder.build();
reader.close();
} catch (InvalidProtocolBufferException e) {
throw Status.INTERNAL.withDescription("Invalid protobuf byte sequence")
.withCause(e).asRuntimeException();
} catch (IOException e) {
// Same for now, might be unavailable
throw Status.INTERNAL.withDescription("Invalid protobuf byte sequence")
.withCause(e).asRuntimeException();
}
return proto;
}
};
}
}
|
GrpcConfig config = clazz.getAnnotation(GrpcConfig.class);
if (config == null || StringUtils.isBlank(config.grpc())) {
throw new MotanFrameworkException("can not find grpc config in class " + clazz.getName());
}
return config.grpc();
| 1,389
| 78
| 1,467
|
<no_super_class>
|
weibocom_motan
|
motan/motan-extension/protocol-extension/motan-protocol-grpc/src/main/java/com/weibo/api/motan/protocol/grpc/MotanHandlerRegistry.java
|
MotanHandlerRegistry
|
addService
|
class MotanHandlerRegistry extends HandlerRegistry {
private ConcurrentHashMap<String, ServerMethodDefinition<?, ?>> methods = new ConcurrentHashMap<String, ServerMethodDefinition<?, ?>>();
@Override
public ServerMethodDefinition<?, ?> lookupMethod(String methodName, String authority) {
return methods.get(methodName);
}
@SuppressWarnings({"rawtypes", "unchecked"})
public void addService(ServerServiceDefinition service, Provider provider) {<FILL_FUNCTION_BODY>}
@SuppressWarnings("rawtypes")
public void addService(BindableService bindableService, Provider provider) {
addService(bindableService.bindService(), provider);
}
public void removeService(ServerServiceDefinition service) {
if (service != null) {
for (ServerMethodDefinition<?, ?> method : service.getMethods()) {
methods.remove(method.getMethodDescriptor().getFullMethodName());
}
}
}
}
|
for (ServerMethodDefinition<?, ?> method : service.getMethods()) {
Method providerMethod = GrpcUtil.getMethod(method.getMethodDescriptor().getFullMethodName(), provider.getInterface());
MotanServerCallHandler handler;
if (method.getServerCallHandler() instanceof MotanServerCallHandler) {
handler = (MotanServerCallHandler) method.getServerCallHandler();
} else {
handler = new MotanServerCallHandler();
method = method.withServerCallHandler(handler);
}
handler.init(provider, providerMethod);
if (GrpcUtil.JSON_CODEC.equals(provider.getUrl().getParameter(URLParamType.serialize.getName()))) {
MethodDescriptor jsonDesc = GrpcUtil.convertJsonDescriptor(method.getMethodDescriptor(), providerMethod.getParameterTypes()[0], providerMethod.getReturnType());
if(jsonDesc != null){
method = ServerMethodDefinition.create(jsonDesc, method.getServerCallHandler());
LoggerUtil.info("grpc method " + jsonDesc.getFullMethodName() +" use codec json.");
}
}
methods.put(method.getMethodDescriptor().getFullMethodName(), method);
}
| 255
| 299
| 554
|
<no_super_class>
|
weibocom_motan
|
motan/motan-extension/protocol-extension/motan-protocol-grpc/src/main/java/com/weibo/api/motan/protocol/grpc/http/HttpProtocolNegotiator.java
|
HttpAdapter
|
channelRead
|
class HttpAdapter extends ChannelInboundHandlerAdapter implements Handler {
private Http2ConnectionHandler handler;
private int maxContentLength = 1024 * 1024 * 64;
public HttpAdapter(Http2ConnectionHandler handler) {
super();
this.handler = handler;
}
@Override
public AsciiString scheme() {
return AsciiString.of("http");
}
public int getMaxContentLength() {
return maxContentLength;
}
public void setMaxContentLength(int maxContentLength) {
this.maxContentLength = maxContentLength;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {<FILL_FUNCTION_BODY>}
}
|
// TODO graceful validation
ByteBuf bf = ((ByteBuf) msg).copy();
Http2Validator validator = new Http2Validator();
validator.channelRead(null, bf);
if (validator.isHttp2()) {
ctx.pipeline().replace(this, null, handler);
} else {
ctx.pipeline().addLast("http-decoder", new HttpRequestDecoder());
ctx.pipeline().addLast("http-aggregator", new HttpObjectAggregator(maxContentLength));
ctx.pipeline().addLast("http-encoder", new HttpResponseEncoder());
ctx.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
ctx.pipeline().addLast("serverHandler", httpHandler);
}
ctx.fireChannelRead(msg);
| 196
| 203
| 399
|
<no_super_class>
|
weibocom_motan
|
motan/motan-extension/protocol-extension/motan-protocol-restful/src/main/java/com/weibo/api/motan/protocol/restful/RestfulProtocol.java
|
RestfulExporter
|
unexport
|
class RestfulExporter<T> extends AbstractExporter<T> {
private RestServer server;
private EndpointFactory endpointFactory;
public RestfulExporter(Provider<T> provider, URL url) {
super(provider, url);
endpointFactory = ExtensionLoader.getExtensionLoader(EndpointFactory.class).getExtension(
url.getParameter(URLParamType.endpointFactory.getName(), URLParamType.endpointFactory.getValue()));
server = endpointFactory.createServer(url);
}
@Override
public void unexport() {<FILL_FUNCTION_BODY>}
@Override
public void destroy() {
endpointFactory.safeReleaseResource(server, url);
LoggerUtil.info("RestfulExporter destory Success: url={}", url);
}
@Override
protected boolean doInit() {
server.getDeployment().getRegistry().addResourceFactory(new ProviderResource<T>(provider));
return true;
}
}
|
server.getDeployment().getRegistry().removeRegistrations(provider.getInterface());
String protocolKey = MotanFrameworkUtil.getProtocolKey(url);
@SuppressWarnings("unchecked")
Exporter<T> exporter = (Exporter<T>) exporterMap.remove(protocolKey);
if (exporter != null) {
exporter.destroy();
}
LoggerUtil.info("RestfulExporter unexport Success: url={}", url);
| 275
| 139
| 414
|
<methods>public non-sealed void <init>() ,public void destroy() ,public Exporter<T> export(Provider<T>, com.weibo.api.motan.rpc.URL) ,public Map<java.lang.String,Exporter<?>> getExporterMap() ,public Referer<T> refer(Class<T>, com.weibo.api.motan.rpc.URL) ,public Referer<T> refer(Class<T>, com.weibo.api.motan.rpc.URL, com.weibo.api.motan.rpc.URL) <variables>protected ConcurrentHashMap<java.lang.String,Exporter<?>> exporterMap
|
weibocom_motan
|
motan/motan-extension/protocol-extension/motan-protocol-restful/src/main/java/com/weibo/api/motan/protocol/restful/support/AbstractEndpointFactory.java
|
AbstractEndpointFactory
|
createClient
|
class AbstractEndpointFactory implements EndpointFactory {
/** 维持share channel 的service列表 **/
protected final Map<String, RestServer> ipPort2ServerShareChannel = new HashMap<String, RestServer>();
// 维持share channel 的client列表 <ip:port,client>
protected final Map<String, ResteasyWebTarget> ipPort2ClientShareChannel = new HashMap<String, ResteasyWebTarget>();
protected Map<RestServer, Set<String>> server2UrlsShareChannel = new HashMap<RestServer, Set<String>>();
protected Map<ResteasyWebTarget, Set<String>> client2UrlsShareChannel = new HashMap<ResteasyWebTarget, Set<String>>();
@Override
public RestServer createServer(URL url) {
String ipPort = url.getServerPortStr();
String protocolKey = MotanFrameworkUtil.getProtocolKey(url);
LoggerUtil.info(this.getClass().getSimpleName() + " create share_channel server: url={}", url);
synchronized (ipPort2ServerShareChannel) {
RestServer server = ipPort2ServerShareChannel.get(ipPort);
if (server != null) {
saveEndpoint2Urls(server2UrlsShareChannel, server, protocolKey);
return server;
}
url = url.createCopy();
url.setPath(""); // 共享server端口,由于有多个interfaces存在,所以把path设置为空
server = innerCreateServer(url);
server.start();
ipPort2ServerShareChannel.put(ipPort, server);
saveEndpoint2Urls(server2UrlsShareChannel, server, protocolKey);
return server;
}
}
@Override
public ResteasyWebTarget createClient(URL url) {<FILL_FUNCTION_BODY>}
@Override
public void safeReleaseResource(RestServer server, URL url) {
String ipPort = url.getServerPortStr();
String protocolKey = MotanFrameworkUtil.getProtocolKey(url);
synchronized (ipPort2ServerShareChannel) {
if (server != ipPort2ServerShareChannel.get(ipPort)) {
server.stop();
return;
}
Set<String> urls = server2UrlsShareChannel.get(server);
urls.remove(protocolKey);
if (urls.isEmpty()) {
server.stop();
ipPort2ServerShareChannel.remove(ipPort);
server2UrlsShareChannel.remove(server);
}
}
}
@Override
public void safeReleaseResource(ResteasyWebTarget client, URL url) {
String ipPort = url.getServerPortStr();
String protocolKey = MotanFrameworkUtil.getProtocolKey(url);
synchronized (ipPort2ClientShareChannel) {
if (client != ipPort2ClientShareChannel.get(ipPort)) {
client.getResteasyClient().close();
return;
}
Set<String> urls = client2UrlsShareChannel.get(client);
urls.remove(protocolKey);
if (urls.isEmpty()) {
client.getResteasyClient().close();
ipPort2ClientShareChannel.remove(ipPort);
client2UrlsShareChannel.remove(client);
}
}
}
private <T> void saveEndpoint2Urls(Map<T, Set<String>> map, T endpoint, String protocolKey) {
Set<String> sets = map.get(endpoint);
if (sets == null) {
sets = new HashSet<String>();
map.put(endpoint, sets);
}
sets.add(protocolKey);
}
protected abstract RestServer innerCreateServer(URL url);
protected ResteasyWebTarget innerCreateClient(URL url) {
ResteasyClient client = new ResteasyClientBuilder().build();
String contextpath = url.getParameter("contextpath", "/");
if (!contextpath.startsWith("/"))
contextpath = "/" + contextpath;
return client.target("http://" + url.getHost() + ":" + url.getPort() + contextpath);
}
}
|
String ipPort = url.getServerPortStr();
String protocolKey = MotanFrameworkUtil.getProtocolKey(url);
LoggerUtil.info(this.getClass().getSimpleName() + " create share_channel client: url={}", url);
synchronized (ipPort2ClientShareChannel) {
ResteasyWebTarget client = ipPort2ClientShareChannel.get(ipPort);
if (client != null) {
saveEndpoint2Urls(client2UrlsShareChannel, client, protocolKey);
return client;
}
client = innerCreateClient(url);
ipPort2ClientShareChannel.put(ipPort, client);
saveEndpoint2Urls(client2UrlsShareChannel, client, protocolKey);
return client;
}
| 1,167
| 217
| 1,384
|
<no_super_class>
|
weibocom_motan
|
motan/motan-extension/protocol-extension/motan-protocol-restful/src/main/java/com/weibo/api/motan/protocol/restful/support/RestfulInjectorFactory.java
|
RestfulMethodInjector
|
invoke
|
class RestfulMethodInjector extends MethodInjectorImpl {
public RestfulMethodInjector(ResourceLocator resourceMethod, ResteasyProviderFactory factory) {
super(resourceMethod, factory);
}
@Override
public Object invoke(HttpRequest request, HttpResponse httpResponse, Object resource)
throws Failure, ApplicationException {<FILL_FUNCTION_BODY>}
}
|
if (!Provider.class.isInstance(resource)) {
return super.invoke(request, httpResponse, resource);
}
Object[] args = injectArguments(request, httpResponse);
RestfulContainerRequest req = new RestfulContainerRequest();
req.setInterfaceName(method.getResourceClass().getClazz().getName());
req.setMethodName(method.getMethod().getName());
req.setParamtersDesc(ReflectUtil.getMethodParamDesc(method.getMethod()));
req.setArguments(args);
req.setHttpRequest(request);
req.setAttachments(RestfulUtil.decodeAttachments(request.getMutableHeaders()));
try {
Response resp = Provider.class.cast(resource).call(req);
RestfulUtil.encodeAttachments(httpResponse.getOutputHeaders(), resp.getAttachments());
return resp.getValue();
} catch (Exception e) {
if (e != null && e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new InternalServerErrorException("provider call process error:" + e.getMessage(), e);
}
| 111
| 314
| 425
|
<no_super_class>
|
weibocom_motan
|
motan/motan-extension/protocol-extension/motan-protocol-restful/src/main/java/com/weibo/api/motan/protocol/restful/support/RestfulUtil.java
|
RestfulUtil
|
encodeAttachments
|
class RestfulUtil {
public static final String ATTACHMENT_HEADER = "X-Attach";
public static final String EXCEPTION_HEADER = "X-Exception";
public static boolean isRpcRequest(MultivaluedMap<String, String> headers) {
return headers != null && headers.containsKey(ATTACHMENT_HEADER);
}
public static void encodeAttachments(MultivaluedMap<String, Object> headers, Map<String, String> attachments) {<FILL_FUNCTION_BODY>}
public static Map<String, String> decodeAttachments(MultivaluedMap<String, String> headers) {
String value = headers.getFirst(ATTACHMENT_HEADER);
Map<String, String> result = Collections.emptyMap();
if (value != null && !value.isEmpty()) {
result = new HashMap<String, String>();
for (String kv : value.split(";")) {
String[] pair = kv.split("=");
if (pair.length == 2) {
result.put(StringTools.urlDecode(pair[0]), StringTools.urlDecode(pair[1]));
}
}
}
return result;
}
public static Response serializeError(Exception ex) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(ex);
oos.flush();
String info = new String(Base64.encodeBytesToBytes(baos.toByteArray()), MotanConstants.DEFAULT_CHARACTER);
return Response.status(Status.EXPECTATION_FAILED).header(EXCEPTION_HEADER, ex.getClass()).entity(info)
.build();
} catch (IOException e) {
LoggerUtil.error("serialize " + ex.getClass() + " error", e);
return Response.status(Status.INTERNAL_SERVER_ERROR).entity("serialization " + ex.getClass() + " error")
.build();
}
}
public static Exception getCause(BuiltResponse resp) {
if (resp == null || resp.getStatus() != Status.EXPECTATION_FAILED.getStatusCode())
return null;
String exceptionClass = resp.getHeaderString(EXCEPTION_HEADER);
if (!StringUtils.isBlank(exceptionClass)) {
String body = resp.readEntity(String.class);
resp.close();
try {
ByteArrayInputStream bais = new ByteArrayInputStream(
Base64.decode(body.getBytes(MotanConstants.DEFAULT_CHARACTER)));
ObjectInputStream ois = new ObjectInputStream(bais);
return (Exception) ois.readObject();
} catch (Exception e) {
LoggerUtil.error("deserialize " + exceptionClass + " error", e);
}
}
return null;
}
}
|
if (attachments == null || attachments.isEmpty())
return;
StringBuilder value = new StringBuilder();
for (Map.Entry<String, String> entry : attachments.entrySet()) {
value.append(StringTools.urlEncode(entry.getKey())).append("=")
.append(StringTools.urlEncode(entry.getValue())).append(";");
}
if (value.length() > 1)
value.deleteCharAt(value.length() - 1);
headers.add(ATTACHMENT_HEADER, value.toString());
| 814
| 162
| 976
|
<no_super_class>
|
weibocom_motan
|
motan/motan-extension/protocol-extension/motan-protocol-restful/src/main/java/com/weibo/api/motan/protocol/restful/support/RpcExceptionMapper.java
|
RpcExceptionMapper
|
toResponse
|
class RpcExceptionMapper implements ExceptionMapper<Exception> {
@Override
public Response toResponse(Exception exception) {<FILL_FUNCTION_BODY>}
}
|
HttpRequest httpRequest = ResteasyProviderFactory.getContextData(HttpRequest.class);
// 当为rpc调用时,序列化异常
if (httpRequest != null && RestfulUtil.isRpcRequest(httpRequest.getMutableHeaders())) {
return RestfulUtil.serializeError(exception);
}
return Response.status(Status.INTERNAL_SERVER_ERROR).entity(exception.getMessage()).build();
| 49
| 119
| 168
|
<no_super_class>
|
weibocom_motan
|
motan/motan-extension/protocol-extension/motan-protocol-restful/src/main/java/com/weibo/api/motan/protocol/restful/support/netty/NettyEndpointFactory.java
|
NettyEndpointFactory
|
innerCreateServer
|
class NettyEndpointFactory extends AbstractEndpointFactory {
@Override
protected RestServer innerCreateServer(URL url) {<FILL_FUNCTION_BODY>}
}
|
NettyJaxrsServer server = new NettyJaxrsServer();
server.setMaxRequestSize(url.getIntParameter(URLParamType.maxContentLength.getName(),
URLParamType.maxContentLength.getIntValue()));
ResteasyDeployment deployment = new ResteasyDeployment();
server.setDeployment(deployment);
server.setExecutorThreadCount(url.getIntParameter(URLParamType.maxWorkerThread.getName(),
URLParamType.maxWorkerThread.getIntValue()));
server.setPort(url.getPort());
server.setRootResourcePath("");
server.setSecurityDomain(null);
deployment.setInjectorFactoryClass(RestfulInjectorFactory.class.getName());
deployment.getProviderClasses().add(RpcExceptionMapper.class.getName());
return new EmbedRestServer(server);
| 49
| 234
| 283
|
<methods>public non-sealed void <init>() ,public ResteasyWebTarget createClient(com.weibo.api.motan.rpc.URL) ,public com.weibo.api.motan.protocol.restful.RestServer createServer(com.weibo.api.motan.rpc.URL) ,public void safeReleaseResource(com.weibo.api.motan.protocol.restful.RestServer, com.weibo.api.motan.rpc.URL) ,public void safeReleaseResource(ResteasyWebTarget, com.weibo.api.motan.rpc.URL) <variables>protected Map<ResteasyWebTarget,Set<java.lang.String>> client2UrlsShareChannel,protected final Map<java.lang.String,ResteasyWebTarget> ipPort2ClientShareChannel,protected final Map<java.lang.String,com.weibo.api.motan.protocol.restful.RestServer> ipPort2ServerShareChannel,protected Map<com.weibo.api.motan.protocol.restful.RestServer,Set<java.lang.String>> server2UrlsShareChannel
|
weibocom_motan
|
motan/motan-extension/protocol-extension/motan-protocol-restful/src/main/java/com/weibo/api/motan/protocol/restful/support/proxy/RestfulClientInvoker.java
|
RestfulClientInvoker
|
invoke
|
class RestfulClientInvoker extends ClientInvoker {
public RestfulClientInvoker(ResteasyWebTarget parent, Class<?> declaring, Method method, ProxyConfig config) {
super(parent, declaring, method, config);
}
public Object invoke(Object[] args, Request req, RestfulClientResponse resp) {<FILL_FUNCTION_BODY>}
protected ClientInvocation createRequest(Object[] args, Request request) {
ClientInvocation inv = super.createRequest(args);
RestfulUtil.encodeAttachments(inv.getHeaders().getHeaders(), request.getAttachments());
return inv;
}
}
|
ClientInvocation request = createRequest(args, req);
ClientResponse response = (ClientResponse) request.invoke();
resp.setAttachments(RestfulUtil.decodeAttachments(response.getStringHeaders()));
resp.setHttpResponse(response);
ClientContext context = new ClientContext(request, response, entityExtractorFactory);
return extractor.extractEntity(context);
| 163
| 96
| 259
|
<no_super_class>
|
weibocom_motan
|
motan/motan-extension/protocol-extension/motan-protocol-restful/src/main/java/com/weibo/api/motan/protocol/restful/support/proxy/RestfulProxyBuilder.java
|
RestfulProxyBuilder
|
proxy
|
class RestfulProxyBuilder<T> {
private final Class<T> iface;
private final ResteasyWebTarget webTarget;
private ClassLoader loader = Thread.currentThread().getContextClassLoader();
private MediaType serverConsumes;
private MediaType serverProduces;
public static <T> RestfulProxyBuilder<T> builder(Class<T> iface, WebTarget webTarget) {
return new RestfulProxyBuilder<T>(iface, (ResteasyWebTarget) webTarget);
}
public static Map<Method, RestfulClientInvoker> proxy(final Class<?> iface, WebTarget base,
final ProxyConfig config) {<FILL_FUNCTION_BODY>}
private static <T> RestfulClientInvoker createClientInvoker(Class<T> clazz, Method method, ResteasyWebTarget base,
ProxyConfig config) {
Set<String> httpMethods = IsHttpMethod.getHttpMethods(method);
if (httpMethods == null || httpMethods.size() != 1) {
throw new RuntimeException(
"You must use at least one, but no more than one http method annotation on: " + method.toString());
}
RestfulClientInvoker invoker = new RestfulClientInvoker(base, clazz, method, config);
invoker.setHttpMethod(httpMethods.iterator().next());
return invoker;
}
private RestfulProxyBuilder(Class<T> iface, ResteasyWebTarget webTarget) {
this.iface = iface;
this.webTarget = webTarget;
}
public RestfulProxyBuilder<T> classloader(ClassLoader cl) {
this.loader = cl;
return this;
}
public RestfulProxyBuilder<T> defaultProduces(MediaType type) {
this.serverProduces = type;
return this;
}
public RestfulProxyBuilder<T> defaultConsumes(MediaType type) {
this.serverConsumes = type;
return this;
}
public RestfulProxyBuilder<T> defaultProduces(String type) {
this.serverProduces = MediaType.valueOf(type);
return this;
}
public RestfulProxyBuilder<T> defaultConsumes(String type) {
this.serverConsumes = MediaType.valueOf(type);
return this;
}
public Map<Method, RestfulClientInvoker> build() {
return proxy(iface, webTarget, new ProxyConfig(loader, serverConsumes, serverProduces));
}
}
|
if (iface.isAnnotationPresent(Path.class)) {
Path path = iface.getAnnotation(Path.class);
if (!path.value().equals("") && !path.value().equals("/")) {
base = base.path(path.value());
}
}
HashMap<Method, RestfulClientInvoker> methodMap = new HashMap<Method, RestfulClientInvoker>();
for (Method method : iface.getMethods()) {
RestfulClientInvoker invoker = createClientInvoker(iface, method, (ResteasyWebTarget) base, config);
methodMap.put(method, invoker);
}
return methodMap;
| 639
| 170
| 809
|
<no_super_class>
|
weibocom_motan
|
motan/motan-extension/protocol-extension/motan-protocol-restful/src/main/java/com/weibo/api/motan/protocol/restful/support/servlet/RestfulServletContainerListener.java
|
RestfulServletContainerListener
|
contextInitialized
|
class RestfulServletContainerListener extends ResteasyBootstrap implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {<FILL_FUNCTION_BODY>}
@Override
public void contextDestroyed(ServletContextEvent sce) {
super.contextDestroyed(sce);
}
}
|
ServletContext servletContext = sce.getServletContext();
servletContext.setInitParameter("resteasy.injector.factory", RestfulInjectorFactory.class.getName());
servletContext.setInitParameter(ResteasyContextParameters.RESTEASY_PROVIDERS,
RpcExceptionMapper.class.getName());
super.contextInitialized(sce);
ServletRestServer.setResteasyDeployment(deployment);
| 90
| 118
| 208
|
<no_super_class>
|
weibocom_motan
|
motan/motan-extension/protocol-extension/motan-protocol-restful/src/main/java/com/weibo/api/motan/protocol/restful/support/servlet/ServletRestServer.java
|
ServletRestServer
|
checkEnv
|
class ServletRestServer implements RestServer {
private static ResteasyDeployment deployment;
public static void setResteasyDeployment(ResteasyDeployment deployment) {
ServletRestServer.deployment = deployment;
}
public void checkEnv() {<FILL_FUNCTION_BODY>}
@Override
public void start() {
}
@Override
public ResteasyDeployment getDeployment() {
return deployment;
}
@Override
public void stop() {
}
}
|
if (deployment == null) {
throw new MotanFrameworkException("please config <listener-class>"
+ RestfulServletContainerListener.class.getName() + "</listener-class> in your web.xml file");
}
| 159
| 68
| 227
|
<no_super_class>
|
weibocom_motan
|
motan/motan-extension/protocol-extension/motan-protocol-yar/src/main/java/com/weibo/api/motan/protocol/yar/YarExporter.java
|
YarExporter
|
validateInterface
|
class YarExporter<T> extends AbstractExporter<T> {
protected Server server;
private YarRpcProtocol yarProtocol;
public YarExporter(URL url, Provider<T> provider, YarRpcProtocol yarProtocol) {
super(provider, url);
EndpointFactory endpointFactory =
ExtensionLoader.getExtensionLoader(EndpointFactory.class).getExtension(
url.getParameter(URLParamType.endpointFactory.getName(), "netty4yar"));
// set noheartbeat factory
String heartbeatFactory = url.getParameter(URLParamType.heartbeatFactory.getName());
if (heartbeatFactory == null) {
url.addParameter(URLParamType.heartbeatFactory.getName(), "noHeartbeat");
}
// FIXME to avoid parameters ambiguous in weak type language,parameters size of method with
// same name must be different.
validateInterface(provider.getInterface());
server = endpointFactory.createServer(url, yarProtocol.initRequestRouter(url, provider));
}
@Override
public void destroy() {
server.close();
}
@Override
public boolean isAvailable() {
return server.isAvailable();
}
@Override
public void unexport() {
yarProtocol.unexport(url, provider);
}
@Override
protected boolean doInit() {
return server.open();
}
protected void validateInterface(Class<?> interfaceClazz) {<FILL_FUNCTION_BODY>}
}
|
HashMap<String, List<Integer>> tempMap = new HashMap<String, List<Integer>>();
for (Method m : interfaceClazz.getDeclaredMethods()) {
if (!tempMap.containsKey(m.getName())) {
List<Integer> templist = new ArrayList<Integer>();
templist.add(m.getParameterTypes().length);
tempMap.put(m.getName(), templist);
} else {
List<Integer> templist = tempMap.get(m.getName());
if (templist.contains(m.getParameterTypes().length)) {
throw new MotanFrameworkException("in yar protocol, methods with same name must have different params size !");
} else {
templist.add(m.getParameterTypes().length);
}
}
}
| 387
| 200
| 587
|
<methods>public void <init>(Provider<T>, com.weibo.api.motan.rpc.URL) ,public java.lang.String desc() ,public Provider<T> getProvider() ,public Map<java.lang.String,java.lang.Object> getRuntimeInfo() <variables>protected Provider<T> provider
|
weibocom_motan
|
motan/motan-extension/protocol-extension/motan-protocol-yar/src/main/java/com/weibo/api/motan/protocol/yar/YarMessageRouter.java
|
YarMessageRouter
|
handle
|
class YarMessageRouter extends ProviderMessageRouter {
protected ConcurrentHashMap<String, Provider<?>> providerMap = new ConcurrentHashMap<String, Provider<?>>();
public YarMessageRouter() {
super();
}
public YarMessageRouter(URL url) {
super(url);
}
@Override
public Object handle(Channel channel, Object message) {<FILL_FUNCTION_BODY>}
@Override
public void addProvider(Provider<?> provider) {
String path = YarProtocolUtil.getYarPath(provider.getInterface(), provider.getUrl());
Provider<?> old = providerMap.putIfAbsent(path, provider);
if (old != null) {
throw new MotanFrameworkException("duplicate yar provider");
}
}
@Override
public void removeProvider(Provider<?> provider) {
String path = YarProtocolUtil.getYarPath(provider.getInterface(), provider.getUrl());
providerMap.remove(path);
}
}
|
YarRequest yarRequest = (YarRequest) message;
String packagerName = yarRequest.getPackagerName();
Provider<?> provider = providerMap.get(yarRequest.getRequestPath());
if (provider == null) {
throw new MotanServiceException("can not find service provider. request path:" + yarRequest.getRequestPath());
}
Class<?> clazz = provider.getInterface();
Request request = YarProtocolUtil.convert(yarRequest, clazz);
Response response = call(request, provider);
YarResponse yarResponse = YarProtocolUtil.convert(response, packagerName);
return yarResponse;
| 272
| 170
| 442
|
<methods>public void <init>() ,public void <init>(com.weibo.api.motan.rpc.URL) ,public void <init>(Provider<?>) ,public synchronized void addProvider(Provider<?>) ,public int getPublicMethodCount() ,public Map<java.lang.String,java.lang.Object> getRuntimeInfo() ,public java.lang.Object handle(com.weibo.api.motan.transport.Channel, java.lang.Object) ,public synchronized void removeProvider(Provider<?>) <variables>private static final boolean STRICT_CHECK_GROUP,protected Map<java.lang.String,Provider<?>> frameworkProviders,protected java.util.concurrent.atomic.AtomicInteger methodCounter,protected Map<java.lang.String,Provider<?>> providers,protected com.weibo.api.motan.transport.ProviderProtectedStrategy strategy
|
weibocom_motan
|
motan/motan-extension/protocol-extension/motan-protocol-yar/src/main/java/com/weibo/api/motan/protocol/yar/YarProtocolUtil.java
|
YarProtocolUtil
|
adaptParams
|
class YarProtocolUtil {
public static String getYarPath(Class<?> interfaceClazz, URL url) {
if (interfaceClazz != null) {
YarConfig config = interfaceClazz.getAnnotation(YarConfig.class);
if (config != null && StringUtils.isNotBlank(config.path())) {
return config.path();
}
}
// '/group/urlpath' as default
return "/" + url.getGroup() + "/" + url.getPath();
}
/**
* convert yar request to motan rpc request
*
* @param yarRequest
* @param interfaceClass
* @return
*/
public static Request convert(YarRequest yarRequest, Class<?> interfaceClass) {
DefaultRequest request = new DefaultRequest();
request.setInterfaceName(interfaceClass.getName());
request.setMethodName(yarRequest.getMethodName());
request.setRequestId(yarRequest.getId());
addArguments(request, interfaceClass, yarRequest.getMethodName(), yarRequest.getParameters());
if (yarRequest instanceof AttachmentRequest) {
request.setAttachments(((AttachmentRequest) yarRequest).getAttachments());
}
return request;
}
public static YarRequest convert(Request request, String packagerName) {
YarRequest yarRequest = new YarRequest();
yarRequest.setId(request.getRequestId());
yarRequest.setMethodName(request.getMethodName());
yarRequest.setPackagerName(packagerName);
yarRequest.setParameters(request.getArguments());
return yarRequest;
}
public static Response convert(YarResponse yarResponse) {
DefaultResponse response = new DefaultResponse();
response.setRequestId(yarResponse.getId());
response.setValue(yarResponse.getRet());
if (StringUtils.isNotBlank(yarResponse.getError())) {
response.setException(new MotanBizException(yarResponse.getError()));
}
return response;
}
public static YarResponse convert(Response response, String packagerName) {
YarResponse yarResponse = new YarResponse();
yarResponse.setId(response.getRequestId());
yarResponse.setPackagerName(packagerName);
if (response.getException() != null) {
if (response.getException() instanceof MotanBizException) {
yarResponse.setError(response.getException().getCause().getMessage());
} else {
yarResponse.setError(response.getException().getMessage());
}
} else {
yarResponse.setRet(response.getValue());
}
return yarResponse;
}
/**
* add arguments
*
* @param interfaceClass
* @param methodName
* @param arguments
* @return
*/
private static void addArguments(DefaultRequest request, Class<?> interfaceClass, String methodName, Object[] arguments) {
Method targetMethod = null;
Method[] methods = interfaceClass.getDeclaredMethods();
for (Method m : methods) {
// FIXME parameters may be ambiguous in weak type language, temporarily by limiting the
// size of parameters with same method name to avoid.
if (m.getName().equalsIgnoreCase(methodName) && m.getParameterTypes().length == arguments.length) {
targetMethod = m;
break;
}
}
if (targetMethod == null) {
throw new MotanServiceException("cann't find request method. method name " + methodName);
}
request.setParamtersDesc(ReflectUtil.getMethodParamDesc(targetMethod));
if (arguments != null && arguments.length > 0) {
Class<?>[] argumentClazz = targetMethod.getParameterTypes();
request.setArguments(adaptParams(targetMethod, arguments, argumentClazz));
}
}
public static YarResponse buildDefaultErrorResponse(String errMsg, String packagerName) {
YarResponse yarResponse = new YarResponse();
yarResponse.setPackagerName(packagerName);
yarResponse.setError(errMsg);
yarResponse.setStatus("500");
return yarResponse;
}
// adapt parameters to java class type
private static Object[] adaptParams(Method method, Object[] arguments, Class<?>[] argumentClazz) {<FILL_FUNCTION_BODY>}
}
|
// FIXME the real parameter type may not same with formal parameter, for instance, formal
// parameter type is int, the real parameter maybe use String in php
// any elegant way?
for (int i = 0; i < argumentClazz.length; i++) {
try {
if ("int".equals(argumentClazz[i].getName()) || "java.lang.Integer".equals(argumentClazz[i].getName())) {
if (arguments[i] == null) {
arguments[i] = 0;// default
} else if (arguments[i] instanceof String) {
arguments[i] = Integer.parseInt((String) arguments[i]);
} else if (arguments[i] instanceof Number) {
arguments[i] = ((Number) arguments[i]).intValue();
} else {
throw new RuntimeException();
}
} else if ("long".equals(argumentClazz[i].getName()) || "java.lang.Long".equals(argumentClazz[i].getName())) {
if (arguments[i] == null) {
arguments[i] = 0;// default
} else if (arguments[i] instanceof String) {
arguments[i] = Long.parseLong((String) arguments[i]);
} else if (arguments[i] instanceof Number) {
arguments[i] = ((Number) arguments[i]).longValue();
} else {
throw new RuntimeException();
}
} else if ("float".equals(argumentClazz[i].getName()) || "java.lang.Float".equals(argumentClazz[i].getName())) {
if (arguments[i] == null) {
arguments[i] = 0.0f;// default
} else if (arguments[i] instanceof String) {
arguments[i] = Float.parseFloat((String) arguments[i]);
} else if (arguments[i] instanceof Number) {
arguments[i] = ((Number) arguments[i]).floatValue();
} else {
throw new RuntimeException();
}
} else if ("double".equals(argumentClazz[i].getName()) || "java.lang.Double".equals(argumentClazz[i].getName())) {
if (arguments[i] == null) {
arguments[i] = 0.0f;// default
} else if (arguments[i] instanceof String) {
arguments[i] = Double.parseDouble((String) arguments[i]);
} else if (arguments[i] instanceof Number) {
arguments[i] = ((Number) arguments[i]).doubleValue();
} else {
throw new RuntimeException();
}
} else if ("boolean".equals(argumentClazz[i].getName()) || "java.lang.Boolean".equals(argumentClazz[i].getName())) {
if (arguments[i] instanceof Boolean) {
continue;
}
if (arguments[i] instanceof String) {
arguments[i] = Boolean.valueOf(((String) arguments[i]));
} else {
throw new RuntimeException();
}
}
} catch (Exception e) {
throw new MotanServiceException("adapt param fail! method:" + method.toString() + ", require param:"
+ argumentClazz[i].getName() + ", actual param:"
+ (arguments[i] == null ? null : arguments[i].getClass().getName() + "-" + arguments[i]));
}
}
return arguments;
| 1,143
| 833
| 1,976
|
<no_super_class>
|
weibocom_motan
|
motan/motan-extension/protocol-extension/motan-protocol-yar/src/main/java/com/weibo/api/motan/protocol/yar/YarRpcProtocol.java
|
YarRpcProtocol
|
unexport
|
class YarRpcProtocol extends AbstractProtocol {
private ConcurrentHashMap<String, ProviderMessageRouter> ipPort2RequestRouter = new ConcurrentHashMap<String, ProviderMessageRouter>();
@Override
protected <T> Exporter<T> createExporter(Provider<T> provider, URL url) {
return new YarExporter<T>(url, provider, this);
}
@Override
protected <T> Referer<T> createReferer(Class<T> clz, URL url, URL serviceUrl) {
//TODO
throw new MotanFrameworkException("not yet implemented!");
}
public ProviderMessageRouter initRequestRouter(URL url, Provider<?> provider) {
String ipPort = url.getServerPortStr();
ProviderMessageRouter requestRouter = ipPort2RequestRouter.get(ipPort);
if (requestRouter == null) {
ipPort2RequestRouter.putIfAbsent(ipPort, new YarMessageRouter(url));
requestRouter = ipPort2RequestRouter.get(ipPort);
}
requestRouter.addProvider(provider);
return requestRouter;
}
public void unexport(URL url, Provider<?> provider){<FILL_FUNCTION_BODY>}
}
|
String protocolKey = MotanFrameworkUtil.getProtocolKey(url);
String ipPort = url.getServerPortStr();
Exporter<?> exporter = (Exporter<?>) exporterMap.remove(protocolKey);
if (exporter != null) {
exporter.destroy();
}
synchronized (ipPort2RequestRouter) {
ProviderMessageRouter requestRouter = ipPort2RequestRouter.get(ipPort);
if (requestRouter != null) {
requestRouter.removeProvider(provider);
}
}
LoggerUtil.info("yarRpcExporter unexport Success: url={}", url);
| 333
| 174
| 507
|
<methods>public non-sealed void <init>() ,public void destroy() ,public Exporter<T> export(Provider<T>, com.weibo.api.motan.rpc.URL) ,public Map<java.lang.String,Exporter<?>> getExporterMap() ,public Referer<T> refer(Class<T>, com.weibo.api.motan.rpc.URL) ,public Referer<T> refer(Class<T>, com.weibo.api.motan.rpc.URL, com.weibo.api.motan.rpc.URL) <variables>protected ConcurrentHashMap<java.lang.String,Exporter<?>> exporterMap
|
weibocom_motan
|
motan/motan-extension/protocol-extension/motan-protocol-yar/src/main/java/com/weibo/api/motan/transport/netty4/yar/YarMessageHandlerWrapper.java
|
YarMessageHandlerWrapper
|
handle
|
class YarMessageHandlerWrapper implements HttpMessageHandler {
public static final String BAD_REQUEST = "/bad-request";
public static final String ROOT_PATH = "/";
public static final String STATUS_PATH = "/rpcstatus";
protected String switcherName = MotanConstants.REGISTRY_HEARTBEAT_SWITCHER;
private final YarMessageRouter orgHandler;
public YarMessageHandlerWrapper(MessageHandler orgHandler) {
if (orgHandler == null) {
throw new MotanFrameworkException("messageHandler is null!");
}
if (orgHandler instanceof YarMessageRouter) {
this.orgHandler = (YarMessageRouter) orgHandler;
} else {
throw new MotanFrameworkException("YarMessageHandlerWrapper can not wrapper " + orgHandler.getClass().getSimpleName());
}
}
@Override
public FullHttpResponse handle(Channel channel, FullHttpRequest httpRequest) {<FILL_FUNCTION_BODY>}
/**
* is service switcher close. http status will be 503 when switcher is close
*/
private boolean isSwitchOpen() {
return MotanSwitcherUtil.isOpen(switcherName);
}
}
|
QueryStringDecoder decoder = new QueryStringDecoder(httpRequest.uri());
String path = decoder.path();
// check badRequest
if (BAD_REQUEST.equals(path)) {
return NettyHttpUtil.buildDefaultResponse("bad request!", HttpResponseStatus.BAD_REQUEST);
}
// service status
if (ROOT_PATH.equals(path) || STATUS_PATH.equals(path)) {
if (isSwitchOpen()) {// 200
return NettyHttpUtil.buildDefaultResponse("ok!", HttpResponseStatus.OK);
}
//503
return NettyHttpUtil.buildErrorResponse("service not available!");
}
Map<String, String> attachments = null;
if (!decoder.parameters().isEmpty()) {
attachments = new HashMap<>(decoder.parameters().size());
for (Map.Entry<String, List<String>> entry : decoder.parameters().entrySet()) {
attachments.put(entry.getKey(), entry.getValue().get(0));
}
}
YarResponse yarResponse;
String packagerName = "JSON";
try {
ByteBuf buf = httpRequest.content();
final byte[] contentBytes = new byte[buf.readableBytes()];
buf.getBytes(0, contentBytes);
YarRequest yarRequest = new AttachmentRequest(YarProtocol.buildRequest(contentBytes), attachments);
yarRequest.setRequestPath(path);
yarResponse = (YarResponse) orgHandler.handle(channel, yarRequest);
} catch (Exception e) {
LoggerUtil.error("YarMessageHandlerWrapper handle yar request fail.", e);
yarResponse = YarProtocolUtil.buildDefaultErrorResponse(e.getMessage(), packagerName);
}
byte[] responseBytes;
try {
responseBytes = YarProtocol.toProtocolBytes(yarResponse);
} catch (IOException e) {
throw new MotanFrameworkException("convert yar response to bytes fail.", e);
}
FullHttpResponse httpResponse =
new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(responseBytes));
httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/x-www-form-urlencoded");
httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, httpResponse.content().readableBytes());
if (HttpUtil.isKeepAlive(httpRequest)) {
httpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
} else {
httpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
}
return httpResponse;
| 305
| 696
| 1,001
|
<no_super_class>
|
weibocom_motan
|
motan/motan-extension/serialization-extension/src/main/java/com/weibo/api/motan/serialize/GrpcPbSerialization.java
|
GrpcPbSerialization
|
deserializeMulti
|
class GrpcPbSerialization implements Serialization {
@Override
public byte[] serialize(Object obj) throws IOException {
if (obj == null) {
throw new IllegalArgumentException("can't serialize null.");
}
if (MessageLite.class.isAssignableFrom(obj.getClass())) {
return ((MessageLite) obj).toByteArray();
} else {
throw new IllegalArgumentException("can't serialize " + obj.getClass());
}
}
@SuppressWarnings("unchecked")
@Override
public <T> T deserialize(byte[] bytes, Class<T> clazz) throws IOException {
if (MessageLite.class.isAssignableFrom(clazz)) {
try {
ByteArrayInputStream input = new ByteArrayInputStream(bytes);
Method method = clazz.getDeclaredMethod("parseFrom", java.io.InputStream.class);
return (T) method.invoke(null, input);
} catch (Exception e) {
throw new MotanFrameworkException(e);
}
} else {
throw new IllegalArgumentException("can't serialize " + clazz);
}
}
@Override
public byte[] serializeMulti(Object[] data) throws IOException {
if (data.length == 1) {
return serialize(data[0]);
}
throw new MotanServiceException("GrpcPbSerialization not support serialize multi Object");
}
@Override
public Object[] deserializeMulti(byte[] data, Class<?>[] classes) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public int getSerializationNumber() {
return 1;
}
}
|
if (classes.length != 1) {
throw new MotanServiceException("only single value serialize was supported in GrpcPbSerialization");
}
Object[] objects = new Object[1];
objects[0] = deserialize(data, classes[0]);
return objects;
| 429
| 75
| 504
|
<no_super_class>
|
weibocom_motan
|
motan/motan-extension/serialization-extension/src/main/java/com/weibo/api/motan/serialize/HproseSerialization.java
|
HproseSerialization
|
serializeMulti
|
class HproseSerialization implements Serialization {
@Override
public byte[] serialize(Object data) throws IOException {
ByteBufferStream stream = null;
try {
stream = new ByteBufferStream();
HproseWriter writer = new HproseWriter(stream.getOutputStream());
writer.serialize(data);
byte[] result = stream.toArray();
return result;
}
finally {
if (stream != null) {
stream.close();
}
}
}
@SuppressWarnings("unchecked")
@Override
public <T> T deserialize(byte[] data, Class<T> clz) throws IOException {
return new HproseReader(data).unserialize(clz);
}
@Override
public byte[] serializeMulti(Object[] data) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public Object[] deserializeMulti(byte[] data, Class<?>[] classes) throws IOException {
HproseReader reader = new HproseReader(data);
Object[] objects = new Object[classes.length];
for (int i = 0; i < classes.length; i++){
objects[i] = reader.unserialize(classes[i]);
}
return objects;
}
@Override
public int getSerializationNumber() {
return 4;
}
}
|
ByteBufferStream stream = null;
try {
stream = new ByteBufferStream();
HproseWriter writer = new HproseWriter(stream.getOutputStream());
for (Object o : data) {
writer.serialize(o);
}
byte[] result = stream.toArray();
return result;
} finally {
if (stream != null) {
stream.close();
}
}
| 354
| 109
| 463
|
<no_super_class>
|
weibocom_motan
|
motan/motan-extension/serialization-extension/src/main/java/com/weibo/api/motan/serialize/ProtobufSerialization.java
|
ProtobufSerialization
|
serialize
|
class ProtobufSerialization implements Serialization {
@Override
public byte[] serialize(Object obj) throws IOException {<FILL_FUNCTION_BODY>}
@SuppressWarnings("unchecked")
@Override
public <T> T deserialize(byte[] bytes, Class<T> clazz) throws IOException {
CodedInputStream in = CodedInputStream.newInstance(bytes);
// 兼容motan1 协议,对throwable类型消息 反序列化String类型的error message,转化为MotanServiceException抛出
if (Throwable.class.isAssignableFrom(clazz)) {
String errorMessage = (String) deserialize(in, String.class);
throw new MotanServiceException(clazz.getName() + ":" + errorMessage);
} else {
return (T) deserialize(in, clazz);
}
}
@Override
public byte[] serializeMulti(Object[] data) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
CodedOutputStream output = CodedOutputStream.newInstance(baos);
for (Object obj : data) {
serialize(output, obj);
}
output.flush();
return baos.toByteArray();
}
@Override
public Object[] deserializeMulti(byte[] data, Class<?>[] classes) throws IOException {
CodedInputStream in = CodedInputStream.newInstance(data);
Object[] objects = new Object[classes.length];
for (int i = 0; i < classes.length; i++) {
objects[i] = deserialize(in, classes[i]);
}
return objects;
}
protected void serialize(CodedOutputStream output, Object obj) throws IOException {
if (obj == null) {
output.writeBoolNoTag(true);
} else {
output.writeBoolNoTag(false);
Class<?> clazz = obj.getClass();
if (clazz == Integer.class) {
output.writeSInt32NoTag((Integer) obj);
} else if (clazz == Long.class) {
output.writeSInt64NoTag((Long) obj);
} else if (clazz == Boolean.class) {
output.writeBoolNoTag((Boolean) obj);
} else if (clazz == Byte.class) {
output.writeRawByte((Byte) obj);
} else if (clazz == Character.class) {
output.writeSInt32NoTag((Character) obj);
} else if (clazz == Short.class) {
output.writeSInt32NoTag((Short) obj);
} else if (clazz == Double.class) {
output.writeDoubleNoTag((Double) obj);
} else if (clazz == Float.class) {
output.writeFloatNoTag((Float) obj);
} else if (clazz == String.class) {
output.writeStringNoTag(obj.toString());
} else if (MessageLite.class.isAssignableFrom(clazz)) {
output.writeMessageNoTag((MessageLite) obj);
} else {
throw new IllegalArgumentException("can't serialize " + clazz);
}
}
}
protected Object deserialize(CodedInputStream in, Class<?> clazz) throws IOException {
if (in.readBool()) {
return null;
} else {
Object value;
if (clazz == int.class || clazz == Integer.class) {
value = in.readSInt32();
} else if (clazz == long.class || clazz == Long.class) {
value = in.readSInt64();
} else if (clazz == boolean.class || clazz == Boolean.class) {
value = in.readBool();
} else if (clazz == byte.class || clazz == Byte.class) {
value = in.readRawByte();
} else if (clazz == char.class || clazz == Character.class) {
value = (char) in.readSInt32();
} else if (clazz == short.class || clazz == Short.class) {
value = (short) in.readSInt32();
} else if (clazz == double.class || clazz == Double.class) {
value = in.readDouble();
} else if (clazz == float.class || clazz == Float.class) {
value = in.readFloat();
} else if (clazz == String.class) {
value = in.readString();
} else if (MessageLite.class.isAssignableFrom(clazz)) {
try {
Method method = clazz.getDeclaredMethod("newBuilder");
MessageLite.Builder builder = (MessageLite.Builder) method.invoke(null);
in.readMessage(builder, null);
value = builder.build();
} catch (Exception e) {
throw new MotanFrameworkException(e);
}
} else {
throw new IllegalArgumentException("can't serialize " + clazz);
}
return value;
}
}
@Override
public int getSerializationNumber() {
return 5;
}
}
|
ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
CodedOutputStream output = CodedOutputStream.newInstance(baos);
// 兼容motan1 协议,对throwable仅将异常信息进行序列化
if (obj != null && Throwable.class.isAssignableFrom(obj.getClass())) {
serialize(output, ((Throwable)obj).getMessage());
} else {
serialize(output, obj);
}
output.flush();
return baos.toByteArray();
| 1,311
| 136
| 1,447
|
<no_super_class>
|
weibocom_motan
|
motan/motan-manager/src/main/java/com/weibo/controller/CommandController.java
|
CommandController
|
deleteCommand
|
class CommandController {
@Resource(name = "${registry.type}" + "CommandService")
private CommandService commandService;
/**
* 获取所有指令
*
* @return
*/
@RequestMapping(value = "", method = RequestMethod.GET)
public ResponseEntity<List<JSONObject>> getAllCommands() {
List<JSONObject> result = commandService.getAllCommands();
return new ResponseEntity<List<JSONObject>>(result, HttpStatus.OK);
}
/**
* 获取指定group的指令列表
*
* @param group
* @return
*/
@RequestMapping(value = "/{group}", method = RequestMethod.GET)
public ResponseEntity<String> getCommandsByGroup(@PathVariable("group") String group) {
if (StringUtils.isEmpty(group)) {
return new ResponseEntity<String>(HttpStatus.BAD_REQUEST);
}
String result = commandService.getCommands(group);
return new ResponseEntity<String>(result, HttpStatus.OK);
}
/**
* 向指定group添加指令
*
* @param group
* @param clientCommand
* @return
*/
@RequestMapping(value = "/{group}", method = RequestMethod.POST)
public ResponseEntity<Boolean> addCommand(@PathVariable("group") String group, @RequestBody ClientCommand clientCommand) {
if (StringUtils.isEmpty(group) || clientCommand == null) {
return new ResponseEntity<Boolean>(HttpStatus.BAD_REQUEST);
}
boolean result = commandService.addCommand(group, clientCommand);
HttpStatus status;
if (result) {
status = HttpStatus.OK;
} else {
status = HttpStatus.NOT_MODIFIED;
}
return new ResponseEntity<Boolean>(result, status);
}
/**
* 更新指定group的某条指令
*
* @param group
* @param clientCommand
* @return
*/
@RequestMapping(value = "/{group}", method = RequestMethod.PUT)
public ResponseEntity<Boolean> updateCommand(@PathVariable("group") String group, @RequestBody ClientCommand clientCommand) {
if (StringUtils.isEmpty(group) || clientCommand == null) {
return new ResponseEntity<Boolean>(HttpStatus.BAD_REQUEST);
}
boolean result = commandService.updateCommand(group, clientCommand);
HttpStatus status;
if (result) {
status = HttpStatus.OK;
} else {
status = HttpStatus.NOT_MODIFIED;
}
return new ResponseEntity<Boolean>(result, status);
}
/**
* 删除指定group的某条指令
*
* @param group
* @param index
* @return
*/
@RequestMapping(value = "/{group}/{index}", method = RequestMethod.DELETE)
public ResponseEntity<Boolean> deleteCommand(@PathVariable("group") String group, @PathVariable("index") int index) {<FILL_FUNCTION_BODY>}
/**
* 预览指令
*
* @param group
* @param clientCommand
* @param previewIP
* @return
*/
@RequestMapping(value = "/{group}/preview", method = RequestMethod.POST)
public ResponseEntity<List<JSONObject>> previewCommand(
@PathVariable("group") String group,
@RequestBody ClientCommand clientCommand,
@RequestParam(value = "previewIP", required = false) String previewIP) {
if (StringUtils.isEmpty(group) || clientCommand == null) {
return new ResponseEntity<List<JSONObject>>(HttpStatus.BAD_REQUEST);
}
List<JSONObject> results = commandService.previewCommand(group, clientCommand, previewIP);
return new ResponseEntity<List<JSONObject>>(results, HttpStatus.OK);
}
@RequestMapping(value = "/operationRecord", method = RequestMethod.GET)
public ResponseEntity<List<OperationRecord>> getAllRecord() {
List<OperationRecord> results = commandService.getAllRecord();
if (results == null) {
return new ResponseEntity<List<OperationRecord>>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<List<OperationRecord>>(results, HttpStatus.OK);
}
}
|
if (StringUtils.isEmpty(group)) {
return new ResponseEntity<Boolean>(HttpStatus.BAD_REQUEST);
}
boolean result = commandService.deleteCommand(group, index);
HttpStatus status;
if (result) {
status = HttpStatus.OK;
} else {
status = HttpStatus.NOT_MODIFIED;
}
return new ResponseEntity<Boolean>(result, status);
| 1,114
| 109
| 1,223
|
<no_super_class>
|
weibocom_motan
|
motan/motan-manager/src/main/java/com/weibo/controller/ServerController.java
|
ServerController
|
getAllNodes
|
class ServerController {
@Resource(name = "${registry.type}" + "RegistryService")
private RegistryService registryService;
/**
* 获取所有group分组名称
*
* @return
*/
@RequestMapping(value = "/groups", method = RequestMethod.GET)
public ResponseEntity<List<String>> getAllGroups() {
List<String> result = registryService.getGroups();
return new ResponseEntity<List<String>>(result, HttpStatus.OK);
}
/**
* 获取group的所有service接口类名
*
* @param group
* @return
*/
@RequestMapping(value = "/{group}/services", method = RequestMethod.GET)
public ResponseEntity<List<String>> getServicesByGroup(@PathVariable("group") String group) {
if (StringUtils.isEmpty(group)) {
return new ResponseEntity<List<String>>(HttpStatus.BAD_REQUEST);
}
List<String> services = registryService.getServicesByGroup(group);
return new ResponseEntity<List<String>>(services, HttpStatus.OK);
}
/**
* 获取group下某个service的节点信息
*
* @param group
* @param service
* @return
*/
@RequestMapping(value = "/{group}/{service}/{nodeType}/nodes", method = RequestMethod.GET)
public ResponseEntity<List<JSONObject>> getServiceNodes(@PathVariable("group") String group, @PathVariable("service") String service, @PathVariable("nodeType") String nodeType) {
if (StringUtils.isEmpty(group) || StringUtils.isEmpty(service)) {
return new ResponseEntity<List<JSONObject>>(HttpStatus.BAD_REQUEST);
}
List<JSONObject> result = registryService.getNodes(group, service, nodeType);
return new ResponseEntity<List<JSONObject>>(result, HttpStatus.OK);
}
/**
* 获取group下所有service的节点信息
*
* @param group
* @return
*/
@RequestMapping(value = "/{group}/nodes", method = RequestMethod.GET)
public ResponseEntity<List<JSONObject>> getAllNodes(@PathVariable("group") String group) {<FILL_FUNCTION_BODY>}
}
|
if (StringUtils.isEmpty(group)) {
return new ResponseEntity<List<JSONObject>>(HttpStatus.BAD_REQUEST);
}
List<JSONObject> results = registryService.getAllNodes(group);
return new ResponseEntity<List<JSONObject>>(results, HttpStatus.OK);
| 581
| 78
| 659
|
<no_super_class>
|
weibocom_motan
|
motan/motan-manager/src/main/java/com/weibo/controller/UserController.java
|
UserController
|
createRoleMap
|
class UserController {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
@Qualifier("authenticationManager")
private AuthenticationManager authManager;
/**
* Retrieves the currently logged in user.
*
* @return A transfer containing the username and the roles.
*/
@RequestMapping(value = "", method = RequestMethod.GET)
public UserTransfer getUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication instanceof AnonymousAuthenticationToken) {
throw new CustomException.UnauthorizedException();
}
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
return new UserTransfer(userDetails.getUsername(), createRoleMap(userDetails));
}
@RequestMapping(value = "/authenticate", method = RequestMethod.POST)
public TokenTransfer authenticate(@RequestParam("username") String username, @RequestParam("password") String password) {
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
Authentication authentication = authManager.authenticate(authenticationToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
return new TokenTransfer(TokenUtils.createToken(userDetails));
}
private Map<String, Boolean> createRoleMap(UserDetails userDetails) {<FILL_FUNCTION_BODY>}
}
|
Map<String, Boolean> roles = new HashMap<String, Boolean>();
for (GrantedAuthority authority : userDetails.getAuthorities()) {
roles.put(authority.getAuthority(), Boolean.TRUE);
}
return roles;
| 375
| 65
| 440
|
<no_super_class>
|
weibocom_motan
|
motan/motan-manager/src/main/java/com/weibo/filter/AuthenticationTokenProcessingFilter.java
|
AuthenticationTokenProcessingFilter
|
extractAuthTokenFromRequest
|
class AuthenticationTokenProcessingFilter extends GenericFilterBean {
private final UserDetailsService userDetailsService;
@Autowired
public AuthenticationTokenProcessingFilter(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = getAsHttpRequest(request);
String authToken = extractAuthTokenFromRequest(httpServletRequest);
String username = TokenUtils.getUserNameFromToken(authToken);
if (username != null) {
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
if (TokenUtils.validateToken(authToken, userDetails)) {
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
}
}
chain.doFilter(request, response);
}
private HttpServletRequest getAsHttpRequest(ServletRequest request) {
if (!(request instanceof HttpServletRequest)) {
throw new RuntimeException("Expecting an HTTP request");
}
return (HttpServletRequest) request;
}
private String extractAuthTokenFromRequest(HttpServletRequest httpServletRequest) {<FILL_FUNCTION_BODY>}
}
|
String authToken = httpServletRequest.getHeader("X-Auth-Token");
if (authToken == null) {
authToken = httpServletRequest.getParameter("token");
}
return authToken;
| 376
| 55
| 431
|
<no_super_class>
|
weibocom_motan
|
motan/motan-manager/src/main/java/com/weibo/service/LoggingAspect.java
|
LoggingAspect
|
logAfter
|
class LoggingAspect {
@Autowired(required = false)
private OperationRecordMapper recordMapper;
// 任意公共方法的执行
@Pointcut("execution(public * * (..))")
private void anyPublicOperation() {
}
// CommandService接口定义的任意方法的执行
@Pointcut("execution(* com.weibo.service.CommandService+.*(..))")
private void execCommandOperation() {
}
@AfterReturning(value = "anyPublicOperation() && execCommandOperation()", returning = "result")
public void logAfter(JoinPoint joinPoint, boolean result) {<FILL_FUNCTION_BODY>}
private String getUsername() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication instanceof AnonymousAuthenticationToken) {
throw new CustomException.UnauthorizedException();
}
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
return TokenUtils.getUserNameFromToken(userDetails.getUsername());
}
}
|
Object[] args = joinPoint.getArgs();
OperationRecord record = new OperationRecord();
record.setOperator(getUsername());
record.setType(joinPoint.getSignature().getName());
record.setGroupName(args[0].toString());
record.setCommand(JSON.toJSONString(args[1]));
int status = result ? 1 : 0;
record.setStatus((byte) status);
if (recordMapper == null) {
LoggerUtil.accessLog(JSON.toJSONString(record));
} else {
recordMapper.insertSelective(record);
}
| 268
| 154
| 422
|
<no_super_class>
|
weibocom_motan
|
motan/motan-manager/src/main/java/com/weibo/service/UnauthorizedEntryPoint.java
|
UnauthorizedEntryPoint
|
commence
|
class UnauthorizedEntryPoint implements AuthenticationEntryPoint
{
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
throws IOException, ServletException
{<FILL_FUNCTION_BODY>}
}
|
response.sendError(
HttpServletResponse.SC_UNAUTHORIZED,
"Unauthorized: Authentication token was either missing or invalid.");
| 65
| 43
| 108
|
<no_super_class>
|
weibocom_motan
|
motan/motan-manager/src/main/java/com/weibo/service/impl/AbstractCommandService.java
|
AbstractCommandService
|
deleteCommand
|
class AbstractCommandService implements CommandService {
@Autowired(required = false)
private OperationRecordMapper recordMapper;
/**
* 向指定group添加指令
*
* @param group
* @param command
* @return
*/
@Override
public boolean addCommand(String group, RpcCommand.ClientCommand command) {
LoggerUtil.info(String.format("add command: group=%s, command=%s: ", group, JSON.toJSONString(command)));
RpcCommand remoteCommand = RpcCommandUtil.stringToCommand(getCommands(group));
if (remoteCommand == null) {
remoteCommand = new RpcCommand();
}
List<RpcCommand.ClientCommand> clientCommandList = remoteCommand.getClientCommandList();
if (clientCommandList == null) {
clientCommandList = new ArrayList<RpcCommand.ClientCommand>();
}
// 该方法只在流量切换界面被调用,此时指令序号默认是0
int index = getRpcCommandMaxIndex(remoteCommand);
command.setIndex(index + 1);
clientCommandList.add(command);
remoteCommand.setClientCommandList(clientCommandList);
return setCommand(group, remoteCommand);
}
/**
* 更新指定group的某条指令
*
* @param command
* @param group
* @return
*/
@Override
public boolean updateCommand(String group, RpcCommand.ClientCommand command) {
LoggerUtil.info(String.format("update command: group=%s, command=%s: ", group, JSON.toJSONString(command)));
RpcCommand remoteCommand = RpcCommandUtil.stringToCommand(getCommands(group));
if (remoteCommand == null) {
LoggerUtil.info("update failed, command not found");
return false;
}
List<RpcCommand.ClientCommand> clientCommandList = remoteCommand.getClientCommandList();
if (clientCommandList == null) {
LoggerUtil.info("update failed, command not found");
return false;
}
boolean found = false;
for (RpcCommand.ClientCommand cmd : clientCommandList) {
if (cmd.getIndex().equals(command.getIndex())) {
clientCommandList.remove(cmd);
clientCommandList.add(command);
found = true;
break;
}
}
if (!found) {
LoggerUtil.info("update failed, command not found");
return false;
}
remoteCommand.setClientCommandList(clientCommandList);
return setCommand(group, remoteCommand);
}
/**
* 删除指定group的某条指令
*
* @param group
* @param index
* @return
*/
@Override
public boolean deleteCommand(String group, int index) {<FILL_FUNCTION_BODY>}
/**
* 获取指令集中最大的指令序号
*
* @param rpcCommand
* @return
*/
@Override
public int getRpcCommandMaxIndex(RpcCommand rpcCommand) {
return 0;
}
/**
* 预览指令
*
* @param group
* @param clientCommand
* @param previewIP
* @return
*/
@Override
public List<JSONObject> previewCommand(String group, RpcCommand.ClientCommand clientCommand, String previewIP) {
return null;
}
/**
* 根据group和clientCommand生成指令
*
* @param group
* @param clientCommand
* @return
*/
@Override
public RpcCommand buildCommand(String group, RpcCommand.ClientCommand clientCommand) {
RpcCommand rpcCommand = new RpcCommand();
List<RpcCommand.ClientCommand> commandList = new ArrayList<RpcCommand.ClientCommand>();
commandList.add(clientCommand);
rpcCommand.setClientCommandList(commandList);
return rpcCommand;
}
/**
* 获取指令操作记录
*
* @return
*/
@Override
public List<OperationRecord> getAllRecord() {
List<OperationRecord> records;
if (recordMapper != null) {
records = recordMapper.selectAll();
} else {
return null;
}
return records;
}
}
|
LoggerUtil.info(String.format("delete command: group=%s, index=%d: ", group, index));
RpcCommand remoteCommand = RpcCommandUtil.stringToCommand(getCommands(group));
if (remoteCommand == null) {
LoggerUtil.info("delete failed, command not found");
return false;
}
List<RpcCommand.ClientCommand> clientCommandList = remoteCommand.getClientCommandList();
if (clientCommandList == null) {
LoggerUtil.info("delete failed, command not found");
return false;
}
boolean found = false;
for (RpcCommand.ClientCommand cmd : clientCommandList) {
if (cmd.getIndex() == index) {
clientCommandList.remove(cmd);
found = true;
break;
}
}
if (!found) {
LoggerUtil.info("delete failed, command not found");
return false;
}
remoteCommand.setClientCommandList(clientCommandList);
return setCommand(group, remoteCommand);
| 1,122
| 265
| 1,387
|
<no_super_class>
|
weibocom_motan
|
motan/motan-manager/src/main/java/com/weibo/service/impl/ConsulCommandService.java
|
ConsulCommandService
|
getCommands
|
class ConsulCommandService extends AbstractCommandService {
@Autowired
private ConsulClientWrapper clientWrapper;
private ConsulClient consulClient;
@PostConstruct
void init() {
consulClient = clientWrapper.getConsulClient();
}
/**
* 获取所有指令
*
* @return
*/
@Override
public List<JSONObject> getAllCommands() {
List<JSONObject> commands = new ArrayList<JSONObject>();
Response<List<GetValue>> response = consulClient.getKVValues(ConsulConstants.CONSUL_MOTAN_COMMAND);
List<GetValue> values = response.getValue();
if (values != null) {
for (GetValue value : values) {
JSONObject node = new JSONObject();
if (value.getValue() == null) {
continue;
}
String group = value.getKey().substring(ConsulConstants.CONSUL_MOTAN_COMMAND.length());
String command = new String(Base64.decodeBase64(value.getValue()));
node.put("group", group);
node.put("command", RpcCommandUtil.stringToCommand(command));
commands.add(node);
}
}
return commands;
}
/**
* 获取指定group的指令列表
*
* @param groupName
* @return
*/
@Override
public String getCommands(String groupName) {<FILL_FUNCTION_BODY>}
/**
* 更新指定group的指令列表
*
* @param command
* @param group
* @return
*/
@Override
public boolean setCommand(String group, RpcCommand command) {
LoggerUtil.info(String.format("set command: group=%s, command=%s: ", group, JSON.toJSONString(command)));
List<RpcCommand.ClientCommand> newCommandList = new ArrayList<RpcCommand.ClientCommand>();
for (RpcCommand.ClientCommand clientCommand : command.getClientCommandList()) {
List<String> newMergeGroups = new ArrayList<String>();
for (String mergeGroup : clientCommand.getMergeGroups()) {
mergeGroup = removeGroupNamePrefix(mergeGroup);
newMergeGroups.add(mergeGroup);
}
clientCommand.setMergeGroups(newMergeGroups);
newCommandList.add(clientCommand);
}
command.setClientCommandList(newCommandList);
Response<Boolean> response = consulClient.setKVValue(
ConsulConstants.CONSUL_MOTAN_COMMAND + removeDatacenterPrefix(group),
RpcCommandUtil.commandToString(command));
return response.getValue();
}
/**
* 去除group的datacenter前缀
*
* @param group
* @return
*/
private String removeDatacenterPrefix(String group) {
int index = group.indexOf(":");
if (index > 0) {
return group.substring(group.indexOf(":") + 1);
} else {
return group;
}
}
/**
* 去除group的motan标识前缀
*
* @param group
* @return
*/
private String removeGroupNamePrefix(String group) {
if (group.contains(ConsulConstants.CONSUL_SERVICE_MOTAN_PRE)) {
return removeDatacenterPrefix(group).substring(ConsulConstants.CONSUL_SERVICE_MOTAN_PRE.length());
} else {
return group;
}
}
}
|
Response<GetValue> response = consulClient.getKVValue(ConsulConstants.CONSUL_MOTAN_COMMAND + groupName);
GetValue value = response.getValue();
String command = "";
if (value != null && value.getValue() != null) {
command = new String(Base64.decodeBase64(value.getValue()));
}
return command;
| 925
| 101
| 1,026
|
<methods>public non-sealed void <init>() ,public boolean addCommand(java.lang.String, com.weibo.api.motan.registry.support.command.RpcCommand.ClientCommand) ,public com.weibo.api.motan.registry.support.command.RpcCommand buildCommand(java.lang.String, com.weibo.api.motan.registry.support.command.RpcCommand.ClientCommand) ,public boolean deleteCommand(java.lang.String, int) ,public List<com.weibo.model.OperationRecord> getAllRecord() ,public int getRpcCommandMaxIndex(com.weibo.api.motan.registry.support.command.RpcCommand) ,public List<com.alibaba.fastjson.JSONObject> previewCommand(java.lang.String, com.weibo.api.motan.registry.support.command.RpcCommand.ClientCommand, java.lang.String) ,public boolean updateCommand(java.lang.String, com.weibo.api.motan.registry.support.command.RpcCommand.ClientCommand) <variables>private com.weibo.dao.OperationRecordMapper recordMapper
|
weibocom_motan
|
motan/motan-manager/src/main/java/com/weibo/service/impl/ConsulRegistryService.java
|
ConsulRegistryService
|
getAllNodes
|
class ConsulRegistryService implements RegistryService {
@Autowired
private ConsulClientWrapper clientWrapper;
private ConsulClient consulClient;
public ConsulRegistryService() {
}
/**
* Unit Test中使用
*
* @param consulClient
*/
public ConsulRegistryService(ConsulClient consulClient) {
this.consulClient = consulClient;
}
@PostConstruct
public void init() {
consulClient = clientWrapper.getConsulClient();
}
public List<String> getDatacenters() {
return consulClient.getCatalogDatacenters().getValue();
}
@Override
public List<String> getGroups() {
List<String> groups = new ArrayList<String>();
for (String dc : getDatacenters()) {
QueryParams queryParams = new QueryParams(dc);
Map<String, List<String>> serviceMap = consulClient.getCatalogServices(queryParams).getValue();
serviceMap.remove("consul");
for (String service : serviceMap.keySet()) {
groups.add(formatGroupName(dc, service));
}
}
return groups;
}
@Override
public List<String> getServicesByGroup(String dcGroup) {
Set<String> services = new HashSet<String>();
List<CatalogService> serviceList = getCatalogServicesByGroup(dcGroup);
for (CatalogService service : serviceList) {
services.add(formatServiceName(service));
}
return new ArrayList<String>(services);
}
private List<CatalogService> getCatalogServicesByGroup(String dcGroup) {
QueryParams queryParams = new QueryParams(getDcName(dcGroup));
return consulClient.getCatalogService(getGroupName(dcGroup), queryParams).getValue();
}
@Override
public List<JSONObject> getNodes(String dcGroup, String service, String nodeType) {
List<JSONObject> results = new ArrayList<JSONObject>();
List<Check> checks = consulClient.getHealthChecksForService(getGroupName(dcGroup), new QueryParams(getDcName(dcGroup))).getValue();
for (Check check : checks) {
String serviceId = check.getServiceId();
String[] strings = serviceId.split("-");
if (strings[1].equals(service)) {
Check.CheckStatus status = check.getStatus();
JSONObject node = new JSONObject();
if (nodeType.equals(status.toString())) {
node.put("host", strings[0]);
node.put("info", null);
results.add(node);
}
}
}
return results;
}
@Override
public List<JSONObject> getAllNodes(String dcGroup) {<FILL_FUNCTION_BODY>}
private String formatGroupName(String dc, String groupName) {
return dc + ":" + groupName;
}
private String formatServiceName(CatalogService catalogService) {
return catalogService.getServiceId().split("-")[1];
}
private String getDcName(String dcString) {
return dcString.substring(0, dcString.indexOf(":"));
}
private String getGroupName(String dcGroup) {
return dcGroup.substring(dcGroup.indexOf(":") + 1);
}
}
|
List<JSONObject> results = new ArrayList<JSONObject>();
List<String> serviceNameSet = getServicesByGroup(dcGroup);
for (String dcServiceName : serviceNameSet) {
JSONObject service = new JSONObject();
service.put("service", dcServiceName);
List<JSONObject> availableServer = getNodes(dcGroup, dcServiceName, "PASSING");
service.put("server", availableServer);
List<JSONObject> unavailableServer = getNodes(dcGroup, dcServiceName, "CRITICAL");
service.put("unavailableServer", unavailableServer);
service.put("client", null);
results.add(service);
}
return results;
| 871
| 178
| 1,049
|
<no_super_class>
|
weibocom_motan
|
motan/motan-manager/src/main/java/com/weibo/service/impl/ZookeeperCommandService.java
|
ZookeeperCommandService
|
getChildren
|
class ZookeeperCommandService extends AbstractCommandService {
@Autowired
private ZkClientWrapper clientWrapper;
private ZkClient zkClient;
@PostConstruct
void init() {
zkClient = clientWrapper.getZkClient();
}
/**
* 获取所有指令
*
* @return
*/
@Override
public List<JSONObject> getAllCommands() {
List<JSONObject> commands = new ArrayList<JSONObject>();
List<String> groups = getChildren(MotanConstants.ZOOKEEPER_REGISTRY_NAMESPACE);
for (String group : groups) {
JSONObject node = new JSONObject();
String command = getCommands(group);
if (command != null) {
node.put("group", group);
node.put("command", RpcCommandUtil.stringToCommand(command));
commands.add(node);
}
}
return commands;
}
private List<String> getChildren(String path) {<FILL_FUNCTION_BODY>}
/**
* 获取指定group的指令列表
*
* @param groupName
* @return
*/
@Override
public String getCommands(String groupName) {
return zkClient.readData(getCommandPath(groupName), true);
}
private String getCommandPath(String groupName) {
return MotanConstants.ZOOKEEPER_REGISTRY_NAMESPACE + MotanConstants.PATH_SEPARATOR + groupName + MotanConstants.ZOOKEEPER_REGISTRY_COMMAND;
}
/**
* 更新指定group的指令列表
*
* @param command
* @param group
* @return
*/
@Override
public boolean setCommand(String group, RpcCommand command) {
String path = getCommandPath(group);
if (!zkClient.exists(path)) {
zkClient.createPersistent(path, true);
}
try {
zkClient.writeData(path, RpcCommandUtil.commandToString(command));
} catch (Exception e) {
return false;
}
return true;
}
}
|
List<String> children = new ArrayList<String>();
if (zkClient.exists(path)) {
children = zkClient.getChildren(path);
}
return children;
| 574
| 51
| 625
|
<methods>public non-sealed void <init>() ,public boolean addCommand(java.lang.String, com.weibo.api.motan.registry.support.command.RpcCommand.ClientCommand) ,public com.weibo.api.motan.registry.support.command.RpcCommand buildCommand(java.lang.String, com.weibo.api.motan.registry.support.command.RpcCommand.ClientCommand) ,public boolean deleteCommand(java.lang.String, int) ,public List<com.weibo.model.OperationRecord> getAllRecord() ,public int getRpcCommandMaxIndex(com.weibo.api.motan.registry.support.command.RpcCommand) ,public List<com.alibaba.fastjson.JSONObject> previewCommand(java.lang.String, com.weibo.api.motan.registry.support.command.RpcCommand.ClientCommand, java.lang.String) ,public boolean updateCommand(java.lang.String, com.weibo.api.motan.registry.support.command.RpcCommand.ClientCommand) <variables>private com.weibo.dao.OperationRecordMapper recordMapper
|
weibocom_motan
|
motan/motan-manager/src/main/java/com/weibo/service/impl/ZookeeperRegistryService.java
|
ZookeeperRegistryService
|
getNodes
|
class ZookeeperRegistryService implements RegistryService {
@Autowired
private ZkClientWrapper clientWrapper;
private ZkClient zkClient;
public ZookeeperRegistryService() {
}
public ZookeeperRegistryService(ZkClient zkClient) {
this.zkClient = zkClient;
}
@PostConstruct
void init() {
zkClient = clientWrapper.getZkClient();
}
@Override
public List<String> getGroups() {
return getChildren(MotanConstants.ZOOKEEPER_REGISTRY_NAMESPACE);
}
@Override
public List<String> getServicesByGroup(String group) {
List<String> services = getChildren(toGroupPath(group));
services.remove("command");
return services;
}
@Override
public List<JSONObject> getNodes(String group, String service, String nodeType) {<FILL_FUNCTION_BODY>}
@Override
public List<JSONObject> getAllNodes(String group) {
List<JSONObject> results = new ArrayList<JSONObject>();
List<String> services = getServicesByGroup(group);
for (String serviceName : services) {
JSONObject service = new JSONObject();
service.put("service", serviceName);
List<JSONObject> availableServer = getNodes(group, serviceName, "server");
service.put("server", availableServer);
List<JSONObject> unavailableServer = getNodes(group, serviceName, "unavailableServer");
service.put("unavailableServer", unavailableServer);
List<JSONObject> clientNode = getNodes(group, serviceName, "client");
service.put("client", clientNode);
results.add(service);
}
return results;
}
private String toGroupPath(String group) {
return MotanConstants.ZOOKEEPER_REGISTRY_NAMESPACE + MotanConstants.PATH_SEPARATOR + group;
}
private String toServicePath(String group, String service) {
return toGroupPath(group) + MotanConstants.PATH_SEPARATOR + service;
}
private String toNodeTypePath(String group, String service, String nodeType) {
return toServicePath(group, service) + MotanConstants.PATH_SEPARATOR + nodeType;
}
private String toNodePath(String group, String service, String nodeType, String node) {
return toNodeTypePath(group, service, nodeType) + MotanConstants.PATH_SEPARATOR + node;
}
private List<String> getChildren(String path) {
List<String> children = new ArrayList<String>();
if (zkClient.exists(path)) {
children = zkClient.getChildren(path);
}
return children;
}
}
|
List<JSONObject> result = new ArrayList<JSONObject>();
List<String> nodes = getChildren(toNodeTypePath(group, service, nodeType));
for (String nodeName : nodes) {
JSONObject node = new JSONObject();
String info = zkClient.readData(toNodePath(group, service, nodeType, nodeName), true);
node.put("host", nodeName);
node.put("info", info);
result.add(node);
}
return result;
| 724
| 128
| 852
|
<no_super_class>
|
weibocom_motan
|
motan/motan-manager/src/main/java/com/weibo/utils/ConsulClientWrapper.java
|
ConsulClientWrapper
|
init
|
class ConsulClientWrapper {
@Value("${registry.url}")
private String registryUrl;
private ConsulClient consulClient;
@PostConstruct
void init() {<FILL_FUNCTION_BODY>}
@PreDestroy
void destory() {
consulClient = null;
}
public ConsulClient getConsulClient() {
return consulClient;
}
}
|
try {
String[] arr = registryUrl.split(":");
String host = arr[0];
int port = Integer.parseInt(arr[1]);
consulClient = new ConsulClient(host, port);
} catch (Exception e) {
throw new MotanFrameworkException("Fail to connect consul, cause: " + e.getMessage());
}
| 113
| 93
| 206
|
<no_super_class>
|
weibocom_motan
|
motan/motan-manager/src/main/java/com/weibo/utils/TokenUtils.java
|
TokenUtils
|
computeSignature
|
class TokenUtils {
public static final String MAGIC_KEY = "obfuscate";
public static String createToken(UserDetails userDetails) {
/* Expires in one hour */
long expires = System.currentTimeMillis() + 1000L * 60 * 60;
StringBuilder tokenBuilder = new StringBuilder();
tokenBuilder.append(userDetails.getUsername());
tokenBuilder.append(":");
tokenBuilder.append(expires);
tokenBuilder.append(":");
tokenBuilder.append(TokenUtils.computeSignature(userDetails, expires));
return tokenBuilder.toString();
}
public static String computeSignature(UserDetails userDetails, long expires) {<FILL_FUNCTION_BODY>}
public static String getUserNameFromToken(String authToken) {
if (null == authToken) {
return null;
}
String[] parts = authToken.split(":");
return parts[0];
}
public static boolean validateToken(String authToken, UserDetails userDetails) {
String[] parts = authToken.split(":");
long expires = Long.parseLong(parts[1]);
String signature = parts[2];
return expires >= System.currentTimeMillis() && signature.equals(TokenUtils.computeSignature(userDetails, expires));
}
}
|
StringBuilder signatureBuilder = new StringBuilder();
signatureBuilder.append(userDetails.getUsername());
signatureBuilder.append(":");
signatureBuilder.append(expires);
signatureBuilder.append(":");
signatureBuilder.append(userDetails.getPassword());
signatureBuilder.append(":");
signatureBuilder.append(TokenUtils.MAGIC_KEY);
MessageDigest digest;
try {
digest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("No MD5 algorithm available!");
}
return new String(Hex.encode(digest.digest(signatureBuilder.toString().getBytes())));
| 347
| 177
| 524
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.