Commit 79d341c1 authored by liaozan's avatar liaozan 🏀

Polish

parent 4bdeb70e
......@@ -16,7 +16,9 @@ import org.springframework.core.env.Environment;
public class EnvUtils {
public static final String DEVELOPMENT = "dev";
public static final String TESTING = "test";
public static final String PRODUCTION = "prod";
public static boolean isDevelopment() {
......
......@@ -17,8 +17,7 @@
package com.schbrain.common.util;
import java.security.SecureRandom;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
/***
* @author adyliu (imxylz@gmail.com)
......@@ -30,30 +29,43 @@ public class IdWorker {
* 生成的自增id的大小减少到18位
*/
private static final long ID_EPOCH = 1420041600000L;
private static final long workerIdBits = 5L;
private static final long datacenterIdBits = 5L;
private static final long maxWorkerId = ~(-1L << workerIdBits);
private static final long maxDatacenterId = ~(-1L << datacenterIdBits);
private static final long sequenceBits = 12L;
private static final long workerIdShift = sequenceBits;
private static final long datacenterIdShift = sequenceBits + workerIdBits;
private static final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
private static final long sequenceMask = ~(-1L << sequenceBits);
private static final Random r = new SecureRandom();
// 需要等 r 初始化
private static final IdWorker INSTANCE = new IdWorker(ID_EPOCH);
private static final IdWorker INSTANCE = new IdWorker();
private final long workerId;
private final long datacenterId;
private final long idEpoch;
private long lastTimestamp = -1L;
private long sequence;
public IdWorker(long idEpoch) {
this(r.nextInt((int) maxWorkerId), r.nextInt((int) maxDatacenterId), 0, idEpoch);
public IdWorker() {
this(ThreadLocalRandom.current().nextLong(maxWorkerId), ThreadLocalRandom.current().nextLong(maxDatacenterId), 0);
}
public IdWorker(long workerId, long datacenterId, long sequence) {
this(workerId, datacenterId, sequence, 1420041600000L);
this(workerId, datacenterId, sequence, ID_EPOCH);
}
public IdWorker(long workerId, long datacenterId, long sequence, long idEpoch) {
......@@ -104,10 +116,7 @@ public class IdWorker {
sequence = 0;
}
lastTimestamp = timestamp;
return ((timestamp - idEpoch) << timestampLeftShift)//
| (datacenterId << datacenterIdShift)//
| (workerId << workerIdShift)//
| sequence;
return ((timestamp - idEpoch) << timestampLeftShift) | (datacenterId << datacenterIdShift) | (workerId << workerIdShift) | sequence;
}
private long tilNextMillis(long lastTimestamp) {
......
package com.schbrain.common.util;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
......@@ -29,6 +28,19 @@ public class InetUtils {
return hostInfo;
}
public static int getIpAddressAsInt(HostInfo hostInfo) {
String host = hostInfo.getIpAddress();
if (host == null) {
host = hostInfo.getHostname();
}
try {
InetAddress inetAddress = InetAddress.getByName(host);
return ByteBuffer.wrap(inetAddress.getAddress()).getInt();
} catch (final UnknownHostException e) {
throw new IllegalArgumentException(e);
}
}
private static InetAddress findFirstNonLoopBackAddress() {
InetAddress result = null;
try {
......@@ -80,25 +92,9 @@ public class InetUtils {
@Data
public static class HostInfo {
public static final String NAME = "machineHostInfo";
private String ipAddress;
private String hostname;
@JsonIgnore
public int getIpAddressAsInt() {
InetAddress inetAddress;
String host = this.ipAddress;
if (host == null) {
host = this.hostname;
}
try {
inetAddress = InetAddress.getByName(host);
} catch (final UnknownHostException e) {
throw new IllegalArgumentException(e);
}
return ByteBuffer.wrap(inetAddress.getAddress()).getInt();
}
private String hostname;
}
......
......@@ -4,9 +4,7 @@ import cn.hutool.extra.spring.SpringUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.node.NullNode;
import com.schbrain.common.constants.ResponseActionConstants;
import com.schbrain.common.constants.ResponseCodeConstants;
import com.schbrain.common.exception.BaseException;
import com.schbrain.common.util.exception.JSONException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
......@@ -25,6 +23,7 @@ import static com.fasterxml.jackson.databind.SerializationFeature.INDENT_OUTPUT;
public class JacksonUtils {
private static ObjectMapper OBJECT_MAPPER;
private static ObjectMapper PRETTY_OBJECT_MAPPER;
public static ObjectMapper getObjectMapper() {
......@@ -230,14 +229,4 @@ public class JacksonUtils {
}
}
public static class JSONException extends BaseException {
private static final long serialVersionUID = 1656914307906296812L;
public JSONException(String message, Throwable cause) {
super(message, cause, ResponseCodeConstants.SERVER_ERROR, ResponseActionConstants.ALERT);
}
}
}
\ No newline at end of file
package com.schbrain.common.util.exception;
import com.schbrain.common.constants.ResponseActionConstants;
import com.schbrain.common.constants.ResponseCodeConstants;
import com.schbrain.common.exception.BaseException;
/**
* @author liaozan
* @since 2023-05-06
*/
public class JSONException extends BaseException {
private static final long serialVersionUID = 1656914307906296812L;
public JSONException(String message, Throwable cause) {
super(message, cause, ResponseCodeConstants.SERVER_ERROR, ResponseActionConstants.ALERT);
}
}
\ No newline at end of file
......@@ -25,7 +25,9 @@ public class ExcelReadListenerBase<T> extends AnalysisEventListener<T> {
protected final Validator validator = SpringUtil.getBean(Validator.class);
protected List<T> dataList = new LinkedList<>();
protected Map<Integer, String> headers = new HashMap<>();
protected Table<String, Integer, String> errors = HashBasedTable.create();
protected boolean terminateOnValidateFail = false;
......
......@@ -80,6 +80,7 @@ public class HierarchicalDataReadListener extends ExcelReadListenerBase<Map<Inte
public static class ImportedRecord {
private String text;
private List<ImportedRecord> children = new LinkedList<>();
public boolean hasChildren() {
......
......@@ -9,25 +9,38 @@ import static java.time.format.DateTimeFormatter.ofPattern;
* @author liaozan
* @since 2021/10/15
*/
@SuppressWarnings("unused")
public class DateTimeFormatters {
public static final String YEAR_MONTH_PATTERN = "yyyy-MM";
public static final String MONTH_DATE_PATTERN = "MM-dd";
public static final String DATE_PATTERN = "yyyy-MM-dd";
public static final String DATE_PATTERN_WITH_DOT = "yyyy.MM.dd";
public static final String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
public static final String TIME_PATTERN = "HH:mm:ss";
public static final String YEAR_MONTH_WITH_SLASH_PATTERN = "yyyy/MM";
public static final String DATE_WITH_SLASH_PATTERN = "yyyy/MM/dd";
public static final DateTimeFormatter YEAR_MONTH = ofPattern(YEAR_MONTH_PATTERN).withZone(systemDefault());
public static final DateTimeFormatter MONTH_DATE = ofPattern(MONTH_DATE_PATTERN).withZone(systemDefault());
public static final DateTimeFormatter DATE = ofPattern(DATE_PATTERN).withZone(systemDefault());
public static final DateTimeFormatter DATE_WITH_DOT = ofPattern(DATE_PATTERN_WITH_DOT).withZone(systemDefault());
public static final DateTimeFormatter DATE_TIME = ofPattern(DATE_TIME_PATTERN).withZone(systemDefault());
public static final DateTimeFormatter TIME = ofPattern(TIME_PATTERN).withZone(systemDefault());
public static final String YEAR_MONTH_WITH_SLASH_PATTERN = "yyyy/MM";
public static final String DATE_WITH_SLASH_PATTERN = "yyyy/MM/dd";
public static final DateTimeFormatter TIME = ofPattern(TIME_PATTERN).withZone(systemDefault());
public static final DateTimeFormatter YEAR_MONTH_WITH_SLASH = ofPattern(YEAR_MONTH_WITH_SLASH_PATTERN).withZone(systemDefault());
public static final DateTimeFormatter DATE_WITH_SLASH = ofPattern(DATE_WITH_SLASH_PATTERN).withZone(systemDefault());
}
\ No newline at end of file
......@@ -10,18 +10,22 @@ public class PageConstants {
* 分页时是否 count
*/
public static final boolean DEFAULT_SEARCH_COUNT = true;
/**
* 默认页码数
*/
public static final int DEFAULT_PAGE_INDEX = 1;
/**
* 默认分页大小
*/
public static final int DEFAULT_PAGE_SIZE = 20;
/**
* 默认总页数
*/
public static final long DEFAULT_TOTAL_PAGE_COUNT = 1;
/**
* 默认总记录数
*/
......
......@@ -10,18 +10,22 @@ public class ResponseActionConstants {
* 业务无异常时统一返回0
*/
public static final int NO_ACTION = 0;
/**
* 忽略异常
*/
public static final int IGNORE = -1;
/**
* 弹框
*/
public static final int ALERT = -2;
/**
* toast
*/
public static final int TOAST = -3;
/**
* 弹框,点击确定后刷新页面
*/
......
......@@ -10,22 +10,27 @@ public class ResponseCodeConstants {
* 成功
*/
public static final int SUCCESS = 0;
/**
* 服务器错误,空指针、数组越界等非业务代码抛出异常
*/
public static final int SERVER_ERROR = -1;
/**
* 非法请求,参数异常、参数格式错误等接口的请求非法性抛出的通用错误
*/
public static final int PARAM_INVALID = -2;
/**
* 无权限
*/
public static final int ACCESS_DENIED = -3;
/**
* 用户未登录,且该接口需要登录
*/
public static final int LOGIN_REQUIRED = -4;
/**
* 系统维护
*/
......
......@@ -22,30 +22,37 @@ public class PaginationInfo<T> implements Serializable {
* 页索引
*/
private long pageIndex = DEFAULT_PAGE_INDEX;
/**
* 每个页面大小
*/
private long pageSize = DEFAULT_PAGE_SIZE;
/**
* 当前结果集记录数量
*/
private long currentPageSize = DEFAULT_PAGE_INDEX;
/**
* 总页面数量
*/
private long totalPageCount = DEFAULT_TOTAL_COUNT;
/**
* 满足条件的记录数量
*/
private long totalCount = DEFAULT_TOTAL_COUNT;
/**
* 是否有前一页
*/
private boolean hasPrevPage = false;
/**
* 是否有下一页
*/
private boolean hasNextPage = false;
/**
* 结果集, Use new ArrayList() instead of collections.emptyList() to prevent errors when users edit it later
*/
......
......@@ -17,6 +17,7 @@ public class StructureTreeNode<NODE> implements Serializable {
private static final long serialVersionUID = -7732621737666937981L;
private NODE node;
private List<StructureTreeNode<NODE>> children;
}
\ No newline at end of file
......@@ -20,6 +20,7 @@ import java.util.*;
public class TreeNodeProcessor<NODE extends TreeNode> {
private final TreeNodeDao<NODE> treeNodeDao;
private final TreeOperationAware<NODE> operationHandler;
public TreeNodeProcessor(BaseDao<NODE> baseDao, TreeOperationAware<NODE> operationHandler) {
......
......@@ -10,29 +10,36 @@ public class TreeQueryOption {
* 包括节点自身
*/
public static final int TREE_QUERY_SELF_INCLUDE = 0;
/**
* 不包括节点自身
*/
public static final int TREE_QUERY_SELF_EXCLUDE = 1;
/**
* 只包含直接子节点
*/
public static final int TREE_QUERY_CHILDREN_DIRECT = 0;
/**
* 包含所有子节点
*/
public static final int TREE_QUERY_CHILDREN_ALL = 1;
/**
* 深度排序-从根到叶子节点
*/
public static final int TREE_QUERY_DEPTH_ORDER_ROOT_2_LEAF = 0;
/**
* 深度排序-从叶子节点到根
*/
public static final int TREE_QUERY_DEPTH_ORDER_LEAF_2_ROOT = 1;
private int selfIncludeMode;
private int childrenMode;
private int depthOrder;
private TreeQueryOption() {
......
......@@ -7,6 +7,7 @@ package com.schbrain.common.module.tree.constant;
public class TreeConstant {
public static final Long ROOT_PARENT_ID = -1L;
public static final Long NODE_DELETE_VERSION_DEFAULT = 0L;
}
\ No newline at end of file
......@@ -3,7 +3,6 @@ package com.schbrain.common.web.exception;
import com.schbrain.common.web.annotation.ResponseWrapOption;
import com.schbrain.common.web.properties.WebProperties;
import com.schbrain.common.web.utils.HandlerMethodAnnotationUtils;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.ServletWebRequest;
......@@ -27,22 +26,24 @@ import java.util.concurrent.ConcurrentHashMap;
* @since 2022/8/30
*/
@Slf4j
@Data
@EqualsAndHashCode(callSuper = true)
public class GlobalExceptionResolver extends AbstractHandlerMethodExceptionResolver {
public class DefaultGlobalExceptionResolver extends AbstractHandlerMethodExceptionResolver {
private final WebProperties webProperties;
private final GlobalExceptionHandler exceptionHandler;
private final ExceptionHandlerMethodResolver handlerMethodResolver;
private final HandlerMethodArgumentResolverComposite argumentResolverComposite;
private final HandlerMethodReturnValueHandlerComposite returnValueHandlerComposite;
private final Map<Class<?>, ExceptionHandlerMethodResolver> exceptionHandlerCache = new ConcurrentHashMap<>(64);
private GlobalExceptionHandler exceptionHandler;
private ExceptionHandlerMethodResolver handlerMethodResolver;
private final Map<Class<?>, ExceptionHandlerMethodResolver> exceptionHandlerCache = new ConcurrentHashMap<>(64);
public GlobalExceptionResolver(ExceptionHandlerExceptionResolver handlerMethodResolver, WebProperties webProperties,
GlobalExceptionHandler exceptionHandler) {
this.exceptionHandler = exceptionHandler;
public DefaultGlobalExceptionResolver(ExceptionHandlerExceptionResolver handlerMethodResolver, WebProperties webProperties, GlobalExceptionHandler exceptionHandler) {
this.webProperties = webProperties;
this.exceptionHandler = exceptionHandler;
this.handlerMethodResolver = new ExceptionHandlerMethodResolver(exceptionHandler.getClass());
this.argumentResolverComposite = handlerMethodResolver.getArgumentResolvers();
this.returnValueHandlerComposite = handlerMethodResolver.getReturnValueHandlers();
......@@ -67,8 +68,7 @@ public class GlobalExceptionResolver extends AbstractHandlerMethodExceptionResol
}
@Override
protected final ModelAndView doResolveHandlerMethodException(HttpServletRequest request, HttpServletResponse response,
@Nullable HandlerMethod handlerMethod, Exception exception) {
protected final ModelAndView doResolveHandlerMethodException(HttpServletRequest request, HttpServletResponse response, @Nullable HandlerMethod handlerMethod, Exception exception) {
ServletInvocableHandlerMethod exceptionHandlerMethod = createExceptionHandlerMethod(exception, handlerMethod, exceptionHandler);
if (exceptionHandlerMethod == null) {
return null;
......@@ -115,6 +115,11 @@ public class GlobalExceptionResolver extends AbstractHandlerMethodExceptionResol
return resolvedMethod;
}
@Override
protected void logException(Exception ex, HttpServletRequest request) {
// nothing to do
}
private ExceptionHandlerMethodResolver getHandlerMethodResolver(Class<?> handlerType) {
return exceptionHandlerCache.computeIfAbsent(handlerType, key -> new ExceptionHandlerMethodResolver(handlerType));
}
......
......@@ -16,6 +16,7 @@ import java.util.List;
public class ExceptionHandlerWebMcvConfigurer implements WebMvcConfigurer {
private final WebProperties webProperties;
private final GlobalExceptionHandler globalExceptionHandler;
public ExceptionHandlerWebMcvConfigurer(WebProperties webProperties, GlobalExceptionHandler globalExceptionHandler) {
......@@ -51,8 +52,8 @@ public class ExceptionHandlerWebMcvConfigurer implements WebMvcConfigurer {
resolvers.add(index, createGlobalExceptionResolver(adviceExceptionResolver));
}
protected GlobalExceptionResolver createGlobalExceptionResolver(ExceptionHandlerExceptionResolver adviceExceptionResolver) {
return new GlobalExceptionResolver(adviceExceptionResolver, webProperties, globalExceptionHandler);
protected HandlerExceptionResolver createGlobalExceptionResolver(ExceptionHandlerExceptionResolver adviceExceptionResolver) {
return new DefaultGlobalExceptionResolver(adviceExceptionResolver, webProperties, globalExceptionHandler);
}
}
\ No newline at end of file
......@@ -23,7 +23,9 @@ import java.util.concurrent.ConcurrentHashMap;
public class ResponseBodyHandler implements ResponseBodyAdvice<Object> {
private final WebProperties webProperties;
private final List<String> basePackages;
private final Map<Method, Boolean> methodCache;
public ResponseBodyHandler(WebProperties webProperties, List<String> basePackages) {
......
......@@ -18,9 +18,13 @@ public class ResponseDTO<T> implements Serializable {
private static final long serialVersionUID = 8559474982311419998L;
private int code;
private int action;
private String message;
private T data;
private String uuid = TraceIdUtils.get();
public static <T> ResponseDTO<T> success() {
......
......@@ -17,10 +17,15 @@ import java.util.Objects;
public class BuilderContext {
private final AbstractBuild<?, ?> build;
private final Launcher launcher;
private final FilePath workspace;
private final BuildListener listener;
private final Logger logger;
private final EnvVars envVars;
private boolean imageHasBeenBuilt;
......@@ -90,10 +95,15 @@ public class BuilderContext {
public static class Builder {
private AbstractBuild<?, ?> build;
private Launcher launcher;
private FilePath workspace;
private BuildListener listener;
private Logger logger;
private EnvVars envVars;
public Builder build(AbstractBuild<?, ?> build) {
......
......@@ -31,7 +31,9 @@ import static com.schbrain.ci.jenkins.plugins.integration.builder.util.FileUtils
public class IntegrationBuilder extends Builder {
private final MavenConfig mavenConfig;
private final DockerConfig dockerConfig;
private final DeployToK8sConfig deployToK8sConfig;
@DataBoundConstructor
......
......@@ -14,11 +14,17 @@ import java.io.IOException;
public abstract class BuildConfig<T extends AbstractDescribableImpl<T>> extends AbstractDescribableImpl<T> {
protected AbstractBuild<?, ?> build;
protected Launcher launcher;
protected FilePath workspace;
protected BuildListener listener;
protected Logger logger;
protected EnvVars envVars;
protected BuilderContext context;
public void build(BuilderContext context) throws IOException, InterruptedException {
......
......@@ -28,11 +28,17 @@ public class DockerConfig extends BuildConfig<DockerConfig> {
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmss").withZone(ZoneId.systemDefault());
private final Boolean buildImage;
private final PushConfig pushConfig;
private final Boolean deleteImageAfterBuild;
private final String javaOpts;
private final String buildScriptUrl;
private final String buildScriptBranch;
private final Boolean disableSkywalking;
@DataBoundConstructor
......@@ -140,6 +146,7 @@ public class DockerConfig extends BuildConfig<DockerConfig> {
public static class PushConfig extends BuildConfig<PushConfig> {
private final Boolean pushImage;
private final String registry;
@DataBoundConstructor
......
......@@ -23,10 +23,15 @@ import static com.schbrain.ci.jenkins.plugins.integration.builder.constants.Cons
public class DeployTemplateComponent extends DeployStyleRadio {
private final String namespace;
private final String replicas;
private final String memoryRequest;
private final String memoryLimit;
private final String nodeTag;
private final String port;
@DataBoundConstructor
......
......@@ -22,8 +22,11 @@ import static com.schbrain.ci.jenkins.plugins.integration.builder.constants.Cons
public class ServiceDeployConfig {
private final String serviceMode;
private final String serviceNamespace;
private final String serviceName;
private final String servicePort;
@DataBoundConstructor
......
......@@ -8,9 +8,13 @@ public class Constants {
public static class BuildConstants {
public static final String DEFAULT_SCRIPT_GIT_REPO = "git@gitlab.schbrain.com:tools/build-script.git";
public static final String DEFAULT_SCRIPT_GIT_BRANCH = "main";
public static final String SCRIPT_ZIP_NAME = "build-script.zip";
public static final String BUILD_SCRIPT_NAME = "build-script";
public static final String ENV_VARS = "envVars";
}
......@@ -18,16 +22,27 @@ public class Constants {
public static class DeployConstants {
public static final String DEPLOYMENT_TEMPLATE_FILE_NAME = "k8s-deploy-template.yaml";
public static final String SERVICE_TEMPLATE_FILE_NAME = "k8s-service-template.yaml";
public static final String K8S_POD_NAMESPACE = "NAMESPACE";
public static final String K8S_POD_PORT = "PORT";
public static final String K8S_POD_REPLICAS = "REPLICAS";
public static final String K8S_POD_MEMORY_LIMIT = "MEMORY_LIMIT";
public static final String K8S_POD_MEMORY_REQUEST = "MEMORY_REQUEST";
public static final String K8S_POD_NODE_TAG = "NODE_TAG";
public static final String K8S_SERVICE_MODE = "SERVICE_MODE";
public static final String K8S_SERVICE_NAMESPACE = "SERVICE_NAMESPACE";
public static final String K8S_SERVICE_NAME = "SERVICE_NAME";
public static final String K8S_SERVICE_PORT = "SERVICE_PORT";
}
......@@ -35,12 +50,19 @@ public class Constants {
public static class DockerConstants {
public static final String BUILD_INFO_FILE_NAME = "dockerBuildInfo";
public static final String DOCKERFILE_NAME = "Dockerfile";
public static final String IMAGE = "IMAGE";
public static final String REGISTRY = "REGISTRY";
public static final String APP_NAME = "APP_NAME";
public static final String VERSION = "VERSION";
public static final String JAVA_OPTS = "JAVA_OPTS";
public static final String DISABLE_SKYWALKING_OPTIONS = "-Dskywalking.agent.enable=false";
}
......@@ -48,7 +70,9 @@ public class Constants {
public static class GitConstants {
public static final String GIT_PROPERTIES_FILE = "git.properties";
public static final String GIT_BRANCH = "git.branch";
public static final String GIT_COMMITTER = "git.commit.user.name";
}
......
......@@ -34,11 +34,8 @@ public class ApolloConfigurationInitializerEnvironmentPostProcessor extends Logg
private static Map<String, Object> INIT_PROPERTIES = new LinkedHashMap<>();
private final ConfigurablePropertiesLoader configurablePropertiesLoader;
public ApolloConfigurationInitializerEnvironmentPostProcessor(DeferredLogFactory deferredLogFactory, ConfigurableBootstrapContext bootstrapContext) {
super(deferredLogFactory, bootstrapContext);
this.configurablePropertiesLoader = new ConfigurablePropertiesLoader(deferredLogFactory);
}
@Override
......@@ -48,7 +45,7 @@ public class ApolloConfigurationInitializerEnvironmentPostProcessor extends Logg
return;
}
setRequiredProperty(environment);
configurablePropertiesLoader.load(environment, application);
new ConfigurablePropertiesLoader(deferredLogFactory, environment, application).load();
}
@Override
......
package com.schbrain.framework.autoconfigure.apollo;
import cn.hutool.core.thread.GlobalThreadPool;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;
import com.schbrain.common.util.properties.OrderedMapPropertySource;
import com.schbrain.common.util.support.ConfigurableProperties;
import com.schbrain.framework.autoconfigure.apollo.listener.PropertiesPreparedEvent;
import com.schbrain.framework.autoconfigure.apollo.listener.PropertiesPreparedEventListener;
import com.schbrain.framework.autoconfigure.apollo.event.ConcurrentEventMulticaster;
import com.schbrain.framework.autoconfigure.apollo.event.PropertiesPreparedEvent;
import com.schbrain.framework.autoconfigure.apollo.event.listener.PropertiesPreparedEventListener;
import com.schbrain.framework.autoconfigure.apollo.properties.ApolloProperties;
import com.schbrain.framework.autoconfigure.apollo.util.ConfigUtils;
import org.apache.commons.collections4.CollectionUtils;
......@@ -14,13 +14,12 @@ import org.apache.commons.logging.Log;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.logging.DeferredLogFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.context.event.SimpleApplicationEventMulticaster;
import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.util.ClassUtils;
import java.util.List;
import java.util.Set;
import static org.springframework.core.io.support.SpringFactoriesLoader.loadFactories;
......@@ -35,23 +34,29 @@ class ConfigurablePropertiesLoader {
*/
private static final String PROPERTIES_PROPERTY_SOURCE = "ConfigurablePropertiesPropertySource";
private final Log log;
private final DeferredLogFactory deferredLogFactory;
private final Log log;
private final ConfigurableEnvironment environment;
ConfigurablePropertiesLoader(DeferredLogFactory deferredLogFactory) {
this.deferredLogFactory = deferredLogFactory;
private final SpringApplication application;
ConfigurablePropertiesLoader(DeferredLogFactory deferredLogFactory, ConfigurableEnvironment environment, SpringApplication application) {
this.log = deferredLogFactory.getLog(ConfigurablePropertiesLoader.class);
this.deferredLogFactory = deferredLogFactory;
this.environment = environment;
this.application = application;
}
void load(ConfigurableEnvironment environment, SpringApplication application) {
void load() {
List<ConfigurableProperties> configurableProperties = loadFactories(ConfigurableProperties.class, getClass().getClassLoader());
if (CollectionUtils.isEmpty(configurableProperties)) {
log.warn("There is no configuration properties found");
return;
}
ApplicationEventMulticaster eventMulticaster = createEventMulticaster(application);
ConcurrentEventMulticaster eventMulticaster = createEventMulticaster(application.getListeners());
ApolloProperties apolloProperties = ApolloProperties.get(environment);
......@@ -71,20 +76,23 @@ class ConfigurablePropertiesLoader {
log.warn("No configuration properties loaded under namespace: " + namespace);
return;
}
ConfigUtils.resolvePlaceHolders(environment, propertySource);
// early add to environment to support properties bind
compositePropertySource.addPropertySource(propertySource);
ConfigurableProperties boundProperties = properties.bind(environment);
eventMulticaster.multicastEvent(new PropertiesPreparedEvent(environment, deferredLogFactory, propertySource, boundProperties, application));
// resolve any placeHolders
ConfigUtils.resolvePlaceHolders(environment, propertySource);
// multicast event
eventMulticaster.multicastEvent(createEvent(propertySource, properties));
});
}
private ApplicationEventMulticaster createEventMulticaster(SpringApplication application) {
SimpleApplicationEventMulticaster eventMulticaster = new SimpleApplicationEventMulticaster();
eventMulticaster.setTaskExecutor(GlobalThreadPool.getExecutor());
for (ApplicationListener<?> listener : application.getListeners()) {
private PropertiesPreparedEvent createEvent(OrderedMapPropertySource propertySource, ConfigurableProperties properties) {
ConfigurableProperties boundProperties = properties.bind(environment);
return new PropertiesPreparedEvent(environment, deferredLogFactory, propertySource, boundProperties, application);
}
private ConcurrentEventMulticaster createEventMulticaster(Set<ApplicationListener<?>> listeners) {
ConcurrentEventMulticaster eventMulticaster = new ConcurrentEventMulticaster();
for (ApplicationListener<?> listener : listeners) {
if (ClassUtils.isAssignableValue(PropertiesPreparedEventListener.class, listener)) {
eventMulticaster.addApplicationListener(listener);
}
......
package com.schbrain.framework.autoconfigure.apollo.event;
import cn.hutool.core.thread.GlobalThreadPool;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.AbstractApplicationEventMulticaster;
import org.springframework.context.event.SimpleApplicationEventMulticaster;
import org.springframework.core.ResolvableType;
import org.springframework.scheduling.support.TaskUtils;
import java.util.Collection;
import java.util.concurrent.Executor;
/**
* expose {@link AbstractApplicationEventMulticaster#getApplicationListeners(ApplicationEvent, ResolvableType)}
*
* @author liaozan
* @since 2023-05-06
*/
public class ConcurrentEventMulticaster extends SimpleApplicationEventMulticaster {
public ConcurrentEventMulticaster() {
this(GlobalThreadPool.getExecutor());
}
public ConcurrentEventMulticaster(Executor executor) {
setTaskExecutor(executor);
setErrorHandler(TaskUtils.LOG_AND_PROPAGATE_ERROR_HANDLER);
}
@Override
public Collection<ApplicationListener<?>> getApplicationListeners() {
return super.getApplicationListeners();
}
}
\ No newline at end of file
package com.schbrain.framework.autoconfigure.apollo.listener;
package com.schbrain.framework.autoconfigure.apollo.event;
import com.schbrain.common.util.properties.OrderedMapPropertySource;
import com.schbrain.common.util.support.ConfigurableProperties;
......
package com.schbrain.framework.autoconfigure.apollo.listener;
package com.schbrain.framework.autoconfigure.apollo.event.listener;
import com.schbrain.common.util.support.ConfigurableProperties;
import com.schbrain.framework.autoconfigure.apollo.event.PropertiesPreparedEvent;
import org.apache.commons.logging.Log;
import org.springframework.core.ResolvableType;
......
package com.schbrain.framework.autoconfigure.apollo.listener;
package com.schbrain.framework.autoconfigure.apollo.event.listener;
import com.schbrain.framework.autoconfigure.apollo.event.PropertiesPreparedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.Ordered;
......
......@@ -18,10 +18,12 @@ public class CacheProperties extends ConfigurableProperties {
* cache prefix
*/
private String prefix;
/**
* cache prefix delimiter
*/
private String delimiter = ":";
/**
* whatever to enable prefix append
*/
......
......@@ -3,8 +3,8 @@ package com.schbrain.framework.autoconfigure.dubbo.listener;
import com.alibaba.fastjson2.JSONFactory;
import com.google.common.collect.Maps;
import com.schbrain.common.util.ApplicationName;
import com.schbrain.framework.autoconfigure.apollo.listener.GenericPropertiesPreparedEventListener;
import com.schbrain.framework.autoconfigure.apollo.listener.PropertiesPreparedEvent;
import com.schbrain.framework.autoconfigure.apollo.event.PropertiesPreparedEvent;
import com.schbrain.framework.autoconfigure.apollo.event.listener.GenericPropertiesPreparedEventListener;
import com.schbrain.framework.autoconfigure.dubbo.properties.DubboProperties;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.spring.ConfigCenterBean;
......
......@@ -7,7 +7,8 @@ import ch.qos.logback.core.*;
import ch.qos.logback.core.rolling.RollingFileAppender;
import ch.qos.logback.core.rolling.TimeBasedRollingPolicy;
import cn.hutool.json.JSONObject;
import com.schbrain.common.util.*;
import com.schbrain.common.util.ApplicationName;
import com.schbrain.common.util.EnvUtils;
import com.schbrain.common.util.InetUtils.HostInfo;
import com.schbrain.framework.autoconfigure.logger.logstash.EnhancedLogstashEncoder;
import com.schbrain.framework.autoconfigure.logger.properties.LoggerProperties;
......@@ -36,12 +37,17 @@ import java.util.List;
public class LoggerConfigurationInitializer {
private final ConfigurableEnvironment environment;
private final LoggerProperties properties;
private final HostInfo hostInfo;
private final String applicationName;
public LoggerConfigurationInitializer(ConfigurableEnvironment environment, LoggerProperties properties) {
public LoggerConfigurationInitializer(ConfigurableEnvironment environment, LoggerProperties properties, HostInfo hostInfo) {
this.environment = environment;
this.properties = properties;
this.hostInfo = hostInfo;
this.applicationName = ApplicationName.get(environment);
this.init();
}
......@@ -114,7 +120,6 @@ public class LoggerConfigurationInitializer {
}
private String getCustomFields() {
HostInfo hostInfo = InetUtils.findFirstNonLoopBackHostInfo();
JSONObject customFields = new JSONObject();
customFields.set("appName", applicationName);
customFields.set("hostName", hostInfo.getHostname());
......
......@@ -8,8 +8,8 @@ import com.ctrip.framework.apollo.core.enums.ConfigFileFormat;
import com.google.common.collect.Maps;
import com.schbrain.common.util.InetUtils;
import com.schbrain.common.util.InetUtils.HostInfo;
import com.schbrain.framework.autoconfigure.apollo.listener.GenericPropertiesPreparedEventListener;
import com.schbrain.framework.autoconfigure.apollo.listener.PropertiesPreparedEvent;
import com.schbrain.framework.autoconfigure.apollo.event.PropertiesPreparedEvent;
import com.schbrain.framework.autoconfigure.apollo.event.listener.GenericPropertiesPreparedEventListener;
import com.schbrain.framework.autoconfigure.logger.LoggerConfigurationInitializer;
import com.schbrain.framework.autoconfigure.logger.properties.LoggerProperties;
import org.springframework.core.env.ConfigurableEnvironment;
......@@ -30,14 +30,17 @@ public class LoggerPropertiesPreparedEventListener extends GenericPropertiesPrep
@Override
protected void onPropertiesPrepared(PropertiesPreparedEvent event, LoggerProperties properties) {
ConfigurableEnvironment environment = event.getEnvironment();
Map<String, String> hostInfoProperties = buildHostInfoProperties();
HostInfo hostInfo = InetUtils.findFirstNonLoopBackHostInfo();
Map<String, String> hostInfoProperties = buildHostInfoProperties(hostInfo);
event.getPropertySource().addProperties(hostInfoProperties);
configLoggingFileLocation(environment, properties.getLogConfigNamespace());
new LoggerConfigurationInitializer(environment, properties).init();
new LoggerConfigurationInitializer(environment, properties, hostInfo).init();
}
private Map<String, String> buildHostInfoProperties() {
HostInfo hostInfo = InetUtils.findFirstNonLoopBackHostInfo();
/**
* hostInfo properties, for logging pattern
*/
private Map<String, String> buildHostInfoProperties(HostInfo hostInfo) {
Map<String, String> properties = Maps.newHashMapWithExpectedSize(2);
properties.put("application.hostname", hostInfo.getHostname());
properties.put("application.ipAddress", hostInfo.getIpAddress());
......
......@@ -3,12 +3,12 @@ package com.schbrain.framework.autoconfigure.logger.logstash;
import ch.qos.logback.classic.spi.ILoggingEvent;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.schbrain.common.constants.DateTimeFormatters;
import net.logstash.logback.composite.AbstractFieldJsonProvider;
import net.logstash.logback.composite.JsonWritingUtils;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
* @author liaozan
......@@ -16,8 +16,7 @@ import java.time.format.DateTimeFormatter;
*/
public class EventDateStringValueJsonProvider extends AbstractFieldJsonProvider<ILoggingEvent> {
public static final String FIELD_EVENT_DATE = "eventDate";
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy.MM.dd");
private static final String FIELD_EVENT_DATE = "eventDate";
public EventDateStringValueJsonProvider() {
setFieldName(FIELD_EVENT_DATE);
......@@ -30,7 +29,7 @@ public class EventDateStringValueJsonProvider extends AbstractFieldJsonProvider<
private String getEventDate(ILoggingEvent event) {
LocalDateTime eventTime = LocalDateTimeUtil.of(event.getTimeStamp());
return DATE_TIME_FORMATTER.format(eventTime);
return DateTimeFormatters.DATE_WITH_DOT.format(eventTime);
}
}
}
\ No newline at end of file
......@@ -10,30 +10,37 @@ public class MybatisConstants {
* 主键
*/
public static final String ID = "id";
/**
* 创建时间
*/
public static final String CREATE_TIME = "create_time";
/**
* 修改时间
*/
public static final String MODIFY_TIME = "modify_time";
/**
* 是否删除
*/
public static final String DELETED = "deleted";
/**
* 删除版本
*/
public static final String DELETE_VERSION = "delete_version";
/**
* 当前时间戳
*/
public static final String CURRENT_TIMESTAMP = "current_timestamp";
/**
* 自增
*/
public static final String AUTO_INCREMENT = "auto_increment";
/**
* 更新为当前时间戳
*/
......
......@@ -13,22 +13,27 @@ public class ColumnMeta {
* 表名
*/
private String tableName;
/**
* 列名
*/
private String columnName;
/**
* 数据类型
*/
private String dataType;
/**
* 是否允许为空
*/
private boolean nullable;
/**
* 列默认值
*/
private String columnDefault;
/**
* 扩展信息
*/
......
......@@ -59,6 +59,7 @@ public class Table {
public static class FieldInfo {
private String field;
private String column;
public FieldInfo(TableFieldInfo tableFieldInfo) {
......
......@@ -19,6 +19,7 @@ public class DataSourceConnectionPostProcessor extends GenericBeanPostProcessor<
// use ObjectProvider to avoid early initialization beans
private final ObjectProvider<DataSourceCustomizer> customizers;
private final ObjectProvider<DataSourceConnectionProperties> connectionProperties;
public DataSourceConnectionPostProcessor(ObjectProvider<DataSourceCustomizer> customizers,
......
......@@ -22,30 +22,37 @@ public class DataSourceConnectionProperties {
* 使用 ssl 连接
*/
private Boolean useSsl = false;
/**
* tinyint(1) 视为 boolean
*/
private Boolean tinyInt1isBit = true;
/**
* 重写批处理sql
*/
private Boolean rewriteBatchedStatements = true;
/**
* 是否允许一个 statement 用分号分割执行多个查询语句
*/
private Boolean allowMultiQueries = true;
/**
* 允许从服务端获取公钥进行连接
*/
private Boolean allowPublicKeyRetrieval = true;
/**
* 连接数据库使用的时区
*/
private ZoneId serverTimeZone = ZoneId.systemDefault();
/**
* 时间格式字段值为 0 的时候的处理方式
*/
private ZeroDatetimeBehavior zeroDatetimeBehavior = ZeroDatetimeBehavior.CONVERT_TO_NULL;
/**
* 数据库连接字符编码
*/
......
......@@ -18,14 +18,17 @@ public class MybatisProperties extends ConfigurableProperties {
* 分页拦截器
*/
private boolean addPageInterceptor = true;
/**
* 阻断全表更新操作,禁止不带 where 更新,删除
*/
private boolean addBlockAttackInterceptor = true;
/**
* 是否开启表约束检查
*/
private boolean enableTableConstraintCheck = true;
/**
* Instant 转为 long
*/
......
......@@ -14,12 +14,15 @@ public class OssOperationResult implements Serializable {
private static final long serialVersionUID = 3651584115463313214L;
protected boolean success;
protected String bucket;
protected String objectKey;
protected String errorMsg;
public boolean isFailed() {
return !success;
return Boolean.FALSE.equals(success);
}
}
\ No newline at end of file
......@@ -18,8 +18,11 @@ public class UploadCredentials extends OssOperationResult {
private static final long serialVersionUID = 5546792221041679671L;
private String accessKeyId;
private String accessKeySecret;
private String securityToken;
private LocalDateTime expiration;
// for json deserialize
......
......@@ -42,9 +42,13 @@ import java.util.stream.Collectors;
public class OssUtils {
private static OSSClient ossClient;
private static DefaultAcsClient stsAcsClient;
private static OssProperties ossProperties;
private static StsProperties stsProperties;
private static String directory;
public static void initialize(OssProperties properties) {
......
......@@ -22,9 +22,13 @@ public class BaseMapper {
private final SqlSessionTemplate sqlSession;
private final Class<?> mapperInterface;
private final BaseMapperStatement bms;
private Class<?> domainClass;
private String tableName;
private Field[] fields;
public BaseMapper(SqlSessionTemplate sqlSession, Class<?> mapperInterface) {
......
......@@ -38,9 +38,13 @@ public class BaseMapperStatement {
private final Class<?> domainClass;
private final Field[] fields;
private final List<ResultMap> objectResultMapList = new ArrayList<>(1);
private final List<ResultMap> intResultMapList = new ArrayList<>(1);
private String selectClause;
private String insertClause;
public BaseMapperStatement(Configuration configuration, Class<?> mapperInterface, Class<?> domainClass, String tableName, Field[] fields) {
......
......@@ -20,7 +20,9 @@ import java.util.regex.Pattern;
public abstract class AbstractSqlSource implements SqlSource {
private static final String GENERIC_PARAM_NAME = "param";
private static final Pattern pattern = Pattern.compile("#\\{.+?}");
protected final Configuration configuration;
protected AbstractSqlSource(Configuration configuration) {
......
......@@ -2,11 +2,10 @@ package com.schbrain.framework.support.spring;
import lombok.Getter;
import org.apache.commons.logging.Log;
import org.springframework.boot.BootstrapContext;
import org.springframework.boot.BootstrapContextClosedEvent;
import org.springframework.boot.ConfigurableBootstrapContext;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.boot.logging.DeferredLogFactory;
import org.springframework.context.ConfigurableApplicationContext;
/**
* @author liaozan
......@@ -16,17 +15,19 @@ import org.springframework.context.ConfigurableApplicationContext;
public abstract class LoggerAwareEnvironmentPostProcessor implements EnvironmentPostProcessor {
protected final Log log;
protected final DeferredLogFactory deferredLogFactory;
protected final ConfigurableBootstrapContext bootstrapContext;
public LoggerAwareEnvironmentPostProcessor(DeferredLogFactory logFactory, ConfigurableBootstrapContext bootstrapContext) {
this.log = logFactory.getLog(getClass());
this.bootstrapContext = bootstrapContext;
this.deferredLogFactory = logFactory;
this.bootstrapContext.addCloseListener(event -> onBootstrapContextClose(event.getBootstrapContext(), event.getApplicationContext()));
this.bootstrapContext.addCloseListener(this::onBootstrapContextClose);
}
protected void onBootstrapContextClose(BootstrapContext bootstrapContext, ConfigurableApplicationContext applicationContext) {
protected void onBootstrapContextClose(BootstrapContextClosedEvent event) {
}
......
......@@ -31,6 +31,7 @@ public class DefaultPropertiesEnvironmentPostProcessor extends LoggerAwareEnviro
public static final Integer DEFAULT_ORDER = ConfigDataEnvironmentPostProcessor.ORDER + 1;
private static final String SPRING_PROFILE_ACTIVE = "spring.profiles.active";
private static final String DUBBO_REGISTER_KEY = "dubbo.registry.register";
public DefaultPropertiesEnvironmentPostProcessor(DeferredLogFactory logFactory, ConfigurableBootstrapContext bootstrapContext) {
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment