Merge branch 'develop' into hotfix_337
This commit is contained in:
commit
52fe7d52c1
@ -40,9 +40,9 @@ It is super easy to get started with your first project.
|
|||||||
|
|
||||||
You can download the package from the [latest stable release](https://github.com/alibaba/nacos/releases).
|
You can download the package from the [latest stable release](https://github.com/alibaba/nacos/releases).
|
||||||
|
|
||||||
Take release nacos-server-0.4.0.zip for example.
|
Take release nacos-server-0.5.0.zip for example.
|
||||||
```
|
```
|
||||||
unzip nacos-server-0.4.0.zip
|
unzip nacos-server-0.5.0.zip
|
||||||
cd nacos/bin
|
cd nacos/bin
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -27,18 +27,15 @@ import com.alibaba.nacos.api.naming.NamingService;
|
|||||||
* Nacos Factory
|
* Nacos Factory
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public class NacosFactory {
|
public class NacosFactory {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create config
|
* Create config
|
||||||
*
|
*
|
||||||
* @param properties
|
* @param properties init param
|
||||||
* init param
|
|
||||||
* @return config
|
* @return config
|
||||||
* @throws NacosException
|
* @throws NacosException Exception
|
||||||
* Exception
|
|
||||||
*/
|
*/
|
||||||
public static ConfigService createConfigService(Properties properties) throws NacosException {
|
public static ConfigService createConfigService(Properties properties) throws NacosException {
|
||||||
return ConfigFactory.createConfigService(properties);
|
return ConfigFactory.createConfigService(properties);
|
||||||
@ -47,11 +44,9 @@ public class NacosFactory {
|
|||||||
/**
|
/**
|
||||||
* Create config
|
* Create config
|
||||||
*
|
*
|
||||||
* @param serverAddr
|
* @param serverAddr server list
|
||||||
* server list
|
|
||||||
* @return config
|
* @return config
|
||||||
* @throws NacosException
|
* @throws NacosException Exception
|
||||||
* Exception
|
|
||||||
*/
|
*/
|
||||||
public static ConfigService createConfigService(String serverAddr) throws NacosException {
|
public static ConfigService createConfigService(String serverAddr) throws NacosException {
|
||||||
return ConfigFactory.createConfigService(serverAddr);
|
return ConfigFactory.createConfigService(serverAddr);
|
||||||
@ -60,11 +55,9 @@ public class NacosFactory {
|
|||||||
/**
|
/**
|
||||||
* Create Naming
|
* Create Naming
|
||||||
*
|
*
|
||||||
* @param serverAddr
|
* @param serverAddr server list
|
||||||
* server list
|
|
||||||
* @return Naming
|
* @return Naming
|
||||||
* @throws NacosException
|
* @throws NacosException Exception
|
||||||
* Exception
|
|
||||||
*/
|
*/
|
||||||
public static NamingService createNamingService(String serverAddr) throws NacosException {
|
public static NamingService createNamingService(String serverAddr) throws NacosException {
|
||||||
return NamingFactory.createNamingService(serverAddr);
|
return NamingFactory.createNamingService(serverAddr);
|
||||||
@ -73,11 +66,9 @@ public class NacosFactory {
|
|||||||
/**
|
/**
|
||||||
* Create Naming
|
* Create Naming
|
||||||
*
|
*
|
||||||
* @param properties
|
* @param properties init param
|
||||||
* init param
|
|
||||||
* @return Naming
|
* @return Naming
|
||||||
* @throws NacosException
|
* @throws NacosException Exception
|
||||||
* Exception
|
|
||||||
*/
|
*/
|
||||||
public static NamingService createNamingService(Properties properties) throws NacosException {
|
public static NamingService createNamingService(Properties properties) throws NacosException {
|
||||||
return NamingFactory.createNamingService(properties);
|
return NamingFactory.createNamingService(properties);
|
||||||
|
@ -17,8 +17,8 @@ package com.alibaba.nacos.api;
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* properties key
|
* properties key
|
||||||
* @author Nacos
|
|
||||||
*
|
*
|
||||||
|
* @author Nacos
|
||||||
*/
|
*/
|
||||||
public class PropertyKeyConst {
|
public class PropertyKeyConst {
|
||||||
|
|
||||||
|
@ -19,7 +19,6 @@ package com.alibaba.nacos.api.common;
|
|||||||
* Constant
|
* Constant
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public class Constants {
|
public class Constants {
|
||||||
|
|
||||||
@ -111,9 +110,9 @@ public class Constants {
|
|||||||
|
|
||||||
public static final int FLOW_CONTROL_INTERVAL = 1000;
|
public static final int FLOW_CONTROL_INTERVAL = 1000;
|
||||||
|
|
||||||
public static final String LINE_SEPARATOR = Character.toString((char) 1);
|
public static final String LINE_SEPARATOR = Character.toString((char)1);
|
||||||
|
|
||||||
public static final String WORD_SEPARATOR = Character.toString((char) 2);
|
public static final String WORD_SEPARATOR = Character.toString((char)2);
|
||||||
|
|
||||||
public static final String LONGPULLING_LINE_SEPARATOR = "\r\n";
|
public static final String LONGPULLING_LINE_SEPARATOR = "\r\n";
|
||||||
|
|
||||||
|
@ -25,24 +25,21 @@ import com.alibaba.nacos.api.exception.NacosException;
|
|||||||
* Config Factory
|
* Config Factory
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public class ConfigFactory {
|
public class ConfigFactory {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create Config
|
* Create Config
|
||||||
*
|
*
|
||||||
* @param properties
|
* @param properties init param
|
||||||
* init param
|
|
||||||
* @return Config
|
* @return Config
|
||||||
* @throws NacosException
|
* @throws NacosException Exception
|
||||||
* Exception
|
|
||||||
*/
|
*/
|
||||||
public static ConfigService createConfigService(Properties properties) throws NacosException {
|
public static ConfigService createConfigService(Properties properties) throws NacosException {
|
||||||
try {
|
try {
|
||||||
Class<?> driverImplClass = Class.forName("com.alibaba.nacos.client.config.NacosConfigService");
|
Class<?> driverImplClass = Class.forName("com.alibaba.nacos.client.config.NacosConfigService");
|
||||||
Constructor constructor = driverImplClass.getConstructor(Properties.class);
|
Constructor constructor = driverImplClass.getConstructor(Properties.class);
|
||||||
ConfigService vendorImpl = (ConfigService) constructor.newInstance(properties);
|
ConfigService vendorImpl = (ConfigService)constructor.newInstance(properties);
|
||||||
return vendorImpl;
|
return vendorImpl;
|
||||||
} catch (Throwable e) {
|
} catch (Throwable e) {
|
||||||
throw new NacosException(-400, e.getMessage());
|
throw new NacosException(-400, e.getMessage());
|
||||||
@ -52,11 +49,9 @@ public class ConfigFactory {
|
|||||||
/**
|
/**
|
||||||
* Create Config
|
* Create Config
|
||||||
*
|
*
|
||||||
* @param ServerAddr
|
* @param ServerAddr serverlist
|
||||||
* serverlist
|
|
||||||
* @return Config
|
* @return Config
|
||||||
* @throws NacosException
|
* @throws NacosException Exception
|
||||||
* Exception
|
|
||||||
*/
|
*/
|
||||||
public static ConfigService createConfigService(String serverAddr) throws NacosException {
|
public static ConfigService createConfigService(String serverAddr) throws NacosException {
|
||||||
Properties properties = new Properties();
|
Properties properties = new Properties();
|
||||||
@ -64,7 +59,7 @@ public class ConfigFactory {
|
|||||||
try {
|
try {
|
||||||
Class<?> driverImplClass = Class.forName("com.alibaba.nacos.client.config.NacosConfigService");
|
Class<?> driverImplClass = Class.forName("com.alibaba.nacos.client.config.NacosConfigService");
|
||||||
Constructor constructor = driverImplClass.getConstructor(Properties.class);
|
Constructor constructor = driverImplClass.getConstructor(Properties.class);
|
||||||
ConfigService vendorImpl = (ConfigService) constructor.newInstance(properties);
|
ConfigService vendorImpl = (ConfigService)constructor.newInstance(properties);
|
||||||
return vendorImpl;
|
return vendorImpl;
|
||||||
} catch (Throwable e) {
|
} catch (Throwable e) {
|
||||||
throw new NacosException(-400, e.getMessage());
|
throw new NacosException(-400, e.getMessage());
|
||||||
|
@ -22,81 +22,60 @@ import com.alibaba.nacos.api.exception.NacosException;
|
|||||||
* Config Interface
|
* Config Interface
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public interface ConfigService {
|
public interface ConfigService {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get Configuration
|
* Get Configuration
|
||||||
*
|
*
|
||||||
* @param dataId
|
* @param dataId Config ID
|
||||||
* Config ID
|
* @param group Config Group
|
||||||
* @param group
|
* @param timeoutMs read timeout
|
||||||
* Config Group
|
|
||||||
* @param timeoutMs
|
|
||||||
* read timeout
|
|
||||||
* @return config value
|
* @return config value
|
||||||
* @throws NacosException
|
* @throws NacosException NacosException
|
||||||
* NacosException
|
|
||||||
*/
|
*/
|
||||||
String getConfig(String dataId, String group, long timeoutMs) throws NacosException;
|
String getConfig(String dataId, String group, long timeoutMs) throws NacosException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Add a listener to the configuration, after the server to modify the
|
* Add a listener to the configuration, after the server to modify the configuration, the client will use the
|
||||||
* configuration, the client will use the incoming listener callback.
|
* incoming listener callback. Recommended asynchronous processing, the application can implement the getExecutor
|
||||||
* Recommended asynchronous processing, the application can implement the
|
* method in the ManagerListener, provide a thread pool of execution. If provided, use the main thread callback, May
|
||||||
* getExecutor method in the ManagerListener, provide a thread pool of
|
* block other configurations or be blocked by other configurations.
|
||||||
* execution. If provided, use the main thread callback, May block other
|
|
||||||
* configurations or be blocked by other configurations.
|
|
||||||
*
|
*
|
||||||
* @param dataId
|
* @param dataId Config ID
|
||||||
* Config ID
|
* @param group Config Group
|
||||||
* @param group
|
* @param listener listener
|
||||||
* Config Group
|
* @throws NacosException NacosException
|
||||||
* @param listener
|
|
||||||
* listener
|
|
||||||
* @throws NacosException
|
|
||||||
* NacosException
|
|
||||||
*/
|
*/
|
||||||
void addListener(String dataId, String group, Listener listener) throws NacosException;
|
void addListener(String dataId, String group, Listener listener) throws NacosException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* publish config.
|
* publish config.
|
||||||
*
|
*
|
||||||
* @param dataId
|
* @param dataId Config ID
|
||||||
* Config ID
|
* @param group Config Group
|
||||||
* @param group
|
* @param content Config Content
|
||||||
* Config Group
|
|
||||||
* @param content
|
|
||||||
* Config Content
|
|
||||||
* @return Whether publish
|
* @return Whether publish
|
||||||
* @throws NacosException
|
* @throws NacosException NacosException
|
||||||
* NacosException
|
|
||||||
*/
|
*/
|
||||||
boolean publishConfig(String dataId, String group, String content) throws NacosException;
|
boolean publishConfig(String dataId, String group, String content) throws NacosException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Remove Config
|
* Remove Config
|
||||||
*
|
*
|
||||||
* @param dataId
|
* @param dataId Config ID
|
||||||
* Config ID
|
* @param group Config Group
|
||||||
* @param group
|
|
||||||
* Config Group
|
|
||||||
* @return whether remove
|
* @return whether remove
|
||||||
* @throws NacosException
|
* @throws NacosException NacosException
|
||||||
* NacosException
|
|
||||||
*/
|
*/
|
||||||
boolean removeConfig(String dataId, String group) throws NacosException;
|
boolean removeConfig(String dataId, String group) throws NacosException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Remove Listener
|
* Remove Listener
|
||||||
*
|
*
|
||||||
* @param dataId
|
* @param dataId Config ID
|
||||||
* Config ID
|
* @param group Config Group
|
||||||
* @param group
|
* @param listener listener
|
||||||
* Config Group
|
|
||||||
* @param listener
|
|
||||||
* listener
|
|
||||||
*/
|
*/
|
||||||
void removeListener(String dataId, String group, Listener listener);
|
void removeListener(String dataId, String group, Listener listener);
|
||||||
|
|
||||||
|
@ -56,8 +56,7 @@ public @interface NacosConfigListener {
|
|||||||
Class<? extends NacosConfigConverter> converter() default NacosConfigConverter.class;
|
Class<? extends NacosConfigConverter> converter() default NacosConfigConverter.class;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The {@link NacosProperties} attribute, If not specified, it will use
|
* The {@link NacosProperties} attribute, If not specified, it will use global Nacos Properties.
|
||||||
* global Nacos Properties.
|
|
||||||
*
|
*
|
||||||
* @return the default value is {@link NacosProperties}
|
* @return the default value is {@link NacosProperties}
|
||||||
*/
|
*/
|
||||||
|
@ -23,7 +23,6 @@ import java.lang.annotation.*;
|
|||||||
|
|
||||||
import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP;
|
import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An annotation for Nacos configuration Properties for binding POJO as Properties Object.
|
* An annotation for Nacos configuration Properties for binding POJO as Properties Object.
|
||||||
*
|
*
|
||||||
@ -51,51 +50,46 @@ public @interface NacosConfigurationProperties {
|
|||||||
String dataId();
|
String dataId();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* It indicates the properties of current doBind bean is auto-refreshed
|
* It indicates the properties of current doBind bean is auto-refreshed when Nacos configuration is changed.
|
||||||
* when Nacos configuration is changed.
|
|
||||||
*
|
*
|
||||||
* @return default value is <code>false</code>
|
* @return default value is <code>false</code>
|
||||||
*/
|
*/
|
||||||
boolean autoRefreshed() default false;
|
boolean autoRefreshed() default false;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Flag to indicate that when binding to this object invalid fields should be ignored.
|
* Flag to indicate that when binding to this object invalid fields should be ignored. Invalid means invalid
|
||||||
* Invalid means invalid according to the binder that is used, and usually this means
|
* according to the binder that is used, and usually this means fields of the wrong type (or that cannot be coerced
|
||||||
* fields of the wrong type (or that cannot be coerced into the correct type).
|
* into the correct type).
|
||||||
*
|
*
|
||||||
* @return the flag value (default false)
|
* @return the flag value (default false)
|
||||||
*/
|
*/
|
||||||
boolean ignoreInvalidFields() default false;
|
boolean ignoreInvalidFields() default false;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Flag to indicate that when binding to this object fields with periods in their
|
* Flag to indicate that when binding to this object fields with periods in their names should be ignored.
|
||||||
* names should be ignored.
|
|
||||||
*
|
*
|
||||||
* @return the flag value (default false)
|
* @return the flag value (default false)
|
||||||
*/
|
*/
|
||||||
boolean ignoreNestedProperties() default false;
|
boolean ignoreNestedProperties() default false;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Flag to indicate that when binding to this object unknown fields should be ignored.
|
* Flag to indicate that when binding to this object unknown fields should be ignored. An unknown field could be a
|
||||||
* An unknown field could be a sign of a mistake in the Properties.
|
* sign of a mistake in the Properties.
|
||||||
*
|
*
|
||||||
* @return the flag value (default true)
|
* @return the flag value (default true)
|
||||||
*/
|
*/
|
||||||
boolean ignoreUnknownFields() default true;
|
boolean ignoreUnknownFields() default true;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Flag to indicate that an exception should be raised if a Validator is available and
|
* Flag to indicate that an exception should be raised if a Validator is available and validation fails. If it is
|
||||||
* validation fails. If it is set to false, validation errors will be swallowed. They
|
* set to false, validation errors will be swallowed. They will be logged, but not propagated to the caller.
|
||||||
* will be logged, but not propagated to the caller.
|
|
||||||
*
|
*
|
||||||
* @return the flag value (default true)
|
* @return the flag value (default true)
|
||||||
*/
|
*/
|
||||||
boolean exceptionIfInvalid() default true;
|
boolean exceptionIfInvalid() default true;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The {@link NacosProperties} attribute, If not specified, it will use
|
* The {@link NacosProperties} attribute, If not specified, it will use global Nacos Properties.
|
||||||
* global Nacos Properties.
|
|
||||||
*
|
*
|
||||||
* @return the default value is {@link NacosProperties}
|
* @return the default value is {@link NacosProperties}
|
||||||
*/
|
*/
|
||||||
|
@ -18,8 +18,7 @@ package com.alibaba.nacos.api.config.annotation;
|
|||||||
import java.lang.annotation.*;
|
import java.lang.annotation.*;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An annotation for ignore field from annotated
|
* An annotation for ignore field from annotated {@link NacosConfigurationProperties} Properties Object.
|
||||||
* {@link NacosConfigurationProperties} Properties Object.
|
|
||||||
*
|
*
|
||||||
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
|
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
|
||||||
* @see NacosConfigurationProperties
|
* @see NacosConfigurationProperties
|
||||||
|
@ -18,9 +18,8 @@ package com.alibaba.nacos.api.config.annotation;
|
|||||||
import java.lang.annotation.*;
|
import java.lang.annotation.*;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An annotation for Nacos Property name of Nacos Configuration to
|
* An annotation for Nacos Property name of Nacos Configuration to bind a field from annotated {@link
|
||||||
* bind a field from annotated {@link NacosConfigurationProperties}
|
* NacosConfigurationProperties} Properties Object.
|
||||||
* Properties Object.
|
|
||||||
*
|
*
|
||||||
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
|
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
|
||||||
* @see NacosConfigurationProperties
|
* @see NacosConfigurationProperties
|
||||||
|
@ -40,5 +40,4 @@ public interface NacosConfigConverter<T> {
|
|||||||
*/
|
*/
|
||||||
T convert(String config);
|
T convert(String config);
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -19,7 +19,6 @@ package com.alibaba.nacos.api.config.filter;
|
|||||||
* Config Context Interface
|
* Config Context Interface
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public interface IConfigContext {
|
public interface IConfigContext {
|
||||||
/**
|
/**
|
||||||
@ -33,10 +32,8 @@ public interface IConfigContext {
|
|||||||
/**
|
/**
|
||||||
* set context
|
* set context
|
||||||
*
|
*
|
||||||
* @param key
|
* @param key key
|
||||||
* key
|
* @param value value
|
||||||
* @param value
|
|
||||||
* value
|
|
||||||
*/
|
*/
|
||||||
public void setParameter(String key, Object value);
|
public void setParameter(String key, Object value);
|
||||||
}
|
}
|
||||||
|
@ -21,28 +21,22 @@ import com.alibaba.nacos.api.exception.NacosException;
|
|||||||
* Config Filter Interface
|
* Config Filter Interface
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public interface IConfigFilter {
|
public interface IConfigFilter {
|
||||||
/**
|
/**
|
||||||
* Init Fuction
|
* Init Fuction
|
||||||
*
|
*
|
||||||
* @param filterConfig
|
* @param filterConfig Filter Config
|
||||||
* Filter Config
|
|
||||||
*/
|
*/
|
||||||
void init(IFilterConfig filterConfig);
|
void init(IFilterConfig filterConfig);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* do filter
|
* do filter
|
||||||
*
|
*
|
||||||
* @param request
|
* @param request request
|
||||||
* request
|
* @param response response
|
||||||
* @param response
|
* @param filterChain filter Chain
|
||||||
* response
|
* @throws NacosException exception
|
||||||
* @param filterChain
|
|
||||||
* filter Chain
|
|
||||||
* @throws NacosException
|
|
||||||
* exception
|
|
||||||
*/
|
*/
|
||||||
void doFilter(IConfigRequest request, IConfigResponse response, IConfigFilterChain filterChain)
|
void doFilter(IConfigRequest request, IConfigResponse response, IConfigFilterChain filterChain)
|
||||||
throws NacosException;
|
throws NacosException;
|
||||||
|
@ -21,18 +21,14 @@ import com.alibaba.nacos.api.exception.NacosException;
|
|||||||
* Config Filter Chain Interface
|
* Config Filter Chain Interface
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public interface IConfigFilterChain {
|
public interface IConfigFilterChain {
|
||||||
/**
|
/**
|
||||||
* Filter aciton
|
* Filter aciton
|
||||||
*
|
*
|
||||||
* @param request
|
* @param request request
|
||||||
* request
|
* @param response response
|
||||||
* @param response
|
* @throws NacosException NacosException
|
||||||
* response
|
|
||||||
* @throws NacosException
|
|
||||||
* NacosException
|
|
||||||
*/
|
*/
|
||||||
public void doFilter(IConfigRequest request, IConfigResponse response) throws NacosException;
|
public void doFilter(IConfigRequest request, IConfigResponse response) throws NacosException;
|
||||||
|
|
||||||
|
@ -19,14 +19,12 @@ package com.alibaba.nacos.api.config.filter;
|
|||||||
* Config Request Interface
|
* Config Request Interface
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public interface IConfigRequest {
|
public interface IConfigRequest {
|
||||||
/**
|
/**
|
||||||
* get param
|
* get param
|
||||||
*
|
*
|
||||||
* @param key
|
* @param key key
|
||||||
* key
|
|
||||||
* @return value
|
* @return value
|
||||||
*/
|
*/
|
||||||
public Object getParameter(String key);
|
public Object getParameter(String key);
|
||||||
|
@ -19,14 +19,12 @@ package com.alibaba.nacos.api.config.filter;
|
|||||||
* Config Response Interface
|
* Config Response Interface
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public interface IConfigResponse {
|
public interface IConfigResponse {
|
||||||
/**
|
/**
|
||||||
* get param
|
* get param
|
||||||
*
|
*
|
||||||
* @param key
|
* @param key key
|
||||||
* key
|
|
||||||
* @return value
|
* @return value
|
||||||
*/
|
*/
|
||||||
public Object getParameter(String key);
|
public Object getParameter(String key);
|
||||||
|
@ -14,10 +14,11 @@
|
|||||||
* limitations under the License.
|
* limitations under the License.
|
||||||
*/
|
*/
|
||||||
package com.alibaba.nacos.api.config.filter;
|
package com.alibaba.nacos.api.config.filter;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Filter Config Interface
|
* Filter Config Interface
|
||||||
* @author Nacos
|
|
||||||
*
|
*
|
||||||
|
* @author Nacos
|
||||||
*/
|
*/
|
||||||
public interface IFilterConfig {
|
public interface IFilterConfig {
|
||||||
|
|
||||||
|
@ -21,7 +21,6 @@ import java.util.concurrent.Executor;
|
|||||||
* Listner Adapter,use default notify thread
|
* Listner Adapter,use default notify thread
|
||||||
*
|
*
|
||||||
* @author water.lyl
|
* @author water.lyl
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("PMD.AbstractClassShouldStartWithAbstractNamingRule")
|
@SuppressWarnings("PMD.AbstractClassShouldStartWithAbstractNamingRule")
|
||||||
public abstract class AbstractListener implements Listener {
|
public abstract class AbstractListener implements Listener {
|
||||||
|
@ -21,7 +21,6 @@ import java.util.concurrent.Executor;
|
|||||||
* shared listener
|
* shared listener
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("PMD.AbstractClassShouldStartWithAbstractNamingRule")
|
@SuppressWarnings("PMD.AbstractClassShouldStartWithAbstractNamingRule")
|
||||||
public abstract class AbstractSharedListener implements Listener {
|
public abstract class AbstractSharedListener implements Listener {
|
||||||
@ -46,12 +45,9 @@ public abstract class AbstractSharedListener implements Listener {
|
|||||||
/**
|
/**
|
||||||
* receive
|
* receive
|
||||||
*
|
*
|
||||||
* @param dataId
|
* @param dataId data ID
|
||||||
* data ID
|
* @param group group
|
||||||
* @param group
|
* @param configInfo content
|
||||||
* group
|
|
||||||
* @param configInfo
|
|
||||||
* content
|
|
||||||
*/
|
*/
|
||||||
public abstract void innerReceive(String dataId, String group, String configInfo);
|
public abstract void innerReceive(String dataId, String group, String configInfo);
|
||||||
}
|
}
|
||||||
|
@ -17,12 +17,10 @@ package com.alibaba.nacos.api.config.listener;
|
|||||||
|
|
||||||
import java.util.concurrent.Executor;
|
import java.util.concurrent.Executor;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Listener for watch config
|
* Listener for watch config
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public interface Listener {
|
public interface Listener {
|
||||||
|
|
||||||
@ -33,7 +31,6 @@ public interface Listener {
|
|||||||
*/
|
*/
|
||||||
public Executor getExecutor();
|
public Executor getExecutor();
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 接收配置信息
|
* 接收配置信息
|
||||||
*
|
*
|
||||||
|
@ -19,9 +19,8 @@ package com.alibaba.nacos.api.exception;
|
|||||||
* Nacos Exception
|
* Nacos Exception
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public class NacosException extends Exception{
|
public class NacosException extends Exception {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* serialVersionUID
|
* serialVersionUID
|
||||||
@ -33,7 +32,9 @@ public class NacosException extends Exception{
|
|||||||
private String errMsg;
|
private String errMsg;
|
||||||
|
|
||||||
public NacosException() {
|
public NacosException() {
|
||||||
};
|
}
|
||||||
|
|
||||||
|
;
|
||||||
|
|
||||||
public NacosException(int errCode, String errMsg) {
|
public NacosException(int errCode, String errMsg) {
|
||||||
this.errCode = errCode;
|
this.errCode = errCode;
|
||||||
@ -74,7 +75,6 @@ public class NacosException extends Exception{
|
|||||||
*/
|
*/
|
||||||
public static final int CLIENT_OVER_THRESHOLD = -503;
|
public static final int CLIENT_OVER_THRESHOLD = -503;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* server error code
|
* server error code
|
||||||
* 400 403 throw exception to user
|
* 400 403 throw exception to user
|
||||||
@ -106,5 +106,4 @@ public class NacosException extends Exception{
|
|||||||
*/
|
*/
|
||||||
public static final int OVER_THRESHOLD = 503;
|
public static final int OVER_THRESHOLD = 503;
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -21,7 +21,7 @@ import java.util.Properties;
|
|||||||
import com.alibaba.nacos.api.exception.NacosException;
|
import com.alibaba.nacos.api.exception.NacosException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author dungu.zpf
|
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
|
||||||
*/
|
*/
|
||||||
public class NamingFactory {
|
public class NamingFactory {
|
||||||
|
|
||||||
@ -29,7 +29,7 @@ public class NamingFactory {
|
|||||||
try {
|
try {
|
||||||
Class<?> driverImplClass = Class.forName("com.alibaba.nacos.client.naming.NacosNamingService");
|
Class<?> driverImplClass = Class.forName("com.alibaba.nacos.client.naming.NacosNamingService");
|
||||||
Constructor constructor = driverImplClass.getConstructor(String.class);
|
Constructor constructor = driverImplClass.getConstructor(String.class);
|
||||||
NamingService vendorImpl = (NamingService) constructor.newInstance(serverList);
|
NamingService vendorImpl = (NamingService)constructor.newInstance(serverList);
|
||||||
return vendorImpl;
|
return vendorImpl;
|
||||||
} catch (Throwable e) {
|
} catch (Throwable e) {
|
||||||
throw new NacosException(-400, e.getMessage());
|
throw new NacosException(-400, e.getMessage());
|
||||||
@ -40,7 +40,7 @@ public class NamingFactory {
|
|||||||
try {
|
try {
|
||||||
Class<?> driverImplClass = Class.forName("com.alibaba.nacos.client.naming.NacosNamingService");
|
Class<?> driverImplClass = Class.forName("com.alibaba.nacos.client.naming.NacosNamingService");
|
||||||
Constructor constructor = driverImplClass.getConstructor(Properties.class);
|
Constructor constructor = driverImplClass.getConstructor(Properties.class);
|
||||||
NamingService vendorImpl = (NamingService) constructor.newInstance(properties);
|
NamingService vendorImpl = (NamingService)constructor.newInstance(properties);
|
||||||
return vendorImpl;
|
return vendorImpl;
|
||||||
} catch (Throwable e) {
|
} catch (Throwable e) {
|
||||||
throw new NacosException(-400, e.getMessage());
|
throw new NacosException(-400, e.getMessage());
|
||||||
|
@ -24,7 +24,7 @@ import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author dungu.zpf
|
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
|
||||||
*/
|
*/
|
||||||
public interface NamingService {
|
public interface NamingService {
|
||||||
|
|
||||||
|
@ -17,7 +17,7 @@ package com.alibaba.nacos.api.naming.listener;
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* event interface
|
* event interface
|
||||||
* @author dungu.zpf
|
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
|
||||||
*/
|
*/
|
||||||
public interface Event {
|
public interface Event {
|
||||||
}
|
}
|
||||||
|
@ -17,12 +17,13 @@ package com.alibaba.nacos.api.naming.listener;
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* event listener
|
* event listener
|
||||||
* @author Nacos
|
|
||||||
*
|
*
|
||||||
|
* @author Nacos
|
||||||
*/
|
*/
|
||||||
public interface EventListener {
|
public interface EventListener {
|
||||||
/**
|
/**
|
||||||
* callback event
|
* callback event
|
||||||
|
*
|
||||||
* @param event
|
* @param event
|
||||||
*/
|
*/
|
||||||
void onEvent(Event event);
|
void onEvent(Event event);
|
||||||
|
@ -20,7 +20,7 @@ import java.util.List;
|
|||||||
import com.alibaba.nacos.api.naming.pojo.Instance;
|
import com.alibaba.nacos.api.naming.pojo.Instance;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author dungu.zpf
|
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
|
||||||
*/
|
*/
|
||||||
public class NamingEvent implements Event {
|
public class NamingEvent implements Event {
|
||||||
|
|
||||||
|
@ -25,7 +25,7 @@ import java.util.Map;
|
|||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author dungu.zpf
|
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
|
||||||
*/
|
*/
|
||||||
public abstract class AbstractHealthChecker implements Cloneable {
|
public abstract class AbstractHealthChecker implements Cloneable {
|
||||||
|
|
||||||
@ -113,7 +113,7 @@ public abstract class AbstractHealthChecker implements Cloneable {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
Http other = (Http) obj;
|
Http other = (Http)obj;
|
||||||
|
|
||||||
if (!strEquals(type, other.getType())) {
|
if (!strEquals(type, other.getType())) {
|
||||||
return false;
|
return false;
|
||||||
@ -212,7 +212,7 @@ public abstract class AbstractHealthChecker implements Cloneable {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
Mysql other = (Mysql) obj;
|
Mysql other = (Mysql)obj;
|
||||||
|
|
||||||
if (!strEquals(user, other.getUser())) {
|
if (!strEquals(user, other.getUser())) {
|
||||||
return false;
|
return false;
|
||||||
|
@ -21,7 +21,7 @@ import java.util.HashMap;
|
|||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author dungu.zpf
|
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
|
||||||
*/
|
*/
|
||||||
public class Cluster {
|
public class Cluster {
|
||||||
|
|
||||||
@ -55,7 +55,6 @@ public class Cluster {
|
|||||||
*/
|
*/
|
||||||
private boolean useIPPort4Check = true;
|
private boolean useIPPort4Check = true;
|
||||||
|
|
||||||
|
|
||||||
private Map<String, String> metadata = new HashMap<String, String>();
|
private Map<String, String> metadata = new HashMap<String, String>();
|
||||||
|
|
||||||
public Cluster() {
|
public Cluster() {
|
||||||
|
@ -22,7 +22,7 @@ import java.util.HashMap;
|
|||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author dungu.zpf
|
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
|
||||||
*/
|
*/
|
||||||
public class Instance {
|
public class Instance {
|
||||||
|
|
||||||
@ -160,7 +160,7 @@ public class Instance {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
Instance host = (Instance) obj;
|
Instance host = (Instance)obj;
|
||||||
|
|
||||||
return strEquals(toString(), host.toString());
|
return strEquals(toString(), host.toString());
|
||||||
}
|
}
|
||||||
|
@ -20,7 +20,7 @@ import com.alibaba.fastjson.JSON;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author dungu.zpf
|
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
|
||||||
*/
|
*/
|
||||||
public class ListView<T> {
|
public class ListView<T> {
|
||||||
|
|
||||||
|
@ -19,7 +19,7 @@ import java.util.HashMap;
|
|||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author dungu.zpf
|
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
|
||||||
*/
|
*/
|
||||||
public class Service {
|
public class Service {
|
||||||
|
|
||||||
|
@ -22,7 +22,7 @@ import java.util.Collection;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author dungu.zpf
|
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
|
||||||
*/
|
*/
|
||||||
public class ServiceInfo {
|
public class ServiceInfo {
|
||||||
|
|
||||||
|
@ -44,8 +44,8 @@ import java.util.Properties;
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Config Impl
|
* Config Impl
|
||||||
* @author Nacos
|
|
||||||
*
|
*
|
||||||
|
* @author Nacos
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("PMD.ServiceOrDaoClassShouldEndWithImplRule")
|
@SuppressWarnings("PMD.ServiceOrDaoClassShouldEndWithImplRule")
|
||||||
public class NacosConfigService implements ConfigService {
|
public class NacosConfigService implements ConfigService {
|
||||||
|
@ -18,8 +18,7 @@ package com.alibaba.nacos.client.config.common;
|
|||||||
import com.alibaba.nacos.client.utils.StringUtils;
|
import com.alibaba.nacos.client.utils.StringUtils;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Synthesize the form of dataId+groupId. Escapes reserved characters in dataId
|
* Synthesize the form of dataId+groupId. Escapes reserved characters in dataId and groupId.
|
||||||
* and groupId.
|
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*/
|
*/
|
||||||
@ -100,12 +99,11 @@ public class GroupKey {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return new String[] { dataId, group, tenant };
|
return new String[] {dataId, group, tenant};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* + -> %2B
|
* + -> %2B % -> %25
|
||||||
* % -> %25
|
|
||||||
*/
|
*/
|
||||||
static void urlEncode(String str, StringBuilder sb) {
|
static void urlEncode(String str, StringBuilder sb) {
|
||||||
for (int idx = 0; idx < str.length(); ++idx) {
|
for (int idx = 0; idx < str.length(); ++idx) {
|
||||||
|
@ -24,7 +24,6 @@ import com.alibaba.nacos.api.config.filter.IConfigContext;
|
|||||||
* Config Context
|
* Config Context
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public class ConfigContext implements IConfigContext {
|
public class ConfigContext implements IConfigContext {
|
||||||
|
|
||||||
|
@ -28,7 +28,6 @@ import com.google.common.collect.Lists;
|
|||||||
* Config Filter Chain Management
|
* Config Filter Chain Management
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public class ConfigFilterChainManager implements IConfigFilterChain {
|
public class ConfigFilterChainManager implements IConfigFilterChain {
|
||||||
|
|
||||||
@ -56,7 +55,6 @@ public class ConfigFilterChainManager implements IConfigFilterChain {
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void doFilter(IConfigRequest request, IConfigResponse response) throws NacosException {
|
public void doFilter(IConfigRequest request, IConfigResponse response) throws NacosException {
|
||||||
new VirtualFilterChain(this.filters).doFilter(request, response);
|
new VirtualFilterChain(this.filters).doFilter(request, response);
|
||||||
|
@ -25,7 +25,6 @@ import com.alibaba.nacos.api.config.filter.IConfigRequest;
|
|||||||
* Config Request
|
* Config Request
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public class ConfigRequest implements IConfigRequest {
|
public class ConfigRequest implements IConfigRequest {
|
||||||
|
|
||||||
@ -34,7 +33,7 @@ public class ConfigRequest implements IConfigRequest {
|
|||||||
private IConfigContext configContext = new ConfigContext();
|
private IConfigContext configContext = new ConfigContext();
|
||||||
|
|
||||||
public String getTenant() {
|
public String getTenant() {
|
||||||
return (String) param.get("tenant");
|
return (String)param.get("tenant");
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setTenant(String tenant) {
|
public void setTenant(String tenant) {
|
||||||
@ -42,7 +41,7 @@ public class ConfigRequest implements IConfigRequest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public String getDataId() {
|
public String getDataId() {
|
||||||
return (String) param.get("dataId");
|
return (String)param.get("dataId");
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setDataId(String dataId) {
|
public void setDataId(String dataId) {
|
||||||
@ -50,7 +49,7 @@ public class ConfigRequest implements IConfigRequest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public String getGroup() {
|
public String getGroup() {
|
||||||
return (String) param.get("group");
|
return (String)param.get("group");
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setGroup(String group) {
|
public void setGroup(String group) {
|
||||||
@ -58,7 +57,7 @@ public class ConfigRequest implements IConfigRequest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public String getContent() {
|
public String getContent() {
|
||||||
return (String) param.get("content");
|
return (String)param.get("content");
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setContent(String content) {
|
public void setContent(String content) {
|
||||||
|
@ -25,7 +25,6 @@ import com.alibaba.nacos.api.config.filter.IConfigResponse;
|
|||||||
* Config Response
|
* Config Response
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public class ConfigResponse implements IConfigResponse {
|
public class ConfigResponse implements IConfigResponse {
|
||||||
|
|
||||||
@ -34,7 +33,7 @@ public class ConfigResponse implements IConfigResponse {
|
|||||||
private IConfigContext configContext = new ConfigContext();
|
private IConfigContext configContext = new ConfigContext();
|
||||||
|
|
||||||
public String getTenant() {
|
public String getTenant() {
|
||||||
return (String) param.get("tenant");
|
return (String)param.get("tenant");
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setTenant(String tenant) {
|
public void setTenant(String tenant) {
|
||||||
@ -42,7 +41,7 @@ public class ConfigResponse implements IConfigResponse {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public String getDataId() {
|
public String getDataId() {
|
||||||
return (String) param.get("dataId");
|
return (String)param.get("dataId");
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setDataId(String dataId) {
|
public void setDataId(String dataId) {
|
||||||
@ -50,7 +49,7 @@ public class ConfigResponse implements IConfigResponse {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public String getGroup() {
|
public String getGroup() {
|
||||||
return (String) param.get("group");
|
return (String)param.get("group");
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setGroup(String group) {
|
public void setGroup(String group) {
|
||||||
@ -58,7 +57,7 @@ public class ConfigResponse implements IConfigResponse {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public String getContent() {
|
public String getContent() {
|
||||||
return (String) param.get("content");
|
return (String)param.get("content");
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setContent(String content) {
|
public void setContent(String content) {
|
||||||
|
@ -34,7 +34,6 @@ import java.util.concurrent.CopyOnWriteArrayList;
|
|||||||
* Listner Management
|
* Listner Management
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public class CacheData {
|
public class CacheData {
|
||||||
|
|
||||||
@ -68,8 +67,7 @@ public class CacheData {
|
|||||||
/**
|
/**
|
||||||
* Add listener
|
* Add listener
|
||||||
*
|
*
|
||||||
* @param listener
|
* @param listener listener
|
||||||
* listener
|
|
||||||
*/
|
*/
|
||||||
public void addListener(Listener listener) {
|
public void addListener(Listener listener) {
|
||||||
if (null == listener) {
|
if (null == listener) {
|
||||||
@ -103,18 +101,18 @@ public class CacheData {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public long getLocalConfigInfoVersion() {
|
public long getLocalConfigInfoVersion() {
|
||||||
return localConfigLastModified;
|
return localConfigLastModified;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setLocalConfigInfoVersion(long localConfigLastModified) {
|
public void setLocalConfigInfoVersion(long localConfigLastModified) {
|
||||||
this.localConfigLastModified = localConfigLastModified;
|
this.localConfigLastModified = localConfigLastModified;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public boolean isUseLocalConfigInfo() {
|
public boolean isUseLocalConfigInfo() {
|
||||||
return isUseLocalConfig;
|
return isUseLocalConfig;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setUseLocalConfigInfo(boolean useLocalConfigInfo) {
|
public void setUseLocalConfigInfo(boolean useLocalConfigInfo) {
|
||||||
this.isUseLocalConfig = useLocalConfigInfo;
|
this.isUseLocalConfig = useLocalConfigInfo;
|
||||||
if (!useLocalConfigInfo) {
|
if (!useLocalConfigInfo) {
|
||||||
@ -147,7 +145,7 @@ public class CacheData {
|
|||||||
if (this == obj) {
|
if (this == obj) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
CacheData other = (CacheData) obj;
|
CacheData other = (CacheData)obj;
|
||||||
return dataId.equals(other.dataId) && group.equals(other.group);
|
return dataId.equals(other.dataId) && group.equals(other.group);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -171,10 +169,10 @@ public class CacheData {
|
|||||||
Runnable job = new Runnable() {
|
Runnable job = new Runnable() {
|
||||||
public void run() {
|
public void run() {
|
||||||
ClassLoader myClassLoader = Thread.currentThread().getContextClassLoader();
|
ClassLoader myClassLoader = Thread.currentThread().getContextClassLoader();
|
||||||
ClassLoader appClassLoader= listener.getClass().getClassLoader();
|
ClassLoader appClassLoader = listener.getClass().getClassLoader();
|
||||||
try {
|
try {
|
||||||
if(listener instanceof AbstractSharedListener){
|
if (listener instanceof AbstractSharedListener) {
|
||||||
AbstractSharedListener adapter = (AbstractSharedListener) listener;
|
AbstractSharedListener adapter = (AbstractSharedListener)listener;
|
||||||
adapter.fillContext(dataId, group);
|
adapter.fillContext(dataId, group);
|
||||||
log.info(name, "[notify-context] dataId={}, group={}, md5={}", dataId, group, md5);
|
log.info(name, "[notify-context] dataId={}, group={}, md5={}", dataId, group, md5);
|
||||||
}
|
}
|
||||||
@ -201,9 +199,7 @@ public class CacheData {
|
|||||||
log.error(name, "NACOS-XXXX",
|
log.error(name, "NACOS-XXXX",
|
||||||
"[notify-error] dataId={}, group={}, md5={}, listener={} tx={}", dataId, group, md5,
|
"[notify-error] dataId={}, group={}, md5={}, listener={} tx={}", dataId, group, md5,
|
||||||
listener, t.getCause());
|
listener, t.getCause());
|
||||||
}
|
} finally {
|
||||||
finally
|
|
||||||
{
|
|
||||||
Thread.currentThread().setContextClassLoader(myClassLoader);
|
Thread.currentThread().setContextClassLoader(myClassLoader);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -224,7 +220,8 @@ public class CacheData {
|
|||||||
dataId, group, md5, listener, t.getCause());
|
dataId, group, md5, listener, t.getCause());
|
||||||
}
|
}
|
||||||
final long finishNotify = System.currentTimeMillis();
|
final long finishNotify = System.currentTimeMillis();
|
||||||
log.info(name, "[notify-listener] time cost={}ms in ClientWorker, dataId={}, group={}, md5={}, listener={} ",(finishNotify - startNotify), dataId ,group, md5, listener);
|
log.info(name, "[notify-listener] time cost={}ms in ClientWorker, dataId={}, group={}, md5={}, listener={} ",
|
||||||
|
(finishNotify - startNotify), dataId, group, md5, listener);
|
||||||
}
|
}
|
||||||
|
|
||||||
static public String getMd5String(String config) {
|
static public String getMd5String(String config) {
|
||||||
@ -253,7 +250,8 @@ public class CacheData {
|
|||||||
this.md5 = getMd5String(content);
|
this.md5 = getMd5String(content);
|
||||||
}
|
}
|
||||||
|
|
||||||
public CacheData(ConfigFilterChainManager configFilterChainManager, String name, String dataId, String group, String tenant) {
|
public CacheData(ConfigFilterChainManager configFilterChainManager, String name, String dataId, String group,
|
||||||
|
String tenant) {
|
||||||
if (null == dataId || null == group) {
|
if (null == dataId || null == group) {
|
||||||
throw new IllegalArgumentException("dataId=" + dataId + ", group=" + group);
|
throw new IllegalArgumentException("dataId=" + dataId + ", group=" + group);
|
||||||
}
|
}
|
||||||
@ -307,7 +305,7 @@ class ManagerListenerWrap {
|
|||||||
if (obj == this) {
|
if (obj == this) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
ManagerListenerWrap other = (ManagerListenerWrap) obj;
|
ManagerListenerWrap other = (ManagerListenerWrap)obj;
|
||||||
return listener.equals(other.listener);
|
return listener.equals(other.listener);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -46,7 +46,6 @@ import static com.alibaba.nacos.api.common.Constants.WORD_SEPARATOR;
|
|||||||
* Longpulling
|
* Longpulling
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public class ClientWorker {
|
public class ClientWorker {
|
||||||
|
|
||||||
@ -128,12 +127,12 @@ public class ClientWorker {
|
|||||||
CacheData cacheFromMap = getCache(dataId, group);
|
CacheData cacheFromMap = getCache(dataId, group);
|
||||||
// multiple listeners on the same dataid+group and race condition,so double check again
|
// multiple listeners on the same dataid+group and race condition,so double check again
|
||||||
//other listener thread beat me to set to cacheMap
|
//other listener thread beat me to set to cacheMap
|
||||||
if(null != cacheFromMap) {
|
if (null != cacheFromMap) {
|
||||||
cache = cacheFromMap;
|
cache = cacheFromMap;
|
||||||
//reset so that server not hang this check
|
//reset so that server not hang this check
|
||||||
cache.setInitializing(true);
|
cache.setInitializing(true);
|
||||||
} else {
|
} else {
|
||||||
int taskId = cacheMap.get().size() / (int) ParamUtil.getPerTaskConfigSize();
|
int taskId = cacheMap.get().size() / (int)ParamUtil.getPerTaskConfigSize();
|
||||||
cache.setTaskId(taskId);
|
cache.setTaskId(taskId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -146,6 +145,7 @@ public class ClientWorker {
|
|||||||
|
|
||||||
return cache;
|
return cache;
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressFBWarnings("JLM_JSR166_UTILCONCURRENT_MONITORENTER")
|
@SuppressFBWarnings("JLM_JSR166_UTILCONCURRENT_MONITORENTER")
|
||||||
public CacheData addCacheDataIfAbsent(String dataId, String group, String tenant) {
|
public CacheData addCacheDataIfAbsent(String dataId, String group, String tenant) {
|
||||||
CacheData cache = getCache(dataId, group, tenant);
|
CacheData cache = getCache(dataId, group, tenant);
|
||||||
@ -184,7 +184,6 @@ public class ClientWorker {
|
|||||||
return cacheMap.get().get(GroupKey.getKeyTenant(dataId, group, tenant));
|
return cacheMap.get().get(GroupKey.getKeyTenant(dataId, group, tenant));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public String getServerConfig(String dataId, String group, String tenant, long readTimeout)
|
public String getServerConfig(String dataId, String group, String tenant, long readTimeout)
|
||||||
throws NacosException {
|
throws NacosException {
|
||||||
if (StringUtils.isBlank(group)) {
|
if (StringUtils.isBlank(group)) {
|
||||||
@ -286,9 +285,9 @@ public class ClientWorker {
|
|||||||
// 分任务
|
// 分任务
|
||||||
int listenerSize = cacheMap.get().size();
|
int listenerSize = cacheMap.get().size();
|
||||||
// 向上取整为批数
|
// 向上取整为批数
|
||||||
int longingTaskCount = (int) Math.ceil(listenerSize / ParamUtil.getPerTaskConfigSize());
|
int longingTaskCount = (int)Math.ceil(listenerSize / ParamUtil.getPerTaskConfigSize());
|
||||||
if (longingTaskCount > currentLongingTaskCount) {
|
if (longingTaskCount > currentLongingTaskCount) {
|
||||||
for (int i = (int) currentLongingTaskCount; i < longingTaskCount; i++) {
|
for (int i = (int)currentLongingTaskCount; i < longingTaskCount; i++) {
|
||||||
// 要判断任务是否在执行 这块需要好好想想。 任务列表现在是无序的。变化过程可能有问题
|
// 要判断任务是否在执行 这块需要好好想想。 任务列表现在是无序的。变化过程可能有问题
|
||||||
executorService.execute(new LongPullingRunnable(i));
|
executorService.execute(new LongPullingRunnable(i));
|
||||||
}
|
}
|
||||||
@ -521,7 +520,8 @@ public class ClientWorker {
|
|||||||
/**
|
/**
|
||||||
* groupKey -> cacheData
|
* groupKey -> cacheData
|
||||||
*/
|
*/
|
||||||
AtomicReference<Map<String, CacheData>> cacheMap = new AtomicReference<Map<String, CacheData>>(new HashMap<String, CacheData>());
|
AtomicReference<Map<String, CacheData>> cacheMap = new AtomicReference<Map<String, CacheData>>(
|
||||||
|
new HashMap<String, CacheData>());
|
||||||
ServerHttpAgent agent;
|
ServerHttpAgent agent;
|
||||||
ConfigFilterChainManager configFilterChainManager;
|
ConfigFilterChainManager configFilterChainManager;
|
||||||
private boolean isHealthServer = true;
|
private boolean isHealthServer = true;
|
||||||
|
@ -24,12 +24,10 @@ import java.util.concurrent.CopyOnWriteArrayList;
|
|||||||
import com.alibaba.nacos.client.config.utils.LogUtils;
|
import com.alibaba.nacos.client.config.utils.LogUtils;
|
||||||
import com.alibaba.nacos.client.logger.Logger;
|
import com.alibaba.nacos.client.logger.Logger;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Event subscription and publishing tools.
|
* Event subscription and publishing tools.
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public class EventDispatcher {
|
public class EventDispatcher {
|
||||||
|
|
||||||
@ -85,7 +83,8 @@ public class EventDispatcher {
|
|||||||
|
|
||||||
// ========================
|
// ========================
|
||||||
|
|
||||||
static final Map<Class<? extends AbstractEvent>, CopyOnWriteArrayList<AbstractEventListener>> LISTENER_MAP = new HashMap<Class<? extends AbstractEvent>, CopyOnWriteArrayList<AbstractEventListener>>();
|
static final Map<Class<? extends AbstractEvent>, CopyOnWriteArrayList<AbstractEventListener>> LISTENER_MAP
|
||||||
|
= new HashMap<Class<? extends AbstractEvent>, CopyOnWriteArrayList<AbstractEventListener>>();
|
||||||
|
|
||||||
// ========================
|
// ========================
|
||||||
|
|
||||||
@ -120,6 +119,7 @@ public class EventDispatcher {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 处理事件
|
* 处理事件
|
||||||
|
*
|
||||||
* @param abstractEvent event to do
|
* @param abstractEvent event to do
|
||||||
*/
|
*/
|
||||||
abstract public void onEvent(AbstractEvent abstractEvent);
|
abstract public void onEvent(AbstractEvent abstractEvent);
|
||||||
|
@ -36,13 +36,11 @@ import java.util.Map;
|
|||||||
* Http tool
|
* Http tool
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public class HttpSimpleClient {
|
public class HttpSimpleClient {
|
||||||
|
|
||||||
|
|
||||||
static public HttpResult httpGet(String url, List<String> headers, List<String> paramValues,
|
static public HttpResult httpGet(String url, List<String> headers, List<String> paramValues,
|
||||||
String encoding, long readTimeoutMs, boolean isSSL) throws IOException{
|
String encoding, long readTimeoutMs, boolean isSSL) throws IOException {
|
||||||
String encodedContent = encodingParams(paramValues, encoding);
|
String encodedContent = encodingParams(paramValues, encoding);
|
||||||
url += (null == encodedContent) ? "" : ("?" + encodedContent);
|
url += (null == encodedContent) ? "" : ("?" + encodedContent);
|
||||||
if (Limiter.isLimit(MD5.getInstance().getMD5String(
|
if (Limiter.isLimit(MD5.getInstance().getMD5String(
|
||||||
@ -54,10 +52,10 @@ public class HttpSimpleClient {
|
|||||||
HttpURLConnection conn = null;
|
HttpURLConnection conn = null;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
conn = (HttpURLConnection) new URL(url).openConnection();
|
conn = (HttpURLConnection)new URL(url).openConnection();
|
||||||
conn.setRequestMethod("GET");
|
conn.setRequestMethod("GET");
|
||||||
conn.setConnectTimeout(ParamUtil.getConnectTimeout() > 100 ? ParamUtil.getConnectTimeout() : 100);
|
conn.setConnectTimeout(ParamUtil.getConnectTimeout() > 100 ? ParamUtil.getConnectTimeout() : 100);
|
||||||
conn.setReadTimeout((int) readTimeoutMs);
|
conn.setReadTimeout((int)readTimeoutMs);
|
||||||
List<String> newHeaders = getHeaders(url, headers, paramValues);
|
List<String> newHeaders = getHeaders(url, headers, paramValues);
|
||||||
setHeaders(conn, newHeaders, encoding);
|
setHeaders(conn, newHeaders, encoding);
|
||||||
|
|
||||||
@ -79,7 +77,6 @@ public class HttpSimpleClient {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 发送GET请求。
|
* 发送GET请求。
|
||||||
*/
|
*/
|
||||||
@ -92,16 +89,11 @@ public class HttpSimpleClient {
|
|||||||
* 发送POST请求。
|
* 发送POST请求。
|
||||||
*
|
*
|
||||||
* @param url
|
* @param url
|
||||||
* @param headers
|
* @param headers 请求Header,可以为null
|
||||||
* 请求Header,可以为null
|
* @param paramValues 参数,可以为null
|
||||||
* @param paramValues
|
* @param encoding URL编码使用的字符集
|
||||||
* 参数,可以为null
|
* @param readTimeoutMs 响应超时
|
||||||
* @param encoding
|
* @param isSSL 是否https
|
||||||
* URL编码使用的字符集
|
|
||||||
* @param readTimeoutMs
|
|
||||||
* 响应超时
|
|
||||||
* @param isSSL
|
|
||||||
* 是否https
|
|
||||||
* @return
|
* @return
|
||||||
* @throws IOException
|
* @throws IOException
|
||||||
*/
|
*/
|
||||||
@ -115,10 +107,10 @@ public class HttpSimpleClient {
|
|||||||
}
|
}
|
||||||
HttpURLConnection conn = null;
|
HttpURLConnection conn = null;
|
||||||
try {
|
try {
|
||||||
conn = (HttpURLConnection) new URL(url).openConnection();
|
conn = (HttpURLConnection)new URL(url).openConnection();
|
||||||
conn.setRequestMethod("POST");
|
conn.setRequestMethod("POST");
|
||||||
conn.setConnectTimeout(ParamUtil.getConnectTimeout() > 3000 ? ParamUtil.getConnectTimeout() : 3000);
|
conn.setConnectTimeout(ParamUtil.getConnectTimeout() > 3000 ? ParamUtil.getConnectTimeout() : 3000);
|
||||||
conn.setReadTimeout((int) readTimeoutMs);
|
conn.setReadTimeout((int)readTimeoutMs);
|
||||||
conn.setDoOutput(true);
|
conn.setDoOutput(true);
|
||||||
conn.setDoInput(true);
|
conn.setDoInput(true);
|
||||||
List<String> newHeaders = getHeaders(url, headers, paramValues);
|
List<String> newHeaders = getHeaders(url, headers, paramValues);
|
||||||
@ -146,14 +138,10 @@ public class HttpSimpleClient {
|
|||||||
* 发送POST请求。
|
* 发送POST请求。
|
||||||
*
|
*
|
||||||
* @param url
|
* @param url
|
||||||
* @param headers
|
* @param headers 请求Header,可以为null
|
||||||
* 请求Header,可以为null
|
* @param paramValues 参数,可以为null
|
||||||
* @param paramValues
|
* @param encoding URL编码使用的字符集
|
||||||
* 参数,可以为null
|
* @param readTimeoutMs 响应超时
|
||||||
* @param encoding
|
|
||||||
* URL编码使用的字符集
|
|
||||||
* @param readTimeoutMs
|
|
||||||
* 响应超时
|
|
||||||
* @return
|
* @return
|
||||||
* @throws IOException
|
* @throws IOException
|
||||||
*/
|
*/
|
||||||
@ -162,9 +150,8 @@ public class HttpSimpleClient {
|
|||||||
return httpPost(url, headers, paramValues, encoding, readTimeoutMs, false);
|
return httpPost(url, headers, paramValues, encoding, readTimeoutMs, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
static public HttpResult httpDelete(String url, List<String> headers, List<String> paramValues,
|
static public HttpResult httpDelete(String url, List<String> headers, List<String> paramValues,
|
||||||
String encoding, long readTimeoutMs, boolean isSSL) throws IOException{
|
String encoding, long readTimeoutMs, boolean isSSL) throws IOException {
|
||||||
String encodedContent = encodingParams(paramValues, encoding);
|
String encodedContent = encodingParams(paramValues, encoding);
|
||||||
url += (null == encodedContent) ? "" : ("?" + encodedContent);
|
url += (null == encodedContent) ? "" : ("?" + encodedContent);
|
||||||
if (Limiter.isLimit(MD5.getInstance().getMD5String(
|
if (Limiter.isLimit(MD5.getInstance().getMD5String(
|
||||||
@ -176,10 +163,10 @@ public class HttpSimpleClient {
|
|||||||
HttpURLConnection conn = null;
|
HttpURLConnection conn = null;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
conn = (HttpURLConnection) new URL(url).openConnection();
|
conn = (HttpURLConnection)new URL(url).openConnection();
|
||||||
conn.setRequestMethod("DELETE");
|
conn.setRequestMethod("DELETE");
|
||||||
conn.setConnectTimeout(ParamUtil.getConnectTimeout() > 100 ? ParamUtil.getConnectTimeout() : 100);
|
conn.setConnectTimeout(ParamUtil.getConnectTimeout() > 100 ? ParamUtil.getConnectTimeout() : 100);
|
||||||
conn.setReadTimeout((int) readTimeoutMs);
|
conn.setReadTimeout((int)readTimeoutMs);
|
||||||
List<String> newHeaders = getHeaders(url, headers, paramValues);
|
List<String> newHeaders = getHeaders(url, headers, paramValues);
|
||||||
setHeaders(conn, newHeaders, encoding);
|
setHeaders(conn, newHeaders, encoding);
|
||||||
|
|
||||||
@ -201,7 +188,6 @@ public class HttpSimpleClient {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
static public HttpResult httpDelete(String url, List<String> headers, List<String> paramValues, String encoding,
|
static public HttpResult httpDelete(String url, List<String> headers, List<String> paramValues, String encoding,
|
||||||
long readTimeoutMs) throws IOException {
|
long readTimeoutMs) throws IOException {
|
||||||
return httpGet(url, headers, paramValues, encoding, readTimeoutMs, false);
|
return httpGet(url, headers, paramValues, encoding, readTimeoutMs, false);
|
||||||
@ -209,7 +195,7 @@ public class HttpSimpleClient {
|
|||||||
|
|
||||||
static private void setHeaders(HttpURLConnection conn, List<String> headers, String encoding) {
|
static private void setHeaders(HttpURLConnection conn, List<String> headers, String encoding) {
|
||||||
if (null != headers) {
|
if (null != headers) {
|
||||||
for (Iterator<String> iter = headers.iterator(); iter.hasNext();) {
|
for (Iterator<String> iter = headers.iterator(); iter.hasNext(); ) {
|
||||||
conn.addRequestProperty(iter.next(), iter.next());
|
conn.addRequestProperty(iter.next(), iter.next());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -231,7 +217,7 @@ public class HttpSimpleClient {
|
|||||||
newHeaders.add("true");
|
newHeaders.add("true");
|
||||||
newHeaders.add("RequestId");
|
newHeaders.add("RequestId");
|
||||||
newHeaders.add(UuidUtil.generateUuid());
|
newHeaders.add(UuidUtil.generateUuid());
|
||||||
if (headers!=null) {
|
if (headers != null) {
|
||||||
newHeaders.addAll(headers);
|
newHeaders.addAll(headers);
|
||||||
}
|
}
|
||||||
return newHeaders;
|
return newHeaders;
|
||||||
@ -244,7 +230,7 @@ public class HttpSimpleClient {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
for (Iterator<String> iter = paramValues.iterator(); iter.hasNext();) {
|
for (Iterator<String> iter = paramValues.iterator(); iter.hasNext(); ) {
|
||||||
sb.append(iter.next()).append("=");
|
sb.append(iter.next()).append("=");
|
||||||
sb.append(URLEncoder.encode(iter.next(), encoding));
|
sb.append(URLEncoder.encode(iter.next(), encoding));
|
||||||
if (iter.hasNext()) {
|
if (iter.hasNext()) {
|
||||||
@ -256,7 +242,7 @@ public class HttpSimpleClient {
|
|||||||
|
|
||||||
static public class HttpResult {
|
static public class HttpResult {
|
||||||
final public int code;
|
final public int code;
|
||||||
final public Map<String,List<String>> headers;
|
final public Map<String, List<String>> headers;
|
||||||
final public String content;
|
final public String content;
|
||||||
|
|
||||||
public HttpResult(int code, String content) {
|
public HttpResult(int code, String content) {
|
||||||
|
@ -29,7 +29,6 @@ import com.google.common.util.concurrent.RateLimiter;
|
|||||||
* Limiter
|
* Limiter
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public class Limiter {
|
public class Limiter {
|
||||||
|
|
||||||
|
@ -25,7 +25,6 @@ import java.io.FileInputStream;
|
|||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Local Disaster Recovery Directory Tool
|
* Local Disaster Recovery Directory Tool
|
||||||
*
|
*
|
||||||
@ -44,7 +43,7 @@ public class LocalConfigInfoProcessor {
|
|||||||
try {
|
try {
|
||||||
return readFile(localPath);
|
return readFile(localPath);
|
||||||
} catch (IOException ioe) {
|
} catch (IOException ioe) {
|
||||||
log.error(serverName, "NACOS-XXXX","get failover error, " + localPath + ioe.toString());
|
log.error(serverName, "NACOS-XXXX", "get failover error, " + localPath + ioe.toString());
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -64,7 +63,7 @@ public class LocalConfigInfoProcessor {
|
|||||||
try {
|
try {
|
||||||
return readFile(file);
|
return readFile(file);
|
||||||
} catch (IOException ioe) {
|
} catch (IOException ioe) {
|
||||||
log.error(name, "NACOS-XXXX","get snapshot error, " + file + ", " + ioe.toString());
|
log.error(name, "NACOS-XXXX", "get snapshot error, " + file + ", " + ioe.toString());
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -92,7 +91,6 @@ public class LocalConfigInfoProcessor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
static public void saveSnapshot(String envName, String dataId, String group, String tenant, String config) {
|
static public void saveSnapshot(String envName, String dataId, String group, String tenant, String config) {
|
||||||
if (!SnapShotSwitch.getIsSnapShot()) {
|
if (!SnapShotSwitch.getIsSnapShot()) {
|
||||||
return;
|
return;
|
||||||
@ -102,7 +100,7 @@ public class LocalConfigInfoProcessor {
|
|||||||
try {
|
try {
|
||||||
IOUtils.delete(file);
|
IOUtils.delete(file);
|
||||||
} catch (IOException ioe) {
|
} catch (IOException ioe) {
|
||||||
log.error(envName, "NACOS-XXXX","delete snapshot error, " + file + ", " + ioe.toString());
|
log.error(envName, "NACOS-XXXX", "delete snapshot error, " + file + ", " + ioe.toString());
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
try {
|
try {
|
||||||
@ -117,7 +115,7 @@ public class LocalConfigInfoProcessor {
|
|||||||
IOUtils.writeStringToFile(file, config, Constants.ENCODE);
|
IOUtils.writeStringToFile(file, config, Constants.ENCODE);
|
||||||
}
|
}
|
||||||
} catch (IOException ioe) {
|
} catch (IOException ioe) {
|
||||||
log.error(envName, "NACOS-XXXX","save snapshot error, " + file + ", " + ioe.toString());
|
log.error(envName, "NACOS-XXXX", "save snapshot error, " + file + ", " + ioe.toString());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -132,17 +130,17 @@ public class LocalConfigInfoProcessor {
|
|||||||
if (files == null || files.length == 0) {
|
if (files == null || files.length == 0) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
for(File file : files){
|
for (File file : files) {
|
||||||
if(file.getName().endsWith("_nacos")){
|
if (file.getName().endsWith("_nacos")) {
|
||||||
IOUtils.cleanDirectory(file);
|
IOUtils.cleanDirectory(file);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (IOException ioe) {
|
} catch (IOException ioe) {
|
||||||
log.error("NACOS-XXXX","clean all snapshot error, " + ioe.toString(), ioe);
|
log.error("NACOS-XXXX", "clean all snapshot error, " + ioe.toString(), ioe);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static public void cleanEnvSnapshot(String envName){
|
static public void cleanEnvSnapshot(String envName) {
|
||||||
File tmp = new File(LOCAL_SNAPSHOT_PATH, envName + "_nacos");
|
File tmp = new File(LOCAL_SNAPSHOT_PATH, envName + "_nacos");
|
||||||
tmp = new File(tmp, "snapshot");
|
tmp = new File(tmp, "snapshot");
|
||||||
try {
|
try {
|
||||||
@ -154,14 +152,12 @@ public class LocalConfigInfoProcessor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
static File getFailoverFile(String serverName, String dataId, String group, String tenant) {
|
static File getFailoverFile(String serverName, String dataId, String group, String tenant) {
|
||||||
File tmp = new File(LOCAL_SNAPSHOT_PATH, serverName + "_nacos");
|
File tmp = new File(LOCAL_SNAPSHOT_PATH, serverName + "_nacos");
|
||||||
tmp = new File(tmp, "data");
|
tmp = new File(tmp, "data");
|
||||||
if (StringUtils.isBlank(tenant)) {
|
if (StringUtils.isBlank(tenant)) {
|
||||||
tmp = new File(tmp, "config-data");
|
tmp = new File(tmp, "config-data");
|
||||||
} else
|
} else {
|
||||||
{
|
|
||||||
tmp = new File(tmp, "config-data-tenant");
|
tmp = new File(tmp, "config-data-tenant");
|
||||||
tmp = new File(tmp, tenant);
|
tmp = new File(tmp, tenant);
|
||||||
}
|
}
|
||||||
@ -182,6 +178,7 @@ public class LocalConfigInfoProcessor {
|
|||||||
|
|
||||||
public static final String LOCAL_FILEROOT_PATH;
|
public static final String LOCAL_FILEROOT_PATH;
|
||||||
public static final String LOCAL_SNAPSHOT_PATH;
|
public static final String LOCAL_SNAPSHOT_PATH;
|
||||||
|
|
||||||
static {
|
static {
|
||||||
LOCAL_FILEROOT_PATH = System.getProperty("JM.LOG.PATH", System.getProperty("user.home")) + File.separator
|
LOCAL_FILEROOT_PATH = System.getProperty("JM.LOG.PATH", System.getProperty("user.home")) + File.separator
|
||||||
+ "nacos" + File.separator + "config";
|
+ "nacos" + File.separator + "config";
|
||||||
|
@ -44,14 +44,13 @@ import java.util.Properties;
|
|||||||
* Server Agent
|
* Server Agent
|
||||||
*
|
*
|
||||||
* @author water.lyl
|
* @author water.lyl
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public class ServerHttpAgent {
|
public class ServerHttpAgent {
|
||||||
|
|
||||||
final static public Logger log = LogUtils.logger(ServerHttpAgent.class);
|
final static public Logger log = LogUtils.logger(ServerHttpAgent.class);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param path
|
* @param path 相对于web应用根,以/开头
|
||||||
* 相对于web应用根,以/开头
|
|
||||||
* @param headers
|
* @param headers
|
||||||
* @param paramValues
|
* @param paramValues
|
||||||
* @param encoding
|
* @param encoding
|
||||||
@ -78,21 +77,21 @@ public class ServerHttpAgent {
|
|||||||
|| result.code == HttpURLConnection.HTTP_BAD_GATEWAY
|
|| result.code == HttpURLConnection.HTTP_BAD_GATEWAY
|
||||||
|| result.code == HttpURLConnection.HTTP_UNAVAILABLE) {
|
|| result.code == HttpURLConnection.HTTP_UNAVAILABLE) {
|
||||||
log.error("NACOS ConnectException", "currentServerAddr:{}. httpCode:",
|
log.error("NACOS ConnectException", "currentServerAddr:{}. httpCode:",
|
||||||
new Object[] { serverListMgr.getCurrentServerAddr(), result.code });
|
new Object[] {serverListMgr.getCurrentServerAddr(), result.code});
|
||||||
} else {
|
} else {
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
} catch (ConnectException ce) {
|
} catch (ConnectException ce) {
|
||||||
log.error("NACOS ConnectException", "currentServerAddr:{}",
|
log.error("NACOS ConnectException", "currentServerAddr:{}",
|
||||||
new Object[] { serverListMgr.getCurrentServerAddr() });
|
new Object[] {serverListMgr.getCurrentServerAddr()});
|
||||||
serverListMgr.refreshCurrentServerAddr();
|
serverListMgr.refreshCurrentServerAddr();
|
||||||
} catch (SocketTimeoutException stoe) {
|
} catch (SocketTimeoutException stoe) {
|
||||||
log.error("NACOS SocketTimeoutException", "currentServerAddr:{}",
|
log.error("NACOS SocketTimeoutException", "currentServerAddr:{}",
|
||||||
new Object[] { serverListMgr.getCurrentServerAddr()});
|
new Object[] {serverListMgr.getCurrentServerAddr()});
|
||||||
serverListMgr.refreshCurrentServerAddr();
|
serverListMgr.refreshCurrentServerAddr();
|
||||||
} catch (IOException ioe) {
|
} catch (IOException ioe) {
|
||||||
log.error("NACOS IOException", "currentServerAddr:{}",
|
log.error("NACOS IOException", "currentServerAddr:{}",
|
||||||
new Object[] { serverListMgr.getCurrentServerAddr()});
|
new Object[] {serverListMgr.getCurrentServerAddr()});
|
||||||
throw ioe;
|
throw ioe;
|
||||||
}
|
}
|
||||||
} while (System.currentTimeMillis() <= endTime);
|
} while (System.currentTimeMillis() <= endTime);
|
||||||
@ -119,21 +118,21 @@ public class ServerHttpAgent {
|
|||||||
|| result.code == HttpURLConnection.HTTP_BAD_GATEWAY
|
|| result.code == HttpURLConnection.HTTP_BAD_GATEWAY
|
||||||
|| result.code == HttpURLConnection.HTTP_UNAVAILABLE) {
|
|| result.code == HttpURLConnection.HTTP_UNAVAILABLE) {
|
||||||
log.error("NACOS ConnectException", "currentServerAddr:{}. httpCode:",
|
log.error("NACOS ConnectException", "currentServerAddr:{}. httpCode:",
|
||||||
new Object[] { serverListMgr.getCurrentServerAddr(), result.code });
|
new Object[] {serverListMgr.getCurrentServerAddr(), result.code});
|
||||||
} else {
|
} else {
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
} catch (ConnectException ce) {
|
} catch (ConnectException ce) {
|
||||||
log.error("NACOS ConnectException", "currentServerAddr:{}",
|
log.error("NACOS ConnectException", "currentServerAddr:{}",
|
||||||
new Object[] { serverListMgr.getCurrentServerAddr()});
|
new Object[] {serverListMgr.getCurrentServerAddr()});
|
||||||
serverListMgr.refreshCurrentServerAddr();
|
serverListMgr.refreshCurrentServerAddr();
|
||||||
} catch (SocketTimeoutException stoe) {
|
} catch (SocketTimeoutException stoe) {
|
||||||
log.error("NACOS SocketTimeoutException", "currentServerAddr:{}",
|
log.error("NACOS SocketTimeoutException", "currentServerAddr:{}",
|
||||||
new Object[] { serverListMgr.getCurrentServerAddr()});
|
new Object[] {serverListMgr.getCurrentServerAddr()});
|
||||||
serverListMgr.refreshCurrentServerAddr();
|
serverListMgr.refreshCurrentServerAddr();
|
||||||
} catch (IOException ioe) {
|
} catch (IOException ioe) {
|
||||||
log.error("NACOS IOException", "currentServerAddr:{}",
|
log.error("NACOS IOException", "currentServerAddr:{}",
|
||||||
new Object[] { serverListMgr.getCurrentServerAddr()});
|
new Object[] {serverListMgr.getCurrentServerAddr()});
|
||||||
throw ioe;
|
throw ioe;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -161,21 +160,21 @@ public class ServerHttpAgent {
|
|||||||
|| result.code == HttpURLConnection.HTTP_BAD_GATEWAY
|
|| result.code == HttpURLConnection.HTTP_BAD_GATEWAY
|
||||||
|| result.code == HttpURLConnection.HTTP_UNAVAILABLE) {
|
|| result.code == HttpURLConnection.HTTP_UNAVAILABLE) {
|
||||||
log.error("NACOS ConnectException", "currentServerAddr:{}. httpCode:",
|
log.error("NACOS ConnectException", "currentServerAddr:{}. httpCode:",
|
||||||
new Object[] { serverListMgr.getCurrentServerAddr(), result.code });
|
new Object[] {serverListMgr.getCurrentServerAddr(), result.code});
|
||||||
} else {
|
} else {
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
} catch (ConnectException ce) {
|
} catch (ConnectException ce) {
|
||||||
log.error("NACOS ConnectException", "currentServerAddr:{}",
|
log.error("NACOS ConnectException", "currentServerAddr:{}",
|
||||||
new Object[] { serverListMgr.getCurrentServerAddr()});
|
new Object[] {serverListMgr.getCurrentServerAddr()});
|
||||||
serverListMgr.refreshCurrentServerAddr();
|
serverListMgr.refreshCurrentServerAddr();
|
||||||
} catch (SocketTimeoutException stoe) {
|
} catch (SocketTimeoutException stoe) {
|
||||||
log.error("NACOS SocketTimeoutException", "currentServerAddr:{}",
|
log.error("NACOS SocketTimeoutException", "currentServerAddr:{}",
|
||||||
new Object[] { serverListMgr.getCurrentServerAddr()});
|
new Object[] {serverListMgr.getCurrentServerAddr()});
|
||||||
serverListMgr.refreshCurrentServerAddr();
|
serverListMgr.refreshCurrentServerAddr();
|
||||||
} catch (IOException ioe) {
|
} catch (IOException ioe) {
|
||||||
log.error("NACOS IOException", "currentServerAddr:{}",
|
log.error("NACOS IOException", "currentServerAddr:{}",
|
||||||
new Object[] { serverListMgr.getCurrentServerAddr()});
|
new Object[] {serverListMgr.getCurrentServerAddr()});
|
||||||
throw ioe;
|
throw ioe;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -321,7 +320,8 @@ public class ServerHttpAgent {
|
|||||||
}
|
}
|
||||||
log.error(respCode + "", "can not get security credentials, securityCredentialsUrl:{}, response:{}",
|
log.error(respCode + "", "can not get security credentials, securityCredentialsUrl:{}, response:{}",
|
||||||
new Object[] {securityCredentialsUrl, response});
|
new Object[] {securityCredentialsUrl, response});
|
||||||
throw new IOException("can not get security credentials, responseCode: " + respCode + ", response: " + response);
|
throw new IOException(
|
||||||
|
"can not get security credentials, responseCode: " + respCode + ", response: " + response);
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getName() {
|
public String getName() {
|
||||||
@ -331,6 +331,7 @@ public class ServerHttpAgent {
|
|||||||
public String getNamespace() {
|
public String getNamespace() {
|
||||||
return serverListMgr.getNamespace();
|
return serverListMgr.getNamespace();
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getTenant() {
|
public String getTenant() {
|
||||||
return serverListMgr.getTenant();
|
return serverListMgr.getTenant();
|
||||||
}
|
}
|
||||||
|
@ -40,7 +40,6 @@ import com.alibaba.nacos.client.utils.StringUtils;
|
|||||||
|
|
||||||
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
|
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Serverlist Manager
|
* Serverlist Manager
|
||||||
*
|
*
|
||||||
@ -49,6 +48,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
|
|||||||
public class ServerListManager {
|
public class ServerListManager {
|
||||||
|
|
||||||
final static public Logger log = LogUtils.logger(ServerListManager.class);
|
final static public Logger log = LogUtils.logger(ServerListManager.class);
|
||||||
|
|
||||||
public ServerListManager() {
|
public ServerListManager() {
|
||||||
isFixed = false;
|
isFixed = false;
|
||||||
isStarted = false;
|
isStarted = false;
|
||||||
@ -209,7 +209,6 @@ public class ServerListManager {
|
|||||||
return new ServerAddressIterator(serverUrls);
|
return new ServerAddressIterator(serverUrls);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
class GetServerListTask implements Runnable {
|
class GetServerListTask implements Runnable {
|
||||||
final String url;
|
final String url;
|
||||||
|
|
||||||
@ -225,7 +224,8 @@ public class ServerListManager {
|
|||||||
try {
|
try {
|
||||||
updateIfChanged(getApacheServerList(url, name));
|
updateIfChanged(getApacheServerList(url, name));
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error(name, "NACOS-XXXX", "[update-serverlist] failed to update serverlist from address server!", e);
|
log.error(name, "NACOS-XXXX", "[update-serverlist] failed to update serverlist from address server!",
|
||||||
|
e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -233,7 +233,8 @@ public class ServerListManager {
|
|||||||
private void updateIfChanged(List<String> newList) {
|
private void updateIfChanged(List<String> newList) {
|
||||||
if (null == newList || newList.isEmpty()) {
|
if (null == newList || newList.isEmpty()) {
|
||||||
|
|
||||||
log.warn("NACOS-0001", LoggerHelper.getErrorCodeStr("NACOS", "NACOS-0001", "环境问题","[update-serverlist] current serverlist from address server is empty!!!"));
|
log.warn("NACOS-0001", LoggerHelper.getErrorCodeStr("NACOS", "NACOS-0001", "环境问题",
|
||||||
|
"[update-serverlist] current serverlist from address server is empty!!!"));
|
||||||
log.warn(name, "[update-serverlist] current serverlist from address server is empty!!!");
|
log.warn(name, "[update-serverlist] current serverlist from address server is empty!!!");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -255,7 +256,7 @@ public class ServerListManager {
|
|||||||
HttpResult httpResult = HttpSimpleClient.httpGet(url, null, null, null, 3000);
|
HttpResult httpResult = HttpSimpleClient.httpGet(url, null, null, null, 3000);
|
||||||
|
|
||||||
if (HttpURLConnection.HTTP_OK == httpResult.code) {
|
if (HttpURLConnection.HTTP_OK == httpResult.code) {
|
||||||
if (DEFAULT_NAME.equals(name) ) {
|
if (DEFAULT_NAME.equals(name)) {
|
||||||
EnvUtil.setSelfEnv(httpResult.headers);
|
EnvUtil.setSelfEnv(httpResult.headers);
|
||||||
}
|
}
|
||||||
List<String> lines = IOUtils.readLines(new StringReader(httpResult.content));
|
List<String> lines = IOUtils.readLines(new StringReader(httpResult.content));
|
||||||
@ -279,7 +280,7 @@ public class ServerListManager {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
log.error("NACOS-0001", LoggerHelper.getErrorCodeStr("NACOS", "NACOS-0001", "环境问题",e.toString()));
|
log.error("NACOS-0001", LoggerHelper.getErrorCodeStr("NACOS", "NACOS-0001", "环境问题", e.toString()));
|
||||||
log.error(addressServerUrl, "NACOS-XXXX", "[check-serverlist] exception. msg={}", e.toString(), e);
|
log.error(addressServerUrl, "NACOS-XXXX", "[check-serverlist] exception. msg={}", e.toString(), e);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@ -302,10 +303,10 @@ public class ServerListManager {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "ServerManager-" + name + "-" +getUrlString();
|
return "ServerManager-" + name + "-" + getUrlString();
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean contain(String ip){
|
public boolean contain(String ip) {
|
||||||
|
|
||||||
return serverUrls.contains(ip);
|
return serverUrls.contains(ip);
|
||||||
}
|
}
|
||||||
@ -321,7 +322,6 @@ public class ServerListManager {
|
|||||||
return currentServerAddr;
|
return currentServerAddr;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public String getContentPath() {
|
public String getContentPath() {
|
||||||
return contentPath;
|
return contentPath;
|
||||||
}
|
}
|
||||||
@ -369,7 +369,6 @@ public class ServerListManager {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 对地址列表排序,同机房优先。
|
* 对地址列表排序,同机房优先。
|
||||||
*/
|
*/
|
||||||
|
@ -29,7 +29,6 @@ import java.util.*;
|
|||||||
* 适配spas接口
|
* 适配spas接口
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public class SpasAdapter {
|
public class SpasAdapter {
|
||||||
|
|
||||||
@ -51,13 +50,12 @@ public class SpasAdapter {
|
|||||||
return header;
|
return header;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public static List<String> getSignHeaders(List<String> paramValues, String secretKey) {
|
public static List<String> getSignHeaders(List<String> paramValues, String secretKey) {
|
||||||
if (null == paramValues) {
|
if (null == paramValues) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
Map<String, String> signMap = new HashMap<String, String>(5);
|
Map<String, String> signMap = new HashMap<String, String>(5);
|
||||||
for (Iterator<String> iter = paramValues.iterator(); iter.hasNext();) {
|
for (Iterator<String> iter = paramValues.iterator(); iter.hasNext(); ) {
|
||||||
String key = iter.next();
|
String key = iter.next();
|
||||||
if (TENANT_KEY.equals(key) || GROUP_KEY.equals(key)) {
|
if (TENANT_KEY.equals(key) || GROUP_KEY.equals(key)) {
|
||||||
signMap.put(key, iter.next());
|
signMap.put(key, iter.next());
|
||||||
|
@ -21,11 +21,10 @@ import java.util.concurrent.ScheduledFuture;
|
|||||||
import java.util.concurrent.ThreadFactory;
|
import java.util.concurrent.ThreadFactory;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Time Service
|
* Time Service
|
||||||
* @author Nacos
|
|
||||||
*
|
*
|
||||||
|
* @author Nacos
|
||||||
*/
|
*/
|
||||||
public class TimerService {
|
public class TimerService {
|
||||||
|
|
||||||
|
@ -28,7 +28,6 @@ import java.util.Properties;
|
|||||||
* Properties Listener
|
* Properties Listener
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("PMD.AbstractClassShouldStartWithAbstractNamingRule")
|
@SuppressWarnings("PMD.AbstractClassShouldStartWithAbstractNamingRule")
|
||||||
public abstract class PropertiesListener extends AbstractListener {
|
public abstract class PropertiesListener extends AbstractListener {
|
||||||
@ -43,9 +42,8 @@ public abstract class PropertiesListener extends AbstractListener {
|
|||||||
try {
|
try {
|
||||||
properties.load(new StringReader(configInfo));
|
properties.load(new StringReader(configInfo));
|
||||||
innerReceive(properties);
|
innerReceive(properties);
|
||||||
}
|
} catch (IOException e) {
|
||||||
catch (IOException e) {
|
log.error("NACOS-XXXX", "load properties error:" + configInfo, e);
|
||||||
log.error("NACOS-XXXX","load properties error:" + configInfo, e);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@ -53,8 +51,7 @@ public abstract class PropertiesListener extends AbstractListener {
|
|||||||
/**
|
/**
|
||||||
* properties type for receiver
|
* properties type for receiver
|
||||||
*
|
*
|
||||||
* @param properties
|
* @param properties properties
|
||||||
* properties
|
|
||||||
*/
|
*/
|
||||||
public abstract void innerReceive(Properties properties);
|
public abstract void innerReceive(Properties properties);
|
||||||
|
|
||||||
|
@ -32,20 +32,16 @@ import java.nio.charset.CharsetDecoder;
|
|||||||
* concurrent disk util;op file with file lock
|
* concurrent disk util;op file with file lock
|
||||||
*
|
*
|
||||||
* @author configCenter
|
* @author configCenter
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public class ConcurrentDiskUtil {
|
public class ConcurrentDiskUtil {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* get file content
|
* get file content
|
||||||
*
|
*
|
||||||
* @param path
|
* @param path file path
|
||||||
* file path
|
* @param charsetName charsetName
|
||||||
* @param charsetName
|
|
||||||
* charsetName
|
|
||||||
* @return content
|
* @return content
|
||||||
* @throws IOException
|
* @throws IOException IOException
|
||||||
* IOException
|
|
||||||
*/
|
*/
|
||||||
public static String getFileContent(String path, String charsetName)
|
public static String getFileContent(String path, String charsetName)
|
||||||
throws IOException {
|
throws IOException {
|
||||||
@ -56,13 +52,10 @@ public class ConcurrentDiskUtil {
|
|||||||
/**
|
/**
|
||||||
* get file content
|
* get file content
|
||||||
*
|
*
|
||||||
* @param file
|
* @param file file
|
||||||
* file
|
* @param charsetName charsetName
|
||||||
* @param charsetName
|
|
||||||
* charsetName
|
|
||||||
* @return content
|
* @return content
|
||||||
* @throws IOException
|
* @throws IOException IOException
|
||||||
* IOException
|
|
||||||
*/
|
*/
|
||||||
public static String getFileContent(File file, String charsetName)
|
public static String getFileContent(File file, String charsetName)
|
||||||
throws IOException {
|
throws IOException {
|
||||||
@ -88,7 +81,7 @@ public class ConcurrentDiskUtil {
|
|||||||
i);
|
i);
|
||||||
}
|
}
|
||||||
} while (null == rlock);
|
} while (null == rlock);
|
||||||
int fileSize = (int) fcin.size();
|
int fileSize = (int)fcin.size();
|
||||||
ByteBuffer byteBuffer = ByteBuffer.allocate(fileSize);
|
ByteBuffer byteBuffer = ByteBuffer.allocate(fileSize);
|
||||||
fcin.read(byteBuffer);
|
fcin.read(byteBuffer);
|
||||||
byteBuffer.flip();
|
byteBuffer.flip();
|
||||||
@ -108,15 +101,11 @@ public class ConcurrentDiskUtil {
|
|||||||
/**
|
/**
|
||||||
* write file content
|
* write file content
|
||||||
*
|
*
|
||||||
* @param path
|
* @param path file path
|
||||||
* file path
|
* @param content content
|
||||||
* @param content
|
* @param charsetName charsetName
|
||||||
* content
|
|
||||||
* @param charsetName
|
|
||||||
* charsetName
|
|
||||||
* @return whether write ok
|
* @return whether write ok
|
||||||
* @throws IOException
|
* @throws IOException IOException
|
||||||
* IOException
|
|
||||||
*/
|
*/
|
||||||
public static Boolean writeFileContent(String path, String content,
|
public static Boolean writeFileContent(String path, String content,
|
||||||
String charsetName) throws IOException {
|
String charsetName) throws IOException {
|
||||||
@ -127,15 +116,11 @@ public class ConcurrentDiskUtil {
|
|||||||
/**
|
/**
|
||||||
* write file content
|
* write file content
|
||||||
*
|
*
|
||||||
* @param file
|
* @param file file
|
||||||
* file
|
* @param content content
|
||||||
* @param content
|
* @param charsetName charsetName
|
||||||
* content
|
|
||||||
* @param charsetName
|
|
||||||
* charsetName
|
|
||||||
* @return whether write ok
|
* @return whether write ok
|
||||||
* @throws IOException
|
* @throws IOException IOException
|
||||||
* IOException
|
|
||||||
*/
|
*/
|
||||||
public static Boolean writeFileContent(File file, String content,
|
public static Boolean writeFileContent(File file, String content,
|
||||||
String charsetName) throws IOException {
|
String charsetName) throws IOException {
|
||||||
@ -210,13 +195,10 @@ public class ConcurrentDiskUtil {
|
|||||||
/**
|
/**
|
||||||
* transfer ByteBuffer to String
|
* transfer ByteBuffer to String
|
||||||
*
|
*
|
||||||
* @param buffer
|
* @param buffer buffer
|
||||||
* buffer
|
* @param charsetName charsetName
|
||||||
* @param charsetName
|
|
||||||
* charsetName
|
|
||||||
* @return String
|
* @return String
|
||||||
* @throws IOException
|
* @throws IOException IOException
|
||||||
* IOException
|
|
||||||
*/
|
*/
|
||||||
public static String byteBufferToString(ByteBuffer buffer,
|
public static String byteBufferToString(ByteBuffer buffer,
|
||||||
String charsetName) throws IOException {
|
String charsetName) throws IOException {
|
||||||
|
@ -23,7 +23,6 @@ import static com.alibaba.nacos.api.common.Constants.WORD_SEPARATOR;
|
|||||||
* Content Util
|
* Content Util
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public class ContentUtils {
|
public class ContentUtils {
|
||||||
|
|
||||||
@ -43,7 +42,6 @@ public class ContentUtils {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public static String getContentIdentity(String content) {
|
public static String getContentIdentity(String content) {
|
||||||
int index = content.indexOf(WORD_SEPARATOR);
|
int index = content.indexOf(WORD_SEPARATOR);
|
||||||
if (index == -1) {
|
if (index == -1) {
|
||||||
@ -52,7 +50,6 @@ public class ContentUtils {
|
|||||||
return content.substring(0, index);
|
return content.substring(0, index);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public static String getContent(String content) {
|
public static String getContent(String content) {
|
||||||
int index = content.indexOf(WORD_SEPARATOR);
|
int index = content.indexOf(WORD_SEPARATOR);
|
||||||
if (index == -1) {
|
if (index == -1) {
|
||||||
@ -61,15 +58,12 @@ public class ContentUtils {
|
|||||||
return content.substring(index + 1);
|
return content.substring(index + 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public static String truncateContent(String content) {
|
public static String truncateContent(String content) {
|
||||||
if (content == null) {
|
if (content == null) {
|
||||||
return "";
|
return "";
|
||||||
}
|
} else if (content.length() <= SHOW_CONTENT_SIZE) {
|
||||||
else if (content.length() <= SHOW_CONTENT_SIZE) {
|
|
||||||
return content;
|
return content;
|
||||||
}
|
} else {
|
||||||
else {
|
|
||||||
return content.substring(0, SHOW_CONTENT_SIZE) + "...";
|
return content.substring(0, SHOW_CONTENT_SIZE) + "...";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -21,12 +21,10 @@ import java.io.*;
|
|||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* IO Util
|
* IO Util
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
|
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
|
||||||
public class IOUtils {
|
public class IOUtils {
|
||||||
@ -45,7 +43,7 @@ public class IOUtils {
|
|||||||
static public long copy(Reader input, Writer output) throws IOException {
|
static public long copy(Reader input, Writer output) throws IOException {
|
||||||
char[] buffer = new char[1 << 12];
|
char[] buffer = new char[1 << 12];
|
||||||
long count = 0;
|
long count = 0;
|
||||||
for (int n = 0; (n = input.read(buffer)) >= 0;) {
|
for (int n = 0; (n = input.read(buffer)) >= 0; ) {
|
||||||
output.write(buffer, 0, n);
|
output.write(buffer, 0, n);
|
||||||
count += n;
|
count += n;
|
||||||
}
|
}
|
||||||
@ -59,7 +57,7 @@ public class IOUtils {
|
|||||||
BufferedReader reader = toBufferedReader(input);
|
BufferedReader reader = toBufferedReader(input);
|
||||||
List<String> list = new ArrayList<String>();
|
List<String> list = new ArrayList<String>();
|
||||||
String line = null;
|
String line = null;
|
||||||
for (;;) {
|
for (; ; ) {
|
||||||
line = reader.readLine();
|
line = reader.readLine();
|
||||||
if (null != line) {
|
if (null != line) {
|
||||||
list.add(line);
|
list.add(line);
|
||||||
@ -71,7 +69,7 @@ public class IOUtils {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static private BufferedReader toBufferedReader(Reader reader) {
|
static private BufferedReader toBufferedReader(Reader reader) {
|
||||||
return reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(
|
return reader instanceof BufferedReader ? (BufferedReader)reader : new BufferedReader(
|
||||||
reader);
|
reader);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -21,7 +21,6 @@ import com.alibaba.nacos.client.logger.Logger;
|
|||||||
* Get jvm config
|
* Get jvm config
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
|
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
|
||||||
public class JVMUtil {
|
public class JVMUtil {
|
||||||
|
@ -24,7 +24,6 @@ import com.alibaba.nacos.client.logger.LoggerFactory;
|
|||||||
* Log Util
|
* Log Util
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public class LogUtils {
|
public class LogUtils {
|
||||||
|
|
||||||
@ -37,20 +36,21 @@ public class LogUtils {
|
|||||||
/**
|
/**
|
||||||
* change timeout from 100 to 200
|
* change timeout from 100 to 200
|
||||||
*/
|
*/
|
||||||
tmp = System.getProperty("JM.LOG.RETAIN.COUNT","7");
|
tmp = System.getProperty("JM.LOG.RETAIN.COUNT", "7");
|
||||||
JM_LOG_RETAIN_COUNT = Integer.parseInt(tmp);
|
JM_LOG_RETAIN_COUNT = Integer.parseInt(tmp);
|
||||||
} catch (NumberFormatException e) {
|
} catch (NumberFormatException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
|
|
||||||
JM_LOG_FILE_SIZE = System.getProperty("JM.LOG.FILE.SIZE","10MB");
|
JM_LOG_FILE_SIZE = System.getProperty("JM.LOG.FILE.SIZE", "10MB");
|
||||||
|
|
||||||
// logger init
|
// logger init
|
||||||
Logger logger = LoggerFactory.getLogger("com.alibaba.nacos.client.config");
|
Logger logger = LoggerFactory.getLogger("com.alibaba.nacos.client.config");
|
||||||
logger.setLevel(Level.INFO);
|
logger.setLevel(Level.INFO);
|
||||||
logger.setAdditivity(false);
|
logger.setAdditivity(false);
|
||||||
logger.activateAppenderWithSizeRolling("nacos", "config.log", Constants.ENCODE, JM_LOG_FILE_SIZE, JM_LOG_RETAIN_COUNT);
|
logger.activateAppenderWithSizeRolling("nacos", "config.log", Constants.ENCODE, JM_LOG_FILE_SIZE,
|
||||||
|
JM_LOG_RETAIN_COUNT);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Logger logger(Class<?> clazz) {
|
public static Logger logger(Class<?> clazz) {
|
||||||
|
@ -27,14 +27,14 @@ import java.util.concurrent.locks.ReentrantLock;
|
|||||||
* MD5 util
|
* MD5 util
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
|
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
|
||||||
public class MD5 {
|
public class MD5 {
|
||||||
private static int DIGITS_SIZE = 16;
|
private static int DIGITS_SIZE = 16;
|
||||||
private static char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
|
private static char[] digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
|
||||||
|
|
||||||
private static Map<Character, Integer> rDigits = new HashMap<Character, Integer>(16);
|
private static Map<Character, Integer> rDigits = new HashMap<Character, Integer>(16);
|
||||||
|
|
||||||
static {
|
static {
|
||||||
for (int i = 0; i < digits.length; ++i) {
|
for (int i = 0; i < digits.length; ++i) {
|
||||||
rDigits.put(digits[i], i);
|
rDigits.put(digits[i], i);
|
||||||
@ -45,38 +45,31 @@ public class MD5 {
|
|||||||
private MessageDigest mHasher;
|
private MessageDigest mHasher;
|
||||||
private ReentrantLock opLock = new ReentrantLock();
|
private ReentrantLock opLock = new ReentrantLock();
|
||||||
|
|
||||||
|
|
||||||
private MD5() {
|
private MD5() {
|
||||||
try {
|
try {
|
||||||
mHasher = MessageDigest.getInstance("md5");
|
mHasher = MessageDigest.getInstance("md5");
|
||||||
}
|
} catch (Exception e) {
|
||||||
catch (Exception e) {
|
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public static MD5 getInstance() {
|
public static MD5 getInstance() {
|
||||||
return me;
|
return me;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public String getMD5String(String content) {
|
public String getMD5String(String content) {
|
||||||
return bytes2string(hash(content));
|
return bytes2string(hash(content));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public String getMD5String(byte[] content) {
|
public String getMD5String(byte[] content) {
|
||||||
return bytes2string(hash(content));
|
return bytes2string(hash(content));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public byte[] getMD5Bytes(byte[] content) {
|
public byte[] getMD5Bytes(byte[] content) {
|
||||||
return hash(content);
|
return hash(content);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 对字符串进行md5
|
* 对字符串进行md5
|
||||||
*
|
*
|
||||||
@ -91,16 +84,13 @@ public class MD5 {
|
|||||||
throw new IllegalArgumentException("md5 need");
|
throw new IllegalArgumentException("md5 need");
|
||||||
}
|
}
|
||||||
return bt;
|
return bt;
|
||||||
}
|
} catch (UnsupportedEncodingException e) {
|
||||||
catch (UnsupportedEncodingException e) {
|
|
||||||
throw new RuntimeException("unsupported utf-8 encoding", e);
|
throw new RuntimeException("unsupported utf-8 encoding", e);
|
||||||
}
|
} finally {
|
||||||
finally {
|
|
||||||
opLock.unlock();
|
opLock.unlock();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 对二进制数据进行md5
|
* 对二进制数据进行md5
|
||||||
*
|
*
|
||||||
@ -115,13 +105,11 @@ public class MD5 {
|
|||||||
throw new IllegalArgumentException("md5 need");
|
throw new IllegalArgumentException("md5 need");
|
||||||
}
|
}
|
||||||
return bt;
|
return bt;
|
||||||
}
|
} finally {
|
||||||
finally {
|
|
||||||
opLock.unlock();
|
opLock.unlock();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 将一个字节数组转化为可见的字符串
|
* 将一个字节数组转化为可见的字符串
|
||||||
*
|
*
|
||||||
@ -141,5 +129,4 @@ public class MD5 {
|
|||||||
return new String(out);
|
return new String(out);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -25,12 +25,10 @@ import com.alibaba.nacos.client.utils.StringUtils;
|
|||||||
* Param check util
|
* Param check util
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public class ParamUtils {
|
public class ParamUtils {
|
||||||
|
|
||||||
private static char[] validChars = new char[] { '_', '-', '.', ':' };
|
private static char[] validChars = new char[] {'_', '-', '.', ':'};
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 白名单的方式检查, 合法的参数只能包含字母、数字、以及validChars中的字符, 并且不能为空
|
* 白名单的方式检查, 合法的参数只能包含字母、数字、以及validChars中的字符, 并且不能为空
|
||||||
@ -47,18 +45,15 @@ public class ParamUtils {
|
|||||||
char ch = param.charAt(i);
|
char ch = param.charAt(i);
|
||||||
if (Character.isLetterOrDigit(ch)) {
|
if (Character.isLetterOrDigit(ch)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
} else if (isValidChar(ch)) {
|
||||||
else if (isValidChar(ch)) {
|
|
||||||
continue;
|
continue;
|
||||||
}
|
} else {
|
||||||
else {
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
private static boolean isValidChar(char ch) {
|
private static boolean isValidChar(char ch) {
|
||||||
for (char c : validChars) {
|
for (char c : validChars) {
|
||||||
if (c == ch) {
|
if (c == ch) {
|
||||||
|
@ -21,7 +21,6 @@ import com.alibaba.nacos.client.config.impl.LocalConfigInfoProcessor;
|
|||||||
* Snapshot switch
|
* Snapshot switch
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public class SnapShotSwitch {
|
public class SnapShotSwitch {
|
||||||
|
|
||||||
|
@ -21,7 +21,6 @@ import com.alibaba.nacos.client.utils.StringUtils;
|
|||||||
* Tenant Util
|
* Tenant Util
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public class TenantUtil {
|
public class TenantUtil {
|
||||||
|
|
||||||
|
@ -19,39 +19,26 @@ package com.alibaba.nacos.client.identify;
|
|||||||
import java.io.UnsupportedEncodingException;
|
import java.io.UnsupportedEncodingException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Provides Base64 encoding and decoding as defined by <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>.
|
* Provides Base64 encoding and decoding as defined by <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>.
|
||||||
*
|
* <p>
|
||||||
* <p>
|
* <p> This class implements section <cite>6.8. Base64 Content-Transfer-Encoding</cite> from RFC 2045 <cite>Multipurpose
|
||||||
* This class implements section <cite>6.8. Base64 Content-Transfer-Encoding</cite> from RFC 2045 <cite>Multipurpose
|
* Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies</cite> by Freed and Borenstein. </p> <p>
|
||||||
* Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies</cite> by Freed and Borenstein.
|
* The class can be parameterized in the following manner with various constructors: <ul> <li>URL-safe mode: Default
|
||||||
* </p>
|
* off.</li> <li>Line length: Default 76. Line length that aren't multiples of 4 will still essentially end up being
|
||||||
* <p>
|
* multiples of 4 in the encoded data. <li>Line separator: Default is CRLF ("\r\n")</li> </ul> </p> <p> Since this class
|
||||||
* The class can be parameterized in the following manner with various constructors:
|
* operates directly on byte streams, and not character streams, it is hard-coded to only encode/decode character
|
||||||
* <ul>
|
* encodings which are compatible with the lower 127 ASCII chart (ISO-8859-1, Windows-1252, UTF-8, etc). </p> <p> This
|
||||||
* <li>URL-safe mode: Default off.</li>
|
* class is not thread-safe. Each thread should use its own instance. </p>
|
||||||
* <li>Line length: Default 76. Line length that aren't multiples of 4 will still essentially end up being multiples of
|
*
|
||||||
* 4 in the encoded data.
|
* @author Apache Software Foundation
|
||||||
* <li>Line separator: Default is CRLF ("\r\n")</li>
|
* @version $Revision: 1080712 $
|
||||||
* </ul>
|
* @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>
|
||||||
* </p>
|
* @since 1.0
|
||||||
* <p>
|
*/
|
||||||
* Since this class operates directly on byte streams, and not character streams, it is hard-coded to only encode/decode
|
|
||||||
* character encodings which are compatible with the lower 127 ASCII chart (ISO-8859-1, Windows-1252, UTF-8, etc).
|
|
||||||
* </p>
|
|
||||||
* <p>
|
|
||||||
* This class is not thread-safe. Each thread should use its own instance.
|
|
||||||
* </p>
|
|
||||||
*
|
|
||||||
* @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>
|
|
||||||
* @author Apache Software Foundation
|
|
||||||
* @since 1.0
|
|
||||||
* @version $Revision: 1080712 $
|
|
||||||
*/
|
|
||||||
public class Base64 {
|
public class Base64 {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* BASE32 characters are 6 bits in length.
|
* BASE32 characters are 6 bits in length. They are formed by taking a block of 3 octets to form a 24-bit string,
|
||||||
* They are formed by taking a block of 3 octets to form a 24-bit string,
|
|
||||||
* which is converted into 4 BASE64 characters.
|
* which is converted into 4 BASE64 characters.
|
||||||
*/
|
*/
|
||||||
private static final int BITS_PER_ENCODED_BYTE = 6;
|
private static final int BITS_PER_ENCODED_BYTE = 6;
|
||||||
@ -60,10 +47,8 @@ public class Base64 {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Chunk separator per RFC 2045 section 2.1.
|
* Chunk separator per RFC 2045 section 2.1.
|
||||||
*
|
|
||||||
* <p>
|
* <p>
|
||||||
* N.B. The next major release may break compatibility and make this field private.
|
* <p> N.B. The next major release may break compatibility and make this field private. </p>
|
||||||
* </p>
|
|
||||||
*
|
*
|
||||||
* @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 2.1</a>
|
* @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 2.1</a>
|
||||||
*/
|
*/
|
||||||
@ -72,9 +57,9 @@ public class Base64 {
|
|||||||
/**
|
/**
|
||||||
* This array is a lookup table that translates 6-bit positive integer index values into their "Base64 Alphabet"
|
* This array is a lookup table that translates 6-bit positive integer index values into their "Base64 Alphabet"
|
||||||
* equivalents as specified in Table 1 of RFC 2045.
|
* equivalents as specified in Table 1 of RFC 2045.
|
||||||
*
|
* <p>
|
||||||
* Thanks to "commons" project in ws.apache.org for this code.
|
* Thanks to "commons" project in ws.apache.org for this code. http://svn.apache
|
||||||
* http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
|
* .org/repos/asf/webservices/commons/trunk/modules/util/
|
||||||
*/
|
*/
|
||||||
private static final byte[] STANDARD_ENCODE_TABLE = {
|
private static final byte[] STANDARD_ENCODE_TABLE = {
|
||||||
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
|
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
|
||||||
@ -85,9 +70,8 @@ public class Base64 {
|
|||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This is a copy of the STANDARD_ENCODE_TABLE above, but with + and /
|
* This is a copy of the STANDARD_ENCODE_TABLE above, but with + and / changed to - and _ to make the encoded Base64
|
||||||
* changed to - and _ to make the encoded Base64 results more URL-SAFE.
|
* results more URL-SAFE. This table is only used when the Base64's mode is set to URL-SAFE.
|
||||||
* This table is only used when the Base64's mode is set to URL-SAFE.
|
|
||||||
*/
|
*/
|
||||||
private static final byte[] URL_SAFE_ENCODE_TABLE = {
|
private static final byte[] URL_SAFE_ENCODE_TABLE = {
|
||||||
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
|
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
|
||||||
@ -101,12 +85,12 @@ public class Base64 {
|
|||||||
* This array is a lookup table that translates Unicode characters drawn from the "Base64 Alphabet" (as specified in
|
* This array is a lookup table that translates Unicode characters drawn from the "Base64 Alphabet" (as specified in
|
||||||
* Table 1 of RFC 2045) into their 6-bit positive integer equivalents. Characters that are not in the Base64
|
* Table 1 of RFC 2045) into their 6-bit positive integer equivalents. Characters that are not in the Base64
|
||||||
* alphabet but fall within the bounds of the array are translated to -1.
|
* alphabet but fall within the bounds of the array are translated to -1.
|
||||||
*
|
* <p>
|
||||||
* Note: '+' and '-' both decode to 62. '/' and '_' both decode to 63. This means decoder seamlessly handles both
|
* Note: '+' and '-' both decode to 62. '/' and '_' both decode to 63. This means decoder seamlessly handles both
|
||||||
* URL_SAFE and STANDARD base64. (The encoder, on the other hand, needs to know ahead of time what to emit).
|
* URL_SAFE and STANDARD base64. (The encoder, on the other hand, needs to know ahead of time what to emit).
|
||||||
*
|
* <p>
|
||||||
* Thanks to "commons" project in ws.apache.org for this code.
|
* Thanks to "commons" project in ws.apache.org for this code. http://svn.apache
|
||||||
* http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
|
* .org/repos/asf/webservices/commons/trunk/modules/util/
|
||||||
*/
|
*/
|
||||||
private static final byte[] DECODE_TABLE = {
|
private static final byte[] DECODE_TABLE = {
|
||||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||||
@ -121,7 +105,9 @@ public class Base64 {
|
|||||||
/**
|
/**
|
||||||
* Base64 uses 6-bit fields.
|
* Base64 uses 6-bit fields.
|
||||||
*/
|
*/
|
||||||
/** Mask used to extract 6 bits, used when encoding */
|
/**
|
||||||
|
* Mask used to extract 6 bits, used when encoding
|
||||||
|
*/
|
||||||
private static final int MASK_6BITS = 0x3f;
|
private static final int MASK_6BITS = 0x3f;
|
||||||
|
|
||||||
// The static final fields above are used for the original static byte[] methods on Base64.
|
// The static final fields above are used for the original static byte[] methods on Base64.
|
||||||
@ -158,55 +144,43 @@ public class Base64 {
|
|||||||
private final int encodeSize;
|
private final int encodeSize;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Place holder for the bytes we're dealing with for our based logic.
|
* Place holder for the bytes we're dealing with for our based logic. Bitwise operations store and extract the
|
||||||
* Bitwise operations store and extract the encoding or decoding from this variable.
|
* encoding or decoding from this variable.
|
||||||
*/
|
*/
|
||||||
private int bitWorkArea;
|
private int bitWorkArea;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.
|
* Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode. <p> When encoding the line
|
||||||
|
* length is 0 (no chunking), and the encoding table is STANDARD_ENCODE_TABLE. </p>
|
||||||
* <p>
|
* <p>
|
||||||
* When encoding the line length is 0 (no chunking), and the encoding table is STANDARD_ENCODE_TABLE.
|
* <p> When decoding all variants are supported. </p>
|
||||||
* </p>
|
|
||||||
*
|
|
||||||
* <p>
|
|
||||||
* When decoding all variants are supported.
|
|
||||||
* </p>
|
|
||||||
*/
|
*/
|
||||||
public Base64() {
|
public Base64() {
|
||||||
this(0, CHUNK_SEPARATOR, false);
|
this(0, CHUNK_SEPARATOR, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.
|
* Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode. <p> When encoding the line
|
||||||
* <p>
|
* length and line separator are given in the constructor, and the encoding table is STANDARD_ENCODE_TABLE. </p> <p>
|
||||||
* When encoding the line length and line separator are given in the constructor, and the encoding table is
|
|
||||||
* STANDARD_ENCODE_TABLE.
|
|
||||||
* </p>
|
|
||||||
* <p>
|
|
||||||
* Line lengths that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data.
|
* Line lengths that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data.
|
||||||
* </p>
|
* </p> <p> When decoding all variants are supported. </p>
|
||||||
* <p>
|
|
||||||
* When decoding all variants are supported.
|
|
||||||
* </p>
|
|
||||||
*
|
*
|
||||||
* @param lineLength
|
* @param lineLength Each line of encoded data will be at most of the given length (rounded down to nearest
|
||||||
* Each line of encoded data will be at most of the given length (rounded down to nearest multiple of 4).
|
* multiple of 4). If lineLength <= 0, then the output will not be divided into lines (chunks).
|
||||||
* If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when decoding.
|
* Ignored when decoding.
|
||||||
* @param lineSeparator
|
* @param lineSeparator Each line of encoded data will end with this sequence of bytes.
|
||||||
* Each line of encoded data will end with this sequence of bytes.
|
* @param urlSafe Instead of emitting '+' and '/' we emit '-' and '_' respectively. urlSafe is only applied to
|
||||||
* @param urlSafe
|
* encode operations. Decoding seamlessly handles both modes.
|
||||||
* Instead of emitting '+' and '/' we emit '-' and '_' respectively. urlSafe is only applied to encode
|
* @throws IllegalArgumentException The provided lineSeparator included some base64 characters. That's not going to
|
||||||
* operations. Decoding seamlessly handles both modes.
|
* work!
|
||||||
* @throws IllegalArgumentException
|
|
||||||
* The provided lineSeparator included some base64 characters. That's not going to work!
|
|
||||||
* @since 1.4
|
* @since 1.4
|
||||||
*/
|
*/
|
||||||
public Base64(int lineLength, byte[] lineSeparator, boolean urlSafe) {
|
public Base64(int lineLength, byte[] lineSeparator, boolean urlSafe) {
|
||||||
chunkSeparatorLength = lineSeparator == null ? 0 : lineSeparator.length;
|
chunkSeparatorLength = lineSeparator == null ? 0 : lineSeparator.length;
|
||||||
unencodedBlockSize = BYTES_PER_UNENCODED_BLOCK;
|
unencodedBlockSize = BYTES_PER_UNENCODED_BLOCK;
|
||||||
encodedBlockSize = BYTES_PER_ENCODED_BLOCK;
|
encodedBlockSize = BYTES_PER_ENCODED_BLOCK;
|
||||||
this.lineLength = (lineLength > 0 && chunkSeparatorLength > 0) ? (lineLength / encodedBlockSize) * encodedBlockSize : 0;
|
this.lineLength = (lineLength > 0 && chunkSeparatorLength > 0) ? (lineLength / encodedBlockSize)
|
||||||
|
* encodedBlockSize : 0;
|
||||||
// TODO could be simplified if there is no requirement to reject invalid line sep when length <=0
|
// TODO could be simplified if there is no requirement to reject invalid line sep when length <=0
|
||||||
// @see test case Base64Test.testConstructors()
|
// @see test case Base64Test.testConstructors()
|
||||||
if (lineSeparator != null) {
|
if (lineSeparator != null) {
|
||||||
@ -218,7 +192,7 @@ public class Base64 {
|
|||||||
}
|
}
|
||||||
throw new IllegalArgumentException("lineSeparator must not contain base64 characters: [" + sep + "]");
|
throw new IllegalArgumentException("lineSeparator must not contain base64 characters: [" + sep + "]");
|
||||||
}
|
}
|
||||||
if (lineLength > 0){
|
if (lineLength > 0) {
|
||||||
this.encodeSize = BYTES_PER_ENCODED_BLOCK + lineSeparator.length;
|
this.encodeSize = BYTES_PER_ENCODED_BLOCK + lineSeparator.length;
|
||||||
this.lineSeparator = new byte[lineSeparator.length];
|
this.lineSeparator = new byte[lineSeparator.length];
|
||||||
System.arraycopy(lineSeparator, 0, this.lineSeparator, 0, lineSeparator.length);
|
System.arraycopy(lineSeparator, 0, this.lineSeparator, 0, lineSeparator.length);
|
||||||
@ -235,22 +209,15 @@ public class Base64 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* <p>
|
* <p> Encodes all of the provided data, starting at inPos, for inAvail bytes. Must be called at least twice: once
|
||||||
* Encodes all of the provided data, starting at inPos, for inAvail bytes. Must be called at least twice: once with
|
* with the data to encode, and once with inAvail set to "-1" to alert encoder that EOF has been reached, so flush
|
||||||
* the data to encode, and once with inAvail set to "-1" to alert encoder that EOF has been reached, so flush last
|
* last remaining bytes (if not multiple of 3). </p> <p> Thanks to "commons" project in ws.apache.org for the
|
||||||
* remaining bytes (if not multiple of 3).
|
* bitwise operations, and general approach. http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
|
||||||
* </p>
|
|
||||||
* <p>
|
|
||||||
* Thanks to "commons" project in ws.apache.org for the bitwise operations, and general approach.
|
|
||||||
* http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
|
|
||||||
* </p>
|
* </p>
|
||||||
*
|
*
|
||||||
* @param in
|
* @param in byte[] array of binary data to base64 encode.
|
||||||
* byte[] array of binary data to base64 encode.
|
* @param inPos Position to start reading data from.
|
||||||
* @param inPos
|
* @param inAvail Amount of bytes available from input for encoding.
|
||||||
* Position to start reading data from.
|
|
||||||
* @param inAvail
|
|
||||||
* Amount of bytes available from input for encoding.
|
|
||||||
*/
|
*/
|
||||||
void encode(byte[] in, int inPos, int inAvail) {
|
void encode(byte[] in, int inPos, int inAvail) {
|
||||||
if (eof) {
|
if (eof) {
|
||||||
@ -264,7 +231,7 @@ public class Base64 {
|
|||||||
ensureBufferSize(encodeSize);
|
ensureBufferSize(encodeSize);
|
||||||
int savedPos = pos;
|
int savedPos = pos;
|
||||||
switch (modulus) {
|
switch (modulus) {
|
||||||
case 1 :
|
case 1:
|
||||||
buffer[pos++] = encodeTable[(bitWorkArea >> 2) & MASK_6BITS];
|
buffer[pos++] = encodeTable[(bitWorkArea >> 2) & MASK_6BITS];
|
||||||
buffer[pos++] = encodeTable[(bitWorkArea << 4) & MASK_6BITS];
|
buffer[pos++] = encodeTable[(bitWorkArea << 4) & MASK_6BITS];
|
||||||
|
|
||||||
@ -274,7 +241,7 @@ public class Base64 {
|
|||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 2 :
|
case 2:
|
||||||
buffer[pos++] = encodeTable[(bitWorkArea >> 10) & MASK_6BITS];
|
buffer[pos++] = encodeTable[(bitWorkArea >> 10) & MASK_6BITS];
|
||||||
buffer[pos++] = encodeTable[(bitWorkArea >> 4) & MASK_6BITS];
|
buffer[pos++] = encodeTable[(bitWorkArea >> 4) & MASK_6BITS];
|
||||||
buffer[pos++] = encodeTable[(bitWorkArea << 2) & MASK_6BITS];
|
buffer[pos++] = encodeTable[(bitWorkArea << 2) & MASK_6BITS];
|
||||||
@ -297,7 +264,7 @@ public class Base64 {
|
|||||||
} else {
|
} else {
|
||||||
for (int i = 0; i < inAvail; i++) {
|
for (int i = 0; i < inAvail; i++) {
|
||||||
ensureBufferSize(encodeSize);
|
ensureBufferSize(encodeSize);
|
||||||
modulus = (modulus+1) % BYTES_PER_UNENCODED_BLOCK;
|
modulus = (modulus + 1) % BYTES_PER_UNENCODED_BLOCK;
|
||||||
int b = in[inPos++];
|
int b = in[inPos++];
|
||||||
if (b < 0) {
|
if (b < 0) {
|
||||||
b += 256;
|
b += 256;
|
||||||
@ -320,27 +287,17 @@ public class Base64 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* <p>
|
* <p> Decodes all of the provided data, starting at inPos, for inAvail bytes. Should be called at least twice: once
|
||||||
* Decodes all of the provided data, starting at inPos, for inAvail bytes. Should be called at least twice: once
|
|
||||||
* with the data to decode, and once with inAvail set to "-1" to alert decoder that EOF has been reached. The "-1"
|
* with the data to decode, and once with inAvail set to "-1" to alert decoder that EOF has been reached. The "-1"
|
||||||
* call is not necessary when decoding, but it doesn't hurt, either.
|
* call is not necessary when decoding, but it doesn't hurt, either. </p> <p> Ignores all non-base64 characters.
|
||||||
* </p>
|
* This is how chunked (e.g. 76 character) data is handled, since CR and LF are silently ignored, but has
|
||||||
* <p>
|
* implications for other bytes, too. This method subscribes to the garbage-in, garbage-out philosophy: it will not
|
||||||
* Ignores all non-base64 characters. This is how chunked (e.g. 76 character) data is handled, since CR and LF are
|
* check the provided data for validity. </p> <p> Thanks to "commons" project in ws.apache.org for the bitwise
|
||||||
* silently ignored, but has implications for other bytes, too. This method subscribes to the garbage-in,
|
* operations, and general approach. http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/ </p>
|
||||||
* garbage-out philosophy: it will not check the provided data for validity.
|
|
||||||
* </p>
|
|
||||||
* <p>
|
|
||||||
* Thanks to "commons" project in ws.apache.org for the bitwise operations, and general approach.
|
|
||||||
* http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
|
|
||||||
* </p>
|
|
||||||
*
|
*
|
||||||
* @param in
|
* @param in byte[] array of ascii data to base64 decode.
|
||||||
* byte[] array of ascii data to base64 decode.
|
* @param inPos Position to start reading data from.
|
||||||
* @param inPos
|
* @param inAvail Amount of bytes available from input for encoding.
|
||||||
* Position to start reading data from.
|
|
||||||
* @param inAvail
|
|
||||||
* Amount of bytes available from input for encoding.
|
|
||||||
*/
|
*/
|
||||||
void decode(byte[] in, int inPos, int inAvail) {
|
void decode(byte[] in, int inPos, int inAvail) {
|
||||||
if (eof) {
|
if (eof) {
|
||||||
@ -360,12 +317,12 @@ public class Base64 {
|
|||||||
if (b >= 0 && b < DECODE_TABLE.length) {
|
if (b >= 0 && b < DECODE_TABLE.length) {
|
||||||
int result = DECODE_TABLE[b];
|
int result = DECODE_TABLE[b];
|
||||||
if (result >= 0) {
|
if (result >= 0) {
|
||||||
modulus = (modulus+1) % BYTES_PER_ENCODED_BLOCK;
|
modulus = (modulus + 1) % BYTES_PER_ENCODED_BLOCK;
|
||||||
bitWorkArea = (bitWorkArea << BITS_PER_ENCODED_BYTE) + result;
|
bitWorkArea = (bitWorkArea << BITS_PER_ENCODED_BYTE) + result;
|
||||||
if (modulus == 0) {
|
if (modulus == 0) {
|
||||||
buffer[pos++] = (byte) ((bitWorkArea >> 16) & MASK_8BITS);
|
buffer[pos++] = (byte)((bitWorkArea >> 16) & MASK_8BITS);
|
||||||
buffer[pos++] = (byte) ((bitWorkArea >> 8) & MASK_8BITS);
|
buffer[pos++] = (byte)((bitWorkArea >> 8) & MASK_8BITS);
|
||||||
buffer[pos++] = (byte) (bitWorkArea & MASK_8BITS);
|
buffer[pos++] = (byte)(bitWorkArea & MASK_8BITS);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -383,14 +340,14 @@ public class Base64 {
|
|||||||
switch (modulus) {
|
switch (modulus) {
|
||||||
// case 1: // 6 bits - ignore entirely
|
// case 1: // 6 bits - ignore entirely
|
||||||
// break;
|
// break;
|
||||||
case 2 :
|
case 2:
|
||||||
bitWorkArea = bitWorkArea >> 4;
|
bitWorkArea = bitWorkArea >> 4;
|
||||||
buffer[pos++] = (byte) ((bitWorkArea) & MASK_8BITS);
|
buffer[pos++] = (byte)((bitWorkArea) & MASK_8BITS);
|
||||||
break;
|
break;
|
||||||
case 3 :
|
case 3:
|
||||||
bitWorkArea = bitWorkArea >> 2;
|
bitWorkArea = bitWorkArea >> 2;
|
||||||
buffer[pos++] = (byte) ((bitWorkArea >> 8) & MASK_8BITS);
|
buffer[pos++] = (byte)((bitWorkArea >> 8) & MASK_8BITS);
|
||||||
buffer[pos++] = (byte) ((bitWorkArea) & MASK_8BITS);
|
buffer[pos++] = (byte)((bitWorkArea) & MASK_8BITS);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
@ -401,8 +358,7 @@ public class Base64 {
|
|||||||
/**
|
/**
|
||||||
* Encodes binary data using the base64 algorithm but does not chunk the output.
|
* Encodes binary data using the base64 algorithm but does not chunk the output.
|
||||||
*
|
*
|
||||||
* @param binaryData
|
* @param binaryData binary data to encode
|
||||||
* binary data to encode
|
|
||||||
* @return byte[] containing Base64 characters in their UTF-8 representation.
|
* @return byte[] containing Base64 characters in their UTF-8 representation.
|
||||||
*/
|
*/
|
||||||
public static byte[] encodeBase64(byte[] binaryData) {
|
public static byte[] encodeBase64(byte[] binaryData) {
|
||||||
@ -412,17 +368,13 @@ public class Base64 {
|
|||||||
/**
|
/**
|
||||||
* Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.
|
* Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.
|
||||||
*
|
*
|
||||||
* @param binaryData
|
* @param binaryData Array containing binary data to encode.
|
||||||
* Array containing binary data to encode.
|
* @param isChunked if <code>true</code> this encoder will chunk the base64 output into 76 character blocks
|
||||||
* @param isChunked
|
* @param urlSafe if <code>true</code> this encoder will emit - and _ instead of the usual + and /
|
||||||
* if <code>true</code> this encoder will chunk the base64 output into 76 character blocks
|
* characters.
|
||||||
* @param urlSafe
|
* @param maxResultSize The maximum result size to accept.
|
||||||
* if <code>true</code> this encoder will emit - and _ instead of the usual + and / characters.
|
|
||||||
* @param maxResultSize
|
|
||||||
* The maximum result size to accept.
|
|
||||||
* @return Base64-encoded data.
|
* @return Base64-encoded data.
|
||||||
* @throws IllegalArgumentException
|
* @throws IllegalArgumentException Thrown when the input array needs an output array bigger than maxResultSize
|
||||||
* Thrown when the input array needs an output array bigger than maxResultSize
|
|
||||||
* @since 1.4
|
* @since 1.4
|
||||||
*/
|
*/
|
||||||
public static byte[] encodeBase64(byte[] binaryData, boolean isChunked, boolean urlSafe, int maxResultSize) {
|
public static byte[] encodeBase64(byte[] binaryData, boolean isChunked, boolean urlSafe, int maxResultSize) {
|
||||||
@ -432,7 +384,8 @@ public class Base64 {
|
|||||||
|
|
||||||
// Create this so can use the super-class method
|
// Create this so can use the super-class method
|
||||||
// Also ensures that the same roundings are performed by the ctor and the code
|
// Also ensures that the same roundings are performed by the ctor and the code
|
||||||
Base64 b64 = isChunked ? new Base64(MIME_CHUNK_SIZE, CHUNK_SEPARATOR, urlSafe) : new Base64(0, CHUNK_SEPARATOR, urlSafe);
|
Base64 b64 = isChunked ? new Base64(MIME_CHUNK_SIZE, CHUNK_SEPARATOR, urlSafe) : new Base64(0, CHUNK_SEPARATOR,
|
||||||
|
urlSafe);
|
||||||
long len = b64.getEncodedLength(binaryData);
|
long len = b64.getEncodedLength(binaryData);
|
||||||
if (len > maxResultSize) {
|
if (len > maxResultSize) {
|
||||||
throw new IllegalArgumentException("Input array too big, the output array would be bigger (" +
|
throw new IllegalArgumentException("Input array too big, the output array would be bigger (" +
|
||||||
@ -444,25 +397,20 @@ public class Base64 {
|
|||||||
return b64.encode(binaryData);
|
return b64.encode(binaryData);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Decodes Base64 data into octets
|
* Decodes Base64 data into octets
|
||||||
*
|
*
|
||||||
* @param base64Data
|
* @param base64Data Byte array containing Base64 data
|
||||||
* Byte array containing Base64 data
|
|
||||||
* @return Array containing decoded data.
|
* @return Array containing decoded data.
|
||||||
*/
|
*/
|
||||||
public static byte[] decodeBase64(byte[] base64Data) {
|
public static byte[] decodeBase64(byte[] base64Data) {
|
||||||
return new Base64().decode(base64Data);
|
return new Base64().decode(base64Data);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns whether or not the <code>octet</code> is in the Base32 alphabet.
|
* Returns whether or not the <code>octet</code> is in the Base32 alphabet.
|
||||||
*
|
*
|
||||||
* @param octet
|
* @param octet The value to test
|
||||||
* The value to test
|
|
||||||
* @return <code>true</code> if the value is defined in the the Base32 alphabet <code>false</code> otherwise.
|
* @return <code>true</code> if the value is defined in the the Base32 alphabet <code>false</code> otherwise.
|
||||||
*/
|
*/
|
||||||
protected boolean isInAlphabet(byte octet) {
|
protected boolean isInAlphabet(byte octet) {
|
||||||
@ -475,11 +423,9 @@ public class Base64 {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* MIME chunk size per RFC 2045 section 6.8.
|
* MIME chunk size per RFC 2045 section 6.8.
|
||||||
*
|
|
||||||
* <p>
|
* <p>
|
||||||
* The {@value} character limit does not count the trailing CRLF, but counts all other characters, including any
|
* <p> The {@value} character limit does not count the trailing CRLF, but counts all other characters, including any
|
||||||
* equal signs.
|
* equal signs. </p>
|
||||||
* </p>
|
|
||||||
*
|
*
|
||||||
* @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 6.8</a>
|
* @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 6.8</a>
|
||||||
*/
|
*/
|
||||||
@ -488,12 +434,14 @@ public class Base64 {
|
|||||||
private static final int DEFAULT_BUFFER_RESIZE_FACTOR = 2;
|
private static final int DEFAULT_BUFFER_RESIZE_FACTOR = 2;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Defines the default buffer size - currently {@value}
|
* Defines the default buffer size - currently {@value} - must be large enough for at least one encoded
|
||||||
* - must be large enough for at least one encoded block+separator
|
* block+separator
|
||||||
*/
|
*/
|
||||||
private static final int DEFAULT_BUFFER_SIZE = 8192;
|
private static final int DEFAULT_BUFFER_SIZE = 8192;
|
||||||
|
|
||||||
/** Mask used to extract 8 bits, used in decoding bytes */
|
/**
|
||||||
|
* Mask used to extract 8 bits, used in decoding bytes
|
||||||
|
*/
|
||||||
private static final int MASK_8BITS = 0xff;
|
private static final int MASK_8BITS = 0xff;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -503,15 +451,18 @@ public class Base64 {
|
|||||||
|
|
||||||
private static final byte PAD = PAD_DEFAULT;
|
private static final byte PAD = PAD_DEFAULT;
|
||||||
|
|
||||||
/** Number of bytes in each full block of unencoded data, e.g. 4 for Base64 and 5 for Base32 */
|
/**
|
||||||
|
* Number of bytes in each full block of unencoded data, e.g. 4 for Base64 and 5 for Base32
|
||||||
|
*/
|
||||||
private final int unencodedBlockSize;
|
private final int unencodedBlockSize;
|
||||||
|
|
||||||
/** Number of bytes in each full block of encoded data, e.g. 3 for Base64 and 8 for Base32 */
|
/**
|
||||||
|
* Number of bytes in each full block of encoded data, e.g. 3 for Base64 and 8 for Base32
|
||||||
|
*/
|
||||||
private final int encodedBlockSize;
|
private final int encodedBlockSize;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Chunksize for encoding. Not used when decoding.
|
* Chunksize for encoding. Not used when decoding. A value of zero or less implies no chunking of the encoded data.
|
||||||
* A value of zero or less implies no chunking of the encoded data.
|
|
||||||
* Rounded down to nearest multiple of encodedBlockSize.
|
* Rounded down to nearest multiple of encodedBlockSize.
|
||||||
*/
|
*/
|
||||||
private final int lineLength;
|
private final int lineLength;
|
||||||
@ -537,8 +488,8 @@ public class Base64 {
|
|||||||
private int readPos;
|
private int readPos;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Boolean flag to indicate the EOF has been reached. Once EOF has been reached, this object becomes useless,
|
* Boolean flag to indicate the EOF has been reached. Once EOF has been reached, this object becomes useless, and
|
||||||
* and must be thrown away.
|
* must be thrown away.
|
||||||
*/
|
*/
|
||||||
private boolean eof;
|
private boolean eof;
|
||||||
|
|
||||||
@ -549,8 +500,8 @@ public class Base64 {
|
|||||||
private int currentLinePos;
|
private int currentLinePos;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Writes to the buffer only occur after every 3/5 reads when encoding, and every 4/8 reads when decoding.
|
* Writes to the buffer only occur after every 3/5 reads when encoding, and every 4/8 reads when decoding. This
|
||||||
* This variable helps track that.
|
* variable helps track that.
|
||||||
*/
|
*/
|
||||||
private int modulus;
|
private int modulus;
|
||||||
|
|
||||||
@ -559,8 +510,8 @@ public class Base64 {
|
|||||||
*
|
*
|
||||||
* @param size minimum spare space required
|
* @param size minimum spare space required
|
||||||
*/
|
*/
|
||||||
private void ensureBufferSize(int size){
|
private void ensureBufferSize(int size) {
|
||||||
if ((buffer == null) || (buffer.length < pos + size)){
|
if ((buffer == null) || (buffer.length < pos + size)) {
|
||||||
if (buffer == null) {
|
if (buffer == null) {
|
||||||
buffer = new byte[DEFAULT_BUFFER_SIZE];
|
buffer = new byte[DEFAULT_BUFFER_SIZE];
|
||||||
pos = 0;
|
pos = 0;
|
||||||
@ -574,15 +525,12 @@ public class Base64 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Extracts buffered data into the provided byte[] array, starting at position bPos,
|
* Extracts buffered data into the provided byte[] array, starting at position bPos, up to a maximum of bAvail
|
||||||
* up to a maximum of bAvail bytes. Returns how many bytes were actually extracted.
|
* bytes. Returns how many bytes were actually extracted.
|
||||||
*
|
*
|
||||||
* @param b
|
* @param b byte[] array to extract the buffered data into.
|
||||||
* byte[] array to extract the buffered data into.
|
* @param bPos position in byte[] array to start extraction at.
|
||||||
* @param bPos
|
* @param bAvail amount of bytes we're allowed to extract. We may extract fewer (if fewer are available).
|
||||||
* position in byte[] array to start extraction at.
|
|
||||||
* @param bAvail
|
|
||||||
* amount of bytes we're allowed to extract. We may extract fewer (if fewer are available).
|
|
||||||
* @return The number of bytes successfully extracted into the provided byte[] array.
|
* @return The number of bytes successfully extracted into the provided byte[] array.
|
||||||
*/
|
*/
|
||||||
private int readResults(byte[] b, int bPos, int bAvail) {
|
private int readResults(byte[] b, int bPos, int bAvail) {
|
||||||
@ -613,8 +561,7 @@ public class Base64 {
|
|||||||
/**
|
/**
|
||||||
* Decodes a byte[] containing characters in the Base-N alphabet.
|
* Decodes a byte[] containing characters in the Base-N alphabet.
|
||||||
*
|
*
|
||||||
* @param pArray
|
* @param pArray A byte array containing Base-N character data
|
||||||
* A byte array containing Base-N character data
|
|
||||||
* @return a byte array containing binary data
|
* @return a byte array containing binary data
|
||||||
*/
|
*/
|
||||||
private byte[] decode(byte[] pArray) {
|
private byte[] decode(byte[] pArray) {
|
||||||
@ -632,8 +579,7 @@ public class Base64 {
|
|||||||
/**
|
/**
|
||||||
* Encodes a byte[] containing binary data, into a byte[] containing characters in the alphabet.
|
* Encodes a byte[] containing binary data, into a byte[] containing characters in the alphabet.
|
||||||
*
|
*
|
||||||
* @param pArray
|
* @param pArray a byte array containing binary data
|
||||||
* a byte array containing binary data
|
|
||||||
* @return A byte array containing only the basen alphabetic character data
|
* @return A byte array containing only the basen alphabetic character data
|
||||||
*/
|
*/
|
||||||
private byte[] encode(byte[] pArray) {
|
private byte[] encode(byte[] pArray) {
|
||||||
@ -650,11 +596,10 @@ public class Base64 {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests a given byte array to see if it contains any characters within the alphabet or PAD.
|
* Tests a given byte array to see if it contains any characters within the alphabet or PAD.
|
||||||
*
|
* <p>
|
||||||
* Intended for use in checking line-ending arrays
|
* Intended for use in checking line-ending arrays
|
||||||
*
|
*
|
||||||
* @param arrayOctet
|
* @param arrayOctet byte array to test
|
||||||
* byte array to test
|
|
||||||
* @return <code>true</code> if any byte is a valid character in the alphabet or PAD; <code>false</code> otherwise
|
* @return <code>true</code> if any byte is a valid character in the alphabet or PAD; <code>false</code> otherwise
|
||||||
*/
|
*/
|
||||||
private boolean containsAlphabetOrPad(byte[] arrayOctet) {
|
private boolean containsAlphabetOrPad(byte[] arrayOctet) {
|
||||||
@ -673,19 +618,18 @@ public class Base64 {
|
|||||||
* Calculates the amount of space needed to encode the supplied array.
|
* Calculates the amount of space needed to encode the supplied array.
|
||||||
*
|
*
|
||||||
* @param pArray byte[] array which will later be encoded
|
* @param pArray byte[] array which will later be encoded
|
||||||
*
|
* @return amount of space needed to encoded the supplied array. Returns a long since a max-len array will require >
|
||||||
* @return amount of space needed to encoded the supplied array.
|
* Integer.MAX_VALUE
|
||||||
* Returns a long since a max-len array will require > Integer.MAX_VALUE
|
|
||||||
*/
|
*/
|
||||||
private long getEncodedLength(byte[] pArray) {
|
private long getEncodedLength(byte[] pArray) {
|
||||||
// Calculate non-chunked size - rounded up to allow for padding
|
// Calculate non-chunked size - rounded up to allow for padding
|
||||||
// cast to long is needed to avoid possibility of overflow
|
// cast to long is needed to avoid possibility of overflow
|
||||||
long len = ((pArray.length + unencodedBlockSize-1) / unencodedBlockSize) * (long) encodedBlockSize;
|
long len = ((pArray.length + unencodedBlockSize - 1) / unencodedBlockSize) * (long)encodedBlockSize;
|
||||||
if (lineLength > 0) {
|
if (lineLength > 0) {
|
||||||
/**
|
/**
|
||||||
* Round up to nearest multiple
|
* Round up to nearest multiple
|
||||||
*/
|
*/
|
||||||
len += ((len + lineLength-1) / lineLength) * chunkSeparatorLength;
|
len += ((len + lineLength - 1) / lineLength) * chunkSeparatorLength;
|
||||||
}
|
}
|
||||||
return len;
|
return len;
|
||||||
}
|
}
|
||||||
|
@ -19,7 +19,6 @@ package com.alibaba.nacos.client.identify;
|
|||||||
* Identify Constants
|
* Identify Constants
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public class Constants {
|
public class Constants {
|
||||||
public static final String ACCESS_KEY = "accessKey";
|
public static final String ACCESS_KEY = "accessKey";
|
||||||
|
@ -19,7 +19,6 @@ package com.alibaba.nacos.client.identify;
|
|||||||
* Credential Listener
|
* Credential Listener
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public interface CredentialListener {
|
public interface CredentialListener {
|
||||||
/**
|
/**
|
||||||
|
@ -25,11 +25,11 @@ import java.util.concurrent.ConcurrentHashMap;
|
|||||||
* Credential Service
|
* Credential Service
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public final class CredentialService implements SpasCredentialLoader {
|
public final class CredentialService implements SpasCredentialLoader {
|
||||||
static final public Logger log = LogUtils.logger(CredentialService.class);
|
static final public Logger log = LogUtils.logger(CredentialService.class);
|
||||||
private static ConcurrentHashMap<String, CredentialService> instances = new ConcurrentHashMap<String, CredentialService>();
|
private static ConcurrentHashMap<String, CredentialService> instances
|
||||||
|
= new ConcurrentHashMap<String, CredentialService>();
|
||||||
|
|
||||||
private String appName;
|
private String appName;
|
||||||
private Credentials credentials = new Credentials();
|
private Credentials credentials = new Credentials();
|
||||||
@ -47,7 +47,6 @@ public final class CredentialService implements SpasCredentialLoader {
|
|||||||
watcher = new CredentialWatcher(appName, this);
|
watcher = new CredentialWatcher(appName, this);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public static CredentialService getInstance() {
|
public static CredentialService getInstance() {
|
||||||
return getInstance(null);
|
return getInstance(null);
|
||||||
}
|
}
|
||||||
|
@ -33,7 +33,6 @@ import com.alibaba.nacos.client.utils.StringUtils;
|
|||||||
* Credential Watcher
|
* Credential Watcher
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public class CredentialWatcher {
|
public class CredentialWatcher {
|
||||||
static final public Logger SpasLogger = LogUtils.logger(CredentialWatcher.class);
|
static final public Logger SpasLogger = LogUtils.logger(CredentialWatcher.class);
|
||||||
@ -110,15 +109,14 @@ public class CredentialWatcher {
|
|||||||
propertyPath = value;
|
propertyPath = value;
|
||||||
}
|
}
|
||||||
if (propertyPath == null || propertyPath.isEmpty()) {
|
if (propertyPath == null || propertyPath.isEmpty()) {
|
||||||
propertyPath = Constants.CREDENTIAL_PATH + (appName == null ? Constants.CREDENTIAL_DEFAULT : appName);
|
propertyPath = Constants.CREDENTIAL_PATH + (appName == null ? Constants.CREDENTIAL_DEFAULT
|
||||||
}
|
: appName);
|
||||||
else {
|
} else {
|
||||||
if (logWarn) {
|
if (logWarn) {
|
||||||
SpasLogger.info(appName, "Defined credential file: -D" + "spas.identity" + "=" + propertyPath);
|
SpasLogger.info(appName, "Defined credential file: -D" + "spas.identity" + "=" + propertyPath);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
} else {
|
||||||
else {
|
|
||||||
if (logWarn) {
|
if (logWarn) {
|
||||||
SpasLogger.info(appName, "Load credential file from classpath: " + Constants.PROPERTIES_FILENAME);
|
SpasLogger.info(appName, "Load credential file from classpath: " + Constants.PROPERTIES_FILENAME);
|
||||||
}
|
}
|
||||||
@ -130,7 +128,8 @@ public class CredentialWatcher {
|
|||||||
try {
|
try {
|
||||||
propertiesIS = new FileInputStream(propertyPath);
|
propertiesIS = new FileInputStream(propertyPath);
|
||||||
} catch (FileNotFoundException e) {
|
} catch (FileNotFoundException e) {
|
||||||
if (appName != null && !appName.equals(Constants.CREDENTIAL_DEFAULT) && propertyPath.equals(Constants.CREDENTIAL_PATH + appName)) {
|
if (appName != null && !appName.equals(Constants.CREDENTIAL_DEFAULT) && propertyPath.equals(
|
||||||
|
Constants.CREDENTIAL_PATH + appName)) {
|
||||||
propertyPath = Constants.CREDENTIAL_PATH + Constants.CREDENTIAL_DEFAULT;
|
propertyPath = Constants.CREDENTIAL_PATH + Constants.CREDENTIAL_DEFAULT;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@ -154,8 +153,7 @@ public class CredentialWatcher {
|
|||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
} else {
|
||||||
else {
|
|
||||||
Properties properties = new Properties();
|
Properties properties = new Properties();
|
||||||
try {
|
try {
|
||||||
properties.load(propertiesIS);
|
properties.load(propertiesIS);
|
||||||
|
@ -19,7 +19,6 @@ package com.alibaba.nacos.client.identify;
|
|||||||
* Credentials
|
* Credentials
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public class Credentials implements SpasCredential {
|
public class Credentials implements SpasCredential {
|
||||||
|
|
||||||
@ -59,7 +58,9 @@ public class Credentials implements SpasCredential {
|
|||||||
public boolean identical(Credentials other) {
|
public boolean identical(Credentials other) {
|
||||||
return this == other ||
|
return this == other ||
|
||||||
(other != null &&
|
(other != null &&
|
||||||
(accessKey == null && other.accessKey == null || accessKey != null && accessKey.equals(other.accessKey)) &&
|
(accessKey == null && other.accessKey == null || accessKey != null && accessKey.equals(other.accessKey))
|
||||||
(secretKey == null && other.secretKey == null || secretKey != null && secretKey.equals(other.secretKey)));
|
&&
|
||||||
|
(secretKey == null && other.secretKey == null || secretKey != null && secretKey.equals(
|
||||||
|
other.secretKey)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -19,7 +19,6 @@ package com.alibaba.nacos.client.identify;
|
|||||||
* Spas Credential Interface
|
* Spas Credential Interface
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public interface SpasCredential {
|
public interface SpasCredential {
|
||||||
/**
|
/**
|
||||||
|
@ -19,7 +19,6 @@ package com.alibaba.nacos.client.identify;
|
|||||||
* Spas Credential Loader
|
* Spas Credential Loader
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public interface SpasCredentialLoader {
|
public interface SpasCredentialLoader {
|
||||||
/**
|
/**
|
||||||
|
@ -24,7 +24,11 @@ public enum Level {
|
|||||||
/**
|
/**
|
||||||
* log level
|
* log level
|
||||||
*/
|
*/
|
||||||
DEBUG("DEBUG"), INFO("INFO"), WARN("WARN"), ERROR("ERROR"), OFF("OFF");
|
DEBUG("DEBUG"),
|
||||||
|
INFO("INFO"),
|
||||||
|
WARN("WARN"),
|
||||||
|
ERROR("ERROR"),
|
||||||
|
OFF("OFF");
|
||||||
|
|
||||||
private String name;
|
private String name;
|
||||||
|
|
||||||
|
@ -213,12 +213,14 @@ public interface Logger extends ActivateOption {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 判断Info级别是否开启
|
* 判断Info级别是否开启
|
||||||
|
*
|
||||||
* @return Info级别是否开启
|
* @return Info级别是否开启
|
||||||
*/
|
*/
|
||||||
boolean isInfoEnabled();
|
boolean isInfoEnabled();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 判断Warn级别是否开启
|
* 判断Warn级别是否开启
|
||||||
|
*
|
||||||
* @return Warn级别是否开启
|
* @return Warn级别是否开启
|
||||||
*/
|
*/
|
||||||
boolean isWarnEnabled();
|
boolean isWarnEnabled();
|
||||||
@ -232,6 +234,7 @@ public interface Logger extends ActivateOption {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* * 获取内部日志实现对象
|
* * 获取内部日志实现对象
|
||||||
|
*
|
||||||
* @return 内部日志实现对象
|
* @return 内部日志实现对象
|
||||||
*/
|
*/
|
||||||
Object getDelegate();
|
Object getDelegate();
|
||||||
|
@ -29,7 +29,7 @@ import java.util.Iterator;
|
|||||||
/**
|
/**
|
||||||
* A JSON array. JSONObject supports java.util.List interface.
|
* A JSON array. JSONObject supports java.util.List interface.
|
||||||
*
|
*
|
||||||
* @author FangYidong<fangyidong@yahoo.com.cn>
|
* @author FangYidong<fangyidong @ yahoo.com.cn>
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
|
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
|
||||||
public class JSONArray extends ArrayList implements JSONAware, JSONStreamAware {
|
public class JSONArray extends ArrayList implements JSONAware, JSONStreamAware {
|
||||||
@ -38,48 +38,46 @@ public class JSONArray extends ArrayList implements JSONAware, JSONStreamAware {
|
|||||||
/**
|
/**
|
||||||
* Constructs an empty JSONArray.
|
* Constructs an empty JSONArray.
|
||||||
*/
|
*/
|
||||||
public JSONArray(){
|
public JSONArray() {
|
||||||
super();
|
super();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs a JSONArray containing the elements of the specified
|
* Constructs a JSONArray containing the elements of the specified collection, in the order they are returned by the
|
||||||
* collection, in the order they are returned by the collection's iterator.
|
* collection's iterator.
|
||||||
*
|
*
|
||||||
* @param c the collection whose elements are to be placed into this JSONArray
|
* @param c the collection whose elements are to be placed into this JSONArray
|
||||||
*/
|
*/
|
||||||
public JSONArray(Collection c){
|
public JSONArray(Collection c) {
|
||||||
super(c);
|
super(c);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Encode a list into JSON text and write it to out.
|
* Encode a list into JSON text and write it to out. If this list is also a JSONStreamAware or a JSONAware,
|
||||||
* If this list is also a JSONStreamAware or a JSONAware, JSONStreamAware and JSONAware specific behaviours will be ignored at this top level.
|
* JSONStreamAware and JSONAware specific behaviours will be ignored at this top level.
|
||||||
*
|
|
||||||
* @see com.alibaba.nacos.client.logger.json.JSONValue#writeJSONString(Object, Writer)
|
|
||||||
*
|
*
|
||||||
* @param collection
|
* @param collection
|
||||||
* @param out
|
* @param out
|
||||||
|
* @see com.alibaba.nacos.client.logger.json.JSONValue#writeJSONString(Object, Writer)
|
||||||
*/
|
*/
|
||||||
public static void writeJSONString(Collection collection, Writer out) throws IOException{
|
public static void writeJSONString(Collection collection, Writer out) throws IOException {
|
||||||
if(collection == null){
|
if (collection == null) {
|
||||||
out.write("null");
|
out.write("null");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
boolean first = true;
|
boolean first = true;
|
||||||
Iterator iter=collection.iterator();
|
Iterator iter = collection.iterator();
|
||||||
|
|
||||||
out.write('[');
|
out.write('[');
|
||||||
while(iter.hasNext()){
|
while (iter.hasNext()) {
|
||||||
if(first) {
|
if (first) {
|
||||||
first = false;
|
first = false;
|
||||||
}
|
} else {
|
||||||
else {
|
|
||||||
out.write(',');
|
out.write(',');
|
||||||
}
|
}
|
||||||
Object value=iter.next();
|
Object value = iter.next();
|
||||||
if(value == null){
|
if (value == null) {
|
||||||
out.write("null");
|
out.write("null");
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@ -89,41 +87,40 @@ public class JSONArray extends ArrayList implements JSONAware, JSONStreamAware {
|
|||||||
out.write(']');
|
out.write(']');
|
||||||
}
|
}
|
||||||
|
|
||||||
public void writeJSONString(Writer out) throws IOException{
|
public void writeJSONString(Writer out) throws IOException {
|
||||||
writeJSONString(this, out);
|
writeJSONString(this, out);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Convert a list to JSON text. The result is a JSON array.
|
* Convert a list to JSON text. The result is a JSON array. If this list is also a JSONAware, JSONAware specific
|
||||||
* If this list is also a JSONAware, JSONAware specific behaviours will be omitted at this top level.
|
* behaviours will be omitted at this top level.
|
||||||
*
|
|
||||||
* @see com.alibaba.nacos.client.logger.json.JSONValue#toJSONString(Object)
|
|
||||||
*
|
*
|
||||||
* @param collection
|
* @param collection
|
||||||
* @return JSON text, or "null" if list is null.
|
* @return JSON text, or "null" if list is null.
|
||||||
|
* @see com.alibaba.nacos.client.logger.json.JSONValue#toJSONString(Object)
|
||||||
*/
|
*/
|
||||||
public static String toJSONString(Collection collection){
|
public static String toJSONString(Collection collection) {
|
||||||
final StringWriter writer = new StringWriter();
|
final StringWriter writer = new StringWriter();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
writeJSONString(collection, writer);
|
writeJSONString(collection, writer);
|
||||||
return writer.toString();
|
return writer.toString();
|
||||||
} catch(IOException e){
|
} catch (IOException e) {
|
||||||
// This should never happen for a StringWriter
|
// This should never happen for a StringWriter
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void writeJSONString(byte[] array, Writer out) throws IOException{
|
public static void writeJSONString(byte[] array, Writer out) throws IOException {
|
||||||
if(array == null){
|
if (array == null) {
|
||||||
out.write("null");
|
out.write("null");
|
||||||
} else if(array.length == 0) {
|
} else if (array.length == 0) {
|
||||||
out.write("[]");
|
out.write("[]");
|
||||||
} else {
|
} else {
|
||||||
out.write("[");
|
out.write("[");
|
||||||
out.write(String.valueOf(array[0]));
|
out.write(String.valueOf(array[0]));
|
||||||
|
|
||||||
for(int i = 1; i < array.length; i++){
|
for (int i = 1; i < array.length; i++) {
|
||||||
out.write(",");
|
out.write(",");
|
||||||
out.write(String.valueOf(array[i]));
|
out.write(String.valueOf(array[i]));
|
||||||
}
|
}
|
||||||
@ -132,28 +129,28 @@ public class JSONArray extends ArrayList implements JSONAware, JSONStreamAware {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String toJSONString(byte[] array){
|
public static String toJSONString(byte[] array) {
|
||||||
final StringWriter writer = new StringWriter();
|
final StringWriter writer = new StringWriter();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
writeJSONString(array, writer);
|
writeJSONString(array, writer);
|
||||||
return writer.toString();
|
return writer.toString();
|
||||||
} catch(IOException e){
|
} catch (IOException e) {
|
||||||
// This should never happen for a StringWriter
|
// This should never happen for a StringWriter
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void writeJSONString(short[] array, Writer out) throws IOException{
|
public static void writeJSONString(short[] array, Writer out) throws IOException {
|
||||||
if(array == null){
|
if (array == null) {
|
||||||
out.write("null");
|
out.write("null");
|
||||||
} else if(array.length == 0) {
|
} else if (array.length == 0) {
|
||||||
out.write("[]");
|
out.write("[]");
|
||||||
} else {
|
} else {
|
||||||
out.write("[");
|
out.write("[");
|
||||||
out.write(String.valueOf(array[0]));
|
out.write(String.valueOf(array[0]));
|
||||||
|
|
||||||
for(int i = 1; i < array.length; i++){
|
for (int i = 1; i < array.length; i++) {
|
||||||
out.write(",");
|
out.write(",");
|
||||||
out.write(String.valueOf(array[i]));
|
out.write(String.valueOf(array[i]));
|
||||||
}
|
}
|
||||||
@ -162,28 +159,28 @@ public class JSONArray extends ArrayList implements JSONAware, JSONStreamAware {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String toJSONString(short[] array){
|
public static String toJSONString(short[] array) {
|
||||||
final StringWriter writer = new StringWriter();
|
final StringWriter writer = new StringWriter();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
writeJSONString(array, writer);
|
writeJSONString(array, writer);
|
||||||
return writer.toString();
|
return writer.toString();
|
||||||
} catch(IOException e){
|
} catch (IOException e) {
|
||||||
// This should never happen for a StringWriter
|
// This should never happen for a StringWriter
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void writeJSONString(int[] array, Writer out) throws IOException{
|
public static void writeJSONString(int[] array, Writer out) throws IOException {
|
||||||
if(array == null){
|
if (array == null) {
|
||||||
out.write("null");
|
out.write("null");
|
||||||
} else if(array.length == 0) {
|
} else if (array.length == 0) {
|
||||||
out.write("[]");
|
out.write("[]");
|
||||||
} else {
|
} else {
|
||||||
out.write("[");
|
out.write("[");
|
||||||
out.write(String.valueOf(array[0]));
|
out.write(String.valueOf(array[0]));
|
||||||
|
|
||||||
for(int i = 1; i < array.length; i++){
|
for (int i = 1; i < array.length; i++) {
|
||||||
out.write(",");
|
out.write(",");
|
||||||
out.write(String.valueOf(array[i]));
|
out.write(String.valueOf(array[i]));
|
||||||
}
|
}
|
||||||
@ -192,28 +189,28 @@ public class JSONArray extends ArrayList implements JSONAware, JSONStreamAware {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String toJSONString(int[] array){
|
public static String toJSONString(int[] array) {
|
||||||
final StringWriter writer = new StringWriter();
|
final StringWriter writer = new StringWriter();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
writeJSONString(array, writer);
|
writeJSONString(array, writer);
|
||||||
return writer.toString();
|
return writer.toString();
|
||||||
} catch(IOException e){
|
} catch (IOException e) {
|
||||||
// This should never happen for a StringWriter
|
// This should never happen for a StringWriter
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void writeJSONString(long[] array, Writer out) throws IOException{
|
public static void writeJSONString(long[] array, Writer out) throws IOException {
|
||||||
if(array == null){
|
if (array == null) {
|
||||||
out.write("null");
|
out.write("null");
|
||||||
} else if(array.length == 0) {
|
} else if (array.length == 0) {
|
||||||
out.write("[]");
|
out.write("[]");
|
||||||
} else {
|
} else {
|
||||||
out.write("[");
|
out.write("[");
|
||||||
out.write(String.valueOf(array[0]));
|
out.write(String.valueOf(array[0]));
|
||||||
|
|
||||||
for(int i = 1; i < array.length; i++){
|
for (int i = 1; i < array.length; i++) {
|
||||||
out.write(",");
|
out.write(",");
|
||||||
out.write(String.valueOf(array[i]));
|
out.write(String.valueOf(array[i]));
|
||||||
}
|
}
|
||||||
@ -222,28 +219,28 @@ public class JSONArray extends ArrayList implements JSONAware, JSONStreamAware {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String toJSONString(long[] array){
|
public static String toJSONString(long[] array) {
|
||||||
final StringWriter writer = new StringWriter();
|
final StringWriter writer = new StringWriter();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
writeJSONString(array, writer);
|
writeJSONString(array, writer);
|
||||||
return writer.toString();
|
return writer.toString();
|
||||||
} catch(IOException e){
|
} catch (IOException e) {
|
||||||
// This should never happen for a StringWriter
|
// This should never happen for a StringWriter
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void writeJSONString(float[] array, Writer out) throws IOException{
|
public static void writeJSONString(float[] array, Writer out) throws IOException {
|
||||||
if(array == null){
|
if (array == null) {
|
||||||
out.write("null");
|
out.write("null");
|
||||||
} else if(array.length == 0) {
|
} else if (array.length == 0) {
|
||||||
out.write("[]");
|
out.write("[]");
|
||||||
} else {
|
} else {
|
||||||
out.write("[");
|
out.write("[");
|
||||||
out.write(String.valueOf(array[0]));
|
out.write(String.valueOf(array[0]));
|
||||||
|
|
||||||
for(int i = 1; i < array.length; i++){
|
for (int i = 1; i < array.length; i++) {
|
||||||
out.write(",");
|
out.write(",");
|
||||||
out.write(String.valueOf(array[i]));
|
out.write(String.valueOf(array[i]));
|
||||||
}
|
}
|
||||||
@ -252,28 +249,28 @@ public class JSONArray extends ArrayList implements JSONAware, JSONStreamAware {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String toJSONString(float[] array){
|
public static String toJSONString(float[] array) {
|
||||||
final StringWriter writer = new StringWriter();
|
final StringWriter writer = new StringWriter();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
writeJSONString(array, writer);
|
writeJSONString(array, writer);
|
||||||
return writer.toString();
|
return writer.toString();
|
||||||
} catch(IOException e){
|
} catch (IOException e) {
|
||||||
// This should never happen for a StringWriter
|
// This should never happen for a StringWriter
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void writeJSONString(double[] array, Writer out) throws IOException{
|
public static void writeJSONString(double[] array, Writer out) throws IOException {
|
||||||
if(array == null){
|
if (array == null) {
|
||||||
out.write("null");
|
out.write("null");
|
||||||
} else if(array.length == 0) {
|
} else if (array.length == 0) {
|
||||||
out.write("[]");
|
out.write("[]");
|
||||||
} else {
|
} else {
|
||||||
out.write("[");
|
out.write("[");
|
||||||
out.write(String.valueOf(array[0]));
|
out.write(String.valueOf(array[0]));
|
||||||
|
|
||||||
for(int i = 1; i < array.length; i++){
|
for (int i = 1; i < array.length; i++) {
|
||||||
out.write(",");
|
out.write(",");
|
||||||
out.write(String.valueOf(array[i]));
|
out.write(String.valueOf(array[i]));
|
||||||
}
|
}
|
||||||
@ -282,28 +279,28 @@ public class JSONArray extends ArrayList implements JSONAware, JSONStreamAware {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String toJSONString(double[] array){
|
public static String toJSONString(double[] array) {
|
||||||
final StringWriter writer = new StringWriter();
|
final StringWriter writer = new StringWriter();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
writeJSONString(array, writer);
|
writeJSONString(array, writer);
|
||||||
return writer.toString();
|
return writer.toString();
|
||||||
} catch(IOException e){
|
} catch (IOException e) {
|
||||||
// This should never happen for a StringWriter
|
// This should never happen for a StringWriter
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void writeJSONString(boolean[] array, Writer out) throws IOException{
|
public static void writeJSONString(boolean[] array, Writer out) throws IOException {
|
||||||
if(array == null){
|
if (array == null) {
|
||||||
out.write("null");
|
out.write("null");
|
||||||
} else if(array.length == 0) {
|
} else if (array.length == 0) {
|
||||||
out.write("[]");
|
out.write("[]");
|
||||||
} else {
|
} else {
|
||||||
out.write("[");
|
out.write("[");
|
||||||
out.write(String.valueOf(array[0]));
|
out.write(String.valueOf(array[0]));
|
||||||
|
|
||||||
for(int i = 1; i < array.length; i++){
|
for (int i = 1; i < array.length; i++) {
|
||||||
out.write(",");
|
out.write(",");
|
||||||
out.write(String.valueOf(array[i]));
|
out.write(String.valueOf(array[i]));
|
||||||
}
|
}
|
||||||
@ -312,28 +309,28 @@ public class JSONArray extends ArrayList implements JSONAware, JSONStreamAware {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String toJSONString(boolean[] array){
|
public static String toJSONString(boolean[] array) {
|
||||||
final StringWriter writer = new StringWriter();
|
final StringWriter writer = new StringWriter();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
writeJSONString(array, writer);
|
writeJSONString(array, writer);
|
||||||
return writer.toString();
|
return writer.toString();
|
||||||
} catch(IOException e){
|
} catch (IOException e) {
|
||||||
// This should never happen for a StringWriter
|
// This should never happen for a StringWriter
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void writeJSONString(char[] array, Writer out) throws IOException{
|
public static void writeJSONString(char[] array, Writer out) throws IOException {
|
||||||
if(array == null){
|
if (array == null) {
|
||||||
out.write("null");
|
out.write("null");
|
||||||
} else if(array.length == 0) {
|
} else if (array.length == 0) {
|
||||||
out.write("[]");
|
out.write("[]");
|
||||||
} else {
|
} else {
|
||||||
out.write("[\"");
|
out.write("[\"");
|
||||||
out.write(String.valueOf(array[0]));
|
out.write(String.valueOf(array[0]));
|
||||||
|
|
||||||
for(int i = 1; i < array.length; i++){
|
for (int i = 1; i < array.length; i++) {
|
||||||
out.write("\",\"");
|
out.write("\",\"");
|
||||||
out.write(String.valueOf(array[i]));
|
out.write(String.valueOf(array[i]));
|
||||||
}
|
}
|
||||||
@ -342,28 +339,28 @@ public class JSONArray extends ArrayList implements JSONAware, JSONStreamAware {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String toJSONString(char[] array){
|
public static String toJSONString(char[] array) {
|
||||||
final StringWriter writer = new StringWriter();
|
final StringWriter writer = new StringWriter();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
writeJSONString(array, writer);
|
writeJSONString(array, writer);
|
||||||
return writer.toString();
|
return writer.toString();
|
||||||
} catch(IOException e){
|
} catch (IOException e) {
|
||||||
// This should never happen for a StringWriter
|
// This should never happen for a StringWriter
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void writeJSONString(Object[] array, Writer out) throws IOException{
|
public static void writeJSONString(Object[] array, Writer out) throws IOException {
|
||||||
if(array == null){
|
if (array == null) {
|
||||||
out.write("null");
|
out.write("null");
|
||||||
} else if(array.length == 0) {
|
} else if (array.length == 0) {
|
||||||
out.write("[]");
|
out.write("[]");
|
||||||
} else {
|
} else {
|
||||||
out.write("[");
|
out.write("[");
|
||||||
JSONValue.writeJSONString(array[0], out);
|
JSONValue.writeJSONString(array[0], out);
|
||||||
|
|
||||||
for(int i = 1; i < array.length; i++){
|
for (int i = 1; i < array.length; i++) {
|
||||||
out.write(",");
|
out.write(",");
|
||||||
JSONValue.writeJSONString(array[i], out);
|
JSONValue.writeJSONString(array[i], out);
|
||||||
}
|
}
|
||||||
@ -372,25 +369,24 @@ public class JSONArray extends ArrayList implements JSONAware, JSONStreamAware {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String toJSONString(Object[] array){
|
public static String toJSONString(Object[] array) {
|
||||||
final StringWriter writer = new StringWriter();
|
final StringWriter writer = new StringWriter();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
writeJSONString(array, writer);
|
writeJSONString(array, writer);
|
||||||
return writer.toString();
|
return writer.toString();
|
||||||
} catch(IOException e){
|
} catch (IOException e) {
|
||||||
// This should never happen for a StringWriter
|
// This should never happen for a StringWriter
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public String toJSONString(){
|
public String toJSONString() {
|
||||||
return toJSONString(this);
|
return toJSONString(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns a string representation of this array. This is equivalent to
|
* Returns a string representation of this array. This is equivalent to calling {@link JSONArray#toJSONString()}.
|
||||||
* calling {@link JSONArray#toJSONString()}.
|
|
||||||
*/
|
*/
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return toJSONString();
|
return toJSONString();
|
||||||
|
@ -17,7 +17,8 @@ package com.alibaba.nacos.client.logger.json;
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Beans that support customized output of JSON text shall implement this interface.
|
* Beans that support customized output of JSON text shall implement this interface.
|
||||||
* @author FangYidong<fangyidong@yahoo.com.cn>
|
*
|
||||||
|
* @author FangYidong<fangyidong @ yahoo.com.cn>
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
|
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
|
||||||
public interface JSONAware {
|
public interface JSONAware {
|
||||||
|
@ -29,21 +29,20 @@ import java.util.Map;
|
|||||||
/**
|
/**
|
||||||
* A JSON object. Key value pairs are unordered. JSONObject supports java.util.Map interface.
|
* A JSON object. Key value pairs are unordered. JSONObject supports java.util.Map interface.
|
||||||
*
|
*
|
||||||
* @author FangYidong<fangyidong@yahoo.com.cn>
|
* @author FangYidong<fangyidong @ yahoo.com.cn>
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
|
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
|
||||||
public class JSONObject extends HashMap implements Map, JSONAware, JSONStreamAware{
|
public class JSONObject extends HashMap implements Map, JSONAware, JSONStreamAware {
|
||||||
|
|
||||||
private static final long serialVersionUID = -503443796854799292L;
|
private static final long serialVersionUID = -503443796854799292L;
|
||||||
|
|
||||||
|
|
||||||
public JSONObject() {
|
public JSONObject() {
|
||||||
super();
|
super();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Allows creation of a JSONObject from a Map. After that, both the
|
* Allows creation of a JSONObject from a Map. After that, both the generated JSONObject and the Map can be modified
|
||||||
* generated JSONObject and the Map can be modified independently.
|
* independently.
|
||||||
*
|
*
|
||||||
* @param map
|
* @param map
|
||||||
*/
|
*/
|
||||||
@ -51,34 +50,31 @@ public class JSONObject extends HashMap implements Map, JSONAware, JSONStreamAwa
|
|||||||
super(map);
|
super(map);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Encode a map into JSON text and write it to out.
|
* Encode a map into JSON text and write it to out. If this map is also a JSONAware or JSONStreamAware, JSONAware or
|
||||||
* If this map is also a JSONAware or JSONStreamAware, JSONAware or JSONStreamAware specific behaviours will be ignored at this top level.
|
* JSONStreamAware specific behaviours will be ignored at this top level.
|
||||||
*
|
|
||||||
* @see com.alibaba.nacos.client.logger.json.JSONValue#writeJSONString(Object, Writer)
|
|
||||||
*
|
*
|
||||||
* @param map
|
* @param map
|
||||||
* @param out
|
* @param out
|
||||||
|
* @see com.alibaba.nacos.client.logger.json.JSONValue#writeJSONString(Object, Writer)
|
||||||
*/
|
*/
|
||||||
public static void writeJSONString(Map map, Writer out) throws IOException {
|
public static void writeJSONString(Map map, Writer out) throws IOException {
|
||||||
if(map == null){
|
if (map == null) {
|
||||||
out.write("null");
|
out.write("null");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
boolean first = true;
|
boolean first = true;
|
||||||
Iterator iter=map.entrySet().iterator();
|
Iterator iter = map.entrySet().iterator();
|
||||||
|
|
||||||
out.write('{');
|
out.write('{');
|
||||||
while(iter.hasNext()){
|
while (iter.hasNext()) {
|
||||||
if (first) {
|
if (first) {
|
||||||
first = false;
|
first = false;
|
||||||
}
|
} else {
|
||||||
else {
|
|
||||||
out.write(',');
|
out.write(',');
|
||||||
}
|
}
|
||||||
Map.Entry entry = (Map.Entry) iter.next();
|
Map.Entry entry = (Map.Entry)iter.next();
|
||||||
out.write('\"');
|
out.write('\"');
|
||||||
out.write(escape(String.valueOf(entry.getKey())));
|
out.write(escape(String.valueOf(entry.getKey())));
|
||||||
out.write('\"');
|
out.write('\"');
|
||||||
@ -88,20 +84,19 @@ public class JSONObject extends HashMap implements Map, JSONAware, JSONStreamAwa
|
|||||||
out.write('}');
|
out.write('}');
|
||||||
}
|
}
|
||||||
|
|
||||||
public void writeJSONString(Writer out) throws IOException{
|
public void writeJSONString(Writer out) throws IOException {
|
||||||
writeJSONString(this, out);
|
writeJSONString(this, out);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Convert a map to JSON text. The result is a JSON object.
|
* Convert a map to JSON text. The result is a JSON object. If this map is also a JSONAware, JSONAware specific
|
||||||
* If this map is also a JSONAware, JSONAware specific behaviours will be omitted at this top level.
|
* behaviours will be omitted at this top level.
|
||||||
*
|
|
||||||
* @see com.alibaba.nacos.client.logger.json.JSONValue#toJSONString(Object)
|
|
||||||
*
|
*
|
||||||
* @param map
|
* @param map
|
||||||
* @return JSON text, or "null" if map is null.
|
* @return JSON text, or "null" if map is null.
|
||||||
|
* @see com.alibaba.nacos.client.logger.json.JSONValue#toJSONString(Object)
|
||||||
*/
|
*/
|
||||||
public static String toJSONString(Map map){
|
public static String toJSONString(Map map) {
|
||||||
final StringWriter writer = new StringWriter();
|
final StringWriter writer = new StringWriter();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@ -113,21 +108,20 @@ public class JSONObject extends HashMap implements Map, JSONAware, JSONStreamAwa
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public String toJSONString(){
|
public String toJSONString() {
|
||||||
return toJSONString(this);
|
return toJSONString(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
public String toString(){
|
public String toString() {
|
||||||
return toJSONString();
|
return toJSONString();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String toString(String key,Object value){
|
public static String toString(String key, Object value) {
|
||||||
StringBuffer sb = new StringBuffer();
|
StringBuffer sb = new StringBuffer();
|
||||||
sb.append('\"');
|
sb.append('\"');
|
||||||
if(key == null) {
|
if (key == null) {
|
||||||
sb.append("null");
|
sb.append("null");
|
||||||
}
|
} else {
|
||||||
else {
|
|
||||||
JSONValue.escape(key, sb);
|
JSONValue.escape(key, sb);
|
||||||
}
|
}
|
||||||
sb.append('\"').append(':');
|
sb.append('\"').append(':');
|
||||||
@ -138,15 +132,14 @@ public class JSONObject extends HashMap implements Map, JSONAware, JSONStreamAwa
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Escape quotes, \, /, \r, \n, \b, \f, \t and other control characters (U+0000 through U+001F).
|
* Escape quotes, \, /, \r, \n, \b, \f, \t and other control characters (U+0000 through U+001F). It's the same as
|
||||||
* It's the same as JSONValue.escape() only for compatibility here.
|
* JSONValue.escape() only for compatibility here.
|
||||||
*
|
|
||||||
* @see com.alibaba.nacos.client.logger.json.JSONValue#escape(String)
|
|
||||||
*
|
*
|
||||||
* @param s
|
* @param s
|
||||||
* @return
|
* @return
|
||||||
|
* @see com.alibaba.nacos.client.logger.json.JSONValue#escape(String)
|
||||||
*/
|
*/
|
||||||
public static String escape(String s){
|
public static String escape(String s) {
|
||||||
return JSONValue.escape(s);
|
return JSONValue.escape(s);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -19,20 +19,17 @@ import java.io.IOException;
|
|||||||
import java.io.Writer;
|
import java.io.Writer;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Beans that support customized output of JSON text to a writer shall implement
|
* Beans that support customized output of JSON text to a writer shall implement this interface.
|
||||||
* this interface.
|
|
||||||
*
|
*
|
||||||
* @author FangYidong<fangyidong@yahoo.com.cn>
|
* @author FangYidong<fangyidong @ yahoo.com.cn>
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
|
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
|
||||||
public interface JSONStreamAware {
|
public interface JSONStreamAware {
|
||||||
/**
|
/**
|
||||||
* write JSON string to out.
|
* write JSON string to out.
|
||||||
*
|
*
|
||||||
* @param out
|
* @param out out writer
|
||||||
* out writer
|
* @throws IOException Exception
|
||||||
* @throws IOException
|
|
||||||
* Exception
|
|
||||||
*/
|
*/
|
||||||
void writeJSONString(Writer out) throws IOException;
|
void writeJSONString(Writer out) throws IOException;
|
||||||
}
|
}
|
||||||
|
@ -30,213 +30,186 @@ import java.util.Map;
|
|||||||
import com.alibaba.nacos.client.logger.json.parser.JSONParser;
|
import com.alibaba.nacos.client.logger.json.parser.JSONParser;
|
||||||
import com.alibaba.nacos.client.logger.json.parser.ParseException;
|
import com.alibaba.nacos.client.logger.json.parser.ParseException;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author FangYidong<fangyidong@yahoo.com.cn>
|
* @author FangYidong<fangyidong @ yahoo.com.cn>
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
|
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
|
||||||
public class JSONValue {
|
public class JSONValue {
|
||||||
/**
|
/**
|
||||||
* Parse JSON text into java object from the input source.
|
* Parse JSON text into java object from the input source. Please use parseWithException() if you don't want to
|
||||||
* Please use parseWithException() if you don't want to ignore the exception.
|
* ignore the exception.
|
||||||
*
|
|
||||||
* @see com.alibaba.nacos.client.logger.jsonparser.JSONParser#parse(Reader)
|
|
||||||
* @see #parseWithException(Reader)
|
|
||||||
*
|
*
|
||||||
* @param in
|
* @param in
|
||||||
* @return Instance of the following:
|
* @return Instance of the following: com.alibaba.nacos.client.logger.jsonJSONObject,
|
||||||
* com.alibaba.nacos.client.logger.jsonJSONObject,
|
* com.alibaba.nacos.client.logger.jsonJSONArray, java.lang.String, java.lang.Number, java.lang.Boolean, null
|
||||||
* com.alibaba.nacos.client.logger.jsonJSONArray,
|
* @see com.alibaba.nacos.client.logger.jsonparser.JSONParser#parse(Reader)
|
||||||
* java.lang.String,
|
* @see #parseWithException(Reader)
|
||||||
* java.lang.Number,
|
* @deprecated this method may throw an {@code Error} instead of returning {@code null}; please use {@link
|
||||||
* java.lang.Boolean,
|
* JSONValue#parseWithException(Reader)} instead
|
||||||
* null
|
|
||||||
*
|
|
||||||
* @deprecated this method may throw an {@code Error} instead of returning
|
|
||||||
* {@code null}; please use {@link JSONValue#parseWithException(Reader)}
|
|
||||||
* instead
|
|
||||||
*/
|
*/
|
||||||
public static Object parse(Reader in){
|
public static Object parse(Reader in) {
|
||||||
try{
|
try {
|
||||||
JSONParser parser=new JSONParser();
|
JSONParser parser = new JSONParser();
|
||||||
return parser.parse(in);
|
return parser.parse(in);
|
||||||
}
|
} catch (Exception e) {
|
||||||
catch(Exception e){
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Parse JSON text into java object from the given string.
|
* Parse JSON text into java object from the given string. Please use parseWithException() if you don't want to
|
||||||
* Please use parseWithException() if you don't want to ignore the exception.
|
* ignore the exception.
|
||||||
*
|
|
||||||
* @see com.alibaba.nacos.client.logger.jsonparser.JSONParser#parse(Reader)
|
|
||||||
* @see #parseWithException(Reader)
|
|
||||||
*
|
*
|
||||||
* @param s
|
* @param s
|
||||||
* @return Instance of the following:
|
* @return Instance of the following: com.alibaba.nacos.client.logger.jsonJSONObject,
|
||||||
* com.alibaba.nacos.client.logger.jsonJSONObject,
|
* com.alibaba.nacos.client.logger.jsonJSONArray, java.lang.String, java.lang.Number, java.lang.Boolean, null
|
||||||
* com.alibaba.nacos.client.logger.jsonJSONArray,
|
* @see com.alibaba.nacos.client.logger.jsonparser.JSONParser#parse(Reader)
|
||||||
* java.lang.String,
|
* @see #parseWithException(Reader)
|
||||||
* java.lang.Number,
|
* @deprecated this method may throw an {@code Error} instead of returning {@code null}; please use {@link
|
||||||
* java.lang.Boolean,
|
* JSONValue#parseWithException(String)} instead
|
||||||
* null
|
|
||||||
*
|
|
||||||
* @deprecated this method may throw an {@code Error} instead of returning
|
|
||||||
* {@code null}; please use {@link JSONValue#parseWithException(String)}
|
|
||||||
* instead
|
|
||||||
*/
|
*/
|
||||||
public static Object parse(String s){
|
public static Object parse(String s) {
|
||||||
StringReader in=new StringReader(s);
|
StringReader in = new StringReader(s);
|
||||||
return parse(in);
|
return parse(in);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Parse JSON text into java object from the input source.
|
* Parse JSON text into java object from the input source.
|
||||||
*
|
*
|
||||||
* @see com.alibaba.nacos.client.logger.jsonparser.JSONParser
|
|
||||||
*
|
|
||||||
* @param in
|
* @param in
|
||||||
* @return Instance of the following:
|
* @return Instance of the following: com.alibaba.nacos.client.logger.jsonJSONObject,
|
||||||
* com.alibaba.nacos.client.logger.jsonJSONObject,
|
* com.alibaba.nacos.client.logger.jsonJSONArray, java.lang.String, java.lang.Number, java.lang.Boolean, null
|
||||||
* com.alibaba.nacos.client.logger.jsonJSONArray,
|
|
||||||
* java.lang.String,
|
|
||||||
* java.lang.Number,
|
|
||||||
* java.lang.Boolean,
|
|
||||||
* null
|
|
||||||
*
|
|
||||||
* @throws IOException
|
* @throws IOException
|
||||||
* @throws ParseException
|
* @throws ParseException
|
||||||
|
* @see com.alibaba.nacos.client.logger.jsonparser.JSONParser
|
||||||
*/
|
*/
|
||||||
public static Object parseWithException(Reader in) throws IOException, ParseException {
|
public static Object parseWithException(Reader in) throws IOException, ParseException {
|
||||||
JSONParser parser=new JSONParser();
|
JSONParser parser = new JSONParser();
|
||||||
return parser.parse(in);
|
return parser.parse(in);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Object parseWithException(String s) throws ParseException{
|
public static Object parseWithException(String s) throws ParseException {
|
||||||
JSONParser parser=new JSONParser();
|
JSONParser parser = new JSONParser();
|
||||||
return parser.parse(s);
|
return parser.parse(s);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Encode an object into JSON text and write it to out.
|
* Encode an object into JSON text and write it to out.
|
||||||
* <p>
|
* <p>
|
||||||
* If this object is a Map or a List, and it's also a JSONStreamAware or a JSONAware, JSONStreamAware or JSONAware will be considered firstly.
|
* If this object is a Map or a List, and it's also a JSONStreamAware or a JSONAware, JSONStreamAware or JSONAware
|
||||||
|
* will be considered firstly.
|
||||||
* <p>
|
* <p>
|
||||||
* DO NOT call this method from writeJSONString(Writer) of a class that implements both JSONStreamAware and (Map or List) with
|
* DO NOT call this method from writeJSONString(Writer) of a class that implements both JSONStreamAware and (Map or
|
||||||
* "this" as the first parameter, use JSONObject.writeJSONString(Map, Writer) or JSONArray.writeJSONString(List, Writer) instead.
|
* List) with "this" as the first parameter, use JSONObject.writeJSONString(Map, Writer) or
|
||||||
*
|
* JSONArray.writeJSONString(List, Writer) instead.
|
||||||
* @see com.alibaba.nacos.client.logger.jsonJSONObject#writeJSONString(Map, Writer)
|
|
||||||
* @see com.alibaba.nacos.client.logger.jsonJSONArray#writeJSONString(List, Writer)
|
|
||||||
*
|
*
|
||||||
* @param value
|
* @param value
|
||||||
* @param writer
|
* @param writer
|
||||||
|
* @see com.alibaba.nacos.client.logger.jsonJSONObject#writeJSONString(Map, Writer)
|
||||||
|
* @see com.alibaba.nacos.client.logger.jsonJSONArray#writeJSONString(List, Writer)
|
||||||
*/
|
*/
|
||||||
public static void writeJSONString(Object value, Writer out) throws IOException {
|
public static void writeJSONString(Object value, Writer out) throws IOException {
|
||||||
if(value == null){
|
if (value == null) {
|
||||||
out.write("null");
|
out.write("null");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(value instanceof String){
|
if (value instanceof String) {
|
||||||
out.write('\"');
|
out.write('\"');
|
||||||
out.write(escape((String)value));
|
out.write(escape((String)value));
|
||||||
out.write('\"');
|
out.write('\"');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(value instanceof Double){
|
if (value instanceof Double) {
|
||||||
if(((Double)value).isInfinite() || ((Double)value).isNaN()) {
|
if (((Double)value).isInfinite() || ((Double)value).isNaN()) {
|
||||||
out.write("null");
|
out.write("null");
|
||||||
}
|
} else {
|
||||||
else {
|
|
||||||
out.write(value.toString());
|
out.write(value.toString());
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(value instanceof Float){
|
if (value instanceof Float) {
|
||||||
if(((Float)value).isInfinite() || ((Float)value).isNaN()) {
|
if (((Float)value).isInfinite() || ((Float)value).isNaN()) {
|
||||||
out.write("null");
|
out.write("null");
|
||||||
}
|
} else {
|
||||||
else {
|
|
||||||
out.write(value.toString());
|
out.write(value.toString());
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(value instanceof Number){
|
if (value instanceof Number) {
|
||||||
out.write(value.toString());
|
out.write(value.toString());
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(value instanceof Boolean){
|
if (value instanceof Boolean) {
|
||||||
out.write(value.toString());
|
out.write(value.toString());
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if((value instanceof JSONStreamAware)){
|
if ((value instanceof JSONStreamAware)) {
|
||||||
((JSONStreamAware)value).writeJSONString(out);
|
((JSONStreamAware)value).writeJSONString(out);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if((value instanceof JSONAware)){
|
if ((value instanceof JSONAware)) {
|
||||||
out.write(((JSONAware)value).toJSONString());
|
out.write(((JSONAware)value).toJSONString());
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(value instanceof Map){
|
if (value instanceof Map) {
|
||||||
JSONObject.writeJSONString((Map)value, out);
|
JSONObject.writeJSONString((Map)value, out);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(value instanceof Collection){
|
if (value instanceof Collection) {
|
||||||
JSONArray.writeJSONString((Collection)value, out);
|
JSONArray.writeJSONString((Collection)value, out);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(value instanceof byte[]){
|
if (value instanceof byte[]) {
|
||||||
JSONArray.writeJSONString((byte[])value, out);
|
JSONArray.writeJSONString((byte[])value, out);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(value instanceof short[]){
|
if (value instanceof short[]) {
|
||||||
JSONArray.writeJSONString((short[])value, out);
|
JSONArray.writeJSONString((short[])value, out);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(value instanceof int[]){
|
if (value instanceof int[]) {
|
||||||
JSONArray.writeJSONString((int[])value, out);
|
JSONArray.writeJSONString((int[])value, out);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(value instanceof long[]){
|
if (value instanceof long[]) {
|
||||||
JSONArray.writeJSONString((long[])value, out);
|
JSONArray.writeJSONString((long[])value, out);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(value instanceof float[]){
|
if (value instanceof float[]) {
|
||||||
JSONArray.writeJSONString((float[])value, out);
|
JSONArray.writeJSONString((float[])value, out);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(value instanceof double[]){
|
if (value instanceof double[]) {
|
||||||
JSONArray.writeJSONString((double[])value, out);
|
JSONArray.writeJSONString((double[])value, out);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(value instanceof boolean[]){
|
if (value instanceof boolean[]) {
|
||||||
JSONArray.writeJSONString((boolean[])value, out);
|
JSONArray.writeJSONString((boolean[])value, out);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(value instanceof char[]){
|
if (value instanceof char[]) {
|
||||||
JSONArray.writeJSONString((char[])value, out);
|
JSONArray.writeJSONString((char[])value, out);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(value instanceof Object[]){
|
if (value instanceof Object[]) {
|
||||||
JSONArray.writeJSONString((Object[])value, out);
|
JSONArray.writeJSONString((Object[])value, out);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -249,21 +222,20 @@ public class JSONValue {
|
|||||||
* <p>
|
* <p>
|
||||||
* If this object is a Map or a List, and it's also a JSONAware, JSONAware will be considered firstly.
|
* If this object is a Map or a List, and it's also a JSONAware, JSONAware will be considered firstly.
|
||||||
* <p>
|
* <p>
|
||||||
* DO NOT call this method from toJSONString() of a class that implements both JSONAware and Map or List with
|
* DO NOT call this method from toJSONString() of a class that implements both JSONAware and Map or List with "this"
|
||||||
* "this" as the parameter, use JSONObject.toJSONString(Map) or JSONArray.toJSONString(List) instead.
|
* as the parameter, use JSONObject.toJSONString(Map) or JSONArray.toJSONString(List) instead.
|
||||||
*
|
|
||||||
* @see com.alibaba.nacos.client.logger.json.JSONObject#toJSONString(Map)
|
|
||||||
*
|
*
|
||||||
* @param value
|
* @param value
|
||||||
* @return JSON text, or "null" if value is null or it's an NaN or an INF number.
|
* @return JSON text, or "null" if value is null or it's an NaN or an INF number.
|
||||||
|
* @see com.alibaba.nacos.client.logger.json.JSONObject#toJSONString(Map)
|
||||||
*/
|
*/
|
||||||
public static String toJSONString(Object value){
|
public static String toJSONString(Object value) {
|
||||||
final StringWriter writer = new StringWriter();
|
final StringWriter writer = new StringWriter();
|
||||||
|
|
||||||
try{
|
try {
|
||||||
writeJSONString(value, writer);
|
writeJSONString(value, writer);
|
||||||
return writer.toString();
|
return writer.toString();
|
||||||
} catch(IOException e){
|
} catch (IOException e) {
|
||||||
// This should never happen for a StringWriter
|
// This should never happen for a StringWriter
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
@ -271,11 +243,12 @@ public class JSONValue {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Escape quotes, \, /, \r, \n, \b, \f, \t and other control characters (U+0000 through U+001F).
|
* Escape quotes, \, /, \r, \n, \b, \f, \t and other control characters (U+0000 through U+001F).
|
||||||
|
*
|
||||||
* @param s
|
* @param s
|
||||||
* @return
|
* @return
|
||||||
*/
|
*/
|
||||||
public static String escape(String s){
|
public static String escape(String s) {
|
||||||
if(s==null) {
|
if (s == null) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
StringBuffer sb = new StringBuffer();
|
StringBuffer sb = new StringBuffer();
|
||||||
@ -289,9 +262,9 @@ public class JSONValue {
|
|||||||
*/
|
*/
|
||||||
static void escape(String s, StringBuffer sb) {
|
static void escape(String s, StringBuffer sb) {
|
||||||
final int len = s.length();
|
final int len = s.length();
|
||||||
for(int i=0;i<len;i++){
|
for (int i = 0; i < len; i++) {
|
||||||
char ch=s.charAt(i);
|
char ch = s.charAt(i);
|
||||||
switch(ch){
|
switch (ch) {
|
||||||
case '"':
|
case '"':
|
||||||
sb.append("\\\"");
|
sb.append("\\\"");
|
||||||
break;
|
break;
|
||||||
@ -318,15 +291,14 @@ public class JSONValue {
|
|||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
//Reference: http://www.unicode.org/versions/Unicode5.1.0/
|
//Reference: http://www.unicode.org/versions/Unicode5.1.0/
|
||||||
if(isUnicodeChar(ch)){
|
if (isUnicodeChar(ch)) {
|
||||||
String ss=Integer.toHexString(ch);
|
String ss = Integer.toHexString(ch);
|
||||||
sb.append("\\u");
|
sb.append("\\u");
|
||||||
for(int k=0;k<FOUR-ss.length();k++){
|
for (int k = 0; k < FOUR - ss.length(); k++) {
|
||||||
sb.append('0');
|
sb.append('0');
|
||||||
}
|
}
|
||||||
sb.append(ss.toUpperCase());
|
sb.append(ss.toUpperCase());
|
||||||
}
|
} else {
|
||||||
else{
|
|
||||||
sb.append(ch);
|
sb.append(ch);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -21,20 +21,23 @@ import java.util.Map;
|
|||||||
/**
|
/**
|
||||||
* Container factory for creating containers for JSON object and JSON array.
|
* Container factory for creating containers for JSON object and JSON array.
|
||||||
*
|
*
|
||||||
|
* @author FangYidong<fangyidong @ yahoo.com.cn>
|
||||||
* @see com.alibaba.nacos.client.logger.json.parser.JSONParser#parse(java.io.Reader, ContainerFactory)
|
* @see com.alibaba.nacos.client.logger.json.parser.JSONParser#parse(java.io.Reader, ContainerFactory)
|
||||||
*
|
|
||||||
* @author FangYidong<fangyidong@yahoo.com.cn>
|
|
||||||
*/
|
*/
|
||||||
public interface ContainerFactory {
|
public interface ContainerFactory {
|
||||||
/**
|
/**
|
||||||
* create json container
|
* create json container
|
||||||
* @return A Map instance to store JSON object, or null if you want to use com.alibaba.nacos.client.logger.jsonJSONObject.
|
*
|
||||||
|
* @return A Map instance to store JSON object, or null if you want to use com.alibaba.nacos.client.logger
|
||||||
|
* .jsonJSONObject.
|
||||||
*/
|
*/
|
||||||
Map createObjectContainer();
|
Map createObjectContainer();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* create array json container
|
* create array json container
|
||||||
* @return A List instance to store JSON array, or null if you want to use com.alibaba.nacos.client.logger.jsonJSONArray.
|
*
|
||||||
|
* @return A List instance to store JSON array, or null if you want to use com.alibaba.nacos.client.logger
|
||||||
|
* .jsonJSONArray.
|
||||||
*/
|
*/
|
||||||
List creatArrayContainer();
|
List creatArrayContainer();
|
||||||
}
|
}
|
||||||
|
@ -20,18 +20,16 @@ import java.io.IOException;
|
|||||||
/**
|
/**
|
||||||
* A simplified and stoppable SAX-like content handler for stream processing of JSON text.
|
* A simplified and stoppable SAX-like content handler for stream processing of JSON text.
|
||||||
*
|
*
|
||||||
|
* @author FangYidong<fangyidong @ yahoo.com.cn>
|
||||||
* @see org.xml.sax.ContentHandler
|
* @see org.xml.sax.ContentHandler
|
||||||
* @see com.alibaba.nacos.client.logger.json.parser.JSONParser#parse(java.io.Reader, ContentHandler, boolean)
|
* @see com.alibaba.nacos.client.logger.json.parser.JSONParser#parse(java.io.Reader, ContentHandler, boolean)
|
||||||
*
|
|
||||||
* @author FangYidong<fangyidong@yahoo.com.cn>
|
|
||||||
*/
|
*/
|
||||||
public interface ContentHandler {
|
public interface ContentHandler {
|
||||||
/**
|
/**
|
||||||
* Receive notification of the beginning of JSON processing.
|
* Receive notification of the beginning of JSON processing. The parser will invoke this method only once.
|
||||||
* The parser will invoke this method only once.
|
|
||||||
*
|
*
|
||||||
* @throws ParseException
|
* @throws ParseException - JSONParser will stop and throw the same exception to the caller when receiving this
|
||||||
* - JSONParser will stop and throw the same exception to the caller when receiving this exception.
|
* exception.
|
||||||
* @throws IOException
|
* @throws IOException
|
||||||
*/
|
*/
|
||||||
void startJSON() throws ParseException, IOException;
|
void startJSON() throws ParseException, IOException;
|
||||||
@ -48,8 +46,8 @@ public interface ContentHandler {
|
|||||||
* Receive notification of the beginning of a JSON object.
|
* Receive notification of the beginning of a JSON object.
|
||||||
*
|
*
|
||||||
* @return false if the handler wants to stop parsing after return.
|
* @return false if the handler wants to stop parsing after return.
|
||||||
* @throws ParseException
|
* @throws ParseException - JSONParser will stop and throw the same exception to the caller when receiving this
|
||||||
* - JSONParser will stop and throw the same exception to the caller when receiving this exception.
|
* exception.
|
||||||
* @throws IOException
|
* @throws IOException
|
||||||
* @see #endJSON
|
* @see #endJSON
|
||||||
*/
|
*/
|
||||||
@ -69,7 +67,6 @@ public interface ContentHandler {
|
|||||||
* Receive notification of the beginning of a JSON object entry.
|
* Receive notification of the beginning of a JSON object entry.
|
||||||
*
|
*
|
||||||
* @param key - Key of a JSON object entry.
|
* @param key - Key of a JSON object entry.
|
||||||
*
|
|
||||||
* @return false if the handler wants to stop parsing after return.
|
* @return false if the handler wants to stop parsing after return.
|
||||||
* @throws ParseException
|
* @throws ParseException
|
||||||
* @throws IOException
|
* @throws IOException
|
||||||
@ -108,18 +105,9 @@ public interface ContentHandler {
|
|||||||
boolean endArray() throws ParseException, IOException;
|
boolean endArray() throws ParseException, IOException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Receive notification of the JSON primitive values:
|
* Receive notification of the JSON primitive values: java.lang.String, java.lang.Number, java.lang.Boolean null
|
||||||
* java.lang.String,
|
|
||||||
* java.lang.Number,
|
|
||||||
* java.lang.Boolean
|
|
||||||
* null
|
|
||||||
*
|
|
||||||
* @param value - Instance of the following:
|
|
||||||
* java.lang.String,
|
|
||||||
* java.lang.Number,
|
|
||||||
* java.lang.Boolean
|
|
||||||
* null
|
|
||||||
*
|
*
|
||||||
|
* @param value - Instance of the following: java.lang.String, java.lang.Number, java.lang.Boolean null
|
||||||
* @return false if the handler wants to stop parsing after return.
|
* @return false if the handler wants to stop parsing after return.
|
||||||
* @throws ParseException
|
* @throws ParseException
|
||||||
* @throws IOException
|
* @throws IOException
|
||||||
|
@ -29,41 +29,39 @@ import java.util.Map;
|
|||||||
import com.alibaba.nacos.client.logger.json.JSONArray;
|
import com.alibaba.nacos.client.logger.json.JSONArray;
|
||||||
import com.alibaba.nacos.client.logger.json.JSONObject;
|
import com.alibaba.nacos.client.logger.json.JSONObject;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Parser for JSON text. Please note that JSONParser is NOT thread-safe.
|
* Parser for JSON text. Please note that JSONParser is NOT thread-safe.
|
||||||
*
|
*
|
||||||
* @author FangYidong<fangyidong@yahoo.com.cn>
|
* @author FangYidong<fangyidong @ yahoo.com.cn>
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
|
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
|
||||||
public class JSONParser {
|
public class JSONParser {
|
||||||
public static final int S_INIT=0;
|
public static final int S_INIT = 0;
|
||||||
public static final int S_IN_FINISHED_VALUE=1;
|
public static final int S_IN_FINISHED_VALUE = 1;
|
||||||
public static final int S_IN_OBJECT=2;
|
public static final int S_IN_OBJECT = 2;
|
||||||
public static final int S_IN_ARRAY=3;
|
public static final int S_IN_ARRAY = 3;
|
||||||
public static final int S_PASSED_PAIR_KEY=4;
|
public static final int S_PASSED_PAIR_KEY = 4;
|
||||||
public static final int S_IN_PAIR_VALUE=5;
|
public static final int S_IN_PAIR_VALUE = 5;
|
||||||
public static final int S_END=6;
|
public static final int S_END = 6;
|
||||||
public static final int S_IN_ERROR=-1;
|
public static final int S_IN_ERROR = -1;
|
||||||
|
|
||||||
private LinkedList handlerStatusStack;
|
private LinkedList handlerStatusStack;
|
||||||
private Yylex lexer = new Yylex((Reader)null);
|
private Yylex lexer = new Yylex((Reader)null);
|
||||||
private Yytoken token = null;
|
private Yytoken token = null;
|
||||||
private int status = S_INIT;
|
private int status = S_INIT;
|
||||||
|
|
||||||
private int peekStatus(LinkedList statusStack){
|
private int peekStatus(LinkedList statusStack) {
|
||||||
if(statusStack.size()==0) {
|
if (statusStack.size() == 0) {
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
Integer status=(Integer)statusStack.getFirst();
|
Integer status = (Integer)statusStack.getFirst();
|
||||||
return status.intValue();
|
return status.intValue();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Reset the parser to the initial state without resetting the underlying reader.
|
* Reset the parser to the initial state without resetting the underlying reader.
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public void reset(){
|
public void reset() {
|
||||||
token = null;
|
token = null;
|
||||||
status = S_INIT;
|
status = S_INIT;
|
||||||
handlerStatusStack = null;
|
handlerStatusStack = null;
|
||||||
@ -76,7 +74,7 @@ public class JSONParser {
|
|||||||
* @throws IOException
|
* @throws IOException
|
||||||
* @throws ParseException
|
* @throws ParseException
|
||||||
*/
|
*/
|
||||||
public void reset(Reader in){
|
public void reset(Reader in) {
|
||||||
lexer.yyreset(in);
|
lexer.yyreset(in);
|
||||||
reset();
|
reset();
|
||||||
}
|
}
|
||||||
@ -84,20 +82,19 @@ public class JSONParser {
|
|||||||
/**
|
/**
|
||||||
* @return The position of the beginning of the current token.
|
* @return The position of the beginning of the current token.
|
||||||
*/
|
*/
|
||||||
public int getPosition(){
|
public int getPosition() {
|
||||||
return lexer.getPosition();
|
return lexer.getPosition();
|
||||||
}
|
}
|
||||||
|
|
||||||
public Object parse(String s) throws ParseException{
|
public Object parse(String s) throws ParseException {
|
||||||
return parse(s, (ContainerFactory)null);
|
return parse(s, (ContainerFactory)null);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Object parse(String s, ContainerFactory containerFactory) throws ParseException{
|
public Object parse(String s, ContainerFactory containerFactory) throws ParseException {
|
||||||
StringReader in=new StringReader(s);
|
StringReader in = new StringReader(s);
|
||||||
try{
|
try {
|
||||||
return parse(in, containerFactory);
|
return parse(in, containerFactory);
|
||||||
}
|
} catch (IOException ie) {
|
||||||
catch(IOException ie){
|
|
||||||
/*
|
/*
|
||||||
* Actually it will never happen.
|
* Actually it will never happen.
|
||||||
*/
|
*/
|
||||||
@ -105,7 +102,7 @@ public class JSONParser {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public Object parse(Reader in) throws IOException, ParseException{
|
public Object parse(Reader in) throws IOException, ParseException {
|
||||||
return parse(in, (ContainerFactory)null);
|
return parse(in, (ContainerFactory)null);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -114,158 +111,148 @@ public class JSONParser {
|
|||||||
*
|
*
|
||||||
* @param in
|
* @param in
|
||||||
* @param containerFactory - Use this factory to createyour own JSON object and JSON array containers.
|
* @param containerFactory - Use this factory to createyour own JSON object and JSON array containers.
|
||||||
* @return Instance of the following:
|
* @return Instance of the following: com.alibaba.nacos.client.logger.jsonJSONObject,
|
||||||
* com.alibaba.nacos.client.logger.jsonJSONObject,
|
* com.alibaba.nacos.client.logger.jsonJSONArray, java.lang.String, java.lang.Number, java.lang.Boolean, null
|
||||||
* com.alibaba.nacos.client.logger.jsonJSONArray,
|
|
||||||
* java.lang.String,
|
|
||||||
* java.lang.Number,
|
|
||||||
* java.lang.Boolean,
|
|
||||||
* null
|
|
||||||
*
|
|
||||||
* @throws IOException
|
* @throws IOException
|
||||||
* @throws ParseException
|
* @throws ParseException
|
||||||
*/
|
*/
|
||||||
public Object parse(Reader in, ContainerFactory containerFactory) throws IOException, ParseException{
|
public Object parse(Reader in, ContainerFactory containerFactory) throws IOException, ParseException {
|
||||||
reset(in);
|
reset(in);
|
||||||
LinkedList statusStack = new LinkedList();
|
LinkedList statusStack = new LinkedList();
|
||||||
LinkedList valueStack = new LinkedList();
|
LinkedList valueStack = new LinkedList();
|
||||||
|
|
||||||
try{
|
try {
|
||||||
do{
|
do {
|
||||||
nextToken();
|
nextToken();
|
||||||
switch(status){
|
switch (status) {
|
||||||
case S_INIT:
|
case S_INIT:
|
||||||
switch(token.type){
|
switch (token.type) {
|
||||||
case Yytoken.TYPE_VALUE:
|
case Yytoken.TYPE_VALUE:
|
||||||
status=S_IN_FINISHED_VALUE;
|
status = S_IN_FINISHED_VALUE;
|
||||||
statusStack.addFirst(Integer.valueOf(status));
|
statusStack.addFirst(Integer.valueOf(status));
|
||||||
valueStack.addFirst(token.value);
|
valueStack.addFirst(token.value);
|
||||||
break;
|
break;
|
||||||
case Yytoken.TYPE_LEFT_BRACE:
|
case Yytoken.TYPE_LEFT_BRACE:
|
||||||
status=S_IN_OBJECT;
|
status = S_IN_OBJECT;
|
||||||
statusStack.addFirst(Integer.valueOf(status));
|
statusStack.addFirst(Integer.valueOf(status));
|
||||||
valueStack.addFirst(createObjectContainer(containerFactory));
|
valueStack.addFirst(createObjectContainer(containerFactory));
|
||||||
break;
|
break;
|
||||||
case Yytoken.TYPE_LEFT_SQUARE:
|
case Yytoken.TYPE_LEFT_SQUARE:
|
||||||
status=S_IN_ARRAY;
|
status = S_IN_ARRAY;
|
||||||
statusStack.addFirst(Integer.valueOf(status));
|
statusStack.addFirst(Integer.valueOf(status));
|
||||||
valueStack.addFirst(createArrayContainer(containerFactory));
|
valueStack.addFirst(createArrayContainer(containerFactory));
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
status=S_IN_ERROR;
|
status = S_IN_ERROR;
|
||||||
}//inner switch
|
}//inner switch
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case S_IN_FINISHED_VALUE:
|
case S_IN_FINISHED_VALUE:
|
||||||
if(token.type==Yytoken.TYPE_EOF) {
|
if (token.type == Yytoken.TYPE_EOF) {
|
||||||
return valueStack.removeFirst();
|
return valueStack.removeFirst();
|
||||||
}
|
} else {
|
||||||
else {
|
|
||||||
throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token);
|
throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token);
|
||||||
}
|
}
|
||||||
case S_IN_OBJECT:
|
case S_IN_OBJECT:
|
||||||
switch(token.type){
|
switch (token.type) {
|
||||||
case Yytoken.TYPE_COMMA:
|
case Yytoken.TYPE_COMMA:
|
||||||
break;
|
break;
|
||||||
case Yytoken.TYPE_VALUE:
|
case Yytoken.TYPE_VALUE:
|
||||||
if(token.value instanceof String){
|
if (token.value instanceof String) {
|
||||||
String key=(String)token.value;
|
String key = (String)token.value;
|
||||||
valueStack.addFirst(key);
|
valueStack.addFirst(key);
|
||||||
status=S_PASSED_PAIR_KEY;
|
status = S_PASSED_PAIR_KEY;
|
||||||
statusStack.addFirst(Integer.valueOf(status));
|
statusStack.addFirst(Integer.valueOf(status));
|
||||||
}
|
} else {
|
||||||
else{
|
status = S_IN_ERROR;
|
||||||
status=S_IN_ERROR;
|
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case Yytoken.TYPE_RIGHT_BRACE:
|
case Yytoken.TYPE_RIGHT_BRACE:
|
||||||
if(valueStack.size()>1){
|
if (valueStack.size() > 1) {
|
||||||
statusStack.removeFirst();
|
statusStack.removeFirst();
|
||||||
valueStack.removeFirst();
|
valueStack.removeFirst();
|
||||||
status=peekStatus(statusStack);
|
status = peekStatus(statusStack);
|
||||||
}
|
} else {
|
||||||
else{
|
status = S_IN_FINISHED_VALUE;
|
||||||
status=S_IN_FINISHED_VALUE;
|
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
status=S_IN_ERROR;
|
status = S_IN_ERROR;
|
||||||
break;
|
break;
|
||||||
}//inner switch
|
}//inner switch
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case S_PASSED_PAIR_KEY:
|
case S_PASSED_PAIR_KEY:
|
||||||
switch(token.type){
|
switch (token.type) {
|
||||||
case Yytoken.TYPE_COLON:
|
case Yytoken.TYPE_COLON:
|
||||||
break;
|
break;
|
||||||
case Yytoken.TYPE_VALUE:
|
case Yytoken.TYPE_VALUE:
|
||||||
statusStack.removeFirst();
|
statusStack.removeFirst();
|
||||||
String key=(String)valueStack.removeFirst();
|
String key = (String)valueStack.removeFirst();
|
||||||
Map parent=(Map)valueStack.getFirst();
|
Map parent = (Map)valueStack.getFirst();
|
||||||
parent.put(key,token.value);
|
parent.put(key, token.value);
|
||||||
status=peekStatus(statusStack);
|
status = peekStatus(statusStack);
|
||||||
break;
|
break;
|
||||||
case Yytoken.TYPE_LEFT_SQUARE:
|
case Yytoken.TYPE_LEFT_SQUARE:
|
||||||
statusStack.removeFirst();
|
statusStack.removeFirst();
|
||||||
key=(String)valueStack.removeFirst();
|
key = (String)valueStack.removeFirst();
|
||||||
parent=(Map)valueStack.getFirst();
|
parent = (Map)valueStack.getFirst();
|
||||||
List newArray=createArrayContainer(containerFactory);
|
List newArray = createArrayContainer(containerFactory);
|
||||||
parent.put(key,newArray);
|
parent.put(key, newArray);
|
||||||
status=S_IN_ARRAY;
|
status = S_IN_ARRAY;
|
||||||
statusStack.addFirst(Integer.valueOf(status));
|
statusStack.addFirst(Integer.valueOf(status));
|
||||||
valueStack.addFirst(newArray);
|
valueStack.addFirst(newArray);
|
||||||
break;
|
break;
|
||||||
case Yytoken.TYPE_LEFT_BRACE:
|
case Yytoken.TYPE_LEFT_BRACE:
|
||||||
statusStack.removeFirst();
|
statusStack.removeFirst();
|
||||||
key=(String)valueStack.removeFirst();
|
key = (String)valueStack.removeFirst();
|
||||||
parent=(Map)valueStack.getFirst();
|
parent = (Map)valueStack.getFirst();
|
||||||
Map newObject=createObjectContainer(containerFactory);
|
Map newObject = createObjectContainer(containerFactory);
|
||||||
parent.put(key,newObject);
|
parent.put(key, newObject);
|
||||||
status=S_IN_OBJECT;
|
status = S_IN_OBJECT;
|
||||||
statusStack.addFirst(Integer.valueOf(status));
|
statusStack.addFirst(Integer.valueOf(status));
|
||||||
valueStack.addFirst(newObject);
|
valueStack.addFirst(newObject);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
status=S_IN_ERROR;
|
status = S_IN_ERROR;
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case S_IN_ARRAY:
|
case S_IN_ARRAY:
|
||||||
switch(token.type){
|
switch (token.type) {
|
||||||
case Yytoken.TYPE_COMMA:
|
case Yytoken.TYPE_COMMA:
|
||||||
break;
|
break;
|
||||||
case Yytoken.TYPE_VALUE:
|
case Yytoken.TYPE_VALUE:
|
||||||
List val=(List)valueStack.getFirst();
|
List val = (List)valueStack.getFirst();
|
||||||
val.add(token.value);
|
val.add(token.value);
|
||||||
break;
|
break;
|
||||||
case Yytoken.TYPE_RIGHT_SQUARE:
|
case Yytoken.TYPE_RIGHT_SQUARE:
|
||||||
if(valueStack.size()>1){
|
if (valueStack.size() > 1) {
|
||||||
statusStack.removeFirst();
|
statusStack.removeFirst();
|
||||||
valueStack.removeFirst();
|
valueStack.removeFirst();
|
||||||
status=peekStatus(statusStack);
|
status = peekStatus(statusStack);
|
||||||
}
|
} else {
|
||||||
else{
|
status = S_IN_FINISHED_VALUE;
|
||||||
status=S_IN_FINISHED_VALUE;
|
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case Yytoken.TYPE_LEFT_BRACE:
|
case Yytoken.TYPE_LEFT_BRACE:
|
||||||
val=(List)valueStack.getFirst();
|
val = (List)valueStack.getFirst();
|
||||||
Map newObject=createObjectContainer(containerFactory);
|
Map newObject = createObjectContainer(containerFactory);
|
||||||
val.add(newObject);
|
val.add(newObject);
|
||||||
status=S_IN_OBJECT;
|
status = S_IN_OBJECT;
|
||||||
statusStack.addFirst(Integer.valueOf(status));
|
statusStack.addFirst(Integer.valueOf(status));
|
||||||
valueStack.addFirst(newObject);
|
valueStack.addFirst(newObject);
|
||||||
break;
|
break;
|
||||||
case Yytoken.TYPE_LEFT_SQUARE:
|
case Yytoken.TYPE_LEFT_SQUARE:
|
||||||
val=(List)valueStack.getFirst();
|
val = (List)valueStack.getFirst();
|
||||||
List newArray=createArrayContainer(containerFactory);
|
List newArray = createArrayContainer(containerFactory);
|
||||||
val.add(newArray);
|
val.add(newArray);
|
||||||
status=S_IN_ARRAY;
|
status = S_IN_ARRAY;
|
||||||
statusStack.addFirst(Integer.valueOf(status));
|
statusStack.addFirst(Integer.valueOf(status));
|
||||||
valueStack.addFirst(newArray);
|
valueStack.addFirst(newArray);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
status=S_IN_ERROR;
|
status = S_IN_ERROR;
|
||||||
}//inner switch
|
}//inner switch
|
||||||
break;
|
break;
|
||||||
case S_IN_ERROR:
|
case S_IN_ERROR:
|
||||||
@ -273,59 +260,57 @@ public class JSONParser {
|
|||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}//switch
|
}//switch
|
||||||
if(status==S_IN_ERROR){
|
if (status == S_IN_ERROR) {
|
||||||
throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token);
|
throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token);
|
||||||
}
|
}
|
||||||
}while(token.type!=Yytoken.TYPE_EOF);
|
} while (token.type != Yytoken.TYPE_EOF);
|
||||||
}
|
} catch (IOException ie) {
|
||||||
catch(IOException ie){
|
|
||||||
throw ie;
|
throw ie;
|
||||||
}
|
}
|
||||||
|
|
||||||
throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token);
|
throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void nextToken() throws ParseException, IOException{
|
private void nextToken() throws ParseException, IOException {
|
||||||
token = lexer.yylex();
|
token = lexer.yylex();
|
||||||
if(token == null) {
|
if (token == null) {
|
||||||
token = new Yytoken(Yytoken.TYPE_EOF, null);
|
token = new Yytoken(Yytoken.TYPE_EOF, null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private Map createObjectContainer(ContainerFactory containerFactory){
|
private Map createObjectContainer(ContainerFactory containerFactory) {
|
||||||
if(containerFactory == null) {
|
if (containerFactory == null) {
|
||||||
return new JSONObject();
|
return new JSONObject();
|
||||||
}
|
}
|
||||||
Map m = containerFactory.createObjectContainer();
|
Map m = containerFactory.createObjectContainer();
|
||||||
|
|
||||||
if(m == null) {
|
if (m == null) {
|
||||||
return new JSONObject();
|
return new JSONObject();
|
||||||
}
|
}
|
||||||
return m;
|
return m;
|
||||||
}
|
}
|
||||||
|
|
||||||
private List createArrayContainer(ContainerFactory containerFactory){
|
private List createArrayContainer(ContainerFactory containerFactory) {
|
||||||
if(containerFactory == null) {
|
if (containerFactory == null) {
|
||||||
return new JSONArray();
|
return new JSONArray();
|
||||||
}
|
}
|
||||||
List l = containerFactory.creatArrayContainer();
|
List l = containerFactory.creatArrayContainer();
|
||||||
|
|
||||||
if(l == null) {
|
if (l == null) {
|
||||||
return new JSONArray();
|
return new JSONArray();
|
||||||
}
|
}
|
||||||
return l;
|
return l;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void parse(String s, ContentHandler contentHandler) throws ParseException{
|
public void parse(String s, ContentHandler contentHandler) throws ParseException {
|
||||||
parse(s, contentHandler, false);
|
parse(s, contentHandler, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void parse(String s, ContentHandler contentHandler, boolean isResume) throws ParseException{
|
public void parse(String s, ContentHandler contentHandler, boolean isResume) throws ParseException {
|
||||||
StringReader in=new StringReader(s);
|
StringReader in = new StringReader(s);
|
||||||
try{
|
try {
|
||||||
parse(in, contentHandler, isResume);
|
parse(in, contentHandler, isResume);
|
||||||
}
|
} catch (IOException ie) {
|
||||||
catch(IOException ie){
|
|
||||||
/*
|
/*
|
||||||
* Actually it will never happen.
|
* Actually it will never happen.
|
||||||
*/
|
*/
|
||||||
@ -333,31 +318,28 @@ public class JSONParser {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void parse(Reader in, ContentHandler contentHandler) throws IOException, ParseException{
|
public void parse(Reader in, ContentHandler contentHandler) throws IOException, ParseException {
|
||||||
parse(in, contentHandler, false);
|
parse(in, contentHandler, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Stream processing of JSON text.
|
* Stream processing of JSON text.
|
||||||
*
|
*
|
||||||
* @see ContentHandler
|
|
||||||
*
|
|
||||||
* @param in
|
* @param in
|
||||||
* @param contentHandler
|
* @param contentHandler
|
||||||
* @param isResume - Indicates if it continues previous parsing operation.
|
* @param isResume - Indicates if it continues previous parsing operation. If set to true, resume parsing the
|
||||||
* If set to true, resume parsing the old stream, and parameter 'in' will be ignored.
|
* old stream, and parameter 'in' will be ignored. If this method is called for the first time
|
||||||
* If this method is called for the first time in this instance, isResume will be ignored.
|
* in this instance, isResume will be ignored.
|
||||||
*
|
|
||||||
* @throws IOException
|
* @throws IOException
|
||||||
* @throws ParseException
|
* @throws ParseException
|
||||||
|
* @see ContentHandler
|
||||||
*/
|
*/
|
||||||
public void parse(Reader in, ContentHandler contentHandler, boolean isResume) throws IOException, ParseException{
|
public void parse(Reader in, ContentHandler contentHandler, boolean isResume) throws IOException, ParseException {
|
||||||
if(!isResume){
|
if (!isResume) {
|
||||||
reset(in);
|
reset(in);
|
||||||
handlerStatusStack = new LinkedList();
|
handlerStatusStack = new LinkedList();
|
||||||
}
|
} else {
|
||||||
else{
|
if (handlerStatusStack == null) {
|
||||||
if(handlerStatusStack == null){
|
|
||||||
isResume = false;
|
isResume = false;
|
||||||
reset(in);
|
reset(in);
|
||||||
handlerStatusStack = new LinkedList();
|
handlerStatusStack = new LinkedList();
|
||||||
@ -366,122 +348,119 @@ public class JSONParser {
|
|||||||
|
|
||||||
LinkedList statusStack = handlerStatusStack;
|
LinkedList statusStack = handlerStatusStack;
|
||||||
|
|
||||||
try{
|
try {
|
||||||
do{
|
do {
|
||||||
switch(status){
|
switch (status) {
|
||||||
case S_INIT:
|
case S_INIT:
|
||||||
contentHandler.startJSON();
|
contentHandler.startJSON();
|
||||||
nextToken();
|
nextToken();
|
||||||
switch(token.type){
|
switch (token.type) {
|
||||||
case Yytoken.TYPE_VALUE:
|
case Yytoken.TYPE_VALUE:
|
||||||
status=S_IN_FINISHED_VALUE;
|
status = S_IN_FINISHED_VALUE;
|
||||||
statusStack.addFirst(Integer.valueOf(status));
|
statusStack.addFirst(Integer.valueOf(status));
|
||||||
if(!contentHandler.primitive(token.value)) {
|
if (!contentHandler.primitive(token.value)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case Yytoken.TYPE_LEFT_BRACE:
|
case Yytoken.TYPE_LEFT_BRACE:
|
||||||
status=S_IN_OBJECT;
|
status = S_IN_OBJECT;
|
||||||
statusStack.addFirst(Integer.valueOf(status));
|
statusStack.addFirst(Integer.valueOf(status));
|
||||||
if(!contentHandler.startObject()) {
|
if (!contentHandler.startObject()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case Yytoken.TYPE_LEFT_SQUARE:
|
case Yytoken.TYPE_LEFT_SQUARE:
|
||||||
status=S_IN_ARRAY;
|
status = S_IN_ARRAY;
|
||||||
statusStack.addFirst(Integer.valueOf(status));
|
statusStack.addFirst(Integer.valueOf(status));
|
||||||
if(!contentHandler.startArray()) {
|
if (!contentHandler.startArray()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
status=S_IN_ERROR;
|
status = S_IN_ERROR;
|
||||||
}//inner switch
|
}//inner switch
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case S_IN_FINISHED_VALUE:
|
case S_IN_FINISHED_VALUE:
|
||||||
nextToken();
|
nextToken();
|
||||||
if(token.type==Yytoken.TYPE_EOF){
|
if (token.type == Yytoken.TYPE_EOF) {
|
||||||
contentHandler.endJSON();
|
contentHandler.endJSON();
|
||||||
status = S_END;
|
status = S_END;
|
||||||
return;
|
return;
|
||||||
}
|
} else {
|
||||||
else{
|
|
||||||
status = S_IN_ERROR;
|
status = S_IN_ERROR;
|
||||||
throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token);
|
throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token);
|
||||||
}
|
}
|
||||||
|
|
||||||
case S_IN_OBJECT:
|
case S_IN_OBJECT:
|
||||||
nextToken();
|
nextToken();
|
||||||
switch(token.type){
|
switch (token.type) {
|
||||||
case Yytoken.TYPE_COMMA:
|
case Yytoken.TYPE_COMMA:
|
||||||
break;
|
break;
|
||||||
case Yytoken.TYPE_VALUE:
|
case Yytoken.TYPE_VALUE:
|
||||||
if(token.value instanceof String){
|
if (token.value instanceof String) {
|
||||||
String key=(String)token.value;
|
String key = (String)token.value;
|
||||||
status=S_PASSED_PAIR_KEY;
|
status = S_PASSED_PAIR_KEY;
|
||||||
statusStack.addFirst(Integer.valueOf(status));
|
statusStack.addFirst(Integer.valueOf(status));
|
||||||
if(!contentHandler.startObjectEntry(key)) {
|
if (!contentHandler.startObjectEntry(key)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
} else {
|
||||||
else{
|
status = S_IN_ERROR;
|
||||||
status=S_IN_ERROR;
|
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case Yytoken.TYPE_RIGHT_BRACE:
|
case Yytoken.TYPE_RIGHT_BRACE:
|
||||||
if(statusStack.size()>1){
|
if (statusStack.size() > 1) {
|
||||||
statusStack.removeFirst();
|
statusStack.removeFirst();
|
||||||
status=peekStatus(statusStack);
|
status = peekStatus(statusStack);
|
||||||
|
} else {
|
||||||
|
status = S_IN_FINISHED_VALUE;
|
||||||
}
|
}
|
||||||
else{
|
if (!contentHandler.endObject()) {
|
||||||
status=S_IN_FINISHED_VALUE;
|
|
||||||
}
|
|
||||||
if(!contentHandler.endObject()) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
status=S_IN_ERROR;
|
status = S_IN_ERROR;
|
||||||
break;
|
break;
|
||||||
}//inner switch
|
}//inner switch
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case S_PASSED_PAIR_KEY:
|
case S_PASSED_PAIR_KEY:
|
||||||
nextToken();
|
nextToken();
|
||||||
switch(token.type){
|
switch (token.type) {
|
||||||
case Yytoken.TYPE_COLON:
|
case Yytoken.TYPE_COLON:
|
||||||
break;
|
break;
|
||||||
case Yytoken.TYPE_VALUE:
|
case Yytoken.TYPE_VALUE:
|
||||||
statusStack.removeFirst();
|
statusStack.removeFirst();
|
||||||
status=peekStatus(statusStack);
|
status = peekStatus(statusStack);
|
||||||
if(!contentHandler.primitive(token.value)) {
|
if (!contentHandler.primitive(token.value)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if(!contentHandler.endObjectEntry()) {
|
if (!contentHandler.endObjectEntry()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case Yytoken.TYPE_LEFT_SQUARE:
|
case Yytoken.TYPE_LEFT_SQUARE:
|
||||||
statusStack.removeFirst();
|
statusStack.removeFirst();
|
||||||
statusStack.addFirst(Integer.valueOf(S_IN_PAIR_VALUE));
|
statusStack.addFirst(Integer.valueOf(S_IN_PAIR_VALUE));
|
||||||
status=S_IN_ARRAY;
|
status = S_IN_ARRAY;
|
||||||
statusStack.addFirst(Integer.valueOf(status));
|
statusStack.addFirst(Integer.valueOf(status));
|
||||||
if(!contentHandler.startArray()) {
|
if (!contentHandler.startArray()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case Yytoken.TYPE_LEFT_BRACE:
|
case Yytoken.TYPE_LEFT_BRACE:
|
||||||
statusStack.removeFirst();
|
statusStack.removeFirst();
|
||||||
statusStack.addFirst(Integer.valueOf(S_IN_PAIR_VALUE));
|
statusStack.addFirst(Integer.valueOf(S_IN_PAIR_VALUE));
|
||||||
status=S_IN_OBJECT;
|
status = S_IN_OBJECT;
|
||||||
statusStack.addFirst(Integer.valueOf(status));
|
statusStack.addFirst(Integer.valueOf(status));
|
||||||
if(!contentHandler.startObject()) {
|
if (!contentHandler.startObject()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
status=S_IN_ERROR;
|
status = S_IN_ERROR;
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
@ -492,49 +471,48 @@ public class JSONParser {
|
|||||||
*/
|
*/
|
||||||
statusStack.removeFirst();
|
statusStack.removeFirst();
|
||||||
status = peekStatus(statusStack);
|
status = peekStatus(statusStack);
|
||||||
if(!contentHandler.endObjectEntry()) {
|
if (!contentHandler.endObjectEntry()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case S_IN_ARRAY:
|
case S_IN_ARRAY:
|
||||||
nextToken();
|
nextToken();
|
||||||
switch(token.type){
|
switch (token.type) {
|
||||||
case Yytoken.TYPE_COMMA:
|
case Yytoken.TYPE_COMMA:
|
||||||
break;
|
break;
|
||||||
case Yytoken.TYPE_VALUE:
|
case Yytoken.TYPE_VALUE:
|
||||||
if(!contentHandler.primitive(token.value)) {
|
if (!contentHandler.primitive(token.value)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case Yytoken.TYPE_RIGHT_SQUARE:
|
case Yytoken.TYPE_RIGHT_SQUARE:
|
||||||
if(statusStack.size()>1){
|
if (statusStack.size() > 1) {
|
||||||
statusStack.removeFirst();
|
statusStack.removeFirst();
|
||||||
status=peekStatus(statusStack);
|
status = peekStatus(statusStack);
|
||||||
|
} else {
|
||||||
|
status = S_IN_FINISHED_VALUE;
|
||||||
}
|
}
|
||||||
else{
|
if (!contentHandler.endArray()) {
|
||||||
status=S_IN_FINISHED_VALUE;
|
|
||||||
}
|
|
||||||
if(!contentHandler.endArray()) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case Yytoken.TYPE_LEFT_BRACE:
|
case Yytoken.TYPE_LEFT_BRACE:
|
||||||
status=S_IN_OBJECT;
|
status = S_IN_OBJECT;
|
||||||
statusStack.addFirst(Integer.valueOf(status));
|
statusStack.addFirst(Integer.valueOf(status));
|
||||||
if(!contentHandler.startObject()) {
|
if (!contentHandler.startObject()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case Yytoken.TYPE_LEFT_SQUARE:
|
case Yytoken.TYPE_LEFT_SQUARE:
|
||||||
status=S_IN_ARRAY;
|
status = S_IN_ARRAY;
|
||||||
statusStack.addFirst(Integer.valueOf(status));
|
statusStack.addFirst(Integer.valueOf(status));
|
||||||
if(!contentHandler.startArray()) {
|
if (!contentHandler.startArray()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
status=S_IN_ERROR;
|
status = S_IN_ERROR;
|
||||||
}//inner switch
|
}//inner switch
|
||||||
break;
|
break;
|
||||||
|
|
||||||
@ -546,24 +524,20 @@ public class JSONParser {
|
|||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}//switch
|
}//switch
|
||||||
if(status==S_IN_ERROR){
|
if (status == S_IN_ERROR) {
|
||||||
throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token);
|
throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token);
|
||||||
}
|
}
|
||||||
}while(token.type!=Yytoken.TYPE_EOF);
|
} while (token.type != Yytoken.TYPE_EOF);
|
||||||
}
|
} catch (IOException ie) {
|
||||||
catch(IOException ie){
|
|
||||||
status = S_IN_ERROR;
|
status = S_IN_ERROR;
|
||||||
throw ie;
|
throw ie;
|
||||||
}
|
} catch (ParseException pe) {
|
||||||
catch(ParseException pe){
|
|
||||||
status = S_IN_ERROR;
|
status = S_IN_ERROR;
|
||||||
throw pe;
|
throw pe;
|
||||||
}
|
} catch (RuntimeException re) {
|
||||||
catch(RuntimeException re){
|
|
||||||
status = S_IN_ERROR;
|
status = S_IN_ERROR;
|
||||||
throw re;
|
throw re;
|
||||||
}
|
} catch (Error e) {
|
||||||
catch(Error e){
|
|
||||||
status = S_IN_ERROR;
|
status = S_IN_ERROR;
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
|
@ -18,8 +18,7 @@ package com.alibaba.nacos.client.logger.json.parser;
|
|||||||
/**
|
/**
|
||||||
* ParseException explains why and where the error occurs in source JSON text.
|
* ParseException explains why and where the error occurs in source JSON text.
|
||||||
*
|
*
|
||||||
* @author FangYidong<fangyidong@yahoo.com.cn>
|
* @author FangYidong<fangyidong @ yahoo.com.cn>
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public class ParseException extends Exception {
|
public class ParseException extends Exception {
|
||||||
private static final long serialVersionUID = -7880698968187728547L;
|
private static final long serialVersionUID = -7880698968187728547L;
|
||||||
@ -32,15 +31,15 @@ public class ParseException extends Exception {
|
|||||||
private Object unexpectedObject;
|
private Object unexpectedObject;
|
||||||
private int position;
|
private int position;
|
||||||
|
|
||||||
public ParseException(int errorType){
|
public ParseException(int errorType) {
|
||||||
this(-1, errorType, null);
|
this(-1, errorType, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
public ParseException(int errorType, Object unexpectedObject){
|
public ParseException(int errorType, Object unexpectedObject) {
|
||||||
this(-1, errorType, unexpectedObject);
|
this(-1, errorType, unexpectedObject);
|
||||||
}
|
}
|
||||||
|
|
||||||
public ParseException(int position, int errorType, Object unexpectedObject){
|
public ParseException(int position, int errorType, Object unexpectedObject) {
|
||||||
this.position = position;
|
this.position = position;
|
||||||
this.errorType = errorType;
|
this.errorType = errorType;
|
||||||
this.unexpectedObject = unexpectedObject;
|
this.unexpectedObject = unexpectedObject;
|
||||||
@ -55,9 +54,8 @@ public class ParseException extends Exception {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @see com.alibaba.nacos.client.logger.json.parser.JSONParser#getPosition()
|
|
||||||
*
|
|
||||||
* @return The character position (starting with 0) of the input where the error occurs.
|
* @return The character position (starting with 0) of the input where the error occurs.
|
||||||
|
* @see com.alibaba.nacos.client.logger.json.parser.JSONParser#getPosition()
|
||||||
*/
|
*/
|
||||||
public int getPosition() {
|
public int getPosition() {
|
||||||
return position;
|
return position;
|
||||||
@ -68,12 +66,10 @@ public class ParseException extends Exception {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
* @return One of the following base on the value of errorType: ERROR_UNEXPECTED_CHAR java.lang.Character
|
||||||
|
* ERROR_UNEXPECTED_TOKEN com.alibaba.nacos.client.logger.jsonparser.Yytoken ERROR_UNEXPECTED_EXCEPTION
|
||||||
|
* java.lang.Exception
|
||||||
* @see com.alibaba.nacos.client.logger.json.parser.Yytoken
|
* @see com.alibaba.nacos.client.logger.json.parser.Yytoken
|
||||||
*
|
|
||||||
* @return One of the following base on the value of errorType:
|
|
||||||
* ERROR_UNEXPECTED_CHAR java.lang.Character
|
|
||||||
* ERROR_UNEXPECTED_TOKEN com.alibaba.nacos.client.logger.jsonparser.Yytoken
|
|
||||||
* ERROR_UNEXPECTED_EXCEPTION java.lang.Exception
|
|
||||||
*/
|
*/
|
||||||
public Object getUnexpectedObject() {
|
public Object getUnexpectedObject() {
|
||||||
return unexpectedObject;
|
return unexpectedObject;
|
||||||
@ -86,12 +82,14 @@ public class ParseException extends Exception {
|
|||||||
public String getMessage() {
|
public String getMessage() {
|
||||||
StringBuffer sb = new StringBuffer();
|
StringBuffer sb = new StringBuffer();
|
||||||
|
|
||||||
switch(errorType){
|
switch (errorType) {
|
||||||
case ERROR_UNEXPECTED_CHAR:
|
case ERROR_UNEXPECTED_CHAR:
|
||||||
sb.append("Unexpected character (").append(unexpectedObject).append(") at position ").append(position).append(".");
|
sb.append("Unexpected character (").append(unexpectedObject).append(") at position ").append(position)
|
||||||
|
.append(".");
|
||||||
break;
|
break;
|
||||||
case ERROR_UNEXPECTED_TOKEN:
|
case ERROR_UNEXPECTED_TOKEN:
|
||||||
sb.append("Unexpected token ").append(unexpectedObject).append(" at position ").append(position).append(".");
|
sb.append("Unexpected token ").append(unexpectedObject).append(" at position ").append(position).append(
|
||||||
|
".");
|
||||||
break;
|
break;
|
||||||
case ERROR_UNEXPECTED_EXCEPTION:
|
case ERROR_UNEXPECTED_EXCEPTION:
|
||||||
sb.append("Unexpected exception at position ").append(position).append(": ").append(unexpectedObject);
|
sb.append("Unexpected exception at position ").append(position).append(": ").append(unexpectedObject);
|
||||||
|
@ -23,28 +23,32 @@ import java.io.UnsupportedEncodingException;
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Yylex
|
* Yylex
|
||||||
* @author Nacos
|
|
||||||
*
|
*
|
||||||
|
* @author Nacos
|
||||||
*/
|
*/
|
||||||
class Yylex {
|
class Yylex {
|
||||||
|
|
||||||
/** This character denotes the end of file */
|
/**
|
||||||
|
* This character denotes the end of file
|
||||||
|
*/
|
||||||
public static final int YYEOF = -1;
|
public static final int YYEOF = -1;
|
||||||
|
|
||||||
/** initial size of the lookahead buffer */
|
/**
|
||||||
|
* initial size of the lookahead buffer
|
||||||
|
*/
|
||||||
private static final int ZZ_BUFFERSIZE = 16384;
|
private static final int ZZ_BUFFERSIZE = 16384;
|
||||||
|
|
||||||
/** lexical states */
|
/**
|
||||||
|
* lexical states
|
||||||
|
*/
|
||||||
public static final int YYINITIAL = 0;
|
public static final int YYINITIAL = 0;
|
||||||
public static final int STRING_BEGIN = 2;
|
public static final int STRING_BEGIN = 2;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l
|
* ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l ZZ_LEXSTATE[l+1] is the state in the DFA for the
|
||||||
* ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l
|
* lexical state l at the beginning of a line l is of the form l = 2*k, k a non negative integer
|
||||||
* at the beginning of a line
|
|
||||||
* l is of the form l = 2*k, k a non negative integer
|
|
||||||
*/
|
*/
|
||||||
private static final int ZZ_LEXSTATE[] = { 0, 0, 1, 1 };
|
private static final int ZZ_LEXSTATE[] = {0, 0, 1, 1};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Translates characters to character classes
|
* Translates characters to character classes
|
||||||
@ -82,7 +86,7 @@ class Yylex {
|
|||||||
while (i < l) {
|
while (i < l) {
|
||||||
int count = packed.charAt(i++);
|
int count = packed.charAt(i++);
|
||||||
int value = packed.charAt(i++);
|
int value = packed.charAt(i++);
|
||||||
do result[j++] = value; while (--count > 0);
|
do { result[j++] = value; } while (--count > 0);
|
||||||
}
|
}
|
||||||
return j;
|
return j;
|
||||||
}
|
}
|
||||||
@ -118,7 +122,7 @@ class Yylex {
|
|||||||
/**
|
/**
|
||||||
* The transition table of the DFA
|
* The transition table of the DFA
|
||||||
*/
|
*/
|
||||||
private static final int ZZ_TRANS[] = { 2, 2, 3, 4, 2, 2, 2, 5, 2, 6, 2, 2, 7, 8, 2, 9, 2, 2, 2, 2, 2, 10, 11, 12,
|
private static final int ZZ_TRANS[] = {2, 2, 3, 4, 2, 2, 2, 5, 2, 6, 2, 2, 7, 8, 2, 9, 2, 2, 2, 2, 2, 10, 11, 12,
|
||||||
13, 14, 15, 16, 16, 16, 16, 16, 16, 16, 16, 17, 18, 16, 16, 16, 16, 16, 16,
|
13, 14, 15, 16, 16, 16, 16, 16, 16, 16, 16, 17, 18, 16, 16, 16, 16, 16, 16,
|
||||||
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, -1, -1, -1, -1, -1, -1, -1, -1,
|
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||||
@ -153,7 +157,7 @@ class Yylex {
|
|||||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, 43, -1, 43, -1, 43, -1, -1, -1, -1, -1,
|
-1, -1, -1, -1, -1, -1, -1, -1, -1, 43, -1, 43, -1, 43, -1, -1, -1, -1, -1,
|
||||||
43, 43, -1, -1, -1, -1, 43, 43, -1, -1, -1, -1, -1, -1, -1, -1, -1, 44, -1,
|
43, 43, -1, -1, -1, -1, 43, 43, -1, -1, -1, -1, -1, -1, -1, -1, -1, 44, -1,
|
||||||
44, -1, 44, -1, -1, -1, -1, -1, 44, 44, -1, -1, -1, -1, 44, 44, -1, -1, -1,
|
44, -1, 44, -1, -1, -1, -1, -1, 44, 44, -1, -1, -1, -1, 44, 44, -1, -1, -1,
|
||||||
-1, -1, -1, -1, -1, };
|
-1, -1, -1, -1, -1,};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* error codes
|
* error codes
|
||||||
@ -165,8 +169,8 @@ class Yylex {
|
|||||||
/**
|
/**
|
||||||
* error messages for the codes above
|
* error messages for the codes above
|
||||||
*/
|
*/
|
||||||
private static final String[] ZZ_ERROR_MSG = { "Unkown internal scanner error", "Error: could not match input",
|
private static final String[] ZZ_ERROR_MSG = {"Unkown internal scanner error", "Error: could not match input",
|
||||||
"Error: pushback value was too large" };
|
"Error: pushback value was too large"};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* ZZ_ATTRIBUTE[aState] contains the attributes of state <code>aState</code>
|
* ZZ_ATTRIBUTE[aState] contains the attributes of state <code>aState</code>
|
||||||
@ -190,45 +194,59 @@ class Yylex {
|
|||||||
while (i < l) {
|
while (i < l) {
|
||||||
int count = packed.charAt(i++);
|
int count = packed.charAt(i++);
|
||||||
int value = packed.charAt(i++);
|
int value = packed.charAt(i++);
|
||||||
do result[j++] = value; while (--count > 0);
|
do { result[j++] = value; } while (--count > 0);
|
||||||
}
|
}
|
||||||
return j;
|
return j;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** the input device */
|
/**
|
||||||
|
* the input device
|
||||||
|
*/
|
||||||
private java.io.Reader zzReader;
|
private java.io.Reader zzReader;
|
||||||
|
|
||||||
/** the current state of the DFA */
|
/**
|
||||||
|
* the current state of the DFA
|
||||||
|
*/
|
||||||
private int zzState;
|
private int zzState;
|
||||||
|
|
||||||
/** the current lexical state */
|
/**
|
||||||
|
* the current lexical state
|
||||||
|
*/
|
||||||
private int zzLexicalState = YYINITIAL;
|
private int zzLexicalState = YYINITIAL;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* this buffer contains the current text to be matched and is
|
* this buffer contains the current text to be matched and is the source of the yytext() string
|
||||||
* the source of the yytext() string
|
|
||||||
*/
|
*/
|
||||||
private char zzBuffer[] = new char[ZZ_BUFFERSIZE];
|
private char zzBuffer[] = new char[ZZ_BUFFERSIZE];
|
||||||
|
|
||||||
/** the textposition at the last accepting state */
|
/**
|
||||||
|
* the textposition at the last accepting state
|
||||||
|
*/
|
||||||
private int zzMarkedPos;
|
private int zzMarkedPos;
|
||||||
|
|
||||||
/** the current text position in the buffer */
|
/**
|
||||||
|
* the current text position in the buffer
|
||||||
|
*/
|
||||||
private int zzCurrentPos;
|
private int zzCurrentPos;
|
||||||
|
|
||||||
/** startRead marks the beginning of the yytext() string in the buffer */
|
/**
|
||||||
|
* startRead marks the beginning of the yytext() string in the buffer
|
||||||
|
*/
|
||||||
private int zzStartRead;
|
private int zzStartRead;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* endRead marks the last character in the buffer, that has been read
|
* endRead marks the last character in the buffer, that has been read from input
|
||||||
* from input
|
|
||||||
*/
|
*/
|
||||||
private int zzEndRead;
|
private int zzEndRead;
|
||||||
|
|
||||||
/** the number of characters up to the start of the matched text */
|
/**
|
||||||
|
* the number of characters up to the start of the matched text
|
||||||
|
*/
|
||||||
private int yychar;
|
private int yychar;
|
||||||
|
|
||||||
/** zzAtEOF == true <=> the scanner is at the EOF */
|
/**
|
||||||
|
* zzAtEOF == true <=> the scanner is at the EOF
|
||||||
|
*/
|
||||||
private boolean zzAtEOF;
|
private boolean zzAtEOF;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -241,8 +259,7 @@ class Yylex {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a new scanner
|
* Creates a new scanner There is also a java.io.InputStream version of this constructor.
|
||||||
* There is also a java.io.InputStream version of this constructor.
|
|
||||||
*
|
*
|
||||||
* @param in the java.io.Reader to read input from.
|
* @param in the java.io.Reader to read input from.
|
||||||
*/
|
*/
|
||||||
@ -251,8 +268,7 @@ class Yylex {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a new scanner.
|
* Creates a new scanner. There is also java.io.Reader version of this constructor.
|
||||||
* There is also java.io.Reader version of this constructor.
|
|
||||||
*
|
*
|
||||||
* @param in the java.io.Inputstream to read input from.
|
* @param in the java.io.Inputstream to read input from.
|
||||||
* @throws UnsupportedEncodingException
|
* @throws UnsupportedEncodingException
|
||||||
@ -274,7 +290,7 @@ class Yylex {
|
|||||||
while (i < NIGTY) {
|
while (i < NIGTY) {
|
||||||
int count = packed.charAt(i++);
|
int count = packed.charAt(i++);
|
||||||
char value = packed.charAt(i++);
|
char value = packed.charAt(i++);
|
||||||
do map[j++] = value; while (--count > 0);
|
do { map[j++] = value; } while (--count > 0);
|
||||||
}
|
}
|
||||||
return map;
|
return map;
|
||||||
}
|
}
|
||||||
@ -319,7 +335,7 @@ class Yylex {
|
|||||||
if (c == -1) {
|
if (c == -1) {
|
||||||
return true;
|
return true;
|
||||||
} else {
|
} else {
|
||||||
zzBuffer[zzEndRead++] = (char) c;
|
zzBuffer[zzEndRead++] = (char)c;
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -341,11 +357,9 @@ class Yylex {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Resets the scanner to read from a new input stream.
|
* Resets the scanner to read from a new input stream. Does not close the old reader. All internal variables are
|
||||||
* Does not close the old reader.
|
* reset, the old input stream <b>cannot</b> be reused (internal buffer is discarded and lost). Lexical state is set
|
||||||
* All internal variables are reset, the old input stream
|
* to <tt>ZZ_INITIAL</tt>.
|
||||||
* <b>cannot</b> be reused (internal buffer is discarded and lost).
|
|
||||||
* Lexical state is set to <tt>ZZ_INITIAL</tt>.
|
|
||||||
*
|
*
|
||||||
* @param reader the new input stream
|
* @param reader the new input stream
|
||||||
*/
|
*/
|
||||||
@ -381,12 +395,10 @@ class Yylex {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the character at position <tt>pos</tt> from the
|
* Returns the character at position <tt>pos</tt> from the matched text. It is equivalent to yytext().charAt(pos),
|
||||||
* matched text.
|
* but faster
|
||||||
* It is equivalent to yytext().charAt(pos), but faster
|
|
||||||
*
|
*
|
||||||
* @param pos the position of the character to fetch.
|
* @param pos the position of the character to fetch. A value from 0 to yylength()-1.
|
||||||
* A value from 0 to yylength()-1.
|
|
||||||
* @return the character at position pos
|
* @return the character at position pos
|
||||||
*/
|
*/
|
||||||
public final char yycharat(int pos) {
|
public final char yycharat(int pos) {
|
||||||
@ -401,14 +413,10 @@ class Yylex {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Reports an error that occured while scanning.
|
* Reports an error that occured while scanning. In a wellformed scanner (no or only correct usage of
|
||||||
* In a wellformed scanner (no or only correct usage of
|
* yypushback(int) and a match-all fallback rule) this method will only be called with things that "Can't Possibly
|
||||||
* yypushback(int) and a match-all fallback rule) this method
|
* Happen". If this method is called, something is seriously wrong (e.g. a JFlex bug producing a faulty scanner
|
||||||
* will only be called with things that "Can't Possibly Happen".
|
* etc.). Usual syntax/scanner level error handling should be done in error fallback rules.
|
||||||
* If this method is called, something is seriously wrong
|
|
||||||
* (e.g. a JFlex bug producing a faulty scanner etc.).
|
|
||||||
* Usual syntax/scanner level error handling should be done
|
|
||||||
* in error fallback rules.
|
|
||||||
*
|
*
|
||||||
* @param errorCode the code of the errormessage to display
|
* @param errorCode the code of the errormessage to display
|
||||||
*/
|
*/
|
||||||
@ -424,11 +432,10 @@ class Yylex {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Pushes the specified amount of characters back into the input stream.
|
* Pushes the specified amount of characters back into the input stream. They will be read again by then next call
|
||||||
* They will be read again by then next call of the scanning method
|
* of the scanning method
|
||||||
*
|
*
|
||||||
* @param number the number of characters to be read again.
|
* @param number the number of characters to be read again. This number must not be greater than yylength()!
|
||||||
* This number must not be greater than yylength()!
|
|
||||||
*/
|
*/
|
||||||
public void yypushback(int number) {
|
public void yypushback(int number) {
|
||||||
if (number > yylength()) {
|
if (number > yylength()) {
|
||||||
@ -439,8 +446,8 @@ class Yylex {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Resumes scanning until the next regular expression is matched,
|
* Resumes scanning until the next regular expression is matched, the end of input is encountered or an I/O-Error
|
||||||
* the end of input is encountered or an I/O-Error occurs.
|
* occurs.
|
||||||
*
|
*
|
||||||
* @return the next token
|
* @return the next token
|
||||||
* @throws java.io.IOException if any I/O-Error occurs
|
* @throws java.io.IOException if any I/O-Error occurs
|
||||||
@ -478,8 +485,7 @@ class Yylex {
|
|||||||
|
|
||||||
if (zzCurrentPosL < zzEndReadL) {
|
if (zzCurrentPosL < zzEndReadL) {
|
||||||
zzInput = zzBufferL[zzCurrentPosL++];
|
zzInput = zzBufferL[zzCurrentPosL++];
|
||||||
}
|
} else if (zzAtEOF) {
|
||||||
else if (zzAtEOF) {
|
|
||||||
zzInput = YYEOF;
|
zzInput = YYEOF;
|
||||||
break zzForAction;
|
break zzForAction;
|
||||||
} else {
|
} else {
|
||||||
@ -572,7 +578,8 @@ class Yylex {
|
|||||||
case 33:
|
case 33:
|
||||||
break;
|
break;
|
||||||
case 1: {
|
case 1: {
|
||||||
throw new ParseException(yychar, ParseException.ERROR_UNEXPECTED_CHAR, Character.valueOf(yycharat(0)));
|
throw new ParseException(yychar, ParseException.ERROR_UNEXPECTED_CHAR,
|
||||||
|
Character.valueOf(yycharat(0)));
|
||||||
}
|
}
|
||||||
case 34:
|
case 34:
|
||||||
break;
|
break;
|
||||||
@ -614,7 +621,7 @@ class Yylex {
|
|||||||
case 24: {
|
case 24: {
|
||||||
try {
|
try {
|
||||||
int ch = Integer.parseInt(yytext().substring(2), 16);
|
int ch = Integer.parseInt(yytext().substring(2), 16);
|
||||||
sb.append((char) ch);
|
sb.append((char)ch);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
throw new ParseException(yychar, ParseException.ERROR_UNEXPECTED_EXCEPTION, e);
|
throw new ParseException(yychar, ParseException.ERROR_UNEXPECTED_EXCEPTION, e);
|
||||||
}
|
}
|
||||||
|
@ -20,35 +20,35 @@
|
|||||||
package com.alibaba.nacos.client.logger.json.parser;
|
package com.alibaba.nacos.client.logger.json.parser;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author FangYidong<fangyidong@yahoo.com.cn>
|
* @author FangYidong<fangyidong @ yahoo.com.cn>
|
||||||
*/
|
*/
|
||||||
public class Yytoken {
|
public class Yytoken {
|
||||||
/**
|
/**
|
||||||
* JSON primitive value: string,number,boolean,null
|
* JSON primitive value: string,number,boolean,null
|
||||||
*/
|
*/
|
||||||
public static final int TYPE_VALUE=0;
|
public static final int TYPE_VALUE = 0;
|
||||||
public static final int TYPE_LEFT_BRACE=1;
|
public static final int TYPE_LEFT_BRACE = 1;
|
||||||
public static final int TYPE_RIGHT_BRACE=2;
|
public static final int TYPE_RIGHT_BRACE = 2;
|
||||||
public static final int TYPE_LEFT_SQUARE=3;
|
public static final int TYPE_LEFT_SQUARE = 3;
|
||||||
public static final int TYPE_RIGHT_SQUARE=4;
|
public static final int TYPE_RIGHT_SQUARE = 4;
|
||||||
public static final int TYPE_COMMA=5;
|
public static final int TYPE_COMMA = 5;
|
||||||
public static final int TYPE_COLON=6;
|
public static final int TYPE_COLON = 6;
|
||||||
/**
|
/**
|
||||||
* end of file
|
* end of file
|
||||||
*/
|
*/
|
||||||
public static final int TYPE_EOF=-1;
|
public static final int TYPE_EOF = -1;
|
||||||
|
|
||||||
public int type=0;
|
public int type = 0;
|
||||||
public Object value=null;
|
public Object value = null;
|
||||||
|
|
||||||
public Yytoken(int type,Object value){
|
public Yytoken(int type, Object value) {
|
||||||
this.type=type;
|
this.type = type;
|
||||||
this.value=value;
|
this.value = value;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String toString(){
|
public String toString() {
|
||||||
StringBuffer sb = new StringBuffer();
|
StringBuffer sb = new StringBuffer();
|
||||||
switch(type){
|
switch (type) {
|
||||||
case TYPE_VALUE:
|
case TYPE_VALUE:
|
||||||
sb.append("VALUE(").append(value).append(")");
|
sb.append("VALUE(").append(value).append(")");
|
||||||
break;
|
break;
|
||||||
|
@ -21,11 +21,10 @@ import com.alibaba.nacos.client.logger.support.LoggerHelper;
|
|||||||
import com.alibaba.nacos.client.logger.support.LoggerSupport;
|
import com.alibaba.nacos.client.logger.support.LoggerSupport;
|
||||||
import com.alibaba.nacos.client.logger.util.MessageUtil;
|
import com.alibaba.nacos.client.logger.util.MessageUtil;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Log4j2Logger
|
* Log4j2Logger
|
||||||
* @author Nacos
|
|
||||||
*
|
*
|
||||||
|
* @author Nacos
|
||||||
*/
|
*/
|
||||||
public class Log4j2Logger extends LoggerSupport implements Logger {
|
public class Log4j2Logger extends LoggerSupport implements Logger {
|
||||||
|
|
||||||
|
@ -24,8 +24,8 @@ import com.alibaba.nacos.client.logger.support.LogLog;
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Log4j2Logger Factory
|
* Log4j2Logger Factory
|
||||||
* @author Nacos
|
|
||||||
*
|
*
|
||||||
|
* @author Nacos
|
||||||
*/
|
*/
|
||||||
public class Log4j2LoggerFactory implements ILoggerFactory {
|
public class Log4j2LoggerFactory implements ILoggerFactory {
|
||||||
|
|
||||||
|
@ -17,14 +17,15 @@ package com.alibaba.nacos.client.logger.nop;
|
|||||||
|
|
||||||
import com.alibaba.nacos.client.logger.Logger;
|
import com.alibaba.nacos.client.logger.Logger;
|
||||||
import com.alibaba.nacos.client.logger.support.LoggerSupport;
|
import com.alibaba.nacos.client.logger.support.LoggerSupport;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* NopLogger
|
* NopLogger
|
||||||
* @author Nacos
|
|
||||||
*
|
*
|
||||||
|
* @author Nacos
|
||||||
*/
|
*/
|
||||||
public class NopLogger extends LoggerSupport implements Logger {
|
public class NopLogger extends LoggerSupport implements Logger {
|
||||||
|
|
||||||
public NopLogger(){
|
public NopLogger() {
|
||||||
super(null);
|
super(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -17,10 +17,11 @@ package com.alibaba.nacos.client.logger.nop;
|
|||||||
|
|
||||||
import com.alibaba.nacos.client.logger.Logger;
|
import com.alibaba.nacos.client.logger.Logger;
|
||||||
import com.alibaba.nacos.client.logger.support.ILoggerFactory;
|
import com.alibaba.nacos.client.logger.support.ILoggerFactory;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* NopLogger Factory
|
* NopLogger Factory
|
||||||
* @author Nacos
|
|
||||||
*
|
*
|
||||||
|
* @author Nacos
|
||||||
*/
|
*/
|
||||||
public class NopLoggerFactory implements ILoggerFactory {
|
public class NopLoggerFactory implements ILoggerFactory {
|
||||||
|
|
||||||
|
@ -24,8 +24,8 @@ import java.util.List;
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* AbstractActiveOption
|
* AbstractActiveOption
|
||||||
* @author Nacos
|
|
||||||
*
|
*
|
||||||
|
* @author Nacos
|
||||||
*/
|
*/
|
||||||
public abstract class AbstractActiveOption implements ActivateOption {
|
public abstract class AbstractActiveOption implements ActivateOption {
|
||||||
|
|
||||||
@ -53,7 +53,7 @@ public abstract class AbstractActiveOption implements ActivateOption {
|
|||||||
for (Object[] arg : args) {
|
for (Object[] arg : args) {
|
||||||
if (arg != null && arg.length == 3) {
|
if (arg != null && arg.length == 3) {
|
||||||
try {
|
try {
|
||||||
Method m = object.getClass().getMethod((String) arg[0], (Class<?>[]) arg[1]);
|
Method m = object.getClass().getMethod((String)arg[0], (Class<?>[])arg[1]);
|
||||||
m.invoke(object, arg[2]);
|
m.invoke(object, arg[2]);
|
||||||
} catch (NoSuchMethodException e) {
|
} catch (NoSuchMethodException e) {
|
||||||
LogLog.info("Can't find method for " + object.getClass() + " " + arg[0] + " " + arg[2]);
|
LogLog.info("Can't find method for " + object.getClass() + " " + arg[0] + " " + arg[2]);
|
||||||
|
@ -140,8 +140,7 @@ public interface ActivateOption {
|
|||||||
int maxBackupIndex);
|
int maxBackupIndex);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 将当前logger对象的appender设置为异步Appender
|
* 将当前logger对象的appender设置为异步Appender 注意:此logger需要提前进行Appender的初始化
|
||||||
* 注意:此logger需要提前进行Appender的初始化
|
|
||||||
*
|
*
|
||||||
* @param queueSize 等待队列大小
|
* @param queueSize 等待队列大小
|
||||||
* @param discardingThreshold discardingThreshold,该参数仅对logback实现有效,log4j和log4j2无效
|
* @param discardingThreshold discardingThreshold,该参数仅对logback实现有效,log4j和log4j2无效
|
||||||
@ -150,11 +149,10 @@ public interface ActivateOption {
|
|||||||
void activateAsync(int queueSize, int discardingThreshold);
|
void activateAsync(int queueSize, int discardingThreshold);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 将当前logger对象的appender设置为异步Appender
|
* 将当前logger对象的appender设置为异步Appender 注意:此logger需要提前进行Appender的初始化
|
||||||
* 注意:此logger需要提前进行Appender的初始化
|
|
||||||
*
|
*
|
||||||
* @param args AsyncAppender配置参数,请自行保证参数的正确性,要求每个Object[]有3个元素,第一个为set方法名,第二个为方法类型数组,第三个为对应的参数值,如
|
* @param args AsyncAppender配置参数,请自行保证参数的正确性,要求每个Object[]有3个元素,第一个为set方法名,第二个为方法类型数组,第三个为对应的参数值,如 args.add(new
|
||||||
* args.add(new Object[] { "setBufferSize", new Class<?>[] { int.class }, queueSize });
|
* Object[] { "setBufferSize", new Class<?>[] { int.class }, queueSize });
|
||||||
* @since 0.2.3
|
* @since 0.2.3
|
||||||
*/
|
*/
|
||||||
void activateAsync(List<Object[]> args);
|
void activateAsync(List<Object[]> args);
|
||||||
@ -176,6 +174,7 @@ public interface ActivateOption {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取日志级别
|
* 获取日志级别
|
||||||
|
*
|
||||||
* @return level
|
* @return level
|
||||||
*/
|
*/
|
||||||
Level getLevel();
|
Level getLevel();
|
||||||
@ -189,6 +188,7 @@ public interface ActivateOption {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取所属的产品名
|
* 获取所属的产品名
|
||||||
|
*
|
||||||
* @return 所属的产品名
|
* @return 所属的产品名
|
||||||
*/
|
*/
|
||||||
String getProductName();
|
String getProductName();
|
||||||
|
@ -47,11 +47,12 @@ public class Log4j2ActivateOption extends AbstractActiveOption {
|
|||||||
public Log4j2ActivateOption(org.apache.logging.log4j.Logger logger) {
|
public Log4j2ActivateOption(org.apache.logging.log4j.Logger logger) {
|
||||||
if (logger != null) {
|
if (logger != null) {
|
||||||
if (logger instanceof org.apache.logging.log4j.core.Logger) {
|
if (logger instanceof org.apache.logging.log4j.core.Logger) {
|
||||||
this.logger = (org.apache.logging.log4j.core.Logger) logger;
|
this.logger = (org.apache.logging.log4j.core.Logger)logger;
|
||||||
|
|
||||||
configuration = this.logger.getContext().getConfiguration();
|
configuration = this.logger.getContext().getConfiguration();
|
||||||
} else {
|
} else {
|
||||||
throw new RuntimeException("logger must instanceof org.apache.logging.log4j.core.Logger, " + logger.getClass().getName());
|
throw new RuntimeException(
|
||||||
|
"logger must instanceof org.apache.logging.log4j.core.Logger, " + logger.getClass().getName());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -64,7 +65,8 @@ public class Log4j2ActivateOption extends AbstractActiveOption {
|
|||||||
.withCharset(Charset.forName(encoding))
|
.withCharset(Charset.forName(encoding))
|
||||||
.build();
|
.build();
|
||||||
org.apache.logging.log4j.core.appender.ConsoleAppender appender = ConsoleAppender.createAppender(layout, null,
|
org.apache.logging.log4j.core.appender.ConsoleAppender appender = ConsoleAppender.createAppender(layout, null,
|
||||||
ConsoleAppender.Target.valueOf(target.toUpperCase().replace(".", "_")), "LoggerApiConsoleAppender", false, false, true);
|
ConsoleAppender.Target.valueOf(target.toUpperCase().replace(".", "_")), "LoggerApiConsoleAppender", false,
|
||||||
|
false, true);
|
||||||
appender.start();
|
appender.start();
|
||||||
removeAllAppenders(logger);
|
removeAllAppenders(logger);
|
||||||
logger.addAppender(appender);
|
logger.addAppender(appender);
|
||||||
@ -100,7 +102,8 @@ public class Log4j2ActivateOption extends AbstractActiveOption {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void activateAsyncAppender(String productName, String file, String encoding, int queueSize, int discardingThreshold) {
|
public void activateAsyncAppender(String productName, String file, String encoding, int queueSize,
|
||||||
|
int discardingThreshold) {
|
||||||
activateAppender(productName, file, encoding);
|
activateAppender(productName, file, encoding);
|
||||||
activateAsync(queueSize, discardingThreshold);
|
activateAsync(queueSize, discardingThreshold);
|
||||||
}
|
}
|
||||||
@ -111,7 +114,8 @@ public class Log4j2ActivateOption extends AbstractActiveOption {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void activateAppenderWithTimeAndSizeRolling(String productName, String file, String encoding, String size, String datePattern) {
|
public void activateAppenderWithTimeAndSizeRolling(String productName, String file, String encoding, String size,
|
||||||
|
String datePattern) {
|
||||||
org.apache.logging.log4j.core.appender.RollingFileAppender appender = RollingFileAppender.newBuilder()
|
org.apache.logging.log4j.core.appender.RollingFileAppender appender = RollingFileAppender.newBuilder()
|
||||||
.withName(productName + "." + file.replace(File.separatorChar, '.') + ".Appender")
|
.withName(productName + "." + file.replace(File.separatorChar, '.') + ".Appender")
|
||||||
.withFileName(LoggerHelper.getLogFileP(productName, file))
|
.withFileName(LoggerHelper.getLogFileP(productName, file))
|
||||||
@ -121,7 +125,8 @@ public class Log4j2ActivateOption extends AbstractActiveOption {
|
|||||||
.withFilePattern(LoggerHelper.getLogFile(productName, file) + ".%d{" + datePattern + "}")
|
.withFilePattern(LoggerHelper.getLogFile(productName, file) + ".%d{" + datePattern + "}")
|
||||||
.withLayout(buildLayout(encoding))
|
.withLayout(buildLayout(encoding))
|
||||||
.withCreateOnDemand(false)
|
.withCreateOnDemand(false)
|
||||||
.withPolicy(CompositeTriggeringPolicy.createPolicy(TimeBasedTriggeringPolicy.createPolicy("1", "true"), SizeBasedTriggeringPolicy.createPolicy(size)))
|
.withPolicy(CompositeTriggeringPolicy.createPolicy(TimeBasedTriggeringPolicy.createPolicy("1", "true"),
|
||||||
|
SizeBasedTriggeringPolicy.createPolicy(size)))
|
||||||
.withStrategy(DefaultRolloverStrategy.createStrategy(null, null, "nomax", null, null, false, configuration))
|
.withStrategy(DefaultRolloverStrategy.createStrategy(null, null, "nomax", null, null, false, configuration))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
@ -133,7 +138,8 @@ public class Log4j2ActivateOption extends AbstractActiveOption {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void activateAppenderWithTimeAndSizeRolling(String productName, String file, String encoding, String size, String datePattern, int maxBackupIndex) {
|
public void activateAppenderWithTimeAndSizeRolling(String productName, String file, String encoding, String size,
|
||||||
|
String datePattern, int maxBackupIndex) {
|
||||||
org.apache.logging.log4j.core.appender.RollingFileAppender appender = RollingFileAppender.newBuilder()
|
org.apache.logging.log4j.core.appender.RollingFileAppender appender = RollingFileAppender.newBuilder()
|
||||||
.withName(productName + "." + file.replace(File.separatorChar, '.') + ".Appender")
|
.withName(productName + "." + file.replace(File.separatorChar, '.') + ".Appender")
|
||||||
.withFileName(LoggerHelper.getLogFileP(productName, file))
|
.withFileName(LoggerHelper.getLogFileP(productName, file))
|
||||||
@ -143,8 +149,10 @@ public class Log4j2ActivateOption extends AbstractActiveOption {
|
|||||||
.withFilePattern(LoggerHelper.getLogFile(productName, file) + ".%d{" + datePattern + "}.%i")
|
.withFilePattern(LoggerHelper.getLogFile(productName, file) + ".%d{" + datePattern + "}.%i")
|
||||||
.withLayout(buildLayout(encoding))
|
.withLayout(buildLayout(encoding))
|
||||||
.withCreateOnDemand(false)
|
.withCreateOnDemand(false)
|
||||||
.withPolicy(CompositeTriggeringPolicy.createPolicy(TimeBasedTriggeringPolicy.createPolicy("1", "true"), SizeBasedTriggeringPolicy.createPolicy(size)))
|
.withPolicy(CompositeTriggeringPolicy.createPolicy(TimeBasedTriggeringPolicy.createPolicy("1", "true"),
|
||||||
.withStrategy(DefaultRolloverStrategy.createStrategy(String.valueOf(maxBackupIndex), "1", "max", null, null, false, configuration))
|
SizeBasedTriggeringPolicy.createPolicy(size)))
|
||||||
|
.withStrategy(DefaultRolloverStrategy
|
||||||
|
.createStrategy(String.valueOf(maxBackupIndex), "1", "max", null, null, false, configuration))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
appender.start();
|
appender.start();
|
||||||
@ -155,7 +163,8 @@ public class Log4j2ActivateOption extends AbstractActiveOption {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void activateAppenderWithSizeRolling(String productName, String file, String encoding, String size, int maxBackupIndex) {
|
public void activateAppenderWithSizeRolling(String productName, String file, String encoding, String size,
|
||||||
|
int maxBackupIndex) {
|
||||||
org.apache.logging.log4j.core.appender.RollingFileAppender appender = RollingFileAppender.newBuilder()
|
org.apache.logging.log4j.core.appender.RollingFileAppender appender = RollingFileAppender.newBuilder()
|
||||||
.withName(productName + "." + file.replace(File.separatorChar, '.') + ".Appender")
|
.withName(productName + "." + file.replace(File.separatorChar, '.') + ".Appender")
|
||||||
.withFileName(LoggerHelper.getLogFileP(productName, file))
|
.withFileName(LoggerHelper.getLogFileP(productName, file))
|
||||||
@ -166,7 +175,8 @@ public class Log4j2ActivateOption extends AbstractActiveOption {
|
|||||||
.withLayout(buildLayout(encoding))
|
.withLayout(buildLayout(encoding))
|
||||||
.withCreateOnDemand(false)
|
.withCreateOnDemand(false)
|
||||||
.withPolicy(SizeBasedTriggeringPolicy.createPolicy(size))
|
.withPolicy(SizeBasedTriggeringPolicy.createPolicy(size))
|
||||||
.withStrategy(DefaultRolloverStrategy.createStrategy(String.valueOf(maxBackupIndex), "1", "max", null, null, false, configuration))
|
.withStrategy(DefaultRolloverStrategy
|
||||||
|
.createStrategy(String.valueOf(maxBackupIndex), "1", "max", null, null, false, configuration))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
appender.start();
|
appender.start();
|
||||||
@ -181,7 +191,7 @@ public class Log4j2ActivateOption extends AbstractActiveOption {
|
|||||||
List<Object[]> args = new ArrayList<Object[]>();
|
List<Object[]> args = new ArrayList<Object[]>();
|
||||||
|
|
||||||
if (queueSize != Integer.MIN_VALUE) {
|
if (queueSize != Integer.MIN_VALUE) {
|
||||||
args.add(new Object[] { "setBufferSize", new Class<?>[] { int.class }, queueSize });
|
args.add(new Object[] {"setBufferSize", new Class<?>[] {int.class}, queueSize});
|
||||||
}
|
}
|
||||||
activateAsync(args);
|
activateAsync(args);
|
||||||
}
|
}
|
||||||
@ -224,7 +234,7 @@ public class Log4j2ActivateOption extends AbstractActiveOption {
|
|||||||
+ logger.getDelegate().getClass());
|
+ logger.getDelegate().getClass());
|
||||||
}
|
}
|
||||||
|
|
||||||
activateAppender(((org.apache.logging.log4j.core.Logger) logger.getDelegate()));
|
activateAppender(((org.apache.logging.log4j.core.Logger)logger.getDelegate()));
|
||||||
|
|
||||||
setProductName(logger.getProductName());
|
setProductName(logger.getProductName());
|
||||||
}
|
}
|
||||||
@ -244,7 +254,8 @@ public class Log4j2ActivateOption extends AbstractActiveOption {
|
|||||||
public void setLevel(Level level) {
|
public void setLevel(Level level) {
|
||||||
this.level = level;
|
this.level = level;
|
||||||
|
|
||||||
org.apache.logging.log4j.Level l = org.apache.logging.log4j.Level.toLevel(level.getName(), org.apache.logging.log4j.Level.ERROR);
|
org.apache.logging.log4j.Level l = org.apache.logging.log4j.Level.toLevel(level.getName(),
|
||||||
|
org.apache.logging.log4j.Level.ERROR);
|
||||||
logger.setLevel(l);
|
logger.setLevel(l);
|
||||||
logger.getContext().getConfiguration().getLoggerConfig(this.logger.getName()).setLevel(l);
|
logger.getContext().getConfiguration().getLoggerConfig(this.logger.getName()).setLevel(l);
|
||||||
}
|
}
|
||||||
|
@ -39,14 +39,14 @@ import com.alibaba.nacos.client.logger.support.LoggerHelper;
|
|||||||
*
|
*
|
||||||
* @author zhuyong 2014年3月20日 上午11:16:26
|
* @author zhuyong 2014年3月20日 上午11:16:26
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
@SuppressWarnings({"rawtypes", "unchecked"})
|
||||||
public class Logback918ActivateOption extends AbstractActiveOption {
|
public class Logback918ActivateOption extends AbstractActiveOption {
|
||||||
|
|
||||||
private ch.qos.logback.classic.Logger logger;
|
private ch.qos.logback.classic.Logger logger;
|
||||||
|
|
||||||
public Logback918ActivateOption(Object logger) {
|
public Logback918ActivateOption(Object logger) {
|
||||||
if (logger instanceof ch.qos.logback.classic.Logger) {
|
if (logger instanceof ch.qos.logback.classic.Logger) {
|
||||||
this.logger = (ch.qos.logback.classic.Logger) logger;
|
this.logger = (ch.qos.logback.classic.Logger)logger;
|
||||||
} else {
|
} else {
|
||||||
throw new IllegalArgumentException("logger must be instanceof ch.qos.logback.classic.Logger");
|
throw new IllegalArgumentException("logger must be instanceof ch.qos.logback.classic.Logger");
|
||||||
}
|
}
|
||||||
@ -150,7 +150,8 @@ public class Logback918ActivateOption extends AbstractActiveOption {
|
|||||||
}
|
}
|
||||||
this.logger.detachAndStopAllAppenders();
|
this.logger.detachAndStopAllAppenders();
|
||||||
|
|
||||||
Iterator<ch.qos.logback.core.Appender<ILoggingEvent>> iter = ((ch.qos.logback.classic.Logger) logger.getDelegate()).iteratorForAppenders();
|
Iterator<ch.qos.logback.core.Appender<ILoggingEvent>> iter = ((ch.qos.logback.classic.Logger)logger
|
||||||
|
.getDelegate()).iteratorForAppenders();
|
||||||
while (iter.hasNext()) {
|
while (iter.hasNext()) {
|
||||||
ch.qos.logback.core.Appender<ILoggingEvent> appender = iter.next();
|
ch.qos.logback.core.Appender<ILoggingEvent> appender = iter.next();
|
||||||
this.logger.addAppender(appender);
|
this.logger.addAppender(appender);
|
||||||
@ -235,11 +236,11 @@ public class Logback918ActivateOption extends AbstractActiveOption {
|
|||||||
List<Object[]> args = new ArrayList<Object[]>();
|
List<Object[]> args = new ArrayList<Object[]>();
|
||||||
|
|
||||||
if (queueSize != Integer.MIN_VALUE) {
|
if (queueSize != Integer.MIN_VALUE) {
|
||||||
args.add(new Object[] { "setQueueSize", new Class<?>[] { int.class }, queueSize });
|
args.add(new Object[] {"setQueueSize", new Class<?>[] {int.class}, queueSize});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (discardingThreshold != Integer.MIN_VALUE) {
|
if (discardingThreshold != Integer.MIN_VALUE) {
|
||||||
args.add(new Object[] { "setDiscardingThreshold", new Class<?>[] { int.class }, discardingThreshold });
|
args.add(new Object[] {"setDiscardingThreshold", new Class<?>[] {int.class}, discardingThreshold});
|
||||||
}
|
}
|
||||||
|
|
||||||
activateAsync(args);
|
activateAsync(args);
|
||||||
|
@ -32,7 +32,7 @@ import ch.qos.logback.core.rolling.TimeBasedRollingPolicy;
|
|||||||
*
|
*
|
||||||
* @author zhuyong 2014年3月20日 上午10:24:58
|
* @author zhuyong 2014年3月20日 上午10:24:58
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
@SuppressWarnings({"rawtypes", "unchecked"})
|
||||||
public class LogbackActivateOption extends Logback918ActivateOption {
|
public class LogbackActivateOption extends Logback918ActivateOption {
|
||||||
|
|
||||||
public LogbackActivateOption(Object logger) {
|
public LogbackActivateOption(Object logger) {
|
||||||
|
@ -20,10 +20,11 @@ import org.slf4j.LoggerFactory;
|
|||||||
|
|
||||||
import ch.qos.logback.classic.LoggerContext;
|
import ch.qos.logback.classic.LoggerContext;
|
||||||
import ch.qos.logback.core.LogbackException;
|
import ch.qos.logback.core.LogbackException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Logback Context Util
|
* Logback Context Util
|
||||||
* @author Nacos
|
|
||||||
*
|
*
|
||||||
|
* @author Nacos
|
||||||
*/
|
*/
|
||||||
public class LogbackLoggerContextUtil {
|
public class LogbackLoggerContextUtil {
|
||||||
|
|
||||||
@ -39,7 +40,7 @@ public class LogbackLoggerContextUtil {
|
|||||||
+ lcObject.getClass().getSimpleName());
|
+ lcObject.getClass().getSimpleName());
|
||||||
}
|
}
|
||||||
|
|
||||||
loggerContext = (LoggerContext) lcObject;
|
loggerContext = (LoggerContext)lcObject;
|
||||||
}
|
}
|
||||||
|
|
||||||
return loggerContext;
|
return loggerContext;
|
||||||
|
@ -41,7 +41,8 @@ public class Slf4jLog4j2AdapterActivateOption extends Log4j2ActivateOption {
|
|||||||
super(null);
|
super(null);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
org.apache.logging.log4j.core.Logger log4j2Logger = (org.apache.logging.log4j.core.Logger) loggerField.get(logger);
|
org.apache.logging.log4j.core.Logger log4j2Logger = (org.apache.logging.log4j.core.Logger)loggerField.get(
|
||||||
|
logger);
|
||||||
super.logger = log4j2Logger;
|
super.logger = log4j2Logger;
|
||||||
super.configuration = super.logger.getContext().getConfiguration();
|
super.configuration = super.logger.getContext().getConfiguration();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
@ -59,7 +60,8 @@ public class Slf4jLog4j2AdapterActivateOption extends Log4j2ActivateOption {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
org.apache.logging.log4j.core.Logger log4j2Logger = (org.apache.logging.log4j.core.Logger) loggerField.get(logger.getDelegate());
|
org.apache.logging.log4j.core.Logger log4j2Logger = (org.apache.logging.log4j.core.Logger)loggerField.get(
|
||||||
|
logger.getDelegate());
|
||||||
super.activateAppender(log4j2Logger);
|
super.activateAppender(log4j2Logger);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
throw new RuntimeException("activateAppender error, ", e);
|
throw new RuntimeException("activateAppender error, ", e);
|
||||||
|
@ -66,7 +66,7 @@ public class Slf4jLogger extends LoggerSupport implements Logger {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
Class<ActivateOption> clazz = (Class<ActivateOption>) Class.forName(activateOptionClass);
|
Class<ActivateOption> clazz = (Class<ActivateOption>)Class.forName(activateOptionClass);
|
||||||
Constructor<ActivateOption> c = clazz.getConstructor(Object.class);
|
Constructor<ActivateOption> c = clazz.getConstructor(Object.class);
|
||||||
this.activateOption = c.newInstance(delegate);
|
this.activateOption = c.newInstance(delegate);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
|
@ -15,15 +15,15 @@
|
|||||||
*/
|
*/
|
||||||
package com.alibaba.nacos.client.logger.slf4j;
|
package com.alibaba.nacos.client.logger.slf4j;
|
||||||
|
|
||||||
|
|
||||||
import com.alibaba.nacos.client.logger.Logger;
|
import com.alibaba.nacos.client.logger.Logger;
|
||||||
import com.alibaba.nacos.client.logger.nop.NopLogger;
|
import com.alibaba.nacos.client.logger.nop.NopLogger;
|
||||||
import com.alibaba.nacos.client.logger.support.ILoggerFactory;
|
import com.alibaba.nacos.client.logger.support.ILoggerFactory;
|
||||||
import com.alibaba.nacos.client.logger.support.LogLog;
|
import com.alibaba.nacos.client.logger.support.LogLog;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Slf4jLogger Factory
|
* Slf4jLogger Factory
|
||||||
* @author Nacos
|
|
||||||
*
|
*
|
||||||
|
* @author Nacos
|
||||||
*/
|
*/
|
||||||
public class Slf4jLoggerFactory implements ILoggerFactory {
|
public class Slf4jLoggerFactory implements ILoggerFactory {
|
||||||
|
|
||||||
|
@ -27,7 +27,7 @@ public class AppenderInfo extends HashMap {
|
|||||||
private static String file = "file";
|
private static String file = "file";
|
||||||
|
|
||||||
public String getName() {
|
public String getName() {
|
||||||
return (String) get(AppenderInfo.name);
|
return (String)get(AppenderInfo.name);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setName(String name) {
|
public void setName(String name) {
|
||||||
|
@ -21,14 +21,12 @@ import com.alibaba.nacos.client.logger.Logger;
|
|||||||
* logger factory interface
|
* logger factory interface
|
||||||
*
|
*
|
||||||
* @author Nacos
|
* @author Nacos
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public interface ILoggerFactory {
|
public interface ILoggerFactory {
|
||||||
/**
|
/**
|
||||||
* get logger
|
* get logger
|
||||||
*
|
*
|
||||||
* @param clazz
|
* @param clazz class
|
||||||
* class
|
|
||||||
* @return logger
|
* @return logger
|
||||||
*/
|
*/
|
||||||
Logger getLogger(Class<?> clazz);
|
Logger getLogger(Class<?> clazz);
|
||||||
@ -36,8 +34,7 @@ public interface ILoggerFactory {
|
|||||||
/**
|
/**
|
||||||
* get logger
|
* get logger
|
||||||
*
|
*
|
||||||
* @param name
|
* @param name logger name
|
||||||
* logger name
|
|
||||||
* @return logger
|
* @return logger
|
||||||
*/
|
*/
|
||||||
Logger getLogger(String name);
|
Logger getLogger(String name);
|
||||||
|
@ -33,10 +33,11 @@ package com.alibaba.nacos.client.logger.support;
|
|||||||
|
|
||||||
import java.io.PrintStream;
|
import java.io.PrintStream;
|
||||||
import java.util.Calendar;
|
import java.util.Calendar;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* logger log
|
* logger log
|
||||||
* @author Nacos
|
|
||||||
*
|
*
|
||||||
|
* @author Nacos
|
||||||
*/
|
*/
|
||||||
public class LogLog {
|
public class LogLog {
|
||||||
|
|
||||||
|
@ -60,7 +60,9 @@ public class LogbackHelper {
|
|||||||
ILoggerFactory lc = org.slf4j.LoggerFactory.getILoggerFactory();
|
ILoggerFactory lc = org.slf4j.LoggerFactory.getILoggerFactory();
|
||||||
|
|
||||||
if (!(lc instanceof LoggerContext)) {
|
if (!(lc instanceof LoggerContext)) {
|
||||||
LogLog.warn("expected logback binding with SLF4J, but another log system has taken the place: " + lcObject.getClass().getSimpleName());
|
LogLog.warn(
|
||||||
|
"expected logback binding with SLF4J, but another log system has taken the place: " + lcObject
|
||||||
|
.getClass().getSimpleName());
|
||||||
} else {
|
} else {
|
||||||
lcObject = lc;
|
lcObject = lc;
|
||||||
|
|
||||||
@ -77,6 +79,7 @@ public class LogbackHelper {
|
|||||||
LogLog.error("failed to init LogbackHelper, " + t.getMessage());
|
LogLog.error("failed to init LogbackHelper, " + t.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressFBWarnings("NP_BOOLEAN_RETURN_NULL")
|
@SuppressFBWarnings("NP_BOOLEAN_RETURN_NULL")
|
||||||
public static Boolean setDepth(int depth) {
|
public static Boolean setDepth(int depth) {
|
||||||
if (Logback) {
|
if (Logback) {
|
||||||
@ -84,7 +87,7 @@ public class LogbackHelper {
|
|||||||
depth = Integer.MAX_VALUE;
|
depth = Integer.MAX_VALUE;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
LoggerContext loggerContext = (LoggerContext) lcObject;
|
LoggerContext loggerContext = (LoggerContext)lcObject;
|
||||||
|
|
||||||
List<Logger> loggers = loggerContext.getLoggerList();
|
List<Logger> loggers = loggerContext.getLoggerList();
|
||||||
for (ch.qos.logback.classic.Logger logger : loggers) {
|
for (ch.qos.logback.classic.Logger logger : loggers) {
|
||||||
@ -100,12 +103,13 @@ public class LogbackHelper {
|
|||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressFBWarnings("NP_BOOLEAN_RETURN_NULL")
|
@SuppressFBWarnings("NP_BOOLEAN_RETURN_NULL")
|
||||||
public static Boolean changeLevel(String name, String level) {
|
public static Boolean changeLevel(String name, String level) {
|
||||||
if (Logback) {
|
if (Logback) {
|
||||||
try {
|
try {
|
||||||
Level l = Level.toLevel(level, Level.ERROR);
|
Level l = Level.toLevel(level, Level.ERROR);
|
||||||
LoggerContext loggerContext = (LoggerContext) lcObject;
|
LoggerContext loggerContext = (LoggerContext)lcObject;
|
||||||
|
|
||||||
Logger logger = loggerContext.exists(name);
|
Logger logger = loggerContext.exists(name);
|
||||||
if (logger != null) {
|
if (logger != null) {
|
||||||
@ -126,7 +130,7 @@ public class LogbackHelper {
|
|||||||
Map<String, LoggerInfo> appenders = new HashMap<String, LoggerInfo>(10);
|
Map<String, LoggerInfo> appenders = new HashMap<String, LoggerInfo>(10);
|
||||||
|
|
||||||
if (Logback) {
|
if (Logback) {
|
||||||
LoggerContext loggerContext = (LoggerContext) lcObject;
|
LoggerContext loggerContext = (LoggerContext)lcObject;
|
||||||
if (name != null && !"".equals(name.trim())) {
|
if (name != null && !"".equals(name.trim())) {
|
||||||
Logger logger = loggerContext.exists(name);
|
Logger logger = loggerContext.exists(name);
|
||||||
if (logger != null) {
|
if (logger != null) {
|
||||||
@ -152,20 +156,20 @@ public class LogbackHelper {
|
|||||||
while (iter.hasNext()) {
|
while (iter.hasNext()) {
|
||||||
Appender<ILoggingEvent> a = iter.next();
|
Appender<ILoggingEvent> a = iter.next();
|
||||||
if (a instanceof AsyncAppenderBase) {
|
if (a instanceof AsyncAppenderBase) {
|
||||||
Iterator<Appender<ILoggingEvent>> aiter = ((AsyncAppenderBase) a).iteratorForAppenders();
|
Iterator<Appender<ILoggingEvent>> aiter = ((AsyncAppenderBase)a).iteratorForAppenders();
|
||||||
doSetDepth(aiter, depth);
|
doSetDepth(aiter, depth);
|
||||||
} else if (a instanceof OutputStreamAppender) {
|
} else if (a instanceof OutputStreamAppender) {
|
||||||
OutputStreamAppender oa = (OutputStreamAppender) a;
|
OutputStreamAppender oa = (OutputStreamAppender)a;
|
||||||
Encoder e = oa.getEncoder();
|
Encoder e = oa.getEncoder();
|
||||||
Layout l = null;
|
Layout l = null;
|
||||||
if (e instanceof PatternLayoutEncoder) {
|
if (e instanceof PatternLayoutEncoder) {
|
||||||
l = ((PatternLayoutEncoder) e).getLayout();
|
l = ((PatternLayoutEncoder)e).getLayout();
|
||||||
} else if (e instanceof LayoutWrappingEncoder) {
|
} else if (e instanceof LayoutWrappingEncoder) {
|
||||||
l = ((LayoutWrappingEncoder) e).getLayout();
|
l = ((LayoutWrappingEncoder)e).getLayout();
|
||||||
}
|
}
|
||||||
if (l != null) {
|
if (l != null) {
|
||||||
if (l instanceof PatternLayoutBase) {
|
if (l instanceof PatternLayoutBase) {
|
||||||
Converter c = (Converter) f.get(l);
|
Converter c = (Converter)f.get(l);
|
||||||
while (c != null) {
|
while (c != null) {
|
||||||
if (c instanceof ThrowableProxyConverter) {
|
if (c instanceof ThrowableProxyConverter) {
|
||||||
f1.set(c, depth);
|
f1.set(c, depth);
|
||||||
@ -203,9 +207,9 @@ public class LogbackHelper {
|
|||||||
info.setName(appender.getName());
|
info.setName(appender.getName());
|
||||||
info.setType(appender.getClass().getName());
|
info.setType(appender.getClass().getName());
|
||||||
if (appender instanceof FileAppender) {
|
if (appender instanceof FileAppender) {
|
||||||
info.setFile(((FileAppender) appender).getFile());
|
info.setFile(((FileAppender)appender).getFile());
|
||||||
} else if (appender instanceof AsyncAppender) {
|
} else if (appender instanceof AsyncAppender) {
|
||||||
AsyncAppender aa = (AsyncAppender) appender;
|
AsyncAppender aa = (AsyncAppender)appender;
|
||||||
Iterator<Appender<ILoggingEvent>> iter = aa.iteratorForAppenders();
|
Iterator<Appender<ILoggingEvent>> iter = aa.iteratorForAppenders();
|
||||||
List<AppenderInfo> asyncs = doGetLoggerAppenders(iter);
|
List<AppenderInfo> asyncs = doGetLoggerAppenders(iter);
|
||||||
// 标明异步appender
|
// 标明异步appender
|
||||||
@ -216,7 +220,7 @@ public class LogbackHelper {
|
|||||||
}
|
}
|
||||||
info.withDetail("nestedNames", nestedNames);
|
info.withDetail("nestedNames", nestedNames);
|
||||||
} else if (appender instanceof ConsoleAppender) {
|
} else if (appender instanceof ConsoleAppender) {
|
||||||
info.withDetail("target", ((ConsoleAppender) appender).getTarget());
|
info.withDetail("target", ((ConsoleAppender)appender).getTarget());
|
||||||
}
|
}
|
||||||
result.add(info);
|
result.add(info);
|
||||||
}
|
}
|
||||||
|
@ -31,8 +31,8 @@ import com.alibaba.nacos.client.logger.Logger;
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* logger help
|
* logger help
|
||||||
* @author Nacos
|
|
||||||
*
|
*
|
||||||
|
* @author Nacos
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("PMD.AbstractClassShouldStartWithAbstractNamingRule")
|
@SuppressWarnings("PMD.AbstractClassShouldStartWithAbstractNamingRule")
|
||||||
public abstract class LoggerHelper {
|
public abstract class LoggerHelper {
|
||||||
@ -55,7 +55,7 @@ public abstract class LoggerHelper {
|
|||||||
LOG_PATH = defaultPath + File.separator + "logs" + File.separator;
|
LOG_PATH = defaultPath + File.separator + "logs" + File.separator;
|
||||||
} else {
|
} else {
|
||||||
if (!new File(dpath).isAbsolute()) {
|
if (!new File(dpath).isAbsolute()) {
|
||||||
// throw new RuntimeException("-DJM.LOG.PATH must be an absolute path.");
|
// throw new RuntimeException("-DJM.LOG.PATH must be an absolute path.");
|
||||||
String defaultPath = System.getProperty("user.home");
|
String defaultPath = System.getProperty("user.home");
|
||||||
dpath = defaultPath + File.separator + dpath;
|
dpath = defaultPath + File.separator + dpath;
|
||||||
}
|
}
|
||||||
@ -214,7 +214,7 @@ public abstract class LoggerHelper {
|
|||||||
return sb.toString();
|
return sb.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressFBWarnings(value = { "RV_RETURN_VALUE_IGNORED_BAD_PRACTICE" })
|
@SuppressFBWarnings(value = {"RV_RETURN_VALUE_IGNORED_BAD_PRACTICE"})
|
||||||
public static String getLogFileP(String productName, String fileName) {
|
public static String getLogFileP(String productName, String fileName) {
|
||||||
String file = getLogFile(productName, fileName);
|
String file = getLogFile(productName, fileName);
|
||||||
File logfile = new File(file);
|
File logfile = new File(file);
|
||||||
@ -223,9 +223,8 @@ public abstract class LoggerHelper {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* When prudent is set to true, file appenders from multiple JVMs can safely
|
* When prudent is set to true, file appenders from multiple JVMs can safely write to the same file.
|
||||||
* write to the same file.
|
* <p>
|
||||||
*
|
|
||||||
* Only support by logback
|
* Only support by logback
|
||||||
*
|
*
|
||||||
* @param prudent
|
* @param prudent
|
||||||
@ -238,11 +237,12 @@ public abstract class LoggerHelper {
|
|||||||
+ logger.getDelegate().getClass());
|
+ logger.getDelegate().getClass());
|
||||||
}
|
}
|
||||||
|
|
||||||
Iterator<Appender<ILoggingEvent>> iter = ((ch.qos.logback.classic.Logger) logger.getDelegate()).iteratorForAppenders();
|
Iterator<Appender<ILoggingEvent>> iter = ((ch.qos.logback.classic.Logger)logger.getDelegate())
|
||||||
|
.iteratorForAppenders();
|
||||||
while (iter.hasNext()) {
|
while (iter.hasNext()) {
|
||||||
ch.qos.logback.core.Appender<ILoggingEvent> appender = iter.next();
|
ch.qos.logback.core.Appender<ILoggingEvent> appender = iter.next();
|
||||||
if (appender instanceof FileAppender) {
|
if (appender instanceof FileAppender) {
|
||||||
((FileAppender) appender).setPrudent(prudent);
|
((FileAppender)appender).setPrudent(prudent);
|
||||||
} else {
|
} else {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
@ -41,11 +41,11 @@ public class LoggerInfo extends HashMap {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public String getLevel() {
|
public String getLevel() {
|
||||||
return (String) get(level);
|
return (String)get(level);
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<AppenderInfo> getAppenders() {
|
public List<AppenderInfo> getAppenders() {
|
||||||
return (List<AppenderInfo>) get(appenders);
|
return (List<AppenderInfo>)get(appenders);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setAppenders(List<AppenderInfo> appenders) {
|
public void setAppenders(List<AppenderInfo> appenders) {
|
||||||
|
@ -21,10 +21,11 @@ import java.util.Map;
|
|||||||
import com.alibaba.nacos.client.logger.Level;
|
import com.alibaba.nacos.client.logger.Level;
|
||||||
import com.alibaba.nacos.client.logger.Logger;
|
import com.alibaba.nacos.client.logger.Logger;
|
||||||
import com.alibaba.nacos.client.logger.option.ActivateOption;
|
import com.alibaba.nacos.client.logger.option.ActivateOption;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Logger Support
|
* Logger Support
|
||||||
* @author Nacos
|
|
||||||
*
|
*
|
||||||
|
* @author Nacos
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("PMD.AbstractClassShouldStartWithAbstractNamingRule")
|
@SuppressWarnings("PMD.AbstractClassShouldStartWithAbstractNamingRule")
|
||||||
public abstract class LoggerSupport implements Logger {
|
public abstract class LoggerSupport implements Logger {
|
||||||
@ -137,7 +138,8 @@ public abstract class LoggerSupport implements Logger {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void activateAsyncAppender(String productName, String file, String encoding, int queueSize, int discardingThreshold) {
|
public void activateAsyncAppender(String productName, String file, String encoding, int queueSize,
|
||||||
|
int discardingThreshold) {
|
||||||
if (activateOption != null) {
|
if (activateOption != null) {
|
||||||
activateOption.activateAsyncAppender(productName, file, encoding, queueSize, discardingThreshold);
|
activateOption.activateAsyncAppender(productName, file, encoding, queueSize, discardingThreshold);
|
||||||
}
|
}
|
||||||
|
@ -22,7 +22,6 @@ package com.alibaba.nacos.client.logger.util;
|
|||||||
*/
|
*/
|
||||||
public class FormattingTuple {
|
public class FormattingTuple {
|
||||||
|
|
||||||
|
|
||||||
static public FormattingTuple NULL = new FormattingTuple(null);
|
static public FormattingTuple NULL = new FormattingTuple(null);
|
||||||
|
|
||||||
private String message;
|
private String message;
|
||||||
@ -36,7 +35,7 @@ public class FormattingTuple {
|
|||||||
public FormattingTuple(String message, Object[] argArray, Throwable throwable) {
|
public FormattingTuple(String message, Object[] argArray, Throwable throwable) {
|
||||||
this.message = message;
|
this.message = message;
|
||||||
this.throwable = throwable;
|
this.throwable = throwable;
|
||||||
if(throwable == null) {
|
if (throwable == null) {
|
||||||
this.argArray = argArray.clone();
|
this.argArray = argArray.clone();
|
||||||
} else {
|
} else {
|
||||||
this.argArray = trimmedCopy(argArray);
|
this.argArray = trimmedCopy(argArray);
|
||||||
@ -44,10 +43,10 @@ public class FormattingTuple {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static Object[] trimmedCopy(Object[] argArray) {
|
static Object[] trimmedCopy(Object[] argArray) {
|
||||||
if(argArray == null || argArray.length == 0) {
|
if (argArray == null || argArray.length == 0) {
|
||||||
throw new IllegalStateException("non-sensical empty or null argument array");
|
throw new IllegalStateException("non-sensical empty or null argument array");
|
||||||
}
|
}
|
||||||
final int trimemdLen = argArray.length -1;
|
final int trimemdLen = argArray.length - 1;
|
||||||
Object[] trimmed = new Object[trimemdLen];
|
Object[] trimmed = new Object[trimemdLen];
|
||||||
System.arraycopy(argArray, 0, trimmed, 0, trimemdLen);
|
System.arraycopy(argArray, 0, trimmed, 0, trimemdLen);
|
||||||
return trimmed;
|
return trimmed;
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user