All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.javaclub.Constants Maven / Gradle / Ivy

/*
 * @(#)Consts.java	2011-6-17
 *
 * Copyright (c) 2011. All Rights Reserved.
 *
 */

package com.github.javaclub;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;

import org.slf4j.MDC;

import com.github.javaclub.toolbox.ToolBox.ClassPath;
import com.github.javaclub.toolbox.ToolBox.IO;
import com.github.javaclub.toolbox.ToolBox.Maps;
import com.github.javaclub.toolbox.ToolBox.Numbers;
import com.github.javaclub.toolbox.ToolBox.Strings;
import com.github.javaclub.toolbox.ToolBox.Systems;
import com.github.javaclub.toolbox.ToolBox.UUID;
import com.github.javaclub.toolbox.ToolBox.Web;
import com.github.javaclub.toolbox.conf.CompositeAppConfigProperties;
import com.github.javaclub.toolbox.output.StringBuilderWriter;

/**
 * Collected constants of general utility.
 * 
 * @author Gerald Chen
 * @version $Id: Constants.java 56 2011-06-27 02:11:24Z [email protected] $
 */
public interface Constants {

	public class Environments {
		
		/** 
		 * the newline character,it is "\r\n" in windows,and "\n" in linux 
		 */
		public static final String LINE_SEPARATER = getPlatformLineSeparator();

		/** File.separator */
		public static final String FILE_SEPARATER = File.separator;
		
		/** System property - path.separator */
		public static final String PATH_SEPARATOR = System.getProperty("path.separator");

		/** the temp file directory in os */
		public static final String SYS_TMP_DIR = System.getProperty("java.io.tmpdir");

		/** the user home directory */
		public static final String USER_HOME_DIR = System.getProperty("user.home");

		/** os name */
		public static final String OS_NAME = System.getProperty("os.name");
		
		/** the username of os */
		public static final String USER_NAME = System.getProperty("user.name");
		
		/** jdk varsion */
		public static final String JAVA_VERSION = System.getProperty("java.version");

		/** is linux os */
		public static final boolean LINUX = OS_NAME.startsWith("Linux");

		/** is windows os */
		public static final boolean WINDOWS = OS_NAME.startsWith("Windows");

		/** True if running on SunOS. */
		public static final boolean SUN_OS = OS_NAME.startsWith("SunOS");

		/** True if this is Java version 1.3. */
		public static final boolean JAVA_1_3 = JAVA_VERSION.startsWith("1.3.");

		/** True if this is Java version 1.4. */
		public static final boolean JAVA_1_4 = JAVA_VERSION.startsWith("1.4.");

		/** True if this is Java version 1.5. */
		public static final boolean JAVA_1_5 = JAVA_VERSION.startsWith("1.5.");

		/** True if this is Java version 1.6. */
		public static final boolean JAVA_1_6 = JAVA_VERSION.startsWith("1.6.");
		
		/**
		 * 核心数 
		 */
		public static final int CORE_NUM = Runtime.getRuntime().availableProcessors();
		
		public static String getPlatformLineSeparator() {
			String separator = null;
	        PrintWriter out = null;
			try {
				// avoid security issues
				final StringBuilderWriter buf = new StringBuilderWriter(4);
				out = new PrintWriter(buf);
				out.println();
				separator = buf.toString();
			} catch (Exception e) {
			} finally {
				if (null == separator) {
					separator = Systems.getSystemProperty("line.separator", "\r\n");
				}
				IO.closeQuietly(out);
			}
			return separator;
		}
		
	}
	
	public class JarPomProperties {
		
		public static Properties getJarPomProperties(String groupId, String artifactId) throws IOException {
			String mavenPomFile = Strings.format("META-INF/maven/{}/{}/pom.properties", groupId, artifactId);
			return ClassPath.readConfigFile(mavenPomFile, null);
		}
		
	}
	
	
	public class SepChars {
		
		public static final String EMPTY = "";
		
		public static final String AT = "@";
		public static final String SLASH = "/";
		public static final String PLAINT = "!";
		public static final String HASH = "#";
		public static final String HAT = "^";
		public static final String DOLLAR = "$";
		public static final String RMB = "¥";
		public static final String DOT = ".";
		public static final String STAR = "*";
		
		public static final String BACKTICK = "`";
		public static final String TILDA = "~";
		
		public static final String PERCENT = "%";
		public static final String PIPE = "|";
		public static final String PLUS = "+";
		public static final String MINUS = "-";
		
		public static final String COMMA = ",";
		public static final String COLON = ":";
		public static final String SEMICOLON = ";";
		
		public static final String L_BRACKET = "(";
		public static final String R_BRACKET = ")";
		public static final String L_BG_BRACKET = "{";
		public static final String R_BG_BRACKET = "}";
		public static final String L_SQ_BRACKET = "[";
		public static final String R_SQ_BRACKET = "]";
		
		public static final char PACKAGE_SEPARATOR = '.';
		public static final char INNER_CLASS_SEPARATOR = '$';
		
		public static final String EQ = "=";
		public static final String LT = "<";
		public static final String LT_EQ = "<=";
		public static final String GT = ">";
		public static final String GT_EQ = ">=";
		
		public static final String LEFT_ARROW = "<";
		public static final String RIGHT_ARROW = ">";
		
		public static final String L_EQ_ARROW = "<=";
		public static final String L_MINUS_ARROW = "<-";
		
		public static final String R_EQ_ARROW = "=>";
		public static final String R_MINUS_ARROW = "->";
		
		public static final String EQUIV = "<=>";
		
		public static final String DOUBLE_COLON = "::";
		
		public static final String NEWLINE = Environments.LINE_SEPARATER;
		public static final String CRLF = "\r\n";
		
		public static final String ONE = "1";
		public static final String ZERO = "0";
		public static final String DOLLAR_LEFT_BRACE = "${";
		public static final String HASH_LEFT_BRACE = "#{";
		
		public static final String ARRAY_SUFFIX = "[]";
		public static final String INTERNAL_ARRAY_PREFIX = "[L";
		
		// XxxClass$$EnhancerBySpringCGLIB$$ede45cbc | XxxClass$$EnhancerByCGLIB$$e6f193aa | 
		public static final String CGLIB_CLASS_SEPARATOR = "$$"; // The CGLIB class separator: {@code "$$"}. 
		public static final String CLASS_FILE_SUFFIX = ".class"; // The ".class" file suffix. 
		
		public static final String PROXY_CLASS_SEP = "$$EnhancerBy";
		
		public static final String DOT_2 = "..";
		public static final String DOT_3 = "...";
		public static final String DOT_6 = "......";
		
		public static final String SPACE = " ";
		public static final String SPACE_2 = "  ";
		public static final String SPACE_3 = "   ";
		public static final String SPACE_4 = "    ";
		public static final String SPACE_8 = "        ";
		
		public static final String UNDER_LINE = "_";
		public static final String UNDER_LINE_2 = "__";
		public static final String UNDER_LINE_3 = "___";
		public static final String UNDER_LINE_4 = "____";
		public static final String UNDER_LINE_5 = "_____";
		public static final String UNDER_LINE_6 = "______";
		
		public static final String TAB = "\t";
		public static final String TAB_2 = "\t\t";
		public static final String SINGLE_QUOTE = "'";
		public static final String DOUBLE_QUOTE = "\"";
		
		public static final String JATJ = "#@#";

