format code

pull/326/head
weihu 2 years ago
parent 72fff2459f
commit 2f27841691

@ -66,7 +66,7 @@ public class PolarisConfigAutoConfiguration {
public SpringValueProcessor springValueProcessor() { public SpringValueProcessor springValueProcessor() {
return new SpringValueProcessor(); return new SpringValueProcessor();
} }
@Bean @Bean
public SpringValueDefinitionProcessor springValueDefinitionProcessor() { public SpringValueDefinitionProcessor springValueDefinitionProcessor() {
return new SpringValueDefinitionProcessor(); return new SpringValueDefinitionProcessor();

@ -89,7 +89,6 @@ public class PolarisPropertySourceAutoRefresher
this.placeholderHelper = SpringInjector.getInstance(PlaceholderHelper.class); this.placeholderHelper = SpringInjector.getInstance(PlaceholderHelper.class);
this.typeConverterHasConvertIfNecessaryWithFieldParameter = testTypeConverterHasConvertIfNecessaryWithFieldParameter(); this.typeConverterHasConvertIfNecessaryWithFieldParameter = testTypeConverterHasConvertIfNecessaryWithFieldParameter();
} }
@Override @Override
@ -136,7 +135,7 @@ public class PolarisPropertySourceAutoRefresher
Map<String, Object> source = polarisPropertySource Map<String, Object> source = polarisPropertySource
.getSource(); .getSource();
for (String changedKey : configKVFileChangeEvent.changedKeys()) { for (String changedKey : configKVFileChangeEvent.changedKeys()) {
// 1. check whether the changed key is relevant // 1. check whether the changed key is relevant
@ -164,14 +163,15 @@ public class PolarisPropertySourceAutoRefresher
LOGGER.info("Auto update polaris changed value successfully, new value: {}, {}", value, LOGGER.info("Auto update polaris changed value successfully, new value: {}, {}", value,
springValue); springValue);
} catch (Throwable ex) { }
catch (Throwable ex) {
LOGGER.error("Auto update polaris changed value failed, {}", springValue.toString(), ex); LOGGER.error("Auto update polaris changed value failed, {}", springValue.toString(), ex);
} }
} }
/** /**
* Logic transplanted from DefaultListableBeanFactory * Logic transplanted from DefaultListableBeanFactory.
* *
* @see org.springframework.beans.factory.support.DefaultListableBeanFactory#doResolveDependency(org.springframework.beans.factory.config.DependencyDescriptor, * @see org.springframework.beans.factory.support.DefaultListableBeanFactory#doResolveDependency(org.springframework.beans.factory.config.DependencyDescriptor,
* java.lang.String, java.util.Set, org.springframework.beans.TypeConverter) * java.lang.String, java.util.Set, org.springframework.beans.TypeConverter)
@ -183,16 +183,19 @@ public class PolarisPropertySourceAutoRefresher
if (springValue.isJson()) { if (springValue.isJson()) {
value = parseJsonValue((String) value, springValue.getTargetType()); value = parseJsonValue((String) value, springValue.getTargetType());
} else { }
else {
if (springValue.isField()) { if (springValue.isField()) {
// org.springframework.beans.TypeConverter#convertIfNecessary(java.lang.Object, java.lang.Class, java.lang.reflect.Field) is available from Spring 3.2.0+ // org.springframework.beans.TypeConverter#convertIfNecessary(java.lang.Object, java.lang.Class, java.lang.reflect.Field) is available from Spring 3.2.0+
if (typeConverterHasConvertIfNecessaryWithFieldParameter) { if (typeConverterHasConvertIfNecessaryWithFieldParameter) {
value = this.typeConverter value = this.typeConverter
.convertIfNecessary(value, springValue.getTargetType(), springValue.getField()); .convertIfNecessary(value, springValue.getTargetType(), springValue.getField());
} else { }
else {
value = this.typeConverter.convertIfNecessary(value, springValue.getTargetType()); value = this.typeConverter.convertIfNecessary(value, springValue.getTargetType());
} }
} else { }
else {
value = this.typeConverter.convertIfNecessary(value, springValue.getTargetType(), value = this.typeConverter.convertIfNecessary(value, springValue.getTargetType(),
springValue.getMethodParameter()); springValue.getMethodParameter());
} }
@ -204,7 +207,8 @@ public class PolarisPropertySourceAutoRefresher
private Object parseJsonValue(String json, Class<?> targetType) { private Object parseJsonValue(String json, Class<?> targetType) {
try { try {
return JacksonUtils.json2JavaBean(json, targetType); return JacksonUtils.json2JavaBean(json, targetType);
} catch (Throwable ex) { }
catch (Throwable ex) {
LOGGER.error("Parsing json '{}' to type {} failed!", json, targetType, ex); LOGGER.error("Parsing json '{}' to type {} failed!", json, targetType, ex);
throw ex; throw ex;
} }
@ -213,7 +217,8 @@ public class PolarisPropertySourceAutoRefresher
private boolean testTypeConverterHasConvertIfNecessaryWithFieldParameter() { private boolean testTypeConverterHasConvertIfNecessaryWithFieldParameter() {
try { try {
TypeConverter.class.getMethod("convertIfNecessary", Object.class, Class.class, Field.class); TypeConverter.class.getMethod("convertIfNecessary", Object.class, Class.class, Field.class);
} catch (Throwable ex) { }
catch (Throwable ex) {
return false; return false;
} }
return true; return true;

@ -54,13 +54,20 @@ public abstract class AbstractPolarisProcessor implements BeanPostProcessor, Pri
return bean; return bean;
} }
/** /**
* subclass should implement this method to process field * subclass should implement this method to process field.
* @param bean bean
* @param beanName beanName
* @param field field
*/ */
protected abstract void processField(Object bean, String beanName, Field field); protected abstract void processField(Object bean, String beanName, Field field);
/** /**
* subclass should implement this method to process method * subclass should implement this method to process method.
* @param bean bean
* @param beanName beanName
* @param method method
*/ */
protected abstract void processMethod(Object bean, String beanName, Method method); protected abstract void processMethod(Object bean, String beanName, Method method);

