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/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/spring/parser/AsyncInitBeanDefinitionDecorator.java
|
AsyncInitBeanDefinitionDecorator
|
decorate
|
class AsyncInitBeanDefinitionDecorator implements BeanDefinitionDecorator,
SofaBootTagNameSupport {
@Override
public BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder definition,
ParserContext parserContext) {<FILL_FUNCTION_BODY>}
@Override
public String supportTagName() {
return "async-init";
}
}
|
if (!Boolean.TRUE.toString().equalsIgnoreCase(((Attr) node).getValue())) {
return definition;
}
String initMethodName = definition.getBeanDefinition().getInitMethodName();
if (StringUtils.hasText(initMethodName)) {
definition.getBeanDefinition().setAttribute(ASYNC_INIT_METHOD_NAME, initMethodName);
}
return definition;
| 99
| 101
| 200
|
<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/parser/ReferenceDefinitionParser.java
|
ReferenceDefinitionParser
|
doParseInternal
|
class ReferenceDefinitionParser extends AbstractContractDefinitionParser {
public static final String JVM_FIRST = "jvm-first";
public static final String PROPERTY_JVM_FIRST = "jvmFirst";
public static final String PROPERTY_LOAD_BALANCE = "loadBalance";
public static final String REQUIRED = "required";
@Override
protected void doParseInternal(Element element, ParserContext parserContext,
BeanDefinitionBuilder builder) {<FILL_FUNCTION_BODY>}
@Override
protected Class getBeanClass(Element element) {
return ReferenceFactoryBean.class;
}
@Override
public String supportTagName() {
return "reference";
}
protected Class getInterfaceClass(String interfaceType) {
try {
return Thread.currentThread().getContextClassLoader().loadClass(interfaceType);
} catch (Throwable t) {
throw new IllegalArgumentException("Failed to load class for interface: "
+ interfaceType, t);
}
}
}
|
String jvmFirstString = element.getAttribute(JVM_FIRST);
if (StringUtils.hasText(jvmFirstString)) {
if ("true".equalsIgnoreCase(jvmFirstString)) {
builder.addPropertyValue(PROPERTY_JVM_FIRST, true);
} else if ("false".equalsIgnoreCase(jvmFirstString)) {
builder.addPropertyValue(PROPERTY_JVM_FIRST, false);
} else {
throw new RuntimeException(
"Invalid value of property jvm-first, can only be true or false.");
}
}
String loadBalance = element.getAttribute(PROPERTY_LOAD_BALANCE);
if (StringUtils.hasText(loadBalance)) {
builder.addPropertyValue(PROPERTY_LOAD_BALANCE, loadBalance);
}
String required = element.getAttribute(REQUIRED);
if (StringUtils.hasText(required)) {
if ("true".equalsIgnoreCase(required)) {
builder.addPropertyValue(REQUIRED, true);
} else if ("false".equalsIgnoreCase(required)) {
builder.addPropertyValue(REQUIRED, false);
} else {
throw new RuntimeException(
"Invalid value of property required, can only be true or false.");
}
}
String interfaceType = element.getAttribute(INTERFACE_ELEMENT);
builder.getBeanDefinition().setAttribute(FactoryBean.OBJECT_TYPE_ATTRIBUTE,
getInterfaceClass(interfaceType));
| 261
| 382
| 643
|
<methods>public non-sealed void <init>() <variables>public static final java.lang.String BEAN_ID_ELEMENT,public static final java.lang.String BEAN_ID_PROPERTY,public static final java.lang.String BINDINGS,public static final java.lang.String BINDING_ADAPTER_FACTORY,public static final java.lang.String BINDING_CONVERTER_FACTORY,public static final java.lang.String DEFINITION_BUILDING_API_TYPE,public static final java.lang.String ELEMENTS,public static final java.lang.String INTERFACE_CLASS_PROPERTY,public static final java.lang.String INTERFACE_ELEMENT,public static final java.lang.String INTERFACE_PROPERTY,public static final java.lang.String REPEAT_REFER_LIMIT_ELEMENT,public static final java.lang.String REPEAT_REFER_LIMIT_PROPERTY,public static final java.lang.String SOFA_RUNTIME_CONTEXT,public static final java.lang.String UNIQUE_ID_ELEMENT,public static final java.lang.String UNIQUE_ID_PROPERTY
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/spring/parser/ServiceDefinitionParser.java
|
ServiceDefinitionParser
|
doParseInternal
|
class ServiceDefinitionParser extends AbstractContractDefinitionParser {
public static final String REF = "ref";
public static final String BEAN_ID = "beanId";
@Override
protected void doParseInternal(Element element, ParserContext parserContext,
BeanDefinitionBuilder builder) {<FILL_FUNCTION_BODY>}
@Override
protected Class getBeanClass(Element element) {
return ServiceFactoryBean.class;
}
@Override
protected String resolveId(Element element, AbstractBeanDefinition definition,
ParserContext parserContext) throws BeanDefinitionStoreException {
return SofaBeanNameGenerator.generateSofaServiceBeanName(definition);
}
@Override
public String supportTagName() {
return "service";
}
}
|
String ref = element.getAttribute(REF);
builder.addPropertyReference(REF, ref);
if (element.hasAttribute("id")) {
String id = element.getAttribute("id");
builder.addPropertyValue(BEAN_ID, id);
} else {
builder.addPropertyValue(BEAN_ID, ref);
}
| 194
| 89
| 283
|
<methods>public non-sealed void <init>() <variables>public static final java.lang.String BEAN_ID_ELEMENT,public static final java.lang.String BEAN_ID_PROPERTY,public static final java.lang.String BINDINGS,public static final java.lang.String BINDING_ADAPTER_FACTORY,public static final java.lang.String BINDING_CONVERTER_FACTORY,public static final java.lang.String DEFINITION_BUILDING_API_TYPE,public static final java.lang.String ELEMENTS,public static final java.lang.String INTERFACE_CLASS_PROPERTY,public static final java.lang.String INTERFACE_ELEMENT,public static final java.lang.String INTERFACE_PROPERTY,public static final java.lang.String REPEAT_REFER_LIMIT_ELEMENT,public static final java.lang.String REPEAT_REFER_LIMIT_PROPERTY,public static final java.lang.String SOFA_RUNTIME_CONTEXT,public static final java.lang.String UNIQUE_ID_ELEMENT,public static final java.lang.String UNIQUE_ID_PROPERTY
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/startup/ComponentBeanStatCustomizer.java
|
ComponentBeanStatCustomizer
|
customize
|
class ComponentBeanStatCustomizer implements BeanStatCustomizer {
@Override
public BeanStat customize(String beanName, Object bean, BeanStat bs) {<FILL_FUNCTION_BODY>}
}
|
if (bean instanceof ServiceFactoryBean) {
bs.putAttribute("interface", ((ServiceFactoryBean) bean).getInterfaceType());
bs.putAttribute("uniqueId", ((ServiceFactoryBean) bean).getUniqueId());
return null;
} else if (bean instanceof ReferenceFactoryBean) {
bs.putAttribute("interface", ((ReferenceFactoryBean) bean).getInterfaceType());
bs.putAttribute("uniqueId", ((ReferenceFactoryBean) bean).getUniqueId());
return null;
}
if (bean instanceof ExtensionFactoryBean) {
bs.putAttribute("extension", bean.toString());
return null;
}
if (bean instanceof ExtensionPointFactoryBean) {
bs.putAttribute("extension", bean.toString());
return null;
}
return bs;
| 55
| 201
| 256
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/tracer-sofa-boot/src/main/java/com/alipay/sofa/boot/tracer/datasource/DataSourceBeanPostProcessor.java
|
DataSourceBeanPostProcessor
|
postProcessAfterInitialization
|
class DataSourceBeanPostProcessor implements BeanPostProcessor, PriorityOrdered {
private String appName;
@Override
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {<FILL_FUNCTION_BODY>}
@Override
public int getOrder() {
return LOWEST_PRECEDENCE;
}
public void setAppName(String appName) {
this.appName = appName;
}
}
|
/*
* filter bean which is type of {@link SmartDataSource}
* filter bean which is not type of {@link DataSource}
*/
if (!(bean instanceof DataSource) || bean instanceof SmartDataSource) {
return bean;
}
String getUrlMethodName;
String url;
/*
* Now DataSource Tracer only support the following type: Druid, C3p0, Dbcp, tomcat datasource, hikari
*/
if (DataSourceUtils.isDruidDataSource(bean) || DataSourceUtils.isDbcpDataSource(bean)
|| DataSourceUtils.isDbcp2DataSource(bean) || DataSourceUtils.isTomcatDataSource(bean)) {
getUrlMethodName = DataSourceUtils.METHOD_GET_URL;
} else if (DataSourceUtils.isC3p0DataSource(bean)
|| DataSourceUtils.isHikariDataSource(bean)) {
getUrlMethodName = DataSourceUtils.METHOD_GET_JDBC_URL;
} else {
return bean;
}
try {
Method urlMethod = ReflectionUtils.findMethod(bean.getClass(), getUrlMethodName);
urlMethod.setAccessible(true);
url = (String) urlMethod.invoke(bean);
} catch (Throwable throwable) {
throw new BeanCreationException(String.format("Can not find method: %s in class %s.",
getUrlMethodName, bean.getClass().getCanonicalName()), throwable);
}
SmartDataSource proxiedDataSource = new SmartDataSource((DataSource) bean);
Assert.isTrue(StringUtils.hasText(appName), TRACER_APPNAME_KEY + " must be configured!");
proxiedDataSource.setAppName(appName);
proxiedDataSource.setDbType(DataSourceUtils.resolveDbTypeFromUrl(url));
proxiedDataSource.setDatabase(DataSourceUtils.resolveDatabaseFromUrl(url));
// execute proxied datasource init-method
proxiedDataSource.init();
return proxiedDataSource;
| 125
| 529
| 654
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/tracer-sofa-boot/src/main/java/com/alipay/sofa/boot/tracer/feign/FeignContextBeanPostProcessor.java
|
FeignContextBeanPostProcessor
|
postProcessBeforeInitialization
|
class FeignContextBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {<FILL_FUNCTION_BODY>}
}
|
if (bean instanceof FeignClientFactory && !(bean instanceof SofaTracerFeignClientFactory)) {
return new SofaTracerFeignClientFactory((FeignClientFactory) bean);
}
return bean;
| 58
| 58
| 116
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/tracer-sofa-boot/src/main/java/com/alipay/sofa/boot/tracer/flexible/SofaTracerIntroductionInterceptor.java
|
SofaTracerIntroductionInterceptor
|
findAnnotation
|
class SofaTracerIntroductionInterceptor implements IntroductionInterceptor {
private final MethodInvocationProcessor sofaMethodInvocationProcessor;
public SofaTracerIntroductionInterceptor(MethodInvocationProcessor sofaMethodInvocationProcessor) {
this.sofaMethodInvocationProcessor = sofaMethodInvocationProcessor;
}
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
Method method = invocation.getMethod();
Method mostSpecificMethod = AopUtils.getMostSpecificMethod(method, invocation.getThis()
.getClass());
Tracer tracerSpan = findAnnotation(mostSpecificMethod, Tracer.class);
if (tracerSpan == null) {
return invocation.proceed();
}
return sofaMethodInvocationProcessor.process(invocation, tracerSpan);
}
@Override
public boolean implementsInterface(Class<?> aClass) {
return true;
}
private <T extends Annotation> T findAnnotation(Method method, Class<T> clazz) {<FILL_FUNCTION_BODY>}
}
|
T annotation = AnnotationUtils.findAnnotation(method, clazz);
if (annotation == null) {
try {
annotation = AnnotationUtils.findAnnotation(
method.getDeclaringClass().getMethod(method.getName(),
method.getParameterTypes()), clazz);
} catch (NoSuchMethodException | SecurityException ex) {
SelfLog.warn("Exception occurred while tyring to find the annotation");
}
}
return annotation;
| 275
| 114
| 389
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/tracer-sofa-boot/src/main/java/com/alipay/sofa/boot/tracer/flexible/SofaTracerMethodInvocationProcessor.java
|
SofaTracerMethodInvocationProcessor
|
proceedProxyMethodWithTracerAnnotation
|
class SofaTracerMethodInvocationProcessor implements MethodInvocationProcessor {
private final io.opentracing.Tracer tracer;
public SofaTracerMethodInvocationProcessor(io.opentracing.Tracer tracer) {
this.tracer = tracer;
}
@Override
public Object process(MethodInvocation invocation, Tracer tracerSpan) throws Throwable {
return proceedProxyMethodWithTracerAnnotation(invocation, tracerSpan);
}
private Object proceedProxyMethodWithTracerAnnotation(MethodInvocation invocation,
Tracer tracerSpan) throws Throwable {<FILL_FUNCTION_BODY>}
}
|
if (tracer instanceof FlexibleTracer) {
try {
String operationName = tracerSpan.operateName();
if (StringUtils.isBlank(operationName)) {
operationName = invocation.getMethod().getName();
}
SofaTracerSpan sofaTracerSpan = ((FlexibleTracer) tracer)
.beforeInvoke(operationName);
sofaTracerSpan.setTag(CommonSpanTags.METHOD, invocation.getMethod().getName());
if (invocation.getArguments().length != 0) {
StringBuilder stringBuilder = new StringBuilder();
for (Object obj : invocation.getArguments()) {
stringBuilder.append(obj.getClass().getName()).append(";");
}
sofaTracerSpan.setTag("param.types",
stringBuilder.substring(0, stringBuilder.length() - 1));
}
Object result = invocation.proceed();
((FlexibleTracer) tracer).afterInvoke();
return result;
} catch (Throwable t) {
((FlexibleTracer) tracer).afterInvoke(t.getMessage());
throw t;
}
} else {
return invocation.proceed();
}
| 171
| 308
| 479
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/tracer-sofa-boot/src/main/java/com/alipay/sofa/boot/tracer/flexible/TracerAnnotationClassPointcut.java
|
AnnotationMethodsResolver
|
hasAnnotatedMethods
|
class AnnotationMethodsResolver {
private final Class<? extends Annotation> annotationType;
AnnotationMethodsResolver(Class<? extends Annotation> annotationType) {
this.annotationType = annotationType;
}
boolean hasAnnotatedMethods(Class<?> clazz) {<FILL_FUNCTION_BODY>}
}
|
final AtomicBoolean found = new AtomicBoolean(false);
ReflectionUtils.doWithMethods(clazz, (method) ->{
if (found.get()) {
return;
}
Annotation annotation = AnnotationUtils.findAnnotation(method,
AnnotationMethodsResolver.this.annotationType);
if (annotation != null) {
found.set(true);
}
});
return found.get();
| 87
| 111
| 198
|
<methods>public void <init>() ,public org.springframework.aop.ClassFilter getClassFilter() ,public final org.springframework.aop.MethodMatcher getMethodMatcher() <variables>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/tracer-sofa-boot/src/main/java/com/alipay/sofa/boot/tracer/kafka/KafkaConsumerFactoryBeanPostProcessor.java
|
KafkaConsumerFactoryBeanPostProcessor
|
postProcessAfterInitialization
|
class KafkaConsumerFactoryBeanPostProcessor implements BeanPostProcessor {
@SuppressWarnings("rawtypes")
@Override
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {<FILL_FUNCTION_BODY>}
}
|
if (bean instanceof ConsumerFactory && !(bean instanceof SofaTracerKafkaConsumerFactory)) {
return new SofaTracerKafkaConsumerFactory((ConsumerFactory) bean);
}
return bean;
| 72
| 57
| 129
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/tracer-sofa-boot/src/main/java/com/alipay/sofa/boot/tracer/kafka/KafkaProducerBeanFactoryPostProcessor.java
|
KafkaProducerBeanFactoryPostProcessor
|
postProcessAfterInitialization
|
class KafkaProducerBeanFactoryPostProcessor implements BeanPostProcessor {
@SuppressWarnings("rawtypes")
@Override
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {<FILL_FUNCTION_BODY>}
}
|
if (bean instanceof ProducerFactory && !(bean instanceof SofaTracerKafkaProducerFactory)) {
return new SofaTracerKafkaProducerFactory((ProducerFactory) bean);
}
return bean;
| 73
| 60
| 133
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/tracer-sofa-boot/src/main/java/com/alipay/sofa/boot/tracer/mongodb/SofaTracerCommandListenerCustomizer.java
|
SofaTracerCommandListenerCustomizer
|
customize
|
class SofaTracerCommandListenerCustomizer implements MongoClientSettingsBuilderCustomizer {
private String appName;
@Override
public void customize(Builder clientSettingsBuilder) {<FILL_FUNCTION_BODY>}
public void setAppName(String appName) {
this.appName = appName;
}
}
|
Assert.isTrue(StringUtils.hasText(appName), TRACER_APPNAME_KEY + " must be configured!");
SofaTracerCommandListener commandListener = new SofaTracerCommandListener(appName);
clientSettingsBuilder.addCommandListener(commandListener);
| 86
| 71
| 157
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/tracer-sofa-boot/src/main/java/com/alipay/sofa/boot/tracer/rabbitmq/RabbitMqBeanPostProcessor.java
|
RabbitMqBeanPostProcessor
|
getAdviceChainOrAddInterceptorToChain
|
class RabbitMqBeanPostProcessor implements BeanPostProcessor, PriorityOrdered {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
if (bean instanceof AbstractRabbitListenerContainerFactory factory) {
registerTracingInterceptor(factory);
} else if (bean instanceof AbstractMessageListenerContainer container) {
registerTracingInterceptor(container);
}
return bean;
}
@SuppressWarnings("rawtypes")
private void registerTracingInterceptor(AbstractRabbitListenerContainerFactory factory) {
Advice[] chain = factory.getAdviceChain();
Advice[] adviceChainWithTracing = getAdviceChainOrAddInterceptorToChain(chain);
factory.setAdviceChain(adviceChainWithTracing);
}
private void registerTracingInterceptor(AbstractMessageListenerContainer container) {
Field adviceChainField = ReflectionUtils.findField(AbstractMessageListenerContainer.class,
"adviceChain");
ReflectionUtils.makeAccessible(adviceChainField);
Advice[] chain = (Advice[]) ReflectionUtils.getField(adviceChainField, container);
Advice[] adviceChainWithTracing = getAdviceChainOrAddInterceptorToChain(chain);
container.setAdviceChain(adviceChainWithTracing);
}
private Advice[] getAdviceChainOrAddInterceptorToChain(Advice... existingAdviceChain) {<FILL_FUNCTION_BODY>}
@Override
public int getOrder() {
return LOWEST_PRECEDENCE;
}
}
|
if (existingAdviceChain == null) {
return new Advice[] { new SofaTracerConsumeInterceptor() };
}
for (Advice advice : existingAdviceChain) {
if (advice instanceof SofaTracerConsumeInterceptor) {
return existingAdviceChain;
}
}
Advice[] newChain = new Advice[existingAdviceChain.length + 1];
System.arraycopy(existingAdviceChain, 0, newChain, 0, existingAdviceChain.length);
newChain[existingAdviceChain.length] = new SofaTracerConsumeInterceptor();
return newChain;
| 408
| 173
| 581
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/tracer-sofa-boot/src/main/java/com/alipay/sofa/boot/tracer/resttemplate/RestTemplateBeanPostProcessor.java
|
RestTemplateBeanPostProcessor
|
postProcessAfterInitialization
|
class RestTemplateBeanPostProcessor implements BeanPostProcessor {
private final RestTemplateEnhance sofaTracerRestTemplateEnhance;
public RestTemplateBeanPostProcessor(RestTemplateEnhance sofaTracerRestTemplateEnhance) {
this.sofaTracerRestTemplateEnhance = sofaTracerRestTemplateEnhance;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {<FILL_FUNCTION_BODY>}
}
|
if (bean instanceof RestTemplate restTemplate) {
sofaTracerRestTemplateEnhance.enhanceRestTemplateWithSofaTracer(restTemplate);
}
return bean;
| 127
| 49
| 176
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/tracer-sofa-boot/src/main/java/com/alipay/sofa/boot/tracer/resttemplate/RestTemplateEnhance.java
|
RestTemplateEnhance
|
enhanceRestTemplateWithSofaTracer
|
class RestTemplateEnhance {
private final RestTemplateInterceptor restTemplateInterceptor;
public RestTemplateEnhance() {
AbstractTracer restTemplateTracer = SofaTracerRestTemplateBuilder.getRestTemplateTracer();
this.restTemplateInterceptor = new RestTemplateInterceptor(restTemplateTracer);
}
public void enhanceRestTemplateWithSofaTracer(RestTemplate restTemplate) {<FILL_FUNCTION_BODY>}
private boolean checkRestTemplateInterceptor(RestTemplate restTemplate) {
for (ClientHttpRequestInterceptor interceptor : restTemplate.getInterceptors()) {
if (interceptor instanceof RestTemplateInterceptor) {
return true;
}
}
return false;
}
}
|
// check interceptor
if (checkRestTemplateInterceptor(restTemplate)) {
return;
}
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(
restTemplate.getInterceptors());
interceptors.add(0, this.restTemplateInterceptor);
restTemplate.setInterceptors(interceptors);
| 195
| 93
| 288
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/tracer-sofa-boot/src/main/java/com/alipay/sofa/boot/tracer/rocketmq/RocketMqConsumerPostProcessor.java
|
RocketMqConsumerPostProcessor
|
postProcessAfterInitialization
|
class RocketMqConsumerPostProcessor implements BeanPostProcessor, PriorityOrdered {
private String appName;
@Override
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {<FILL_FUNCTION_BODY>}
@Override
public int getOrder() {
return LOWEST_PRECEDENCE;
}
public void setAppName(String appName) {
this.appName = appName;
}
}
|
if (bean instanceof DefaultRocketMQListenerContainer container) {
Assert.isTrue(StringUtils.hasText(appName), TRACER_APPNAME_KEY + " must be configured!");
SofaTracerConsumeMessageHook hook = new SofaTracerConsumeMessageHook(appName);
container.getConsumer().getDefaultMQPushConsumerImpl().registerConsumeMessageHook(hook);
return container;
}
return bean;
| 127
| 114
| 241
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/tracer-sofa-boot/src/main/java/com/alipay/sofa/boot/tracer/rocketmq/RocketMqProducerPostProcessor.java
|
RocketMqProducerPostProcessor
|
postProcessAfterInitialization
|
class RocketMqProducerPostProcessor implements BeanPostProcessor, PriorityOrdered {
private String appName;
@Override
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {<FILL_FUNCTION_BODY>}
@Override
public int getOrder() {
return LOWEST_PRECEDENCE;
}
public void setAppName(String appName) {
this.appName = appName;
}
}
|
if (bean instanceof DefaultMQProducer producer) {
Assert.isTrue(StringUtils.hasText(appName), TRACER_APPNAME_KEY + " must be configured!");
SofaTracerSendMessageHook hook = new SofaTracerSendMessageHook(appName);
producer.getDefaultMQProducerImpl().registerSendMessageHook(hook);
return producer;
}
return bean;
| 128
| 105
| 233
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/tracer-sofa-boot/src/main/java/com/alipay/sofa/boot/tracer/springmessage/SpringMessageTracerBeanPostProcessor.java
|
SpringMessageTracerBeanPostProcessor
|
postProcessBeforeInitialization
|
class SpringMessageTracerBeanPostProcessor implements BeanPostProcessor, PriorityOrdered {
private String appName;
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {<FILL_FUNCTION_BODY>}
@Override
public int getOrder() {
return LOWEST_PRECEDENCE;
}
public void setAppName(String appName) {
this.appName = appName;
}
}
|
if (bean instanceof AbstractMessageChannel) {
Assert
.isTrue(StringUtils.hasText(appName), TRACER_APPNAME_KEY + " must be configured!");
((AbstractMessageChannel) bean).addInterceptor(SofaTracerChannelInterceptor
.create(appName));
}
return bean;
| 127
| 86
| 213
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot/src/main/java/com/alipay/sofa/boot/Initializer/SwitchableApplicationContextInitializer.java
|
SwitchableApplicationContextInitializer
|
isEnable
|
class SwitchableApplicationContextInitializer
implements
ApplicationContextInitializer<ConfigurableApplicationContext> {
protected static final String CONFIG_KEY_PREFIX = "sofa.boot.switch.initializer.";
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
if (isEnable(applicationContext)) {
doInitialize(applicationContext);
}
}
/**
* @param applicationContext
*/
protected abstract void doInitialize(ConfigurableApplicationContext applicationContext);
/**
* start with :sofa.boot.switch.initializer
*
* @return switch key, must not be null.
*/
protected abstract String switchKey();
/**
* Specify if the condition should match if the property is not set. Defaults to
* {@code true}.
*
* @return if the condition should match if the property is missing
*/
protected boolean matchIfMissing() {
return true;
}
protected boolean isEnable(ConfigurableApplicationContext applicationContext) {<FILL_FUNCTION_BODY>}
}
|
String switchKey = switchKey();
Assert.hasText(switchKey, "switch key must has text.");
String realKey = CONFIG_KEY_PREFIX + switchKey + ".enabled";
String switchStr = applicationContext.getEnvironment().getProperty(realKey);
if (StringUtils.hasText(switchStr)) {
return Boolean.parseBoolean(switchStr);
} else {
return matchIfMissing();
}
| 273
| 107
| 380
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot/src/main/java/com/alipay/sofa/boot/annotation/AnnotationWrapper.java
|
AnnotationWrapper
|
build
|
class AnnotationWrapper<A extends Annotation> {
private final Class<A> clazz;
private Annotation delegate;
private PlaceHolderBinder binder;
private Environment environment;
private AnnotationWrapper(Class<A> clazz) {
this.clazz = clazz;
}
public static <A extends Annotation> AnnotationWrapper<A> create(Class<A> clazz) {
return new AnnotationWrapper<>(clazz);
}
public static <A extends Annotation> AnnotationWrapper<A> create(Annotation annotation) {
return new AnnotationWrapper(annotation.getClass());
}
public AnnotationWrapper<A> withBinder(PlaceHolderBinder binder) {
this.binder = binder;
return this;
}
public AnnotationWrapper<A> withEnvironment(Environment environment) {
this.environment = environment;
return this;
}
public A wrap(A annotation) {
Assert.notNull(annotation, "annotation must not be null.");
Assert.isInstanceOf(clazz, annotation, "parameter must be annotation type.");
this.delegate = annotation;
return build();
}
@SuppressWarnings("unchecked")
private A build() {<FILL_FUNCTION_BODY>}
}
|
ClassLoader cl = this.getClass().getClassLoader();
Class<?>[] exposedInterface = { delegate.annotationType(), WrapperAnnotation.class };
return (A) Proxy.newProxyInstance(cl, exposedInterface,
new PlaceHolderAnnotationInvocationHandler(delegate, binder, environment));
| 335
| 78
| 413
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot/src/main/java/com/alipay/sofa/boot/annotation/PlaceHolderAnnotationInvocationHandler.java
|
PlaceHolderAnnotationInvocationHandler
|
invoke
|
class PlaceHolderAnnotationInvocationHandler implements InvocationHandler {
private final Annotation delegate;
private final PlaceHolderBinder binder;
private final Environment environment;
public PlaceHolderAnnotationInvocationHandler(Annotation delegate, PlaceHolderBinder binder,
Environment environment) {
this.delegate = delegate;
this.binder = binder;
this.environment = environment;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {<FILL_FUNCTION_BODY>}
private boolean isAttributeMethod(Method method) {
return method != null && method.getParameterTypes().length == 0
&& method.getReturnType() != void.class;
}
public Object resolvePlaceHolder(Object origin) {
if (origin.getClass().isArray()) {
int length = Array.getLength(origin);
Object ret = Array.newInstance(origin.getClass().getComponentType(), length);
for (int i = 0; i < length; ++i) {
Array.set(ret, i, resolvePlaceHolder(Array.get(origin, i)));
}
return ret;
} else {
return doResolvePlaceHolder(origin);
}
}
private Object doResolvePlaceHolder(Object origin) {
if (origin instanceof String) {
return binder.bind(environment, (String) origin);
} else if (origin instanceof Annotation && !(origin instanceof WrapperAnnotation)) {
return AnnotationWrapper.create((Annotation) origin).withBinder(binder)
.withEnvironment(environment).wrap((Annotation) origin);
} else {
return origin;
}
}
}
|
Object ret = method.invoke(delegate, args);
if (ret != null && !ReflectionUtils.isObjectMethod(method) && isAttributeMethod(method)) {
return resolvePlaceHolder(ret);
}
return ret;
| 430
| 63
| 493
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot/src/main/java/com/alipay/sofa/boot/aop/framework/autoproxy/ExcludeBeanNameAutoProxyCreator.java
|
ExcludeBeanNameAutoProxyCreator
|
setExcludeBeanNames
|
class ExcludeBeanNameAutoProxyCreator extends BeanNameAutoProxyCreator {
@Nullable
private List<String> excludeBeanNames;
/**
* Set the names of the beans that should not automatically get wrapped with proxies.
* A name can specify a prefix to match by ending with "*", e.g. "myBean,tx*"
* will match the bean named "myBean" and all beans whose name start with "tx".
* <p><b>NOTE:</b> In case of a FactoryBean, only the objects created by the
* FactoryBean will get proxied. This default behavior applies as of Spring 2.0.
* If you intend to proxy a FactoryBean instance itself (a rare use case, but
* Spring 1.2's default behavior), specify the bean name of the FactoryBean
* including the factory-bean prefix "&": e.g. "&myFactoryBean".
* @see org.springframework.beans.factory.FactoryBean
* @see org.springframework.beans.factory.BeanFactory#FACTORY_BEAN_PREFIX
*/
public void setExcludeBeanNames(String... beanNames) {<FILL_FUNCTION_BODY>}
@Override
protected boolean isMatch(String beanName, String mappedName) {
return super.isMatch(beanName, mappedName) && !isExcluded(beanName);
}
private boolean isExcluded(String beanName) {
if (excludeBeanNames != null) {
for (String mappedName : this.excludeBeanNames) {
if (PatternMatchUtils.simpleMatch(mappedName, beanName)) {
return true;
}
}
}
return false;
}
}
|
Assert.notEmpty(beanNames, "'excludeBeanNames' must not be empty");
this.excludeBeanNames = new ArrayList<>(beanNames.length);
for (String mappedName : beanNames) {
this.excludeBeanNames.add(mappedName.strip());
}
| 429
| 74
| 503
|
<methods>public void <init>() ,public transient void setBeanNames(java.lang.String[]) <variables>private static final java.lang.String[] NO_ALIASES,private List<java.lang.String> beanNames
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot/src/main/java/com/alipay/sofa/boot/compatibility/AbstractJarVersionVerifier.java
|
AbstractJarVersionVerifier
|
compatibilityPredicate
|
class AbstractJarVersionVerifier extends AbstractSwitchableCompatibilityVerifier {
public AbstractJarVersionVerifier(Environment environment) {
super(environment);
}
@Override
public CompatibilityPredicate compatibilityPredicate() {<FILL_FUNCTION_BODY>}
@Override
public String errorDescription() {
return String.format("SOFABoot is not compatible with jar [%s] for current version.",
name());
}
@Override
public String action() {
return String.format(
"Change [%s] to appropriate version,"
+ "you can visit this doc [%s] and find an appropriate version,"
+ "If you want to disable this check, just set the property [%s=false].",
name(), doc(), this.enableKey);
}
public abstract Collection<CompatibilityPredicate> getJarCompatibilityPredicates();
public abstract String name();
public abstract String doc();
}
|
return () -> {
Collection<CompatibilityPredicate> compatibilityPredicates = getJarCompatibilityPredicates();
if (compatibilityPredicates == null) {
return true;
}
return compatibilityPredicates.stream().allMatch(CompatibilityPredicate::isCompatible);
};
| 241
| 79
| 320
|
<methods>public void <init>(org.springframework.core.env.Environment) ,public abstract java.lang.String action() ,public abstract com.alipay.sofa.boot.compatibility.CompatibilityPredicate compatibilityPredicate() ,public abstract java.lang.String enableKey() ,public abstract java.lang.String errorDescription() ,public com.alipay.sofa.boot.compatibility.VerificationResult verify() <variables>private static final java.lang.String ENABLE_KEY_FORMAT,protected java.lang.String enableKey,protected final non-sealed org.springframework.core.env.Environment environment
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot/src/main/java/com/alipay/sofa/boot/compatibility/AbstractSwitchableCompatibilityVerifier.java
|
AbstractSwitchableCompatibilityVerifier
|
verify
|
class AbstractSwitchableCompatibilityVerifier implements CompatibilityVerifier {
private static final String ENABLE_KEY_FORMAT = "sofa.boot.compatibility-verifier.%s.enabled";
protected final Environment environment;
protected String enableKey;
public AbstractSwitchableCompatibilityVerifier(Environment environment) {
this.environment = environment;
}
@Override
public VerificationResult verify() {<FILL_FUNCTION_BODY>}
public abstract CompatibilityPredicate compatibilityPredicate();
public abstract String errorDescription();
public abstract String action();
public abstract String enableKey();
}
|
this.enableKey = String.format(ENABLE_KEY_FORMAT, enableKey());
if (!Boolean.parseBoolean(environment.getProperty(enableKey, "true"))) {
return VerificationResult.compatible();
}
CompatibilityPredicate compatibilityPredicate = compatibilityPredicate();
boolean matches = compatibilityPredicate.isCompatible();
if (matches) {
return VerificationResult.compatible();
}
return VerificationResult.notCompatible(errorDescription(), action());
| 159
| 122
| 281
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot/src/main/java/com/alipay/sofa/boot/compatibility/CompatibilityVerifierApplicationContextInitializer.java
|
CompatibilityVerifierApplicationContextInitializer
|
initialize
|
class CompatibilityVerifierApplicationContextInitializer
implements
ApplicationContextInitializer<ConfigurableApplicationContext> {
public static final String COMPATIBILITY_VERIFIER_ENABLED = "sofa.boot.compatibility-verifier.enabled";
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {<FILL_FUNCTION_BODY>}
private List<CompatibilityVerifier> getCompatibilityVerifierInstances(Environment environment) {
SpringFactoriesLoader.ArgumentResolver argumentResolver = SpringFactoriesLoader.ArgumentResolver
.of(Environment.class, environment);
SpringFactoriesLoader springFactoriesLoader = SpringFactoriesLoader
.forDefaultResourceLocation();
// Use names and ensure unique to protect against duplicates
List<CompatibilityVerifier> instances = springFactoriesLoader.load(
CompatibilityVerifier.class, argumentResolver);
AnnotationAwareOrderComparator.sort(instances);
return instances;
}
}
|
Environment environment = applicationContext.getEnvironment();
if (!Boolean.parseBoolean(environment.getProperty(COMPATIBILITY_VERIFIER_ENABLED, "true"))) {
Logger logger = LoggerFactory
.getLogger(CompatibilityVerifierApplicationContextInitializer.class);
logger.info("Skip SOFABoot compatibility Verifier");
return;
}
// Load all CompatibilityVerifier and verify.
CompositeCompatibilityVerifier compositeCompatibilityVerifier = new CompositeCompatibilityVerifier(
getCompatibilityVerifierInstances(environment));
compositeCompatibilityVerifier.verifyCompatibilities();
| 241
| 154
| 395
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot/src/main/java/com/alipay/sofa/boot/compatibility/CompositeCompatibilityVerifier.java
|
CompositeCompatibilityVerifier
|
verifierErrors
|
class CompositeCompatibilityVerifier {
private final List<CompatibilityVerifier> verifiers;
public CompositeCompatibilityVerifier(List<CompatibilityVerifier> verifiers) {
this.verifiers = verifiers;
}
public void verifyCompatibilities() {
List<VerificationResult> errors = verifierErrors();
if (errors.isEmpty()) {
return;
}
String errorMessage = errors.stream().map(VerificationResult::toErrorMessage).toList().toString();
throw new CompatibilityNotMetException(errors, errorMessage);
}
private List<VerificationResult> verifierErrors() {<FILL_FUNCTION_BODY>}
}
|
List<VerificationResult> errors = new ArrayList<>();
for (CompatibilityVerifier verifier : this.verifiers) {
VerificationResult result = verifier.verify();
if (result.isNotCompatible()) {
errors.add(result);
}
}
return errors;
| 172
| 78
| 250
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot/src/main/java/com/alipay/sofa/boot/compatibility/VerificationResult.java
|
VerificationResult
|
toErrorMessage
|
class VerificationResult {
private final String description;
private final String action;
// if OK
private VerificationResult() {
this.description = "";
this.action = "";
}
// if not OK
private VerificationResult(String errorDescription, String action) {
this.description = errorDescription;
this.action = action;
}
public static VerificationResult compatible() {
return new VerificationResult();
}
public static VerificationResult notCompatible(String errorDescription, String action) {
return new VerificationResult(errorDescription, action);
}
public boolean isNotCompatible() {
return StringUtils.hasText(this.description) || StringUtils.hasText(this.action);
}
public String toErrorMessage() {<FILL_FUNCTION_BODY>}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof VerificationResult that)) {
return false;
}
return description.equals(that.description) && action.equals(that.action);
}
@Override
public int hashCode() {
return Objects.hash(description, action);
}
}
|
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("\n");
stringBuilder.append("VerificationResult:");
stringBuilder.append("\n");
stringBuilder.append("—— description: ");
stringBuilder.append(description);
stringBuilder.append("\n");
stringBuilder.append("—— action: ");
stringBuilder.append(action);
return stringBuilder.toString();
| 319
| 101
| 420
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot/src/main/java/com/alipay/sofa/boot/context/SofaGenericApplicationContext.java
|
SofaGenericApplicationContext
|
publishEvent
|
class SofaGenericApplicationContext extends GenericApplicationContext {
private static final Method GET_APPLICATION_EVENT_MULTICASTER_METHOD;
private static final Field EARLY_APPLICATION_EVENTS_FIELD;
private List<ContextRefreshInterceptor> interceptors = new ArrayList<>();
private boolean publishEventToParent;
static {
try {
GET_APPLICATION_EVENT_MULTICASTER_METHOD = AbstractApplicationContext.class
.getDeclaredMethod("getApplicationEventMulticaster");
GET_APPLICATION_EVENT_MULTICASTER_METHOD.setAccessible(true);
EARLY_APPLICATION_EVENTS_FIELD = AbstractApplicationContext.class
.getDeclaredField("earlyApplicationEvents");
EARLY_APPLICATION_EVENTS_FIELD.setAccessible(true);
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
public SofaGenericApplicationContext() {
this(new SofaDefaultListableBeanFactory());
}
/**
* Create a new SofaApplicationContext with the given DefaultListableBeanFactory.
* @param beanFactory the DefaultListableBeanFactory instance to use for this context
* @see #registerBeanDefinition
* @see #refresh
*/
public SofaGenericApplicationContext(SofaDefaultListableBeanFactory beanFactory) {
super(beanFactory);
}
@Override
public void refresh() throws BeansException, IllegalStateException {
if (CollectionUtils.isEmpty(interceptors)) {
super.refresh();
return;
}
Throwable throwable = null;
try {
applyInterceptorBeforeRefresh();
super.refresh();
} catch (Throwable t) {
throwable = t;
throw t;
} finally {
applyInterceptorAfterRefresh(throwable);
}
}
/**
* @see org.springframework.context.support.AbstractApplicationContext#publishEvent(java.lang.Object, org.springframework.core.ResolvableType)
*/
@Override
protected void publishEvent(Object event, ResolvableType eventType) {<FILL_FUNCTION_BODY>}
protected void applyInterceptorBeforeRefresh() {
interceptors.forEach(interceptor -> interceptor.beforeRefresh(this));
}
protected void applyInterceptorAfterRefresh(Throwable throwable) {
interceptors.forEach(interceptor -> interceptor.afterRefresh(this, throwable));
}
public void setPublishEventToParent(boolean publishEventToParent) {
this.publishEventToParent = publishEventToParent;
}
public void setInterceptors(List<ContextRefreshInterceptor> interceptors) {
this.interceptors = interceptors;
}
@SuppressWarnings("unchecked")
private <T> T getFieldValueByReflect(Field field, Object obj) {
try {
return (T) field.get(obj);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("unchecked")
private <T> T getMethodValueByReflect(Method method, Object obj, Object... args) {
try {
return (T) method.invoke(obj, args);
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
}
|
if (publishEventToParent) {
super.publishEvent(event, eventType);
return;
}
Assert.notNull(event, "Event must not be null");
// Decorate event as an ApplicationEvent if necessary
ApplicationEvent applicationEvent;
if (event instanceof ApplicationEvent) {
applicationEvent = (ApplicationEvent) event;
} else {
applicationEvent = new PayloadApplicationEvent<>(this, event);
if (eventType == null) {
eventType = ((PayloadApplicationEvent<?>) applicationEvent).getResolvableType();
}
}
Set<ApplicationEvent> earlyApplicationEvents = getFieldValueByReflect(
EARLY_APPLICATION_EVENTS_FIELD, this);
if (earlyApplicationEvents != null) {
earlyApplicationEvents.add(applicationEvent);
} else {
ApplicationEventMulticaster applicationEventMulticaster = getMethodValueByReflect(
GET_APPLICATION_EVENT_MULTICASTER_METHOD, this);
applicationEventMulticaster.multicastEvent(applicationEvent, eventType);
}
| 891
| 276
| 1,167
|
<methods>public void <init>() ,public void <init>(org.springframework.beans.factory.support.DefaultListableBeanFactory) ,public void <init>(org.springframework.context.ApplicationContext) ,public void <init>(org.springframework.beans.factory.support.DefaultListableBeanFactory, org.springframework.context.ApplicationContext) ,public org.springframework.beans.factory.config.AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws java.lang.IllegalStateException,public org.springframework.beans.factory.config.BeanDefinition getBeanDefinition(java.lang.String) throws org.springframework.beans.factory.NoSuchBeanDefinitionException,public final org.springframework.beans.factory.config.ConfigurableListableBeanFactory getBeanFactory() ,public java.lang.ClassLoader getClassLoader() ,public final org.springframework.beans.factory.support.DefaultListableBeanFactory getDefaultListableBeanFactory() ,public org.springframework.core.io.Resource getResource(java.lang.String) ,public org.springframework.core.io.Resource[] getResources(java.lang.String) throws java.io.IOException,public boolean isAlias(java.lang.String) ,public boolean isBeanDefinitionOverridable(java.lang.String) ,public boolean isBeanNameInUse(java.lang.String) ,public void refreshForAotProcessing(org.springframework.aot.hint.RuntimeHints) ,public void registerAlias(java.lang.String, java.lang.String) ,public transient void registerBean(Class<T>, java.lang.Object[]) ,public final transient void registerBean(Class<T>, org.springframework.beans.factory.config.BeanDefinitionCustomizer[]) ,public transient void registerBean(java.lang.String, Class<T>, java.lang.Object[]) ,public final transient void registerBean(java.lang.String, Class<T>, org.springframework.beans.factory.config.BeanDefinitionCustomizer[]) ,public final transient void registerBean(Class<T>, Supplier<T>, org.springframework.beans.factory.config.BeanDefinitionCustomizer[]) ,public transient void registerBean(java.lang.String, Class<T>, Supplier<T>, org.springframework.beans.factory.config.BeanDefinitionCustomizer[]) ,public void registerBeanDefinition(java.lang.String, org.springframework.beans.factory.config.BeanDefinition) throws org.springframework.beans.factory.BeanDefinitionStoreException,public void removeAlias(java.lang.String) ,public void removeBeanDefinition(java.lang.String) throws org.springframework.beans.factory.NoSuchBeanDefinitionException,public void setAllowBeanDefinitionOverriding(boolean) ,public void setAllowCircularReferences(boolean) ,public void setApplicationStartup(org.springframework.core.metrics.ApplicationStartup) ,public void setClassLoader(java.lang.ClassLoader) ,public void setParent(org.springframework.context.ApplicationContext) ,public void setResourceLoader(org.springframework.core.io.ResourceLoader) <variables>private final org.springframework.beans.factory.support.DefaultListableBeanFactory beanFactory,private boolean customClassLoader,private final java.util.concurrent.atomic.AtomicBoolean refreshed,private org.springframework.core.io.ResourceLoader resourceLoader
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot/src/main/java/com/alipay/sofa/boot/context/SofaSpringContextSupport.java
|
SofaSpringContextSupport
|
createBeanFactory
|
class SofaSpringContextSupport {
public static SofaDefaultListableBeanFactory createBeanFactory(ClassLoader beanClassLoader,
Supplier<SofaDefaultListableBeanFactory> supplier) {<FILL_FUNCTION_BODY>}
public static SofaGenericApplicationContext createApplicationContext(SofaDefaultListableBeanFactory beanFactory,
Function<SofaDefaultListableBeanFactory, SofaGenericApplicationContext> function) {
SofaGenericApplicationContext ctx = function.apply(beanFactory);
ctx.setClassLoader(beanFactory.getBeanClassLoader());
return ctx;
}
}
|
SofaDefaultListableBeanFactory beanFactory = supplier.get();
if (!(beanFactory.getAutowireCandidateResolver() instanceof QualifierAnnotationAutowireCandidateResolver)) {
beanFactory.setAutowireCandidateResolver(new QualifierAnnotationAutowireCandidateResolver());
}
beanFactory.setParameterNameDiscoverer(new DefaultParameterNameDiscoverer());
beanFactory.setBeanClassLoader(beanClassLoader);
beanFactory.addPropertyEditorRegistrar(registry -> {
registry.registerCustomEditor(Class.class, new ClassEditor(beanClassLoader));
registry.registerCustomEditor(Class[].class, new ClassArrayEditor(beanClassLoader));
});
CachedIntrospectionResults.acceptClassLoader(beanClassLoader);
return beanFactory;
| 156
| 194
| 350
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot/src/main/java/com/alipay/sofa/boot/context/processor/SofaPostProcessorShareManager.java
|
SofaPostProcessorShareManager
|
afterPropertiesSet
|
class SofaPostProcessorShareManager implements BeanFactoryAware, InitializingBean {
private static final String[] WHITE_NAME_LIST = new String[] {
ConfigurationClassPostProcessor.class.getName() + ".importAwareProcessor",
ConfigurationClassPostProcessor.class.getName() + ".importRegistry",
ConfigurationClassPostProcessor.class.getName() + ".enhancedConfigurationProcessor" };
private final Map<String, Object> registerSingletonMap = new HashMap<>();
private final Map<String, BeanDefinition> registerBeanDefinitionMap = new HashMap<>();
private ConfigurableListableBeanFactory beanFactory;
private boolean isShareParentContextPostProcessors = true;
private List<SofaPostProcessorShareFilter> sofaPostProcessorShareFilters = new ArrayList<>();
@Override
public void afterPropertiesSet() throws Exception {<FILL_FUNCTION_BODY>}
private void initShareSofaPostProcessors() {
Set<String> beanNames = new HashSet<>();
Set<String> allBeanDefinitionNames = new HashSet<>(Arrays.asList(beanFactory
.getBeanDefinitionNames()));
String[] eanFactoryPostProcessors = beanFactory.getBeanNamesForType(
BeanFactoryPostProcessor.class, true, false);
String[] beanPostProcessors = beanFactory.getBeanNamesForType(BeanPostProcessor.class,
true, false);
beanNames.addAll(Arrays.asList(eanFactoryPostProcessors));
beanNames.addAll(Arrays.asList(beanPostProcessors));
for (String beanName : beanNames) {
if (notInWhiteNameList(beanName) && allBeanDefinitionNames.contains(beanName)) {
BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
Class<?> clazz = BeanDefinitionUtil.resolveBeanClassType(beanDefinition);
if (clazz == null) {
continue;
}
if (shouldBeanShare(beanName, clazz)) {
if (shouldBeanSingleton(beanName, clazz)) {
registerSingletonMap.put(beanName, beanFactory.getBean(beanName));
} else {
registerBeanDefinitionMap.put(beanName, beanDefinition);
}
}
}
}
}
private boolean shouldBeanShare(String beanName, Class<?> clazz) {
if (AnnotationUtils.findAnnotation(clazz, UnshareSofaPostProcessor.class) != null) {
return false;
}
for (SofaPostProcessorShareFilter filter : sofaPostProcessorShareFilters) {
if (filter.skipShareByBeanName(beanName) || filter.skipShareByClass(clazz)) {
return false;
}
}
return true;
}
private boolean shouldBeanSingleton(String beanName, Class<?> clazz) {
if (AnnotationUtils.findAnnotation(clazz, SingletonSofaPostProcessor.class) != null) {
return true;
}
for (SofaPostProcessorShareFilter filter : sofaPostProcessorShareFilters) {
if (filter.useSingletonByBeanName(beanName) || filter.useSingletonByClass(clazz)) {
return true;
}
}
return false;
}
private boolean notInWhiteNameList(String beanName) {
for (String whiteName : WHITE_NAME_LIST) {
if (whiteName.equals(beanName)) {
return false;
}
}
return true;
}
public boolean isShareParentContextPostProcessors() {
return isShareParentContextPostProcessors;
}
public void setShareParentContextPostProcessors(boolean shareParentContextPostProcessors) {
isShareParentContextPostProcessors = shareParentContextPostProcessors;
}
public List<SofaPostProcessorShareFilter> getSofaPostProcessorShareFilters() {
return sofaPostProcessorShareFilters;
}
public void setSofaPostProcessorShareFilters(List<SofaPostProcessorShareFilter> sofaPostProcessorShareFilters) {
this.sofaPostProcessorShareFilters = sofaPostProcessorShareFilters;
}
public Map<String, Object> getRegisterSingletonMap() {
return registerSingletonMap;
}
public Map<String, BeanDefinition> getRegisterBeanDefinitionMap() {
return registerBeanDefinitionMap;
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
Assert.isInstanceOf(ConfigurableListableBeanFactory.class, beanFactory,
"beanFactory must be ConfigurableListableBeanFactory");
this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
}
}
|
if (!isShareParentContextPostProcessors) {
return;
}
Assert.notNull(beanFactory, "beanFactory must not be null");
Assert.notNull(registerSingletonMap, "registerSingletonMap must not be null");
Assert.notNull(registerBeanDefinitionMap, "registerBeanDefinitionMap must not be null");
Assert.notNull(sofaPostProcessorShareFilters,
"sofaPostProcessorShareFilters must not be null");
initShareSofaPostProcessors();
| 1,189
| 126
| 1,315
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot/src/main/java/com/alipay/sofa/boot/env/ScenesEnvironmentPostProcessor.java
|
ScenesEnvironmentPostProcessor
|
scenesResources
|
class ScenesEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered {
public static final String SCENES_KEY = "sofa.boot.scenes";
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment,
SpringApplication application) {
ResourceLoader resourceLoader = application.getResourceLoader();
resourceLoader = (resourceLoader != null) ? resourceLoader : new DefaultResourceLoader();
List<PropertySourceLoader> propertySourceLoaders = SpringFactoriesLoader.loadFactories(
PropertySourceLoader.class, getClass().getClassLoader());
String scenesValue = environment.getProperty(SCENES_KEY);
if (!StringUtils.hasText(scenesValue)) {
return;
}
Set<String> scenes = StringUtils.commaDelimitedListToSet(scenesValue);
List<SceneConfigDataReference> sceneConfigDataReferences = scenesResources(resourceLoader,
propertySourceLoaders, scenes);
SofaBootLoggerFactory.getLogger(ScenesEnvironmentPostProcessor.class).info(
"Configs for scenes {} enable", scenes);
processAndApply(sceneConfigDataReferences, environment);
}
@Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE - 100;
}
private List<SceneConfigDataReference> scenesResources(ResourceLoader resourceLoader, List<PropertySourceLoader> propertySourceLoaders,
Set<String> scenes) {<FILL_FUNCTION_BODY>}
/**
* Process all scene config property sources to the
* {@link org.springframework.core.env.Environment}.
*/
private void processAndApply(List<SceneConfigDataReference> sceneConfigDataReferences, ConfigurableEnvironment environment) {
for (SceneConfigDataReference sceneConfigDataReference :
sceneConfigDataReferences) {
try {
List<PropertySource<?>> propertySources = sceneConfigDataReference.propertySourceLoader.load(
sceneConfigDataReference.getName(),
sceneConfigDataReference.getResource());
if (propertySources != null) {
propertySources.forEach(environment.getPropertySources()::addLast);
}
} catch (IOException e) {
throw new IllegalStateException("IO error on loading scene config data from " + sceneConfigDataReference.name, e);
}
}
}
private static class SceneConfigDataReference {
private String name;
private Resource resource;
private PropertySourceLoader propertySourceLoader;
public SceneConfigDataReference(String name, Resource resource,
PropertySourceLoader propertySourceLoader) {
this.name = name;
this.resource = resource;
this.propertySourceLoader = propertySourceLoader;
}
/**
* Getter method for property <tt>resource</tt>.
*
* @return property value of resource
*/
public Resource getResource() {
return resource;
}
/**
* Setter method for property <tt>resource</tt>.
*
* @param resource value to be assigned to property resource
*/
public void setResource(Resource resource) {
this.resource = resource;
}
/**
* Getter method for property <tt>propertySourceLoader</tt>.
*
* @return property value of propertySourceLoader
*/
public PropertySourceLoader getPropertySourceLoader() {
return propertySourceLoader;
}
/**
* Setter method for property <tt>propertySourceLoader</tt>.
*
* @param propertySourceLoader value to be assigned to property propertySourceLoader
*/
public void setPropertySourceLoader(PropertySourceLoader propertySourceLoader) {
this.propertySourceLoader = propertySourceLoader;
}
/**
* Getter method for property <tt>name</tt>.
*
* @return property value of name
*/
public String getName() {
return name;
}
/**
* Setter method for property <tt>name</tt>.
*
* @param name value to be assigned to property name
*/
public void setName(String name) {
this.name = name;
}
}
}
|
List<SceneConfigDataReference> resources = new ArrayList<>();
if (scenes != null && !scenes.isEmpty()) {
scenes.forEach(scene -> propertySourceLoaders.forEach(psl -> {
for (String extension : psl.getFileExtensions()) {
String location =
"classpath:/" + SofaBootConstants.SOFA_BOOT_SCENES_FILE_DIR + File.separator + scene + "." + extension;
Resource resource = resourceLoader.getResource(location);
if (resource.exists()) {
resources.add(new SceneConfigDataReference(location, resource, psl));
}
}
}));
}
return resources;
| 1,048
| 179
| 1,227
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot/src/main/java/com/alipay/sofa/boot/env/SofaBootEnvironmentPostProcessor.java
|
SofaBootEnvironmentPostProcessor
|
getSofaBootVersionProperties
|
class SofaBootEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered {
private static final String PROPERTY_NAME_AUTOCONFIGURE_EXCLUDE = "spring.autoconfigure.exclude";
private static final List<String> SOFABOOT_EXCLUDE_AUTOCONFIGURATION_CLASSES = List
.of("org.springframework.boot.actuate.autoconfigure.startup.StartupEndpointAutoConfiguration");
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment,
SpringApplication application) {
if (environment.getPropertySources().get(SofaBootConstants.SOFA_DEFAULT_PROPERTY_SOURCE) != null) {
return;
}
addSofaBootDefaultPropertySource(environment);
addSpringExcludeConfigurationPropertySource(environment);
// set required properties, {@link MissingRequiredPropertiesException}
environment.setRequiredProperties(SofaBootConstants.APP_NAME_KEY);
}
private void addSofaBootDefaultPropertySource(ConfigurableEnvironment environment) {
// Get SOFABoot version properties
Properties defaultConfiguration = getSofaBootVersionProperties();
// Config default value of {@literal management.endpoints.web.exposure.include}
defaultConfiguration.put(SofaBootConstants.ENDPOINTS_WEB_EXPOSURE_INCLUDE_CONFIG,
SofaBootConstants.SOFA_DEFAULT_ENDPOINTS_WEB_EXPOSURE_VALUE);
PropertiesPropertySource propertySource = new PropertiesPropertySource(
SofaBootConstants.SOFA_DEFAULT_PROPERTY_SOURCE, defaultConfiguration);
environment.getPropertySources().addLast(propertySource);
}
private void addSpringExcludeConfigurationPropertySource(ConfigurableEnvironment environment) {
// Append exclude autoconfigure classes config
Binder binder = Binder.get(environment);
List<String> excludeConfigs = new ArrayList<>();
List<String> stringList = binder.bind(PROPERTY_NAME_AUTOCONFIGURE_EXCLUDE, String[].class).map(List::of)
.orElse(new ArrayList<>());
excludeConfigs.addAll(SOFABOOT_EXCLUDE_AUTOCONFIGURATION_CLASSES);
excludeConfigs.addAll(stringList);
// Update spring.autoconfigure.exclude
Properties properties = new Properties();
properties.put(PROPERTY_NAME_AUTOCONFIGURE_EXCLUDE, StringUtils.collectionToCommaDelimitedString(excludeConfigs));
PropertiesPropertySource propertySource = new PropertiesPropertySource(
SofaBootConstants.SOFA_EXCLUDE_AUTO_CONFIGURATION_PROPERTY_SOURCE, properties);
environment.getPropertySources().addFirst(propertySource);
}
/**
* Get SOFABoot Version and print it on banner
*/
protected Properties getSofaBootVersionProperties() {<FILL_FUNCTION_BODY>}
/**
* Get SOFABoot Version string.
*/
protected String getSofaBootVersion() {
return SofaBootEnvironmentPostProcessor.class.getPackage().getImplementationVersion();
}
@Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE - 100;
}
}
|
Properties properties = new Properties();
String sofaBootVersion = getSofaBootVersion();
// generally, it would not be null and just for test.
sofaBootVersion = !StringUtils.hasText(sofaBootVersion) ? "" : sofaBootVersion;
String sofaBootFormattedVersion = sofaBootVersion.isEmpty() ? "" : String.format(" (v%s)",
sofaBootVersion);
properties.setProperty(SofaBootConstants.SOFA_BOOT_VERSION, sofaBootVersion);
properties.setProperty(SofaBootConstants.SOFA_BOOT_FORMATTED_VERSION,
sofaBootFormattedVersion);
return properties;
| 850
| 161
| 1,011
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot/src/main/java/com/alipay/sofa/boot/listener/SofaConfigSourceSupportListener.java
|
SofaConfigSourceSupportListener
|
registerSofaConfigs
|
class SofaConfigSourceSupportListener
implements
ApplicationListener<ApplicationEnvironmentPreparedEvent>,
Ordered {
private final AtomicBoolean registered = new AtomicBoolean();
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
if (registered.compareAndSet(false, true)) {
registerSofaConfigs(event.getEnvironment());
}
}
private void registerSofaConfigs(ConfigurableEnvironment environment) {<FILL_FUNCTION_BODY>}
@Override
public int getOrder() {
return ApplicationListenerOrderConstants.SOFA_CONFIG_SOURCE_SUPPORT_LISTENER_ORDER;
}
}
|
SofaConfigs.addConfigSource(new AbstractConfigSource() {
@Override
public int getOrder() {
return LOWEST_PRECEDENCE;
}
@Override
public String getName() {
return SofaBootConstants.SOFA_BOOT_SPACE_NAME;
}
@Override
public String doGetConfig(String key) {
return environment.getProperty(key);
}
@Override
public boolean hasKey(String key) {
return StringUtils.hasText(environment.getProperty(key));
}
});
| 177
| 153
| 330
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot/src/main/java/com/alipay/sofa/boot/listener/SpringCloudConfigListener.java
|
SpringCloudConfigListener
|
onApplicationEvent
|
class SpringCloudConfigListener implements
ApplicationListener<ApplicationEnvironmentPreparedEvent>,
Ordered {
private final static MapPropertySource HIGH_PRIORITY_CONFIG = new MapPropertySource(
SofaBootConstants.SOFA_HIGH_PRIORITY_CONFIG,
new HashMap<>());
/**
* config log settings
*/
private void assemblyLogSetting(ConfigurableEnvironment environment) {
StreamSupport.stream(environment.getPropertySources().spliterator(), false)
.filter(propertySource -> propertySource instanceof EnumerablePropertySource)
.map(propertySource -> Arrays
.asList(((EnumerablePropertySource<?>) propertySource).getPropertyNames()))
.flatMap(Collection::stream).filter(LogEnvUtils::isSofaCommonLoggingConfig)
.forEach((key) -> HIGH_PRIORITY_CONFIG.getSource().put(key, environment.getProperty(key)));
}
/**
* config required properties
*/
private void assemblyRequireProperties(ConfigurableEnvironment environment) {
if (StringUtils.hasText(environment.getProperty(SofaBootConstants.APP_NAME_KEY))) {
HIGH_PRIORITY_CONFIG.getSource().put(SofaBootConstants.APP_NAME_KEY,
environment.getProperty(SofaBootConstants.APP_NAME_KEY));
}
}
@Override
public int getOrder() {
return ApplicationListenerOrderConstants.SOFA_BOOTSTRAP_RUN_LISTENER_ORDER;
}
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {<FILL_FUNCTION_BODY>}
}
|
ConfigurableEnvironment environment = event.getEnvironment();
// only work in spring cloud application
if (SofaBootEnvUtils.isSpringCloudEnvironmentEnabled(environment)) {
if (environment.getPropertySources().contains(SofaBootConstants.SPRING_CLOUD_BOOTSTRAP)) {
// in bootstrap application context, add high priority config
environment.getPropertySources().addLast(HIGH_PRIORITY_CONFIG);
} else {
// in application context, build high priority config
SpringApplication application = event.getSpringApplication();
StandardEnvironment bootstrapEnvironment = new StandardEnvironment();
StreamSupport.stream(environment.getPropertySources().spliterator(), false)
.filter(source -> !(source instanceof PropertySource.StubPropertySource))
.forEach(source -> bootstrapEnvironment.getPropertySources().addLast(source));
List<Class<?>> sources = new ArrayList<>();
for (Object s : application.getAllSources()) {
if (s instanceof Class) {
sources.add((Class<?>) s);
} else if (s instanceof String) {
sources.add(ClassUtils.resolveClassName((String) s, null));
}
}
SpringApplication bootstrapApplication = new SpringApplicationBuilder()
.profiles(environment.getActiveProfiles()).bannerMode(Banner.Mode.OFF)
.environment(bootstrapEnvironment).sources(sources.toArray(new Class[]{}))
.registerShutdownHook(false).logStartupInfo(false).web(WebApplicationType.NONE)
.listeners().initializers().build(event.getArgs());
ConfigurableBootstrapContext bootstrapContext = event.getBootstrapContext();
ApplicationEnvironmentPreparedEvent bootstrapEvent = new ApplicationEnvironmentPreparedEvent(
bootstrapContext, bootstrapApplication, event.getArgs(), bootstrapEnvironment);
application.getListeners().stream()
.filter(listener -> listener instanceof EnvironmentPostProcessorApplicationListener)
.forEach(listener -> ((EnvironmentPostProcessorApplicationListener) listener)
.onApplicationEvent(bootstrapEvent));
assemblyLogSetting(bootstrapEnvironment);
assemblyRequireProperties(bootstrapEnvironment);
}
}
| 421
| 542
| 963
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot/src/main/java/com/alipay/sofa/boot/listener/SwitchableApplicationListener.java
|
SwitchableApplicationListener
|
onApplicationEvent
|
class SwitchableApplicationListener<E extends ApplicationEvent>
implements
ApplicationListener<E> {
protected static final String CONFIG_KEY_PREFIX = "sofa.boot.switch.listener.";
@Override
public void onApplicationEvent(E event) {<FILL_FUNCTION_BODY>}
protected abstract void doOnApplicationEvent(E event);
/**
* sofa.boot.switch.listener
*
* @return switch key, must not be null.
*/
protected abstract String switchKey();
/**
* Specify if the condition should match if the property is not set. Defaults to
* {@code true}.
*
* @return if the condition should match if the property is missing
*/
protected boolean matchIfMissing() {
return true;
}
protected boolean isEnable(Environment environment) {
String switchKey = switchKey();
Assert.hasText(switchKey, "switch key must has text.");
String realKey = CONFIG_KEY_PREFIX + switchKey + ".enabled";
String switchStr = environment.getProperty(realKey);
if (StringUtils.hasText(switchStr)) {
return Boolean.parseBoolean(switchStr);
} else {
return matchIfMissing();
}
}
}
|
ApplicationContext applicationContext = null;
Environment environment = null;
if (event instanceof ApplicationContextEvent applicationContextEvent) {
applicationContext = applicationContextEvent.getApplicationContext();
} else if (event instanceof ApplicationContextInitializedEvent applicationContextInitializedEvent) {
applicationContext = applicationContextInitializedEvent.getApplicationContext();
} else if (event instanceof ApplicationEnvironmentPreparedEvent environmentPreparedEvent) {
environment = environmentPreparedEvent.getEnvironment();
} else if (event instanceof ApplicationPreparedEvent applicationPreparedEvent) {
applicationContext = applicationPreparedEvent.getApplicationContext();
} else if (event instanceof ApplicationReadyEvent applicationReadyEvent) {
applicationContext = applicationReadyEvent.getApplicationContext();
} else if (event instanceof ApplicationStartedEvent applicationStartedEvent) {
applicationContext = applicationStartedEvent.getApplicationContext();
} else if (event instanceof ApplicationFailedEvent applicationFailedEvent) {
applicationContext = applicationFailedEvent.getApplicationContext();
}
if (environment == null && applicationContext != null) {
environment = applicationContext.getEnvironment();
}
if (environment != null) {
if (isEnable(environment)) {
doOnApplicationEvent(event);
}
} else {
doOnApplicationEvent(event);
}
| 323
| 320
| 643
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot/src/main/java/com/alipay/sofa/boot/log/SofaBootLoggerFactory.java
|
SofaBootLoggerFactory
|
getLogger
|
class SofaBootLoggerFactory {
/**
* get Logger Object
*
* @param name name of the logger
* @return Logger Object
*/
public static Logger getLogger(String name) {
if (name == null || name.isEmpty()) {
return null;
}
return LoggerSpaceManager.getLoggerBySpace(name, SofaBootConstants.SOFA_BOOT_SPACE_NAME);
}
/**
* get Logger Object
* @param clazz the returned logger will be named after clazz
* @return Logger Object
*/
public static Logger getLogger(Class<?> clazz) {<FILL_FUNCTION_BODY>}
}
|
if (clazz == null) {
return null;
}
return getLogger(clazz.getCanonicalName());
| 182
| 35
| 217
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot/src/main/java/com/alipay/sofa/boot/logging/LogEnvironmentPostProcessor.java
|
LogEnvironmentPostProcessor
|
initLoggingConfig
|
class LogEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered {
public static final int ORDER = ConfigDataEnvironmentPostProcessor.ORDER + 1;
/**
* support use config to disable sofa common thread pool monitor.
*/
public static final String SOFA_THREAD_POOL_MONITOR_DISABLE = "sofa.boot.tools.threadpool.monitor.disable";
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment,
SpringApplication application) {
defaultConsoleLoggers();
initLoggingConfig(environment);
initSofaCommonThread(environment);
}
@Override
public int getOrder() {
return ORDER;
}
private void initLoggingConfig(ConfigurableEnvironment environment) {<FILL_FUNCTION_BODY>}
private void defaultConsoleLoggers() {
if (SofaBootEnvUtils.isLocalEnv() || SofaBootEnvUtils.isSpringTestEnv()) {
CommonLoggingConfigurations.loadExternalConfiguration(
Constants.SOFA_MIDDLEWARE_ALL_LOG_CONSOLE_SWITCH, "true");
}
}
private void loadLogConfiguration(String key, String value, String defaultValue,
Map<String, String> context) {
if (StringUtils.hasText(value)) {
context.put(key, value);
} else {
context.put(key, defaultValue);
}
}
private void loadLogConfiguration(String key, String value, Map<String, String> context) {
if (StringUtils.hasText(value)) {
context.put(key, value);
}
}
private void initSofaCommonThread(ConfigurableEnvironment environment) {
if (Boolean.parseBoolean(environment.getProperty(SOFA_THREAD_POOL_MONITOR_DISABLE))) {
System
.setProperty(SofaThreadPoolConstants.SOFA_THREAD_POOL_LOGGING_CAPABILITY, "false");
}
}
}
|
Map<String, String> context = new HashMap<>();
loadLogConfiguration(Constants.LOG_PATH, environment.getProperty(Constants.LOG_PATH),
Constants.LOGGING_PATH_DEFAULT, context);
loadLogConfiguration(Constants.OLD_LOG_PATH,
environment.getProperty(Constants.OLD_LOG_PATH), context.get(Constants.LOG_PATH),
context);
loadLogConfiguration(Constants.LOG_ENCODING_PROP_KEY,
environment.getProperty(Constants.LOG_ENCODING_PROP_KEY), context);
// Don't delete this!
// Some old SOFA SDKs rely on JVM system properties to determine log configurations.
LogEnvUtils.keepCompatible(context, true);
for (Map.Entry<String, String> entry : context.entrySet()) {
CommonLoggingConfigurations.loadExternalConfiguration(entry.getKey(), entry.getValue());
}
for (PropertySource<?> propertySource : environment.getPropertySources()) {
if (propertySource instanceof EnumerablePropertySource) {
for (String key : ((EnumerablePropertySource) propertySource).getPropertyNames()) {
if (LogEnvUtils.isSofaCommonLoggingConfig(key)) {
CommonLoggingConfigurations.loadExternalConfiguration(key,
environment.getProperty(key));
}
}
}
}
| 508
| 341
| 849
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot/src/main/java/com/alipay/sofa/boot/spring/namespace/handler/SofaBootNamespaceHandler.java
|
SofaBootNamespaceHandler
|
registerTagParser
|
class SofaBootNamespaceHandler extends NamespaceHandlerSupport {
private static final Logger logger = SofaBootLoggerFactory
.getLogger(SofaBootNamespaceHandler.class);
@Override
public void init() {
List<SofaBootTagNameSupport> sofaBootTagNameSupports = SpringFactoriesLoader.loadFactories(SofaBootTagNameSupport.class, null);
sofaBootTagNameSupports.forEach(this::registerTagParser);
}
private void registerTagParser(SofaBootTagNameSupport tagNameSupport) {<FILL_FUNCTION_BODY>}
}
|
if (tagNameSupport instanceof BeanDefinitionParser) {
registerBeanDefinitionParser(tagNameSupport.supportTagName(),
(BeanDefinitionParser) tagNameSupport);
} else if (tagNameSupport instanceof BeanDefinitionDecorator) {
registerBeanDefinitionDecoratorForAttribute(tagNameSupport.supportTagName(),
(BeanDefinitionDecorator) tagNameSupport);
} else {
logger
.error(
"{} class supported [{}] parser are not instance of BeanDefinitionParser or BeanDefinitionDecorator",
tagNameSupport.getClass().getName(), tagNameSupport.supportTagName());
}
| 153
| 154
| 307
|
<methods>public void <init>() ,public org.springframework.beans.factory.config.BeanDefinitionHolder decorate(org.w3c.dom.Node, org.springframework.beans.factory.config.BeanDefinitionHolder, org.springframework.beans.factory.xml.ParserContext) ,public org.springframework.beans.factory.config.BeanDefinition parse(org.w3c.dom.Element, org.springframework.beans.factory.xml.ParserContext) <variables>private final Map<java.lang.String,org.springframework.beans.factory.xml.BeanDefinitionDecorator> attributeDecorators,private final Map<java.lang.String,org.springframework.beans.factory.xml.BeanDefinitionDecorator> decorators,private final Map<java.lang.String,org.springframework.beans.factory.xml.BeanDefinitionParser> parsers
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot/src/main/java/com/alipay/sofa/boot/spring/parameter/LocalVariableTableParameterNameDiscoverer.java
|
LocalVariableTableVisitor
|
resolveExecutable
|
class LocalVariableTableVisitor extends MethodVisitor {
private static final String CONSTRUCTOR = "<init>";
private final Class<?> clazz;
private final Map<Executable, String[]> executableMap;
private final String name;
private final Type[] args;
private final String[] parameterNames;
private final boolean isStatic;
private boolean hasLvtInfo = false;
/*
* The nth entry contains the slot index of the LVT table entry holding the
* argument name for the nth parameter.
*/
private final int[] lvtSlotIndex;
public LocalVariableTableVisitor(Class<?> clazz, Map<Executable, String[]> map,
String name, String desc, boolean isStatic) {
super(SpringAsmInfo.ASM_VERSION);
this.clazz = clazz;
this.executableMap = map;
this.name = name;
this.args = Type.getArgumentTypes(desc);
this.parameterNames = new String[this.args.length];
this.isStatic = isStatic;
this.lvtSlotIndex = computeLvtSlotIndices(isStatic, this.args);
}
@Override
public void visitLocalVariable(String name, String description, String signature,
Label start, Label end, int index) {
this.hasLvtInfo = true;
for (int i = 0; i < this.lvtSlotIndex.length; i++) {
if (this.lvtSlotIndex[i] == index) {
this.parameterNames[i] = name;
}
}
}
@Override
public void visitEnd() {
if (this.hasLvtInfo || (this.isStatic && this.parameterNames.length == 0)) {
// visitLocalVariable will never be called for static no args methods
// which doesn't use any local variables.
// This means that hasLvtInfo could be false for that kind of methods
// even if the class has local variable info.
this.executableMap.put(resolveExecutable(), this.parameterNames);
}
}
private Executable resolveExecutable() {<FILL_FUNCTION_BODY>}
private static int[] computeLvtSlotIndices(boolean isStatic, Type[] paramTypes) {
int[] lvtIndex = new int[paramTypes.length];
int nextIndex = (isStatic ? 0 : 1);
for (int i = 0; i < paramTypes.length; i++) {
lvtIndex[i] = nextIndex;
if (isWideType(paramTypes[i])) {
nextIndex += 2;
} else {
nextIndex++;
}
}
return lvtIndex;
}
private static boolean isWideType(Type aType) {
// float is not a wide type
return (aType == Type.LONG_TYPE || aType == Type.DOUBLE_TYPE);
}
}
|
ClassLoader loader = this.clazz.getClassLoader();
Class<?>[] argTypes = new Class<?>[this.args.length];
for (int i = 0; i < this.args.length; i++) {
argTypes[i] = ClassUtils.resolveClassName(this.args[i].getClassName(), loader);
}
try {
if (CONSTRUCTOR.equals(this.name)) {
return this.clazz.getDeclaredConstructor(argTypes);
}
return this.clazz.getDeclaredMethod(this.name, argTypes);
} catch (NoSuchMethodException ex) {
throw new IllegalStateException(
"Method ["
+ this.name
+ "] was discovered in the .class file but cannot be resolved in the class object",
ex);
}
| 762
| 210
| 972
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot/src/main/java/com/alipay/sofa/boot/startup/StartupReporterBeanPostProcessor.java
|
StartupReporterBeanPostProcessor
|
postProcessBeforeInitialization
|
class StartupReporterBeanPostProcessor implements BeanPostProcessor {
private final StartupReporter startupReporter;
public StartupReporterBeanPostProcessor(StartupReporter startupReporter) {
this.startupReporter = startupReporter;
}
@Override
@Nullable
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {<FILL_FUNCTION_BODY>}
}
|
if (bean instanceof StartupReporterAware) {
((StartupReporterAware) bean).setStartupReporter(startupReporter);
}
return bean;
| 113
| 48
| 161
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot/src/main/java/com/alipay/sofa/boot/startup/StartupSmartLifecycle.java
|
StartupSmartLifecycle
|
start
|
class StartupSmartLifecycle implements SmartLifecycle, ApplicationContextAware {
public static final String ROOT_MODULE_NAME = "ROOT_APPLICATION_CONTEXT";
private final StartupReporter startupReporter;
private ConfigurableApplicationContext applicationContext;
public StartupSmartLifecycle(StartupReporter startupReporter) {
this.startupReporter = startupReporter;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = (ConfigurableApplicationContext) applicationContext;
}
@Override
public void start() {<FILL_FUNCTION_BODY>}
@Override
public void stop() {
}
@Override
public boolean isRunning() {
return false;
}
@Override
public int getPhase() {
return Integer.MIN_VALUE;
}
}
|
// init ContextRefreshStageStat
ChildrenStat<ModuleStat> stat = new ChildrenStat<>();
stat.setName(APPLICATION_CONTEXT_REFRESH_STAGE);
stat.setEndTime(System.currentTimeMillis());
// build root ModuleStat
ModuleStat rootModuleStat = new ModuleStat();
rootModuleStat.setName(ROOT_MODULE_NAME);
rootModuleStat.setEndTime(stat.getEndTime());
rootModuleStat.setThreadName(Thread.currentThread().getName());
// getBeanStatList from ApplicationStartup
rootModuleStat.setChildren(startupReporter.generateBeanStats(applicationContext));
// report ContextRefreshStageStat
stat.addChild(rootModuleStat);
startupReporter.addCommonStartupStat(stat);
| 242
| 202
| 444
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot/src/main/java/com/alipay/sofa/boot/startup/StartupSpringApplication.java
|
StartupSpringApplication
|
applyInitializers
|
class StartupSpringApplication extends SpringApplication {
private final List<BaseStat> initializerStartupStatList = new ArrayList<>();
public StartupSpringApplication(Class<?>... primarySources) {
super(primarySources);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
protected void applyInitializers(ConfigurableApplicationContext context) {<FILL_FUNCTION_BODY>}
public List<BaseStat> getInitializerStartupStatList() {
return initializerStartupStatList;
}
}
|
for (ApplicationContextInitializer initializer : getInitializers()) {
Class<?> requiredType = GenericTypeResolver.resolveTypeArgument(initializer.getClass(),
ApplicationContextInitializer.class);
if (requiredType != null) {
Assert.isInstanceOf(requiredType, context, "Unable to call initializer.");
BaseStat stat = new BaseStat();
stat.setName(initializer.getClass().getName());
stat.setStartTime(System.currentTimeMillis());
initializer.initialize(context);
stat.setEndTime(System.currentTimeMillis());
initializerStartupStatList.add(stat);
}
}
| 146
| 168
| 314
|
<methods>public transient void <init>(Class<?>[]) ,public transient void <init>(org.springframework.core.io.ResourceLoader, Class<?>[]) ,public void addBootstrapRegistryInitializer(org.springframework.boot.BootstrapRegistryInitializer) ,public transient void addInitializers(ApplicationContextInitializer<?>[]) ,public transient void addListeners(ApplicationListener<?>[]) ,public void addPrimarySources(Collection<Class<?>>) ,public static transient int exit(org.springframework.context.ApplicationContext, org.springframework.boot.ExitCodeGenerator[]) ,public static org.springframework.boot.SpringApplication.Augmented from(ThrowingConsumer<java.lang.String[]>) ,public Set<java.lang.String> getAdditionalProfiles() ,public Set<java.lang.Object> getAllSources() ,public org.springframework.core.metrics.ApplicationStartup getApplicationStartup() ,public java.lang.ClassLoader getClassLoader() ,public java.lang.String getEnvironmentPrefix() ,public Set<ApplicationContextInitializer<?>> getInitializers() ,public Set<ApplicationListener<?>> getListeners() ,public Class<?> getMainApplicationClass() ,public org.springframework.core.io.ResourceLoader getResourceLoader() ,public static org.springframework.boot.SpringApplicationShutdownHandlers getShutdownHandlers() ,public Set<java.lang.String> getSources() ,public org.springframework.boot.WebApplicationType getWebApplicationType() ,public boolean isKeepAlive() ,public static void main(java.lang.String[]) throws java.lang.Exception,public transient org.springframework.context.ConfigurableApplicationContext run(java.lang.String[]) ,public static transient org.springframework.context.ConfigurableApplicationContext run(Class<?>, java.lang.String[]) ,public static org.springframework.context.ConfigurableApplicationContext run(Class<?>[], java.lang.String[]) ,public void setAddCommandLineProperties(boolean) ,public void setAddConversionService(boolean) ,public transient void setAdditionalProfiles(java.lang.String[]) ,public void setAllowBeanDefinitionOverriding(boolean) ,public void setAllowCircularReferences(boolean) ,public void setApplicationContextFactory(org.springframework.boot.ApplicationContextFactory) ,public void setApplicationStartup(org.springframework.core.metrics.ApplicationStartup) ,public void setBanner(org.springframework.boot.Banner) ,public void setBannerMode(org.springframework.boot.Banner.Mode) ,public void setBeanNameGenerator(org.springframework.beans.factory.support.BeanNameGenerator) ,public void setDefaultProperties(Map<java.lang.String,java.lang.Object>) ,public void setDefaultProperties(java.util.Properties) ,public void setEnvironment(org.springframework.core.env.ConfigurableEnvironment) ,public void setEnvironmentPrefix(java.lang.String) ,public void setHeadless(boolean) ,public void setInitializers(Collection<? extends ApplicationContextInitializer<?>>) ,public void setKeepAlive(boolean) ,public void setLazyInitialization(boolean) ,public void setListeners(Collection<? extends ApplicationListener<?>>) ,public void setLogStartupInfo(boolean) ,public void setMainApplicationClass(Class<?>) ,public void setRegisterShutdownHook(boolean) ,public void setResourceLoader(org.springframework.core.io.ResourceLoader) ,public void setSources(Set<java.lang.String>) ,public void setWebApplicationType(org.springframework.boot.WebApplicationType) ,public static void withHook(org.springframework.boot.SpringApplicationHook, java.lang.Runnable) ,public static T withHook(org.springframework.boot.SpringApplicationHook, ThrowingSupplier<T>) <variables>public static final java.lang.String BANNER_LOCATION_PROPERTY,public static final java.lang.String BANNER_LOCATION_PROPERTY_VALUE,private static final java.lang.String SYSTEM_PROPERTY_JAVA_AWT_HEADLESS,private boolean addCommandLineProperties,private boolean addConversionService,private Set<java.lang.String> additionalProfiles,private boolean allowBeanDefinitionOverriding,private boolean allowCircularReferences,private org.springframework.boot.ApplicationContextFactory applicationContextFactory,private static final ThreadLocal<org.springframework.boot.SpringApplicationHook> applicationHook,private org.springframework.core.metrics.ApplicationStartup applicationStartup,private org.springframework.boot.Banner banner,private org.springframework.boot.Banner.Mode bannerMode,private org.springframework.beans.factory.support.BeanNameGenerator beanNameGenerator,private final List<org.springframework.boot.BootstrapRegistryInitializer> bootstrapRegistryInitializers,private Map<java.lang.String,java.lang.Object> defaultProperties,private org.springframework.core.env.ConfigurableEnvironment environment,private java.lang.String environmentPrefix,private boolean headless,private List<ApplicationContextInitializer<?>> initializers,private boolean isCustomEnvironment,private boolean keepAlive,private boolean lazyInitialization,private List<ApplicationListener<?>> listeners,private boolean logStartupInfo,private static final org.apache.commons.logging.Log logger,private Class<?> mainApplicationClass,private final Set<Class<?>> primarySources,private boolean registerShutdownHook,private org.springframework.core.io.ResourceLoader resourceLoader,static final org.springframework.boot.SpringApplicationShutdownHook shutdownHook,private Set<java.lang.String> sources,private org.springframework.boot.WebApplicationType webApplicationType
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot/src/main/java/com/alipay/sofa/boot/startup/StartupSpringApplicationRunListener.java
|
StartupSpringApplicationRunListener
|
environmentPrepared
|
class StartupSpringApplicationRunListener implements SpringApplicationRunListener, Ordered {
private final SpringApplication application;
private final String[] args;
private final StartupReporter startupReporter;
private final ApplicationStartup userApplicationStartup;
private BufferingApplicationStartup applicationStartup;
private BaseStat jvmStartingStage;
private BaseStat environmentPrepareStage;
private ChildrenStat<BaseStat> applicationContextPrepareStage;
private BaseStat applicationContextLoadStage;
public StartupSpringApplicationRunListener(SpringApplication springApplication, String[] args) {
this.application = springApplication;
this.args = args;
this.startupReporter = new StartupReporter();
this.userApplicationStartup = springApplication.getApplicationStartup();
}
@Override
public void starting(ConfigurableBootstrapContext bootstrapContext) {
jvmStartingStage = new BaseStat();
jvmStartingStage.setName(BootStageConstants.JVM_STARTING_STAGE);
jvmStartingStage.setStartTime(ManagementFactory.getRuntimeMXBean().getStartTime());
jvmStartingStage.setEndTime(System.currentTimeMillis());
}
@Override
public void environmentPrepared(ConfigurableBootstrapContext bootstrapContext,
ConfigurableEnvironment environment) {<FILL_FUNCTION_BODY>}
@Override
public void contextPrepared(ConfigurableApplicationContext context) {
applicationContextPrepareStage = new ChildrenStat<>();
applicationContextPrepareStage
.setName(BootStageConstants.APPLICATION_CONTEXT_PREPARE_STAGE);
applicationContextPrepareStage.setStartTime(environmentPrepareStage.getEndTime());
applicationContextPrepareStage.setEndTime(System.currentTimeMillis());
if (application instanceof StartupSpringApplication startupSpringApplication) {
List<BaseStat> baseStatList = startupSpringApplication.getInitializerStartupStatList();
applicationContextPrepareStage.setChildren(new ArrayList<>(baseStatList));
baseStatList.clear();
}
if (applicationStartup != null) {
context.setApplicationStartup(applicationStartup);
}
}
@Override
public void contextLoaded(ConfigurableApplicationContext context) {
applicationContextLoadStage = new BaseStat();
applicationContextLoadStage.setName(BootStageConstants.APPLICATION_CONTEXT_LOAD_STAGE);
applicationContextLoadStage.setStartTime(applicationContextPrepareStage.getEndTime());
applicationContextLoadStage.setEndTime(System.currentTimeMillis());
context.getBeanFactory().addBeanPostProcessor(
new StartupReporterBeanPostProcessor(startupReporter));
context.getBeanFactory().registerSingleton("STARTUP_REPORTER_BEAN", startupReporter);
StartupSmartLifecycle startupSmartLifecycle = new StartupSmartLifecycle(startupReporter);
startupSmartLifecycle.setApplicationContext(context);
context.getBeanFactory().registerSingleton("STARTUP_SMART_LIfE_CYCLE",
startupSmartLifecycle);
}
@Override
public void started(ConfigurableApplicationContext context, Duration timeTaken) {
// refresh applicationRefreshStage
ChildrenStat<ModuleStat> applicationRefreshStage = (ChildrenStat<ModuleStat>) startupReporter
.getStageNyName(BootStageConstants.APPLICATION_CONTEXT_REFRESH_STAGE);
applicationRefreshStage.setStartTime(applicationContextLoadStage.getEndTime());
applicationRefreshStage.setCost(applicationRefreshStage.getEndTime()
- applicationRefreshStage.getStartTime());
// init rootModuleStat
ModuleStat rootModule = applicationRefreshStage.getChildren().get(0);
rootModule.setStartTime(applicationRefreshStage.getStartTime());
rootModule.setCost(rootModule.getEndTime() - rootModule.getStartTime());
// report all stage
startupReporter.addCommonStartupStat(jvmStartingStage);
startupReporter.addCommonStartupStat(environmentPrepareStage);
startupReporter.addCommonStartupStat(applicationContextPrepareStage);
startupReporter.addCommonStartupStat(applicationContextLoadStage);
startupReporter.applicationBootFinish();
SofaBootLoggerFactory.getLogger(StartupSpringApplicationRunListener.class).info(
getStartedMessage(context.getEnvironment(), timeTaken));
}
@Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
private String getStartedMessage(Environment environment, Duration timeTakenToStartup) {
StringBuilder message = new StringBuilder();
message.append("Started ");
message.append(environment.getProperty(SofaBootConstants.APP_NAME_KEY));
String startupLogExtraInfo = environment
.getProperty(SofaBootConstants.STARTUP_LOG_EXTRA_INFO);
if (StringUtils.hasText(startupLogExtraInfo)) {
message.append(" with extra info [");
message.append(startupLogExtraInfo);
message.append("]");
}
message.append(" in ");
message.append(timeTakenToStartup.toMillis() / 1000.0);
message.append(" seconds");
return message.toString();
}
}
|
environmentPrepareStage = new BaseStat();
environmentPrepareStage.setName(BootStageConstants.ENVIRONMENT_PREPARE_STAGE);
environmentPrepareStage.setStartTime(jvmStartingStage.getEndTime());
environmentPrepareStage.setEndTime(System.currentTimeMillis());
startupReporter.setAppName(environment.getProperty(SofaBootConstants.APP_NAME_KEY));
startupReporter.bindToStartupReporter(environment);
// create BufferingApplicationStartup if user not custom.
if (ApplicationStartup.DEFAULT == userApplicationStartup || userApplicationStartup == null) {
this.applicationStartup = new BufferingApplicationStartup(startupReporter.getBufferSize());
} else if (userApplicationStartup instanceof BufferingApplicationStartup userApplicationStartup) {
// use user custom BufferingApplicationStartup
this.applicationStartup = userApplicationStartup;
} else {
// disable startup static when user custom other type ApplicationStartup;
this.applicationStartup = null;
}
| 1,418
| 272
| 1,690
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot/src/main/java/com/alipay/sofa/boot/util/BeanDefinitionUtil.java
|
BeanDefinitionUtil
|
resolveBeanClassType
|
class BeanDefinitionUtil {
/**
* {@link AnnotatedGenericBeanDefinition}
* {@link ScannedGenericBeanDefinition}
* {@link GenericBeanDefinition}
* {@link org.springframework.beans.factory.support.ChildBeanDefinition}
* {@link org.springframework.beans.factory.support.RootBeanDefinition}
*
* @param beanDefinition resolve bean class type from bean definition
* @return class for bean definition, could be null.
*/
public static Class<?> resolveBeanClassType(BeanDefinition beanDefinition) {<FILL_FUNCTION_BODY>}
/**
* @param beanDefinition Check whether it is a bean definition created from a configuration class
* as opposed to any other configuration source.
* @return
*/
public static boolean isFromConfigurationSource(BeanDefinition beanDefinition) {
return beanDefinition
.getClass()
.getCanonicalName()
.startsWith(
"org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader");
}
}
|
Class<?> clazz = null;
if (beanDefinition instanceof AnnotatedBeanDefinition) {
String className;
if (isFromConfigurationSource(beanDefinition)) {
MethodMetadata methodMetadata = ((AnnotatedBeanDefinition) beanDefinition)
.getFactoryMethodMetadata();
className = methodMetadata.getReturnTypeName();
} else {
AnnotationMetadata annotationMetadata = ((AnnotatedBeanDefinition) beanDefinition)
.getMetadata();
className = annotationMetadata.getClassName();
}
try {
if (StringUtils.hasText(className)) {
clazz = ClassUtils.forName(className, null);
}
} catch (Throwable throwable) {
// ignore
}
}
if (clazz == null) {
try {
clazz = ((AbstractBeanDefinition) beanDefinition).getBeanClass();
} catch (IllegalStateException ex) {
try {
String className = beanDefinition.getBeanClassName();
if (StringUtils.hasText(className)) {
clazz = ClassUtils.forName(className, null);
}
} catch (Throwable throwable) {
// ignore
}
}
}
if (clazz == null) {
if (beanDefinition instanceof RootBeanDefinition) {
clazz = ((RootBeanDefinition) beanDefinition).getTargetType();
}
}
if (ClassUtils.isCglibProxyClass(clazz)) {
return clazz.getSuperclass();
} else {
return clazz;
}
| 254
| 389
| 643
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot/src/main/java/com/alipay/sofa/boot/util/ClassLoaderContextUtils.java
|
ClassLoaderContextUtils
|
callWithTemporaryContextClassloader
|
class ClassLoaderContextUtils {
/**
* Store thread context classloader then use new classloader to invoke runnable,
* finally reset thread context classloader.
* @param runnable runnable to invoke
* @param newClassloader classloader used to invoke runnable
*/
public static void runWithTemporaryContextClassloader(Runnable runnable,
ClassLoader newClassloader) {
ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(newClassloader);
try {
runnable.run();
} finally {
Thread.currentThread().setContextClassLoader(oldClassLoader);
}
}
/**
* Store thread context classloader then use new classloader to invoke callable,
* finally reset thread context classloader.
* @param callable callable to invoke
* @param newClassloader classloader used to invoke callable
*/
public static <T> T callWithTemporaryContextClassloader(Callable<T> callable,
ClassLoader newClassloader) {<FILL_FUNCTION_BODY>}
}
|
ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(newClassloader);
try {
return callable.call();
} catch (Exception e) {
throw new RuntimeException("Failed to invoke callable", e);
} finally {
Thread.currentThread().setContextClassLoader(oldClassLoader);
}
| 284
| 97
| 381
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot/src/main/java/com/alipay/sofa/boot/util/SmartAnnotationUtils.java
|
SmartAnnotationUtils
|
getAnnotations
|
class SmartAnnotationUtils {
/**
* 使用 {@link MergedAnnotations.SearchStrategy#TYPE_HIERARCHY} 搜索策略获取最近的注解集合
* <p> 如果元素上无注解,返回空的集合
* <p> 如果元素上仅有一个注解,返回包含该注解的集合
* <p> 如果元素上有多个注解,通过 {@link MergedAnnotations#get(Class)} 方法拿到最近的注解,返回的集合仅包含最近的注解所在元素上的注解
*
* @param element 注解所在元素
* @param annotationType 注解类
* @param <T> 注解类型
* @return 注解集合,可能为空或者多个,如果存在多个注解,仅保留最高优先级元素上的注解
*/
public static <T extends Annotation> Collection<T> getAnnotations(AnnotatedElement element,
Class<T> annotationType) {
return getAnnotations(element, annotationType,
MergedAnnotations.SearchStrategy.TYPE_HIERARCHY);
}
/**
* 使用指定搜索策略获取最近的注解集合
* <p> 如果元素上无注解,返回空的集合
* <p> 如果元素上仅有一个注解,返回包含该注解的集合
* <p> 如果元素上有多个注解,通过 {@link MergedAnnotations#get(Class)} 方法拿到最近的注解,返回的集合仅包含最近的注解所在元素上的注解
*
* @param element 注解所在元素
* @param annotationType 注解类
* @param searchStrategy 搜索策略
* @param <T> 注解类型
* @return 注解集合,可能为空或者多个,如果存在多个注解,仅保留最高优先级元素上的注解
*/
public static <T extends Annotation> Collection<T> getAnnotations(AnnotatedElement element, Class<T> annotationType,
MergedAnnotations.SearchStrategy searchStrategy) {<FILL_FUNCTION_BODY>}
}
|
MergedAnnotations annotations = MergedAnnotations.from(element, searchStrategy);
List<T> sofaServiceList = annotations.stream(annotationType).map(MergedAnnotation::synthesize).collect(Collectors.toList());
if (sofaServiceList.size() > 1) {
// 如果存在多个注解,先通过 get 方法拿到最高优先级的注解所在的 element
Object source = annotations.get(annotationType).getSource();
// 排除非最高优先级 element 以外的注解
return annotations.stream(annotationType)
.filter(annotation -> Objects.equals(annotation.getSource(), source))
.map(MergedAnnotation::synthesize).collect(Collectors.toList());
} else {
// 如果不存在注解或者只有一个注解,直接返回
return sofaServiceList;
}
| 537
| 222
| 759
|
<no_super_class>
|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot/src/main/java/com/alipay/sofa/boot/util/SofaBootEnvUtils.java
|
SofaBootEnvUtils
|
initLocalEnv
|
class SofaBootEnvUtils {
/**
* Property name for bootstrap configuration class name.
*/
public static final String CLOUD_BOOTSTRAP_CONFIGURATION_CLASS = "org.springframework.cloud.bootstrap.BootstrapConfiguration";
/**
* Boolean if bootstrap configuration class exists.
*/
public static final boolean CLOUD_BOOTSTRAP_CONFIGURATION_CLASS_EXISTS = ClassUtils
.isPresent(
CLOUD_BOOTSTRAP_CONFIGURATION_CLASS,
null);
/**
* Property source name for bootstrap.
*/
public static final String BOOTSTRAP_PROPERTY_SOURCE_NAME = "bootstrap";
public static final String LOCAL_ENV_KEY = "sofa.boot.useLocalEnv";
public static final String INTELLIJ_IDE_MAIN_CLASS = "com.intellij.rt.execution.application.AppMainV2";
private static final String ARK_BIZ_CLASSLOADER_NAME = "com.alipay.sofa.ark.container.service.classloader.BizClassLoader";
private static boolean LOCAL_ENV = false;
private static boolean TEST_ENV = false;
static {
initLocalEnv();
initSpringTestEnv();
}
private static void initSpringTestEnv() {
// Detection of test environment
StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
for (StackTraceElement stackTraceElement : stackTrace) {
if ("loadContext".equals(stackTraceElement.getMethodName())
&& "org.springframework.boot.test.context.SpringBootContextLoader"
.equals(stackTraceElement.getClassName())) {
TEST_ENV = true;
break;
}
}
}
private static void initLocalEnv() {<FILL_FUNCTION_BODY>}
/**
* Determine whether the {@link org.springframework.core.env.Environment} is Spring Cloud bootstrap environment.
*
* Reference doc is https://cloud.spring.io/spring-cloud-static/spring-cloud.html#_application_context_hierarchies and
* issue https://github.com/spring-cloud/spring-cloud-config/issues/1151.
*
* Pay attention only can be used in one implementation which implements {@link ApplicationContextInitializer} because the bootstrap
* properties will be removed after initialized.
*
* @param environment the environment get from spring context
* @return true indicates Spring Cloud environment
*/
public static boolean isSpringCloudBootstrapEnvironment(Environment environment) {
if (environment != null && isSpringCloudEnvironmentEnabled(environment)) {
return ((ConfigurableEnvironment) environment).getPropertySources().contains(
BOOTSTRAP_PROPERTY_SOURCE_NAME);
} else {
return false;
}
}
/**
* Check whether spring cloud Bootstrap environment enabled
* @return true indicates spring cloud Bootstrap environment enabled
*/
public static boolean isSpringCloudEnvironmentEnabled(Environment environment) {
return CLOUD_BOOTSTRAP_CONFIGURATION_CLASS_EXISTS
&& PropertyUtils.bootstrapEnabled(environment);
}
/**
* Check whether import spring cloud BootstrapConfiguration
* @return true indicates spring cloud BootstrapConfiguration is imported
*/
public static boolean isSpringCloud() {
return CLOUD_BOOTSTRAP_CONFIGURATION_CLASS_EXISTS;
}
/**
* Check whether running in spring test environment
* @return true indicates in spring test environment
*/
public static boolean isSpringTestEnv() {
return TEST_ENV;
}
/**
* Check whether running in local development environment
* @return true indicates in local development environment
*/
public static boolean isLocalEnv() {
return LOCAL_ENV;
}
/**
* Check whether running in sofa ark environment
* @return true indicates in sofa ark environment
*/
public static boolean isArkEnv() {
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
return contextClassLoader != null
&& ARK_BIZ_CLASSLOADER_NAME.equals(contextClassLoader.getClass().getName());
}
}
|
if (Boolean.getBoolean(LOCAL_ENV_KEY)) {
LOCAL_ENV = true;
return;
}
try {
Class.forName(INTELLIJ_IDE_MAIN_CLASS);
LOCAL_ENV = true;
} catch (ClassNotFoundException e) {
LOCAL_ENV = false;
}
| 1,084
| 92
| 1,176
|
<no_super_class>
|
noear_solon
|
solon/__hatch/solon.boot.reactor-netty/src/main/java/org/noear/solon/boot/reactornetty/HttpRequestParser.java
|
HttpRequestParser
|
parse
|
class HttpRequestParser {
private final DefaultFullHttpRequest _request;
protected final Map<String, List<String>> parmMap = new HashMap<>();
protected final Map<String, List<UploadedFile>> fileMap = new HashMap<>();
public HttpRequestParser(DefaultFullHttpRequest req) {
_request = req;
}
protected HttpRequestParser parse() throws Exception {<FILL_FUNCTION_BODY>}
}
|
HttpMethod method = _request.method();
// url 参数
if (_request.uri().indexOf("?") > 0) {
QueryStringDecoder decoder = new QueryStringDecoder(_request.uri());
decoder.parameters().entrySet().forEach(entry -> {
parmMap.put(entry.getKey(), entry.getValue());
});
}
// body
if (HttpMethod.POST == method
|| HttpMethod.PUT == method
|| HttpMethod.DELETE == method
|| HttpMethod.PATCH == method) {
HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(_request);
decoder.offer(_request);
List<InterfaceHttpData> parmList = decoder.getBodyHttpDatas();
for (InterfaceHttpData p1 : parmList) {
if (p1.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) {
//参数
//
Attribute a1 = (Attribute) p1;
List<String> tmp = parmMap.get(a1.getName());
if (tmp == null) {
tmp = new ArrayList<>();
parmMap.put(a1.getName(), tmp);
}
tmp.add(a1.getValue());
continue;
}
if (p1.getHttpDataType() == InterfaceHttpData.HttpDataType.FileUpload) {
//文件
//
FileUpload f0 = (FileUpload) p1;
List<UploadedFile> tmp = fileMap.get(p1.getName());
if (tmp == null) {
tmp = new ArrayList<>();
fileMap.put(p1.getName(), tmp);
}
String contentType = f0.getContentType();
InputStream content = new FileInputStream(f0.getFile());
int contentSize = content.available();
String name = f0.getFilename();
String extension = null;
int idx = name.lastIndexOf(".");
if (idx > 0) {
extension = name.substring(idx + 1);
}
UploadedFile f1 = new UploadedFile(f0::delete, contentType, contentSize, content, name, extension);
tmp.add(f1);
}
}
}
return this;
| 112
| 586
| 698
|
<no_super_class>
|
noear_solon
|
solon/__hatch/solon.boot.reactor-netty/src/main/java/org/noear/solon/boot/reactornetty/RnHttpContext.java
|
RnHttpContext
|
cookieSet
|
class RnHttpContext extends WebContextBase {
private final HttpServerRequest _request;
private final HttpServerResponse _response;
private final HttpRequestParser _request_parse;
public RnHttpContext(HttpServerRequest request, HttpServerResponse response, HttpRequestParser request_parse) {
_request = request;
_response = response;
try {
_request_parse = request_parse.parse();
}catch (Exception ex){
throw new RuntimeException(ex);
}
}
@Override
public Object request() {
return _request;
}
@Override
public String remoteIp() {
return _request.remoteAddress().getAddress().getHostAddress();
}
@Override
public int remotePort() {
return _request.remoteAddress().getPort();
}
@Override
public String method() {
return _request.method().name();
}
@Override
public String protocol() {
return _request.version().protocolName();
}
private URI _uri;
@Override
public URI uri() {
if(_uri == null){
_uri = URI.create(url());
}
return _uri;
}
@Override
public boolean isSecure() {
return "https".equals(uri().getScheme());
}
private String _url;
@Override
public String url() {
if (_url == null) {
_url = _request.uri();
if (_url != null && _url.startsWith("/")) {
_url = _request.scheme()+"://" + header("Host") + _url;
}
}
return _url;
}
@Override
public long contentLength() {
return _request.receiveContent().count().block();
}
@Override
public String contentType() {
return header("Content-Type");
}
@Override
public String queryString() {
return null;
}
@Override
public InputStream bodyAsStream() throws IOException {
return _request.receive().asInputStream().blockFirst();
}
private NvMap _paramMap;
@Override
public NvMap paramMap() {
if(_paramMap == null){
_paramMap = new NvMap();
_request_parse.parmMap.forEach((k,l)->{
if(l.size() > 0){
_paramMap.put(k,l.get(0));
}
});
}
return _paramMap;
}
@Override
public Map<String, List<String>> paramsMap() {
return _request_parse.parmMap;
}
@Override
public Map<String, List<UploadedFile>> filesMap() throws IOException {
return _request_parse.fileMap;
}
private NvMap _cookieMap;
@Override
public NvMap cookieMap() {
if(_cookieMap == null){
_cookieMap = new NvMap();
String _cookieMapStr = _request.requestHeaders().get(COOKIE);
if (_cookieMapStr != null) {
Set<Cookie> tmp = ServerCookieDecoder.LAX.decode(_cookieMapStr);
for(Cookie c1 :tmp){
_cookieMap.put(c1.name(),c1.value());
}
}
}
return _cookieMap;
}
private NvMap _headerMap;
@Override
public NvMap headerMap() {
if(_headerMap == null) {
_headerMap = new NvMap();
HttpHeaders headers = _request.requestHeaders();
for(Map.Entry<String, String> kv : headers){
_headerMap.put(kv.getKey(), kv.getValue());
}
}
return _headerMap;
}
private Map<String, List<String>> _headersMap;
@Override
public Map<String, List<String>> headersMap() {
if (_headersMap == null) {
_headersMap = new IgnoreCaseMap<>();
HttpHeaders headers = _request.requestHeaders();
for (Map.Entry<String, String> kv : headers) {
List<String> values = _headersMap.get(kv.getKey());
if (values == null) {
values = new ArrayList<>();
_headersMap.put(kv.getKey(), values);
}
values.add(kv.getValue());
}
}
return _headersMap;
}
@Override
public Object response() {
return _response;
}
@Override
protected void contentTypeDoSet(String contentType) {
if (charset != null) {
if (contentType.indexOf(";") < 0) {
headerSet("Content-Type", contentType + ";charset=" + charset);
return;
}
}
headerSet("Content-Type", contentType);
}
@Override
public OutputStream outputStream() throws IOException{
return _outputStream;
}
@Override
public void output(byte[] bytes) {
try {
OutputStream out = outputStream();
out.write(bytes);
}catch (Throwable ex){
throw new RuntimeException(ex);
}
}
@Override
public void output(InputStream stream) {
try {
OutputStream out = outputStream();
IoUtil.transferTo(stream, out);
}catch (Throwable ex){
throw new RuntimeException(ex);
}
}
protected ByteBufOutputStream _outputStream = new ByteBufOutputStream(Unpooled.buffer());
@Override
public void headerSet(String key, String val) {
_response.header(key,val);
}
@Override
public void headerAdd(String key, String val) {
_response.addHeader(key,val);
}
@Override
public String headerOfResponse(String name) {
return null;
}
@Override
public void cookieSet(String key, String val, String domain, String path, int maxAge) {<FILL_FUNCTION_BODY>}
@Override
public void redirect(String url, int code) {
url = RedirectUtils.getRedirectPath(url);
headerSet(Constants.HEADER_LOCATION, url);
statusDoSet(code);
}
@Override
public int status() {
return _status;
}
private int _status = 200;
@Override
protected void statusDoSet(int status) {
_status = status;
_response.status(status);
}
@Override
public void flush() throws IOException {
//不用实现
}
@Override
public void close() throws IOException {
}
@Override
public boolean asyncSupported() {
return false;
}
@Override
public void asyncStart(long timeout, ContextAsyncListener listener) {
throw new UnsupportedOperationException();
}
@Override
public void asyncComplete() {
throw new UnsupportedOperationException();
}
}
|
StringBuilder sb = new StringBuilder();
sb.append(key).append("=").append(val).append(";");
if (Utils.isNotEmpty(path)) {
sb.append("path=").append(path).append(";");
}
if (maxAge >= 0) {
sb.append("max-age=").append(maxAge).append(";");
}
if (Utils.isNotEmpty(domain)) {
sb.append("domain=").append(domain.toLowerCase()).append(";");
}
_response.addHeader(SET_COOKIE, sb.toString());
| 1,851
| 160
| 2,011
|
<methods>public non-sealed void <init>() ,public java.lang.String contentCharset() ,public java.lang.String contentType() ,public void filesDelete() throws java.io.IOException,public void outputAsFile(org.noear.solon.core.handle.DownloadedFile) throws java.io.IOException,public void outputAsFile(java.io.File) throws java.io.IOException,public final T session(java.lang.String, Class<T>) ,public final double sessionAsDouble(java.lang.String) ,public final double sessionAsDouble(java.lang.String, double) ,public final int sessionAsInt(java.lang.String) ,public final int sessionAsInt(java.lang.String, int) ,public final long sessionAsLong(java.lang.String) ,public final long sessionAsLong(java.lang.String, long) ,public final void sessionClear() ,public final java.lang.String sessionId() ,public final T sessionOrDefault(java.lang.String, T) ,public final void sessionRemove(java.lang.String) ,public final void sessionSet(java.lang.String, java.lang.Object) <variables>protected Map<java.lang.String,List<org.noear.solon.core.handle.UploadedFile>> _filesMap,private java.lang.String contentCharset
|
noear_solon
|
solon/__hatch/solon.boot.reactor-netty/src/main/java/org/noear/solon/boot/reactornetty/RnHttpHandler.java
|
RnHttpHandler
|
apply
|
class RnHttpHandler implements BiFunction<HttpServerRequest, HttpServerResponse, Publisher<Void>> {
@Override
public Publisher<Void> apply(HttpServerRequest request, HttpServerResponse response) {<FILL_FUNCTION_BODY>}
protected ByteBuf applyDo(HttpServerRequest request, HttpServerResponse response, ByteBuf byteBuf){
DefaultFullHttpRequest req = new DefaultFullHttpRequest(
request.version(),
request.method(),
request.uri(),
byteBuf,
request.requestHeaders(),
EmptyHttpHeaders.INSTANCE);
return applyDo(request,response, new HttpRequestParser(req));
}
protected ByteBuf applyDo(HttpServerRequest request, HttpServerResponse response, HttpRequestParser parser) {
RnHttpContext ctx = new RnHttpContext(request, response, parser);
ctx.contentType("text/plain;charset=UTF-8");//默认
if (ServerProps.output_meta) {
ctx.headerSet("Solon-Boot", XPluginImp.solon_boot_ver());
}
Solon.app().tryHandle(ctx);
if (ctx.status() == 404) {
return null; //response.sendNotFound();
} else {
return ctx._outputStream.buffer();//response.send(Mono.just(context._outputStream.buffer())).neverComplete();
}
}
}
|
List<ByteBuf> ary = new ArrayList<>();
request.receive().aggregate().map(m->{
ary.add(m);
return m;
}).subscribe().dispose();
// Mono<ByteBuf> mono = request.receive()
// .aggregate()
// .map(byteBuf -> applyDo(request, response,byteBuf));
return response.send(Mono.just(applyDo(request, response, ary.get(0))));
// ByteBufAllocator bba = ((HttpOperations) request).alloc();
//
//
// return applyDo(request, response, new HttpRequestParser(req));
| 354
| 178
| 532
|
<no_super_class>
|
noear_solon
|
solon/__hatch/solon.boot.reactor-netty/src/main/java/org/noear/solon/boot/reactornetty/XPluginImp.java
|
XPluginImp
|
start0
|
class XPluginImp implements Plugin {
DisposableServer _server = null;
public static String solon_boot_ver() {
return "reactor-netty-http 1.0.20/" + Solon.version();
}
@Override
public void start(AppContext context) {
if (Solon.app().enableHttp() == false) {
return;
}
new Thread(() -> {
start0(Solon.app());
});
}
private void start0(SolonApp app) {<FILL_FUNCTION_BODY>}
@Override
public void stop() throws Throwable {
if (_server != null) {
_server.dispose();
_server = null;
LogUtil.global().info("Server:main: reactor-netty-http: Has Stopped (" + solon_boot_ver() + ")");
}
}
}
|
long time_start = System.currentTimeMillis();
try {
RnHttpHandler handler = new RnHttpHandler();
//
// https://projectreactor.io/docs/netty/release/reference/index.html#_starting_and_stopping_2
//
_server = HttpServer.create()
.compress(true)
.protocol(HttpProtocol.HTTP11)
.port(app.cfg().serverPort())
.handle(handler)
.bindNow();
_server.onDispose()
.block();
long time_end = System.currentTimeMillis();
LogUtil.global().info("Connector:main: reactor-netty-http: Started ServerConnector@{HTTP/1.1,[http/1.1]}{http://localhost:" + app.cfg().serverPort() + "}");
LogUtil.global().info("Server:main: reactor-netty-http: Started (" + solon_boot_ver() + ") @" + (time_end - time_start) + "ms");
} catch (Throwable ex) {
throw new RuntimeException(ex);
}
| 239
| 292
| 531
|
<no_super_class>
|
noear_solon
|
solon/__hatch/solon.serialization.avro/src/main/java/org/noear/solon/serialization/avro/AvroSerializer.java
|
AvroSerializer
|
serialize
|
class AvroSerializer implements StringSerializer {
@Override
public String serialize(Object obj) throws IOException {<FILL_FUNCTION_BODY>}
}
|
DatumWriter datumWriter = new SpecificDatumWriter(obj.getClass());
ByteArrayOutputStream out = new ByteArrayOutputStream();
BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(out, null);
datumWriter.write(obj, encoder);
return out.toString();
| 40
| 79
| 119
|
<no_super_class>
|
noear_solon
|
solon/__hatch/solon.serialization.avro/src/main/java/org/noear/solon/serialization/avro/XPluginImp.java
|
XPluginImp
|
start
|
class XPluginImp implements Plugin {
public static boolean output_meta = false;
@Override
public void start(AppContext context) {<FILL_FUNCTION_BODY>}
}
|
output_meta = Solon.cfg().getInt("solon.output.meta", 0) > 0;
//RenderManager.register(render);
RenderManager.mapping("@avro", new AvroStringRender());
| 51
| 59
| 110
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-breaker/guava-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/guava/impl/CloudBreakerEntryImpl.java
|
CloudBreakerEntryImpl
|
enter
|
class CloudBreakerEntryImpl extends BreakerEntrySim {
RateLimiter limiter;
int thresholdValue;
public CloudBreakerEntryImpl(int permitsPerSecond) {
this.thresholdValue = permitsPerSecond;
loadRules();
}
private void loadRules(){
limiter = RateLimiter.create(thresholdValue);
}
@Override
public AutoCloseable enter() throws BreakerException {<FILL_FUNCTION_BODY>}
@Override
public void reset(int value) {
if(thresholdValue != value){
thresholdValue = value;
loadRules();
}
}
}
|
if (limiter.tryAcquire()) {
return this;
} else {
throw new BreakerException();
}
| 172
| 36
| 208
|
<methods>public non-sealed void <init>() ,public abstract void reset(int) <variables>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-breaker/semaphore-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/semaphore/impl/CloudBreakerEntryImpl.java
|
CloudBreakerEntryImpl
|
enter
|
class CloudBreakerEntryImpl extends BreakerEntrySim {
String breakerName;
int thresholdValue;
Semaphore limiter;
public CloudBreakerEntryImpl(String breakerName, int permits) {
this.breakerName = breakerName;
this.thresholdValue = permits;
this.limiter = new Semaphore(permits);
}
@Override
public AutoCloseable enter() throws BreakerException {<FILL_FUNCTION_BODY>}
@Override
public void close() throws Exception {
limiter.release();
}
@Override
public void reset(int value) {
if (thresholdValue != value) {
thresholdValue = value;
limiter = new Semaphore(value);
}
}
}
|
if (limiter.tryAcquire()) {
return this;
} else {
throw new BreakerException();
}
| 202
| 36
| 238
|
<methods>public non-sealed void <init>() ,public abstract void reset(int) <variables>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-breaker/sentinel-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/sentinel/impl/CloudBreakerEntryImpl.java
|
CloudBreakerEntryImpl
|
loadRules
|
class CloudBreakerEntryImpl extends BreakerEntrySim {
String breakerName;
int thresholdValue;
public CloudBreakerEntryImpl(String breakerName, int permits) {
this.breakerName = breakerName;
this.thresholdValue = permits;
loadRules();
}
private void loadRules(){<FILL_FUNCTION_BODY>}
@Override
public AutoCloseable enter() throws BreakerException {
try {
return SphU.entry(breakerName);
} catch (BlockException ex) {
throw new BreakerException(ex);
}
}
@Override
public void reset(int value) {
if(thresholdValue != value){
thresholdValue = value;
loadRules();
}
}
}
|
List<FlowRule> ruleList = new ArrayList<>();
FlowRule rule = null;
rule = new FlowRule();
rule.setResource(breakerName);
rule.setGrade(RuleConstant.FLOW_GRADE_QPS); //qps
rule.setCount(thresholdValue);
ruleList.add(rule);
rule = new FlowRule();
rule.setResource(breakerName);
rule.setGrade(RuleConstant.FLOW_GRADE_THREAD); //并发数
rule.setCount(thresholdValue);
ruleList.add(rule);
FlowRuleManager.loadRules(ruleList);
| 207
| 168
| 375
|
<methods>public non-sealed void <init>() ,public abstract void reset(int) <variables>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-config/kubernetes-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/kubernetes/XPluginImp.java
|
XPluginImp
|
start
|
class XPluginImp implements Plugin {
private Timer clientTimer = new Timer();
/*
https://support.huaweicloud.com/sdkreference-cci/cci_09_0004.html
https://github.com/kubernetes-client/java/wiki/3.-Code-Examples
*/
@Override
public void start(AppContext context) {<FILL_FUNCTION_BODY>}
}
|
CloudProps cloudProps = new CloudProps(context, "kubernetes");
if (Utils.isEmpty(cloudProps.getServer())) {
return;
}
//1.登记配置服务
if (cloudProps.getConfigEnable()) {
CloudConfigServiceK8sImpl serviceImp = new CloudConfigServiceK8sImpl(cloudProps);
CloudManager.register(serviceImp);
if (serviceImp.getRefreshInterval() > 0) {
long interval = serviceImp.getRefreshInterval();
clientTimer.schedule(serviceImp, interval, interval);
}
//1.1.加载配置
CloudClient.configLoad(cloudProps.getConfigLoad());
}
| 115
| 181
| 296
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-config/kubernetes-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/kubernetes/service/CloudConfigServiceK8sImpl.java
|
CloudConfigServiceK8sImpl
|
pull
|
class CloudConfigServiceK8sImpl extends TimerTask implements CloudConfigService {
final ApiClient client;
final CoreV1Api configApi;
private long refreshInterval;
public CloudConfigServiceK8sImpl(CloudProps cloudProps) {
try {
client = ClientBuilder.defaultClient();
configApi = new CoreV1Api(client);
refreshInterval = IntervalUtils.getInterval(cloudProps.getConfigRefreshInterval("5s"));
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
public long getRefreshInterval() {
return refreshInterval;
}
@Override
public Config pull(String group, String name) {<FILL_FUNCTION_BODY>}
@Override
public boolean push(String group, String name, String value) {
return false;
}
@Override
public boolean remove(String group, String name) {
return false;
}
@Override
public void attention(String group, String name, CloudConfigHandler observer) {
}
@Override
public void run() {
}
}
|
try {
V1ConfigMap v1ConfigMap = configApi.readNamespacedConfigMap(name, group, null);
if(v1ConfigMap == null){
return null;
}
StringBuilder kvs = new StringBuilder();
v1ConfigMap.getData().forEach((k, v) -> {
kvs.append(k).append("=").append(v).append("\n");
});
return new Config(group, name, kvs.toString(), 0);
} catch (Exception e) {
throw new IllegalStateException(e);
}
| 290
| 150
| 440
|
<methods>public boolean cancel() ,public abstract void run() ,public long scheduledExecutionTime() <variables>static final int CANCELLED,static final int EXECUTED,static final int SCHEDULED,static final int VIRGIN,final java.lang.Object lock,long nextExecutionTime,long period,int state
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-discovery/jmdns-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/jmdns/XPluginImp.java
|
XPluginImp
|
start
|
class XPluginImp implements Plugin {
CloudDiscoveryServiceJmdnsImpl discoveryServiceJmdnsImpl;
@Override
public void start(AppContext context) {<FILL_FUNCTION_BODY>}
@Override
public void stop() throws IOException {
if (discoveryServiceJmdnsImpl != null) {
discoveryServiceJmdnsImpl.close();
}
}
}
|
CloudProps cloudProps = new CloudProps(context, "jmdns");
if (Utils.isEmpty(cloudProps.getServer())) {
return;
}
if (cloudProps.getDiscoveryEnable()) {
discoveryServiceJmdnsImpl = new CloudDiscoveryServiceJmdnsImpl(cloudProps);
CloudManager.register(discoveryServiceJmdnsImpl);
}
| 104
| 98
| 202
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-discovery/jmdns-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/jmdns/service/CloudDiscoveryServiceJmdnsImpl.java
|
CloudDiscoveryServiceJmdnsImpl
|
attention
|
class CloudDiscoveryServiceJmdnsImpl implements CloudDiscoveryService {
/**
* solon 作为固定前缀,区分其他使用 JmDNS 应用
*/
public static final String PREFIX = "solon";
/**
* 服务所属域,使用 local 表示通过 mDNS 在局域网广播从而实现服务发现,其他值则涉及全局DNS服务器
*/
public static final String DOMAIN = "local";
/**
* JmDNS 实例
*/
JmDNS jmDNS;
/**
* 寻找服务超时时间,单位 ms
* <p>偶尔会因为网络无法正常找到服务,需要重试</p>
*/
private static final long RETRY_LIMIT_TIME = 5000;
public CloudDiscoveryServiceJmdnsImpl(CloudProps cloudProps) {
try {
String server = cloudProps.getServer().split(":")[0];
InetAddress jmDNSAddress = "localhost".equals(server) ?
InetAddress.getLocalHost() : InetAddress.getByName(server);
jmDNS = JmDNS.create(jmDNSAddress,
jmDNSAddress.toString(), // jmdns 实例名称,意义不大
IntervalUtils.getInterval(cloudProps.getDiscoveryRefreshInterval("100ms"))); // 由于依靠DNS多播,太长会导致服务难以发现
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public void register(String group, Instance instance) {
registerState(group, instance, true);
}
@Override
public void registerState(String group, Instance instance, boolean health) {
int priority = (int) (10 - instance.weight() % 10); // 只取个位和十分位作为权重和优先级,优先级越小越优先
int weight = (int) ((instance.weight()*10) % 10); // 权重越大越优先
Map<String, String> props = new HashMap<>();
props.put(instance.address(), ONode.stringify(instance));
ServiceInfo serviceInfo = ServiceInfo.create(
getType(group),
instance.address(),
instance.service(),
Integer.parseInt(instance.address().split(":")[1]),
weight,
priority,
false,
props);
if (health) {
try {
jmDNS.registerService(serviceInfo);
} catch (IOException e) {
throw new RuntimeException(e);
}
} else {
jmDNS.unregisterService(serviceInfo);
}
}
@Override
public void deregister(String group, Instance instance) {
registerState(group, instance, false);
}
@Override
public Discovery find(String group, String service) {
if (Utils.isEmpty(group)) {
group = Solon.cfg().appGroup();
}
ServiceInfo[] serviceInfos = getServiceInfos(group, service);
Discovery discovery = new Discovery(service);
for (ServiceInfo serviceInfo: serviceInfos) {
// 单个服务器上可有多个 ip:port 提供服务,通常只有一个
Enumeration<String> nodeKeyList = serviceInfo.getPropertyNames();
while (nodeKeyList.hasMoreElements()) {
Instance instance = ONode.deserialize(serviceInfo.getPropertyString(nodeKeyList.nextElement()),
Instance.class);
discovery.instanceAdd(instance);
}
}
return discovery;
}
@Override
public void attention(String group, String service, CloudDiscoveryHandler observer) {<FILL_FUNCTION_BODY>}
/**
* 关闭
*/
public void close() throws IOException {
if (jmDNS != null) {
jmDNS.close();
}
}
/**
* 限时重试
*/
private ServiceInfo[] getServiceInfos(String group, String service) {
String type = getType(group);
ServiceInfo[] serviceInfos = null;
long begin = System.currentTimeMillis();
while (Utils.isEmpty(serviceInfos) && System.currentTimeMillis()-begin < RETRY_LIMIT_TIME) {
serviceInfos = jmDNS.listBySubtype(type).get(service);
}
return serviceInfos;
}
/**
* 组合成 type
*/
private String getType(String group) {
return String.format("_%s._%s.%s.", group, PREFIX, DOMAIN);
}
}
|
if (Utils.isEmpty(group)) {
group = Solon.cfg().appGroup();
}
CloudDiscoveryObserverEntity entity = new CloudDiscoveryObserverEntity(group, service, observer);
Consumer<ServiceEvent> handle = event -> {
Discovery discovery = find(entity.group, service);
entity.handle(discovery);
};
jmDNS.addServiceListener(getType(group), new ServiceListener() {
@Override
public void serviceAdded(ServiceEvent event) {
handle.accept(event);
}
@Override
public void serviceRemoved(ServiceEvent event) {
handle.accept(event);
}
@Override
public void serviceResolved(ServiceEvent event) {
handle.accept(event);
}
});
| 1,216
| 202
| 1,418
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/activemq-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/activemq/ActivemqProps.java
|
ActivemqProps
|
getTopicNew
|
class ActivemqProps {
public static final String GROUP_SPLIT_MARK = ":";
public static String getTopicNew(Event event){<FILL_FUNCTION_BODY>}
}
|
//new topic
String topicNew;
if (Utils.isEmpty(event.group())) {
topicNew = event.topic();
} else {
topicNew = event.group() + ActivemqProps.GROUP_SPLIT_MARK + event.topic();
}
return topicNew;
| 54
| 79
| 133
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/activemq-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/activemq/XPluginImp.java
|
XPluginImp
|
start
|
class XPluginImp implements Plugin {
@Override
public void start(AppContext context) throws Throwable {<FILL_FUNCTION_BODY>}
}
|
CloudProps cloudProps = new CloudProps(context,"activemq");
if (Utils.isEmpty(cloudProps.getEventServer())) {
return;
}
if (cloudProps.getEventEnable()) {
CloudEventServiceActivemqImp eventServiceImp = new CloudEventServiceActivemqImp(cloudProps);
CloudManager.register(eventServiceImp);
context.lifecycle(-99, () -> eventServiceImp.subscribe());
}
| 43
| 124
| 167
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/activemq-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/activemq/impl/ActivemqConsumeHandler.java
|
ActivemqConsumeHandler
|
onReceiveDo
|
class ActivemqConsumeHandler implements MessageListener {
static final Logger log = LoggerFactory.getLogger(ActivemqConsumeHandler.class);
private CloudEventObserverManger observerManger;
private Session session;
public ActivemqConsumeHandler(CloudEventObserverManger observerManger, Session session) {
super();
this.observerManger = observerManger;
this.session = session;
}
@Override
public void onMessage(Message message) {
ActiveMQTextMessage textmsg = (ActiveMQTextMessage) message;
try {
Event event = ONode.deserialize(textmsg.getText(), Event.class);
event.times(textmsg.getRedeliveryCounter());
//已设置自动延时策略
boolean isOk = onReceive(event);
if(isOk){
textmsg.acknowledge();
}else{
session.recover();
}
} catch (Throwable e) {
e = Utils.throwableUnwrap(e);
log.warn(e.getMessage(), e); //todo: ?
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
} else {
throw new RuntimeException(e);
}
}
}
/**
* 处理接收事件(会吃掉异常)
* */
private boolean onReceive(Event event) throws Throwable {
try {
return onReceiveDo(event);
} catch (Throwable e) {
log.warn(e.getMessage(), e);
return false;
}
}
/**
* 处理接收事件
*/
private boolean onReceiveDo(Event event) throws Throwable {<FILL_FUNCTION_BODY>}
private String getTopicNew(Event event){
return ActivemqProps.getTopicNew(event);
}
}
|
boolean isOk = true;
CloudEventHandler handler = null;
//new topic
String topicNew = getTopicNew(event);
handler = observerManger.getByTopic(topicNew);
if (handler != null) {
isOk = handler.handle(event);
} else {
//只需要记录一下
log.warn("There is no observer for this event topic[{}]", topicNew);
}
return isOk;
| 484
| 120
| 604
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/activemq-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/activemq/impl/ActivemqConsumer.java
|
ActivemqConsumer
|
init
|
class ActivemqConsumer {
static Logger log = LoggerFactory.getLogger(ActivemqConsumer.class);
private ActiveMQConnectionFactory factory;
private ActivemqProducer producer;
private Connection connection;
private ActivemqConsumeHandler handler;
public ActivemqConsumer(ActiveMQConnectionFactory factory, ActivemqProducer producer) {
this.factory = factory;
this.producer = producer;
}
public void init(CloudEventObserverManger observerManger) throws JMSException {<FILL_FUNCTION_BODY>}
public void close() throws JMSException {
if (connection != null) {
connection.close();
}
}
}
|
if (connection != null) {
return;
}
connection = factory.createConnection();
connection.start();
//创建会话
Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
handler = new ActivemqConsumeHandler(observerManger, session);
//订阅所有主题
for (String topic : observerManger.topicAll()) {
//创建一个目标
Destination destination = session.createTopic(topic);
//创建一个消费者
MessageConsumer consumer = session.createConsumer(destination);
consumer.setMessageListener(handler);
}
| 170
| 169
| 339
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/activemq-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/activemq/impl/ActivemqProducer.java
|
ActivemqProducer
|
init
|
class ActivemqProducer {
static Logger log = LoggerFactory.getLogger(ActivemqProducer.class);
private ActiveMQConnectionFactory factory;
private Connection connection;
public ActivemqProducer(ActiveMQConnectionFactory factory) {
this.factory = factory;
}
private void init() throws JMSException {<FILL_FUNCTION_BODY>}
private void close() throws JMSException {
if (connection != null) {
connection.close();
}
}
/**
* 发布事件
*/
public boolean publish(Event event, String topic) throws Exception {
init();
long delay = 0;
if (event.scheduled() != null) {
delay = event.scheduled().getTime() - System.currentTimeMillis();
}
if (delay > 0) {
return publish(event, topic, delay);
} else {
return publish(event, topic, 0);
}
}
public boolean publish(Event event, String topic, long delay) throws JMSException {
//创建会话
Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
//创建一个目标
Destination destination = session.createTopic(topic);
//创建一个生产者
MessageProducer producer = session.createProducer(destination);
//创建消息
TextMessage message = session.createTextMessage(ONode.stringify(event));
//支持延时消息
if (delay > 0) {
message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, delay);
}
//发布消息
try {
producer.send(destination, message);
return true;
} catch (JMSException e) {
log.error(e.getMessage(), e);
return false;
}
}
}
|
if (connection == null) {
synchronized (factory) {
if (connection == null) {
connection = factory.createConnection();
connection.start();
}
}
}
| 482
| 56
| 538
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/activemq-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/activemq/service/CloudEventServiceActivemqImp.java
|
CloudEventServiceActivemqImp
|
publish
|
class CloudEventServiceActivemqImp implements CloudEventServicePlus {
static Logger log = LoggerFactory.getLogger(CloudEventServiceActivemqImp.class);
private CloudProps cloudProps;
private ActivemqProducer producer;
private ActivemqConsumer consumer;
public CloudEventServiceActivemqImp(CloudProps cloudProps) {
this.cloudProps = cloudProps;
ActiveMQConnectionFactory factory = null;
String brokerUrl = cloudProps.getEventServer();
if (brokerUrl.indexOf("://") < 0) {
brokerUrl = "tcp://" + brokerUrl;
}
String username = cloudProps.getUsername();
String password = cloudProps.getPassword();
if (Utils.isEmpty(cloudProps.getUsername())) {
factory = new ActiveMQConnectionFactory(brokerUrl);
} else {
factory = new ActiveMQConnectionFactory(username, password, brokerUrl);
}
//增加自动重发策略
RedeliveryPolicy redeliveryPolicy = new RedeliveryPolicy();
redeliveryPolicy.setInitialRedeliveryDelay(5000);//5s
redeliveryPolicy.setBackOffMultiplier(2);
redeliveryPolicy.setUseExponentialBackOff(true);
redeliveryPolicy.setMaximumRedeliveries(-1);//不限次
redeliveryPolicy.setMaximumRedeliveryDelay(1000 * 60 * 60 * 2);//2小时
factory.setRedeliveryPolicy(redeliveryPolicy);
producer = new ActivemqProducer(factory);
consumer = new ActivemqConsumer(factory, producer);
}
@Override
public boolean publish(Event event) throws CloudEventException {<FILL_FUNCTION_BODY>}
CloudEventObserverManger observerManger = new CloudEventObserverManger();
@Override
public void attention(EventLevel level, String channel, String group,
String topic, String tag, int qos, CloudEventHandler observer) {
//new topic
String topicNew;
if (Utils.isEmpty(group)) {
topicNew = topic;
} else {
topicNew = group + ActivemqProps.GROUP_SPLIT_MARK + topic;
}
observerManger.add(topicNew, level, group, topic, tag, qos, observer);
}
public void subscribe() {
if (observerManger.topicSize() > 0) {
try {
consumer.init(observerManger);
} catch (Throwable ex) {
throw new RuntimeException(ex);
}
}
}
private String channel;
private String group;
@Override
public String getChannel() {
if (channel == null) {
channel = cloudProps.getEventChannel();
}
return channel;
}
@Override
public String getGroup() {
if (group == null) {
group = cloudProps.getEventGroup();
}
return group;
}
}
|
if (Utils.isEmpty(event.topic())) {
throw new IllegalArgumentException("Event missing topic");
}
if (Utils.isEmpty(event.content())) {
throw new IllegalArgumentException("Event missing content");
}
if (Utils.isEmpty(event.key())) {
event.key(Utils.guid());
}
//new topic
String topicNew = ActivemqProps.getTopicNew(event);
try {
boolean re = producer.publish(event, topicNew);
return re;
} catch (Throwable ex) {
throw new CloudEventException(ex);
}
| 767
| 157
| 924
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/aliyun-ons-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/aliyun/ons/XPluginImp.java
|
XPluginImp
|
start
|
class XPluginImp implements Plugin {
@Override
public void start(AppContext context) {<FILL_FUNCTION_BODY>}
}
|
CloudProps cloudProps = new CloudProps(context,"aliyun.ons");
if (Utils.isEmpty(cloudProps.getEventServer())) {
return;
}
if (cloudProps.getEventEnable()) {
CloudEventServiceOnsImp eventServiceImp = new CloudEventServiceOnsImp(cloudProps);
CloudManager.register(eventServiceImp);
context.lifecycle(-99, () -> eventServiceImp.subscribe());
}
| 39
| 123
| 162
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/aliyun-ons-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/aliyun/ons/impl/OnsConfig.java
|
OnsConfig
|
getConsumerProperties
|
class OnsConfig {
static final Logger log = LoggerFactory.getLogger(OnsConfig.class);
private static final String PROP_EVENT_consumerGroup = "event.consumerGroup";
private static final String PROP_EVENT_producerGroup = "event.producerGroup";
private static final String PROP_EVENT_consumeThreadNums = "event.consumeThreadNums";
private static final String PROP_EVENT_maxReconsumeTimes = "event.maxReconsumeTimes";
private final String channelName;
private final String server;
private final String accessKey;
private final String secretKey;
private final long timeout;
private String producerGroup;
private String consumerGroup;
//实例的消费线程数,0表示默认
private final int consumeThreadNums;
//设置消息消费失败的最大重试次数,0表示默认
private final int maxReconsumeTimes;
public OnsConfig(CloudProps cloudProps) {
server = cloudProps.getEventServer();
channelName = cloudProps.getEventChannel();
accessKey = cloudProps.getEventAccessKey();
secretKey = cloudProps.getEventSecretKey();
timeout = cloudProps.getEventPublishTimeout();
consumeThreadNums = Integer.valueOf(cloudProps.getValue(PROP_EVENT_consumeThreadNums, "0"));
maxReconsumeTimes = Integer.valueOf(cloudProps.getValue(PROP_EVENT_maxReconsumeTimes, "0"));
producerGroup = cloudProps.getValue(PROP_EVENT_producerGroup);
consumerGroup = cloudProps.getValue(PROP_EVENT_consumerGroup);
if (Utils.isEmpty(producerGroup)) {
producerGroup = "DEFAULT";
}
if (Utils.isEmpty(consumerGroup)) {
consumerGroup = Solon.cfg().appGroup() + "_" + Solon.cfg().appName();
}
log.trace("producerGroup=" + producerGroup);
log.trace("consumerGroup=" + consumerGroup);
}
public String getChannelName() {
return channelName;
}
public Properties getProducerProperties() {
Properties producer = getBaseProperties();
producer.put(PropertyKeyConst.GROUP_ID, producerGroup);
producer.put(PropertyKeyConst.SendMsgTimeoutMillis, timeout);
return producer;
}
public Properties getConsumerProperties() {<FILL_FUNCTION_BODY>}
public Properties getBaseProperties() {
Properties properties = new Properties();
if (Utils.isNotEmpty(accessKey)) {
properties.put(PropertyKeyConst.AccessKey, accessKey);
}
if (Utils.isNotEmpty(secretKey)) {
properties.put(PropertyKeyConst.SecretKey, secretKey);
}
properties.put(PropertyKeyConst.NAMESRV_ADDR, server);
return properties;
}
}
|
Properties consumer = getBaseProperties();
consumer.put(PropertyKeyConst.GROUP_ID, consumerGroup);
//只能是集群模式
consumer.put(PropertyKeyConst.MessageModel, PropertyValueConst.CLUSTERING);
//实例的消费线程数
if (consumeThreadNums > 0) {
consumer.put(PropertyKeyConst.ConsumeThreadNums, consumeThreadNums);
}
//设置消息消费失败的最大重试次数
if (maxReconsumeTimes > 0) {
consumer.put(PropertyKeyConst.MaxReconsumeTimes, maxReconsumeTimes);
}
return consumer;
| 737
| 162
| 899
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/aliyun-ons-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/aliyun/ons/impl/OnsConsumer.java
|
OnsConsumer
|
init
|
class OnsConsumer {
static Logger log = LoggerFactory.getLogger(OnsConsumer.class);
private OnsConfig config;
private ConsumerBean consumer;
public OnsConsumer(OnsConfig config) {
this.config = config;
}
public void init(CloudProps cloudProps, CloudEventObserverManger observerManger) {<FILL_FUNCTION_BODY>}
}
|
if (consumer != null) {
return;
}
Utils.locker().lock();
try {
if (consumer != null) {
return;
}
consumer = new ConsumerBean();
consumer.setProperties(config.getConsumerProperties());
OnsConsumerHandler handler = new OnsConsumerHandler(config, observerManger);
Map<Subscription, MessageListener> subscriptionTable = new HashMap<>();
for (Map.Entry<String, Set<String>> kv : observerManger.topicTags().entrySet()) {
String topic = kv.getKey();
Set<String> tags = kv.getValue();
String tagsExpr = String.join("||", tags);
Subscription subscription = new Subscription();
subscription.setTopic(topic);
if (tags.contains("*")) {
subscription.setExpression("*");
} else {
subscription.setExpression(tagsExpr);
}
subscriptionTable.put(subscription, handler);
log.trace("Ons consumer subscribe [" + topic + "(" + tagsExpr + ")] ok!");
}
consumer.setSubscriptionTable(subscriptionTable);
consumer.start();
if (consumer.isStarted()) {
log.trace("Ons consumer started!");
} else {
log.warn("Ons consumer start failure!");
}
} finally {
Utils.locker().unlock();
}
| 104
| 369
| 473
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/aliyun-ons-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/aliyun/ons/impl/OnsConsumerHandler.java
|
OnsConsumerHandler
|
consume
|
class OnsConsumerHandler implements MessageListener {
static final Logger log = LoggerFactory.getLogger(OnsConsumerHandler.class);
private CloudEventObserverManger observerManger;
private OnsConfig config;
public OnsConsumerHandler(OnsConfig config, CloudEventObserverManger observerManger) {
this.observerManger = observerManger;
this.config = config;
}
@Override
public Action consume(Message message, ConsumeContext consumeContext) {<FILL_FUNCTION_BODY>}
/**
* 处理接收事件
*/
protected boolean onReceive(Event event, String topicNew) throws Throwable {
boolean isOk = true;
CloudEventHandler handler = null;
if (Utils.isEmpty(event.tags())) {
handler = observerManger.getByTopicAndTag(topicNew, "*");
} else {
handler = observerManger.getByTopicAndTag(topicNew, event.tags());
if (handler == null) {
handler = observerManger.getByTopicAndTag(topicNew, "*");
}
}
if (handler != null) {
isOk = handler.handle(event);
} else {
//只需要记录一下
log.warn("There is no observer for this event topic[{}]", topicNew);
}
return isOk;
}
}
|
boolean isOk = true;
try {
String topicNew = message.getTopic();
String group = null;
String topic = null;
if (topicNew.contains(OnsProps.GROUP_SPLIT_MARK)) {
group = topicNew.split(OnsProps.GROUP_SPLIT_MARK)[0];
topic = topicNew.split(OnsProps.GROUP_SPLIT_MARK)[1];
} else {
topic = topicNew;
}
Event event = new Event(topic, new String(message.getBody()));
event.key(message.getKey());
event.tags(message.getTag());
event.times(message.getReconsumeTimes());
event.channel(config.getChannelName());
if (Utils.isNotEmpty(group)) {
event.group(group);
}
isOk = isOk && onReceive(event, topicNew);
} catch (Throwable e) {
isOk = false;
log.warn(e.getMessage(), e);
}
if (isOk) {
return Action.CommitMessage;
} else {
return Action.ReconsumeLater;
}
| 357
| 306
| 663
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/aliyun-ons-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/aliyun/ons/impl/OnsProducer.java
|
OnsProducer
|
init
|
class OnsProducer {
static Logger log = LoggerFactory.getLogger(OnsProducer.class);
OnsConfig config;
Producer producer;
public OnsProducer(OnsConfig config) {
this.config = config;
}
private void init() {<FILL_FUNCTION_BODY>}
public boolean publish(Event event, String topic) {
init();
//普通消息发送。
Message message = MessageUtil.buildNewMessage(event, topic);
//发送消息,需要关注发送结果,并捕获失败等异常。
SendResult sendReceipt = producer.send(message);
if (sendReceipt != null) {
return true;
} else {
return false;
}
}
}
|
if (producer != null) {
return;
}
Utils.locker().lock();
try {
if (producer != null) {
return;
}
producer = ONSFactory.createProducer(config.getProducerProperties());
producer.start();
log.debug("Ons producer started: " + producer.isStarted());
} finally {
Utils.locker().unlock();
}
| 201
| 119
| 320
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/aliyun-ons-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/aliyun/ons/service/CloudEventServiceOnsImp.java
|
CloudEventServiceOnsImp
|
publish
|
class CloudEventServiceOnsImp implements CloudEventServicePlus {
private CloudProps cloudProps;
private OnsProducer producer;
private OnsConsumer consumer;
public CloudEventServiceOnsImp(CloudProps cloudProps) {
this.cloudProps = cloudProps;
OnsConfig config = new OnsConfig(cloudProps);
producer = new OnsProducer(config);
consumer = new OnsConsumer(config);
}
@Override
public boolean publish(Event event) throws CloudEventException {<FILL_FUNCTION_BODY>}
CloudEventObserverManger observerManger = new CloudEventObserverManger();
@Override
public void attention(EventLevel level, String channel, String group, String topic, String tag, int qos, CloudEventHandler observer) {
topic = topic.replace(".", "_");
//new topic
String topicNew;
if (Utils.isEmpty(group)) {
topicNew = topic;
} else {
topicNew = group + OnsProps.GROUP_SPLIT_MARK + topic;
}
if (Utils.isEmpty(tag)) {
tag = "*";
}
observerManger.add(topicNew, level, group, topic, tag, qos, observer);
}
public void subscribe() {
if (observerManger.topicSize() > 0) {
consumer.init(cloudProps, observerManger);
}
}
private String channel;
private String group;
@Override
public String getChannel() {
if (channel == null) {
channel = cloudProps.getEventChannel();
}
return channel;
}
@Override
public String getGroup() {
if (group == null) {
group = cloudProps.getEventGroup();
}
return group;
}
}
|
if (Utils.isEmpty(event.topic())) {
throw new IllegalArgumentException("Event missing topic");
}
if (Utils.isEmpty(event.content())) {
throw new IllegalArgumentException("Event missing content");
}
if (Utils.isEmpty(event.key())) {
event.key(Utils.guid());
}
//new topic
String topicNew;
if (Utils.isEmpty(event.group())) {
topicNew = event.topic();
} else {
topicNew = event.group() + OnsProps.GROUP_SPLIT_MARK + event.topic();
}
topicNew = topicNew.replace(".", "_");
try {
return producer.publish(event, topicNew);
} catch (Throwable ex) {
throw new CloudEventException(ex);
}
| 467
| 210
| 677
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/folkmq-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/folkmq/FolkmqProps.java
|
FolkmqProps
|
getTopicNew
|
class FolkmqProps {
public static final String GROUP_SPLIT_MARK = ":";
public static String getTopicNew(Event event){<FILL_FUNCTION_BODY>}
}
|
//new topic
String topicNew;
if (Utils.isEmpty(event.group())) {
topicNew = event.topic();
} else {
topicNew = event.group() + FolkmqProps.GROUP_SPLIT_MARK + event.topic();
}
return topicNew;
| 54
| 79
| 133
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/folkmq-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/folkmq/XPluginImpl.java
|
XPluginImpl
|
start
|
class XPluginImpl implements Plugin {
@Override
public void start(AppContext context) throws Throwable {<FILL_FUNCTION_BODY>}
}
|
CloudProps cloudProps = new CloudProps(context,"folkmq");
if (Utils.isEmpty(cloudProps.getEventServer())) {
return;
}
if (cloudProps.getEventEnable()) {
CloudEventServiceFolkMqImpl eventServiceImp = new CloudEventServiceFolkMqImpl(cloudProps);
CloudManager.register(eventServiceImp);
context.lifecycle(-99, () -> eventServiceImp.subscribe());
}
| 42
| 123
| 165
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/folkmq-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/folkmq/impl/FolkmqConsumeHandler.java
|
FolkmqConsumeHandler
|
onReceiveDo
|
class FolkmqConsumeHandler implements MqConsumeHandler {
static final Logger log = LoggerFactory.getLogger(FolkmqConsumeHandler.class);
private CloudEventObserverManger observerManger;
public FolkmqConsumeHandler(CloudEventObserverManger observerManger) {
this.observerManger = observerManger;
}
@Override
public void consume(MqMessageReceived message) throws IOException {
try {
Event event = new Event(message.getTopic(), message.getContent());
event.key(message.getTid());
event.times(message.getTimes());
event.tags(message.getTag());
//已设置自动延时策略
boolean isOk = onReceive(event);
message.acknowledge(isOk);
} catch (Throwable e) {
message.acknowledge(false);
e = Utils.throwableUnwrap(e);
log.warn(e.getMessage(), e); //todo: ?
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
} else {
throw new RuntimeException(e);
}
}
}
/**
* 处理接收事件(会吃掉异常)
*/
private boolean onReceive(Event event) throws Throwable {
try {
return onReceiveDo(event);
} catch (Throwable e) {
log.warn(e.getMessage(), e);
return false;
}
}
/**
* 处理接收事件
*/
private boolean onReceiveDo(Event event) throws Throwable {<FILL_FUNCTION_BODY>}
private String getTopicNew(Event event) {
return FolkmqProps.getTopicNew(event);
}
}
|
boolean isOk = true;
CloudEventHandler handler = null;
//new topic
String topicNew = getTopicNew(event);
handler = observerManger.getByTopic(topicNew);
if (handler != null) {
isOk = handler.handle(event);
} else {
//只需要记录一下
log.warn("There is no observer for this event topic[{}]", topicNew);
}
return isOk;
| 460
| 120
| 580
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/folkmq-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/folkmq/service/CloudEventServiceFolkMqImpl.java
|
CloudEventServiceFolkMqImpl
|
subscribe
|
class CloudEventServiceFolkMqImpl implements CloudEventServicePlus {
protected final MqClient client;
private final CloudProps cloudProps;
private final FolkmqConsumeHandler folkmqConsumeHandler;
private final CloudEventObserverManger observerManger;
private final long publishTimeout;
public CloudEventServiceFolkMqImpl(CloudProps cloudProps) {
this.cloudProps = cloudProps;
this.observerManger = new CloudEventObserverManger();
this.folkmqConsumeHandler = new FolkmqConsumeHandler(observerManger);
this.publishTimeout = cloudProps.getEventPublishTimeout();
this.client = FolkMQ.createClient(cloudProps.getEventServer())
.nameAs(Solon.cfg().appName())
.autoAcknowledge(false);
if (publishTimeout > 0) {
client.config(c -> c.requestTimeout(publishTimeout));
}
//总线扩展
EventBus.publish(client);
//加入容器
Solon.context().wrapAndPut(MqClient.class, client);
//异步获取 MqTransactionCheckback
Solon.context().getBeanAsync(MqTransactionCheckback.class, bean->{
client.transactionCheckback(bean);
});
Solon.context().getBeanAsync(MqConsumeListener.class, bean->{
client.listen(bean);
});
try {
client.connect();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public boolean publish(Event event) throws CloudEventException {
if (Utils.isEmpty(event.topic())) {
throw new IllegalArgumentException("Event missing topic");
}
if (Utils.isEmpty(event.content())) {
throw new IllegalArgumentException("Event missing content");
}
//new topic
String topicNew = FolkmqProps.getTopicNew(event);
try {
MqMessage message = new MqMessage(event.content(), event.key())
.scheduled(event.scheduled())
.tag(event.tags())
.qos(event.qos());
if (publishTimeout > 0) {
//同步
client.publish(topicNew, message);
} else {
//异步
client.publishAsync(topicNew, message);
}
} catch (Throwable ex) {
throw new CloudEventException(ex);
}
return true;
}
@Override
public void attention(EventLevel level, String channel, String group,
String topic, String tag, int qos, CloudEventHandler observer) {
//new topic
String topicNew;
if (Utils.isEmpty(group)) {
topicNew = topic;
} else {
topicNew = group + FolkmqProps.GROUP_SPLIT_MARK + topic;
}
observerManger.add(topicNew, level, group, topic, tag, qos, observer);
}
public void subscribe() throws IOException {<FILL_FUNCTION_BODY>}
private String channel;
private String group;
@Override
public String getChannel() {
if (channel == null) {
channel = cloudProps.getEventChannel();
}
return channel;
}
@Override
public String getGroup() {
if (group == null) {
group = cloudProps.getEventGroup();
}
return group;
}
}
|
if (observerManger.topicSize() > 0) {
Instance instance = Instance.local();
for (String topicNew : observerManger.topicAll()) {
client.subscribe(topicNew, instance.service(), folkmqConsumeHandler);
}
}
| 895
| 73
| 968
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/jedis-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/jedis/XPluginImp.java
|
XPluginImp
|
start
|
class XPluginImp implements Plugin {
@Override
public void start(AppContext context) {<FILL_FUNCTION_BODY>}
}
|
CloudProps cloudProps = new CloudProps(context,"jedis");
if (cloudProps.getLockEnable() && Utils.isNotEmpty(cloudProps.getLockServer())) {
CloudLockServiceJedisImpl lockServiceImp = new CloudLockServiceJedisImpl(cloudProps);
CloudManager.register(lockServiceImp);
}
if (cloudProps.getEventEnable() && Utils.isNotEmpty(cloudProps.getEventServer())) {
CloudEventServiceJedisImpl eventServiceImp = new CloudEventServiceJedisImpl(cloudProps);
CloudManager.register(eventServiceImp);
context.lifecycle(-99, () -> eventServiceImp.subscribe());
}
| 40
| 181
| 221
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/jedis-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/jedis/impl/JedisEventConsumer.java
|
JedisEventConsumer
|
onReceiveDo
|
class JedisEventConsumer extends JedisPubSub {
static final Logger log = LoggerFactory.getLogger(JedisEventConsumer.class);
CloudEventObserverManger observerManger;
String eventChannelName;
public JedisEventConsumer(CloudProps cloudProps, CloudEventObserverManger observerManger) {
this.observerManger = observerManger;
this.eventChannelName = cloudProps.getEventChannel();
}
@Override
public void onMessage(String channel, String message) {
try {
Event event = ONode.deserialize(message, Event.class);
event.channel(eventChannelName);
onReceive(event);
} catch (Throwable e) {
e = Utils.throwableUnwrap(e);
log.warn(e.getMessage(), e); //todo: ?
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
} else {
throw new RuntimeException(e);
}
}
}
private boolean onReceive(Event event) {
try {
return onReceiveDo(event);
} catch (Throwable e) {
log.warn(e.getMessage(), e);
return false;
}
}
/**
* 处理接收事件
*/
private boolean onReceiveDo(Event event) throws Throwable {<FILL_FUNCTION_BODY>}
}
|
boolean isOk = true;
CloudEventHandler handler = null;
//new topic
String topicNew;
if (Utils.isEmpty(event.group())) {
topicNew = event.topic();
} else {
topicNew = event.group() + JedisProps.GROUP_SPLIT_MARK + event.topic();
}
handler = observerManger.getByTopic(topicNew);
if (handler != null) {
isOk = handler.handle(event);
} else {
//只需要记录一下
log.warn("There is no observer for this event topic[{}]", topicNew);
}
return isOk;
| 363
| 171
| 534
|
<methods>public void <init>() <variables>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/jedis-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/jedis/service/CloudEventServiceJedisImpl.java
|
CloudEventServiceJedisImpl
|
publish
|
class CloudEventServiceJedisImpl implements CloudEventServicePlus {
private final RedisClient client;
private final CloudProps cloudProps;
public CloudEventServiceJedisImpl(CloudProps cloudProps) {
Props props = cloudProps.getProp("event");
if (props.get("server") == null) {
props.putIfNotNull("server", cloudProps.getServer());
}
if (props.get("user") == null) {
props.putIfNotNull("user", cloudProps.getUsername());
}
if (props.get("password") == null) {
props.putIfNotNull("password", cloudProps.getPassword());
}
this.client = new RedisClient(props);
this.cloudProps = cloudProps;
}
@Override
public boolean publish(Event event) throws CloudEventException {<FILL_FUNCTION_BODY>}
CloudEventObserverManger observerManger = new CloudEventObserverManger();
@Override
public void attention(EventLevel level, String channel, String group, String topic, String tag, int qos, CloudEventHandler observer) {
//new topic
String topicNew;
if (Utils.isEmpty(group)) {
topicNew = topic;
} else {
topicNew = group + JedisProps.GROUP_SPLIT_MARK + topic;
}
observerManger.add(topicNew, level, group, topic, tag, qos, observer);
}
public void subscribe() {
if (observerManger.topicSize() > 0) {
try {
String[] topicAll = new String[observerManger.topicAll().size()];
observerManger.topicAll().toArray(topicAll);
//用异步处理
new Thread(() -> {
client.open(s -> s.subscribe(new JedisEventConsumer(cloudProps, observerManger), topicAll));
}).start();
} catch (Throwable ex) {
throw new RuntimeException(ex);
}
}
}
@Override
public String getChannel() {
if (cloudProps == null) {
return null;
} else {
return cloudProps.getEventChannel();
}
}
@Override
public String getGroup() {
if (cloudProps == null) {
return null;
} else {
return cloudProps.getEventGroup();
}
}
}
|
if (Utils.isEmpty(event.topic())) {
throw new IllegalArgumentException("Event missing topic");
}
if (Utils.isEmpty(event.content())) {
throw new IllegalArgumentException("Event missing content");
}
if (Utils.isEmpty(event.key())) {
event.key(Utils.guid());
}
//new topic
String topicNew;
if (Utils.isEmpty(event.group())) {
topicNew = event.topic();
} else {
topicNew = event.group() + JedisProps.GROUP_SPLIT_MARK + event.topic();
}
client.open(s -> s.publish(topicNew, ONode.stringify(event)));
return true;
| 615
| 187
| 802
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/kafka-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/kafka/XPluginImpl.java
|
XPluginImpl
|
start
|
class XPluginImpl implements Plugin {
CloudEventServiceKafkaImpl eventServiceImpl;
@Override
public void start(AppContext context) {<FILL_FUNCTION_BODY>}
@Override
public void stop() throws Throwable {
if (eventServiceImpl != null) {
eventServiceImpl.close();
}
}
}
|
CloudProps cloudProps = new CloudProps(context, "kafka");
if (Utils.isEmpty(cloudProps.getEventServer())) {
return;
}
if (cloudProps.getEventEnable()) {
eventServiceImpl = new CloudEventServiceKafkaImpl(cloudProps);
CloudManager.register(eventServiceImpl);
context.lifecycle(-99, () -> eventServiceImpl.subscribe());
}
| 94
| 112
| 206
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/kafka-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/kafka/impl/KafkaConfig.java
|
KafkaConfig
|
getProducerProperties
|
class KafkaConfig {
private final CloudProps cloudProps;
private final String server;
private final long publishTimeout;
private final String eventChannel;
private final String eventGroup;
public long getPublishTimeout() {
return publishTimeout;
}
public String getEventChannel() {
return eventChannel;
}
public String getEventGroup() {
return eventGroup;
}
public KafkaConfig(CloudProps cloudProps){
this.cloudProps = cloudProps;
server = cloudProps.getEventServer();
publishTimeout = cloudProps.getEventPublishTimeout();
eventChannel = cloudProps.getEventChannel();
eventGroup = cloudProps.getEventGroup();
}
public Properties getProducerProperties() {<FILL_FUNCTION_BODY>}
public Properties getConsumerProperties() {
Properties properties = new Properties();
properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, server);
properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
properties.put(ConsumerConfig.GROUP_ID_CONFIG, Solon.cfg().appGroup() + "_" + Solon.cfg().appName());
properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
properties.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "30000");
properties.put(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG, 100);
properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
//绑定定制属性
Properties props = cloudProps.getEventConsumerProps();
if (props.size() > 0) {
props.forEach((k, v) -> {
properties.put(k, v);
});
}
return properties;
}
}
|
Properties properties = new Properties();
properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, server);
properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
//发送ack级别(最高了)
properties.put(ProducerConfig.ACKS_CONFIG, "all");
//重试次数
properties.put(ProducerConfig.RETRIES_CONFIG, 0);
properties.put(ProducerConfig.BATCH_SIZE_CONFIG, 16384); //默认是16384Bytes,即16kB
//绑定定制属性
Properties props = cloudProps.getEventProducerProps();
if (props.size() > 0) {
props.forEach((k, v) -> {
properties.put(k, v);
});
}
return properties;
| 515
| 258
| 773
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/kafka-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/kafka/service/CloudEventServiceKafkaImpl.java
|
CloudEventServiceKafkaImpl
|
publish
|
class CloudEventServiceKafkaImpl implements CloudEventServicePlus, Closeable {
static final Logger log = LoggerFactory.getLogger(CloudEventServiceKafkaImpl.class);
private final KafkaConfig config;
private KafkaProducer<String, String> producer;
private KafkaConsumer<String, String> consumer;
public CloudEventServiceKafkaImpl(CloudProps cloudProps) {
this.config = new KafkaConfig(cloudProps);
}
private void initProducer() {
if (producer != null) {
return;
}
Utils.locker().lock();
try {
if (producer != null) {
return;
}
Properties properties = config.getProducerProperties();
producer = new KafkaProducer<>(properties);
} finally {
Utils.locker().unlock();
}
}
private void initConsumer() {
if (consumer != null) {
return;
}
Utils.locker().lock();
try {
if (consumer != null) {
return;
}
Properties properties = config.getConsumerProperties();
consumer = new KafkaConsumer<>(properties);
} finally {
Utils.locker().unlock();
}
}
@Override
public boolean publish(Event event) throws CloudEventException {<FILL_FUNCTION_BODY>}
CloudEventObserverManger observerManger = new CloudEventObserverManger();
@Override
public void attention(EventLevel level, String channel, String group, String topic, String tag, int qos, CloudEventHandler observer) {
observerManger.add(topic, level, group, topic, tag, qos, observer);
}
public void subscribe() {
//订阅
if (observerManger.topicSize() > 0) {
try {
initConsumer();
consumer.subscribe(observerManger.topicAll());
//开始拉取
new Thread(this::subscribePull).start();
} catch (Throwable ex) {
throw new RuntimeException(ex);
}
}
}
private void subscribePull() {
while (true) {
try {
subscribePullDo();
} catch (EOFException e) {
break;
} catch (Throwable e) {
log.warn(e.getMessage(), e);
}
}
}
private void subscribePullDo() throws Throwable {
//拉取
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
//如果没有小休息下
if (records.isEmpty()) {
Thread.sleep(100);
return;
}
Map<TopicPartition, OffsetAndMetadata> topicOffsets = new LinkedHashMap<>();
for (ConsumerRecord<String, String> record : records) {
Event event = new Event(record.topic(), record.value())
.key(record.key())
.channel(config.getEventChannel());
try {
//接收并处理事件
if (onReceive(event)) {
//接收需要提交的偏移量
topicOffsets.put(new TopicPartition(record.topic(), record.partition()),
new OffsetAndMetadata(record.offset() + 1));
}
} catch (Throwable e) {
log.warn(e.getMessage(), e);
}
}
if (topicOffsets.size() > 0) {
consumer.commitAsync(topicOffsets, null);
}
}
/**
* 处理接收事件
*/
public boolean onReceive(Event event) throws Throwable {
boolean isOk = true;
CloudEventHandler handler = null;
handler = observerManger.getByTopic(event.topic());
if (handler != null) {
isOk = handler.handle(event);
} else {
//只需要记录一下
log.warn("There is no observer for this event topic[{}]", event.topic());
}
return isOk;
}
@Override
public String getChannel() {
return config.getEventChannel();
}
@Override
public String getGroup() {
return config.getEventGroup();
}
@Override
public void close() throws IOException {
if (producer != null) {
producer.close();
}
if (consumer != null) {
consumer.close();
}
}
}
|
initProducer();
if (Utils.isEmpty(event.key())) {
event.key(Utils.guid());
}
Future<RecordMetadata> future = producer.send(new ProducerRecord<>(event.topic(), event.key(), event.content()));
if (config.getPublishTimeout() > 0 && event.qos() > 0) {
try {
future.get(config.getPublishTimeout(), TimeUnit.MILLISECONDS);
} catch (Exception e) {
throw new CloudEventException(e);
}
}
return true;
| 1,165
| 149
| 1,314
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/mqtt-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/mqtt/XPluginImpl.java
|
XPluginImpl
|
start
|
class XPluginImpl implements Plugin {
@Override
public void start(AppContext context) {<FILL_FUNCTION_BODY>}
}
|
CloudProps cloudProps = new CloudProps(context,"mqtt");
if (Utils.isEmpty(cloudProps.getEventServer())) {
return;
}
if (cloudProps.getEventEnable()) {
CloudEventServiceMqtt3 eventServiceImp = new CloudEventServiceMqtt3(cloudProps);
CloudManager.register(eventServiceImp);
context.wrapAndPut(MqttClientManager.class, eventServiceImp.getClientManager());
context.lifecycle(-99, () -> eventServiceImp.subscribe());
}
| 38
| 146
| 184
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/mqtt-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/mqtt/event/MqttDeliveryCompleteEvent.java
|
MqttDeliveryCompleteEvent
|
toString
|
class MqttDeliveryCompleteEvent implements Serializable {
private String clientId;
private int messageId;
private transient IMqttToken token;
public MqttDeliveryCompleteEvent(String clientId, int messageId, IMqttToken token){
this.clientId = clientId;
this.messageId = messageId;
this.token = token;
}
public int getMessageId() {
return messageId;
}
public String getClientId() {
return clientId;
}
public IMqttToken getToken() {
return token;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "MqttDeliveryCompleteEvent{" +
"clientId='" + clientId + '\'' +
", messageId=" + messageId +
'}';
| 178
| 46
| 224
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/mqtt-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/mqtt/service/CloudEventServiceMqtt3.java
|
CloudEventServiceMqtt3
|
publish
|
class CloudEventServiceMqtt3 implements CloudEventServicePlus {
private final CloudProps cloudProps;
private final long publishTimeout;
private MqttClientManagerImpl clientManager;
private CloudEventObserverManger observerMap = new CloudEventObserverManger();
/**
* 获取客户端
*/
public MqttClientManager getClientManager() {
return clientManager;
}
//
// 1833(MQTT的默认端口号)
//
public CloudEventServiceMqtt3(CloudProps cloudProps) {
this.cloudProps = cloudProps;
this.publishTimeout = cloudProps.getEventPublishTimeout();
this.clientManager = new MqttClientManagerImpl(observerMap, cloudProps);
}
@Override
public boolean publish(Event event) throws CloudEventException {<FILL_FUNCTION_BODY>}
@Override
public void attention(EventLevel level, String channel, String group, String topic, String tag, int qos, CloudEventHandler observer) {
observerMap.add(topic, level, group, topic, tag, qos, observer);
}
public void subscribe() {
try {
//获取客户端时,自动会完成订阅
clientManager.getClient();
} catch (Throwable ex) {
throw new RuntimeException(ex);
}
}
private String channel;
private String group;
@Override
public String getChannel() {
if (channel == null) {
channel = cloudProps.getEventChannel();
}
return channel;
}
@Override
public String getGroup() {
if (group == null) {
group = cloudProps.getEventGroup();
}
return group;
}
}
|
MqttMessage message = new MqttMessage();
message.setQos(event.qos());
message.setRetained(event.retained());
message.setPayload(event.content().getBytes());
try {
IMqttToken token = clientManager.getClient().publish(event.topic(), message);
if (!clientManager.getAsync() && event.qos() > 0) {
token.waitForCompletion(publishTimeout);
return token.isComplete();
} else {
return true;
}
} catch (Throwable ex) {
throw new CloudEventException(ex);
}
| 457
| 164
| 621
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/mqtt-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/mqtt/service/MqttClientManagerImpl.java
|
MqttClientManagerImpl
|
messageArrived
|
class MqttClientManagerImpl implements MqttClientManager, MqttCallbackExtended {
private static final Logger log = LoggerFactory.getLogger(MqttClientManagerImpl.class);
private static final String PROP_EVENT_clientId = "event.clientId";
private final String server;
private final String username;
private final String password;
private final CloudEventObserverManger observerManger;
private final String eventChannelName;
private final MqttConnectOptions options;
private String clientId;
private boolean async = true;
private final Set<ConnectCallback> connectCallbacks = Collections.synchronizedSet(new HashSet<>());
public MqttClientManagerImpl(CloudEventObserverManger observerManger, CloudProps cloudProps) {
this.observerManger = observerManger;
this.eventChannelName = cloudProps.getEventChannel();
this.server = cloudProps.getEventServer();
this.username = cloudProps.getUsername();
this.password = cloudProps.getPassword();
this.clientId = cloudProps.getValue(PROP_EVENT_clientId);
if (Utils.isEmpty(this.clientId)) {
this.clientId = Solon.cfg().appName() + "-" + Utils.guid();
}
this.options = new MqttConnectOptions();
if (Utils.isNotEmpty(username)) {
options.setUserName(username);
} else {
options.setUserName(Solon.cfg().appName());
}
if (Utils.isNotEmpty(password)) {
options.setPassword(password.toCharArray());
}
//设置死信
options.setWill("client.close", clientId.getBytes(StandardCharsets.UTF_8), 1, false);
options.setConnectionTimeout(30); //超时时长
options.setKeepAliveInterval(20); //心跳时长,秒
options.setServerURIs(new String[]{server});
options.setCleanSession(false);
options.setAutomaticReconnect(true);
options.setMaxInflight(128); //根据情况再调整
//绑定定制属性
Properties props = cloudProps.getEventClientProps();
if (props.size() > 0) {
Utils.injectProperties(options, props);
}
//支持事件总线扩展
EventBus.publish(options);
}
//在断开连接时调用
@Override
public void connectionLost(Throwable cause) {
log.warn("MQTT connection lost, clientId={}", clientId, cause);
if (options.isAutomaticReconnect() == false) {
//如果不是自动重链,把客户端清掉(如果有自己重链,内部会自己处理)
client = null;
}
}
//已经预订的消息
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {<FILL_FUNCTION_BODY>}
//发布的 QoS 1 或 QoS 2 消息的传递令牌时调用
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
if (token.getMessageId() > 0) {
if (log.isDebugEnabled()) {
log.debug("MQTT message delivery completed, clientId={}, messageId={}", clientId, token.getMessageId());
}
EventBus.publish(new MqttDeliveryCompleteEvent(clientId, token.getMessageId(), token));
}
}
@Override
public void connectComplete(boolean reconnect, String serverURI) {
connectCallbacks.forEach(callback -> callback.connectComplete(reconnect));
}
private IMqttAsyncClient client;
private final ReentrantLock SYNC_LOCK = new ReentrantLock();
/**
* 获取客户端
*/
@Override
public IMqttAsyncClient getClient() {
if (client != null) {
return client;
}
SYNC_LOCK.lock();
try {
if (client == null) {
client = createClient();
}
return client;
} finally {
SYNC_LOCK.unlock();
}
}
@Override
public String getClientId() {
return clientId;
}
@Override
public void setAsync(boolean async) {
this.async = async;
}
@Override
public boolean getAsync() {
return async;
}
@Override
public void addCallback(ConnectCallback connectCallback) {
connectCallbacks.add(connectCallback);
}
@Override
public boolean removeCallback(ConnectCallback connectCallback) {
return connectCallbacks.remove(connectCallback);
}
/**
* 创建客户端
*/
private IMqttAsyncClient createClient() {
try {
client = new MqttAsyncClient(server, clientId, new MemoryPersistence());
//设置手动ack
client.setManualAcks(true);
//设置默认回调
client.setCallback(this);
//转为毫秒
long waitConnectionTimeout = options.getConnectionTimeout() * 1000;
//开始链接
client.connect(options).waitForCompletion(waitConnectionTimeout);
//订阅
subscribe();
return client;
} catch (MqttException e) {
throw new IllegalStateException(e);
}
}
/**
* 订阅
*/
private void subscribe() throws MqttException {
if (observerManger.topicSize() < 1) {
return;
}
String[] topicAry = observerManger.topicAll().toArray(new String[0]);
int[] topicQos = new int[topicAry.length];
IMqttMessageListener[] topicListener = new IMqttMessageListener[topicAry.length];
for (int i = 0, len = topicQos.length; i < len; i++) {
EventObserver eventObserver = observerManger.getByTopic(topicAry[i]);
topicQos[i] = eventObserver.getQos();
topicListener[i] = new MqttMessageListenerImpl(this, eventChannelName, eventObserver);
}
IMqttToken token = getClient().subscribe(topicAry, topicQos, topicListener);
//转为毫秒
long waitConnectionTimeout = options.getConnectionTimeout() * 1000;
token.waitForCompletion(waitConnectionTimeout);
}
}
|
if (log.isTraceEnabled()) {
log.trace("MQTT message arrived, clientId={}, messageId={}", clientId, message.getId());
}
CloudEventHandler eventHandler = observerManger.getByTopic(topic);
if (eventHandler != null) {
MqttMessageHandler handler = new MqttMessageHandler(this, eventChannelName, eventHandler, topic, message);
if (getAsync()) {
RunUtil.parallel(handler);
} else {
handler.run();
}
}
| 1,681
| 141
| 1,822
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/mqtt-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/mqtt/service/MqttMessageHandler.java
|
MqttMessageHandler
|
run
|
class MqttMessageHandler implements Runnable {
private static Logger log = LoggerFactory.getLogger(MqttMessageListenerImpl.class);
private MqttClientManager clientManager;
private String eventChannelName;
private CloudEventHandler eventHandler;
private String topic;
private MqttMessage message;
public MqttMessageHandler(MqttClientManager clientManager, String eventChannelName, CloudEventHandler eventHandler, String topic, MqttMessage message) {
this.clientManager = clientManager;
this.eventChannelName = eventChannelName;
this.eventHandler = eventHandler;
this.topic = topic;
this.message = message;
}
@Override
public void run() {<FILL_FUNCTION_BODY>}
}
|
try {
Event event = new Event(topic, new String(message.getPayload()))
.qos(message.getQos())
.retained(message.isRetained())
.channel(eventChannelName);
if (eventHandler != null) {
if (eventHandler.handle(event)) {
//手动 ack
clientManager.getClient().messageArrivedComplete(message.getId(), message.getQos());
}
} else {
//手动 ack
clientManager.getClient().messageArrivedComplete(message.getId(), message.getQos());
//记录一下它是没有订阅的
log.warn("There is no observer for this event topic[{}]", event.topic());
}
} catch (Throwable e) {
e = Utils.throwableUnwrap(e);
//不返回异常,不然会关掉客户端(已使用手动ack)
log.warn(e.getMessage(), e);
}
| 195
| 249
| 444
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/mqtt-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/mqtt/service/MqttMessageListenerImpl.java
|
MqttMessageListenerImpl
|
messageArrived
|
class MqttMessageListenerImpl implements IMqttMessageListener {
private CloudEventHandler eventHandler;
private String eventChannelName;
private MqttClientManager clientManager;
public MqttMessageListenerImpl(MqttClientManager clientManager, String eventChannelName, CloudEventHandler eventHandler) {
this.eventHandler = eventHandler;
this.eventChannelName = eventChannelName;
this.clientManager = clientManager;
}
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {<FILL_FUNCTION_BODY>}
}
|
MqttMessageHandler handler = new MqttMessageHandler(clientManager, eventChannelName, eventHandler, topic, message);
if (clientManager.getAsync()) {
RunUtil.parallel(handler);
} else {
handler.run();
}
| 148
| 68
| 216
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/mqtt5-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/mqtt5/XPluginImpl.java
|
XPluginImpl
|
start
|
class XPluginImpl implements Plugin {
@Override
public void start(AppContext context) {<FILL_FUNCTION_BODY>}
}
|
CloudProps cloudProps = new CloudProps(context, "mqtt");
if (Utils.isEmpty(cloudProps.getEventServer())) {
return;
}
if (cloudProps.getEventEnable()) {
CloudEventServiceMqtt5 eventServiceImp = new CloudEventServiceMqtt5(cloudProps);
CloudManager.register(eventServiceImp);
context.wrapAndPut(MqttClientManager.class, eventServiceImp.getClientManager());
context.lifecycle(-99, () -> eventServiceImp.subscribe());
}
| 38
| 147
| 185
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/mqtt5-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/mqtt5/event/MqttDeliveryCompleteEvent.java
|
MqttDeliveryCompleteEvent
|
toString
|
class MqttDeliveryCompleteEvent implements Serializable {
private String clientId;
private int messageId;
private transient IMqttToken token;
public MqttDeliveryCompleteEvent(String clientId, int messageId, IMqttToken token){
this.clientId = clientId;
this.messageId = messageId;
this.token = token;
}
public int getMessageId() {
return messageId;
}
public String getClientId() {
return clientId;
}
public IMqttToken getToken() {
return token;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "MqttDeliveryCompleteEvent{" +
"clientId='" + clientId + '\'' +
", messageId=" + messageId +
'}';
| 178
| 46
| 224
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/mqtt5-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/mqtt5/service/CloudEventServiceMqtt5.java
|
CloudEventServiceMqtt5
|
publish
|
class CloudEventServiceMqtt5 implements CloudEventServicePlus {
private final CloudProps cloudProps;
private final long publishTimeout;
private MqttClientManagerImpl clientManager;
private CloudEventObserverManger observerMap = new CloudEventObserverManger();
/**
* 获取客户端
*/
public MqttClientManager getClientManager() {
return clientManager;
}
//
// 1833(MQTT的默认端口号)
//
public CloudEventServiceMqtt5(CloudProps cloudProps) {
this.cloudProps = cloudProps;
this.publishTimeout = cloudProps.getEventPublishTimeout();
this.clientManager = new MqttClientManagerImpl(observerMap, cloudProps);
}
@Override
public boolean publish(Event event) throws CloudEventException {<FILL_FUNCTION_BODY>}
@Override
public void attention(EventLevel level, String channel, String group, String topic, String tag, int qos, CloudEventHandler observer) {
observerMap.add(topic, level, group, topic, tag, qos, observer);
}
public void subscribe() {
try {
//获取客户端时,自动会完成订阅
clientManager.getClient();
} catch (Throwable ex) {
throw new RuntimeException(ex);
}
}
private String channel;
private String group;
@Override
public String getChannel() {
if (channel == null) {
channel = cloudProps.getEventChannel();
}
return channel;
}
@Override
public String getGroup() {
if (group == null) {
group = cloudProps.getEventGroup();
}
return group;
}
}
|
MqttMessage message = new MqttMessage();
message.setQos(event.qos());
message.setRetained(event.retained());
message.setPayload(event.content().getBytes());
try {
IMqttToken token = clientManager.getClient().publish(event.topic(), message);
if (event.qos() > 0) {
token.waitForCompletion(publishTimeout);
return token.isComplete();
} else {
return true;
}
} catch (Throwable ex) {
throw new CloudEventException(ex);
}
| 457
| 157
| 614
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/mqtt5-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/mqtt5/service/MqttMessageHandler.java
|
MqttMessageHandler
|
run
|
class MqttMessageHandler implements Runnable{
private static Logger log = LoggerFactory.getLogger(MqttMessageListenerImpl.class);
private MqttClientManager clientManager;
private String eventChannelName;
private CloudEventHandler eventHandler;
private String topic;
private MqttMessage message;
public MqttMessageHandler(MqttClientManager clientManager, String eventChannelName, CloudEventHandler eventHandler, String topic, MqttMessage message){
this.clientManager = clientManager;
this.eventChannelName = eventChannelName;
this.eventHandler = eventHandler;
this.topic = topic;
this.message = message;
}
@Override
public void run() {<FILL_FUNCTION_BODY>}
}
|
try {
Event event = new Event(topic, new String(message.getPayload()))
.qos(message.getQos())
.retained(message.isRetained())
.channel(eventChannelName);
if (eventHandler != null) {
if (eventHandler.handle(event)) {
//手动 ack
clientManager.getClient().messageArrivedComplete(message.getId(), message.getQos());
}
} else {
//手动 ack
clientManager.getClient().messageArrivedComplete(message.getId(), message.getQos());
//记录一下它是没有订阅的
log.warn("There is no observer for this event topic[{}]", event.topic());
}
} catch (Throwable e) {
e = Utils.throwableUnwrap(e);
//不返回异常,不然会关掉客户端(已使用手动ack)
log.warn(e.getMessage(), e);
}
| 195
| 249
| 444
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/mqtt5-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/mqtt5/service/MqttMessageListenerImpl.java
|
MqttMessageListenerImpl
|
messageArrived
|
class MqttMessageListenerImpl implements IMqttMessageListener {
private CloudEventHandler eventHandler;
private String eventChannelName;
private MqttClientManager clientManager;
public MqttMessageListenerImpl(MqttClientManager clientManager, String eventChannelName, CloudEventHandler eventHandler) {
this.eventHandler = eventHandler;
this.eventChannelName = eventChannelName;
this.clientManager = clientManager;
}
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {<FILL_FUNCTION_BODY>}
}
|
MqttMessageHandler handler = new MqttMessageHandler(clientManager, eventChannelName, eventHandler, topic, message);
if (clientManager.getAsync()) {
RunUtil.parallel(handler);
} else {
handler.run();
}
| 148
| 68
| 216
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/pulsar-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/pulsar/XPluginImp.java
|
XPluginImp
|
start
|
class XPluginImp implements Plugin {
@Override
public void start(AppContext context) {<FILL_FUNCTION_BODY>}
}
|
CloudProps cloudProps = new CloudProps(context,"pulsar");
if (Utils.isEmpty(cloudProps.getEventServer())) {
return;
}
if (cloudProps.getEventEnable()) {
CloudEventServicePulsarImp eventServiceImp = new CloudEventServicePulsarImp(cloudProps);
CloudManager.register(eventServiceImp);
context.lifecycle(-99, () -> eventServiceImp.subscribe());
}
| 39
| 123
| 162
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/pulsar-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/pulsar/impl/PulsarMessageListenerImpl.java
|
PulsarMessageListenerImpl
|
onReceiveDo
|
class PulsarMessageListenerImpl implements MessageListener<byte[]> {
static final Logger log = LoggerFactory.getLogger(PulsarMessageListenerImpl.class);
private CloudEventObserverManger observerManger;
private String eventChannelName;
public PulsarMessageListenerImpl(CloudProps cloudProps, CloudEventObserverManger observerManger) {
this.observerManger = observerManger;
this.eventChannelName = cloudProps.getEventChannel();
}
@Override
public void received(Consumer<byte[]> consumer, Message<byte[]> msg) {
try {
String event_json = new String(msg.getValue());
Event event = ONode.deserialize(event_json, Event.class);
event.channel(eventChannelName);
boolean isOk = onReceive(event); //吃掉异常,方便下面的动作
if (isOk == false) {
event.times(event.times() + 1);
consumer.reconsumeLater(msg, ExpirationUtils.getExpiration(event.times()), TimeUnit.SECONDS);
} else {
consumer.acknowledge(msg);
}
} catch (Throwable e) {
e = Utils.throwableUnwrap(e);
log.warn(e.getMessage(), e); //todo: ?
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
} else {
throw new RuntimeException(e);
}
}
}
@Override
public void reachedEndOfTopic(Consumer<byte[]> consumer) {
MessageListener.super.reachedEndOfTopic(consumer);
}
private boolean onReceive(Event event) {
try {
return onReceiveDo(event);
} catch (Throwable e) {
log.warn(e.getMessage(), e);
return false;
}
}
/**
* 处理接收事件
*/
private boolean onReceiveDo(Event event) throws Throwable {<FILL_FUNCTION_BODY>}
}
|
boolean isOk = true;
CloudEventHandler handler = null;
//new topic
String topicNew;
if (Utils.isEmpty(event.group())) {
topicNew = event.topic();
} else {
topicNew = event.group() + PulsarProps.GROUP_SPLIT_MARK + event.topic();
}
handler = observerManger.getByTopic(topicNew);
if (handler != null) {
isOk = handler.handle(event);
} else {
//只需要记录一下
log.warn("There is no observer for this event topic[{}]", topicNew);
}
return isOk;
| 522
| 171
| 693
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/pulsar-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/pulsar/service/CloudEventServicePulsarImp.java
|
CloudEventServicePulsarImp
|
publish
|
class CloudEventServicePulsarImp implements CloudEventServicePlus {
private static final String PROP_EVENT_consumerGroup = "event.consumerGroup";
private static final String PROP_EVENT_producerGroup = "event.producerGroup";
private final CloudProps cloudProps;
private PulsarClient client;
public CloudEventServicePulsarImp(CloudProps cloudProps) {
this.cloudProps = cloudProps;
try {
client = PulsarClient.builder()
.serviceUrl(cloudProps.getEventServer())
.build();
} catch (PulsarClientException e) {
throw new CloudEventException(e);
}
}
@Override
public boolean publish(Event event) throws CloudEventException {<FILL_FUNCTION_BODY>}
CloudEventObserverManger observerManger = new CloudEventObserverManger();
@Override
public void attention(EventLevel level, String channel, String group, String topic, String tag, int qos, CloudEventHandler observer) {
//new topic
String topicNew;
if (Utils.isEmpty(group)) {
topicNew = topic;
} else {
topicNew = group + PulsarProps.GROUP_SPLIT_MARK + topic;
}
observerManger.add(topicNew, level, group, topic, tag, qos, observer);
}
public void subscribe() {
if (observerManger.topicSize() > 0) {
String consumerGroup = getEventConsumerGroup();
if (Utils.isEmpty(consumerGroup)) {
consumerGroup = Solon.cfg().appGroup() + "_" + Solon.cfg().appName();
}
try {
client.newConsumer()
.topics(new ArrayList<>(observerManger.topicAll()))
.messageListener(new PulsarMessageListenerImpl(cloudProps, observerManger))
.subscriptionName(consumerGroup)
.subscriptionType(SubscriptionType.Shared)
.subscribe();
} catch (Exception e) {
throw new CloudEventException(e);
}
}
}
private String channel;
private String group;
@Override
public String getChannel() {
if (channel == null) {
channel = cloudProps.getEventChannel();
}
return channel;
}
@Override
public String getGroup() {
if (group == null) {
group = cloudProps.getEventGroup();
}
return group;
}
/**
* 消费组
*/
public String getEventConsumerGroup() {
return cloudProps.getValue(PROP_EVENT_consumerGroup);
}
/**
* 产品组
*/
public String getEventProducerGroup() {
return cloudProps.getValue(PROP_EVENT_producerGroup);
}
}
|
if (Utils.isEmpty(event.topic())) {
throw new IllegalArgumentException("Event missing topic");
}
if (Utils.isEmpty(event.content())) {
throw new IllegalArgumentException("Event missing content");
}
if (Utils.isEmpty(event.key())) {
event.key(Utils.guid());
}
//new topic
String topicNew;
if (Utils.isEmpty(event.group())) {
topicNew = event.topic();
} else {
topicNew = event.group() + PulsarProps.GROUP_SPLIT_MARK + event.topic();
}
byte[] event_data = ONode.stringify(event).getBytes(StandardCharsets.UTF_8);
try (Producer<byte[]> producer = client.newProducer().topic(topicNew).create()) {
if (event.scheduled() == null) {
producer.newMessage()
.key(event.key())
.value(event_data)
.send();
} else {
producer.newMessage()
.key(event.key())
.value(event_data)
.deliverAt(event.scheduled().getTime())
.send();
}
return true;
} catch (Throwable ex) {
throw new CloudEventException(ex);
}
| 722
| 338
| 1,060
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/rabbitmq-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/rabbitmq/XPluginImp.java
|
XPluginImp
|
start
|
class XPluginImp implements Plugin {
@Override
public void start(AppContext context) {<FILL_FUNCTION_BODY>}
}
|
CloudProps cloudProps = new CloudProps(context,"rabbitmq");
if (Utils.isEmpty(cloudProps.getEventServer())) {
return;
}
if (cloudProps.getEventEnable()) {
CloudEventServiceRabbitmqImp eventServiceImp = new CloudEventServiceRabbitmqImp(cloudProps);
CloudManager.register(eventServiceImp);
context.lifecycle(-99, () -> eventServiceImp.subscribe());
}
| 39
| 128
| 167
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/rabbitmq-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/rabbitmq/impl/RabbitChannelFactory.java
|
RabbitChannelFactory
|
initChannel
|
class RabbitChannelFactory {
private ConnectionFactory connectionFactory;
private RabbitConfig config;
public RabbitChannelFactory(RabbitConfig config) {
this.config = config;
String host = config.server.split(":")[0];
int port = Integer.parseInt(config.server.split(":")[1]);
connectionFactory = new ConnectionFactory();
// 配置连接信息
connectionFactory.setHost(host);
connectionFactory.setPort(port);
connectionFactory.setRequestedHeartbeat(30);
if (Utils.isNotEmpty(config.username)) {
connectionFactory.setUsername(config.username);
}
if (Utils.isNotEmpty(config.password)) {
connectionFactory.setPassword(config.password);
}
if (Utils.isNotEmpty(config.virtualHost)) {
connectionFactory.setVirtualHost(config.virtualHost);
}
// 网络异常自动连接恢复
connectionFactory.setAutomaticRecoveryEnabled(true);
// 每5秒尝试重试连接一次
connectionFactory.setNetworkRecoveryInterval(5000L);
}
private Channel initChannel(Channel channel) throws IOException {<FILL_FUNCTION_BODY>}
/**
* 创建通道
*/
public Channel createChannel() throws IOException, TimeoutException {
Channel channel = connectionFactory.newConnection().createChannel();
return initChannel(channel);
}
}
|
//for exchange
channel.exchangeDeclare(config.exchangeName,
config.exchangeType,
config.durable,
config.autoDelete,
config.internal, new HashMap<>());
//for producer
if (config.publishTimeout > 0) {
channel.confirmSelect(); //申明需要发布确认(以提高可靠性)
}
//for consumer
channel.basicQos(config.prefetchCount); //申明同时接收数量
return channel;
| 371
| 134
| 505
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/rabbitmq-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/rabbitmq/impl/RabbitConfig.java
|
RabbitConfig
|
getVirtualHostInternal
|
class RabbitConfig {
static final Logger log = LoggerFactory.getLogger(RabbitConfig.class);
/**
* 虚拟主机
*/
public final String virtualHost;
/**
* 交换器名称
*/
public final String exchangeName;
/**
* 交换器类型
*/
public final BuiltinExchangeType exchangeType = BuiltinExchangeType.DIRECT;
/**
* 是否持久化
*/
public final boolean durable = true;
/**
* 是否自动删除
*/
public final boolean autoDelete = false;
/**
* 是否为内部
*/
public final boolean internal = false;
/**
* 标志告诉服务器至少将该消息route到一个队列中,否则将消息返还给生产者
*/
public final boolean mandatory = false;
/**
* 标志告诉服务器如果该消息关联的queue上有消费者,则马上将消息投递给它;
* 如果所有queue都没有消费者,直接把消息返还给生产者,不用将消息入队列等待消费者了。
*/
public final boolean immediate = false;
/**
* 是否排它
*/
public final boolean exclusive = false;
/**
* 服务器地址
*/
public final String server;
/**
* 用户名
*/
public final String username;
/**
* 密码
*/
public final String password;
public final String queue_normal;
public final String queue_ready;
public final String queue_retry;
/**
* 发布超时
* */
public final long publishTimeout;
/**
*
* */
public final int prefetchCount;
private final CloudProps cloudProps;
public RabbitConfig(CloudProps cloudProps) {
this.cloudProps = cloudProps;
publishTimeout = cloudProps.getEventPublishTimeout();
prefetchCount = getPrefetchCountInternal();
server = cloudProps.getEventServer();
username = cloudProps.getEventUsername();
password = cloudProps.getEventPassword();
virtualHost = getVirtualHostInternal();
exchangeName = getEventExchangeInternal();
String queueName = getEventQueueInternal();
if (Utils.isEmpty(queueName)) {
queueName = exchangeName + "_" + Solon.cfg().appName();
}
queue_normal = queueName + "@normal";
queue_ready = queueName + "@ready";
queue_retry = queueName + "@retry";
log.trace("queue_normal=" + queue_normal);
log.trace("queue_ready=" + queue_ready);
log.trace("queue_retry=" + queue_retry);
}
public String getEventChannel(){
return cloudProps.getEventChannel();
}
private int getPrefetchCountInternal(){
int tmp = cloudProps.getEventPrefetchCount();
if (tmp < 1) {
tmp = 10;
}
return tmp;
}
private String getVirtualHostInternal() {<FILL_FUNCTION_BODY>}
/**
* 交换机
*/
private String getEventExchangeInternal() {
String tmp = cloudProps.getValue(RabbitmqProps.PROP_EVENT_exchange);
if (Utils.isEmpty(tmp)) {
return Solon.cfg().appGroup();
} else {
return tmp;
}
}
/**
* 队列
*/
private String getEventQueueInternal() {
return cloudProps.getValue(RabbitmqProps.PROP_EVENT_queue);
}
}
|
String tmp = cloudProps.getValue(RabbitmqProps.PROP_EVENT_virtualHost);
if (Utils.isEmpty(tmp)) {
return Solon.cfg().appNamespace();
} else {
return tmp;
}
| 945
| 63
| 1,008
|
<no_super_class>
|
noear_solon
|
solon/solon-projects-cloud/solon-cloud-event/rabbitmq-solon-cloud-plugin/src/main/java/org/noear/solon/cloud/extend/rabbitmq/impl/RabbitConsumeTask.java
|
RabbitConsumeTask
|
onReceiveDo
|
class RabbitConsumeTask implements Runnable{
static final Logger log = LoggerFactory.getLogger(RabbitConsumeTask.class);
private String consumerTag;
private Envelope envelope;
private AMQP.BasicProperties properties;
private byte[] body;
private RabbitConsumeHandler master;
public RabbitConsumeTask(RabbitConsumeHandler master, String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) {
this.consumerTag = consumerTag;
this.envelope = envelope;
this.properties = properties;
this.body = body;
this.master = master;
}
@Override
public void run() {
try {
String event_json = new String(body);
Event event = ONode.deserialize(event_json, Event.class);
event.channel(master.eventChannelName);
boolean isOk = onReceive(event); //吃掉异常,方便下面的动作
if (isOk == false) {
event.times(event.times() + 1);
try {
isOk = master.producer.publish(event, master.config.queue_ready, ExpirationUtils.getExpiration(event.times()));
} catch (Throwable ex) {
master.getChannel().basicNack(envelope.getDeliveryTag(), false, true);
isOk = true;
}
}
if (isOk) {
master.getChannel().basicAck(envelope.getDeliveryTag(), false);
}
} catch (Throwable e) {
e = Utils.throwableUnwrap(e);
log.warn(e.getMessage(), e);
}
}
/**
* 处理接收事件(会吃掉异常)
* */
private boolean onReceive(Event event) throws Throwable {
try {
return onReceiveDo(event);
} catch (Throwable e) {
log.warn(e.getMessage(), e);
return false;
}
}
/**
* 处理接收事件
*/
private boolean onReceiveDo(Event event) throws Throwable {<FILL_FUNCTION_BODY>}
}
|
boolean isOk = true;
CloudEventHandler handler = null;
//new topic
String topicNew;
if (Utils.isEmpty(event.group())) {
topicNew = event.topic();
} else {
topicNew = event.group() + RabbitmqProps.GROUP_SPLIT_MARK + event.topic();
}
handler = master.observerManger.getByTopic(topicNew);
if (handler != null) {
isOk = handler.handle(event);
} else {
//只需要记录一下
log.warn("There is no observer for this event topic[{}]", topicNew);
}
return isOk;
| 569
| 175
| 744
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.