		public static final String HTML_NBSP = " ";
		public static final String HTML_AMP = "&";
		public static final String HTML_QUOTE = """;
		public static final String HTML_LT = "<";
		public static final String HTML_GT = ">";
		
		public static final String CHAR_BEFROE_EX_AT = Strings.fromCodePoint(9);
		
		public static String newLine(int count) {
			StringBuilder sbf = new StringBuilder();
			for (int i = 0; i < count; i++) {
				sbf.append(Environments.LINE_SEPARATER);
			}
			return sbf.toString();
		}
		
	}
	
	public class EncodingCharsets {
		
		/** the prefered encoding */
		public static final String PREFERED_ENCODING = "UTF-8";

		/** encoding: UTF-8 */
		public static final String ENCODING_UTF8 = "UTF-8";

		/** encoding: ISO-8859-1 */
		public static final String ENCODING_ISO8859_1 = "ISO-8859-1";

		/** encoding: GBK */
		public static final String ENCODING_GBK = "GBK";
		
	}
	
	public class Charsets {
		
		public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1");
	    public static final Charset US_ASCII = Charset.forName("US-ASCII");
	    public static final Charset UTF_16 = Charset.forName("UTF-16");
	    public static final Charset UTF_16BE = Charset.forName("UTF-16BE");
	    public static final Charset UTF_16LE = Charset.forName("UTF-16LE");
	    public static final Charset UTF_8 = Charset.forName("UTF-8");

		public static Charset toCharset(Charset charset) {
	        return charset == null ? Charset.defaultCharset() : charset;
	    }

	    public static Charset toCharset(String charset) {
	        return charset == null ? Charset.defaultCharset() : Charset.forName(charset);
	    }
	    
	}
	
	public class AppDefaultConfig {
		
		public static final int THREAD_POOL_INIT_QUEQUE_CAPACITY = 6000;
		
		public static final int GEN_ID_COUNT_BITS = 32; // 生成ID的末尾 序列号的位数
		public static final long GEN_ID_START_TIMESTAMP = 1693232338L; // 2023-08-28 22:18:58
		public static final long GEN_ID_STEP = 10L;
		
		public static final String COMPONENT_BEAN_THREAD_TASK_EXECUTOR = "internalThreadTaskExecutor";
		public static final String COMPONENT_BEAN_ALARM_MONITOR = "internalAlarmMonitor";
		
		public static final String REDIS_STORE_SUBSCRIBER_EXECUTOR = "JedisSubscriberExecutor";
		
		public static final String ENV_KEY_APP_START_TIME = "java.app.startTime";
		public static final String ENV_KEY_APP_STOP_TIME = "java.app.stopTime";
		public static final String ENV_KEY_APP_MACHINES = "java.app.machines";
		
		public static final String ENV_KEY_CONFIGSERVER_NODES = "configserver.nodes";
		
		public static final String AOP_ANNO_EXPR_TESTMOCK = "@annotation(com.github.javaclub.sword.annotation.TestMock)";
		
	}
	
	public class Contexts {
		
		public static final String TRACE_ID = "traceId";
		public static final String TRACE_KEY = "distributed.trace.key";
		
		public static final String CURRENT_OPERATOR = "currentOperator"; // 标记当前操作人
		public static final String CURRENT_INVOKE_START = "currentInvokeStart"; // 当前请求开始时间
		public static final String CURRENT_CLIENT_IP = "__clientRequestIp";
		
		public static final String CTX_REQ_PATH = "_ctx_req_path_";
		
		public static final String GUEST_READONLY = "readonlyFlag"; // 是否只读模式
		
		public static final String getTraceKey() {
			String key = CompositeAppConfigProperties.getInstance().getValue(TRACE_KEY);
			return Strings.noneBlank(key, TRACE_ID);
		}
		
		public static String currentTraceId() {
			final String traceKey = getTraceKey();
			String traceId = MDC.get(traceKey);
			if (Strings.isBlank(traceId) || 5 >= traceId.length()) {
				traceId = UUID.randomUUID();
				MDC.put(traceKey, traceId);
			}
			return traceId;
		}
		
		public static String currentClientIP() {
			return MDC.get(CURRENT_CLIENT_IP);
		}
		
		public static void setCurrentOperator(Object operator) {
			if (null != operator) {
				String value = Objects.toString(operator);
				MDC.put(CURRENT_OPERATOR, value);
			}
		}
		
		public static void setCurrentInvokeStart() {
			MDC.put(CURRENT_INVOKE_START, String.valueOf(System.currentTimeMillis()));
		}
		
		public static void setCurrentClientRequestIp() {
			MDC.put(CURRENT_CLIENT_IP, Web.requestClientIpAddr());
		}
		
		public static void setReadonly() {
			set(GUEST_READONLY, "true");
		}
		
		public static void clearCurrentInvokeStart() {
			MDC.remove(CURRENT_INVOKE_START);
		}
		
		public static void clearCurrentOperator() {
			MDC.remove(CURRENT_OPERATOR);
		}
		
		public static void clearReadonlyFlag() {
			MDC.remove(GUEST_READONLY);
		}
		
		public static void clearCurrentClientRequestIp() {
			MDC.remove(CURRENT_CLIENT_IP);
		}
		
		public static void set(String key, String value) {
			MDC.put(key, value);
		}
		
		public static void clearCurrentAll() {
			 clearCurrentOperator();
			 clearCurrentInvokeStart();
			 clearReadonlyFlag();
			 clearCurrentClientRequestIp();
		}
		 
		 public static Long getCurrentInvokeElapsedMillis() {
			 if (Strings.isBlank(MDC.get(CURRENT_INVOKE_START))) {
				 return null;
			 }
			 try {
				return System.currentTimeMillis() - Long.valueOf(MDC.get(CURRENT_INVOKE_START));
			 } catch (Exception e) {
			 }
			 return null;
		 }
		 
		 public static void putContextMap(Map map) {
			 if (Maps.isNotEmpty(map)) {
				 for (Map.Entry entry : map.entrySet()) {
					 MDC.put(entry.getKey(), entry.getValue());
			     }
			 }
		 }
		 
		 public static void clearContextMap(Map map) {
			 if (Maps.isNotEmpty(map)) {
				 for (Map.Entry entry : map.entrySet()) {
					 MDC.remove(entry.getKey());
			     }
			 }
		 }
		
	}
	
	public class MonitorConstants { 
		
		/*
		 * # Server端
		 * 
			 monitor:
			  redis:
				host: 192.168.31.248
				port: 6379
				password: redisAdmin_123456Pass
				db: 1
			  mutexwork:
			    enabled: true
			  report:
			    enabled: true
				postInterval: 10
				flushInterval: 5
				apiUrl: http://midware.idev.vip/configcenter/perfApi/report
				  
			# Client 端
			  
			  monitor:
			    report:
			      enabled: true
				  postInterval: 10
				  apiUrl: http://midware.idev.vip/configcenter/perfApi/report
			
		 * 
		 */
		
		public static final String DELAYTASK_ENABLED = "delaytask.enabled";
		
		public static final String MUTEXWORK_ENABLED = "mutexwork.enabled";
		public static final String MUTEXWORK_CUSTOM_WORKHOST = "mutexwork.workHost";
		public static final String MONITOR_MUTEXWORK_ENABLED = "monitor.mutexwork.enabled";
		public static final String MONITOR_MUTEXWORK_CUSTOM_WORKHOST = "monitor.mutexwork.workHost";
		
		public static final String MONITOR_CONTROLLER_ENABLED = "monitor.controller.enabled";
		
		public static final String MONITOR_REPORT_ENABLED = "monitor.report.enabled";
		public static final String MONITOR_REPORT_POST_INTERVAL = "monitor.report.postInterval"; // 秒
		public static final String MONITOR_REPORT_APIURL = "monitor.report.apiUrl";
		
		public static final String MONITOR_REPORT_FLUSH_INTERVAL = "monitor.report.flushInterval"; // 秒
		public static final String MONITOR_REDIS_HOST = "monitor.redis.host";
		public static final String MONITOR_REDIS_PORT = "monitor.redis.port";
		public static final String MONITOR_REDIS_PASSWORD = "monitor.redis.password";
		public static final String MONITOR_REDIS_DB = "monitor.redis.db";
		
		public static final String MONITOR_JVM_ALARM_FREE_MEMORY = "monitor.jvm.warnFreeMemory";
		
		// 钉钉报警监控AK配置
		public static final String DINGTALK_AKS_MASTER = "dingtalk.aks.master";
		public static final String DINGTALK_AKS_SLAVE = "dingtalk.aks.slave";
		
		// 性能监控的几个默认分组
		public static final String MONITOR_GROUP_DEFAULT = "default";    // 默认归组
		public static final String MONITOR_GROUP_DATABASE = "database";  // DB SQL的执行情况
		public static final String MONITOR_GROUP_DUBBO = "dubbo";        // Dubbo服务的执行 或 调用情况
		public static final String MONITOR_GROUP_HTTP = "http";          // 对外发起的http请求
		public static final String MONITOR_GROUP_WEB = "web";            // Controler的执行情况
		
	}
	
	public static class MonitorAlarmConfig {
		
		/**
		 * 默认sql耗时告警阀值(毫秒) 
		 */
		public static final long DEFAULT_SQL_WARN_MILLS = 100L; // 单位:毫秒
		
		public static final String SQL_WARN_ENABLED_MYBATIS = "mybatis.sql.enabled";
		public static final String SQL_WARN_MILLS_MYBATIS = "mybatis.sql.warnMills";
		public static final String SQL_WARN_SKIP_MAPPER_MYBATIS = "mybatis.sql.warnSkipMapperIds";
		public static final String SQL_WARN_IGNORE_MAPPER_MYBATIS = "mybatis.sql.ignore-mapper-ids";
		
		public static final String SQL_WARN_ENABLED = "monitor.sql.enabled";
		public static final String SQL_WARN_MILLS = "monitor.sql.warnMills";
		public static final String SQL_WARN_SKIP_MAPPER = "monitor.sql.warnSkipMapperIds";
		public static final String SQL_WARN_IGNORE_MAPPER = "monitor.sql.ignore-exceptions";
		
		public static final long DEFAULT_DUBBO_WARN_MILLS = 1500L; // 单位:毫秒
		public static final String DUBBO_WARN_ENABLED = "monitor.dubbo.enabled";
		public static final String DUBBO_WARN_MILLS = "monitor.dubbo.warnMills";
		public static final String DUBBO_WARN_SKIP_METHODS = "monitor.dubbo.warnSkipMethods";
		public static final String DUBBO_WARN_IGNORE_METHODS = "monitor.dubbo.ignore-methods";
		
		public static final long DEFAULT_CONTROLLER_WARN_MILLS = 1500L; // 单位:毫秒
		public static final String CONTROLLER_WARN_ENABLED = "monitor.controller.enabled";
		public static final String CONTROLLER_WARN_MILLS = "monitor.controller.warnMills";
		public static final String CONTROLLER_WARN_SKIP_EXCEPTIONS = "monitor.controller.warnSkipExceptions";
		public static final String CONTROLLER_WARN_IGNORE_EXCEPTIONS = "monitor.controller.ignore-exceptions";
		
		public static final long DEFAULT_HTTP_WARN_MILLS = 3000L; // 单位:毫秒
		public static final String HTTP_WARN_ENABLED = "monitor.http.enabled";
		public static final String HTTP_WARN_MILLS = "monitor.http.warnMills";
		
		public static final String MONITOR_APPLICATION_OWNER = "monitor.application.owner";
	}
	
	public static class CacheConfig {
		
		/**
		 * GeneralCache 组件是否开启了本地缓存(默认开启: true) 
		 */
		public static final String CACHE_LOCAL_ENABLED = "cache.local.enabled";
		
		/**
		 * GeneralCache 组件是否开启(默认不开启: false) 
		 */
		public static final String GENERAL_CACHE_ENABLED = "cache.generalInterceptor.enabled";
		
		/**
		 * 用于配置是否开启缓存统计日志打印
		 */
		public static final String CACHE_STATLOG_ENABLED = "cache.statslog.enabled";
		
		/**
		 * caffeine缓存最大容量(可容纳元素个数) 
		 */
		public static final String CAFFEINE_MAXIMUM_SIZE = "cache.caffeine.maximumSize";
		/**
		 * caffeine缓存统一失效时长(毫秒)
		 */
		public static final String CAFFEINE_EXPIRED_MILLS = "cache.caffeine.expiredMills";
		
		/**
		 * JVM 最大保留内存(当剩余可用内存小于此值时,本地缓存不再接受新元素)
		 */
		public static final String LOCAL_MAX_FREE_MEMORY = "cache.local.maxFreeMemory";
		
		/**
		 * Redis 订阅消息通道topic 
		 */
		public static final String REDIS_SUBSCRIBED_TOPIC = "cache.redis.message.topics";
		
		/**
		 * GeneralCache 组件缓存变更,Redis消息topic
		 */
		public static final String GENERAL_CACHE_REDIS_TOPIC = "GENERAL_CACHE_CHANGED";
		
	}
	
	public static class RedisStoreConfig {
		
		public static final String STORE_KEY_COMMON = "REDIS_STORE_COMMON";
		public static final String STORE_KEY_MUTEXWORK = "REDIS_STORE_MUTEXWORK";
		public static final String STORE_KEY_DELAYTASK = "REDIS_STORE_DELAYTASK";
		
		// redis组件默认配置
		public static final String HOST = "redis.host";
		public static final String PORT = "redis.port";
		public static final String PASSWORD = "redis.password";
		public static final String DB = "redis.db";
		
		public static final String[] SPRING_CONFIG = new String[] {
			SpringRedisConfig.HOST, 
			SpringRedisConfig.PORT,
			SpringRedisConfig.PASSWORD,
			SpringRedisConfig.DATABASE
		};
		
		public static final String[] REDIS_STORE_CONFIG = new String[] {
			HOST,
			PORT,
			PASSWORD, 
			DB
		};
		
		public static final String[] REDIS_STORE_CONFIG_MONITOR = new String[] {
			"monitor.redis.host",
			"monitor.redis.port",
			"monitor.redis.password",
			"monitor.redis.db"
		};
		
		public static final String[] REDIS_STORE_CONFIG_DALAYTASK = new String[] {
			"delaytask.redis.host",
			"delaytask.redis.port",
			"delaytask.redis.password",
			"delaytask.redis.db"
		};
		
	}
	
	public static class MonitorMailConfig {
		public static final String HOST = "monitor.mail.host";
		public static final String USERNAME = "monitor.mail.username";
		public static final String PASSWORD = "monitor.mail.password";
		
		public static final String INTERNAL_MAIL_HOST = "smtp.126.com";
		public static final String INTERNAL_USER_ACCOUNT = "Ld7xRYpKz9YnWBlrV4QxxE0TVlrDr1EK"; // robot_notify
		public static final String INTERNAL_USER_PASSWORD = "B3H8pGzy0U80ZZ9h4SSJP2uC/fM4LDmh";
	}
	
	public static class SpringMailConfig {
		public static final String HOST = "spring.mail.host";
		public static final String USERNAME = "spring.mail.username";
		public static final String PASSWORD = "spring.mail.password";
	}
	
	public static class SpringRedisConfig {
		public static final String HOST = "spring.redis.host";
		public static final String PORT = "spring.redis.port";
		public static final String PASSWORD = "spring.redis.password";
		public static final String DATABASE = "spring.redis.database";
		
		public static final String TIMEOUT = "spring.redis.timeout";
		
		/**
		 * Redis默认端口号 
		 */
		public static final int DEFAULT_PORT = 6379;
		/**
		 * spring配置没配置DB时,默认DB值
		 */
		public static final int DEFAULT_DB = 0;
	}
	
	/**
	 * 网络相关变量及参数
	 */
	public class NetworkConfig {
		
		public static final String DEFAULT_CONN_TIMEOUT_KEY = "sun.net.client.defaultConnectTimeout";
		public static final String DEFAULT_READ_TIMEOUT_KEY = "sun.net.client.defaultReadTimeout";
		
		public static final String LOCAL_NETWORK_BIND_IP_PREFIX = "network.localip.prefix";
		public static final String NETWORK_CONNECTION_TIMEOUT_KEY = "network.connection.timeout";
		public static final String NETWORK_READ_TIMEOUT_KEY = "network.read.timeout";
		public static final String NETWORK_WRITE_TIMEOUT_KEY = "network.write.timeout";
		
		public static final Long NETWORK_DEFAULT_CONNECTION_TIMEOUT = 5000L; // 5秒连接超时
		public static final Long NETWORK_DEFAULT_READ_TIMEOUT = 10000L; // 10秒读取超时
		public static final Long NETWORK_DEFAULT_WRITE_TIMEOUT = 30000L; // 30秒写超时
		
		public static final String ANYHOST_VALUE = "0.0.0.0";
		
		/**
		 * 取网络超时配置
		 * 
		 * 
  • 同时取网络连接超时和读取超时配置 *
  • 优先选择超时时间值较大的值 *
  • 获取不到值则返回默认值10秒 * * @return 网络超时配置值(毫秒) */ public static int getTimeout() { String connTimeout = Systems.getSystemProperty(DEFAULT_CONN_TIMEOUT_KEY); // 连接超时 String readTimeout = Systems.getSystemProperty(DEFAULT_READ_TIMEOUT_KEY); // 读取超时 if (Strings.isBlank(connTimeout)) { connTimeout = CompositeAppConfigProperties.getInstance().getValue(new String[] { DEFAULT_CONN_TIMEOUT_KEY, NETWORK_CONNECTION_TIMEOUT_KEY }); } if (Strings.isBlank(readTimeout)) { readTimeout = CompositeAppConfigProperties.getInstance().getValue(new String[] { DEFAULT_READ_TIMEOUT_KEY, NETWORK_READ_TIMEOUT_KEY }); } String springTimeout = CompositeAppConfigProperties.getInstance().getValue(SpringRedisConfig.TIMEOUT); int CONN_TIMEOUT = Numbers.toInt(connTimeout, 0); int SOCK_TIMEOUT = Numbers.toInt(readTimeout, 0); int SPRING_TIMEOUT = Numbers.toInt(springTimeout, 0); int timeout = Numbers.max(CONN_TIMEOUT, SOCK_TIMEOUT, SPRING_TIMEOUT); return timeout > 0 ? timeout : NETWORK_DEFAULT_READ_TIMEOUT.intValue(); } } public class NacosConfig { public static final String NACOS_ADDR_KEY_SPRING_BOOT = "nacos.config.server-addr"; public static final String NACOS_ADDR_KEY_SPRING_CLOUD = "spring.cloud.nacos.config.server-addr"; public static final String NACOS_CONFIG_FILE_EXTENTION_SPRING_CLOUD = "spring.cloud.nacos.config.file-extension"; } public class ChangedType { public static final int UPDATED = 0; public static final int MODIFIED = 0; public static final int CREATED = 1; public static final int ADDED = 1; public static final int REMOVED = 2; public static final int DELETED = 2; public static final int ADD_OR_REMOVED = 3; // 混合操作(既有增加也有删除) public static String desc(int changedType) { switch (changedType) { case ADDED: return "ADDED"; case MODIFIED: return "MODIFIED"; case REMOVED: return "REMOVED"; case ADD_OR_REMOVED: return "ADD_OR_REMOVED"; } return "N/A"; } } public class GeneralCacheChangedType { public static final int UPDATED = 0; public static final int CREATED = 1; public static final int REMOVED = 2; public static String desc(int type) { switch (type) { case CREATED: return "CREATED"; case UPDATED: return "UPDATED"; case REMOVED: return "REMOVED"; default: return "N/A"; } } } public enum MemCapacity { B, KB, MB, GB, TB, ; public long byteAmount() { switch (this) { case B: return 1L; case KB: return 1024L; case MB: return 1048576L; // 1024*1024 case GB: return 1073741824L; // 1024*1024*1024 case TB: return 1099511627776L; // 1024*1024*1024*1024 } throw new UnsupportedOperationException(); } public static MemCapacity from(String unit) { if (Strings.isBlank(unit)) { throw new IllegalArgumentException("Capacity unit is empty!"); } switch (unit.toUpperCase()) { case "B": return B; case "KB": case "K": return KB; case "MB": case "M": return MB; case "GB": case "G": return GB; case "TB": case "T": return TB; } throw new UnsupportedOperationException("Invalid capacity unit"); } public static long bytesAmount(long amount, String unit) { switch (unit.toUpperCase()) { case "": case "B": return amount; case "KB": return MemCapacity.longBytesOfKB((int) amount); case "MB": return MemCapacity.longBytesOfMB((int) amount); case "GB": return MemCapacity.longBytesOfGB((int) amount); case "TB": return MemCapacity.longBytesOfTB((int) amount); } throw new IllegalArgumentException("'" + unit + "' is not a valid data size unit."); } public static int intBytesOfKB(int kb) { return Long.valueOf(kb * KB.byteAmount()).intValue(); } public static long longBytesOfKB(int kb) { return Long.valueOf(kb * KB.byteAmount()); } public static int intBytesOfMB(int mb) { return Long.valueOf(mb * MB.byteAmount()).intValue(); } public static long longBytesOfMB(int mb) { return Long.valueOf(mb * MB.byteAmount()); } public static int intBytesOfGB(int gb) { return Long.valueOf(gb * GB.byteAmount()).intValue(); } public static long longBytesOfGB(int gb) { return Long.valueOf(gb * GB.byteAmount()); } public static long longBytesOfTB(int tb) { return Long.valueOf(tb * TB.byteAmount()); } /** * 检查长度大小是否超出限制 */ public static boolean isLengthOverflow(long length, int limit, String unit) { return length > bytesAmount(limit, unit) ? true : false; } } public class WebMvc { public static final String HEADER_UA = "User-Agent"; public static final String HEADER_ACCEPT = "Accept"; public static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding"; public static final String HEADER_ACCEPT_LANGUAGE = "Accept-Language"; public static final String HEADER_CACHE_CONTROL = "Cache-Control"; public static final String HEADER_CONNECTION = "Connection"; public static final String HEADER_CONTENT_TYPE = "Content-Type"; public static final String HEADER_CONTENT_LENGTH = "Content-Length"; public static final String HEADER_PRAGMA = "Pragma"; public static final String HEADER_COOKIE = "Cookie"; public static final String HEADER_HOST = "Host"; public static final String HEADER_ORIGIN = "Origin"; public static final String HEADER_REFERER = "Referer"; public static final String[] HEADERS_IGNORE = new String[] { HEADER_UA, HEADER_ACCEPT, HEADER_ACCEPT_ENCODING, HEADER_ACCEPT_LANGUAGE, HEADER_CACHE_CONTROL, HEADER_CONNECTION, HEADER_CONTENT_TYPE, HEADER_CONTENT_LENGTH, HEADER_PRAGMA }; public static final String[] HEADERS_NORMAL = new String[] { HEADER_UA, HEADER_ACCEPT, HEADER_ACCEPT_ENCODING, HEADER_ACCEPT_LANGUAGE, HEADER_CACHE_CONTROL, HEADER_CONNECTION, HEADER_CONTENT_TYPE, HEADER_CONTENT_LENGTH, HEADER_PRAGMA, HEADER_HOST, HEADER_ORIGIN, HEADER_REFERER, }; public static final String ANNOTATION_REQUEST_MAPPING = "@annotation(org.springframework.web.bind.annotation.RequestMapping)"; public static final String ANNOTATION_GET_MAPPING = "@annotation(org.springframework.web.bind.annotation.GetMapping)"; public static final String ANNOTATION_POST_MAPPING = "@annotation(org.springframework.web.bind.annotation.PostMapping)"; public static final String ANNOTATION_DELETE_MAPPING = "@annotation(org.springframework.web.bind.annotation.DeleteMapping)"; public static final String ANNOTATION_PATCH_MAPPING = "@annotation(org.springframework.web.bind.annotation.PatchMapping)"; public static final String ANNOTATION_PUT_MAPPING = "@annotation(org.springframework.web.bind.annotation.PutMapping)"; public static final String API_STATUS_FLAG = "httpapi.reponse.key.status"; public static final String API_RETURN_MSG = "httpapi.reponse.key.message"; public static final String API_RETURN_DATA = "httpapi.reponse.key.data"; public static final String CT_APPLICATION_JSON = "application/json"; public static final String CT_MULTIPART_FORM = "multipart/form-data"; public static final String CT_X_WWW_FORM_URLENCODED = "application/x-www-form-urlencoded"; } public class WebCors { public static final String CORS_ALLOW_CREDENTIALS = "system.configs.webcors.allowCredentials"; public static final String CORS_ALLOW_ORIGIN = "system.configs.webcors.allowOrigin"; public static final String CORS_ALLOW_HEADERS = "system.configs.webcors.allowHeaders"; public static final String CORS_ALLOW_METHODS = "system.configs.webcors.allowMethods"; public static final String CORS_MAX_AGE = "system.configs.webcors.maxAge"; public static final String MAX_AGE_DEFAULT = "1800"; // 30分钟 public static final String ALLOW_CREDENTIALS_DEFAULT = "true"; public static final String ALLOW_METHODS_DEFAULT = "POST, GET, OPTIONS, DELETE, HEAD, PUT, PATCH"; public static final String ALLOW_HEADERS_DEFAULT = "Origin, X-Requested-With, Content-Type, content-type, Accept, Authorization, Token, token"; } public class CodecType { public static final int ENCRYPT = 1; // 加密 public static final int DECRYPT = 2; // 解密 } public class NumberType { public static final int BYTE = 1; public static final int SHORT = 2; public static final int INT = 3; public static final int LONG = 4; public static final int FLOAT = 5; public static final int DOUBLE = 6; public static final int BIG_DECIMAL = 7; /** * 获取数据类型精度顺序 */ public static int getNumericTypeSeq(Class clazz) { if (clazz == Byte.class || clazz == byte.class) { return BYTE; } if (clazz == Short.class || clazz == short.class) { return SHORT; } if (clazz == Integer.class || clazz == int.class) { return INT; } if (clazz == Long.class || clazz == long.class) { return LONG; } if (clazz == Float.class || clazz == float.class) { return FLOAT; } if (clazz == Double.class || clazz == double.class) { return DOUBLE; } if (clazz == BigDecimal.class) { return BIG_DECIMAL; } throw new BizException("不能处理的数据类型:" + clazz.getName()); } } public static final class DeleteFlag { public static final int NORMAL = 0; // 正常状态 public static final int DELETED = 1; // 已删除 } public static final class EnableStatus { public static final int NORMAL = 1; // 正常可用状态 public static final int ENABLED = 1; // 已启用状态 public static final int DISABLED = 0; // 已禁用状态 } public static final class UpAndDownStatus { public static final int UPSHELF = 1; // 已(上架/上线) public static final int ONLINE = 1; // 已(上架/上线) public static final int DOWNSHELF = 0; // 已(下架/下线) public static final int OFFLINE = 0; // 已(下架/下线) } public static final class WebappConfig { public static final String KEY_OF_CTRL_PACKAGE_PATH = "systems.configs.app-conctroller-package"; } public static final class SwaggerConf { public static final String DOC_DEFAULT_SERVICE_URL = "https://github.com/javaclub"; public static final String DOC_URL_PROTOCOL = "system.configs.doc.protocol"; public static final String DOC_URL_HOST = "system.configs.doc.host"; public static final String DOC_URL_CONTEXT = "system.configs.doc.context"; public static final String DOC_PROJECT = "system.configs.doc.project"; public static final String DOC_VERSION = "system.configs.doc.version"; public static final String DOC_DATE = "system.configs.doc.date"; public static final String DOC_AUTHOR = "system.configs.doc.author"; public static final String DOC_EMAIL = "system.configs.doc.email"; public static final String DOC_EXCLUDE_PATH = "system.configs.doc.exclude-paths"; } public static final class RSAConfig { public static final String RSA_PRIVATE_KEY = "system.configs.rsa.private-key"; public static final String RSA_PUBLIC_KEY = "system.configs.rsa.public-key"; } public static class ContentTypeMap { public static final String BINARY_STREAM = "octet-stream"; // see: https://help.aliyun.com/zh/oss/user-guide/configure-the-content-type-header static final Map TYPES_MAP = Maps.createStringMap( ".a11", "application/x-a11", ".ai", "application/postscript", ".aifc", "audio/aiff", ".anv", "application/x-anv", ".asa", "text/asa", ".asp", "text/asp", ".au", "audio/basic", ".awf", "application/vnd.adobe.workflow", ".bmp", "application/x-bmp", ".c4t", "application/x-c4t", ".cal", "application/x-cals", ".cdf", "application/x-netcdf", ".cel", "application/x-cel", ".cg4", "application/x-g4", ".cit", "application/x-cit", ".cml", "text/xml", ".cmx", "application/x-cmx", ".crl", "application/pkix-crl", ".csi", "application/x-csi", ".csv", "text/csv" ); public static boolean isFormDataContentType(String contentType) { return Strings.startsWithIgnoreCase(contentType, "application/x-www-form-urlencoded"); } public static boolean isRequestPayloadContentType(String contentType) { return Strings.startsWithIgnoreCase(contentType, "application/json"); } public static final String contentType(String extention) { if (Strings.isBlank(extention)) { return BINARY_STREAM; } if (TYPES_MAP.containsKey(extention)) { return TYPES_MAP.get(extention); } return BINARY_STREAM; } } }




  • © 2015 - 2024 Weber Informatics LLC | Privacy Policy