@ -36,7 +36,7 @@ import org.springframework.context.annotation.Bean;
public class SpringValueProcessor extends AbstractPolarisProcessor implements BeanFactoryPostProcessor, BeanFactoryAware { public class SpringValueProcessor extends AbstractPolarisProcessor implements BeanFactoryPostProcessor, BeanFactoryAware {
private static final Logger logger = LoggerFactory.getLogger(SpringValueProcessor.class); private static final Logger logger = LoggerFactory.getLogger(SpringValueProcessor.class);
private final PlaceholderHelper placeholderHelper; private final PlaceholderHelper placeholderHelper;
private final SpringValueRegistry springValueRegistry; private final SpringValueRegistry springValueRegistry;
@ -111,10 +111,12 @@ public class SpringValueProcessor extends AbstractPolarisProcessor implements Be
if (member instanceof Field) { if (member instanceof Field) {
Field field = (Field) member; Field field = (Field) member;
springValue = new SpringValue(key, value.value(), bean, beanName, field, false); springValue = new SpringValue(key, value.value(), bean, beanName, field, false);
} else if (member instanceof Method) { }
else if (member instanceof Method) {
Method method = (Method) member; Method method = (Method) member;
springValue = new SpringValue(key, value.value(), bean, beanName, method, false); springValue = new SpringValue(key, value.value(), bean, beanName, method, false);
} else { }
else {
logger.error("polaris @Value annotation currently only support to be used on methods and fields, " logger.error("polaris @Value annotation currently only support to be used on methods and fields, "
+ "but is used on {}", member.getClass()); + "but is used on {}", member.getClass());
return; return;
@ -143,7 +145,8 @@ public class SpringValueProcessor extends AbstractPolarisProcessor implements Be
bean, beanName, method, false); bean, beanName, method, false);
springValueRegistry.register(beanFactory, definition.getKey(), springValue); springValueRegistry.register(beanFactory, definition.getKey(), springValue);
logger.debug("Monitoring {}", springValue); logger.debug("Monitoring {}", springValue);
} catch (Throwable ex) { }
catch (Throwable ex) {
logger.error("Failed to enable auto update feature for {}.{}", bean.getClass(), logger.error("Failed to enable auto update feature for {}.{}", bean.getClass(),
definition.getPropertyName()); definition.getPropertyName());
} }

