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-boot
sofa-boot/sofa-boot-project/sofa-boot-core/rpc-sofa-boot/src/main/java/com/alipay/sofa/rpc/boot/config/ZookeeperConfigurator.java
ZookeeperConfigurator
buildFromAddress
class ZookeeperConfigurator implements RegistryConfigureProcessor { public ZookeeperConfigurator() { } @Override public RegistryConfig buildFromAddress(String address) {<FILL_FUNCTION_BODY>} @Override public String registryType() { return SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_ZOOKEEPER; } }
String zkAddress = RegistryParseUtil.parseAddress(address, SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_ZOOKEEPER); Map<String, String> map = RegistryParseUtil.parseParam(address, SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_ZOOKEEPER); String file = map.get("file"); if (StringUtils.isEmpty(file)) { file = SofaBootRpcConfigConstants.REGISTRY_FILE_PATH_DEFAULT; } return new RegistryConfig().setAddress(zkAddress).setFile(file) .setProtocol(SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_ZOOKEEPER).setParameters(map);
108
200
308
<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/container/ConsumerConfigContainer.java
ConsumerConfigContainer
removeAndUnReferConsumerConfig
class ConsumerConfigContainer { /** * ConsumerConfig 缓存 */ private final ConcurrentMap<Binding, ConsumerConfig> consumerConfigMap = new ConcurrentHashMap<>(); /** * 增加 ConsumerConfig * * @param binding the {@link Binding} * @param consumerConfig consumerConfigs */ public void addConsumerConfig(Binding binding, ConsumerConfig consumerConfig) { if (binding != null) { consumerConfigMap.put(binding, consumerConfig); } } /** * 移除对应的 ConsumerConfig,并进行unRefer。 * * @param binding the {@link Binding} */ public void removeAndUnReferConsumerConfig(Binding binding) {<FILL_FUNCTION_BODY>} public ConcurrentMap<Binding, ConsumerConfig> getConsumerConfigMap() { return consumerConfigMap; } }
if (binding != null) { ConsumerConfig consumerConfig = consumerConfigMap.remove(binding); if (consumerConfig != null) { consumerConfig.unRefer(); } }
237
56
293
<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/container/RegistryConfigContainer.java
RegistryConfigContainer
getRegistryConfig
class RegistryConfigContainer { private static final String DEFAULT_REGISTRY = "DEFAULT"; private Map<String, RegistryConfigureProcessor> registryConfigMap; /** * for cache */ private final Map<String, RegistryConfig> registryConfigs = new ConcurrentHashMap<String, RegistryConfig>(); /** * for custom extends */ private final String customDefaultRegistry; /** * for default address for customDefaultRegistry */ private String customDefaultRegistryAddress; private Map<String, String> registries = new HashMap<>(); private String defaultRegistryAddress; private String meshConfig; private boolean ignoreRegistry; public RegistryConfigContainer(Map<String, RegistryConfigureProcessor> registryConfigMap) { this.registryConfigMap = registryConfigMap; customDefaultRegistry = SofaConfigs.getOrDefault(SofaBootRpcConfigKeys.DEFAULT_REGISTRY); if (StringUtils.isNotBlank(customDefaultRegistry)) { customDefaultRegistryAddress = System.getProperty(customDefaultRegistry); } } /** * @param registryAlias * @return * @throws SofaBootRpcRuntimeException */ public RegistryConfig getRegistryConfig(String registryAlias) throws SofaBootRpcRuntimeException {<FILL_FUNCTION_BODY>} /** * 获取 RegistryConfig * * @return the RegistryConfig * @throws SofaBootRpcRuntimeException SofaBoot运行时异常 */ public RegistryConfig getRegistryConfig() throws SofaBootRpcRuntimeException { if (StringUtils.isNotBlank(customDefaultRegistry)) { return getRegistryConfig(customDefaultRegistry); } else { return getRegistryConfig(DEFAULT_REGISTRY); } } /** * 移除所有 RegistryConfig */ public void removeAllRegistryConfig() { registryConfigMap.clear(); } public Map<String, RegistryConfigureProcessor> getRegistryConfigMap() { return registryConfigMap; } public void setRegistryConfigMap(Map<String, RegistryConfigureProcessor> registryConfigMap) { this.registryConfigMap = registryConfigMap; } public Map<String, RegistryConfig> getRegistryConfigs() { return registryConfigs; } /** * protocol can be meshed * * @param protocol * @return */ public boolean isMeshEnabled(String protocol) { if (StringUtils.isNotBlank(meshConfig) && registries != null && registries.get(SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_MESH) != null) { if (meshConfig.equalsIgnoreCase(SofaBootRpcConfigConstants.ENABLE_MESH_ALL)) { return true; } else { List<String> meshEnableProtocols = Arrays.asList(meshConfig.split(",")); for (String meshProtocol : meshEnableProtocols) { if (StringUtils.equals(meshProtocol, protocol)) { return true; } } return false; } } else { return false; } } public void setRegistries(Map<String, String> registries) { this.registries = registries; } public void setDefaultRegistryAddress(String defaultRegistryAddress) { this.defaultRegistryAddress = defaultRegistryAddress; } public void setMeshConfig(String meshConfig) { this.meshConfig = meshConfig; } public void setIgnoreRegistry(boolean ignoreRegistry) { this.ignoreRegistry = ignoreRegistry; } }
RegistryConfig registryConfig; String registryProtocol; String registryAddress; String currentDefaultAlias; if (StringUtils.isNotBlank(customDefaultRegistry)) { currentDefaultAlias = customDefaultRegistry; } else { currentDefaultAlias = DEFAULT_REGISTRY; } if (StringUtils.isEmpty(registryAlias)) { registryAlias = currentDefaultAlias; } //cloud be mesh,default,zk if (registryConfigs.get(registryAlias) != null) { return registryConfigs.get(registryAlias); } // just for new address if (DEFAULT_REGISTRY.equalsIgnoreCase(registryAlias)) { registryAddress = defaultRegistryAddress; } else if (registryAlias.equals(customDefaultRegistry)) { registryAddress = customDefaultRegistryAddress; } else { registryAddress = registries.get(registryAlias); } //for worst condition. if (StringUtils.isBlank(registryAddress)) { registryProtocol = SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_LOCAL; } else { final int endIndex = registryAddress.indexOf("://"); if (endIndex != -1) { registryProtocol = registryAddress.substring(0, endIndex); } else { registryProtocol = registryAlias; } } if (registryConfigMap.get(registryProtocol) != null) { RegistryConfigureProcessor registryConfigureProcessor = registryConfigMap .get(registryProtocol); registryConfig = registryConfigureProcessor.buildFromAddress(registryAddress); registryConfigs.put(registryAlias, registryConfig); //不再处理以.分隔的. if (ignoreRegistry) { registryConfig.setRegister(false); } return registryConfig; } else { throw new SofaBootRpcRuntimeException(LogCodes.getLog( LogCodes.ERROR_REGISTRY_NOT_SUPPORT, registryAddress)); }
976
537
1,513
<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/container/RpcFilterContainer.java
RpcFilterContainer
loadFilters
class RpcFilterContainer { private List<String> filterIds = new CopyOnWriteArrayList<String>(); private List<String> filterClasses = new CopyOnWriteArrayList<String>(); private boolean alreadyLoad = false; private final Object LOAD_LOCK = new Object(); private List<Filter> filters = new CopyOnWriteArrayList<Filter>(); private static final RpcFilterContainer INSTANCE = new RpcFilterContainer(); public static RpcFilterContainer getInstance() { return INSTANCE; } /** * 增加 Filter id * * @param filterId id */ public void addFilterId(String filterId) { if (StringUtils.hasText(filterId)) { filterIds.add(filterId); } } /** * 增加 Filter 实例 * * @param filterClass 实例 */ public void addFilterClass(String filterClass) { if (StringUtils.hasText(filterClass)) { filterClasses.add(filterClass); } } /** * 获取所有的 Filter 实例 * * @param applicationContext Spring 上下文 * @return 所有的 Filter 实例 */ public List<Filter> getFilters(ApplicationContext applicationContext) { if (applicationContext != null) { if (!alreadyLoad) { synchronized (LOAD_LOCK) { if (!alreadyLoad) { loadFilters(applicationContext); alreadyLoad = true; } } } return filters; } else { throw new SofaBootRpcRuntimeException("The applicationContext should not be null"); } } /** * 加载并持有所有的 Filter id 或实例 * * @param applicationContext Spring 上下文 */ private void loadFilters(ApplicationContext applicationContext) {<FILL_FUNCTION_BODY>} }
for (String filterId : filterIds) { filters.add((applicationContext.getBean(filterId, Filter.class))); } for (String clazz : filterClasses) { Class filterClass; try { filterClass = Class.forName(clazz); } catch (ClassNotFoundException e) { throw new SofaBootRpcRuntimeException("Can not find filter class " + clazz + " ", e); } if (Filter.class.isAssignableFrom(filterClass)) { try { filters.add((Filter) filterClass.newInstance()); } catch (Exception e) { throw new SofaBootRpcRuntimeException("Error happen when create instance of " + filterClass + " ", e); } } else { throw new SofaBootRpcRuntimeException("The class of " + clazz + " should be a subclass of Filter"); } }
506
236
742
<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/context/RpcEnvironmentApplicationListener.java
RpcEnvironmentApplicationListener
onApplicationEvent
class RpcEnvironmentApplicationListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> { @Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {<FILL_FUNCTION_BODY>} }
Environment env = event.getEnvironment(); String defaultTracer = env.getProperty("sofa.boot.rpc.defaultTracer"); if (defaultTracer != null) { RpcConfigs.putValue(RpcOptions.DEFAULT_TRACER, defaultTracer); }
61
76
137
<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/context/RpcStartApplicationListener.java
RpcStartApplicationListener
publishRpcStartEvent
class RpcStartApplicationListener implements ApplicationContextAware, ApplicationListener<ContextRefreshedEvent>, Ordered { private final AtomicBoolean published = new AtomicBoolean(false); private final AtomicBoolean success = new AtomicBoolean(false); private ApplicationContext applicationContext; private boolean enableAutoPublish; @Override public void onApplicationEvent(ContextRefreshedEvent event) { if (applicationContext.equals(event.getApplicationContext()) && enableAutoPublish) { publishRpcStartEvent(); } } public void publishRpcStartEvent() {<FILL_FUNCTION_BODY>} public boolean isSuccess() { return success.get(); } public boolean isEnableAutoPublish() { return enableAutoPublish; } public void setEnableAutoPublish(boolean enableAutoPublish) { this.enableAutoPublish = enableAutoPublish; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @Override public int getOrder() { // must after ReadinessCheckListener return LOWEST_PRECEDENCE; } }
if (published.compareAndSet(false, true)) { //rpc 开始启动事件监听器 applicationContext.publishEvent(new SofaBootRpcStartEvent(applicationContext)); //rpc 启动完毕事件监听器 applicationContext.publishEvent(new SofaBootRpcStartAfterEvent(applicationContext)); success.compareAndSet(false, true); }
316
103
419
<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/context/RpcStopApplicationListener.java
RpcStopApplicationListener
onApplicationEvent
class RpcStopApplicationListener implements ApplicationListener, ApplicationContextAware { private final ProviderConfigContainer providerConfigContainer; private final ServerConfigContainer serverConfigContainer; private ApplicationContext applicationContext; public RpcStopApplicationListener(ProviderConfigContainer providerConfigContainer, ServerConfigContainer serverConfigContainer) { this.providerConfigContainer = providerConfigContainer; this.serverConfigContainer = serverConfigContainer; } @Override public void onApplicationEvent(ApplicationEvent event) {<FILL_FUNCTION_BODY>} @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } }
if ((event instanceof ContextClosedEvent) || (event instanceof ContextStoppedEvent)) { if (applicationContext .equals(((ApplicationContextEvent) event).getApplicationContext())) { providerConfigContainer.unExportAllProviderConfig(); serverConfigContainer.closeAllServer(); } }
174
75
249
<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/context/SofaBootRpcStartListener.java
SofaBootRpcStartListener
onApplicationEvent
class SofaBootRpcStartListener implements ApplicationListener<SofaBootRpcStartEvent> { protected final ProviderConfigContainer providerConfigContainer; protected final FaultToleranceConfigurator faultToleranceConfigurator; protected final ServerConfigContainer serverConfigContainer; protected final RegistryConfigContainer registryConfigContainer; private String lookoutCollectDisable; public SofaBootRpcStartListener(ProviderConfigContainer providerConfigContainer, FaultToleranceConfigurator faultToleranceConfigurator, ServerConfigContainer serverConfigContainer, RegistryConfigContainer registryConfigContainer) { this.providerConfigContainer = providerConfigContainer; this.faultToleranceConfigurator = faultToleranceConfigurator; this.serverConfigContainer = serverConfigContainer; this.registryConfigContainer = registryConfigContainer; } @Override public void onApplicationEvent(SofaBootRpcStartEvent event) {<FILL_FUNCTION_BODY>} protected void processExtra(SofaBootRpcStartEvent event) { } protected void disableLookout() { Boolean disable = SofaBootRpcParserUtil.parseBoolean(lookoutCollectDisable); if (disable != null) { LookoutSubscriber.setLookoutCollectDisable(disable); } } public void setLookoutCollectDisable(String lookoutCollectDisable) { this.lookoutCollectDisable = lookoutCollectDisable; } }
//choose disable metrics lookout disableLookout(); //extra info processExtra(event); //start fault tolerance if (faultToleranceConfigurator != null) { faultToleranceConfigurator.startFaultTolerance(); } Collection<ProviderConfig> allProviderConfig = providerConfigContainer .getAllProviderConfig(); if (!CollectionUtils.isEmpty(allProviderConfig)) { //start server serverConfigContainer.startServers(); } //set allow all publish providerConfigContainer.setAllowPublish(true); //register registry providerConfigContainer.publishAllProviderConfig(); //export dubbo providerConfigContainer.exportAllDubboProvideConfig();
384
190
574
<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/log/SofaBootRpcLoggerFactory.java
SofaBootRpcLoggerFactory
getLogger
class SofaBootRpcLoggerFactory { /** * 日志命名空间。对应的日志路径配置 com/alipay/sofa/rpc/boot/log */ public static final String RPC_LOG_SPACE = "com.alipay.sofa.rpc.boot"; /** * 获取Logger * @param clazz the clazz * @return ths Logger */ public static org.slf4j.Logger getLogger(Class<?> clazz) {<FILL_FUNCTION_BODY>} /** * 获取Logger * @param name the name * @return the Logger */ public static org.slf4j.Logger getLogger(String name) { if (name == null || name.isEmpty()) { return null; } return LoggerSpaceManager.getLoggerBySpace(name, RPC_LOG_SPACE); } }
if (clazz == null) { return null; } return getLogger(clazz.getCanonicalName());
244
35
279
<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/runtime/adapter/DubboBindingAdapter.java
DubboBindingAdapter
postUnoutBinding
class DubboBindingAdapter extends RpcBindingAdapter { @Override public BindingType getBindingType() { return RpcBindingType.DUBBO_BINDING_TYPE; } @Override public Object outBinding(Object contract, RpcBinding binding, Object target, SofaRuntimeContext sofaRuntimeContext) { return Boolean.TRUE; } @Override public void postUnoutBinding(Object contract, RpcBinding binding, Object target, SofaRuntimeContext sofaRuntimeContext) {<FILL_FUNCTION_BODY>} }
try { ApplicationContext applicationContext = sofaRuntimeContext.getSofaRuntimeManager() .getRootApplicationContext(); ProviderConfigContainer providerConfigContainer = applicationContext .getBean(ProviderConfigContainer.class); String key = providerConfigContainer.createUniqueName((Contract) contract, binding); providerConfigContainer.removeProviderConfig(key); } catch (Exception e) { throw new ServiceRuntimeException( LogCodes.getLog(LogCodes.ERROR_PROXY_POST_UNPUBLISH_FAIL), e); }
145
139
284
<methods>public non-sealed void <init>() ,public Class<com.alipay.sofa.rpc.boot.runtime.binding.RpcBinding> getBindingClass() ,public java.lang.Object inBinding(java.lang.Object, com.alipay.sofa.rpc.boot.runtime.binding.RpcBinding, com.alipay.sofa.runtime.spi.component.SofaRuntimeContext) ,public java.lang.Object outBinding(java.lang.Object, com.alipay.sofa.rpc.boot.runtime.binding.RpcBinding, java.lang.Object, com.alipay.sofa.runtime.spi.component.SofaRuntimeContext) ,public void postUnoutBinding(java.lang.Object, com.alipay.sofa.rpc.boot.runtime.binding.RpcBinding, java.lang.Object, com.alipay.sofa.runtime.spi.component.SofaRuntimeContext) ,public void preOutBinding(java.lang.Object, com.alipay.sofa.rpc.boot.runtime.binding.RpcBinding, java.lang.Object, com.alipay.sofa.runtime.spi.component.SofaRuntimeContext) ,public void preUnoutBinding(java.lang.Object, com.alipay.sofa.rpc.boot.runtime.binding.RpcBinding, java.lang.Object, com.alipay.sofa.runtime.spi.component.SofaRuntimeContext) ,public void unInBinding(java.lang.Object, com.alipay.sofa.rpc.boot.runtime.binding.RpcBinding, com.alipay.sofa.runtime.spi.component.SofaRuntimeContext) <variables>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/rpc-sofa-boot/src/main/java/com/alipay/sofa/rpc/boot/runtime/adapter/RpcBindingAdapter.java
RpcBindingAdapter
preOutBinding
class RpcBindingAdapter implements BindingAdapter<RpcBinding> { /** * pre out binding * * @param contract binding contract * @param binding binding object * @param target binding target * @param sofaRuntimeContext sofa runtime context */ @Override public void preOutBinding(Object contract, RpcBinding binding, Object target, SofaRuntimeContext sofaRuntimeContext) {<FILL_FUNCTION_BODY>} /** * out binding, out binding means provide service * * @param contract binding contract * @param binding binding object * @param target binding target * @param sofaRuntimeContext sofa runtime context * @return binding result */ @Override public Object outBinding(Object contract, RpcBinding binding, Object target, SofaRuntimeContext sofaRuntimeContext) { ApplicationContext applicationContext = sofaRuntimeContext.getSofaRuntimeManager() .getRootApplicationContext(); ProviderConfigContainer providerConfigContainer = applicationContext .getBean(ProviderConfigContainer.class); ProcessorContainer processorContainer = applicationContext .getBean(ProcessorContainer.class); String uniqueName = providerConfigContainer.createUniqueName((Contract) contract, binding); ProviderConfig providerConfig = providerConfigContainer.getProviderConfig(uniqueName); processorContainer.processorProvider(providerConfig); if (providerConfig == null) { throw new ServiceRuntimeException(LogCodes.getLog( LogCodes.INFO_SERVICE_METADATA_IS_NULL, uniqueName)); } try { providerConfig.export(); } catch (Exception e) { throw new ServiceRuntimeException(LogCodes.getLog(LogCodes.ERROR_PROXY_PUBLISH_FAIL), e); } if (providerConfigContainer.isAllowPublish()) { providerConfig.setRegister(true); List<RegistryConfig> registrys = providerConfig.getRegistry(); for (RegistryConfig registryConfig : registrys) { Registry registry = RegistryFactory.getRegistry(registryConfig); registry.init(); registry.start(); registry.register(providerConfig); } } return Boolean.TRUE; } /** * pre unout binding * * @param contract binding contract * @param binding binding object * @param target binding target * @param sofaRuntimeContext sofa runtime context */ @Override public void preUnoutBinding(Object contract, RpcBinding binding, Object target, SofaRuntimeContext sofaRuntimeContext) { ApplicationContext applicationContext = sofaRuntimeContext.getSofaRuntimeManager() .getRootApplicationContext(); ProviderConfigContainer providerConfigContainer = applicationContext .getBean(ProviderConfigContainer.class); String key = providerConfigContainer.createUniqueName((Contract) contract, binding); ProviderConfig providerConfig = providerConfigContainer.getProviderConfig(key); try { providerConfig.unExport(); } catch (Exception e) { throw new ServiceRuntimeException( LogCodes.getLog(LogCodes.ERROR_PROXY_PRE_UNPUBLISH_FAIL), e); } } /** * post unout binding * * @param contract binding contract * @param binding binding object * @param target binding target * @param sofaRuntimeContext sofa runtime context */ @Override public void postUnoutBinding(Object contract, RpcBinding binding, Object target, SofaRuntimeContext sofaRuntimeContext) { ApplicationContext applicationContext = sofaRuntimeContext.getSofaRuntimeManager() .getRootApplicationContext(); ProviderConfigContainer providerConfigContainer = applicationContext .getBean(ProviderConfigContainer.class); String key = providerConfigContainer.createUniqueName((Contract) contract, binding); try { providerConfigContainer.removeProviderConfig(key); } catch (Exception e) { throw new ServiceRuntimeException( LogCodes.getLog(LogCodes.ERROR_PROXY_POST_UNPUBLISH_FAIL), e); } } /** * in binding, in binding means reference service * * @param contract binding contract * @param binding binding object * @param sofaRuntimeContext sofa runtime context */ @Override public Object inBinding(Object contract, RpcBinding binding, SofaRuntimeContext sofaRuntimeContext) { ApplicationContext applicationContext = sofaRuntimeContext.getSofaRuntimeManager() .getRootApplicationContext(); ConsumerConfigHelper consumerConfigHelper = applicationContext .getBean(ConsumerConfigHelper.class); ConsumerConfigContainer consumerConfigContainer = applicationContext .getBean(ConsumerConfigContainer.class); ProcessorContainer processorContainer = applicationContext .getBean(ProcessorContainer.class); ConsumerConfig consumerConfig = consumerConfigHelper.getConsumerConfig((Contract) contract, binding); processorContainer.processorConsumer(consumerConfig); if (MockMode.LOCAL.equalsIgnoreCase(binding.getRpcBindingParam().getMockMode())) { consumerConfig.setMockRef(consumerConfigHelper.getMockRef(binding, applicationContext)); } consumerConfigContainer.addConsumerConfig(binding, consumerConfig); try { Object result = consumerConfig.refer(); binding.setConsumerConfig(consumerConfig); return result; } catch (Exception e) { throw new ServiceRuntimeException(LogCodes.getLog(LogCodes.ERROR_PROXY_CONSUME_FAIL), e); } } /** * undo in binding * * @param contract * @param binding * @param sofaRuntimeContext */ @Override public void unInBinding(Object contract, RpcBinding binding, SofaRuntimeContext sofaRuntimeContext) { try { ApplicationContext applicationContext = sofaRuntimeContext.getSofaRuntimeManager() .getRootApplicationContext(); ConsumerConfigContainer consumerConfigContainer = applicationContext .getBean(ConsumerConfigContainer.class); consumerConfigContainer.removeAndUnReferConsumerConfig(binding); } catch (Exception e) { throw new ServiceRuntimeException(LogCodes.getLog(LogCodes.ERROR_PROXY_UNCOSUME_FAIL), e); } } /** * get binding class * * @return binding class */ @Override public Class<RpcBinding> getBindingClass() { return RpcBinding.class; } }
ApplicationContext applicationContext = sofaRuntimeContext.getSofaRuntimeManager() .getRootApplicationContext(); ProviderConfigContainer providerConfigContainer = applicationContext .getBean(ProviderConfigContainer.class); String uniqueName = providerConfigContainer.createUniqueName((Contract) contract, binding); ProviderConfigHelper providerConfigHelper = applicationContext .getBean(ProviderConfigHelper.class); ProviderConfig providerConfig = providerConfigHelper.getProviderConfig((Contract) contract, binding, target); try { providerConfigContainer.addProviderConfig(uniqueName, providerConfig); } catch (Exception e) { throw new ServiceRuntimeException(LogCodes.getLog(LogCodes.ERROR_PROXY_PUBLISH_FAIL), e); }
1,648
190
1,838
<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/runtime/adapter/helper/ConsumerConfigHelper.java
ConsumerConfigHelper
getConsumerConfig
class ConsumerConfigHelper { private final RegistryConfigContainer registryConfigContainer; private final String appName; private String referenceLimit; private String hystrixEnable; public ConsumerConfigHelper(RegistryConfigContainer registryConfigContainer, String appName) { this.registryConfigContainer = registryConfigContainer; this.appName = appName; } /** * 获取 ConsumerConfig * * @param contract the Contract * @param binding the RpcBinding * @return the ConsumerConfig */ public ConsumerConfig getConsumerConfig(Contract contract, RpcBinding binding) {<FILL_FUNCTION_BODY>} private List<MethodConfig> convertToMethodConfig(List<RpcBindingMethodInfo> methodInfos) { List<MethodConfig> methodConfigs = new ArrayList<MethodConfig>(); if (!CollectionUtils.isEmpty(methodInfos)) { for (RpcBindingMethodInfo info : methodInfos) { String name = info.getName(); Integer timeout = info.getTimeout(); Integer retries = info.getRetries(); String type = info.getType(); Object callbackHandler = info.getCallbackHandler(); MethodConfig methodConfig = new MethodConfig(); methodConfig.setName(name); if (timeout != null) { methodConfig.setTimeout(timeout); } if (retries != null) { methodConfig.setRetries(retries); } if (StringUtils.hasText(type)) { methodConfig.setInvokeType(type); } if (callbackHandler != null) { if (callbackHandler instanceof SofaResponseCallback) { methodConfig.setOnReturn((SofaResponseCallback) callbackHandler); } else { throw new SofaBootRpcRuntimeException( "callback handler must implement SofaResponseCallback [" + callbackHandler + "]"); } } methodConfigs.add(methodConfig); } } return methodConfigs; } public Object getMockRef(RpcBinding binding, ApplicationContext applicationContext) { RpcBindingParam rpcBindingParam = binding.getRpcBindingParam(); String mockBean = rpcBindingParam.getMockBean(); if (StringUtils.hasText(mockBean)) { return applicationContext.getBean(mockBean); } else { throw new IllegalArgumentException("Mock mode is open, mock bean can't be empty."); } } public void setReferenceLimit(String referenceLimit) { this.referenceLimit = referenceLimit; } public void setHystrixEnable(String hystrixEnable) { this.hystrixEnable = hystrixEnable; } }
RpcBindingParam param = binding.getRpcBindingParam(); String id = binding.getBeanId(); String interfaceId = contract.getInterfaceType().getName(); String uniqueId = contract.getUniqueId(); Integer timeout = param.getTimeout(); Integer retries = param.getRetries(); String type = param.getType(); Integer addressWaitTime = param.getAddressWaitTime(); Object callbackHandler = param.getCallbackHandler(); String genericInterface = param.getGenericInterface(); String loadBalancer = param.getLoadBalancer(); Integer connectionNum = param.getConnectionNum(); Boolean lazy = param.getLazy(); Boolean check = param.getCheck(); String mockMode = param.getMockMode(); String serialization = param.getSerialization(); List<Filter> filters = param.getFilters(); List<MethodConfig> methodConfigs = convertToMethodConfig(param.getMethodInfos()); String targetUrl = param.getTargetUrl(); ConsumerConfig consumerConfig = new ConsumerConfig(); if (StringUtils.hasText(appName)) { consumerConfig.setApplication(new ApplicationConfig().setAppName(appName)); } if (StringUtils.hasText(id)) { consumerConfig.setId(id); } if (StringUtils.hasText(genericInterface)) { consumerConfig.setGeneric(true); consumerConfig.setInterfaceId(genericInterface); } else if (StringUtils.hasText(interfaceId)) { consumerConfig.setInterfaceId(interfaceId); } if (StringUtils.hasText(uniqueId)) { consumerConfig.setUniqueId(uniqueId); } if (timeout != null) { consumerConfig.setTimeout(timeout); } if (retries != null) { consumerConfig.setRetries(retries); } if (StringUtils.hasText(type)) { consumerConfig.setInvokeType(type); } if (addressWaitTime != null) { consumerConfig.setAddressWait(addressWaitTime); } if (StringUtils.hasText(loadBalancer)) { consumerConfig.setLoadBalancer(loadBalancer); } if (connectionNum != null) { consumerConfig.setConnectionNum(connectionNum); } if (lazy != null) { consumerConfig.setLazy(lazy); } if (check != null) { consumerConfig.setCheck(check); } if (mockMode != null) { consumerConfig.setMockMode(mockMode); } if (callbackHandler != null) { if (callbackHandler instanceof SofaResponseCallback) { consumerConfig.setOnReturn((SofaResponseCallback) callbackHandler); } else { throw new SofaBootRpcRuntimeException( "callback handler must implement SofaResponseCallback [" + callbackHandler + "]"); } } if (!CollectionUtils.isEmpty(filters)) { consumerConfig.setFilterRef(filters); } if (!CollectionUtils.isEmpty(methodConfigs)) { consumerConfig.setMethods(methodConfigs); } if (StringUtils.hasText(targetUrl)) { consumerConfig.setDirectUrl(targetUrl); consumerConfig.setLazy(true); consumerConfig.setSubscribe(false); consumerConfig.setRegister(false); } if (StringUtils.hasText(referenceLimit)) { consumerConfig.setRepeatedReferLimit(Integer.valueOf(referenceLimit)); } String protocol = binding.getBindingType().getType(); consumerConfig.setBootstrap(protocol); if (protocol.equals(SofaBootRpcConfigConstants.RPC_PROTOCOL_DUBBO)) { consumerConfig.setInJVM(false); } if (param.getRegistrys() != null && param.getRegistrys().size() > 0) { List<String> registrys = param.getRegistrys(); for (String registryAlias : registrys) { RegistryConfig registryConfig = registryConfigContainer .getRegistryConfig(registryAlias); consumerConfig.setRegistry(registryConfig); } } else if (registryConfigContainer.isMeshEnabled(protocol)) { RegistryConfig registryConfig = registryConfigContainer .getRegistryConfig(SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_MESH); consumerConfig.setRegistry(registryConfig); } else { RegistryConfig registryConfig = registryConfigContainer.getRegistryConfig(); consumerConfig.setRegistry(registryConfig); } if (StringUtils.hasText(serialization)) { consumerConfig.setSerialization(serialization); } if (Boolean.TRUE.toString().equals(hystrixEnable)) { consumerConfig.setParameter(HystrixConstants.SOFA_HYSTRIX_ENABLED, Boolean.TRUE.toString()); } // after sofaBootRpcProperties#getHystrixEnable for override global config if (param.getParameters() != null) { consumerConfig.setParameters(param.getParameters()); } return consumerConfig.setProtocol(protocol);
699
1,325
2,024
<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/runtime/adapter/helper/ProviderConfigHelper.java
ProviderConfigHelper
getProviderConfig
class ProviderConfigHelper { private final ServerConfigContainer serverConfigContainer; private final RegistryConfigContainer registryConfigContainer; private final String appName; public ProviderConfigHelper(ServerConfigContainer serverConfigContainer, RegistryConfigContainer registryConfigContainer, String appName) { this.serverConfigContainer = serverConfigContainer; this.registryConfigContainer = registryConfigContainer; this.appName = appName; } /** * 获取 ProviderConfig * * @param contract the Contract * @param binding the RpcBinding * @param target 服务实例 * @return the ProviderConfig * @throws SofaBootRpcRuntimeException */ public ProviderConfig getProviderConfig(Contract contract, RpcBinding binding, Object target) throws SofaBootRpcRuntimeException {<FILL_FUNCTION_BODY>} private List<MethodConfig> convertToMethodConfig(List<RpcBindingMethodInfo> methodInfos) { List<MethodConfig> methodConfigs = new ArrayList<MethodConfig>(); if (!CollectionUtils.isEmpty(methodInfos)) { for (RpcBindingMethodInfo info : methodInfos) { String name = info.getName(); Integer timeout = info.getTimeout(); MethodConfig methodConfig = new MethodConfig(); methodConfig.setName(name); if (timeout != null) { methodConfig.setTimeout(timeout); } methodConfigs.add(methodConfig); } } return methodConfigs; } }
RpcBindingParam param = binding.getRpcBindingParam(); String id = binding.getBeanId(); String interfaceId = contract.getInterfaceType().getName(); Object ref = target; String uniqueId = contract.getUniqueId(); Integer timeout = param.getTimeout(); Integer weight = param.getWeight(); Integer warmupTime = param.getWarmUpTime(); Integer warmupWeight = param.getWarmUpWeight(); UserThreadPool threadPool = param.getUserThreadPool(); String serialization = param.getSerialization(); List<Filter> filters = param.getFilters(); List<MethodConfig> methodConfigs = convertToMethodConfig(param.getMethodInfos()); ServerConfig serverConfig = serverConfigContainer.getServerConfig(binding.getBindingType() .getType()); ProviderConfig providerConfig = new ProviderConfig(); if (StringUtils.hasText(appName)) { providerConfig.setApplication(new ApplicationConfig().setAppName(appName)); } if (StringUtils.hasText(id)) { providerConfig.setId(id); } if (StringUtils.hasText(interfaceId)) { providerConfig.setInterfaceId(interfaceId); } if (contract.getInterfaceType() != null) { providerConfig.setProxyClass(contract.getInterfaceType()); } if (ref != null) { providerConfig.setRef(ref); } if (StringUtils.hasText(uniqueId)) { providerConfig.setUniqueId(uniqueId); } if (timeout != null) { providerConfig.setTimeout(timeout); } if (weight != null) { providerConfig.setWeight(weight); } if (warmupTime != null) { providerConfig.setParameter(ProviderInfoAttrs.ATTR_WARMUP_TIME, String.valueOf(warmupTime)); } if (warmupWeight != null) { providerConfig.setParameter(ProviderInfoAttrs.ATTR_WARMUP_WEIGHT, String.valueOf(warmupWeight)); } if (!CollectionUtils.isEmpty(filters)) { providerConfig.setFilterRef(filters); } if (!CollectionUtils.isEmpty(methodConfigs)) { providerConfig.setMethods(methodConfigs); } if (threadPool != null) { UserThreadPoolManager.registerUserThread( ConfigUniqueNameGenerator.getUniqueName(providerConfig), threadPool); } providerConfig.setServer(serverConfig); String protocol = binding.getBindingType().getType(); // http protocol use default protocol if (!SofaBootRpcConfigConstants.RPC_PROTOCOL_HTTP.equals(protocol)) { providerConfig.setBootstrap(protocol); } if (StringUtils.hasText(serialization)) { providerConfig.setSerialization(serialization); } if (param.getParameters() != null) { providerConfig.setParameters(param.getParameters()); } if (param.getRegistrys() != null && param.getRegistrys().size() > 0) { List<String> registrys = param.getRegistrys(); for (String registryAlias : registrys) { RegistryConfig registryConfig = registryConfigContainer .getRegistryConfig(registryAlias); providerConfig.setRegistry(registryConfig); } } else if (registryConfigContainer.isMeshEnabled(protocol)) { RegistryConfig registryConfig = registryConfigContainer .getRegistryConfig(SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_MESH); providerConfig.setRegistry(registryConfig); } else { RegistryConfig registryConfig = registryConfigContainer.getRegistryConfig(); providerConfig.setRegistry(registryConfig); } providerConfig.setRegister(false); return providerConfig;
402
1,004
1,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/runtime/adapter/processor/ConsumerMockProcessor.java
ConsumerMockProcessor
processorConsumer
class ConsumerMockProcessor implements ConsumerConfigProcessor { public static final String MOCK_URL = "mockUrl"; private String mockUrl; public ConsumerMockProcessor(String mockUrl) { this.mockUrl = mockUrl; } @Override public void processorConsumer(ConsumerConfig consumerConfig) {<FILL_FUNCTION_BODY>} public String getMockUrl() { return mockUrl; } public void setMockUrl(String mockUrl) { this.mockUrl = mockUrl; } }
String mockMode = consumerConfig.getMockMode(); if (StringUtils.hasText(mockUrl) && (!StringUtils.hasText(mockMode) || MockMode.REMOTE.equals(mockMode))) { String originMockUrl = consumerConfig.getParameter(MOCK_URL); if (!StringUtils.hasText(originMockUrl)) { consumerConfig.setMockMode(MockMode.REMOTE); consumerConfig.setParameter(MOCK_URL, mockUrl); } }
142
129
271
<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/runtime/adapter/processor/DynamicConfigProcessor.java
DynamicConfigProcessor
setDynamicConfig
class DynamicConfigProcessor implements ConsumerConfigProcessor, ProviderConfigProcessor { private String dynamicConfig; public DynamicConfigProcessor(String dynamicConfig) { this.dynamicConfig = dynamicConfig; } @Override public void processorConsumer(ConsumerConfig consumerConfig) { setDynamicConfig(consumerConfig); } @Override public void processorProvider(ProviderConfig providerConfig) { setDynamicConfig(providerConfig); } private void setDynamicConfig(AbstractInterfaceConfig config) {<FILL_FUNCTION_BODY>} public String getDynamicConfig() { return dynamicConfig; } public void setDynamicConfig(String dynamicConfig) { this.dynamicConfig = dynamicConfig; } }
String configAlias = config.getParameter(DynamicConfigKeys.DYNAMIC_ALIAS); if (StringUtils.isBlank(configAlias) && StringUtils.isNotBlank(dynamicConfig)) { config.setParameter(DynamicConfigKeys.DYNAMIC_ALIAS, dynamicConfig); }
188
84
272
<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/runtime/adapter/processor/ProcessorContainer.java
ProcessorContainer
processorProvider
class ProcessorContainer { private final List<ProviderConfigProcessor> providerProcessors; private final List<ConsumerConfigProcessor> consumerProcessors; public ProcessorContainer(List<ProviderConfigProcessor> providerProcessors, List<ConsumerConfigProcessor> consumerProcessors) { this.providerProcessors = providerProcessors; this.consumerProcessors = consumerProcessors; } public void processorConsumer(ConsumerConfig consumerConfig) { if (CommonUtils.isNotEmpty(consumerProcessors)) { for (ConsumerConfigProcessor consumerProcessor : consumerProcessors) { consumerProcessor.processorConsumer(consumerConfig); } } } public void processorProvider(ProviderConfig providerConfig) {<FILL_FUNCTION_BODY>} }
if (CommonUtils.isNotEmpty(providerProcessors)) { for (ProviderConfigProcessor providerProcessor : providerProcessors) { providerProcessor.processorProvider(providerConfig); } }
191
52
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/runtime/adapter/processor/ProviderRegisterProcessor.java
ProviderRegisterProcessor
processorProvider
class ProviderRegisterProcessor implements ProviderConfigProcessor { @Override public void processorProvider(ProviderConfig providerConfig) {<FILL_FUNCTION_BODY>} }
if (SofaConfigs.getOrDefault(SofaBootRpcConfigKeys.DISABLE_REGISTER_PUB)) { if (providerConfig != null) { providerConfig.setRegister(false); } }
45
64
109
<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/runtime/binding/RpcBinding.java
RpcBinding
equals
class RpcBinding extends AbstractBinding { protected String appName; protected String beanId; protected RpcBindingParam rpcBindingParam; /** * Spring 上下文 */ protected ApplicationContext applicationContext; /** * 是否是服务引用方 */ protected boolean inBinding; /** * the ConsumerConfig 。在服务引用方才有值。 */ protected ConsumerConfig consumerConfig; public RpcBinding(RpcBindingParam bindingParam, ApplicationContext applicationContext, boolean inBinding) { this.rpcBindingParam = bindingParam; this.applicationContext = applicationContext; this.inBinding = inBinding; } public String getBootStrap() { String bindingType = getBindingType().getType(); if (bindingType.equalsIgnoreCase(SofaBootRpcConfigConstants.RPC_PROTOCOL_DUBBO)) { return SofaBootRpcConfigConstants.RPC_PROTOCOL_DUBBO; } else { return SofaBootRpcConfigConstants.RPC_PROTOCOL_BOLT; } } @Override public String getURI() { return null; } @Override public Element getBindingPropertyContent() { return null; } @Override public int getBindingHashCode() { return this.hashCode(); } /** * 健康检查 * * @return 健康检查结果 */ @Override public HealthResult healthCheck() { HealthResult result = new HealthResult(getName()); // health check when reference if (inBinding && consumerConfig != null) { if (consumerConfig.getConsumerBootstrap().isSubscribed()) { result.setHealthy(true); } else if (getRpcBindingParam().isHealthyDestine(getAppName())) { result.setHealthy(true); } else { result.setHealthy(false); result.setHealthReport("Addresses unavailable"); } } else { result.setHealthy(isHealthy); } return result; } /** * Getter method for property <code>appName</code>. * * @return property value of appName */ public String getAppName() { return appName; } /** * Setter method for property <code>appName</code>. * * @param appName value to be assigned to property appName */ public void setAppName(String appName) { this.appName = appName; } /** * Getter method for property <code>beanId</code>. * * @return property value of beanId */ public String getBeanId() { return beanId; } /** * Setter method for property <code>beanId</code>. * * @param beanId value to be assigned to property beanId */ public void setBeanId(String beanId) { this.beanId = beanId; } /** * Getter method for property <code>rpcBindingParam</code>. * * @return property value of rpcBindingParam */ public RpcBindingParam getRpcBindingParam() { return rpcBindingParam; } /** * Setter method for property <code>rpcBindingParam</code>. * * @param rpcBindingParam value to be assigned to property rpcBindingParam */ public void setRpcBindingParam(RpcBindingParam rpcBindingParam) { this.rpcBindingParam = rpcBindingParam; } /** * Getter method for property <code>applicationContext</code>. * * @return property value of applicationContext */ public ApplicationContext getApplicationContext() { return applicationContext; } /** * Setter method for property <code>applicationContext</code>. * * @param applicationContext value to be assigned to property applicationContext */ public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } /** * Getter method for property <code>inBinding</code>. * * @return property value of inBinding */ public boolean isInBinding() { return inBinding; } /** * Setter method for property <code>inBinding</code>. * * @param inBinding value to be assigned to property inBinding */ public void setInBinding(boolean inBinding) { this.inBinding = inBinding; } /** * Getter method for property <code>consumerConfig</code>. * * @return property value of consumerConfig */ public ConsumerConfig getConsumerConfig() { return consumerConfig; } /** * Setter method for property <code>consumerConfig</code>. * * @param consumerConfig value to be assigned to property consumerConfig */ public void setConsumerConfig(ConsumerConfig consumerConfig) { this.consumerConfig = consumerConfig; } @Override public boolean equals(Object object) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { int result = appName != null ? appName.hashCode() : 0; result = 31 * result + (beanId != null ? beanId.hashCode() : 0); result = 31 * result + (rpcBindingParam != null ? rpcBindingParam.hashCode() : 0); result = 31 * result + (applicationContext != null ? applicationContext.hashCode() : 0); result = 31 * result + (inBinding ? 1 : 0); result = 31 * result + (consumerConfig != null ? consumerConfig.hashCode() : 0); return result; } }
if (this == object) { return true; } if (object == null || getClass() != object.getClass()) { return false; } RpcBinding that = (RpcBinding) object; if (inBinding != that.inBinding) { return false; } if (appName != null ? !appName.equals(that.appName) : that.appName != null) { return false; } if (beanId != null ? !beanId.equals(that.beanId) : that.beanId != null) { return false; } if (rpcBindingParam != null ? !rpcBindingParam.equals(that.rpcBindingParam) : that.rpcBindingParam != null) { return false; } if (applicationContext != null ? !applicationContext.equals(that.applicationContext) : that.applicationContext != null) { return false; } return consumerConfig != null ? consumerConfig.equals(that.consumerConfig) : that.consumerConfig == null;
1,545
284
1,829
<methods>public non-sealed void <init>() ,public java.lang.String dump() ,public java.lang.String getName() ,public boolean isDestroyed() ,public void setDestroyed(boolean) ,public void setHealthy(boolean) ,public java.lang.String toString() <variables>protected boolean isDestroyed,protected boolean isHealthy
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/rpc-sofa-boot/src/main/java/com/alipay/sofa/rpc/boot/runtime/converter/BoltBindingConverter.java
BoltBindingConverter
convert
class BoltBindingConverter extends RpcBindingConverter { @Override protected RpcBinding createRpcBinding(RpcBindingParam bindingParam, ApplicationContext applicationContext, boolean inBinding) { return new BoltBinding(bindingParam, applicationContext, inBinding); } @Override protected RpcBindingParam createRpcBindingParam() { return new BoltBindingParam(); } @Override public RpcBinding convert(SofaService sofaServiceAnnotation, SofaServiceBinding sofaServiceBindingAnnotation, BindingConverterContext bindingConverterContext) {<FILL_FUNCTION_BODY>} @Override public RpcBinding convert(SofaReference sofaReferenceAnnotation, SofaReferenceBinding sofaReferenceBindingAnnotation, BindingConverterContext bindingConverterContext) { RpcBindingParam bindingParam = new BoltBindingParam(); convertReferenceAnnotation(bindingParam, sofaReferenceBindingAnnotation, bindingConverterContext); return new BoltBinding(bindingParam, bindingConverterContext.getApplicationContext(), bindingConverterContext.isInBinding()); } @Override public BindingType supportBindingType() { return RpcBindingType.BOLT_BINDING_TYPE; } @Override public String supportTagName() { return "binding." + SofaBootRpcConfigConstants.RPC_PROTOCOL_BOLT; } }
RpcBindingParam bindingParam = new BoltBindingParam(); convertServiceAnnotation(bindingParam, sofaServiceAnnotation, sofaServiceBindingAnnotation, bindingConverterContext); return new BoltBinding(bindingParam, bindingConverterContext.getApplicationContext(), bindingConverterContext.isInBinding());
347
71
418
<methods>public non-sealed void <init>() ,public com.alipay.sofa.rpc.boot.runtime.binding.RpcBinding convert(com.alipay.sofa.rpc.boot.runtime.param.RpcBindingParam, com.alipay.sofa.runtime.spi.service.BindingConverterContext) ,public com.alipay.sofa.rpc.boot.runtime.binding.RpcBinding convert(org.w3c.dom.Element, com.alipay.sofa.runtime.spi.service.BindingConverterContext) ,public abstract com.alipay.sofa.rpc.boot.runtime.binding.RpcBinding convert(com.alipay.sofa.runtime.api.annotation.SofaService, com.alipay.sofa.runtime.api.annotation.SofaServiceBinding, com.alipay.sofa.runtime.spi.service.BindingConverterContext) ,public abstract com.alipay.sofa.rpc.boot.runtime.binding.RpcBinding convert(com.alipay.sofa.runtime.api.annotation.SofaReference, com.alipay.sofa.runtime.api.annotation.SofaReferenceBinding, com.alipay.sofa.runtime.spi.service.BindingConverterContext) ,public List<com.alipay.sofa.rpc.boot.runtime.binding.RpcBindingMethodInfo> parseSofaMethods(com.alipay.sofa.runtime.api.annotation.SofaMethod[]) <variables>private static final char EXCLUDE_FILTER_BEGIN_SYMBOL,private static final java.lang.String FILTER_SEPERATOR_SYMBOL
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/rpc-sofa-boot/src/main/java/com/alipay/sofa/rpc/boot/runtime/converter/DubboBindingConverter.java
DubboBindingConverter
convert
class DubboBindingConverter extends RpcBindingConverter { @Override protected RpcBinding createRpcBinding(RpcBindingParam bindingParam, ApplicationContext applicationContext, boolean inBinding) { return new DubboBinding(bindingParam, applicationContext, inBinding); } @Override protected RpcBindingParam createRpcBindingParam() { return new DubboBindingParam(); } @Override public RpcBinding convert(SofaService sofaServiceAnnotation, SofaServiceBinding sofaServiceBindingAnnotation, BindingConverterContext bindingConverterContext) {<FILL_FUNCTION_BODY>} @Override public RpcBinding convert(SofaReference sofaReferenceAnnotation, SofaReferenceBinding sofaReferenceBindingAnnotation, BindingConverterContext bindingConverterContext) { RpcBindingParam bindingParam = new DubboBindingParam(); convertReferenceAnnotation(bindingParam, sofaReferenceBindingAnnotation, bindingConverterContext); return new DubboBinding(bindingParam, bindingConverterContext.getApplicationContext(), bindingConverterContext.isInBinding()); } @Override public BindingType supportBindingType() { return RpcBindingType.DUBBO_BINDING_TYPE; } @Override public String supportTagName() { return "binding." + SofaBootRpcConfigConstants.RPC_PROTOCOL_DUBBO; } }
RpcBindingParam bindingParam = new DubboBindingParam(); convertServiceAnnotation(bindingParam, sofaServiceAnnotation, sofaServiceBindingAnnotation, bindingConverterContext); return new DubboBinding(bindingParam, bindingConverterContext.getApplicationContext(), bindingConverterContext.isInBinding());
348
71
419
<methods>public non-sealed void <init>() ,public com.alipay.sofa.rpc.boot.runtime.binding.RpcBinding convert(com.alipay.sofa.rpc.boot.runtime.param.RpcBindingParam, com.alipay.sofa.runtime.spi.service.BindingConverterContext) ,public com.alipay.sofa.rpc.boot.runtime.binding.RpcBinding convert(org.w3c.dom.Element, com.alipay.sofa.runtime.spi.service.BindingConverterContext) ,public abstract com.alipay.sofa.rpc.boot.runtime.binding.RpcBinding convert(com.alipay.sofa.runtime.api.annotation.SofaService, com.alipay.sofa.runtime.api.annotation.SofaServiceBinding, com.alipay.sofa.runtime.spi.service.BindingConverterContext) ,public abstract com.alipay.sofa.rpc.boot.runtime.binding.RpcBinding convert(com.alipay.sofa.runtime.api.annotation.SofaReference, com.alipay.sofa.runtime.api.annotation.SofaReferenceBinding, com.alipay.sofa.runtime.spi.service.BindingConverterContext) ,public List<com.alipay.sofa.rpc.boot.runtime.binding.RpcBindingMethodInfo> parseSofaMethods(com.alipay.sofa.runtime.api.annotation.SofaMethod[]) <variables>private static final char EXCLUDE_FILTER_BEGIN_SYMBOL,private static final java.lang.String FILTER_SEPERATOR_SYMBOL
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/rpc-sofa-boot/src/main/java/com/alipay/sofa/rpc/boot/runtime/converter/H2cBindingConverter.java
H2cBindingConverter
convert
class H2cBindingConverter extends RpcBindingConverter { @Override protected RpcBinding createRpcBinding(RpcBindingParam bindingParam, ApplicationContext applicationContext, boolean inBinding) { return new H2cBinding(bindingParam, applicationContext, inBinding); } @Override protected RpcBindingParam createRpcBindingParam() { return new H2cBindingParam(); } @Override public RpcBinding convert(SofaService sofaServiceAnnotation, SofaServiceBinding sofaServiceBindingAnnotation, BindingConverterContext bindingConverterContext) {<FILL_FUNCTION_BODY>} @Override public RpcBinding convert(SofaReference sofaReferenceAnnotation, SofaReferenceBinding sofaReferenceBindingAnnotation, BindingConverterContext bindingConverterContext) { RpcBindingParam bindingParam = new H2cBindingParam(); convertReferenceAnnotation(bindingParam, sofaReferenceBindingAnnotation, bindingConverterContext); return new H2cBinding(bindingParam, bindingConverterContext.getApplicationContext(), bindingConverterContext.isInBinding()); } @Override public BindingType supportBindingType() { return RpcBindingType.H2C_BINDING_TYPE; } @Override public String supportTagName() { return "binding." + SofaBootRpcConfigConstants.RPC_PROTOCOL_H2C; } }
RpcBindingParam bindingParam = new H2cBindingParam(); convertServiceAnnotation(bindingParam, sofaServiceAnnotation, sofaServiceBindingAnnotation, bindingConverterContext); return new H2cBinding(bindingParam, bindingConverterContext.getApplicationContext(), bindingConverterContext.isInBinding());
352
73
425
<methods>public non-sealed void <init>() ,public com.alipay.sofa.rpc.boot.runtime.binding.RpcBinding convert(com.alipay.sofa.rpc.boot.runtime.param.RpcBindingParam, com.alipay.sofa.runtime.spi.service.BindingConverterContext) ,public com.alipay.sofa.rpc.boot.runtime.binding.RpcBinding convert(org.w3c.dom.Element, com.alipay.sofa.runtime.spi.service.BindingConverterContext) ,public abstract com.alipay.sofa.rpc.boot.runtime.binding.RpcBinding convert(com.alipay.sofa.runtime.api.annotation.SofaService, com.alipay.sofa.runtime.api.annotation.SofaServiceBinding, com.alipay.sofa.runtime.spi.service.BindingConverterContext) ,public abstract com.alipay.sofa.rpc.boot.runtime.binding.RpcBinding convert(com.alipay.sofa.runtime.api.annotation.SofaReference, com.alipay.sofa.runtime.api.annotation.SofaReferenceBinding, com.alipay.sofa.runtime.spi.service.BindingConverterContext) ,public List<com.alipay.sofa.rpc.boot.runtime.binding.RpcBindingMethodInfo> parseSofaMethods(com.alipay.sofa.runtime.api.annotation.SofaMethod[]) <variables>private static final char EXCLUDE_FILTER_BEGIN_SYMBOL,private static final java.lang.String FILTER_SEPERATOR_SYMBOL
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/rpc-sofa-boot/src/main/java/com/alipay/sofa/rpc/boot/runtime/converter/HttpBindingConverter.java
HttpBindingConverter
convert
class HttpBindingConverter extends RpcBindingConverter { @Override protected RpcBinding createRpcBinding(RpcBindingParam bindingParam, ApplicationContext applicationContext, boolean inBinding) { return new HttpBinding(bindingParam, applicationContext, inBinding); } @Override protected RpcBindingParam createRpcBindingParam() { return new HttpBindingParam(); } @Override public RpcBinding convert(SofaService sofaServiceAnnotation, SofaServiceBinding sofaServiceBindingAnnotation, BindingConverterContext bindingConverterContext) {<FILL_FUNCTION_BODY>} @Override public RpcBinding convert(SofaReference sofaReferenceAnnotation, SofaReferenceBinding sofaReferenceBindingAnnotation, BindingConverterContext bindingConverterContext) { RpcBindingParam bindingParam = new HttpBindingParam(); convertReferenceAnnotation(bindingParam, sofaReferenceBindingAnnotation, bindingConverterContext); return new HttpBinding(bindingParam, bindingConverterContext.getApplicationContext(), bindingConverterContext.isInBinding()); } @Override public BindingType supportBindingType() { return RpcBindingType.HTTP_BINDING_TYPE; } @Override public String supportTagName() { return "binding." + SofaBootRpcConfigConstants.RPC_PROTOCOL_HTTP; } }
RpcBindingParam bindingParam = new HttpBindingParam(); convertServiceAnnotation(bindingParam, sofaServiceAnnotation, sofaServiceBindingAnnotation, bindingConverterContext); return new HttpBinding(bindingParam, bindingConverterContext.getApplicationContext(), bindingConverterContext.isInBinding());
338
69
407
<methods>public non-sealed void <init>() ,public com.alipay.sofa.rpc.boot.runtime.binding.RpcBinding convert(com.alipay.sofa.rpc.boot.runtime.param.RpcBindingParam, com.alipay.sofa.runtime.spi.service.BindingConverterContext) ,public com.alipay.sofa.rpc.boot.runtime.binding.RpcBinding convert(org.w3c.dom.Element, com.alipay.sofa.runtime.spi.service.BindingConverterContext) ,public abstract com.alipay.sofa.rpc.boot.runtime.binding.RpcBinding convert(com.alipay.sofa.runtime.api.annotation.SofaService, com.alipay.sofa.runtime.api.annotation.SofaServiceBinding, com.alipay.sofa.runtime.spi.service.BindingConverterContext) ,public abstract com.alipay.sofa.rpc.boot.runtime.binding.RpcBinding convert(com.alipay.sofa.runtime.api.annotation.SofaReference, com.alipay.sofa.runtime.api.annotation.SofaReferenceBinding, com.alipay.sofa.runtime.spi.service.BindingConverterContext) ,public List<com.alipay.sofa.rpc.boot.runtime.binding.RpcBindingMethodInfo> parseSofaMethods(com.alipay.sofa.runtime.api.annotation.SofaMethod[]) <variables>private static final char EXCLUDE_FILTER_BEGIN_SYMBOL,private static final java.lang.String FILTER_SEPERATOR_SYMBOL
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/rpc-sofa-boot/src/main/java/com/alipay/sofa/rpc/boot/runtime/converter/RestBindingConverter.java
RestBindingConverter
convert
class RestBindingConverter extends RpcBindingConverter { @Override protected RpcBinding createRpcBinding(RpcBindingParam bindingParam, ApplicationContext applicationContext, boolean inBinding) { return new RestBinding(bindingParam, applicationContext, inBinding); } @Override protected RpcBindingParam createRpcBindingParam() { return new RestBindingParam(); } @Override public RpcBinding convert(SofaService sofaServiceAnnotation, SofaServiceBinding sofaServiceBindingAnnotation, BindingConverterContext bindingConverterContext) {<FILL_FUNCTION_BODY>} @Override public RpcBinding convert(SofaReference sofaReferenceAnnotation, SofaReferenceBinding sofaReferenceBindingAnnotation, BindingConverterContext bindingConverterContext) { RpcBindingParam bindingParam = new RestBindingParam(); convertReferenceAnnotation(bindingParam, sofaReferenceBindingAnnotation, bindingConverterContext); return new RestBinding(bindingParam, bindingConverterContext.getApplicationContext(), bindingConverterContext.isInBinding()); } @Override public BindingType supportBindingType() { return RpcBindingType.REST_BINDING_TYPE; } @Override public String supportTagName() { return "binding." + SofaBootRpcConfigConstants.RPC_PROTOCOL_REST; } }
RpcBindingParam bindingParam = new RestBindingParam(); convertServiceAnnotation(bindingParam, sofaServiceAnnotation, sofaServiceBindingAnnotation, bindingConverterContext); return new RestBinding(bindingParam, bindingConverterContext.getApplicationContext(), bindingConverterContext.isInBinding());
341
69
410
<methods>public non-sealed void <init>() ,public com.alipay.sofa.rpc.boot.runtime.binding.RpcBinding convert(com.alipay.sofa.rpc.boot.runtime.param.RpcBindingParam, com.alipay.sofa.runtime.spi.service.BindingConverterContext) ,public com.alipay.sofa.rpc.boot.runtime.binding.RpcBinding convert(org.w3c.dom.Element, com.alipay.sofa.runtime.spi.service.BindingConverterContext) ,public abstract com.alipay.sofa.rpc.boot.runtime.binding.RpcBinding convert(com.alipay.sofa.runtime.api.annotation.SofaService, com.alipay.sofa.runtime.api.annotation.SofaServiceBinding, com.alipay.sofa.runtime.spi.service.BindingConverterContext) ,public abstract com.alipay.sofa.rpc.boot.runtime.binding.RpcBinding convert(com.alipay.sofa.runtime.api.annotation.SofaReference, com.alipay.sofa.runtime.api.annotation.SofaReferenceBinding, com.alipay.sofa.runtime.spi.service.BindingConverterContext) ,public List<com.alipay.sofa.rpc.boot.runtime.binding.RpcBindingMethodInfo> parseSofaMethods(com.alipay.sofa.runtime.api.annotation.SofaMethod[]) <variables>private static final char EXCLUDE_FILTER_BEGIN_SYMBOL,private static final java.lang.String FILTER_SEPERATOR_SYMBOL
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/rpc-sofa-boot/src/main/java/com/alipay/sofa/rpc/boot/runtime/converter/TripleBindingConverter.java
TripleBindingConverter
convert
class TripleBindingConverter extends RpcBindingConverter { @Override protected RpcBinding createRpcBinding(RpcBindingParam bindingParam, ApplicationContext applicationContext, boolean inBinding) { return new TripleBinding(bindingParam, applicationContext, inBinding); } @Override protected RpcBindingParam createRpcBindingParam() { return new TripleBindingParam(); } @Override public RpcBinding convert(SofaService sofaServiceAnnotation, SofaServiceBinding sofaServiceBindingAnnotation, BindingConverterContext bindingConverterContext) {<FILL_FUNCTION_BODY>} @Override public RpcBinding convert(SofaReference sofaReferenceAnnotation, SofaReferenceBinding sofaReferenceBindingAnnotation, BindingConverterContext bindingConverterContext) { RpcBindingParam bindingParam = new TripleBindingParam(); convertReferenceAnnotation(bindingParam, sofaReferenceBindingAnnotation, bindingConverterContext); return new TripleBinding(bindingParam, bindingConverterContext.getApplicationContext(), bindingConverterContext.isInBinding()); } @Override protected void parseGlobalAttrs(Element element, RpcBindingParam param, BindingConverterContext bindingConverterContext) { super.parseGlobalAttrs(element, param, bindingConverterContext); if (element == null) { param.setSerialization(RpcConstants.SERIALIZE_PROTOBUF); } else { String serialization = element.getAttribute(RpcBindingXmlConstants.TAG_SERIALIZE_TYPE); if (StringUtils.isBlank(serialization)) { param.setSerialization(RpcConstants.SERIALIZE_PROTOBUF); } } } @Override public BindingType supportBindingType() { return RpcBindingType.TRIPLE_BINDING_TYPE; } @Override public String supportTagName() { return "binding." + SofaBootRpcConfigConstants.RPC_PROTOCOL_TRIPLE; } }
RpcBindingParam bindingParam = new TripleBindingParam(); convertServiceAnnotation(bindingParam, sofaServiceAnnotation, sofaServiceBindingAnnotation, bindingConverterContext); return new TripleBinding(bindingParam, bindingConverterContext.getApplicationContext(), bindingConverterContext.isInBinding());
506
71
577
<methods>public non-sealed void <init>() ,public com.alipay.sofa.rpc.boot.runtime.binding.RpcBinding convert(com.alipay.sofa.rpc.boot.runtime.param.RpcBindingParam, com.alipay.sofa.runtime.spi.service.BindingConverterContext) ,public com.alipay.sofa.rpc.boot.runtime.binding.RpcBinding convert(org.w3c.dom.Element, com.alipay.sofa.runtime.spi.service.BindingConverterContext) ,public abstract com.alipay.sofa.rpc.boot.runtime.binding.RpcBinding convert(com.alipay.sofa.runtime.api.annotation.SofaService, com.alipay.sofa.runtime.api.annotation.SofaServiceBinding, com.alipay.sofa.runtime.spi.service.BindingConverterContext) ,public abstract com.alipay.sofa.rpc.boot.runtime.binding.RpcBinding convert(com.alipay.sofa.runtime.api.annotation.SofaReference, com.alipay.sofa.runtime.api.annotation.SofaReferenceBinding, com.alipay.sofa.runtime.spi.service.BindingConverterContext) ,public List<com.alipay.sofa.rpc.boot.runtime.binding.RpcBindingMethodInfo> parseSofaMethods(com.alipay.sofa.runtime.api.annotation.SofaMethod[]) <variables>private static final char EXCLUDE_FILTER_BEGIN_SYMBOL,private static final java.lang.String FILTER_SEPERATOR_SYMBOL
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/rpc-sofa-boot/src/main/java/com/alipay/sofa/rpc/boot/runtime/parser/GlobalFilterParser.java
GlobalFilterParser
doParse
class GlobalFilterParser extends AbstractSimpleBeanDefinitionParser implements SofaBootTagNameSupport { private static final Logger LOGGER = SofaBootRpcLoggerFactory .getLogger(GlobalFilterParser.class); private static final String TAG_GLOBAL_FILTER = "rpc-global-filter"; private static final String TAG_REF = "ref"; private static final String TAG_CLASS = "class"; /** * 从 XML 解析全局 Filter。 * * @param element * @param parserContext * @param builder */ @Override protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {<FILL_FUNCTION_BODY>} /** * 支持的 tag 名字 * * @return 支持的 tag 名字 */ @Override public String supportTagName() { return TAG_GLOBAL_FILTER; } @Override protected boolean shouldGenerateIdAsFallback() { return true; } @Override protected Class<?> getBeanClass(Element element) { return Object.class; } }
String filterId = element.getAttribute(TAG_REF); String filterClass = element.getAttribute(TAG_CLASS); if (StringUtils.hasText(filterId)) { RpcFilterContainer.getInstance().addFilterId(filterId); if (LOGGER.isInfoEnabled()) { LOGGER.info("global filter take effect[" + filterId + "]"); } return; } if (StringUtils.hasText(filterClass)) { RpcFilterContainer.getInstance().addFilterClass(filterClass); if (LOGGER.isInfoEnabled()) { LOGGER.info("global filter take effect[" + filterClass + "]"); } return; } if (LOGGER.isWarnEnabled()) { LOGGER .warn("both the ref attr and class attr is blank, this rpc global filter is invalid"); }
314
222
536
<methods>public void <init>() <variables>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/rpc-sofa-boot/src/main/java/com/alipay/sofa/rpc/boot/swagger/BoltSwaggerServiceApplicationListener.java
BoltSwaggerServiceApplicationListener
onApplicationEvent
class BoltSwaggerServiceApplicationListener implements ApplicationListener<ApplicationStartedEvent> { private final ClientFactory clientFactory; public BoltSwaggerServiceApplicationListener(SofaRuntimeManager sofaRuntimeManager) { this.clientFactory = sofaRuntimeManager.getClientFactoryInternal(); } @Override public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {<FILL_FUNCTION_BODY>} }
List<BindingParam> bindingParams = new ArrayList<>(); bindingParams.add(new RestBindingParam()); ServiceParam serviceParam = new ServiceParam(); serviceParam.setInterfaceType(SwaggerRestService.class); serviceParam.setInstance(new SwaggerRestServiceImpl()); serviceParam.setBindingParams(bindingParams); ServiceClient serviceClient = clientFactory.getClient(ServiceClient.class); serviceClient.service(serviceParam);
110
114
224
<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/swagger/SwaggerServiceApplicationListener.java
SwaggerServiceApplicationListener
onApplicationEvent
class SwaggerServiceApplicationListener implements ApplicationListener<ApplicationStartedEvent> { private final ComponentManager componentManager; private final ClientFactory clientFactory; public SwaggerServiceApplicationListener(SofaRuntimeManager sofaRuntimeManager) { this.componentManager = sofaRuntimeManager.getComponentManager(); this.clientFactory = sofaRuntimeManager.getClientFactoryInternal(); } @Override public void onApplicationEvent(ApplicationStartedEvent event) {<FILL_FUNCTION_BODY>} }
List<BindingParam> bindingParams = new ArrayList<>(); bindingParams.add(new RestBindingParam()); ServiceParam serviceParam = new ServiceParam(); serviceParam.setInterfaceType(SwaggerService.class); serviceParam.setInstance(new SwaggerServiceImpl(componentManager)); serviceParam.setBindingParams(bindingParams); ServiceClient serviceClient = clientFactory.getClient(ServiceClient.class); serviceClient.service(serviceParam);
127
114
241
<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/swagger/SwaggerServiceImpl.java
SwaggerServiceImpl
getAllRestfulService
class SwaggerServiceImpl implements SwaggerService { private final ComponentManager componentManager; private volatile OpenAPI openapi; private Set<String> restfulServices; public SwaggerServiceImpl(ComponentManager componentManager) { this.componentManager = componentManager; } @Override public String openapi() { if (openapi == null) { synchronized (this) { if (openapi == null) { openapi = buildOpenApi(); } } } else { if (!getAllRestfulService().equals(restfulServices)) { synchronized (this) { if (!getAllRestfulService().equals(restfulServices)) { openapi = updateOpenApi(); } } } } return Json.pretty(openapi); } private OpenAPI updateOpenApi() { OpenApiContext openApiContext = OpenApiContextLocator.getInstance().getOpenApiContext( OpenApiContext.OPENAPI_CONTEXT_ID_DEFAULT); if (openApiContext instanceof GenericOpenApiContext) { restfulServices = getAllRestfulService(); SwaggerConfiguration oasConfig = new SwaggerConfiguration() .resourceClasses(restfulServices); ((GenericOpenApiContext) openApiContext).getOpenApiScanner() .setConfiguration(oasConfig); try { ((GenericOpenApiContext) openApiContext).setCacheTTL(0); return openApiContext.read(); } finally { ((GenericOpenApiContext) openApiContext).setCacheTTL(-1); } } else { return null; } } private OpenAPI buildOpenApi() { try { restfulServices = getAllRestfulService(); SwaggerConfiguration oasConfig = new SwaggerConfiguration() .resourceClasses(restfulServices); OpenApiContext oac = new JaxrsOpenApiContextBuilder().openApiConfiguration(oasConfig) .buildContext(true); return oac.read(); } catch (OpenApiConfigurationException e) { throw new RuntimeException(e.getMessage(), e); } } private Set<String> getAllRestfulService() {<FILL_FUNCTION_BODY>} }
return componentManager.getComponentInfosByType(ServiceComponent.SERVICE_COMPONENT_TYPE).stream() .filter(ci -> { ServiceComponent sc = (ServiceComponent) ci; return sc.getService().getBinding(RpcBindingType.REST_BINDING_TYPE) != null; }) .map(sc -> ((ServiceComponent) sc).getService().getInterfaceType()) .map(Class::getName).collect(Collectors.toSet());
566
121
687
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/common/xmap/Context.java
Context
getObject
class Context extends ArrayList<Object> { private static final long serialVersionUID = 1L; public Class loadClass(String className) throws ClassNotFoundException { return Thread.currentThread().getContextClassLoader().loadClass(className); } public URL getResource(String name) { return Thread.currentThread().getContextClassLoader().getResource(name); } public Object getObject() {<FILL_FUNCTION_BODY>} public Object getParent() { int size = size(); if (size > 1) { return get(size - 2); } return null; } public void push(Object object) { add(object); } public Object pop() { int size = size(); if (size > 0) { return remove(size - 1); } return null; } }
int size = size(); if (size > 0) { return get(size - 1); } return null;
228
37
265
<methods>public void <init>() ,public void <init>(int) ,public void <init>(Collection<? extends java.lang.Object>) ,public boolean add(java.lang.Object) ,public void add(int, java.lang.Object) ,public boolean addAll(Collection<? extends java.lang.Object>) ,public boolean addAll(int, Collection<? extends java.lang.Object>) ,public void clear() ,public java.lang.Object clone() ,public boolean contains(java.lang.Object) ,public void ensureCapacity(int) ,public boolean equals(java.lang.Object) ,public void forEach(Consumer<? super java.lang.Object>) ,public java.lang.Object get(int) ,public int hashCode() ,public int indexOf(java.lang.Object) ,public boolean isEmpty() ,public Iterator<java.lang.Object> iterator() ,public int lastIndexOf(java.lang.Object) ,public ListIterator<java.lang.Object> listIterator() ,public ListIterator<java.lang.Object> listIterator(int) ,public java.lang.Object remove(int) ,public boolean remove(java.lang.Object) ,public boolean removeAll(Collection<?>) ,public boolean removeIf(Predicate<? super java.lang.Object>) ,public void replaceAll(UnaryOperator<java.lang.Object>) ,public boolean retainAll(Collection<?>) ,public java.lang.Object set(int, java.lang.Object) ,public int size() ,public void sort(Comparator<? super java.lang.Object>) ,public Spliterator<java.lang.Object> spliterator() ,public List<java.lang.Object> subList(int, int) ,public java.lang.Object[] toArray() ,public T[] toArray(T[]) ,public void trimToSize() <variables>private static final java.lang.Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA,private static final int DEFAULT_CAPACITY,private static final java.lang.Object[] EMPTY_ELEMENTDATA,transient java.lang.Object[] elementData,private static final long serialVersionUID,private int size
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/common/xmap/DOMHelper.java
DOMHelper
getElementNode
class DOMHelper { private DOMHelper() { } /** * Gets the value of the node at the given path * relative to the given base element. * For element nodes the value is the text content and for * the attributes node the attribute value. * * @param base base element * @param path path * @return the node value or null if no such node was found */ public static String getNodeValue(Element base, Path path) { Node node = getElementNode(base, path); if (node != null) { if (path.attribute != null) { Node at = node.getAttributes().getNamedItem(path.attribute); return at != null ? at.getNodeValue() : null; } else { return node.getTextContent(); } } return null; } public static void visitNodes(Context ctx, XAnnotatedList xam, Element base, Path path, NodeVisitor visitor, Collection<Object> result) { Node el = base; int len = path.segments.length - 1; for (int i = 0; i < len; i++) { el = getElementNode(el, path.segments[i]); if (el == null) { return; } } String name = path.segments[len]; if (path.attribute != null) { visitAttributes(ctx, xam, el, name, path.attribute, visitor, result); } else { visitElements(ctx, xam, el, name, visitor, result); } } public static void visitAttributes(Context ctx, XAnnotatedList xam, Node base, String name, String attrName, NodeVisitor visitor, Collection<Object> result) { Node p = base.getFirstChild(); while (p != null) { if (p.getNodeType() == Node.ELEMENT_NODE) { if (name.equals(p.getNodeName())) { Node at = p.getAttributes().getNamedItem(attrName); if (at != null) { visitor.visitNode(ctx, xam, at, result); } } } p = p.getNextSibling(); } } public static void visitElements(Context ctx, XAnnotatedList xam, Node base, String name, NodeVisitor visitor, Collection<Object> result) { Node p = base.getFirstChild(); while (p != null) { if (p.getNodeType() == Node.ELEMENT_NODE) { if (name.equals(p.getNodeName())) { visitor.visitNode(ctx, xam, p, result); } } p = p.getNextSibling(); } } public static void visitMapNodes(Context ctx, XAnnotatedMap xam, Element base, Path path, NodeMapVisitor visitor, Map<String, Object> result) { Node el = base; int len = path.segments.length - 1; for (int i = 0; i < len; i++) { el = getElementNode(el, path.segments[i]); if (el == null) { return; } } String name = path.segments[len]; if (path.attribute != null) { visitMapAttributes(ctx, xam, el, name, path.attribute, visitor, result); } else { visitMapElements(ctx, xam, el, name, visitor, result); } } public static void visitMapAttributes(Context ctx, XAnnotatedMap xam, Node base, String name, String attrName, NodeMapVisitor visitor, Map<String, Object> result) { Node p = base.getFirstChild(); while (p != null) { if (p.getNodeType() == Node.ELEMENT_NODE) { if (name.equals(p.getNodeName())) { Node at = p.getAttributes().getNamedItem(attrName); if (at != null) { String key = getNodeValue((Element) p, xam.key); if (key != null) { visitor.visitNode(ctx, xam, at, key, result); } } } } p = p.getNextSibling(); } } public static void visitMapElements(Context ctx, XAnnotatedMap xam, Node base, String name, NodeMapVisitor visitor, Map<String, Object> result) { Node p = base.getFirstChild(); while (p != null) { if (p.getNodeType() == Node.ELEMENT_NODE) { if (name.equals(p.getNodeName())) { String key = getNodeValue((Element) p, xam.key); if (key != null) { visitor.visitNode(ctx, xam, p, key, result); } } } p = p.getNextSibling(); } } public static Node getElementNode(Node base, String name) { Node node = base.getFirstChild(); while (node != null) { if (node.getNodeType() == Node.ELEMENT_NODE) { if (name.equals(node.getNodeName())) { return node; } } node = node.getNextSibling(); } return null; } public static Node getElementNode(Node base, Path path) {<FILL_FUNCTION_BODY>} public abstract static class NodeVisitor { public abstract void visitNode(Context ctx, XAnnotatedMember xam, Node node, Collection<Object> result); } public abstract static class NodeMapVisitor { public abstract void visitNode(Context ctx, XAnnotatedMember xam, Node node, String key, Map<String, Object> result); } }
Node el = base; int len = path.segments.length; for (int i = 0; i < len; i++) { el = getElementNode(el, path.segments[i]); if (el == null) { return null; } } return el;
1,531
81
1,612
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/common/xmap/DOMSerializer.java
DOMSerializer
toString
class DOMSerializer { private static final DocumentBuilderFactory BUILDER_FACTORY = DocumentBuilderFactory .newInstance(); // Default output format which is : no xml declaration, no document type, indent. private static final OutputFormat DEFAULT_FORMAT = new OutputFormat(); static { DEFAULT_FORMAT.setOmitXMLDeclaration(false); DEFAULT_FORMAT.setIndenting(true); DEFAULT_FORMAT.setMethod("xml"); DEFAULT_FORMAT.setEncoding("UTF-8"); } private DOMSerializer() { } public static DocumentBuilderFactory getBuilderFactory() { return BUILDER_FACTORY; } public static String toString(Element element) throws IOException { return toString(element, DEFAULT_FORMAT); } public static String toString(Element element, OutputFormat format) throws IOException {<FILL_FUNCTION_BODY>} public static String toString(DocumentFragment fragment) throws IOException { return toString(fragment, DEFAULT_FORMAT); } public static String toString(DocumentFragment fragment, OutputFormat format) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); write(fragment, format, baos); return baos.toString(); } public static String toString(Document doc) throws IOException { return toString(doc, DEFAULT_FORMAT); } public static String toString(Document doc, OutputFormat format) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); write(doc, format, baos); return baos.toString(); } public static void write(Element element, OutputStream out) throws IOException { write(element, DEFAULT_FORMAT, out); } public static void write(Element element, OutputFormat format, OutputStream out) throws IOException { XMLSerializer serializer = new XMLSerializer(out, format); serializer.asDOMSerializer().serialize(element); } public static void write(DocumentFragment fragment, OutputStream out) throws IOException { write(fragment, DEFAULT_FORMAT, out); } public static void write(DocumentFragment fragment, OutputFormat format, OutputStream out) throws IOException { XMLSerializer serializer = new XMLSerializer(out, format); serializer.asDOMSerializer().serialize(fragment); } public static void write(Document doc, OutputStream out) throws IOException { write(doc, DEFAULT_FORMAT, out); } public static void write(Document doc, OutputFormat format, OutputStream out) throws IOException { XMLSerializer serializer = new XMLSerializer(out, format); serializer.asDOMSerializer().serialize(doc); } }
ByteArrayOutputStream baos = new ByteArrayOutputStream(); write(element, format, baos); return baos.toString();
675
35
710
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/common/xmap/Path.java
Path
parse
class Path { public static final String[] EMPTY_SEGMENTS = new String[0]; public final String path; public String[] segments; public String attribute; public Path(String path) { this.path = path; parse(path); } @Override public String toString() { return path; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof Path) { return ((Path) obj).path.equals(path); } return false; } @Override public int hashCode() { return path.hashCode(); } private void parse(String path) {<FILL_FUNCTION_BODY>} }
ArrayList<String> seg = new ArrayList<String>(); StringBuilder buf = new StringBuilder(); char[] chars = path.toCharArray(); boolean attr = false; for (char c : chars) { switch (c) { case '/': seg.add(buf.toString()); buf.setLength(0); break; case '@': attr = true; seg.add(buf.toString()); buf.setLength(0); break; default: buf.append(c); break; } } if (buf.length() > 0) { if (attr) { attribute = buf.toString(); } else { seg.add(buf.toString()); } } int size = seg.size(); if (size == 1 && seg.get(0).length() == 0) { segments = EMPTY_SEGMENTS; } else { segments = seg.toArray(new String[size]); }
214
262
476
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/common/xmap/PrimitiveArrays.java
PrimitiveArrays
toFloatArray
class PrimitiveArrays { private PrimitiveArrays() { } @SuppressWarnings({ "ObjectEquality" }) public static Object toPrimitiveArray(Collection<Object> col, Class primitiveArrayType) { if (primitiveArrayType == Integer.TYPE) { return toIntArray(col); } else if (primitiveArrayType == Long.TYPE) { return toLongArray(col); } else if (primitiveArrayType == Double.TYPE) { return toDoubleArray(col); } else if (primitiveArrayType == Float.TYPE) { return toFloatArray(col); } else if (primitiveArrayType == Boolean.TYPE) { return toBooleanArray(col); } else if (primitiveArrayType == Byte.TYPE) { return toByteArray(col); } else if (primitiveArrayType == Character.TYPE) { return toCharArray(col); } else if (primitiveArrayType == Short.TYPE) { return toShortArray(col); } return null; } public static int[] toIntArray(Collection col) { int size = col.size(); int[] ar = new int[size]; Iterator it = col.iterator(); int i = 0; while (it.hasNext()) { ar[i++] = (Integer) it.next(); } return ar; } public static long[] toLongArray(Collection col) { int size = col.size(); long[] ar = new long[size]; Iterator it = col.iterator(); int i = 0; while (it.hasNext()) { ar[i++] = (Long) it.next(); } return ar; } public static double[] toDoubleArray(Collection col) { int size = col.size(); double[] ar = new double[size]; Iterator it = col.iterator(); int i = 0; while (it.hasNext()) { ar[i++] = (Double) it.next(); } return ar; } public static float[] toFloatArray(Collection col) {<FILL_FUNCTION_BODY>} public static boolean[] toBooleanArray(Collection col) { int size = col.size(); boolean[] ar = new boolean[size]; Iterator it = col.iterator(); int i = 0; while (it.hasNext()) { ar[i++] = (Boolean) it.next(); } return ar; } public static short[] toShortArray(Collection col) { int size = col.size(); short[] ar = new short[size]; Iterator it = col.iterator(); int i = 0; while (it.hasNext()) { ar[i++] = (Short) it.next(); } return ar; } public static byte[] toByteArray(Collection col) { int size = col.size(); byte[] ar = new byte[size]; Iterator it = col.iterator(); int i = 0; while (it.hasNext()) { ar[i++] = (Byte) it.next(); } return ar; } public static char[] toCharArray(Collection col) { int size = col.size(); char[] ar = new char[size]; Iterator it = col.iterator(); int i = 0; while (it.hasNext()) { ar[i++] = (Character) it.next(); } return ar; } }
int size = col.size(); float[] ar = new float[size]; Iterator it = col.iterator(); int i = 0; while (it.hasNext()) { ar[i++] = (Float) it.next(); } return ar;
914
73
987
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/common/xmap/Resource.java
Resource
toFile
class Resource { private final URL url; public Resource(URL url) { this.url = url; } public Resource(Context ctx, String path) { url = ctx.getResource(path); } public URL toURL() { return url; } public URI toURI() throws URISyntaxException { return url != null ? url.toURI() : null; } public File toFile() throws URISyntaxException {<FILL_FUNCTION_BODY>} }
return url != null ? new File(url.toURI()) : null;
141
22
163
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/common/xmap/XAnnotatedContent.java
XAnnotatedContent
getValue
class XAnnotatedContent extends XAnnotatedMember { private static final OutputFormat DEFAULT_FORMAT = new OutputFormat(); static { DEFAULT_FORMAT.setOmitXMLDeclaration(true); DEFAULT_FORMAT.setIndenting(true); DEFAULT_FORMAT.setMethod("xml"); DEFAULT_FORMAT.setEncoding("UTF-8"); } public XAnnotatedContent(XMap xmap, XSetter setter, XGetter getter, XContent anno) { super(xmap, setter, getter); this.path = new Path(anno.value()); this.type = setter.getType(); this.valueFactory = xmap.getValueFactory(this.type); this.xao = xmap.register(this.type); } @Override protected Object getValue(Context ctx, Element base) throws IOException {<FILL_FUNCTION_BODY>} @Override public void decode(Object instance, Node base, Document document, List<String> filters) throws Exception { // do nothing } }
Element el = (Element) DOMHelper.getElementNode(base, path); if (el == null) { return null; } el.normalize(); Node node = el.getFirstChild(); if (node == null) { return ""; } Range range = ((DocumentRange) el.getOwnerDocument()).createRange(); range.setStartBefore(node); range.setEndAfter(el.getLastChild()); DocumentFragment fragment = range.cloneContents(); boolean asDOM = setter.getType() == DocumentFragment.class; return asDOM ? fragment : DOMSerializer.toString(fragment, DEFAULT_FORMAT);
274
162
436
<methods>public void <init>(com.alipay.sofa.common.xmap.XMap, com.alipay.sofa.common.xmap.XSetter, com.alipay.sofa.common.xmap.XGetter, com.alipay.sofa.common.xmap.annotation.XNode) ,public void decode(java.lang.Object, org.w3c.dom.Node, org.w3c.dom.Document, List<java.lang.String>) throws java.lang.Exception,public void process(com.alipay.sofa.common.xmap.Context, org.w3c.dom.Element) throws java.lang.Exception,public void process(com.alipay.sofa.common.xmap.Context, Map<java.lang.String,java.lang.Object>, java.lang.String) throws java.lang.Exception<variables>public boolean cdata,public final non-sealed com.alipay.sofa.common.xmap.XGetter getter,public com.alipay.sofa.common.xmap.Path path,public final non-sealed com.alipay.sofa.common.xmap.XSetter setter,public boolean trim,public Class#RAW type,public com.alipay.sofa.common.xmap.XValueFactory valueFactory,public com.alipay.sofa.common.xmap.XAnnotatedObject xao,public final non-sealed com.alipay.sofa.common.xmap.XMap xmap
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/common/xmap/XAnnotatedList.java
XAnnotatedList
decode
class XAnnotatedList extends XAnnotatedMember { protected static final ElementVisitor elementListVisitor = new ElementVisitor(); protected static final ElementValueVisitor elementVisitor = new ElementValueVisitor(); protected static final AttributeValueVisitor attributeVisitor = new AttributeValueVisitor(); // indicates the type of the collection components public Class<?> componentType; protected XAnnotatedList(XMap xmap, XSetter setter, XGetter getter) { super(xmap, setter, getter); } public XAnnotatedList(XMap xmap, XSetter setter, XGetter getter, XNodeList anno) { super(xmap, setter, getter); path = new Path(anno.value()); trim = anno.trim(); type = anno.type(); cdata = anno.cdata(); componentType = anno.componentType(); valueFactory = xmap.getValueFactory(componentType); xao = xmap.register(componentType); } @SuppressWarnings("unchecked") @Override protected Object getValue(Context ctx, Element base) throws Exception { ArrayList<Object> values = new ArrayList<Object>(); if (xao != null) { DOMHelper.visitNodes(ctx, this, base, path, elementListVisitor, values); } else { if (path.attribute != null) { // attribute list DOMHelper.visitNodes(ctx, this, base, path, attributeVisitor, values); } else { // element list DOMHelper.visitNodes(ctx, this, base, path, elementVisitor, values); } } if (type != ArrayList.class) { if (type.isArray()) { if (componentType.isPrimitive()) { // primitive arrays cannot be cast to Object[] return PrimitiveArrays.toPrimitiveArray(values, componentType); } else { return values .toArray((Object[]) Array.newInstance(componentType, values.size())); } } else { Collection col = (Collection) type.newInstance(); col.addAll(values); return col; } } return values; } @SuppressWarnings("unchecked") public void decode(Object instance, Node base, Document document, List<String> filters) throws Exception {<FILL_FUNCTION_BODY>} }
if (!isFilter(filters)) { return; } Collection col = null; if (Collection.class.isAssignableFrom(type)) { col = (Collection) getter.getValue(instance); } else { if (type.isArray()) { col = new ArrayList(); Object obj = getter.getValue(instance); int length = Array.getLength(obj); for (int i = 0; i < length; i++) { col.add(Array.get(obj, i)); } } else { throw new Exception("@XNodeList " + base.getNodeName() + " 'type' only support Collection ande Array type"); } } Node node = base; int len = path.segments.length - 1; for (int i = 0; i < len; i++) { Node n = DOMHelper.getElementNode(node, path.segments[i]); if (n == null) { Element element = document.createElement(path.segments[i]); node = node.appendChild(element); } else { node = n; } } String name = path.segments[len]; Node lastParentNode = node; for (Object object : col) { Element element = document.createElement(name); node = lastParentNode.appendChild(element); if (xao != null) { xao.decode(object, node, document, filters); } else { String value = object == null ? "" : object.toString(); if (path.attribute != null && path.attribute.length() > 0) { Attr attr = document.createAttribute(path.attribute); attr.setNodeValue(value); ((Element) node).setAttributeNode(attr); } else { if (cdata) { CDATASection cdataSection = document.createCDATASection(value); node.appendChild(cdataSection); } else { node.setTextContent(value); } } } }
636
538
1,174
<methods>public void <init>(com.alipay.sofa.common.xmap.XMap, com.alipay.sofa.common.xmap.XSetter, com.alipay.sofa.common.xmap.XGetter, com.alipay.sofa.common.xmap.annotation.XNode) ,public void decode(java.lang.Object, org.w3c.dom.Node, org.w3c.dom.Document, List<java.lang.String>) throws java.lang.Exception,public void process(com.alipay.sofa.common.xmap.Context, org.w3c.dom.Element) throws java.lang.Exception,public void process(com.alipay.sofa.common.xmap.Context, Map<java.lang.String,java.lang.Object>, java.lang.String) throws java.lang.Exception<variables>public boolean cdata,public final non-sealed com.alipay.sofa.common.xmap.XGetter getter,public com.alipay.sofa.common.xmap.Path path,public final non-sealed com.alipay.sofa.common.xmap.XSetter setter,public boolean trim,public Class#RAW type,public com.alipay.sofa.common.xmap.XValueFactory valueFactory,public com.alipay.sofa.common.xmap.XAnnotatedObject xao,public final non-sealed com.alipay.sofa.common.xmap.XMap xmap
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/common/xmap/XAnnotatedMap.java
XAnnotatedMap
getValue
class XAnnotatedMap extends XAnnotatedList { protected static final ElementMapVisitor elementMapVisitor = new ElementMapVisitor(); protected static final ElementValueMapVisitor elementVisitor = new ElementValueMapVisitor(); protected static final AttributeValueMapVisitor attributeVisitor = new AttributeValueMapVisitor(); protected Path key; public XAnnotatedMap(XMap xmap, XSetter setter, XGetter getter, XNodeMap anno) { super(xmap, setter, getter); if (anno != null) { path = new Path(anno.value()); trim = anno.trim(); key = new Path(anno.key()); type = anno.type(); cdata = anno.cdata(); componentType = anno.componentType(); valueFactory = xmap.getValueFactory(componentType); xao = xmap.register(componentType); } } @SuppressWarnings("unchecked") @Override protected Object getValue(Context ctx, Element base) throws IllegalAccessException, InstantiationException {<FILL_FUNCTION_BODY>} @SuppressWarnings("unchecked") @Override public void decode(Object instance, Node base, Document document, List<String> filters) throws Exception { if (!isFilter(filters)) { return; } Map values = (Map) getter.getValue(instance); Node node = base; int len = path.segments.length - 1; for (int i = 0; i < len; i++) { Node n = DOMHelper.getElementNode(node, path.segments[i]); if (n == null) { Element element = document.createElement(path.segments[i]); node = node.appendChild(element); } else { node = n; } } String name = path.segments[len]; Node lastParentNode = node; Set<Map.Entry> entrys = values.entrySet(); for (Map.Entry entry : entrys) { Element element = document.createElement(name); node = lastParentNode.appendChild(element); Object keyObj = entry.getKey(); String keyValue = keyObj == null ? "" : keyObj.toString(); Object object = entry.getValue(); Attr attrKey = document.createAttribute(key.attribute); attrKey.setNodeValue(keyValue); ((Element) node).setAttributeNode(attrKey); if (xao != null) { xao.decode(object, node, document, filters); } else { String value = object == null ? "" : object.toString(); if (path.attribute != null && path.attribute.length() > 0) { Attr attrValue = document.createAttribute(path.attribute); attrValue.setNodeValue(value); ((Element) node).setAttributeNode(attrValue); } else { if (cdata) { CDATASection cdataSection = document.createCDATASection(value); node.appendChild(cdataSection); } else { node.setTextContent(value); } } } } } }
Map<String, Object> values = (Map) type.newInstance(); if (xao != null) { DOMHelper.visitMapNodes(ctx, this, base, path, elementMapVisitor, values); } else { if (path.attribute != null) { // attribute list DOMHelper.visitMapNodes(ctx, this, base, path, attributeVisitor, values); } else { // element list DOMHelper.visitMapNodes(ctx, this, base, path, elementVisitor, values); } } return values;
840
149
989
<methods>public void <init>(com.alipay.sofa.common.xmap.XMap, com.alipay.sofa.common.xmap.XSetter, com.alipay.sofa.common.xmap.XGetter, com.alipay.sofa.common.xmap.annotation.XNodeList) ,public void decode(java.lang.Object, org.w3c.dom.Node, org.w3c.dom.Document, List<java.lang.String>) throws java.lang.Exception<variables>protected static final com.alipay.sofa.common.xmap.AttributeValueVisitor attributeVisitor,public Class<?> componentType,protected static final com.alipay.sofa.common.xmap.ElementVisitor elementListVisitor,protected static final com.alipay.sofa.common.xmap.ElementValueVisitor elementVisitor
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/common/xmap/XAnnotatedMember.java
XAnnotatedMember
isFilter
class XAnnotatedMember { public final XMap xmap; public final XSetter setter; public final XGetter getter; public Path path; public boolean trim; public boolean cdata; // the java type of the described element public Class type; // not null if the described object is an xannotated object public XAnnotatedObject xao; // the value factory used to transform strings in objects compatible // with this member type // In the case of collection types this factory is // used for collection components public XValueFactory valueFactory; protected XAnnotatedMember(XMap xmap, XSetter setter, XGetter getter) { this.xmap = xmap; this.setter = setter; this.getter = getter; } public XAnnotatedMember(XMap xmap, XSetter setter, XGetter getter, XNode anno) { this.xmap = xmap; this.setter = setter; this.getter = getter; this.path = new Path(anno.value()); this.trim = anno.trim(); this.cdata = anno.cdata(); this.type = setter.getType(); this.valueFactory = xmap.getValueFactory(this.type); this.xao = xmap.register(this.type); } protected void setValue(Object instance, Object value) throws Exception { setter.setValue(instance, value); } public void process(Context ctx, Element element) throws Exception { Object value = getValue(ctx, element); if (value != null) { setValue(ctx.getObject(), value); } } public void process(Context ctx, Map<String, Object> map, String keyPrefix) throws Exception { Object value = getValue(ctx, map, keyPrefix); if (value != null) { setValue(ctx.getObject(), value); } } public void decode(Object instance, Node base, Document document, List<String> filters) throws Exception { if (!isFilter(filters)) { return; } Node node = base; int len = path.segments.length; for (int i = 0; i < len; i++) { Node n = DOMHelper.getElementNode(node, path.segments[i]); if (n == null) { Element element = document.createElement(path.segments[i]); node = node.appendChild(element); } else { node = n; } } Object object = getter.getValue(instance); if (object != null && Element.class.isAssignableFrom(object.getClass())) { return; } if (xao != null) { xao.decode(object, node, document, filters); } else { String value = object == null ? "" : object.toString(); if (path.attribute != null && path.attribute.length() > 0) { Attr attr = document.createAttribute(path.attribute); attr.setNodeValue(value); ((Element) node).setAttributeNode(attr); } else { if (cdata) { CDATASection cdataSection = document.createCDATASection(value); node.appendChild(cdataSection); } else { node.setTextContent(value); } } } } protected Object getValue(Context ctx, Element base) throws Exception { if (xao != null) { Element el = (Element) DOMHelper.getElementNode(base, path); return el == null ? null : xao.newInstance(ctx, el); } // scalar field if (type == Element.class) { // allow DOM elements as values return base; } String val = DOMHelper.getNodeValue(base, path); if (val != null) { if (trim) { val = val.trim(); } return valueFactory.getValue(ctx, val); } return null; } protected Object getValue(Context ctx, Map<String, Object> map, String keyPrefix) throws Exception { String key = keyPrefix == null ? path.path : keyPrefix + path.path; Object val = map.get(key); Object result = null; if (val == null) { result = null; } else if (val instanceof String) { String str = (String) val; if (str != null) { if (trim) { str = str.trim(); } result = valueFactory.getValue(ctx, str); } } else { result = val; } return result; } protected boolean isFilter(List<String> filters) {<FILL_FUNCTION_BODY>} }
boolean filter = false; if (filters == null || filters.size() == 0) { filter = true; } else { filter = filters.contains(path.path); } return filter;
1,273
60
1,333
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/common/xmap/XAnnotatedObject.java
XAnnotatedObject
newInstance
class XAnnotatedObject { public final XMap xmap; public final Class<?> klass; public final Path path; final List<XAnnotatedMember> members; Sorter sorter; Sorter deSorter; public XAnnotatedObject(XMap xmap, Class<?> klass, XObject xob) { this.xmap = xmap; this.klass = klass; path = new Path(xob.value()); members = new ArrayList<>(); String[] order = xob.order(); if (order.length > 0) { sorter = new Sorter(order); } } public void addMember(XAnnotatedMember member) { members.add(member); } public Path getPath() { return path; } public Object newInstance(Context ctx, Element element) throws Exception {<FILL_FUNCTION_BODY>} public Object newInstance(Context ctx, Map<String, Object> map, String keyPrefix) throws Exception { Object ob = klass.newInstance(); ctx.push(ob); // set annotated members for (XAnnotatedMember member : members) { member.process(ctx, map, keyPrefix); } return ctx.pop(); } public void decode(Object instance, Node base, Document document, List<String> filters) throws Exception { Node node = base; String name = path.path; if (sorter != null) { deSorter = sorter; } if (deSorter != null) { Collections.sort(members, deSorter); deSorter = null; // sort only once } if (name != null && name.length() > 0) { Element element = document.createElement(name); node = node.appendChild(element); } for (XAnnotatedMember annotatedMember : members) { annotatedMember.decode(instance, node, document, filters); } } }
Object ob = klass.newInstance(); ctx.push(ob); if (sorter != null) { Collections.sort(members, sorter); deSorter = sorter; sorter = null; // sort only once } // set annotated members for (XAnnotatedMember member : members) { member.process(ctx, element); } return ctx.pop();
544
112
656
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/common/xmap/XFieldGetter.java
XFieldGetter
getValue
class XFieldGetter implements XGetter { /** * field */ private Field field; public XFieldGetter(Field field) { this.field = field; this.field.setAccessible(true); } /** * @see XGetter#getType() */ public Class<?> getType() { return field.getType(); } /** * @see XGetter#getValue(Object) */ public Object getValue(Object instance) throws Exception {<FILL_FUNCTION_BODY>} }
if (instance == null) { return null; } return field.get(instance);
153
29
182
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/common/xmap/XMethodGetter.java
XMethodGetter
getType
class XMethodGetter implements XGetter { /** * method */ private Method method; /** * class */ private Class<?> clazz; /** * bean name */ private String name; public XMethodGetter(Method method, Class<?> clazz, String name) { this.method = method; this.clazz = clazz; this.name = name; } /** * @see XGetter#getType() */ public Class<?> getType() {<FILL_FUNCTION_BODY>} /** * @see XGetter#getValue(Object) */ public Object getValue(Object instance) throws Exception { if (method == null) { throw new IllegalArgumentException("no such getter method: " + clazz.getName() + '.' + name); } if (instance == null) { return null; } return method.invoke(instance, new Object[0]); } }
if (method == null) { throw new IllegalArgumentException("no such getter method: " + clazz.getName() + '.' + name); } return method.getReturnType();
274
53
327
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/common/xmap/XValueFactory.java
XValueFactory
getValue
class XValueFactory { private static final Logger LOGGER = SofaBootLoggerFactory .getLogger(XValueFactory.class); static final Map<Class, XValueFactory> defaultFactories = new Hashtable<Class, XValueFactory>(); public abstract Object getValue(Context ctx, String value); public final Object getElementValue(Context ctx, Node element, boolean trim) { String text = element.getTextContent(); return getValue(ctx, trim ? text.trim() : text); } public final Object getAttributeValue(Context ctx, Node element, String name) { Node at = element.getAttributes().getNamedItem(name); return at != null ? getValue(ctx, at.getNodeValue()) : null; } public static void addFactory(Class klass, XValueFactory factory) { defaultFactories.put(klass, factory); } public static XValueFactory getFactory(Class type) { return defaultFactories.get(type); } public static Object getValue(Context ctx, Class klass, String value) { XValueFactory factory = defaultFactories.get(klass); if (factory == null) { return null; } return factory.getValue(ctx, value); } public static final XValueFactory STRING = new XValueFactory() { @Override public Object getValue(Context ctx, String value) { return value; } }; public static final XValueFactory INTEGER = new XValueFactory() { @Override public Object getValue(Context ctx, String value) { return Integer.valueOf(value); } }; public static final XValueFactory LONG = new XValueFactory() { @Override public Object getValue(Context ctx, String value) { return Long.valueOf(value); } }; public static final XValueFactory DOUBLE = new XValueFactory() { @Override public Object getValue(Context ctx, String value) { return Double.valueOf(value); } }; public static final XValueFactory FLOAT = new XValueFactory() { @Override public Object getValue(Context ctx, String value) { return Float.valueOf(value); } }; public static final XValueFactory BOOLEAN = new XValueFactory() { @Override public Object getValue(Context ctx, String value) { return Boolean.valueOf(value); } }; public static final XValueFactory DATE = new XValueFactory() { final DateFormat df = new SimpleDateFormat( "dd-MM-yyyy"); @Override public Object getValue(Context ctx, String value) { try { return df.parse(value); } catch (Exception e) { return null; } } }; public static final XValueFactory FILE = new XValueFactory() { @Override public Object getValue(Context ctx, String value) { return new File(value); } }; public static final XValueFactory URL = new XValueFactory() { @Override public Object getValue(Context ctx, String value) { try { return new java.net.URL(value); } catch (Exception e) { return null; } } }; public static final XValueFactory CLASS = new XValueFactory() { @Override public Object getValue(Context ctx, String value) { try { return ctx.loadClass(value); } catch (Throwable t) { LOGGER.error("load class error", t); return null; } } }; public static final XValueFactory RESOURCE = new XValueFactory() { @Override public Object getValue(Context ctx, String value) { try { return new Resource( ctx.getResource(value)); } catch (Throwable t) { LOGGER.error("new resource error", t); return null; } } }; public static final XValueFactory SHORT = new XValueFactory() { @Override public Object getValue(Context ctx, String value) { return Short.valueOf(value); } }; public static final XValueFactory CHAR = new XValueFactory() { @Override public Object getValue(Context ctx, String value) { try { return value.toCharArray()[0]; } catch (Throwable e) { return null; } } }; public static final XValueFactory BYTE = new XValueFactory() { @Override public Object getValue(Context ctx, String value) {<FILL_FUNCTION_BODY>} }; static { addFactory(String.class, STRING); addFactory(Integer.class, INTEGER); addFactory(Long.class, LONG); addFactory(Float.class, FLOAT); addFactory(Double.class, DOUBLE); addFactory(Date.class, DATE); addFactory(Boolean.class, BOOLEAN); addFactory(File.class, FILE); addFactory(java.net.URL.class, URL); addFactory(Short.class, SHORT); addFactory(Character.class, CHAR); addFactory(Byte.class, BYTE); addFactory(int.class, INTEGER); addFactory(long.class, LONG); addFactory(double.class, DOUBLE); addFactory(float.class, FLOAT); addFactory(boolean.class, BOOLEAN); addFactory(short.class, SHORT); addFactory(char.class, CHAR); addFactory(byte.class, BYTE); addFactory(Class.class, CLASS); addFactory(Resource.class, RESOURCE); } }
try { return value.getBytes()[0]; } catch (Throwable e) { return null; }
1,607
42
1,649
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/common/xmap/annotation/spring/XAnnotatedListSpring.java
XAnnotatedListSpring
getValue
class XAnnotatedListSpring extends XAnnotatedList { /** * dom visitor */ protected static final ElementValueVisitor elementVisitor = new ElementValueVisitor(); protected static final AttributeValueVisitor attributeVisitor = new AttributeValueVisitor(); private XAnnotatedSpringObject xaso; protected XAnnotatedListSpring(XMap xmap, XSetter setter, XGetter getter) { super(xmap, setter, getter); } public XAnnotatedListSpring(XMap xmap, XSetter setter, XGetter getter, XNodeListSpring anno, XAnnotatedSpringObject xaso) { super(xmap, setter, getter); path = new Path(anno.value()); trim = anno.trim(); type = anno.type(); componentType = anno.componentType(); this.xaso = xaso; } @SuppressWarnings("unchecked") @Override protected Object getValue(Context ctx, Element base) throws Exception {<FILL_FUNCTION_BODY>} public void setXaso(XAnnotatedSpringObject xaso) { this.xaso = xaso; } public XAnnotatedSpringObject getXaso() { return xaso; } }
ArrayList<Object> values = new ArrayList<Object>(); if (path.attribute != null) { // attribute list DOMHelper.visitNodes(ctx, this, base, path, attributeVisitor, values); } else { // element list DOMHelper.visitNodes(ctx, this, base, path, elementVisitor, values); } if (type != ArrayList.class) { if (type.isArray() && !componentType.isPrimitive()) { values.toArray((Object[]) Array.newInstance(componentType, values.size())); } else { Collection col = (Collection) type.newInstance(); col.addAll(values); return col; } } return values;
362
190
552
<methods>public void <init>(com.alipay.sofa.common.xmap.XMap, com.alipay.sofa.common.xmap.XSetter, com.alipay.sofa.common.xmap.XGetter, com.alipay.sofa.common.xmap.annotation.XNodeList) ,public void decode(java.lang.Object, org.w3c.dom.Node, org.w3c.dom.Document, List<java.lang.String>) throws java.lang.Exception<variables>protected static final com.alipay.sofa.common.xmap.AttributeValueVisitor attributeVisitor,public Class<?> componentType,protected static final com.alipay.sofa.common.xmap.ElementVisitor elementListVisitor,protected static final com.alipay.sofa.common.xmap.ElementValueVisitor elementVisitor
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/common/xmap/annotation/spring/XAnnotatedMapSpring.java
ElementValueMapVisitor
visitNode
class ElementValueMapVisitor extends DOMHelper.NodeMapVisitor { @Override public void visitNode(Context ctx, XAnnotatedMember xam, Node node, String key, Map<String, Object> result) {<FILL_FUNCTION_BODY>} }
String val = node.getTextContent(); if (val != null && val.length() > 0) { if (xam.trim) val = val.trim(); Object object = XMapSpringUtil.getSpringObject( ((XAnnotatedMapSpring) xam).componentType, val, ((XAnnotatedMapSpring) xam) .getXaso().getApplicationContext()); if (object != null) result.put(key, object); }
70
128
198
<methods>public non-sealed void <init>() ,public abstract void visitNode(com.alipay.sofa.common.xmap.Context, com.alipay.sofa.common.xmap.XAnnotatedMember, org.w3c.dom.Node, java.lang.String, Map<java.lang.String,java.lang.Object>) <variables>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/common/xmap/annotation/spring/XAnnotatedSpring.java
XAnnotatedSpring
getValue
class XAnnotatedSpring extends XAnnotatedMember { public XAnnotatedSpringObject xaso; protected XAnnotatedSpring(XMap xmap, XSetter setter, XGetter getter) { super(xmap, setter, getter); } public XAnnotatedSpring(XMap xmap, XSetter setter, XGetter getter, XNodeSpring anno, XAnnotatedSpringObject xaso) { super(xmap, setter, getter); path = new Path(anno.value()); trim = anno.trim(); type = setter.getType(); this.xaso = xaso; } @SuppressWarnings("unchecked") @Override protected Object getValue(Context ctx, Element base) throws Exception {<FILL_FUNCTION_BODY>} }
// scalar field if (type == Element.class) { // allow DOM elements as values return base; } return XMapSpringUtil.getSpringObject(this, xaso.getApplicationContext(), base);
230
61
291
<methods>public void <init>(com.alipay.sofa.common.xmap.XMap, com.alipay.sofa.common.xmap.XSetter, com.alipay.sofa.common.xmap.XGetter, com.alipay.sofa.common.xmap.annotation.XNode) ,public void decode(java.lang.Object, org.w3c.dom.Node, org.w3c.dom.Document, List<java.lang.String>) throws java.lang.Exception,public void process(com.alipay.sofa.common.xmap.Context, org.w3c.dom.Element) throws java.lang.Exception,public void process(com.alipay.sofa.common.xmap.Context, Map<java.lang.String,java.lang.Object>, java.lang.String) throws java.lang.Exception<variables>public boolean cdata,public final non-sealed com.alipay.sofa.common.xmap.XGetter getter,public com.alipay.sofa.common.xmap.Path path,public final non-sealed com.alipay.sofa.common.xmap.XSetter setter,public boolean trim,public Class#RAW type,public com.alipay.sofa.common.xmap.XValueFactory valueFactory,public com.alipay.sofa.common.xmap.XAnnotatedObject xao,public final non-sealed com.alipay.sofa.common.xmap.XMap xmap
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/common/xmap/annotation/spring/XMapSpring.java
XMapSpring
scan
class XMapSpring extends XMap { @SuppressWarnings("unchecked") public XAnnotatedObject register(Class klass, ApplicationContext applicationContext) { XAnnotatedObject xao = objects.get(klass); if (xao == null) { // avoid scanning twice XObject xob = checkObjectAnnotation(klass, klass.getClassLoader()); if (xob != null) { xao = new XAnnotatedSpringObject(this, klass, xob, applicationContext); objects.put(xao.klass, xao); scan(xao); String key = xob.value(); if (key.length() > 0) { roots.put(xao.path.path, xao); } } } return xao; } /** * Scan Field * * @param xob XAnnotated Object */ private void scan(XAnnotatedObject xob) {<FILL_FUNCTION_BODY>} private XAnnotatedMember createExtendFieldMember(Field field, Annotation annotation, XAnnotatedObject xob) { XSetter setter = new XFieldSetter(field); XGetter getter = new XFieldGetter(field); return createExtendMember(annotation, setter, getter, xob); } public final XAnnotatedMember createExtendMethodMember(Method method, Annotation annotation, XAnnotatedObject xob) { XSetter setter = new XMethodSetter(method); XGetter getter = new XMethodGetter(null, null, null); return createExtendMember(annotation, setter, getter, xob); } private XAnnotatedMember createExtendMember(Annotation annotation, XSetter setter, XGetter getter, XAnnotatedObject xob) { XAnnotatedMember member = null; int type = annotation.annotationType().getAnnotation(XMemberAnnotation.class).value(); if (type == XMemberAnnotation.NODE_SPRING) { member = new XAnnotatedSpring(this, setter, getter, (XNodeSpring) annotation, (XAnnotatedSpringObject) xob); } else if (type == XMemberAnnotation.NODE_LIST_SPRING) { member = new XAnnotatedListSpring(this, setter, getter, (XNodeListSpring) annotation, (XAnnotatedSpringObject) xob); } else if (type == XMemberAnnotation.NODE_MAP_SPRING) { member = new XAnnotatedMapSpring(this, setter, getter, (XNodeMapSpring) annotation, (XAnnotatedSpringObject) xob); } return member; } }
Field[] fields = xob.klass.getDeclaredFields(); for (Field field : fields) { Annotation anno = checkMemberAnnotation(field); if (anno != null) { XAnnotatedMember member = createFieldMember(field, anno); if (member == null) { member = createExtendFieldMember(field, anno, xob); } xob.addMember(member); } } Method[] methods = xob.klass.getDeclaredMethods(); for (Method method : methods) { // we accept only methods with one parameter Class[] paramTypes = method.getParameterTypes(); if (paramTypes.length != 1) { continue; } Annotation anno = checkMemberAnnotation(method); if (anno != null) { XAnnotatedMember member = createMethodMember(method, xob.klass, anno); if (member == null) { member = createExtendMethodMember(method, anno, xob); } xob.addMember(member); } }
718
283
1,001
<methods>public void <init>() ,public org.w3c.dom.Document asXml(java.lang.Object, List<java.lang.String>) throws java.lang.Exception,public java.lang.String asXmlString(java.lang.Object, java.lang.String, List<java.lang.String>) throws java.lang.Exception,public java.lang.String asXmlString(java.lang.Object, java.lang.String, List<java.lang.String>, boolean) throws java.lang.Exception,public final com.alipay.sofa.common.xmap.XAnnotatedMember createFieldMember(java.lang.reflect.Field, java.lang.annotation.Annotation) ,public final com.alipay.sofa.common.xmap.XAnnotatedMember createMethodMember(java.lang.reflect.Method, Class<?>, java.lang.annotation.Annotation) ,public java.lang.reflect.Method getGetterMethod(Class<?>, java.lang.String) ,public Collection<com.alipay.sofa.common.xmap.XAnnotatedObject> getRootObjects() ,public Collection<com.alipay.sofa.common.xmap.XAnnotatedObject> getScannedObjects() ,public com.alipay.sofa.common.xmap.XValueFactory getValueFactory(Class#RAW) ,public java.lang.Object load(java.net.URL) throws java.lang.Exception,public java.lang.Object load(com.alipay.sofa.common.xmap.Context, java.net.URL) throws java.lang.Exception,public java.lang.Object load(java.io.InputStream) throws java.lang.Exception,public java.lang.Object load(com.alipay.sofa.common.xmap.Context, java.io.InputStream) throws java.lang.Exception,public java.lang.Object load(org.w3c.dom.Element) throws java.lang.Exception,public java.lang.Object load(com.alipay.sofa.common.xmap.Context, org.w3c.dom.Element) throws java.lang.Exception,public T load(Map<java.lang.String,java.lang.Object>, java.lang.String, Class<T>) throws java.lang.Exception,public java.lang.Object[] loadAll(java.net.URL) throws java.lang.Exception,public java.lang.Object[] loadAll(com.alipay.sofa.common.xmap.Context, java.net.URL) throws java.lang.Exception,public java.lang.Object[] loadAll(java.io.InputStream) throws java.lang.Exception,public java.lang.Object[] loadAll(com.alipay.sofa.common.xmap.Context, java.io.InputStream) throws java.lang.Exception,public java.lang.Object[] loadAll(com.alipay.sofa.common.xmap.Context, org.w3c.dom.Element) throws java.lang.Exception,public java.lang.Object[] loadAll(org.w3c.dom.Element) throws java.lang.Exception,public void loadAll(org.w3c.dom.Element, Collection<java.lang.Object>) throws java.lang.Exception,public void loadAll(com.alipay.sofa.common.xmap.Context, org.w3c.dom.Element, Collection<java.lang.Object>) throws java.lang.Exception,public com.alipay.sofa.common.xmap.XAnnotatedObject register(Class#RAW) ,public com.alipay.sofa.common.xmap.XAnnotatedObject register(Class#RAW, boolean) ,public void setValueFactory(Class#RAW, com.alipay.sofa.common.xmap.XValueFactory) <variables>private static final java.lang.String DDD,protected final non-sealed Map<Class#RAW,com.alipay.sofa.common.xmap.XValueFactory> factories,protected final non-sealed Map<Class#RAW,com.alipay.sofa.common.xmap.XAnnotatedObject> objects,protected final non-sealed Map<java.lang.String,com.alipay.sofa.common.xmap.XAnnotatedObject> roots
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/common/xmap/annotation/spring/XMapSpringUtil.java
XMapSpringUtil
getSpringObject
class XMapSpringUtil { /** * Get spring object * @param type type * @param beanName bean name * @param applicationContext application context * @return spring object */ public static Object getSpringObject(Class type, String beanName, ApplicationContext applicationContext) { if (type == Resource.class) { return applicationContext.getResource(beanName); } else { return applicationContext.getBean(beanName, type); } } /** * Get spring object * @param xam XAnnotated member * @param applicationContext application context * @param base element base * @return */ public static Object getSpringObject(XAnnotatedMember xam, ApplicationContext applicationContext, Element base) {<FILL_FUNCTION_BODY>} }
String val = DOMHelper.getNodeValue(base, xam.path); if (val != null && val.length() > 0) { if (xam.trim) { val = val.trim(); } return getSpringObject(xam.type, val, applicationContext); } return null;
216
86
302
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/api/binding/BindingType.java
BindingType
equals
class BindingType { private final String type; /** * Set the binding type. * * @param type The binding type to set. */ public BindingType(String type) { this.type = type; } /** * Get the binding type. * * @return The binding type. */ public String getType() { return type; } /** * String representation of {@link BindingType} * * @return String representation of {@link BindingType} */ @Override public String toString() { return type; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return type != null ? type.hashCode() : 0; } }
if (this == o) { return true; } else if (o == null || getClass() != o.getClass()) { return false; } BindingType that = (BindingType) o; return type != null ? type.equals(that.type) : that.type == null;
227
84
311
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/api/component/ComponentName.java
ComponentName
equals
class ComponentName implements Serializable { @Serial private static final long serialVersionUID = -6856142686482394411L; /** * component type */ private final ComponentType type; /** * component name */ private final String name; /** * raw name */ private final String rawName; /** * build ComponentName by component type and component name * * @param type component type * @param name component name */ public ComponentName(ComponentType type, String name) { this.type = type; this.name = name; this.rawName = this.type.getName() + ":" + this.name; } public final ComponentType getType() { return type; } /** * Gets the name part of the component name. * * @return the name part */ public final String getName() { return name; } public final String getRawName() { return rawName; } @Override public boolean equals(Object obj) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return rawName.hashCode(); } @Override public String toString() { return rawName; } }
if (obj == this) { return true; } return obj instanceof ComponentName && rawName.equals(((ComponentName) obj).rawName);
360
42
402
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/async/AsyncInitMethodManager.java
AsyncInitMethodManager
findAsyncInitMethod
class AsyncInitMethodManager implements PriorityOrdered, ApplicationListener<ContextRefreshedEvent>, ApplicationContextAware { public static final String ASYNC_INIT_METHOD_EXECUTOR_BEAN_NAME = "async-init-method-executor"; public static final String ASYNC_INIT_METHOD_NAME = "async-init-method-name"; private final AtomicReference<ExecutorService> executorServiceRef = new AtomicReference<>(); private final Map<BeanFactory, Map<String, String>> asyncInitBeanNameMap = new ConcurrentHashMap<>(); private final List<Future<?>> futures = new ArrayList<>(); private ApplicationContext applicationContext; private boolean startUpFinish = false; @Override public void onApplicationEvent(ContextRefreshedEvent event) { if (applicationContext.equals(event.getApplicationContext())) { ensureAsyncTasksFinish(); } } @Override public int getOrder() { return Ordered.HIGHEST_PRECEDENCE + 1; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } public void submitTask(Runnable runnable) { if (executorServiceRef.get() == null) { ExecutorService executorService = createAsyncExecutorService(); boolean success = executorServiceRef.compareAndSet(null, executorService); if (!success) { executorService.shutdown(); } } Future<?> future = executorServiceRef.get().submit(runnable); futures.add(future); } private ExecutorService createAsyncExecutorService() { return (ExecutorService) applicationContext.getBean(ASYNC_INIT_METHOD_EXECUTOR_BEAN_NAME, Supplier.class).get(); } void ensureAsyncTasksFinish() { for (Future<?> future : futures) { try { future.get(); } catch (Throwable e) { throw new RuntimeException("Async init task finish fail", e); } } startUpFinish = true; futures.clear(); asyncInitBeanNameMap.clear(); if (executorServiceRef.get() != null) { executorServiceRef.get().shutdown(); executorServiceRef.set(null); } } public boolean isStartUpFinish() { return startUpFinish; } public void registerAsyncInitBean(ConfigurableListableBeanFactory beanFactory, String beanName, String asyncInitMethodName) { Map<String, String> map = asyncInitBeanNameMap.computeIfAbsent(beanFactory, k -> new ConcurrentHashMap<>()); map.put(beanName, asyncInitMethodName); } public String findAsyncInitMethod(ConfigurableListableBeanFactory beanFactory, String beanName) {<FILL_FUNCTION_BODY>} }
Map<String, String> map = asyncInitBeanNameMap.get(beanFactory); if (map == null) { return null; } else { return map.get(beanName); }
775
56
831
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/async/AsyncInitializeBeanMethodInvoker.java
AsyncInitializeBeanMethodInvoker
invoke
class AsyncInitializeBeanMethodInvoker implements MethodInterceptor { private static final Logger LOGGER = SofaBootLoggerFactory .getLogger(AsyncInitializeBeanMethodInvoker.class); private final AsyncInitMethodManager asyncInitMethodManager; private final Object targetObject; private final String asyncMethodName; private final String beanName; private final CountDownLatch initCountDownLatch = new CountDownLatch(1); /** * mark async-init method is during first invocation. */ private volatile boolean isAsyncCalling = false; /** * mark init-method is called. */ private volatile boolean isAsyncCalled = false; public AsyncInitializeBeanMethodInvoker(AsyncInitMethodManager asyncInitMethodManager, Object targetObject, String beanName, String methodName) { this.asyncInitMethodManager = asyncInitMethodManager; this.targetObject = targetObject; this.beanName = beanName; this.asyncMethodName = methodName; } @Override public Object invoke(final MethodInvocation invocation) throws Throwable {<FILL_FUNCTION_BODY>} void asyncMethodFinish() { this.initCountDownLatch.countDown(); this.isAsyncCalling = false; } }
// if the spring refreshing is finished if (asyncInitMethodManager.isStartUpFinish()) { return invocation.getMethod().invoke(targetObject, invocation.getArguments()); } Method method = invocation.getMethod(); final String methodName = method.getName(); if (!isAsyncCalled && methodName.equals(asyncMethodName)) { isAsyncCalled = true; isAsyncCalling = true; asyncInitMethodManager.submitTask(() -> { try { long startTime = System.currentTimeMillis(); invocation.getMethod().invoke(targetObject, invocation.getArguments()); LOGGER.info("{}({}) {} method execute {}dms.", targetObject .getClass().getName(), beanName, methodName, (System .currentTimeMillis() - startTime)); } catch (Throwable e) { throw new RuntimeException(e); } finally { asyncMethodFinish(); } }); return null; } if (isAsyncCalling) { long startTime = System.currentTimeMillis(); initCountDownLatch.await(); LOGGER.info("{}({}) {} method wait {}ms.", targetObject.getClass().getName(), beanName, methodName, (System.currentTimeMillis() - startTime)); } return invocation.getMethod().invoke(targetObject, invocation.getArguments());
347
358
705
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/context/ComponentContextRefreshInterceptor.java
ComponentContextRefreshInterceptor
afterRefresh
class ComponentContextRefreshInterceptor implements ContextRefreshInterceptor { private static final Logger LOGGER = SofaBootLoggerFactory .getLogger(ComponentContextRefreshInterceptor.class); private final ComponentManager componentManager; private final SofaRuntimeContext sofaRuntimeContext; ; public ComponentContextRefreshInterceptor(SofaRuntimeManager sofaRuntimeManager) { this.componentManager = sofaRuntimeManager.getComponentManager(); this.sofaRuntimeContext = sofaRuntimeManager.getSofaRuntimeContext(); } @Override public void afterRefresh(SofaGenericApplicationContext context, Throwable throwable) {<FILL_FUNCTION_BODY>} }
if (throwable == null) { ComponentName componentName = ComponentNameFactory.createComponentName( SpringContextComponent.SPRING_COMPONENT_TYPE, context.getId()); Implementation implementation = new SpringContextImplementation(context); ComponentInfo componentInfo = new SpringContextComponent(componentName, implementation, sofaRuntimeContext); componentManager.register(componentInfo); } else { Collection<ComponentInfo> componentInfos = componentManager .getComponentInfosByApplicationContext(context); for (ComponentInfo componentInfo : componentInfos) { try { componentManager.unregister(componentInfo); } catch (ServiceRuntimeException e) { LOGGER.error(ErrorCode.convert("01-03001", componentInfo.getName()), e); } } }
181
203
384
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/context/SpringContextComponent.java
SpringContextComponent
deactivate
class SpringContextComponent extends AbstractComponent { public static ComponentType SPRING_COMPONENT_TYPE = new ComponentType("Spring"); public SpringContextComponent(ComponentName componentName, Implementation implementation, SofaRuntimeContext sofaRuntimeContext) { this.implementation = implementation; this.componentName = componentName; this.sofaRuntimeContext = sofaRuntimeContext; } @Override public ComponentType getType() { return SPRING_COMPONENT_TYPE; } @Override public Map<String, Property> getProperties() { return null; } @Override public ApplicationContext getApplicationContext() { return (ApplicationContext) implementation.getTarget(); } @Override public void activate() throws ServiceRuntimeException { if (componentStatus != ComponentStatus.RESOLVED) { return; } componentStatus = ComponentStatus.ACTIVATED; } @Override public void deactivate() throws ServiceRuntimeException {<FILL_FUNCTION_BODY>} }
if (implementation instanceof SpringContextImplementation) { AbstractApplicationContext applicationContext = (AbstractApplicationContext) implementation .getTarget(); applicationContext.close(); } super.deactivate();
271
54
325
<methods>public non-sealed void <init>() ,public void activate() throws com.alipay.sofa.runtime.api.ServiceRuntimeException,public boolean canBeDuplicate() ,public void deactivate() throws com.alipay.sofa.runtime.api.ServiceRuntimeException,public java.lang.String dump() ,public void exception(java.lang.Exception) throws com.alipay.sofa.runtime.api.ServiceRuntimeException,public org.springframework.context.ApplicationContext getApplicationContext() ,public com.alipay.sofa.runtime.spi.component.SofaRuntimeContext getContext() ,public com.alipay.sofa.runtime.spi.component.Implementation getImplementation() ,public com.alipay.sofa.runtime.api.component.ComponentName getName() ,public Map<java.lang.String,com.alipay.sofa.runtime.api.component.Property> getProperties() ,public com.alipay.sofa.runtime.model.ComponentStatus getState() ,public boolean isActivated() ,public com.alipay.sofa.runtime.spi.health.HealthResult isHealthy() ,public boolean isResolved() ,public void register() ,public boolean resolve() ,public void setApplicationContext(org.springframework.context.ApplicationContext) ,public void unregister() throws com.alipay.sofa.runtime.api.ServiceRuntimeException,public void unresolve() throws com.alipay.sofa.runtime.api.ServiceRuntimeException<variables>protected org.springframework.context.ApplicationContext applicationContext,protected com.alipay.sofa.runtime.api.component.ComponentName componentName,protected com.alipay.sofa.runtime.model.ComponentStatus componentStatus,protected java.lang.Exception e,protected com.alipay.sofa.runtime.spi.component.Implementation implementation,protected Map<java.lang.String,com.alipay.sofa.runtime.api.component.Property> properties,protected com.alipay.sofa.runtime.spi.component.SofaRuntimeContext sofaRuntimeContext
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/ext/client/ExtensionClientImpl.java
ExtensionClientImpl
publishExtension
class ExtensionClientImpl implements ExtensionClient { private final SofaRuntimeContext sofaRuntimeContext; public ExtensionClientImpl(SofaRuntimeContext sofaRuntimeContext) { this.sofaRuntimeContext = sofaRuntimeContext; } @Override public void publishExtension(ExtensionParam extensionParam) {<FILL_FUNCTION_BODY>} @Override public void publishExtensionPoint(ExtensionPointParam extensionPointParam) { Assert.notNull(extensionPointParam, "extensionPointParam can not be null."); Assert.notNull(extensionPointParam.getName(), "Extension point name can not be null."); Assert.notNull(extensionPointParam.getContributionClass(), "Extension point contribution can not be null."); Assert.notNull(extensionPointParam.getTarget(), "Extension point target can not be null."); ExtensionPoint extensionPoint = new ExtensionPointImpl(extensionPointParam.getName(), extensionPointParam.getContributionClass()); Implementation implementation = new DefaultImplementation( extensionPointParam.getTargetName()); implementation.setTarget(extensionPointParam.getTarget()); ComponentInfo extensionPointComponent = new ExtensionPointComponent(extensionPoint, sofaRuntimeContext, implementation); sofaRuntimeContext.getComponentManager().register(extensionPointComponent); } }
Assert.notNull(extensionParam, "extensionParam can not be null."); Assert.notNull(extensionParam.getElement(), "Extension contribution element can not be null."); Assert.notNull(extensionParam.getTargetInstanceName(), "Extension target instance name can not be null."); Assert.notNull(extensionParam.getTargetName(), "Extension target name can not be null."); ExtensionImpl extension = new ExtensionImpl(null, extensionParam.getTargetName(), extensionParam.getElement(), sofaRuntimeContext.getAppClassLoader()); extension.setTargetComponentName(ComponentNameFactory.createComponentName( ExtensionPointComponent.EXTENSION_POINT_COMPONENT_TYPE, extensionParam.getTargetInstanceName() + ExtensionComponent.LINK_SYMBOL + extensionParam.getTargetName())); ComponentInfo extensionComponent = new ExtensionComponent(extension, sofaRuntimeContext); sofaRuntimeContext.getComponentManager().register(extensionComponent);
310
228
538
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/ext/component/ExtensionComponent.java
ExtensionComponent
loadContributions
class ExtensionComponent extends AbstractComponent { private static final Logger LOGGER = SofaBootLoggerFactory .getLogger(ExtensionComponent.class); public static final String LINK_SYMBOL = "$"; public static final ComponentType EXTENSION_COMPONENT_TYPE = new ComponentType("extension"); private final Extension extension; public ExtensionComponent(Extension extension, SofaRuntimeContext sofaRuntimeContext) { this.extension = extension; this.sofaRuntimeContext = sofaRuntimeContext; this.componentName = ComponentNameFactory.createComponentName( EXTENSION_COMPONENT_TYPE, extension.getTargetComponentName().getName() + LINK_SYMBOL + ObjectUtils.getIdentityHexString(extension)); } @Override public ComponentType getType() { return EXTENSION_COMPONENT_TYPE; } @Override public boolean resolve() { if (componentStatus != ComponentStatus.REGISTERED) { return false; } ComponentManager componentManager = sofaRuntimeContext.getComponentManager(); ComponentName extensionPointComponentName = extension.getTargetComponentName(); ComponentInfo extensionPointComponentInfo = componentManager .getComponentInfo(extensionPointComponentName); if (extensionPointComponentInfo != null && extensionPointComponentInfo.isActivated()) { componentStatus = ComponentStatus.RESOLVED; return true; } return false; } @Override public void activate() throws ServiceRuntimeException { if (componentStatus != ComponentStatus.RESOLVED) { return; } ComponentManager componentManager = sofaRuntimeContext.getComponentManager(); ComponentName extensionPointComponentName = extension.getTargetComponentName(); ComponentInfo extensionPointComponentInfo = componentManager .getComponentInfo(extensionPointComponentName); if (extensionPointComponentInfo == null || !extensionPointComponentInfo.isActivated()) { return; } loadContributions( ((ExtensionPointComponent) extensionPointComponentInfo).getExtensionPoint(), extension); Object target = extensionPointComponentInfo.getImplementation().getTarget(); try { if (target instanceof Extensible) { ((Extensible) target).registerExtension(extension); } else { Method method = ReflectionUtils.findMethod(target.getClass(), "registerExtension", Extension.class); if (method == null) { throw new RuntimeException(ErrorCode.convert("01-01001", target.getClass() .getCanonicalName())); } ReflectionUtils.invokeMethod(method, target, extension); } } catch (Throwable t) { throw new ServiceRuntimeException(ErrorCode.convert("01-01000", extensionPointComponentInfo.getName()), t); } componentStatus = ComponentStatus.ACTIVATED; } @Override public HealthResult isHealthy() { if (sofaRuntimeContext.getProperties().isSkipExtensionHealthCheck()) { HealthResult healthResult = new HealthResult(componentName.getRawName()); healthResult.setHealthy(true); return healthResult; } HealthResult healthResult = new HealthResult(componentName.getRawName()); //表示 loadContributions 异常的 Extension if (e != null) { healthResult.setHealthy(false); healthResult.setHealthReport("Extension loadContributions error: " + e.getMessage()); return healthResult; } //表示注册成功的 Extension if (isActivated()) { healthResult.setHealthy(true); return healthResult; } //表示对应的 ExtensionPoint 未注册 if (!isResolved()) { healthResult.setHealthy(false); healthResult.setHealthReport("Can not find corresponding ExtensionPoint: " + extension.getTargetComponentName().getName()); return healthResult; } else { // 表示 registerExtension 异常的 Extension healthResult.setHealthy(false); healthResult.setHealthReport("Extension registerExtension error"); return healthResult; } } public Extension getExtension() { return extension; } private void loadContributions(ExtensionPoint extensionPoint, Extension extension) {<FILL_FUNCTION_BODY>} }
if (extensionPoint != null && extensionPoint.hasContribution()) { try { Object[] contribs = ((ExtensionPointInternal) extensionPoint) .loadContributions((ExtensionInternal) extension); ((ExtensionInternal) extension).setContributions(contribs); } catch (Exception e) { if (sofaRuntimeContext.getProperties().isExtensionFailureInsulating()) { this.e = e; } LOGGER.error( ErrorCode.convert("01-01002", extensionPoint.getName(), extension.getComponentName()), e); } }
1,088
150
1,238
<methods>public non-sealed void <init>() ,public void activate() throws com.alipay.sofa.runtime.api.ServiceRuntimeException,public boolean canBeDuplicate() ,public void deactivate() throws com.alipay.sofa.runtime.api.ServiceRuntimeException,public java.lang.String dump() ,public void exception(java.lang.Exception) throws com.alipay.sofa.runtime.api.ServiceRuntimeException,public org.springframework.context.ApplicationContext getApplicationContext() ,public com.alipay.sofa.runtime.spi.component.SofaRuntimeContext getContext() ,public com.alipay.sofa.runtime.spi.component.Implementation getImplementation() ,public com.alipay.sofa.runtime.api.component.ComponentName getName() ,public Map<java.lang.String,com.alipay.sofa.runtime.api.component.Property> getProperties() ,public com.alipay.sofa.runtime.model.ComponentStatus getState() ,public boolean isActivated() ,public com.alipay.sofa.runtime.spi.health.HealthResult isHealthy() ,public boolean isResolved() ,public void register() ,public boolean resolve() ,public void setApplicationContext(org.springframework.context.ApplicationContext) ,public void unregister() throws com.alipay.sofa.runtime.api.ServiceRuntimeException,public void unresolve() throws com.alipay.sofa.runtime.api.ServiceRuntimeException<variables>protected org.springframework.context.ApplicationContext applicationContext,protected com.alipay.sofa.runtime.api.component.ComponentName componentName,protected com.alipay.sofa.runtime.model.ComponentStatus componentStatus,protected java.lang.Exception e,protected com.alipay.sofa.runtime.spi.component.Implementation implementation,protected Map<java.lang.String,com.alipay.sofa.runtime.api.component.Property> properties,protected com.alipay.sofa.runtime.spi.component.SofaRuntimeContext sofaRuntimeContext
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/ext/component/ExtensionImpl.java
ExtensionImpl
toString
class ExtensionImpl implements ExtensionInternal, Serializable { @Serial private static final long serialVersionUID = 14648778982899384L; protected ComponentName name; protected ComponentName target; protected String extensionPoint; protected String documentation; protected ClassLoader appClassLoader; protected transient Element element; protected transient Object[] contributions; public ExtensionImpl(ComponentName name, String extensionPoint) { this(name, extensionPoint, null, null); } public ExtensionImpl(ComponentName name, String extensionPoint, Element element, ClassLoader appClassLoader) { this.name = name; this.extensionPoint = extensionPoint; this.element = element; this.appClassLoader = appClassLoader; } @Override public void dispose() { element = null; contributions = null; } @Override public Element getElement() { return element; } @Override public void setElement(Element element) { this.element = element; } @Override public String getExtensionPoint() { return extensionPoint; } @Override public ComponentName getComponentName() { return this.name; } @Override public ComponentName getTargetComponentName() { return this.target; } @Override public void setTargetComponentName(ComponentName target) { this.target = target; } @Override public Object[] getContributions() { return contributions; } @Override public ClassLoader getAppClassLoader() { return appClassLoader; } @Override public void setContributions(Object[] contributions) { this.contributions = contributions; } public String getDocumentation() { return documentation; } @Override public String getId() { return null; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
final StringBuilder buf = new StringBuilder(); buf.append(ExtensionImpl.class.getSimpleName()); buf.append(" {"); buf.append("target: "); buf.append(name); buf.append(", point:"); buf.append(extensionPoint); buf.append('}'); return buf.toString();
535
88
623
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/ext/component/ExtensionPointComponent.java
ExtensionPointComponent
deactivate
class ExtensionPointComponent extends AbstractComponent { private static final String LINK_SYMBOL = "$"; public static final ComponentType EXTENSION_POINT_COMPONENT_TYPE = new ComponentType( "extension-point"); // Extension private final ExtensionPoint extensionPoint; public ExtensionPointComponent(ExtensionPoint extensionPoint, SofaRuntimeContext sofaRuntimeContext, Implementation implementation) { this.extensionPoint = extensionPoint; this.sofaRuntimeContext = sofaRuntimeContext; this.implementation = implementation; this.componentName = ComponentNameFactory.createComponentName( EXTENSION_POINT_COMPONENT_TYPE, implementation.getName() + LINK_SYMBOL + this.extensionPoint.getName()); } @Override public ComponentType getType() { return EXTENSION_POINT_COMPONENT_TYPE; } @Override public void activate() throws ServiceRuntimeException { super.activate(); ComponentManager componentManager = sofaRuntimeContext.getComponentManager(); for (ComponentInfo componentInfo : componentManager.getComponents()) { if (componentInfo.getType().equals(ExtensionComponent.EXTENSION_COMPONENT_TYPE) && !componentInfo.isResolved()) { ExtensionComponent extensionComponent = (ExtensionComponent) componentInfo; if (extensionComponent.getExtension().getTargetComponentName() .equals(componentName)) { componentManager.resolvePendingResolveComponent(componentInfo.getName()); } } } } @Override public void deactivate() throws ServiceRuntimeException {<FILL_FUNCTION_BODY>} public ExtensionPoint getExtensionPoint() { return extensionPoint; } }
ComponentManager componentManager = sofaRuntimeContext.getComponentManager(); for (ComponentInfo componentInfo : componentManager.getComponents()) { if (componentInfo.getType().equals(ExtensionComponent.EXTENSION_COMPONENT_TYPE)) { ExtensionComponent extensionComponent = (ExtensionComponent) componentInfo; if (extensionComponent.getExtension().getTargetComponentName() .equals(componentName)) { componentManager.unregister(componentInfo); } } } if (componentStatus != ComponentStatus.ACTIVATED) { return; } // skip deactivate SpringImplementationImpl because it's already deactivated if (this.implementation != null && !(implementation instanceof SpringImplementationImpl)) { Object target = this.implementation.getTarget(); if (target instanceof ComponentLifeCycle) { ((ComponentLifeCycle) target).deactivate(); } } componentStatus = ComponentStatus.RESOLVED;
443
245
688
<methods>public non-sealed void <init>() ,public void activate() throws com.alipay.sofa.runtime.api.ServiceRuntimeException,public boolean canBeDuplicate() ,public void deactivate() throws com.alipay.sofa.runtime.api.ServiceRuntimeException,public java.lang.String dump() ,public void exception(java.lang.Exception) throws com.alipay.sofa.runtime.api.ServiceRuntimeException,public org.springframework.context.ApplicationContext getApplicationContext() ,public com.alipay.sofa.runtime.spi.component.SofaRuntimeContext getContext() ,public com.alipay.sofa.runtime.spi.component.Implementation getImplementation() ,public com.alipay.sofa.runtime.api.component.ComponentName getName() ,public Map<java.lang.String,com.alipay.sofa.runtime.api.component.Property> getProperties() ,public com.alipay.sofa.runtime.model.ComponentStatus getState() ,public boolean isActivated() ,public com.alipay.sofa.runtime.spi.health.HealthResult isHealthy() ,public boolean isResolved() ,public void register() ,public boolean resolve() ,public void setApplicationContext(org.springframework.context.ApplicationContext) ,public void unregister() throws com.alipay.sofa.runtime.api.ServiceRuntimeException,public void unresolve() throws com.alipay.sofa.runtime.api.ServiceRuntimeException<variables>protected org.springframework.context.ApplicationContext applicationContext,protected com.alipay.sofa.runtime.api.component.ComponentName componentName,protected com.alipay.sofa.runtime.model.ComponentStatus componentStatus,protected java.lang.Exception e,protected com.alipay.sofa.runtime.spi.component.Implementation implementation,protected Map<java.lang.String,com.alipay.sofa.runtime.api.component.Property> properties,protected com.alipay.sofa.runtime.spi.component.SofaRuntimeContext sofaRuntimeContext
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/ext/component/ExtensionPointImpl.java
ExtensionPointImpl
loadContributions
class ExtensionPointImpl implements ExtensionPointInternal, Serializable { @Serial private static final long serialVersionUID = 3939941819263075106L; protected String name; protected String documentation; protected transient List<Class<?>> contributions = new ArrayList<>(2); protected ClassLoader beanClassLoader; public ExtensionPointImpl(String name, Class<?> contributionClass) { this.name = name; if (contributionClass != null) { this.contributions.add(contributionClass); } } @Override public void setBeanClassLoader(ClassLoader beanClassLoader) { this.beanClassLoader = beanClassLoader; } @Override public List<Class<?>> getContributions() { return contributions; } @Override public boolean hasContribution() { return contributions.size() > 0; } @Override public String getName() { return name; } @Override public String getDocumentation() { return documentation; } @Override public void addContribution(Class<?> javaClass) { this.contributions.add(javaClass); } @Override public void addContribution(String className) { this.addContribution(ClassUtils.resolveClassName(className, beanClassLoader)); } @Override public Object[] loadContributions(ExtensionInternal extension) throws Exception {<FILL_FUNCTION_BODY>} }
if (contributions != null) { XMap xmap = new XMap(); for (Class<?> contrib : contributions) { xmap.register(contrib); } Object[] contributions = xmap.loadAll(new XMapContext(extension.getAppClassLoader()), extension.getElement()); extension.setContributions(contributions); return contributions; } return null;
399
105
504
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/ext/spring/ExtensionBuilder.java
ExtensionBuilder
genericExtension
class ExtensionBuilder { private ExtensionInternal extensionInternal; private ExtensionBuilder() { } /** * Get extension * @return extension */ public Extension getExtension() { return this.extensionInternal; } /** * create extension builder * * @param extensionPoint extension point name * @param element element * @param applicationContext application context * @return extension builder */ public static ExtensionBuilder genericExtension(String extensionPoint, Element element, ApplicationContext applicationContext, ClassLoader appClassLoader) {<FILL_FUNCTION_BODY>} /** * Set element * * @param element element of the extension */ public void setElement(Element element) { this.extensionInternal.setElement(element); } /** * Set target component name * * @param target target component name */ public void setExtensionPoint(ComponentName target) { this.extensionInternal.setTargetComponentName(target); } }
ExtensionBuilder builder = new ExtensionBuilder(); builder.extensionInternal = new SpringExtensionImpl(null, extensionPoint, element, appClassLoader, applicationContext); return builder;
270
46
316
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/ext/spring/ExtensionFactoryBean.java
ExtensionFactoryBean
publishAsNuxeoExtension
class ExtensionFactoryBean extends AbstractExtFactoryBean { private static final Logger LOGGER = SofaBootLoggerFactory .getLogger(ExtensionFactoryBean.class); /* extension bean */ private String bean; /* extension point name */ private String point; /* content need to be parsed with XMap */ private Element content; private String[] require; private ClassLoader classLoader; @Override public void afterPropertiesSet() throws Exception { super.afterPropertiesSet(); Assert.notNull(applicationContext, "required property 'applicationContext' has not been set"); Assert.notNull(getPoint(), "required property 'point' has not been set for extension"); // checked if (!StringUtils.hasText(getPoint())) { throw new IllegalArgumentException("'point' have to be specified"); } if (getBeanClassLoaderWrapper() == null || getBeanClassLoaderWrapper().getInnerClassLoader() == null) { classLoader = Thread.currentThread().getContextClassLoader(); } else { classLoader = getBeanClassLoaderWrapper().getInnerClassLoader(); } try { publishAsNuxeoExtension(); } catch (Exception e) { LOGGER.error("failed to publish extension", e); throw e; } } private void publishAsNuxeoExtension() throws Exception {<FILL_FUNCTION_BODY>} private ComponentName getExtensionPointComponentName() { return ComponentNameFactory.createComponentName( ExtensionPointComponent.EXTENSION_POINT_COMPONENT_TYPE, this.getBean() + LINK_SYMBOL + this.getPoint()); } public void setContribution(String[] contribution) throws Exception { if (contribution != null && contribution.length != 0) { Class<?>[] contrClass = new Class[contribution.length]; int i = 0; for (String cntr : contribution) { contrClass[i] = classLoader.loadClass(cntr); i++; } } } public void setRequire(String[] require) { this.require = require; } public String[] getRequire() { return require; } public void setBean(String bean) { this.bean = bean; } public String getBean() { return bean; } public void setContent(Element content) { this.content = content; } public Element getContent() { return content; } public void setPoint(String point) { this.point = point; } public String getPoint() { return point; } @Override public String toString() { return "ExtensionPointTarget: " + bean; } }
ExtensionBuilder extensionBuilder = ExtensionBuilder.genericExtension(this.getPoint(), this.getContent(), applicationContext, classLoader); extensionBuilder.setExtensionPoint(getExtensionPointComponentName()); ComponentInfo componentInfo = new ExtensionComponent(extensionBuilder.getExtension(), sofaRuntimeContext); ComponentDefinitionInfo extensionDefinitionInfo = new ComponentDefinitionInfo(); extensionDefinitionInfo.setInterfaceMode(InterfaceMode.spring); extensionDefinitionInfo.putInfo(BEAN_ID, bean); extensionDefinitionInfo.putInfo(EXTENSION_POINT_NAME, point); Property property = new Property(); property.setName(SOURCE); property.setValue(extensionDefinitionInfo); componentInfo.getProperties().put(SOURCE, property); componentInfo.setApplicationContext(applicationContext); sofaRuntimeContext.getComponentManager().register(componentInfo);
726
209
935
<methods>public non-sealed void <init>() ,public void afterPropertiesSet() throws java.lang.Exception,public com.alipay.sofa.runtime.ext.spring.ClassLoaderWrapper getBeanClassLoaderWrapper() ,public java.lang.Object getObject() throws java.lang.Exception,public Class<?> getObjectType() ,public int getOrder() ,public boolean isSingleton() ,public void setApplicationContext(org.springframework.context.ApplicationContext) throws org.springframework.beans.BeansException,public void setBeanClassLoaderWrapper(com.alipay.sofa.runtime.ext.spring.ClassLoaderWrapper) ,public void setBeanFactory(org.springframework.beans.factory.BeanFactory) throws org.springframework.beans.BeansException,public void setBeanName(java.lang.String) ,public void setTarget(java.lang.Object) ,public void setTargetBeanName(java.lang.String) <variables>public static final java.lang.String LINK_SYMBOL,protected org.springframework.context.ApplicationContext applicationContext,protected com.alipay.sofa.runtime.ext.spring.ClassLoaderWrapper beanClassLoaderWrapper,protected org.springframework.beans.factory.BeanFactory beanFactory,protected java.lang.String beanName,protected com.alipay.sofa.runtime.spi.component.SofaRuntimeContext sofaRuntimeContext,protected java.lang.Object target,protected java.lang.String targetBeanName
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/ext/spring/ExtensionPointBuilder.java
ExtensionPointBuilder
genericExtensionPoint
class ExtensionPointBuilder { private ExtensionPointInternal extensionPointInternal; private ExtensionPointBuilder() { } /** * Get extension point * @return extension point */ public ExtensionPoint getExtensionPoint() { return this.extensionPointInternal; } /** * Create extension point builder * @param name extension point name * @param beanClassLoader classloader * @return extension point builder */ public static ExtensionPointBuilder genericExtensionPoint(String name, ClassLoader beanClassLoader) { return genericExtensionPoint(name, null, beanClassLoader); } /** * Create extension point builder * @param name extension point name * @param contributionClass contribution class * @param beanClassLoader classloader * @return extension point builder */ public static ExtensionPointBuilder genericExtensionPoint(String name, Class<?> contributionClass, ClassLoader beanClassLoader) {<FILL_FUNCTION_BODY>} /** * add contribution to extension point * @param javaClass contribution class */ public void addContribution(Class<?> javaClass) { this.extensionPointInternal.addContribution(javaClass); } /** * add contribution to extension point * @param className contribution class name */ public void addContribution(String className) { this.extensionPointInternal.addContribution(className); } }
ExtensionPointBuilder builder = new ExtensionPointBuilder(); ExtensionPointInternal extensionPoint = new SpringExtensionPointImpl(name, contributionClass); extensionPoint.setBeanClassLoader(beanClassLoader); builder.extensionPointInternal = extensionPoint; return builder;
365
68
433
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/ext/spring/ExtensionPointFactoryBean.java
ExtensionPointFactoryBean
afterPropertiesSet
class ExtensionPointFactoryBean extends AbstractExtFactoryBean { private static final Logger LOGGER = SofaBootLoggerFactory .getLogger(ExtensionPointFactoryBean.class); /* extension point name */ private String name; /* contributions for the extension point */ private String[] contribution; @Override public void afterPropertiesSet() throws Exception {<FILL_FUNCTION_BODY>} private void publishAsNuxeoExtensionPoint(Class<?> beanClass) throws Exception { Assert.notNull(beanClass, "Service must be implement!"); ExtensionPointBuilder extensionPointBuilder = ExtensionPointBuilder.genericExtensionPoint( this.name, applicationContext.getClassLoader()); if (this.contribution != null && this.contribution.length != 0) { for (String s : contribution) { extensionPointBuilder.addContribution(s); } } Assert.hasLength(beanName, "required property 'beanName' has not been set for creating implementation"); Assert.notNull(applicationContext, "required property 'applicationContext' has not been set for creating implementation"); Implementation implementation = new SpringImplementationImpl(targetBeanName, applicationContext); ComponentInfo extensionPointComponent = new ExtensionPointComponent( extensionPointBuilder.getExtensionPoint(), sofaRuntimeContext, implementation); ComponentDefinitionInfo definitionInfo = new ComponentDefinitionInfo(); definitionInfo.setInterfaceMode(InterfaceMode.spring); definitionInfo.putInfo(EXTENSION_POINT_NAME, name); definitionInfo.putInfo(BEAN_ID, targetBeanName); Property property = new Property(); property.setName(SOURCE); property.setValue(definitionInfo); extensionPointComponent.getProperties().put(SOURCE, property); extensionPointComponent.setApplicationContext(applicationContext); sofaRuntimeContext.getComponentManager().register(extensionPointComponent); } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setContribution(String[] contribution) throws Exception { this.contribution = contribution; } @Override public String toString() { return "ExtensionPointTarget: " + targetBeanName; } }
super.afterPropertiesSet(); Assert.notNull(beanFactory, "required property 'beanFactory' has not been set"); Assert.notNull(name, "required property 'name' has not been set for extension point"); if (!StringUtils.hasText(targetBeanName) && target == null || (StringUtils.hasText(targetBeanName) && target != null)) { throw new IllegalArgumentException( "either 'target' or 'targetBeanName' have to be specified"); } // determine serviceClass (can still be null if using a FactoryBean // which doesn't declare its product type) Class<?> extensionPointClass = (target != null ? target.getClass() : beanFactory .getType(targetBeanName)); // check if there is a reference to a non-lazy bean if (StringUtils.hasText(targetBeanName)) { if (beanFactory instanceof ConfigurableListableBeanFactory) { // in case the target is non-lazy, singleton bean, initialize it BeanDefinition beanDef = ((ConfigurableListableBeanFactory) beanFactory) .getBeanDefinition(targetBeanName); if (beanDef.isSingleton() && !beanDef.isLazyInit()) { LOGGER .atDebug() .log( "target bean [{}] is a non-lazy singleton; forcing initialization before publishing", targetBeanName); beanFactory.getBean(targetBeanName); } } } try { publishAsNuxeoExtensionPoint(extensionPointClass); } catch (Exception e) { LOGGER.error("Failed to publish extension point.", e); throw e; }
571
422
993
<methods>public non-sealed void <init>() ,public void afterPropertiesSet() throws java.lang.Exception,public com.alipay.sofa.runtime.ext.spring.ClassLoaderWrapper getBeanClassLoaderWrapper() ,public java.lang.Object getObject() throws java.lang.Exception,public Class<?> getObjectType() ,public int getOrder() ,public boolean isSingleton() ,public void setApplicationContext(org.springframework.context.ApplicationContext) throws org.springframework.beans.BeansException,public void setBeanClassLoaderWrapper(com.alipay.sofa.runtime.ext.spring.ClassLoaderWrapper) ,public void setBeanFactory(org.springframework.beans.factory.BeanFactory) throws org.springframework.beans.BeansException,public void setBeanName(java.lang.String) ,public void setTarget(java.lang.Object) ,public void setTargetBeanName(java.lang.String) <variables>public static final java.lang.String LINK_SYMBOL,protected org.springframework.context.ApplicationContext applicationContext,protected com.alipay.sofa.runtime.ext.spring.ClassLoaderWrapper beanClassLoaderWrapper,protected org.springframework.beans.factory.BeanFactory beanFactory,protected java.lang.String beanName,protected com.alipay.sofa.runtime.spi.component.SofaRuntimeContext sofaRuntimeContext,protected java.lang.Object target,protected java.lang.String targetBeanName
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/ext/spring/SpringExtensionPointImpl.java
SpringExtensionPointImpl
loadContributions
class SpringExtensionPointImpl extends ExtensionPointImpl { @Serial private static final long serialVersionUID = -7891847787889605861L; public SpringExtensionPointImpl(String name, Class<?> contributionClass) { super(name, contributionClass); } @Override public Object[] loadContributions(ExtensionInternal extension) throws Exception {<FILL_FUNCTION_BODY>} }
ApplicationContext applicationContext = null; if (extension instanceof SpringExtensionImpl) { applicationContext = ((SpringExtensionImpl) extension).getApplicationContext(); } if (contributions != null) { XMapSpring xmapSpring = new XMapSpring(); for (Class<?> contrib : contributions) { xmapSpring.register(contrib, applicationContext); } Object[] contributions = xmapSpring.loadAll( new XMapContext(extension.getAppClassLoader()), extension.getElement()); for (Object o : contributions) { if (applicationContext != null && o instanceof BeanFactoryAware) { ((BeanFactoryAware) o).setBeanFactory(applicationContext .getAutowireCapableBeanFactory()); } } extension.setContributions(contributions); return contributions; } return null;
116
224
340
<methods>public void <init>(java.lang.String, Class<?>) ,public void addContribution(Class<?>) ,public void addContribution(java.lang.String) ,public List<Class<?>> getContributions() ,public java.lang.String getDocumentation() ,public java.lang.String getName() ,public boolean hasContribution() ,public java.lang.Object[] loadContributions(com.alipay.sofa.runtime.ext.component.ExtensionInternal) throws java.lang.Exception,public void setBeanClassLoader(java.lang.ClassLoader) <variables>protected java.lang.ClassLoader beanClassLoader,protected transient List<Class<?>> contributions,protected java.lang.String documentation,protected java.lang.String name,private static final long serialVersionUID
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/ext/spring/parser/AbstractExtBeanDefinitionParser.java
AbstractExtBeanDefinitionParser
configBeanClassLoader
class AbstractExtBeanDefinitionParser extends AbstractSingleExtPointBeanDefinitionParser implements SofaBootTagNameSupport { public static final String REF = "ref"; private static final String BEAN_CLASS_LOADER_WRAPPER = "beanClassLoaderWrapper"; /** * * @param element the XML element being parsed * @param parserContext the object encapsulating the current state of the parsing process * @param builder used to define the <code>BeanDefinition</code> */ @Override protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { Resource res = parserContext.getReaderContext().getResource(); builder.getBeanDefinition().setResource(res); builder.getRawBeanDefinition().setResource(res); configBeanClassLoader(parserContext, builder); // parse attributes parseAttribute(element, parserContext, builder); // parser subElement(i.e. <content/>) parserSubElement(element, parserContext, builder); } protected void configBeanClassLoader(ParserContext parserContext, BeanDefinitionBuilder builder) {<FILL_FUNCTION_BODY>} protected void parseAttribute(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { parseCustomAttributes(element, parserContext, builder, (parent, attribute, builder1, parserContext1) -> { String name = attribute.getLocalName(); // fallback mechanism if (!REF.equals(name)) { builder1.addPropertyValue(Conventions.attributeNameToPropertyName(name), attribute.getValue()); } }); } /** * Actually parse sub element. * * @param element element * @param parserContext parserContext * @param builder builder */ protected abstract void parserSubElement(Element element, ParserContext parserContext, BeanDefinitionBuilder builder); @Override protected boolean shouldGenerateIdAsFallback() { return true; } /** * Parse custom attributes, as ID, LAZY-INIT, DEPENDS-ON。 * * @param element element * @param parserContext parser context * @param builder builder * @param callback callback */ protected void parseCustomAttributes(Element element, ParserContext parserContext, BeanDefinitionBuilder builder, AttributeCallback callback) { NamedNodeMap attributes = element.getAttributes(); for (int x = 0; x < attributes.getLength(); x++) { Attr attribute = (Attr) attributes.item(x); String name = attribute.getLocalName(); if (BeanDefinitionParserDelegate.DEPENDS_ON_ATTRIBUTE.equals(name)) { builder.getBeanDefinition().setDependsOn( (StringUtils.tokenizeToStringArray(attribute.getValue(), BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS))); } else if (BeanDefinitionParserDelegate.LAZY_INIT_ATTRIBUTE.equals(name)) { builder.setLazyInit(Boolean.parseBoolean(attribute.getValue())); } else if (BeanDefinitionParserDelegate.ABSTRACT_ATTRIBUTE.equals(name)) { builder.setAbstract(Boolean.parseBoolean(attribute.getValue())); } else if (BeanDefinitionParserDelegate.PARENT_ATTRIBUTE.equals(name)) { builder.setParentName(attribute.getValue()); } else { callback.process(element, attribute, builder, parserContext); } } } /** * * @author xi.hux@alipay.com * @since 2.6.0 */ public interface AttributeCallback { /** * Parser attribute * * @param parent element parent * @param attribute attribute * @param builder builder * @param parserContext parser context */ void process(Element parent, Attr attribute, BeanDefinitionBuilder builder, ParserContext parserContext); } }
ClassLoader beanClassLoader = parserContext.getReaderContext().getBeanClassLoader(); // not support setClassLoder since spring framework 5.2.20.RELEASE builder .addPropertyValue(BEAN_CLASS_LOADER_WRAPPER, new ClassLoaderWrapper(beanClassLoader));
1,024
77
1,101
<methods>public non-sealed void <init>() <variables>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/ext/spring/parser/AbstractExtPointBeanDefinitionParser.java
AbstractExtPointBeanDefinitionParser
parse
class AbstractExtPointBeanDefinitionParser implements BeanDefinitionParser { /** * Constant for the id attribute */ public static final String ID_ATTRIBUTE = "id"; @Override public final BeanDefinition parse(Element element, ParserContext parserContext) {<FILL_FUNCTION_BODY>} /** * Resolve the ID for the supplied {@link BeanDefinition}. * <p>When using {@link #shouldGenerateId generation}, a name is generated automatically. * Otherwise, the ID is extracted from the "id" attribute, potentially with a * {@link #shouldGenerateIdAsFallback() fallback} to a generated id. * * @param element the element that the bean definition has been built from * @param definition the bean definition to be registered * @param parserContext the object encapsulating the current state of the parsing process; * provides access to a {@link BeanDefinitionRegistry} * @return the resolved id * @throws BeanDefinitionStoreException if no unique name could be generated * for the given bean definition */ protected String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext) throws BeanDefinitionStoreException { if (shouldGenerateId()) { return parserContext.getReaderContext().generateBeanName(definition); } else { String id = element.getAttribute(ID_ATTRIBUTE); if (!StringUtils.hasText(id) && shouldGenerateIdAsFallback()) { id = parserContext.getReaderContext().generateBeanName(definition); } return id; } } /** * Register the supplied {@link BeanDefinitionHolder bean} with the supplied * {@link BeanDefinitionRegistry registry}. * <p>Subclasses can override this method to control whether or not the supplied * {@link BeanDefinitionHolder bean} is actually even registered, or to * register even more beans. * <p>The default implementation registers the supplied {@link BeanDefinitionHolder bean} * with the supplied {@link BeanDefinitionRegistry registry} only if the <code>isNested</code> * parameter is <code>false</code>, because one typically does not want inner beans * to be registered as top level beans. * * @param definition the bean definition to be registered * @param registry the registry that the bean is to be registered with * @see BeanDefinitionReaderUtils#registerBeanDefinition(BeanDefinitionHolder, BeanDefinitionRegistry) */ protected void registerBeanDefinition(BeanDefinitionHolder definition, BeanDefinitionRegistry registry) { BeanDefinitionReaderUtils.registerBeanDefinition(definition, registry); } /** * Central template method to actually parse the supplied {@link Element} * into one or more {@link BeanDefinition BeanDefinitions}. * * @param element the element that is to be parsed into one or more {@link BeanDefinition BeanDefinitions} * @param parserContext the object encapsulating the current state of the parsing process; * provides access to a {@link BeanDefinitionRegistry} * @return the primary {@link BeanDefinition} resulting from the parsing of the supplied {@link Element} * @see #parse(Element, ParserContext) * @see #postProcessComponentDefinition(BeanComponentDefinition) */ protected abstract AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext); /** * Should an ID be generated instead of read from the passed in {@link Element}? * <p>Disabled by default; subclasses can override this to enable ID generation. * Note that this flag is about <i>always</i> generating an ID; the parser * won't even check for an "id" attribute in this case. * * @return whether the parser should always generate an id */ protected boolean shouldGenerateId() { return false; } /** * Should an ID be generated instead if the passed in {@link Element} does not * specify an "id" attribute explicitly? * <p>Disabled by default; subclasses can override this to enable ID generation * as fallback: The parser will first check for an "id" attribute in this case, * only falling back to a generated ID if no value was specified. * * @return whether the parser should generate an id if no id was specified */ protected boolean shouldGenerateIdAsFallback() { return false; } /** * Controls whether this parser is supposed to fire a * {@link BeanComponentDefinition} * event after parsing the bean definition. * <p>This implementation returns <code>true</code> by default; that is, * an event will be fired when a bean definition has been completely parsed. * Override this to return <code>false</code> in order to suppress the event. * * @return <code>true</code> in order to fire a component registration event * after parsing the bean definition; <code>false</code> to suppress the event * @see #postProcessComponentDefinition * @see org.springframework.beans.factory.parsing.ReaderContext#fireComponentRegistered */ protected boolean shouldFireEvents() { return true; } /** * Hook method called after the primary parsing of a * {@link BeanComponentDefinition} but before the * {@link BeanComponentDefinition} has been registered with a * {@link BeanDefinitionRegistry}. * <p>Derived classes can override this method to supply any custom logic that * is to be executed after all the parsing is finished. * <p>The default implementation is a no-op. * * @param componentDefinition the {@link BeanComponentDefinition} that is to be processed */ protected void postProcessComponentDefinition(BeanComponentDefinition componentDefinition) { } }
AbstractBeanDefinition definition = parseInternal(element, parserContext); if (definition != null && !parserContext.isNested()) { try { String id = resolveId(element, definition, parserContext); if (!StringUtils.hasText(id)) { parserContext.getReaderContext().error( "Id is required for element '" + parserContext.getDelegate().getLocalName(element) + "' when used as a top-level tag", element); } BeanDefinitionHolder holder = new BeanDefinitionHolder(definition, id); registerBeanDefinition(holder, parserContext.getRegistry()); if (shouldFireEvents()) { BeanComponentDefinition componentDefinition = new BeanComponentDefinition( holder); postProcessComponentDefinition(componentDefinition); parserContext.registerComponent(componentDefinition); } } catch (BeanDefinitionStoreException ex) { parserContext.getReaderContext().error(ex.getMessage(), element); return null; } } return definition;
1,458
250
1,708
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/ext/spring/parser/AbstractSingleExtPointBeanDefinitionParser.java
AbstractSingleExtPointBeanDefinitionParser
parseInternal
class AbstractSingleExtPointBeanDefinitionParser extends AbstractExtPointBeanDefinitionParser { /** * Creates a {@link BeanDefinitionBuilder} instance for the * {@link #getBeanClass bean Class} and passes it to the * {@link #doParse} strategy method. * * @param element the element that is to be parsed into a single BeanDefinition * @param parserContext the object encapsulating the current state of the parsing process * @return the BeanDefinition resulting from the parsing of the supplied {@link Element} * @throws IllegalStateException if the bean {@link Class} returned from * {@link #getBeanClass(Element)} is <code>null</code> * @see #doParse */ @Override protected final AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {<FILL_FUNCTION_BODY>} /** * Determine the name for the parent of the currently parsed bean, * in case of the current bean being defined as a child bean. * <p>The default implementation returns <code>null</code>, * indicating a root bean definition. * * @param element the <code>Element</code> that is being parsed * @return the name of the parent bean for the currently parsed bean, * or <code>null</code> if none */ protected String getParentName(Element element) { return null; } /** * Determine the bean class corresponding to the supplied {@link Element}. * <p>Note that, for application classes, it is generally preferable to * override {@link #getBeanClassName} instead, in order to avoid a direct * dependence on the bean implementation class. The BeanDefinitionParser * and its NamespaceHandler can be used within an IDE plugin then, even * if the application classes are not available on the plugin's classpath. * * @param element the <code>Element</code> that is being parsed * @return the {@link Class} of the bean that is being defined via parsing * the supplied <code>Element</code>, or <code>null</code> if none * @see #getBeanClassName */ protected Class<?> getBeanClass(Element element) { return null; } /** * Determine the bean class name corresponding to the supplied {@link Element}. * * @param element the <code>Element</code> that is being parsed * @return the class name of the bean that is being defined via parsing * the supplied <code>Element</code>, or <code>null</code> if none * @see #getBeanClass */ protected String getBeanClassName(Element element) { return null; } /** * Parse the supplied {@link Element} and populate the supplied * {@link BeanDefinitionBuilder} as required. * <p>The default implementation delegates to the <code>doParse</code> * version without ParserContext argument. * * @param element the XML element being parsed * @param parserContext the object encapsulating the current state of the parsing process * @param builder used to define the <code>BeanDefinition</code> * @see #doParse(Element, BeanDefinitionBuilder) */ protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { doParse(element, builder); } /** * Parse the supplied {@link Element} and populate the supplied * {@link BeanDefinitionBuilder} as required. * <p>The default implementation does nothing. * * @param element the XML element being parsed * @param builder used to define the <code>BeanDefinition</code> */ protected void doParse(Element element, BeanDefinitionBuilder builder) { } }
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(); String parentName = getParentName(element); if (parentName != null) { builder.getRawBeanDefinition().setParentName(parentName); } Class<?> beanClass = getBeanClass(element); if (beanClass != null) { builder.getRawBeanDefinition().setBeanClass(beanClass); } else { String beanClassName = getBeanClassName(element); if (beanClassName != null) { builder.getRawBeanDefinition().setBeanClassName(beanClassName); } } builder.getRawBeanDefinition().setSource(parserContext.extractSource(element)); if (parserContext.isNested()) { // Inner bean definition must receive same scope as containing bean. builder.setScope(parserContext.getContainingBeanDefinition().getScope()); } if (parserContext.isDefaultLazyInit()) { // Default-lazy-init applies to custom bean definitions as well. builder.setLazyInit(true); } doParse(element, parserContext, builder); return builder.getBeanDefinition();
974
295
1,269
<methods>public non-sealed void <init>() ,public final org.springframework.beans.factory.config.BeanDefinition parse(org.w3c.dom.Element, org.springframework.beans.factory.xml.ParserContext) <variables>public static final java.lang.String ID_ATTRIBUTE
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/ext/spring/parser/ExtensionBeanDefinitionParser.java
ExtensionBeanDefinitionParser
parserSubElement
class ExtensionBeanDefinitionParser extends AbstractExtBeanDefinitionParser { public static final String CONTENT = "content"; private static final ExtensionBeanDefinitionParser INSTANCE = new ExtensionBeanDefinitionParser(); public ExtensionBeanDefinitionParser() { } public static ExtensionBeanDefinitionParser getInstance() { return INSTANCE; } @Override protected Class<?> getBeanClass(Element element) { return ExtensionFactoryBean.class; } @Override protected void parserSubElement(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {<FILL_FUNCTION_BODY>} @Override public String supportTagName() { return "extension"; } }
NodeList nl = element.getChildNodes(); // parse all sub elements for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); if (node instanceof Element subElement) { // osgi:content if (CONTENT.equals(subElement.getLocalName())) { builder.addPropertyValue(CONTENT, subElement); } } }
183
116
299
<methods>public non-sealed void <init>() <variables>private static final java.lang.String BEAN_CLASS_LOADER_WRAPPER,public static final java.lang.String REF
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/ext/spring/parser/ExtensionPointBeanDefinitionParser.java
ExtensionPointBeanDefinitionParser
parserSubElement
class ExtensionPointBeanDefinitionParser extends AbstractExtBeanDefinitionParser { private static final Logger LOGGER = SofaBootLoggerFactory .getLogger(ExtensionPointBeanDefinitionParser.class); public static final String CLASS = "class"; public static final String OBJECT = "object"; public static final String CONTRIBUTION = "contribution"; private static final ExtensionPointBeanDefinitionParser INSTANCE = new ExtensionPointBeanDefinitionParser(); public ExtensionPointBeanDefinitionParser() { } public static ExtensionPointBeanDefinitionParser getInstance() { return INSTANCE; } @Override protected Class<?> getBeanClass(Element element) { return ExtensionPointFactoryBean.class; } @Override protected void parserSubElement(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {<FILL_FUNCTION_BODY>} @Override public String supportTagName() { return "extension-point"; } }
// determine nested/referred beans // only referred bean is supported now Object target = null; if (element.hasAttribute(REF)) { target = new RuntimeBeanReference(element.getAttribute(REF)); } NodeList nl = element.getChildNodes(); final Set<String> contributions = new LinkedHashSet<String>(); // parse all sub elements for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); if (node instanceof Element subElement) { // sofa:object if (OBJECT.equals(subElement.getLocalName())) { parseCustomAttributes(subElement, parserContext, builder, (parent, attribute, builder1, parserContext1) -> { String name = attribute.getLocalName(); if (CLASS.equals(name)) { contributions.add(attribute.getValue()); } else { builder1.addPropertyValue( Conventions.attributeNameToPropertyName(name), attribute.getValue()); } }); } else { if (element.hasAttribute(REF)) { LOGGER.error("nested bean definition/reference cannot be used when attribute 'ref' is specified"); } target = parserContext.getDelegate().parsePropertySubElement(subElement, builder.getBeanDefinition()); } } } builder.addPropertyValue(CONTRIBUTION, contributions); // do we have a bean reference ? if (target instanceof RuntimeBeanReference) { builder.addPropertyValue("targetBeanName", ((RuntimeBeanReference) target).getBeanName()); } // or a nested bean? -- not supported yet else { builder.addPropertyValue("target", target); }
260
442
702
<methods>public non-sealed void <init>() <variables>private static final java.lang.String BEAN_CLASS_LOADER_WRAPPER,public static final java.lang.String REF
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/filter/JvmFilterHolder.java
JvmFilterHolder
afterInvoking
class JvmFilterHolder { private final List<JvmFilter> JVM_FILTERS = new CopyOnWriteArrayList<>(); private final AtomicBoolean FILTERS_SORTED = new AtomicBoolean(false); public void addJvmFilter(JvmFilter f) { JVM_FILTERS.add(f); FILTERS_SORTED.compareAndSet(true, false); } public void clearJvmFilters() { JVM_FILTERS.clear(); } private void sortJvmFilters() { if (FILTERS_SORTED.compareAndSet(false, true)) { JVM_FILTERS.sort(AnnotationAwareOrderComparator.INSTANCE); } } public List<JvmFilter> getJvmFilters() { sortJvmFilters(); return JVM_FILTERS; } public static boolean beforeInvoking(JvmFilterContext context) { List<JvmFilter> filters = context.getSofaRuntimeContext().getJvmFilterHolder() .getJvmFilters(); for (JvmFilter filter : filters) { if (!filter.before(context)) { return false; } } return true; } public static boolean afterInvoking(JvmFilterContext context) {<FILL_FUNCTION_BODY>} }
List<JvmFilter> filters = context.getSofaRuntimeContext().getJvmFilterHolder() .getJvmFilters(); for (int i = filters.size() - 1; i >= 0; --i) { if (!filters.get(i).after(context)) { return false; } } return true;
363
92
455
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/impl/ComponentManagerImpl.java
ComponentManagerImpl
shutdown
class ComponentManagerImpl implements ComponentManager { private static final Logger LOGGER = SofaBootLoggerFactory .getLogger(ComponentManager.class); /** container for all components */ protected ConcurrentMap<ComponentName, ComponentInfo> registry; /** container for resolved components */ protected ConcurrentMap<ComponentType, Map<ComponentName, ComponentInfo>> resolvedRegistry; /** client factory */ private ClientFactoryInternal clientFactoryInternal; private SofaRuntimeContext sofaRuntimeContext; private final ClassLoader appClassLoader; public ComponentManagerImpl(ClientFactoryInternal clientFactoryInternal, ClassLoader appClassLoader) { this.registry = new ConcurrentHashMap<>(16); this.resolvedRegistry = new ConcurrentHashMap<>(16); this.clientFactoryInternal = clientFactoryInternal; this.appClassLoader = appClassLoader; } public Collection<ComponentInfo> getComponentInfos() { return new ArrayList<>(registry.values()); } public Collection<ComponentName> getPendingComponentInfos() { List<ComponentName> names = new ArrayList<>(); for (ComponentInfo ri : registry.values()) { if (ri.getState() == ComponentStatus.REGISTERED) { names.add(ri.getName()); } } return names; } @Override public ComponentInfo getComponentInfo(ComponentName name) { return registry.get(name); } @Override public boolean isRegistered(ComponentName name) { return registry.containsKey(name); } @Override public Collection<ComponentInfo> getComponents() { return registry.values(); } @Override public int size() { return registry.size(); } @Override public void shutdown() {<FILL_FUNCTION_BODY>} @Override public Collection<ComponentType> getComponentTypes() { return resolvedRegistry.keySet(); } @Override public void register(ComponentInfo componentInfo) { doRegister(componentInfo); } @Override public ComponentInfo registerAndGet(ComponentInfo componentInfo) { return doRegister(componentInfo); } @Override public void registerComponentClient(Class<?> clientType, Object client) { clientFactoryInternal.registerClient(clientType, client); } public void setSofaRuntimeContext(SofaRuntimeContext sofaRuntimeContext) { this.sofaRuntimeContext = sofaRuntimeContext; } private ComponentInfo doRegister(ComponentInfo ci) { ComponentName name = ci.getName(); if (isRegistered(name)) { LOGGER.warn("Component was already registered: {}", name); if (ci.canBeDuplicate()) { return getComponentInfo(name); } throw new ServiceRuntimeException(ErrorCode.convert("01-03002", name)); } try { ci.register(); } catch (Throwable t) { LOGGER.error(ErrorCode.convert("01-03003", ci.getName()), t); return null; } LOGGER.info("Registering component: {}", ci.getName()); try { ComponentInfo old = registry.putIfAbsent(ci.getName(), ci); if (old != null) { LOGGER.warn("Component was already registered: {}", name); if (ci.canBeDuplicate()) { return old; } throw new ServiceRuntimeException(ErrorCode.convert("01-03002", name)); } if (ci.resolve()) { typeRegistry(ci); ci.activate(); } } catch (Throwable t) { ci.exception(new Exception(t)); LOGGER.error(ErrorCode.convert("01-03004", ci.getName()), t); } return ci; } @Override public void unregister(ComponentInfo componentInfo) throws ServiceRuntimeException { ComponentName componentName = componentInfo.getName(); registry.remove(componentName); if (componentName != null) { ComponentType componentType = componentName.getType(); Map<ComponentName, ComponentInfo> typesRi = resolvedRegistry.get(componentType); if (typesRi != null) { typesRi.remove(componentName); } } componentInfo.unregister(); } @Override public Collection<ComponentInfo> getComponentInfosByType(ComponentType type) { List<ComponentInfo> componentInfos = new ArrayList<>(); for (ComponentInfo componentInfo : registry.values()) { if (type.equals(componentInfo.getType())) { componentInfos.add(componentInfo); } } return componentInfos; } @Override public void resolvePendingResolveComponent(ComponentName componentName) { ComponentInfo componentInfo = registry.get(componentName); if (componentInfo.isResolved()) { return; } if (componentInfo.resolve()) { typeRegistry(componentInfo); try { componentInfo.activate(); } catch (Throwable t) { componentInfo.exception(new Exception(t)); LOGGER.error(ErrorCode.convert("01-03005", componentInfo.getName()), t); } } } @Override public Collection<ComponentInfo> getComponentInfosByApplicationContext(ApplicationContext application) { List<ComponentInfo> componentInfos = new ArrayList<>(); for (ComponentInfo componentInfo : registry.values()) { if (Objects.equals(application, componentInfo.getApplicationContext())) { componentInfos.add(componentInfo); } } return componentInfos; } private void typeRegistry(ComponentInfo componentInfo) { ComponentName name = componentInfo.getName(); if (name != null) { ComponentType type = name.getType(); Map<ComponentName, ComponentInfo> typesRi = resolvedRegistry.get(type); if (typesRi == null) { resolvedRegistry.putIfAbsent(type, new HashMap<ComponentName, ComponentInfo>()); typesRi = resolvedRegistry.get(type); } typesRi.put(name, componentInfo); } } }
if (sofaRuntimeContext.getProperties().isSkipAllComponentShutdown()) { return; } List<ComponentInfo> elems = new ArrayList<>(registry.values()); // shutdown spring contexts first List<ComponentInfo> springContextComponents = elems.stream() .filter(componentInfo -> componentInfo instanceof SpringContextComponent).toList(); for (ComponentInfo ri : springContextComponents) { try { unregister(ri); } catch (Throwable t) { LOGGER.error(ErrorCode.convert("01-03001", ri.getName()), t); } } if (!springContextComponents.isEmpty()) { elems.removeAll(springContextComponents); } if (sofaRuntimeContext.getProperties().isSkipCommonComponentShutdown()) { return; } // shutdown remaining components for (ComponentInfo ri : elems) { try { unregister(ri); } catch (Throwable t) { LOGGER.error(ErrorCode.convert("01-03001", ri.getName()), t); } } try { if (registry != null) { registry.clear(); } if (resolvedRegistry != null) { resolvedRegistry.clear(); } clientFactoryInternal = null; } catch (Throwable t) { LOGGER.error(ErrorCode.convert("01-03000"), t); }
1,621
380
2,001
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/impl/StandardSofaRuntimeManager.java
StandardSofaRuntimeManager
shutdown
class StandardSofaRuntimeManager implements SofaRuntimeManager, ApplicationContextAware { private final String appName; private final List<RuntimeShutdownAware> runtimeShutdownAwareList = new CopyOnWriteArrayList<>(); private ComponentManagerImpl componentManager; private ClientFactoryInternal clientFactoryInternal; private SofaRuntimeContext sofaRuntimeContext; private ClassLoader appClassLoader; private ApplicationContext rootApplicationContext; public StandardSofaRuntimeManager(String appName, ClassLoader appClassLoader, ClientFactoryInternal clientFactoryInternal) { this.appName = appName; this.appClassLoader = appClassLoader; this.clientFactoryInternal = clientFactoryInternal; this.componentManager = new ComponentManagerImpl(clientFactoryInternal, appClassLoader); this.sofaRuntimeContext = new SofaRuntimeContext(this); this.componentManager.setSofaRuntimeContext(sofaRuntimeContext); } @Override public ComponentManager getComponentManager() { return componentManager; } @Override public ClientFactoryInternal getClientFactoryInternal() { return clientFactoryInternal; } @Override public SofaRuntimeContext getSofaRuntimeContext() { return sofaRuntimeContext; } @Override public String getAppName() { return appName; } @Override public ClassLoader getAppClassLoader() { return appClassLoader; } /** * shutdown sofa runtime manager * * @throws ServiceRuntimeException exception occur */ @Override public void shutdown() throws ServiceRuntimeException {<FILL_FUNCTION_BODY>} @Override public void shutDownExternally() throws ServiceRuntimeException { try { AbstractApplicationContext applicationContext = (AbstractApplicationContext) rootApplicationContext; // only need shutdown when root context is active if (applicationContext.isActive()) { applicationContext.close(); } appClassLoader = null; } catch (Throwable throwable) { throw new ServiceRuntimeException(ErrorCode.convert("01-03100"), throwable); } } @Override public void registerShutdownAware(RuntimeShutdownAware callback) { runtimeShutdownAwareList.add(callback); } @Override public ApplicationContext getRootApplicationContext() { return rootApplicationContext; } protected void clear() { componentManager = null; sofaRuntimeContext = null; clientFactoryInternal = null; runtimeShutdownAwareList.clear(); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { rootApplicationContext = applicationContext; } }
try { for (RuntimeShutdownAware shutdownAware : runtimeShutdownAwareList) { shutdownAware.shutdown(); } if (componentManager != null) { componentManager.shutdown(); } clear(); } catch (Throwable throwable) { throw new ServiceRuntimeException(ErrorCode.convert("01-03100"), throwable); }
696
107
803
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/model/ComponentType.java
ComponentType
equals
class ComponentType { private final String typeName; public ComponentType(String typeName) { this.typeName = typeName; } /** * get component type name * * @return type name */ public String getName() { return typeName; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return typeName.hashCode(); } }
if (this == o) { return true; } if (!(o instanceof ComponentType that)) { return false; } return typeName.equals(that.typeName);
134
54
188
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/proxy/ProxyBeanFactoryPostProcessor.java
ProxyBeanFactoryPostProcessor
postProcessBeanDefinitionRegistry
class ProxyBeanFactoryPostProcessor implements BeanDefinitionRegistryPostProcessor, PriorityOrdered { @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {<FILL_FUNCTION_BODY>} @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { } @Override public int getOrder() { return PriorityOrdered.HIGHEST_PRECEDENCE; } }
boolean updateProxyBean = false; for (String beanName : registry.getBeanDefinitionNames()) { String transformedBeanName = BeanFactoryUtils.transformedBeanName(beanName); if (registry.containsBeanDefinition(transformedBeanName)) { BeanDefinition beanDefinition = registry.getBeanDefinition(transformedBeanName); if (ProxyFactoryBean.class.getName().equals(beanDefinition.getBeanClassName())) { beanDefinition.setBeanClassName(SofaProxyFactoryBean.class.getName()); Object proxyInterfaces = beanDefinition.getPropertyValues().get( "proxyInterfaces"); if (proxyInterfaces == null) { proxyInterfaces = beanDefinition.getPropertyValues().get("interfaces"); } beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(0, proxyInterfaces); beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(1, beanDefinition.getPropertyValues().get("targetName")); beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(2, beanDefinition.getPropertyValues().get("targetClass")); // must be true if (registry instanceof ConfigurableListableBeanFactory) { beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(3, registry); } updateProxyBean = true; } } } if (updateProxyBean && registry instanceof ConfigurableListableBeanFactory) { // must clear metadata cache ((ConfigurableListableBeanFactory) registry).clearMetadataCache(); }
134
378
512
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/service/binding/JvmBindingAdapter.java
JvmBindingAdapter
createServiceProxy
class JvmBindingAdapter implements BindingAdapter<JvmBinding> { @Override public void preOutBinding(Object contract, JvmBinding binding, Object target, SofaRuntimeContext sofaRuntimeContext) { } @Override public Object outBinding(Object contract, JvmBinding binding, Object target, SofaRuntimeContext sofaRuntimeContext) { return null; } @Override public void preUnoutBinding(Object contract, JvmBinding binding, Object target, SofaRuntimeContext sofaRuntimeContext) { } @Override public void postUnoutBinding(Object contract, JvmBinding binding, Object target, SofaRuntimeContext sofaRuntimeContext) { } @Override public BindingType getBindingType() { return JvmBinding.JVM_BINDING_TYPE; } @Override public Class<JvmBinding> getBindingClass() { return JvmBinding.class; } @Override public Object inBinding(Object contract, JvmBinding binding, SofaRuntimeContext sofaRuntimeContext) { return createServiceProxy((Contract) contract, binding, sofaRuntimeContext); } @Override public void unInBinding(Object contract, JvmBinding binding, SofaRuntimeContext sofaRuntimeContext) { binding.setDestroyed(true); if (binding.hasBackupProxy()) { binding.setBackupProxy(null); } } /** * create service proxy object * * @return proxy object */ private Object createServiceProxy(Contract contract, JvmBinding binding, SofaRuntimeContext sofaRuntimeContext) {<FILL_FUNCTION_BODY>} }
ClassLoader newClassLoader; ClassLoader appClassLoader = sofaRuntimeContext.getAppClassLoader(); Class<?> javaClass = contract.getInterfaceType(); try { Class<?> appLoadedClass = appClassLoader.loadClass(javaClass.getName()); if (appLoadedClass == javaClass) { newClassLoader = appClassLoader; } else { newClassLoader = javaClass.getClassLoader(); } } catch (ClassNotFoundException e) { newClassLoader = javaClass.getClassLoader(); } ClassLoader finalClassLoader = newClassLoader; return ClassLoaderContextUtils.callWithTemporaryContextClassloader(() -> { ServiceProxy handler = new JvmServiceInvoker(contract, binding, sofaRuntimeContext); ProxyFactory factory = new ProxyFactory(); if (javaClass.isInterface()) { factory.addInterface(javaClass); factory.addInterface(JvmBindingInterface.class); } else { factory.setTargetClass(javaClass); factory.setProxyTargetClass(true); } factory.addAdvice(handler); return factory.getProxy(finalClassLoader); }, finalClassLoader);
435
305
740
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/service/binding/JvmBindingConverter.java
JvmBindingConverter
convert
class JvmBindingConverter implements BindingConverter<JvmBindingParam, JvmBinding> { @Override public JvmBinding convert(JvmBindingParam bindingParam, BindingConverterContext bindingConverterContext) { return new JvmBinding().setJvmBindingParam(bindingParam); } @Override public JvmBinding convert(Element element, BindingConverterContext bindingConverterContext) {<FILL_FUNCTION_BODY>} @Override public JvmBinding convert(SofaService sofaServiceAnnotation, SofaServiceBinding sofaServiceBindingAnnotation, BindingConverterContext bindingConverterContext) { if (JvmBinding.XmlConstants.BINDING_TYPE.equals(sofaServiceBindingAnnotation.bindingType())) { JvmBindingParam jvmBindingParam = new JvmBindingParam(); jvmBindingParam.setSerialize(sofaServiceBindingAnnotation.serialize()); return new JvmBinding().setJvmBindingParam(jvmBindingParam); } return null; } @Override public JvmBinding convert(SofaReference sofaReferenceAnnotation, SofaReferenceBinding sofaReferenceBindingAnnotation, BindingConverterContext bindingConverterContext) { if (JvmBinding.XmlConstants.BINDING_TYPE.equals(sofaReferenceBindingAnnotation .bindingType())) { JvmBindingParam jvmBindingParam = new JvmBindingParam(); jvmBindingParam.setSerialize(sofaReferenceBindingAnnotation.serialize()); return new JvmBinding().setJvmBindingParam(jvmBindingParam); } return null; } @Override public BindingType supportBindingType() { return JvmBinding.JVM_BINDING_TYPE; } @Override public String supportTagName() { return JvmBinding.XmlConstants.SUPPORT_TAG_NAME; } }
JvmBindingParam jvmBindingParam = new JvmBindingParam(); if (element != null) { jvmBindingParam.setSerialize(Boolean.TRUE.toString().equalsIgnoreCase( element.getAttribute(JvmBinding.XmlConstants.SERIALIZE))); } return new JvmBinding().setJvmBindingParam(jvmBindingParam);
464
92
556
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/service/binding/JvmServiceInvoker.java
JvmServiceInvoker
invoke
class JvmServiceInvoker extends ServiceProxy { private static final Logger LOGGER = SofaBootLoggerFactory .getLogger(JvmServiceInvoker.class); private final Contract contract; private final JvmBinding binding; private final SofaRuntimeContext sofaRuntimeContext; private Object target; public JvmServiceInvoker(Contract contract, JvmBinding binding, SofaRuntimeContext sofaRuntimeContext) { super(sofaRuntimeContext.getAppClassLoader()); this.binding = binding; this.sofaRuntimeContext = sofaRuntimeContext; this.contract = contract; } @Override public Object invoke(MethodInvocation invocation) throws Throwable {<FILL_FUNCTION_BODY>} @Override public Object doInvoke(MethodInvocation invocation) throws Throwable { if (binding.isDestroyed()) { throw new IllegalStateException("Can not call destroyed reference! JVM Reference[" + getInterfaceName() + "#" + getUniqueId() + "] has already been destroyed."); } LOGGER.atDebug().log(">> Start in JVM service invoke, the service interface is - {}.", getInterfaceName()); Object retVal; Object targetObj = this.getTarget(); // invoke internal dynamic-biz jvm service if (targetObj == null) { ServiceProxy serviceProxy = sofaRuntimeContext.getServiceProxyManager() .getDynamicServiceProxy(contract, sofaRuntimeContext.getAppClassLoader()); if (serviceProxy != null) { try { return serviceProxy.invoke(invocation); } finally { LOGGER.atDebug().log( "<< Finish Cross App JVM service invoke, the service is - {}.", getInterfaceName() + "#" + getUniqueId()); } } } if (targetObj == null || ((targetObj instanceof Proxy) && binding.hasBackupProxy())) { targetObj = binding.getBackupProxy(); LOGGER.atDebug().log("<<{}.{} backup proxy invoke.", getInterfaceName().getName(), invocation.getMethod().getName()); } if (targetObj == null) { throw new IllegalStateException(ErrorCode.convert("01-00400", getInterfaceName(), getUniqueId())); } ClassLoader tcl = Thread.currentThread().getContextClassLoader(); try { pushThreadContextClassLoader(sofaRuntimeContext.getAppClassLoader()); retVal = invocation.getMethod().invoke(targetObj, invocation.getArguments()); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } finally { LOGGER.atDebug().log( "<< Finish JVM service invoke, the service implementation is - {}]", (this.target == null ? "null" : this.target.getClass().getName())); popThreadContextClassLoader(tcl); } return retVal; } @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)); } protected Object getTarget() { if (this.target == null) { ServiceComponent serviceComponent = JvmServiceSupport.foundServiceComponent( sofaRuntimeContext.getComponentManager(), contract); if (serviceComponent != null) { this.target = serviceComponent.getImplementation().getTarget(); } } return target; } protected Class<?> getInterfaceName() { return contract.getInterfaceType(); } protected String getUniqueId() { return contract.getUniqueId(); } }
if (!sofaRuntimeContext.getProperties().isJvmFilterEnable()) { // Jvm filtering is not enabled return super.invoke(invocation); } ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); JvmFilterContext context = new JvmFilterContext(invocation); Object rtn; if (getTarget() == null) { ServiceComponent serviceComponent = sofaRuntimeContext.getServiceProxyManager() .getDynamicServiceComponent(contract, sofaRuntimeContext.getAppClassLoader()); if (serviceComponent == null) { // Jvm service is not found in normal or Ark environment // We're actually invoking an RPC service, skip Jvm filtering return super.invoke(invocation); } context.setSofaRuntimeContext(serviceComponent.getContext()); } else { context.setSofaRuntimeContext(sofaRuntimeContext); } long startTime = System.currentTimeMillis(); try { Thread.currentThread().setContextClassLoader(serviceClassLoader); // Do Jvm filter <code>before</code> invoking // if some filter returns false, skip remaining filters and actual Jvm invoking if (JvmFilterHolder.beforeInvoking(context)) { rtn = doInvoke(invocation); context.setInvokeResult(rtn); } } catch (Throwable e) { // Exception occurs, set <code>e</code> in Jvm context context.setException(e); doCatch(invocation, e, startTime); throw e; } finally { // Do Jvm Filter <code>after</code> invoking regardless of the fact whether exception happens or not JvmFilterHolder.afterInvoking(context); rtn = context.getInvokeResult(); doFinally(invocation, startTime); Thread.currentThread().setContextClassLoader(oldClassLoader); } return rtn;
1,010
491
1,501
<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/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/service/binding/JvmServiceSupport.java
JvmServiceSupport
foundServiceComponent
class JvmServiceSupport { public static ServiceComponent foundServiceComponent(ComponentManager componentManager, Contract contract) {<FILL_FUNCTION_BODY>} }
ComponentName componentName = ComponentNameFactory.createComponentName( ServiceComponent.SERVICE_COMPONENT_TYPE, contract.getInterfaceType(), contract.getUniqueId()); return (ServiceComponent) componentManager.getComponentInfo(componentName);
44
64
108
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/service/client/ReferenceClientImpl.java
ReferenceClientImpl
getReferenceFromReferenceParam
class ReferenceClientImpl implements ReferenceClient { private final SofaRuntimeContext sofaRuntimeContext; private final BindingConverterFactory bindingConverterFactory; private final BindingAdapterFactory bindingAdapterFactory; public ReferenceClientImpl(SofaRuntimeContext sofaRuntimeContext, BindingConverterFactory bindingConverterFactory, BindingAdapterFactory bindingAdapterFactory) { this.sofaRuntimeContext = sofaRuntimeContext; this.bindingConverterFactory = bindingConverterFactory; this.bindingAdapterFactory = bindingAdapterFactory; } @SuppressWarnings("unchecked") private <T> Reference getReferenceFromReferenceParam(ReferenceParam<T> referenceParam) {<FILL_FUNCTION_BODY>} @SuppressWarnings("unchecked") @Override public <T> T reference(ReferenceParam<T> referenceParam) { return (T) ReferenceRegisterHelper.registerReference( getReferenceFromReferenceParam(referenceParam), bindingAdapterFactory, sofaRuntimeContext); } @Override public <T> void removeReference(ReferenceParam<T> referenceParam) { Reference reference = getReferenceFromReferenceParam(referenceParam); ComponentName referenceComponentName = ComponentNameFactory.createComponentName( ReferenceComponent.REFERENCE_COMPONENT_TYPE, reference.getInterfaceType(), reference.getUniqueId() + "#" + ReferenceRegisterHelper.generateBindingHashCode(reference)); Collection<ComponentInfo> referenceComponents = sofaRuntimeContext.getComponentManager() .getComponentInfosByType(ReferenceComponent.REFERENCE_COMPONENT_TYPE); for (ComponentInfo referenceComponent : referenceComponents) { if (referenceComponent.getName().equals(referenceComponentName)) { sofaRuntimeContext.getComponentManager().unregister(referenceComponent); } } } @Override public void removeReference(Class<?> interfaceClass) { removeReference(interfaceClass, ""); } @Override public void removeReference(Class<?> interfaceClass, String uniqueId) { Collection<ComponentInfo> referenceComponents = sofaRuntimeContext.getComponentManager() .getComponentInfosByType(ReferenceComponent.REFERENCE_COMPONENT_TYPE); for (ComponentInfo componentInfo : referenceComponents) { if (!(componentInfo instanceof ReferenceComponent)) { continue; } ReferenceComponent referenceComponent = (ReferenceComponent) componentInfo; if (referenceComponent.getReference().getInterfaceType() == interfaceClass && referenceComponent.getReference().getUniqueId().equals(uniqueId)) { sofaRuntimeContext.getComponentManager().unregister(referenceComponent); } } } }
BindingParam bindingParam = referenceParam.getBindingParam(); Reference reference = new ReferenceImpl(referenceParam.getUniqueId(), referenceParam.getInterfaceType(), InterfaceMode.api, referenceParam.isJvmFirst(), null); reference.setRequired(referenceParam.isRequired()); if (bindingParam == null) { // default add jvm binding and reference jvm binding should set serialize as false JvmBindingParam jvmBindingParam = new JvmBindingParam(); jvmBindingParam.setSerialize(false); reference.addBinding(new JvmBinding().setJvmBindingParam(jvmBindingParam)); } else { BindingConverter bindingConverter = bindingConverterFactory .getBindingConverter(bindingParam.getBindingType()); if (bindingConverter == null) { throw new ServiceRuntimeException(ErrorCode.convert("01-00200", bindingParam.getBindingType())); } BindingConverterContext bindingConverterContext = new BindingConverterContext(); bindingConverterContext.setInBinding(true); bindingConverterContext.setAppName(sofaRuntimeContext.getAppName()); bindingConverterContext.setAppClassLoader(sofaRuntimeContext.getAppClassLoader()); Binding binding = bindingConverter.convert(bindingParam, bindingConverterContext); reference.addBinding(binding); } return reference;
660
333
993
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/service/client/ServiceClientImpl.java
ServiceClientImpl
removeService
class ServiceClientImpl implements ServiceClient { private final SofaRuntimeContext sofaRuntimeContext; private final BindingConverterFactory bindingConverterFactory; private final BindingAdapterFactory bindingAdapterFactory; public ServiceClientImpl(SofaRuntimeContext sofaRuntimeContext, BindingConverterFactory bindingConverterFactory, BindingAdapterFactory bindingAdapterFactory) { this.sofaRuntimeContext = sofaRuntimeContext; this.bindingConverterFactory = bindingConverterFactory; this.bindingAdapterFactory = bindingAdapterFactory; } @SuppressWarnings("unchecked") @Override public void service(ServiceParam serviceParam) { Implementation implementation = new DefaultImplementation(); implementation.setTarget(serviceParam.getInstance()); if (serviceParam.getInterfaceType() == null) { throw new ServiceRuntimeException(ErrorCode.convert("01-00201")); } Service service = new ServiceImpl(serviceParam.getUniqueId(), serviceParam.getInterfaceType(), InterfaceMode.api, serviceParam.getInstance(), null); for (BindingParam bindingParam : serviceParam.getBindingParams()) { BindingConverter bindingConverter = bindingConverterFactory .getBindingConverter(bindingParam.getBindingType()); if (bindingConverter == null) { throw new ServiceRuntimeException(ErrorCode.convert("01-00200", bindingParam.getBindingType())); } BindingConverterContext bindingConverterContext = new BindingConverterContext(); bindingConverterContext.setInBinding(false); bindingConverterContext.setAppName(sofaRuntimeContext.getAppName()); bindingConverterContext.setAppClassLoader(sofaRuntimeContext.getAppClassLoader()); Binding binding = bindingConverter.convert(bindingParam, bindingConverterContext); service.addBinding(binding); } boolean hasJvmBinding = false; for (Binding binding : service.getBindings()) { if (binding.getBindingType().equals(JvmBinding.JVM_BINDING_TYPE)) { hasJvmBinding = true; break; } } if (!hasJvmBinding) { service.addBinding(new JvmBinding()); } ComponentInfo componentInfo = new ServiceComponent(implementation, service, bindingAdapterFactory, sofaRuntimeContext); sofaRuntimeContext.getComponentManager().register(componentInfo); } @Override public void removeService(Class<?> interfaceClass, int millisecondsToDelay) { removeService(interfaceClass, "", millisecondsToDelay); } @Override public void removeService(Class<?> interfaceClass, String uniqueId, int millisecondsToDelay) {<FILL_FUNCTION_BODY>} }
if (millisecondsToDelay < 0) { throw new IllegalArgumentException(ErrorCode.convert("01-00202")); } Collection<ComponentInfo> serviceComponents = sofaRuntimeContext.getComponentManager() .getComponentInfosByType(ServiceComponent.SERVICE_COMPONENT_TYPE); for (ComponentInfo componentInfo : serviceComponents) { if (!(componentInfo instanceof ServiceComponent serviceComponent)) { continue; } if (serviceComponent.getService().getInterfaceType() == interfaceClass && serviceComponent.getService().getUniqueId().equals(uniqueId)) { Map<String, Property> properties = serviceComponent.getProperties(); Property property = new Property(); property.setValue(millisecondsToDelay); properties.put(ServiceComponent.UNREGISTER_DELAY_MILLISECONDS, property); sofaRuntimeContext.getComponentManager().unregister(serviceComponent); } }
677
241
918
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/service/component/AbstractContract.java
AbstractContract
getProperty
class AbstractContract implements Contract { /** associated binding */ protected Set<Binding> bindings = new HashSet<>(2); /** unique id */ protected String uniqueId; /** interface class type */ protected Class<?> interfaceType; /** interface class type name*/ protected String interfaceTypeCanonicalName; /** interface mode */ protected InterfaceMode interfaceMode = InterfaceMode.spring; /** properties of contract */ protected Map<String, String> property = new HashMap<>(); protected AbstractContract(String uniqueId, Class<?> interfaceType) { this.uniqueId = Objects.requireNonNullElse(uniqueId, ""); this.interfaceType = interfaceType; this.interfaceTypeCanonicalName = interfaceType.getCanonicalName(); } protected AbstractContract(String uniqueId, Class<?> interfaceType, InterfaceMode interfaceMode) { this(uniqueId, interfaceType); this.interfaceMode = interfaceMode; } protected AbstractContract(String uniqueId, Class<?> interfaceType, InterfaceMode interfaceMode, Map<String, String> property) { this(uniqueId, interfaceType, interfaceMode); this.property = property; } @Override public <T extends Binding> void addBinding(T binding) { this.bindings.add(binding); } @Override public <T extends Binding> void addBinding(Set<T> bindings) { this.bindings.addAll(bindings); } @Override public Binding getBinding(BindingType bindingType) { for (Binding binding : this.bindings) { if (binding != null && binding.getBindingType() == bindingType) { return binding; } } return null; } @SuppressWarnings("unchecked") @Override public Set<Binding> getBindings() { return this.bindings; } @Override public boolean hasBinding() { return this.bindings.size() > 0; } @Override public String getUniqueId() { return uniqueId; } @Override public InterfaceMode getInterfaceMode() { return this.interfaceMode; } @Override public Class<?> getInterfaceType() { return interfaceType; } @Override public String getProperty(String key) {<FILL_FUNCTION_BODY>} @Override public Map<String, String> getProperty() { return property; } @Override public String getInterfaceTypeCanonicalName() { return interfaceTypeCanonicalName; } }
if (property == null) { return null; } return property.get(key);
682
30
712
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/service/component/impl/ReferenceImpl.java
ReferenceImpl
toString
class ReferenceImpl extends AbstractContract implements Reference { /** jvm first or not */ private final boolean jvmFirst; /** jvm reference health check or not */ private boolean required = true; public ReferenceImpl(String uniqueId, Class<?> interfaceType, InterfaceMode interfaceMode, boolean jvmFirst) { super(uniqueId, interfaceType, interfaceMode); this.jvmFirst = jvmFirst; } public ReferenceImpl(String uniqueId, Class<?> interfaceType, InterfaceMode interfaceMode, boolean jvmFirst, Map<String, String> properties) { super(uniqueId, interfaceType, interfaceMode, properties); this.jvmFirst = jvmFirst; } @Override public boolean isJvmFirst() { return jvmFirst; } @Override public String toString() {<FILL_FUNCTION_BODY>} @Override public boolean isRequired() { return required; } @Override public void setRequired(boolean required) { this.required = required; } }
return this.getInterfaceType().getName() + (StringUtils.hasText(uniqueId) ? ":" + uniqueId : "");
277
36
313
<methods>public void addBinding(T) ,public void addBinding(Set<T>) ,public com.alipay.sofa.runtime.spi.binding.Binding getBinding(com.alipay.sofa.runtime.api.binding.BindingType) ,public Set<com.alipay.sofa.runtime.spi.binding.Binding> getBindings() ,public com.alipay.sofa.runtime.model.InterfaceMode getInterfaceMode() ,public Class<?> getInterfaceType() ,public java.lang.String getInterfaceTypeCanonicalName() ,public java.lang.String getProperty(java.lang.String) ,public Map<java.lang.String,java.lang.String> getProperty() ,public java.lang.String getUniqueId() ,public boolean hasBinding() <variables>protected Set<com.alipay.sofa.runtime.spi.binding.Binding> bindings,protected com.alipay.sofa.runtime.model.InterfaceMode interfaceMode,protected Class<?> interfaceType,protected java.lang.String interfaceTypeCanonicalName,protected Map<java.lang.String,java.lang.String> property,protected java.lang.String uniqueId
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/service/component/impl/ServiceImpl.java
ServiceImpl
toString
class ServiceImpl extends AbstractContract implements Service { private final Object target; public ServiceImpl(String uniqueId, Class<?> interfaceType, Object target) { super(uniqueId, interfaceType); this.target = target; } public ServiceImpl(String uniqueId, Class<?> interfaceType, InterfaceMode interfaceMode, Object target) { super(uniqueId, interfaceType, interfaceMode); this.target = target; } public ServiceImpl(String uniqueId, Class<?> interfaceType, InterfaceMode interfaceMode, Object target, Map<String, String> property) { super(uniqueId, interfaceType, interfaceMode, property); this.target = target; } @Override public Object getTarget() { return target; } @Override public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return this.getInterfaceType().getName() + (StringUtils.hasText(uniqueId) ? ":" + uniqueId : "");
257
36
293
<methods>public void addBinding(T) ,public void addBinding(Set<T>) ,public com.alipay.sofa.runtime.spi.binding.Binding getBinding(com.alipay.sofa.runtime.api.binding.BindingType) ,public Set<com.alipay.sofa.runtime.spi.binding.Binding> getBindings() ,public com.alipay.sofa.runtime.model.InterfaceMode getInterfaceMode() ,public Class<?> getInterfaceType() ,public java.lang.String getInterfaceTypeCanonicalName() ,public java.lang.String getProperty(java.lang.String) ,public Map<java.lang.String,java.lang.String> getProperty() ,public java.lang.String getUniqueId() ,public boolean hasBinding() <variables>protected Set<com.alipay.sofa.runtime.spi.binding.Binding> bindings,protected com.alipay.sofa.runtime.model.InterfaceMode interfaceMode,protected Class<?> interfaceType,protected java.lang.String interfaceTypeCanonicalName,protected Map<java.lang.String,java.lang.String> property,protected java.lang.String uniqueId
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/service/helper/ReferenceRegisterHelper.java
ReferenceRegisterHelper
generateBindingHashCode
class ReferenceRegisterHelper { public static Object registerReference(Reference reference, BindingAdapterFactory bindingAdapterFactory, SofaRuntimeContext sofaRuntimeContext) { return registerReference(reference, bindingAdapterFactory, sofaRuntimeContext, null, null); } public static Object registerReference(Reference reference, BindingAdapterFactory bindingAdapterFactory, SofaRuntimeContext sofaRuntimeContext, ApplicationContext applicationContext) { return registerReference(reference, bindingAdapterFactory, sofaRuntimeContext, applicationContext, null); } public static Object registerReference(Reference reference, BindingAdapterFactory bindingAdapterFactory, SofaRuntimeContext sofaRuntimeContext, ApplicationContext applicationContext, ComponentDefinitionInfo definitionInfo) { Binding binding = (Binding) reference.getBindings().toArray()[0]; if (!binding.getBindingType().equals(JvmBinding.JVM_BINDING_TYPE) && !sofaRuntimeContext.getProperties().isDisableJvmFirst() && reference.isJvmFirst()) { // as rpc invocation would be serialized, so here would Not ignore serialized reference.addBinding(new JvmBinding()); } ComponentManager componentManager = sofaRuntimeContext.getComponentManager(); ReferenceComponent referenceComponent = new ReferenceComponent(reference, new DefaultImplementation(), bindingAdapterFactory, sofaRuntimeContext); Property property = new Property(); property.setName(SOURCE); property.setValue(definitionInfo); referenceComponent.getProperties().put(SOURCE, property); if (componentManager.isRegistered(referenceComponent.getName())) { return componentManager.getComponentInfo(referenceComponent.getName()) .getImplementation().getTarget(); } ComponentInfo componentInfo = componentManager.registerAndGet(referenceComponent); componentInfo.setApplicationContext(applicationContext); return componentInfo.getImplementation().getTarget(); } public static int generateBindingHashCode(Reference reference) {<FILL_FUNCTION_BODY>} }
Collection<Binding> bindings = reference.getBindings(); int result = 1; for (Binding binding : bindings) { result = result * 31 + binding.getBindingHashCode(); } ClassLoader cl = reference.getInterfaceType().getClassLoader(); if (cl != null) { result += reference.getInterfaceType().getClassLoader().hashCode(); } return result;
509
110
619
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/service/impl/BindingAdapterFactoryImpl.java
BindingAdapterFactoryImpl
addBindingAdapters
class BindingAdapterFactoryImpl implements BindingAdapterFactory { private final Map<BindingType, BindingAdapter> bindingTypeBindingAdapterMap = new HashMap<>(); @Override public BindingAdapter getBindingAdapter(BindingType bindingType) { return bindingTypeBindingAdapterMap.get(bindingType); } @Override public void addBindingAdapters(Set<BindingAdapter> bindingAdapters) {<FILL_FUNCTION_BODY>} }
if (bindingAdapters == null || bindingAdapters.size() == 0) { return; } List<BindingAdapter> sortedBindingAdapters = new ArrayList<>(bindingAdapters); sortedBindingAdapters.sort(AnnotationAwareOrderComparator.INSTANCE); for (BindingAdapter bindingAdapter : sortedBindingAdapters) { bindingTypeBindingAdapterMap.putIfAbsent(bindingAdapter.getBindingType(), bindingAdapter); }
116
120
236
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/service/impl/BindingConverterFactoryImpl.java
BindingConverterFactoryImpl
addBindingConverters
class BindingConverterFactoryImpl implements BindingConverterFactory { private final Map<BindingType, BindingConverter> bindingTypeBindingConverterMap = new HashMap<>(); private final Map<String, BindingConverter> tagBindingConverterMap = new HashMap<>(); @Override public BindingConverter getBindingConverter(BindingType bindingType) { return bindingTypeBindingConverterMap.get(bindingType); } @Override public BindingConverter getBindingConverterByTagName(String tagName) { return tagBindingConverterMap.get(tagName); } @Override public void addBindingConverters(Set<BindingConverter> bindingConverters) {<FILL_FUNCTION_BODY>} }
if (bindingConverters == null || bindingConverters.size() == 0) { return; } List<BindingConverter> sortedBindingConverter = new ArrayList<>(bindingConverters); sortedBindingConverter.sort(AnnotationAwareOrderComparator.INSTANCE); for (BindingConverter<?, ?> bindingConverter : sortedBindingConverter) { bindingTypeBindingConverterMap.putIfAbsent(bindingConverter.supportBindingType(), bindingConverter); tagBindingConverterMap.putIfAbsent(bindingConverter.supportTagName(), bindingConverter); }
180
141
321
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/spi/component/AbstractComponent.java
AbstractComponent
deactivate
class AbstractComponent implements ComponentInfo { /** * component status */ protected ComponentStatus componentStatus = ComponentStatus.UNREGISTERED; protected Implementation implementation; protected ComponentName componentName; protected SofaRuntimeContext sofaRuntimeContext; protected Exception e; protected ApplicationContext applicationContext; protected Map<String, Property> properties = new ConcurrentHashMap<>(); @Override public SofaRuntimeContext getContext() { return sofaRuntimeContext; } @Override public ComponentStatus getState() { return componentStatus; } @Override public ComponentName getName() { return componentName; } @Override public ApplicationContext getApplicationContext() { return applicationContext; } @Override public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } @Override public Implementation getImplementation() { return implementation; } @Override public boolean isActivated() { return componentStatus == ComponentStatus.ACTIVATED; } @Override public boolean isResolved() { return componentStatus == ComponentStatus.ACTIVATED || componentStatus == ComponentStatus.RESOLVED; } @Override public void register() { if (componentStatus != ComponentStatus.UNREGISTERED) { return; } componentStatus = ComponentStatus.REGISTERED; } @Override public void unregister() throws ServiceRuntimeException { if (componentStatus == ComponentStatus.UNREGISTERED) { return; } if (componentStatus == ComponentStatus.ACTIVATED || componentStatus == ComponentStatus.RESOLVED) { unresolve(); } componentStatus = ComponentStatus.UNREGISTERED; } @Override public void unresolve() throws ServiceRuntimeException { if (componentStatus == ComponentStatus.REGISTERED || componentStatus == ComponentStatus.UNREGISTERED) { return; } if (componentStatus == ComponentStatus.ACTIVATED) { deactivate(); } componentStatus = ComponentStatus.REGISTERED; } @Override public boolean resolve() { if (componentStatus != ComponentStatus.REGISTERED) { return false; } componentStatus = ComponentStatus.RESOLVED; return true; } @Override public void activate() throws ServiceRuntimeException { if (componentStatus != ComponentStatus.RESOLVED) { return; } if (this.implementation != null) { Object target = this.implementation.getTarget(); if (target instanceof ComponentLifeCycle) { ((ComponentLifeCycle) target).activate(); } } componentStatus = ComponentStatus.ACTIVATED; } @Override public void exception(Exception e) throws ServiceRuntimeException { this.e = e; } @Override public void deactivate() throws ServiceRuntimeException {<FILL_FUNCTION_BODY>} @Override public String dump() { return componentName.getRawName(); } @Override public HealthResult isHealthy() { HealthResult healthResult = new HealthResult(componentName.getRawName()); if (!isActivated()) { healthResult.setHealthy(false); healthResult.setHealthReport("Status: " + this.getState().toString()); } else if (e != null) { healthResult.setHealthy(false); healthResult.setHealthReport(e.getMessage()); } else { healthResult.setHealthy(true); } return healthResult; } protected String aggregateBindingHealth(Collection<Binding> bindings) { List<String> healthResult = new ArrayList<>(); for (Binding binding : bindings) { HealthResult result = binding.healthCheck(); String report = "[" + result.getHealthName() + "," + (result.getHealthReport() == null ? (result.isHealthy() ? "passed" : "failed") : result.getHealthReport()) + "]"; healthResult.add(report); } return String.join(" ", healthResult); } @Override public boolean canBeDuplicate() { return true; } @Override public Map<String, Property> getProperties() { return properties; } }
if (componentStatus != ComponentStatus.ACTIVATED) { return; } if (this.implementation != null) { Object target = this.implementation.getTarget(); if (target instanceof ComponentLifeCycle) { ((ComponentLifeCycle) target).deactivate(); } } componentStatus = ComponentStatus.RESOLVED;
1,163
99
1,262
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/spi/component/ComponentNameFactory.java
ComponentNameFactory
mergeComponentName
class ComponentNameFactory { /** * Create ComponentName by component type and class type. * * @param type component type * @param clazz clazz */ public static ComponentName createComponentName(ComponentType type, Class<?> clazz) { return new ComponentName(type, mergeComponentName(clazz, null)); } /** * Create ComponentName by component type and component name. * * @param type component type * @param name name * @return component name */ public static ComponentName createComponentName(ComponentType type, String name) { return new ComponentName(type, name); } /** * Create ComponentName by component type,class type and unique id. * * @param type component type * @param clazz clazz * @param uniqueId unique id */ public static ComponentName createComponentName(ComponentType type, Class<?> clazz, String uniqueId) { return new ComponentName(type, mergeComponentName(clazz, uniqueId)); } /** * Create ComponentName by class type and unique id. * * @param clazz clazz * @param uniqueId unique id */ private static String mergeComponentName(Class<?> clazz, String uniqueId) {<FILL_FUNCTION_BODY>} }
String ret = clazz.getName(); if (StringUtils.hasText(uniqueId)) { ret += ":" + uniqueId; } return ret;
344
45
389
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/spi/service/ServiceProxy.java
ServiceProxy
invoke
class ServiceProxy implements MethodInterceptor { protected ClassLoader serviceClassLoader; public ServiceProxy(ClassLoader serviceClassLoader) { this.serviceClassLoader = serviceClassLoader; } @Override public Object invoke(MethodInvocation invocation) throws Throwable {<FILL_FUNCTION_BODY>} protected void pushThreadContextClassLoader(ClassLoader newContextClassLoader) { if (newContextClassLoader != null) { Thread.currentThread().setContextClassLoader(newContextClassLoader); } } protected void popThreadContextClassLoader(ClassLoader tcl) { Thread.currentThread().setContextClassLoader(tcl); } protected String getCommonInvocationLog(String start, MethodInvocation invocation, long startTime) { String appStart = ""; if (StringUtils.hasText(appStart)) { appStart = "-" + start; } long endTime = System.currentTimeMillis(); StringBuilder sb = new StringBuilder("SOFA-Reference" + appStart + "("); sb.append(invocation.getMethod().getName()).append(","); for (Object o : invocation.getArguments()) { sb.append(o); sb.append(","); } sb.append((endTime - startTime)).append("ms").append(")"); return sb.toString(); } public ClassLoader getServiceClassLoader() { return serviceClassLoader; } /** * Actually do invoke. * * @param invocation invocation * @return invoke result * @throws Throwable invoke exception */ protected abstract Object doInvoke(MethodInvocation invocation) throws Throwable; /** * Hook to handle exception. * * @param invocation invocation * @param e exception * @param startTime start time */ protected abstract void doCatch(MethodInvocation invocation, Throwable e, long startTime); /** * Hook to handle after invocatino. * * @param invocation invocation * @param startTime start time */ protected abstract void doFinally(MethodInvocation invocation, long startTime); }
ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); long startTime = System.currentTimeMillis(); try { Thread.currentThread().setContextClassLoader(serviceClassLoader); return doInvoke(invocation); } catch (Throwable e) { doCatch(invocation, e, startTime); throw e; } finally { doFinally(invocation, startTime); Thread.currentThread().setContextClassLoader(oldClassLoader); }
569
128
697
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/spring/AsyncInitBeanFactoryPostProcessor.java
AsyncInitBeanFactoryPostProcessor
scanAsyncInitBeanDefinitionOnMethod
class AsyncInitBeanFactoryPostProcessor implements BeanFactoryPostProcessor, EnvironmentAware { private static final Logger LOGGER = SofaBootLoggerFactory .getLogger(AsyncInitBeanFactoryPostProcessor.class); private AnnotationWrapper<SofaAsyncInit> annotationWrapper; @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { Arrays.stream(beanFactory.getBeanDefinitionNames()) .collect(Collectors.toMap(Function.identity(), beanFactory::getBeanDefinition)) .forEach(this::scanAsyncInitBeanDefinition); } /** * {@link ScannedGenericBeanDefinition} * {@link AnnotatedGenericBeanDefinition} * {@link GenericBeanDefinition} * {@link org.springframework.beans.factory.support.ChildBeanDefinition} * {@link org.springframework.beans.factory.support.RootBeanDefinition} */ private void scanAsyncInitBeanDefinition(String beanId, BeanDefinition beanDefinition) { if (BeanDefinitionUtil.isFromConfigurationSource(beanDefinition)) { scanAsyncInitBeanDefinitionOnMethod(beanId, (AnnotatedBeanDefinition) beanDefinition); } else { Class<?> beanClassType = BeanDefinitionUtil.resolveBeanClassType(beanDefinition); if (beanClassType == null) { return; } scanAsyncInitBeanDefinitionOnClass(beanClassType, beanDefinition); } } private void scanAsyncInitBeanDefinitionOnMethod(String beanId, AnnotatedBeanDefinition beanDefinition) {<FILL_FUNCTION_BODY>} private void scanAsyncInitBeanDefinitionOnClass(Class<?> beanClass, BeanDefinition beanDefinition) { // See issue: https://github.com/sofastack/sofa-boot/issues/835 SofaAsyncInit sofaAsyncInitAnnotation = AnnotationUtils.findAnnotation(beanClass, SofaAsyncInit.class); registerAsyncInitBean(sofaAsyncInitAnnotation, beanDefinition); } @SuppressWarnings("unchecked") private void registerAsyncInitBean(SofaAsyncInit sofaAsyncInitAnnotation, BeanDefinition beanDefinition) { if (sofaAsyncInitAnnotation == null) { return; } sofaAsyncInitAnnotation = annotationWrapper.wrap(sofaAsyncInitAnnotation); String initMethodName = beanDefinition.getInitMethodName(); if (sofaAsyncInitAnnotation.value() && StringUtils.hasText(initMethodName)) { beanDefinition.setAttribute(ASYNC_INIT_METHOD_NAME, initMethodName); } } @Override public void setEnvironment(Environment environment) { this.annotationWrapper = AnnotationWrapper.create(SofaAsyncInit.class) .withEnvironment(environment).withBinder(DefaultPlaceHolderBinder.INSTANCE); } }
Class<?> returnType; Class<?> declaringClass; List<Method> candidateMethods = new ArrayList<>(); MethodMetadata methodMetadata = beanDefinition.getFactoryMethodMetadata(); try { returnType = ClassUtils.forName(methodMetadata.getReturnTypeName(), null); declaringClass = ClassUtils.forName(methodMetadata.getDeclaringClassName(), null); } catch (Throwable throwable) { // it's impossible to catch throwable here LOGGER.error(ErrorCode.convert("01-02001", beanId), throwable); return; } if (methodMetadata instanceof StandardMethodMetadata) { candidateMethods.add(((StandardMethodMetadata) methodMetadata).getIntrospectedMethod()); } else { for (Method m : declaringClass.getDeclaredMethods()) { // check methodName and return type if (!m.getName().equals(methodMetadata.getMethodName()) || !m.getReturnType().getTypeName().equals(methodMetadata.getReturnTypeName())) { continue; } // check bean method if (!AnnotatedElementUtils.hasAnnotation(m, Bean.class)) { continue; } Bean bean = m.getAnnotation(Bean.class); Set<String> beanNames = new HashSet<>(); beanNames.add(m.getName()); if (bean != null) { beanNames.addAll(Arrays.asList(bean.name())); beanNames.addAll(Arrays.asList(bean.value())); } // check bean name if (!beanNames.contains(beanId)) { continue; } candidateMethods.add(m); } } if (candidateMethods.size() == 1) { SofaAsyncInit sofaAsyncInitAnnotation = candidateMethods.get(0).getAnnotation( SofaAsyncInit.class); if (sofaAsyncInitAnnotation == null) { sofaAsyncInitAnnotation = returnType.getAnnotation(SofaAsyncInit.class); } registerAsyncInitBean(sofaAsyncInitAnnotation, beanDefinition); } else if (candidateMethods.size() > 1) { for (Method m : candidateMethods) { if (AnnotatedElementUtils.hasAnnotation(m, SofaAsyncInit.class) || AnnotatedElementUtils.hasAnnotation(returnType, SofaAsyncInit.class)) { throw new FatalBeanException(ErrorCode.convert("01-02002", declaringClass.getCanonicalName())); } } }
723
654
1,377
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/spring/AsyncProxyBeanPostProcessor.java
AsyncProxyBeanPostProcessor
postProcessBeforeInitialization
class AsyncProxyBeanPostProcessor implements BeanPostProcessor, InitializingBean, BeanFactoryAware, Ordered { private final AsyncInitMethodManager asyncInitMethodManager; private ConfigurableListableBeanFactory beanFactory; public AsyncProxyBeanPostProcessor(AsyncInitMethodManager asyncInitMethodManager) { this.asyncInitMethodManager = asyncInitMethodManager; } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {<FILL_FUNCTION_BODY>} @Override public int getOrder() { return PriorityOrdered.HIGHEST_PRECEDENCE; } @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = (ConfigurableListableBeanFactory) beanFactory; } @Override public void afterPropertiesSet() throws Exception { for (String beanName : beanFactory.getBeanDefinitionNames()) { BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName); String asyncInitMethodName = (String) beanDefinition .getAttribute(ASYNC_INIT_METHOD_NAME); if (StringUtils.hasText(asyncInitMethodName)) { asyncInitMethodManager.registerAsyncInitBean(beanFactory, beanName, asyncInitMethodName); } } } }
String methodName = asyncInitMethodManager.findAsyncInitMethod(beanFactory, beanName); if (!StringUtils.hasText(methodName)) { return bean; } ProxyFactory proxyFactory = new ProxyFactory(); proxyFactory.setTargetClass(bean.getClass()); proxyFactory.setProxyTargetClass(true); AsyncInitializeBeanMethodInvoker asyncInitializeBeanMethodInvoker = new AsyncInitializeBeanMethodInvoker( asyncInitMethodManager, bean, beanName, methodName); proxyFactory.addAdvice(asyncInitializeBeanMethodInvoker); return proxyFactory.getProxy();
350
156
506
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/spring/ClientFactoryAnnotationBeanPostProcessor.java
ClientFactoryAnnotationBeanPostProcessor
postProcessBeforeInitialization
class ClientFactoryAnnotationBeanPostProcessor implements BeanPostProcessor, PriorityOrdered { private final ClientFactory clientFactory; public ClientFactoryAnnotationBeanPostProcessor(ClientFactory clientFactory) { this.clientFactory = clientFactory; } @Override public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {<FILL_FUNCTION_BODY>} @Override public int getOrder() { return PriorityOrdered.HIGHEST_PRECEDENCE; } }
ReflectionUtils.doWithFields(bean.getClass(), field -> { if (ClientFactory.class.isAssignableFrom(field.getType())) { ReflectionUtils.makeAccessible(field); ReflectionUtils.setField(field, bean, clientFactory); } else if ((clientFactory instanceof ClientFactoryImpl) && ((ClientFactoryImpl) clientFactory).getAllClientTypes().contains( field.getType())) { Object client = clientFactory.getClient(field.getType()); ReflectionUtils.makeAccessible(field); ReflectionUtils.setField(field, bean, client); } else { throw new RuntimeException(ErrorCode.convert("01-02000")); } }, field -> !Modifier.isStatic(field.getModifiers()) && field.isAnnotationPresent(SofaClientFactory.class)); return bean;
138
225
363
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/spring/ReferenceAnnotationBeanPostProcessor.java
ReferenceAnnotationBeanPostProcessor
processSofaReference
class ReferenceAnnotationBeanPostProcessor implements BeanPostProcessor, ApplicationContextAware, PriorityOrdered { private static final Logger LOGGER = SofaBootLoggerFactory .getLogger(ReferenceAnnotationBeanPostProcessor.class); private final SofaRuntimeContext sofaRuntimeContext; private final BindingAdapterFactory bindingAdapterFactory; private final BindingConverterFactory bindingConverterFactory; private ApplicationContext applicationContext; private AnnotationWrapper<SofaReference> annotationWrapper; /** * To construct a ReferenceAnnotationBeanPostProcessor via a Spring Bean * sofaRuntimeContext and sofaRuntimeProperties will be obtained from applicationContext. */ public ReferenceAnnotationBeanPostProcessor(SofaRuntimeContext sofaRuntimeContext, BindingAdapterFactory bindingAdapterFactory, BindingConverterFactory bindingConverterFactory) { this.sofaRuntimeContext = sofaRuntimeContext; this.bindingAdapterFactory = bindingAdapterFactory; this.bindingConverterFactory = bindingConverterFactory; } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { processSofaReference(bean, beanName); return bean; } private void processSofaReference(final Object bean, String beanName) {<FILL_FUNCTION_BODY>} private Object createReferenceProxy(SofaReference sofaReferenceAnnotation, Class<?> interfaceType, Class beanClass, String fieldName, String beanName) { Reference reference = new ReferenceImpl(sofaReferenceAnnotation.uniqueId(), interfaceType, InterfaceMode.annotation, sofaReferenceAnnotation.jvmFirst()); reference.setRequired(sofaReferenceAnnotation.required()); BindingConverter bindingConverter = bindingConverterFactory .getBindingConverter(new BindingType(sofaReferenceAnnotation.binding().bindingType())); if (bindingConverter == null) { throw new ServiceRuntimeException(ErrorCode.convert("01-00200", sofaReferenceAnnotation .binding().bindingType())); } BindingConverterContext bindingConverterContext = new BindingConverterContext(); bindingConverterContext.setInBinding(true); bindingConverterContext.setApplicationContext(applicationContext); bindingConverterContext.setAppName(sofaRuntimeContext.getAppName()); bindingConverterContext.setAppClassLoader(sofaRuntimeContext.getAppClassLoader()); Binding binding = bindingConverter.convert(sofaReferenceAnnotation, sofaReferenceAnnotation.binding(), bindingConverterContext); reference.addBinding(binding); ComponentDefinitionInfo definitionInfo = new ComponentDefinitionInfo(); definitionInfo.setInterfaceMode(InterfaceMode.annotation); definitionInfo.putInfo(ComponentDefinitionInfo.LOCATION, fieldName); definitionInfo.putInfo(ComponentDefinitionInfo.BEAN_ID, beanName); definitionInfo.putInfo(ComponentDefinitionInfo.BEAN_CLASS_NAME, beanClass.getCanonicalName()); return ReferenceRegisterHelper.registerReference(reference, bindingAdapterFactory, sofaRuntimeContext, applicationContext, definitionInfo); } @Override public int getOrder() { return PriorityOrdered.HIGHEST_PRECEDENCE; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; this.annotationWrapper = AnnotationWrapper.create(SofaReference.class) .withEnvironment(applicationContext.getEnvironment()) .withBinder(DefaultPlaceHolderBinder.INSTANCE); } }
final Class<?> beanClass = bean.getClass(); ReflectionUtils.doWithFields(beanClass, field -> { SofaReference sofaReferenceAnnotation = field.getAnnotation(SofaReference.class); if (sofaReferenceAnnotation == null) { return; } sofaReferenceAnnotation = annotationWrapper.wrap(sofaReferenceAnnotation); Class<?> interfaceType = sofaReferenceAnnotation.interfaceType(); if (interfaceType.equals(void.class)) { interfaceType = field.getType(); } Object proxy = createReferenceProxy(sofaReferenceAnnotation, interfaceType, beanClass, field.getName(), beanName); ReflectionUtils.makeAccessible(field); ReflectionUtils.setField(field, bean, proxy); }, field -> { if (!field.isAnnotationPresent(SofaReference.class)) { return false; } if (Modifier.isStatic(field.getModifiers())) { LOGGER.warn( "SofaReference annotation is not supported on static fields: {}", field); return false; } return true; }); ReflectionUtils.doWithMethods(beanClass, method -> { Class<?>[] parameterTypes = method.getParameterTypes(); Assert.isTrue(parameterTypes.length == 1, "method should have one and only one parameter."); SofaReference sofaReferenceAnnotation = method.getAnnotation(SofaReference.class); if (sofaReferenceAnnotation == null) { return; } sofaReferenceAnnotation = annotationWrapper.wrap(sofaReferenceAnnotation); Class<?> interfaceType = sofaReferenceAnnotation.interfaceType(); if (interfaceType.equals(void.class)) { interfaceType = parameterTypes[0]; } Object proxy = createReferenceProxy(sofaReferenceAnnotation, interfaceType, beanClass, method.getName(), beanName); ReflectionUtils.invokeMethod(method, bean, proxy); }, method -> method.isAnnotationPresent(SofaReference.class));
863
514
1,377
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/spring/RuntimeContextBeanFactoryPostProcessor.java
RuntimeContextBeanFactoryPostProcessor
postProcessBeanFactory
class RuntimeContextBeanFactoryPostProcessor implements BeanFactoryPostProcessor, ApplicationContextAware, InitializingBean, Ordered { protected BindingAdapterFactory bindingAdapterFactory; protected BindingConverterFactory bindingConverterFactory; protected SofaRuntimeManager sofaRuntimeManager; protected ApplicationContext applicationContext; protected SofaRuntimeAwareProcessor sofaRuntimeAwareProcessor; protected ClientFactoryAnnotationBeanPostProcessor clientFactoryAnnotationBeanPostProcessor; @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {<FILL_FUNCTION_BODY>} @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; this.bindingAdapterFactory = applicationContext.getBean("bindingAdapterFactory", BindingAdapterFactory.class); this.bindingConverterFactory = applicationContext.getBean("bindingConverterFactory", BindingConverterFactory.class); this.sofaRuntimeManager = applicationContext.getBean("sofaRuntimeManager", SofaRuntimeManager.class); } @Override public int getOrder() { return HIGHEST_PRECEDENCE; } @Override public void afterPropertiesSet() throws Exception { this.sofaRuntimeAwareProcessor = new SofaRuntimeAwareProcessor(sofaRuntimeManager); this.clientFactoryAnnotationBeanPostProcessor = new ClientFactoryAnnotationBeanPostProcessor( sofaRuntimeManager.getClientFactoryInternal()); } }
// make sure those BeanPostProcessor work on other BeanPostProcessor beanFactory.addBeanPostProcessor(sofaRuntimeAwareProcessor); beanFactory.addBeanPostProcessor(clientFactoryAnnotationBeanPostProcessor); // none singleton bean ReferenceAnnotationBeanPostProcessor referenceAnnotationBeanPostProcessor = new ReferenceAnnotationBeanPostProcessor( sofaRuntimeManager.getSofaRuntimeContext(), bindingAdapterFactory, bindingConverterFactory); referenceAnnotationBeanPostProcessor.setApplicationContext(applicationContext); beanFactory.addBeanPostProcessor(referenceAnnotationBeanPostProcessor);
386
136
522
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/spring/SofaRuntimeAwareProcessor.java
SofaRuntimeAwareProcessor
postProcessBeforeInitialization
class SofaRuntimeAwareProcessor implements BeanPostProcessor, PriorityOrdered { private final SofaRuntimeManager sofaRuntimeManager; private final SofaRuntimeContext sofaRuntimeContext; private final ClientFactoryInternal clientFactory; private final ExtensionClientImpl extensionClient; public SofaRuntimeAwareProcessor(SofaRuntimeManager sofaRuntimeManager) { this.sofaRuntimeManager = sofaRuntimeManager; this.sofaRuntimeContext = sofaRuntimeManager.getSofaRuntimeContext(); this.clientFactory = sofaRuntimeManager.getClientFactoryInternal(); this.extensionClient = new ExtensionClientImpl(sofaRuntimeContext); } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {<FILL_FUNCTION_BODY>} @Override public int getOrder() { return PriorityOrdered.HIGHEST_PRECEDENCE; } }
if (bean instanceof SofaRuntimeContextAware) { ((SofaRuntimeContextAware) bean).setSofaRuntimeContext(sofaRuntimeContext); } if (bean instanceof ClientFactoryAware) { ((ClientFactoryAware) bean).setClientFactory(clientFactory); } if (bean instanceof ExtensionClientAware) { ((ExtensionClientAware) bean).setExtensionClient(extensionClient); } if (bean instanceof JvmFilter) { sofaRuntimeContext.getJvmFilterHolder().addJvmFilter((JvmFilter) bean); } if (bean instanceof RuntimeShutdownAware) { sofaRuntimeManager.registerShutdownAware((RuntimeShutdownAware) bean); } return bean;
242
189
431
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/spring/bean/SofaBeanNameGenerator.java
SofaBeanNameGenerator
generateSofaServiceBeanName
class SofaBeanNameGenerator { private static final String SERVICE_BEAN_NAME_PREFIX = "ServiceFactoryBean#"; private static final String REFERENCE_BEAN_NAME_PREFIX = "ReferenceFactoryBean#"; public static String generateSofaServiceBeanName(BeanDefinition definition) {<FILL_FUNCTION_BODY>} public static String generateSofaServiceBeanName(Class<?> interfaceType, String uniqueId) { return generateSofaServiceBeanName(interfaceType.getCanonicalName(), uniqueId); } public static String generateSofaServiceBeanName(String interfaceName, String uniqueId, String beanId) { return generateSofaServiceBeanName(interfaceName, uniqueId) + ":" + beanId; } public static String generateSofaServiceBeanName(Class<?> interfaceType, String uniqueId, String beanId) { return generateSofaServiceBeanName(interfaceType, uniqueId) + ":" + beanId; } public static String generateSofaServiceBeanName(String interfaceName, String uniqueId) { if (!StringUtils.hasText(uniqueId)) { return SERVICE_BEAN_NAME_PREFIX + interfaceName; } return SERVICE_BEAN_NAME_PREFIX + interfaceName + ":" + uniqueId; } public static String generateSofaReferenceBeanName(Class<?> interfaceType, String uniqueId) { if (!StringUtils.hasText(uniqueId)) { return REFERENCE_BEAN_NAME_PREFIX + interfaceType.getCanonicalName(); } return REFERENCE_BEAN_NAME_PREFIX + interfaceType.getCanonicalName() + ":" + uniqueId; } }
String interfaceName = (String) definition.getPropertyValues().get( AbstractContractDefinitionParser.INTERFACE_PROPERTY); Class<?> clazz = (Class<?>) definition.getPropertyValues().get( AbstractContractDefinitionParser.INTERFACE_CLASS_PROPERTY); if (clazz != null) { interfaceName = clazz.getCanonicalName(); } String uniqueId = (String) definition.getPropertyValues().get( AbstractContractDefinitionParser.UNIQUE_ID_PROPERTY); return generateSofaServiceBeanName(interfaceName, uniqueId, (String) definition .getPropertyValues().get(BEAN_ID));
441
171
612
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/spring/bean/SofaParameterNameDiscoverer.java
SofaParameterNameDiscoverer
getParameterNames
class SofaParameterNameDiscoverer implements ParameterNameDiscoverer { private final ParameterNameDiscoverer parameterNameDiscoverer; private final AnnotationWrapper<SofaReference> referenceAnnotationWrapper; public SofaParameterNameDiscoverer(ParameterNameDiscoverer parameterNameDiscoverer, AnnotationWrapper<SofaReference> referenceAnnotationWrapper) { this.parameterNameDiscoverer = parameterNameDiscoverer; this.referenceAnnotationWrapper = referenceAnnotationWrapper; } @Override public String[] getParameterNames(Method method) { String[] parameterNames = parameterNameDiscoverer.getParameterNames(method); Class<?>[] parameterTypes = method.getParameterTypes(); Annotation[][] annotations = method.getParameterAnnotations(); return transformParameterNames(parameterNames, parameterTypes, annotations); } @Override public String[] getParameterNames(Constructor<?> ctor) {<FILL_FUNCTION_BODY>} @SuppressWarnings("unchecked") protected String[] transformParameterNames(String[] parameterNames, Class<?>[] parameterType, Annotation[][] annotations) { if (parameterNames == null) { return null; } for (int i = 0; i < annotations.length; ++i) { for (Annotation annotation : annotations[i]) { if (annotation instanceof SofaReference) { SofaReference delegate = referenceAnnotationWrapper .wrap((SofaReference) annotation); Class<?> interfaceType = delegate.interfaceType(); if (interfaceType.equals(void.class)) { interfaceType = parameterType[i]; } String uniqueId = delegate.uniqueId(); parameterNames[i] = SofaBeanNameGenerator.generateSofaReferenceBeanName( interfaceType, uniqueId); } } } return parameterNames; } }
String[] parameterNames = parameterNameDiscoverer.getParameterNames(ctor); Class<?>[] parameterTypes = ctor.getParameterTypes(); Annotation[][] annotations = ctor.getParameterAnnotations(); return transformParameterNames(parameterNames, parameterTypes, annotations);
482
72
554
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/spring/factory/AbstractContractFactoryBean.java
AbstractContractFactoryBean
afterPropertiesSet
class AbstractContractFactoryBean implements InitializingBean, FactoryBean, ApplicationContextAware { /** bean id */ protected String beanId; /** unique id */ protected String uniqueId; /** interface class name */ protected String interfaceType; /** interface class type */ protected Class<?> interfaceClass; /** sofa runtime context */ protected SofaRuntimeContext sofaRuntimeContext; /** xml elements */ protected List<TypedStringValue> elements; /** spring context */ protected ApplicationContext applicationContext; /** bindings */ protected List<Binding> bindings = new ArrayList<>(2); /** document encoding */ protected String documentEncoding; /** repeat times */ protected String repeatReferLimit; /** binding converter factory */ protected BindingConverterFactory bindingConverterFactory; /** binding adapter factory */ protected BindingAdapterFactory bindingAdapterFactory; /** way to create factory bean. api or xml*/ protected boolean apiType; @Override public void afterPropertiesSet() throws Exception {<FILL_FUNCTION_BODY>} protected List<Binding> parseBindings(List<Element> parseElements, ApplicationContext appContext, boolean isInBinding) { List<Binding> result = new ArrayList<>(); if (parseElements != null) { for (Element element : parseElements) { String tagName = element.getLocalName(); BindingConverter bindingConverter = bindingConverterFactory .getBindingConverterByTagName(tagName); if (bindingConverter == null) { dealWithbindingConverterNotExist(tagName); continue; } BindingConverterContext bindingConverterContext = new BindingConverterContext(); bindingConverterContext.setInBinding(isInBinding); bindingConverterContext.setApplicationContext(appContext); bindingConverterContext.setAppName(sofaRuntimeContext.getAppName()); bindingConverterContext.setAppClassLoader(sofaRuntimeContext.getAppClassLoader()); bindingConverterContext.setRepeatReferLimit(repeatReferLimit); bindingConverterContext.setBeanId(beanId); setProperties(bindingConverterContext); Binding binding = bindingConverter.convert(element, bindingConverterContext); result.add(binding); } } return result; } protected void dealWithbindingConverterNotExist(String tagName) { throw new ServiceRuntimeException(ErrorCode.convert("01-00200", tagName)); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } public Class<?> getInterfaceClass() { if (interfaceClass == null) { try { interfaceClass = Thread.currentThread().getContextClassLoader() .loadClass(interfaceType); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (NullPointerException e) { // No type found for shortcut FactoryBean instance: // fall back to full creation of the FactoryBean instance return null; } } return interfaceClass; } public void setInterfaceClass(Class interfaceType) { this.interfaceClass = interfaceType; } public List<Binding> getBindings() { return bindings; } public void setBindings(List<Binding> bindings) { this.bindings = bindings; } public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } public String getUniqueId() { return uniqueId; } public void setInterfaceType(String interfaceType) { this.interfaceType = interfaceType; } public String getInterfaceType() { return this.interfaceType; } public void setElements(List<TypedStringValue> elements) { this.elements = elements; } public void setDocumentEncoding(String documentEncoding) { this.documentEncoding = documentEncoding; } public void setRepeatReferLimit(String repeatReferLimit) { this.repeatReferLimit = repeatReferLimit; } public String getBeanId() { return beanId; } public void setBeanId(String beanId) { this.beanId = beanId; } @Override public boolean isSingleton() { return true; } public boolean isApiType() { return apiType; } public void setApiType(boolean apiType) { this.apiType = apiType; } public void setSofaRuntimeContext(SofaRuntimeContext sofaRuntimeContext) { this.sofaRuntimeContext = sofaRuntimeContext; } public void setBindingConverterFactory(BindingConverterFactory bindingConverterFactory) { this.bindingConverterFactory = bindingConverterFactory; } public void setBindingAdapterFactory(BindingAdapterFactory bindingAdapterFactory) { this.bindingAdapterFactory = bindingAdapterFactory; } /** * Is in binding or not. * * @return true or false */ protected abstract boolean isInBinding(); /** * Set properties to bindingConverterContext. * * @param bindingConverterContext bindingConverterContext */ protected abstract void setProperties(BindingConverterContext bindingConverterContext); }
List<Element> tempElements = new ArrayList<>(); if (elements != null) { for (TypedStringValue element : elements) { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory .newInstance(); documentBuilderFactory.setNamespaceAware(true); InputSource inputSource; if (documentEncoding != null) { inputSource = new InputSource(new ByteArrayInputStream(element.getValue() .getBytes(documentEncoding))); } else { inputSource = new InputSource(new ByteArrayInputStream(element.getValue() .getBytes())); } inputSource.setEncoding(documentEncoding); Element node = documentBuilderFactory.newDocumentBuilder().parse(inputSource) .getDocumentElement(); tempElements.add(node); } } if (!apiType) { this.bindings = parseBindings(tempElements, applicationContext, isInBinding()); }
1,356
230
1,586
<no_super_class>
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/spring/factory/ReferenceFactoryBean.java
ReferenceFactoryBean
afterPropertiesSet
class ReferenceFactoryBean extends AbstractContractFactoryBean { protected Object proxy; /** * jvm first or not */ protected boolean jvmFirst = true; /** * load balance **/ protected String loadBalance; protected boolean required = true; public ReferenceFactoryBean() { } public ReferenceFactoryBean(String interfaceType) { this.interfaceType = interfaceType; } @Override public void afterPropertiesSet() throws Exception {<FILL_FUNCTION_BODY>} @Override protected void setProperties(BindingConverterContext bindingConverterContext) { bindingConverterContext.setLoadBalance(loadBalance); } protected Reference buildReference() { Reference reference = new ReferenceImpl(uniqueId, getInterfaceClass(), InterfaceMode.spring, jvmFirst); reference.setRequired(required); return reference; } @Override public Object getObject() throws Exception { return proxy; } @Override public Class<?> getObjectType() { try { Class<?> type = getInterfaceClass(); return type != null ? type : ReferenceFactoryBean.class; } catch (Throwable t) { // Class not found return ReferenceFactoryBean.class; } } @Override protected boolean isInBinding() { return true; } public void setJvmFirst(boolean jvmFirst) { this.jvmFirst = jvmFirst; } public String getLoadBalance() { return loadBalance; } public void setLoadBalance(String loadBalance) { this.loadBalance = loadBalance; } public void setRequired(boolean required) { this.required = required; } public boolean getRequired() { return required; } }
super.afterPropertiesSet(); Reference reference = buildReference(); Assert .isTrue(bindings.size() <= 1, "Found more than one binding in <sofa:reference/>, <sofa:reference/> can only have one binding."); // default add jvm binding and reference jvm binding should set serialize as false if (bindings.size() == 0) { // default reference prefer to ignore serialize JvmBindingParam jvmBindingParam = new JvmBindingParam(); jvmBindingParam.setSerialize(false); bindings.add(new JvmBinding().setJvmBindingParam(jvmBindingParam)); } reference.addBinding(bindings.get(0)); ComponentDefinitionInfo definitionInfo = new ComponentDefinitionInfo(); definitionInfo.setInterfaceMode(apiType ? InterfaceMode.api : InterfaceMode.spring); definitionInfo.putInfo(BEAN_ID, beanId); proxy = ReferenceRegisterHelper.registerReference(reference, bindingAdapterFactory, sofaRuntimeContext, applicationContext, definitionInfo);
480
260
740
<methods>public non-sealed void <init>() ,public void afterPropertiesSet() throws java.lang.Exception,public java.lang.String getBeanId() ,public List<com.alipay.sofa.runtime.spi.binding.Binding> getBindings() ,public Class<?> getInterfaceClass() ,public java.lang.String getInterfaceType() ,public java.lang.String getUniqueId() ,public boolean isApiType() ,public boolean isSingleton() ,public void setApiType(boolean) ,public void setApplicationContext(org.springframework.context.ApplicationContext) throws org.springframework.beans.BeansException,public void setBeanId(java.lang.String) ,public void setBindingAdapterFactory(com.alipay.sofa.runtime.spi.binding.BindingAdapterFactory) ,public void setBindingConverterFactory(com.alipay.sofa.runtime.spi.service.BindingConverterFactory) ,public void setBindings(List<com.alipay.sofa.runtime.spi.binding.Binding>) ,public void setDocumentEncoding(java.lang.String) ,public void setElements(List<org.springframework.beans.factory.config.TypedStringValue>) ,public void setInterfaceClass(Class#RAW) ,public void setInterfaceType(java.lang.String) ,public void setRepeatReferLimit(java.lang.String) ,public void setSofaRuntimeContext(com.alipay.sofa.runtime.spi.component.SofaRuntimeContext) ,public void setUniqueId(java.lang.String) <variables>protected boolean apiType,protected org.springframework.context.ApplicationContext applicationContext,protected java.lang.String beanId,protected com.alipay.sofa.runtime.spi.binding.BindingAdapterFactory bindingAdapterFactory,protected com.alipay.sofa.runtime.spi.service.BindingConverterFactory bindingConverterFactory,protected List<com.alipay.sofa.runtime.spi.binding.Binding> bindings,protected java.lang.String documentEncoding,protected List<org.springframework.beans.factory.config.TypedStringValue> elements,protected Class<?> interfaceClass,protected java.lang.String interfaceType,protected java.lang.String repeatReferLimit,protected com.alipay.sofa.runtime.spi.component.SofaRuntimeContext sofaRuntimeContext,protected java.lang.String uniqueId
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/spring/factory/ServiceFactoryBean.java
ServiceFactoryBean
hasSofaServiceAnnotation
class ServiceFactoryBean extends AbstractContractFactoryBean { protected Object ref; protected Service service; public ServiceFactoryBean() { } public ServiceFactoryBean(String interfaceType) { this.interfaceType = interfaceType; } @Override public void afterPropertiesSet() throws Exception { super.afterPropertiesSet(); if (!apiType && hasSofaServiceAnnotation()) { throw new ServiceRuntimeException(ErrorCode.convert("01-00103", beanId, ref.getClass())); } Implementation implementation = new DefaultImplementation(); implementation.setTarget(ref); service = buildService(); // default add jvm binding and service jvm binding should set serialize as true if (bindings.size() == 0) { JvmBindingParam jvmBindingParam = new JvmBindingParam().setSerialize(true); bindings.add(new JvmBinding().setJvmBindingParam(jvmBindingParam)); } for (Binding binding : bindings) { service.addBinding(binding); } ComponentInfo componentInfo = new ServiceComponent(implementation, service, bindingAdapterFactory, sofaRuntimeContext); componentInfo.setApplicationContext(applicationContext); ComponentDefinitionInfo definitionInfo = new ComponentDefinitionInfo(); definitionInfo.setInterfaceMode(apiType ? InterfaceMode.api : InterfaceMode.spring); definitionInfo.putInfo(BEAN_ID, beanId); Property property = new Property(); property.setName(SOURCE); property.setValue(definitionInfo); componentInfo.getProperties().put(SOURCE, property); sofaRuntimeContext.getComponentManager().register(componentInfo); } private boolean hasSofaServiceAnnotation() {<FILL_FUNCTION_BODY>} @Override protected void setProperties(BindingConverterContext bindingConverterContext) { bindingConverterContext.setBeanId(beanId); } protected Service buildService() { return new ServiceImpl(uniqueId, getInterfaceClass(), InterfaceMode.spring, ref); } @Override public Object getObject() throws Exception { return service; } @Override public Class<?> getObjectType() { return service != null ? service.getClass() : Service.class; } @Override protected boolean isInBinding() { return false; } public void setRef(Object ref) { this.ref = ref; } }
Class<?> implementationClazz = ref.getClass(); SofaService sofaService = implementationClazz.getAnnotation(SofaService.class); if (sofaService == null) { return false; } String annotationUniqueId = sofaService.uniqueId(); if ((uniqueId == null || uniqueId.isEmpty()) && (annotationUniqueId == null || annotationUniqueId.isEmpty())) { return true; } return annotationUniqueId.equals(uniqueId);
623
129
752
<methods>public non-sealed void <init>() ,public void afterPropertiesSet() throws java.lang.Exception,public java.lang.String getBeanId() ,public List<com.alipay.sofa.runtime.spi.binding.Binding> getBindings() ,public Class<?> getInterfaceClass() ,public java.lang.String getInterfaceType() ,public java.lang.String getUniqueId() ,public boolean isApiType() ,public boolean isSingleton() ,public void setApiType(boolean) ,public void setApplicationContext(org.springframework.context.ApplicationContext) throws org.springframework.beans.BeansException,public void setBeanId(java.lang.String) ,public void setBindingAdapterFactory(com.alipay.sofa.runtime.spi.binding.BindingAdapterFactory) ,public void setBindingConverterFactory(com.alipay.sofa.runtime.spi.service.BindingConverterFactory) ,public void setBindings(List<com.alipay.sofa.runtime.spi.binding.Binding>) ,public void setDocumentEncoding(java.lang.String) ,public void setElements(List<org.springframework.beans.factory.config.TypedStringValue>) ,public void setInterfaceClass(Class#RAW) ,public void setInterfaceType(java.lang.String) ,public void setRepeatReferLimit(java.lang.String) ,public void setSofaRuntimeContext(com.alipay.sofa.runtime.spi.component.SofaRuntimeContext) ,public void setUniqueId(java.lang.String) <variables>protected boolean apiType,protected org.springframework.context.ApplicationContext applicationContext,protected java.lang.String beanId,protected com.alipay.sofa.runtime.spi.binding.BindingAdapterFactory bindingAdapterFactory,protected com.alipay.sofa.runtime.spi.service.BindingConverterFactory bindingConverterFactory,protected List<com.alipay.sofa.runtime.spi.binding.Binding> bindings,protected java.lang.String documentEncoding,protected List<org.springframework.beans.factory.config.TypedStringValue> elements,protected Class<?> interfaceClass,protected java.lang.String interfaceType,protected java.lang.String repeatReferLimit,protected com.alipay.sofa.runtime.spi.component.SofaRuntimeContext sofaRuntimeContext,protected java.lang.String uniqueId
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/spring/parser/AbstractContractDefinitionParser.java
AbstractContractDefinitionParser
doParse
class AbstractContractDefinitionParser extends AbstractSingleBeanDefinitionParser implements SofaBootTagNameSupport { public static final String INTERFACE_ELEMENT = "interface"; public static final String INTERFACE_PROPERTY = "interfaceType"; public static final String INTERFACE_CLASS_PROPERTY = "interfaceClass"; public static final String BEAN_ID_ELEMENT = "id"; public static final String BEAN_ID_PROPERTY = "beanId"; public static final String UNIQUE_ID_ELEMENT = "unique-id"; public static final String UNIQUE_ID_PROPERTY = "uniqueId"; public static final String ELEMENTS = "elements"; public static final String BINDINGS = "bindings"; public static final String REPEAT_REFER_LIMIT_ELEMENT = "repeatReferLimit"; public static final String REPEAT_REFER_LIMIT_PROPERTY = "repeatReferLimit"; public static final String DEFINITION_BUILDING_API_TYPE = "apiType"; public static final String SOFA_RUNTIME_CONTEXT = "sofaRuntimeContext"; public static final String BINDING_CONVERTER_FACTORY = "bindingConverterFactory"; public static final String BINDING_ADAPTER_FACTORY = "bindingAdapterFactory"; @Override protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {<FILL_FUNCTION_BODY>} /** * Actually parse internal element. * * @param element element * @param parserContext parserContext * @param builder builder */ protected abstract void doParseInternal(Element element, ParserContext parserContext, BeanDefinitionBuilder builder); }
builder.addAutowiredProperty(SOFA_RUNTIME_CONTEXT); builder.addAutowiredProperty(BINDING_CONVERTER_FACTORY); builder.addAutowiredProperty(BINDING_ADAPTER_FACTORY); String id = element.getAttribute(BEAN_ID_ELEMENT); builder.addPropertyValue(BEAN_ID_PROPERTY, id); String interfaceType = element.getAttribute(INTERFACE_ELEMENT); builder.addPropertyValue(INTERFACE_PROPERTY, interfaceType); builder.getBeanDefinition().getConstructorArgumentValues() .addIndexedArgumentValue(0, interfaceType); String uniqueId = element.getAttribute(UNIQUE_ID_ELEMENT); builder.addPropertyValue(UNIQUE_ID_PROPERTY, uniqueId); String repeatReferLimit = element.getAttribute(REPEAT_REFER_LIMIT_ELEMENT); builder.addPropertyValue(REPEAT_REFER_LIMIT_PROPERTY, repeatReferLimit); List<Element> childElements = DomUtils.getChildElements(element); List<TypedStringValue> elementAsTypedStringValueList = new ArrayList<>(); for (Element childElement : childElements) { try { TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); StringWriter buffer = new StringWriter(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.transform(new DOMSource(childElement), new StreamResult(buffer)); String str = buffer.toString(); elementAsTypedStringValueList.add(new TypedStringValue(str, Element.class)); } catch (Throwable e) { throw new ServiceRuntimeException(e); } } builder.addPropertyValue("documentEncoding", element.getOwnerDocument().getXmlEncoding()); builder.addPropertyValue(ELEMENTS, elementAsTypedStringValueList); doParseInternal(element, parserContext, builder);
464
518
982
<methods>public void <init>() <variables>