From 85df9e077fa76471e8c843f0360a88ec81196180 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Sun, 30 Sep 2018 16:41:40 +0800 Subject: [PATCH 01/30] Fixed alibaba/nacos#98 --- api/pom.xml | 2 +- client/pom.xml | 2 +- common/pom.xml | 2 +- config/pom.xml | 2 +- .../server/controller/CommunicationController.java | 8 ++++---- .../config/server/controller/ConfigServletInner.java | 8 ++++---- .../{LongPullingService.java => LongPollingService.java} | 9 ++++----- console/pom.xml | 2 +- core/pom.xml | 2 +- distribution/pom.xml | 2 +- example/pom.xml | 2 +- naming/pom.xml | 2 +- pom.xml | 4 ++-- test/pom.xml | 2 +- 14 files changed, 24 insertions(+), 25 deletions(-) rename config/src/main/java/com/alibaba/nacos/config/server/service/{LongPullingService.java => LongPollingService.java} (98%) diff --git a/api/pom.xml b/api/pom.xml index 6bec84582..28f6ff2b5 100644 --- a/api/pom.xml +++ b/api/pom.xml @@ -16,7 +16,7 @@ com.alibaba.nacos nacos-all - 0.2.1 + 0.2.2-SNAPSHOT 4.0.0 diff --git a/client/pom.xml b/client/pom.xml index dcf7bcc87..9c9f368c0 100644 --- a/client/pom.xml +++ b/client/pom.xml @@ -16,7 +16,7 @@ com.alibaba.nacos nacos-all - 0.2.1 + 0.2.2-SNAPSHOT 4.0.0 diff --git a/common/pom.xml b/common/pom.xml index 27684516c..2a89ef3d5 100644 --- a/common/pom.xml +++ b/common/pom.xml @@ -18,7 +18,7 @@ com.alibaba.nacos nacos-all - 0.2.1 + 0.2.2-SNAPSHOT 4.0.0 diff --git a/config/pom.xml b/config/pom.xml index 7085dcb91..d2b5033c5 100644 --- a/config/pom.xml +++ b/config/pom.xml @@ -17,7 +17,7 @@ com.alibaba.nacos nacos-all - 0.2.1 + 0.2.2-SNAPSHOT 4.0.0 diff --git a/config/src/main/java/com/alibaba/nacos/config/server/controller/CommunicationController.java b/config/src/main/java/com/alibaba/nacos/config/server/controller/CommunicationController.java index f1f6651b2..2f7197370 100755 --- a/config/src/main/java/com/alibaba/nacos/config/server/controller/CommunicationController.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/controller/CommunicationController.java @@ -32,7 +32,7 @@ import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.nacos.config.server.constant.Constants; import com.alibaba.nacos.config.server.model.SampleResult; -import com.alibaba.nacos.config.server.service.LongPullingService; +import com.alibaba.nacos.config.server.service.LongPollingService; import com.alibaba.nacos.config.server.service.dump.DumpService; import com.alibaba.nacos.config.server.service.notify.NotifyService; @@ -51,7 +51,7 @@ public class CommunicationController { private DumpService dumpService; @Autowired - protected LongPullingService longPullingService; + protected LongPollingService longPollingService; private String trueStr = "true"; @@ -92,7 +92,7 @@ public class CommunicationController { ModelMap modelMap) throws IOException, ServletException, Exception { group = StringUtils.isBlank(group) ? Constants.DEFAULT_GROUP : group; - SampleResult sampleResult = longPullingService.getCollectSubscribleInfo(dataId, group, tenant); + SampleResult sampleResult = longPollingService.getCollectSubscribleInfo(dataId, group, tenant); return sampleResult; } @@ -106,7 +106,7 @@ public class CommunicationController { @RequestParam("ip") String ip, ModelMap modelMap) throws IOException, ServletException, Exception { - SampleResult sampleResult = longPullingService.getCollectSubscribleInfoByIp(ip); + SampleResult sampleResult = longPollingService.getCollectSubscribleInfoByIp(ip); return sampleResult; } } diff --git a/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigServletInner.java b/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigServletInner.java index 35a3e90e6..cc7cae477 100755 --- a/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigServletInner.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigServletInner.java @@ -40,7 +40,7 @@ import com.alibaba.nacos.config.server.model.CacheItem; import com.alibaba.nacos.config.server.model.ConfigInfoBase; import com.alibaba.nacos.config.server.service.ConfigService; import com.alibaba.nacos.config.server.service.DiskUtil; -import com.alibaba.nacos.config.server.service.LongPullingService; +import com.alibaba.nacos.config.server.service.LongPollingService; import com.alibaba.nacos.config.server.service.PersistService; import com.alibaba.nacos.config.server.service.trace.ConfigTraceService; import com.alibaba.nacos.config.server.utils.GroupKey2; @@ -60,7 +60,7 @@ import com.alibaba.nacos.config.server.utils.TimeUtils; public class ConfigServletInner { @Autowired - private LongPullingService longPullingService; + private LongPollingService longPollingService; @Autowired private PersistService persistService; @@ -74,8 +74,8 @@ public class ConfigServletInner { public String doPollingConfig(HttpServletRequest request, HttpServletResponse response, Map clientMd5Map, int probeRequestSize) throws IOException, ServletException { // 长轮询 - if (LongPullingService.isSupportLongPulling(request)) { - longPullingService.addLongPullingClient(request, response, clientMd5Map, probeRequestSize); + if (LongPollingService.isSupportLongPulling(request)) { + longPollingService.addLongPullingClient(request, response, clientMd5Map, probeRequestSize); return HttpServletResponse.SC_OK + ""; } diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/LongPullingService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/LongPollingService.java similarity index 98% rename from config/src/main/java/com/alibaba/nacos/config/server/service/LongPullingService.java rename to config/src/main/java/com/alibaba/nacos/config/server/service/LongPollingService.java index 1609dce8e..b848132fd 100755 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/LongPullingService.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/LongPollingService.java @@ -18,7 +18,6 @@ package com.alibaba.nacos.config.server.service; import static com.alibaba.nacos.config.server.utils.LogUtil.memoryLog; import static com.alibaba.nacos.config.server.utils.LogUtil.pullLog; -import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -57,7 +56,7 @@ import com.alibaba.nacos.config.server.utils.event.EventDispatcher.Event; * @author Nacos */ @Service -public class LongPullingService extends AbstractEventListener { +public class LongPollingService extends AbstractEventListener { private static final int FIXED_POLLING_INTERVAL_MS = 10000; @@ -222,8 +221,8 @@ public class LongPullingService extends AbstractEventListener { public void addLongPullingClient(HttpServletRequest req, HttpServletResponse rsp, Map clientMd5Map, int probeRequestSize) { - String str = req.getHeader(LongPullingService.LONG_PULLING_HEADER); - String noHangUpFlag = req.getHeader(LongPullingService.LONG_PULLING_NO_HANG_UP_HEADER); + String str = req.getHeader(LongPollingService.LONG_PULLING_HEADER); + String noHangUpFlag = req.getHeader(LongPollingService.LONG_PULLING_NO_HANG_UP_HEADER); String appName = req.getHeader(RequestUtil.CLIENT_APPNAME_HEADER); String tag = req.getHeader("Vipserver-Tag"); int delayTime=SwitchService.getSwitchInteger(SwitchService.FIXED_DELAY_TIME, 500); @@ -285,7 +284,7 @@ public class LongPullingService extends AbstractEventListener { } @SuppressWarnings("PMD.ThreadPoolCreationRule") - public LongPullingService() { + public LongPollingService() { allSubs = new ConcurrentLinkedQueue(); scheduler = Executors.newScheduledThreadPool(1, new ThreadFactory() { diff --git a/console/pom.xml b/console/pom.xml index 3b96e6e77..dceefbcf4 100644 --- a/console/pom.xml +++ b/console/pom.xml @@ -18,7 +18,7 @@ com.alibaba.nacos nacos-all - 0.2.1 + 0.2.2-SNAPSHOT nacos-console diff --git a/core/pom.xml b/core/pom.xml index 079481765..25ae61ec9 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -18,7 +18,7 @@ com.alibaba.nacos nacos-all - 0.2.1 + 0.2.2-SNAPSHOT 4.0.0 diff --git a/distribution/pom.xml b/distribution/pom.xml index b780cae49..7d42c622d 100644 --- a/distribution/pom.xml +++ b/distribution/pom.xml @@ -18,7 +18,7 @@ com.alibaba.nacos nacos-all - 0.2.1 + 0.2.2-SNAPSHOT 4.0.0 diff --git a/example/pom.xml b/example/pom.xml index fe588b550..84e6b2971 100644 --- a/example/pom.xml +++ b/example/pom.xml @@ -18,7 +18,7 @@ com.alibaba.nacos nacos-all - 0.2.1 + 0.2.2-SNAPSHOT 4.0.0 diff --git a/naming/pom.xml b/naming/pom.xml index 88642e0ba..fb763c2d6 100644 --- a/naming/pom.xml +++ b/naming/pom.xml @@ -18,7 +18,7 @@ com.alibaba.nacos nacos-all - 0.2.1 + 0.2.2-SNAPSHOT 4.0.0 diff --git a/pom.xml b/pom.xml index 87cc8c1f3..2d109efa3 100644 --- a/pom.xml +++ b/pom.xml @@ -21,7 +21,7 @@ 2018 com.alibaba.nacos nacos-all - 0.2.1 + 0.2.2-SNAPSHOT pom Alibaba NACOS ${project.version} @@ -36,7 +36,7 @@ git@github.com:alibaba/nacos.git scm:git@github.com:alibaba/nacos.git scm:git@github.com:alibaba/nacos.git - nacos-all-0.2.1-RC1 + nacos-all-0.2.2-SNAPSHOT diff --git a/test/pom.xml b/test/pom.xml index cd1a7f6b5..9e255cfce 100644 --- a/test/pom.xml +++ b/test/pom.xml @@ -17,7 +17,7 @@ com.alibaba.nacos nacos-all - 0.2.1 + 0.2.2-SNAPSHOT 4.0.0 From 7b2549131b530f410866be19400fc4b70ca73165 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Sun, 30 Sep 2018 20:54:43 +0800 Subject: [PATCH 02/30] Move the location of SQL scripts --- config/src/main/resources/{ => META-INF}/nacos-db.sql | 0 config/src/main/resources/{ => META-INF}/schema.sql | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename config/src/main/resources/{ => META-INF}/nacos-db.sql (100%) rename config/src/main/resources/{ => META-INF}/schema.sql (100%) diff --git a/config/src/main/resources/nacos-db.sql b/config/src/main/resources/META-INF/nacos-db.sql similarity index 100% rename from config/src/main/resources/nacos-db.sql rename to config/src/main/resources/META-INF/nacos-db.sql diff --git a/config/src/main/resources/schema.sql b/config/src/main/resources/META-INF/schema.sql similarity index 100% rename from config/src/main/resources/schema.sql rename to config/src/main/resources/META-INF/schema.sql From ae0feb80f40c9060e081f3b3dfdef384f009b74d Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Sun, 30 Sep 2018 20:55:20 +0800 Subject: [PATCH 03/30] Move the location of SQL scripts for code --- .../nacos/config/server/service/LocalDataSourceServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/LocalDataSourceServiceImpl.java b/config/src/main/java/com/alibaba/nacos/config/server/service/LocalDataSourceServiceImpl.java index 527ce5503..6760c9ceb 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/LocalDataSourceServiceImpl.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/LocalDataSourceServiceImpl.java @@ -98,7 +98,7 @@ public class LocalDataSourceServiceImpl implements DataSourceService { throw new RuntimeException("datasource is null"); } try { - execute(ds.getConnection(), "schema.sql"); + execute(ds.getConnection(), "META-INF/schema.sql"); } catch (Exception e) { throw new RuntimeException("load schema.sql error." + e); } From 4f273e70c5b4e0d3d7392be3e8af8fb2735f1c24 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Mon, 1 Oct 2018 00:12:31 +0800 Subject: [PATCH 04/30] Add Configurations for Database --- .../configuration/DataBaseConfiguration.java | 63 ++++++++++++++++ .../LocalDataSourceConfiguration.java | 75 +++++++++++++++++++ 2 files changed, 138 insertions(+) create mode 100644 config/src/main/java/com/alibaba/nacos/config/server/configuration/DataBaseConfiguration.java create mode 100644 config/src/main/java/com/alibaba/nacos/config/server/configuration/LocalDataSourceConfiguration.java diff --git a/config/src/main/java/com/alibaba/nacos/config/server/configuration/DataBaseConfiguration.java b/config/src/main/java/com/alibaba/nacos/config/server/configuration/DataBaseConfiguration.java new file mode 100644 index 000000000..791326351 --- /dev/null +++ b/config/src/main/java/com/alibaba/nacos/config/server/configuration/DataBaseConfiguration.java @@ -0,0 +1,63 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.nacos.config.server.configuration; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.transaction.PlatformTransactionManager; + +import javax.sql.DataSource; + +/** + * DataBase {@link Configuration} + * + * @author Mercy + * @since 0.2.2 + */ +@Configuration +public class DataBaseConfiguration { + + /** + * The bean name of {@link DataSource} for Nacos Config + */ + public static final String DATA_SOURCE_BEAN_NAME = "nacosDataSource"; + + @Bean + @Autowired + public JdbcTemplate jdbcTemplate(@Qualifier(DATA_SOURCE_BEAN_NAME) DataSource dataSource, Environment environment) { + JdbcTemplate jdbcTemplate = new JdbcTemplate(); + jdbcTemplate = new JdbcTemplate(); + jdbcTemplate.setMaxRows(50000); + jdbcTemplate.setQueryTimeout(5000); + jdbcTemplate.setDataSource(dataSource); + return jdbcTemplate; + } + + @Bean + @Autowired + public PlatformTransactionManager transactionManager(@Qualifier(DATA_SOURCE_BEAN_NAME) DataSource dataSource) { + DataSourceTransactionManager manager = new DataSourceTransactionManager(); + manager.setDataSource(dataSource); + return manager; + } + +} diff --git a/config/src/main/java/com/alibaba/nacos/config/server/configuration/LocalDataSourceConfiguration.java b/config/src/main/java/com/alibaba/nacos/config/server/configuration/LocalDataSourceConfiguration.java new file mode 100644 index 000000000..03508bcc8 --- /dev/null +++ b/config/src/main/java/com/alibaba/nacos/config/server/configuration/LocalDataSourceConfiguration.java @@ -0,0 +1,75 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.nacos.config.server.configuration; + +import org.apache.commons.dbcp.BasicDataSource; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.core.env.Environment; + +import javax.sql.DataSource; +import java.io.File; +import java.util.concurrent.TimeUnit; + +import static com.alibaba.nacos.config.server.configuration.DataBaseConfiguration.DATA_SOURCE_BEAN_NAME; + +/** + * Local {@link DataSource} {@link Configuration} + * + * @author Mercy + * @since 0.2.2 + */ +@Profile("standalone") +@Configuration +public class LocalDataSourceConfiguration { + + private static final String JDBC_DRIVER_NAME = "org.apache.derby.jdbc.EmbeddedDriver"; + + private static final String DERBY_BASE_DIR = "data" + File.separator + "derby-data"; + + private static final String NACOS_HOME_KEY = "nacos.home"; + + private static final String DEFAULT_APP_NAME = System.getProperty("user.home") + File.separator + "nacos"; + + private static final String APP_HOME = System.getProperty(NACOS_HOME_KEY, DEFAULT_APP_NAME); + + private static final String DATAS_SOURCE_URL = "jdbc:derby:" + APP_HOME + File.separator + DERBY_BASE_DIR + + ";create=true"; + + private static final String USER_NAME = "nacos"; + + private static final String PASSWORD = "nacos"; + + @Bean(name = DATA_SOURCE_BEAN_NAME) + public DataSource dataSource(Environment environment) { + BasicDataSource ds = new BasicDataSource(); + ds.setDriverClassName(JDBC_DRIVER_NAME); + ds.setUrl(DATAS_SOURCE_URL); + ds.setUsername(USER_NAME); + ds.setPassword(PASSWORD); + ds.setInitialSize(environment.getProperty("db.initialSize", int.class, 20)); + ds.setMaxActive(environment.getProperty("db.maxActive", int.class, 30)); + ds.setMaxIdle(environment.getProperty("db.maxIdle", int.class, 50)); + ds.setMaxWait(environment.getProperty("db.maxWait", long.class, 10000L)); + ds.setPoolPreparedStatements(true); + ds.setTimeBetweenEvictionRunsMillis(TimeUnit.MINUTES.toMillis(10L)); + ds.setTestWhileIdle(true); + return ds; + } + +} From 421e9a347f8e66ea434f42d779643aa7fff8ee89 Mon Sep 17 00:00:00 2001 From: xiaomage <1191971402@qq.com> Date: Mon, 1 Oct 2018 10:00:29 +0800 Subject: [PATCH 05/30] Bug fix --- config/pom.xml | 326 +++++++++--------- .../alibaba/nacos/config/server/Config.java | 17 +- .../ClusterDataSourceConfiguration.java | 198 +++++++++++ .../configuration/DataBaseConfiguration.java | 126 +++---- .../LocalDataSourceConfiguration.java | 150 ++++---- .../service/LocalDataSourceServiceImpl.java | 93 ++--- .../server/service/ServerListService.java | 4 +- .../LocalDataSourceConfigurationTest.java | 91 +++++ naming/src/main/resources/naming-logback.xml | 1 - pom.xml | 4 +- 10 files changed, 656 insertions(+), 354 deletions(-) create mode 100644 config/src/main/java/com/alibaba/nacos/config/server/configuration/ClusterDataSourceConfiguration.java create mode 100644 config/src/test/java/com/alibaba/nacos/config/server/configuration/LocalDataSourceConfigurationTest.java diff --git a/config/pom.xml b/config/pom.xml index d2b5033c5..a7f0b7a6f 100644 --- a/config/pom.xml +++ b/config/pom.xml @@ -12,169 +12,179 @@ limitations under the License. --> + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - - com.alibaba.nacos - nacos-all - 0.2.2-SNAPSHOT - + + com.alibaba.nacos + nacos-all + 0.2.2-SNAPSHOT + - 4.0.0 + 4.0.0 - nacos-config - jar + nacos-config + jar - nacos-config ${project.version} - http://maven.apache.org + nacos-config ${project.version} + http://maven.apache.org - - UTF-8 - + + UTF-8 + - - - junit - junit - test - - - org.springframework.boot - spring-boot-starter-web - - - ${project.groupId} - nacos-core - - - com.google.guava - guava - - - taglibs - standard - - - org.springframework.boot - spring-boot-starter-jdbc - - - commons-io - commons-io - - - commons-lang - commons-lang - - - mysql - mysql-connector-java - - - commons-dbcp - commons-dbcp - - - org.apache.derby - derby - - - ch.qos.logback - logback-classic - + - - - org.aspectj - aspectjrt - - - cglib - cglib-nodep - - - org.apache.httpcomponents - httpasyncclient - - - - - org.springframework.boot - spring-boot-starter-tomcat - - - org.codehaus.jackson - jackson-mapper-lgpl - - - net.jcip - jcip-annotations - true - - - com.github.spotbugs - spotbugs-annotations - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - true - -Dnacos.standalone=true - - - - org.apache.maven.plugins - maven-assembly-plugin - - - - com.alibaba.nacos.config.server.Config - - - - jar-with-dependencies - - - - - - - true - src/main/resources - - application.properties - banner.txt - schema.sql - nacos-db.sql - - - - - - - springboot - - - com.alibaba.nacos - nacos-core - - - - - - org.springframework.boot - spring-boot-maven-plugin - - com.alibaba.nacos.config.server.Config - - - - nacos-config - - - + + + com.alibaba.spring + spring-context-support + 1.0.1 + + + + org.springframework.boot + spring-boot-starter-web + + + ${project.groupId} + nacos-core + + + com.google.guava + guava + + + taglibs + standard + + + org.springframework.boot + spring-boot-starter-jdbc + + + commons-io + commons-io + + + commons-lang + commons-lang + + + mysql + mysql-connector-java + + + commons-dbcp + commons-dbcp + + + org.apache.derby + derby + + + ch.qos.logback + logback-classic + + + + + org.aspectj + aspectjrt + + + cglib + cglib-nodep + + + org.apache.httpcomponents + httpasyncclient + + + + + org.springframework.boot + spring-boot-starter-tomcat + + + org.codehaus.jackson + jackson-mapper-lgpl + + + net.jcip + jcip-annotations + true + + + com.github.spotbugs + spotbugs-annotations + + + + junit + junit + test + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + true + -Dnacos.standalone=true + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + com.alibaba.nacos.config.server.Config + + + + jar-with-dependencies + + + + + + + true + src/main/resources + + application.properties + banner.txt + schema.sql + nacos-db.sql + + + + + + + springboot + + + com.alibaba.nacos + nacos-core + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.alibaba.nacos.config.server.Config + + + + nacos-config + + + diff --git a/config/src/main/java/com/alibaba/nacos/config/server/Config.java b/config/src/main/java/com/alibaba/nacos/config/server/Config.java index 3b2c0e0a9..01c9d5134 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/Config.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/Config.java @@ -25,16 +25,15 @@ import org.springframework.boot.web.servlet.ServletComponentScan; /** * Config main - * - * @author Nacos * + * @author Nacos */ -@SpringBootApplication(scanBasePackages = "com.alibaba.nacos.config.server") -@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) -@ServletComponentScan +@SpringBootApplication( + scanBasePackages = "com.alibaba.nacos.config.server", + exclude = {DataSourceAutoConfiguration.class}) public class Config { - public static void main(String[] args) throws UnknownHostException { - SpringApplication.run(Config.class, args); - } - + public static void main(String[] args) throws UnknownHostException { + SpringApplication.run(Config.class, args); + } + } diff --git a/config/src/main/java/com/alibaba/nacos/config/server/configuration/ClusterDataSourceConfiguration.java b/config/src/main/java/com/alibaba/nacos/config/server/configuration/ClusterDataSourceConfiguration.java new file mode 100644 index 000000000..c4e44cde1 --- /dev/null +++ b/config/src/main/java/com/alibaba/nacos/config/server/configuration/ClusterDataSourceConfiguration.java @@ -0,0 +1,198 @@ +///* +// * Licensed to the Apache Software Foundation (ASF) under one or more +// * contributor license agreements. See the NOTICE file distributed with +// * this work for additional information regarding copyright ownership. +// * The ASF licenses this file to You under the Apache License, Version 2.0 +// * (the "License"); you may not use this file except in compliance with +// * the License. You may obtain a copy of the License at +// * +// * http://www.apache.org/licenses/LICENSE-2.0 +// * +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an "AS IS" BASIS, +// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// * See the License for the specific language governing permissions and +// * limitations under the License. +// */ +//package com.alibaba.nacos.config.server.configuration; +// +//import com.alibaba.nacos.config.server.service.BasicDataSourceServiceImpl; +//import com.alibaba.nacos.config.server.service.TimerTaskService; +//import com.alibaba.nacos.config.server.utils.PropertyUtil; +//import org.apache.commons.dbcp.BasicDataSource; +//import org.apache.commons.lang.math.NumberUtils; +//import org.springframework.context.annotation.Configuration; +//import org.springframework.context.annotation.Profile; +//import org.springframework.jdbc.core.JdbcTemplate; +//import org.springframework.jdbc.datasource.DataSourceTransactionManager; +//import org.springframework.transaction.support.TransactionTemplate; +// +//import javax.annotation.PostConstruct; +//import javax.sql.DataSource; +//import java.io.IOException; +//import java.util.ArrayList; +//import java.util.List; +//import java.util.concurrent.TimeUnit; +//import java.util.regex.Pattern; +// +//import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog; +// +///** +// * Cluster {@link DataSource} {@link Configuration} +// * +// * @author Mercy +// * @since 0.2.2 +// */ +//@Profile("!standalone") +//@Configuration +//public class ClusterDataSourceConfiguration { +// +// private static final String JDBC_DRIVER_NAME = "com.mysql.jdbc.Driver"; +// +// /** +// * JDBC执行超时时间, 单位秒 +// */ +// private int queryTimeout = 3; +// +// private static final int TRANSACTION_QUERY_TIMEOUT = 5; +// +// private static final String DB_LOAD_ERROR_MSG = "[db-load-error]load jdbc.properties error"; +// +// private List dataSourceList = new ArrayList(); +// private JdbcTemplate jt; +// private DataSourceTransactionManager tm; +// private TransactionTemplate tjt; +// +// private JdbcTemplate testMasterJT; +// private JdbcTemplate testMasterWritableJT; +// +// volatile private List testJTList; +// volatile private List isHealthList; +// private volatile int masterIndex; +// private static Pattern ipPattern = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"); +// +// +// +// @PostConstruct +// public void init() { +// queryTimeout = NumberUtils +// .toInt(System.getProperty("QUERYTIMEOUT"), 3); +// jt = new JdbcTemplate(); +// /** +// * 设置最大记录数,防止内存膨胀 +// */ +// jt.setMaxRows(50000); +// jt.setQueryTimeout(queryTimeout); +// +// testMasterJT = new JdbcTemplate(); +// testMasterJT.setQueryTimeout(queryTimeout); +// +// testMasterWritableJT = new JdbcTemplate(); +// /** +// * 防止login接口因为主库不可用而rt太长 +// */ +// testMasterWritableJT.setQueryTimeout(1); +// /** +// * 数据库健康检测 +// */ +// testJTList = new ArrayList(); +// isHealthList = new ArrayList(); +// +// tm = new DataSourceTransactionManager(); +// tjt = new TransactionTemplate(tm); +// /** +// * 事务的超时时间需要与普通操作区分开 +// */ +// tjt.setTimeout(TRANSACTION_QUERY_TIMEOUT); +// if (!PropertyUtil.isStandaloneMode()) { +// try { +// reload(); +// } catch (IOException e) { +// e.printStackTrace(); +// throw new RuntimeException(DB_LOAD_ERROR_MSG); +// } +// +// TimerTaskService.scheduleWithFixedDelay(new BasicDataSourceServiceImpl.SelectMasterTask(), 10, 10, +// TimeUnit.SECONDS); +// TimerTaskService.scheduleWithFixedDelay(new BasicDataSourceServiceImpl.CheckDBHealthTask(), 10, 10, +// TimeUnit.SECONDS); +// } +// } +// +// public synchronized void reload() throws IOException { +// List dblist = new ArrayList(); +// try { +// String val = null; +// val = env.getProperty("db.num"); +// if (null == val) { +// throw new IllegalArgumentException("db.num is null"); +// } +// int dbNum = Integer.parseInt(val.trim()); +// +// for (int i = 0; i < dbNum; i++) { +// BasicDataSource ds = new BasicDataSource(); +// ds.setDriverClassName(JDBC_DRIVER_NAME); +// +// val = env.getProperty("db.url." + i); +// if (null == val) { +// fatalLog.error("db.url." + i + " is null"); +// throw new IllegalArgumentException(); +// } +// ds.setUrl(val.trim()); +// +// val = env.getProperty("db.user"); +// if (null == val) { +// fatalLog.error("db.user is null"); +// throw new IllegalArgumentException(); +// } +// ds.setUsername(val.trim()); +// +// val = env.getProperty("db.password"); +// if (null == val) { +// fatalLog.error("db.password is null"); +// throw new IllegalArgumentException(); +// } +// ds.setPassword(val.trim()); +// +// val = env.getProperty("db.initialSize"); +// ds.setInitialSize(Integer.parseInt(defaultIfNull(val, "10"))); +// +// val = env.getProperty("db.maxActive"); +// ds.setMaxActive(Integer.parseInt(defaultIfNull(val, "20"))); +// +// val = env.getProperty("db.maxIdle"); +// ds.setMaxIdle(Integer.parseInt(defaultIfNull(val, "50"))); +// +// ds.setMaxWait(3000L); +// ds.setPoolPreparedStatements(true); +// +// // 每10分钟检查一遍连接池 +// ds.setTimeBetweenEvictionRunsMillis(TimeUnit.MINUTES +// .toMillis(10L)); +// ds.setTestWhileIdle(true); +// ds.setValidationQuery("SELECT 1 FROM dual"); +// +// dblist.add(ds); +// +// JdbcTemplate jdbcTemplate = new JdbcTemplate(); +// jdbcTemplate.setQueryTimeout(queryTimeout); +// jdbcTemplate.setDataSource(ds); +// +// testJTList.add(jdbcTemplate); +// isHealthList.add(Boolean.TRUE); +// } +// +// if (dblist == null || dblist.size() == 0) { +// throw new RuntimeException("no datasource available"); +// } +// +// dataSourceList = dblist; +// new BasicDataSourceServiceImpl.SelectMasterTask().run(); +// new BasicDataSourceServiceImpl.CheckDBHealthTask().run(); +// } catch (RuntimeException e) { +// fatalLog.error(DB_LOAD_ERROR_MSG, e); +// throw new IOException(e); +// } finally { +// } +// } +//} diff --git a/config/src/main/java/com/alibaba/nacos/config/server/configuration/DataBaseConfiguration.java b/config/src/main/java/com/alibaba/nacos/config/server/configuration/DataBaseConfiguration.java index 791326351..edb148950 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/configuration/DataBaseConfiguration.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/configuration/DataBaseConfiguration.java @@ -1,63 +1,63 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.nacos.config.server.configuration; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.datasource.DataSourceTransactionManager; -import org.springframework.transaction.PlatformTransactionManager; - -import javax.sql.DataSource; - -/** - * DataBase {@link Configuration} - * - * @author Mercy - * @since 0.2.2 - */ -@Configuration -public class DataBaseConfiguration { - - /** - * The bean name of {@link DataSource} for Nacos Config - */ - public static final String DATA_SOURCE_BEAN_NAME = "nacosDataSource"; - - @Bean - @Autowired - public JdbcTemplate jdbcTemplate(@Qualifier(DATA_SOURCE_BEAN_NAME) DataSource dataSource, Environment environment) { - JdbcTemplate jdbcTemplate = new JdbcTemplate(); - jdbcTemplate = new JdbcTemplate(); - jdbcTemplate.setMaxRows(50000); - jdbcTemplate.setQueryTimeout(5000); - jdbcTemplate.setDataSource(dataSource); - return jdbcTemplate; - } - - @Bean - @Autowired - public PlatformTransactionManager transactionManager(@Qualifier(DATA_SOURCE_BEAN_NAME) DataSource dataSource) { - DataSourceTransactionManager manager = new DataSourceTransactionManager(); - manager.setDataSource(dataSource); - return manager; - } - -} +///* +// * Licensed to the Apache Software Foundation (ASF) under one or more +// * contributor license agreements. See the NOTICE file distributed with +// * this work for additional information regarding copyright ownership. +// * The ASF licenses this file to You under the Apache License, Version 2.0 +// * (the "License"); you may not use this file except in compliance with +// * the License. You may obtain a copy of the License at +// * +// * http://www.apache.org/licenses/LICENSE-2.0 +// * +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an "AS IS" BASIS, +// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// * See the License for the specific language governing permissions and +// * limitations under the License. +// */ +//package com.alibaba.nacos.config.server.configuration; +// +//import org.springframework.beans.factory.annotation.Autowired; +//import org.springframework.beans.factory.annotation.Qualifier; +//import org.springframework.context.annotation.Bean; +//import org.springframework.context.annotation.Configuration; +//import org.springframework.core.env.Environment; +//import org.springframework.jdbc.core.JdbcTemplate; +//import org.springframework.jdbc.datasource.DataSourceTransactionManager; +//import org.springframework.transaction.PlatformTransactionManager; +// +//import javax.sql.DataSource; +// +///** +// * DataBase {@link Configuration} +// * +// * @author Mercy +// * @since 0.2.2 +// */ +//@Configuration +//public class DataBaseConfiguration { +// +// /** +// * The bean name of {@link DataSource} for Nacos Config +// */ +// public static final String DATA_SOURCE_BEAN_NAME = "nacosConfigDataSource"; +// +// @Bean +// @Autowired +// public JdbcTemplate jdbcTemplate(@Qualifier(DATA_SOURCE_BEAN_NAME) DataSource dataSource, Environment environment) { +// JdbcTemplate jdbcTemplate = new JdbcTemplate(); +// jdbcTemplate = new JdbcTemplate(); +// jdbcTemplate.setMaxRows(50000); +// jdbcTemplate.setQueryTimeout(5000); +// jdbcTemplate.setDataSource(dataSource); +// return jdbcTemplate; +// } +// +// @Bean +// @Autowired +// public PlatformTransactionManager transactionManager(@Qualifier(DATA_SOURCE_BEAN_NAME) DataSource dataSource) { +// DataSourceTransactionManager manager = new DataSourceTransactionManager(); +// manager.setDataSource(dataSource); +// return manager; +// } +// +//} diff --git a/config/src/main/java/com/alibaba/nacos/config/server/configuration/LocalDataSourceConfiguration.java b/config/src/main/java/com/alibaba/nacos/config/server/configuration/LocalDataSourceConfiguration.java index 03508bcc8..f0c30bda3 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/configuration/LocalDataSourceConfiguration.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/configuration/LocalDataSourceConfiguration.java @@ -1,75 +1,75 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.nacos.config.server.configuration; - -import org.apache.commons.dbcp.BasicDataSource; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; -import org.springframework.core.env.Environment; - -import javax.sql.DataSource; -import java.io.File; -import java.util.concurrent.TimeUnit; - -import static com.alibaba.nacos.config.server.configuration.DataBaseConfiguration.DATA_SOURCE_BEAN_NAME; - -/** - * Local {@link DataSource} {@link Configuration} - * - * @author Mercy - * @since 0.2.2 - */ -@Profile("standalone") -@Configuration -public class LocalDataSourceConfiguration { - - private static final String JDBC_DRIVER_NAME = "org.apache.derby.jdbc.EmbeddedDriver"; - - private static final String DERBY_BASE_DIR = "data" + File.separator + "derby-data"; - - private static final String NACOS_HOME_KEY = "nacos.home"; - - private static final String DEFAULT_APP_NAME = System.getProperty("user.home") + File.separator + "nacos"; - - private static final String APP_HOME = System.getProperty(NACOS_HOME_KEY, DEFAULT_APP_NAME); - - private static final String DATAS_SOURCE_URL = "jdbc:derby:" + APP_HOME + File.separator + DERBY_BASE_DIR + - ";create=true"; - - private static final String USER_NAME = "nacos"; - - private static final String PASSWORD = "nacos"; - - @Bean(name = DATA_SOURCE_BEAN_NAME) - public DataSource dataSource(Environment environment) { - BasicDataSource ds = new BasicDataSource(); - ds.setDriverClassName(JDBC_DRIVER_NAME); - ds.setUrl(DATAS_SOURCE_URL); - ds.setUsername(USER_NAME); - ds.setPassword(PASSWORD); - ds.setInitialSize(environment.getProperty("db.initialSize", int.class, 20)); - ds.setMaxActive(environment.getProperty("db.maxActive", int.class, 30)); - ds.setMaxIdle(environment.getProperty("db.maxIdle", int.class, 50)); - ds.setMaxWait(environment.getProperty("db.maxWait", long.class, 10000L)); - ds.setPoolPreparedStatements(true); - ds.setTimeBetweenEvictionRunsMillis(TimeUnit.MINUTES.toMillis(10L)); - ds.setTestWhileIdle(true); - return ds; - } - -} +///* +// * Licensed to the Apache Software Foundation (ASF) under one or more +// * contributor license agreements. See the NOTICE file distributed with +// * this work for additional information regarding copyright ownership. +// * The ASF licenses this file to You under the Apache License, Version 2.0 +// * (the "License"); you may not use this file except in compliance with +// * the License. You may obtain a copy of the License at +// * +// * http://www.apache.org/licenses/LICENSE-2.0 +// * +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an "AS IS" BASIS, +// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// * See the License for the specific language governing permissions and +// * limitations under the License. +// */ +//package com.alibaba.nacos.config.server.configuration; +// +//import org.apache.commons.dbcp.BasicDataSource; +//import org.springframework.context.annotation.Bean; +//import org.springframework.context.annotation.Configuration; +//import org.springframework.context.annotation.Profile; +//import org.springframework.core.env.Environment; +// +//import javax.sql.DataSource; +//import java.io.File; +//import java.util.concurrent.TimeUnit; +// +//import static com.alibaba.nacos.config.server.configuration.DataBaseConfiguration.DATA_SOURCE_BEAN_NAME; +// +///** +// * Local {@link DataSource} {@link Configuration} +// * +// * @author Mercy +// * @since 0.2.2 +// */ +//@Profile("standalone") +//@Configuration +//public class LocalDataSourceConfiguration { +// +// private static final String JDBC_DRIVER_NAME = "org.apache.derby.jdbc.EmbeddedDriver"; +// +// private static final String DERBY_BASE_DIR = "data" + File.separator + "derby-data"; +// +// private static final String NACOS_HOME_PROPERTY_NAME = "nacos.home"; +// +// private static final String DEFAULT_APP_NAME = System.getProperty("user.home") + File.separator + "nacos"; +// +// private static final String APP_HOME = System.getProperty(NACOS_HOME_PROPERTY_NAME, DEFAULT_APP_NAME); +// +// private static final String DATA_SOURCE_URL = "jdbc:derby:" + APP_HOME + File.separator + DERBY_BASE_DIR + +// ";create=true"; +// +// private static final String USER_NAME = "nacos"; +// +// private static final String PASSWORD = "nacos"; +// +// @Bean(name = DATA_SOURCE_BEAN_NAME,destroyMethod = "close") +// public DataSource nacosConfigDataSource(Environment environment) { +// BasicDataSource ds = new BasicDataSource(); +// ds.setDriverClassName(JDBC_DRIVER_NAME); +// ds.setUrl(DATA_SOURCE_URL); +// ds.setUsername(USER_NAME); +// ds.setPassword(PASSWORD); +// ds.setInitialSize(environment.getProperty("db.initialSize", int.class, 20)); +// ds.setMaxActive(environment.getProperty("db.maxActive", int.class, 30)); +// ds.setMaxIdle(environment.getProperty("db.maxIdle", int.class, 50)); +// ds.setMaxWait(environment.getProperty("db.maxWait", long.class, 10000L)); +// ds.setPoolPreparedStatements(true); +// ds.setTimeBetweenEvictionRunsMillis(TimeUnit.MINUTES.toMillis(10L)); +// ds.setTestWhileIdle(true); +// return ds; +// } +// +//} diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/LocalDataSourceServiceImpl.java b/config/src/main/java/com/alibaba/nacos/config/server/service/LocalDataSourceServiceImpl.java index 6760c9ceb..a36ec8f66 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/LocalDataSourceServiceImpl.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/LocalDataSourceServiceImpl.java @@ -30,6 +30,8 @@ import javax.sql.DataSource; import com.alibaba.nacos.config.server.utils.PropertyUtil; import org.apache.commons.dbcp.BasicDataSource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.stereotype.Service; @@ -41,28 +43,30 @@ import com.alibaba.nacos.config.server.utils.StringUtils; /** * local data source - * - * @author Nacos * + * @author Nacos */ @Service("localDataSourceService") public class LocalDataSourceServiceImpl implements DataSourceService { - private static final String JDBC_DRIVER_NAME = "org.apache.derby.jdbc.EmbeddedDriver"; - private static final String DERBY_BASE_DIR = "data" + File.separator + "derby-data"; - private static String appHome = System.getProperty("user.home") + File.separator + "nacos"; - private static final String NACOS_HOME_KEY = "nacos.home"; - private static final String USER_NAME = "nacos"; - private static final String PASSWORD = "nacos"; + + private static final Logger logger = LoggerFactory.getLogger(LocalDataSourceServiceImpl.class); + + private static final String JDBC_DRIVER_NAME = "org.apache.derby.jdbc.EmbeddedDriver"; + private static final String DERBY_BASE_DIR = "data" + File.separator + "derby-data"; + private static String appHome = System.getProperty("user.home") + File.separator + "nacos"; + private static final String NACOS_HOME_KEY = "nacos.home"; + private static final String USER_NAME = "nacos"; + private static final String PASSWORD = "nacos"; private JdbcTemplate jt; private TransactionTemplate tjt; @PostConstruct public void init() { - String nacosBaseDir = System.getProperty(NACOS_HOME_KEY); - if (!StringUtils.isBlank(nacosBaseDir)) { - setAppHome(nacosBaseDir); - } + String nacosBaseDir = System.getProperty(NACOS_HOME_KEY); + if (!StringUtils.isBlank(nacosBaseDir)) { + setAppHome(nacosBaseDir); + } BasicDataSource ds = new BasicDataSource(); ds.setDriverClassName(JDBC_DRIVER_NAME); ds.setUrl("jdbc:derby:" + appHome + File.separator + DERBY_BASE_DIR + ";create=true"); @@ -92,17 +96,20 @@ public class LocalDataSourceServiceImpl implements DataSourceService { } @Override - public void reload() { - DataSource ds = jt.getDataSource(); - if (ds == null) { - throw new RuntimeException("datasource is null"); - } - try { - execute(ds.getConnection(), "META-INF/schema.sql"); - } catch (Exception e) { - throw new RuntimeException("load schema.sql error." + e); - } - } + public void reload() { + DataSource ds = jt.getDataSource(); + if (ds == null) { + throw new RuntimeException("datasource is null"); + } + try { + execute(ds.getConnection(), "META-INF/schema.sql"); + } catch (Exception e) { + if (logger.isErrorEnabled()) { + logger.error(e.getMessage(), e); + } + throw new RuntimeException("load schema.sql error." + e); + } + } @Override public boolean checkMasterWritable() { @@ -131,6 +138,7 @@ public class LocalDataSourceServiceImpl implements DataSourceService { /** * 读取SQL文件 + * * @param sqlFile sql * @return sqls * @throws Exception Exception @@ -139,7 +147,7 @@ public class LocalDataSourceServiceImpl implements DataSourceService { List sqlList = new ArrayList(); InputStream sqlFileIn = null; try { - if (StringUtils.isBlank(System.getProperty(NACOS_HOME_KEY))) { + if (StringUtils.isBlank(System.getProperty(NACOS_HOME_KEY))) { ClassLoader classLoader = getClass().getClassLoader(); URL url = classLoader.getResource(sqlFile); sqlFileIn = url.openStream(); @@ -151,9 +159,9 @@ public class LocalDataSourceServiceImpl implements DataSourceService { StringBuffer sqlSb = new StringBuffer(); byte[] buff = new byte[1024]; int byteRead = 0; - while ((byteRead = sqlFileIn.read(buff)) != -1) { - sqlSb.append(new String(buff, 0, byteRead, Constants.ENCODE)); - } + while ((byteRead = sqlFileIn.read(buff)) != -1) { + sqlSb.append(new String(buff, 0, byteRead, Constants.ENCODE)); + } String[] sqlArr = sqlSb.toString().split(";"); for (int i = 0; i < sqlArr.length; i++) { @@ -163,18 +171,19 @@ public class LocalDataSourceServiceImpl implements DataSourceService { } } return sqlList; - } catch (Exception ex) { - throw new Exception(ex.getMessage()); - } finally { - if (sqlFileIn != null) { - sqlFileIn.close(); - } - } + } catch (Exception ex) { + throw new Exception(ex.getMessage()); + } finally { + if (sqlFileIn != null) { + sqlFileIn.close(); + } + } } /** * 执行SQL语句 - * @param conn connect + * + * @param conn connect * @param sqlFile sql * @throws Exception Exception */ @@ -193,13 +202,13 @@ public class LocalDataSourceServiceImpl implements DataSourceService { stmt.close(); } - public static String getAppHome() { - return appHome; - } + public static String getAppHome() { + return appHome; + } + + public static void setAppHome(String appHome) { + LocalDataSourceServiceImpl.appHome = appHome; + } - public static void setAppHome(String appHome) { - LocalDataSourceServiceImpl.appHome = appHome; - } - } diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/ServerListService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/ServerListService.java index 5e849657e..6437bd582 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/ServerListService.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/ServerListService.java @@ -71,10 +71,8 @@ public class ServerListService implements ApplicationListenerMercy +// * @since 0.2.2 +// */ +//@RunWith(SpringRunner.class) +//@ContextConfiguration(classes = { +// LocalDataSourceConfiguration.class, +// DataBaseConfiguration.class, +// LocalDataSourceConfigurationTest.class +//}) +//@TestPropertySource(properties = { +// "db.initialSize=1", +// "db.maxActive=2", +// "db.maxIdle=3", +// "db.maxWait=4", +//}) +//@ActiveProfiles("standalone") +//public class LocalDataSourceConfigurationTest { +// +// @Autowired +// @Qualifier(DATA_SOURCE_BEAN_NAME) +// private DataSource nacosConfigDataSource; +// +// @Autowired +// private JdbcTemplate jdbcTemplate; +// +// @Autowired +// private PlatformTransactionManager platformTransactionManager; +// +// @Test +// public void testDataSource() { +// Assert.assertNotNull(nacosConfigDataSource); +// Assert.assertTrue(nacosConfigDataSource instanceof BasicDataSource); +// BasicDataSource dataSource = BasicDataSource.class.cast(nacosConfigDataSource); +// Assert.assertEquals(1, dataSource.getInitialSize()); +// Assert.assertEquals(2, dataSource.getMaxActive()); +// Assert.assertEquals(3, dataSource.getMaxIdle()); +// Assert.assertEquals(4, dataSource.getMaxWait()); +// } +// +// @Test +// public void testJdbcTemplate() { +// Assert.assertEquals(jdbcTemplate.getDataSource(), nacosConfigDataSource); +// } +// +// @Test +// public void testPlatformTransactionManager() { +// Assert.assertTrue(platformTransactionManager instanceof DataSourceTransactionManager); +// DataSourceTransactionManager transactionManager = (DataSourceTransactionManager) platformTransactionManager; +// Assert.assertEquals(transactionManager.getDataSource(), nacosConfigDataSource); +// } +// +//} diff --git a/naming/src/main/resources/naming-logback.xml b/naming/src/main/resources/naming-logback.xml index 641b92745..58500d543 100644 --- a/naming/src/main/resources/naming-logback.xml +++ b/naming/src/main/resources/naming-logback.xml @@ -1,5 +1,4 @@ - org.springframework.boot spring-boot-starter-test - 2.0.1.RELEASE test - @@ -456,7 +454,7 @@ org.springframework.boot spring-boot-dependencies - 2.0.1.RELEASE + 2.0.5.RELEASE pom import From b0b7146a869ac8874632122c6d77620129e73693 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Mon, 1 Oct 2018 10:30:24 +0800 Subject: [PATCH 06/30] Remove unused class --- .../alibaba/nacos/common/AppendLicense.java | 85 ------------------- 1 file changed, 85 deletions(-) delete mode 100644 common/src/main/java/com/alibaba/nacos/common/AppendLicense.java diff --git a/common/src/main/java/com/alibaba/nacos/common/AppendLicense.java b/common/src/main/java/com/alibaba/nacos/common/AppendLicense.java deleted file mode 100644 index d88e46700..000000000 --- a/common/src/main/java/com/alibaba/nacos/common/AppendLicense.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright 1999-2018 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.nacos.common; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import org.apache.commons.io.IOUtils; - -/** - * - * 遍历目标文件夹下的所有文件,在文件头上加上license协议 - * 注意:读取/写入文件默认用utf-8进行 - * @author en.xuze@alipay.com - * @version $Id: AppendLicense.java, v 0.1 2018年7月4日 下午2:31:16 en.xuze@alipay.com Exp $ - */ -public class AppendLicense { - - private static List targetFiles = new LinkedList(); - private static String licenseFile = "/Users/en.xuze/git/nacos/common/license"; - private static String targetDirOrFile = "/Users/en.xuze/git/nacos"; - - public static void main(String[] args) throws Exception { - List licenseContents = IOUtils.readLines(new FileInputStream(new File(licenseFile)), "utf-8"); - readFiles(targetDirOrFile); - for (Iterator iterator = targetFiles.iterator(); iterator.hasNext();) { - File file = (File) iterator.next(); - List srcFileContents = IOUtils.readLines(new FileInputStream(file), "utf-8"); - List writeContents = new ArrayList(); - writeContents.addAll(licenseContents); - writeContents.addAll(srcFileContents); - IOUtils.writeLines(writeContents, "\n", new FileOutputStream(file)); - System.out.println("append license to file:" + file.getAbsolutePath()); - } - } - - private static void readFiles(String filePath) { - if (filePath == null) { - return; - } - File temp = new File(filePath); - File[] files = null; - if (temp.isFile()) { - if (needAppend(temp.getName())) { - targetFiles.add(temp); - } - } else { - files = temp.listFiles(); - } - if (files == null) { - return; - } - for (File f : files) { - if (f.isFile()) { - if (needAppend(f.getName())) { - targetFiles.add(f); - } - } else if (f.isDirectory()) { - readFiles(f.getPath()); - } - } - } - - private static boolean needAppend(String fileName) { - return (fileName.endsWith(".java")); - } -} From a718c84d4cccb314b6a205cbbbcba58bdfd4938c Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Mon, 1 Oct 2018 10:48:34 +0800 Subject: [PATCH 07/30] Polish alibaba/nacos#104 --- .../naming/cache/ConcurrentDiskUtil.java | 3 - .../nacos/client/naming/net/HttpClient.java | 6 - .../alibaba/nacos/common/util/IoUtils.java | 7 - .../alibaba/nacos/common/util/SystemUtil.java | 4 - config/src/main/java/LogbackInitTest.java | 68 ---------- .../server/monitor/ResponseMonitor.java | 123 ++++++++---------- .../config/server/utils/RegexParser.java | 4 - .../nacos/config/server/utils/TimeUtils.java | 14 +- .../main/java/com/alibaba/nacos/core/App.java | 28 ---- .../alibaba/nacos/naming/core/Cluster.java | 7 - .../monitor/PerformanceLoggerThread.java | 3 - .../main/java/com/alibaba/nacos/test/App.java | 28 ---- .../nacos/test/naming/RandomUtils.java | 15 --- 13 files changed, 59 insertions(+), 251 deletions(-) delete mode 100644 config/src/main/java/LogbackInitTest.java delete mode 100644 core/src/main/java/com/alibaba/nacos/core/App.java delete mode 100644 test/src/main/java/com/alibaba/nacos/test/App.java diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/cache/ConcurrentDiskUtil.java b/client/src/main/java/com/alibaba/nacos/client/naming/cache/ConcurrentDiskUtil.java index 114a65158..6fc5fa897 100644 --- a/client/src/main/java/com/alibaba/nacos/client/naming/cache/ConcurrentDiskUtil.java +++ b/client/src/main/java/com/alibaba/nacos/client/naming/cache/ConcurrentDiskUtil.java @@ -229,9 +229,6 @@ public class ConcurrentDiskUtil { } } - public static void main(String[] args) { - } - static final public Logger log = LogUtils.LOG; static final int RETRY_COUNT = 10; static final int SLEEP_BASETIME = 10; diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/net/HttpClient.java b/client/src/main/java/com/alibaba/nacos/client/naming/net/HttpClient.java index b49b559bf..24b9836e5 100644 --- a/client/src/main/java/com/alibaba/nacos/client/naming/net/HttpClient.java +++ b/client/src/main/java/com/alibaba/nacos/client/naming/net/HttpClient.java @@ -175,12 +175,6 @@ public class HttpClient { return sb.toString(); } - public static void main(String[] args) throws UnsupportedEncodingException { - Map params = new HashMap(2); - params.put("s", "Wms+rkGG8jlaBBbpl8FIDxxNQGA="); - System.out.println(encodingParams(params, "utf-8")); - } - public static class HttpResult { final public int code; final public String content; diff --git a/common/src/main/java/com/alibaba/nacos/common/util/IoUtils.java b/common/src/main/java/com/alibaba/nacos/common/util/IoUtils.java index f9f489dc0..33356073b 100644 --- a/common/src/main/java/com/alibaba/nacos/common/util/IoUtils.java +++ b/common/src/main/java/com/alibaba/nacos/common/util/IoUtils.java @@ -162,12 +162,5 @@ public class IoUtils { return null; } - public static void main(String[] args) throws IOException { - -// String path = "/Users/zhupengfei/test_write.txt"; - -// writeStringToFile(new File(path), "hello2222", "utf-8"); - } - } diff --git a/common/src/main/java/com/alibaba/nacos/common/util/SystemUtil.java b/common/src/main/java/com/alibaba/nacos/common/util/SystemUtil.java index 4955187e2..54f2f9181 100644 --- a/common/src/main/java/com/alibaba/nacos/common/util/SystemUtil.java +++ b/common/src/main/java/com/alibaba/nacos/common/util/SystemUtil.java @@ -45,10 +45,6 @@ public class SystemUtil { return env; } - public static void main(String[] args) throws SQLException { - System.out.println(Boolean.parseBoolean("Tfue")); - } - public static float getLoad() { return (float) operatingSystemMXBean.getSystemLoadAverage(); } diff --git a/config/src/main/java/LogbackInitTest.java b/config/src/main/java/LogbackInitTest.java deleted file mode 100644 index 408d0fb3a..000000000 --- a/config/src/main/java/LogbackInitTest.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 1999-2018 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.alibaba.nacos.config.server.utils.AppNameUtils; - -import ch.qos.logback.classic.LoggerContext; -import ch.qos.logback.classic.joran.JoranConfigurator; - -/** - * logback test - * @author Nacos - * - */ -public class LogbackInitTest { - - private static final Logger logger = LoggerFactory.getLogger(LogbackInitTest.class); - - - - public static void main(String[] args) throws Exception { - AppNameUtils.class.getClassLoader(); - String classpath = AppNameUtils.class.getResource("/").getPath(); - System.out.println("The classpath is " + classpath); - - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - lc.reset(); - - JoranConfigurator configurator = new JoranConfigurator(); - configurator.setContext(lc); - configurator.doConfigure(LogbackInitTest.class.getResource("logback-jiuren.xml")); - - for (;;) { - logger.info("hello"); - System.out.println(getLevel(logger)); - Thread.sleep(1000L); - } - } - - - static String getLevel(Logger logger) { - if (logger.isDebugEnabled()) { - return "debug"; - } else if (logger.isInfoEnabled()) { - return "info"; - } else if (logger.isWarnEnabled()) { - return "warn"; - } else if (logger.isErrorEnabled()) { - return "error"; - } else { - return "unknown"; - } - } -} diff --git a/config/src/main/java/com/alibaba/nacos/config/server/monitor/ResponseMonitor.java b/config/src/main/java/com/alibaba/nacos/config/server/monitor/ResponseMonitor.java index ea98ae7b0..a7ad949a5 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/monitor/ResponseMonitor.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/monitor/ResponseMonitor.java @@ -20,78 +20,61 @@ import java.util.concurrent.atomic.AtomicLong; /** * Response Monitory - * - * @author Nacos * + * @author Nacos */ public class ResponseMonitor { - static AtomicLong[] getConfigCountDetail = new AtomicLong[8]; - static AtomicLong getConfigCount = new AtomicLong(); - private static final int MS_50 = 50; - private static final int MS_100 = 100; - private static final int MS_200 = 200; - private static final int MS_500 = 500; - private static final int MS_1000 = 1000; - private static final int MS_2000 = 2000; - private static final int MS_3000 = 3000; + static AtomicLong[] getConfigCountDetail = new AtomicLong[8]; + static AtomicLong getConfigCount = new AtomicLong(); + private static final int MS_50 = 50; + private static final int MS_100 = 100; + private static final int MS_200 = 200; + private static final int MS_500 = 500; + private static final int MS_1000 = 1000; + private static final int MS_2000 = 2000; + private static final int MS_3000 = 3000; - static{ - refresh(); - } - - public static void refresh(){ - for(int i = 0; i< getConfigCountDetail.length;i++){ - getConfigCountDetail[i] = new AtomicLong(); - } - } - - public static void addConfigTime(long time){ - getConfigCount.incrementAndGet(); - if(time < MS_50){ - getConfigCountDetail[0].incrementAndGet(); - } else if(time < MS_100) { - getConfigCountDetail[1].incrementAndGet(); - } else if (time < MS_200){ - getConfigCountDetail[2].incrementAndGet(); - } else if(time < MS_500){ - getConfigCountDetail[3].incrementAndGet(); - } else if(time < MS_1000){ - getConfigCountDetail[4].incrementAndGet(); - } else if(time < MS_2000){ - getConfigCountDetail[5].incrementAndGet(); - } else if(time < MS_3000){ - getConfigCountDetail[6].incrementAndGet(); - } else { - getConfigCountDetail[7].incrementAndGet(); - } - } - - public static String getStringForPrint(){ - DecimalFormat df = new DecimalFormat("##.0"); - StringBuilder s = new StringBuilder("getConfig monitor:\r\n"); - s.append("0-50ms:" + df.format(getConfigCountDetail[0].getAndSet(0)*100/ getConfigCount.get())).append("%\r\n"); - s.append("100-200ms:" + df.format(getConfigCountDetail[2].getAndSet(0)*100/ getConfigCount.get())).append("%\r\n"); - s.append("200-500ms:" + df.format(getConfigCountDetail[3].getAndSet(0)*100/ getConfigCount.get())).append("%\r\n"); - s.append("500-1000ms:" + df.format(getConfigCountDetail[4].getAndSet(0)*100/ getConfigCount.get())).append("%\r\n"); - s.append("1000-2000ms:" + df.format(getConfigCountDetail[5].getAndSet(0)*100/ getConfigCount.get())).append("%\r\n"); - s.append("2000-3000ms:" + df.format(getConfigCountDetail[6].getAndSet(0)*100/ getConfigCount.get())).append("%\r\n"); - s.append("3000以上ms:" + df.format(getConfigCountDetail[7].getAndSet(0)*100/ getConfigCount.getAndSet(0))).append("%\r\n"); - return s.toString(); - } - - public static void main(String[] args) { - ResponseMonitor.addConfigTime(10); - ResponseMonitor.addConfigTime(10); - ResponseMonitor.addConfigTime(10); - ResponseMonitor.addConfigTime(10); - ResponseMonitor.addConfigTime(100); - ResponseMonitor.addConfigTime(150); - ResponseMonitor.addConfigTime(250); - ResponseMonitor.addConfigTime(350); - ResponseMonitor.addConfigTime(750); - ResponseMonitor.addConfigTime(15000); - System.out.println(ResponseMonitor.getStringForPrint()); - System.out.println(ResponseMonitor.getStringForPrint()); - - } + static { + refresh(); + } + + public static void refresh() { + for (int i = 0; i < getConfigCountDetail.length; i++) { + getConfigCountDetail[i] = new AtomicLong(); + } + } + + public static void addConfigTime(long time) { + getConfigCount.incrementAndGet(); + if (time < MS_50) { + getConfigCountDetail[0].incrementAndGet(); + } else if (time < MS_100) { + getConfigCountDetail[1].incrementAndGet(); + } else if (time < MS_200) { + getConfigCountDetail[2].incrementAndGet(); + } else if (time < MS_500) { + getConfigCountDetail[3].incrementAndGet(); + } else if (time < MS_1000) { + getConfigCountDetail[4].incrementAndGet(); + } else if (time < MS_2000) { + getConfigCountDetail[5].incrementAndGet(); + } else if (time < MS_3000) { + getConfigCountDetail[6].incrementAndGet(); + } else { + getConfigCountDetail[7].incrementAndGet(); + } + } + + public static String getStringForPrint() { + DecimalFormat df = new DecimalFormat("##.0"); + StringBuilder s = new StringBuilder("getConfig monitor:\r\n"); + s.append("0-50ms:" + df.format(getConfigCountDetail[0].getAndSet(0) * 100 / getConfigCount.get())).append("%\r\n"); + s.append("100-200ms:" + df.format(getConfigCountDetail[2].getAndSet(0) * 100 / getConfigCount.get())).append("%\r\n"); + s.append("200-500ms:" + df.format(getConfigCountDetail[3].getAndSet(0) * 100 / getConfigCount.get())).append("%\r\n"); + s.append("500-1000ms:" + df.format(getConfigCountDetail[4].getAndSet(0) * 100 / getConfigCount.get())).append("%\r\n"); + s.append("1000-2000ms:" + df.format(getConfigCountDetail[5].getAndSet(0) * 100 / getConfigCount.get())).append("%\r\n"); + s.append("2000-3000ms:" + df.format(getConfigCountDetail[6].getAndSet(0) * 100 / getConfigCount.get())).append("%\r\n"); + s.append("3000以上ms:" + df.format(getConfigCountDetail[7].getAndSet(0) * 100 / getConfigCount.getAndSet(0))).append("%\r\n"); + return s.toString(); + } } diff --git a/config/src/main/java/com/alibaba/nacos/config/server/utils/RegexParser.java b/config/src/main/java/com/alibaba/nacos/config/server/utils/RegexParser.java index a8c321b00..a32d33c2b 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/utils/RegexParser.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/utils/RegexParser.java @@ -75,8 +75,4 @@ public class RegexParser { return (regex.contains("?") || regex.contains("*")); } - public static void main(String[] args) { - String str = "com.taobao.uic.*"; - System.out.println(str + " -> " + regexFormat(str)); - } } diff --git a/config/src/main/java/com/alibaba/nacos/config/server/utils/TimeUtils.java b/config/src/main/java/com/alibaba/nacos/config/server/utils/TimeUtils.java index 644af4811..9f57e01b9 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/utils/TimeUtils.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/utils/TimeUtils.java @@ -15,27 +15,25 @@ */ package com.alibaba.nacos.config.server.utils; +import org.apache.commons.lang.time.FastDateFormat; + import java.sql.Timestamp; import java.util.Calendar; import java.util.Date; -import org.apache.commons.lang.time.FastDateFormat; /** * Time util - * @author Nacos * + * @author Nacos */ public class TimeUtils { - public static Timestamp getCurrentTime() { + public static Timestamp getCurrentTime() { Date date = new Date(); return new Timestamp(date.getTime()); } - public static void main(String[] args) { - System.out.println(getCurrentTime().toString()); - } - - static public String getCurrentTimeStr() { + + static public String getCurrentTimeStr() { Calendar c = Calendar.getInstance(); c.setTime(new Date()); c.get(Calendar.HOUR); diff --git a/core/src/main/java/com/alibaba/nacos/core/App.java b/core/src/main/java/com/alibaba/nacos/core/App.java deleted file mode 100644 index b006320b4..000000000 --- a/core/src/main/java/com/alibaba/nacos/core/App.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright 1999-2018 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.nacos.core; - -/** - * Hello world! - * @author xxc - */ -public class App -{ - public static void main( String[] args ) - { - System.out.println( "Hello World!" ); - } -} diff --git a/naming/src/main/java/com/alibaba/nacos/naming/core/Cluster.java b/naming/src/main/java/com/alibaba/nacos/naming/core/Cluster.java index e911e015e..7462bd90e 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/core/Cluster.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/core/Cluster.java @@ -451,11 +451,4 @@ public class Cluster implements Cloneable { } } } - - public static void main(String[] args) { - String v1 = "nesttest"; - if (v1.matches(CLUSTER_NAME_SYNTAX)) { - System.out.print(""); - } - } } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/monitor/PerformanceLoggerThread.java b/naming/src/main/java/com/alibaba/nacos/naming/monitor/PerformanceLoggerThread.java index a9c604c80..c33669f7e 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/monitor/PerformanceLoggerThread.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/monitor/PerformanceLoggerThread.java @@ -136,7 +136,4 @@ public class PerformanceLoggerThread { } return avgCost; } - - public static void main(String[] args) { - } } diff --git a/test/src/main/java/com/alibaba/nacos/test/App.java b/test/src/main/java/com/alibaba/nacos/test/App.java deleted file mode 100644 index bf3ea7e9c..000000000 --- a/test/src/main/java/com/alibaba/nacos/test/App.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright 1999-2018 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.nacos.test; - -/** - * Hello world! - * @author xxc - */ -public class App -{ - public static void main( String[] args ) - { - System.out.println( "Hello World!" ); - } -} diff --git a/test/src/test/java/com/alibaba/nacos/test/naming/RandomUtils.java b/test/src/test/java/com/alibaba/nacos/test/naming/RandomUtils.java index c6bd7f69d..b24adbbb9 100644 --- a/test/src/test/java/com/alibaba/nacos/test/naming/RandomUtils.java +++ b/test/src/test/java/com/alibaba/nacos/test/naming/RandomUtils.java @@ -263,21 +263,6 @@ public class RandomUtils { return getIntegerMoreThanZeroLessThan(3) == 1; } - public static void main(String[] args) { - for(int t = 0; t < 20; ++t) { - Collection arrs = getRandomCollection(1, 5, 5); - Iterator var3 = arrs.iterator(); - - while(var3.hasNext()) { - int i = (Integer)var3.next(); - System.out.println(i); - } - - System.out.println("----"); - } - - } - public static String getStringByUUID() { return UUID.randomUUID().toString(); } From be8f3c2052e91dc05f3137e7df7d8db219df3952 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Mon, 1 Oct 2018 10:58:27 +0800 Subject: [PATCH 08/30] Polish alibaba/nacos#103 --- api/pom.xml | 41 +++++---- client/pom.xml | 212 +++++++++++++++++++++++-------------------- common/pom.xml | 65 +++++++------ config/pom.xml | 8 +- console/pom.xml | 1 + core/pom.xml | 1 + distribution/pom.xml | 1 + example/pom.xml | 1 + naming/pom.xml | 1 + test/pom.xml | 1 + 10 files changed, 176 insertions(+), 156 deletions(-) diff --git a/api/pom.xml b/api/pom.xml index 28f6ff2b5..e4ae34193 100644 --- a/api/pom.xml +++ b/api/pom.xml @@ -12,30 +12,31 @@ limitations under the License. --> - - com.alibaba.nacos - nacos-all - 0.2.2-SNAPSHOT - + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + com.alibaba.nacos + nacos-all + 0.2.2-SNAPSHOT + ../pom.xml + - 4.0.0 + 4.0.0 - nacos-api - jar + nacos-api + jar - nacos-api ${project.version} - http://maven.apache.org + nacos-api ${project.version} + http://maven.apache.org - - UTF-8 - + + UTF-8 + - - - com.alibaba - fastjson - - + + + com.alibaba + fastjson + + diff --git a/client/pom.xml b/client/pom.xml index 9c9f368c0..82832aa72 100644 --- a/client/pom.xml +++ b/client/pom.xml @@ -12,113 +12,127 @@ limitations under the License. --> - - com.alibaba.nacos - nacos-all - 0.2.2-SNAPSHOT - + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + com.alibaba.nacos + nacos-all + 0.2.2-SNAPSHOT + ../pom.xml + - 4.0.0 + 4.0.0 - nacos-client - jar + nacos-client + jar - nacos-client ${project.version} - http://maven.apache.org + nacos-client ${project.version} + http://maven.apache.org - - UTF-8 - + + UTF-8 + - - - org.slf4j - slf4j-api - provided - - - log4j - log4j - provided - - - org.apache.logging.log4j - log4j-core - 2.8.2 - provided - - - commons-logging - commons-logging - provided - - - org.slf4j - slf4j-log4j12 - provided - - - org.apache.logging.log4j - log4j-slf4j-impl - provided - - - org.slf4j - jcl-over-slf4j - provided - - - junit - junit - test - - - ${project.groupId} - nacos-common - - - ${project.groupId} - nacos-api - - - com.alibaba - fastjson - + + + org.slf4j + slf4j-api + true + - - ch.qos.logback - logback-classic - - - ch.qos.logback - logback-core - + + log4j + log4j + true + - - com.google.guava - guava - + + org.apache.logging.log4j + log4j-core + 2.8.2 + true + - - commons-codec - commons-codec - + + commons-logging + commons-logging + true + - - org.codehaus.jackson - jackson-mapper-lgpl - - - net.jcip - jcip-annotations - true - - - com.github.spotbugs - spotbugs-annotations - true - - + + org.slf4j + slf4j-log4j12 + true + + + + org.apache.logging.log4j + log4j-slf4j-impl + true + + + + org.slf4j + jcl-over-slf4j + true + + + + ${project.groupId} + nacos-common + + + + ${project.groupId} + nacos-api + + + + com.alibaba + fastjson + + + + ch.qos.logback + logback-classic + + + + ch.qos.logback + logback-core + + + + com.google.guava + guava + + + + commons-codec + commons-codec + + + + org.codehaus.jackson + jackson-mapper-lgpl + + + net.jcip + jcip-annotations + true + + + + com.github.spotbugs + spotbugs-annotations + true + + + + junit + junit + test + + + diff --git a/common/pom.xml b/common/pom.xml index 2a89ef3d5..4eef4feba 100644 --- a/common/pom.xml +++ b/common/pom.xml @@ -12,40 +12,45 @@ limitations under the License. --> + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - - com.alibaba.nacos - nacos-all - 0.2.2-SNAPSHOT - - 4.0.0 + + com.alibaba.nacos + nacos-all + 0.2.2-SNAPSHOT + ../pom.xml + + 4.0.0 - nacos-common - jar + nacos-common + jar - nacos-common ${project.version} - http://maven.apache.org + nacos-common ${project.version} + http://maven.apache.org - - UTF-8 - + + UTF-8 + - - - commons-io - commons-io - - - junit - junit - test - + - - org.apache.commons - commons-lang3 - - + + commons-io + commons-io + + + + org.apache.commons + commons-lang3 + + + + + junit + junit + test + + + diff --git a/config/pom.xml b/config/pom.xml index a7f0b7a6f..495b0c361 100644 --- a/config/pom.xml +++ b/config/pom.xml @@ -18,6 +18,7 @@ com.alibaba.nacos nacos-all 0.2.2-SNAPSHOT + ../pom.xml 4.0.0 @@ -34,13 +35,6 @@ - - - com.alibaba.spring - spring-context-support - 1.0.1 - - org.springframework.boot spring-boot-starter-web diff --git a/console/pom.xml b/console/pom.xml index dceefbcf4..4c367b782 100644 --- a/console/pom.xml +++ b/console/pom.xml @@ -19,6 +19,7 @@ com.alibaba.nacos nacos-all 0.2.2-SNAPSHOT + ../pom.xml nacos-console diff --git a/core/pom.xml b/core/pom.xml index 25ae61ec9..cbaaba35b 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -19,6 +19,7 @@ com.alibaba.nacos nacos-all 0.2.2-SNAPSHOT + ../pom.xml 4.0.0 diff --git a/distribution/pom.xml b/distribution/pom.xml index 7d42c622d..cc86139c3 100644 --- a/distribution/pom.xml +++ b/distribution/pom.xml @@ -19,6 +19,7 @@ com.alibaba.nacos nacos-all 0.2.2-SNAPSHOT + ../pom.xml 4.0.0 diff --git a/example/pom.xml b/example/pom.xml index 84e6b2971..42295d5c6 100644 --- a/example/pom.xml +++ b/example/pom.xml @@ -19,6 +19,7 @@ com.alibaba.nacos nacos-all 0.2.2-SNAPSHOT + ../pom.xml 4.0.0 diff --git a/naming/pom.xml b/naming/pom.xml index fb763c2d6..ca1e6771f 100644 --- a/naming/pom.xml +++ b/naming/pom.xml @@ -19,6 +19,7 @@ com.alibaba.nacos nacos-all 0.2.2-SNAPSHOT + ../pom.xml 4.0.0 diff --git a/test/pom.xml b/test/pom.xml index 9e255cfce..ec33a71e9 100644 --- a/test/pom.xml +++ b/test/pom.xml @@ -18,6 +18,7 @@ com.alibaba.nacos nacos-all 0.2.2-SNAPSHOT + ../pom.xml 4.0.0 From 99b5827409799e9142fa7fdd76f93ebe5c65a5f7 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Mon, 1 Oct 2018 11:19:53 +0800 Subject: [PATCH 09/30] Polish alibaba/nacos#101 --- api/pom.xml | 14 + .../com/alibaba/nacos/client/AppTest.java | 53 - client/pom.xml | 27 +- .../nacos/client/logger/LoggerFactory.java | 22 +- .../client/logger/log4j/Log4jLogger.java | 146 -- .../logger/log4j/Log4jLoggerFactory.java | 53 - .../logger/option/AbstractActiveOption.java | 2 - .../logger/option/Log4jActivateOption.java | 212 --- .../Slf4jLog4jAdapterActivateOption.java | 71 - .../client/logger/slf4j/Slf4jLogger.java | 16 +- .../support/DepthThrowableRenderer.java | 90 -- .../client/logger/support/Log4jHelper.java | 201 --- config/pom.xml | 19 + pom.xml | 1344 +++++++++-------- test/pom.xml | 18 + 15 files changed, 742 insertions(+), 1546 deletions(-) delete mode 100644 api/src/test/java/com/alibaba/nacos/client/AppTest.java delete mode 100644 client/src/main/java/com/alibaba/nacos/client/logger/log4j/Log4jLogger.java delete mode 100644 client/src/main/java/com/alibaba/nacos/client/logger/log4j/Log4jLoggerFactory.java delete mode 100644 client/src/main/java/com/alibaba/nacos/client/logger/option/Log4jActivateOption.java delete mode 100644 client/src/main/java/com/alibaba/nacos/client/logger/option/Slf4jLog4jAdapterActivateOption.java delete mode 100644 client/src/main/java/com/alibaba/nacos/client/logger/support/DepthThrowableRenderer.java delete mode 100644 client/src/main/java/com/alibaba/nacos/client/logger/support/Log4jHelper.java diff --git a/api/pom.xml b/api/pom.xml index e4ae34193..0863cf634 100644 --- a/api/pom.xml +++ b/api/pom.xml @@ -37,6 +37,20 @@ com.alibaba fastjson + + + + junit + junit + test + + + + org.springframework + spring-test + test + + diff --git a/api/src/test/java/com/alibaba/nacos/client/AppTest.java b/api/src/test/java/com/alibaba/nacos/client/AppTest.java deleted file mode 100644 index 7c119e067..000000000 --- a/api/src/test/java/com/alibaba/nacos/client/AppTest.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 1999-2018 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.nacos.client; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -/** - * Unit test for simple App. - */ -public class AppTest - extends TestCase -{ - /** - * Create the test case - * - * @param testName name of the test case - */ - public AppTest( String testName ) - { - super( testName ); - } - - /** - * @return the suite of tests being tested - */ - public static Test suite() - { - return new TestSuite( AppTest.class ); - } - - /** - * Rigourous Test :-) - */ - public void testApp() - { - assertTrue( true ); - } -} diff --git a/client/pom.xml b/client/pom.xml index 82832aa72..6dc477aeb 100644 --- a/client/pom.xml +++ b/client/pom.xml @@ -33,18 +33,13 @@ + org.slf4j slf4j-api true - - log4j - log4j - true - - org.apache.logging.log4j log4j-core @@ -52,30 +47,12 @@ true - - commons-logging - commons-logging - true - - - - org.slf4j - slf4j-log4j12 - true - - org.apache.logging.log4j log4j-slf4j-impl true - - org.slf4j - jcl-over-slf4j - true - - ${project.groupId} nacos-common @@ -94,11 +71,13 @@ ch.qos.logback logback-classic + true ch.qos.logback logback-core + true diff --git a/client/src/main/java/com/alibaba/nacos/client/logger/LoggerFactory.java b/client/src/main/java/com/alibaba/nacos/client/logger/LoggerFactory.java index bc421aca7..2de5eee6e 100644 --- a/client/src/main/java/com/alibaba/nacos/client/logger/LoggerFactory.java +++ b/client/src/main/java/com/alibaba/nacos/client/logger/LoggerFactory.java @@ -15,16 +15,15 @@ */ package com.alibaba.nacos.client.logger; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import com.alibaba.nacos.client.logger.log4j.Log4jLoggerFactory; import com.alibaba.nacos.client.logger.log4j2.Log4j2LoggerFactory; import com.alibaba.nacos.client.logger.nop.NopLoggerFactory; import com.alibaba.nacos.client.logger.slf4j.Slf4jLoggerFactory; import com.alibaba.nacos.client.logger.support.ILoggerFactory; import com.alibaba.nacos.client.logger.support.LogLog; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + /** *
  * 阿里中间件LoggerFactory,获取具体日志实现
@@ -57,17 +56,12 @@ public class LoggerFactory {
             LogLog.info("Init JM logger with Slf4jLoggerFactory success, " + LoggerFactory.class.getClassLoader());
         } catch (Throwable e1) {
             try {
-                setLoggerFactory(new Log4jLoggerFactory());
-                LogLog.info("Init JM logger with Log4jLoggerFactory, " + LoggerFactory.class.getClassLoader());
+                setLoggerFactory(new Log4j2LoggerFactory());
+                LogLog.info("Init JM logger with Log4j2LoggerFactory, " + LoggerFactory.class.getClassLoader());
             } catch (Throwable e2) {
-                try {
-                    setLoggerFactory(new Log4j2LoggerFactory());
-                    LogLog.info("Init JM logger with Log4j2LoggerFactory, " + LoggerFactory.class.getClassLoader());
-                } catch (Throwable e3) {
-                    setLoggerFactory(new NopLoggerFactory());
-                    LogLog.warn("Init JM logger with NopLoggerFactory, pay attention. "
-                                + LoggerFactory.class.getClassLoader(), e2);
-                }
+                setLoggerFactory(new NopLoggerFactory());
+                LogLog.warn("Init JM logger with NopLoggerFactory, pay attention. "
+                        + LoggerFactory.class.getClassLoader(), e2);
             }
         }
 
diff --git a/client/src/main/java/com/alibaba/nacos/client/logger/log4j/Log4jLogger.java b/client/src/main/java/com/alibaba/nacos/client/logger/log4j/Log4jLogger.java
deleted file mode 100644
index 04389b494..000000000
--- a/client/src/main/java/com/alibaba/nacos/client/logger/log4j/Log4jLogger.java
+++ /dev/null
@@ -1,146 +0,0 @@
-/*
- * Copyright 1999-2018 Alibaba Group Holding Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.alibaba.nacos.client.logger.log4j;
-
-import org.apache.log4j.Level;
-
-import com.alibaba.nacos.client.logger.Logger;
-import com.alibaba.nacos.client.logger.option.Log4jActivateOption;
-import com.alibaba.nacos.client.logger.support.LoggerHelper;
-import com.alibaba.nacos.client.logger.support.LoggerSupport;
-import com.alibaba.nacos.client.logger.util.MessageUtil;
-
-
-/**
- * Log4jLogger
- * @author Nacos
- *
- */
-public class Log4jLogger extends LoggerSupport implements Logger {
-
-    private org.apache.log4j.Logger delegate;
-
-    public Log4jLogger(org.apache.log4j.Logger delegate) {
-        super(delegate);
-
-        if (delegate == null) {
-            throw new IllegalArgumentException("delegate Logger is null");
-        }
-        this.delegate = delegate;
-
-        this.activateOption = new Log4jActivateOption(delegate);
-    }
-
-    @Override
-    public void debug(String context, String message) {
-        if (isDebugEnabled()) {
-            message = LoggerHelper.getResourceBundleString(getProductName(), message);
-            delegate.debug(MessageUtil.getMessage(context, message));
-        }
-    }
-
-    @Override
-    public void debug(String context, String format, Object... args) {
-        if (isDebugEnabled()) {
-            format = LoggerHelper.getResourceBundleString(getProductName(), format);
-            delegate.debug(MessageUtil.getMessage(context, MessageUtil.formatMessage(format, args)));
-        }
-    }
-
-    @Override
-    public void info(String context, String message) {
-        if (isInfoEnabled()) {
-            message = LoggerHelper.getResourceBundleString(getProductName(), message);
-            delegate.info(MessageUtil.getMessage(context, message));
-        }
-    }
-
-    @Override
-    public void info(String context, String format, Object... args) {
-        if (isInfoEnabled()) {
-            format = LoggerHelper.getResourceBundleString(getProductName(), format);
-            delegate.info(MessageUtil.getMessage(context, MessageUtil.formatMessage(format, args)));
-        }
-    }
-
-    @Override
-    public void warn(String message, Throwable t) {
-        if (isWarnEnabled()) {
-            message = LoggerHelper.getResourceBundleString(getProductName(), message);
-            delegate.warn(MessageUtil.getMessage(null, message), t);
-        }
-    }
-
-    @Override
-    public void warn(String context, String message) {
-        if (isWarnEnabled()) {
-            message = LoggerHelper.getResourceBundleString(getProductName(), message);
-            delegate.warn(MessageUtil.getMessage(context, message));
-        }
-    }
-
-    @Override
-    public void warn(String context, String format, Object... args) {
-        if (isWarnEnabled()) {
-            format = LoggerHelper.getResourceBundleString(getProductName(), format);
-            delegate.warn(MessageUtil.getMessage(context, MessageUtil.formatMessage(format, args)));
-        }
-    }
-
-    @Override
-    public void error(String context, String errorCode, String message) {
-        if (isErrorEnabled()) {
-            message = LoggerHelper.getResourceBundleString(getProductName(), message);
-            delegate.error(MessageUtil.getMessage(context, errorCode, message));
-        }
-    }
-
-    @Override
-    public void error(String context, String errorCode, String message, Throwable t) {
-        if (isErrorEnabled()) {
-            message = LoggerHelper.getResourceBundleString(getProductName(), message);
-            delegate.error(MessageUtil.getMessage(context, errorCode, message), t);
-        }
-    }
-
-    @Override
-    public void error(String context, String errorCode, String format, Object... args) {
-        if (isErrorEnabled()) {
-            format = LoggerHelper.getResourceBundleString(getProductName(), format);
-            delegate.error(MessageUtil.getMessage(context, errorCode, MessageUtil.formatMessage(format, args)));
-        }
-    }
-
-    @Override
-    public boolean isDebugEnabled() {
-        return delegate.isDebugEnabled();
-    }
-
-    @Override
-    public boolean isInfoEnabled() {
-        return delegate.isInfoEnabled();
-    }
-
-    @Override
-    public boolean isWarnEnabled() {
-        return delegate.isEnabledFor(Level.WARN);
-    }
-
-    @Override
-    public boolean isErrorEnabled() {
-        return delegate.isEnabledFor(Level.ERROR);
-    }
-}
diff --git a/client/src/main/java/com/alibaba/nacos/client/logger/log4j/Log4jLoggerFactory.java b/client/src/main/java/com/alibaba/nacos/client/logger/log4j/Log4jLoggerFactory.java
deleted file mode 100644
index 86ca0aa9f..000000000
--- a/client/src/main/java/com/alibaba/nacos/client/logger/log4j/Log4jLoggerFactory.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright 1999-2018 Alibaba Group Holding Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.alibaba.nacos.client.logger.log4j;
-
-import org.apache.log4j.LogManager;
-
-import com.alibaba.nacos.client.logger.Logger;
-import com.alibaba.nacos.client.logger.nop.NopLogger;
-import com.alibaba.nacos.client.logger.support.ILoggerFactory;
-import com.alibaba.nacos.client.logger.support.LogLog;
-
-/**
- * Log4jLogger Factory
- * @author Nacos
- *
- */
-public class Log4jLoggerFactory implements ILoggerFactory {
-
-    public Log4jLoggerFactory() throws ClassNotFoundException {
-        Class.forName("org.apache.log4j.Level");
-    }
-
-    public Logger getLogger(Class clazz) {
-        try {
-            return new Log4jLogger(LogManager.getLogger(clazz));
-        } catch (Throwable t) {
-            LogLog.error("Failed to get Log4jLogger", t);
-            return new NopLogger();
-        }
-    }
-
-    public Logger getLogger(String name) {
-        try {
-            return new Log4jLogger(LogManager.getLogger(name));
-        } catch (Throwable t) {
-            LogLog.error("Failed to get Log4jLogger", t);
-            return new NopLogger();
-        }
-    }
-}
diff --git a/client/src/main/java/com/alibaba/nacos/client/logger/option/AbstractActiveOption.java b/client/src/main/java/com/alibaba/nacos/client/logger/option/AbstractActiveOption.java
index 209054e68..7debb078d 100644
--- a/client/src/main/java/com/alibaba/nacos/client/logger/option/AbstractActiveOption.java
+++ b/client/src/main/java/com/alibaba/nacos/client/logger/option/AbstractActiveOption.java
@@ -15,8 +15,6 @@
  */
 package com.alibaba.nacos.client.logger.option;
 
-import org.apache.log4j.AsyncAppender;
-
 import com.alibaba.nacos.client.logger.Level;
 import com.alibaba.nacos.client.logger.support.LogLog;
 
diff --git a/client/src/main/java/com/alibaba/nacos/client/logger/option/Log4jActivateOption.java b/client/src/main/java/com/alibaba/nacos/client/logger/option/Log4jActivateOption.java
deleted file mode 100644
index ca3e3a6f9..000000000
--- a/client/src/main/java/com/alibaba/nacos/client/logger/option/Log4jActivateOption.java
+++ /dev/null
@@ -1,212 +0,0 @@
-/*
- * Copyright 1999-2018 Alibaba Group Holding Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.alibaba.nacos.client.logger.option;
-
-import org.apache.log4j.*;
-
-import com.alibaba.nacos.client.logger.Logger;
-import com.alibaba.nacos.client.logger.support.LoggerHelper;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * ActivateOption的Log4j实现
- *
- * @author zhuyong 2014年3月20日 上午10:24:36
- */
-public class Log4jActivateOption extends AbstractActiveOption {
-
-    protected org.apache.log4j.Logger logger;
-
-    public Log4jActivateOption(org.apache.log4j.Logger logger) {
-        this.logger = logger;
-    }
-
-    @Override
-    public void activateConsoleAppender(String target, String encoding) {
-        org.apache.log4j.ConsoleAppender appender = new org.apache.log4j.ConsoleAppender();
-        appender.setLayout(new PatternLayout(LoggerHelper.getPattern()));
-        appender.setTarget(target);
-        appender.setEncoding(encoding);
-        appender.activateOptions();
-
-        logger.removeAllAppenders();
-        logger.addAppender(appender);
-    }
-
-    @Override
-    public void activateAppender(String productName, String file, String encoding) {
-        org.apache.log4j.Appender appender = getLog4jDailyRollingFileAppender(productName, file, encoding);
-        logger.removeAllAppenders();
-        logger.addAppender(appender);
-
-        setProductName(productName);
-    }
-
-    @Override
-    public void activateAsyncAppender(String productName, String file, String encoding) {
-        activateAsyncAppender(productName, file, encoding, Integer.MIN_VALUE, Integer.MIN_VALUE);
-    }
-
-    @Override
-    public void activateAsyncAppender(String productName, String file, String encoding, int queueSize,
-                                      int discardingThreshold) {
-        activateAppender(productName, file, encoding);
-        activateAsync(queueSize, discardingThreshold);
-    }
-
-    @Override
-    public void activateAppenderWithTimeAndSizeRolling(String productName, String file, String encoding, String size) {
-        activateAppender(productName, file, encoding);
-    }
-
-    @Override
-    public void setLevel(com.alibaba.nacos.client.logger.Level level) {
-        this.level = level;
-        logger.setLevel(org.apache.log4j.Level.toLevel(level.getName()));
-    }
-
-    @Override
-    public void setAdditivity(boolean additivity) {
-        logger.setAdditivity(additivity);
-    }
-
-    protected org.apache.log4j.Appender getLog4jDailyRollingFileAppender(String productName, String file,
-                                                                         String encoding) {
-        DailyRollingFileAppender appender = new DailyRollingFileAppender();
-        appender.setName(productName + "." + file.replace(File.separatorChar, '.') + ".Appender");
-        appender.setLayout(new PatternLayout(LoggerHelper.getPattern(productName)));
-        appender.setAppend(true);
-        appender.setFile(LoggerHelper.getLogFileP(productName, file));
-        appender.setEncoding(encoding);
-        appender.activateOptions();
-
-        return appender;
-    }
-
-    @Override
-    public void activateAppender(Logger logger) {
-        if (!(logger.getDelegate() instanceof org.apache.log4j.Logger)) {
-            throw new IllegalArgumentException(
-                    "logger must be org.apache.log4j.Logger, but it's " + logger.getDelegate().getClass());
-        }
-        activateAppender((org.apache.log4j.Logger) logger.getDelegate());
-
-        setProductName(logger.getProductName());
-    }
-
-    protected void activateAppender(org.apache.log4j.Logger logger) {
-        this.logger.removeAllAppenders();
-
-        Enumeration enums = logger.getAllAppenders();
-        while (enums != null && enums.hasMoreElements()) {
-            this.logger.addAppender((Appender) enums.nextElement());
-        }
-    }
-
-    @Override
-    public void activateAppenderWithTimeAndSizeRolling(String productName, String file, String encoding, String size,
-                                                       String datePattern) {
-        Appender appender = getLog4jRollingFileAppender(productName, file, encoding, size, datePattern, -1);
-
-        logger.removeAllAppenders();
-        logger.addAppender(appender);
-
-        setProductName(productName);
-    }
-
-    @Override
-    public void activateAppenderWithTimeAndSizeRolling(String productName, String file, String encoding, String size,
-                                                       String datePattern, int maxBackupIndex) {
-        Appender appender = getLog4jRollingFileAppender(productName, file, encoding, size, datePattern, maxBackupIndex);
-        logger.removeAllAppenders();
-        logger.addAppender(appender);
-
-        setProductName(productName);
-    }
-
-    protected org.apache.log4j.Appender getLog4jRollingFileAppender(String productName, String file, String encoding,
-                                                                    String size, String datePattern,
-                                                                    int maxBackupIndex) {
-        RollingFileAppender appender = new RollingFileAppender();
-        appender.setName(productName + "." + file.replace(File.separatorChar, '.') + ".Appender");
-        appender.setLayout(new PatternLayout(LoggerHelper.getPattern(productName)));
-        appender.setAppend(true);
-        appender.setFile(LoggerHelper.getLogFileP(productName, file));
-        appender.setEncoding(encoding);
-        appender.setMaxFileSize(size);
-        if (maxBackupIndex >= 0) {
-            // 等于0表示直接truck
-            appender.setMaxBackupIndex(maxBackupIndex);
-        }
-        appender.activateOptions();
-
-        return appender;
-    }
-
-    @Override
-    public void activateAppenderWithSizeRolling(String productName, String file, String encoding, String size,
-                                                int maxBackupIndex) {
-        Appender appender = getLog4jRollingFileAppender(productName, file, encoding, size, null, maxBackupIndex);
-        logger.removeAllAppenders();
-        logger.addAppender(appender);
-
-        setProductName(productName);
-    }
-
-    @Override
-    public void activateAsync(int queueSize, int discardingThreshold) {
-        // discardingThreshold is unused for log4j
-        List args = new ArrayList();
-
-        if (queueSize != Integer.MIN_VALUE) {
-            args.add(new Object[] { "setBufferSize", new Class[] { int.class }, queueSize });
-        }
-        activateAsync(args);
-    }
-
-    @Override
-    public void activateAsync(List args) {
-        AsyncAppender asyncAppender = new AsyncAppender();
-
-        invokeMethod(asyncAppender, args);
-
-        asyncAppender.setName(productName + "." + logger.getName() + ".AsyncAppender");
-        Enumeration appenders = logger.getAllAppenders();
-
-        if (appenders == null) {
-            throw new IllegalStateException("Activate async appender failed, no appender exist.");
-        }
-
-        while (appenders.hasMoreElements()) {
-            asyncAppender.addAppender(appenders.nextElement());
-        }
-
-        appenders = logger.getAllAppenders();
-        while (appenders.hasMoreElements()) {
-            logger.removeAppender(appenders.nextElement());
-        }
-
-        logger.addAppender(asyncAppender);
-
-        setProductName(productName);
-    }
-}
diff --git a/client/src/main/java/com/alibaba/nacos/client/logger/option/Slf4jLog4jAdapterActivateOption.java b/client/src/main/java/com/alibaba/nacos/client/logger/option/Slf4jLog4jAdapterActivateOption.java
deleted file mode 100644
index 71c0a1956..000000000
--- a/client/src/main/java/com/alibaba/nacos/client/logger/option/Slf4jLog4jAdapterActivateOption.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright 1999-2018 Alibaba Group Holding Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.alibaba.nacos.client.logger.option;
-
-import java.lang.reflect.Field;
-
-import com.alibaba.nacos.client.logger.Logger;
-
-import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
-
-/**
- * Slf4j-log4j12架构下的ActivateOption实现
- *
- * @author zhuyong 2014年3月20日 上午10:26:04
- */
-public class Slf4jLog4jAdapterActivateOption extends Log4jActivateOption {
-
-    private static Field loggerField = null;
-
-    static {
-        try {
-            loggerField = org.slf4j.impl.Log4jLoggerAdapter.class.getDeclaredField("logger");
-            loggerField.setAccessible(true);
-        } catch (Exception e) {
-            throw new RuntimeException("logger must be instanceof org.slf4j.impl.Log4jLoggerAdapter", e);
-        }
-    }
-
-    public Slf4jLog4jAdapterActivateOption(Object logger) {
-        super(null);
-
-        try {
-            org.apache.log4j.Logger log4jLogger = (org.apache.log4j.Logger) loggerField.get(logger);
-            super.logger = log4jLogger;
-        } catch (Exception e) {
-            throw new RuntimeException("logger must be instanceof org.slf4j.impl.Log4jLoggerAdapter", e);
-        }
-    }
-
-    @Override
-    @SuppressFBWarnings("NM_WRONG_PACKAGE")
-    public void activateAppender(Logger logger) {
-        if (!(logger.getDelegate() instanceof org.slf4j.impl.Log4jLoggerAdapter)) {
-            throw new IllegalArgumentException(
-                    "logger must be org.slf4j.impl.Log4jLoggerAdapter, but it's "
-                            + logger.getDelegate().getClass());
-        }
-
-        try {
-            org.apache.log4j.Logger log4jLogger =
-                    (org.apache.log4j.Logger) loggerField.get(logger.getDelegate());
-            super.activateAppender(log4jLogger);
-            setProductName(logger.getProductName());
-        } catch (Exception e) {
-            throw new RuntimeException("activateAppender error, ", e);
-        }
-    }
-}
diff --git a/client/src/main/java/com/alibaba/nacos/client/logger/slf4j/Slf4jLogger.java b/client/src/main/java/com/alibaba/nacos/client/logger/slf4j/Slf4jLogger.java
index 9d5fd03c2..d3543e0c0 100644
--- a/client/src/main/java/com/alibaba/nacos/client/logger/slf4j/Slf4jLogger.java
+++ b/client/src/main/java/com/alibaba/nacos/client/logger/slf4j/Slf4jLogger.java
@@ -15,24 +15,25 @@
  */
 package com.alibaba.nacos.client.logger.slf4j;
 
-import java.lang.reflect.Constructor;
-
 import com.alibaba.nacos.client.logger.Logger;
 import com.alibaba.nacos.client.logger.option.ActivateOption;
 import com.alibaba.nacos.client.logger.support.LoggerHelper;
 import com.alibaba.nacos.client.logger.support.LoggerSupport;
 import com.alibaba.nacos.client.logger.util.MessageUtil;
+
+import java.lang.reflect.Constructor;
+
 /**
  * slf4j logger
- * @author Nacos
  *
+ * @author Nacos
  */
 public class Slf4jLogger extends LoggerSupport implements Logger {
 
-    private static boolean   CanUseEncoder = false;
+    private static boolean CanUseEncoder = false;
     private static final String LOGBACK_CLASSNAME = "ch.qos.logback.classic.Logger";
-    private static final String SLF4J_CLASSNAME = "org.slf4j.impl.Log4jLoggerAdapter";
     private static final String SLF4JLOG4J_CLASSNAME = "org.apache.logging.slf4j.Log4jLogger";
+
     static {
         try {
             // logback从0.9.19开始采用encoder,@see http://logback.qos.ch/manual/encoders.html
@@ -46,8 +47,7 @@ public class Slf4jLogger extends LoggerSupport implements Logger {
     private org.slf4j.Logger delegate;
 
     @SuppressWarnings("unchecked")
-    public
-    Slf4jLogger(org.slf4j.Logger delegate){
+    public Slf4jLogger(org.slf4j.Logger delegate) {
         super(delegate);
         if (delegate == null) {
             throw new IllegalArgumentException("delegate Logger is null");
@@ -61,8 +61,6 @@ public class Slf4jLogger extends LoggerSupport implements Logger {
             } else {
                 activateOptionClass = "com.alibaba.nacos.client.logger.option.Logback918ActivateOption";
             }
-        } else if (SLF4J_CLASSNAME.equals(delegate.getClass().getName())) {
-            activateOptionClass = "com.alibaba.nacos.client.logger.option.Slf4jLog4jAdapterActivateOption";
         } else if (SLF4JLOG4J_CLASSNAME.equals(delegate.getClass().getName())) {
             activateOptionClass = "com.alibaba.nacos.client.logger.option.Slf4jLog4j2AdapterActivateOption";
         }
diff --git a/client/src/main/java/com/alibaba/nacos/client/logger/support/DepthThrowableRenderer.java b/client/src/main/java/com/alibaba/nacos/client/logger/support/DepthThrowableRenderer.java
deleted file mode 100644
index 59e4299a4..000000000
--- a/client/src/main/java/com/alibaba/nacos/client/logger/support/DepthThrowableRenderer.java
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * Copyright 1999-2018 Alibaba Group Holding Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-/*
- * Copyright 2014 Alibaba.com All right reserved. This software is the
- * confidential and proprietary information of Alibaba.com ("Confidential
- * Information"). You shall not disclose such Confidential Information and shall
- * use it only in accordance with the terms of the license agreement you entered
- * into with Alibaba.com.
- */
-package com.alibaba.nacos.client.logger.support;
-
-import java.io.IOException;
-import java.io.InterruptedIOException;
-import java.io.LineNumberReader;
-import java.io.PrintWriter;
-import java.io.StringReader;
-import java.io.StringWriter;
-import java.util.ArrayList;
-
-import org.apache.log4j.spi.ThrowableRenderer;
-
-/**
- * 针对 Log4j 1.2.16 及以上版本,提供对异常栈的深度控制
- *
- * @author zhuyong 2014年9月19日 上午10:31:48
- */
-public final class DepthThrowableRenderer implements ThrowableRenderer {
-
-    private int depth = -1;
-
-    public DepthThrowableRenderer(int depth) {
-        this.depth = depth;
-    }
-
-    public void setDepth(int depth) {
-        this.depth = depth;
-    }
-
-    public String[] doRender(final Throwable throwable) {
-        return render(throwable, depth);
-    }
-
-    /**
-     * Render throwable using Throwable.printStackTrace.
-     *
-     * @param throwable throwable, may not be null.
-     * @param depth     stack depth
-     * @return string representation.
-     */
-    public static String[] render(final Throwable throwable, final int depth) {
-        StringWriter sw = new StringWriter();
-        PrintWriter pw = new PrintWriter(sw);
-        try {
-            throwable.printStackTrace(pw);
-        } catch (RuntimeException ex) {
-        }
-        pw.flush();
-        LineNumberReader reader = new LineNumberReader(new StringReader(sw.toString()));
-        ArrayList lines = new ArrayList();
-        try {
-            String line = reader.readLine();
-            int count = 0;
-            while (line != null && (depth == -1 || count++ <= depth)) {
-                lines.add(line);
-                line = reader.readLine();
-            }
-        } catch (IOException ex) {
-            if (ex instanceof InterruptedIOException) {
-                Thread.currentThread().interrupt();
-            }
-            lines.add(ex.toString());
-        }
-        String[] tempRep = new String[lines.size()];
-        lines.toArray(tempRep);
-        return tempRep;
-    }
-}
diff --git a/client/src/main/java/com/alibaba/nacos/client/logger/support/Log4jHelper.java b/client/src/main/java/com/alibaba/nacos/client/logger/support/Log4jHelper.java
deleted file mode 100644
index 2597a9ba6..000000000
--- a/client/src/main/java/com/alibaba/nacos/client/logger/support/Log4jHelper.java
+++ /dev/null
@@ -1,201 +0,0 @@
-/*
- * Copyright 1999-2018 Alibaba Group Holding Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.alibaba.nacos.client.logger.support;
-
-import org.apache.log4j.Appender;
-import org.apache.log4j.AsyncAppender;
-import org.apache.log4j.ConsoleAppender;
-import org.apache.log4j.FileAppender;
-import org.apache.log4j.Level;
-import org.apache.log4j.LogManager;
-import org.apache.log4j.Logger;
-import org.apache.log4j.spi.LoggerRepository;
-import org.apache.log4j.spi.ThrowableRenderer;
-import org.apache.log4j.spi.ThrowableRendererSupport;
-
-import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
-
-import java.util.ArrayList;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * @author zhuyong on 2017/6/28.
- */
-@SuppressWarnings("PMD.AbstractClassShouldStartWithAbstractNamingRule")
-public class Log4jHelper {
-
-    private static boolean Log4j = false, Log4jGT1216 = false;
-
-    static {
-        try {
-            Class loggerClass = Class.forName("org.apache.log4j.Logger");
-            // 这里可能会加载到应用中依赖的log4j,因此需要判断classloader
-            if (loggerClass.getClassLoader().equals(Log4jHelper.class.getClassLoader())) {
-                LogManager.getLoggerRepository();
-                try {
-                    Class throwableRendererClass = Class.forName("org.apache.log4j.spi.ThrowableRenderer");
-                    // 这里可能会加载到应用中依赖的log4j 1.2.16版本的类,因此需要额外判断
-                    if (loggerClass.getClassLoader().equals(throwableRendererClass.getClassLoader())
-                        && throwableRendererClass.getClassLoader().equals(Log4jHelper.class.getClassLoader())) {
-                        Log4jGT1216 = true;
-                    }
-                } catch (Throwable t) {
-                    LogLog.warn("log4j must >= 1.2.16 for change throwable depth");
-                }
-                Log4j = true;
-            }
-        } catch (Throwable t) {
-        }
-    }
-    @SuppressFBWarnings("NP_BOOLEAN_RETURN_NULL")
-    public static Boolean setDepth(int depth) {
-        if (Log4j && Log4jGT1216) {
-            try {
-                LoggerRepository repo = LogManager.getLoggerRepository();
-                doSetDepth(repo, depth);
-                return Boolean.TRUE;
-            } catch (Throwable t) {
-                // ignore
-                LogLog.error("failed to set depth for log4j", t);
-                return Boolean.FALSE;
-            }
-        }
-
-        return null;
-    }
-    @SuppressFBWarnings("NP_BOOLEAN_RETURN_NULL")
-    public static Boolean changeLevel(String name, String level) {
-        if (Log4j) {
-            Level l = Level.toLevel(level, Level.ERROR);
-            Logger logger = LogManager.getLoggerRepository().exists(name);
-            if (logger != null) {
-                logger.setLevel(l);
-                LogLog.info("set log4j log level success, " + name + ": " + l);
-                return true;
-            } else {
-                Logger root = LogManager.getLoggerRepository().getRootLogger();
-                if (root.getName().equals(name)) {
-                    root.setLevel(l);
-                    LogLog.info("set log4j log level success, " + name + ": " + l);
-                    return true;
-                }
-            }
-            LogLog.info("set log4j log level fail, no logger name exists: " + name);
-            return false;
-        }
-        return null;
-    }
-
-    public static Map getLoggers(String name) {
-        Map appenders = new HashMap(10);
-        if (!Log4j) {
-            return appenders;
-        }
-
-        if (name != null && !"".equals(name.trim())) {
-            Logger logger = LogManager.getLoggerRepository().exists(name);
-            if (logger != null) {
-                appenders.put(name, doGetLoggerInfo(logger));
-            }
-        } else {
-            // 获取所有logger时,如果没有appender则忽略
-            Enumeration loggers = LogManager.getLoggerRepository().getCurrentLoggers();
-
-            if (loggers != null) {
-                while (loggers.hasMoreElements()) {
-                    Logger logger = loggers.nextElement();
-                    LoggerInfo info = doGetLoggerInfo(logger);
-                    if (info.getAppenders() == null || !info.getAppenders().isEmpty()) {
-                        appenders.put(logger.getName(), info);
-                    }
-                }
-            }
-
-            Logger root = LogManager.getLoggerRepository().getRootLogger();
-            if (root != null) {
-                LoggerInfo info = doGetLoggerInfo(root);
-                if (info.getAppenders() == null || !info.getAppenders().isEmpty()) {
-                    appenders.put(root.getName(), info);
-                }
-            }
-        }
-
-        return appenders;
-    }
-
-    private static LoggerInfo doGetLoggerInfo(Logger logger) {
-        LoggerInfo info = new LoggerInfo(logger.getName(), logger.getAdditivity());
-        Level level = logger.getLevel(), effectiveLevel = logger.getEffectiveLevel();
-        if (level != null) {
-        	info.setLevel(level.toString());
-        }
-        if (effectiveLevel != null) {
-        	info.setEffectiveLevel(effectiveLevel.toString());
-        }
-
-        List result = doGetLoggerAppenders(logger.getAllAppenders());
-        info.setAppenders(result);
-        return info;
-    }
-
-    private static List doGetLoggerAppenders(Enumeration appenders) {
-        List result = new ArrayList();
-
-        while (appenders.hasMoreElements()) {
-            AppenderInfo info = new AppenderInfo();
-            Appender appender = appenders.nextElement();
-
-            info.setName(appender.getName());
-            info.setType(appender.getClass().getName());
-
-            result.add(info);
-            if (appender instanceof FileAppender) {
-                info.setFile(((FileAppender) appender).getFile());
-            } else if (appender instanceof ConsoleAppender) {
-                info.withDetail("target", ((ConsoleAppender) appender).getTarget());
-            } else if (appender instanceof AsyncAppender) {
-                List asyncs = doGetLoggerAppenders(((AsyncAppender) appender).getAllAppenders());
-                // 标明异步appender
-                List nestedNames = new ArrayList();
-                for (AppenderInfo a : asyncs) {
-                    nestedNames.add(a.getName());
-                    result.add(a);
-                }
-                info.withDetail("nestedNames", nestedNames);
-            }
-        }
-
-        return result;
-    }
-
-    private static void doSetDepth(LoggerRepository repo, int depth) {
-        if (repo instanceof ThrowableRendererSupport) {
-            Object tr = ((ThrowableRendererSupport) repo).getThrowableRenderer();
-            if (tr == null || !(tr instanceof DepthThrowableRenderer)) {
-                Object ctr = new DepthThrowableRenderer(depth);
-                // 自定义ThrowableRender,栈深度设置
-                ((ThrowableRendererSupport) repo).setThrowableRenderer((ThrowableRenderer) ctr);
-                LogLog.info("set log4j log depth success, depth: " + depth);
-            } else {
-                ((DepthThrowableRenderer) tr).setDepth(depth);
-                LogLog.info("set log4j log depth success, depth: " + depth);
-            }
-        }
-    }
-}
diff --git a/config/pom.xml b/config/pom.xml
index 495b0c361..0c974c098 100644
--- a/config/pom.xml
+++ b/config/pom.xml
@@ -119,7 +119,26 @@
             test
         
 
+        
+            org.mockito
+            mockito-core
+            test
+        
+
+        
+            org.springframework
+            spring-test
+            test
+        
+
+        
+            org.springframework.boot
+            spring-boot-test
+            test
+        
+
     
+
     
         
             
diff --git a/pom.xml b/pom.xml
index 2cba0f885..1eb733b91 100644
--- a/pom.xml
+++ b/pom.xml
@@ -14,705 +14,707 @@
   limitations under the License.
  -->
 
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 
-	4.0.0
-	2018
-	com.alibaba.nacos
-	nacos-all
-	0.2.2-SNAPSHOT
-	pom
+    4.0.0
+    2018
+    com.alibaba.nacos
+    nacos-all
+    0.2.2-SNAPSHOT
+    pom
 
-	Alibaba NACOS ${project.version}
-	Top Nacos project pom.xml file
-	http://nacos.io
-	
-		3.2.5
-	
+    Alibaba NACOS ${project.version}
+    Top Nacos project pom.xml file
+    http://nacos.io
+    
+        3.2.5
+    
 
 
-	
-		git@github.com:alibaba/nacos.git
-		scm:git@github.com:alibaba/nacos.git
-		scm:git@github.com:alibaba/nacos.git
-		nacos-all-0.2.2-SNAPSHOT
-	
+    
+        git@github.com:alibaba/nacos.git
+        scm:git@github.com:alibaba/nacos.git
+        scm:git@github.com:alibaba/nacos.git
+        nacos-all-0.2.2-SNAPSHOT
+    
 
-	
-		
-			Development List
-			dev-nacos+subscribe@googlegroups.com
-			dev-nacos+unsubscribe@googlegroups.com
-			dev-nacos@googlegroups.com
-		
-		
-			User List
-			users-nacos+subscribe@googlegroups.com
-			users-nacos+unsubscribe@googlegroups.com
-			users-nacos@googlegroups.com
-		
-		
-			Commits List
-			commits-nacos+subscribe@googlegroups.com
-			commits-nacos+unsubscribe@googlegroups.com
-			commits-nacos@googlegroups.com
-		
-	
+    
+        
+            Development List
+            dev-nacos+subscribe@googlegroups.com
+            dev-nacos+unsubscribe@googlegroups.com
+            dev-nacos@googlegroups.com
+        
+        
+            User List
+            users-nacos+subscribe@googlegroups.com
+            users-nacos+unsubscribe@googlegroups.com
+            users-nacos@googlegroups.com
+        
+        
+            Commits List
+            commits-nacos+subscribe@googlegroups.com
+            commits-nacos+unsubscribe@googlegroups.com
+            commits-nacos@googlegroups.com
+        
+    
 
-	
-		
-			Alibaba Nacos
-			Nacos
-			http://nacos.io
-			nacos_dev@linux.alibaba.com
-		
-	
+    
+        
+            Alibaba Nacos
+            Nacos
+            http://nacos.io
+            nacos_dev@linux.alibaba.com
+        
+    
 
-	
-		
-			Apache License, Version 2.0
-			http://www.apache.org/licenses/LICENSE-2.0
-			repo
-		
-	
+    
+        
+            Apache License, Version 2.0
+            http://www.apache.org/licenses/LICENSE-2.0
+            repo
+        
+    
 
-	
-		Alibaba Group
-		https://github.com/alibaba
-	
+    
+        Alibaba Group
+        https://github.com/alibaba
+    
 
-	
-		github
-		https://github.com/alibaba/nacos/issues
-	
+    
+        github
+        https://github.com/alibaba/nacos/issues
+    
 
-	
-		UTF-8
-		UTF-8
+    
+        UTF-8
+        UTF-8
 
-		
-		false
-		true
-		
-		1.6
-		1.6
-		jacoco
-		
-		${project.basedir}/../test/target/jacoco-it.exec
-		file:**/generated-sources/**,**/test/**
+        
+        false
+        true
+        
+        1.6
+        1.6
+        jacoco
+        
+        ${project.basedir}/../test/target/jacoco-it.exec
+        file:**/generated-sources/**,**/test/**
 
-	
-	
-	
-	
-	
-		
-			
-				org.codehaus.mojo
-				versions-maven-plugin
-				2.2
-			
-			
-				com.github.vongosling
-				dependency-mediator-maven-plugin
-				1.0.2
-			
-			
-				org.codehaus.mojo
-				clirr-maven-plugin
-				2.7
-			
-			
-				maven-enforcer-plugin
-				1.4.1
-				
-					
-						enforce-ban-circular-dependencies
-						
-							enforce
-						
-					
-				
-				
-					
-						
-					
-					true
-				
-				
-					
-						org.codehaus.mojo
-						extra-enforcer-rules
-						1.0-beta-4
-					
-				
-			
-			
-				maven-compiler-plugin
-				3.5.1
-				
-					${maven.compiler.source}
-					${maven.compiler.target}
-					${maven.compiler.source}
-					true
-					true
-				
-			
-			
-				maven-javadoc-plugin
-				2.10.4
-				
-					UTF-8
-				
-				
-					
-						attach-javadocs
-						
-							jar
-						
-					
-				
-			
-			
-				maven-source-plugin
-				3.0.1
-				
-					
-						attach-sources
-						
-							jar
-						
-					
-				
-			
-			
-				org.apache.maven.plugins
-				maven-pmd-plugin
-				3.8
-				
-					
-						rulesets/java/ali-comment.xml
-						rulesets/java/ali-concurrent.xml
-						rulesets/java/ali-constant.xml
-						rulesets/java/ali-exception.xml
-						rulesets/java/ali-flowcontrol.xml
-						rulesets/java/ali-naming.xml
-						rulesets/java/ali-oop.xml
-						rulesets/java/ali-orm.xml
-						rulesets/java/ali-other.xml
-						rulesets/java/ali-set.xml
-					
-					true
-				
-				
-					
-						
-							check
-						
-					
-				
-				
-					
-						com.alibaba.p3c
-						p3c-pmd
-						1.3.0
-					
-				
-			
-			
-				org.apache.rat
-				apache-rat-plugin
-				0.12
+    
+    
+    
+    
+    
+        
+            
+                org.codehaus.mojo
+                versions-maven-plugin
+                2.2
+            
+            
+                com.github.vongosling
+                dependency-mediator-maven-plugin
+                1.0.2
+            
+            
+                org.codehaus.mojo
+                clirr-maven-plugin
+                2.7
+            
+            
+                maven-enforcer-plugin
+                1.4.1
+                
+                    
+                        enforce-ban-circular-dependencies
+                        
+                            enforce
+                        
+                    
+                
+                
+                    
+                        
+                    
+                    true
+                
+                
+                    
+                        org.codehaus.mojo
+                        extra-enforcer-rules
+                        1.0-beta-4
+                    
+                
+            
+            
+                maven-compiler-plugin
+                3.5.1
+                
+                    ${maven.compiler.source}
+                    ${maven.compiler.target}
+                    ${maven.compiler.source}
+                    true
+                    true
+                
+            
+            
+                maven-javadoc-plugin
+                2.10.4
+                
+                    UTF-8
+                
+                
+                    
+                        attach-javadocs
+                        
+                            jar
+                        
+                    
+                
+            
+            
+                maven-source-plugin
+                3.0.1
+                
+                    
+                        attach-sources
+                        
+                            jar
+                        
+                    
+                
+            
+            
+                org.apache.maven.plugins
+                maven-pmd-plugin
+                3.8
+                
+                    
+                        rulesets/java/ali-comment.xml
+                        rulesets/java/ali-concurrent.xml
+                        rulesets/java/ali-constant.xml
+                        rulesets/java/ali-exception.xml
+                        rulesets/java/ali-flowcontrol.xml
+                        rulesets/java/ali-naming.xml
+                        rulesets/java/ali-oop.xml
+                        rulesets/java/ali-orm.xml
+                        rulesets/java/ali-other.xml
+                        rulesets/java/ali-set.xml
+                    
+                    true
+                
+                
+                    
+                        
+                            check
+                        
+                    
+                
+                
+                    
+                        com.alibaba.p3c
+                        p3c-pmd
+                        1.3.0
+                    
+                
+            
+            
+                org.apache.rat
+                apache-rat-plugin
+                0.12
 
-				
+                
 
-					
-						.travis.yml
-						CONTRIBUTING.md
-						CHANGELOG.md
-						style/codeStyle.md
-						REPORTING-BUGS.md
-						README.md
-						.github/*
-						.github/ISSUE_TEMPLATE/bug_report.md
-						.github/ISSUE_TEMPLATE/feature_request.md
-						src/main/resources/*/*
-						src/main/resources/*
-						src/test/resources/*
-						bin/*
-						conf/*
+                    
+                        .travis.yml
+                        CONTRIBUTING.md
+                        CHANGELOG.md
+                        style/codeStyle.md
+                        REPORTING-BUGS.md
+                        README.md
+                        .github/*
+                        .github/ISSUE_TEMPLATE/bug_report.md
+                        .github/ISSUE_TEMPLATE/feature_request.md
+                        src/main/resources/*/*
+                        src/main/resources/*
+                        src/test/resources/*
+                        bin/*
+                        conf/*
                         derby.log
 
-					
-				
-			
-			
-				maven-resources-plugin
-				3.0.2
-				
-					
-					${project.build.sourceEncoding}
-				
-			
-			
-				org.eluder.coveralls
-				coveralls-maven-plugin
-				4.3.0
-			
-			
-				org.jacoco
-				jacoco-maven-plugin
-				0.7.8
-				
-					
-						default-prepare-agent
-						
-							prepare-agent
-						
-						
-							${project.build.directory}/jacoco.exec
-						
-					
-					
-						default-prepare-agent-integration
-						pre-integration-test
-						
-							prepare-agent-integration
-						
-						
-							${project.build.directory}/jacoco-it.exec
-							failsafeArgLine
-						
-					
-					
-						default-report
-						
-							report
-						
-					
-					
-						default-report-integration
-						
-							report-integration
-						
-					
-				
-			
-			
-				maven-surefire-plugin
-				2.19.1
-				
-					1
-					true
-				
-			
-			
-				org.codehaus.mojo
-				findbugs-maven-plugin
-				3.0.4
-			
-			
-				org.sonarsource.scanner.maven
-				sonar-maven-plugin
-				3.0.2
-			
-		
+                    
+                
+            
+            
+                maven-resources-plugin
+                3.0.2
+                
+                    
+                    ${project.build.sourceEncoding}
+                
+            
+            
+                org.eluder.coveralls
+                coveralls-maven-plugin
+                4.3.0
+            
+            
+                org.jacoco
+                jacoco-maven-plugin
+                0.7.8
+                
+                    
+                        default-prepare-agent
+                        
+                            prepare-agent
+                        
+                        
+                            ${project.build.directory}/jacoco.exec
+                        
+                    
+                    
+                        default-prepare-agent-integration
+                        pre-integration-test
+                        
+                            prepare-agent-integration
+                        
+                        
+                            ${project.build.directory}/jacoco-it.exec
+                            failsafeArgLine
+                        
+                    
+                    
+                        default-report
+                        
+                            report
+                        
+                    
+                    
+                        default-report-integration
+                        
+                            report-integration
+                        
+                    
+                
+            
+            
+                maven-surefire-plugin
+                2.19.1
+                
+                    1
+                    true
+                
+            
+            
+                org.codehaus.mojo
+                findbugs-maven-plugin
+                3.0.4
+            
+            
+                org.sonarsource.scanner.maven
+                sonar-maven-plugin
+                3.0.2
+            
+        
 
-	
+    
 
-	
-		
-			jdk7
-			
-				[1.7,)
-			
-			
-			
-				
-					
-						maven-javadoc-plugin
-						2.10.4
-						
-							-Xdoclint:none
-						
-					
-				
-			
-			
-				
-					
-						maven-javadoc-plugin
-						2.10.4
-						
-							-Xdoclint:none
-						
-					
-				
-			
-		
-		
-			release-sign-artifacts
-			
-				
-					performRelease
-					true
-				
-			
-			
-				
-					
-						maven-gpg-plugin
-						1.6
-						
-							
-								sign-artifacts
-								verify
-								
-									sign
-								
-							
-						
-					
-				
-			
-		
-		
-			it-test
-			
-				
-					
-						maven-failsafe-plugin
-						2.19.1
-						
-							@{failsafeArgLine}
-							-Dnacos.standalone=true
-							
-								**/*ITCase.java
-							
-							
-								**/RestAPI_ITCase.java
-							
-						
-						
-							
-								
-									integration-test
-									verify
-								
-							
-						
-					
-				
-			
-		
-		
-			sonar-apache
-			
-				
-				https://builds.apache.org/analysis
-			
-		
-	
-	
-		
-			
-				org.codehaus.mojo
-				findbugs-maven-plugin
-				3.0.1
-			
-		
-	
+    
+        
+            jdk7
+            
+                [1.7,)
+            
+            
+            
+                
+                    
+                        maven-javadoc-plugin
+                        2.10.4
+                        
+                            -Xdoclint:none
+                        
+                    
+                
+            
+            
+                
+                    
+                        maven-javadoc-plugin
+                        2.10.4
+                        
+                            -Xdoclint:none
+                        
+                    
+                
+            
+        
+        
+            release-sign-artifacts
+            
+                
+                    performRelease
+                    true
+                
+            
+            
+                
+                    
+                        maven-gpg-plugin
+                        1.6
+                        
+                            
+                                sign-artifacts
+                                verify
+                                
+                                    sign
+                                
+                            
+                        
+                    
+                
+            
+        
+        
+            it-test
+            
+                
+                    
+                        maven-failsafe-plugin
+                        2.19.1
+                        
+                            @{failsafeArgLine}
+                            -Dnacos.standalone=true
+                            
+                                **/*ITCase.java
+                            
+                            
+                                **/RestAPI_ITCase.java
+                            
+                        
+                        
+                            
+                                
+                                    integration-test
+                                    verify
+                                
+                            
+                        
+                    
+                
+            
+        
+        
+            sonar-apache
+            
+                
+                https://builds.apache.org/analysis
+            
+        
+    
+    
+        
+            
+                org.codehaus.mojo
+                findbugs-maven-plugin
+                3.0.1
+            
+        
+    
 
-	
-	
-		config
-		core
-		naming
-		test
-		api
-		client
-		example
-		common
-		distribution
-		console
-	
+    
+    
+        config
+        core
+        naming
+        test
+        api
+        client
+        example
+        common
+        distribution
+        console
+    
 
-	
-	
-		
-			org.springframework.boot
-			spring-boot-starter-test
-			test
-		
-	
+    
+    
 
-	
-	
-		
-			
-				
-				org.springframework.boot
-				spring-boot-dependencies
-				2.0.5.RELEASE
-				pom
-				import
-			
+        
+            junit
+            junit
+            test
+        
 
-			
-				${project.groupId}
-				nacos-config
-				${project.version}
-			
-			
-				${project.groupId}
-				nacos-core
-				${project.version}
-			
-			
-				${project.groupId}
-				nacos-naming
-				${project.version}
-			
-			
-				${project.groupId}
-				nacos-api
-				${project.version}
-			
-			
-				${project.groupId}
-				nacos-client
-				${project.version}
-			
-			
-				${project.groupId}
-				nacos-test
-				${project.version}
-			
-			
-				${project.groupId}
-				nacos-common
-				${project.version}
-			
-			
-				${project.groupId}
-				nacos-console
-				${project.version}
-			
-			
-				${project.groupId}
-				nacos-distribution
-				${project.version}
-			
-			
-				${project.groupId}
-				nacos-example
-				${project.version}
-			
-			
-				org.slf4j
-				slf4j-api
-				1.7.7
-			
-			
-				ch.qos.logback
-				logback-classic
-				1.2.3
-			
-			
-				ch.qos.logback
-				logback-core
-				1.2.3
-			
-			
-				commons-cli
-				commons-cli
-				1.2
-			
-			
-				io.netty
-				netty-all
-				4.0.42.Final
-			
-			
-				com.alibaba
-				fastjson
-				1.2.47
-			
-			
-				com.ning
-				async-http-client
-				1.7.17
-			
-			
-				org.apache.commons
-				commons-lang3
-				3.4
-			
-			
-				commons-lang
-				commons-lang
-				2.6
-			
-			
-				commons-collections
-				commons-collections
-				3.2.2
-			
-			
-				commons-logging
-				commons-logging
-				1.2
-			
-			
-				org.codehaus.jackson
-				jackson-core-asl
-				1.9.10
-			
-			
-				apache-log4j
-				log4j
-				1.2.15
-			
-			
-				log4j
-				log4j
-				1.2.17
-			
-			
-				org.apache.logging.log4j
-				log4j-core
-				2.10.0
-			
-			
-				org.apache.logging.log4j
-				log4j-slf4j-impl
-				2.10.0
-			
-			
-				com.github.spotbugs
-				spotbugs-annotations
-				3.1.3
-			
-			
+    
 
-			
-				javax.ws.rs
-				javax.ws.rs
-				2.1
-			
-			
-				javax.servlet
-				servlet-api
-				3.0
-				provided
-			
-			
-				taglibs
-				standard
-				1.1.2
-			
+    
+    
+        
+            
+                
+                org.springframework.boot
+                spring-boot-dependencies
+                2.0.5.RELEASE
+                pom
+                import
+            
 
-			
-				commons-io
-				commons-io
-				2.2
-			
-			
-				mysql
-				mysql-connector-java
-				5.1.34
-			
+            
+                ${project.groupId}
+                nacos-config
+                ${project.version}
+            
+            
+                ${project.groupId}
+                nacos-core
+                ${project.version}
+            
+            
+                ${project.groupId}
+                nacos-naming
+                ${project.version}
+            
+            
+                ${project.groupId}
+                nacos-api
+                ${project.version}
+            
+            
+                ${project.groupId}
+                nacos-client
+                ${project.version}
+            
+            
+                ${project.groupId}
+                nacos-test
+                ${project.version}
+            
+            
+                ${project.groupId}
+                nacos-common
+                ${project.version}
+            
+            
+                ${project.groupId}
+                nacos-console
+                ${project.version}
+            
+            
+                ${project.groupId}
+                nacos-distribution
+                ${project.version}
+            
+            
+                ${project.groupId}
+                nacos-example
+                ${project.version}
+            
+            
+                org.slf4j
+                slf4j-api
+                1.7.7
+            
+            
+                ch.qos.logback
+                logback-classic
+                1.2.3
+            
+            
+                ch.qos.logback
+                logback-core
+                1.2.3
+            
+            
+                commons-cli
+                commons-cli
+                1.2
+            
+            
+                io.netty
+                netty-all
+                4.0.42.Final
+            
+            
+                com.alibaba
+                fastjson
+                1.2.47
+            
+            
+                com.ning
+                async-http-client
+                1.7.17
+            
+            
+                org.apache.commons
+                commons-lang3
+                3.4
+            
+            
+                commons-lang
+                commons-lang
+                2.6
+            
+            
+                commons-collections
+                commons-collections
+                3.2.2
+            
+            
+                commons-logging
+                commons-logging
+                1.2
+            
+            
+                org.codehaus.jackson
+                jackson-core-asl
+                1.9.10
+            
+            
+                apache-log4j
+                log4j
+                1.2.15
+            
+            
+                log4j
+                log4j
+                1.2.17
+            
+            
+                org.apache.logging.log4j
+                log4j-core
+                2.10.0
+            
+            
+                org.apache.logging.log4j
+                log4j-slf4j-impl
+                2.10.0
+            
+            
+                com.github.spotbugs
+                spotbugs-annotations
+                3.1.3
+            
+            
 
-			
-				commons-dbcp
-				commons-dbcp
-				1.4
-			
+            
+                javax.ws.rs
+                javax.ws.rs
+                2.1
+            
+            
+                javax.servlet
+                servlet-api
+                3.0
+                provided
+            
+            
+                taglibs
+                standard
+                1.1.2
+            
 
-			
-				org.apache.derby
-				derby
-				10.10.1.1
-			
+            
+                commons-io
+                commons-io
+                2.2
+            
+            
+                mysql
+                mysql-connector-java
+                5.1.34
+            
 
-			
-				cglib
-				cglib-nodep
-				2.1
-			
-			
-				org.apache.httpcomponents
-				httpasyncclient
-				4.1.3
-			
-			
-				net.jcip
-				jcip-annotations
-				1.0
-			
-			
-				org.codehaus.jackson
-				jackson-mapper-lgpl
-				1.9.6
-			
-			
+            
+                commons-dbcp
+                commons-dbcp
+                1.4
+            
+
+            
+                org.apache.derby
+                derby
+                10.10.1.1
+            
+
+            
+                cglib
+                cglib-nodep
+                2.1
+            
+            
+                org.apache.httpcomponents
+                httpasyncclient
+                4.1.3
+            
+            
+                net.jcip
+                jcip-annotations
+                1.0
+            
+            
+                org.codehaus.jackson
+                jackson-mapper-lgpl
+                1.9.6
+            
+            
 
 
-			
-			
-				org.apache.mina
-				mina-core
-				2.0.0-RC1
-			
-			
-				com.google.guava
-				guava
-				19.0
-			
-			
-				org.javatuples
-				javatuples
-				1.2
-			
-			
-				org.apache.velocity
-				velocity
-				1.7
-			
-			
-				org.apache.velocity
-				velocity-tools
-				2.0
-				
-					
-						commons-logging
-						commons-logging
-					
-					
-						commons-digester
-						commons-digester
-					
-				
-			
-			
-				org.apache.httpcomponents
-				httpcore
-				4.4.1
-			
-			
-				org.apache.httpcomponents
-				httpclient
-				4.5
-				
-					
-						commons-logging
-						commons-logging
-					
-				
-			
-			
-		
-	
+            
+            
+                org.apache.mina
+                mina-core
+                2.0.0-RC1
+            
+            
+                com.google.guava
+                guava
+                19.0
+            
+            
+                org.javatuples
+                javatuples
+                1.2
+            
+            
+                org.apache.velocity
+                velocity
+                1.7
+            
+            
+                org.apache.velocity
+                velocity-tools
+                2.0
+                
+                    
+                        commons-logging
+                        commons-logging
+                    
+                    
+                        commons-digester
+                        commons-digester
+                    
+                
+            
+            
+                org.apache.httpcomponents
+                httpcore
+                4.4.1
+            
+            
+                org.apache.httpcomponents
+                httpclient
+                4.5
+                
+                    
+                        commons-logging
+                        commons-logging
+                    
+                
+            
+            
+        
+    
 
 
diff --git a/test/pom.xml b/test/pom.xml
index ec33a71e9..ffffc016d 100644
--- a/test/pom.xml
+++ b/test/pom.xml
@@ -73,6 +73,24 @@
 			${project.groupId}
 			nacos-core
 		
+
+		
+			junit
+			junit
+			test
+		
+
+		
+			org.springframework
+			spring-test
+			test
+		
+
+		
+			org.springframework.boot
+			spring-boot-test
+			test
+		
 	
 
 	

From dc7a4eaa8582cec7aa41139f8fbbba54161bcdbb Mon Sep 17 00:00:00 2001
From: mercyblitz 
Date: Mon, 1 Oct 2018 11:34:36 +0800
Subject: [PATCH 10/30] Polish alibaba/nacos#102

---
 .../alibaba/nacos/common/util/IoUtils.java    | 121 +-----------------
 .../alibaba/nacos/naming/misc/HttpClient.java |  13 +-
 .../nacos/naming/misc/NamingProxy.java        |   9 +-
 .../nacos/naming/misc/UtilsAndCommons.java    |  12 +-
 .../alibaba/nacos/naming/web/ApiCommands.java |  21 ++-
 .../nacos/naming/web/RaftCommands.java        |   9 +-
 6 files changed, 36 insertions(+), 149 deletions(-)

diff --git a/common/src/main/java/com/alibaba/nacos/common/util/IoUtils.java b/common/src/main/java/com/alibaba/nacos/common/util/IoUtils.java
index 33356073b..293d66ca6 100644
--- a/common/src/main/java/com/alibaba/nacos/common/util/IoUtils.java
+++ b/common/src/main/java/com/alibaba/nacos/common/util/IoUtils.java
@@ -15,11 +15,9 @@
  */
 package com.alibaba.nacos.common.util;
 
-import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.io.IOUtils;
 
 import java.io.*;
-import java.util.ArrayList;
-import java.util.List;
 import java.util.zip.GZIPInputStream;
 
 /**
@@ -29,120 +27,6 @@ import java.util.zip.GZIPInputStream;
  */
 public class IoUtils {
 
-    static public String toString(InputStream input, String encoding) throws IOException {
-        return (null == encoding) ? toString(new InputStreamReader(input, "UTF-8"))
-                : toString(new InputStreamReader(input, encoding));
-    }
-
-    static public String toString(Reader reader) throws IOException {
-        CharArrayWriter sw = new CharArrayWriter();
-        copy(reader, sw);
-        return sw.toString();
-    }
-
-
-    static public long copy(Reader input, Writer output) throws IOException {
-        char[] buffer = new char[1 << 12];
-        long count = 0;
-        for (int n = 0; (n = input.read(buffer)) >= 0; ) {
-            output.write(buffer, 0, n);
-            count += n;
-        }
-        return count;
-    }
-
-    static public long copy(InputStream input, OutputStream output) throws IOException {
-        byte[] buffer = new byte[1024];
-        int bytesRead;
-        int totalBytes = 0;
-        while ((bytesRead = input.read(buffer)) != -1) {
-            output.write(buffer, 0, bytesRead);
-
-            totalBytes += bytesRead;
-        }
-
-        return totalBytes;
-    }
-
-    static public List readLines(Reader input) throws IOException {
-        BufferedReader reader = toBufferedReader(input);
-        List list = new ArrayList();
-        String line = null;
-        for (; ; ) {
-            line = reader.readLine();
-            if (null != line) {
-                if (StringUtils.isNotEmpty(line)) {
-                    list.add(line.trim());
-                }
-            } else {
-                break;
-            }
-        }
-        return list;
-    }
-
-    static private BufferedReader toBufferedReader(Reader reader) {
-        return reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(
-                reader);
-    }
-
-
-    public static boolean delete(File fileOrDir) throws IOException {
-        if (fileOrDir == null) {
-            return false;
-        }
-
-        if (fileOrDir.isDirectory()) {
-            cleanDirectory(fileOrDir);
-        }
-
-        return fileOrDir.delete();
-    }
-
-    public static void cleanDirectory(File directory) throws IOException {
-        if (!directory.exists()) {
-            String message = directory + " does not exist";
-            throw new IllegalArgumentException(message);
-        }
-
-        if (!directory.isDirectory()) {
-            String message = directory + " is not a directory";
-            throw new IllegalArgumentException(message);
-        }
-
-        File[] files = directory.listFiles();
-        if (files == null) {
-            throw new IOException("Failed to list contents of " + directory);
-        }
-
-        IOException exception = null;
-        for (File file : files) {
-            try {
-                delete(file);
-            } catch (IOException ioe) {
-                exception = ioe;
-            }
-        }
-
-        if (null != exception) {
-            throw exception;
-        }
-    }
-
-    public static void writeStringToFile(File file, String data, String encoding)
-            throws IOException {
-        OutputStream os = null;
-        try {
-            os = new FileOutputStream(file);
-            os.write(data.getBytes(encoding));
-            os.flush();
-        } finally {
-            if (null != os) {
-                os.close();
-            }
-        }
-    }
-
     public static byte[] tryDecompress(InputStream raw) throws Exception {
 
         try {
@@ -151,8 +35,7 @@ public class IoUtils {
             ByteArrayOutputStream out
                     = new ByteArrayOutputStream();
 
-
-            IoUtils.copy(gis, out);
+            IOUtils.copy(gis, out);
 
             return out.toByteArray();
         } catch (Exception e) {
diff --git a/naming/src/main/java/com/alibaba/nacos/naming/misc/HttpClient.java b/naming/src/main/java/com/alibaba/nacos/naming/misc/HttpClient.java
index 4d9170168..f4edfe086 100644
--- a/naming/src/main/java/com/alibaba/nacos/naming/misc/HttpClient.java
+++ b/naming/src/main/java/com/alibaba/nacos/naming/misc/HttpClient.java
@@ -22,6 +22,7 @@ import com.ning.http.client.AsyncHttpClientConfig;
 import com.ning.http.client.FluentStringsMap;
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.collections.MapUtils;
+import org.apache.commons.io.IOUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.http.*;
 import org.apache.http.client.config.RequestConfig;
@@ -261,7 +262,7 @@ public class HttpClient {
                 }
             }
 
-            return new HttpResult(response.getStatusLine().getStatusCode(), IoUtils.toString(entity.getContent(), charset), Collections.emptyMap());
+            return new HttpResult(response.getStatusLine().getStatusCode(), IOUtils.toString(entity.getContent(), charset), Collections.emptyMap());
         } catch (Throwable e) {
             return new HttpResult(500, e.toString(), Collections.emptyMap());
         }
@@ -288,7 +289,7 @@ public class HttpClient {
             String charset = headerElements[0].getParameterByName("charset").getValue();
 
             return new HttpResult(response.getStatusLine().getStatusCode(),
-                    IoUtils.toString(entity.getContent(), charset), Collections.emptyMap());
+                    IOUtils.toString(entity.getContent(), charset), Collections.emptyMap());
         } catch (Exception e) {
             return new HttpResult(500, e.toString(), Collections.emptyMap());
         }
@@ -315,7 +316,7 @@ public class HttpClient {
             inputStream = new GZIPInputStream(inputStream);
         }
 
-        HttpResult result = new HttpResult(respCode, IoUtils.toString(inputStream, getCharset(conn)), respHeaders);
+        HttpResult result = new HttpResult(respCode, IOUtils.toString(inputStream, getCharset(conn)), respHeaders);
         inputStream.close();
 
         return result;
@@ -324,15 +325,15 @@ public class HttpClient {
     private static String getCharset(HttpURLConnection conn) {
         String contentType = conn.getContentType();
         if (StringUtils.isEmpty(contentType)) {
-            return "utf-8";
+            return "UTF-8";
         }
 
         String[] values = contentType.split(";");
         if (values.length == 0) {
-            return "utf-8";
+            return "UTF-8";
         }
 
-        String charset = "utf-8";
+        String charset = "UTF-8";
         for (String value : values) {
             value = value.trim();
 
diff --git a/naming/src/main/java/com/alibaba/nacos/naming/misc/NamingProxy.java b/naming/src/main/java/com/alibaba/nacos/naming/misc/NamingProxy.java
index ac1ed7ca7..55ac393e9 100644
--- a/naming/src/main/java/com/alibaba/nacos/naming/misc/NamingProxy.java
+++ b/naming/src/main/java/com/alibaba/nacos/naming/misc/NamingProxy.java
@@ -15,15 +15,14 @@
  */
 package com.alibaba.nacos.naming.misc;
 
-import com.alibaba.nacos.common.util.IoUtils;
 import com.alibaba.nacos.common.util.SystemUtil;
 import com.alibaba.nacos.naming.boot.RunningConfig;
 import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.io.FileUtils;
 import org.apache.commons.lang3.StringUtils;
 
-import java.io.FileInputStream;
+import java.io.File;
 import java.io.IOException;
-import java.io.InputStreamReader;
 import java.net.HttpURLConnection;
 import java.net.InetAddress;
 import java.util.ArrayList;
@@ -157,9 +156,9 @@ public class NamingProxy {
         List result = new ArrayList<>();
         // read nacos config if necessary.
         try {
-            result = IoUtils.readLines(new InputStreamReader(new FileInputStream(UtilsAndCommons.getConfFile()), "UTF-8"));
+            result = FileUtils.readLines(UtilsAndCommons.getConfFile(), "UTF-8");
         } catch (Exception e) {
-            Loggers.SRV_LOG.warn("failed to get config: " + UtilsAndCommons.getConfFile(), e);
+            Loggers.SRV_LOG.warn("failed to get config: " + UtilsAndCommons.getConfFilePath(), e);
         }
 
         Loggers.DEBUG_LOG.debug("REFRESH-SERVER-LIST1", result);
diff --git a/naming/src/main/java/com/alibaba/nacos/naming/misc/UtilsAndCommons.java b/naming/src/main/java/com/alibaba/nacos/naming/misc/UtilsAndCommons.java
index 89797bb0e..f0b4b3b70 100644
--- a/naming/src/main/java/com/alibaba/nacos/naming/misc/UtilsAndCommons.java
+++ b/naming/src/main/java/com/alibaba/nacos/naming/misc/UtilsAndCommons.java
@@ -37,7 +37,7 @@ public class UtilsAndCommons {
 
     private static final String NACOS_CONF_FILE_NAME = "cluster.conf";
 
-    private static String NACOS_CONF_FILE = NACOS_CONF_DIR_PATH + File.separator + NACOS_CONF_FILE_NAME;
+    private static String NACOS_CONF_FILE_PATH = NACOS_CONF_DIR_PATH + File.separator + NACOS_CONF_FILE_NAME;
 
     public static final String NACOS_SERVER_CONTEXT = "/nacos";
 
@@ -127,7 +127,7 @@ public class UtilsAndCommons {
         String nacosHome = System.getProperty("nacos.home");
 
         if (StringUtils.isNotBlank(nacosHome)) {
-            NACOS_CONF_FILE = nacosHome + File.separator + "conf" + File.separator + NACOS_CONF_FILE_NAME;
+            NACOS_CONF_FILE_PATH = nacosHome + File.separator + "conf" + File.separator + NACOS_CONF_FILE_NAME;
         }
 
         DOMAIN_SYNCHRONIZATION_EXECUTOR
@@ -188,8 +188,12 @@ public class UtilsAndCommons {
         return strBuilder.toString();
     }
 
-    public static String getConfFile() {
-        return NACOS_CONF_FILE;
+    public static String getConfFilePath() {
+        return NACOS_CONF_FILE_PATH;
+    }
+
+    public static File getConfFile() {
+        return new File(getConfFilePath());
     }
 
 
diff --git a/naming/src/main/java/com/alibaba/nacos/naming/web/ApiCommands.java b/naming/src/main/java/com/alibaba/nacos/naming/web/ApiCommands.java
index 61b2d1839..57e637426 100644
--- a/naming/src/main/java/com/alibaba/nacos/naming/web/ApiCommands.java
+++ b/naming/src/main/java/com/alibaba/nacos/naming/web/ApiCommands.java
@@ -39,6 +39,7 @@ import com.ning.http.client.Response;
 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
 import org.apache.catalina.util.ParameterMap;
 import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.io.FileUtils;
 import org.apache.commons.lang3.ArrayUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.commons.lang3.math.NumberUtils;
@@ -57,7 +58,8 @@ import java.security.AccessControlException;
 import java.security.InvalidParameterException;
 import java.text.SimpleDateFormat;
 import java.util.*;
-import java.util.concurrent.*;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
 import java.util.concurrent.locks.Lock;
 import java.util.concurrent.locks.ReentrantLock;
 
@@ -340,7 +342,7 @@ public class ApiCommands {
 
         String dom = BaseServlet.required(request, "dom");
         String owners = BaseServlet.optional(request, "owners", StringUtils.EMPTY);
-        String token = BaseServlet.optional(request, "token", Md5Utils.getMD5(dom, "utf-8"));
+        String token = BaseServlet.optional(request, "token", Md5Utils.getMD5(dom, "UTF-8"));
 
         float protectThreshold = NumberUtils.toFloat(BaseServlet.optional(request, "protectThreshold", "0.0"));
         boolean isUseSpecifiedURL = Boolean.parseBoolean(BaseServlet.optional(request, "isUseSpecifiedURL", "false"));
@@ -2019,8 +2021,7 @@ public class ApiCommands {
 
         if (SwitchEntry.ACTION_ADD.equals(action)) {
 
-            List oldList =
-                    IoUtils.readLines(new InputStreamReader(new FileInputStream(UtilsAndCommons.getConfFile()), "UTF-8"));
+            List oldList = FileUtils.readLines(UtilsAndCommons.getConfFile(), "UTF-8");
             StringBuilder sb = new StringBuilder();
             for (String ip : oldList) {
                 sb.append(ip).append("\r\n");
@@ -2030,7 +2031,7 @@ public class ApiCommands {
             }
 
             Loggers.SRV_LOG.info("UPDATE-CLUSTER", "new ips:" + sb.toString());
-            IoUtils.writeStringToFile(new File(UtilsAndCommons.getConfFile()), sb.toString(), "utf-8");
+            FileUtils.writeStringToFile(UtilsAndCommons.getConfFile(), sb.toString(), "UTF-8");
             return result;
         }
 
@@ -2041,7 +2042,7 @@ public class ApiCommands {
                 sb.append(ip).append("\r\n");
             }
             Loggers.SRV_LOG.info("UPDATE-CLUSTER", "new ips:" + sb.toString());
-            IoUtils.writeStringToFile(new File(UtilsAndCommons.getConfFile()), sb.toString(), "utf-8");
+            FileUtils.writeStringToFile(UtilsAndCommons.getConfFile(), sb.toString(), "UTF-8");
             return result;
         }
 
@@ -2052,8 +2053,7 @@ public class ApiCommands {
                 removeIps.add(ip);
             }
 
-            List oldList =
-                    IoUtils.readLines(new InputStreamReader(new FileInputStream(UtilsAndCommons.getConfFile()), "utf-8"));
+            List oldList = FileUtils.readLines(UtilsAndCommons.getConfFile(), "UTF-8");
 
             Iterator iterator = oldList.iterator();
 
@@ -2070,15 +2070,14 @@ public class ApiCommands {
                 sb.append(ip).append("\r\n");
             }
 
-            IoUtils.writeStringToFile(new File(UtilsAndCommons.getConfFile()), sb.toString(), "utf-8");
+            FileUtils.writeStringToFile(UtilsAndCommons.getConfFile(), sb.toString(), "UTF-8");
 
             return result;
         }
 
         if (SwitchEntry.ACTION_VIEW.equals(action)) {
 
-            List oldList =
-                    IoUtils.readLines(new InputStreamReader(new FileInputStream(UtilsAndCommons.getConfFile()), "utf-8"));
+            List oldList = FileUtils.readLines(UtilsAndCommons.getConfFile(), "UTF-8");
             result.put("list", oldList);
 
             return result;
diff --git a/naming/src/main/java/com/alibaba/nacos/naming/web/RaftCommands.java b/naming/src/main/java/com/alibaba/nacos/naming/web/RaftCommands.java
index d09715cf0..c504f98c2 100644
--- a/naming/src/main/java/com/alibaba/nacos/naming/web/RaftCommands.java
+++ b/naming/src/main/java/com/alibaba/nacos/naming/web/RaftCommands.java
@@ -24,6 +24,7 @@ import com.alibaba.nacos.naming.core.VirtualClusterDomain;
 import com.alibaba.nacos.naming.misc.NetUtils;
 import com.alibaba.nacos.naming.misc.UtilsAndCommons;
 import com.alibaba.nacos.naming.raft.*;
+import org.apache.commons.io.IOUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.RequestMapping;
@@ -107,7 +108,7 @@ public class RaftCommands {
         response.setHeader("Cache-Control", "no-cache");
         response.setHeader("Content-Encode", "gzip");
 
-        String entity = IoUtils.toString(request.getInputStream(), "UTF-8");
+        String entity = IOUtils.toString(request.getInputStream(), "UTF-8");
 
         String value = Arrays.asList(entity).toArray(new String[1])[0];
         JSONObject json = JSON.parseObject(value);
@@ -125,7 +126,7 @@ public class RaftCommands {
         response.setHeader("Cache-Control", "no-cache");
         response.setHeader("Content-Encode", "gzip");
 
-        String entity = IoUtils.toString(request.getInputStream(), "UTF-8");
+        String entity = IOUtils.toString(request.getInputStream(), "UTF-8");
 
         String value = Arrays.asList(entity).toArray(new String[1])[0];
         JSONObject json = JSON.parseObject(value);
@@ -186,7 +187,7 @@ public class RaftCommands {
         response.setHeader("Cache-Control", "no-cache");
         response.setHeader("Content-Encode", "gzip");
 
-        String entity = IoUtils.toString(request.getInputStream(), "UTF-8");
+        String entity = IOUtils.toString(request.getInputStream(), "UTF-8");
 
         String value = Arrays.asList(entity).toArray(new String[1])[0];
         JSONObject jsonObject = JSON.parseObject(value);
@@ -202,7 +203,7 @@ public class RaftCommands {
         response.setHeader("Cache-Control", "no-cache");
         response.setHeader("Content-Encode", "gzip");
 
-        String entity = IoUtils.toString(request.getInputStream(), "UTF-8");
+        String entity = IOUtils.toString(request.getInputStream(), "UTF-8");
 
         String value = Arrays.asList(entity).toArray(new String[1])[0];
         RaftCore.onDelete(JSON.parseObject(value));

From 83f536b27de4e5a21e7df6e267b2d91ac5c1a3b7 Mon Sep 17 00:00:00 2001
From: mercyblitz 
Date: Mon, 1 Oct 2018 11:43:48 +0800
Subject: [PATCH 11/30] Polish alibaba/nacos#102

---
 config/pom.xml                                |   4 +-
 .../alibaba/nacos/config/server/Config.java   |   6 +-
 .../aspect/CapacityManagementAspect.java      |  24 +-
 .../server/aspect/RequestLogAspect.java       |  13 +-
 .../server/controller/CapacityController.java |  13 +-
 .../controller/CommunicationController.java   |  22 +-
 .../server/controller/ConfigController.java   |  54 +-
 .../server/controller/ConfigServletInner.java |  40 +-
 .../server/controller/HealthController.java   |  13 +-
 .../server/controller/HistoryController.java  |  15 +-
 .../server/controller/ListenerController.java |  26 +-
 .../server/controller/OpsController.java      |  11 +-
 .../exception/GlobalExceptionHandler.java     |   7 +-
 .../nacos/config/server/filter/WebFilter.java |  14 +-
 .../config/server/manager/TaskManager.java    |  10 +-
 .../nacos/config/server/model/CacheItem.java  |   6 +-
 .../config/server/model/ConfigInfoBase.java   |   4 +-
 .../config/server/monitor/MemoryMonitor.java  |  12 +-
 .../config/server/service/AggrWhitelist.java  |  13 +-
 .../service/BasicDataSourceServiceImpl.java   | 501 +++++++++---------
 .../server/service/ClientIpWhiteList.java     |  11 +-
 .../server/service/ClientTrackService.java    |   4 +-
 .../server/service/ConfigDataChangeEvent.java |   3 +-
 .../config/server/service/ConfigService.java  |  32 +-
 .../server/service/ConfigSubService.java      |  36 +-
 .../nacos/config/server/service/DiskUtil.java |  19 +-
 .../server/service/LocalDataChangeEvent.java  |   4 +-
 .../service/LocalDataSourceServiceImpl.java   |  30 +-
 .../server/service/LongPollingService.java    |  39 +-
 .../config/server/service/PersistService.java |  55 +-
 .../server/service/ServerListService.java     |  59 +--
 .../config/server/service/SwitchService.java  |  11 +-
 .../service/capacity/CapacityService.java     |   5 +-
 .../capacity/GroupCapacityPersistService.java |   9 +-
 .../TenantCapacityPersistService.java         |   9 +-
 .../server/service/dump/DumpService.java      |  17 +-
 .../config/server/service/dump/DumpTask.java  |  16 +-
 .../service/merge/MergeDatumService.java      |  19 +-
 .../service/merge/MergeTaskProcessor.java     |   3 +-
 .../service/notify/AsyncNotifyService.java    |  39 +-
 .../server/service/notify/NotifyService.java  |  16 +-
 .../service/notify/NotifySingleService.java   |  19 +-
 .../service/notify/NotifyTaskProcessor.java   |  15 +-
 .../service/trace/ConfigTraceService.java     |   3 +-
 .../config/server/utils/ContentUtils.java     |   4 +-
 .../nacos/config/server/utils/JSONUtils.java  |   6 +-
 .../nacos/config/server/utils/LogUtil.java    |   4 +-
 .../nacos/config/server/utils/MD5.java        |   4 +-
 .../nacos/config/server/utils/MD5Util.java    |  23 +-
 .../config/server/utils/PaginationHelper.java |   5 +-
 .../nacos/config/server/utils/ParamUtils.java |   7 +-
 .../config/server/utils/PropertyUtil.java     |   4 +-
 .../config/server/utils/RegexParser.java      |   8 +-
 .../config/server/utils/ResourceUtils.java    |  10 +-
 .../config/server/utils/ResponseUtil.java     |   6 +-
 .../server/utils/RunningConfigUtils.java      |   4 +-
 .../config/server/utils/SystemConfig.java     |   8 +-
 .../nacos/config/server/utils/TimeUtils.java  |   3 +-
 .../config/server/utils/UrlAnalysisUtils.java |   4 +-
 .../server/utils/event/EventDispatcher.java   |   6 +-
 pom.xml                                       |   5 -
 61 files changed, 610 insertions(+), 782 deletions(-)

diff --git a/config/pom.xml b/config/pom.xml
index 0c974c098..a691842c8 100644
--- a/config/pom.xml
+++ b/config/pom.xml
@@ -60,8 +60,8 @@
             commons-io
         
         
-            commons-lang
-            commons-lang
+            org.apache.commons
+            commons-lang3
         
         
             mysql
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/Config.java b/config/src/main/java/com/alibaba/nacos/config/server/Config.java
index 01c9d5134..229c17296 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/Config.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/Config.java
@@ -15,13 +15,11 @@
  */
 package com.alibaba.nacos.config.server;
 
-import java.net.UnknownHostException;
-
 import org.springframework.boot.SpringApplication;
-import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
 import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
-import org.springframework.boot.web.servlet.ServletComponentScan;
+
+import java.net.UnknownHostException;
 
 /**
  * Config main
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/aspect/CapacityManagementAspect.java b/config/src/main/java/com/alibaba/nacos/config/server/aspect/CapacityManagementAspect.java
index 793765461..1fe35a006 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/aspect/CapacityManagementAspect.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/aspect/CapacityManagementAspect.java
@@ -15,19 +15,6 @@
  */
 package com.alibaba.nacos.config.server.aspect;
 
-import java.nio.charset.Charset;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.commons.lang.StringUtils;
-import org.aspectj.lang.ProceedingJoinPoint;
-import org.aspectj.lang.annotation.Around;
-import org.aspectj.lang.annotation.Aspect;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-
 import com.alibaba.nacos.config.server.constant.Constants;
 import com.alibaba.nacos.config.server.constant.CounterMode;
 import com.alibaba.nacos.config.server.model.ConfigInfo;
@@ -35,6 +22,17 @@ import com.alibaba.nacos.config.server.model.capacity.Capacity;
 import com.alibaba.nacos.config.server.service.PersistService;
 import com.alibaba.nacos.config.server.service.capacity.CapacityService;
 import com.alibaba.nacos.config.server.utils.PropertyUtil;
+import org.apache.commons.lang3.StringUtils;
+import org.aspectj.lang.ProceedingJoinPoint;
+import org.aspectj.lang.annotation.Around;
+import org.aspectj.lang.annotation.Aspect;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.nio.charset.Charset;
 
 /**
  * 容量管理切面:批量写入、更新暂不处理
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/aspect/RequestLogAspect.java b/config/src/main/java/com/alibaba/nacos/config/server/aspect/RequestLogAspect.java
index eb21966d8..56d0c28fa 100755
--- a/config/src/main/java/com/alibaba/nacos/config/server/aspect/RequestLogAspect.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/aspect/RequestLogAspect.java
@@ -15,18 +15,17 @@
  */
 package com.alibaba.nacos.config.server.aspect;
 
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.aspectj.lang.ProceedingJoinPoint;
-import org.aspectj.lang.annotation.Around;
-import org.aspectj.lang.annotation.Aspect;
-
 import com.alibaba.nacos.config.server.service.ConfigService;
 import com.alibaba.nacos.config.server.utils.GroupKey2;
 import com.alibaba.nacos.config.server.utils.LogUtil;
 import com.alibaba.nacos.config.server.utils.MD5;
 import com.alibaba.nacos.config.server.utils.RequestUtil;
+import org.aspectj.lang.ProceedingJoinPoint;
+import org.aspectj.lang.annotation.Around;
+import org.aspectj.lang.annotation.Aspect;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
 
 /**
  * * Created with IntelliJ IDEA. User: dingjoey Date: 13-12-12 Time: 21:12
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/controller/CapacityController.java b/config/src/main/java/com/alibaba/nacos/config/server/controller/CapacityController.java
index 1c52b6c10..850108514 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/controller/CapacityController.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/controller/CapacityController.java
@@ -15,9 +15,11 @@
  */
 package com.alibaba.nacos.config.server.controller;
 
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.commons.lang.StringUtils;
+import com.alibaba.nacos.config.server.constant.Constants;
+import com.alibaba.nacos.config.server.model.RestResult;
+import com.alibaba.nacos.config.server.model.capacity.Capacity;
+import com.alibaba.nacos.config.server.service.capacity.CapacityService;
+import org.apache.commons.lang3.StringUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -27,10 +29,7 @@ import org.springframework.web.bind.annotation.RequestMethod;
 import org.springframework.web.bind.annotation.RequestParam;
 import org.springframework.web.bind.annotation.ResponseBody;
 
-import com.alibaba.nacos.config.server.constant.Constants;
-import com.alibaba.nacos.config.server.model.RestResult;
-import com.alibaba.nacos.config.server.model.capacity.Capacity;
-import com.alibaba.nacos.config.server.service.capacity.CapacityService;
+import javax.servlet.http.HttpServletResponse;
 
 /**
  * capcity manage
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/controller/CommunicationController.java b/config/src/main/java/com/alibaba/nacos/config/server/controller/CommunicationController.java
index 2f7197370..1b38f06e7 100755
--- a/config/src/main/java/com/alibaba/nacos/config/server/controller/CommunicationController.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/controller/CommunicationController.java
@@ -15,13 +15,12 @@
  */
 package com.alibaba.nacos.config.server.controller;
 
-import java.io.IOException;
-
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.commons.lang.StringUtils;
+import com.alibaba.nacos.config.server.constant.Constants;
+import com.alibaba.nacos.config.server.model.SampleResult;
+import com.alibaba.nacos.config.server.service.LongPollingService;
+import com.alibaba.nacos.config.server.service.dump.DumpService;
+import com.alibaba.nacos.config.server.service.notify.NotifyService;
+import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Controller;
 import org.springframework.ui.ModelMap;
@@ -30,11 +29,10 @@ import org.springframework.web.bind.annotation.RequestMethod;
 import org.springframework.web.bind.annotation.RequestParam;
 import org.springframework.web.bind.annotation.ResponseBody;
 
-import com.alibaba.nacos.config.server.constant.Constants;
-import com.alibaba.nacos.config.server.model.SampleResult;
-import com.alibaba.nacos.config.server.service.LongPollingService;
-import com.alibaba.nacos.config.server.service.dump.DumpService;
-import com.alibaba.nacos.config.server.service.notify.NotifyService;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
 
 
 /**
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigController.java b/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigController.java
index 922ea7db4..64c250043 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigController.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigController.java
@@ -15,16 +15,18 @@
  */
 package com.alibaba.nacos.config.server.controller;
 
-import java.io.IOException;
-import java.net.URLDecoder;
-import java.sql.Timestamp;
-import java.util.HashMap;
-import java.util.Map;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import org.apache.commons.lang.StringUtils;
+import com.alibaba.nacos.config.server.constant.Constants;
+import com.alibaba.nacos.config.server.exception.NacosException;
+import com.alibaba.nacos.config.server.model.*;
+import com.alibaba.nacos.config.server.service.AggrWhitelist;
+import com.alibaba.nacos.config.server.service.ConfigDataChangeEvent;
+import com.alibaba.nacos.config.server.service.ConfigSubService;
+import com.alibaba.nacos.config.server.service.PersistService;
+import com.alibaba.nacos.config.server.service.merge.MergeDatumService;
+import com.alibaba.nacos.config.server.service.trace.ConfigTraceService;
+import com.alibaba.nacos.config.server.utils.*;
+import com.alibaba.nacos.config.server.utils.event.EventDispatcher;
+import org.apache.commons.lang3.StringUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -34,28 +36,16 @@ import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMethod;
 import org.springframework.web.bind.annotation.RequestParam;
 import org.springframework.web.bind.annotation.ResponseBody;
-import com.alibaba.nacos.config.server.constant.Constants;
-import com.alibaba.nacos.config.server.exception.NacosException;
-import com.alibaba.nacos.config.server.model.ConfigAdvanceInfo;
-import com.alibaba.nacos.config.server.model.ConfigAllInfo;
-import com.alibaba.nacos.config.server.model.ConfigInfo;
-import com.alibaba.nacos.config.server.model.ConfigInfo4Beta;
-import com.alibaba.nacos.config.server.model.GroupkeyListenserStatus;
-import com.alibaba.nacos.config.server.model.Page;
-import com.alibaba.nacos.config.server.model.RestResult;
-import com.alibaba.nacos.config.server.model.SampleResult;
-import com.alibaba.nacos.config.server.service.AggrWhitelist;
-import com.alibaba.nacos.config.server.service.ConfigDataChangeEvent;
-import com.alibaba.nacos.config.server.service.ConfigSubService;
-import com.alibaba.nacos.config.server.service.PersistService;
-import com.alibaba.nacos.config.server.service.merge.MergeDatumService;
-import com.alibaba.nacos.config.server.service.trace.ConfigTraceService;
-import com.alibaba.nacos.config.server.utils.MD5Util;
-import com.alibaba.nacos.config.server.utils.ParamUtils;
-import com.alibaba.nacos.config.server.utils.RequestUtil;
-import com.alibaba.nacos.config.server.utils.SystemConfig;
-import com.alibaba.nacos.config.server.utils.TimeUtils;
-import com.alibaba.nacos.config.server.utils.event.EventDispatcher;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.net.URLDecoder;
+import java.sql.Timestamp;
+import java.util.HashMap;
+import java.util.Map;
 
 /**
  * 软负载客户端发布数据专用控制器
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigServletInner.java b/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigServletInner.java
index cc7cae477..1d4782bd0 100755
--- a/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigServletInner.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigServletInner.java
@@ -15,8 +15,22 @@
  */
 package com.alibaba.nacos.config.server.controller;
 
-import static com.alibaba.nacos.config.server.utils.LogUtil.pullLog;
+import com.alibaba.nacos.config.server.constant.Constants;
+import com.alibaba.nacos.config.server.model.CacheItem;
+import com.alibaba.nacos.config.server.model.ConfigInfoBase;
+import com.alibaba.nacos.config.server.service.ConfigService;
+import com.alibaba.nacos.config.server.service.DiskUtil;
+import com.alibaba.nacos.config.server.service.LongPollingService;
+import com.alibaba.nacos.config.server.service.PersistService;
+import com.alibaba.nacos.config.server.service.trace.ConfigTraceService;
+import com.alibaba.nacos.config.server.utils.*;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
 
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.IOException;
@@ -27,29 +41,7 @@ import java.nio.charset.StandardCharsets;
 import java.util.List;
 import java.util.Map;
 
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.commons.lang.StringUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-
-import com.alibaba.nacos.config.server.constant.Constants;
-import com.alibaba.nacos.config.server.model.CacheItem;
-import com.alibaba.nacos.config.server.model.ConfigInfoBase;
-import com.alibaba.nacos.config.server.service.ConfigService;
-import com.alibaba.nacos.config.server.service.DiskUtil;
-import com.alibaba.nacos.config.server.service.LongPollingService;
-import com.alibaba.nacos.config.server.service.PersistService;
-import com.alibaba.nacos.config.server.service.trace.ConfigTraceService;
-import com.alibaba.nacos.config.server.utils.GroupKey2;
-import com.alibaba.nacos.config.server.utils.LogUtil;
-import com.alibaba.nacos.config.server.utils.MD5Util;
-import com.alibaba.nacos.config.server.utils.PropertyUtil;
-import com.alibaba.nacos.config.server.utils.Protocol;
-import com.alibaba.nacos.config.server.utils.RequestUtil;
-import com.alibaba.nacos.config.server.utils.TimeUtils;
+import static com.alibaba.nacos.config.server.utils.LogUtil.pullLog;
 
 /**
  * ConfigServlet inner for aop
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/controller/HealthController.java b/config/src/main/java/com/alibaba/nacos/config/server/controller/HealthController.java
index 68a2f1b01..aa2ee407a 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/controller/HealthController.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/controller/HealthController.java
@@ -15,17 +15,18 @@
  */
 package com.alibaba.nacos.config.server.controller;
 
-import javax.annotation.PostConstruct;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.ResponseBody;
 import com.alibaba.nacos.config.server.constant.Constants;
 import com.alibaba.nacos.config.server.service.DataSourceService;
 import com.alibaba.nacos.config.server.service.DynamicDataSource;
 import com.alibaba.nacos.config.server.service.ServerListService;
 import com.alibaba.nacos.config.server.utils.SystemConfig;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.ResponseBody;
+
+import javax.annotation.PostConstruct;
 
 /**
  * health service
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/controller/HistoryController.java b/config/src/main/java/com/alibaba/nacos/config/server/controller/HistoryController.java
index 50cd17b26..6a3b66a02 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/controller/HistoryController.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/controller/HistoryController.java
@@ -15,10 +15,11 @@
  */
 package com.alibaba.nacos.config.server.controller;
 
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.commons.lang.StringUtils;
+import com.alibaba.nacos.config.server.constant.Constants;
+import com.alibaba.nacos.config.server.model.ConfigHistoryInfo;
+import com.alibaba.nacos.config.server.model.Page;
+import com.alibaba.nacos.config.server.service.PersistService;
+import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Controller;
 import org.springframework.ui.ModelMap;
@@ -27,10 +28,8 @@ import org.springframework.web.bind.annotation.RequestMethod;
 import org.springframework.web.bind.annotation.RequestParam;
 import org.springframework.web.bind.annotation.ResponseBody;
 
-import com.alibaba.nacos.config.server.constant.Constants;
-import com.alibaba.nacos.config.server.model.ConfigHistoryInfo;
-import com.alibaba.nacos.config.server.model.Page;
-import com.alibaba.nacos.config.server.service.PersistService;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
 
 /**
  * 管理控制器。 
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/controller/ListenerController.java b/config/src/main/java/com/alibaba/nacos/config/server/controller/ListenerController.java
index 9a8a08644..93dc8253e 100755
--- a/config/src/main/java/com/alibaba/nacos/config/server/controller/ListenerController.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/controller/ListenerController.java
@@ -15,15 +15,12 @@
  */
 package com.alibaba.nacos.config.server.controller;
 
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.commons.lang.StringUtils;
+import com.alibaba.nacos.config.server.constant.Constants;
+import com.alibaba.nacos.config.server.model.GroupkeyListenserStatus;
+import com.alibaba.nacos.config.server.model.SampleResult;
+import com.alibaba.nacos.config.server.service.ConfigSubService;
+import com.alibaba.nacos.config.server.utils.GroupKey2;
+import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Controller;
 import org.springframework.ui.ModelMap;
@@ -32,11 +29,12 @@ import org.springframework.web.bind.annotation.RequestMethod;
 import org.springframework.web.bind.annotation.RequestParam;
 import org.springframework.web.bind.annotation.ResponseBody;
 
-import com.alibaba.nacos.config.server.constant.Constants;
-import com.alibaba.nacos.config.server.model.GroupkeyListenserStatus;
-import com.alibaba.nacos.config.server.model.SampleResult;
-import com.alibaba.nacos.config.server.service.ConfigSubService;
-import com.alibaba.nacos.config.server.utils.GroupKey2;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
 
 /**
  * Config longpulling
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/controller/OpsController.java b/config/src/main/java/com/alibaba/nacos/config/server/controller/OpsController.java
index 56d4a0d57..827fe8ff3 100755
--- a/config/src/main/java/com/alibaba/nacos/config/server/controller/OpsController.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/controller/OpsController.java
@@ -15,9 +15,9 @@
  */
 package com.alibaba.nacos.config.server.controller;
 
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
+import com.alibaba.nacos.config.server.constant.Constants;
+import com.alibaba.nacos.config.server.service.PersistService;
+import com.alibaba.nacos.config.server.service.dump.DumpService;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -26,9 +26,8 @@ import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMethod;
 import org.springframework.web.bind.annotation.ResponseBody;
 
-import com.alibaba.nacos.config.server.constant.Constants;
-import com.alibaba.nacos.config.server.service.PersistService;
-import com.alibaba.nacos.config.server.service.dump.DumpService;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
 
 /**
  * 管理控制器。
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/exception/GlobalExceptionHandler.java b/config/src/main/java/com/alibaba/nacos/config/server/exception/GlobalExceptionHandler.java
index 52dce3509..a6b7144a8 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/exception/GlobalExceptionHandler.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/exception/GlobalExceptionHandler.java
@@ -15,13 +15,12 @@
  */
 package com.alibaba.nacos.config.server.exception;
 
-import java.io.IOException;
-
-import javax.servlet.http.HttpServletResponse;
-
 import org.springframework.web.bind.annotation.ControllerAdvice;
 import org.springframework.web.bind.annotation.ExceptionHandler;
 
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
 /**
  * global exception handler
  * 
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/filter/WebFilter.java b/config/src/main/java/com/alibaba/nacos/config/server/filter/WebFilter.java
index f27d9f335..60539714a 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/filter/WebFilter.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/filter/WebFilter.java
@@ -15,19 +15,13 @@
  */
 package com.alibaba.nacos.config.server.filter;
 
-import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog;
+import com.alibaba.nacos.config.server.constant.Constants;
+import org.springframework.core.annotation.Order;
 
+import javax.servlet.*;
 import java.io.IOException;
 
-import javax.servlet.Filter;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletContext;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import org.springframework.core.annotation.Order;
-import com.alibaba.nacos.config.server.constant.Constants;
+import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog;
 
 /**
  * encode filter
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/manager/TaskManager.java b/config/src/main/java/com/alibaba/nacos/config/server/manager/TaskManager.java
index 5042e4c39..a6366636d 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/manager/TaskManager.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/manager/TaskManager.java
@@ -15,6 +15,11 @@
  */
 package com.alibaba.nacos.config.server.manager;
 
+import com.alibaba.nacos.config.server.constant.Constants;
+import com.alibaba.nacos.config.server.utils.LogUtil;
+import org.slf4j.Logger;
+
+import javax.management.ObjectName;
 import java.lang.management.ManagementFactory;
 import java.util.Date;
 import java.util.Map;
@@ -23,11 +28,6 @@ import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.locks.Condition;
 import java.util.concurrent.locks.ReentrantLock;
-import javax.management.ObjectName;
-import org.slf4j.Logger;
-
-import com.alibaba.nacos.config.server.constant.Constants;
-import com.alibaba.nacos.config.server.utils.LogUtil;
 
 
 /**
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/model/CacheItem.java b/config/src/main/java/com/alibaba/nacos/config/server/model/CacheItem.java
index cc1c294a4..51800ad59 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/model/CacheItem.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/model/CacheItem.java
@@ -15,12 +15,12 @@
  */
 package com.alibaba.nacos.config.server.model;
 
-import java.util.List;
-import java.util.Map;
-
 import com.alibaba.nacos.config.server.constant.Constants;
 import com.alibaba.nacos.config.server.utils.SimpleReadWriteLock;
 import com.alibaba.nacos.config.server.utils.SingletonRepository.DataIdGroupIdCache;
+
+import java.util.List;
+import java.util.Map;
 /**
  * cache item
  * @author Nacos
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/model/ConfigInfoBase.java b/config/src/main/java/com/alibaba/nacos/config/server/model/ConfigInfoBase.java
index fdf519f5f..256cf1442 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/model/ConfigInfoBase.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/model/ConfigInfoBase.java
@@ -15,11 +15,11 @@
  */
 package com.alibaba.nacos.config.server.model;
 
+import com.alibaba.nacos.config.server.utils.MD5;
+
 import java.io.PrintWriter;
 import java.io.Serializable;
 
-import com.alibaba.nacos.config.server.utils.MD5;
-
 /**
  * 不能增加字段,为了兼容老前台接口(老接口增加一个字段会出现不兼容问题)设置的model。
  * 
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/monitor/MemoryMonitor.java b/config/src/main/java/com/alibaba/nacos/config/server/monitor/MemoryMonitor.java
index d9e5bf9c7..65d71ec96 100755
--- a/config/src/main/java/com/alibaba/nacos/config/server/monitor/MemoryMonitor.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/monitor/MemoryMonitor.java
@@ -15,15 +15,17 @@
  */
 package com.alibaba.nacos.config.server.monitor;
 
-import static com.alibaba.nacos.config.server.utils.LogUtil.memoryLog;
-import java.util.concurrent.ScheduledThreadPoolExecutor;
-import java.util.concurrent.TimeUnit;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
 import com.alibaba.nacos.config.server.service.ClientTrackService;
 import com.alibaba.nacos.config.server.service.ConfigService;
 import com.alibaba.nacos.config.server.service.TimerTaskService;
 import com.alibaba.nacos.config.server.service.notify.AsyncNotifyService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import java.util.concurrent.ScheduledThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+
+import static com.alibaba.nacos.config.server.utils.LogUtil.memoryLog;
 
 /**
  * Memory monitor
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/AggrWhitelist.java b/config/src/main/java/com/alibaba/nacos/config/server/service/AggrWhitelist.java
index 7b7f65ead..cc8869940 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/service/AggrWhitelist.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/service/AggrWhitelist.java
@@ -15,8 +15,10 @@
  */
 package com.alibaba.nacos.config.server.service;
 
-import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog;
-import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog;
+import com.alibaba.nacos.config.server.utils.RegexParser;
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.stereotype.Service;
 
 import java.io.StringReader;
 import java.util.ArrayList;
@@ -24,11 +26,8 @@ import java.util.List;
 import java.util.concurrent.atomic.AtomicReference;
 import java.util.regex.Pattern;
 
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.lang.StringUtils;
-import org.springframework.stereotype.Service;
-
-import com.alibaba.nacos.config.server.utils.RegexParser;
+import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog;
+import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog;
 
 
 /**
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/BasicDataSourceServiceImpl.java b/config/src/main/java/com/alibaba/nacos/config/server/service/BasicDataSourceServiceImpl.java
index 56025a2e1..f004580af 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/service/BasicDataSourceServiceImpl.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/service/BasicDataSourceServiceImpl.java
@@ -15,23 +15,10 @@
  */
 package com.alibaba.nacos.config.server.service;
 
-import static com.alibaba.nacos.config.server.service.PersistService.CONFIG_INFO4BETA_ROW_MAPPER;
-import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog;
-import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.TimeUnit;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import javax.annotation.PostConstruct;
-import javax.sql.DataSource;
-
+import com.alibaba.nacos.config.server.utils.PropertyUtil;
 import org.apache.commons.dbcp.BasicDataSource;
-import org.apache.commons.lang.StringUtils;
-import org.apache.commons.lang.math.NumberUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.math.NumberUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.core.env.Environment;
 import org.springframework.dao.DataAccessException;
@@ -41,291 +28,301 @@ import org.springframework.jdbc.datasource.DataSourceTransactionManager;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.support.TransactionTemplate;
 
-import com.alibaba.nacos.config.server.utils.PropertyUtil;
+import javax.annotation.PostConstruct;
+import javax.sql.DataSource;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import static com.alibaba.nacos.config.server.service.PersistService.CONFIG_INFO4BETA_ROW_MAPPER;
+import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog;
+import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog;
 
 /**
  * Base data source
- * @author Nacos
  *
+ * @author Nacos
  */
 @Service("basicDataSourceService")
 public class BasicDataSourceServiceImpl implements DataSourceService {
-	private static final String JDBC_DRIVER_NAME = "com.mysql.jdbc.Driver";
+    private static final String JDBC_DRIVER_NAME = "com.mysql.jdbc.Driver";
 
-	/**
-	 *  JDBC执行超时时间, 单位秒
-	 */
-	private int queryTimeout = 3;
+    /**
+     * JDBC执行超时时间, 单位秒
+     */
+    private int queryTimeout = 3;
 
-	private static final int TRANSACTION_QUERY_TIMEOUT = 5;
+    private static final int TRANSACTION_QUERY_TIMEOUT = 5;
 
-	private static final String DB_LOAD_ERROR_MSG = "[db-load-error]load jdbc.properties error";
+    private static final String DB_LOAD_ERROR_MSG = "[db-load-error]load jdbc.properties error";
 
-	private List dataSourceList = new ArrayList();
-	private JdbcTemplate jt;
-	private DataSourceTransactionManager tm;
-	private TransactionTemplate tjt;
+    private List dataSourceList = new ArrayList();
+    private JdbcTemplate jt;
+    private DataSourceTransactionManager tm;
+    private TransactionTemplate tjt;
 
-	private JdbcTemplate testMasterJT;
-	private JdbcTemplate testMasterWritableJT;
+    private JdbcTemplate testMasterJT;
+    private JdbcTemplate testMasterWritableJT;
 
-	volatile private List testJTList;
-	volatile private List isHealthList;
-	private volatile int masterIndex;
-	private static Pattern ipPattern = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");
+    volatile private List testJTList;
+    volatile private List isHealthList;
+    private volatile int masterIndex;
+    private static Pattern ipPattern = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");
 
-	@Autowired
-	private Environment env;
+    @Autowired
+    private Environment env;
 
-	@PostConstruct
-	public void init() {
-		queryTimeout = NumberUtils
-				.toInt(System.getProperty("QUERYTIMEOUT"), 3);
-		jt = new JdbcTemplate();
-		/**
-		 *  设置最大记录数,防止内存膨胀
-		 */
-		jt.setMaxRows(50000); 
-		jt.setQueryTimeout(queryTimeout);
+    @PostConstruct
+    public void init() {
+        queryTimeout = NumberUtils.toInt(System.getProperty("QUERYTIMEOUT"), 3);
+        jt = new JdbcTemplate();
+        /**
+         *  设置最大记录数,防止内存膨胀
+         */
+        jt.setMaxRows(50000);
+        jt.setQueryTimeout(queryTimeout);
 
-		testMasterJT = new JdbcTemplate();
-		testMasterJT.setQueryTimeout(queryTimeout);
+        testMasterJT = new JdbcTemplate();
+        testMasterJT.setQueryTimeout(queryTimeout);
 
-		testMasterWritableJT = new JdbcTemplate();
-		/**
-		 * 防止login接口因为主库不可用而rt太长
-		 */
-		testMasterWritableJT.setQueryTimeout(1);
-		/**
-		 * 数据库健康检测
-		 */
-		testJTList = new ArrayList();
-		isHealthList = new ArrayList();
+        testMasterWritableJT = new JdbcTemplate();
+        /**
+         * 防止login接口因为主库不可用而rt太长
+         */
+        testMasterWritableJT.setQueryTimeout(1);
+        /**
+         * 数据库健康检测
+         */
+        testJTList = new ArrayList();
+        isHealthList = new ArrayList();
 
-		tm = new DataSourceTransactionManager();
-		tjt = new TransactionTemplate(tm);
-		/**
-		 *  事务的超时时间需要与普通操作区分开
-		 */
-		tjt.setTimeout(TRANSACTION_QUERY_TIMEOUT);
-		if (!PropertyUtil.isStandaloneMode()) {
-			try {
-				reload();
-			} catch (IOException e) {
-				e.printStackTrace();
-				throw new RuntimeException(DB_LOAD_ERROR_MSG);
-			}
+        tm = new DataSourceTransactionManager();
+        tjt = new TransactionTemplate(tm);
+        /**
+         *  事务的超时时间需要与普通操作区分开
+         */
+        tjt.setTimeout(TRANSACTION_QUERY_TIMEOUT);
+        if (!PropertyUtil.isStandaloneMode()) {
+            try {
+                reload();
+            } catch (IOException e) {
+                e.printStackTrace();
+                throw new RuntimeException(DB_LOAD_ERROR_MSG);
+            }
 
-			TimerTaskService.scheduleWithFixedDelay(new SelectMasterTask(), 10, 10,
-					TimeUnit.SECONDS);
-			TimerTaskService.scheduleWithFixedDelay(new CheckDBHealthTask(), 10, 10,
-					TimeUnit.SECONDS);
-		}
-	}
+            TimerTaskService.scheduleWithFixedDelay(new SelectMasterTask(), 10, 10,
+                    TimeUnit.SECONDS);
+            TimerTaskService.scheduleWithFixedDelay(new CheckDBHealthTask(), 10, 10,
+                    TimeUnit.SECONDS);
+        }
+    }
 
-	public synchronized void reload() throws IOException {
-		List dblist = new ArrayList();
-		try {
-			String val = null;
-			val = env.getProperty("db.num");
-			if (null == val) {
-				throw new IllegalArgumentException("db.num is null");
-			}
-			int dbNum = Integer.parseInt(val.trim());
+    public synchronized void reload() throws IOException {
+        List dblist = new ArrayList();
+        try {
+            String val = null;
+            val = env.getProperty("db.num");
+            if (null == val) {
+                throw new IllegalArgumentException("db.num is null");
+            }
+            int dbNum = Integer.parseInt(val.trim());
 
-			for (int i = 0; i < dbNum; i++) {
-				BasicDataSource ds = new BasicDataSource();
-				ds.setDriverClassName(JDBC_DRIVER_NAME);
+            for (int i = 0; i < dbNum; i++) {
+                BasicDataSource ds = new BasicDataSource();
+                ds.setDriverClassName(JDBC_DRIVER_NAME);
 
-				val = env.getProperty("db.url." + i);
-				if (null == val) {
-					fatalLog.error("db.url." + i + " is null");
-					throw new IllegalArgumentException();
-				}
-				ds.setUrl(val.trim());
+                val = env.getProperty("db.url." + i);
+                if (null == val) {
+                    fatalLog.error("db.url." + i + " is null");
+                    throw new IllegalArgumentException();
+                }
+                ds.setUrl(val.trim());
 
-				val = env.getProperty("db.user");
-				if (null == val) {
-					fatalLog.error("db.user is null");
-					throw new IllegalArgumentException();
-				}
-				ds.setUsername(val.trim());
+                val = env.getProperty("db.user");
+                if (null == val) {
+                    fatalLog.error("db.user is null");
+                    throw new IllegalArgumentException();
+                }
+                ds.setUsername(val.trim());
 
-				val = env.getProperty("db.password");
-				if (null == val) {
-					fatalLog.error("db.password is null");
-					throw new IllegalArgumentException();
-				}
-				ds.setPassword(val.trim());
+                val = env.getProperty("db.password");
+                if (null == val) {
+                    fatalLog.error("db.password is null");
+                    throw new IllegalArgumentException();
+                }
+                ds.setPassword(val.trim());
 
-				val = env.getProperty("db.initialSize");
-				ds.setInitialSize(Integer.parseInt(defaultIfNull(val, "10")));
+                val = env.getProperty("db.initialSize");
+                ds.setInitialSize(Integer.parseInt(defaultIfNull(val, "10")));
 
-				val = env.getProperty("db.maxActive");
-				ds.setMaxActive(Integer.parseInt(defaultIfNull(val, "20")));
+                val = env.getProperty("db.maxActive");
+                ds.setMaxActive(Integer.parseInt(defaultIfNull(val, "20")));
 
-				val = env.getProperty("db.maxIdle");
-				ds.setMaxIdle(Integer.parseInt(defaultIfNull(val, "50")));
+                val = env.getProperty("db.maxIdle");
+                ds.setMaxIdle(Integer.parseInt(defaultIfNull(val, "50")));
 
-				ds.setMaxWait(3000L);
-				ds.setPoolPreparedStatements(true);
+                ds.setMaxWait(3000L);
+                ds.setPoolPreparedStatements(true);
 
-				// 每10分钟检查一遍连接池
-				ds.setTimeBetweenEvictionRunsMillis(TimeUnit.MINUTES
-						.toMillis(10L));
-				ds.setTestWhileIdle(true);
-				ds.setValidationQuery("SELECT 1 FROM dual");
+                // 每10分钟检查一遍连接池
+                ds.setTimeBetweenEvictionRunsMillis(TimeUnit.MINUTES
+                        .toMillis(10L));
+                ds.setTestWhileIdle(true);
+                ds.setValidationQuery("SELECT 1 FROM dual");
 
-				dblist.add(ds);
+                dblist.add(ds);
 
-				JdbcTemplate jdbcTemplate = new JdbcTemplate();
-				jdbcTemplate.setQueryTimeout(queryTimeout);
-				jdbcTemplate.setDataSource(ds);
+                JdbcTemplate jdbcTemplate = new JdbcTemplate();
+                jdbcTemplate.setQueryTimeout(queryTimeout);
+                jdbcTemplate.setDataSource(ds);
 
-				testJTList.add(jdbcTemplate);
-				isHealthList.add(Boolean.TRUE);
-			}
+                testJTList.add(jdbcTemplate);
+                isHealthList.add(Boolean.TRUE);
+            }
 
-			if (dblist == null || dblist.size() == 0) {
-				throw new RuntimeException("no datasource available");
-			}
+            if (dblist == null || dblist.size() == 0) {
+                throw new RuntimeException("no datasource available");
+            }
 
-			dataSourceList = dblist;
-			new SelectMasterTask().run();
-			new CheckDBHealthTask().run();
-		} catch (RuntimeException e) {
-			fatalLog.error(DB_LOAD_ERROR_MSG, e);
-			throw new IOException(e);
-		} finally {
-		}
-	}
+            dataSourceList = dblist;
+            new SelectMasterTask().run();
+            new CheckDBHealthTask().run();
+        } catch (RuntimeException e) {
+            fatalLog.error(DB_LOAD_ERROR_MSG, e);
+            throw new IOException(e);
+        } finally {
+        }
+    }
 
-	public boolean checkMasterWritable() {
+    public boolean checkMasterWritable() {
 
-		testMasterWritableJT.setDataSource(jt.getDataSource());
-		/**
-		 *  防止login接口因为主库不可用而rt太长
-		 */
-		testMasterWritableJT.setQueryTimeout(1); 
-		String sql = " select @@read_only ";
+        testMasterWritableJT.setDataSource(jt.getDataSource());
+        /**
+         *  防止login接口因为主库不可用而rt太长
+         */
+        testMasterWritableJT.setQueryTimeout(1);
+        String sql = " select @@read_only ";
 
-		try {
-			Integer result = testMasterWritableJT.queryForObject(sql, Integer.class);
-			if (result == null) {
-				return false;
-			} else {
-				return result.intValue() == 0 ? true : false;
-			}
-		} catch (CannotGetJdbcConnectionException e) {
-			fatalLog.error("[db-error] " + e.toString(), e);
-			return false;
-		}
+        try {
+            Integer result = testMasterWritableJT.queryForObject(sql, Integer.class);
+            if (result == null) {
+                return false;
+            } else {
+                return result.intValue() == 0 ? true : false;
+            }
+        } catch (CannotGetJdbcConnectionException e) {
+            fatalLog.error("[db-error] " + e.toString(), e);
+            return false;
+        }
 
-	}
+    }
 
-	public JdbcTemplate getJdbcTemplate() {
-		return this.jt;
-	}
+    public JdbcTemplate getJdbcTemplate() {
+        return this.jt;
+    }
 
-	public TransactionTemplate getTransactionTemplate() {
-		return this.tjt;
-	}
+    public TransactionTemplate getTransactionTemplate() {
+        return this.tjt;
+    }
 
-	public String getCurrentDBUrl() {
-		DataSource ds = this.jt.getDataSource();
-		if (ds == null) {
-			return StringUtils.EMPTY;
-		}
-		BasicDataSource bds = (BasicDataSource) ds;
-		return bds.getUrl();
-	}
+    public String getCurrentDBUrl() {
+        DataSource ds = this.jt.getDataSource();
+        if (ds == null) {
+            return StringUtils.EMPTY;
+        }
+        BasicDataSource bds = (BasicDataSource) ds;
+        return bds.getUrl();
+    }
 
-	public String getHealth() {
-		for (int i = 0 ; i < isHealthList.size(); i++) {
-			if (!isHealthList.get(i)) {
-				if (i == masterIndex) {    
-					/**
-					 * 主库不健康
-					 */
-					return "DOWN:" + getIpFromUrl(dataSourceList.get(i).getUrl());
-				} else {      
-					/**
-					 * 从库不健康
-					 */
-					return "WARN:" + getIpFromUrl(dataSourceList.get(i).getUrl());
-				}
-			}
-		}
+    public String getHealth() {
+        for (int i = 0; i < isHealthList.size(); i++) {
+            if (!isHealthList.get(i)) {
+                if (i == masterIndex) {
+                    /**
+                     * 主库不健康
+                     */
+                    return "DOWN:" + getIpFromUrl(dataSourceList.get(i).getUrl());
+                } else {
+                    /**
+                     * 从库不健康
+                     */
+                    return "WARN:" + getIpFromUrl(dataSourceList.get(i).getUrl());
+                }
+            }
+        }
 
-		return "UP";
-	}
+        return "UP";
+    }
 
-	private String getIpFromUrl(String url) {
-		
-		Matcher m = ipPattern.matcher(url);
-		if (m.find()) {
-			return m.group();
-		}
+    private String getIpFromUrl(String url) {
 
-		return "";
-	}
+        Matcher m = ipPattern.matcher(url);
+        if (m.find()) {
+            return m.group();
+        }
 
-	static String defaultIfNull(String value, String defaultValue) {
-		return null == value ? defaultValue : value;
-	}
+        return "";
+    }
 
-	class SelectMasterTask implements Runnable {
-		public void run() {
-			defaultLog.info("check master db.");
-			boolean isFound = false;
+    static String defaultIfNull(String value, String defaultValue) {
+        return null == value ? defaultValue : value;
+    }
 
-			int index = -1;
-			for (BasicDataSource ds : dataSourceList) {
-				index++;
-				testMasterJT.setDataSource(ds);
-				testMasterJT.setQueryTimeout(queryTimeout);
-				try {
-					testMasterJT
-							.update("delete from config_info where data_id='com.alibaba.nacos.testMasterDB'");
-					if (jt.getDataSource() != ds) {
-						fatalLog.warn("[master-db] {}", ds.getUrl());
-					}
-					jt.setDataSource(ds);
-					tm.setDataSource(ds);
-					isFound = true;
-					masterIndex = index;
-					break;
-				} catch (DataAccessException e) { // read only
-					e.printStackTrace(); // TODO remove
-				}
-			}
+    class SelectMasterTask implements Runnable {
+        public void run() {
+            defaultLog.info("check master db.");
+            boolean isFound = false;
 
-			if (!isFound) {
-				fatalLog.error("[master-db] master db not found.");
-			}
-		}
-	}
+            int index = -1;
+            for (BasicDataSource ds : dataSourceList) {
+                index++;
+                testMasterJT.setDataSource(ds);
+                testMasterJT.setQueryTimeout(queryTimeout);
+                try {
+                    testMasterJT
+                            .update("delete from config_info where data_id='com.alibaba.nacos.testMasterDB'");
+                    if (jt.getDataSource() != ds) {
+                        fatalLog.warn("[master-db] {}", ds.getUrl());
+                    }
+                    jt.setDataSource(ds);
+                    tm.setDataSource(ds);
+                    isFound = true;
+                    masterIndex = index;
+                    break;
+                } catch (DataAccessException e) { // read only
+                    e.printStackTrace(); // TODO remove
+                }
+            }
 
-	@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
-	class CheckDBHealthTask implements Runnable {
-		public void run() {
-			defaultLog.info("check db health.");
-			String sql = "SELECT * FROM config_info_beta WHERE id = 1";
+            if (!isFound) {
+                fatalLog.error("[master-db] master db not found.");
+            }
+        }
+    }
 
-			for (int i = 0; i < testJTList.size(); i++) {
-				JdbcTemplate jdbcTemplate = testJTList.get(i);
-				try {
-					jdbcTemplate.query(sql, CONFIG_INFO4BETA_ROW_MAPPER);
-					isHealthList.set(i, Boolean.TRUE);
-				} catch (DataAccessException e) {
-					if (i == masterIndex) {
-						fatalLog.error("[db-error] master db {} down.", getIpFromUrl(dataSourceList.get(i).getUrl()));
-					} else {
-						fatalLog.error("[db-error] slave db {} down.", getIpFromUrl(dataSourceList.get(i).getUrl()));
-					}
-					isHealthList.set(i, Boolean.FALSE);
-				}
-			}
-		}
-	}
+    @SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
+    class CheckDBHealthTask implements Runnable {
+        public void run() {
+            defaultLog.info("check db health.");
+            String sql = "SELECT * FROM config_info_beta WHERE id = 1";
+
+            for (int i = 0; i < testJTList.size(); i++) {
+                JdbcTemplate jdbcTemplate = testJTList.get(i);
+                try {
+                    jdbcTemplate.query(sql, CONFIG_INFO4BETA_ROW_MAPPER);
+                    isHealthList.set(i, Boolean.TRUE);
+                } catch (DataAccessException e) {
+                    if (i == masterIndex) {
+                        fatalLog.error("[db-error] master db {} down.", getIpFromUrl(dataSourceList.get(i).getUrl()));
+                    } else {
+                        fatalLog.error("[db-error] slave db {} down.", getIpFromUrl(dataSourceList.get(i).getUrl()));
+                    }
+                    isHealthList.set(i, Boolean.FALSE);
+                }
+            }
+        }
+    }
 }
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/ClientIpWhiteList.java b/config/src/main/java/com/alibaba/nacos/config/server/service/ClientIpWhiteList.java
index e3f011205..c3e41aea8 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/service/ClientIpWhiteList.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/service/ClientIpWhiteList.java
@@ -15,17 +15,16 @@
  */
 package com.alibaba.nacos.config.server.service;
 
-import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog;
+import com.alibaba.nacos.config.server.model.ACLInfo;
+import com.alibaba.nacos.config.server.utils.JSONUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.stereotype.Service;
 
 import java.util.ArrayList;
 import java.util.List;
 import java.util.concurrent.atomic.AtomicReference;
 
-import org.apache.commons.lang.StringUtils;
-import org.springframework.stereotype.Service;
-
-import com.alibaba.nacos.config.server.model.ACLInfo;
-import com.alibaba.nacos.config.server.utils.JSONUtils;
+import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog;
 /**
  * Client ip whitelist
  * @author Nacos
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/ClientTrackService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/ClientTrackService.java
index 448e6de47..0b8930df4 100755
--- a/config/src/main/java/com/alibaba/nacos/config/server/service/ClientTrackService.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/service/ClientTrackService.java
@@ -15,13 +15,13 @@
  */
 package com.alibaba.nacos.config.server.service;
 
+import com.alibaba.nacos.config.server.model.SubscriberStatus;
+
 import java.util.HashMap;
 import java.util.Map;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentMap;
 
-import com.alibaba.nacos.config.server.model.SubscriberStatus;
-
 
 /**
  * 跟踪客户端md5的服务。 一段时间没有比较md5后,就删除IP对应的记录。
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigDataChangeEvent.java b/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigDataChangeEvent.java
index ed9030e37..83c35c012 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigDataChangeEvent.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigDataChangeEvent.java
@@ -15,9 +15,8 @@
  */
 package com.alibaba.nacos.config.server.service;
 
-import org.apache.commons.lang.StringUtils;
-
 import com.alibaba.nacos.config.server.utils.event.EventDispatcher.Event;
+import org.apache.commons.lang3.StringUtils;
 
 
 /**
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigService.java
index 0460660b2..95f209ab8 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigService.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigService.java
@@ -15,34 +15,26 @@
  */
 package com.alibaba.nacos.config.server.service;
 
-import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog;
-import static com.alibaba.nacos.config.server.utils.LogUtil.dumpLog;
-import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.concurrent.ConcurrentHashMap;
-
-import com.alibaba.nacos.config.server.model.ConfigInfoBase;
-import com.alibaba.nacos.config.server.utils.PropertyUtil;
-import org.apache.commons.lang.StringUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
 import com.alibaba.nacos.config.server.constant.Constants;
 import com.alibaba.nacos.config.server.model.CacheItem;
+import com.alibaba.nacos.config.server.model.ConfigInfoBase;
 import com.alibaba.nacos.config.server.utils.GroupKey;
 import com.alibaba.nacos.config.server.utils.GroupKey2;
 import com.alibaba.nacos.config.server.utils.MD5;
+import com.alibaba.nacos.config.server.utils.PropertyUtil;
 import com.alibaba.nacos.config.server.utils.event.EventDispatcher;
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 
+import java.io.IOException;
+import java.util.*;
+import java.util.Map.Entry;
+import java.util.concurrent.ConcurrentHashMap;
+
+import static com.alibaba.nacos.config.server.utils.LogUtil.*;
+
 /**
  * config service
  * @author Nacos
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigSubService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigSubService.java
index 759f6f1db..773baec09 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigSubService.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigSubService.java
@@ -15,30 +15,6 @@
  */
 package com.alibaba.nacos.config.server.service;
 
-import java.net.HttpURLConnection;
-import java.net.URLEncoder;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.Callable;
-import java.util.concurrent.CompletionService;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.ExecutorCompletionService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-import java.util.concurrent.LinkedBlockingDeque;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ThreadFactory;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-
-import org.apache.commons.lang.StringUtils;
-import org.codehaus.jackson.type.TypeReference;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-
 import com.alibaba.nacos.config.server.constant.Constants;
 import com.alibaba.nacos.config.server.model.SampleResult;
 import com.alibaba.nacos.config.server.service.notify.NotifyService;
@@ -46,6 +22,18 @@ import com.alibaba.nacos.config.server.utils.JSONUtils;
 import com.alibaba.nacos.config.server.utils.LogUtil;
 import com.alibaba.nacos.config.server.utils.RunningConfigUtils;
 import com.alibaba.nacos.config.server.utils.ThreadUtil;
+import org.apache.commons.lang3.StringUtils;
+import org.codehaus.jackson.type.TypeReference;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import java.net.HttpURLConnection;
+import java.net.URLEncoder;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.*;
 /**
  * config sub service
  * @author Nacos
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/DiskUtil.java b/config/src/main/java/com/alibaba/nacos/config/server/service/DiskUtil.java
index 24c1797af..00832eef1 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/service/DiskUtil.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/service/DiskUtil.java
@@ -15,21 +15,20 @@
  */
 package com.alibaba.nacos.config.server.service;
 
+import com.alibaba.nacos.config.server.constant.Constants;
+import com.alibaba.nacos.config.server.utils.LogUtil;
+import com.alibaba.nacos.config.server.utils.MD5;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.IOException;
 
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.lang.StringUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.alibaba.nacos.config.server.constant.Constants;
-import com.alibaba.nacos.config.server.utils.LogUtil;
-import com.alibaba.nacos.config.server.utils.MD5;
-
 
 /**
  * 磁盘操作工具类。
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/LocalDataChangeEvent.java b/config/src/main/java/com/alibaba/nacos/config/server/service/LocalDataChangeEvent.java
index c88a88982..f694604f5 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/service/LocalDataChangeEvent.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/service/LocalDataChangeEvent.java
@@ -15,10 +15,10 @@
  */
 package com.alibaba.nacos.config.server.service;
 
-import java.util.List;
-
 import com.alibaba.nacos.config.server.utils.event.EventDispatcher.Event;
 
+import java.util.List;
+
 /**
  * 本地数据发生变更的事件。
  * @author Nacos
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/LocalDataSourceServiceImpl.java b/config/src/main/java/com/alibaba/nacos/config/server/service/LocalDataSourceServiceImpl.java
index a36ec8f66..f12008b44 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/service/LocalDataSourceServiceImpl.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/service/LocalDataSourceServiceImpl.java
@@ -15,6 +15,20 @@
  */
 package com.alibaba.nacos.config.server.service;
 
+import com.alibaba.nacos.config.server.constant.Constants;
+import com.alibaba.nacos.config.server.utils.LogUtil;
+import com.alibaba.nacos.config.server.utils.PropertyUtil;
+import com.alibaba.nacos.config.server.utils.StringUtils;
+import org.apache.commons.dbcp.BasicDataSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.jdbc.datasource.DataSourceTransactionManager;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.support.TransactionTemplate;
+
+import javax.annotation.PostConstruct;
+import javax.sql.DataSource;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.InputStream;
@@ -25,22 +39,6 @@ import java.util.ArrayList;
 import java.util.List;
 import java.util.concurrent.TimeUnit;
 
-import javax.annotation.PostConstruct;
-import javax.sql.DataSource;
-
-import com.alibaba.nacos.config.server.utils.PropertyUtil;
-import org.apache.commons.dbcp.BasicDataSource;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.jdbc.core.JdbcTemplate;
-import org.springframework.jdbc.datasource.DataSourceTransactionManager;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.support.TransactionTemplate;
-
-import com.alibaba.nacos.config.server.constant.Constants;
-import com.alibaba.nacos.config.server.utils.LogUtil;
-import com.alibaba.nacos.config.server.utils.StringUtils;
-
 /**
  * local data source
  *
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/LongPollingService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/LongPollingService.java
index b848132fd..bb43b2e84 100755
--- a/config/src/main/java/com/alibaba/nacos/config/server/service/LongPollingService.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/service/LongPollingService.java
@@ -15,34 +15,6 @@
  */
 package com.alibaba.nacos.config.server.service;
 
-import static com.alibaba.nacos.config.server.utils.LogUtil.memoryLog;
-import static com.alibaba.nacos.config.server.utils.LogUtil.pullLog;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Queue;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentLinkedQueue;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ThreadFactory;
-import java.util.concurrent.TimeUnit;
-
-import javax.servlet.AsyncContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.commons.lang.StringUtils;
-import org.springframework.stereotype.Service;
-
 import com.alibaba.nacos.config.server.model.SampleResult;
 import com.alibaba.nacos.config.server.utils.GroupKey;
 import com.alibaba.nacos.config.server.utils.LogUtil;
@@ -50,6 +22,17 @@ import com.alibaba.nacos.config.server.utils.MD5Util;
 import com.alibaba.nacos.config.server.utils.RequestUtil;
 import com.alibaba.nacos.config.server.utils.event.EventDispatcher.AbstractEventListener;
 import com.alibaba.nacos.config.server.utils.event.EventDispatcher.Event;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.stereotype.Service;
+
+import javax.servlet.AsyncContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.util.*;
+import java.util.concurrent.*;
+
+import static com.alibaba.nacos.config.server.utils.LogUtil.memoryLog;
+import static com.alibaba.nacos.config.server.utils.LogUtil.pullLog;
 
 /**
  * 长轮询服务。负责处理
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/PersistService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/PersistService.java
index cb7230e8f..d5643c6c1 100755
--- a/config/src/main/java/com/alibaba/nacos/config/server/service/PersistService.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/service/PersistService.java
@@ -15,25 +15,14 @@
  */
 package com.alibaba.nacos.config.server.service;
 
-import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog;
-import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog;
-
-import java.io.IOException;
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.sql.Timestamp;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import javax.annotation.PostConstruct;
-
-import org.apache.commons.lang.StringUtils;
+import com.alibaba.nacos.config.server.model.*;
+import com.alibaba.nacos.config.server.utils.LogUtil;
+import com.alibaba.nacos.config.server.utils.MD5;
+import com.alibaba.nacos.config.server.utils.PaginationHelper;
+import com.alibaba.nacos.config.server.utils.event.EventDispatcher;
+import com.google.common.collect.Lists;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.dao.DataAccessException;
 import org.springframework.dao.DataIntegrityViolationException;
@@ -54,25 +43,17 @@ import org.springframework.transaction.support.TransactionCallback;
 import org.springframework.transaction.support.TransactionTemplate;
 import org.springframework.util.CollectionUtils;
 
-import com.alibaba.nacos.config.server.model.ConfigAdvanceInfo;
-import com.alibaba.nacos.config.server.model.ConfigAllInfo;
-import com.alibaba.nacos.config.server.model.ConfigHistoryInfo;
-import com.alibaba.nacos.config.server.model.ConfigInfo;
-import com.alibaba.nacos.config.server.model.ConfigInfo4Beta;
-import com.alibaba.nacos.config.server.model.ConfigInfo4Tag;
-import com.alibaba.nacos.config.server.model.ConfigInfoAggr;
-import com.alibaba.nacos.config.server.model.ConfigInfoBase;
-import com.alibaba.nacos.config.server.model.ConfigInfoChanged;
-import com.alibaba.nacos.config.server.model.ConfigKey;
-import com.alibaba.nacos.config.server.model.Page;
-import com.alibaba.nacos.config.server.model.SubInfo;
-import com.alibaba.nacos.config.server.utils.LogUtil;
-import com.alibaba.nacos.config.server.utils.MD5;
-import com.alibaba.nacos.config.server.utils.PaginationHelper;
-import com.alibaba.nacos.config.server.utils.event.EventDispatcher;
-import com.google.common.collect.Lists;
+import javax.annotation.PostConstruct;
+import java.io.IOException;
+import java.sql.*;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
 
-import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog;
+import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog;
 
 /**
  * 数据库服务,提供ConfigInfo在数据库的存取
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/ServerListService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/ServerListService.java index 6437bd582..cff097f9e 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/ServerListService.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/ServerListService.java @@ -15,39 +15,6 @@ */ package com.alibaba.nacos.config.server.service; -import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog; -import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog; - -import java.io.IOException; -import java.io.StringReader; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; - -import javax.annotation.PostConstruct; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.http.HttpResponse; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.utils.HttpClientUtils; -import org.apache.http.concurrent.FutureCallback; -import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; -import org.apache.http.impl.nio.client.HttpAsyncClients; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.web.context.WebServerInitializedEvent; -import org.springframework.context.ApplicationListener; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Service; - import com.alibaba.nacos.config.server.constant.Constants; import com.alibaba.nacos.config.server.service.notify.NotifyService; import com.alibaba.nacos.config.server.service.notify.NotifyService.HttpResult; @@ -56,6 +23,32 @@ import com.alibaba.nacos.config.server.utils.PropertyUtil; import com.alibaba.nacos.config.server.utils.RunningConfigUtils; import com.alibaba.nacos.config.server.utils.SystemConfig; import com.alibaba.nacos.config.server.utils.event.EventDispatcher; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.http.HttpResponse; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.utils.HttpClientUtils; +import org.apache.http.concurrent.FutureCallback; +import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; +import org.apache.http.impl.nio.client.HttpAsyncClients; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.web.context.WebServerInitializedEvent; +import org.springframework.context.ApplicationListener; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.StringReader; +import java.util.*; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; + +import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog; +import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog; /** * Serverlist service diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/SwitchService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/SwitchService.java index a0303c428..52eb66223 100755 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/SwitchService.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/SwitchService.java @@ -15,19 +15,18 @@ */ package com.alibaba.nacos.config.server.service; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang.StringUtils; -import org.springframework.stereotype.Service; - import com.alibaba.nacos.config.server.utils.LogUtil; - -import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.stereotype.Service; import java.io.IOException; import java.io.StringReader; import java.util.HashMap; import java.util.Map; +import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog; + /** * Switch * @author Nacos diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/capacity/CapacityService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/capacity/CapacityService.java index a5b8a213e..eea8d776e 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/capacity/CapacityService.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/capacity/CapacityService.java @@ -20,13 +20,12 @@ import com.alibaba.nacos.config.server.model.capacity.Capacity; import com.alibaba.nacos.config.server.model.capacity.GroupCapacity; import com.alibaba.nacos.config.server.model.capacity.TenantCapacity; import com.alibaba.nacos.config.server.service.PersistService; -import com.alibaba.nacos.config.server.utils.PropertyUtil; import com.alibaba.nacos.config.server.utils.LogUtil; +import com.alibaba.nacos.config.server.utils.PropertyUtil; import com.alibaba.nacos.config.server.utils.TimeUtils; import com.google.common.base.Stopwatch; import com.google.common.util.concurrent.ThreadFactoryBuilder; - -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/capacity/GroupCapacityPersistService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/capacity/GroupCapacityPersistService.java index 3d85f49e4..9533b25e8 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/capacity/GroupCapacityPersistService.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/capacity/GroupCapacityPersistService.java @@ -17,16 +17,12 @@ package com.alibaba.nacos.config.server.service.capacity; import com.alibaba.nacos.config.server.model.capacity.Capacity; import com.alibaba.nacos.config.server.model.capacity.GroupCapacity; -import com.alibaba.nacos.config.server.service.BasicDataSourceServiceImpl; import com.alibaba.nacos.config.server.service.DataSourceService; import com.alibaba.nacos.config.server.service.DynamicDataSource; -import com.alibaba.nacos.config.server.service.LocalDataSourceServiceImpl; import com.alibaba.nacos.config.server.utils.PropertyUtil; import com.alibaba.nacos.config.server.utils.TimeUtils; import com.google.common.collect.Lists; - import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.CannotGetJdbcConnectionException; import org.springframework.jdbc.core.JdbcTemplate; @@ -35,12 +31,11 @@ import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.stereotype.Service; -import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog; - +import javax.annotation.PostConstruct; import java.sql.*; import java.util.List; -import javax.annotation.PostConstruct; +import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog; /** * Group Capacity Service diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/capacity/TenantCapacityPersistService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/capacity/TenantCapacityPersistService.java index 3f3c25621..a435e9746 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/capacity/TenantCapacityPersistService.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/capacity/TenantCapacityPersistService.java @@ -16,16 +16,12 @@ package com.alibaba.nacos.config.server.service.capacity; import com.alibaba.nacos.config.server.model.capacity.TenantCapacity; -import com.alibaba.nacos.config.server.service.BasicDataSourceServiceImpl; import com.alibaba.nacos.config.server.service.DataSourceService; import com.alibaba.nacos.config.server.service.DynamicDataSource; -import com.alibaba.nacos.config.server.service.LocalDataSourceServiceImpl; import com.alibaba.nacos.config.server.utils.PropertyUtil; import com.alibaba.nacos.config.server.utils.TimeUtils; import com.google.common.collect.Lists; - import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.CannotGetJdbcConnectionException; import org.springframework.jdbc.core.JdbcTemplate; @@ -34,12 +30,11 @@ import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.stereotype.Service; -import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog; - +import javax.annotation.PostConstruct; import java.sql.*; import java.util.List; -import javax.annotation.PostConstruct; +import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog; /** * Tenant Capacity Service diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/dump/DumpService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/dump/DumpService.java index 5c17497b3..87a385b5f 100755 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/dump/DumpService.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/dump/DumpService.java @@ -21,41 +21,32 @@ import com.alibaba.nacos.config.server.model.ConfigInfo; import com.alibaba.nacos.config.server.model.ConfigInfoAggr; import com.alibaba.nacos.config.server.model.ConfigInfoChanged; import com.alibaba.nacos.config.server.model.Page; -import com.alibaba.nacos.config.server.service.ConfigService; -import com.alibaba.nacos.config.server.service.DiskUtil; -import com.alibaba.nacos.config.server.service.PersistService; -import com.alibaba.nacos.config.server.service.ServerListService; -import com.alibaba.nacos.config.server.service.TimerTaskService; +import com.alibaba.nacos.config.server.service.*; import com.alibaba.nacos.config.server.service.PersistService.ConfigInfoWrapper; import com.alibaba.nacos.config.server.service.merge.MergeTaskProcessor; import com.alibaba.nacos.config.server.utils.*; - import org.apache.commons.io.IOUtils; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Service; -import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog; - +import javax.annotation.PostConstruct; import java.io.File; import java.io.FileInputStream; import java.io.IOException; -import java.net.URI; -import java.net.URL; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; -import java.util.Properties; import java.util.Random; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -import javax.annotation.PostConstruct; +import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog; /** * Dump data service diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/dump/DumpTask.java b/config/src/main/java/com/alibaba/nacos/config/server/service/dump/DumpTask.java index e3c2453da..14def8dae 100755 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/dump/DumpTask.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/dump/DumpTask.java @@ -15,22 +15,13 @@ */ package com.alibaba.nacos.config.server.service.dump; -import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog; - -import java.sql.Timestamp; -import java.util.List; - import com.alibaba.nacos.config.server.manager.AbstractTask; import com.alibaba.nacos.config.server.manager.TaskProcessor; import com.alibaba.nacos.config.server.model.ConfigInfo; import com.alibaba.nacos.config.server.model.ConfigInfo4Beta; import com.alibaba.nacos.config.server.model.ConfigInfo4Tag; import com.alibaba.nacos.config.server.model.Page; -import com.alibaba.nacos.config.server.service.AggrWhitelist; -import com.alibaba.nacos.config.server.service.ClientIpWhiteList; -import com.alibaba.nacos.config.server.service.ConfigService; -import com.alibaba.nacos.config.server.service.PersistService; -import com.alibaba.nacos.config.server.service.SwitchService; +import com.alibaba.nacos.config.server.service.*; import com.alibaba.nacos.config.server.service.PersistService.ConfigInfoBetaWrapper; import com.alibaba.nacos.config.server.service.PersistService.ConfigInfoTagWrapper; import com.alibaba.nacos.config.server.service.PersistService.ConfigInfoWrapper; @@ -40,6 +31,11 @@ import com.alibaba.nacos.config.server.utils.LogUtil; import com.alibaba.nacos.config.server.utils.MD5; import com.alibaba.nacos.config.server.utils.StringUtils; +import java.sql.Timestamp; +import java.util.List; + +import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog; + /** * Dump data task * @author Nacos diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/merge/MergeDatumService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/merge/MergeDatumService.java index 0bc686ce8..548b0e7c7 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/merge/MergeDatumService.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/merge/MergeDatumService.java @@ -15,16 +15,6 @@ */ package com.alibaba.nacos.config.server.service.merge; -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - import com.alibaba.nacos.config.server.manager.TaskManager; import com.alibaba.nacos.config.server.model.ConfigInfo; import com.alibaba.nacos.config.server.model.ConfigInfoAggr; @@ -34,6 +24,15 @@ import com.alibaba.nacos.config.server.service.PersistService; import com.alibaba.nacos.config.server.utils.ContentUtils; import com.alibaba.nacos.config.server.utils.SystemConfig; import com.alibaba.nacos.config.server.utils.TimeUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; /** diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/merge/MergeTaskProcessor.java b/config/src/main/java/com/alibaba/nacos/config/server/service/merge/MergeTaskProcessor.java index 38ac2aada..fe4fe845a 100755 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/merge/MergeTaskProcessor.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/merge/MergeTaskProcessor.java @@ -29,13 +29,12 @@ import com.alibaba.nacos.config.server.utils.StringUtils; import com.alibaba.nacos.config.server.utils.SystemConfig; import com.alibaba.nacos.config.server.utils.TimeUtils; import com.alibaba.nacos.config.server.utils.event.EventDispatcher; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.Timestamp; -import java.util.List; import java.util.ArrayList; +import java.util.List; /** diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/notify/AsyncNotifyService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/notify/AsyncNotifyService.java index 3afdbc3d1..a07f81f89 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/notify/AsyncNotifyService.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/notify/AsyncNotifyService.java @@ -15,19 +15,13 @@ */ package com.alibaba.nacos.config.server.service.notify; -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; -import java.util.Queue; -import java.util.concurrent.Executor; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; - +import com.alibaba.nacos.config.server.constant.Constants; +import com.alibaba.nacos.config.server.service.ConfigDataChangeEvent; +import com.alibaba.nacos.config.server.service.ServerListService; +import com.alibaba.nacos.config.server.service.trace.ConfigTraceService; +import com.alibaba.nacos.config.server.utils.*; +import com.alibaba.nacos.config.server.utils.event.EventDispatcher.AbstractEventListener; +import com.alibaba.nacos.config.server.utils.event.EventDispatcher.Event; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.config.RequestConfig; @@ -41,17 +35,14 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import com.alibaba.nacos.config.server.constant.Constants; -import com.alibaba.nacos.config.server.service.ConfigDataChangeEvent; -import com.alibaba.nacos.config.server.service.ServerListService; -import com.alibaba.nacos.config.server.service.trace.ConfigTraceService; -import com.alibaba.nacos.config.server.utils.LogUtil; -import com.alibaba.nacos.config.server.utils.PropertyUtil; -import com.alibaba.nacos.config.server.utils.RunningConfigUtils; -import com.alibaba.nacos.config.server.utils.StringUtils; -import com.alibaba.nacos.config.server.utils.SystemConfig; -import com.alibaba.nacos.config.server.utils.event.EventDispatcher.AbstractEventListener; -import com.alibaba.nacos.config.server.utils.event.EventDispatcher.Event; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; +import java.util.concurrent.*; /** * Async notify service diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/notify/NotifyService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/notify/NotifyService.java index 439000e16..4e9ca010f 100755 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/notify/NotifyService.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/notify/NotifyService.java @@ -15,21 +15,19 @@ */ package com.alibaba.nacos.config.server.service.notify; +import com.alibaba.nacos.config.server.manager.TaskManager; +import com.alibaba.nacos.config.server.service.ServerListService; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; + +import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.util.Iterator; import java.util.List; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; - -import com.alibaba.nacos.config.server.manager.TaskManager; -import com.alibaba.nacos.config.server.service.ServerListService; - /** * 通知其他节点取最新数据的服务。 监听数据变更事件,通知所有的server。 diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/notify/NotifySingleService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/notify/NotifySingleService.java index a2024f8cf..11a9b2395 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/notify/NotifySingleService.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/notify/NotifySingleService.java @@ -15,23 +15,16 @@ */ package com.alibaba.nacos.config.server.service.notify; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.Executor; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -import org.slf4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; - import com.alibaba.nacos.config.server.manager.AbstractTask; import com.alibaba.nacos.config.server.service.ServerListService; import com.alibaba.nacos.config.server.utils.GroupKey2; import com.alibaba.nacos.config.server.utils.LogUtil; +import org.slf4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.*; /** * Notify Single server diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/notify/NotifyTaskProcessor.java b/config/src/main/java/com/alibaba/nacos/config/server/service/notify/NotifyTaskProcessor.java index 722ca42d5..163812d31 100755 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/notify/NotifyTaskProcessor.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/notify/NotifyTaskProcessor.java @@ -15,14 +15,6 @@ */ package com.alibaba.nacos.config.server.service.notify; -import java.text.MessageFormat; -import java.util.Arrays; -import java.util.List; - -import org.apache.http.HttpStatus; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.alibaba.nacos.config.server.constant.Constants; import com.alibaba.nacos.config.server.manager.AbstractTask; import com.alibaba.nacos.config.server.manager.TaskProcessor; @@ -31,6 +23,13 @@ import com.alibaba.nacos.config.server.service.notify.NotifyService.HttpResult; import com.alibaba.nacos.config.server.service.trace.ConfigTraceService; import com.alibaba.nacos.config.server.utils.RunningConfigUtils; import com.alibaba.nacos.config.server.utils.SystemConfig; +import org.apache.http.HttpStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.text.MessageFormat; +import java.util.Arrays; +import java.util.List; /** diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/trace/ConfigTraceService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/trace/ConfigTraceService.java index 83e87ae07..f0511ca2f 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/trace/ConfigTraceService.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/trace/ConfigTraceService.java @@ -18,8 +18,7 @@ package com.alibaba.nacos.config.server.service.trace; import com.alibaba.nacos.config.server.utils.LogUtil; import com.alibaba.nacos.config.server.utils.MD5; import com.alibaba.nacos.config.server.utils.SystemConfig; - -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; /** * Config trace diff --git a/config/src/main/java/com/alibaba/nacos/config/server/utils/ContentUtils.java b/config/src/main/java/com/alibaba/nacos/config/server/utils/ContentUtils.java index 45154a0a0..4b1b4ef80 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/utils/ContentUtils.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/utils/ContentUtils.java @@ -15,10 +15,10 @@ */ package com.alibaba.nacos.config.server.utils; -import static com.alibaba.nacos.config.server.constant.Constants.WORD_SEPARATOR; - import com.alibaba.nacos.config.server.constant.Constants; +import static com.alibaba.nacos.config.server.constant.Constants.WORD_SEPARATOR; + /** * Content utils * @author Nacos diff --git a/config/src/main/java/com/alibaba/nacos/config/server/utils/JSONUtils.java b/config/src/main/java/com/alibaba/nacos/config/server/utils/JSONUtils.java index db6b5c217..1d39d7a26 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/utils/JSONUtils.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/utils/JSONUtils.java @@ -15,13 +15,13 @@ */ package com.alibaba.nacos.config.server.utils; -import java.io.IOException; - -import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.DeserializationConfig.Feature; +import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.JavaType; import org.codehaus.jackson.type.TypeReference; +import java.io.IOException; + /** * json util * @author Nacos diff --git a/config/src/main/java/com/alibaba/nacos/config/server/utils/LogUtil.java b/config/src/main/java/com/alibaba/nacos/config/server/utils/LogUtil.java index c9072505c..ade7d2fe6 100755 --- a/config/src/main/java/com/alibaba/nacos/config/server/utils/LogUtil.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/utils/LogUtil.java @@ -15,11 +15,11 @@ */ package com.alibaba.nacos.config.server.utils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.core.joran.spi.JoranException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * log util diff --git a/config/src/main/java/com/alibaba/nacos/config/server/utils/MD5.java b/config/src/main/java/com/alibaba/nacos/config/server/utils/MD5.java index 8e41b3221..6de1b42d2 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/utils/MD5.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/utils/MD5.java @@ -15,14 +15,14 @@ */ package com.alibaba.nacos.config.server.utils; +import com.alibaba.nacos.config.server.constant.Constants; + import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.ReentrantLock; -import com.alibaba.nacos.config.server.constant.Constants; - /** * md5 * @author Nacos diff --git a/config/src/main/java/com/alibaba/nacos/config/server/utils/MD5Util.java b/config/src/main/java/com/alibaba/nacos/config/server/utils/MD5Util.java index 8de5c9522..4749c26ae 100755 --- a/config/src/main/java/com/alibaba/nacos/config/server/utils/MD5Util.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/utils/MD5Util.java @@ -15,28 +15,21 @@ */ package com.alibaba.nacos.config.server.utils; -import static com.alibaba.nacos.config.server.constant.Constants.LINE_SEPARATOR; -import static com.alibaba.nacos.config.server.constant.Constants.WORD_SEPARATOR; +import com.alibaba.nacos.config.server.constant.Constants; +import com.alibaba.nacos.config.server.service.ConfigService; +import org.apache.commons.lang3.StringUtils; -import java.io.CharArrayWriter; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.Writer; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.*; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.lang.StringUtils; - -import com.alibaba.nacos.config.server.constant.Constants; -import com.alibaba.nacos.config.server.service.ConfigService; +import static com.alibaba.nacos.config.server.constant.Constants.LINE_SEPARATOR; +import static com.alibaba.nacos.config.server.constant.Constants.WORD_SEPARATOR; /** * 轮询逻辑封装类 diff --git a/config/src/main/java/com/alibaba/nacos/config/server/utils/PaginationHelper.java b/config/src/main/java/com/alibaba/nacos/config/server/utils/PaginationHelper.java index 63b1a377a..a4b42554b 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/utils/PaginationHelper.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/utils/PaginationHelper.java @@ -15,12 +15,11 @@ */ package com.alibaba.nacos.config.server.utils; -import java.util.List; - +import com.alibaba.nacos.config.server.model.Page; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; -import com.alibaba.nacos.config.server.model.Page; +import java.util.List; /** diff --git a/config/src/main/java/com/alibaba/nacos/config/server/utils/ParamUtils.java b/config/src/main/java/com/alibaba/nacos/config/server/utils/ParamUtils.java index 24b734938..9b92197a9 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/utils/ParamUtils.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/utils/ParamUtils.java @@ -15,11 +15,10 @@ */ package com.alibaba.nacos.config.server.utils; -import java.util.Map; - -import org.apache.commons.lang.StringUtils; - import com.alibaba.nacos.config.server.exception.NacosException; +import org.apache.commons.lang3.StringUtils; + +import java.util.Map; /** * 参数合法性检查工具类 diff --git a/config/src/main/java/com/alibaba/nacos/config/server/utils/PropertyUtil.java b/config/src/main/java/com/alibaba/nacos/config/server/utils/PropertyUtil.java index c33b837c0..e2507aac9 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/utils/PropertyUtil.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/utils/PropertyUtil.java @@ -15,13 +15,13 @@ */ package com.alibaba.nacos.config.server.utils; -import javax.annotation.PostConstruct; - import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; +import javax.annotation.PostConstruct; + /** * properties utils * diff --git a/config/src/main/java/com/alibaba/nacos/config/server/utils/RegexParser.java b/config/src/main/java/com/alibaba/nacos/config/server/utils/RegexParser.java index a32d33c2b..a06226a02 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/utils/RegexParser.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/utils/RegexParser.java @@ -15,9 +15,7 @@ */ package com.alibaba.nacos.config.server.utils; -import org.apache.commons.lang.CharUtils; -import org.apache.commons.lang.NullArgumentException; - +import org.apache.commons.lang3.CharUtils; /** @@ -28,7 +26,7 @@ import org.apache.commons.lang.NullArgumentException; */ public class RegexParser { - private final static char QUESTION_MARK = '?'; + private final static char QUESTION_MARK = '?'; /** * 替换输入字符串中非正则特殊字符为标准正则表达式字符串;
@@ -40,7 +38,7 @@ public class RegexParser { */ static public String regexFormat(String regex) { if (regex == null) { - throw new NullArgumentException("regex string can't be null"); + throw new NullPointerException("regex string can't be null"); } StringBuffer result = new StringBuffer(); result.append("^"); diff --git a/config/src/main/java/com/alibaba/nacos/config/server/utils/ResourceUtils.java b/config/src/main/java/com/alibaba/nacos/config/server/utils/ResourceUtils.java index f00f95ba2..d411a12bf 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/utils/ResourceUtils.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/utils/ResourceUtils.java @@ -15,16 +15,12 @@ */ package com.alibaba.nacos.config.server.utils; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; +import com.alibaba.nacos.config.server.constant.Constants; + +import java.io.*; import java.net.URL; import java.util.Properties; -import com.alibaba.nacos.config.server.constant.Constants; - /** * resource util diff --git a/config/src/main/java/com/alibaba/nacos/config/server/utils/ResponseUtil.java b/config/src/main/java/com/alibaba/nacos/config/server/utils/ResponseUtil.java index 2437ddcbb..ae800f26f 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/utils/ResponseUtil.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/utils/ResponseUtil.java @@ -15,10 +15,10 @@ */ package com.alibaba.nacos.config.server.utils; -import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog; - -import java.io.IOException; import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog; /** * write response diff --git a/config/src/main/java/com/alibaba/nacos/config/server/utils/RunningConfigUtils.java b/config/src/main/java/com/alibaba/nacos/config/server/utils/RunningConfigUtils.java index a1dccf2b8..41660922e 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/utils/RunningConfigUtils.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/utils/RunningConfigUtils.java @@ -15,13 +15,13 @@ */ package com.alibaba.nacos.config.server.utils; -import javax.servlet.ServletContext; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.context.WebServerInitializedEvent; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; +import javax.servlet.ServletContext; + /** * Running config * @author dungu.zpf diff --git a/config/src/main/java/com/alibaba/nacos/config/server/utils/SystemConfig.java b/config/src/main/java/com/alibaba/nacos/config/server/utils/SystemConfig.java index cc70258d0..e8e837d05 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/utils/SystemConfig.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/utils/SystemConfig.java @@ -15,14 +15,14 @@ */ package com.alibaba.nacos.config.server.utils; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.net.InetAddress; import java.net.NetworkInterface; import java.util.Enumeration; -import org.apache.commons.lang.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * System config * @author Nacos diff --git a/config/src/main/java/com/alibaba/nacos/config/server/utils/TimeUtils.java b/config/src/main/java/com/alibaba/nacos/config/server/utils/TimeUtils.java index 9f57e01b9..d1d366e4f 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/utils/TimeUtils.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/utils/TimeUtils.java @@ -15,7 +15,8 @@ */ package com.alibaba.nacos.config.server.utils; -import org.apache.commons.lang.time.FastDateFormat; + +import org.apache.commons.lang3.time.FastDateFormat; import java.sql.Timestamp; import java.util.Calendar; diff --git a/config/src/main/java/com/alibaba/nacos/config/server/utils/UrlAnalysisUtils.java b/config/src/main/java/com/alibaba/nacos/config/server/utils/UrlAnalysisUtils.java index 261b3250f..983703521 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/utils/UrlAnalysisUtils.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/utils/UrlAnalysisUtils.java @@ -15,11 +15,11 @@ */ package com.alibaba.nacos.config.server.utils; +import com.alibaba.nacos.config.server.constant.Constants; + import java.util.regex.Matcher; import java.util.regex.Pattern; -import com.alibaba.nacos.config.server.constant.Constants; - /** * 分析url的工具类 diff --git a/config/src/main/java/com/alibaba/nacos/config/server/utils/event/EventDispatcher.java b/config/src/main/java/com/alibaba/nacos/config/server/utils/event/EventDispatcher.java index a6c8dd19d..ae20e2835 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/utils/event/EventDispatcher.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/utils/event/EventDispatcher.java @@ -15,12 +15,12 @@ */ package com.alibaba.nacos.config.server.utils.event; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + /** * Event dispatcher diff --git a/pom.xml b/pom.xml index 1eb733b91..5c9e516e9 100644 --- a/pom.xml +++ b/pom.xml @@ -551,11 +551,6 @@ commons-lang3 3.4
- - commons-lang - commons-lang - 2.6 - commons-collections commons-collections From 3b5eb060e878acdcd02f6cdc9a27e94a6127e480 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Mon, 1 Oct 2018 12:15:21 +0800 Subject: [PATCH 12/30] Polish alibaba/nacos#103 --- api/pom.xml | 3 +- client/pom.xml | 5 - config/pom.xml | 14 +- .../nacos/config/mock/FilterConfigMock.java | 56 --- .../nacos/config/mock/ServletContextMock.java | 356 ------------------ naming/pom.xml | 5 - pom.xml | 276 +++++++------- test/pom.xml | 160 ++++---- 8 files changed, 215 insertions(+), 660 deletions(-) delete mode 100644 config/src/test/java/com/alibaba/nacos/config/mock/FilterConfigMock.java delete mode 100644 config/src/test/java/com/alibaba/nacos/config/mock/ServletContextMock.java diff --git a/api/pom.xml b/api/pom.xml index 0863cf634..72b688a18 100644 --- a/api/pom.xml +++ b/api/pom.xml @@ -33,12 +33,13 @@ + com.alibaba fastjson - + junit junit diff --git a/client/pom.xml b/client/pom.xml index 6dc477aeb..d9b0e361e 100644 --- a/client/pom.xml +++ b/client/pom.xml @@ -63,11 +63,6 @@ nacos-api - - com.alibaba - fastjson - - ch.qos.logback logback-classic diff --git a/config/pom.xml b/config/pom.xml index a691842c8..acc9c69f2 100644 --- a/config/pom.xml +++ b/config/pom.xml @@ -47,22 +47,12 @@ com.google.guava guava - - taglibs - standard - + org.springframework.boot spring-boot-starter-jdbc - - commons-io - commons-io - - - org.apache.commons - commons-lang3 - + mysql mysql-connector-java diff --git a/config/src/test/java/com/alibaba/nacos/config/mock/FilterConfigMock.java b/config/src/test/java/com/alibaba/nacos/config/mock/FilterConfigMock.java deleted file mode 100644 index 02095a9b9..000000000 --- a/config/src/test/java/com/alibaba/nacos/config/mock/FilterConfigMock.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright 1999-2018 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.nacos.config.mock; - -import java.util.Enumeration; - -import javax.servlet.FilterConfig; -import javax.servlet.ServletContext; - - - -public class FilterConfigMock implements FilterConfig { - - public FilterConfigMock(ServletContext context) { - this.context = context; - } - - - @Override - public String getFilterName() { - // TODO Auto-generated method stub - return null; - } - - @Override - public ServletContext getServletContext() { - return context; - } - - @Override - public String getInitParameter(String name) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Enumeration getInitParameterNames() { - // TODO Auto-generated method stub - return null; - } - - final ServletContext context; -} diff --git a/config/src/test/java/com/alibaba/nacos/config/mock/ServletContextMock.java b/config/src/test/java/com/alibaba/nacos/config/mock/ServletContextMock.java deleted file mode 100644 index 736543b65..000000000 --- a/config/src/test/java/com/alibaba/nacos/config/mock/ServletContextMock.java +++ /dev/null @@ -1,356 +0,0 @@ -/* - * Copyright 1999-2018 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.nacos.config.mock; - -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Enumeration; -import java.util.EventListener; -import java.util.Map; -import java.util.Set; - -import javax.servlet.Filter; -import javax.servlet.FilterRegistration; -import javax.servlet.FilterRegistration.Dynamic; -import javax.servlet.RequestDispatcher; -import javax.servlet.Servlet; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRegistration; -import javax.servlet.SessionCookieConfig; -import javax.servlet.SessionTrackingMode; -import javax.servlet.descriptor.JspConfigDescriptor; - - - - -public class ServletContextMock implements ServletContext { - - @Override - public String getContextPath() { - // TODO Auto-generated method stub - return null; - } - - @Override - public ServletContext getContext(String uripath) { - // TODO Auto-generated method stub - return null; - } - - @Override - public int getMajorVersion() { - // TODO Auto-generated method stub - return 0; - } - - @Override - public int getMinorVersion() { - // TODO Auto-generated method stub - return 0; - } - - @Override - public String getMimeType(String file) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Set getResourcePaths(String path) { - // TODO Auto-generated method stub - return null; - } - - @Override - public URL getResource(String path) throws MalformedURLException { - // TODO Auto-generated method stub - return null; - } - - @Override - public InputStream getResourceAsStream(String path) { - // TODO Auto-generated method stub - return null; - } - - @Override - public RequestDispatcher getRequestDispatcher(String path) { - // TODO Auto-generated method stub - return null; - } - - @Override - public RequestDispatcher getNamedDispatcher(String name) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Servlet getServlet(String name) throws ServletException { - // TODO Auto-generated method stub - return null; - } - - @Override - public Enumeration getServlets() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Enumeration getServletNames() { - // TODO Auto-generated method stub - return null; - } - - @Override - public void log(String msg) { - // TODO Auto-generated method stub - - } - - @Override - public void log(Exception exception, String msg) { - // TODO Auto-generated method stub - - } - - @Override - public void log(String message, Throwable throwable) { - // TODO Auto-generated method stub - - } - - @Override - public String getRealPath(String path) { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getServerInfo() { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getInitParameter(String name) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Enumeration getInitParameterNames() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Object getAttribute(String name) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Enumeration getAttributeNames() { - // TODO Auto-generated method stub - return null; - } - - @Override - public void setAttribute(String name, Object object) { - // TODO Auto-generated method stub - - } - - @Override - public void removeAttribute(String name) { - // TODO Auto-generated method stub - - } - - @Override - public String getServletContextName() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Dynamic addFilter(String arg0, String arg1) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Dynamic addFilter(String arg0, Filter arg1) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Dynamic addFilter(String arg0, Class arg1) { - // TODO Auto-generated method stub - return null; - } - - @Override - public void addListener(Class arg0) { - // TODO Auto-generated method stub - - } - - @Override - public void addListener(String arg0) { - // TODO Auto-generated method stub - - } - - @Override - public void addListener(T arg0) { - // TODO Auto-generated method stub - - } - - @Override - public javax.servlet.ServletRegistration.Dynamic addServlet(String arg0, String arg1) { - // TODO Auto-generated method stub - return null; - } - - @Override - public javax.servlet.ServletRegistration.Dynamic addServlet(String arg0, Servlet arg1) { - // TODO Auto-generated method stub - return null; - } - - @Override - public javax.servlet.ServletRegistration.Dynamic addServlet(String arg0, - Class arg1) { - // TODO Auto-generated method stub - return null; - } - - @Override - public T createFilter(Class arg0) throws ServletException { - // TODO Auto-generated method stub - return null; - } - - @Override - public T createListener(Class arg0) throws ServletException { - // TODO Auto-generated method stub - return null; - } - - @Override - public T createServlet(Class arg0) throws ServletException { - // TODO Auto-generated method stub - return null; - } - - @Override - public void declareRoles(String... arg0) { - // TODO Auto-generated method stub - - } - - @Override - public ClassLoader getClassLoader() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Set getDefaultSessionTrackingModes() { - // TODO Auto-generated method stub - return null; - } - - @Override - public int getEffectiveMajorVersion() { - // TODO Auto-generated method stub - return 0; - } - - @Override - public int getEffectiveMinorVersion() { - // TODO Auto-generated method stub - return 0; - } - - @Override - public Set getEffectiveSessionTrackingModes() { - // TODO Auto-generated method stub - return null; - } - - @Override - public FilterRegistration getFilterRegistration(String arg0) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Map getFilterRegistrations() { - // TODO Auto-generated method stub - return null; - } - - @Override - public JspConfigDescriptor getJspConfigDescriptor() { - // TODO Auto-generated method stub - return null; - } - - @Override - public ServletRegistration getServletRegistration(String arg0) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Map getServletRegistrations() { - // TODO Auto-generated method stub - return null; - } - - @Override - public SessionCookieConfig getSessionCookieConfig() { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean setInitParameter(String arg0, String arg1) { - // TODO Auto-generated method stub - return false; - } - - @Override - public void setSessionTrackingModes(Set arg0) - throws IllegalStateException, IllegalArgumentException { - // TODO Auto-generated method stub - } - - @Override - public String getVirtualServerName() { - // TODO Auto-generated method stub - return null; - } - -} diff --git a/naming/pom.xml b/naming/pom.xml index ca1e6771f..9c157c619 100644 --- a/naming/pom.xml +++ b/naming/pom.xml @@ -52,11 +52,6 @@ fastjson - - org.apache.commons - commons-lang3 - - io.netty netty-all diff --git a/pom.xml b/pom.xml index 5c9e516e9..da576c18d 100644 --- a/pom.xml +++ b/pom.xml @@ -90,7 +90,6 @@ UTF-8 UTF-8 - false true @@ -101,7 +100,6 @@ ${project.basedir}/../test/target/jacoco-it.exec file:**/generated-sources/**,**/test/** - @@ -461,6 +459,7 @@ import + ${project.groupId} nacos-config @@ -511,103 +510,33 @@ nacos-example ${project.version} - - org.slf4j - slf4j-api - 1.7.7 - - - ch.qos.logback - logback-classic - 1.2.3 - - - ch.qos.logback - logback-core - 1.2.3 - - - commons-cli - commons-cli - 1.2 - - - io.netty - netty-all - 4.0.42.Final - + + com.alibaba fastjson 1.2.47 - - com.ning - async-http-client - 1.7.17 - - - org.apache.commons - commons-lang3 - 3.4 - - - commons-collections - commons-collections - 3.2.2 - - - commons-logging - commons-logging - 1.2 - - - org.codehaus.jackson - jackson-core-asl - 1.9.10 - - - apache-log4j - log4j - 1.2.15 - - - log4j - log4j - 1.2.17 - - - org.apache.logging.log4j - log4j-core - 2.10.0 - - - org.apache.logging.log4j - log4j-slf4j-impl - 2.10.0 - - - com.github.spotbugs - spotbugs-annotations - 3.1.3 - - + javax.ws.rs javax.ws.rs 2.1 + javax.servlet servlet-api 3.0 provided + + - taglibs - standard - 1.1.2 + org.apache.commons + commons-lang3 + 3.4 @@ -615,10 +544,17 @@ commons-io 2.2 + - mysql - mysql-connector-java - 5.1.34 + commons-collections + commons-collections + 3.2.2 + + + + commons-logging + commons-logging + 1.2 @@ -628,75 +564,49 @@ - org.apache.derby - derby - 10.10.1.1 - - - - cglib - cglib-nodep - 2.1 - - - org.apache.httpcomponents - httpasyncclient - 4.1.3 - - - net.jcip - jcip-annotations - 1.0 - - - org.codehaus.jackson - jackson-mapper-lgpl - 1.9.6 - - - - - - - org.apache.mina - mina-core - 2.0.0-RC1 - - - com.google.guava - guava - 19.0 - - - org.javatuples - javatuples + commons-cli + commons-cli 1.2 + + - org.apache.velocity - velocity - 1.7 + org.slf4j + slf4j-api + 1.7.7 + - org.apache.velocity - velocity-tools - 2.0 - - - commons-logging - commons-logging - - - commons-digester - commons-digester - - + ch.qos.logback + logback-classic + 1.2.3 + + + ch.qos.logback + logback-core + 1.2.3 + + + + org.apache.logging.log4j + log4j-core + 2.10.0 + + + + org.apache.logging.log4j + log4j-slf4j-impl + 2.10.0 + + + org.apache.httpcomponents httpcore 4.4.1 + org.apache.httpcomponents httpclient @@ -708,7 +618,87 @@ - + + + org.apache.httpcomponents + httpasyncclient + 4.1.3 + + + + com.ning + async-http-client + 1.7.17 + + + + + mysql + mysql-connector-java + 5.1.34 + + + + org.apache.derby + derby + 10.10.1.1 + + + + + cglib + cglib-nodep + 2.1 + + + + net.jcip + jcip-annotations + 1.0 + + + + org.codehaus.jackson + jackson-mapper-lgpl + 1.9.6 + + + + org.codehaus.jackson + jackson-core-asl + 1.9.10 + + + + com.github.spotbugs + spotbugs-annotations + 3.1.3 + + + + io.netty + netty-all + 4.0.42.Final + + + + org.apache.mina + mina-core + 2.0.0-RC1 + + + + com.google.guava + guava + 19.0 + + + + org.javatuples + javatuples + 1.2 + + diff --git a/test/pom.xml b/test/pom.xml index ffffc016d..e65e57569 100644 --- a/test/pom.xml +++ b/test/pom.xml @@ -12,97 +12,93 @@ limitations under the License. --> - - com.alibaba.nacos - nacos-all - 0.2.2-SNAPSHOT - ../pom.xml - - 4.0.0 + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + com.alibaba.nacos + nacos-all + 0.2.2-SNAPSHOT + ../pom.xml + + 4.0.0 - nacos-test - jar + nacos-test + jar - nacos-test ${project.version} - http://maven.apache.org + nacos-test ${project.version} + http://maven.apache.org - - UTF-8 - + + UTF-8 + - - - log4j - log4j - + - - org.slf4j - slf4j-api - - - ch.qos.logback - logback-classic - - - ch.qos.logback - logback-core - + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + ch.qos.logback + logback-core + - - com.google.truth - truth - 0.30 - + + com.google.truth + truth + 0.30 + - - ${project.groupId} - nacos-client - - - ${project.groupId} - nacos-config - - - ${project.groupId} - nacos-naming - - - ${project.groupId} - nacos-core - + + ${project.groupId} + nacos-client + + + ${project.groupId} + nacos-config + + + ${project.groupId} + nacos-naming + + + ${project.groupId} + nacos-core + - - junit - junit - test - + + junit + junit + test + - - org.springframework - spring-test - test - + + org.springframework + spring-test + test + - - org.springframework.boot - spring-boot-test - test - - + + org.springframework.boot + spring-boot-test + test + + - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.9 - - -Dnacos.standalone=true - - - - + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.9 + + -Dnacos.standalone=true + + + + From c0a25c148a97027a5704c374d4d0853a73be0f1f Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Mon, 1 Oct 2018 22:54:37 +0800 Subject: [PATCH 13/30] Polish alibaba/nacos#105 --- .../{SystemUtil.java => SystemUtils.java} | 13 +- .../ClusterDataSourceConfiguration.java | 2 +- .../NacosConfigConfiguration.java | 29 ++ .../server/controller/ConfigServletInner.java | 13 +- .../{WebFilter.java => NacosWebFilter.java} | 5 +- .../service/BasicDataSourceServiceImpl.java | 4 +- .../config/server/service/ConfigService.java | 22 +- .../server/service/DynamicDataSource.java | 5 +- .../service/LocalDataSourceServiceImpl.java | 5 +- .../server/service/ServerListService.java | 3 +- .../capacity/GroupCapacityPersistService.java | 4 +- .../TenantCapacityPersistService.java | 4 +- .../server/service/dump/DumpService.java | 3 +- .../config/server/utils/PaginationHelper.java | 12 +- .../config/server/utils/PropertyUtil.java | 393 +++++++++--------- .../nacos/naming/misc/NamingProxy.java | 11 +- .../nacos/naming/misc/UtilsAndCommons.java | 2 - .../alibaba/nacos/naming/raft/PeerSet.java | 9 +- .../alibaba/nacos/naming/raft/RaftCore.java | 4 +- .../alibaba/nacos/naming/web/ApiCommands.java | 14 +- 20 files changed, 297 insertions(+), 260 deletions(-) rename common/src/main/java/com/alibaba/nacos/common/util/{SystemUtil.java => SystemUtils.java} (91%) create mode 100644 config/src/main/java/com/alibaba/nacos/config/server/configuration/NacosConfigConfiguration.java rename config/src/main/java/com/alibaba/nacos/config/server/filter/{WebFilter.java => NacosWebFilter.java} (93%) diff --git a/common/src/main/java/com/alibaba/nacos/common/util/SystemUtil.java b/common/src/main/java/com/alibaba/nacos/common/util/SystemUtils.java similarity index 91% rename from common/src/main/java/com/alibaba/nacos/common/util/SystemUtil.java rename to common/src/main/java/com/alibaba/nacos/common/util/SystemUtils.java index 54f2f9181..49a964226 100644 --- a/common/src/main/java/com/alibaba/nacos/common/util/SystemUtil.java +++ b/common/src/main/java/com/alibaba/nacos/common/util/SystemUtils.java @@ -16,18 +16,23 @@ package com.alibaba.nacos.common.util; +import com.sun.management.OperatingSystemMXBean; +import org.apache.commons.lang3.StringUtils; + import java.lang.management.ManagementFactory; -import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import org.apache.commons.lang3.StringUtils; -import com.sun.management.OperatingSystemMXBean; /** * @author nacos */ -public class SystemUtil { +public class SystemUtils { + + /** + * Standalone mode or not + */ + public static final boolean STANDALONE_MODE = Boolean.getBoolean("nacos.standalone"); private static OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(); diff --git a/config/src/main/java/com/alibaba/nacos/config/server/configuration/ClusterDataSourceConfiguration.java b/config/src/main/java/com/alibaba/nacos/config/server/configuration/ClusterDataSourceConfiguration.java index c4e44cde1..c4a42d710 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/configuration/ClusterDataSourceConfiguration.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/configuration/ClusterDataSourceConfiguration.java @@ -104,7 +104,7 @@ // * 事务的超时时间需要与普通操作区分开 // */ // tjt.setTimeout(TRANSACTION_QUERY_TIMEOUT); -// if (!PropertyUtil.isStandaloneMode()) { +// if (!STANDALONE_MODE) { // try { // reload(); // } catch (IOException e) { diff --git a/config/src/main/java/com/alibaba/nacos/config/server/configuration/NacosConfigConfiguration.java b/config/src/main/java/com/alibaba/nacos/config/server/configuration/NacosConfigConfiguration.java new file mode 100644 index 000000000..383379b0a --- /dev/null +++ b/config/src/main/java/com/alibaba/nacos/config/server/configuration/NacosConfigConfiguration.java @@ -0,0 +1,29 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.nacos.config.server.configuration; + +import org.springframework.context.annotation.Configuration; + +/** + * Nacos Config {@link Configuration} includes required Spring components. + * + * @author Mercy + * @since 0.2.2 + */ +@Configuration +public class NacosConfigConfiguration { +} diff --git a/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigServletInner.java b/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigServletInner.java index 1d4782bd0..cd8883eba 100755 --- a/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigServletInner.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigServletInner.java @@ -41,6 +41,7 @@ import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; +import static com.alibaba.nacos.common.util.SystemUtils.STANDALONE_MODE; import static com.alibaba.nacos.config.server.utils.LogUtil.pullLog; /** @@ -133,7 +134,7 @@ public class ConfigServletInner { if (isBeta) { md5 = cacheItem.getMd54Beta(); lastModified = cacheItem.getLastModifiedTs4Beta(); - if (PropertyUtil.isStandaloneMode()) { + if (STANDALONE_MODE) { configInfoBase = persistService.findConfigInfo4Beta(dataId, group,tenant); } else { file = DiskUtil.targetBetaFile(dataId, group, tenant); @@ -150,7 +151,7 @@ public class ConfigServletInner { lastModified = cacheItem.tagLastModifiedTs.get(autoTag); } } - if (PropertyUtil.isStandaloneMode()) { + if (STANDALONE_MODE) { configInfoBase = persistService.findConfigInfo4Tag(dataId, group, tenant, autoTag); } else { file = DiskUtil.targetTagFile(dataId, group, tenant, autoTag); @@ -161,7 +162,7 @@ public class ConfigServletInner { } else { md5 = cacheItem.getMd5(); lastModified = cacheItem.getLastModifiedTs(); - if (PropertyUtil.isStandaloneMode()) { + if (STANDALONE_MODE) { configInfoBase = persistService.findConfigInfo(dataId, group, tenant); } else { file = DiskUtil.targetFile(dataId, group, tenant); @@ -193,7 +194,7 @@ public class ConfigServletInner { } } } - if (PropertyUtil.isStandaloneMode()) { + if (STANDALONE_MODE) { configInfoBase = persistService.findConfigInfo4Tag(dataId, group, tenant, tag); } else { file = DiskUtil.targetTagFile(dataId, group, tenant, tag); @@ -222,7 +223,7 @@ public class ConfigServletInner { response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache,no-store"); - if (PropertyUtil.isStandaloneMode()) { + if (STANDALONE_MODE) { response.setDateHeader("Last-Modified", lastModified); } else { fis = new FileInputStream(file); @@ -230,7 +231,7 @@ public class ConfigServletInner { } - if (PropertyUtil.isStandaloneMode()) { + if (STANDALONE_MODE) { out = response.getWriter(); out.print(configInfoBase.getContent()); out.flush(); diff --git a/config/src/main/java/com/alibaba/nacos/config/server/filter/WebFilter.java b/config/src/main/java/com/alibaba/nacos/config/server/filter/NacosWebFilter.java similarity index 93% rename from config/src/main/java/com/alibaba/nacos/config/server/filter/WebFilter.java rename to config/src/main/java/com/alibaba/nacos/config/server/filter/NacosWebFilter.java index 60539714a..86a882ac4 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/filter/WebFilter.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/filter/NacosWebFilter.java @@ -19,6 +19,7 @@ import com.alibaba.nacos.config.server.constant.Constants; import org.springframework.core.annotation.Order; import javax.servlet.*; +import javax.servlet.annotation.WebFilter; import java.io.IOException; import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog; @@ -30,8 +31,8 @@ import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog; * */ @Order(1) -@javax.servlet.annotation.WebFilter(filterName = "webFilter", urlPatterns = "/*") -public class WebFilter implements Filter { +@WebFilter(filterName = "webFilter", urlPatterns = "/*") +public class NacosWebFilter implements Filter { static private String webRootPath; diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/BasicDataSourceServiceImpl.java b/config/src/main/java/com/alibaba/nacos/config/server/service/BasicDataSourceServiceImpl.java index f004580af..a5ef71ecb 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/BasicDataSourceServiceImpl.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/BasicDataSourceServiceImpl.java @@ -15,7 +15,6 @@ */ package com.alibaba.nacos.config.server.service; -import com.alibaba.nacos.config.server.utils.PropertyUtil; import org.apache.commons.dbcp.BasicDataSource; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; @@ -37,6 +36,7 @@ import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; +import static com.alibaba.nacos.common.util.SystemUtils.STANDALONE_MODE; import static com.alibaba.nacos.config.server.service.PersistService.CONFIG_INFO4BETA_ROW_MAPPER; import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog; import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog; @@ -105,7 +105,7 @@ public class BasicDataSourceServiceImpl implements DataSourceService { * 事务的超时时间需要与普通操作区分开 */ tjt.setTimeout(TRANSACTION_QUERY_TIMEOUT); - if (!PropertyUtil.isStandaloneMode()) { + if (!STANDALONE_MODE) { try { reload(); } catch (IOException e) { diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigService.java index 95f209ab8..3b5c6178d 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigService.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigService.java @@ -21,7 +21,6 @@ import com.alibaba.nacos.config.server.model.ConfigInfoBase; import com.alibaba.nacos.config.server.utils.GroupKey; import com.alibaba.nacos.config.server.utils.GroupKey2; import com.alibaba.nacos.config.server.utils.MD5; -import com.alibaba.nacos.config.server.utils.PropertyUtil; import com.alibaba.nacos.config.server.utils.event.EventDispatcher; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; @@ -33,6 +32,7 @@ import java.util.*; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; +import static com.alibaba.nacos.common.util.SystemUtils.STANDALONE_MODE; import static com.alibaba.nacos.config.server.utils.LogUtil.*; /** @@ -74,7 +74,7 @@ public class ConfigService { "[dump-ignore] ignore to save cache file. groupKey={}, md5={}, lastModifiedOld={}, " + "lastModifiedNew={}", groupKey, md5, ConfigService.getLastModifiedTs(groupKey), lastModifiedTs); - } else if (!PropertyUtil.isStandaloneMode()) { + } else if (!STANDALONE_MODE) { DiskUtil.saveToDisk(dataId, group, tenant, content); } updateMd5(groupKey, md5, lastModifiedTs); @@ -118,7 +118,7 @@ public class ConfigService { "[dump-beta-ignore] ignore to save cache file. groupKey={}, md5={}, lastModifiedOld={}, " + "lastModifiedNew={}", groupKey, md5, ConfigService.getLastModifiedTs(groupKey), lastModifiedTs); - } else if (!PropertyUtil.isStandaloneMode()) { + } else if (!STANDALONE_MODE) { DiskUtil.saveBetaToDisk(dataId, group, tenant, content); } String[] betaIpsArr = betaIps.split(","); @@ -156,7 +156,7 @@ public class ConfigService { "[dump-tag-ignore] ignore to save cache file. groupKey={}, md5={}, lastModifiedOld={}, " + "lastModifiedNew={}", groupKey, md5, ConfigService.getLastModifiedTs(groupKey), lastModifiedTs); - } else if (!PropertyUtil.isStandaloneMode()) { + } else if (!STANDALONE_MODE) { DiskUtil.saveTagToDisk(dataId, group, tenant, tag, content); } @@ -188,7 +188,7 @@ public class ConfigService { try { final String md5 = MD5.getInstance().getMD5String(content); - if (!PropertyUtil.isStandaloneMode()) { + if (!STANDALONE_MODE) { String loacalMd5 = DiskUtil.getLocalConfigMd5(dataId, group, tenant); if(md5.equals(loacalMd5)) { dumpLog.warn( @@ -214,7 +214,7 @@ public class ConfigService { { String aggreds = null; try { - if (PropertyUtil.isStandaloneMode()) { + if (STANDALONE_MODE) { ConfigInfoBase config = persistService.findConfigInfoBase(AggrWhitelist.AGGRIDS_METADATA, "DEFAULT_GROUP"); if (config != null) { aggreds = config.getContent(); @@ -232,7 +232,7 @@ public class ConfigService { String clientIpWhitelist = null; try { - if (PropertyUtil.isStandaloneMode()) { + if (STANDALONE_MODE) { ConfigInfoBase config = persistService.findConfigInfoBase(ClientIpWhiteList.CLIENT_IP_WHITELIST_METADATA, "DEFAULT_GROUP"); if (config != null) { clientIpWhitelist = config.getContent(); @@ -251,7 +251,7 @@ public class ConfigService { String switchContent= null; try { - if (PropertyUtil.isStandaloneMode()) { + if (STANDALONE_MODE) { ConfigInfoBase config = persistService.findConfigInfoBase(SwitchService.SWITCH_META_DATAID, "DEFAULT_GROUP"); if (config != null) { switchContent = config.getContent(); @@ -318,7 +318,7 @@ public class ConfigService { } try { - if (!PropertyUtil.isStandaloneMode()) { + if (!STANDALONE_MODE) { DiskUtil.removeConfigInfo(dataId, group, tenant); } CACHE.remove(groupKey); @@ -351,7 +351,7 @@ public class ConfigService { } try { - if (!PropertyUtil.isStandaloneMode()) { + if (!STANDALONE_MODE) { DiskUtil.removeConfigInfo4Beta(dataId, group, tenant); } EventDispatcher.fireEvent(new LocalDataChangeEvent(groupKey, true, CACHE.get(groupKey).getIps4Beta())); @@ -386,7 +386,7 @@ public class ConfigService { } try { - if (!PropertyUtil.isStandaloneMode()) { + if (!STANDALONE_MODE) { DiskUtil.removeConfigInfo4Tag(dataId, group, tenant, tag); } diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/DynamicDataSource.java b/config/src/main/java/com/alibaba/nacos/config/server/service/DynamicDataSource.java index b720aaf3e..74d0593f9 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/DynamicDataSource.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/DynamicDataSource.java @@ -15,11 +15,12 @@ */ package com.alibaba.nacos.config.server.service; -import com.alibaba.nacos.config.server.utils.PropertyUtil; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; +import static com.alibaba.nacos.common.util.SystemUtils.STANDALONE_MODE; + /** * datasource adapter * @author Nacos @@ -40,7 +41,7 @@ public class DynamicDataSource implements ApplicationContextAware { public DataSourceService getDataSource() { DataSourceService dataSourceService = null; - if (PropertyUtil.isStandaloneMode()) { + if (STANDALONE_MODE) { dataSourceService = (DataSourceService)applicationContext.getBean("localDataSourceService"); } else { dataSourceService = (DataSourceService)applicationContext.getBean("basicDataSourceService"); diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/LocalDataSourceServiceImpl.java b/config/src/main/java/com/alibaba/nacos/config/server/service/LocalDataSourceServiceImpl.java index f12008b44..abc105de5 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/LocalDataSourceServiceImpl.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/LocalDataSourceServiceImpl.java @@ -17,7 +17,6 @@ package com.alibaba.nacos.config.server.service; import com.alibaba.nacos.config.server.constant.Constants; import com.alibaba.nacos.config.server.utils.LogUtil; -import com.alibaba.nacos.config.server.utils.PropertyUtil; import com.alibaba.nacos.config.server.utils.StringUtils; import org.apache.commons.dbcp.BasicDataSource; import org.slf4j.Logger; @@ -39,6 +38,8 @@ import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; +import static com.alibaba.nacos.common.util.SystemUtils.STANDALONE_MODE; + /** * local data source * @@ -88,7 +89,7 @@ public class LocalDataSourceServiceImpl implements DataSourceService { tm.setDataSource(ds); tjt.setTimeout(5000); - if (PropertyUtil.isStandaloneMode()) { + if (STANDALONE_MODE) { reload(); } } diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/ServerListService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/ServerListService.java index cff097f9e..49c0f26cf 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/ServerListService.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/ServerListService.java @@ -47,6 +47,7 @@ import java.util.*; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; +import static com.alibaba.nacos.common.util.SystemUtils.STANDALONE_MODE; import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog; import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog; @@ -240,7 +241,7 @@ public class ServerListService implements ApplicationListener getCapacityList4CorrectUsage(long lastId, int pageSize) { String sql = "select id, group_id from group_capacity where id>? limit ?"; - if (PropertyUtil.isStandaloneMode()) { + if (STANDALONE_MODE) { sql = "select id, group_id from group_capacity where id>? OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY"; } try { diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/capacity/TenantCapacityPersistService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/capacity/TenantCapacityPersistService.java index a435e9746..01c3b06bc 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/capacity/TenantCapacityPersistService.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/capacity/TenantCapacityPersistService.java @@ -18,7 +18,6 @@ package com.alibaba.nacos.config.server.service.capacity; import com.alibaba.nacos.config.server.model.capacity.TenantCapacity; import com.alibaba.nacos.config.server.service.DataSourceService; import com.alibaba.nacos.config.server.service.DynamicDataSource; -import com.alibaba.nacos.config.server.utils.PropertyUtil; import com.alibaba.nacos.config.server.utils.TimeUtils; import com.google.common.collect.Lists; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; @@ -34,6 +33,7 @@ import javax.annotation.PostConstruct; import java.sql.*; import java.util.List; +import static com.alibaba.nacos.common.util.SystemUtils.STANDALONE_MODE; import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog; /** @@ -229,7 +229,7 @@ public class TenantCapacityPersistService { public List getCapacityList4CorrectUsage(long lastId, int pageSize) { String sql = "select id, tenant_id from tenant_capacity where id>? limit ?"; - if (PropertyUtil.isStandaloneMode()) { + if (STANDALONE_MODE) { sql = "select id, tenant_id from tenant_capacity where id>? OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY"; } diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/dump/DumpService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/dump/DumpService.java index 87a385b5f..40f770088 100755 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/dump/DumpService.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/dump/DumpService.java @@ -46,6 +46,7 @@ import java.util.Random; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import static com.alibaba.nacos.common.util.SystemUtils.STANDALONE_MODE; import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog; /** @@ -152,7 +153,7 @@ public class DumpService { throw new RuntimeException( "Nacos Server did not start because dumpservice bean construction failure :\n" + e.getMessage()); } - if (!PropertyUtil.isStandaloneMode()) { + if (!STANDALONE_MODE) { Runnable heartbeat = new Runnable() { @Override public void run() { diff --git a/config/src/main/java/com/alibaba/nacos/config/server/utils/PaginationHelper.java b/config/src/main/java/com/alibaba/nacos/config/server/utils/PaginationHelper.java index a4b42554b..7a96a2f1d 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/utils/PaginationHelper.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/utils/PaginationHelper.java @@ -21,6 +21,8 @@ import org.springframework.jdbc.core.RowMapper; import java.util.List; +import static com.alibaba.nacos.common.util.SystemUtils.STANDALONE_MODE; + /** * 分页辅助类 @@ -87,7 +89,7 @@ public class PaginationHelper { final int startRow = (pageNo - 1) * pageSize; String selectSQL = ""; - if (PropertyUtil.isStandaloneMode()) { + if (STANDALONE_MODE) { selectSQL = sqlFetchRows + " OFFSET "+startRow+" ROWS FETCH NEXT "+pageSize+" ROWS ONLY"; } else if (lastMaxId != null) { selectSQL = sqlFetchRows + " and id > " + lastMaxId + " order by id asc" + " limit " + 0 + "," + pageSize; @@ -131,7 +133,7 @@ public class PaginationHelper { } String selectSQL = sqlFetchRows; - if (PropertyUtil.isStandaloneMode()) { + if (STANDALONE_MODE) { selectSQL = selectSQL.replaceAll("(?i)LIMIT \\?,\\?", "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"); } @@ -171,7 +173,7 @@ public class PaginationHelper { } String selectSQL = sqlFetchRows; - if (PropertyUtil.isStandaloneMode()) { + if (STANDALONE_MODE) { selectSQL = selectSQL.replaceAll("(?i)LIMIT \\?,\\?", "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"); } @@ -191,7 +193,7 @@ public class PaginationHelper { final Page page = new Page(); String selectSQL = sqlFetchRows; - if (PropertyUtil.isStandaloneMode()) { + if (STANDALONE_MODE) { selectSQL = selectSQL.replaceAll("(?i)LIMIT \\?,\\?", "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"); } @@ -205,7 +207,7 @@ public class PaginationHelper { public void updateLimit(final JdbcTemplate jt, final String sql, final Object args[]) { String sqlUpdate = sql; - if (PropertyUtil.isStandaloneMode()) { + if (STANDALONE_MODE) { sqlUpdate = sqlUpdate.replaceAll("limit \\?", "OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY"); } diff --git a/config/src/main/java/com/alibaba/nacos/config/server/utils/PropertyUtil.java b/config/src/main/java/com/alibaba/nacos/config/server/utils/PropertyUtil.java index e2507aac9..d588ddbc8 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/utils/PropertyUtil.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/utils/PropertyUtil.java @@ -22,255 +22,246 @@ import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; +import static com.alibaba.nacos.common.util.SystemUtils.STANDALONE_MODE; + /** * properties utils - * - * @author Nacos * + * @author Nacos */ @Component public class PropertyUtil { - private final static Logger logger = LogUtil.defaultLog; - - private static int notifyConnectTimeout = 100; - private static int notifySocketTimeout = 200; - private static int maxHealthCheckFailCount = 12; - private static boolean isHealthCheck = true; - private static int maxContent = 10 * 1024 * 1024; + private final static Logger logger = LogUtil.defaultLog; - /** - * 是否开启容量管理 - */ - private static boolean isManageCapacity = true; - /** - * 是否开启容量管理的限制检验功能,包括配置个数上限、配置内容大小限制等 - */ - private static boolean isCapacityLimitCheck = false; - /** - * 集群默认容量上限 - */ - private static int defaultClusterQuota = 100000; - /** - * 每个Group默认容量上限 - */ - private static int defaultGroupQuota = 200; - /** - * 每个Tenant默认容量上限 - */ - private static int defaultTenantQuota = 200; - /** - * 单个配置中content的最大大小,单位为字节 - */ - private static int defaultMaxSize = 100 * 1024; - /** - * 聚合数据子配置最大个数 - */ - private static int defaultMaxAggrCount = 10000; - /** - * 聚合数据单个子配置中content的最大大小,单位为字节 - */ - private static int defaultMaxAggrSize = 1024; - /** - * 初始化容量信息记录时,发现已经到达限额时的扩容百分比 - */ - private static int initialExpansionPercent = 100; - /** - * 修正容量信息表使用量(usage)的时间间隔,单位为秒 - */ - private static int correctUsageDelay = 10 * 60; + private static int notifyConnectTimeout = 100; + private static int notifySocketTimeout = 200; + private static int maxHealthCheckFailCount = 12; + private static boolean isHealthCheck = true; + private static int maxContent = 10 * 1024 * 1024; - private static boolean standaloneMode = false; + /** + * 是否开启容量管理 + */ + private static boolean isManageCapacity = true; + /** + * 是否开启容量管理的限制检验功能,包括配置个数上限、配置内容大小限制等 + */ + private static boolean isCapacityLimitCheck = false; + /** + * 集群默认容量上限 + */ + private static int defaultClusterQuota = 100000; + /** + * 每个Group默认容量上限 + */ + private static int defaultGroupQuota = 200; + /** + * 每个Tenant默认容量上限 + */ + private static int defaultTenantQuota = 200; + /** + * 单个配置中content的最大大小,单位为字节 + */ + private static int defaultMaxSize = 100 * 1024; + /** + * 聚合数据子配置最大个数 + */ + private static int defaultMaxAggrCount = 10000; + /** + * 聚合数据单个子配置中content的最大大小,单位为字节 + */ + private static int defaultMaxAggrSize = 1024; + /** + * 初始化容量信息记录时,发现已经到达限额时的扩容百分比 + */ + private static int initialExpansionPercent = 100; + /** + * 修正容量信息表使用量(usage)的时间间隔,单位为秒 + */ + private static int correctUsageDelay = 10 * 60; - @Autowired - private Environment env; + @Autowired + private Environment env; - static { - setStandaloneMode(Boolean.parseBoolean(System.getProperty("nacos.standalone", "false"))); - } + @PostConstruct + public void init() { + try { - @PostConstruct - public void init() { - try { + setNotifyConnectTimeout(Integer.parseInt(env.getProperty("notifyConnectTimeout", "100"))); + logger.info("notifyConnectTimeout:{}", notifyConnectTimeout); + setNotifySocketTimeout(Integer.parseInt(env.getProperty("notifySocketTimeout", "200"))); + logger.info("notifySocketTimeout:{}", notifySocketTimeout); + setHealthCheck(Boolean.valueOf(env.getProperty("isHealthCheck", "true"))); + logger.info("isHealthCheck:{}", isHealthCheck); + setMaxHealthCheckFailCount(Integer.parseInt(env.getProperty("maxHealthCheckFailCount", "12"))); + logger.info("maxHealthCheckFailCount:{}", maxHealthCheckFailCount); + setMaxContent(Integer.parseInt(env.getProperty("maxContent", String.valueOf(maxContent)))); + logger.info("maxContent:{}", maxContent); + // 容量管理 + setManageCapacity(getBoolean("isManageCapacity", isManageCapacity)); + setCapacityLimitCheck(getBoolean("isCapacityLimitCheck", isCapacityLimitCheck)); + setDefaultClusterQuota(getInt("defaultClusterQuota", defaultClusterQuota)); + setDefaultGroupQuota(getInt("defaultGroupQuota", defaultGroupQuota)); + setDefaultTenantQuota(getInt("defaultTenantQuota", defaultTenantQuota)); + setDefaultMaxSize(getInt("defaultMaxSize", defaultMaxSize)); + setDefaultMaxAggrCount(getInt("defaultMaxAggrCount", defaultMaxAggrCount)); + setDefaultMaxAggrSize(getInt("defaultMaxAggrSize", defaultMaxAggrSize)); + setCorrectUsageDelay(getInt("correctUsageDelay", correctUsageDelay)); + setInitialExpansionPercent(getInt("initialExpansionPercent", initialExpansionPercent)); - setNotifyConnectTimeout(Integer.parseInt(env.getProperty("notifyConnectTimeout", "100"))); - logger.info("notifyConnectTimeout:{}", notifyConnectTimeout); - setNotifySocketTimeout(Integer.parseInt(env.getProperty("notifySocketTimeout", "200"))); - logger.info("notifySocketTimeout:{}", notifySocketTimeout); - setHealthCheck(Boolean.valueOf(env.getProperty("isHealthCheck", "true"))); - logger.info("isHealthCheck:{}", isHealthCheck); - setMaxHealthCheckFailCount(Integer.parseInt(env.getProperty("maxHealthCheckFailCount", "12"))); - logger.info("maxHealthCheckFailCount:{}", maxHealthCheckFailCount); - setMaxContent(Integer.parseInt(env.getProperty("maxContent", String.valueOf(maxContent)))); - logger.info("maxContent:{}", maxContent); - // 容量管理 - setManageCapacity(getBoolean("isManageCapacity", isManageCapacity)); - setCapacityLimitCheck(getBoolean("isCapacityLimitCheck", isCapacityLimitCheck)); - setDefaultClusterQuota(getInt("defaultClusterQuota", defaultClusterQuota)); - setDefaultGroupQuota(getInt("defaultGroupQuota", defaultGroupQuota)); - setDefaultTenantQuota(getInt("defaultTenantQuota", defaultTenantQuota)); - setDefaultMaxSize(getInt("defaultMaxSize", defaultMaxSize)); - setDefaultMaxAggrCount(getInt("defaultMaxAggrCount", defaultMaxAggrCount)); - setDefaultMaxAggrSize(getInt("defaultMaxAggrSize", defaultMaxAggrSize)); - setCorrectUsageDelay(getInt("correctUsageDelay", correctUsageDelay)); - setInitialExpansionPercent(getInt("initialExpansionPercent", initialExpansionPercent)); - - } catch (Exception e) { - logger.error("read application.properties failed", e); - } - } + } catch (Exception e) { + logger.error("read application.properties failed", e); + } + } - public static int getNotifyConnectTimeout() { - return notifyConnectTimeout; - } + public static int getNotifyConnectTimeout() { + return notifyConnectTimeout; + } - public static int getNotifySocketTimeout() { - return notifySocketTimeout; - } + public static int getNotifySocketTimeout() { + return notifySocketTimeout; + } - public static int getMaxHealthCheckFailCount() { - return maxHealthCheckFailCount; - } + public static int getMaxHealthCheckFailCount() { + return maxHealthCheckFailCount; + } - public static boolean isHealthCheck() { - return isHealthCheck; - } + public static boolean isHealthCheck() { + return isHealthCheck; + } - private boolean getBoolean(String key, boolean defaultValue) { - return Boolean.valueOf(getString(key, String.valueOf(defaultValue))); - } + private boolean getBoolean(String key, boolean defaultValue) { + return Boolean.valueOf(getString(key, String.valueOf(defaultValue))); + } - private int getInt(String key, int defaultValue) { - return Integer.parseInt(getString(key, String.valueOf(defaultValue))); - } + private int getInt(String key, int defaultValue) { + return Integer.parseInt(getString(key, String.valueOf(defaultValue))); + } - private String getString(String key, String defaultValue) { - String value = env.getProperty(key); - if (value == null) { - return defaultValue; - } - logger.info("{}:{}", key, value); - return value; - } + private String getString(String key, String defaultValue) { + String value = env.getProperty(key); + if (value == null) { + return defaultValue; + } + logger.info("{}:{}", key, value); + return value; + } - public String getProperty(String key) { - return env.getProperty(key); - } + public String getProperty(String key) { + return env.getProperty(key); + } - public String getProperty(String key, String defaultValue) { - return env.getProperty(key, defaultValue); - } + public String getProperty(String key, String defaultValue) { + return env.getProperty(key, defaultValue); + } - public static int getMaxContent() { - return maxContent; - } + public static int getMaxContent() { + return maxContent; + } - public static boolean isManageCapacity() { - return isManageCapacity; - } + public static boolean isManageCapacity() { + return isManageCapacity; + } - public static int getDefaultClusterQuota() { - return defaultClusterQuota; - } + public static int getDefaultClusterQuota() { + return defaultClusterQuota; + } - public static boolean isCapacityLimitCheck() { - return isCapacityLimitCheck; - } + public static boolean isCapacityLimitCheck() { + return isCapacityLimitCheck; + } - public static int getDefaultGroupQuota() { - return defaultGroupQuota; - } + public static int getDefaultGroupQuota() { + return defaultGroupQuota; + } - public static int getDefaultTenantQuota() { - return defaultTenantQuota; - } + public static int getDefaultTenantQuota() { + return defaultTenantQuota; + } - public static int getInitialExpansionPercent() { - return initialExpansionPercent; - } + public static int getInitialExpansionPercent() { + return initialExpansionPercent; + } - public static int getDefaultMaxSize() { - return defaultMaxSize; - } + public static int getDefaultMaxSize() { + return defaultMaxSize; + } - public static int getDefaultMaxAggrCount() { - return defaultMaxAggrCount; - } + public static int getDefaultMaxAggrCount() { + return defaultMaxAggrCount; + } - public static int getDefaultMaxAggrSize() { - return defaultMaxAggrSize; - } + public static int getDefaultMaxAggrSize() { + return defaultMaxAggrSize; + } - public static int getCorrectUsageDelay() { - return correctUsageDelay; - } + public static int getCorrectUsageDelay() { + return correctUsageDelay; + } - public static boolean isStandaloneMode() { - return standaloneMode; - } + public static boolean isStandaloneMode() { + return STANDALONE_MODE; + } - public static void setStandaloneMode(boolean standaloneMode) { - PropertyUtil.standaloneMode = standaloneMode; - } + public static void setNotifyConnectTimeout(int notifyConnectTimeout) { + PropertyUtil.notifyConnectTimeout = notifyConnectTimeout; + } - public static void setNotifyConnectTimeout(int notifyConnectTimeout) { - PropertyUtil.notifyConnectTimeout = notifyConnectTimeout; - } + public static void setNotifySocketTimeout(int notifySocketTimeout) { + PropertyUtil.notifySocketTimeout = notifySocketTimeout; + } - public static void setNotifySocketTimeout(int notifySocketTimeout) { - PropertyUtil.notifySocketTimeout = notifySocketTimeout; - } + public static void setMaxHealthCheckFailCount(int maxHealthCheckFailCount) { + PropertyUtil.maxHealthCheckFailCount = maxHealthCheckFailCount; + } - public static void setMaxHealthCheckFailCount(int maxHealthCheckFailCount) { - PropertyUtil.maxHealthCheckFailCount = maxHealthCheckFailCount; - } + public static void setHealthCheck(boolean isHealthCheck) { + PropertyUtil.isHealthCheck = isHealthCheck; + } - public static void setHealthCheck(boolean isHealthCheck) { - PropertyUtil.isHealthCheck = isHealthCheck; - } + public static void setMaxContent(int maxContent) { + PropertyUtil.maxContent = maxContent; + } - public static void setMaxContent(int maxContent) { - PropertyUtil.maxContent = maxContent; - } + public static void setManageCapacity(boolean isManageCapacity) { + PropertyUtil.isManageCapacity = isManageCapacity; + } - public static void setManageCapacity(boolean isManageCapacity) { - PropertyUtil.isManageCapacity = isManageCapacity; - } + public static void setCapacityLimitCheck(boolean isCapacityLimitCheck) { + PropertyUtil.isCapacityLimitCheck = isCapacityLimitCheck; + } - public static void setCapacityLimitCheck(boolean isCapacityLimitCheck) { - PropertyUtil.isCapacityLimitCheck = isCapacityLimitCheck; - } + public static void setDefaultClusterQuota(int defaultClusterQuota) { + PropertyUtil.defaultClusterQuota = defaultClusterQuota; + } - public static void setDefaultClusterQuota(int defaultClusterQuota) { - PropertyUtil.defaultClusterQuota = defaultClusterQuota; - } + public static void setDefaultGroupQuota(int defaultGroupQuota) { + PropertyUtil.defaultGroupQuota = defaultGroupQuota; + } - public static void setDefaultGroupQuota(int defaultGroupQuota) { - PropertyUtil.defaultGroupQuota = defaultGroupQuota; - } + public static void setDefaultTenantQuota(int defaultTenantQuota) { + PropertyUtil.defaultTenantQuota = defaultTenantQuota; + } - public static void setDefaultTenantQuota(int defaultTenantQuota) { - PropertyUtil.defaultTenantQuota = defaultTenantQuota; - } + public static void setDefaultMaxSize(int defaultMaxSize) { + PropertyUtil.defaultMaxSize = defaultMaxSize; + } - public static void setDefaultMaxSize(int defaultMaxSize) { - PropertyUtil.defaultMaxSize = defaultMaxSize; - } + public static void setDefaultMaxAggrCount(int defaultMaxAggrCount) { + PropertyUtil.defaultMaxAggrCount = defaultMaxAggrCount; + } - public static void setDefaultMaxAggrCount(int defaultMaxAggrCount) { - PropertyUtil.defaultMaxAggrCount = defaultMaxAggrCount; - } + public static void setDefaultMaxAggrSize(int defaultMaxAggrSize) { + PropertyUtil.defaultMaxAggrSize = defaultMaxAggrSize; + } - public static void setDefaultMaxAggrSize(int defaultMaxAggrSize) { - PropertyUtil.defaultMaxAggrSize = defaultMaxAggrSize; - } + public static void setInitialExpansionPercent(int initialExpansionPercent) { + PropertyUtil.initialExpansionPercent = initialExpansionPercent; + } - public static void setInitialExpansionPercent(int initialExpansionPercent) { - PropertyUtil.initialExpansionPercent = initialExpansionPercent; - } + public static void setCorrectUsageDelay(int correctUsageDelay) { + PropertyUtil.correctUsageDelay = correctUsageDelay; + } - public static void setCorrectUsageDelay(int correctUsageDelay) { - PropertyUtil.correctUsageDelay = correctUsageDelay; - } - } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/misc/NamingProxy.java b/naming/src/main/java/com/alibaba/nacos/naming/misc/NamingProxy.java index 55ac393e9..ee87dd582 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/misc/NamingProxy.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/misc/NamingProxy.java @@ -15,13 +15,12 @@ */ package com.alibaba.nacos.naming.misc; -import com.alibaba.nacos.common.util.SystemUtil; +import com.alibaba.nacos.common.util.SystemUtils; import com.alibaba.nacos.naming.boot.RunningConfig; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; -import java.io.File; import java.io.IOException; import java.net.HttpURLConnection; import java.net.InetAddress; @@ -32,6 +31,8 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; +import static com.alibaba.nacos.common.util.SystemUtils.STANDALONE_MODE; + /** * @author nacos */ @@ -62,7 +63,7 @@ public class NamingProxy { private static String jmenv; public static String getJmenv() { - jmenv = SystemUtil.getSystemEnv("nacos_jmenv_domain"); + jmenv = SystemUtils.getSystemEnv("nacos_jmenv_domain"); if (StringUtils.isEmpty(jmenv)) { jmenv = System.getProperty("com.alibaba.nacos.naming.jmenv", "jmenv.tbsite.net"); @@ -106,7 +107,7 @@ public class NamingProxy { return; } - if (UtilsAndCommons.STANDALONE_MODE) { + if (STANDALONE_MODE) { servers = new ArrayList<>(); servers.add(InetAddress.getLocalHost().getHostAddress() + ":" + RunningConfig.getServerPort()); return; @@ -165,7 +166,7 @@ public class NamingProxy { //use system env if (CollectionUtils.isEmpty(result)) { - result = SystemUtil.getIPsBySystemEnv(UtilsAndCommons.SELF_SERVICE_CLUSTER_ENV); + result = SystemUtils.getIPsBySystemEnv(UtilsAndCommons.SELF_SERVICE_CLUSTER_ENV); Loggers.DEBUG_LOG.debug("REFRESH-SERVER-LIST4: " + result); } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/misc/UtilsAndCommons.java b/naming/src/main/java/com/alibaba/nacos/naming/misc/UtilsAndCommons.java index f0b4b3b70..33f8ce7dd 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/misc/UtilsAndCommons.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/misc/UtilsAndCommons.java @@ -80,8 +80,6 @@ public class UtilsAndCommons { public static final String SELF_SERVICE_CLUSTER_ENV = "naming_self_service_cluster_ips"; - public static final boolean STANDALONE_MODE = Boolean.parseBoolean(System.getProperty("nacos.standalone", "false")); - public static final String CACHE_KEY_SPLITER = "@@@@"; public static final String LOCAL_HOST_IP = "127.0.0.1"; diff --git a/naming/src/main/java/com/alibaba/nacos/naming/raft/PeerSet.java b/naming/src/main/java/com/alibaba/nacos/naming/raft/PeerSet.java index 97af12c79..c67454dfa 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/raft/PeerSet.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/raft/PeerSet.java @@ -19,7 +19,6 @@ import com.alibaba.fastjson.JSON; import com.alibaba.nacos.naming.misc.HttpClient; import com.alibaba.nacos.naming.misc.Loggers; import com.alibaba.nacos.naming.misc.NetUtils; -import com.alibaba.nacos.naming.misc.UtilsAndCommons; import com.ning.http.client.AsyncCompletionHandler; import com.ning.http.client.Response; import org.apache.commons.collections.SortedBag; @@ -30,6 +29,8 @@ import org.apache.commons.lang3.StringUtils; import java.net.HttpURLConnection; import java.util.*; +import static com.alibaba.nacos.common.util.SystemUtils.STANDALONE_MODE; + /** * @author nacos */ @@ -45,7 +46,7 @@ public class PeerSet { } public RaftPeer getLeader() { - if (UtilsAndCommons.STANDALONE_MODE) { + if (STANDALONE_MODE) { return local(); } return leader; @@ -63,7 +64,7 @@ public class PeerSet { peers.put(server, peer); } - if (UtilsAndCommons.STANDALONE_MODE) { + if (STANDALONE_MODE) { RaftPeer local = local(); local.state = RaftPeer.State.LEADER; local.voteFor = NetUtils.localIP(); @@ -83,7 +84,7 @@ public class PeerSet { } public boolean isLeader(String ip) { - if (UtilsAndCommons.STANDALONE_MODE) { + if (STANDALONE_MODE) { return true; } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/raft/RaftCore.java b/naming/src/main/java/com/alibaba/nacos/naming/raft/RaftCore.java index 43af2a0db..76b539dc7 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/raft/RaftCore.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/raft/RaftCore.java @@ -37,6 +37,8 @@ import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.zip.GZIPOutputStream; +import static com.alibaba.nacos.common.util.SystemUtils.STANDALONE_MODE; + /** * @author nacos */ @@ -525,7 +527,7 @@ public class RaftCore { public static void sendBeat() throws IOException, InterruptedException { RaftPeer local = peers.local(); - if (local.state != RaftPeer.State.LEADER && !UtilsAndCommons.STANDALONE_MODE) { + if (local.state != RaftPeer.State.LEADER && !STANDALONE_MODE) { return; } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/web/ApiCommands.java b/naming/src/main/java/com/alibaba/nacos/naming/web/ApiCommands.java index 57e637426..615b6359e 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/web/ApiCommands.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/web/ApiCommands.java @@ -19,9 +19,8 @@ import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.TypeReference; -import com.alibaba.nacos.common.util.IoUtils; import com.alibaba.nacos.common.util.Md5Utils; -import com.alibaba.nacos.common.util.SystemUtil; +import com.alibaba.nacos.common.util.SystemUtils; import com.alibaba.nacos.naming.boot.RunningConfig; import com.alibaba.nacos.naming.core.*; import com.alibaba.nacos.naming.exception.NacosException; @@ -50,7 +49,10 @@ import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; -import java.io.*; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.InetAddress; import java.net.InetSocketAddress; @@ -2002,9 +2004,9 @@ public class ApiCommands { result.put("ipCount", ipCount); result.put("responsibleDomCount", responsibleDomCount); result.put("responsibleIPCount", responsibleIPCount); - result.put("cpu", SystemUtil.getCPU()); - result.put("load", SystemUtil.getLoad()); - result.put("mem", SystemUtil.getMem()); + result.put("cpu", SystemUtils.getCPU()); + result.put("load", SystemUtils.getLoad()); + result.put("mem", SystemUtils.getMem()); return result; } From 64c6189ccb5068b29ea7b87a234ca15af34cdf9a Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Mon, 1 Oct 2018 23:10:21 +0800 Subject: [PATCH 14/30] Polish alibaba/nacos#105 : add test cases --- .../alibaba/nacos/common/SystemUtilsTest.java | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 common/src/test/java/com/alibaba/nacos/common/SystemUtilsTest.java diff --git a/common/src/test/java/com/alibaba/nacos/common/SystemUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/SystemUtilsTest.java new file mode 100644 index 000000000..59474c1d1 --- /dev/null +++ b/common/src/test/java/com/alibaba/nacos/common/SystemUtilsTest.java @@ -0,0 +1,57 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.nacos.common; + +import com.alibaba.nacos.common.util.SystemUtils; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.Random; + +/** + * {@link SystemUtils} Test + * + * @author Mercy + * @since 0.2.2 + */ +public class SystemUtilsTest { + + private static final Random random = new Random(); + + private static boolean standaloneMode = random.nextBoolean(); + + @BeforeClass + public static void init() { + System.setProperty("nacos.standalone", String.valueOf(standaloneMode)); + } + + @Test + public void testStandaloneModeConstants() { + + System.out.printf("System property \"%s\" = %s \n", "nacos.standalone", standaloneMode); + + if ("true".equalsIgnoreCase(System.getProperty("nacos.standalone"))) { + Assert.assertTrue(SystemUtils.STANDALONE_MODE); + } else { + Assert.assertFalse(SystemUtils.STANDALONE_MODE); + } + + Assert.assertEquals(standaloneMode, SystemUtils.STANDALONE_MODE); + + } +} From adaf5f54d1d009fa35085150066e4c3e17fa90f6 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Tue, 2 Oct 2018 11:20:54 +0800 Subject: [PATCH 15/30] Polish alibaba/nacos#95 : add "standalone" profile --- common/pom.xml | 5 + .../alibaba/nacos/common/util/Constants.java | 31 ++++ config/pom.xml | 6 +- console/pom.xml | 140 ++++++++---------- core/pom.xml | 74 +++++---- .../StandaloneProfileApplicationListener.java | 66 +++++++++ .../main/resources/META-INF/spring.factories | 3 + .../java/com/alibaba/nacos/core/AppTest.java | 53 ------- ...ndaloneProfileApplicationListenerTest.java | 56 +++++++ 9 files changed, 271 insertions(+), 163 deletions(-) create mode 100644 common/src/main/java/com/alibaba/nacos/common/util/Constants.java create mode 100644 core/src/main/java/com/alibaba/nacos/core/listener/StandaloneProfileApplicationListener.java create mode 100644 core/src/main/resources/META-INF/spring.factories delete mode 100644 core/src/test/java/com/alibaba/nacos/core/AppTest.java create mode 100644 core/src/test/java/com/alibaba/nacos/core/listener/StandaloneProfileApplicationListenerTest.java diff --git a/common/pom.xml b/common/pom.xml index 4eef4feba..ed9db89fb 100644 --- a/common/pom.xml +++ b/common/pom.xml @@ -35,6 +35,11 @@ + + org.slf4j + slf4j-api + + commons-io commons-io diff --git a/common/src/main/java/com/alibaba/nacos/common/util/Constants.java b/common/src/main/java/com/alibaba/nacos/common/util/Constants.java new file mode 100644 index 000000000..2150b05d3 --- /dev/null +++ b/common/src/main/java/com/alibaba/nacos/common/util/Constants.java @@ -0,0 +1,31 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.nacos.common.util; + +/** + * Nacos common constants + * + * @author Mercy + * @since 0.2.2 + */ +public interface Constants { + + /** + * Spring Profile : "standalone" + */ + String STANDALONE_SPRING_PROFILE = "standalone"; +} diff --git a/config/pom.xml b/config/pom.xml index acc9c69f2..849882922 100644 --- a/config/pom.xml +++ b/config/pom.xml @@ -39,10 +39,12 @@ org.springframework.boot spring-boot-starter-web + ${project.groupId} nacos-core + com.google.guava guava @@ -85,10 +87,6 @@ - - org.springframework.boot - spring-boot-starter-tomcat - org.codehaus.jackson jackson-mapper-lgpl diff --git a/console/pom.xml b/console/pom.xml index 4c367b782..e4c441bbc 100644 --- a/console/pom.xml +++ b/console/pom.xml @@ -12,86 +12,70 @@ limitations under the License. --> - 4.0.0 - - com.alibaba.nacos - nacos-all - 0.2.2-SNAPSHOT - ../pom.xml - - nacos-console - - jar - nacos-console ${project.version} - http://maven.apache.org - - UTF-8 - - + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + + com.alibaba.nacos + nacos-all + 0.2.2-SNAPSHOT + ../pom.xml + + nacos-console + + jar + nacos-console ${project.version} + http://maven.apache.org + + UTF-8 + + - - ${project.groupId} - nacos-config - - - org.apache.tomcat.embed - tomcat-embed-jasper - 7.0.59 - - - ${project.groupId} - nacos-naming - - - - org.slf4j - log4j-over-slf4j - - - - org.slf4j - jcl-over-slf4j - - - - org.slf4j - jul-to-slf4j + ${project.groupId} + nacos-config - - - - nacos-server - - - org.springframework.boot - spring-boot-maven-plugin - - com.alibaba.nacos.Nacos - - - - - repackage - - - - - - - - true - src/main/resources - - application.properties - banner.txt - diamond-server-logback.xml - schema.sql - - - - + + ${project.groupId} + nacos-naming + + + + org.apache.tomcat.embed + tomcat-embed-jasper + + + + + nacos-server + + + org.springframework.boot + spring-boot-maven-plugin + + com.alibaba.nacos.Nacos + + + + + repackage + + + + + + + + true + src/main/resources + + application.properties + banner.txt + diamond-server-logback.xml + schema.sql + + + + diff --git a/core/pom.xml b/core/pom.xml index cbaaba35b..46aece468 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -12,38 +12,56 @@ limitations under the License. --> + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - - com.alibaba.nacos - nacos-all - 0.2.2-SNAPSHOT - ../pom.xml - + + com.alibaba.nacos + nacos-all + 0.2.2-SNAPSHOT + ../pom.xml + - 4.0.0 + 4.0.0 - nacos-core - jar + nacos-core + jar - nacos-core ${project.version} - http://maven.apache.org + nacos-core ${project.version} + http://maven.apache.org - - UTF-8 - + + UTF-8 + - - - junit - junit - 3.8.1 - test - - - ${project.groupId} - nacos-common - - + + + + ${project.groupId} + nacos-common + + + + org.springframework.boot + spring-boot-starter + true + + + + junit + junit + test + + + + org.springframework + spring-test + + + + org.springframework.boot + spring-boot-test + + + diff --git a/core/src/main/java/com/alibaba/nacos/core/listener/StandaloneProfileApplicationListener.java b/core/src/main/java/com/alibaba/nacos/core/listener/StandaloneProfileApplicationListener.java new file mode 100644 index 000000000..cdc5063f0 --- /dev/null +++ b/core/src/main/java/com/alibaba/nacos/core/listener/StandaloneProfileApplicationListener.java @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.nacos.core.listener; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent; +import org.springframework.context.ApplicationListener; +import org.springframework.context.annotation.Profile; +import org.springframework.core.PriorityOrdered; +import org.springframework.core.env.ConfigurableEnvironment; + +import java.util.Arrays; + +import static com.alibaba.nacos.common.util.Constants.STANDALONE_SPRING_PROFILE; +import static com.alibaba.nacos.common.util.SystemUtils.STANDALONE_MODE; + +/** + * Standalone {@link Profile} {@link ApplicationListener} for {@link ApplicationEnvironmentPreparedEvent} + * + * @author Mercy + * @see ConfigurableEnvironment#addActiveProfile(String) + * @since 0.2.2 + */ +public class StandaloneProfileApplicationListener implements ApplicationListener, + PriorityOrdered { + + private static final Logger logger = LoggerFactory.getLogger(StandaloneProfileApplicationListener.class); + + @Override + public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { + + ConfigurableEnvironment environment = event.getEnvironment(); + + if (STANDALONE_MODE) { + environment.addActiveProfile(STANDALONE_SPRING_PROFILE); + } + + if (logger.isInfoEnabled()) { + logger.info("Spring Environment's active profiles : {} in standalone mode : {}", + Arrays.asList(environment.getActiveProfiles()), + STANDALONE_MODE + ); + } + + } + + @Override + public int getOrder() { + return HIGHEST_PRECEDENCE; + } +} diff --git a/core/src/main/resources/META-INF/spring.factories b/core/src/main/resources/META-INF/spring.factories new file mode 100644 index 000000000..975bb4ba4 --- /dev/null +++ b/core/src/main/resources/META-INF/spring.factories @@ -0,0 +1,3 @@ +# ApplicationListener +org.springframework.context.ApplicationListener=\ +com.alibaba.nacos.core.listener.StandaloneProfileApplicationListener \ No newline at end of file diff --git a/core/src/test/java/com/alibaba/nacos/core/AppTest.java b/core/src/test/java/com/alibaba/nacos/core/AppTest.java deleted file mode 100644 index 60c39f223..000000000 --- a/core/src/test/java/com/alibaba/nacos/core/AppTest.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 1999-2018 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.nacos.core; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -/** - * Unit test for simple App. - */ -public class AppTest - extends TestCase -{ - /** - * Create the test case - * - * @param testName name of the test case - */ - public AppTest( String testName ) - { - super( testName ); - } - - /** - * @return the suite of tests being tested - */ - public static Test suite() - { - return new TestSuite( AppTest.class ); - } - - /** - * Rigourous Test :-) - */ - public void testApp() - { - assertTrue( true ); - } -} diff --git a/core/src/test/java/com/alibaba/nacos/core/listener/StandaloneProfileApplicationListenerTest.java b/core/src/test/java/com/alibaba/nacos/core/listener/StandaloneProfileApplicationListenerTest.java new file mode 100644 index 000000000..fd8190d06 --- /dev/null +++ b/core/src/test/java/com/alibaba/nacos/core/listener/StandaloneProfileApplicationListenerTest.java @@ -0,0 +1,56 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.nacos.core.listener; + +import org.apache.commons.lang3.ArrayUtils; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.core.env.Environment; +import org.springframework.test.context.junit4.SpringRunner; + +import static com.alibaba.nacos.common.util.Constants.STANDALONE_SPRING_PROFILE; + +/** + * {@link StandaloneProfileApplicationListener} Test + * + * @author Mercy + * @since 0.2.2 + */ +@RunWith(SpringRunner.class) +@SpringBootTest( + classes = StandaloneProfileApplicationListenerTest.class, + webEnvironment = SpringBootTest.WebEnvironment.NONE) +public class StandaloneProfileApplicationListenerTest { + + @BeforeClass + public static void init() { + System.setProperty("nacos.standalone", "true"); + } + + @Autowired + private Environment environment; + + @Test + public void testProfile() { + Assert.assertTrue(ArrayUtils.contains(environment.getActiveProfiles(), STANDALONE_SPRING_PROFILE)); + } + +} From 08af83caac9ea801e6ccf18be5242234b208f8a3 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Tue, 2 Oct 2018 12:22:18 +0800 Subject: [PATCH 16/30] Polish alibaba/nacos#95 : more generic implementation --- .../java/com/alibaba/nacos/common/util/SystemUtils.java | 7 ++++++- .../listener/StandaloneProfileApplicationListener.java | 3 ++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/common/src/main/java/com/alibaba/nacos/common/util/SystemUtils.java b/common/src/main/java/com/alibaba/nacos/common/util/SystemUtils.java index 49a964226..c08a31758 100644 --- a/common/src/main/java/com/alibaba/nacos/common/util/SystemUtils.java +++ b/common/src/main/java/com/alibaba/nacos/common/util/SystemUtils.java @@ -29,10 +29,15 @@ import java.util.List; */ public class SystemUtils { + /** + * The System property name of Standalone mode + */ + public static final String STANDALONE_MODE_PROPERTY_NAME = "nacos.standalone"; + /** * Standalone mode or not */ - public static final boolean STANDALONE_MODE = Boolean.getBoolean("nacos.standalone"); + public static final boolean STANDALONE_MODE = Boolean.getBoolean(STANDALONE_MODE_PROPERTY_NAME); private static OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(); diff --git a/core/src/main/java/com/alibaba/nacos/core/listener/StandaloneProfileApplicationListener.java b/core/src/main/java/com/alibaba/nacos/core/listener/StandaloneProfileApplicationListener.java index cdc5063f0..6faf8e0d7 100644 --- a/core/src/main/java/com/alibaba/nacos/core/listener/StandaloneProfileApplicationListener.java +++ b/core/src/main/java/com/alibaba/nacos/core/listener/StandaloneProfileApplicationListener.java @@ -28,6 +28,7 @@ import java.util.Arrays; import static com.alibaba.nacos.common.util.Constants.STANDALONE_SPRING_PROFILE; import static com.alibaba.nacos.common.util.SystemUtils.STANDALONE_MODE; +import static com.alibaba.nacos.common.util.SystemUtils.STANDALONE_MODE_PROPERTY_NAME; /** * Standalone {@link Profile} {@link ApplicationListener} for {@link ApplicationEnvironmentPreparedEvent} @@ -46,7 +47,7 @@ public class StandaloneProfileApplicationListener implements ApplicationListener ConfigurableEnvironment environment = event.getEnvironment(); - if (STANDALONE_MODE) { + if (environment.getProperty(STANDALONE_MODE_PROPERTY_NAME, boolean.class, false)) { environment.addActiveProfile(STANDALONE_SPRING_PROFILE); } From c4374dbf4e3622656b43655ee98687abcb92432f Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Tue, 2 Oct 2018 18:21:54 +0800 Subject: [PATCH 17/30] Polish alibaba/nacos#94 : fixed the grammar of logback xml files --- config/src/main/resources/nacos-config-logback.xml | 1 - console/src/main/resources/diamond-server-logback.xml | 3 ++- distribution/conf/nacos-logback.xml | 1 - 3 files changed, 2 insertions(+), 3 deletions(-) diff --git a/config/src/main/resources/nacos-config-logback.xml b/config/src/main/resources/nacos-config-logback.xml index 207b7bd66..176c64e2e 100755 --- a/config/src/main/resources/nacos-config-logback.xml +++ b/config/src/main/resources/nacos-config-logback.xml @@ -1,5 +1,4 @@ - - GBK + ${user.home}/diamond/logs/pull.log @@ -34,6 +34,7 @@ GBK + ${user.home}/diamond/logs/fatal.log diff --git a/distribution/conf/nacos-logback.xml b/distribution/conf/nacos-logback.xml index 0fbbd6e2e..6646bd5e4 100644 --- a/distribution/conf/nacos-logback.xml +++ b/distribution/conf/nacos-logback.xml @@ -1,5 +1,4 @@ - Date: Tue, 2 Oct 2018 21:05:56 +0800 Subject: [PATCH 18/30] Polish alibaba/nacos#108 : Remove duplicated banner.txt in sub-modules and move one into core module --- console/src/main/resources/banner.txt | 15 --------------- {config => core}/src/main/resources/banner.txt | 0 naming/src/main/resources/banner.txt | 15 --------------- 3 files changed, 30 deletions(-) delete mode 100644 console/src/main/resources/banner.txt rename {config => core}/src/main/resources/banner.txt (100%) delete mode 100644 naming/src/main/resources/banner.txt diff --git a/console/src/main/resources/banner.txt b/console/src/main/resources/banner.txt deleted file mode 100644 index 4ebabe6fa..000000000 --- a/console/src/main/resources/banner.txt +++ /dev/null @@ -1,15 +0,0 @@ - - ,--. - ,--.'| - ,--,: : | -,`--.'`| ' : ,---. -| : : | | ' ,'\ .--.--. -: | \ | : ,--.--. ,---. / / | / / ' -| : ' '; | / \ / \. ; ,. :| : /`./ -' ' ;. ;.--. .-. | / / '' | |: :| : ;_ -| | | \ | \__\/: . .. ' / ' | .; : \ \ `. -' : | ; .' ," .--.; |' ; :__| : | `----. \ -| | '`--' / / ,. |' | '.'|\ \ / / /`--' / -' : | ; : .' \ : : `----' '--'. / -; |.' | , .-./\ \ / `--'---' -'---' `--`---' `----' diff --git a/config/src/main/resources/banner.txt b/core/src/main/resources/banner.txt similarity index 100% rename from config/src/main/resources/banner.txt rename to core/src/main/resources/banner.txt diff --git a/naming/src/main/resources/banner.txt b/naming/src/main/resources/banner.txt deleted file mode 100644 index 4ebabe6fa..000000000 --- a/naming/src/main/resources/banner.txt +++ /dev/null @@ -1,15 +0,0 @@ - - ,--. - ,--.'| - ,--,: : | -,`--.'`| ' : ,---. -| : : | | ' ,'\ .--.--. -: | \ | : ,--.--. ,---. / / | / / ' -| : ' '; | / \ / \. ; ,. :| : /`./ -' ' ;. ;.--. .-. | / / '' | |: :| : ;_ -| | | \ | \__\/: . .. ' / ' | .; : \ \ `. -' : | ; .' ," .--.; |' ; :__| : | `----. \ -| | '`--' / / ,. |' | '.'|\ \ / / /`--' / -' : | ; : .' \ : : `----' '--'. / -; |.' | , .-./\ \ / `--'---' -'---' `--`---' `----' From 700a755ac5e7ea561bd0700da5672e884bf3d7ff Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Tue, 2 Oct 2018 21:50:59 +0800 Subject: [PATCH 19/30] Polish alibaba/nacos#109 : Exclude DataSourceAutoConfiguration using externalized configuration --- .../alibaba/nacos/config/server/Config.java | 7 +-- ...tySourceApplicationContextInitializer.java | 47 +++++++++++++++++++ .../META-INF/nacos-default.properties | 7 +++ .../main/resources/META-INF/spring.factories | 6 ++- .../com/alibaba/nacos/naming/NamingApp.java | 5 +- 5 files changed, 62 insertions(+), 10 deletions(-) create mode 100644 core/src/main/java/com/alibaba/nacos/core/context/NacosDefaultPropertySourceApplicationContextInitializer.java create mode 100644 core/src/main/resources/META-INF/nacos-default.properties diff --git a/config/src/main/java/com/alibaba/nacos/config/server/Config.java b/config/src/main/java/com/alibaba/nacos/config/server/Config.java index 229c17296..4a5e7dcd4 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/Config.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/Config.java @@ -17,7 +17,6 @@ package com.alibaba.nacos.config.server; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import java.net.UnknownHostException; @@ -26,12 +25,10 @@ import java.net.UnknownHostException; * * @author Nacos */ -@SpringBootApplication( - scanBasePackages = "com.alibaba.nacos.config.server", - exclude = {DataSourceAutoConfiguration.class}) +@SpringBootApplication public class Config { + public static void main(String[] args) throws UnknownHostException { SpringApplication.run(Config.class, args); } - } diff --git a/core/src/main/java/com/alibaba/nacos/core/context/NacosDefaultPropertySourceApplicationContextInitializer.java b/core/src/main/java/com/alibaba/nacos/core/context/NacosDefaultPropertySourceApplicationContextInitializer.java new file mode 100644 index 000000000..9a2584b90 --- /dev/null +++ b/core/src/main/java/com/alibaba/nacos/core/context/NacosDefaultPropertySourceApplicationContextInitializer.java @@ -0,0 +1,47 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.nacos.core.context; + +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.ApplicationContextInitializer; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.PropertySource; + +/** + * An {@link ApplicationContextInitializer} implementation is used to append + * Nacos default {@link org.springframework.core.env.PropertySource} via annotating {@link PropertySource @PropertySource} + * + * @author Mercy + * @since 0.2.2 + */ +@PropertySource(name = "nacos-default", value = "classpath:/META-INF/nacos-default.properties", encoding = "UTF-8") +public class NacosDefaultPropertySourceApplicationContextInitializer implements + ApplicationContextInitializer { + + public static final String BEAN_NAME = "nacosDefaultPropertySource"; + + @Override + public void initialize(ConfigurableApplicationContext applicationContext) { + + ConfigurableBeanFactory beanFactory = applicationContext.getBeanFactory(); + + if (!beanFactory.containsSingleton(BEAN_NAME)) { // If current bean is absent, will be registered + beanFactory.registerSingleton(BEAN_NAME, this); + } + + } +} diff --git a/core/src/main/resources/META-INF/nacos-default.properties b/core/src/main/resources/META-INF/nacos-default.properties new file mode 100644 index 000000000..ce8e8b487 --- /dev/null +++ b/core/src/main/resources/META-INF/nacos-default.properties @@ -0,0 +1,7 @@ +# Nacos Default Properties + +## Exclude Spring Boot Auto-Configuration class(es) +spring.autoconfigure.exclude=\ +org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration + + diff --git a/core/src/main/resources/META-INF/spring.factories b/core/src/main/resources/META-INF/spring.factories index 975bb4ba4..e44fce047 100644 --- a/core/src/main/resources/META-INF/spring.factories +++ b/core/src/main/resources/META-INF/spring.factories @@ -1,3 +1,7 @@ # ApplicationListener org.springframework.context.ApplicationListener=\ -com.alibaba.nacos.core.listener.StandaloneProfileApplicationListener \ No newline at end of file +com.alibaba.nacos.core.listener.StandaloneProfileApplicationListener + +# ApplicationContextInitializer +org.springframework.context.ApplicationContextInitializer=\ +com.alibaba.nacos.core.context.NacosDefaultPropertySourceApplicationContextInitializer \ No newline at end of file diff --git a/naming/src/main/java/com/alibaba/nacos/naming/NamingApp.java b/naming/src/main/java/com/alibaba/nacos/naming/NamingApp.java index c65244602..2ce5d5f24 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/NamingApp.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/NamingApp.java @@ -16,17 +16,14 @@ package com.alibaba.nacos.naming; import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; -import org.springframework.context.ConfigurableApplicationContext; /** * Hello world! + * * @author xxc */ @SpringBootApplication -@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class}) public class NamingApp { public static void main(String[] args) { From 0ef461f2b842ad568adb262f1b91249c390702c4 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Wed, 3 Oct 2018 00:22:32 +0800 Subject: [PATCH 20/30] Polish alibaba/nacos#109 : Change implementation to be EnvironmentPostProcessor --- ...tySourceApplicationContextInitializer.java | 47 -------- ...ropertySourceEnvironmentPostProcessor.java | 112 ++++++++++++++++++ .../main/resources/META-INF/spring.factories | 6 +- ...rtySourceEnvironmentPostProcessorTest.java | 57 +++++++++ 4 files changed, 172 insertions(+), 50 deletions(-) delete mode 100644 core/src/main/java/com/alibaba/nacos/core/context/NacosDefaultPropertySourceApplicationContextInitializer.java create mode 100644 core/src/main/java/com/alibaba/nacos/core/env/NacosDefaultPropertySourceEnvironmentPostProcessor.java create mode 100644 core/src/test/java/com/alibaba/nacos/core/env/NacosDefaultPropertySourceEnvironmentPostProcessorTest.java diff --git a/core/src/main/java/com/alibaba/nacos/core/context/NacosDefaultPropertySourceApplicationContextInitializer.java b/core/src/main/java/com/alibaba/nacos/core/context/NacosDefaultPropertySourceApplicationContextInitializer.java deleted file mode 100644 index 9a2584b90..000000000 --- a/core/src/main/java/com/alibaba/nacos/core/context/NacosDefaultPropertySourceApplicationContextInitializer.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.nacos.core.context; - -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.ApplicationContextInitializer; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.annotation.PropertySource; - -/** - * An {@link ApplicationContextInitializer} implementation is used to append - * Nacos default {@link org.springframework.core.env.PropertySource} via annotating {@link PropertySource @PropertySource} - * - * @author Mercy - * @since 0.2.2 - */ -@PropertySource(name = "nacos-default", value = "classpath:/META-INF/nacos-default.properties", encoding = "UTF-8") -public class NacosDefaultPropertySourceApplicationContextInitializer implements - ApplicationContextInitializer { - - public static final String BEAN_NAME = "nacosDefaultPropertySource"; - - @Override - public void initialize(ConfigurableApplicationContext applicationContext) { - - ConfigurableBeanFactory beanFactory = applicationContext.getBeanFactory(); - - if (!beanFactory.containsSingleton(BEAN_NAME)) { // If current bean is absent, will be registered - beanFactory.registerSingleton(BEAN_NAME, this); - } - - } -} diff --git a/core/src/main/java/com/alibaba/nacos/core/env/NacosDefaultPropertySourceEnvironmentPostProcessor.java b/core/src/main/java/com/alibaba/nacos/core/env/NacosDefaultPropertySourceEnvironmentPostProcessor.java new file mode 100644 index 000000000..9d044b310 --- /dev/null +++ b/core/src/main/java/com/alibaba/nacos/core/env/NacosDefaultPropertySourceEnvironmentPostProcessor.java @@ -0,0 +1,112 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.nacos.core.env; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.env.EnvironmentPostProcessor; +import org.springframework.core.Ordered; +import org.springframework.core.env.*; +import org.springframework.core.io.DefaultResourceLoader; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; +import org.springframework.core.io.support.EncodedResource; +import org.springframework.core.io.support.PathMatchingResourcePatternResolver; +import org.springframework.core.io.support.ResourcePatternResolver; +import org.springframework.core.io.support.ResourcePropertySource; + +import java.io.IOException; + +import static org.springframework.core.io.support.ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX; + +/** + * A lowest precedence {@link EnvironmentPostProcessor} implementation to append + * Nacos default {@link PropertySource} with lowest order in {@link Environment} + * + * @author Mercy + * @since 0.2.2 + */ +public class NacosDefaultPropertySourceEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { + + /** + * The name of Nacos default {@link PropertySource} + */ + public static final String PROPERTY_SOURCE_NAME = "nacos-default"; + + /** + * The resource location pattern of Nacos default {@link PropertySource} + * + * @see ResourcePatternResolver#CLASSPATH_ALL_URL_PREFIX + */ + public static final String RESOURCE_LOCATION_PATTERN = CLASSPATH_ALL_URL_PREFIX + "META-INF/nacos-default.properties"; + + private static final String FILE_ENCODING = "UTF-8"; + + @Override + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { + + ResourceLoader resourceLoader = getResourceLoader(application); + + processPropertySource(environment, resourceLoader); + + } + + private ResourceLoader getResourceLoader(SpringApplication application) { + + ResourceLoader resourceLoader = application.getResourceLoader(); + + if (resourceLoader == null) { + resourceLoader = new DefaultResourceLoader(application.getClassLoader()); + } + + return resourceLoader; + } + + private void processPropertySource(ConfigurableEnvironment environment, ResourceLoader resourceLoader) { + + try { + PropertySource nacosDefaultPropertySource = buildPropertySource(resourceLoader); + MutablePropertySources propertySources = environment.getPropertySources(); + // append nacosDefaultPropertySource as last one in order to be overrided by higher order + propertySources.addLast(nacosDefaultPropertySource); + } catch (IOException e) { + throw new IllegalStateException(e.getMessage(), e); + } + } + + private PropertySource buildPropertySource(ResourceLoader resourceLoader) throws IOException { + CompositePropertySource propertySource = new CompositePropertySource(PROPERTY_SOURCE_NAME); + appendPropertySource(propertySource, resourceLoader); + return propertySource; + } + + private void appendPropertySource(CompositePropertySource propertySource, ResourceLoader resourceLoader) throws IOException { + ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(resourceLoader); + Resource[] resources = resourcePatternResolver.getResources(RESOURCE_LOCATION_PATTERN); + for (Resource resource : resources) { + if (resource.exists()) { // Add if exists + String internalName = String.valueOf(resource.getURL()); + propertySource.addPropertySource(new ResourcePropertySource(internalName, + new EncodedResource(resource, FILE_ENCODING))); + } + } + } + + @Override + public int getOrder() { + return LOWEST_PRECEDENCE; + } +} diff --git a/core/src/main/resources/META-INF/spring.factories b/core/src/main/resources/META-INF/spring.factories index e44fce047..17aca100e 100644 --- a/core/src/main/resources/META-INF/spring.factories +++ b/core/src/main/resources/META-INF/spring.factories @@ -2,6 +2,6 @@ org.springframework.context.ApplicationListener=\ com.alibaba.nacos.core.listener.StandaloneProfileApplicationListener -# ApplicationContextInitializer -org.springframework.context.ApplicationContextInitializer=\ -com.alibaba.nacos.core.context.NacosDefaultPropertySourceApplicationContextInitializer \ No newline at end of file +# EnvironmentPostProcessor +org.springframework.boot.env.EnvironmentPostProcessor=\ +com.alibaba.nacos.core.env.NacosDefaultPropertySourceEnvironmentPostProcessor \ No newline at end of file diff --git a/core/src/test/java/com/alibaba/nacos/core/env/NacosDefaultPropertySourceEnvironmentPostProcessorTest.java b/core/src/test/java/com/alibaba/nacos/core/env/NacosDefaultPropertySourceEnvironmentPostProcessorTest.java new file mode 100644 index 000000000..cb5d0cb67 --- /dev/null +++ b/core/src/test/java/com/alibaba/nacos/core/env/NacosDefaultPropertySourceEnvironmentPostProcessorTest.java @@ -0,0 +1,57 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.nacos.core.env; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.MutablePropertySources; +import org.springframework.core.env.PropertySource; +import org.springframework.test.context.junit4.SpringRunner; + +import static com.alibaba.nacos.core.env.NacosDefaultPropertySourceEnvironmentPostProcessor.PROPERTY_SOURCE_NAME; + +/** + * {@link NacosDefaultPropertySourceEnvironmentPostProcessor} Test + * + * @author Mercy + * @since 0.2.2 + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = NacosDefaultPropertySourceEnvironmentPostProcessorTest.class, + webEnvironment = SpringBootTest.WebEnvironment.NONE) +public class NacosDefaultPropertySourceEnvironmentPostProcessorTest { + + @Autowired + private ConfigurableEnvironment environment; + + @Test + public void testNacosDefaultPropertySourcePresent() { + MutablePropertySources propertySources = environment.getPropertySources(); + // "nacos-default" must be present + Assert.assertTrue(propertySources.contains("nacos-default")); + // Get PropertySource via PROPERTY_SOURCE_NAME + PropertySource propertySource = propertySources.get(PROPERTY_SOURCE_NAME); + // "nacos-default" must be present + Assert.assertNotNull(propertySource); + // make sure propertySource is last one + Assert.assertEquals(propertySources.size() - 1, propertySources.precedenceOf(propertySource)); + } +} From 8a73c805d8bb0f2ff2a13d31f01773c4064a93d5 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Wed, 3 Oct 2018 01:18:09 +0800 Subject: [PATCH 21/30] Polish alibaba/nacos#110 : remove application.properties and copy to META-INF/nacos-default.properties --- config/pom.xml | 3 - .../src/main/resources/application.properties | 17 ------ .../alibaba/nacos/config/server/Config.java | 0 .../nacos-default.properties} | 7 +-- .../main/resources/{ => META-INF}/schema.sql | 0 .../META-INF/nacos-default.properties | 17 +++++- ...rtySourceEnvironmentPostProcessorTest.java | 58 ++++++++++++++++++- distribution/conf/application.properties | 2 +- .../conf/application.properties.example | 2 +- naming/pom.xml | 9 +++ .../src/main/resources/application.properties | 10 ---- .../com/alibaba/nacos/naming/NamingApp.java | 0 .../src/test/resources/application.properties | 2 +- 13 files changed, 85 insertions(+), 42 deletions(-) delete mode 100644 config/src/main/resources/application.properties rename config/src/{main => test}/java/com/alibaba/nacos/config/server/Config.java (100%) rename console/src/main/resources/{application.properties => META-INF/nacos-default.properties} (91%) rename console/src/main/resources/{ => META-INF}/schema.sql (100%) delete mode 100644 naming/src/main/resources/application.properties rename naming/src/{main => test}/java/com/alibaba/nacos/naming/NamingApp.java (100%) diff --git a/config/pom.xml b/config/pom.xml index 849882922..60e16d6d9 100644 --- a/config/pom.xml +++ b/config/pom.xml @@ -158,9 +158,6 @@ src/main/resources application.properties - banner.txt - schema.sql - nacos-db.sql diff --git a/config/src/main/resources/application.properties b/config/src/main/resources/application.properties deleted file mode 100644 index 1bf0abb4d..000000000 --- a/config/src/main/resources/application.properties +++ /dev/null @@ -1,17 +0,0 @@ -# spring -management.security.enabled=false -server.servlet.context-path=/nacos -server.port=8848 - -db.num=2 -db.url.0=url1 -db.url.1=url2 -db.user=user -db.password=pwd - -spring.http.encoding.force=true -spring.http.encoding.charset=UTF-8 -spring.http.encoding.enabled=true -server.tomcat.uri-encoding=UTF-8 -spring.messages.encoding=UTF-8 -security.headers.content-type=application/json;charset=UTF-8 \ No newline at end of file diff --git a/config/src/main/java/com/alibaba/nacos/config/server/Config.java b/config/src/test/java/com/alibaba/nacos/config/server/Config.java similarity index 100% rename from config/src/main/java/com/alibaba/nacos/config/server/Config.java rename to config/src/test/java/com/alibaba/nacos/config/server/Config.java diff --git a/console/src/main/resources/application.properties b/console/src/main/resources/META-INF/nacos-default.properties similarity index 91% rename from console/src/main/resources/application.properties rename to console/src/main/resources/META-INF/nacos-default.properties index 34a749946..2b3eca1f7 100644 --- a/console/src/main/resources/application.properties +++ b/console/src/main/resources/META-INF/nacos-default.properties @@ -1,8 +1,5 @@ -# spring -management.security.enabled=false -server.contextPath=/nacos -server.servlet.contextPath=/nacos -server.port=8848 +# Console Default Properties + spring.mvc.view.prefix=/jsp/ # 响应页面默认后缀 spring.mvc.view.suffix=.jsp diff --git a/console/src/main/resources/schema.sql b/console/src/main/resources/META-INF/schema.sql similarity index 100% rename from console/src/main/resources/schema.sql rename to console/src/main/resources/META-INF/schema.sql diff --git a/core/src/main/resources/META-INF/nacos-default.properties b/core/src/main/resources/META-INF/nacos-default.properties index ce8e8b487..917f3f203 100644 --- a/core/src/main/resources/META-INF/nacos-default.properties +++ b/core/src/main/resources/META-INF/nacos-default.properties @@ -1,7 +1,18 @@ # Nacos Default Properties +## Web Server +server.servlet.context-path=/nacos +server.port=8848 +server.tomcat.uri-encoding=UTF-8 + +## HTTP Encoding +spring.http.encoding.force=true +spring.http.encoding.enabled=true + +## i18n +spring.messages.encoding=UTF-8 + ## Exclude Spring Boot Auto-Configuration class(es) spring.autoconfigure.exclude=\ -org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration - - +org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\ +org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration \ No newline at end of file diff --git a/core/src/test/java/com/alibaba/nacos/core/env/NacosDefaultPropertySourceEnvironmentPostProcessorTest.java b/core/src/test/java/com/alibaba/nacos/core/env/NacosDefaultPropertySourceEnvironmentPostProcessorTest.java index cb5d0cb67..b9de60a14 100644 --- a/core/src/test/java/com/alibaba/nacos/core/env/NacosDefaultPropertySourceEnvironmentPostProcessorTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/env/NacosDefaultPropertySourceEnvironmentPostProcessorTest.java @@ -21,12 +21,17 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.core.env.CompositePropertySource; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.PropertySource; import org.springframework.test.context.junit4.SpringRunner; +import java.util.HashSet; + import static com.alibaba.nacos.core.env.NacosDefaultPropertySourceEnvironmentPostProcessor.PROPERTY_SOURCE_NAME; +import static com.alibaba.nacos.core.env.NacosDefaultPropertySourceEnvironmentPostProcessor.RESOURCE_LOCATION_PATTERN; +import static java.util.Arrays.asList; /** * {@link NacosDefaultPropertySourceEnvironmentPostProcessor} Test @@ -48,10 +53,61 @@ public class NacosDefaultPropertySourceEnvironmentPostProcessorTest { // "nacos-default" must be present Assert.assertTrue(propertySources.contains("nacos-default")); // Get PropertySource via PROPERTY_SOURCE_NAME - PropertySource propertySource = propertySources.get(PROPERTY_SOURCE_NAME); + PropertySource propertySource = getNacosDefaultPropertySource(); // "nacos-default" must be present Assert.assertNotNull(propertySource); // make sure propertySource is last one Assert.assertEquals(propertySources.size() - 1, propertySources.precedenceOf(propertySource)); } + + @Test + public void testDefaultProperties() { + + // Web Server + assertPropertyEquals("server.servlet.context-path", "/nacos"); + assertPropertyEquals("server.port", "8848"); + assertPropertyEquals("server.tomcat.uri-encoding", "UTF-8"); + + // HTTP Encoding + assertPropertyEquals("spring.http.encoding.force", "true"); + assertPropertyEquals("spring.http.encoding.enabled", "true"); + + // i18n + assertPropertyEquals("spring.messages.encoding", "UTF-8"); + } + + @Test + public void testDefaultPropertyNames() { + + assertPropertyNames( + "server.servlet.context-path", + "server.port", + "server.tomcat.uri-encoding", + "spring.http.encoding.force", + "spring.http.encoding.enabled", + "spring.messages.encoding", + "spring.autoconfigure.exclude" + ); + } + + private void assertPropertyNames(String... propertyNames) { + + CompositePropertySource propertySource = getNacosDefaultPropertySource(); + + Assert.assertEquals("Please Properties from resources[" + RESOURCE_LOCATION_PATTERN + "]", + new HashSet(asList(propertyNames)), + new HashSet(asList(propertySource.getPropertyNames()))); + } + + private void assertPropertyEquals(String propertyName, String expectedValue) { + PropertySource propertySource = getNacosDefaultPropertySource(); + Assert.assertEquals(expectedValue, propertySource.getProperty(propertyName)); + } + + private CompositePropertySource getNacosDefaultPropertySource() { + MutablePropertySources propertySources = environment.getPropertySources(); + // Get PropertySource via PROPERTY_SOURCE_NAME + CompositePropertySource propertySource = (CompositePropertySource) propertySources.get(PROPERTY_SOURCE_NAME); + return propertySource; + } } diff --git a/distribution/conf/application.properties b/distribution/conf/application.properties index b08022440..f041dcf48 100644 --- a/distribution/conf/application.properties +++ b/distribution/conf/application.properties @@ -1,5 +1,5 @@ # spring -management.security.enabled=false + server.contextPath=/nacos server.servlet.contextPath=/nacos server.port=8848 diff --git a/distribution/conf/application.properties.example b/distribution/conf/application.properties.example index 91a5f1f09..4536d16ea 100644 --- a/distribution/conf/application.properties.example +++ b/distribution/conf/application.properties.example @@ -1,5 +1,5 @@ # spring -management.security.enabled=false + server.contextPath=/nacos server.servlet.contextPath=/nacos server.port=8848 diff --git a/naming/pom.xml b/naming/pom.xml index 9c157c619..5ee9b9d2c 100644 --- a/naming/pom.xml +++ b/naming/pom.xml @@ -177,6 +177,15 @@ + + + true + src/main/resources + + application.properties + + +
diff --git a/naming/src/main/resources/application.properties b/naming/src/main/resources/application.properties deleted file mode 100644 index 0342d6dde..000000000 --- a/naming/src/main/resources/application.properties +++ /dev/null @@ -1,10 +0,0 @@ -server.port=8080 -server.servlet.context-path=/nacos - - -# Number of ms to wait before throwing an exception if no connection is available. -spring.datasource.max-wait=10000 -# Maximum number of active connections that can be allocated from this pool at the same time. -spring.datasource.max-active=15 -## Validate the connection before borrowing it from the pool. -#spring.datasource.test-on-borrow=true diff --git a/naming/src/main/java/com/alibaba/nacos/naming/NamingApp.java b/naming/src/test/java/com/alibaba/nacos/naming/NamingApp.java similarity index 100% rename from naming/src/main/java/com/alibaba/nacos/naming/NamingApp.java rename to naming/src/test/java/com/alibaba/nacos/naming/NamingApp.java diff --git a/test/src/test/resources/application.properties b/test/src/test/resources/application.properties index 45af80bde..d56cb4c9f 100644 --- a/test/src/test/resources/application.properties +++ b/test/src/test/resources/application.properties @@ -1,5 +1,5 @@ # spring -management.security.enabled=false + server.servlet.context-path=/nacos server.port=8848 From e91ccc9c0fb3ae7a57bdc4e9333f5dbc1df18b8b Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Wed, 3 Oct 2018 03:58:26 +0800 Subject: [PATCH 22/30] Polish alibaba/nacos#96 : add command arguments into startup scripts --- distribution/bin/startup.cmd | 1 + distribution/bin/startup.sh | 1 + 2 files changed, 2 insertions(+) diff --git a/distribution/bin/startup.cmd b/distribution/bin/startup.cmd index 36d7b5370..97ed77812 100755 --- a/distribution/bin/startup.cmd +++ b/distribution/bin/startup.cmd @@ -34,5 +34,6 @@ set "JAVA_OPT=%JAVA_OPT% -XX:-OmitStackTraceInFastThrow" set "JAVA_OPT=%JAVA_OPT% -XX:-UseLargePages" set "JAVA_OPT=%JAVA_OPT% -jar %BASE_DIR%\target\nacos-server.jar" set "JAVA_OPT=%JAVA_OPT% --spring.config.location="%CUSTOM_SEARCH_LOCATIONS%"" +set "JAVA_OPT=%JAVA_OPT% --logging.config="%BASE_DIR%/conf/nacos-logback.xml"" call "%JAVA%" %JAVA_OPT% %* \ No newline at end of file diff --git a/distribution/bin/startup.sh b/distribution/bin/startup.sh index d7ed7783e..137e9860d 100644 --- a/distribution/bin/startup.sh +++ b/distribution/bin/startup.sh @@ -59,6 +59,7 @@ JAVA_OPT="${JAVA_OPT} -XX:-UseLargePages" JAVA_OPT="${JAVA_OPT} -jar ${BASE_DIR}/target/nacos-server.jar" JAVA_OPT="${JAVA_OPT} ${JAVA_OPT_EXT}" JAVA_OPT="${JAVA_OPT} --spring.config.location=${CUSTOM_SEARCH_LOCATIONS}" +JAVA_OPT="${JAVA_OPT} --logging.config=${BASE_DIR}/conf/nacos-nacos-included.xml" if [ ! -d "${BASE_DIR}/logs" ]; then mkdir ${BASE_DIR}/logs fi From 0424a4a1db46852d7b14b3b5e940133787ee5a47 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Wed, 3 Oct 2018 04:00:33 +0800 Subject: [PATCH 23/30] Polish alibaba/nacos#94 : adapter modular logback whether current application is Spring or Spring Boot --- config/pom.xml | 1 - .../alibaba/nacos/config/server/Config.java | 0 .../nacos/config/server/utils/LogUtil.java | 27 - .../logback/nacos-included.xml} | 564 +++++++++--------- .../LoggingSpringApplicationRunListener.java | 103 ++++ .../main/resources/META-INF/logback/nacos.xml | 30 + .../main/resources/META-INF/spring.factories | 6 +- .../com/alibaba/nacos/naming/NamingApp.java | 0 .../alibaba/nacos/naming/misc/Loggers.java | 25 - .../logback/nacos-included.xml} | 5 +- 10 files changed, 423 insertions(+), 338 deletions(-) rename config/src/{test => main}/java/com/alibaba/nacos/config/server/Config.java (100%) rename config/src/main/resources/{nacos-config-logback.xml => META-INF/logback/nacos-included.xml} (71%) create mode 100644 core/src/main/java/com/alibaba/nacos/core/listener/LoggingSpringApplicationRunListener.java create mode 100644 core/src/main/resources/META-INF/logback/nacos.xml rename naming/src/{test => main}/java/com/alibaba/nacos/naming/NamingApp.java (100%) rename naming/src/main/resources/{naming-logback.xml => META-INF/logback/nacos-included.xml} (99%) diff --git a/config/pom.xml b/config/pom.xml index 60e16d6d9..d5637a5c2 100644 --- a/config/pom.xml +++ b/config/pom.xml @@ -154,7 +154,6 @@ - true src/main/resources application.properties diff --git a/config/src/test/java/com/alibaba/nacos/config/server/Config.java b/config/src/main/java/com/alibaba/nacos/config/server/Config.java similarity index 100% rename from config/src/test/java/com/alibaba/nacos/config/server/Config.java rename to config/src/main/java/com/alibaba/nacos/config/server/Config.java diff --git a/config/src/main/java/com/alibaba/nacos/config/server/utils/LogUtil.java b/config/src/main/java/com/alibaba/nacos/config/server/utils/LogUtil.java index ade7d2fe6..9beef6519 100755 --- a/config/src/main/java/com/alibaba/nacos/config/server/utils/LogUtil.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/utils/LogUtil.java @@ -15,9 +15,6 @@ */ package com.alibaba.nacos.config.server.utils; -import ch.qos.logback.classic.LoggerContext; -import ch.qos.logback.classic.joran.JoranConfigurator; -import ch.qos.logback.core.joran.spi.JoranException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -28,30 +25,6 @@ import org.slf4j.LoggerFactory; */ public class LogUtil { - static { - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - lc.reset(); - - JoranConfigurator configurator = new JoranConfigurator(); - - String nacosDir = System.getProperty("nacos.home"); - if (StringUtils.isBlank(nacosDir)) { - configurator.setContext(lc); - try { - configurator.doConfigure(LogUtil.class.getResource("/nacos-config-logback.xml")); - } catch (JoranException e) { - System.err.println("init logger fail by nacos-config-logback.xml"); - } - } else { - configurator.setContext(lc); - try { - configurator.doConfigure(nacosDir + "/conf/nacos-logback.xml"); - } catch (JoranException e) { - System.err.println("init logger fail by " + nacosDir + "/conf/nacos-logback.xml"); - } - } - } - /** * 默认的日志 */ diff --git a/config/src/main/resources/nacos-config-logback.xml b/config/src/main/resources/META-INF/logback/nacos-included.xml similarity index 71% rename from config/src/main/resources/nacos-config-logback.xml rename to config/src/main/resources/META-INF/logback/nacos-included.xml index 176c64e2e..0bc76ec69 100755 --- a/config/src/main/resources/nacos-config-logback.xml +++ b/config/src/main/resources/META-INF/logback/nacos-included.xml @@ -1,282 +1,282 @@ - - - - - ${user.home}/nacos/logs/config-dump.log - true - - ${user.home}/nacos/logs/config-dump.log.%d{yyyy-MM-dd}.%i - 2GB - 15 - 7GB - true - - - %date %level %msg%n%n - GBK - - - - ${user.home}/nacos/logs/config-pull.log - true - - ${user.home}/nacos/logs/config-pull.log.%d{yyyy-MM-dd}.%i - 20MB - 15 - 128MB - true - - - %date %level %msg%n%n - GBK - - - - ${user.home}/nacos/logs/config-fatal.log - true - - ${user.home}/nacos/logs/config-fatal.log.%d{yyyy-MM-dd}.%i - 20MB - 15 - 128MB - true - - - %date %level %msg%n%n - GBK - - - - ${user.home}/nacos/logs/config-memory.log - true - - ${user.home}/nacos/logs/config-memory.log.%d{yyyy-MM-dd}.%i - 20MB - 15 - 128MB - true - - - %date %level %msg%n%n - GBK - - - - ${user.home}/nacos/logs/config-pull-check.log - true - - ${user.home}/nacos/logs/config-pull-check.log.%d{yyyy-MM-dd}.%i - 1GB - 15 - 3GB - true - - - %msg%n - GBK - - - - - ${user.home}/nacos/logs/config-acl.log - true - - ${user.home}/nacos/logs/config-acl.log.%d{yyyy-MM-dd}.%i - 50MB - 15 - 512MB - true - - - %date %level %msg%n%n - GBK - - - - - ${user.home}/nacos/logs/config-client-request.log - true - - ${user.home}/nacos/logs/config-client-request.log.%d{yyyy-MM-dd}.%i - 2GB - 15 - 7GB - true - - - %date|%msg%n - GBK - - - - - ${user.home}/nacos/logs/config-sdk-request.log - true - - ${user.home}/nacos/logs/config-sdk-request.log.%d{yyyy-MM-dd}.%i - 1GB - 15 - 3GB - true - - - %date|%msg%n - GBK - - - - - ${user.home}/nacos/logs/config-trace.log - true - - ${user.home}/nacos/logs/config-trace.log.%d{yyyy-MM-dd}.%i - 2GB - 15 - 7GB - true - - - %date|%msg%n - GBK - - - - - ${user.home}/nacos/logs/config-notify.log - true - - ${user.home}/nacos/logs/config-notify.log.%d{yyyy-MM-dd}.%i - 1GB - 15 - 3GB - true - - - %date %level %msg%n%n - GBK - - - - - ${user.home}/nacos/logs/config-app.log - true - - ${user.home}/nacos/logs/config-app.log.%d{yyyy-MM-dd}.%i - 20MB - 15 - 128MB - true - - - %date %level %msg%n%n - GBK - - - - - ${user.home}/nacos/logs/config-server.log - true - - ${user.home}/nacos/logs/config-server.log.%d{yyyy-MM-dd}.%i - 50MB - 15 - 512MB - true - - - %date %level %msg%n%n - GBK - - - - - ${user.home}/nacos/logs/nacos.log - true - - ${user.home}/nacos/logs/nacos.log.%d{yyyy-MM-dd}.%i - 50MB - 15 - 512MB - true - - - %date %level %msg%n%n - GBK - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + ${user.home}/nacos/logs/config-dump.log + true + + ${user.home}/nacos/logs/config-dump.log.%d{yyyy-MM-dd}.%i + 2GB + 15 + 7GB + true + + + %date %level %msg%n%n + GBK + + + + ${user.home}/nacos/logs/config-pull.log + true + + ${user.home}/nacos/logs/config-pull.log.%d{yyyy-MM-dd}.%i + 20MB + 15 + 128MB + true + + + %date %level %msg%n%n + GBK + + + + ${user.home}/nacos/logs/config-fatal.log + true + + ${user.home}/nacos/logs/config-fatal.log.%d{yyyy-MM-dd}.%i + 20MB + 15 + 128MB + true + + + %date %level %msg%n%n + GBK + + + + ${user.home}/nacos/logs/config-memory.log + true + + ${user.home}/nacos/logs/config-memory.log.%d{yyyy-MM-dd}.%i + 20MB + 15 + 128MB + true + + + %date %level %msg%n%n + GBK + + + + ${user.home}/nacos/logs/config-pull-check.log + true + + ${user.home}/nacos/logs/config-pull-check.log.%d{yyyy-MM-dd}.%i + 1GB + 15 + 3GB + true + + + %msg%n + GBK + + + + + ${user.home}/nacos/logs/config-acl.log + true + + ${user.home}/nacos/logs/config-acl.log.%d{yyyy-MM-dd}.%i + 50MB + 15 + 512MB + true + + + %date %level %msg%n%n + GBK + + + + + ${user.home}/nacos/logs/config-client-request.log + true + + ${user.home}/nacos/logs/config-client-request.log.%d{yyyy-MM-dd}.%i + 2GB + 15 + 7GB + true + + + %date|%msg%n + GBK + + + + + ${user.home}/nacos/logs/config-sdk-request.log + true + + ${user.home}/nacos/logs/config-sdk-request.log.%d{yyyy-MM-dd}.%i + 1GB + 15 + 3GB + true + + + %date|%msg%n + GBK + + + + + ${user.home}/nacos/logs/config-trace.log + true + + ${user.home}/nacos/logs/config-trace.log.%d{yyyy-MM-dd}.%i + 2GB + 15 + 7GB + true + + + %date|%msg%n + GBK + + + + + ${user.home}/nacos/logs/config-notify.log + true + + ${user.home}/nacos/logs/config-notify.log.%d{yyyy-MM-dd}.%i + 1GB + 15 + 3GB + true + + + %date %level %msg%n%n + GBK + + + + + ${user.home}/nacos/logs/config-app.log + true + + ${user.home}/nacos/logs/config-app.log.%d{yyyy-MM-dd}.%i + 20MB + 15 + 128MB + true + + + %date %level %msg%n%n + GBK + + + + + ${user.home}/nacos/logs/config-server.log + true + + ${user.home}/nacos/logs/config-server.log.%d{yyyy-MM-dd}.%i + 50MB + 15 + 512MB + true + + + %date %level %msg%n%n + GBK + + + + + ${user.home}/nacos/logs/nacos.log + true + + ${user.home}/nacos/logs/nacos.log.%d{yyyy-MM-dd}.%i + 50MB + 15 + 512MB + true + + + %date %level %msg%n%n + GBK + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/src/main/java/com/alibaba/nacos/core/listener/LoggingSpringApplicationRunListener.java b/core/src/main/java/com/alibaba/nacos/core/listener/LoggingSpringApplicationRunListener.java new file mode 100644 index 000000000..686f12b68 --- /dev/null +++ b/core/src/main/java/com/alibaba/nacos/core/listener/LoggingSpringApplicationRunListener.java @@ -0,0 +1,103 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.nacos.core.listener; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.SpringApplicationRunListener; +import org.springframework.boot.context.event.EventPublishingRunListener; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.Ordered; +import org.springframework.core.env.ConfigurableEnvironment; + +import static org.springframework.boot.context.logging.LoggingApplicationListener.CONFIG_PROPERTY; +import static org.springframework.core.io.ResourceLoader.CLASSPATH_URL_PREFIX; + +/** + * Logging {@link SpringApplicationRunListener} before {@link EventPublishingRunListener} execution + * + * @author Mercy + * @since 0.2.2 + */ +public class LoggingSpringApplicationRunListener implements SpringApplicationRunListener, Ordered { + + private static final String DEFAULT_NACOS_LOGBACK_LOCATION = CLASSPATH_URL_PREFIX + "META-INF/logback/nacos.xml"; + + private static final Logger logger = LoggerFactory.getLogger(LoggingSpringApplicationRunListener.class); + + private final SpringApplication application; + + private final String[] args; + + + public LoggingSpringApplicationRunListener(SpringApplication application, String[] args) { + this.application = application; + this.args = args; + } + + @Override + public void starting() { + } + + @Override + public void environmentPrepared(ConfigurableEnvironment environment) { + if (!environment.containsProperty(CONFIG_PROPERTY)) { + System.setProperty(CONFIG_PROPERTY, DEFAULT_NACOS_LOGBACK_LOCATION); + if (logger.isInfoEnabled()) { + logger.info("There is no property named \"{}\" in Spring Boot Environment, " + + "and whose value is {} will be set into System's Properties", CONFIG_PROPERTY, + DEFAULT_NACOS_LOGBACK_LOCATION); + } + } + } + + @Override + public void contextPrepared(ConfigurableApplicationContext context) { + + } + + @Override + public void contextLoaded(ConfigurableApplicationContext context) { + + } + + @Override + public void started(ConfigurableApplicationContext context) { + + } + + @Override + public void running(ConfigurableApplicationContext context) { + + } + + @Override + public void failed(ConfigurableApplicationContext context, Throwable exception) { + + } + + /** + * Before {@link EventPublishingRunListener} + * + * @return HIGHEST_PRECEDENCE + */ + @Override + public int getOrder() { + return HIGHEST_PRECEDENCE; + } +} diff --git a/core/src/main/resources/META-INF/logback/nacos.xml b/core/src/main/resources/META-INF/logback/nacos.xml new file mode 100644 index 000000000..3191031dd --- /dev/null +++ b/core/src/main/resources/META-INF/logback/nacos.xml @@ -0,0 +1,30 @@ + + + + + + + + + + ${CONSOLE_LOG_PATTERN} + utf8 + + + + + + + + + + + + + + + + + + + diff --git a/core/src/main/resources/META-INF/spring.factories b/core/src/main/resources/META-INF/spring.factories index 17aca100e..51c264778 100644 --- a/core/src/main/resources/META-INF/spring.factories +++ b/core/src/main/resources/META-INF/spring.factories @@ -4,4 +4,8 @@ com.alibaba.nacos.core.listener.StandaloneProfileApplicationListener # EnvironmentPostProcessor org.springframework.boot.env.EnvironmentPostProcessor=\ -com.alibaba.nacos.core.env.NacosDefaultPropertySourceEnvironmentPostProcessor \ No newline at end of file +com.alibaba.nacos.core.env.NacosDefaultPropertySourceEnvironmentPostProcessor + +# SpringApplicationRunListener +org.springframework.boot.SpringApplicationRunListener=\ +com.alibaba.nacos.core.listener.LoggingSpringApplicationRunListener \ No newline at end of file diff --git a/naming/src/test/java/com/alibaba/nacos/naming/NamingApp.java b/naming/src/main/java/com/alibaba/nacos/naming/NamingApp.java similarity index 100% rename from naming/src/test/java/com/alibaba/nacos/naming/NamingApp.java rename to naming/src/main/java/com/alibaba/nacos/naming/NamingApp.java diff --git a/naming/src/main/java/com/alibaba/nacos/naming/misc/Loggers.java b/naming/src/main/java/com/alibaba/nacos/naming/misc/Loggers.java index a1c476846..67d2207ec 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/misc/Loggers.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/misc/Loggers.java @@ -15,39 +15,14 @@ */ package com.alibaba.nacos.naming.misc; -import ch.qos.logback.classic.LoggerContext; -import ch.qos.logback.classic.joran.JoranConfigurator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.File; - /** * @author nacos */ public class Loggers { - static { - - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - lc.reset(); - JoranConfigurator configurator = new JoranConfigurator(); - configurator.setContext(lc); - - try { - configurator.doConfigure(System.getProperty("nacos.home") + "/conf/nacos-logback.xml"); - } catch (Exception ignore) { - } - - try { - configurator.doConfigure(Loggers.class - .getResource("/naming-logback.xml")); - } catch (Exception e) { - e.printStackTrace(); - throw new RuntimeException("Init logger failed!", e); - } - } - public static final Logger PUSH = LoggerFactory.getLogger("com.alibaba.nacos.naming.push"); public static final Logger CHECK_RT = LoggerFactory.getLogger("com.alibaba.nacos.naming.rt"); diff --git a/naming/src/main/resources/naming-logback.xml b/naming/src/main/resources/META-INF/logback/nacos-included.xml similarity index 99% rename from naming/src/main/resources/naming-logback.xml rename to naming/src/main/resources/META-INF/logback/nacos-included.xml index 58500d543..ac4de5d03 100644 --- a/naming/src/main/resources/naming-logback.xml +++ b/naming/src/main/resources/META-INF/logback/nacos-included.xml @@ -1,5 +1,5 @@ - + @@ -242,5 +242,6 @@ - + + From a203ab309f06650391d9716e149cbe84a739748e Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Wed, 3 Oct 2018 04:01:40 +0800 Subject: [PATCH 24/30] Polish alibaba/nacos#94 : remove true --- naming/pom.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/naming/pom.xml b/naming/pom.xml index 5ee9b9d2c..d82c9e251 100644 --- a/naming/pom.xml +++ b/naming/pom.xml @@ -179,7 +179,6 @@ - true src/main/resources application.properties From baa3e307396990a4f46cdaf70aa5b811b1d5b9aa Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Wed, 3 Oct 2018 04:26:40 +0800 Subject: [PATCH 25/30] Polish alibaba/nacos#96 : fixed logging file name --- distribution/bin/startup.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/distribution/bin/startup.sh b/distribution/bin/startup.sh index 137e9860d..957b208c0 100644 --- a/distribution/bin/startup.sh +++ b/distribution/bin/startup.sh @@ -59,7 +59,7 @@ JAVA_OPT="${JAVA_OPT} -XX:-UseLargePages" JAVA_OPT="${JAVA_OPT} -jar ${BASE_DIR}/target/nacos-server.jar" JAVA_OPT="${JAVA_OPT} ${JAVA_OPT_EXT}" JAVA_OPT="${JAVA_OPT} --spring.config.location=${CUSTOM_SEARCH_LOCATIONS}" -JAVA_OPT="${JAVA_OPT} --logging.config=${BASE_DIR}/conf/nacos-nacos-included.xml" +JAVA_OPT="${JAVA_OPT} --logging.config=${BASE_DIR}/conf/nacos-logback.xml" if [ ! -d "${BASE_DIR}/logs" ]; then mkdir ${BASE_DIR}/logs fi From 91e8795486ae8e835e3cb6135c1113f2123d748a Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Wed, 3 Oct 2018 05:10:39 +0800 Subject: [PATCH 26/30] Polish alibaba/nacos#94 : fixed logback missing --- .../nacos/config/server/service/LocalDataSourceServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/LocalDataSourceServiceImpl.java b/config/src/main/java/com/alibaba/nacos/config/server/service/LocalDataSourceServiceImpl.java index abc105de5..2a322bd67 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/LocalDataSourceServiceImpl.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/LocalDataSourceServiceImpl.java @@ -151,7 +151,7 @@ public class LocalDataSourceServiceImpl implements DataSourceService { URL url = classLoader.getResource(sqlFile); sqlFileIn = url.openStream(); } else { - File file = new File(System.getProperty(NACOS_HOME_KEY) + File.separator + "conf" + File.separator + sqlFile); + File file = new File(System.getProperty(NACOS_HOME_KEY) + "/conf/schema.sql"); sqlFileIn = new FileInputStream(file); } From 356d994e3905dd6b3287aacf99167ac4334e478b Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Wed, 3 Oct 2018 21:58:09 +0800 Subject: [PATCH 27/30] Fixed PMD issue --- .../NacosDefaultPropertySourceEnvironmentPostProcessor.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/src/main/java/com/alibaba/nacos/core/env/NacosDefaultPropertySourceEnvironmentPostProcessor.java b/core/src/main/java/com/alibaba/nacos/core/env/NacosDefaultPropertySourceEnvironmentPostProcessor.java index 9d044b310..eaf7594b2 100644 --- a/core/src/main/java/com/alibaba/nacos/core/env/NacosDefaultPropertySourceEnvironmentPostProcessor.java +++ b/core/src/main/java/com/alibaba/nacos/core/env/NacosDefaultPropertySourceEnvironmentPostProcessor.java @@ -97,7 +97,8 @@ public class NacosDefaultPropertySourceEnvironmentPostProcessor implements Envir ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(resourceLoader); Resource[] resources = resourcePatternResolver.getResources(RESOURCE_LOCATION_PATTERN); for (Resource resource : resources) { - if (resource.exists()) { // Add if exists + // Add if exists + if (resource.exists()) { String internalName = String.valueOf(resource.getURL()); propertySource.addPropertySource(new ResourcePropertySource(internalName, new EncodedResource(resource, FILE_ENCODING))); From e08dca3d75e4a45655bf417bdb67497399116c04 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Thu, 4 Oct 2018 00:47:46 +0800 Subject: [PATCH 28/30] Polish alibaba/nacos#111 : Replace config module --- .../config/server/constant/Constants.java | 94 +++++++++++-------- .../config/server/constant/ConstantsTest.java | 55 +++++++++++ .../META-INF/nacos-default.properties | 1 - 3 files changed, 110 insertions(+), 40 deletions(-) create mode 100644 config/src/test/java/com/alibaba/nacos/config/server/constant/ConstantsTest.java diff --git a/config/src/main/java/com/alibaba/nacos/config/server/constant/Constants.java b/config/src/main/java/com/alibaba/nacos/config/server/constant/Constants.java index fae9f2c02..6e211bee8 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/constant/Constants.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/constant/Constants.java @@ -17,8 +17,8 @@ package com.alibaba.nacos.config.server.constant; /** * Server Constants - * @author Nacos * + * @author Nacos */ public class Constants { @@ -27,21 +27,21 @@ public class Constants { public static final String CLIENT_VERSION = "3.0.0"; public static int DATA_IN_BODY_VERSION = 204; - + public static final String DEFAULT_GROUP = "DEFAULT_GROUP"; /** - * server端配置文件基目录 + * server端配置文件基目录 */ public static final String BASE_DIR = "config-data"; - + /** * server端配置文件备份目录 */ public static final String CONFIG_BAK_DIR = System.getProperty("user.home", "/home/admin") + "/nacos/bak_data"; public static final String APPNAME = "AppName"; - + public static final String UNKNOWN_APP = "UnknownApp"; public static final String DEFAULT_DOMAINNAME = "commonconfig.config-host.taobao.com"; @@ -79,7 +79,7 @@ public class Constants { /** * 秒 */ - public static final int ASYNC_UPDATE_ADDRESS_INTERVAL = 300; + public static final int ASYNC_UPDATE_ADDRESS_INTERVAL = 300; /** * 秒 */ @@ -101,24 +101,40 @@ public class Constants { */ public static final int RECV_WAIT_TIMEOUT = ONCE_TIMEOUT * 5; - public static final String BASE_PATH = "/v1/cs"; - - public static final String OPS_CONTROLLER_PATH = BASE_PATH + "/ops"; + public static final String BASE_PATH = "/nacos/v1/cs"; - public static final String CAPACITY_CONTROLLER_PATH = BASE_PATH + "/capacity"; - - public static final String COMMUNICATION_CONTROLLER_PATH = BASE_PATH + "/communication"; - - public static final String CONFIG_CONTROLLER_PATH = BASE_PATH + "/configs"; - - public static final String HEALTH_CONTROLLER_PATH = BASE_PATH + "/health"; + public static final String DEFAULT_OPS_CONTROLLER_PATH = BASE_PATH + "/ops"; - public static final String HISTORY_CONTROLLER_PATH = BASE_PATH + "/history"; + public static final String OPS_CONTROLLER_PATH = "${nacos.config.ops.path" + ":" + DEFAULT_OPS_CONTROLLER_PATH + "}"; + + public static final String DEFAULT_CAPACITY_CONTROLLER_PATH = BASE_PATH + "/capacity"; + + public static final String CAPACITY_CONTROLLER_PATH = "${nacos.config.capacity.path" + ":" + DEFAULT_CAPACITY_CONTROLLER_PATH + "}"; + + public static final String DEFAULT_COMMUNICATION_CONTROLLER_PATH = BASE_PATH + "/communication"; + + public static final String COMMUNICATION_CONTROLLER_PATH = "${nacos.config.communication.path" + ":" + DEFAULT_COMMUNICATION_CONTROLLER_PATH + "}"; + + public static final String DEFAULT_CONFIG_CONTROLLER_PATH = BASE_PATH + "/configs"; + + public static final String CONFIG_CONTROLLER_PATH = "${nacos.config.path" + ":" + DEFAULT_CONFIG_CONTROLLER_PATH + "}"; + + public static final String DEFAULT_HEALTH_CONTROLLER_PATH = BASE_PATH + "/health"; + + public static final String HEALTH_CONTROLLER_PATH = "${nacos.config.health.path" + ":" + DEFAULT_HEALTH_CONTROLLER_PATH + "}"; + + public static final String DEFAULT_HISTORY_CONTROLLER_PATH = BASE_PATH + "/history"; + + public static final String HISTORY_CONTROLLER_PATH = "${nacos.config.history.path" + ":" + DEFAULT_HISTORY_CONTROLLER_PATH + "}"; + + public static final String DEFAULT_LISTENER_CONTROLLER_PATH = BASE_PATH + "/listener"; + + public static final String LISTENER_CONTROLLER_PATH = "${nacos.config.listener.path" + ":" + DEFAULT_LISTENER_CONTROLLER_PATH + "}"; + + public static final String DEFAULT_NAMESPACE_CONTROLLER_PATH = BASE_PATH + "/namespaces"; + + public static final String NAMESPACE_CONTROLLER_PATH = "${nacos.config.namespaces.path" + ":" + DEFAULT_NAMESPACE_CONTROLLER_PATH + "}"; - public static final String LISTENER_CONTROLLER_PATH = BASE_PATH + "/listener"; - - public static final String NAMESPACE_CONTROLLER_PATH = BASE_PATH + "/namespaces"; - public static final String ENCODE = "UTF-8"; public static final String MAP_FILE = "map-file.js"; @@ -136,11 +152,11 @@ public class Constants { public static final String NACOS_LINE_SEPARATOR = "\r\n"; /** - * 从网络获取数据的总时间, 当超过此时间, 不再从网络获取数据, 单位ms + * 从网络获取数据的总时间, 当超过此时间, 不再从网络获取数据, 单位ms */ public static final long TOTALTIME_FROM_SERVER = 10000; /** - * 从网络获取数据的总时间的失效时间, 单位ms + * 从网络获取数据的总时间的失效时间, 单位ms */ public static final long TOTALTIME_INVALID_THRESHOLD = 60000; @@ -148,27 +164,27 @@ public class Constants { * 批量操作时, 单条数据的状态码 */ /** - * 发生异常 + * 发生异常 */ public static final int BATCH_OP_ERROR = -1; public static final String BATCH_OP_ERROR_IO_MSG = "get config dump error"; public static final String BATCH_OP_ERROR_CONFLICT_MSG = "config get conflicts"; /** - * 查询成功, 数据存在 + * 查询成功, 数据存在 */ public static final int BATCH_QUERY_EXISTS = 1; public static final String BATCH_QUERY_EXISTS_MSG = "config exits"; /** - * 查询成功, 数据不存在 + * 查询成功, 数据不存在 */ public static final int BATCH_QUERY_NONEXISTS = 2; public static final String BATCH_QUERY_NONEEXISTS_MSG = "config not exits"; /** - * 新增成功 + * 新增成功 */ public static final int BATCH_ADD_SUCCESS = 3; /** - * 更新成功 + * 更新成功 */ public static final int BATCH_UPDATE_SUCCESS = 4; @@ -180,20 +196,20 @@ public class Constants { public static final int MAX_ADDACK_COUNT = 5; /** - * 数据的初始版本号 + * 数据的初始版本号 */ public static final int FIRST_VERSION = 1; /** - * 数据被删除的标识版本号 + * 数据被删除的标识版本号 */ public static final int POISON_VERSION = -1; /** - * 写磁盘文件时, 临时版本号 + * 写磁盘文件时, 临时版本号 */ public static final int TEMP_VERSION = 0; - /** - * 获取数据的顺序:容灾文件-> 服务器 -> 本地缓存 - */ + /** + * 获取数据的顺序:容灾文件-> 服务器 -> 本地缓存 + */ public static final int GETCONFIG_LOCAL_SERVER_SNAPSHOT = 1; /** * 获取数据的顺序:容灾文件-> 本地缓存 -> 服务器 @@ -204,13 +220,13 @@ public class Constants { public static final String CLIENT_REQUEST_TS_HEADER = "Client-RequestTS"; public static final String CLIENT_REQUEST_TOKEN_HEADER = "Client-RequestToken"; /** - * client, sdk请求server服务的身份 + * client, sdk请求server服务的身份 */ - public static final String REQUEST_IDENTITY = "Request-Identity"; + public static final String REQUEST_IDENTITY = "Request-Identity"; /** - * 鉴权结果信息 + * 鉴权结果信息 */ - public static final String ACL_RESPONSE = "ACL-Response"; - + public static final String ACL_RESPONSE = "ACL-Response"; + public static final int ATOMIC_MAX_SIZE = 1000; } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/constant/ConstantsTest.java b/config/src/test/java/com/alibaba/nacos/config/server/constant/ConstantsTest.java new file mode 100644 index 000000000..1177a4757 --- /dev/null +++ b/config/src/test/java/com/alibaba/nacos/config/server/constant/ConstantsTest.java @@ -0,0 +1,55 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.nacos.config.server.constant; + +import org.junit.Assert; +import org.junit.Test; +import org.springframework.mock.env.MockEnvironment; + +import static com.alibaba.nacos.config.server.constant.Constants.*; + +/** + * {@link Constants} Test + * + * @author Mercy + * @since 0.2.2 + */ +public class ConstantsTest { + + @Test + public void testControllerPathsDefaultValues() { + + MockEnvironment environment = new MockEnvironment(); + + Assert.assertEquals(DEFAULT_CAPACITY_CONTROLLER_PATH, environment.resolvePlaceholders(CAPACITY_CONTROLLER_PATH)); + Assert.assertEquals(DEFAULT_COMMUNICATION_CONTROLLER_PATH, environment.resolvePlaceholders(COMMUNICATION_CONTROLLER_PATH)); + Assert.assertEquals(DEFAULT_CONFIG_CONTROLLER_PATH, environment.resolvePlaceholders(CONFIG_CONTROLLER_PATH)); + Assert.assertEquals(DEFAULT_HEALTH_CONTROLLER_PATH, environment.resolvePlaceholders(HEALTH_CONTROLLER_PATH)); + Assert.assertEquals(DEFAULT_HISTORY_CONTROLLER_PATH, environment.resolvePlaceholders(HISTORY_CONTROLLER_PATH)); + Assert.assertEquals(DEFAULT_LISTENER_CONTROLLER_PATH, environment.resolvePlaceholders(LISTENER_CONTROLLER_PATH)); + Assert.assertEquals(DEFAULT_NAMESPACE_CONTROLLER_PATH, environment.resolvePlaceholders(NAMESPACE_CONTROLLER_PATH)); + + + Assert.assertEquals("/nacos/v1/cs/capacity", DEFAULT_CAPACITY_CONTROLLER_PATH); + Assert.assertEquals("/nacos/v1/cs/communication", DEFAULT_COMMUNICATION_CONTROLLER_PATH); + Assert.assertEquals("/nacos/v1/cs/configs", DEFAULT_CONFIG_CONTROLLER_PATH); + Assert.assertEquals("/nacos/v1/cs/health", DEFAULT_HEALTH_CONTROLLER_PATH); + Assert.assertEquals("/nacos/v1/cs/history", DEFAULT_HISTORY_CONTROLLER_PATH); + Assert.assertEquals("/nacos/v1/cs/listener", DEFAULT_LISTENER_CONTROLLER_PATH); + Assert.assertEquals("/nacos/v1/cs/namespaces", DEFAULT_NAMESPACE_CONTROLLER_PATH); + } +} diff --git a/core/src/main/resources/META-INF/nacos-default.properties b/core/src/main/resources/META-INF/nacos-default.properties index 917f3f203..d59c22de6 100644 --- a/core/src/main/resources/META-INF/nacos-default.properties +++ b/core/src/main/resources/META-INF/nacos-default.properties @@ -1,7 +1,6 @@ # Nacos Default Properties ## Web Server -server.servlet.context-path=/nacos server.port=8848 server.tomcat.uri-encoding=UTF-8 From 741ea7cbd73b58b60d0ef99162e991149d93daba Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Thu, 4 Oct 2018 00:53:05 +0800 Subject: [PATCH 29/30] Polish alibaba/nacos#111 : Replace naming module --- .../nacos/naming/misc/UtilsAndCommons.java | 6 ++- .../naming/misc/UtilsAndCommonsTest.java | 44 +++++++++++++++++++ 2 files changed, 48 insertions(+), 2 deletions(-) create mode 100644 naming/src/test/java/com/alibaba/nacos/naming/misc/UtilsAndCommonsTest.java diff --git a/naming/src/main/java/com/alibaba/nacos/naming/misc/UtilsAndCommons.java b/naming/src/main/java/com/alibaba/nacos/naming/misc/UtilsAndCommons.java index 33f8ce7dd..26b32c39e 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/misc/UtilsAndCommons.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/misc/UtilsAndCommons.java @@ -41,9 +41,11 @@ public class UtilsAndCommons { public static final String NACOS_SERVER_CONTEXT = "/nacos"; - public static final String NACOS_SERVER_VERSION = "/v1"; + public static final String NACOS_SERVER_VERSION = NACOS_SERVER_CONTEXT + "/v1"; - public static final String NACOS_NAMING_CONTEXT = NACOS_SERVER_VERSION + "/ns"; + public static final String DEFAULT_NACOS_NAMING_CONTEXT = NACOS_SERVER_VERSION + "/ns"; + + public static final String NACOS_NAMING_CONTEXT = "${nacos.naming.context.path" + ":" + DEFAULT_NACOS_NAMING_CONTEXT + "}"; public static final String NACOS_NAMING_INSTANCE_CONTEXT = "/instance"; diff --git a/naming/src/test/java/com/alibaba/nacos/naming/misc/UtilsAndCommonsTest.java b/naming/src/test/java/com/alibaba/nacos/naming/misc/UtilsAndCommonsTest.java new file mode 100644 index 000000000..89f7d2f2c --- /dev/null +++ b/naming/src/test/java/com/alibaba/nacos/naming/misc/UtilsAndCommonsTest.java @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.nacos.naming.misc; + +import org.junit.Assert; +import org.junit.Test; +import org.springframework.mock.env.MockEnvironment; + +import static com.alibaba.nacos.naming.misc.UtilsAndCommons.DEFAULT_NACOS_NAMING_CONTEXT; +import static com.alibaba.nacos.naming.misc.UtilsAndCommons.NACOS_NAMING_CONTEXT; + +/** + * {@link UtilsAndCommons} + * + * @author Mercy + * @since 0.2.2 + */ +public class UtilsAndCommonsTest { + + @Test + public void testControllerPathsDefaultValues() { + + MockEnvironment environment = new MockEnvironment(); + + Assert.assertEquals(DEFAULT_NACOS_NAMING_CONTEXT, environment.resolvePlaceholders(NACOS_NAMING_CONTEXT)); + + + Assert.assertEquals("/nacos/v1/ns", DEFAULT_NACOS_NAMING_CONTEXT); + } +} From 8d55b3fd33116329e32b771ee0555ce41a6ee21d Mon Sep 17 00:00:00 2001 From: xiaomage <1191971402@qq.com> Date: Fri, 5 Oct 2018 19:51:20 +0800 Subject: [PATCH 30/30] Bug fix --- .../alibaba/nacos/config/server/constant/Constants.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/config/src/main/java/com/alibaba/nacos/config/server/constant/Constants.java b/config/src/main/java/com/alibaba/nacos/config/server/constant/Constants.java index 6e211bee8..7272fbd01 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/constant/Constants.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/constant/Constants.java @@ -113,7 +113,9 @@ public class Constants { public static final String DEFAULT_COMMUNICATION_CONTROLLER_PATH = BASE_PATH + "/communication"; - public static final String COMMUNICATION_CONTROLLER_PATH = "${nacos.config.communication.path" + ":" + DEFAULT_COMMUNICATION_CONTROLLER_PATH + "}"; +// public static final String COMMUNICATION_CONTROLLER_PATH = "${nacos.config.communication.path" + ":" + DEFAULT_COMMUNICATION_CONTROLLER_PATH + "}"; + + public static final String COMMUNICATION_CONTROLLER_PATH = DEFAULT_COMMUNICATION_CONTROLLER_PATH; public static final String DEFAULT_CONFIG_CONTROLLER_PATH = BASE_PATH + "/configs"; @@ -121,7 +123,9 @@ public class Constants { public static final String DEFAULT_HEALTH_CONTROLLER_PATH = BASE_PATH + "/health"; - public static final String HEALTH_CONTROLLER_PATH = "${nacos.config.health.path" + ":" + DEFAULT_HEALTH_CONTROLLER_PATH + "}"; +// public static final String HEALTH_CONTROLLER_PATH = "${nacos.config.health.path" + ":" + DEFAULT_HEALTH_CONTROLLER_PATH + "}"; + + public static final String HEALTH_CONTROLLER_PATH = DEFAULT_HEALTH_CONTROLLER_PATH; public static final String DEFAULT_HISTORY_CONTROLLER_PATH = BASE_PATH + "/history";