@ -44,11 +44,13 @@ public class PlaceholderHelper {
private static final String EXPRESSION_PREFIX = "#{"; private static final String EXPRESSION_PREFIX = "#{";
private static final String EXPRESSION_SUFFIX = "}"; private static final String EXPRESSION_SUFFIX = "}";
/** /**
* Resolve placeholder property values, e.g. * Resolve placeholder property values, e.g.
* <br /> * @param beanFactory beanFactory
* <br /> * @param beanName beanName
* "${somePropertyValue}" -> "the actual property value" * @param placeholder placeholder
* @return "${somePropertyValue}" -> "the actual property value"
*/ */
public Object resolvePropertyValue(ConfigurableBeanFactory beanFactory, String beanName, String placeholder) { public Object resolvePropertyValue(ConfigurableBeanFactory beanFactory, String beanName, String placeholder) {
// resolve string value // resolve string value
@ -74,6 +76,8 @@ public class PlaceholderHelper {
/** /**
* Extract keys from placeholder, e.g. * Extract keys from placeholder, e.g.
* @param propertyString propertyString
* @return
* <ul> * <ul>
* <li>${some.key} => "some.key"</li> * <li>${some.key} => "some.key"</li>
* <li>${some.key:${some.other.key:100}} => "some.key", "some.other.key"</li> * <li>${some.key:${some.other.key:100}} => "some.key", "some.other.key"</li>
@ -111,13 +115,15 @@ public class PlaceholderHelper {
// ${some.key:other.key} // ${some.key:other.key}
if (placeholderCandidate.startsWith(PLACEHOLDER_PREFIX)) { if (placeholderCandidate.startsWith(PLACEHOLDER_PREFIX)) {
stack.push(placeholderCandidate); stack.push(placeholderCandidate);
} else { }
else {
// some.key:${some.other.key:100} // some.key:${some.other.key:100}
int separatorIndex = placeholderCandidate.indexOf(VALUE_SEPARATOR); int separatorIndex = placeholderCandidate.indexOf(VALUE_SEPARATOR);
if (separatorIndex == -1) { if (separatorIndex == -1) {
stack.push(placeholderCandidate); stack.push(placeholderCandidate);
} else { }
else {
stack.push(placeholderCandidate.substring(0, separatorIndex)); stack.push(placeholderCandidate.substring(0, separatorIndex));
String defaultValuePart = String defaultValuePart =
normalizeToPlaceholder(placeholderCandidate.substring(separatorIndex + VALUE_SEPARATOR.length())); normalizeToPlaceholder(placeholderCandidate.substring(separatorIndex + VALUE_SEPARATOR.length()));
@ -169,13 +175,16 @@ public class PlaceholderHelper {
if (withinNestedPlaceholder > 0) { if (withinNestedPlaceholder > 0) {
withinNestedPlaceholder--; withinNestedPlaceholder--;
index = index + PLACEHOLDER_SUFFIX.length(); index = index + PLACEHOLDER_SUFFIX.length();
} else { }
else {
return index; return index;
} }
} else if (StringUtils.substringMatch(buf, index, SIMPLE_PLACEHOLDER_PREFIX)) { }
else if (StringUtils.substringMatch(buf, index, SIMPLE_PLACEHOLDER_PREFIX)) {
withinNestedPlaceholder++; withinNestedPlaceholder++;
index = index + SIMPLE_PLACEHOLDER_PREFIX.length(); index = index + SIMPLE_PLACEHOLDER_PREFIX.length();
} else { }
else {
index++; index++;
} }
} }

@ -51,7 +51,7 @@ public class SpringValue {
this.placeholder = placeholder; this.placeholder = placeholder;
this.targetType = field.getType(); this.targetType = field.getType();
this.isJson = isJson; this.isJson = isJson;
if(isJson){ if (isJson) {
this.genericType = field.getGenericType(); this.genericType = field.getGenericType();
} }
} }
@ -65,7 +65,7 @@ public class SpringValue {
Class<?>[] paramTps = method.getParameterTypes(); Class<?>[] paramTps = method.getParameterTypes();
this.targetType = paramTps[0]; this.targetType = paramTps[0];
this.isJson = isJson; this.isJson = isJson;
if(isJson){ if (isJson) {
this.genericType = method.getGenericParameterTypes()[0]; this.genericType = method.getGenericParameterTypes()[0];
} }
} }
@ -73,7 +73,8 @@ public class SpringValue {
public void update(Object newVal) throws IllegalAccessException, InvocationTargetException { public void update(Object newVal) throws IllegalAccessException, InvocationTargetException {
if (isField()) { if (isField()) {
injectField(newVal); injectField(newVal);
} else { }
else {
injectMethod(newVal); injectMethod(newVal);
} }
} }
@ -142,7 +143,8 @@ public class SpringValue {
} }
if (isField()) { if (isField()) {
return String return String
.format("key: %s, beanName: %s, field: %s.%s", key, beanName, bean.getClass().getName(), field.getName()); .format("key: %s, beanName: %s, field: %s.%s", key, beanName, bean.getClass()
.getName(), field.getName());
} }
return String.format("key: %s, beanName: %s, method: %s.%s", key, beanName, bean.getClass().getName(), return String.format("key: %s, beanName: %s, method: %s.%s", key, beanName, bean.getClass().getName(),
methodParameter.getMethod().getName()); methodParameter.getMethod().getName());

@ -74,17 +74,19 @@ public class SpringValueRegistry {
} }
private void initialize() { private void initialize() {
Executors.newSingleThreadScheduledExecutor(PolarisThreadFactory.create("SpringValueRegistry", true)).scheduleAtFixedRate( Executors.newSingleThreadScheduledExecutor(PolarisThreadFactory.create("SpringValueRegistry", true))
new Runnable() { .scheduleAtFixedRate(
@Override new Runnable() {
public void run() { @Override
try { public void run() {
scanAndClean(); try {
} catch (Throwable ex) { scanAndClean();
logger.error(ex.getMessage(), ex); }
} catch (Throwable ex) {
} logger.error(ex.getMessage(), ex);
}, CLEAN_INTERVAL_IN_SECONDS, CLEAN_INTERVAL_IN_SECONDS, TimeUnit.SECONDS); }
}
}, CLEAN_INTERVAL_IN_SECONDS, CLEAN_INTERVAL_IN_SECONDS, TimeUnit.SECONDS);
} }
private void scanAndClean() { private void scanAndClean() {

@ -41,7 +41,8 @@ public class SpringInjector {
if (s_injector == null) { if (s_injector == null) {
try { try {
s_injector = Guice.createInjector(new SpringModule()); s_injector = Guice.createInjector(new SpringModule());
} catch (Throwable ex) { }
catch (Throwable ex) {
PolarisConfigException exception = new PolarisConfigException("Unable to initialize Apollo Spring Injector!", ex); PolarisConfigException exception = new PolarisConfigException("Unable to initialize Apollo Spring Injector!", ex);
throw exception; throw exception;
} }
@ -55,7 +56,8 @@ public class SpringInjector {
public static <T> T getInstance(Class<T> clazz) { public static <T> T getInstance(Class<T> clazz) {
try { try {
return getInjector().getInstance(clazz); return getInjector().getInstance(clazz);
} catch (Throwable ex) { }
catch (Throwable ex) {
throw new PolarisConfigException( throw new PolarisConfigException(
String.format("Unable to load instance for %s!", clazz.getName()), ex); String.format("Unable to load instance for %s!", clazz.getName()), ex);
} }

@ -15,7 +15,7 @@ import org.slf4j.LoggerFactory;
*@date : 2022/6/28 09:26 *@date : 2022/6/28 09:26
*@description: *@description:
*/ */
public class PolarisThreadFactory implements ThreadFactory { public final class PolarisThreadFactory implements ThreadFactory {
private static Logger log = LoggerFactory.getLogger(PolarisThreadFactory.class); private static Logger log = LoggerFactory.getLogger(PolarisThreadFactory.class);
private final AtomicLong threadNumber = new AtomicLong(1); private final AtomicLong threadNumber = new AtomicLong(1);
@ -53,10 +53,12 @@ public class PolarisThreadFactory implements ThreadFactory {
log.info("Alive polaris threads: {}", alives); log.info("Alive polaris threads: {}", alives);
try { try {
TimeUnit.SECONDS.sleep(2); TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException ex) { }
catch (InterruptedException ex) {
// ignore // ignore
} }
} else { }
else {
log.info("All polaris threads are shutdown."); log.info("All polaris threads are shutdown.");
return true; return true;
} }
@ -66,9 +68,6 @@ public class PolarisThreadFactory implements ThreadFactory {
return false; return false;
} }
private interface ClassifyStandard<T> {
boolean satisfy(T thread);
}
private static <T> void classify(Set<T> src, Set<T> des, ClassifyStandard<T> standard) { private static <T> void classify(Set<T> src, Set<T> des, ClassifyStandard<T> standard) {
Set<T> set = new HashSet<>(); Set<T> set = new HashSet<>();
@ -87,7 +86,7 @@ public class PolarisThreadFactory implements ThreadFactory {
} }
public Thread newThread(Runnable runnable) { public Thread newThread(Runnable runnable) {
Thread thread = new Thread(threadGroup, runnable,// Thread thread = new Thread(threadGroup, runnable,
threadGroup.getName() + "-" + namePrefix + "-" + threadNumber.getAndIncrement()); threadGroup.getName() + "-" + namePrefix + "-" + threadNumber.getAndIncrement());
thread.setDaemon(daemon); thread.setDaemon(daemon);
if (thread.getPriority() != Thread.NORM_PRIORITY) { if (thread.getPriority() != Thread.NORM_PRIORITY) {
@ -95,4 +94,9 @@ public class PolarisThreadFactory implements ThreadFactory {
} }
return thread; return thread;
} }
private interface ClassifyStandard<T> {
boolean satisfy(T thread);
}
} }

@ -2,11 +2,11 @@ server:
port: 48084 port: 48084
spring: spring:
application: application:
name: polaris-config-example name: xiaozou
cloud: cloud:
polaris: polaris:
address: grpc://183.47.111.80:8091 address: grpc://183.47.111.80:8091
namespace: default namespace: xiaozou
config: config:
auto-refresh: true # auto refresh when config file changed auto-refresh: true # auto refresh when config file changed
groups: groups:

Loading…
Cancel
Save