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
|
|---|---|---|---|---|---|---|---|---|---|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/rpc/HeartbeatHandler.java
|
HeartbeatHandler
|
userEventTriggered
|
class HeartbeatHandler extends ChannelDuplexHandler {
/**
*
* @see io.netty.channel.ChannelInboundHandlerAdapter#userEventTriggered(io.netty.channel.ChannelHandlerContext, java.lang.Object)
*/
@Override
public void userEventTriggered(final ChannelHandlerContext ctx, Object evt) throws Exception {<FILL_FUNCTION_BODY>}
}
|
if (evt instanceof IdleStateEvent) {
ProtocolCode protocolCode = ctx.channel().attr(Connection.PROTOCOL).get();
Protocol protocol = ProtocolManager.getProtocol(protocolCode);
protocol.getHeartbeatTrigger().heartbeatTriggered(ctx);
} else {
super.userEventTriggered(ctx, evt);
}
| 105
| 96
| 201
|
<no_super_class>
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/rpc/RpcClientRemoting.java
|
RpcClientRemoting
|
preProcessInvokeContext
|
class RpcClientRemoting extends RpcRemoting {
public RpcClientRemoting(CommandFactory commandFactory, RemotingAddressParser addressParser,
ConnectionManager connectionManager) {
super(commandFactory, addressParser, connectionManager);
}
/**
* @see com.alipay.remoting.rpc.RpcRemoting#oneway(com.alipay.remoting.Url, java.lang.Object, InvokeContext)
*/
@Override
public void oneway(Url url, Object request, InvokeContext invokeContext)
throws RemotingException,
InterruptedException {
if (invokeContext == null) {
invokeContext = new InvokeContext();
}
final Connection conn = getConnectionAndInitInvokeContext(url, invokeContext);
this.connectionManager.check(conn);
this.oneway(conn, request, invokeContext);
}
/**
* @see com.alipay.remoting.rpc.RpcRemoting#invokeSync(com.alipay.remoting.Url, java.lang.Object, InvokeContext, int)
*/
@Override
public Object invokeSync(Url url, Object request, InvokeContext invokeContext, int timeoutMillis)
throws RemotingException,
InterruptedException {
// Use the specified timeout to overwrite the configuration in the url
url.setConnectTimeout(timeoutMillis);
if (invokeContext == null) {
invokeContext = new InvokeContext();
}
final Connection conn = getConnectionAndInitInvokeContext(url, invokeContext);
this.connectionManager.check(conn);
return this.invokeSync(conn, request, invokeContext, timeoutMillis);
}
/**
* @see com.alipay.remoting.rpc.RpcRemoting#invokeWithFuture(com.alipay.remoting.Url, java.lang.Object, InvokeContext, int)
*/
@Override
public RpcResponseFuture invokeWithFuture(Url url, Object request, InvokeContext invokeContext,
int timeoutMillis) throws RemotingException,
InterruptedException {
url.setConnectTimeout(timeoutMillis);
if (invokeContext == null) {
invokeContext = new InvokeContext();
}
final Connection conn = getConnectionAndInitInvokeContext(url, invokeContext);
this.connectionManager.check(conn);
return this.invokeWithFuture(conn, request, invokeContext, timeoutMillis);
}
/**
* @see com.alipay.remoting.rpc.RpcRemoting#invokeWithCallback(com.alipay.remoting.Url, java.lang.Object, InvokeContext, com.alipay.remoting.InvokeCallback, int)
*/
@Override
public void invokeWithCallback(Url url, Object request, InvokeContext invokeContext,
InvokeCallback invokeCallback, int timeoutMillis)
throws RemotingException,
InterruptedException {
url.setConnectTimeout(timeoutMillis);
if (invokeContext == null) {
invokeContext = new InvokeContext();
}
final Connection conn = getConnectionAndInitInvokeContext(url, invokeContext);
this.connectionManager.check(conn);
this.invokeWithCallback(conn, request, invokeContext, invokeCallback, timeoutMillis);
}
/**
* @see RpcRemoting#preProcessInvokeContext(InvokeContext, RemotingCommand, Connection)
*/
@Override
protected void preProcessInvokeContext(InvokeContext invokeContext, RemotingCommand cmd,
Connection connection) {<FILL_FUNCTION_BODY>}
/**
* Get connection and set init invokeContext if invokeContext not {@code null}
*
* @param url target url
* @param invokeContext invoke context to set
* @return connection
*/
protected Connection getConnectionAndInitInvokeContext(Url url, InvokeContext invokeContext)
throws RemotingException,
InterruptedException {
long start = System.currentTimeMillis();
long startInNano = System.nanoTime();
Connection conn;
try {
conn = this.connectionManager.getAndCreateIfAbsent(url);
} finally {
if (null != invokeContext) {
invokeContext.putIfAbsent(InvokeContext.CLIENT_CONN_CREATETIME,
(System.currentTimeMillis() - start));
invokeContext.putIfAbsent(InvokeContext.CLIENT_CONN_CREATE_START_IN_NANO,
startInNano);
invokeContext.putIfAbsent(InvokeContext.CLIENT_CONN_CREATE_END_IN_NANO,
System.nanoTime());
}
}
return conn;
}
}
|
if (null != invokeContext) {
invokeContext.putIfAbsent(InvokeContext.CLIENT_LOCAL_IP,
RemotingUtil.parseLocalIP(connection.getChannel()));
invokeContext.putIfAbsent(InvokeContext.CLIENT_LOCAL_PORT,
RemotingUtil.parseLocalPort(connection.getChannel()));
invokeContext.putIfAbsent(InvokeContext.CLIENT_REMOTE_IP,
RemotingUtil.parseRemoteIP(connection.getChannel()));
invokeContext.putIfAbsent(InvokeContext.CLIENT_REMOTE_PORT,
RemotingUtil.parseRemotePort(connection.getChannel()));
invokeContext.putIfAbsent(InvokeContext.BOLT_INVOKE_REQUEST_ID, cmd.getId());
}
| 1,186
| 199
| 1,385
|
<methods>public void <init>(com.alipay.remoting.CommandFactory) ,public void <init>(com.alipay.remoting.CommandFactory, com.alipay.remoting.RemotingAddressParser, com.alipay.remoting.ConnectionManager) ,public java.lang.Object invokeSync(java.lang.String, java.lang.Object, com.alipay.remoting.InvokeContext, int) throws com.alipay.remoting.exception.RemotingException, java.lang.InterruptedException,public abstract java.lang.Object invokeSync(com.alipay.remoting.Url, java.lang.Object, com.alipay.remoting.InvokeContext, int) throws com.alipay.remoting.exception.RemotingException, java.lang.InterruptedException,public java.lang.Object invokeSync(com.alipay.remoting.Connection, java.lang.Object, com.alipay.remoting.InvokeContext, int) throws com.alipay.remoting.exception.RemotingException, java.lang.InterruptedException,public void invokeWithCallback(java.lang.String, java.lang.Object, com.alipay.remoting.InvokeContext, com.alipay.remoting.InvokeCallback, int) throws com.alipay.remoting.exception.RemotingException, java.lang.InterruptedException,public abstract void invokeWithCallback(com.alipay.remoting.Url, java.lang.Object, com.alipay.remoting.InvokeContext, com.alipay.remoting.InvokeCallback, int) throws com.alipay.remoting.exception.RemotingException, java.lang.InterruptedException,public void invokeWithCallback(com.alipay.remoting.Connection, java.lang.Object, com.alipay.remoting.InvokeContext, com.alipay.remoting.InvokeCallback, int) throws com.alipay.remoting.exception.RemotingException,public com.alipay.remoting.rpc.RpcResponseFuture invokeWithFuture(java.lang.String, java.lang.Object, com.alipay.remoting.InvokeContext, int) throws com.alipay.remoting.exception.RemotingException, java.lang.InterruptedException,public abstract com.alipay.remoting.rpc.RpcResponseFuture invokeWithFuture(com.alipay.remoting.Url, java.lang.Object, com.alipay.remoting.InvokeContext, int) throws com.alipay.remoting.exception.RemotingException, java.lang.InterruptedException,public com.alipay.remoting.rpc.RpcResponseFuture invokeWithFuture(com.alipay.remoting.Connection, java.lang.Object, com.alipay.remoting.InvokeContext, int) throws com.alipay.remoting.exception.RemotingException,public void oneway(java.lang.String, java.lang.Object, com.alipay.remoting.InvokeContext) throws com.alipay.remoting.exception.RemotingException, java.lang.InterruptedException,public abstract void oneway(com.alipay.remoting.Url, java.lang.Object, com.alipay.remoting.InvokeContext) throws com.alipay.remoting.exception.RemotingException, java.lang.InterruptedException,public void oneway(com.alipay.remoting.Connection, java.lang.Object, com.alipay.remoting.InvokeContext) throws com.alipay.remoting.exception.RemotingException<variables>protected com.alipay.remoting.RemotingAddressParser addressParser,protected com.alipay.remoting.ConnectionManager connectionManager,private static final Logger logger
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/rpc/RpcCommand.java
|
RpcCommand
|
setHeader
|
class RpcCommand implements RemotingCommand {
/** For serialization */
private static final long serialVersionUID = -3570261012462596503L;
/**
* Code which stands for the command.
*/
private CommandCode cmdCode;
/* command version */
private byte version = 0x1;
private byte type;
/**
* Serializer, see the Configs.SERIALIZER_DEFAULT for the default serializer.
* Notice: this can not be changed after initialized at runtime.
*/
private byte serializer = ConfigManager.serializer;
/**
* protocol switches
*/
private ProtocolSwitch protocolSwitch = new ProtocolSwitch();
private int id;
/** The length of clazz */
private short clazzLength = 0;
private short headerLength = 0;
private int contentLength = 0;
/** The class of content */
private byte[] clazz;
/** Header is used for transparent transmission. */
private byte[] header;
/** The bytes format of the content of the command. */
private byte[] content;
/** invoke context of each rpc command. */
private InvokeContext invokeContext;
public RpcCommand() {
}
public RpcCommand(byte type) {
this();
this.type = type;
}
public RpcCommand(CommandCode cmdCode) {
this();
this.cmdCode = cmdCode;
}
public RpcCommand(byte type, CommandCode cmdCode) {
this(cmdCode);
this.type = type;
}
public RpcCommand(byte version, byte type, CommandCode cmdCode) {
this(type, cmdCode);
this.version = version;
}
/**
* Serialize the class header and content.
*
* @throws Exception
*/
@Override
public void serialize() throws SerializationException {
this.serializeClazz();
this.serializeHeader(this.invokeContext);
this.serializeContent(this.invokeContext);
}
/**
* Deserialize the class header and content.
*
* @throws Exception
*/
@Override
public void deserialize() throws DeserializationException {
this.deserializeClazz();
this.deserializeHeader(this.invokeContext);
this.deserializeContent(this.invokeContext);
}
/**
* Deserialize according to mask.
* <ol>
* <li>If mask <= {@link RpcDeserializeLevel#DESERIALIZE_CLAZZ}, only deserialize clazz - only one part.</li>
* <li>If mask <= {@link RpcDeserializeLevel#DESERIALIZE_HEADER}, deserialize clazz and header - two parts.</li>
* <li>If mask <= {@link RpcDeserializeLevel#DESERIALIZE_ALL}, deserialize clazz, header and content - all three parts.</li>
* </ol>
*
* @param mask
* @throws CodecException
*/
public void deserialize(long mask) throws DeserializationException {
if (mask <= RpcDeserializeLevel.DESERIALIZE_CLAZZ) {
this.deserializeClazz();
} else if (mask <= RpcDeserializeLevel.DESERIALIZE_HEADER) {
this.deserializeClazz();
this.deserializeHeader(this.getInvokeContext());
} else if (mask <= RpcDeserializeLevel.DESERIALIZE_ALL) {
this.deserialize();
}
}
/**
* Serialize content class.
*
* @throws Exception
*/
public void serializeClazz() throws SerializationException {
}
/**
* Deserialize the content class.
*
* @throws Exception
*/
public void deserializeClazz() throws DeserializationException {
}
/**
* Serialize the header.
*
* @throws Exception
*/
public void serializeHeader(InvokeContext invokeContext) throws SerializationException {
}
/**
* Serialize the content.
*
* @throws Exception
*/
@Override
public void serializeContent(InvokeContext invokeContext) throws SerializationException {
}
/**
* Deserialize the header.
*
* @throws Exception
*/
public void deserializeHeader(InvokeContext invokeContext) throws DeserializationException {
}
/**
* Deserialize the content.
*
* @throws Exception
*/
@Override
public void deserializeContent(InvokeContext invokeContext) throws DeserializationException {
}
@Override
public ProtocolCode getProtocolCode() {
return ProtocolCode.fromBytes(RpcProtocol.PROTOCOL_CODE);
}
@Override
public CommandCode getCmdCode() {
return cmdCode;
}
@Override
public InvokeContext getInvokeContext() {
return invokeContext;
}
@Override
public byte getSerializer() {
return serializer;
}
@Override
public ProtocolSwitch getProtocolSwitch() {
return protocolSwitch;
}
public void setCmdCode(CommandCode cmdCode) {
this.cmdCode = cmdCode;
}
public byte getVersion() {
return version;
}
public void setVersion(byte version) {
this.version = version;
}
public byte getType() {
return type;
}
public void setType(byte type) {
this.type = type;
}
public void setSerializer(byte serializer) {
this.serializer = serializer;
}
public void setProtocolSwitch(ProtocolSwitch protocolSwitch) {
this.protocolSwitch = protocolSwitch;
}
@Override
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public byte[] getHeader() {
return header;
}
public void setHeader(byte[] header) {<FILL_FUNCTION_BODY>}
public byte[] getContent() {
return content;
}
public void setContent(byte[] content) {
if (content != null) {
this.content = content;
this.contentLength = content.length;
}
}
public short getHeaderLength() {
return headerLength;
}
public int getContentLength() {
return contentLength;
}
public short getClazzLength() {
return clazzLength;
}
public byte[] getClazz() {
return clazz;
}
public void setClazz(byte[] clazz) {
if (clazz != null) {
if (clazz.length > Short.MAX_VALUE) {
throw new RuntimeException("class length exceed maximum, len=" + clazz.length);
}
this.clazzLength = (short) clazz.length;
this.clazz = clazz;
}
}
public void setInvokeContext(InvokeContext invokeContext) {
this.invokeContext = invokeContext;
}
}
|
if (header != null) {
if (header.length > Short.MAX_VALUE) {
throw new RuntimeException("header length exceed maximum, len=" + header.length);
}
this.headerLength = (short) header.length;
this.header = header;
}
| 1,900
| 76
| 1,976
|
<no_super_class>
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/rpc/RpcCommandFactory.java
|
RpcCommandFactory
|
createExceptionResponse
|
class RpcCommandFactory implements CommandFactory {
@Override
public RpcRequestCommand createRequestCommand(Object requestObject) {
return new RpcRequestCommand(requestObject);
}
@Override
public RpcResponseCommand createResponse(final Object responseObject,
final RemotingCommand requestCmd) {
RpcResponseCommand response = new RpcResponseCommand(requestCmd.getId(), responseObject);
if (null != responseObject) {
response.setResponseClass(responseObject.getClass().getName());
} else {
response.setResponseClass(null);
}
response.setSerializer(requestCmd.getSerializer());
response.setProtocolSwitch(requestCmd.getProtocolSwitch());
response.setResponseStatus(ResponseStatus.SUCCESS);
return response;
}
@Override
public RpcResponseCommand createExceptionResponse(int id, String errMsg) {
return createExceptionResponse(id, null, errMsg);
}
@Override
public RpcResponseCommand createExceptionResponse(int id, final Throwable t, String errMsg) {
RpcResponseCommand response = null;
if (null == t) {
response = new RpcResponseCommand(id, createServerException(errMsg));
} else {
response = new RpcResponseCommand(id, createServerException(t, errMsg));
}
response.setResponseClass(RpcServerException.class.getName());
response.setResponseStatus(ResponseStatus.SERVER_EXCEPTION);
return response;
}
@Override
public RpcResponseCommand createExceptionResponse(int id, ResponseStatus status) {
RpcResponseCommand responseCommand = new RpcResponseCommand();
responseCommand.setId(id);
responseCommand.setResponseStatus(status);
return responseCommand;
}
@Override
public RpcResponseCommand createExceptionResponse(int id, ResponseStatus status, Throwable t) {<FILL_FUNCTION_BODY>}
@Override
public ResponseCommand createTimeoutResponse(InetSocketAddress address) {
ResponseCommand responseCommand = new ResponseCommand();
responseCommand.setResponseStatus(ResponseStatus.TIMEOUT);
responseCommand.setResponseTimeMillis(System.currentTimeMillis());
responseCommand.setResponseHost(address);
return responseCommand;
}
@Override
public RemotingCommand createSendFailedResponse(final InetSocketAddress address,
Throwable throwable) {
ResponseCommand responseCommand = new ResponseCommand();
responseCommand.setResponseStatus(ResponseStatus.CLIENT_SEND_ERROR);
responseCommand.setResponseTimeMillis(System.currentTimeMillis());
responseCommand.setResponseHost(address);
responseCommand.setCause(throwable);
return responseCommand;
}
@Override
public RemotingCommand createConnectionClosedResponse(InetSocketAddress address, String message) {
ResponseCommand responseCommand = new ResponseCommand();
responseCommand.setResponseStatus(ResponseStatus.CONNECTION_CLOSED);
responseCommand.setResponseTimeMillis(System.currentTimeMillis());
responseCommand.setResponseHost(address);
return responseCommand;
}
/**
* create server exception using error msg, no stack trace
* @param errMsg the assigned error message
* @return an instance of RpcServerException
*/
private RpcServerException createServerException(String errMsg) {
return new RpcServerException(errMsg);
}
/**
* create server exception using error msg and fill the stack trace using the stack trace of throwable.
*
* @param t the origin throwable to fill the stack trace of rpc server exception
* @param errMsg additional error msg, <code>null</code> is allowed
* @return an instance of RpcServerException
*/
private RpcServerException createServerException(Throwable t, String errMsg) {
String formattedErrMsg = String.format(
"[Server]OriginErrorMsg: %s: %s. AdditionalErrorMsg: %s", t.getClass().getName(),
t.getMessage(), errMsg);
RpcServerException e = new RpcServerException(formattedErrMsg);
e.setStackTrace(t.getStackTrace());
return e;
}
}
|
RpcResponseCommand responseCommand = this.createExceptionResponse(id, status);
responseCommand.setResponseObject(createServerException(t, null));
responseCommand.setResponseClass(RpcServerException.class.getName());
return responseCommand;
| 1,049
| 63
| 1,112
|
<no_super_class>
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/rpc/RpcConnectionEventHandler.java
|
RpcConnectionEventHandler
|
channelInactive
|
class RpcConnectionEventHandler extends ConnectionEventHandler {
public RpcConnectionEventHandler() {
super();
}
public RpcConnectionEventHandler(Configuration configuration) {
super(configuration);
}
/**
* @see com.alipay.remoting.ConnectionEventHandler#channelInactive(io.netty.channel.ChannelHandlerContext)
*/
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {<FILL_FUNCTION_BODY>}
}
|
Connection conn = ctx.channel().attr(Connection.CONNECTION).get();
if (conn != null) {
this.getConnectionManager().remove(conn);
}
super.channelInactive(ctx);
| 127
| 57
| 184
|
<methods>public void <init>() ,public void <init>(com.alipay.remoting.config.Configuration) ,public void channelActive(ChannelHandlerContext) throws java.lang.Exception,public void channelInactive(ChannelHandlerContext) throws java.lang.Exception,public void channelRegistered(ChannelHandlerContext) throws java.lang.Exception,public void channelUnregistered(ChannelHandlerContext) throws java.lang.Exception,public void close(ChannelHandlerContext, ChannelPromise) throws java.lang.Exception,public void connect(ChannelHandlerContext, java.net.SocketAddress, java.net.SocketAddress, ChannelPromise) throws java.lang.Exception,public void disconnect(ChannelHandlerContext, ChannelPromise) throws java.lang.Exception,public void exceptionCaught(ChannelHandlerContext, java.lang.Throwable) throws java.lang.Exception,public com.alipay.remoting.ConnectionEventListener getConnectionEventListener() ,public com.alipay.remoting.ConnectionManager getConnectionManager() ,public void setConnectionEventListener(com.alipay.remoting.ConnectionEventListener) ,public void setConnectionManager(com.alipay.remoting.ConnectionManager) ,public void setReconnectManager(com.alipay.remoting.ReconnectManager) ,public void setReconnector(com.alipay.remoting.Reconnector) ,public void userEventTriggered(ChannelHandlerContext, java.lang.Object) throws java.lang.Exception<variables>private com.alipay.remoting.config.Configuration configuration,private com.alipay.remoting.ConnectionManager connectionManager,private com.alipay.remoting.ConnectionEventHandler.ConnectionEventExecutor eventExecutor,private com.alipay.remoting.ConnectionEventListener eventListener,private static final Logger logger,private com.alipay.remoting.Reconnector reconnectManager
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/rpc/RpcHandler.java
|
RpcHandler
|
channelRead
|
class RpcHandler extends ChannelInboundHandlerAdapter {
private boolean serverSide;
private ConcurrentHashMap<String, UserProcessor<?>> userProcessors;
public RpcHandler(ConcurrentHashMap<String, UserProcessor<?>> userProcessors) {
serverSide = false;
this.userProcessors = userProcessors;
}
public RpcHandler(boolean serverSide, ConcurrentHashMap<String, UserProcessor<?>> userProcessors) {
this.serverSide = serverSide;
this.userProcessors = userProcessors;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {<FILL_FUNCTION_BODY>}
}
|
ProtocolCode protocolCode = ctx.channel().attr(Connection.PROTOCOL).get();
Protocol protocol = ProtocolManager.getProtocol(protocolCode);
protocol.getCommandHandler().handleCommand(
new RemotingContext(ctx, new InvokeContext(), serverSide, userProcessors), msg);
ctx.fireChannelRead(msg);
| 178
| 85
| 263
|
<no_super_class>
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/rpc/RpcInvokeCallbackListener.java
|
CallbackTask
|
run
|
class CallbackTask implements Runnable {
InvokeFuture future;
String remoteAddress;
/**
*
*/
public CallbackTask(String remoteAddress, InvokeFuture future) {
this.remoteAddress = remoteAddress;
this.future = future;
}
/**
* @see java.lang.Runnable#run()
*/
@Override
public void run() {<FILL_FUNCTION_BODY>} // end of run
}
|
InvokeCallback callback = future.getInvokeCallback();
// a lot of try-catches to protect thread pool
ResponseCommand response = null;
try {
response = (ResponseCommand) future.waitResponse(0);
} catch (InterruptedException e) {
String msg = "Exception caught when getting response from InvokeFuture. The address is "
+ this.remoteAddress;
logger.error(msg, e);
}
if (response == null || response.getResponseStatus() != ResponseStatus.SUCCESS) {
try {
Exception e;
if (response == null) {
e = new InvokeException("Exception caught in invocation. The address is "
+ this.remoteAddress + " responseStatus:"
+ ResponseStatus.UNKNOWN, future.getCause());
} else {
response.setInvokeContext(future.getInvokeContext());
switch (response.getResponseStatus()) {
case TIMEOUT:
e = new InvokeTimeoutException(
"Invoke timeout when invoke with callback.The address is "
+ this.remoteAddress);
break;
case CONNECTION_CLOSED:
e = new ConnectionClosedException(
"Connection closed when invoke with callback.The address is "
+ this.remoteAddress);
break;
case SERVER_THREADPOOL_BUSY:
e = new InvokeServerBusyException(
"Server thread pool busy when invoke with callback.The address is "
+ this.remoteAddress);
break;
case SERVER_EXCEPTION:
String msg = "Server exception when invoke with callback.Please check the server log! The address is "
+ this.remoteAddress;
RpcResponseCommand resp = (RpcResponseCommand) response;
resp.deserialize();
Object ex = resp.getResponseObject();
if (ex instanceof Throwable) {
e = new InvokeServerException(msg, (Throwable) ex);
} else {
e = new InvokeServerException(msg);
}
break;
default:
e = new InvokeException(
"Exception caught in invocation. The address is "
+ this.remoteAddress + " responseStatus:"
+ response.getResponseStatus(), future.getCause());
}
}
callback.onException(e);
} catch (Throwable e) {
logger
.error(
"Exception occurred in user defined InvokeCallback#onException() logic, The address is {}",
this.remoteAddress, e);
}
} else {
ClassLoader oldClassLoader = null;
try {
if (future.getAppClassLoader() != null) {
oldClassLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(future.getAppClassLoader());
}
response.setInvokeContext(future.getInvokeContext());
RpcResponseCommand rpcResponse = (RpcResponseCommand) response;
response.deserialize();
try {
callback.onResponse(rpcResponse.getResponseObject());
} catch (Throwable e) {
logger
.error(
"Exception occurred in user defined InvokeCallback#onResponse() logic.",
e);
}
} catch (CodecException e) {
logger
.error(
"CodecException caught on when deserialize response in RpcInvokeCallbackListener. The address is {}.",
this.remoteAddress, e);
} catch (Throwable e) {
logger.error(
"Exception caught in RpcInvokeCallbackListener. The address is {}",
this.remoteAddress, e);
} finally {
if (oldClassLoader != null) {
Thread.currentThread().setContextClassLoader(oldClassLoader);
}
}
} // enf of else
| 125
| 951
| 1,076
|
<no_super_class>
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/rpc/RpcResponseFuture.java
|
RpcResponseFuture
|
get
|
class RpcResponseFuture {
/** rpc server address */
private String addr;
/** rpc server port */
private InvokeFuture future;
/**
* Constructor
*/
public RpcResponseFuture(String addr, InvokeFuture future) {
this.addr = addr;
this.future = future;
}
/**
* Whether the future is done.
*/
public boolean isDone() {
return this.future.isDone();
}
/**
* get result with timeout specified
*
* if request done, resolve normal responseObject
* if request not done, throws InvokeTimeoutException
*/
public Object get(int timeoutMillis) throws InvokeTimeoutException, RemotingException,
InterruptedException {<FILL_FUNCTION_BODY>}
public Object get() throws RemotingException, InterruptedException {
ResponseCommand responseCommand = (ResponseCommand) this.future.waitResponse();
responseCommand.setInvokeContext(this.future.getInvokeContext());
return RpcResponseResolver.resolveResponseObject(responseCommand, addr);
}
}
|
this.future.waitResponse(timeoutMillis);
if (!isDone()) {
throw new InvokeTimeoutException("Future get result timeout!");
}
ResponseCommand responseCommand = (ResponseCommand) this.future.waitResponse();
responseCommand.setInvokeContext(this.future.getInvokeContext());
return RpcResponseResolver.resolveResponseObject(responseCommand, addr);
| 282
| 96
| 378
|
<no_super_class>
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/rpc/RpcResponseResolver.java
|
RpcResponseResolver
|
preProcess
|
class RpcResponseResolver {
private static final Logger logger = BoltLoggerFactory.getLogger("RpcRemoting");
/**
* Analyze the response command and generate the response object.
*
* @param responseCommand response command
* @param addr response address
* @return response object
*/
public static Object resolveResponseObject(ResponseCommand responseCommand, String addr)
throws RemotingException {
preProcess(responseCommand, addr);
if (responseCommand.getResponseStatus() == ResponseStatus.SUCCESS) {
return toResponseObject(responseCommand);
} else {
String msg = String.format("Rpc invocation exception: %s, the address is %s, id=%s",
responseCommand.getResponseStatus(), addr, responseCommand.getId());
logger.warn(msg);
if (responseCommand.getCause() != null) {
throw new InvokeException(msg, responseCommand.getCause());
} else {
throw new InvokeException(msg + ", please check the server log for more.");
}
}
}
private static void preProcess(ResponseCommand responseCommand, String addr)
throws RemotingException {<FILL_FUNCTION_BODY>}
/**
* Convert remoting response command to application response object.
*/
private static Object toResponseObject(ResponseCommand responseCommand) throws CodecException {
RpcResponseCommand response = (RpcResponseCommand) responseCommand;
response.deserialize();
return response.getResponseObject();
}
/**
* Convert remoting response command to throwable if it is a throwable, otherwise return null.
*/
private static Throwable toThrowable(ResponseCommand responseCommand) throws CodecException {
RpcResponseCommand resp = (RpcResponseCommand) responseCommand;
resp.deserialize();
Object ex = resp.getResponseObject();
if (ex instanceof Throwable) {
return (Throwable) ex;
}
return null;
}
/**
* Detail your error msg with the error msg returned from response command
*/
private static String detailErrMsg(String clientErrMsg, ResponseCommand responseCommand) {
RpcResponseCommand resp = (RpcResponseCommand) responseCommand;
if (StringUtils.isNotBlank(resp.getErrorMsg())) {
return String.format("%s, ServerErrorMsg:%s", clientErrMsg, resp.getErrorMsg());
} else {
return String.format("%s, ServerErrorMsg:null", clientErrMsg);
}
}
}
|
RemotingException e = null;
String msg = null;
if (responseCommand == null) {
msg = String.format("Rpc invocation timeout[responseCommand null]! the address is %s",
addr);
e = new InvokeTimeoutException(msg);
} else {
switch (responseCommand.getResponseStatus()) {
case TIMEOUT:
msg = String.format(
"Rpc invocation timeout[responseCommand TIMEOUT]! the address is %s", addr);
e = new InvokeTimeoutException(msg);
break;
case CLIENT_SEND_ERROR:
msg = String.format("Rpc invocation send failed! the address is %s", addr);
e = new InvokeSendFailedException(msg, responseCommand.getCause());
break;
case CONNECTION_CLOSED:
msg = String.format("Connection closed! the address is %s", addr);
e = new ConnectionClosedException(msg);
break;
case SERVER_THREADPOOL_BUSY:
msg = String.format("Server thread pool busy! the address is %s, id=%s", addr,
responseCommand.getId());
e = new InvokeServerBusyException(msg);
break;
case CODEC_EXCEPTION:
msg = String.format("Codec exception! the address is %s, id=%s", addr,
responseCommand.getId());
e = new CodecException(msg);
break;
case SERVER_SERIAL_EXCEPTION:
msg = String
.format(
"Server serialize response exception! the address is %s, id=%s, serverSide=true",
addr, responseCommand.getId());
e = new SerializationException(detailErrMsg(msg, responseCommand),
toThrowable(responseCommand), true);
break;
case SERVER_DESERIAL_EXCEPTION:
msg = String
.format(
"Server deserialize request exception! the address is %s, id=%s, serverSide=true",
addr, responseCommand.getId());
e = new DeserializationException(detailErrMsg(msg, responseCommand),
toThrowable(responseCommand), true);
break;
case SERVER_EXCEPTION:
msg = String.format(
"Server exception! Please check the server log, the address is %s, id=%s",
addr, responseCommand.getId());
e = new InvokeServerException(detailErrMsg(msg, responseCommand),
toThrowable(responseCommand));
break;
default:
break;
}
}
if (StringUtils.isNotBlank(msg)) {
logger.warn(msg);
}
if (null != e) {
throw e;
}
| 634
| 693
| 1,327
|
<no_super_class>
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/rpc/RpcServerRemoting.java
|
RpcServerRemoting
|
invokeSync
|
class RpcServerRemoting extends RpcRemoting {
/**
* default constructor
*/
public RpcServerRemoting(CommandFactory commandFactory) {
super(commandFactory);
}
/**
* @param addressParser
* @param connectionManager
*/
public RpcServerRemoting(CommandFactory commandFactory, RemotingAddressParser addressParser,
DefaultConnectionManager connectionManager) {
super(commandFactory, addressParser, connectionManager);
}
/**
* @see com.alipay.remoting.rpc.RpcRemoting#invokeSync(com.alipay.remoting.Url, java.lang.Object, InvokeContext, int)
*/
@Override
public Object invokeSync(Url url, Object request, InvokeContext invokeContext, int timeoutMillis)
throws RemotingException,
InterruptedException {<FILL_FUNCTION_BODY>}
/**
* @see com.alipay.remoting.rpc.RpcRemoting#oneway(com.alipay.remoting.Url, java.lang.Object, InvokeContext)
*/
@Override
public void oneway(Url url, Object request, InvokeContext invokeContext)
throws RemotingException {
Connection conn = this.connectionManager.get(url.getUniqueKey());
if (null == conn) {
throw new RemotingException("Client address [" + url.getOriginUrl()
+ "] not connected yet!");
}
this.connectionManager.check(conn);
this.oneway(conn, request, invokeContext);
}
/**
* @see com.alipay.remoting.rpc.RpcRemoting#invokeWithFuture(com.alipay.remoting.Url, java.lang.Object, InvokeContext, int)
*/
@Override
public RpcResponseFuture invokeWithFuture(Url url, Object request, InvokeContext invokeContext,
int timeoutMillis) throws RemotingException {
Connection conn = this.connectionManager.get(url.getUniqueKey());
if (null == conn) {
throw new RemotingException("Client address [" + url.getUniqueKey()
+ "] not connected yet!");
}
this.connectionManager.check(conn);
return this.invokeWithFuture(conn, request, invokeContext, timeoutMillis);
}
/**
* @see com.alipay.remoting.rpc.RpcRemoting#invokeWithCallback(com.alipay.remoting.Url, java.lang.Object, InvokeContext, com.alipay.remoting.InvokeCallback, int)
*/
@Override
public void invokeWithCallback(Url url, Object request, InvokeContext invokeContext,
InvokeCallback invokeCallback, int timeoutMillis)
throws RemotingException {
Connection conn = this.connectionManager.get(url.getUniqueKey());
if (null == conn) {
throw new RemotingException("Client address [" + url.getUniqueKey()
+ "] not connected yet!");
}
this.connectionManager.check(conn);
this.invokeWithCallback(conn, request, invokeContext, invokeCallback, timeoutMillis);
}
@Override
protected void preProcessInvokeContext(InvokeContext invokeContext, RemotingCommand cmd,
Connection connection) {
if (null != invokeContext) {
invokeContext.putIfAbsent(InvokeContext.SERVER_REMOTE_IP,
RemotingUtil.parseRemoteIP(connection.getChannel()));
invokeContext.putIfAbsent(InvokeContext.SERVER_REMOTE_PORT,
RemotingUtil.parseRemotePort(connection.getChannel()));
invokeContext.putIfAbsent(InvokeContext.SERVER_LOCAL_IP,
RemotingUtil.parseLocalIP(connection.getChannel()));
invokeContext.putIfAbsent(InvokeContext.SERVER_LOCAL_PORT,
RemotingUtil.parseLocalPort(connection.getChannel()));
invokeContext.putIfAbsent(InvokeContext.BOLT_INVOKE_REQUEST_ID, cmd.getId());
}
}
}
|
Connection conn = this.connectionManager.get(url.getUniqueKey());
if (null == conn) {
throw new RemotingException("Client address [" + url.getUniqueKey()
+ "] not connected yet!");
}
this.connectionManager.check(conn);
return this.invokeSync(conn, request, invokeContext, timeoutMillis);
| 1,028
| 93
| 1,121
|
<methods>public void <init>(com.alipay.remoting.CommandFactory) ,public void <init>(com.alipay.remoting.CommandFactory, com.alipay.remoting.RemotingAddressParser, com.alipay.remoting.ConnectionManager) ,public java.lang.Object invokeSync(java.lang.String, java.lang.Object, com.alipay.remoting.InvokeContext, int) throws com.alipay.remoting.exception.RemotingException, java.lang.InterruptedException,public abstract java.lang.Object invokeSync(com.alipay.remoting.Url, java.lang.Object, com.alipay.remoting.InvokeContext, int) throws com.alipay.remoting.exception.RemotingException, java.lang.InterruptedException,public java.lang.Object invokeSync(com.alipay.remoting.Connection, java.lang.Object, com.alipay.remoting.InvokeContext, int) throws com.alipay.remoting.exception.RemotingException, java.lang.InterruptedException,public void invokeWithCallback(java.lang.String, java.lang.Object, com.alipay.remoting.InvokeContext, com.alipay.remoting.InvokeCallback, int) throws com.alipay.remoting.exception.RemotingException, java.lang.InterruptedException,public abstract void invokeWithCallback(com.alipay.remoting.Url, java.lang.Object, com.alipay.remoting.InvokeContext, com.alipay.remoting.InvokeCallback, int) throws com.alipay.remoting.exception.RemotingException, java.lang.InterruptedException,public void invokeWithCallback(com.alipay.remoting.Connection, java.lang.Object, com.alipay.remoting.InvokeContext, com.alipay.remoting.InvokeCallback, int) throws com.alipay.remoting.exception.RemotingException,public com.alipay.remoting.rpc.RpcResponseFuture invokeWithFuture(java.lang.String, java.lang.Object, com.alipay.remoting.InvokeContext, int) throws com.alipay.remoting.exception.RemotingException, java.lang.InterruptedException,public abstract com.alipay.remoting.rpc.RpcResponseFuture invokeWithFuture(com.alipay.remoting.Url, java.lang.Object, com.alipay.remoting.InvokeContext, int) throws com.alipay.remoting.exception.RemotingException, java.lang.InterruptedException,public com.alipay.remoting.rpc.RpcResponseFuture invokeWithFuture(com.alipay.remoting.Connection, java.lang.Object, com.alipay.remoting.InvokeContext, int) throws com.alipay.remoting.exception.RemotingException,public void oneway(java.lang.String, java.lang.Object, com.alipay.remoting.InvokeContext) throws com.alipay.remoting.exception.RemotingException, java.lang.InterruptedException,public abstract void oneway(com.alipay.remoting.Url, java.lang.Object, com.alipay.remoting.InvokeContext) throws com.alipay.remoting.exception.RemotingException, java.lang.InterruptedException,public void oneway(com.alipay.remoting.Connection, java.lang.Object, com.alipay.remoting.InvokeContext) throws com.alipay.remoting.exception.RemotingException<variables>protected com.alipay.remoting.RemotingAddressParser addressParser,protected com.alipay.remoting.ConnectionManager connectionManager,private static final Logger logger
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/rpc/RpcTaskScanner.java
|
RpcTaskScanner
|
run
|
class RpcTaskScanner extends AbstractLifeCycle {
private static final Logger logger = BoltLoggerFactory.getLogger("RpcRemoting");
private final List<Scannable> scanList;
private ScheduledExecutorService scheduledService;
public RpcTaskScanner() {
this.scanList = new LinkedList<Scannable>();
}
@Override
public void startup() throws LifeCycleException {
super.startup();
scheduledService = new ScheduledThreadPoolExecutor(1, new NamedThreadFactory(
"RpcTaskScannerThread", true));
scheduledService.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {<FILL_FUNCTION_BODY>}
}, 10000, 10000, TimeUnit.MILLISECONDS);
}
@Override
public void shutdown() throws LifeCycleException {
super.shutdown();
scheduledService.shutdown();
}
/**
* Use {@link RpcTaskScanner#startup()} instead
*/
@Deprecated
public void start() {
startup();
}
/**
* Add scan target.
*/
public void add(Scannable target) {
scanList.add(target);
}
}
|
for (Scannable scanned : scanList) {
try {
scanned.scan();
} catch (Throwable t) {
logger.error("Exception caught when scannings.", t);
}
}
| 343
| 59
| 402
|
<methods>public non-sealed void <init>() ,public boolean isStarted() ,public void shutdown() throws com.alipay.remoting.LifeCycleException,public void startup() throws com.alipay.remoting.LifeCycleException<variables>private final java.util.concurrent.atomic.AtomicBoolean isStarted
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/rpc/protocol/AsyncMultiInterestUserProcessor.java
|
AsyncMultiInterestUserProcessor
|
handleRequest
|
class AsyncMultiInterestUserProcessor<T> extends
AbstractMultiInterestUserProcessor<T> {
/**
* unsupported here!
*
* @see com.alipay.remoting.rpc.protocol.UserProcessor#handleRequest(com.alipay.remoting.BizContext, java.lang.Object)
*/
@Override
public Object handleRequest(BizContext bizCtx, T request) throws Exception {<FILL_FUNCTION_BODY>}
/**
* @see com.alipay.remoting.rpc.protocol.UserProcessor#handleRequest(com.alipay.remoting.BizContext, com.alipay.remoting.AsyncContext, java.lang.Object)
*/
@Override
public abstract void handleRequest(BizContext bizCtx, AsyncContext asyncCtx, T request);
/**
* @see com.alipay.remoting.rpc.protocol.MultiInterestUserProcessor#multiInterest()
*/
@Override
public abstract List<String> multiInterest();
}
|
throw new UnsupportedOperationException(
"SYNC handle request is unsupported in AsyncMultiInterestUserProcessor!");
| 265
| 31
| 296
|
<methods>public non-sealed void <init>() ,public java.lang.String interest() <variables>
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/rpc/protocol/AsyncUserProcessor.java
|
AsyncUserProcessor
|
handleRequest
|
class AsyncUserProcessor<T> extends AbstractUserProcessor<T> {
/**
* unsupported here!
*
* @see com.alipay.remoting.rpc.protocol.UserProcessor#handleRequest(com.alipay.remoting.BizContext, java.lang.Object)
*/
@Override
public Object handleRequest(BizContext bizCtx, T request) throws Exception {<FILL_FUNCTION_BODY>}
/**
* @see com.alipay.remoting.rpc.protocol.UserProcessor#handleRequest(com.alipay.remoting.BizContext, com.alipay.remoting.AsyncContext, java.lang.Object)
*/
@Override
public abstract void handleRequest(BizContext bizCtx, AsyncContext asyncCtx, T request);
/**
* @see com.alipay.remoting.rpc.protocol.UserProcessor#interest()
*/
@Override
public abstract String interest();
}
|
throw new UnsupportedOperationException(
"SYNC handle request is unsupported in AsyncUserProcessor!");
| 251
| 29
| 280
|
<methods>public non-sealed void <init>() ,public java.lang.ClassLoader getBizClassLoader() ,public java.util.concurrent.Executor getExecutor() ,public com.alipay.remoting.rpc.protocol.UserProcessor.ExecutorSelector getExecutorSelector() ,public com.alipay.remoting.BizContext preHandleRequest(com.alipay.remoting.RemotingContext, T) ,public boolean processInIOThread() ,public void setExecutorSelector(com.alipay.remoting.rpc.protocol.UserProcessor.ExecutorSelector) ,public boolean timeoutDiscard() <variables>protected com.alipay.remoting.rpc.protocol.UserProcessor.ExecutorSelector executorSelector
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/rpc/protocol/RpcAsyncContext.java
|
RpcAsyncContext
|
sendResponse
|
class RpcAsyncContext implements AsyncContext {
/** remoting context */
private RemotingContext ctx;
/** rpc request command */
private RpcRequestCommand cmd;
private RpcRequestProcessor processor;
/** is response sent already */
private AtomicBoolean isResponseSentAlready = new AtomicBoolean();
/**
* Default constructor.
*
* @param ctx remoting context
* @param cmd rpc request command
* @param processor rpc request processor
*/
public RpcAsyncContext(final RemotingContext ctx, final RpcRequestCommand cmd,
final RpcRequestProcessor processor) {
this.ctx = ctx;
this.cmd = cmd;
this.processor = processor;
}
/**
* @see com.alipay.remoting.AsyncContext#sendResponse(java.lang.Object)
*/
@Override
public void sendResponse(Object responseObject) {<FILL_FUNCTION_BODY>}
/**
* @see com.alipay.remoting.AsyncContext#sendException(java.lang.Throwable)
*/
@Override
public void sendException(Throwable ex) {
if (isResponseSentAlready.compareAndSet(false, true)) {
processor.sendResponseIfNecessary(
this.ctx,
cmd.getType(),
processor.getCommandFactory().createExceptionResponse(this.cmd.getId(),
ResponseStatus.SERVER_EXCEPTION, ex));
} else {
throw new IllegalStateException("Should not send rpc response repeatedly!");
}
}
}
|
if (isResponseSentAlready.compareAndSet(false, true)) {
processor.sendResponseIfNecessary(this.ctx, cmd.getType(), processor
.getCommandFactory().createResponse(responseObject, this.cmd));
} else {
throw new IllegalStateException("Should not send rpc response repeatedly!");
}
| 401
| 85
| 486
|
<no_super_class>
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/rpc/protocol/RpcCommandDecoder.java
|
RpcCommandDecoder
|
decode
|
class RpcCommandDecoder implements CommandDecoder {
private static final Logger logger = BoltLoggerFactory.getLogger("RpcRemoting");
private int lessLen;
{
lessLen = RpcProtocol.getResponseHeaderLength() < RpcProtocol.getRequestHeaderLength() ? RpcProtocol
.getResponseHeaderLength() : RpcProtocol.getRequestHeaderLength();
}
/**
* @see com.alipay.remoting.CommandDecoder#decode(io.netty.channel.ChannelHandlerContext, io.netty.buffer.ByteBuf, java.util.List)
*/
@Override
public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {<FILL_FUNCTION_BODY>}
private ResponseCommand createResponseCommand(short cmdCode) {
ResponseCommand command = new RpcResponseCommand();
command.setCmdCode(RpcCommandCode.valueOf(cmdCode));
return command;
}
private RpcRequestCommand createRequestCommand(short cmdCode, long headerArriveTimeInNano) {
RpcRequestCommand command = new RpcRequestCommand();
command.setCmdCode(RpcCommandCode.valueOf(cmdCode));
command.setArriveTime(System.currentTimeMillis());
command.setArriveHeaderTimeInNano(headerArriveTimeInNano);
command.setArriveBodyTimeInNano(System.nanoTime());
return command;
}
}
|
// the less length between response header and request header
if (in.readableBytes() >= lessLen) {
in.markReaderIndex();
byte protocol = in.readByte();
in.resetReaderIndex();
if (protocol == RpcProtocol.PROTOCOL_CODE) {
/*
* ver: version for protocol
* type: request/response/request oneway
* cmdcode: code for remoting command
* ver2:version for remoting command
* requestId: id of request
* codec: code for codec
* (req)timeout: request timeout
* (resp)respStatus: response status
* classLen: length of request or response class name
* headerLen: length of header
* contentLen: length of content
* className
* header
* content
*/
if (in.readableBytes() > 2) {
in.markReaderIndex();
in.readByte(); //version
byte type = in.readByte(); //type
if (type == RpcCommandType.REQUEST || type == RpcCommandType.REQUEST_ONEWAY) {
//decode request
if (in.readableBytes() >= RpcProtocol.getRequestHeaderLength() - 2) {
short cmdCode = in.readShort();
byte ver2 = in.readByte();
int requestId = in.readInt();
byte serializer = in.readByte();
int timeout = in.readInt();
short classLen = in.readShort();
short headerLen = in.readShort();
int contentLen = in.readInt();
byte[] clazz = null;
byte[] header = null;
byte[] content = null;
Channel channel = ctx.channel();
ThreadLocalArriveTimeHolder.arrive(channel, requestId);
if (in.readableBytes() >= classLen + headerLen + contentLen) {
if (classLen > 0) {
clazz = new byte[classLen];
in.readBytes(clazz);
}
if (headerLen > 0) {
header = new byte[headerLen];
in.readBytes(header);
}
if (contentLen > 0) {
content = new byte[contentLen];
in.readBytes(content);
}
} else {// not enough data
in.resetReaderIndex();
return;
}
RequestCommand command;
long headerArriveTimeInNano = ThreadLocalArriveTimeHolder.getAndClear(
channel, requestId);
if (cmdCode == CommandCode.HEARTBEAT_VALUE) {
command = new HeartbeatCommand();
} else {
command = createRequestCommand(cmdCode, headerArriveTimeInNano);
}
command.setType(type);
command.setVersion(ver2);
command.setId(requestId);
command.setSerializer(serializer);
command.setTimeout(timeout);
command.setClazz(clazz);
command.setHeader(header);
command.setContent(content);
out.add(command);
} else {
in.resetReaderIndex();
}
} else if (type == RpcCommandType.RESPONSE) {
//decode response
if (in.readableBytes() >= RpcProtocol.getResponseHeaderLength() - 2) {
short cmdCode = in.readShort();
byte ver2 = in.readByte();
int requestId = in.readInt();
byte serializer = in.readByte();
short status = in.readShort();
short classLen = in.readShort();
short headerLen = in.readShort();
int contentLen = in.readInt();
byte[] clazz = null;
byte[] header = null;
byte[] content = null;
if (in.readableBytes() >= classLen + headerLen + contentLen) {
if (classLen > 0) {
clazz = new byte[classLen];
in.readBytes(clazz);
}
if (headerLen > 0) {
header = new byte[headerLen];
in.readBytes(header);
}
if (contentLen > 0) {
content = new byte[contentLen];
in.readBytes(content);
}
} else {// not enough data
in.resetReaderIndex();
return;
}
ResponseCommand command;
if (cmdCode == CommandCode.HEARTBEAT_VALUE) {
command = new HeartbeatAckCommand();
} else {
command = createResponseCommand(cmdCode);
}
command.setType(type);
command.setVersion(ver2);
command.setId(requestId);
command.setSerializer(serializer);
command.setResponseStatus(ResponseStatus.valueOf(status));
command.setClazz(clazz);
command.setHeader(header);
command.setContent(content);
command.setResponseTimeMillis(System.currentTimeMillis());
command.setResponseHost((InetSocketAddress) ctx.channel()
.remoteAddress());
out.add(command);
} else {
in.resetReaderIndex();
}
} else {
String emsg = "Unknown command type: " + type;
logger.error(emsg);
throw new RuntimeException(emsg);
}
}
} else {
String emsg = "Unknown protocol: " + protocol;
logger.error(emsg);
throw new RuntimeException(emsg);
}
}
| 372
| 1,374
| 1,746
|
<no_super_class>
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/rpc/protocol/RpcCommandEncoder.java
|
RpcCommandEncoder
|
encode
|
class RpcCommandEncoder implements CommandEncoder {
/** logger */
private static final Logger logger = BoltLoggerFactory.getLogger("RpcRemoting");
/**
* @see com.alipay.remoting.CommandEncoder#encode(io.netty.channel.ChannelHandlerContext, java.io.Serializable, io.netty.buffer.ByteBuf)
*/
@Override
public void encode(ChannelHandlerContext ctx, Serializable msg, ByteBuf out) throws Exception {<FILL_FUNCTION_BODY>}
}
|
try {
if (msg instanceof RpcCommand) {
/*
* ver: version for protocol
* type: request/response/request oneway
* cmdcode: code for remoting command
* ver2:version for remoting command
* requestId: id of request
* codec: code for codec
* (req)timeout: request timeout.
* (resp)respStatus: response status
* classLen: length of request or response class name
* headerLen: length of header
* cotentLen: length of content
* className
* header
* content
*/
RpcCommand cmd = (RpcCommand) msg;
out.writeByte(RpcProtocol.PROTOCOL_CODE);
out.writeByte(cmd.getType());
out.writeShort(((RpcCommand) msg).getCmdCode().value());
out.writeByte(cmd.getVersion());
out.writeInt(cmd.getId());
out.writeByte(cmd.getSerializer());
if (cmd instanceof RequestCommand) {
//timeout
out.writeInt(((RequestCommand) cmd).getTimeout());
}
if (cmd instanceof ResponseCommand) {
//response status
ResponseCommand response = (ResponseCommand) cmd;
out.writeShort(response.getResponseStatus().getValue());
}
out.writeShort(cmd.getClazzLength());
out.writeShort(cmd.getHeaderLength());
out.writeInt(cmd.getContentLength());
if (cmd.getClazzLength() > 0) {
out.writeBytes(cmd.getClazz());
}
if (cmd.getHeaderLength() > 0) {
out.writeBytes(cmd.getHeader());
}
if (cmd.getContentLength() > 0) {
out.writeBytes(cmd.getContent());
}
} else {
String warnMsg = "msg type [" + msg.getClass() + "] is not subclass of RpcCommand";
logger.warn(warnMsg);
}
} catch (Exception e) {
logger.error("Exception caught!", e);
throw e;
}
| 134
| 530
| 664
|
<no_super_class>
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/rpc/protocol/RpcCommandEncoderV2.java
|
RpcCommandEncoderV2
|
encode
|
class RpcCommandEncoderV2 implements CommandEncoder {
/** logger */
private static final Logger logger = BoltLoggerFactory.getLogger("RpcRemoting");
/**
* @see CommandEncoder#encode(ChannelHandlerContext, Serializable, ByteBuf)
*/
@Override
public void encode(ChannelHandlerContext ctx, Serializable msg, ByteBuf out) throws Exception {<FILL_FUNCTION_BODY>}
}
|
try {
if (msg instanceof RpcCommand) {
/*
* proto: magic code for protocol
* ver: version for protocol
* type: request/response/request oneway
* cmdcode: code for remoting command
* ver2:version for remoting command
* requestId: id of request
* codec: code for codec
* switch: function switch
* (req)timeout: request timeout.
* (resp)respStatus: response status
* classLen: length of request or response class name
* headerLen: length of header
* cotentLen: length of content
* className
* header
* content
* crc (optional)
*/
int index = out.writerIndex();
RpcCommand cmd = (RpcCommand) msg;
out.writeByte(RpcProtocolV2.PROTOCOL_CODE);
Attribute<Byte> version = ctx.channel().attr(Connection.VERSION);
byte ver = RpcProtocolV2.PROTOCOL_VERSION_1;
if (version != null && version.get() != null) {
ver = version.get();
}
out.writeByte(ver);
out.writeByte(cmd.getType());
out.writeShort(((RpcCommand) msg).getCmdCode().value());
out.writeByte(cmd.getVersion());
out.writeInt(cmd.getId());
out.writeByte(cmd.getSerializer());
out.writeByte(cmd.getProtocolSwitch().toByte());
if (cmd instanceof RequestCommand) {
//timeout
out.writeInt(((RequestCommand) cmd).getTimeout());
}
if (cmd instanceof ResponseCommand) {
//response status
ResponseCommand response = (ResponseCommand) cmd;
out.writeShort(response.getResponseStatus().getValue());
}
out.writeShort(cmd.getClazzLength());
out.writeShort(cmd.getHeaderLength());
out.writeInt(cmd.getContentLength());
if (cmd.getClazzLength() > 0) {
out.writeBytes(cmd.getClazz());
}
if (cmd.getHeaderLength() > 0) {
out.writeBytes(cmd.getHeader());
}
if (cmd.getContentLength() > 0) {
out.writeBytes(cmd.getContent());
}
if (ver == RpcProtocolV2.PROTOCOL_VERSION_2
&& cmd.getProtocolSwitch().isOn(ProtocolSwitch.CRC_SWITCH_INDEX)) {
// compute the crc32 and write to out
byte[] frame = new byte[out.readableBytes()];
out.getBytes(index, frame);
out.writeInt(CrcUtil.crc32(frame));
}
} else {
String warnMsg = "msg type [" + msg.getClass() + "] is not subclass of RpcCommand";
logger.warn(warnMsg);
}
} catch (Exception e) {
logger.error("Exception caught!", e);
throw e;
}
| 109
| 763
| 872
|
<no_super_class>
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/rpc/protocol/RpcCommandHandler.java
|
RpcCommandHandler
|
processExceptionForSingleCommand
|
class RpcCommandHandler implements CommandHandler {
private static final Logger logger = BoltLoggerFactory.getLogger("RpcRemoting");
/** All processors */
ProcessorManager processorManager;
CommandFactory commandFactory;
/**
* Constructor. Initialize the processor manager and register processors.
*/
public RpcCommandHandler(CommandFactory commandFactory) {
this.commandFactory = commandFactory;
this.processorManager = new ProcessorManager();
//process request
this.processorManager.registerProcessor(RpcCommandCode.RPC_REQUEST,
new RpcRequestProcessor(this.commandFactory));
//process response
this.processorManager.registerProcessor(RpcCommandCode.RPC_RESPONSE,
new RpcResponseProcessor());
this.processorManager.registerProcessor(CommonCommandCode.HEARTBEAT,
new RpcHeartBeatProcessor());
this.processorManager
.registerDefaultProcessor(new AbstractRemotingProcessor<RemotingCommand>() {
@Override
public void doProcess(RemotingContext ctx, RemotingCommand msg) throws Exception {
logger.error("No processor available for command code {}, msgId {}",
msg.getCmdCode(), msg.getId());
}
});
}
/**
* @see CommandHandler#handleCommand(RemotingContext, Object)
*/
@Override
public void handleCommand(RemotingContext ctx, Object msg) throws Exception {
this.handle(ctx, msg);
}
/*
* Handle the request(s).
*/
private void handle(final RemotingContext ctx, final Object msg) {
try {
if (msg instanceof List) {
final Runnable handleTask = new Runnable() {
@Override
public void run() {
if (logger.isDebugEnabled()) {
logger.debug("Batch message! size={}", ((List<?>) msg).size());
}
for (final Object m : (List<?>) msg) {
RpcCommandHandler.this.process(ctx, m);
}
}
};
if (RpcConfigManager.dispatch_msg_list_in_default_executor()) {
// If msg is list ,then the batch submission to biz threadpool can save io thread.
// See com.alipay.remoting.decoder.ProtocolDecoder
processorManager.getDefaultExecutor().execute(handleTask);
} else {
handleTask.run();
}
} else {
process(ctx, msg);
}
} catch (final Throwable t) {
processException(ctx, msg, t);
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private void process(RemotingContext ctx, Object msg) {
try {
final RpcCommand cmd = (RpcCommand) msg;
final RemotingProcessor processor = processorManager.getProcessor(cmd.getCmdCode());
processor.process(ctx, cmd, processorManager.getDefaultExecutor());
} catch (final Throwable t) {
processException(ctx, msg, t);
}
}
private void processException(RemotingContext ctx, Object msg, Throwable t) {
if (msg instanceof List) {
for (final Object m : (List<?>) msg) {
processExceptionForSingleCommand(ctx, m, t);
}
} else {
processExceptionForSingleCommand(ctx, msg, t);
}
}
/*
* Return error command if necessary.
*/
private void processExceptionForSingleCommand(RemotingContext ctx, Object msg, Throwable t) {<FILL_FUNCTION_BODY>}
/**
* @see CommandHandler#registerProcessor(com.alipay.remoting.CommandCode, RemotingProcessor)
*/
@Override
public void registerProcessor(CommandCode cmd,
@SuppressWarnings("rawtypes") RemotingProcessor processor) {
this.processorManager.registerProcessor(cmd, processor);
}
/**
* @see CommandHandler#registerDefaultExecutor(java.util.concurrent.ExecutorService)
*/
@Override
public void registerDefaultExecutor(ExecutorService executor) {
this.processorManager.registerDefaultExecutor(executor);
}
/**
* @see CommandHandler#getDefaultExecutor()
*/
@Override
public ExecutorService getDefaultExecutor() {
return this.processorManager.getDefaultExecutor();
}
}
|
final int id = ((RpcCommand) msg).getId();
final String emsg = "Exception caught when processing "
+ ((msg instanceof RequestCommand) ? "request, id=" : "response, id=");
logger.warn(emsg + id, t);
if (msg instanceof RequestCommand) {
final RequestCommand cmd = (RequestCommand) msg;
if (cmd.getType() != RpcCommandType.REQUEST_ONEWAY) {
if (t instanceof RejectedExecutionException) {
final ResponseCommand response = this.commandFactory.createExceptionResponse(
id, ResponseStatus.SERVER_THREADPOOL_BUSY);
// RejectedExecutionException here assures no response has been sent back
// Other exceptions should be processed where exception was caught, because here we don't known whether ack had been sent back.
ctx.getChannelContext().writeAndFlush(response)
.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
if (logger.isInfoEnabled()) {
logger
.info(
"Write back exception response done, requestId={}, status={}",
id, response.getResponseStatus());
}
} else {
logger.error(
"Write back exception response failed, requestId={}", id,
future.cause());
}
}
});
}
}
}
| 1,115
| 360
| 1,475
|
<no_super_class>
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/rpc/protocol/RpcDeserializeLevel.java
|
RpcDeserializeLevel
|
valueOf
|
class RpcDeserializeLevel {
/** deserialize clazz, header, contents all three parts of rpc command */
public final static int DESERIALIZE_ALL = 0x02;
/** deserialize both header and clazz parts of rpc command */
public final static int DESERIALIZE_HEADER = 0x01;
/** deserialize only the clazz part of rpc command */
public final static int DESERIALIZE_CLAZZ = 0x00;
/**
* Convert to String.
*/
public static String valueOf(int value) {<FILL_FUNCTION_BODY>}
}
|
switch (value) {
case 0x00:
return "DESERIALIZE_CLAZZ";
case 0x01:
return "DESERIALIZE_HEADER";
case 0x02:
return "DESERIALIZE_ALL";
}
throw new IllegalArgumentException("Unknown deserialize level value ," + value);
| 163
| 96
| 259
|
<no_super_class>
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/rpc/protocol/RpcHeartBeatProcessor.java
|
RpcHeartBeatProcessor
|
doProcess
|
class RpcHeartBeatProcessor extends AbstractRemotingProcessor {
private static final Logger logger = BoltLoggerFactory.getLogger("RpcRemoting");
@Override
public void doProcess(final RemotingContext ctx, RemotingCommand msg) {<FILL_FUNCTION_BODY>}
}
|
if (msg instanceof HeartbeatCommand) {// process the heartbeat
final int id = msg.getId();
if (logger.isDebugEnabled()) {
logger.debug("Heartbeat received! Id=" + id + ", from "
+ RemotingUtil.parseRemoteAddress(ctx.getChannelContext().channel()));
}
HeartbeatAckCommand ack = new HeartbeatAckCommand();
ack.setId(id);
ctx.writeAndFlush(ack).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
if (logger.isDebugEnabled()) {
logger.debug("Send heartbeat ack done! Id={}, to remoteAddr={}", id,
RemotingUtil.parseRemoteAddress(ctx.getChannelContext().channel()));
}
} else {
logger.error("Send heartbeat ack failed! Id={}, to remoteAddr={}", id,
RemotingUtil.parseRemoteAddress(ctx.getChannelContext().channel()));
}
}
});
} else if (msg instanceof HeartbeatAckCommand) {
Connection conn = ctx.getChannelContext().channel().attr(Connection.CONNECTION).get();
InvokeFuture future = conn.removeInvokeFuture(msg.getId());
if (future != null) {
future.putResponse(msg);
future.cancelTimeout();
try {
future.executeInvokeCallback();
} catch (Exception e) {
logger.error(
"Exception caught when executing heartbeat invoke callback. From {}",
RemotingUtil.parseRemoteAddress(ctx.getChannelContext().channel()), e);
}
} else {
logger
.warn(
"Cannot find heartbeat InvokeFuture, maybe already timeout. Id={}, From {}",
msg.getId(),
RemotingUtil.parseRemoteAddress(ctx.getChannelContext().channel()));
}
} else {
throw new RuntimeException("Cannot process command: " + msg.getClass().getName());
}
| 76
| 511
| 587
|
<methods>public void <init>() ,public void <init>(com.alipay.remoting.CommandFactory) ,public void <init>(java.util.concurrent.ExecutorService) ,public void <init>(com.alipay.remoting.CommandFactory, java.util.concurrent.ExecutorService) ,public abstract void doProcess(com.alipay.remoting.RemotingContext, com.alipay.remoting.RemotingCommand) throws java.lang.Exception,public com.alipay.remoting.CommandFactory getCommandFactory() ,public java.util.concurrent.ExecutorService getExecutor() ,public void process(com.alipay.remoting.RemotingContext, com.alipay.remoting.RemotingCommand, java.util.concurrent.ExecutorService) throws java.lang.Exception,public void setCommandFactory(com.alipay.remoting.CommandFactory) ,public void setExecutor(java.util.concurrent.ExecutorService) <variables>private com.alipay.remoting.CommandFactory commandFactory,private java.util.concurrent.ExecutorService executor,private static final Logger logger
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/rpc/protocol/RpcHeartbeatTrigger.java
|
RpcHeartbeatTrigger
|
heartbeatTriggered
|
class RpcHeartbeatTrigger implements HeartbeatTrigger {
private static final Logger logger = BoltLoggerFactory.getLogger("RpcRemoting");
/** max trigger times */
public static final Integer maxCount = ConfigManager.tcp_idle_maxtimes();
private static final long heartbeatTimeoutMillis = 1000;
private CommandFactory commandFactory;
public RpcHeartbeatTrigger(CommandFactory commandFactory) {
this.commandFactory = commandFactory;
}
/**
* @see com.alipay.remoting.HeartbeatTrigger#heartbeatTriggered(io.netty.channel.ChannelHandlerContext)
*/
@Override
public void heartbeatTriggered(final ChannelHandlerContext ctx) throws Exception {<FILL_FUNCTION_BODY>}
}
|
Integer heartbeatTimes = ctx.channel().attr(Connection.HEARTBEAT_COUNT).get();
final Connection conn = ctx.channel().attr(Connection.CONNECTION).get();
if (heartbeatTimes >= maxCount) {
try {
conn.close();
logger.error(
"Heartbeat failed for {} times, close the connection from client side: {} ",
heartbeatTimes, RemotingUtil.parseRemoteAddress(ctx.channel()));
} catch (Exception e) {
logger.warn("Exception caught when closing connection in SharableHandler.", e);
}
} else {
boolean heartbeatSwitch = ctx.channel().attr(Connection.HEARTBEAT_SWITCH).get();
if (!heartbeatSwitch) {
return;
}
final HeartbeatCommand heartbeat = new HeartbeatCommand();
final InvokeFuture future = new DefaultInvokeFuture(heartbeat.getId(),
new InvokeCallbackListener() {
@Override
public void onResponse(InvokeFuture future) {
ResponseCommand response;
try {
response = (ResponseCommand) future.waitResponse(0);
} catch (InterruptedException e) {
logger.error("Heartbeat ack process error! Id={}, from remoteAddr={}",
heartbeat.getId(), RemotingUtil.parseRemoteAddress(ctx.channel()),
e);
return;
}
if (response != null
&& response.getResponseStatus() == ResponseStatus.SUCCESS) {
if (logger.isDebugEnabled()) {
logger.debug("Heartbeat ack received! Id={}, from remoteAddr={}",
response.getId(),
RemotingUtil.parseRemoteAddress(ctx.channel()));
}
ctx.channel().attr(Connection.HEARTBEAT_COUNT).set(0);
} else {
if (response != null
&& response.getResponseStatus() == ResponseStatus.TIMEOUT) {
logger.error("Heartbeat timeout! The address is {}",
RemotingUtil.parseRemoteAddress(ctx.channel()));
} else {
logger.error(
"Heartbeat exception caught! Error code={}, The address is {}",
response == null ? null : response.getResponseStatus(),
RemotingUtil.parseRemoteAddress(ctx.channel()));
}
Integer times = ctx.channel().attr(Connection.HEARTBEAT_COUNT).get();
ctx.channel().attr(Connection.HEARTBEAT_COUNT).set(times + 1);
}
}
@Override
public String getRemoteAddress() {
return ctx.channel().remoteAddress().toString();
}
}, null, heartbeat.getProtocolCode().getFirstByte(), this.commandFactory);
final int heartbeatId = heartbeat.getId();
conn.addInvokeFuture(future);
if (logger.isDebugEnabled()) {
logger.debug("Send heartbeat, successive count={}, Id={}, to remoteAddr={}",
heartbeatTimes, heartbeatId, RemotingUtil.parseRemoteAddress(ctx.channel()));
}
ctx.writeAndFlush(heartbeat).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
if (logger.isDebugEnabled()) {
logger.debug("Send heartbeat done! Id={}, to remoteAddr={}",
heartbeatId, RemotingUtil.parseRemoteAddress(ctx.channel()));
}
} else {
logger.error("Send heartbeat failed! Id={}, to remoteAddr={}", heartbeatId,
RemotingUtil.parseRemoteAddress(ctx.channel()));
}
}
});
TimerHolder.getTimer().newTimeout(new TimerTask() {
@Override
public void run(Timeout timeout) throws Exception {
InvokeFuture future = conn.removeInvokeFuture(heartbeatId);
if (future != null) {
future.putResponse(commandFactory.createTimeoutResponse(conn
.getRemoteAddress()));
future.tryAsyncExecuteInvokeCallbackAbnormally();
}
}
}, heartbeatTimeoutMillis, TimeUnit.MILLISECONDS);
}
| 209
| 1,034
| 1,243
|
<no_super_class>
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/rpc/protocol/RpcProtocolDecoder.java
|
RpcProtocolDecoder
|
decodeProtocolVersion
|
class RpcProtocolDecoder extends ProtocolCodeBasedDecoder {
public static final int MIN_PROTOCOL_CODE_WITH_VERSION = 2;
public RpcProtocolDecoder(int protocolCodeLength) {
super(protocolCodeLength);
}
@Override
protected byte decodeProtocolVersion(ByteBuf in) {<FILL_FUNCTION_BODY>}
}
|
in.resetReaderIndex();
if (in.readableBytes() >= protocolCodeLength + DEFAULT_PROTOCOL_VERSION_LENGTH) {
byte rpcProtocolCodeByte = in.readByte();
if (rpcProtocolCodeByte >= MIN_PROTOCOL_CODE_WITH_VERSION) {
return in.readByte();
}
}
return DEFAULT_ILLEGAL_PROTOCOL_VERSION_LENGTH;
| 95
| 108
| 203
|
<methods>public void <init>(int) <variables>public static final int DEFAULT_ILLEGAL_PROTOCOL_VERSION_LENGTH,public static final int DEFAULT_PROTOCOL_VERSION_LENGTH,protected int protocolCodeLength
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/rpc/protocol/RpcRequestCommand.java
|
RpcRequestCommand
|
deserializeHeader
|
class RpcRequestCommand extends RequestCommand {
/** For serialization */
private static final long serialVersionUID = -4602613826188210946L;
private Object requestObject;
private String requestClass;
private CustomSerializer customSerializer;
private Object requestHeader;
private transient long arriveTime = -1;
private transient long arriveHeaderTimeInNano = -1;
private transient long arriveBodyTimeInNano = -1;
private transient long beforeEnterQueueTime = -1;
/**
* create request command without id
*/
public RpcRequestCommand() {
super(RpcCommandCode.RPC_REQUEST);
}
/**
* create request command with id and request object
* @param request request object
*/
public RpcRequestCommand(Object request) {
super(RpcCommandCode.RPC_REQUEST);
this.requestObject = request;
this.setId(IDGenerator.nextId());
}
@Override
public void serializeClazz() throws SerializationException {
if (this.requestClass != null) {
try {
byte[] clz = this.requestClass.getBytes(Configs.DEFAULT_CHARSET);
this.setClazz(clz);
} catch (UnsupportedEncodingException e) {
throw new SerializationException("Unsupported charset: " + Configs.DEFAULT_CHARSET,
e);
}
}
}
@Override
public void deserializeClazz() throws DeserializationException {
if (this.getClazz() != null && this.getRequestClass() == null) {
try {
this.setRequestClass(new String(this.getClazz(), Configs.DEFAULT_CHARSET));
} catch (UnsupportedEncodingException e) {
throw new DeserializationException("Unsupported charset: "
+ Configs.DEFAULT_CHARSET, e);
}
}
}
@Override
public void serializeHeader(InvokeContext invokeContext) throws SerializationException {
if (this.getCustomSerializer() != null) {
try {
this.getCustomSerializer().serializeHeader(this, invokeContext);
} catch (SerializationException e) {
throw e;
} catch (Exception e) {
throw new SerializationException(
"Exception caught when serialize header of rpc request command!", e);
}
}
}
@Override
public void deserializeHeader(InvokeContext invokeContext) throws DeserializationException {<FILL_FUNCTION_BODY>}
@Override
public void serializeContent(InvokeContext invokeContext) throws SerializationException {
if (this.requestObject != null) {
try {
if (this.getCustomSerializer() != null
&& this.getCustomSerializer().serializeContent(this, invokeContext)) {
return;
}
this.setContent(SerializerManager.getSerializer(this.getSerializer()).serialize(
this.requestObject));
} catch (SerializationException e) {
throw e;
} catch (Exception e) {
throw new SerializationException(
"Exception caught when serialize content of rpc request command!", e);
}
}
}
@Override
public void deserializeContent(InvokeContext invokeContext) throws DeserializationException {
if (this.getRequestObject() == null) {
try {
if (this.getCustomSerializer() != null
&& this.getCustomSerializer().deserializeContent(this)) {
return;
}
if (this.getContent() != null) {
this.setRequestObject(SerializerManager.getSerializer(this.getSerializer())
.deserialize(this.getContent(), this.requestClass));
}
} catch (DeserializationException e) {
throw e;
} catch (Exception e) {
throw new DeserializationException(
"Exception caught when deserialize content of rpc request command!", e);
}
}
}
/**
* Getter method for property <tt>requestObject</tt>.
*
* @return property value of requestObject
*/
public Object getRequestObject() {
return requestObject;
}
/**
* Setter method for property <tt>requestObject</tt>.
*
* @param requestObject value to be assigned to property requestObject
*/
public void setRequestObject(Object requestObject) {
this.requestObject = requestObject;
}
/**
* Getter method for property <tt>requestHeader</tt>.
*
* @return property value of requestHeader
*/
public Object getRequestHeader() {
return requestHeader;
}
/**
* Setter method for property <tt>requestHeader</tt>.
*
* @param requestHeader value to be assigned to property requestHeader
*/
public void setRequestHeader(Object requestHeader) {
this.requestHeader = requestHeader;
}
/**
* Getter method for property <tt>requestClass</tt>.
*
* @return property value of requestClass
*/
public String getRequestClass() {
return requestClass;
}
/**
* Setter method for property <tt>requestClass</tt>.
*
* @param requestClass value to be assigned to property requestClass
*/
public void setRequestClass(String requestClass) {
this.requestClass = requestClass;
}
/**
* Getter method for property <tt>customSerializer</tt>.
*
* @return property value of customSerializer
*/
public CustomSerializer getCustomSerializer() {
if (this.customSerializer != null) {
return customSerializer;
}
if (this.requestClass != null) {
this.customSerializer = CustomSerializerManager.getCustomSerializer(this.requestClass);
}
if (this.customSerializer == null) {
this.customSerializer = CustomSerializerManager.getCustomSerializer(this.getCmdCode());
}
return this.customSerializer;
}
/**
* Getter method for property <tt>arriveTime</tt>.
*
* @return property value of arriveTime
*/
public long getArriveTime() {
return arriveTime;
}
/**
* Setter method for property <tt>arriveTime</tt>.
*
* @param arriveTime value to be assigned to property arriveTime
*/
public void setArriveTime(long arriveTime) {
this.arriveTime = arriveTime;
}
public long getArriveHeaderTimeInNano() {
return arriveHeaderTimeInNano;
}
public void setArriveHeaderTimeInNano(long arriveHeaderTimeInNano) {
this.arriveHeaderTimeInNano = arriveHeaderTimeInNano;
}
public long getArriveBodyTimeInNano() {
return arriveBodyTimeInNano;
}
public void setArriveBodyTimeInNano(long arriveBodyTimeInNano) {
this.arriveBodyTimeInNano = arriveBodyTimeInNano;
}
public long getBeforeEnterQueueTime() {
return beforeEnterQueueTime;
}
public void setBeforeEnterQueueTime(long beforeEnterQueueTime) {
this.beforeEnterQueueTime = beforeEnterQueueTime;
}
}
|
if (this.getHeader() != null && this.getRequestHeader() == null) {
if (this.getCustomSerializer() != null) {
try {
this.getCustomSerializer().deserializeHeader(this);
} catch (DeserializationException e) {
throw e;
} catch (Exception e) {
throw new DeserializationException(
"Exception caught when deserialize header of rpc request command!", e);
}
}
}
| 1,898
| 123
| 2,021
|
<methods>public void <init>() ,public void <init>(com.alipay.remoting.CommandCode) ,public void <init>(byte, com.alipay.remoting.CommandCode) ,public void <init>(byte, byte, com.alipay.remoting.CommandCode) ,public int getTimeout() ,public void setTimeout(int) <variables>private static final long serialVersionUID,private int timeout
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/rpc/protocol/RpcResponseCommand.java
|
RpcResponseCommand
|
deserializeContent
|
class RpcResponseCommand extends ResponseCommand {
/** For serialization */
private static final long serialVersionUID = 5667111367880018776L;
private Object responseObject;
private String responseClass;
private CustomSerializer customSerializer;
private Object responseHeader;
private String errorMsg;
public RpcResponseCommand() {
super(RpcCommandCode.RPC_RESPONSE);
}
public RpcResponseCommand(Object response) {
super(RpcCommandCode.RPC_RESPONSE);
this.responseObject = response;
}
public RpcResponseCommand(int id, Object response) {
super(RpcCommandCode.RPC_RESPONSE, id);
this.responseObject = response;
}
/**
* Getter method for property <tt>responseObject</tt>.
*
* @return property value of responseObject
*/
public Object getResponseObject() {
return responseObject;
}
/**
* Setter method for property <tt>responseObject</tt>.
*
* @param response value to be assigned to property responseObject
*/
public void setResponseObject(Object response) {
this.responseObject = response;
}
@Override
public void serializeClazz() throws SerializationException {
if (this.getResponseClass() != null) {
try {
byte[] clz = this.getResponseClass().getBytes(Configs.DEFAULT_CHARSET);
this.setClazz(clz);
} catch (UnsupportedEncodingException e) {
throw new SerializationException("Unsupported charset: " + Configs.DEFAULT_CHARSET,
e);
}
}
}
@Override
public void deserializeClazz() throws DeserializationException {
if (this.getClazz() != null && this.getResponseClass() == null) {
try {
this.setResponseClass(new String(this.getClazz(), Configs.DEFAULT_CHARSET));
} catch (UnsupportedEncodingException e) {
throw new DeserializationException("Unsupported charset: "
+ Configs.DEFAULT_CHARSET, e);
}
}
}
@Override
public void serializeContent(InvokeContext invokeContext) throws SerializationException {
if (this.getResponseObject() != null) {
try {
if (this.getCustomSerializer() != null
&& this.getCustomSerializer().serializeContent(this)) {
return;
}
this.setContent(SerializerManager.getSerializer(this.getSerializer()).serialize(
this.responseObject));
} catch (SerializationException e) {
throw e;
} catch (Exception e) {
throw new SerializationException(
"Exception caught when serialize content of rpc response command!", e);
}
}
}
@Override
public void deserializeContent(InvokeContext invokeContext) throws DeserializationException {<FILL_FUNCTION_BODY>}
@Override
public void serializeHeader(InvokeContext invokeContext) throws SerializationException {
if (this.getCustomSerializer() != null) {
try {
this.getCustomSerializer().serializeHeader(this);
} catch (SerializationException e) {
throw e;
} catch (Exception e) {
throw new SerializationException(
"Exception caught when serialize header of rpc response command!", e);
}
}
}
@Override
public void deserializeHeader(InvokeContext invokeContext) throws DeserializationException {
if (this.getHeader() != null && this.getResponseHeader() == null) {
if (this.getCustomSerializer() != null) {
try {
this.getCustomSerializer().deserializeHeader(this, invokeContext);
} catch (DeserializationException e) {
throw e;
} catch (Exception e) {
throw new DeserializationException(
"Exception caught when deserialize header of rpc response command!", e);
}
}
}
}
/**
* Getter method for property <tt>responseClass</tt>.
*
* @return property value of responseClass
*/
public String getResponseClass() {
return responseClass;
}
/**
* Setter method for property <tt>responseClass</tt>.
*
* @param responseClass value to be assigned to property responseClass
*/
public void setResponseClass(String responseClass) {
this.responseClass = responseClass;
}
/**
* Getter method for property <tt>responseHeader</tt>.
*
* @return property value of responseHeader
*/
public Object getResponseHeader() {
return responseHeader;
}
/**
* Setter method for property <tt>responseHeader</tt>.
*
* @param responseHeader value to be assigned to property responseHeader
*/
public void setResponseHeader(Object responseHeader) {
this.responseHeader = responseHeader;
}
/**
* Getter method for property <tt>customSerializer</tt>.
*
* @return property value of customSerializer
*/
public CustomSerializer getCustomSerializer() {
if (this.customSerializer != null) {
return customSerializer;
}
if (this.responseClass != null) {
this.customSerializer = CustomSerializerManager.getCustomSerializer(this.responseClass);
}
if (this.customSerializer == null) {
this.customSerializer = CustomSerializerManager.getCustomSerializer(this.getCmdCode());
}
return this.customSerializer;
}
/**
* Getter method for property <tt>errorMsg</tt>.
*
* @return property value of errorMsg
*/
public String getErrorMsg() {
return errorMsg;
}
/**
* Setter method for property <tt>errorMsg</tt>.
*
* @param errorMsg value to be assigned to property errorMsg
*/
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
}
|
if (this.getResponseObject() == null) {
try {
if (this.getCustomSerializer() != null
&& this.getCustomSerializer().deserializeContent(this, invokeContext)) {
return;
}
if (this.getContent() != null) {
this.setResponseObject(SerializerManager.getSerializer(this.getSerializer())
.deserialize(this.getContent(), this.responseClass));
}
} catch (DeserializationException e) {
throw e;
} catch (Exception e) {
throw new DeserializationException(
"Exception caught when deserialize content of rpc response command!", e);
}
}
| 1,588
| 175
| 1,763
|
<methods>public void <init>() ,public void <init>(com.alipay.remoting.CommandCode) ,public void <init>(int) ,public void <init>(com.alipay.remoting.CommandCode, int) ,public void <init>(byte, byte, com.alipay.remoting.CommandCode, int) ,public java.lang.Throwable getCause() ,public java.net.InetSocketAddress getResponseHost() ,public com.alipay.remoting.ResponseStatus getResponseStatus() ,public long getResponseTimeMillis() ,public void setCause(java.lang.Throwable) ,public void setResponseHost(java.net.InetSocketAddress) ,public void setResponseStatus(com.alipay.remoting.ResponseStatus) ,public void setResponseTimeMillis(long) <variables>private java.lang.Throwable cause,private java.net.InetSocketAddress responseHost,private com.alipay.remoting.ResponseStatus responseStatus,private long responseTimeMillis,private static final long serialVersionUID
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/rpc/protocol/RpcResponseProcessor.java
|
RpcResponseProcessor
|
doProcess
|
class RpcResponseProcessor extends AbstractRemotingProcessor<RemotingCommand> {
private static final Logger logger = BoltLoggerFactory.getLogger("RpcRemoting");
/**
* Default constructor.
*/
public RpcResponseProcessor() {
}
/**
* Constructor.
*/
public RpcResponseProcessor(ExecutorService executor) {
super(executor);
}
/**
* @see com.alipay.remoting.AbstractRemotingProcessor#doProcess
*/
@Override
public void doProcess(RemotingContext ctx, RemotingCommand cmd) {<FILL_FUNCTION_BODY>}
}
|
Connection conn = ctx.getChannelContext().channel().attr(Connection.CONNECTION).get();
InvokeFuture future = conn.removeInvokeFuture(cmd.getId());
ClassLoader oldClassLoader = null;
try {
if (future != null) {
if (future.getAppClassLoader() != null) {
oldClassLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(future.getAppClassLoader());
}
future.putResponse(cmd);
future.cancelTimeout();
try {
future.executeInvokeCallback();
} catch (Exception e) {
logger.error("Exception caught when executing invoke callback, id={}",
cmd.getId(), e);
}
} else {
logger
.warn("Cannot find InvokeFuture, maybe already timeout, id={}, from={} ",
cmd.getId(),
RemotingUtil.parseRemoteAddress(ctx.getChannelContext().channel()));
}
} finally {
if (null != oldClassLoader) {
Thread.currentThread().setContextClassLoader(oldClassLoader);
}
}
| 168
| 287
| 455
|
<methods>public void <init>() ,public void <init>(com.alipay.remoting.CommandFactory) ,public void <init>(java.util.concurrent.ExecutorService) ,public void <init>(com.alipay.remoting.CommandFactory, java.util.concurrent.ExecutorService) ,public abstract void doProcess(com.alipay.remoting.RemotingContext, com.alipay.remoting.RemotingCommand) throws java.lang.Exception,public com.alipay.remoting.CommandFactory getCommandFactory() ,public java.util.concurrent.ExecutorService getExecutor() ,public void process(com.alipay.remoting.RemotingContext, com.alipay.remoting.RemotingCommand, java.util.concurrent.ExecutorService) throws java.lang.Exception,public void setCommandFactory(com.alipay.remoting.CommandFactory) ,public void setExecutor(java.util.concurrent.ExecutorService) <variables>private com.alipay.remoting.CommandFactory commandFactory,private java.util.concurrent.ExecutorService executor,private static final Logger logger
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/rpc/protocol/SyncMultiInterestUserProcessor.java
|
SyncMultiInterestUserProcessor
|
handleRequest
|
class SyncMultiInterestUserProcessor<T> extends
AbstractMultiInterestUserProcessor<T> {
/**
* @see com.alipay.remoting.rpc.protocol.UserProcessor#handleRequest(com.alipay.remoting.BizContext, java.lang.Object)
*/
@Override
public abstract Object handleRequest(BizContext bizCtx, T request) throws Exception;
/**
* unsupported here!
*
* @see com.alipay.remoting.rpc.protocol.UserProcessor#handleRequest(com.alipay.remoting.BizContext, com.alipay.remoting.AsyncContext, java.lang.Object)
*/
@Override
public void handleRequest(BizContext bizCtx, AsyncContext asyncCtx, T request) {<FILL_FUNCTION_BODY>}
/**
* @see com.alipay.remoting.rpc.protocol.MultiInterestUserProcessor#multiInterest()
*/
@Override
public abstract List<String> multiInterest();
}
|
throw new UnsupportedOperationException(
"ASYNC handle request is unsupported in SyncMultiInterestUserProcessor!");
| 268
| 32
| 300
|
<methods>public non-sealed void <init>() ,public java.lang.String interest() <variables>
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/rpc/protocol/SyncUserProcessor.java
|
SyncUserProcessor
|
handleRequest
|
class SyncUserProcessor<T> extends AbstractUserProcessor<T> {
/**
* @see com.alipay.remoting.rpc.protocol.UserProcessor#handleRequest(com.alipay.remoting.BizContext, java.lang.Object)
*/
@Override
public abstract Object handleRequest(BizContext bizCtx, T request) throws Exception;
/**
* unsupported here!
*
* @see com.alipay.remoting.rpc.protocol.UserProcessor#handleRequest(com.alipay.remoting.BizContext, com.alipay.remoting.AsyncContext, java.lang.Object)
*/
@Override
public void handleRequest(BizContext bizCtx, AsyncContext asyncCtx, T request) {<FILL_FUNCTION_BODY>}
/**
* @see com.alipay.remoting.rpc.protocol.UserProcessor#interest()
*/
@Override
public abstract String interest();
}
|
throw new UnsupportedOperationException(
"ASYNC handle request is unsupported in SyncUserProcessor!");
| 252
| 30
| 282
|
<methods>public non-sealed void <init>() ,public java.lang.ClassLoader getBizClassLoader() ,public java.util.concurrent.Executor getExecutor() ,public com.alipay.remoting.rpc.protocol.UserProcessor.ExecutorSelector getExecutorSelector() ,public com.alipay.remoting.BizContext preHandleRequest(com.alipay.remoting.RemotingContext, T) ,public boolean processInIOThread() ,public void setExecutorSelector(com.alipay.remoting.rpc.protocol.UserProcessor.ExecutorSelector) ,public boolean timeoutDiscard() <variables>protected com.alipay.remoting.rpc.protocol.UserProcessor.ExecutorSelector executorSelector
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/rpc/protocol/UserProcessorRegisterHelper.java
|
UserProcessorRegisterHelper
|
registerUserProcessor
|
class UserProcessorRegisterHelper {
/**
* Help register single-interest user processor.
*
* @param processor the processor need to be registered
* @param userProcessors the map of user processors
*/
public static void registerUserProcessor(UserProcessor<?> processor,
ConcurrentHashMap<String, UserProcessor<?>> userProcessors) {
if (null == processor) {
throw new RuntimeException("User processor should not be null!");
}
if (processor instanceof MultiInterestUserProcessor) {
registerUserProcessor((MultiInterestUserProcessor) processor, userProcessors);
} else {
if (StringUtils.isBlank(processor.interest())) {
throw new RuntimeException("Processor interest should not be blank!");
}
UserProcessor<?> preProcessor = userProcessors.putIfAbsent(processor.interest(),
processor);
if (preProcessor != null) {
String errMsg = "Processor with interest key ["
+ processor.interest()
+ "] has already been registered to rpc server, can not register again!";
throw new RuntimeException(errMsg);
}
}
}
/**
* Help register multi-interest user processor.
*
* @param processor the processor with multi-interest need to be registered
* @param userProcessors the map of user processors
*/
private static void registerUserProcessor(MultiInterestUserProcessor<?> processor,
ConcurrentHashMap<String, UserProcessor<?>> userProcessors) {<FILL_FUNCTION_BODY>}
}
|
if (null == processor.multiInterest() || processor.multiInterest().isEmpty()) {
throw new RuntimeException("Processor interest should not be blank!");
}
for (String interest : processor.multiInterest()) {
UserProcessor<?> preProcessor = userProcessors.putIfAbsent(interest, processor);
if (preProcessor != null) {
String errMsg = "Processor with interest key ["
+ interest
+ "] has already been registered to rpc server, can not register again!";
throw new RuntimeException(errMsg);
}
}
| 388
| 141
| 529
|
<no_super_class>
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/serialization/HessianSerializer.java
|
HessianSerializer
|
serialize
|
class HessianSerializer implements Serializer {
private SerializerFactory serializerFactory = new SerializerFactory();
private static ThreadLocal<ByteArrayOutputStream> localOutputByteArray = new ThreadLocal<ByteArrayOutputStream>() {
@Override
protected ByteArrayOutputStream initialValue() {
return new ByteArrayOutputStream();
}
};
/**
* @see com.alipay.remoting.serialization.Serializer#serialize(java.lang.Object)
*/
@Override
public byte[] serialize(Object obj) throws CodecException {<FILL_FUNCTION_BODY>}
/**
*
* @see com.alipay.remoting.serialization.Serializer#deserialize(byte[], java.lang.String)
*/
@SuppressWarnings("unchecked")
@Override
public <T> T deserialize(byte[] data, String classOfT) throws CodecException {
Hessian2Input input = new Hessian2Input(new ByteArrayInputStream(data));
input.setSerializerFactory(serializerFactory);
Object resultObject;
try {
resultObject = input.readObject();
input.close();
} catch (IOException e) {
throw new CodecException("IOException occurred when Hessian serializer decode!", e);
}
return (T) resultObject;
}
}
|
ByteArrayOutputStream byteArray = localOutputByteArray.get();
byteArray.reset();
Hessian2Output output = new Hessian2Output(byteArray);
output.setSerializerFactory(serializerFactory);
try {
output.writeObject(obj);
output.close();
} catch (IOException e) {
throw new CodecException("IOException occurred when Hessian serializer encode!", e);
}
return byteArray.toByteArray();
| 348
| 118
| 466
|
<no_super_class>
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/serialization/SerializerManager.java
|
SerializerManager
|
addSerializer
|
class SerializerManager {
private static Serializer[] serializers = new Serializer[5];
public static final byte Hessian2 = 1;
//public static final byte Json = 2;
private static final ReentrantLock REENTRANT_LOCK = new ReentrantLock();
public static Serializer getSerializer(int idx) {
Serializer currentSerializer = serializers[idx];
if (currentSerializer == null && idx == Hessian2) {
REENTRANT_LOCK.lock();
try {
currentSerializer = serializers[idx];
if (currentSerializer == null) {
currentSerializer = new HessianSerializer();
addSerializer(Hessian2, currentSerializer);
}
} finally {
REENTRANT_LOCK.unlock();
}
}
return currentSerializer;
}
public static void addSerializer(int idx, Serializer serializer) {<FILL_FUNCTION_BODY>}
}
|
if (serializers.length <= idx) {
Serializer[] newSerializers = new Serializer[idx + 5];
System.arraycopy(serializers, 0, newSerializers, 0, serializers.length);
serializers = newSerializers;
}
serializers[idx] = serializer;
| 243
| 80
| 323
|
<no_super_class>
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/util/ConnectionUtil.java
|
ConnectionUtil
|
getConnectionFromChannel
|
class ConnectionUtil {
public static Connection getConnectionFromChannel(Channel channel) {<FILL_FUNCTION_BODY>}
public static void addIdPoolKeyMapping(Integer id, String group, Channel channel) {
Connection connection = getConnectionFromChannel(channel);
if (connection != null) {
connection.addIdPoolKeyMapping(id, group);
}
}
public static String removeIdPoolKeyMapping(Integer id, Channel channel) {
Connection connection = getConnectionFromChannel(channel);
if (connection != null) {
return connection.removeIdPoolKeyMapping(id);
}
return null;
}
public static void addIdGroupCallbackMapping(Integer id, InvokeFuture callback, Channel channel) {
Connection connection = getConnectionFromChannel(channel);
if (connection != null) {
connection.addInvokeFuture(callback);
}
}
public static InvokeFuture removeIdGroupCallbackMapping(Integer id, Channel channel) {
Connection connection = getConnectionFromChannel(channel);
if (connection != null) {
return connection.removeInvokeFuture(id);
}
return null;
}
public static InvokeFuture getGroupRequestCallBack(Integer id, Channel channel) {
Connection connection = getConnectionFromChannel(channel);
if (connection != null) {
return connection.getInvokeFuture(id);
}
return null;
}
}
|
if (channel == null) {
return null;
}
Attribute<Connection> connAttr = channel.attr(Connection.CONNECTION);
if (connAttr != null) {
Connection connection = connAttr.get();
return connection;
}
return null;
| 360
| 75
| 435
|
<no_super_class>
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/util/CrcUtil.java
|
CrcUtil
|
crc32
|
class CrcUtil {
private static final ThreadLocal<CRC32> CRC_32_THREAD_LOCAL = new ThreadLocal<CRC32>() {
@Override
protected CRC32 initialValue() {
return new CRC32();
}
};
/**
* Compute CRC32 code for byte[].
*
* @param array
* @return
*/
public static final int crc32(byte[] array) {
if (array != null) {
return crc32(array, 0, array.length);
}
return 0;
}
/**
* Compute CRC32 code for byte[].
*
* @param array
* @param offset
* @param length
* @return
*/
public static final int crc32(byte[] array, int offset, int length) {<FILL_FUNCTION_BODY>}
}
|
CRC32 crc32 = CRC_32_THREAD_LOCAL.get();
crc32.update(array, offset, length);
int ret = (int) crc32.getValue();
crc32.reset();
return ret;
| 253
| 72
| 325
|
<no_super_class>
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/util/FutureTaskUtil.java
|
FutureTaskUtil
|
launderThrowable
|
class FutureTaskUtil {
/**
* get the result of a future task
*
* Notice: the run method of this task should have been called at first.
*
* @param task
* @param <T>
* @return
*/
public static <T> T getFutureTaskResult(RunStateRecordedFutureTask<T> task, Logger logger) {
T t = null;
if (null != task) {
try {
t = task.getAfterRun();
} catch (InterruptedException e) {
logger.error("Future task interrupted!", e);
} catch (ExecutionException e) {
logger.error("Future task execute failed!", e);
} catch (FutureTaskNotRunYetException e) {
logger.warn("Future task has not run yet!", e);
} catch (FutureTaskNotCompleted e) {
logger.warn("Future task has not completed!", e);
}
}
return t;
}
/**
* launder the throwable
*
* @param t
*/
public static void launderThrowable(Throwable t) {<FILL_FUNCTION_BODY>}
}
|
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else if (t instanceof Error) {
throw (Error) t;
} else {
throw new IllegalStateException("Not unchecked!", t);
}
| 298
| 64
| 362
|
<no_super_class>
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/util/IoUtils.java
|
IoUtils
|
closeQuietly
|
class IoUtils {
public static void closeQuietly(Closeable closeable) {<FILL_FUNCTION_BODY>}
}
|
try {
if (closeable != null) {
closeable.close();
}
} catch (IOException e) { // NOPMD
// ignore
}
| 35
| 48
| 83
|
<no_super_class>
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/util/NettyEventLoopUtil.java
|
NettyEventLoopUtil
|
newEventLoopGroup
|
class NettyEventLoopUtil {
/** check whether epoll enabled, and it would not be changed during runtime. */
private static boolean epollEnabled = ConfigManager.netty_epoll() && Epoll.isAvailable();
/**
* Create the right event loop according to current platform and system property, fallback to NIO when epoll not enabled.
*
* @param nThreads
* @param threadFactory
* @return an EventLoopGroup suitable for the current platform
*/
public static EventLoopGroup newEventLoopGroup(int nThreads, ThreadFactory threadFactory) {<FILL_FUNCTION_BODY>}
/**
* @return a SocketChannel class suitable for the given EventLoopGroup implementation
*/
public static Class<? extends SocketChannel> getClientSocketChannelClass() {
return epollEnabled ? EpollSocketChannel.class : NioSocketChannel.class;
}
/**
* @return a ServerSocketChannel class suitable for the given EventLoopGroup implementation
*/
public static Class<? extends ServerSocketChannel> getServerSocketChannelClass() {
return epollEnabled ? EpollServerSocketChannel.class : NioServerSocketChannel.class;
}
/**
* Use {@link EpollMode#LEVEL_TRIGGERED} for server bootstrap if level trigger enabled by system properties,
* otherwise use {@link EpollMode#EDGE_TRIGGERED}.
* @param serverBootstrap server bootstrap
*/
public static void enableTriggeredMode(ServerBootstrap serverBootstrap) {
if (epollEnabled) {
if (ConfigManager.netty_epoll_lt_enabled()) {
serverBootstrap.childOption(EpollChannelOption.EPOLL_MODE,
EpollMode.LEVEL_TRIGGERED);
} else {
serverBootstrap
.childOption(EpollChannelOption.EPOLL_MODE, EpollMode.EDGE_TRIGGERED);
}
}
}
}
|
return epollEnabled ? new EpollEventLoopGroup(nThreads, threadFactory)
: new NioEventLoopGroup(nThreads, threadFactory);
| 490
| 41
| 531
|
<no_super_class>
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/util/RemotingUtil.java
|
RemotingUtil
|
parseRemoteAddress
|
class RemotingUtil {
/**
* Parse the remote address of the channel.
*
* @param channel
* @return
*/
public static String parseRemoteAddress(final Channel channel) {<FILL_FUNCTION_BODY>}
/**
* Parse the local address of the channel.
*
* @param channel
* @return
*/
public static String parseLocalAddress(final Channel channel) {
if (null == channel) {
return StringUtils.EMPTY;
}
final SocketAddress local = channel.localAddress();
return doParse(local != null ? local.toString().trim() : StringUtils.EMPTY);
}
/**
* Parse the remote host ip of the channel.
*
* @param channel
* @return
*/
public static String parseRemoteIP(final Channel channel) {
if (null == channel) {
return StringUtils.EMPTY;
}
final InetSocketAddress remote = (InetSocketAddress) channel.remoteAddress();
if (remote != null) {
return remote.getAddress().getHostAddress();
}
return StringUtils.EMPTY;
}
/**
* Parse the remote hostname of the channel.
*
* Note: take care to use this method, for a reverse name lookup takes uncertain time in {@link InetAddress#getHostName}.
*
* @param channel
* @return
*/
public static String parseRemoteHostName(final Channel channel) {
if (null == channel) {
return StringUtils.EMPTY;
}
final InetSocketAddress remote = (InetSocketAddress) channel.remoteAddress();
if (remote != null) {
return remote.getAddress().getHostName();
}
return StringUtils.EMPTY;
}
/**
* Parse the local host ip of the channel.
*
* @param channel
* @return
*/
public static String parseLocalIP(final Channel channel) {
if (null == channel) {
return StringUtils.EMPTY;
}
final InetSocketAddress local = (InetSocketAddress) channel.localAddress();
if (local != null) {
return local.getAddress().getHostAddress();
}
return StringUtils.EMPTY;
}
/**
* Parse the remote host port of the channel.
*
* @param channel
* @return int
*/
public static int parseRemotePort(final Channel channel) {
if (null == channel) {
return -1;
}
final InetSocketAddress remote = (InetSocketAddress) channel.remoteAddress();
if (remote != null) {
return remote.getPort();
}
return -1;
}
/**
* Parse the local host port of the channel.
*
* @param channel
* @return int
*/
public static int parseLocalPort(final Channel channel) {
if (null == channel) {
return -1;
}
final InetSocketAddress local = (InetSocketAddress) channel.localAddress();
if (local != null) {
return local.getPort();
}
return -1;
}
/**
* Parse the socket address, omit the leading "/" if present.
*
* e.g.1 /127.0.0.1:1234 -> 127.0.0.1:1234
* e.g.2 sofatest-2.stack.alipay.net/10.209.155.54:12200 -> 10.209.155.54:12200
*
* @param socketAddress
* @return String
*/
public static String parseSocketAddressToString(SocketAddress socketAddress) {
if (socketAddress != null) {
return doParse(socketAddress.toString().trim());
}
return StringUtils.EMPTY;
}
/**
* Parse the host ip of socket address.
*
* e.g. /127.0.0.1:1234 -> 127.0.0.1
*
* @param socketAddress
* @return String
*/
public static String parseSocketAddressToHostIp(SocketAddress socketAddress) {
final InetSocketAddress addrs = (InetSocketAddress) socketAddress;
if (addrs != null) {
InetAddress addr = addrs.getAddress();
if (null != addr) {
return addr.getHostAddress();
}
}
return StringUtils.EMPTY;
}
/**
* <ol>
* <li>if an address starts with a '/', skip it.
* <li>if an address contains a '/', substring it.
* </ol>
*
* @param addr
* @return
*/
private static String doParse(String addr) {
if (StringUtils.isBlank(addr)) {
return StringUtils.EMPTY;
}
if (addr.charAt(0) == '/') {
return addr.substring(1);
} else {
int len = addr.length();
for (int i = 1; i < len; ++i) {
if (addr.charAt(i) == '/') {
return addr.substring(i + 1);
}
}
return addr;
}
}
}
|
if (null == channel) {
return StringUtils.EMPTY;
}
final SocketAddress remote = channel.remoteAddress();
return doParse(remote != null ? remote.toString().trim() : StringUtils.EMPTY);
| 1,420
| 63
| 1,483
|
<no_super_class>
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/util/RunStateRecordedFutureTask.java
|
RunStateRecordedFutureTask
|
getAfterRun
|
class RunStateRecordedFutureTask<V> extends FutureTask<V> {
private AtomicBoolean hasRun = new AtomicBoolean();
public RunStateRecordedFutureTask(Callable<V> callable) {
super(callable);
}
@Override
public void run() {
this.hasRun.set(true);
super.run();
}
public V getAfterRun() throws InterruptedException, ExecutionException,
FutureTaskNotRunYetException, FutureTaskNotCompleted {<FILL_FUNCTION_BODY>}
}
|
if (!hasRun.get()) {
throw new FutureTaskNotRunYetException();
}
if (!isDone()) {
throw new FutureTaskNotCompleted();
}
return super.get();
| 141
| 57
| 198
|
<methods>public void <init>(Callable<V>) ,public void <init>(java.lang.Runnable, V) ,public boolean cancel(boolean) ,public V get() throws java.lang.InterruptedException, java.util.concurrent.ExecutionException,public V get(long, java.util.concurrent.TimeUnit) throws java.lang.InterruptedException, java.util.concurrent.ExecutionException, java.util.concurrent.TimeoutException,public boolean isCancelled() ,public boolean isDone() ,public void run() ,public java.lang.String toString() <variables>private static final int CANCELLED,private static final int COMPLETING,private static final int EXCEPTIONAL,private static final int INTERRUPTED,private static final int INTERRUPTING,private static final int NEW,private static final int NORMAL,private static final java.lang.invoke.VarHandle RUNNER,private static final java.lang.invoke.VarHandle STATE,private static final java.lang.invoke.VarHandle WAITERS,private Callable<V> callable,private java.lang.Object outcome,private volatile java.lang.Thread runner,private volatile int state,private volatile java.util.concurrent.FutureTask.WaitNode waiters
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/util/StringUtils.java
|
StringUtils
|
splitWorker
|
class StringUtils {
public static final String EMPTY = "";
public static final String[] EMPTY_STRING_ARRAY = new String[0];
// Empty checks
//-----------------------------------------------------------------------
public static boolean isEmpty(CharSequence cs) {
return cs == null || cs.length() == 0;
}
public static boolean isNotEmpty(CharSequence cs) {
return !StringUtils.isEmpty(cs);
}
public static boolean isBlank(CharSequence cs) {
int strLen;
if (cs == null || (strLen = cs.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(cs.charAt(i))) {
return false;
}
}
return true;
}
public static boolean isNotBlank(CharSequence cs) {
return !StringUtils.isBlank(cs);
}
// Splitting
//-----------------------------------------------------------------------
public static String[] split(final String str, final char separatorChar) {
return splitWorker(str, separatorChar, false);
}
private static String[] splitWorker(final String str, final char separatorChar,
final boolean preserveAllTokens) {<FILL_FUNCTION_BODY>}
public static boolean isNumeric(String str) {
if (str == null) {
return false;
} else {
int sz = str.length();
for (int i = 0; i < sz; ++i) {
if (!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
}
public static boolean equals(String str1, String str2) {
return str1 == null ? str2 == null : str1.equals(str2);
}
}
|
// Performance tuned for 2.0 (JDK1.4)
if (str == null) {
return null;
}
final int len = str.length();
if (len == 0) {
return EMPTY_STRING_ARRAY;
}
final List<String> list = new ArrayList<String>();
int i = 0, start = 0;
boolean match = false;
boolean lastMatch = false;
while (i < len) {
if (str.charAt(i) == separatorChar) {
if (match || preserveAllTokens) {
list.add(str.substring(start, i));
match = false;
lastMatch = true;
}
start = ++i;
continue;
}
lastMatch = false;
match = true;
i++;
}
if (match || preserveAllTokens && lastMatch) {
list.add(str.substring(start, i));
}
return list.toArray(new String[list.size()]);
| 495
| 266
| 761
|
<no_super_class>
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/util/ThreadLocalArriveTimeHolder.java
|
ThreadLocalArriveTimeHolder
|
getArriveTimeMap
|
class ThreadLocalArriveTimeHolder {
private static FastThreadLocal<WeakHashMap<Channel, Map<Integer, Long>>> arriveTimeInNano = new FastThreadLocal<WeakHashMap<Channel, Map<Integer, Long>>>();
public static void arrive(Channel channel, Integer key) {
Map<Integer, Long> map = getArriveTimeMap(channel);
if (map.get(key) == null) {
map.put(key, System.nanoTime());
}
}
public static long getAndClear(Channel channel, Integer key) {
Map<Integer, Long> map = getArriveTimeMap(channel);
Long result = map.remove(key);
if (result == null) {
return -1;
}
return result;
}
private static Map<Integer, Long> getArriveTimeMap(Channel channel) {<FILL_FUNCTION_BODY>}
}
|
WeakHashMap<Channel, Map<Integer, Long>> map = arriveTimeInNano.get();
if (map == null) {
arriveTimeInNano.set(new WeakHashMap<Channel, Map<Integer, Long>>(256));
map = arriveTimeInNano.get();
}
Map<Integer, Long> subMap = map.get(channel);
if (subMap == null) {
map.put(channel, new HashMap<Integer, Long>());
}
return map.get(channel);
| 230
| 137
| 367
|
<no_super_class>
|
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/util/TraceLogUtil.java
|
TraceLogUtil
|
printConnectionTraceLog
|
class TraceLogUtil {
/**
* print trace log
* @param traceId
* @param invokeContext
*/
public static void printConnectionTraceLog(Logger logger, String traceId,
InvokeContext invokeContext) {<FILL_FUNCTION_BODY>}
}
|
String sourceIp = invokeContext.get(InvokeContext.CLIENT_LOCAL_IP);
Integer sourcePort = invokeContext.get(InvokeContext.CLIENT_LOCAL_PORT);
String targetIp = invokeContext.get(InvokeContext.CLIENT_REMOTE_IP);
Integer targetPort = invokeContext.get(InvokeContext.CLIENT_REMOTE_PORT);
StringBuilder logMsg = new StringBuilder();
logMsg.append(traceId).append(",");
logMsg.append(sourceIp).append(",");
logMsg.append(sourcePort).append(",");
logMsg.append(targetIp).append(",");
logMsg.append(targetPort);
if (logger.isInfoEnabled()) {
logger.info(logMsg.toString());
}
| 74
| 205
| 279
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-actuator-autoconfigure/src/main/java/com/alipay/sofa/boot/actuator/autoconfigure/health/ReadinessAutoConfiguration.java
|
ReadinessAutoConfiguration
|
healthCheckerProcessor
|
class ReadinessAutoConfiguration {
private static final Logger LOGGER = SofaBootLoggerFactory
.getLogger(ReadinessAutoConfiguration.class);
@Bean
@ConditionalOnMissingBean(value = ReadinessCheckListener.class)
public ReadinessCheckListener readinessCheckListener(HealthCheckerProcessor healthCheckerProcessor,
HealthIndicatorProcessor healthIndicatorProcessor,
ReadinessCheckCallbackProcessor afterReadinessCheckCallbackProcessor,
ExecutorService readinessHealthCheckExecutor,
HealthProperties healthCheckProperties) {
ReadinessCheckListener readinessCheckListener = new ReadinessCheckListener(
healthCheckerProcessor, healthIndicatorProcessor, afterReadinessCheckCallbackProcessor);
readinessCheckListener.setManualReadinessCallback(healthCheckProperties
.isManualReadinessCallback());
readinessCheckListener.setThrowExceptionWhenHealthCheckFailed(healthCheckProperties
.isInsulator());
readinessCheckListener.setSkipAll(healthCheckProperties.isSkipAll());
readinessCheckListener.setSkipHealthChecker(healthCheckProperties.isSkipHealthChecker());
readinessCheckListener
.setSkipHealthIndicator(healthCheckProperties.isSkipHealthIndicator());
readinessCheckListener.setHealthCheckExecutor(readinessHealthCheckExecutor);
return readinessCheckListener;
}
@Bean
@ConditionalOnMissingBean
public HealthCheckerProcessor healthCheckerProcessor(HealthProperties healthCheckProperties,
ExecutorService readinessHealthCheckExecutor) {<FILL_FUNCTION_BODY>}
@Bean
@ConditionalOnMissingBean
public HealthIndicatorProcessor healthIndicatorProcessor(HealthProperties healthCheckProperties,
ExecutorService readinessHealthCheckExecutor) {
HealthIndicatorProcessor healthIndicatorProcessor = new HealthIndicatorProcessor();
healthIndicatorProcessor.setHealthCheckExecutor(readinessHealthCheckExecutor);
healthIndicatorProcessor.initExcludedIndicators(healthCheckProperties
.getExcludedIndicators());
healthIndicatorProcessor.setParallelCheck(healthCheckProperties.isParallelCheck());
healthIndicatorProcessor.setParallelCheckTimeout(healthCheckProperties
.getParallelCheckTimeout());
healthIndicatorProcessor.setGlobalTimeout(healthCheckProperties
.getGlobalHealthIndicatorTimeout());
healthIndicatorProcessor.setHealthIndicatorConfig(healthCheckProperties
.getHealthIndicatorConfig());
return healthIndicatorProcessor;
}
@Bean
@ConditionalOnMissingBean
public ReadinessCheckCallbackProcessor afterReadinessCheckCallbackProcessor() {
return new ReadinessCheckCallbackProcessor();
}
@Bean(name = ReadinessCheckListener.READINESS_HEALTH_CHECK_EXECUTOR_BEAN_NAME)
@ConditionalOnMissingBean(name = ReadinessCheckListener.READINESS_HEALTH_CHECK_EXECUTOR_BEAN_NAME)
@Conditional(OnVirtualThreadStartupDisableCondition.class)
public ExecutorService readinessHealthCheckExecutor(HealthProperties properties) {
int threadPoolSize;
if (properties.isParallelCheck()) {
threadPoolSize = SofaBootConstants.CPU_CORE * 5;
} else {
threadPoolSize = 1;
}
LOGGER.info("Create health-check thread pool, corePoolSize: {}, maxPoolSize: {}.",
threadPoolSize, threadPoolSize);
return new SofaThreadPoolExecutor(threadPoolSize, threadPoolSize, 30, TimeUnit.SECONDS,
new SynchronousQueue<>(), new NamedThreadFactory("health-check"),
new ThreadPoolExecutor.CallerRunsPolicy(), "health-check",
SofaBootConstants.SOFA_BOOT_SPACE_NAME);
}
@Bean(name = ReadinessCheckListener.READINESS_HEALTH_CHECK_EXECUTOR_BEAN_NAME)
@ConditionalOnMissingBean(name = ReadinessCheckListener.READINESS_HEALTH_CHECK_EXECUTOR_BEAN_NAME)
@Conditional(OnVirtualThreadStartupAvailableCondition.class)
public ExecutorService readinessHealthCheckVirtualExecutor() {
LOGGER.info("Create health-check virtual executor service");
return SofaVirtualThreadFactory.ofExecutorService("health-check");
}
}
|
HealthCheckerProcessor healthCheckerProcessor = new HealthCheckerProcessor();
healthCheckerProcessor.setHealthCheckExecutor(readinessHealthCheckExecutor);
healthCheckerProcessor.setParallelCheck(healthCheckProperties.isParallelCheck());
healthCheckerProcessor.setParallelCheckTimeout(healthCheckProperties
.getParallelCheckTimeout());
healthCheckerProcessor.setGlobalTimeout(healthCheckProperties
.getGlobalHealthCheckerTimeout());
healthCheckerProcessor.setHealthCheckerConfigs(healthCheckProperties
.getHealthCheckerConfig());
return healthCheckerProcessor;
| 1,064
| 142
| 1,206
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-actuator/src/main/java/com/alipay/sofa/boot/actuator/beans/IsleBeansEndpoint.java
|
IsleBeansEndpoint
|
getModuleApplicationContexts
|
class IsleBeansEndpoint extends BeansEndpoint {
private final ApplicationRuntimeModel applicationRuntimeModel;
/**
* Creates a new {@code BeansEndpoint} that will describe the beans in the given
* {@code context} and all of its ancestors.
*
* @param context the application context
* @param applicationRuntimeModel the application runtime model
* @see ConfigurableApplicationContext#getParent()
*/
public IsleBeansEndpoint(ConfigurableApplicationContext context,
ApplicationRuntimeModel applicationRuntimeModel) {
super(context);
this.applicationRuntimeModel = applicationRuntimeModel;
}
@ReadOperation
@Override
public BeansEndpoint.BeansDescriptor beans() {
BeansEndpoint.BeansDescriptor beansDescriptor = super.beans();
Map<String, BeansEndpoint.ContextBeansDescriptor> moduleApplicationContexts = getModuleApplicationContexts(applicationRuntimeModel);
beansDescriptor.getContexts().putAll(moduleApplicationContexts);
return beansDescriptor;
}
private Map<String, BeansEndpoint.ContextBeansDescriptor> getModuleApplicationContexts(ApplicationRuntimeModel applicationRuntimeModel) {<FILL_FUNCTION_BODY>}
private BeansEndpoint.ContextBeansDescriptor describing(ConfigurableApplicationContext context,
String parentModuleName) {
Map<String, BeanDescriptor> beanDescriptorMap = callContextBeansDescribeBeans(context
.getBeanFactory());
return createContextBeans(beanDescriptorMap, parentModuleName);
}
// FIXME only can use reflect now
private Map<String, BeanDescriptor> callContextBeansDescribeBeans(ConfigurableListableBeanFactory beanFactory) {
try {
Class<?> clazz = BeansEndpoint.ContextBeansDescriptor.class;
Method method = clazz.getDeclaredMethod("describeBeans",
ConfigurableListableBeanFactory.class);
method.setAccessible(true);
Object result = method.invoke(null, beanFactory);
return (Map<String, BeanDescriptor>) result;
} catch (Throwable e) {
// ignore
return new HashMap<>();
}
}
// FIXME only can use reflect now
private BeansEndpoint.ContextBeansDescriptor createContextBeans(Map<String, BeanDescriptor> beans,
String parentId) {
try {
Class<?> clazz = BeansEndpoint.ContextBeansDescriptor.class;
Constructor<?> constructor = clazz.getDeclaredConstructor(Map.class, String.class);
constructor.setAccessible(true);
return (BeansEndpoint.ContextBeansDescriptor) constructor.newInstance(beans, parentId);
} catch (Throwable e) {
// ignore
return null;
}
}
}
|
Map<String, BeansEndpoint.ContextBeansDescriptor> contexts = new HashMap<>();
List<DeploymentDescriptor> installedModules = applicationRuntimeModel.getInstalled();
installedModules.forEach(descriptor -> {
ApplicationContext applicationContext = descriptor.getApplicationContext();
if (applicationContext instanceof ConfigurableApplicationContext) {
BeansEndpoint.ContextBeansDescriptor contextBeans = describing((ConfigurableApplicationContext) applicationContext,
descriptor.getSpringParent());
if (contextBeans != null) {
contexts.put(descriptor.getModuleName(), contextBeans);
}
}
});
return contexts;
| 684
| 160
| 844
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-actuator/src/main/java/com/alipay/sofa/boot/actuator/components/ComponentsEndpoint.java
|
ComponentsEndpoint
|
components
|
class ComponentsEndpoint {
private final SofaRuntimeContext sofaRuntimeContext;
/**
* Creates a new {@code SofaBootComponentsEndPoint} that will describe the components in the {@link SofaRuntimeContext}
*
* @param sofaRuntimeContext the sofa runtime context
*/
public ComponentsEndpoint(SofaRuntimeContext sofaRuntimeContext) {
this.sofaRuntimeContext = sofaRuntimeContext;
}
@ReadOperation
public ComponentsDescriptor components() {<FILL_FUNCTION_BODY>}
public static final class ComponentsDescriptor implements OperationResponseBody {
private final Map<String, Collection<ComponentDisplayInfo>> componentsInfoMap;
private ComponentsDescriptor(Map<String, Collection<ComponentDisplayInfo>> componentsInfoMap) {
this.componentsInfoMap = componentsInfoMap;
}
public Map<String, Collection<ComponentDisplayInfo>> getComponentsInfoMap() {
return this.componentsInfoMap;
}
}
public static final class ComponentDisplayInfo {
private final String name;
private final String applicationId;
private List<PropertyInfo> properties;
private ComponentDisplayInfo(String name, String applicationId,
List<PropertyInfo> properties) {
this.name = name;
this.applicationId = applicationId;
this.properties = properties;
}
public String getName() {
return name;
}
public String getApplicationId() {
return applicationId;
}
public List<PropertyInfo> getProperties() {
return properties;
}
}
public static final class PropertyInfo {
private String name;
private Object value;
public PropertyInfo(Property property) {
this.name = property.getName();
this.value = property.getValue();
}
public PropertyInfo(String name, Object value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public Object getValue() {
return value;
}
}
}
|
ComponentManager componentManager = sofaRuntimeContext.getComponentManager();
Map<String, Collection<ComponentDisplayInfo>> componentsInfoMap = new HashMap<>();
Collection<ComponentType> componentTypes = componentManager.getComponentTypes();
componentTypes.forEach(componentType -> {
Collection<ComponentInfo> componentInfos = componentManager.getComponentInfosByType(componentType);
Collection<ComponentDisplayInfo> componentDisplayInfos = componentInfos.stream()
.map(componentInfo -> {
String applicationId = componentInfo.getApplicationContext() == null ? "null"
: componentInfo.getApplicationContext().getId();
Map<String, Property> propertyMap = componentInfo.getProperties();
return new ComponentDisplayInfo(componentInfo.getName().getName(), applicationId,
propertyMap != null ? propertyMap.values().stream().map(PropertyInfo::new).collect(Collectors.toList())
: null);
})
.collect(Collectors.toList());
componentsInfoMap.put(componentType.getName(), componentDisplayInfos);
});
return new ComponentsDescriptor(componentsInfoMap);
| 528
| 269
| 797
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-actuator/src/main/java/com/alipay/sofa/boot/actuator/health/ComponentHealthChecker.java
|
ComponentHealthChecker
|
isHealthy
|
class ComponentHealthChecker implements HealthChecker {
public static final String COMPONENT_NAME = "components";
private final SofaRuntimeContext sofaRuntimeContext;
public ComponentHealthChecker(SofaRuntimeContext sofaRuntimeContext) {
this.sofaRuntimeContext = sofaRuntimeContext;
}
@Override
public Health isHealthy() {<FILL_FUNCTION_BODY>}
@Override
public String getComponentName() {
return COMPONENT_NAME;
}
@Override
public int getRetryCount() {
return 20;
}
@Override
public long getRetryTimeInterval() {
return 1000;
}
@Override
public boolean isStrictCheck() {
return true;
}
@Override
public int getTimeout() {
return 10 * 1000;
}
}
|
boolean allPassed = true;
Health.Builder builder = new Health.Builder();
for (ComponentInfo componentInfo : sofaRuntimeContext.getComponentManager().getComponents()) {
HealthResult healthy = componentInfo.isHealthy();
String healthReport = healthy.getHealthReport();
if (!healthy.isHealthy()) {
allPassed = false;
builder.withDetail(healthy.getHealthName(),
StringUtils.hasText(healthReport) ? healthReport : "failed");
}
}
if (allPassed) {
return builder.status(Status.UP).build();
} else {
return builder.status(Status.DOWN).build();
}
| 238
| 175
| 413
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-actuator/src/main/java/com/alipay/sofa/boot/actuator/health/HealthCheckComparatorSupport.java
|
HealthCheckComparatorSupport
|
sortMapAccordingToValue
|
class HealthCheckComparatorSupport {
public static Comparator<Object> getComparatorToUse(BeanFactory beanFactory) {
Comparator<Object> comparatorToUse = null;
if (beanFactory instanceof DefaultListableBeanFactory) {
comparatorToUse = ((DefaultListableBeanFactory) beanFactory).getDependencyComparator();
}
if (beanFactory != null) {
ObjectProvider<HealthCheckerComparatorProvider> objectProvider = beanFactory
.getBeanProvider(HealthCheckerComparatorProvider.class);
HealthCheckerComparatorProvider healthCheckerComparatorProvider = objectProvider
.getIfUnique();
if (healthCheckerComparatorProvider != null) {
comparatorToUse = healthCheckerComparatorProvider.getComparator();
}
}
if (comparatorToUse == null) {
comparatorToUse = AnnotationAwareOrderComparator.INSTANCE;
}
return comparatorToUse;
}
public static <T, U> LinkedHashMap<T, U> sortMapAccordingToValue(Map<T, U> origin, Comparator<Object> comparatorToUse) {<FILL_FUNCTION_BODY>}
}
|
List<Map.Entry<T, U>> entryList = new ArrayList<>(origin.entrySet());
entryList.sort((o1, o2) -> comparatorToUse.compare(o1.getValue(), o2.getValue()));
LinkedHashMap<T, U> result = new LinkedHashMap<>();
for (Map.Entry<T, U> entry : entryList) {
result.put(entry.getKey(), entry.getValue());
}
return result;
| 307
| 119
| 426
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-actuator/src/main/java/com/alipay/sofa/boot/actuator/health/ModuleHealthChecker.java
|
ModuleHealthChecker
|
isHealthy
|
class ModuleHealthChecker implements HealthChecker {
public static final String COMPONENT_NAME = "modules";
private final ApplicationRuntimeModel applicationRuntimeModel;
public ModuleHealthChecker(ApplicationRuntimeModel applicationRuntimeModel) {
this.applicationRuntimeModel = applicationRuntimeModel;
}
@Override
public Health isHealthy() {<FILL_FUNCTION_BODY>}
@Override
public String getComponentName() {
return COMPONENT_NAME;
}
@Override
public int getRetryCount() {
return 0;
}
@Override
public long getRetryTimeInterval() {
return 1000;
}
@Override
public boolean isStrictCheck() {
return true;
}
@Override
public int getTimeout() {
return 10 * 1000;
}
}
|
Health.Builder builder = new Health.Builder();
for (DeploymentDescriptor deploymentDescriptor : applicationRuntimeModel.getFailed()) {
builder.withDetail(deploymentDescriptor.getName(), "failed");
}
if (applicationRuntimeModel.getFailed().size() == 0) {
return builder.status(Status.UP).build();
} else {
return builder.status(Status.DOWN).build();
}
| 232
| 106
| 338
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-actuator/src/main/java/com/alipay/sofa/boot/actuator/health/ReadinessCheckCallbackProcessor.java
|
ReadinessCheckCallbackProcessor
|
readinessCheckCallback
|
class ReadinessCheckCallbackProcessor implements ApplicationContextAware {
private static final Logger logger = SofaBootLoggerFactory
.getLogger(ReadinessCheckCallbackProcessor.class);
private final ObjectMapper objectMapper = new ObjectMapper();
private final AtomicBoolean isInitiated = new AtomicBoolean(
false);
private final List<BaseStat> readinessCheckCallbackStartupStatList = new CopyOnWriteArrayList<>();
private ApplicationContext applicationContext;
private LinkedHashMap<String, ReadinessCheckCallback> readinessCheckCallbacks = null;
public void init() {
if (isInitiated.compareAndSet(false, true)) {
Assert.notNull(applicationContext, () -> "Application must not be null");
Map<String, ReadinessCheckCallback> beansOfType = applicationContext
.getBeansOfType(ReadinessCheckCallback.class);
readinessCheckCallbacks = HealthCheckComparatorSupport.sortMapAccordingToValue(beansOfType,
HealthCheckComparatorSupport.getComparatorToUse(applicationContext.getAutowireCapableBeanFactory()));
String applicationCallbackInfo = "Found " + readinessCheckCallbacks.size() + " ReadinessCheckCallback implementation: " + String.join(",", beansOfType.keySet());
logger.info(applicationCallbackInfo);
}
}
public boolean readinessCheckCallback(Map<String, Health> callbackDetails) {<FILL_FUNCTION_BODY>}
private boolean doHealthCheckCallback(String beanId,
ReadinessCheckCallback readinessCheckCallback,
Map<String, Health> callbackDetails) {
Assert.notNull(callbackDetails, () -> "HealthCallbackDetails must not be null");
boolean result = false;
Health health = null;
logger.info("ReadinessCheckCallback [{}] check start.", beanId);
BaseStat baseStat = new BaseStat();
baseStat.setName(beanId);
baseStat.putAttribute("type", "readinessCheckCallbacn");
baseStat.setStartTime(System.currentTimeMillis());
try {
health = readinessCheckCallback.onHealthy(applicationContext);
result = health.getStatus().equals(Status.UP);
if (!result) {
logger.error(
ErrorCode.convert("01-24001", beanId,
objectMapper.writeValueAsString(health.getDetails())));
}
} catch (Throwable t) {
if (health == null) {
health = new Health.Builder().down(new RuntimeException(t)).build();
}
logger.error(ErrorCode.convert("01-24002", beanId), t);
} finally {
callbackDetails.put(beanId, health);
}
baseStat.setEndTime(System.currentTimeMillis());
readinessCheckCallbackStartupStatList.add(baseStat);
return result;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public List<BaseStat> getReadinessCheckCallbackStartupStatList() {
return readinessCheckCallbackStartupStatList;
}
}
|
logger.info("Begin ReadinessCheckCallback readiness check");
Assert.notNull(readinessCheckCallbacks, "ReadinessCheckCallbacks must not be null.");
boolean allResult = true;
String failedBeanId = "";
for (Map.Entry<String, ReadinessCheckCallback> entry : readinessCheckCallbacks.entrySet()) {
String beanId = entry.getKey();
if (allResult) {
if (!doHealthCheckCallback(beanId, entry.getValue(), callbackDetails)) {
failedBeanId = beanId;
allResult = false;
}
} else {
logger.warn(beanId + " is skipped due to the failure of " + failedBeanId);
callbackDetails.put(
beanId,
Health.down()
.withDetail("invoking", "skipped due to the failure of " + failedBeanId)
.build());
}
}
if (allResult) {
logger.info("ReadinessCheckCallback readiness check result: success.");
} else {
logger.error(ErrorCode.convert("01-24000"));
}
return allResult;
| 807
| 285
| 1,092
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-actuator/src/main/java/com/alipay/sofa/boot/actuator/health/ReadinessEndpoint.java
|
ReadinessEndpoint
|
health
|
class ReadinessEndpoint {
private final ReadinessCheckListener readinessCheckListener;
public ReadinessEndpoint(ReadinessCheckListener readinessCheckListener) {
this.readinessCheckListener = readinessCheckListener;
}
@ReadOperation
public Health health(@Nullable String showDetail) {<FILL_FUNCTION_BODY>}
}
|
Health health = readinessCheckListener.aggregateReadinessHealth();
if (showDetail == null || Boolean.parseBoolean(showDetail)) {
return health;
}
return new Health.Builder(health.getStatus()).build();
| 87
| 61
| 148
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-actuator/src/main/java/com/alipay/sofa/boot/actuator/health/ReadinessHttpCodeStatusMapper.java
|
ReadinessHttpCodeStatusMapper
|
getUniformMappings
|
class ReadinessHttpCodeStatusMapper implements HttpCodeStatusMapper {
private static final Map<String, Integer> DEFAULT_MAPPINGS;
static {
Map<String, Integer> defaultMappings = new HashMap<>(8);
defaultMappings.put(Status.DOWN.getCode(), WebEndpointResponse.STATUS_SERVICE_UNAVAILABLE);
defaultMappings.put(Status.OUT_OF_SERVICE.getCode(),
WebEndpointResponse.STATUS_INTERNAL_SERVER_ERROR);
defaultMappings.put(Status.UNKNOWN.getCode(),
WebEndpointResponse.STATUS_INTERNAL_SERVER_ERROR);
DEFAULT_MAPPINGS = getUniformMappings(defaultMappings);
}
private final SimpleHttpCodeStatusMapper statusMapper;
public ReadinessHttpCodeStatusMapper() {
this(null);
}
public ReadinessHttpCodeStatusMapper(Map<String, Integer> mappings) {
Map<String, Integer> mapping = new HashMap<>(8);
// add custom status mapper
mapping.putAll(DEFAULT_MAPPINGS);
if (mappings != null) {
mapping.putAll(getUniformMappings(mappings));
}
statusMapper = new SimpleHttpCodeStatusMapper(mapping);
}
@Override
public int getStatusCode(Status status) {
return statusMapper.getStatusCode(status);
}
private static Map<String, Integer> getUniformMappings(Map<String, Integer> mappings) {<FILL_FUNCTION_BODY>}
private static String getUniformCode(String code) {
if (code == null) {
return null;
}
StringBuilder builder = new StringBuilder();
for (int i = 0; i < code.length(); i++) {
char ch = code.charAt(i);
if (Character.isAlphabetic(ch) || Character.isDigit(ch)) {
builder.append(Character.toLowerCase(ch));
}
}
return builder.toString();
}
}
|
Map<String, Integer> result = new LinkedHashMap<>();
for (Map.Entry<String, Integer> entry : mappings.entrySet()) {
String code = getUniformCode(entry.getKey());
if (code != null) {
result.putIfAbsent(code, entry.getValue());
}
}
return Collections.unmodifiableMap(result);
| 520
| 99
| 619
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-actuator/src/main/java/com/alipay/sofa/boot/actuator/isle/IsleEndpoint.java
|
IsleEndpoint
|
createBaseModuleInfo
|
class IsleEndpoint {
private final ApplicationRuntimeModel applicationRuntimeModel;
public IsleEndpoint(ApplicationRuntimeModel applicationRuntimeModel) {
this.applicationRuntimeModel = applicationRuntimeModel;
}
@ReadOperation
public IsleDescriptor modules() {
// already installed modules
List<ModuleDisplayInfo> installedModuleList = convertModuleDisplayInfoList(applicationRuntimeModel
.getInstalled());
List<ModuleDisplayInfo> failedModuleList = convertModuleDisplayInfoList(applicationRuntimeModel
.getFailed());
List<ModuleDisplayInfo> inactiveModuleList = convertModuleDisplayInfoList(applicationRuntimeModel
.getAllInactiveDeployments());
return new IsleDescriptor(installedModuleList, failedModuleList, inactiveModuleList);
}
private List<ModuleDisplayInfo> convertModuleDisplayInfoList(List<DeploymentDescriptor> deploymentDescriptors) {
return deploymentDescriptors.stream().map(this::createBaseModuleInfo).collect(Collectors.toList());
}
private ModuleDisplayInfo createBaseModuleInfo(DeploymentDescriptor dd) {<FILL_FUNCTION_BODY>}
public static final class IsleDescriptor implements OperationResponseBody {
/** 刷新成功的模块 **/
private final List<ModuleDisplayInfo> installedModuleList;
/** 创建失败的模块 **/
private final List<ModuleDisplayInfo> failedModuleList;
/** 未激活的模块 **/
private final List<ModuleDisplayInfo> inactiveModuleList;
public IsleDescriptor(List<ModuleDisplayInfo> installedModuleList,
List<ModuleDisplayInfo> failedModuleList,
List<ModuleDisplayInfo> inactiveModuleList) {
this.installedModuleList = installedModuleList;
this.failedModuleList = failedModuleList;
this.inactiveModuleList = inactiveModuleList;
}
public List<ModuleDisplayInfo> getInstalledModuleList() {
return installedModuleList;
}
public List<ModuleDisplayInfo> getFailedModuleList() {
return failedModuleList;
}
public List<ModuleDisplayInfo> getInactiveModuleList() {
return inactiveModuleList;
}
}
public static final class ModuleDisplayInfo {
private String name;
private String springParent;
private List<String> requireModules;
private String resourceName;
private long startupTime;
private long elapsedTime;
private List<String> installSpringXmls;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSpringParent() {
return springParent;
}
public void setSpringParent(String springParent) {
this.springParent = springParent;
}
public List<String> getRequireModules() {
return requireModules;
}
public void setRequireModules(List<String> requireModules) {
this.requireModules = requireModules;
}
public String getResourceName() {
return resourceName;
}
public void setResourceName(String resourceName) {
this.resourceName = resourceName;
}
public List<String> getInstallSpringXmls() {
return installSpringXmls;
}
public void setInstallSpringXmls(List<String> installSpringXmls) {
this.installSpringXmls = installSpringXmls;
}
public long getStartupTime() {
return startupTime;
}
public void setStartupTime(long startupTime) {
this.startupTime = startupTime;
}
public long getElapsedTime() {
return elapsedTime;
}
public void setElapsedTime(long elapsedTime) {
this.elapsedTime = elapsedTime;
}
}
}
|
ModuleDisplayInfo moduleDisplayInfo = new ModuleDisplayInfo();
moduleDisplayInfo.setName(dd.getModuleName());
moduleDisplayInfo.setResourceName(dd.getName());
moduleDisplayInfo.setSpringParent(dd.getSpringParent());
moduleDisplayInfo.setRequireModules(dd.getRequiredModules());
ApplicationContext applicationContext = dd.getApplicationContext();
if (applicationContext != null) {
moduleDisplayInfo.setInstallSpringXmls(dd.getInstalledSpringXml());
moduleDisplayInfo.setElapsedTime(dd.getElapsedTime());
moduleDisplayInfo.setStartupTime(dd.getStartTime());
}
return moduleDisplayInfo;
| 989
| 175
| 1,164
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-actuator/src/main/java/com/alipay/sofa/boot/actuator/rpc/RpcAfterHealthCheckCallback.java
|
RpcAfterHealthCheckCallback
|
onHealthy
|
class RpcAfterHealthCheckCallback implements ReadinessCheckCallback, PriorityOrdered {
private final RpcStartApplicationListener rpcStartApplicationListener;
public RpcAfterHealthCheckCallback(RpcStartApplicationListener rpcStartApplicationListener) {
this.rpcStartApplicationListener = rpcStartApplicationListener;
}
@Override
public Health onHealthy(ApplicationContext applicationContext) {<FILL_FUNCTION_BODY>}
@Override
public int getOrder() {
return PriorityOrdered.LOWEST_PRECEDENCE;
}
}
|
Health.Builder builder = new Health.Builder();
rpcStartApplicationListener.publishRpcStartEvent();
if (rpcStartApplicationListener.isSuccess()) {
return builder.status(Status.UP).build();
} else {
return builder.status(Status.DOWN).withDetail("Reason", "Rpc service start fail")
.build();
}
| 143
| 96
| 239
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-actuator/src/main/java/com/alipay/sofa/boot/actuator/threadpool/ThreadPoolEndpoint.java
|
ThreadPoolEndpoint
|
threadPools
|
class ThreadPoolEndpoint {
private final ThreadPoolGovernor threadPoolGovernor;
public ThreadPoolEndpoint(ThreadPoolGovernor threadPoolGovernor) {
this.threadPoolGovernor = threadPoolGovernor;
}
@ReadOperation
public ThreadPoolsDescriptor threadPools () {<FILL_FUNCTION_BODY>}
private ThreadPoolInfo convertToThreadPoolInfo(ThreadPoolMonitorWrapper wrapper) {
ThreadPoolConfig threadPoolConfig = wrapper.getThreadPoolConfig();
String threadPoolName = threadPoolConfig.getThreadPoolName();
String spaceName = threadPoolConfig.getSpaceName();
long period = threadPoolConfig.getPeriod();
long taskTimeout = threadPoolConfig.getTaskTimeoutMilli();
ThreadPoolExecutor threadPoolExecutor = wrapper.getThreadPoolExecutor();
String threadPoolClassName = threadPoolExecutor.getClass().getName();
int coreSize = threadPoolExecutor.getCorePoolSize();
int maxSize = threadPoolExecutor.getMaximumPoolSize();
int queueSize = threadPoolExecutor.getQueue().size();
int queueRemainingCapacity = threadPoolExecutor.getQueue().remainingCapacity();
String queueClassName = threadPoolExecutor.getQueue().getClass().getName();
return new ThreadPoolInfo(threadPoolName, spaceName, threadPoolClassName, coreSize, maxSize, queueClassName, queueSize, queueRemainingCapacity, period, taskTimeout);
}
public record ThreadPoolsDescriptor(List<ThreadPoolInfo> threadPoolInfoList) implements OperationResponseBody {}
public record ThreadPoolInfo(String threadPoolName,
String spaceName,
String threadPoolClassName,
int coreSize,
int maxSize,
String queueClassName,
int queueSize,
int queueRemainingCapacity,
long monitorPeriod,
long taskTimeout) {}
}
|
Collection<ThreadPoolMonitorWrapper> threadPoolWrappers = threadPoolGovernor.getAllThreadPoolWrappers();
List<ThreadPoolInfo> threadPoolInfoList = threadPoolWrappers.stream().map(this::convertToThreadPoolInfo).toList();
return new ThreadPoolsDescriptor(threadPoolInfoList);
| 451
| 80
| 531
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-autoconfigure/src/main/java/com/alipay/sofa/boot/autoconfigure/ark/SofaArkAutoConfiguration.java
|
SofaArkAutoConfiguration
|
sofaRuntimeContainer
|
class SofaArkAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public SofaRuntimeContainer sofaRuntimeContainer(SofaRuntimeManager sofaRuntimeManager,
SofaArkProperties sofaArkProperties) {<FILL_FUNCTION_BODY>}
@Bean
@ConditionalOnMissingBean
public DynamicServiceProxyManager arkDynamicServiceProxyManager() {
return new ArkDynamicServiceProxyManager();
}
}
|
SofaRuntimeContainer sofaRuntimeContainer = new SofaRuntimeContainer(sofaRuntimeManager);
sofaRuntimeContainer.setJvmServiceCache(sofaArkProperties.isJvmServiceCache());
sofaRuntimeContainer.setJvmInvokeSerialize(sofaArkProperties.isJvmInvokeSerialize());
return sofaRuntimeContainer;
| 115
| 85
| 200
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-autoconfigure/src/main/java/com/alipay/sofa/boot/autoconfigure/condition/OnMasterBizCondition.java
|
OnMasterBizCondition
|
getMatchOutcome
|
class OnMasterBizCondition extends SpringBootCondition {
private static Object masterBiz;
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {<FILL_FUNCTION_BODY>}
private List<AnnotationAttributes> annotationAttributesFromMultiValueMap(
MultiValueMap<String, Object> multiValueMap) {
List<Map<String, Object>> maps = new ArrayList<>();
multiValueMap.forEach((key, value) -> {
for (int i = 0; i < value.size(); i++) {
Map<String, Object> map;
if (i < maps.size()) {
map = maps.get(i);
}
else {
map = new HashMap<>();
maps.add(map);
}
map.put(key, value.get(i));
}
});
List<AnnotationAttributes> annotationAttributes = new ArrayList<>(maps.size());
for (Map<String, Object> map : maps) {
annotationAttributes.add(AnnotationAttributes.fromMap(map));
}
return annotationAttributes;
}
private static class Spec {
private final String extensionCondition;
Spec(AnnotationAttributes annotationAttributes) {
this.extensionCondition = annotationAttributes.getString("extensionCondition");
}
public String getExtensionCondition() {
return extensionCondition;
}
}
}
|
// 非 Ark 环境
if (!SofaBootEnvUtils.isArkEnv()) {
return new ConditionOutcome(true, "SOFAArk has not started.");
}
if (masterBiz == null) {
String masterBizName = ArkConfigs.getStringValue(Constants.MASTER_BIZ);
List<Biz> biz = ArkClient.getBizManagerService().getBiz(masterBizName);
Assert.isTrue(biz.size() == 1, "master biz should have and only have one.");
masterBiz = biz.get(0);
}
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
// is master biz, return directly
if (contextClassLoader.equals(((Biz) masterBiz).getBizClassLoader())) {
return new ConditionOutcome(true,
"Current context classloader equals master biz classloader.");
}
// if not master biz, should be determine by extensionCondition
List<AnnotationAttributes> allAnnotationAttributes = annotationAttributesFromMultiValueMap(metadata
.getAllAnnotationAttributes(ConditionalOnMasterBiz.class.getName()));
for (AnnotationAttributes annotationAttributes : allAnnotationAttributes) {
Spec spec = new Spec(annotationAttributes);
String extensionCondition = spec.getExtensionCondition();
String property = context.getEnvironment().getProperty(extensionCondition);
if ("true".equalsIgnoreCase(property)) {
return new ConditionOutcome(true,
"Current context classloader not equals master biz classloader, but allow by extension condition.");
}
}
return new ConditionOutcome(false,
"Current context classloader not equals master biz classloader.");
| 350
| 419
| 769
|
<methods>public void <init>() ,public abstract org.springframework.boot.autoconfigure.condition.ConditionOutcome getMatchOutcome(org.springframework.context.annotation.ConditionContext, org.springframework.core.type.AnnotatedTypeMetadata) ,public final boolean matches(org.springframework.context.annotation.ConditionContext, org.springframework.core.type.AnnotatedTypeMetadata) <variables>private final org.apache.commons.logging.Log logger
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-autoconfigure/src/main/java/com/alipay/sofa/boot/autoconfigure/condition/OnSwitchCondition.java
|
OnSwitchCondition
|
getClassOrMethodName
|
class OnSwitchCondition extends SpringBootCondition {
private static final String CONFIG_KEY_PREFIX = "sofa.boot.switch.bean";
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
return getMatchOutcome(context.getEnvironment(), metadata);
}
private ConditionOutcome getMatchOutcome(Environment environment, AnnotatedTypeMetadata metadata) {
ConditionMessage.Builder message = ConditionMessage.forCondition(ConditionalOnSwitch.class);
String key = getKey(metadata);
Boolean userDefinedEnabled = environment.getProperty(key, Boolean.class);
if (userDefinedEnabled != null) {
return new ConditionOutcome(userDefinedEnabled, message.because("found property " + key
+ " with value "
+ userDefinedEnabled));
}
MergedAnnotation<ConditionalOnSwitch> conditionAnnotation = metadata.getAnnotations().get(
ConditionalOnSwitch.class);
Boolean matchIfMissing = conditionAnnotation.getBoolean("matchIfMissing");
return new ConditionOutcome(matchIfMissing, message.because("matchIfMissing " + key
+ " with value "
+ matchIfMissing));
}
private String getKey(AnnotatedTypeMetadata metadata) {
MergedAnnotation<ConditionalOnSwitch> conditionAnnotation = metadata.getAnnotations().get(
ConditionalOnSwitch.class);
String key = conditionAnnotation.getString("value");
if (StringUtils.hasText(key)) {
return CONFIG_KEY_PREFIX.concat(".").concat(key).concat(".enabled");
} else {
return CONFIG_KEY_PREFIX.concat(".").concat(getClassOrMethodName(metadata))
.concat(".enabled");
}
}
private String getClassOrMethodName(AnnotatedTypeMetadata metadata) {<FILL_FUNCTION_BODY>}
}
|
if (metadata instanceof ClassMetadata classMetadata) {
return classMetadata.getClassName();
}
MethodMetadata methodMetadata = (MethodMetadata) metadata;
return methodMetadata.getMethodName();
| 472
| 51
| 523
|
<methods>public void <init>() ,public abstract org.springframework.boot.autoconfigure.condition.ConditionOutcome getMatchOutcome(org.springframework.context.annotation.ConditionContext, org.springframework.core.type.AnnotatedTypeMetadata) ,public final boolean matches(org.springframework.context.annotation.ConditionContext, org.springframework.core.type.AnnotatedTypeMetadata) <variables>private final org.apache.commons.logging.Log logger
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-autoconfigure/src/main/java/com/alipay/sofa/boot/autoconfigure/condition/OnTestCondition.java
|
OnTestCondition
|
getMatchOutcome
|
class OnTestCondition extends SpringBootCondition {
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {<FILL_FUNCTION_BODY>}
}
|
ConditionMessage matchMessage = ConditionMessage.empty();
if (metadata.isAnnotated(ConditionalOnNotTest.class.getName())) {
if (SofaBootEnvUtils.isSpringTestEnv()) {
return ConditionOutcome.noMatch(ConditionMessage.forCondition(
ConditionalOnNotTest.class).notAvailable("spring test environment"));
}
matchMessage = matchMessage.andCondition(ConditionalOnNotTest.class).available(
"none spring test environment");
}
return ConditionOutcome.match(matchMessage);
| 52
| 135
| 187
|
<methods>public void <init>() ,public abstract org.springframework.boot.autoconfigure.condition.ConditionOutcome getMatchOutcome(org.springframework.context.annotation.ConditionContext, org.springframework.core.type.AnnotatedTypeMetadata) ,public final boolean matches(org.springframework.context.annotation.ConditionContext, org.springframework.core.type.AnnotatedTypeMetadata) <variables>private final org.apache.commons.logging.Log logger
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-autoconfigure/src/main/java/com/alipay/sofa/boot/autoconfigure/detect/LegacyAutoConfigurationDetectListener.java
|
LegacyAutoConfigurationDetectListener
|
onAutoConfigurationImportEvent
|
class LegacyAutoConfigurationDetectListener implements AutoConfigurationImportListener,
BeanClassLoaderAware {
private static final Logger LOGGER = SofaBootLoggerFactory
.getLogger(LegacyAutoConfigurationDetectListener.class);
private ClassLoader beanClassLoader;
@Override
public void onAutoConfigurationImportEvent(AutoConfigurationImportEvent event) {<FILL_FUNCTION_BODY>}
private StringBuilder builderWarnLog(Set<String> legacyConfigurations) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("These configurations defined in spring.factories file will be ignored:");
stringBuilder.append("\n");
legacyConfigurations.forEach(legacyConfiguration -> {
stringBuilder.append("--- ");
stringBuilder.append(legacyConfiguration);
stringBuilder.append("\n");
});
return stringBuilder;
}
@Override
public void setBeanClassLoader(ClassLoader classLoader) {
this.beanClassLoader = classLoader;
}
}
|
// configurations form *.import file
Set<String> importConfigurations = new HashSet<>();
importConfigurations.addAll(event.getCandidateConfigurations());
importConfigurations.addAll(event.getExclusions());
// configurations from spring.factories file
List<String> configurations = new ArrayList<>(
SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class, beanClassLoader));
// configurations which in spring.factories but not in *.import will be ignored.
Set<String> legacyConfigurations = new HashSet<>();
configurations.forEach(className -> {
if (!importConfigurations.contains(className)) {
legacyConfigurations.add(className);
}
});
if (!legacyConfigurations.isEmpty()) {
LOGGER.warn(builderWarnLog(legacyConfigurations).toString());
}
| 258
| 223
| 481
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-autoconfigure/src/main/java/com/alipay/sofa/boot/autoconfigure/isle/SofaModuleAutoConfiguration.java
|
SofaModuleAutoConfiguration
|
modelCreatingStage
|
class SofaModuleAutoConfiguration {
private static final Logger LOGGER = SofaBootLoggerFactory
.getLogger(SofaModuleAutoConfiguration.class);
@Bean
@ConditionalOnMissingBean
public PipelineContext pipelineContext(List<PipelineStage> stageList) {
PipelineContext pipelineContext = new DefaultPipelineContext();
stageList.forEach(pipelineContext::appendStage);
return pipelineContext;
}
@Bean
@ConditionalOnMissingBean
public SofaModuleContextLifecycle sofaModuleContextLifecycle(PipelineContext pipelineContext) {
return new SofaModuleContextLifecycle(pipelineContext);
}
@Bean({ ApplicationRuntimeModel.APPLICATION_RUNTIME_MODEL_NAME,
ApplicationRuntimeModel.APPLICATION })
@ConditionalOnMissingBean
public ApplicationRuntimeModel applicationRuntimeModel(ModuleDeploymentValidator moduleDeploymentValidator,
SofaModuleProfileChecker sofaModuleProfileChecker) {
ApplicationRuntimeModel applicationRuntimeModel = new ApplicationRuntimeModel();
applicationRuntimeModel.setModuleDeploymentValidator(moduleDeploymentValidator);
applicationRuntimeModel.setSofaModuleProfileChecker(sofaModuleProfileChecker);
return applicationRuntimeModel;
}
@Bean
@ConditionalOnMissingBean
public ModelCreatingStage modelCreatingStage(
SofaModuleProperties sofaModuleProperties,
ApplicationRuntimeModel applicationRuntimeModel) {<FILL_FUNCTION_BODY>}
@Bean
@ConditionalOnMissingBean
public SpringContextInstallStage springContextInstallStage(SofaModuleProperties sofaModuleProperties,
SpringContextLoader springContextLoader,
ApplicationRuntimeModel applicationRuntimeModel) {
SpringContextInstallStage springContextInstallStage = new SpringContextInstallStage();
springContextInstallStage.setApplicationRuntimeModel(applicationRuntimeModel);
springContextInstallStage.setSpringContextLoader(springContextLoader);
springContextInstallStage.setModuleStartUpParallel(sofaModuleProperties
.isModuleStartUpParallel());
springContextInstallStage.setIgnoreModuleInstallFailure(sofaModuleProperties
.isIgnoreModuleInstallFailure());
return springContextInstallStage;
}
@Bean
@ConditionalOnMissingBean
public ModuleLogOutputStage moduleLogOutputStage(ApplicationRuntimeModel applicationRuntimeModel) {
ModuleLogOutputStage moduleLogOutputStage = new ModuleLogOutputStage();
moduleLogOutputStage.setApplicationRuntimeModel(applicationRuntimeModel);
return moduleLogOutputStage;
}
@Bean
@ConditionalOnMissingBean
public SpringContextLoader sofaDynamicSpringContextLoader(SofaModuleProperties sofaModuleProperties,
ApplicationContext applicationContext,
ObjectProvider<ContextRefreshInterceptor> contextRefreshInterceptors,
SofaPostProcessorShareManager sofaPostProcessorShareManager) {
DynamicSpringContextLoader dynamicSpringContextLoader = new DynamicSpringContextLoader(
applicationContext);
dynamicSpringContextLoader.setActiveProfiles(sofaModuleProperties.getActiveProfiles());
dynamicSpringContextLoader.setAllowBeanOverriding(sofaModuleProperties
.isAllowBeanDefinitionOverriding());
dynamicSpringContextLoader.setPublishEventToParent(sofaModuleProperties
.isPublishEventToParent());
dynamicSpringContextLoader.setContextRefreshInterceptors(new ArrayList<>(
contextRefreshInterceptors.orderedStream().toList()));
dynamicSpringContextLoader.setSofaPostProcessorShareManager(sofaPostProcessorShareManager);
return dynamicSpringContextLoader;
}
@Bean(SpringContextInstallStage.SOFA_MODULE_REFRESH_EXECUTOR_BEAN_NAME)
@ConditionalOnMissingBean(name = SpringContextInstallStage.SOFA_MODULE_REFRESH_EXECUTOR_BEAN_NAME)
@ConditionalOnProperty(value = "sofa.boot.isle.moduleStartUpParallel", havingValue = "true", matchIfMissing = true)
@Conditional(OnVirtualThreadStartupDisableCondition.class)
public Supplier<ExecutorService> sofaModuleRefreshExecutor(SofaModuleProperties sofaModuleProperties) {
int coreSize = (int) (SofaBootConstants.CPU_CORE * sofaModuleProperties.getParallelRefreshPoolSizeFactor());
long taskTimeout = sofaModuleProperties.getParallelRefreshTimeout();
long checkPeriod = sofaModuleProperties.getParallelRefreshCheckPeriod();
LOGGER.info("Create SOFA module refresh thread pool, corePoolSize: {}, maxPoolSize: {}," +
" taskTimeout:{}, checkPeriod:{}",
coreSize, coreSize, taskTimeout, checkPeriod);
return () -> new SofaThreadPoolExecutor(coreSize, coreSize, 60,
TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(1000),
new NamedThreadFactory("sofa-module-refresh"), new ThreadPoolExecutor.CallerRunsPolicy(),
"sofa-module-refresh", SofaBootConstants.SOFA_BOOT_SPACE_NAME, taskTimeout, checkPeriod,
TimeUnit.SECONDS);
}
@Bean(SpringContextInstallStage.SOFA_MODULE_REFRESH_EXECUTOR_BEAN_NAME)
@ConditionalOnMissingBean(name = SpringContextInstallStage.SOFA_MODULE_REFRESH_EXECUTOR_BEAN_NAME)
@ConditionalOnProperty(value = "sofa.boot.isle.moduleStartUpParallel", havingValue = "true", matchIfMissing = true)
@Conditional(OnVirtualThreadStartupAvailableCondition.class)
public Supplier<ExecutorService> sofaModuleRefreshVirtualExecutor() {
return () -> {
LOGGER.info("Create SOFA module refresh virtual executor service");
return SofaVirtualThreadFactory.ofExecutorService("sofa-module-refresh");
};
}
@Bean
@ConditionalOnMissingBean
public SofaModuleProfileChecker sofaModuleProfileChecker(SofaModuleProperties sofaModuleProperties) {
DefaultSofaModuleProfileChecker defaultSofaModuleProfileChecker = new DefaultSofaModuleProfileChecker();
defaultSofaModuleProfileChecker.setUserCustomProfiles(sofaModuleProperties
.getActiveProfiles());
return defaultSofaModuleProfileChecker;
}
@Bean
@ConditionalOnMissingBean
public ModuleDeploymentValidator sofaModuleDeploymentValidator() {
return new DefaultModuleDeploymentValidator();
}
@Bean
@ConditionalOnMissingBean
public SofaPostProcessorShareManager sofaModulePostProcessorShareManager(SofaModuleProperties sofaModuleProperties,
ObjectProvider<SofaPostProcessorShareFilter> sofaPostProcessorShareFilters) {
SofaPostProcessorShareManager sofaPostProcessorShareManager = new SofaPostProcessorShareManager();
sofaPostProcessorShareManager.setShareParentContextPostProcessors(sofaModuleProperties
.isShareParentPostProcessor());
sofaPostProcessorShareManager
.setSofaPostProcessorShareFilters(sofaPostProcessorShareFilters.orderedStream()
.toList());
return sofaPostProcessorShareManager;
}
}
|
ModelCreatingStage modelCreatingStage = new ModelCreatingStage();
sofaModuleProperties.getIgnoreModules().forEach(modelCreatingStage::addIgnoreModule);
sofaModuleProperties.getIgnoreCalculateRequireModules().forEach(modelCreatingStage::addIgnoredCalculateRequireModule);
modelCreatingStage.setAllowModuleOverriding(sofaModuleProperties.isAllowModuleOverriding());
modelCreatingStage.setApplicationRuntimeModel(applicationRuntimeModel);
return modelCreatingStage;
| 1,798
| 129
| 1,927
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-autoconfigure/src/main/java/com/alipay/sofa/boot/autoconfigure/rpc/RegistryConfigurations.java
|
RegistryConfigurations
|
registryConfigurationClass
|
class RegistryConfigurations {
public static String[] registryConfigurationClass() {<FILL_FUNCTION_BODY>}
}
|
return new String[] { LocalRegistryConfiguration.class.getName(),
ZookeeperRegistryConfiguration.class.getName(),
NacosRegistryConfiguration.class.getName(),
MulticastRegistryConfiguration.class.getName(),
MeshRegistryConfiguration.class.getName(),
ConsulRegistryConfiguration.class.getName(),
SofaRegistryConfiguration.class.getName(),
PolarisRegistryConfiguration.class.getName(),
KubernetesRegistryConfiguration.class.getName() };
| 34
| 113
| 147
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-autoconfigure/src/main/java/com/alipay/sofa/boot/autoconfigure/rpc/RestFilterConfiguration.java
|
RestFilterConfiguration
|
clientRequestFilters
|
class RestFilterConfiguration {
@Bean
@ConditionalOnMissingBean
public ContainerRequestFilterContainer containerRequestFilters(List<ContainerRequestFilter> containerRequestFilters) {
for (ContainerRequestFilter filter : containerRequestFilters) {
JAXRSProviderManager.registerCustomProviderInstance(filter);
}
return new ContainerRequestFilterContainer(containerRequestFilters);
}
@Bean
@ConditionalOnMissingBean
public ContainerResponseFilterContainer containerResponseFilters(List<ContainerResponseFilter> containerResponseFilters) {
for (ContainerResponseFilter filter : containerResponseFilters) {
JAXRSProviderManager.registerCustomProviderInstance(filter);
}
return new ContainerResponseFilterContainer(containerResponseFilters);
}
@Bean
@ConditionalOnMissingBean
public ClientRequestFilterContainer clientRequestFilters(List<ClientRequestFilter> clientRequestFilters) {<FILL_FUNCTION_BODY>}
@Bean
@ConditionalOnMissingBean
public ClientResponseFilterContainer clientResponseFilters(List<ClientResponseFilter> clientResponseFilters) {
for (ClientResponseFilter filter : clientResponseFilters) {
JAXRSProviderManager.registerCustomProviderInstance(filter);
}
return new ClientResponseFilterContainer(clientResponseFilters);
}
static class ContainerResponseFilterContainer {
private List<ContainerResponseFilter> containerResponseFilters;
public ContainerResponseFilterContainer(List<ContainerResponseFilter> containerResponseFilters) {
this.containerResponseFilters = containerResponseFilters;
}
}
static class ContainerRequestFilterContainer {
private List<ContainerRequestFilter> containerRequestFilters;
public ContainerRequestFilterContainer(List<ContainerRequestFilter> containerRequestFilters) {
this.containerRequestFilters = containerRequestFilters;
}
}
static class ClientRequestFilterContainer {
private List<ClientRequestFilter> clientRequestFilters;
public ClientRequestFilterContainer(List<ClientRequestFilter> clientRequestFilters) {
this.clientRequestFilters = clientRequestFilters;
}
}
static class ClientResponseFilterContainer {
private List<ClientResponseFilter> clientResponseFilters;
public ClientResponseFilterContainer(List<ClientResponseFilter> clientResponseFilters) {
this.clientResponseFilters = clientResponseFilters;
}
}
}
|
for (ClientRequestFilter filter : clientRequestFilters) {
JAXRSProviderManager.registerCustomProviderInstance(filter);
}
return new ClientRequestFilterContainer(clientRequestFilters);
| 589
| 50
| 639
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-autoconfigure/src/main/java/com/alipay/sofa/boot/autoconfigure/runtime/SofaRuntimeAutoConfiguration.java
|
SofaRuntimeAutoConfiguration
|
sofaRuntimeManager
|
class SofaRuntimeAutoConfiguration {
private static final Logger LOGGER = SofaBootLoggerFactory
.getLogger(SofaRuntimeAutoConfiguration.class);
@Bean
@ConditionalOnMissingBean
public static SofaRuntimeManager sofaRuntimeManager(Environment environment,
BindingConverterFactory bindingConverterFactory,
BindingAdapterFactory bindingAdapterFactory,
ObjectProvider<DynamicServiceProxyManager> dynamicServiceProxyManager) {<FILL_FUNCTION_BODY>}
@Bean
@ConditionalOnMissingBean
public static SofaRuntimeContext sofaRuntimeContext(SofaRuntimeManager sofaRuntimeManager) {
return sofaRuntimeManager.getSofaRuntimeContext();
}
@Bean
@ConditionalOnMissingBean
public static BindingConverterFactory bindingConverterFactory() {
BindingConverterFactory bindingConverterFactory = new BindingConverterFactoryImpl();
bindingConverterFactory.addBindingConverters(new HashSet<>(SpringFactoriesLoader
.loadFactories(BindingConverter.class, null)));
return bindingConverterFactory;
}
@Bean
@ConditionalOnMissingBean
public static BindingAdapterFactory bindingAdapterFactory() {
BindingAdapterFactory bindingAdapterFactory = new BindingAdapterFactoryImpl();
bindingAdapterFactory.addBindingAdapters(new HashSet<>(SpringFactoriesLoader.loadFactories(
BindingAdapter.class, null)));
return bindingAdapterFactory;
}
@Bean
@ConditionalOnMissingBean
public static RuntimeContextBeanFactoryPostProcessor runtimeContextBeanFactoryPostProcessor() {
return new RuntimeContextBeanFactoryPostProcessor();
}
@Bean
@ConditionalOnMissingBean
public static ServiceBeanFactoryPostProcessor serviceBeanFactoryPostProcessor() {
return new ServiceBeanFactoryPostProcessor();
}
@Bean
@ConditionalOnMissingBean
public static ProxyBeanFactoryPostProcessor proxyBeanFactoryPostProcessor() {
return new ProxyBeanFactoryPostProcessor();
}
@Bean
@ConditionalOnMissingBean
public ComponentContextRefreshInterceptor componentContextRefreshInterceptor(SofaRuntimeManager sofaRuntimeManager) {
return new ComponentContextRefreshInterceptor(sofaRuntimeManager);
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnSwitch(value = "runtimeAsyncInit")
static class AsyncInitConfiguration {
@Bean
@ConditionalOnMissingBean
public static AsyncInitMethodManager asyncInitMethodManager() {
return new AsyncInitMethodManager();
}
@Bean(AsyncInitMethodManager.ASYNC_INIT_METHOD_EXECUTOR_BEAN_NAME)
@ConditionalOnMissingBean(name = AsyncInitMethodManager.ASYNC_INIT_METHOD_EXECUTOR_BEAN_NAME)
@Conditional(OnVirtualThreadStartupDisableCondition.class)
public Supplier<ExecutorService> asyncInitMethodExecutor(SofaRuntimeProperties sofaRuntimeProperties) {
return ()-> {
int coreSize = sofaRuntimeProperties.getAsyncInitExecutorCoreSize();
int maxSize = sofaRuntimeProperties.getAsyncInitExecutorMaxSize();
Assert.isTrue(coreSize >= 0, "executorCoreSize must no less than zero");
Assert.isTrue(maxSize >= 0, "executorMaxSize must no less than zero");
LOGGER.info("create async-init-bean thread pool, corePoolSize: {}, maxPoolSize: {}.",
coreSize, maxSize);
return new SofaThreadPoolExecutor(coreSize, maxSize, 30, TimeUnit.SECONDS,
new SynchronousQueue<>(), new NamedThreadFactory("async-init-bean"),
new ThreadPoolExecutor.CallerRunsPolicy(), "async-init-bean",
SofaBootConstants.SOFA_BOOT_SPACE_NAME);
};
}
@Bean(AsyncInitMethodManager.ASYNC_INIT_METHOD_EXECUTOR_BEAN_NAME)
@ConditionalOnMissingBean(name = AsyncInitMethodManager.ASYNC_INIT_METHOD_EXECUTOR_BEAN_NAME)
@Conditional(OnVirtualThreadStartupAvailableCondition.class)
public Supplier<ExecutorService> asyncInitMethodVirtualExecutor() {
return ()-> {
LOGGER.info("create async-init-bean virtual executor service");
return SofaVirtualThreadFactory.ofExecutorService("async-init-bean");
};
}
@Bean
@ConditionalOnMissingBean
public static AsyncProxyBeanPostProcessor asyncProxyBeanPostProcessor(AsyncInitMethodManager asyncInitMethodManager) {
return new AsyncProxyBeanPostProcessor(asyncInitMethodManager);
}
@Bean
@ConditionalOnMissingBean
public static AsyncInitBeanFactoryPostProcessor asyncInitBeanFactoryPostProcessor() {
return new AsyncInitBeanFactoryPostProcessor();
}
}
}
|
ClientFactoryInternal clientFactoryInternal = new ClientFactoryImpl();
SofaRuntimeManager sofaRuntimeManager = new StandardSofaRuntimeManager(
environment.getProperty(SofaBootConstants.APP_NAME_KEY), Thread.currentThread()
.getContextClassLoader(), clientFactoryInternal);
clientFactoryInternal.registerClient(ReferenceClient.class, new ReferenceClientImpl(
sofaRuntimeManager.getSofaRuntimeContext(), bindingConverterFactory,
bindingAdapterFactory));
clientFactoryInternal.registerClient(ServiceClient.class, new ServiceClientImpl(
sofaRuntimeManager.getSofaRuntimeContext(), bindingConverterFactory,
bindingAdapterFactory));
// use bind to inject properties, avoid bean early init problem.
SofaRuntimeContext sofaRuntimeContext = sofaRuntimeManager.getSofaRuntimeContext();
dynamicServiceProxyManager.ifUnique(sofaRuntimeContext::setServiceProxyManager);
Binder binder = Binder.get(environment);
SofaRuntimeContext.Properties properties = sofaRuntimeContext.getProperties();
Bindable<SofaRuntimeContext.Properties> bindable = Bindable.of(SofaRuntimeContext.Properties.class)
.withExistingValue(properties);
binder.bind("sofa.boot.runtime", bindable);
return sofaRuntimeManager;
| 1,205
| 315
| 1,520
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-autoconfigure/src/main/java/com/alipay/sofa/boot/autoconfigure/tracer/SofaTracerAutoConfiguration.java
|
SofaTracerAutoConfiguration
|
sofaTracerSpanReportListener
|
class SofaTracerAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public SpanReportListenerHolder sofaTracerSpanReportListener(List<SpanReportListener> spanReportListenerList) {<FILL_FUNCTION_BODY>}
}
|
if (!CollectionUtils.isEmpty(spanReportListenerList)) {
//cache in tracer listener core
SpanReportListenerHolder.addSpanReportListeners(spanReportListenerList);
}
return null;
| 64
| 54
| 118
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-autoconfigure/src/main/java/com/alipay/sofa/boot/autoconfigure/tracer/SofaTracerConfigurationListener.java
|
SofaTracerConfigurationListener
|
onApplicationEvent
|
class SofaTracerConfigurationListener
implements
ApplicationListener<ApplicationEnvironmentPreparedEvent>,
Ordered {
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {<FILL_FUNCTION_BODY>}
@Override
public int getOrder() {
return ApplicationListenerOrderConstants.SOFA_TRACER_CONFIGURATION_LISTENER_ORDER;
}
}
|
if (SofaBootEnvUtils.isSpringCloudBootstrapEnvironment(event.getEnvironment())) {
return;
}
ConfigurableEnvironment environment = event.getEnvironment();
// check spring.application.name
String applicationName = environment.getProperty(SofaBootConstants.APP_NAME_KEY);
Assert.isTrue(StringUtils.hasText(applicationName), SofaBootConstants.APP_NAME_KEY
+ " must be configured!");
SofaTracerConfiguration.setProperty(SofaTracerConfiguration.TRACER_APPNAME_KEY,
applicationName);
Binder binder = Binder.get(environment);
SofaTracerProperties sofaTracerProperties = new SofaTracerProperties();
Bindable<SofaTracerProperties> bindable = Bindable.of(SofaTracerProperties.class)
.withExistingValue(sofaTracerProperties);
binder.bind("sofa.boot.tracer", bindable);
//properties convert to tracer
SofaTracerConfiguration.setProperty(
SofaTracerConfiguration.DISABLE_MIDDLEWARE_DIGEST_LOG_KEY,
sofaTracerProperties.getDisableDigestLog());
SofaTracerConfiguration.setProperty(SofaTracerConfiguration.DISABLE_DIGEST_LOG_KEY,
sofaTracerProperties.getDisableConfiguration());
SofaTracerConfiguration.setProperty(SofaTracerConfiguration.TRACER_GLOBAL_ROLLING_KEY,
sofaTracerProperties.getTracerGlobalRollingPolicy());
SofaTracerConfiguration.setProperty(SofaTracerConfiguration.TRACER_GLOBAL_LOG_RESERVE_DAY,
sofaTracerProperties.getTracerGlobalLogReserveDay());
//stat log interval
SofaTracerConfiguration.setProperty(SofaTracerConfiguration.STAT_LOG_INTERVAL,
sofaTracerProperties.getStatLogInterval());
//baggage length
SofaTracerConfiguration.setProperty(
SofaTracerConfiguration.TRACER_PENETRATE_ATTRIBUTE_MAX_LENGTH,
sofaTracerProperties.getBaggageMaxLength());
SofaTracerConfiguration.setProperty(
SofaTracerConfiguration.TRACER_SYSTEM_PENETRATE_ATTRIBUTE_MAX_LENGTH,
sofaTracerProperties.getBaggageMaxLength());
//sampler config
if (sofaTracerProperties.getSamplerName() != null) {
SofaTracerConfiguration.setProperty(SofaTracerConfiguration.SAMPLER_STRATEGY_NAME_KEY,
sofaTracerProperties.getSamplerName());
}
if (StringUtils.hasText(sofaTracerProperties.getSamplerCustomRuleClassName())) {
SofaTracerConfiguration.setProperty(
SofaTracerConfiguration.SAMPLER_STRATEGY_CUSTOM_RULE_CLASS_NAME,
sofaTracerProperties.getSamplerCustomRuleClassName());
}
SofaTracerConfiguration.setProperty(
SofaTracerConfiguration.SAMPLER_STRATEGY_PERCENTAGE_KEY,
String.valueOf(sofaTracerProperties.getSamplerPercentage()));
SofaTracerConfiguration.setProperty(SofaTracerConfiguration.JSON_FORMAT_OUTPUT,
String.valueOf(sofaTracerProperties.isJsonOutput()));
| 107
| 878
| 985
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-autoconfigure/src/main/java/com/alipay/sofa/boot/autoconfigure/tracer/datasource/DataSourceAutoConfiguration.java
|
DataSourceAutoConfiguration
|
dataSourceBeanPostProcessor
|
class DataSourceAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public static DataSourceBeanPostProcessor dataSourceBeanPostProcessor(Environment environment) {<FILL_FUNCTION_BODY>}
}
|
String appName = environment.getProperty(SofaTracerConfiguration.TRACER_APPNAME_KEY);
DataSourceBeanPostProcessor dataSourceBeanPostProcessor = new DataSourceBeanPostProcessor();
dataSourceBeanPostProcessor.setAppName(appName);
return dataSourceBeanPostProcessor;
| 53
| 74
| 127
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-autoconfigure/src/main/java/com/alipay/sofa/boot/autoconfigure/tracer/flexible/FlexibleAutoConfiguration.java
|
FlexibleAutoConfiguration
|
sofaTracer
|
class FlexibleAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public Tracer sofaTracer(ObjectProvider<SofaTracerProperties> sofaTracerPropertiesObjectProvider)
throws Exception {<FILL_FUNCTION_BODY>}
@Bean
@ConditionalOnMissingBean
public MethodInvocationProcessor sofaMethodInvocationProcessor(Tracer tracer) {
return new SofaTracerMethodInvocationProcessor(tracer);
}
@Bean
@ConditionalOnMissingBean
public SofaTracerIntroductionInterceptor sofaTracerIntroductionInterceptor(MethodInvocationProcessor methodInvocationProcessor) {
return new SofaTracerIntroductionInterceptor(methodInvocationProcessor);
}
@Bean
@ConditionalOnMissingBean
public SofaTracerAdvisingBeanPostProcessor tracerAnnotationBeanPostProcessor(SofaTracerIntroductionInterceptor methodInterceptor) {
return new SofaTracerAdvisingBeanPostProcessor(methodInterceptor);
}
}
|
SofaTracerProperties sofaTracerProperties = sofaTracerPropertiesObjectProvider
.getIfUnique();
String reporterName = null;
if (sofaTracerProperties != null) {
reporterName = sofaTracerProperties.getReporterName();
}
if (StringUtils.hasText(reporterName)) {
Reporter reporter = (Reporter) Class.forName(reporterName).getDeclaredConstructor()
.newInstance();
Sampler sampler = SamplerFactory.getSampler();
return new FlexibleTracer(sampler, reporter);
}
return new FlexibleTracer();
| 255
| 158
| 413
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-autoconfigure/src/main/java/com/alipay/sofa/boot/autoconfigure/tracer/mongo/MongoAutoConfiguration.java
|
MongoAutoConfiguration
|
sofaTracerMongoClientSettingsBuilderCustomizer
|
class MongoAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public SofaTracerCommandListenerCustomizer sofaTracerMongoClientSettingsBuilderCustomizer(Environment environment) {<FILL_FUNCTION_BODY>}
}
|
String appName = environment.getProperty(SofaTracerConfiguration.TRACER_APPNAME_KEY);
SofaTracerCommandListenerCustomizer sofaTracerCommandListenerCustomizer = new SofaTracerCommandListenerCustomizer();
sofaTracerCommandListenerCustomizer.setAppName(appName);
return sofaTracerCommandListenerCustomizer;
| 61
| 88
| 149
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-autoconfigure/src/main/java/com/alipay/sofa/boot/autoconfigure/tracer/rocketmq/RocketMqAutoConfiguration.java
|
RocketMqAutoConfiguration
|
sofaTracerRocketMqConsumerPostProcessor
|
class RocketMqAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public static RocketMqProducerPostProcessor sofaTracerRocketMqProducerPostProcessor(Environment environment) {
String appName = environment.getProperty(SofaTracerConfiguration.TRACER_APPNAME_KEY);
RocketMqProducerPostProcessor rocketMqProducerPostProcessor = new RocketMqProducerPostProcessor();
rocketMqProducerPostProcessor.setAppName(appName);
return rocketMqProducerPostProcessor;
}
@Bean
@ConditionalOnMissingBean
public static RocketMqConsumerPostProcessor sofaTracerRocketMqConsumerPostProcessor(Environment environment) {<FILL_FUNCTION_BODY>}
}
|
String appName = environment.getProperty(SofaTracerConfiguration.TRACER_APPNAME_KEY);
RocketMqConsumerPostProcessor rocketMqConsumerPostProcessor = new RocketMqConsumerPostProcessor();
rocketMqConsumerPostProcessor.setAppName(appName);
return rocketMqConsumerPostProcessor;
| 192
| 84
| 276
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-autoconfigure/src/main/java/com/alipay/sofa/boot/autoconfigure/tracer/springmessage/SpringMessageAutoConfiguration.java
|
SpringMessageAutoConfiguration
|
springMessageTracerBeanPostProcessor
|
class SpringMessageAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public static SpringMessageTracerBeanPostProcessor springMessageTracerBeanPostProcessor(Environment environment) {<FILL_FUNCTION_BODY>}
}
|
String appName = environment.getProperty(SofaTracerConfiguration.TRACER_APPNAME_KEY);
SpringMessageTracerBeanPostProcessor springMessageTracerBeanPostProcessor = new SpringMessageTracerBeanPostProcessor();
springMessageTracerBeanPostProcessor.setAppName(appName);
return springMessageTracerBeanPostProcessor;
| 57
| 84
| 141
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-autoconfigure/src/main/java/com/alipay/sofa/boot/autoconfigure/tracer/springmvc/OpenTracingSpringMvcAutoConfiguration.java
|
SpringMvcDelegatingFilterProxyConfiguration
|
springMvcSofaTracerFilter
|
class SpringMvcDelegatingFilterProxyConfiguration {
@Bean
public FilterRegistrationBean<SpringMvcSofaTracerFilter> springMvcSofaTracerFilter(OpenTracingSpringMvcProperties openTracingSpringMvcProperties) {<FILL_FUNCTION_BODY>}
}
|
FilterRegistrationBean<SpringMvcSofaTracerFilter> filterRegistrationBean = new FilterRegistrationBean<>();
SpringMvcSofaTracerFilter filter = new SpringMvcSofaTracerFilter();
filterRegistrationBean.setFilter(filter);
List<String> urlPatterns = openTracingSpringMvcProperties.getUrlPatterns();
if (urlPatterns == null || urlPatterns.size() <= 0) {
filterRegistrationBean.addUrlPatterns("/*");
} else {
filterRegistrationBean.setUrlPatterns(urlPatterns);
}
filterRegistrationBean.setName(filter.getFilterName());
filterRegistrationBean.setAsyncSupported(true);
filterRegistrationBean.setOrder(openTracingSpringMvcProperties.getFilterOrder());
return filterRegistrationBean;
| 79
| 212
| 291
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-autoconfigure/src/main/java/com/alipay/sofa/boot/autoconfigure/tracer/zipkin/ZipkinAutoConfiguration.java
|
ZipkinAutoConfiguration
|
zipkinSofaTracerSpanReporter
|
class ZipkinAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public ZipkinSofaTracerRestTemplateCustomizer zipkinSofaTracerRestTemplateCustomizer(ZipkinProperties zipkinProperties) {
return new ZipkinSofaTracerRestTemplateCustomizer(zipkinProperties.isGzipped());
}
@Bean
@ConditionalOnMissingBean
public ZipkinSofaTracerSpanRemoteReporter zipkinSofaTracerSpanReporter(ZipkinSofaTracerRestTemplateCustomizer zipkinSofaTracerRestTemplateCustomizer,
ZipkinProperties zipkinProperties) {<FILL_FUNCTION_BODY>}
}
|
RestTemplate restTemplate = new RestTemplate();
zipkinSofaTracerRestTemplateCustomizer.customize(restTemplate);
return new ZipkinSofaTracerSpanRemoteReporter(restTemplate, zipkinProperties.getBaseUrl());
| 175
| 62
| 237
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/ark-sofa-boot/src/main/java/com/alipay/sofa/boot/ark/SofaRuntimeActivator.java
|
SofaRuntimeActivator
|
registerEventHandler
|
class SofaRuntimeActivator implements PluginActivator {
@Override
public void start(PluginContext context) {
registerEventHandler(context);
context.publishService(DynamicJvmServiceProxyFinder.class,
DynamicJvmServiceProxyFinder.getInstance());
}
private void registerEventHandler(final PluginContext context) {<FILL_FUNCTION_BODY>}
@Override
public void stop(PluginContext context) {
// no op
}
}
|
EventAdminService eventAdminService = context.referenceService(EventAdminService.class)
.getService();
eventAdminService.register(new SofaBizUninstallEventHandler());
eventAdminService.register(new SofaBizHealthCheckEventHandler());
eventAdminService.register(new FinishStartupEventHandler());
eventAdminService.register(new AfterBizStartupEventHandler());
| 126
| 100
| 226
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/ark-sofa-boot/src/main/java/com/alipay/sofa/boot/ark/handler/SofaBizHealthCheckEventHandler.java
|
SofaBizHealthCheckEventHandler
|
doHealthCheck
|
class SofaBizHealthCheckEventHandler implements EventHandler<AfterBizStartupEvent> {
private static final String READINESS_CHECK_LISTENER_CLASS = "com.alipay.sofa.boot.actuator.health.ReadinessCheckListener";
private static boolean isReadinessCheckListenerClassExist;
static {
try {
Class.forName(READINESS_CHECK_LISTENER_CLASS);
isReadinessCheckListenerClassExist = true;
} catch (ClassNotFoundException e) {
isReadinessCheckListenerClassExist = false;
}
}
@Override
public void handleEvent(AfterBizStartupEvent event) {
doHealthCheck(event.getSource());
}
private void doHealthCheck(Biz biz) {<FILL_FUNCTION_BODY>}
@Override
public int getPriority() {
return PriorityOrdered.DEFAULT_PRECEDENCE;
}
}
|
if (!isReadinessCheckListenerClassExist) {
return;
}
ApplicationContext applicationContext = SofaRuntimeContainer.getApplicationContext(biz
.getBizClassLoader());
if (applicationContext == null) {
throw new IllegalStateException("No application match classLoader");
}
ObjectProvider<ReadinessCheckListener> provider = applicationContext
.getBeanProvider(ReadinessCheckListener.class);
ReadinessCheckListener readinessCheckListener = provider.getIfUnique();
if (readinessCheckListener != null) {
if (!readinessCheckListener.aggregateReadinessHealth().getStatus().equals(Status.UP)) {
throw new RuntimeException("Readiness health check failed.");
}
}
| 248
| 187
| 435
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/ark-sofa-boot/src/main/java/com/alipay/sofa/boot/ark/handler/SofaBizUninstallEventHandler.java
|
SofaBizUninstallEventHandler
|
doUninstallBiz
|
class SofaBizUninstallEventHandler implements EventHandler<BeforeBizStopEvent> {
@Override
public void handleEvent(BeforeBizStopEvent event) {
doUninstallBiz(event.getSource());
}
private void doUninstallBiz(Biz biz) {<FILL_FUNCTION_BODY>}
@Override
public int getPriority() {
return PriorityOrdered.DEFAULT_PRECEDENCE;
}
}
|
// Remove dynamic JVM service cache
DynamicJvmServiceProxyFinder.getInstance().afterBizUninstall(biz);
SofaRuntimeManager sofaRuntimeManager = SofaRuntimeContainer.getSofaRuntimeManager(biz
.getBizClassLoader());
if (sofaRuntimeManager == null) {
throw new IllegalStateException("No SofaRuntimeManager match classLoader");
}
sofaRuntimeManager.shutDownExternally();
| 120
| 117
| 237
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/ark-sofa-boot/src/main/java/com/alipay/sofa/boot/ark/invoke/DynamicJvmServiceInvoker.java
|
DynamicJvmServiceInvoker
|
hessianTransport
|
class DynamicJvmServiceInvoker extends ServiceProxy {
private static final Logger LOGGER = SofaBootLoggerFactory
.getLogger(DynamicJvmServiceInvoker.class);
private final Contract contract;
private final Object targetService;
private final String bizIdentity;
private final ClassLoader clientClassloader;
private final boolean serialize;
static protected final String TOSTRING_METHOD = "toString";
static protected final String EQUALS_METHOD = "equals";
static protected final String HASHCODE_METHOD = "hashCode";
public DynamicJvmServiceInvoker(ClassLoader clientClassloader, ClassLoader serviceClassLoader,
Object targetService, Contract contract, String bizIdentity,
boolean serialize) {
super(serviceClassLoader);
this.clientClassloader = clientClassloader;
this.targetService = targetService;
this.contract = contract;
this.bizIdentity = bizIdentity;
this.serialize = serialize;
}
@Override
protected Object doInvoke(MethodInvocation invocation) throws Throwable {
try {
LOGGER.atDebug().log(() -> ">> Start in Cross App JVM service invoke, the service interface is - "
+ getInterfaceType());
if (DynamicJvmServiceProxyFinder.getInstance().getBizManagerService() != null) {
ReplayContext.setPlaceHolder();
}
Method targetMethod = invocation.getMethod();
Object[] targetArguments = invocation.getArguments();
if (TOSTRING_METHOD.equalsIgnoreCase(targetMethod.getName())
&& targetMethod.getParameterTypes().length == 0) {
return targetService.toString();
} else if (EQUALS_METHOD.equalsIgnoreCase(targetMethod.getName())
&& targetMethod.getParameterTypes().length == 1) {
return targetService.equals(targetArguments[0]);
} else if (HASHCODE_METHOD.equalsIgnoreCase(targetMethod.getName())
&& targetMethod.getParameterTypes().length == 0) {
return targetService.hashCode();
}
Class[] oldArgumentTypes = targetMethod.getParameterTypes();
Method transformMethod;
// check whether skip serialize or not
if (!serialize) {
ClassLoader tcl = Thread.currentThread().getContextClassLoader();
try {
pushThreadContextClassLoader(getServiceClassLoader());
transformMethod = getTargetMethod(targetMethod, oldArgumentTypes);
return transformMethod.invoke(targetService, targetArguments);
} finally {
pushThreadContextClassLoader(tcl);
}
} else {
Object[] arguments = (Object[]) hessianTransport(targetArguments, null);
Class<?>[] argumentTypes = (Class<?>[]) hessianTransport(oldArgumentTypes, null);
transformMethod = getTargetMethod(targetMethod, argumentTypes);
Object retVal = transformMethod.invoke(targetService, arguments);
return hessianTransport(retVal, clientClassloader);
}
} catch (InvocationTargetException ex) {
throw ex.getTargetException();
} finally {
if (DynamicJvmServiceProxyFinder.getInstance().getBizManagerService() != null) {
ReplayContext.clearPlaceHolder();
}
}
}
@Override
protected void doCatch(MethodInvocation invocation, Throwable e, long startTime) {
LOGGER.atDebug().log(() -> getCommonInvocationLog("Exception", invocation, startTime));
}
@Override
protected void doFinally(MethodInvocation invocation, long startTime) {
LOGGER.atDebug().log(() -> getCommonInvocationLog("Finally", invocation, startTime));
}
public boolean isSerialize() {
return serialize;
}
public Class<?> getInterfaceType() {
return contract.getInterfaceType();
}
private Method getTargetMethod(Method method, Class<?>[] argumentTypes) {
try {
return targetService.getClass().getMethod(method.getName(), argumentTypes);
} catch (NoSuchMethodException ex) {
throw new IllegalStateException(targetService + " in " + bizIdentity
+ " don't have the method " + method);
}
}
private static Object hessianTransport(Object source, ClassLoader contextClassLoader) {<FILL_FUNCTION_BODY>}
}
|
Object target;
ClassLoader currentContextClassloader = Thread.currentThread().getContextClassLoader();
try {
if (contextClassLoader != null) {
Thread.currentThread().setContextClassLoader(contextClassLoader);
}
SerializerFactory serializerFactory = new SerializerFactory();
serializerFactory.setAllowNonSerializable(true);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Hessian2Output h2o = new Hessian2Output(bos);
h2o.setSerializerFactory(serializerFactory);
h2o.writeObject(source);
h2o.flush();
byte[] content = bos.toByteArray();
Hessian2Input h2i = new Hessian2Input(new ByteArrayInputStream(content));
h2i.setSerializerFactory(serializerFactory);
target = h2i.readObject();
} catch (IOException ex) {
throw new RuntimeException(ex);
} finally {
Thread.currentThread().setContextClassLoader(currentContextClassloader);
}
return target;
| 1,101
| 267
| 1,368
|
<methods>public void <init>(java.lang.ClassLoader) ,public java.lang.ClassLoader getServiceClassLoader() ,public java.lang.Object invoke(org.aopalliance.intercept.MethodInvocation) throws java.lang.Throwable<variables>protected java.lang.ClassLoader serviceClassLoader
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/ark-sofa-boot/src/main/java/com/alipay/sofa/boot/ark/invoke/JvmServiceTargetHabitat.java
|
JvmServiceTargetHabitat
|
getDefaultServiceComponent
|
class JvmServiceTargetHabitat {
private final String bizName;
/**
* Key as version
* Value as target bean
*/
private final Map<String, ServiceComponent> habitat = new ConcurrentHashMap<>();
public JvmServiceTargetHabitat(String bizName) {
this.bizName = bizName;
}
public void addServiceComponent(String bizVersion, ServiceComponent serviceComponent) {
habitat.put(bizVersion, serviceComponent);
}
public void removeServiceComponent(String bizVersion) {
habitat.remove(bizVersion);
}
public ServiceComponent getServiceComponent(String version) {
return habitat.get(version);
}
public ServiceComponent getDefaultServiceComponent() {<FILL_FUNCTION_BODY>}
}
|
for (String bizVersion : habitat.keySet()) {
if (ArkClient.getBizManagerService().isActiveBiz(bizName, bizVersion)) {
return habitat.get(bizVersion);
}
}
return null;
| 206
| 68
| 274
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/isle-sofa-boot/src/main/java/com/alipay/sofa/boot/isle/ApplicationRuntimeModel.java
|
ApplicationRuntimeModel
|
getResolvedDeployments
|
class ApplicationRuntimeModel implements IsleDeploymentModel {
public static final String APPLICATION_RUNTIME_MODEL_NAME = "APPLICATION_RUNTIME_MODEL";
@Deprecated
public static final String APPLICATION = "SOFABOOT-APPLICATION";
/** deploys */
private final List<DeploymentDescriptor> deploys = new ArrayList<>();
/** inactive deploys */
private final List<DeploymentDescriptor> inactiveDeploys = new ArrayList<>();
/** failed deployments */
private final List<DeploymentDescriptor> failed = new CopyOnWriteArrayList<>();
/** installed deployments */
private final List<DeploymentDescriptor> installed = new CopyOnWriteArrayList<>();
/** module name to deployment */
private final Map<String, DeploymentDescriptor> deploymentMap = new LinkedHashMap<>();
/** deploy registry */
private final DeployRegistry deployRegistry = new DeployRegistry();
/** no spring powered deploys name*/
private final Set<String> noSpringPoweredDeploys = new HashSet<>();
/** module deployment validator */
private ModuleDeploymentValidator moduleDeploymentValidator;
/** module profiles checker */
protected SofaModuleProfileChecker sofaModuleProfileChecker;
/** resolved deployments */
private List<DeploymentDescriptor> resolvedDeployments;
public boolean isModuleDeployment(DeploymentDescriptor deploymentDescriptor) {
return this.moduleDeploymentValidator.isModuleDeployment(deploymentDescriptor);
}
public boolean acceptModule(DeploymentDescriptor deploymentDescriptor) {
return this.sofaModuleProfileChecker.acceptModule(deploymentDescriptor);
}
public DeploymentDescriptor addDeployment(DeploymentDescriptor dd) {
deploys.add(dd);
deployRegistry.add(dd);
return deploymentMap.put(dd.getModuleName(), dd);
}
public List<DeploymentDescriptor> getAllDeployments() {
Collections.sort(deploys);
return deploys;
}
public void addInactiveDeployment(DeploymentDescriptor dd) {
inactiveDeploys.add(dd);
}
public List<DeploymentDescriptor> getAllInactiveDeployments() {
Collections.sort(inactiveDeploys);
return inactiveDeploys;
}
public List<DeploymentDescriptor> getResolvedDeployments() {<FILL_FUNCTION_BODY>}
public void addNoSpringPoweredDeployment(DeploymentDescriptor dd) {
noSpringPoweredDeploys.add(dd.getModuleName());
}
public DeployRegistry getDeployRegistry() {
return deployRegistry;
}
public DeploymentDescriptor getDeploymentByName(String moduleName) {
return deploymentMap.get(moduleName);
}
public void addFailed(DeploymentDescriptor failed) {
this.failed.add(failed);
}
public List<DeploymentDescriptor> getFailed() {
return failed;
}
public void addInstalled(DeploymentDescriptor installed) {
this.installed.add(installed);
}
public List<DeploymentDescriptor> getInstalled() {
return installed;
}
public ModuleDeploymentValidator getModuleDeploymentValidator() {
return moduleDeploymentValidator;
}
public void setModuleDeploymentValidator(ModuleDeploymentValidator moduleDeploymentValidator) {
this.moduleDeploymentValidator = moduleDeploymentValidator;
}
public SofaModuleProfileChecker getSofaModuleProfileChecker() {
return sofaModuleProfileChecker;
}
public void setSofaModuleProfileChecker(SofaModuleProfileChecker sofaModuleProfileChecker) {
this.sofaModuleProfileChecker = sofaModuleProfileChecker;
}
@Override
@NonNull
public Map<String, ApplicationContext> getModuleApplicationContextMap() {
Map<String, ApplicationContext> result = new HashMap<>(8);
installed.forEach(deploymentDescriptor -> result.put(deploymentDescriptor.getModuleName(), deploymentDescriptor.getApplicationContext()));
return result;
}
}
|
if (resolvedDeployments != null) {
return resolvedDeployments;
}
//remove all required when no spring powered module exist
deploymentMap.values().forEach(dd -> {
List<String> requiredModules = dd.getRequiredModules();
if (requiredModules != null) {
// if required module is no spring powered, remove it
requiredModules.removeIf(module -> !deploymentMap.containsKey(module) && noSpringPoweredDeploys.contains(module));
}
});
resolvedDeployments = deployRegistry.getResolvedObjects();
return resolvedDeployments;
| 1,052
| 163
| 1,215
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/isle-sofa-boot/src/main/java/com/alipay/sofa/boot/isle/deployment/AbstractDeploymentDescriptor.java
|
AbstractDeploymentDescriptor
|
getFormattedModuleInfo
|
class AbstractDeploymentDescriptor implements DeploymentDescriptor {
protected final Properties properties;
protected final DeploymentDescriptorConfiguration deploymentDescriptorConfiguration;
protected final ClassLoader classLoader;
protected final URL url;
protected final List<String> installedSpringXml = new ArrayList<>();
protected final Map<String, Resource> springResources = new HashMap<>();
protected final String moduleName;
protected final String name;
protected final List<String> requiredModules;
protected final String parentModule;
protected ApplicationContext applicationContext;
protected long startTime;
protected long elapsedTime;
private boolean ignoreRequireModule;
public AbstractDeploymentDescriptor(URL url,
Properties properties,
DeploymentDescriptorConfiguration deploymentDescriptorConfiguration,
ClassLoader classLoader) {
this.url = url;
this.properties = properties;
this.deploymentDescriptorConfiguration = deploymentDescriptorConfiguration;
this.classLoader = classLoader;
this.moduleName = getModuleNameFromProperties();
this.name = getNameFormUrl();
this.parentModule = getSpringParentFromProperties();
this.requiredModules = getRequiredModulesFromProperties();
}
@Override
public String getModuleName() {
return moduleName;
}
@Override
public String getName() {
return name;
}
@Override
public List<String> getRequiredModules() {
if (ignoreRequireModule) {
return null;
}
return requiredModules;
}
@Override
public String getSpringParent() {
return parentModule;
}
@Override
public String getProperty(String key) {
return properties.getProperty(key);
}
@Override
public ClassLoader getClassLoader() {
return classLoader;
}
@Override
public ApplicationContext getApplicationContext() {
return applicationContext;
}
@Override
public Map<String, Resource> getSpringResources() {
return springResources;
}
@Override
public boolean isSpringPowered() {
return !springResources.isEmpty();
}
@Override
public void addInstalledSpringXml(String fileName) {
installedSpringXml.add(fileName);
}
@Override
public void startDeploy() {
startTime = System.currentTimeMillis();
}
@Override
public void deployFinish() {
elapsedTime = System.currentTimeMillis() - startTime;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Override
public long getElapsedTime() {
return elapsedTime;
}
@Override
public long getStartTime() {
return startTime;
}
@Override
public List<String> getInstalledSpringXml() {
Collections.sort(installedSpringXml);
return installedSpringXml;
}
@Override
public int compareTo(DeploymentDescriptor o) {
return this.getName().compareTo(o.getName());
}
@Override
public void setIgnoreRequireModule(boolean ignoreRequireModule) {
this.ignoreRequireModule = ignoreRequireModule;
}
protected String getModuleNameFromProperties() {
List<String> moduleNameIdentities = deploymentDescriptorConfiguration
.getModuleNameIdentities();
if (CollectionUtils.isEmpty(moduleNameIdentities)) {
return null;
}
for (String moduleNameIdentity : moduleNameIdentities) {
List<String> moduleNames = getFormattedModuleInfo(moduleNameIdentity);
if (!CollectionUtils.isEmpty(moduleNames)) {
return moduleNames.get(0);
}
}
return null;
}
protected String getNameFormUrl() {
int jarIndex = url.toString().lastIndexOf(".jar");
if (jarIndex == -1) {
String moduleName = getModuleName();
return moduleName == null ? "" : moduleName;
}
String jarPath = url.toString().substring(0, jarIndex + ".jar".length());
int lastIndex = jarPath.lastIndexOf("/");
return jarPath.substring(lastIndex + 1);
}
protected List<String> getRequiredModulesFromProperties() {
List<String> requires = new ArrayList<>();
List<String> requireModuleIdentities = deploymentDescriptorConfiguration
.getRequireModuleIdentities();
if (CollectionUtils.isEmpty(requireModuleIdentities)) {
return requires;
}
for (String requireModuleIdentity : requireModuleIdentities) {
List<String> requireModules = getFormattedModuleInfo(requireModuleIdentity);
if (!CollectionUtils.isEmpty(requireModules)) {
requires.addAll(requireModules);
break;
}
}
String springParent = getSpringParent();
if (StringUtils.hasText(springParent)) {
requires.add(springParent);
}
return requires.stream().distinct().collect(Collectors.toList());
}
protected String getSpringParentFromProperties() {
List<String> name = getFormattedModuleInfo(DeploymentDescriptorConfiguration.SPRING_PARENT);
return CollectionUtils.isEmpty(name) ? null : name.get(0);
}
protected List<String> getFormattedModuleInfo(String key) {<FILL_FUNCTION_BODY>}
/**
* Actually load spring xml resources.
*/
protected abstract void loadSpringXMLs();
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof AbstractDeploymentDescriptor that)) {
return false;
}
return Objects.equals(this.getModuleName(), that.getModuleName());
}
@Override
public int hashCode() {
return Objects.hash(getModuleName());
}
}
|
String ret = properties.getProperty(key);
if (StringUtils.hasText(ret)) {
String[] array = StringUtils.commaDelimitedListToStringArray(ret);
List<String> list = new ArrayList<>(array.length);
for (String item : array) {
int idx = item.indexOf(';');
if (idx > -1) {
item = item.substring(0, idx);
}
list.add(item.trim());
}
return list;
}
return null;
| 1,525
| 137
| 1,662
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/isle-sofa-boot/src/main/java/com/alipay/sofa/boot/isle/deployment/DeployRegistry.java
|
DeployRegistry
|
commitDeployments
|
class DeployRegistry extends DependencyTree<String, DeploymentDescriptor> {
// this is needed to handle requiredBy dependencies
private final Map<String, DeploymentDescriptor> deployments = Collections
.synchronizedSortedMap(new TreeMap<String, DeploymentDescriptor>());
public void add(DeploymentDescriptor deployment) {
deployments.put(deployment.getName(), deployment);
}
public void remove(String key) {
deployments.remove(key);
}
@Override
public List<Entry<String, DeploymentDescriptor>> getResolvedEntries() {
if (!deployments.isEmpty()) {
commitDeployments();
}
return super.getResolvedEntries();
}
@Override
public List<Entry<String, DeploymentDescriptor>> getMissingRequirements() {
if (!deployments.isEmpty()) {
commitDeployments();
}
return super.getMissingRequirements();
}
@Override
public DeploymentDescriptor get(String key) {
if (!deployments.isEmpty()) {
commitDeployments();
}
return super.get(key);
}
@Override
public Collection<Entry<String, DeploymentDescriptor>> getEntries() {
if (!deployments.isEmpty()) {
commitDeployments();
}
return super.getEntries();
}
@Override
public List<DeploymentDescriptor> getResolvedObjects() {
if (!deployments.isEmpty()) {
commitDeployments();
}
return super.getResolvedObjects();
}
@Override
public List<DeploymentDescriptor> getPendingObjects() {
if (!deployments.isEmpty()) {
commitDeployments();
}
return super.getPendingObjects();
}
@Override
public Entry<String, DeploymentDescriptor> getEntry(String key) {
if (!deployments.isEmpty()) {
commitDeployments();
}
return super.getEntry(key);
}
@Override
public List<Entry<String, DeploymentDescriptor>> getPendingEntries() {
if (!deployments.isEmpty()) {
commitDeployments();
}
return super.getPendingEntries();
}
private void commitDeployments() {<FILL_FUNCTION_BODY>}
}
|
for (DeploymentDescriptor fd : deployments.values()) {
add(fd.getModuleName(), fd, fd.getRequiredModules());
}
deployments.clear();
| 595
| 50
| 645
|
<methods>public void <init>() ,public transient void add(java.lang.String, com.alipay.sofa.boot.isle.deployment.DeploymentDescriptor, java.lang.String[]) ,public void add(java.lang.String, com.alipay.sofa.boot.isle.deployment.DeploymentDescriptor, Collection<java.lang.String>) ,public void add(java.lang.String, com.alipay.sofa.boot.isle.deployment.DeploymentDescriptor) ,public void clear() ,public com.alipay.sofa.boot.isle.deployment.DeploymentDescriptor get(java.lang.String) ,public Collection<Entry<java.lang.String,com.alipay.sofa.boot.isle.deployment.DeploymentDescriptor>> getEntries() ,public Entry<java.lang.String,com.alipay.sofa.boot.isle.deployment.DeploymentDescriptor> getEntry(java.lang.String) ,public List<Entry<java.lang.String,com.alipay.sofa.boot.isle.deployment.DeploymentDescriptor>> getMissingRequirements() ,public List<Entry<java.lang.String,com.alipay.sofa.boot.isle.deployment.DeploymentDescriptor>> getPendingEntries() ,public List<com.alipay.sofa.boot.isle.deployment.DeploymentDescriptor> getPendingObjects() ,public List<Entry<java.lang.String,com.alipay.sofa.boot.isle.deployment.DeploymentDescriptor>> getResolvedEntries() ,public List<com.alipay.sofa.boot.isle.deployment.DeploymentDescriptor> getResolvedObjects() ,public Iterator<Entry<java.lang.String,com.alipay.sofa.boot.isle.deployment.DeploymentDescriptor>> iterator() ,public void remove(java.lang.String) ,public void resolve(Entry<java.lang.String,com.alipay.sofa.boot.isle.deployment.DeploymentDescriptor>) ,public void unregister(Entry<java.lang.String,com.alipay.sofa.boot.isle.deployment.DeploymentDescriptor>) ,public void unresolve(Entry<java.lang.String,com.alipay.sofa.boot.isle.deployment.DeploymentDescriptor>) <variables>private final non-sealed Map<java.lang.String,Entry<java.lang.String,com.alipay.sofa.boot.isle.deployment.DeploymentDescriptor>> registry,private final non-sealed List<Entry<java.lang.String,com.alipay.sofa.boot.isle.deployment.DeploymentDescriptor>> resolved
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/isle-sofa-boot/src/main/java/com/alipay/sofa/boot/isle/deployment/DeploymentDescriptorFactory.java
|
DeploymentDescriptorFactory
|
build
|
class DeploymentDescriptorFactory {
/**
* Build a SOFABoot Module deployment descriptor.
*
* @param url SOFABoot module file url
* @param props properties
* @param deploymentDescriptorConfiguration deployment descriptor configuration
* @param modulePropertyName moduleProperty file
* @return deployment descriptor
*/
public DeploymentDescriptor build(URL url,
Properties props,
DeploymentDescriptorConfiguration deploymentDescriptorConfiguration,
ClassLoader classLoader, String modulePropertyName) {<FILL_FUNCTION_BODY>}
protected DeploymentDescriptor createJarDeploymentDescriptor(URL url,
Properties props,
DeploymentDescriptorConfiguration deploymentDescriptorConfiguration,
ClassLoader classLoader) {
return new JarDeploymentDescriptor(url, props, deploymentDescriptorConfiguration,
classLoader);
}
protected DeploymentDescriptor createFileDeploymentDescriptor(URL url,
Properties props,
DeploymentDescriptorConfiguration deploymentDescriptorConfiguration,
ClassLoader classLoader,
String modulePropertyName) {
return new FileDeploymentDescriptor(url, props, deploymentDescriptorConfiguration,
classLoader, modulePropertyName);
}
}
|
if (ResourceUtils.isJarURL(url)) {
return createJarDeploymentDescriptor(url, props, deploymentDescriptorConfiguration,
classLoader);
} else {
return createFileDeploymentDescriptor(url, props, deploymentDescriptorConfiguration,
classLoader, modulePropertyName);
}
| 276
| 75
| 351
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/isle-sofa-boot/src/main/java/com/alipay/sofa/boot/isle/deployment/FileDeploymentDescriptor.java
|
FileDeploymentDescriptor
|
listFiles
|
class FileDeploymentDescriptor extends AbstractDeploymentDescriptor {
private final String modulePropertyName;
public FileDeploymentDescriptor(URL url,
Properties props,
DeploymentDescriptorConfiguration deploymentDescriptorConfiguration,
ClassLoader classLoader, String modulePropertyName) {
super(url, props, deploymentDescriptorConfiguration, classLoader);
this.modulePropertyName = modulePropertyName;
loadSpringXMLs();
}
@Override
public void loadSpringXMLs() {
try {
// When path contains special characters (e.g., white space, Chinese), URL converts them to UTF8 code point.
// In order to process correctly, create File from URI
URI springXmlUri = new URI("file://"
+ url.getFile().substring(0,
url.getFile().length() - modulePropertyName.length())
+ DeploymentDescriptorConfiguration.SPRING_CONTEXT_PATH);
File springXml = new File(springXmlUri);
List<File> springFiles = new ArrayList<>();
if (springXml.exists()) {
listFiles(springFiles, springXml, ".xml");
}
for (File f : springFiles) {
springResources.put(f.getAbsolutePath(), new FileSystemResource(f));
}
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
private void listFiles(List<File> subFiles, File parent, String suffix) {<FILL_FUNCTION_BODY>}
}
|
File[] files = parent.listFiles();
if (files == null || files.length == 0) {
return;
}
for (File f : files) {
if (f.isFile() && f.getName().endsWith(suffix)) {
subFiles.add(f);
} else if (f.isDirectory()) {
listFiles(subFiles, f, suffix);
}
}
| 372
| 106
| 478
|
<methods>public void <init>(java.net.URL, java.util.Properties, com.alipay.sofa.boot.isle.deployment.DeploymentDescriptorConfiguration, java.lang.ClassLoader) ,public void addInstalledSpringXml(java.lang.String) ,public int compareTo(com.alipay.sofa.boot.isle.deployment.DeploymentDescriptor) ,public void deployFinish() ,public boolean equals(java.lang.Object) ,public org.springframework.context.ApplicationContext getApplicationContext() ,public java.lang.ClassLoader getClassLoader() ,public long getElapsedTime() ,public List<java.lang.String> getInstalledSpringXml() ,public java.lang.String getModuleName() ,public java.lang.String getName() ,public java.lang.String getProperty(java.lang.String) ,public List<java.lang.String> getRequiredModules() ,public java.lang.String getSpringParent() ,public Map<java.lang.String,org.springframework.core.io.Resource> getSpringResources() ,public long getStartTime() ,public int hashCode() ,public boolean isSpringPowered() ,public void setApplicationContext(org.springframework.context.ApplicationContext) ,public void setIgnoreRequireModule(boolean) ,public void startDeploy() <variables>protected org.springframework.context.ApplicationContext applicationContext,protected final non-sealed java.lang.ClassLoader classLoader,protected final non-sealed com.alipay.sofa.boot.isle.deployment.DeploymentDescriptorConfiguration deploymentDescriptorConfiguration,protected long elapsedTime,private boolean ignoreRequireModule,protected final List<java.lang.String> installedSpringXml,protected final non-sealed java.lang.String moduleName,protected final non-sealed java.lang.String name,protected final non-sealed java.lang.String parentModule,protected final non-sealed java.util.Properties properties,protected final non-sealed List<java.lang.String> requiredModules,protected final Map<java.lang.String,org.springframework.core.io.Resource> springResources,protected long startTime,protected final non-sealed java.net.URL url
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/isle-sofa-boot/src/main/java/com/alipay/sofa/boot/isle/deployment/JarDeploymentDescriptor.java
|
JarDeploymentDescriptor
|
loadSpringXMLs
|
class JarDeploymentDescriptor extends AbstractDeploymentDescriptor {
public JarDeploymentDescriptor(URL url,
Properties props,
DeploymentDescriptorConfiguration deploymentDescriptorConfiguration,
ClassLoader classLoader) {
super(url, props, deploymentDescriptorConfiguration, classLoader);
loadSpringXMLs();
}
@Override
public void loadSpringXMLs() {<FILL_FUNCTION_BODY>}
private ByteArrayResource convertToByteArrayResource(InputStream inputStream) {
try {
int nRead;
byte[] data = new byte[2048];
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
return new ByteArrayResource(buffer.toByteArray());
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
}
|
JarFile jarFile;
try {
URLConnection con = url.openConnection();
Assert.isInstanceOf(JarURLConnection.class, con);
JarURLConnection jarCon = (JarURLConnection) con;
ResourceUtils.useCachesIfNecessary(jarCon);
jarFile = jarCon.getJarFile();
for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
JarEntry entry = entries.nextElement();
String entryPath = entry.getName();
if (entryPath.startsWith(DeploymentDescriptorConfiguration.SPRING_CONTEXT_PATH)
&& entryPath.endsWith("xml")) {
String fileName = entry.getName().substring(
DeploymentDescriptorConfiguration.SPRING_CONTEXT_PATH.length() + 1);
springResources.put(fileName,
convertToByteArrayResource(jarFile.getInputStream(entry)));
}
}
} catch (Throwable t) {
throw new RuntimeException(t);
}
| 249
| 263
| 512
|
<methods>public void <init>(java.net.URL, java.util.Properties, com.alipay.sofa.boot.isle.deployment.DeploymentDescriptorConfiguration, java.lang.ClassLoader) ,public void addInstalledSpringXml(java.lang.String) ,public int compareTo(com.alipay.sofa.boot.isle.deployment.DeploymentDescriptor) ,public void deployFinish() ,public boolean equals(java.lang.Object) ,public org.springframework.context.ApplicationContext getApplicationContext() ,public java.lang.ClassLoader getClassLoader() ,public long getElapsedTime() ,public List<java.lang.String> getInstalledSpringXml() ,public java.lang.String getModuleName() ,public java.lang.String getName() ,public java.lang.String getProperty(java.lang.String) ,public List<java.lang.String> getRequiredModules() ,public java.lang.String getSpringParent() ,public Map<java.lang.String,org.springframework.core.io.Resource> getSpringResources() ,public long getStartTime() ,public int hashCode() ,public boolean isSpringPowered() ,public void setApplicationContext(org.springframework.context.ApplicationContext) ,public void setIgnoreRequireModule(boolean) ,public void startDeploy() <variables>protected org.springframework.context.ApplicationContext applicationContext,protected final non-sealed java.lang.ClassLoader classLoader,protected final non-sealed com.alipay.sofa.boot.isle.deployment.DeploymentDescriptorConfiguration deploymentDescriptorConfiguration,protected long elapsedTime,private boolean ignoreRequireModule,protected final List<java.lang.String> installedSpringXml,protected final non-sealed java.lang.String moduleName,protected final non-sealed java.lang.String name,protected final non-sealed java.lang.String parentModule,protected final non-sealed java.util.Properties properties,protected final non-sealed List<java.lang.String> requiredModules,protected final Map<java.lang.String,org.springframework.core.io.Resource> springResources,protected long startTime,protected final non-sealed java.net.URL url
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/isle-sofa-boot/src/main/java/com/alipay/sofa/boot/isle/loader/DynamicSpringContextLoader.java
|
DynamicSpringContextLoader
|
loadBeanDefinitions
|
class DynamicSpringContextLoader implements SpringContextLoader, InitializingBean,
StartupReporterAware {
private static final Logger LOGGER = SofaBootLoggerFactory
.getLogger(DynamicSpringContextLoader.class);
protected final ConfigurableApplicationContext rootApplicationContext;
private boolean allowBeanOverriding;
private List<String> activeProfiles = new ArrayList<>();
private List<ContextRefreshInterceptor> contextRefreshInterceptors = new ArrayList<>();
private boolean publishEventToParent;
private SofaPostProcessorShareManager sofaPostProcessorShareManager;
private StartupReporter startupReporter;
public DynamicSpringContextLoader(ApplicationContext rootApplicationContext) {
this.rootApplicationContext = (ConfigurableApplicationContext) rootApplicationContext;
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(rootApplicationContext, "rootApplicationContext must not be null");
Assert.isInstanceOf(ConfigurableApplicationContext.class, rootApplicationContext,
"rootApplicationContext must be ConfigurableApplicationContext");
}
@Override
public void loadSpringContext(DeploymentDescriptor deployment,
ApplicationRuntimeModel application) {
ClassLoader classLoader = deployment.getClassLoader();
SofaDefaultListableBeanFactory beanFactory = SofaSpringContextSupport.createBeanFactory(classLoader, this::createBeanFactory);
beanFactory.setId(deployment.getModuleName());
SofaGenericApplicationContext context = SofaSpringContextSupport.createApplicationContext(beanFactory, this::createApplicationContext);
if (startupReporter != null) {
BufferingApplicationStartup bufferingApplicationStartup = new BufferingApplicationStartup(startupReporter.getBufferSize());
context.setApplicationStartup(bufferingApplicationStartup);
}
context.setId(deployment.getModuleName());
if (!CollectionUtils.isEmpty(activeProfiles)) {
context.getEnvironment().setActiveProfiles(StringUtils.toStringArray(activeProfiles));
}
context.setAllowBeanDefinitionOverriding(allowBeanOverriding);
context.setPublishEventToParent(publishEventToParent);
if (!CollectionUtils.isEmpty(contextRefreshInterceptors)) {
contextRefreshInterceptors.sort(AnnotationAwareOrderComparator.INSTANCE);
context.setInterceptors(contextRefreshInterceptors);
}
ConfigurableApplicationContext parentContext = getSpringParentContext(deployment, application);
context.setParent(parentContext);
context.getEnvironment().setConversionService(parentContext.getEnvironment().getConversionService());
XmlBeanDefinitionReader beanDefinitionReader = createXmlBeanDefinitionReader(context);
beanDefinitionReader.setNamespaceAware(true);
beanDefinitionReader.setBeanClassLoader(classLoader);
beanDefinitionReader.setResourceLoader(context);
loadBeanDefinitions(deployment, beanDefinitionReader);
deployment.setApplicationContext(context);
addPostProcessors(beanFactory);
}
protected XmlBeanDefinitionReader createXmlBeanDefinitionReader(SofaGenericApplicationContext context) {
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(context);
beanDefinitionReader.setValidating(true);
return beanDefinitionReader;
}
protected SofaDefaultListableBeanFactory createBeanFactory() {
return new SofaDefaultListableBeanFactory();
}
protected SofaGenericApplicationContext createApplicationContext(SofaDefaultListableBeanFactory beanFactory) {
return new SofaGenericApplicationContext(beanFactory);
}
protected ConfigurableApplicationContext getSpringParentContext(DeploymentDescriptor deployment,
ApplicationRuntimeModel application) {
ConfigurableApplicationContext parentSpringContext = null;
if (deployment.getSpringParent() != null) {
String springParent = deployment.getSpringParent();
if (StringUtils.hasText(springParent)) {
DeploymentDescriptor parent = application.getDeploymentByName(springParent);
if (parent != null) {
parentSpringContext = (ConfigurableApplicationContext) parent
.getApplicationContext();
if (parentSpringContext == null) {
LOGGER.warn("Module [{}]'s Spring-Parent [{}] is Null!",
deployment.getModuleName(), springParent);
}
}
}
}
return parentSpringContext == null ? rootApplicationContext : parentSpringContext;
}
protected void loadBeanDefinitions(DeploymentDescriptor deployment,
BeanDefinitionReader beanDefinitionReader) {<FILL_FUNCTION_BODY>}
protected void addPostProcessors(SofaDefaultListableBeanFactory beanFactory) {
if (sofaPostProcessorShareManager != null) {
sofaPostProcessorShareManager.getRegisterSingletonMap().forEach((beanName, singletonObject) -> {
if (!beanFactory.containsBeanDefinition(beanName)) {
beanFactory.registerSingleton(beanName, singletonObject);
}
});
sofaPostProcessorShareManager.getRegisterBeanDefinitionMap().forEach((beanName, beanDefinition) -> {
if (!beanFactory.containsBeanDefinition(beanName)) {
beanFactory.registerBeanDefinition(beanName, beanDefinition);
}
});
}
}
public boolean isAllowBeanOverriding() {
return allowBeanOverriding;
}
public void setAllowBeanOverriding(boolean allowBeanOverriding) {
this.allowBeanOverriding = allowBeanOverriding;
}
public List<String> getActiveProfiles() {
return activeProfiles;
}
public void setActiveProfiles(List<String> activeProfiles) {
this.activeProfiles = activeProfiles;
}
public boolean isPublishEventToParent() {
return publishEventToParent;
}
public void setPublishEventToParent(boolean publishEventToParent) {
this.publishEventToParent = publishEventToParent;
}
public List<ContextRefreshInterceptor> getContextRefreshInterceptors() {
return contextRefreshInterceptors;
}
public void setContextRefreshInterceptors(List<ContextRefreshInterceptor> contextRefreshInterceptors) {
this.contextRefreshInterceptors = contextRefreshInterceptors;
}
public SofaPostProcessorShareManager getSofaPostProcessorShareManager() {
return sofaPostProcessorShareManager;
}
public void setSofaPostProcessorShareManager(SofaPostProcessorShareManager sofaPostProcessorShareManager) {
this.sofaPostProcessorShareManager = sofaPostProcessorShareManager;
}
@Override
public void setStartupReporter(StartupReporter startupReporter) throws BeansException {
this.startupReporter = startupReporter;
}
}
|
if (deployment.getSpringResources() != null) {
for (Map.Entry<String, Resource> entry : deployment.getSpringResources().entrySet()) {
String fileName = entry.getKey();
beanDefinitionReader.loadBeanDefinitions(entry.getValue());
deployment.addInstalledSpringXml(fileName);
}
}
| 1,721
| 92
| 1,813
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/isle-sofa-boot/src/main/java/com/alipay/sofa/boot/isle/profile/DefaultSofaModuleProfileChecker.java
|
DefaultSofaModuleProfileChecker
|
acceptProfiles
|
class DefaultSofaModuleProfileChecker implements SofaModuleProfileChecker, InitializingBean {
private final Set<String> activeProfiles = new HashSet<>();
private List<String> userCustomProfiles;
@Override
public void afterPropertiesSet() {
init();
}
public void init() {
activeProfiles.add(DeploymentDescriptorConfiguration.DEFAULT_PROFILE_VALUE);
if (userCustomProfiles != null) {
activeProfiles.addAll(userCustomProfiles.stream().map(String::trim).collect(Collectors.toSet()));
}
for (String sofaProfile : activeProfiles) {
validateProfile(sofaProfile);
}
}
@Override
public boolean acceptProfiles(String[] sofaModuleProfiles) {<FILL_FUNCTION_BODY>}
@Override
public boolean acceptModule(DeploymentDescriptor deploymentDescriptor) {
return acceptProfiles(getModuleProfiles(deploymentDescriptor));
}
private boolean isProfileActive(String moduleProfile) {
validateProfile(moduleProfile);
return this.activeProfiles.contains(moduleProfile.trim());
}
private void validateProfile(String profile) {
if (!StringUtils.hasText(profile)) {
throw new IllegalArgumentException(ErrorCode.convert("01-13001", profile,
DeploymentDescriptorConfiguration.DEFAULT_PROFILE_VALUE));
}
if (profile.charAt(0) == '!') {
throw new IllegalArgumentException(ErrorCode.convert("01-13002", profile));
}
}
private String[] getModuleProfiles(DeploymentDescriptor deploymentDescriptor) {
String profiles = deploymentDescriptor
.getProperty(DeploymentDescriptorConfiguration.MODULE_PROFILE);
if (StringUtils.hasText(profiles)) {
return StringUtils.commaDelimitedListToStringArray(profiles);
} else {
return new String[] { DeploymentDescriptorConfiguration.DEFAULT_PROFILE_VALUE };
}
}
public List<String> getUserCustomProfiles() {
return userCustomProfiles;
}
public void setUserCustomProfiles(List<String> userCustomProfiles) {
this.userCustomProfiles = userCustomProfiles;
}
}
|
Assert.notEmpty(sofaModuleProfiles,
ErrorCode.convert("01-13000", DeploymentDescriptorConfiguration.DEFAULT_PROFILE_VALUE));
for (String sofaModuleProfile : sofaModuleProfiles) {
if (StringUtils.hasText(sofaModuleProfile) && sofaModuleProfile.charAt(0) == '!') {
if (!isProfileActive(sofaModuleProfile.substring(1))) {
return true;
}
} else if (isProfileActive(sofaModuleProfile)) {
return true;
}
}
return false;
| 571
| 148
| 719
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/isle-sofa-boot/src/main/java/com/alipay/sofa/boot/isle/spring/SofaModuleContextLifecycle.java
|
SofaModuleContextLifecycle
|
start
|
class SofaModuleContextLifecycle implements SmartLifecycle {
private static final Logger LOGGER = SofaBootLoggerFactory
.getLogger(SofaModuleContextLifecycle.class);
private final AtomicBoolean isleRefreshed = new AtomicBoolean(false);
private final PipelineContext pipelineContext;
public SofaModuleContextLifecycle(PipelineContext pipelineContext) {
this.pipelineContext = pipelineContext;
}
@Override
public void start() {<FILL_FUNCTION_BODY>}
@Override
public void stop() {
}
@Override
public boolean isRunning() {
return isleRefreshed.get();
}
@Override
public int getPhase() {
return -100;
}
}
|
if (isleRefreshed.compareAndSet(false, true)) {
try {
pipelineContext.process();
} catch (Throwable t) {
LOGGER.error(ErrorCode.convert("01-10000"), t);
throw new RuntimeException(ErrorCode.convert("01-10000"), t);
}
}
| 217
| 95
| 312
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/isle-sofa-boot/src/main/java/com/alipay/sofa/boot/isle/stage/AbstractPipelineStage.java
|
AbstractPipelineStage
|
setApplicationContext
|
class AbstractPipelineStage implements PipelineStage, ApplicationContextAware,
BeanFactoryAware, StartupReporterAware, InitializingBean {
protected final ClassLoader appClassLoader = Thread.currentThread()
.getContextClassLoader();
protected ApplicationRuntimeModel application;
protected ConfigurableApplicationContext applicationContext;
protected StartupReporter startupReporter;
protected ConfigurableListableBeanFactory beanFactory;
protected BaseStat baseStat;
@Override
public void process() throws Exception {
BaseStat stat = createBaseStat();
stat.setName(getName());
stat.setStartTime(System.currentTimeMillis());
this.baseStat = stat;
try {
doProcess();
} finally {
stat.setEndTime(System.currentTimeMillis());
if (startupReporter != null) {
startupReporter.addCommonStartupStat(stat);
}
}
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(application, "applicationRuntimeModel must not be null");
}
@Override
public void setStartupReporter(StartupReporter startupReporter) throws BeansException {
this.startupReporter = startupReporter;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {<FILL_FUNCTION_BODY>}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
Assert.isTrue(beanFactory instanceof ConfigurableListableBeanFactory,
"beanFactory must implement ConfigurableListableBeanFactory");
this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
}
public ApplicationRuntimeModel getApplicationRuntimeModel() {
return application;
}
public void setApplicationRuntimeModel(ApplicationRuntimeModel application) {
this.application = application;
}
protected BaseStat createBaseStat() {
return new BaseStat();
}
/**
* Do process pipeline stage, subclasses should override this method.
*
* @throws Exception if a failure occurred
*/
protected abstract void doProcess() throws Exception;
}
|
Assert.isTrue(applicationContext instanceof ConfigurableApplicationContext,
"applicationContext must implement ConfigurableApplicationContext");
this.applicationContext = (ConfigurableApplicationContext) applicationContext;
| 551
| 46
| 597
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/isle-sofa-boot/src/main/java/com/alipay/sofa/boot/isle/stage/DefaultPipelineContext.java
|
DefaultPipelineContext
|
appendStages
|
class DefaultPipelineContext implements PipelineContext {
private final List<PipelineStage> stageList = new ArrayList<>();
@Override
public void process() throws Exception {
stageList.sort(AnnotationAwareOrderComparator.INSTANCE);
for (PipelineStage pipelineStage : stageList) {
pipelineStage.process();
}
}
@Override
public PipelineContext appendStage(PipelineStage stage) {
this.stageList.add(stage);
return this;
}
@Override
public PipelineContext appendStages(List<PipelineStage> stages) {<FILL_FUNCTION_BODY>}
public List<PipelineStage> getStageList() {
return stageList;
}
}
|
for (PipelineStage pipelineStage : stages) {
appendStage(pipelineStage);
}
return this;
| 198
| 37
| 235
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/isle-sofa-boot/src/main/java/com/alipay/sofa/boot/isle/stage/ModuleLogOutputStage.java
|
ModuleLogOutputStage
|
logInstalledModules
|
class ModuleLogOutputStage extends AbstractPipelineStage {
private static final Logger LOGGER = SofaBootLoggerFactory
.getLogger(ModuleLogOutputStage.class);
public static final String MODULE_LOG_OUTPUT_STAGE_NAME = "ModuleLogOutputStage";
private static final String SYMBOLIC1 = " ├─";
private static final String SYMBOLIC2 = " └─";
private static final String SYMBOLIC3 = " │ +---";
private static final String SYMBOLIC4 = " │ `---";
private static final String SYMBOLIC5 = " +---";
private static final String SYMBOLIC6 = " `---";
@Override
protected void doProcess() throws Exception {
logInstalledModules();
logFailedModules();
}
protected void logInstalledModules() {<FILL_FUNCTION_BODY>}
protected void logFailedModules() {
List<DeploymentDescriptor> deploys = application.getFailed();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("\n").append("Spring context initialize failed module list")
.append("(").append(deploys.size()).append(") >>>>>>>\n");
for (Iterator<DeploymentDescriptor> i = deploys.iterator(); i.hasNext();) {
DeploymentDescriptor dd = i.next();
String treeSymbol = SYMBOLIC1;
if (!i.hasNext()) {
treeSymbol = SYMBOLIC2;
}
stringBuilder.append(treeSymbol).append(dd.getName()).append("\n");
}
LOGGER.info(stringBuilder.toString());
}
@Override
public String getName() {
return MODULE_LOG_OUTPUT_STAGE_NAME;
}
@Override
public int getOrder() {
return 30000;
}
}
|
List<DeploymentDescriptor> deploys = application.getInstalled();
StringBuilder stringBuilder = new StringBuilder();
long totalTime = 0;
long realStart = 0;
long realEnd = 0;
stringBuilder.append("\n").append("Spring context initialize success module list")
.append("(").append(deploys.size()).append(") >>>>>>>");
StringBuilder sb = new StringBuilder();
for (Iterator<DeploymentDescriptor> i = deploys.iterator(); i.hasNext();) {
DeploymentDescriptor dd = i.next();
String outTreeSymbol = SYMBOLIC1;
String innerTreeSymbol1 = SYMBOLIC3;
String innerTreeSymbol2 = SYMBOLIC4;
if (!i.hasNext()) {
outTreeSymbol = SYMBOLIC2;
innerTreeSymbol1 = SYMBOLIC5;
innerTreeSymbol2 = SYMBOLIC6;
}
sb.append(outTreeSymbol).append(dd.getName()).append(" [").append(dd.getElapsedTime())
.append(" ms]\n");
totalTime += dd.getElapsedTime();
for (Iterator<String> j = dd.getInstalledSpringXml().iterator(); j.hasNext();) {
String xmlPath = j.next();
String innerTreeSymbol = innerTreeSymbol1;
if (!j.hasNext()) {
innerTreeSymbol = innerTreeSymbol2;
}
sb.append(innerTreeSymbol).append(xmlPath).append("\n");
}
if (realStart == 0 || dd.getStartTime() < realStart) {
realStart = dd.getStartTime();
}
if (realEnd == 0 || (dd.getStartTime() + dd.getElapsedTime()) > realEnd) {
realEnd = dd.getStartTime() + dd.getElapsedTime();
}
}
stringBuilder.append(" [totalTime = ").append(totalTime).append(" ms, realTime = ")
.append(realEnd - realStart).append(" ms]\n").append(sb);
LOGGER.info(stringBuilder.toString());
| 503
| 542
| 1,045
|
<methods>public non-sealed void <init>() ,public void afterPropertiesSet() throws java.lang.Exception,public com.alipay.sofa.boot.isle.ApplicationRuntimeModel getApplicationRuntimeModel() ,public void process() throws java.lang.Exception,public void setApplicationContext(org.springframework.context.ApplicationContext) throws org.springframework.beans.BeansException,public void setApplicationRuntimeModel(com.alipay.sofa.boot.isle.ApplicationRuntimeModel) ,public void setBeanFactory(org.springframework.beans.factory.BeanFactory) throws org.springframework.beans.BeansException,public void setStartupReporter(com.alipay.sofa.boot.startup.StartupReporter) throws org.springframework.beans.BeansException<variables>protected final java.lang.ClassLoader appClassLoader,protected com.alipay.sofa.boot.isle.ApplicationRuntimeModel application,protected org.springframework.context.ConfigurableApplicationContext applicationContext,protected com.alipay.sofa.boot.startup.BaseStat baseStat,protected org.springframework.beans.factory.config.ConfigurableListableBeanFactory beanFactory,protected com.alipay.sofa.boot.startup.StartupReporter startupReporter
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/rpc-sofa-boot/src/main/java/com/alipay/sofa/rpc/boot/common/NetworkAddressUtil.java
|
IpRange
|
parseEnd
|
class IpRange {
private long start;
private long end;
public IpRange(String ip) {
start = parseStart(ip);
end = parseEnd(ip);
}
public IpRange(String startIp, String endIp) {
start = parseStart(startIp);
end = parseEnd(endIp);
}
private long parseStart(String ip) {
int[] starts = { 0, 0, 0, 0 };
return parse(starts, ip);
}
private long parseEnd(String ip) {<FILL_FUNCTION_BODY>}
private long parse(int[] segments, String ip) {
String[] ipSegments = ip.split("\\.");
for (int i = 0; i < ipSegments.length; i++) {
segments[i] = Integer.parseInt(ipSegments[i]);
}
long ret = 0;
for (int i : segments) {
ret += ret * 255L + i;
}
return ret;
}
public boolean isEnabled(String ip) {
String[] ipSegments = ip.split("\\.");
long ipInt = 0;
for (String ipSegment : ipSegments) {
ipInt += ipInt * 255L + Integer.parseInt(ipSegment);
}
return ipInt >= start && ipInt <= end;
}
}
|
int[] ends = { 255, 255, 255, 255 };
return parse(ends, ip);
| 367
| 39
| 406
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/rpc-sofa-boot/src/main/java/com/alipay/sofa/rpc/boot/common/RegistryParseUtil.java
|
RegistryParseUtil
|
parseParam
|
class RegistryParseUtil {
/**
* Parse address string.
*
* @param config the config
* @param protocol the protocol
* @return the string
*/
public static String parseAddress(String config, String protocol) {
String address = null;
if (StringUtils.isNotEmpty(config) && config.startsWith(protocol)) {
final String nacosProtocol = protocol + "://";
String value = config.substring(nacosProtocol.length());
if (!value.contains("?")) {
address = value;
} else {
int index = value.lastIndexOf('?');
address = value.substring(0, index);
}
}
return address;
}
/**
* Parse param map.
*
* @param address the address
* @param protocol the protocol
* @return the map
*/
public static Map<String, String> parseParam(String address, String protocol) {<FILL_FUNCTION_BODY>}
/**
* Parse key value map.
*
* @param kv the kv
* @return the map
*/
public static Map<String, String> parseKeyValue(String kv) {
Map<String, String> map = new HashMap<String, String>();
if (StringUtils.isNotEmpty(kv)) {
String[] kvSplit = kv.split("=");
String key = kvSplit[0];
String value = kvSplit[1];
map.put(key, value);
}
return map;
}
}
|
String host = parseAddress(address, protocol);
//for config ?
String paramString = address.substring(address.indexOf(host) + host.length());
if (StringUtils.isNotEmpty(paramString) && paramString.startsWith("?")) {
paramString = paramString.substring(1);
}
Map<String, String> map = new HashMap<String, String>();
if (paramString.contains("&")) {
String[] paramSplit = paramString.split("&");
for (String param : paramSplit) {
Map<String, String> tempMap = parseKeyValue(param);
map.putAll(tempMap);
}
} else {
Map<String, String> tempMap = parseKeyValue(paramString);
map.putAll(tempMap);
}
return map;
| 415
| 216
| 631
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/rpc-sofa-boot/src/main/java/com/alipay/sofa/rpc/boot/common/RpcThreadPoolMonitor.java
|
RpcThreadPoolMonitor
|
start
|
class RpcThreadPoolMonitor {
private static final long DEFAULT_SLEEP_TIME = 30000;
private final Logger logger;
private long sleepTimeMS;
/**
* 线程池
*/
private ThreadPoolExecutor threadPoolExecutor;
/**
* 开启标志
*/
private AtomicInteger startTimes = new AtomicInteger(0);
private volatile boolean active = true;
private Thread monitor;
private String poolName = "";
public RpcThreadPoolMonitor(String loggerName) {
this(null, loggerName, DEFAULT_SLEEP_TIME);
}
public RpcThreadPoolMonitor(final ThreadPoolExecutor threadPoolExecutor, String loggerName) {
this(threadPoolExecutor, loggerName, DEFAULT_SLEEP_TIME);
}
public RpcThreadPoolMonitor(final ThreadPoolExecutor threadPoolExecutor, String loggerName,
long sleepTimeMS) {
this.threadPoolExecutor = threadPoolExecutor;
this.logger = SofaBootRpcLoggerFactory.getLogger(loggerName);
this.sleepTimeMS = sleepTimeMS;
}
/**
* 开启线程池监测
*/
public void start() {<FILL_FUNCTION_BODY>}
public void setThreadPoolExecutor(ThreadPoolExecutor threadPoolExecutor) {
this.threadPoolExecutor = threadPoolExecutor;
}
public void setPoolName(String poolName) {
this.poolName = poolName;
}
public String getPoolName() {
return poolName;
}
public void stop() {
synchronized (this) {
this.active = false;
if (this.monitor != null) {
this.monitor.interrupt();
this.monitor = null;
}
this.threadPoolExecutor = null;
this.startTimes.set(0);
}
}
@VisibleForTesting
public Thread getMonitor() {
return monitor;
}
}
|
synchronized (this) {
if (threadPoolExecutor != null) {
if (startTimes.intValue() == 0) {
if (startTimes.incrementAndGet() == 1) {
StringBuilder sb = new StringBuilder();
sb.append("coreSize:" + threadPoolExecutor.getCorePoolSize() + ",");
sb.append("maxPoolSize:" + threadPoolExecutor.getMaximumPoolSize() + ",");
sb.append("queueRemainingSize:"
+ threadPoolExecutor.getQueue().remainingCapacity() + ",");
sb.append("keepAliveTime:"
+ threadPoolExecutor.getKeepAliveTime(TimeUnit.MILLISECONDS)
+ "\n");
if (logger.isInfoEnabled()) {
logger.info(sb.toString());
}
monitor = new Thread() {
public void run() {
while (active) {
try {
if (logger.isInfoEnabled()) {
StringBuilder sb = new StringBuilder();
int blockQueueSize = threadPoolExecutor.getQueue()
.size();
int activeSize = threadPoolExecutor.getActiveCount();
int poolSize = threadPoolExecutor.getPoolSize();
sb.append("blockQueue:" + blockQueueSize + ", ");
sb.append("active:" + activeSize + ", ");
sb.append("idle:" + (poolSize - activeSize) + ", ");
sb.append("poolSize:" + poolSize);
if (StringUtils.isNotBlank(poolName)) {
sb.append(", poolName: " + poolName);
}
logger.info(sb.toString());
}
} catch (Throwable throwable) {
logger.error("Thread pool monitor error", throwable);
}
try {
sleep(sleepTimeMS);
} catch (InterruptedException e) {
logger
.error("Error happened when the thread pool monitor is sleeping");
}
}
}
};
monitor.setDaemon(true);
monitor.setName("RPC-RES-MONITOR");
monitor.start();
} else {
throw new RuntimeException("rpc started event has been consumed");
}
} else {
throw new RuntimeException("rpc started event has been consumed");
}
} else {
throw new RuntimeException("the rpc thread pool is null");
}
}
| 517
| 593
| 1,110
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/rpc-sofa-boot/src/main/java/com/alipay/sofa/rpc/boot/common/SofaBootRpcSpringUtil.java
|
SofaBootRpcSpringUtil
|
newInstance
|
class SofaBootRpcSpringUtil {
private static final Logger LOGGER = SofaBootRpcLoggerFactory
.getLogger(SofaBootRpcSpringUtil.class);
/**
* 根据配置的ref以及class字符串,获得真正的spring bean
* 先优先获得refBean,再获得class
*
* @param beanRef spring ref
* @param beanClass 简单class配置
* @param applicationContext spring上下文
* @param appClassLoader 业务上下文
* @return 业务bean
*/
public static Object getSpringBean(String beanRef, String beanClass,
ApplicationContext applicationContext,
ClassLoader appClassLoader, String appName) {
Object callbackHandler = null;
callbackHandler = getSpringBean(beanRef, applicationContext, appClassLoader, appName);
if (callbackHandler == null && StringUtils.hasText(beanClass)) {
callbackHandler = newInstance(beanClass, appClassLoader, appName);
}
return callbackHandler;
}
/**
* 根据配置的ref获得真正的spring bean
*
* @param beanRef spring ref
* @param applicationContext spring上下文
* @param appClassLoader 业务上下文
* @return 业务bean
*/
public static Object getSpringBean(String beanRef, ApplicationContext applicationContext,
ClassLoader appClassLoader, String appName) {
Object object = null;
if (StringUtils.hasText(beanRef)) {
if (applicationContext == null) {
LOGGER.error("get bean from spring failed. beanRef[" + beanRef + "];classLoader["
+ appClassLoader + "];appName[" + appName + "]");
} else {
object = applicationContext.getBean(beanRef);
}
}
return object;
}
/**
* 使用指定的classloader实例化某个类
*
* @param clazz 全类名
* @param loader 类加载器
* @return 类实例
*/
public static Object newInstance(String clazz, ClassLoader loader, String appName) {<FILL_FUNCTION_BODY>}
}
|
if (!StringUtils.hasText(clazz)) {
return null;
}
try {
return Class.forName(clazz, true, loader).newInstance();
} catch (Exception e) {
LOGGER.error("new instance failed. clazz[" + clazz + "];classLoader[" + loader
+ "];appName[" + appName + "]", e);
throw new RuntimeException(LogCodes.getLog(
LogCodes.ERROR_PROXY_BINDING_CLASS_CANNOT_FOUND, clazz), e);
}
| 560
| 144
| 704
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/rpc-sofa-boot/src/main/java/com/alipay/sofa/rpc/boot/config/ConsulConfigurator.java
|
ConsulConfigurator
|
parseParam
|
class ConsulConfigurator implements RegistryConfigureProcessor {
public ConsulConfigurator() {
}
/**
* 解析配置 value
*
* @param config 配置 value
*/
public String parseAddress(String config) {
String address = null;
if (StringUtils.isNotEmpty(config)
&& config.startsWith(SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_CONSUL)) {
final String consulProtocol = SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_CONSUL
+ "://";
String value = config.substring(consulProtocol.length());
if (!value.contains("?")) {
address = value;
} else {
int index = value.lastIndexOf('?');
address = value.substring(0, index);
}
}
return address;
}
/**
* 传递原始 url
*
* @param address
* @return
*/
public Map<String, String> parseParam(String address) {<FILL_FUNCTION_BODY>}
private Map<String, String> parseKeyValue(String kv) {
Map<String, String> map = new HashMap<String, String>();
if (StringUtils.isNotEmpty(kv)) {
String[] kvSplit = kv.split("=");
String key = kvSplit[0];
String value = kvSplit[1];
map.put(key, value);
}
return map;
}
@Override
public RegistryConfig buildFromAddress(String address) {
String consulAddress = parseAddress(address);
Map<String, String> map = parseParam(address);
return new RegistryConfig().setAddress(consulAddress)
.setProtocol(SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_CONSUL).setParameters(map);
}
@Override
public String registryType() {
return SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_CONSUL;
}
}
|
String host = parseAddress(address);
//for config ?
String paramString = address.substring(address.indexOf(host) + host.length());
if (StringUtils.isNotEmpty(paramString) && paramString.startsWith("?")) {
paramString = paramString.substring(1);
}
Map<String, String> map = new HashMap<String, String>();
if (paramString.contains("&")) {
String[] paramSplit = paramString.split("&");
for (String param : paramSplit) {
Map<String, String> tempMap = parseKeyValue(param);
map.putAll(tempMap);
}
} else {
Map<String, String> tempMap = parseKeyValue(paramString);
map.putAll(tempMap);
}
return map;
| 544
| 214
| 758
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/rpc-sofa-boot/src/main/java/com/alipay/sofa/rpc/boot/config/FaultToleranceConfigurator.java
|
FaultToleranceConfigurator
|
startFaultTolerance
|
class FaultToleranceConfigurator {
private String appName;
private String regulationEffectiveStr;
private String degradeEffectiveStr;
private String timeWindowStr;
private String leastWindowCountStr;
private String leastWindowExceptionRateMultipleStr;
private String weightDegradeRateStr;
private String weightRecoverRateStr;
private String degradeLeastWeightStr;
private String degradeMaxIpCountStr;
/**
* 解析并生效自动故障剔除配置参数
*/
public void startFaultTolerance() {<FILL_FUNCTION_BODY>}
public void setAppName(String appName) {
this.appName = appName;
}
public void setRegulationEffectiveStr(String regulationEffectiveStr) {
this.regulationEffectiveStr = regulationEffectiveStr;
}
public void setDegradeEffectiveStr(String degradeEffectiveStr) {
this.degradeEffectiveStr = degradeEffectiveStr;
}
public void setTimeWindowStr(String timeWindowStr) {
this.timeWindowStr = timeWindowStr;
}
public void setLeastWindowCountStr(String leastWindowCountStr) {
this.leastWindowCountStr = leastWindowCountStr;
}
public void setLeastWindowExceptionRateMultipleStr(String leastWindowExceptionRateMultipleStr) {
this.leastWindowExceptionRateMultipleStr = leastWindowExceptionRateMultipleStr;
}
public void setWeightDegradeRateStr(String weightDegradeRateStr) {
this.weightDegradeRateStr = weightDegradeRateStr;
}
public void setWeightRecoverRateStr(String weightRecoverRateStr) {
this.weightRecoverRateStr = weightRecoverRateStr;
}
public void setDegradeLeastWeightStr(String degradeLeastWeightStr) {
this.degradeLeastWeightStr = degradeLeastWeightStr;
}
public void setDegradeMaxIpCountStr(String degradeMaxIpCountStr) {
this.degradeMaxIpCountStr = degradeMaxIpCountStr;
}
}
|
Boolean regulationEffective = SofaBootRpcParserUtil.parseBoolean(regulationEffectiveStr);
Boolean degradeEffective = SofaBootRpcParserUtil.parseBoolean(degradeEffectiveStr);
Long timeWindow = SofaBootRpcParserUtil.parseLong(timeWindowStr);
Long leastWindowCount = SofaBootRpcParserUtil.parseLong(leastWindowCountStr);
Double leastWindowExceptionRateMultiple = SofaBootRpcParserUtil
.parseDouble(leastWindowExceptionRateMultipleStr);
Double weightDegradeRate = SofaBootRpcParserUtil.parseDouble(weightDegradeRateStr);
Double weightRecoverRate = SofaBootRpcParserUtil.parseDouble(weightRecoverRateStr);
Integer degradeLeastWeight = SofaBootRpcParserUtil.parseInteger(degradeLeastWeightStr);
Integer degradeMaxIpCount = SofaBootRpcParserUtil.parseInteger(degradeMaxIpCountStr);
FaultToleranceConfig faultToleranceConfig = new FaultToleranceConfig();
if (regulationEffective != null) {
faultToleranceConfig.setRegulationEffective(regulationEffective);
}
if (degradeEffective != null) {
faultToleranceConfig.setDegradeEffective(degradeEffective);
}
if (timeWindow != null) {
faultToleranceConfig.setTimeWindow(timeWindow);
}
if (leastWindowCount != null) {
faultToleranceConfig.setLeastWindowCount(leastWindowCount);
}
if (leastWindowExceptionRateMultiple != null) {
faultToleranceConfig
.setLeastWindowExceptionRateMultiple(leastWindowExceptionRateMultiple);
}
if (weightDegradeRate != null) {
faultToleranceConfig.setWeightDegradeRate(weightDegradeRate);
}
if (weightRecoverRate != null) {
faultToleranceConfig.setWeightRecoverRate(weightRecoverRate);
}
if (degradeLeastWeight != null) {
faultToleranceConfig.setDegradeLeastWeight(degradeLeastWeight);
}
if (degradeMaxIpCount != null) {
faultToleranceConfig.setDegradeMaxIpCount(degradeMaxIpCount);
}
FaultToleranceConfigManager.putAppConfig(appName, faultToleranceConfig);
| 564
| 622
| 1,186
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/rpc-sofa-boot/src/main/java/com/alipay/sofa/rpc/boot/config/KubernetesConfigurator.java
|
KubernetesConfigurator
|
buildFromAddress
|
class KubernetesConfigurator implements RegistryConfigureProcessor {
public KubernetesConfigurator() {
}
@Override
public RegistryConfig buildFromAddress(String address) {<FILL_FUNCTION_BODY>}
@Override
public String registryType() {
return SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_KUBERNETES;
}
}
|
String kubernetesAddress = RegistryParseUtil.parseAddress(address,
SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_KUBERNETES);
Map<String, String> map = RegistryParseUtil.parseParam(address,
SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_KUBERNETES);
return new RegistryConfig().setAddress(kubernetesAddress).setParameters(map)
.setProtocol(SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_KUBERNETES);
| 107
| 145
| 252
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/rpc-sofa-boot/src/main/java/com/alipay/sofa/rpc/boot/config/LocalFileConfigurator.java
|
LocalFileConfigurator
|
buildFromAddress
|
class LocalFileConfigurator implements RegistryConfigureProcessor {
private static String COLON = "://";
public LocalFileConfigurator() {
}
/**
* 读取配置 key ,获取其 value 进行解析。
*/
public String parseConfig(String config) {
String file = null;
if (StringUtils.isNotEmpty(config)
&& config.startsWith(SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_LOCAL)
&& config.length() > SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_LOCAL.length()) {
file = config.substring(SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_LOCAL.length()
+ COLON.length());
}
return file;
}
@Override
public RegistryConfig buildFromAddress(String address) {<FILL_FUNCTION_BODY>}
@Override
public String registryType() {
return SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_LOCAL;
}
}
|
String filePath = parseConfig(address);
if (StringUtils.isEmpty(filePath)) {
filePath = SofaBootRpcConfigConstants.REGISTRY_FILE_PATH_DEFAULT;
}
return new RegistryConfig().setFile(filePath).setProtocol(
SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_LOCAL);
| 283
| 97
| 380
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/rpc-sofa-boot/src/main/java/com/alipay/sofa/rpc/boot/config/MeshConfigurator.java
|
MeshConfigurator
|
buildFromAddress
|
class MeshConfigurator implements RegistryConfigureProcessor {
public static final String HTTP = "http://";
public MeshConfigurator() {
}
@Override
public RegistryConfig buildFromAddress(String address) {<FILL_FUNCTION_BODY>}
@Override
public String registryType() {
return SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_MESH;
}
}
|
String meshAddress = RegistryParseUtil.parseAddress(address,
SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_MESH);
meshAddress = HTTP + meshAddress;
return new RegistryConfig().setAddress(meshAddress).setProtocol(
SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_MESH);
| 116
| 96
| 212
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/rpc-sofa-boot/src/main/java/com/alipay/sofa/rpc/boot/config/MulticastConfigurator.java
|
MulticastConfigurator
|
buildFromAddress
|
class MulticastConfigurator implements RegistryConfigureProcessor {
public MulticastConfigurator() {
}
@Override
public RegistryConfig buildFromAddress(String address) {<FILL_FUNCTION_BODY>}
@Override
public String registryType() {
return SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_MULTICAST;
}
}
|
String multicastAddress = RegistryParseUtil.parseAddress(address,
SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_MULTICAST);
Map<String, String> map = RegistryParseUtil.parseParam(address,
SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_MULTICAST);
return new RegistryConfig().setAddress(multicastAddress)
.setProtocol(SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_MULTICAST).setParameters(map);
| 106
| 142
| 248
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/rpc-sofa-boot/src/main/java/com/alipay/sofa/rpc/boot/config/NacosConfigurator.java
|
NacosConfigurator
|
buildFromAddress
|
class NacosConfigurator implements RegistryConfigureProcessor {
public NacosConfigurator() {
}
@Override
public RegistryConfig buildFromAddress(String address) {<FILL_FUNCTION_BODY>}
@Override
public String registryType() {
return SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_NACOS;
}
}
|
String nacosAddress = RegistryParseUtil.parseAddress(address,
SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_NACOS);
Map<String, String> map = RegistryParseUtil.parseParam(address,
SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_NACOS);
return new RegistryConfig().setAddress(nacosAddress).setParameters(map)
.setProtocol(SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_NACOS);
| 104
| 139
| 243
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/rpc-sofa-boot/src/main/java/com/alipay/sofa/rpc/boot/config/PolarisRegistryConfigurator.java
|
PolarisRegistryConfigurator
|
buildFromAddress
|
class PolarisRegistryConfigurator implements RegistryConfigureProcessor {
public PolarisRegistryConfigurator() {
}
@Override
public RegistryConfig buildFromAddress(String address) {<FILL_FUNCTION_BODY>}
@Override
public String registryType() {
return SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_POLARIS;
}
}
|
String polarisAddress = RegistryParseUtil.parseAddress(address,
SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_POLARIS);
Map<String, String> map = RegistryParseUtil.parseParam(address,
SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_POLARIS);
return new RegistryConfig().setAddress(polarisAddress).setParameters(map)
.setProtocol(SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_POLARIS);
| 105
| 140
| 245
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/rpc-sofa-boot/src/main/java/com/alipay/sofa/rpc/boot/config/SofaRegistryConfigurator.java
|
SofaRegistryConfigurator
|
buildFromAddress
|
class SofaRegistryConfigurator implements RegistryConfigureProcessor {
public SofaRegistryConfigurator() {
}
@Override
public RegistryConfig buildFromAddress(String address) {<FILL_FUNCTION_BODY>}
@Override
public String registryType() {
return SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_SOFA;
}
}
|
String sofaRegistryAddress = RegistryParseUtil.parseAddress(address,
SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_SOFA);
Map<String, String> map = RegistryParseUtil.parseParam(address,
SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_SOFA);
return new RegistryConfig().setAddress(sofaRegistryAddress)
.setProtocol(SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_SOFA).setParameters(map);
| 105
| 135
| 240
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.