Java源码示例:com.alipay.sofa.common.utils.StringUtil
示例1
/**
* 获取某个服务的所有提供方
*
* @return
*/
@GetMapping("query/services")
public List<ServiceModel> queryService(@RequestParam("serviceName") String serviceName) {
List<ServiceModel> data = new ArrayList<>();
Map<String, RpcService> rpcServices = registryDataCache.fetchService();
for (Map.Entry<String, RpcService> rpcServiceEntry : rpcServices.entrySet()) {
final String currentServiceName = rpcServiceEntry.getKey();
if (StringUtil.contains(currentServiceName, serviceName)) {
ServiceModel model = fetchServiceModel(currentServiceName);
data.add(model);
}
}
return data;
}
示例2
/**
* test logging.level.com.* config
* @throws IOException
*/
@Test
public void testWildLogLevel() throws IOException {
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(Constants.LOG_LEVEL_PREFIX + "test.*", "debug");
SpringApplication springApplication = new SpringApplication(EmptyConfig.class);
springApplication.setDefaultProperties(properties);
ConfigurableApplicationContext applicationContext = springApplication.run(new String[] {});
Environment environment = applicationContext.getEnvironment();
File logFile = getLogbackDefaultFile(environment);
FileUtils.write(logFile, StringUtil.EMPTY_STRING,
environment.getProperty(Constants.LOG_ENCODING_PROP_KEY));
logger.info("info level");
logger.debug("debug level");
List<String> contents = FileUtils.readLines(logFile,
environment.getProperty(Constants.LOG_ENCODING_PROP_KEY));
Assert.assertEquals(2, contents.size());
Assert.assertTrue(contents.get(0).contains("info level"));
Assert.assertTrue(contents.get(1).contains("debug level"));
LogEnvUtils.processGlobalSystemLogProperties()
.remove(Constants.LOG_LEVEL_PREFIX + "test.*");
}
示例3
/**
* test logging.level.{space id} config
* @throws IOException
*/
@Test
public void testSpecifyLogLevel() throws IOException {
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(Constants.LOG_LEVEL_PREFIX + "test.space", "debug");
SpringApplication springApplication = new SpringApplication(EmptyConfig.class);
springApplication.setDefaultProperties(properties);
ConfigurableApplicationContext applicationContext = springApplication.run(new String[] {});
Environment environment = applicationContext.getEnvironment();
File logFile = getLogbackDefaultFile(environment);
FileUtils.write(logFile, StringUtil.EMPTY_STRING,
environment.getProperty(Constants.LOG_ENCODING_PROP_KEY));
logger.info("info level");
logger.debug("debug level");
List<String> contents = FileUtils.readLines(logFile,
environment.getProperty(Constants.LOG_ENCODING_PROP_KEY));
Assert.assertEquals(2, contents.size());
Assert.assertTrue(contents.get(0).contains("info level"));
Assert.assertTrue(contents.get(1).contains("debug level"));
LogEnvUtils.processGlobalSystemLogProperties().remove(
Constants.LOG_LEVEL_PREFIX + "test.space");
}
示例4
/**
* test logging.config.{space id} config
* @throws IOException
*/
@Test
public void testLogConfig() throws IOException {
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(Constants.LOG_CONFIG_PREFIX + TEST_SPACE, "logback-test-conf.xml");
SpringApplication springApplication = new SpringApplication(EmptyConfig.class);
springApplication.setDefaultProperties(properties);
ConfigurableApplicationContext applicationContext = springApplication.run(new String[] {});
Environment environment = applicationContext.getEnvironment();
File logFile = getLogbackDefaultFile(environment);
FileUtils.write(logFile, StringUtil.EMPTY_STRING,
environment.getProperty(Constants.LOG_ENCODING_PROP_KEY));
logger.info("info level");
List<String> contents = FileUtils.readLines(logFile,
environment.getProperty(Constants.LOG_ENCODING_PROP_KEY));
Assert.assertEquals(1, contents.size());
Assert.assertTrue(contents.get(0).contains("logback-test-conf"));
LogEnvUtils.processGlobalSystemLogProperties().remove(
Constants.LOG_CONFIG_PREFIX + TEST_SPACE);
}
示例5
public String getMessage() {
String messageString = null;
if (this.message instanceof String) {
messageString = (String) this.message;
} else if (this.message instanceof Profiler.Message) {
Profiler.Message messageObject = (Profiler.Message) this.message;
Profiler.MessageLevel level = Profiler.MessageLevel.BRIEF_MESSAGE;
if (this.isReleased()) {
level = messageObject.getMessageLevel(this);
}
if (level == Profiler.MessageLevel.DETAILED_MESSAGE) {
messageString = messageObject.getDetailedMessage();
} else {
messageString = messageObject.getBriefMessage();
}
}
return StringUtil.defaultIfEmpty(messageString, (String) null);
}
示例6
/**
* Can also be used to manage JDK thread pool.
* SofaThreadPoolExecutor should **not** call this method!
* @param name thread pool name
* @param threadPoolExecutor thread pool instance
*/
public static void registerThreadPoolExecutor(String name, ThreadPoolExecutor threadPoolExecutor) {
if (StringUtil.isEmpty(name)) {
ThreadLogger.error("Rejected registering request of instance {} with empty name: {}.",
threadPoolExecutor, name);
return;
}
ThreadPoolExecutor existingExecutor = registry.putIfAbsent(name, threadPoolExecutor);
if (existingExecutor != null) {
ThreadLogger.error(
"Rejected registering request of instance {} with duplicate name: {}",
threadPoolExecutor, name);
} else {
ThreadLogger.info("Thread pool with name '{}' registered", name);
}
}
示例7
@Override
public String deleteMessage(String str) {
if (StringUtil.contains(str, "123")) {
return str + " deleted";
} else {
return "error args";
}
}
示例8
private void readLogConfiguration(String key, String value, Map<String, String> context,
String defaultValue) {
if (!StringUtil.isBlank(value)) {
context.put(key, value);
} else {
context.put(key, defaultValue);
}
}
示例9
public String getProperty(String key) {
String value = System.getProperty(key);
if (StringUtil.isBlank(value)) {
return (String) properties.get(key);
}
return value;
}
示例10
private Level getConsoleLevel(String spaceId, Properties properties) {
SystemPropertiesGetter propertiesGetter = new SystemPropertiesGetter(properties);
String level = propertiesGetter.getProperty(SOFA_MIDDLEWARE_ALL_LOG_CONSOLE_LEVEL);
String defaultLevel = StringUtil.isBlank(level) ? "INFO" : level;
level = propertiesGetter.getProperty(
String.format(SOFA_MIDDLEWARE_SINGLE_LOG_CONSOLE_LEVEL, spaceId), defaultLevel);
return Level.toLevel(level, Level.INFO);
}
示例11
private boolean isConsoleAppenderOpen(String spaceId, Properties properties) {
SystemPropertiesGetter propertiesGetter = new SystemPropertiesGetter(properties);
String value = propertiesGetter.getProperty(String.format(
SOFA_MIDDLEWARE_SINGLE_LOG_CONSOLE_SWITCH, spaceId));
if (StringUtil.isBlank(value)) {
return "true".equalsIgnoreCase(propertiesGetter
.getProperty(SOFA_MIDDLEWARE_ALL_LOG_CONSOLE_SWITCH));
} else {
return "true".equalsIgnoreCase(value);
}
}
示例12
private Level getConsoleLevel(String spaceId, Properties properties) {
SystemPropertiesGetter propertiesGetter = new SystemPropertiesGetter(properties);
String level = propertiesGetter.getProperty(SOFA_MIDDLEWARE_ALL_LOG_CONSOLE_LEVEL);
String defaultLevel = StringUtil.isBlank(level) ? "INFO" : level;
level = propertiesGetter.getProperty(
String.format(SOFA_MIDDLEWARE_SINGLE_LOG_CONSOLE_LEVEL, spaceId), defaultLevel);
return Level.toLevel(level, Level.INFO);
}
示例13
private boolean isConsoleAppenderOpen(String spaceId, Properties properties) {
SystemPropertiesGetter propertiesGetter = new SystemPropertiesGetter(properties);
String value = propertiesGetter.getProperty(String.format(
SOFA_MIDDLEWARE_SINGLE_LOG_CONSOLE_SWITCH, spaceId));
if (StringUtil.isBlank(value)) {
return "true".equalsIgnoreCase(propertiesGetter
.getProperty(SOFA_MIDDLEWARE_ALL_LOG_CONSOLE_SWITCH));
} else {
return "true".equalsIgnoreCase(value);
}
}
示例14
@Test
public void testDefaultLevel() throws IOException {
SpringApplication springApplication = new SpringApplication(EmptyConfig.class);
ConfigurableApplicationContext applicationContext = springApplication.run(new String[] {});
Environment environment = applicationContext.getEnvironment();
File logFile = getLogbackDefaultFile(environment);
FileUtils.write(logFile, StringUtil.EMPTY_STRING,
environment.getProperty(Constants.LOG_ENCODING_PROP_KEY));
logger.info("info level");
logger.debug("debug level");
List<String> contents = FileUtils.readLines(logFile,
environment.getProperty(Constants.LOG_ENCODING_PROP_KEY));
Assert.assertEquals(1, contents.size());
Assert.assertTrue(contents.get(0).contains("info level"));
}
示例15
/**
* test space config override global config
* @throws IOException
*/
@Test
public void testSpaceOverrideGlobalConfig() throws IOException {
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(Constants.SOFA_MIDDLEWARE_ALL_LOG_CONSOLE_SWITCH, "true");
properties.put(Constants.SOFA_MIDDLEWARE_ALL_LOG_CONSOLE_LEVEL, "debug");
properties
.put(String.format(Constants.SOFA_MIDDLEWARE_SINGLE_LOG_CONSOLE_SWITCH, TEST_SPACE),
"false");
properties.put(
String.format(Constants.SOFA_MIDDLEWARE_SINGLE_LOG_CONSOLE_LEVEL, TEST_SPACE), "info");
SpringApplication springApplication = new SpringApplication(EmptyConfig.class);
springApplication.setDefaultProperties(properties);
springApplication.run(new String[] {});
ConfigurableApplicationContext applicationContext = springApplication.run(new String[] {});
Environment environment = applicationContext.getEnvironment();
File logFile = getLogbackDefaultFile(environment);
FileUtils.write(logFile, StringUtil.EMPTY_STRING,
environment.getProperty(Constants.LOG_ENCODING_PROP_KEY));
logger.info("info level");
logger.debug("debug level");
List<String> contents = FileUtils.readLines(logFile,
environment.getProperty(Constants.LOG_ENCODING_PROP_KEY));
Assert.assertEquals(1, contents.size());
Assert.assertTrue(contents.get(0).contains("info level"));
Assert.assertFalse(outContent.toString().contains("info level"));
Assert.assertFalse(outContent.toString().contains("debug level"));
LogEnvUtils.processGlobalSystemLogProperties().remove(
Constants.SOFA_MIDDLEWARE_ALL_LOG_CONSOLE_SWITCH);
LogEnvUtils.processGlobalSystemLogProperties().remove(
Constants.SOFA_MIDDLEWARE_ALL_LOG_CONSOLE_LEVEL);
LogEnvUtils.processGlobalSystemLogProperties().remove(
String.format(Constants.SOFA_MIDDLEWARE_SINGLE_LOG_CONSOLE_SWITCH, TEST_SPACE));
LogEnvUtils.processGlobalSystemLogProperties().remove(
String.format(Constants.SOFA_MIDDLEWARE_SINGLE_LOG_CONSOLE_LEVEL, TEST_SPACE));
}
示例16
protected File getLogbackDefaultFile(Environment environment) {
String loggingRoot = environment.getProperty(Constants.LOG_PATH_PREFIX + TEST_SPACE);
if (StringUtil.isBlank(loggingRoot)) {
loggingRoot = environment.getProperty(Constants.LOG_PATH);
}
return new File(loggingRoot + File.separator + "test-space" + File.separator
+ "logback-common-default.log");
}
示例17
private static Enum createEnum(String name, Number value, boolean withValue) {
String enumClassName = null;
Class enumClass;
Enum enumObject;
try {
enumClassName = getCallerClassName();
enumClass = ClassLoaderUtil.loadClass(enumClassName);
enumObject = (Enum) enumClass.newInstance();
enumObject.setName(StringUtil.trimToNull(name));
} catch (ClassNotFoundException var8) {
throw new RuntimeException("Could not find enum class " + enumClassName, var8);
} catch (Exception var9) {
throw new RuntimeException("Could not instantiate enum instance of class "
+ enumClassName, var9);
}
if (withValue && value == null) {
throw new NullPointerException("The Enum value must not be null");
} else {
Enum.EnumType enumType = EnumUtil.getEnumType(enumClass);
boolean flagMode = enumObject instanceof Flags;
if (withValue) {
enumObject.value = enumType.setValue(value, flagMode);
} else {
enumObject.value = enumType.getNextValue(flagMode);
}
enumType.enumList.add(enumObject);
if (!enumType.valueMap.containsKey(enumObject.value)) {
enumType.valueMap.put(enumObject.value, enumObject);
}
if (enumObject.name != null && !enumType.nameMap.containsKey(enumObject.name)) {
enumType.nameMap.put(enumObject.name, enumObject);
}
return enumObject;
}
}
示例18
public void reInitialize(Map<String, String> environment) {
properties.putAll(environment);
String spaceLoggingPath = environment.get(Constants.LOG_PATH_PREFIX
+ spaceId.getSpaceName());
if (!StringUtil.isBlank(spaceLoggingPath)) {
properties.setProperty(Constants.LOG_PATH_PREFIX + spaceId.getSpaceName(),
spaceLoggingPath);
} else if (Boolean.TRUE.toString().equals(properties.getProperty(IS_DEFAULT_LOG_PATH))) {
properties.setProperty(Constants.LOG_PATH_PREFIX + spaceId.getSpaceName(),
properties.getProperty(LOG_PATH));
}
String loggingLevelKey = LOG_LEVEL_PREFIX + spaceId.getSpaceName();
if (Boolean.TRUE.toString().equals(properties.getProperty(Constants.IS_DEFAULT_LOG_LEVEL))
&& StringUtil.isBlank(environment.get(loggingLevelKey))) {
for (int i = Constants.LOG_LEVEL.length(); i < loggingLevelKey.length(); ++i) {
if (loggingLevelKey.charAt(i) == '.') {
String level = environment.get(loggingLevelKey.substring(0, i + 1)
+ Constants.LOG_START);
if (!StringUtil.isBlank(level)) {
properties.setProperty(loggingLevelKey, level);
}
}
}
}
String spaceLoggingConfig = environment.get(String.format(Constants.LOGGING_CONFIG_PATH,
spaceId.getSpaceName()));
if (!StringUtil.isBlank(spaceLoggingConfig)) {
confFile = this.getClass().getClassLoader().getResource(spaceLoggingConfig);
}
Iterator<LogbackReInitializer> matchers = ServiceLoader.load(LogbackReInitializer.class,
this.getClass().getClassLoader()).iterator();
if (matchers.hasNext()) {
LogbackReInitializer logbackReInitializer = matchers.next();
logbackReInitializer.reInitialize(spaceId, loggerContext, properties, confFile);
}
}
示例19
public void reInitialize(Map<String, String> environment) {
properties.putAll(environment);
String spaceLoggingPath = environment.get(Constants.LOG_PATH_PREFIX
+ spaceId.getSpaceName());
if (!StringUtil.isBlank(spaceLoggingPath)) {
properties.setProperty(Constants.LOG_PATH_PREFIX + spaceId.getSpaceName(),
spaceLoggingPath);
} else if (Boolean.TRUE.toString().equals(properties.getProperty(IS_DEFAULT_LOG_PATH))) {
properties.setProperty(Constants.LOG_PATH_PREFIX + spaceId.getSpaceName(),
properties.getProperty(LOG_PATH));
}
String loggingLevelKey = LOG_LEVEL_PREFIX + spaceId.getSpaceName();
if (Boolean.TRUE.toString().equals(properties.getProperty(Constants.IS_DEFAULT_LOG_LEVEL))
&& StringUtil.isBlank(environment.get(loggingLevelKey))) {
for (int i = Constants.LOG_LEVEL.length(); i < loggingLevelKey.length(); ++i) {
if (loggingLevelKey.charAt(i) == '.') {
String level = environment.get(loggingLevelKey.substring(0, i + 1)
+ Constants.LOG_START);
if (!StringUtil.isBlank(level)) {
properties.setProperty(loggingLevelKey, level);
}
}
}
}
String spaceLoggingConfig = environment.get(String.format(Constants.LOGGING_CONFIG_PATH,
spaceId.getSpaceName()));
if (!StringUtil.isBlank(spaceLoggingConfig)) {
confFile = this.getClass().getClassLoader().getResource(spaceLoggingConfig);
}
Iterator<Log4j2ReInitializer> matchers = ServiceLoader.load(Log4j2ReInitializer.class,
this.getClass().getClassLoader()).iterator();
if (matchers.hasNext()) {
Log4j2ReInitializer log4j2ReInitializer = matchers.next();
log4j2ReInitializer.reInitialize(spaceId, loggerContext, properties, confFile);
}
}
示例20
private void specifySpaceLogConfigProperties(String spaceName) {
/*
* == 1.space's logger path
*/
String loggingPathKey = LOG_PATH_PREFIX + spaceName;
String defaultLoggingPath = spaceInfo.getProperty(LOG_PATH);
if (spaceInfo.getProperty(loggingPathKey) == null) {
spaceInfo.setProperty(IS_DEFAULT_LOG_PATH, Boolean.TRUE.toString());
spaceInfo.setProperty(loggingPathKey, defaultLoggingPath);
}
/*
* == 2.space's logger level
*/
String loggingLevelKey = LOG_LEVEL_PREFIX + spaceName;
if (spaceInfo.getProperty(loggingLevelKey) == null) {
spaceInfo.setProperty(IS_DEFAULT_LOG_LEVEL, Boolean.TRUE.toString());
spaceInfo.setProperty(loggingLevelKey, DEFAULT_MIDDLEWARE_SPACE_LOG_LEVEL);
for (int i = LOG_LEVEL.length(); i < loggingLevelKey.length(); ++i) {
if (loggingLevelKey.charAt(i) == '.') {
String level = spaceInfo.getProperty(loggingLevelKey.substring(0, i + 1)
+ LOG_START);
if (!StringUtil.isBlank(level)) {
spaceInfo.setProperty(loggingLevelKey, level);
}
}
}
}
}
示例21
@Override
public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
// 解决自动重连情况下出现的空指针问题
ChildData data = event.getData();
if (data == null) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("event type : {}", event.getType());
}
return;
}
final String path = data.getPath();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("provider : {}", path);
}
switch (event.getType()) {
case CHILD_ADDED:
String providerData = StringUtil.substringAfterLast(path, "/");
String serviceName = StringUtil.substringBetween(path, "/sofa-rpc/", "/providers/");
List<RpcProvider> providerDataList = new ArrayList<>();
providerDataList.add(convert2Provider(serviceName, providerData));
registryDataCache.addProviders(serviceName, providerDataList);
break;
case CHILD_REMOVED:
List<RpcProvider> removeProviders = new ArrayList<>();
String removeProviderData = StringUtil.substringAfterLast(path, "/");
String removeServiceName = StringUtil.substringBetween(path, "/sofa-rpc/",
"/providers/");
removeProviders.add(convert2Provider(removeServiceName, removeProviderData));
registryDataCache.removeProviders(removeServiceName, removeProviders);
break;
case CHILD_UPDATED:
List<RpcProvider> updateProviders = new ArrayList<>();
String updateProviderData = StringUtil.substringAfterLast(path, "/");
String updateServiceName = StringUtil.substringBetween(path, "/sofa-rpc/",
"/providers/");
updateProviders.add(convert2Provider(updateServiceName, updateProviderData));
registryDataCache.updateProviders(updateServiceName, updateProviders);
break;
default:
break;
}
}
示例22
@Override
public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) {
// 解决自动重连情况下出现的空指针问题
ChildData data = event.getData();
if (data == null) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("event type : {}", event.getType());
}
return;
}
final String path = data.getPath();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("consumer : {}", path);
}
switch (event.getType()) {
case CHILD_ADDED:
String addConsumerData = StringUtil.substringAfterLast(path, "/");
String addServiceName = StringUtil.substringBetween(path, "/sofa-rpc/",
"/consumers/");
List<RpcConsumer> addConsumers = new ArrayList<>();
addConsumers.add(convert2Consumer(addServiceName, addConsumerData));
registryDataCache.addConsumers(addServiceName, addConsumers);
break;
case CHILD_REMOVED:
String removeConsumerData = StringUtil.substringAfterLast(path, "/");
String removeServiceName = StringUtil.substringBetween(path, "/sofa-rpc/",
"/consumers/");
List<RpcConsumer> removeConsumers = new ArrayList<>();
removeConsumers.add(convert2Consumer(removeServiceName, removeConsumerData));
registryDataCache.removeConsumers(removeServiceName, removeConsumers);
break;
case CHILD_UPDATED:
String updateConsumerData = StringUtil.substringAfterLast(path, "/");
String updateServiceName = StringUtil.substringBetween(path, "/sofa-rpc/",
"/consumers/");
List<RpcConsumer> updateConsumers = new ArrayList<>();
updateConsumers.add(convert2Consumer(updateServiceName, updateConsumerData));
registryDataCache.updateConsumers(updateServiceName, updateConsumers);
break;
default:
break;
}
}
示例23
private void addToGlobalSystemProperties(String key, String value) {
if (!StringUtil.isBlank(key) && !StringUtil.isBlank(value)) {
LogEnvUtils.processGlobalSystemLogProperties().put(key, value);
}
}
示例24
private void readLogConfiguration(String key, String value, Map<String, String> context) {
if (!StringUtil.isBlank(value)) {
context.put(key, value);
}
}
示例25
public String getProperty(String key, String defaultValue) {
String value = getProperty(key);
return StringUtil.isBlank(value) ? defaultValue : value;
}
示例26
public static void setConsoleLevel(String level) {
Level value = LEVELS.get(level.toUpperCase());
if (!StringUtil.isBlank(level) && value != null) {
consoleLogLevel = value;
}
}