proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
pig-mesh_pig
|
pig/pig-auth/src/main/java/com/pig4cloud/pig/auth/support/sms/OAuth2ResourceOwnerSmsAuthenticationProvider.java
|
OAuth2ResourceOwnerSmsAuthenticationProvider
|
checkClient
|
class OAuth2ResourceOwnerSmsAuthenticationProvider
extends OAuth2ResourceOwnerBaseAuthenticationProvider<OAuth2ResourceOwnerSmsAuthenticationToken> {
private static final Logger LOGGER = LogManager.getLogger(OAuth2ResourceOwnerSmsAuthenticationProvider.class);
/**
* Constructs an {@code OAuth2AuthorizationCodeAuthenticationProvider} using the
* provided parameters.
* @param authenticationManager
* @param authorizationService the authorization service
* @param tokenGenerator the token generator
* @since 0.2.3
*/
public OAuth2ResourceOwnerSmsAuthenticationProvider(AuthenticationManager authenticationManager,
OAuth2AuthorizationService authorizationService,
OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator) {
super(authenticationManager, authorizationService, tokenGenerator);
}
@Override
public boolean supports(Class<?> authentication) {
boolean supports = OAuth2ResourceOwnerSmsAuthenticationToken.class.isAssignableFrom(authentication);
LOGGER.debug("supports authentication=" + authentication + " returning " + supports);
return supports;
}
@Override
public void checkClient(RegisteredClient registeredClient) {<FILL_FUNCTION_BODY>}
@Override
public UsernamePasswordAuthenticationToken buildToken(Map<String, Object> reqParameters) {
String phone = (String) reqParameters.get(SecurityConstants.SMS_PARAMETER_NAME);
return new UsernamePasswordAuthenticationToken(phone, null);
}
}
|
assert registeredClient != null;
if (!registeredClient.getAuthorizationGrantTypes()
.contains(new AuthorizationGrantType(SecurityConstants.MOBILE))) {
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.UNAUTHORIZED_CLIENT);
}
| 372
| 78
| 450
|
<methods>public void <init>(org.springframework.security.authentication.AuthenticationManager, OAuth2AuthorizationService, OAuth2TokenGenerator<? extends OAuth2Token>) ,public org.springframework.security.core.Authentication authenticate(org.springframework.security.core.Authentication) throws org.springframework.security.core.AuthenticationException,public abstract org.springframework.security.authentication.UsernamePasswordAuthenticationToken buildToken(Map<java.lang.String,java.lang.Object>) ,public abstract void checkClient(RegisteredClient) ,public void setRefreshTokenGenerator(Supplier<java.lang.String>) ,public abstract boolean supports(Class<?>) <variables>private static final java.lang.String ERROR_URI,private static final org.apache.logging.log4j.Logger LOGGER,private final non-sealed org.springframework.security.authentication.AuthenticationManager authenticationManager,private final non-sealed OAuth2AuthorizationService authorizationService,private final non-sealed org.springframework.context.support.MessageSourceAccessor messages,private Supplier<java.lang.String> refreshTokenGenerator,private final non-sealed OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator
|
pig-mesh_pig
|
pig/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/config/JacksonConfiguration.java
|
JacksonConfiguration
|
customizer
|
class JacksonConfiguration {
@Bean
@ConditionalOnMissingBean
public Jackson2ObjectMapperBuilderCustomizer customizer() {<FILL_FUNCTION_BODY>}
}
|
return builder -> {
builder.locale(Locale.CHINA);
builder.timeZone(TimeZone.getTimeZone(ZoneId.systemDefault()));
builder.simpleDateFormat(DatePattern.NORM_DATETIME_PATTERN);
builder.serializerByType(Long.class, ToStringSerializer.instance);
builder.modules(new PigJavaTimeModule());
};
| 44
| 106
| 150
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/config/RedisTemplateConfiguration.java
|
RedisTemplateConfiguration
|
redisTemplate
|
class RedisTemplateConfiguration {
@Bean
@Primary
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {<FILL_FUNCTION_BODY>}
@Bean
public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForHash();
}
@Bean
public ValueOperations<String, String> valueOperations(RedisTemplate<String, String> redisTemplate) {
return redisTemplate.opsForValue();
}
@Bean
public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForList();
}
@Bean
public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForSet();
}
@Bean
public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForZSet();
}
}
|
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setKeySerializer(RedisSerializer.string());
redisTemplate.setHashKeySerializer(RedisSerializer.string());
redisTemplate.setValueSerializer(RedisSerializer.java());
redisTemplate.setHashValueSerializer(RedisSerializer.java());
redisTemplate.setConnectionFactory(factory);
return redisTemplate;
| 275
| 114
| 389
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/config/TaskExecutorConfiguration.java
|
TaskExecutorConfiguration
|
getAsyncExecutor
|
class TaskExecutorConfiguration implements AsyncConfigurer {
/**
* 获取当前机器的核数, 不一定准确 请根据实际场景 CPU密集 || IO 密集
*/
public static final int cpuNum = Runtime.getRuntime().availableProcessors();
@Value("${thread.pool.corePoolSize:}")
private Optional<Integer> corePoolSize;
@Value("${thread.pool.maxPoolSize:}")
private Optional<Integer> maxPoolSize;
@Value("${thread.pool.queueCapacity:}")
private Optional<Integer> queueCapacity;
@Value("${thread.pool.awaitTerminationSeconds:}")
private Optional<Integer> awaitTerminationSeconds;
@Override
@Bean
public Executor getAsyncExecutor() {<FILL_FUNCTION_BODY>}
}
|
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
// 核心线程大小 默认区 CPU 数量
taskExecutor.setCorePoolSize(corePoolSize.orElse(cpuNum));
// 最大线程大小 默认区 CPU * 2 数量
taskExecutor.setMaxPoolSize(maxPoolSize.orElse(cpuNum * 2));
// 队列最大容量
taskExecutor.setQueueCapacity(queueCapacity.orElse(500));
taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
taskExecutor.setAwaitTerminationSeconds(awaitTerminationSeconds.orElse(60));
taskExecutor.setThreadNamePrefix("PIG-Thread-");
taskExecutor.initialize();
return taskExecutor;
| 204
| 232
| 436
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/config/WebMvcConfiguration.java
|
WebMvcConfiguration
|
addFormatters
|
class WebMvcConfiguration implements WebMvcConfigurer {
/**
* 增加GET请求参数中时间类型转换 {@link com.pig4cloud.pig.common.core.jackson.PigJavaTimeModule}
* <ul>
* <li>HH:mm:ss -> LocalTime</li>
* <li>yyyy-MM-dd -> LocalDate</li>
* <li>yyyy-MM-dd HH:mm:ss -> LocalDateTime</li>
* </ul>
* @param registry
*/
@Override
public void addFormatters(FormatterRegistry registry) {<FILL_FUNCTION_BODY>}
/**
* 系统国际化文件配置
* @return MessageSource
*/
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:i18n/messages");
return messageSource;
}
}
|
DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
registrar.setTimeFormatter(DatePattern.NORM_TIME_FORMATTER);
registrar.setDateFormatter(DatePattern.NORM_DATE_FORMATTER);
registrar.setDateTimeFormatter(DatePattern.NORM_DATETIME_FORMATTER);
registrar.registerFormatters(registry);
| 256
| 105
| 361
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/factory/YamlPropertySourceFactory.java
|
YamlPropertySourceFactory
|
createPropertySource
|
class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {<FILL_FUNCTION_BODY>}
private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
try {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource.getResource());
factory.afterPropertiesSet();
return factory.getObject();
}
catch (IllegalStateException e) {
Throwable cause = e.getCause();
if (cause instanceof FileNotFoundException) {
throw (FileNotFoundException) e.getCause();
}
throw e;
}
}
}
|
Properties propertiesFromYaml = loadYamlIntoProperties(resource);
String sourceName = name != null ? name : resource.getResource().getFilename();
return new PropertiesPropertySource(sourceName, propertiesFromYaml);
| 194
| 59
| 253
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/servlet/RepeatBodyRequestWrapper.java
|
RepeatBodyRequestWrapper
|
getByteBody
|
class RepeatBodyRequestWrapper extends HttpServletRequestWrapper {
private final byte[] bodyByteArray;
private final Map<String, String[]> parameterMap;
public RepeatBodyRequestWrapper(HttpServletRequest request) {
super(request);
this.bodyByteArray = getByteBody(request);
this.parameterMap = super.getParameterMap();
}
@Override
public BufferedReader getReader() {
return ObjectUtils.isEmpty(this.bodyByteArray) ? null
: new BufferedReader(new InputStreamReader(getInputStream()));
}
@Override
public ServletInputStream getInputStream() {
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(this.bodyByteArray);
return new ServletInputStream() {
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setReadListener(ReadListener readListener) {
// doNoting
}
@Override
public int read() {
return byteArrayInputStream.read();
}
};
}
private static byte[] getByteBody(HttpServletRequest request) {<FILL_FUNCTION_BODY>}
/**
* 重写 getParameterMap() 方法 解决 undertow 中流被读取后,会进行标记,从而导致无法正确获取 body 中的表单数据的问题
* @return Map<String, String [ ]> parameterMap
*/
@Override
public Map<String, String[]> getParameterMap() {
return this.parameterMap;
}
}
|
byte[] body = new byte[0];
try {
body = StreamUtils.copyToByteArray(request.getInputStream());
}
catch (IOException e) {
log.error("解析流中数据异常", e);
}
return body;
| 399
| 74
| 473
|
<methods>public void <init>(jakarta.servlet.http.HttpServletRequest) ,public boolean authenticate(jakarta.servlet.http.HttpServletResponse) throws java.io.IOException, jakarta.servlet.ServletException,public java.lang.String changeSessionId() ,public java.lang.String getAuthType() ,public java.lang.String getContextPath() ,public jakarta.servlet.http.Cookie[] getCookies() ,public long getDateHeader(java.lang.String) ,public java.lang.String getHeader(java.lang.String) ,public Enumeration<java.lang.String> getHeaderNames() ,public Enumeration<java.lang.String> getHeaders(java.lang.String) ,public jakarta.servlet.http.HttpServletMapping getHttpServletMapping() ,public int getIntHeader(java.lang.String) ,public java.lang.String getMethod() ,public jakarta.servlet.http.Part getPart(java.lang.String) throws java.io.IOException, jakarta.servlet.ServletException,public Collection<jakarta.servlet.http.Part> getParts() throws java.io.IOException, jakarta.servlet.ServletException,public java.lang.String getPathInfo() ,public java.lang.String getPathTranslated() ,public java.lang.String getQueryString() ,public java.lang.String getRemoteUser() ,public java.lang.String getRequestURI() ,public java.lang.StringBuffer getRequestURL() ,public java.lang.String getRequestedSessionId() ,public java.lang.String getServletPath() ,public jakarta.servlet.http.HttpSession getSession() ,public jakarta.servlet.http.HttpSession getSession(boolean) ,public Map<java.lang.String,java.lang.String> getTrailerFields() ,public java.security.Principal getUserPrincipal() ,public boolean isRequestedSessionIdFromCookie() ,public boolean isRequestedSessionIdFromURL() ,public boolean isRequestedSessionIdValid() ,public boolean isTrailerFieldsReady() ,public boolean isUserInRole(java.lang.String) ,public void login(java.lang.String, java.lang.String) throws jakarta.servlet.ServletException,public void logout() throws jakarta.servlet.ServletException,public jakarta.servlet.http.PushBuilder newPushBuilder() ,public T upgrade(Class<T>) throws java.io.IOException, jakarta.servlet.ServletException<variables>
|
pig-mesh_pig
|
pig/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/util/ClassUtils.java
|
ClassUtils
|
getAnnotation
|
class ClassUtils extends org.springframework.util.ClassUtils {
private final ParameterNameDiscoverer PARAMETERNAMEDISCOVERER = new DefaultParameterNameDiscoverer();
/**
* 获取方法参数信息
* @param constructor 构造器
* @param parameterIndex 参数序号
* @return {MethodParameter}
*/
public MethodParameter getMethodParameter(Constructor<?> constructor, int parameterIndex) {
MethodParameter methodParameter = new SynthesizingMethodParameter(constructor, parameterIndex);
methodParameter.initParameterNameDiscovery(PARAMETERNAMEDISCOVERER);
return methodParameter;
}
/**
* 获取方法参数信息
* @param method 方法
* @param parameterIndex 参数序号
* @return {MethodParameter}
*/
public MethodParameter getMethodParameter(Method method, int parameterIndex) {
MethodParameter methodParameter = new SynthesizingMethodParameter(method, parameterIndex);
methodParameter.initParameterNameDiscovery(PARAMETERNAMEDISCOVERER);
return methodParameter;
}
/**
* 获取Annotation
* @param method Method
* @param annotationType 注解类
* @param <A> 泛型标记
* @return {Annotation}
*/
public <A extends Annotation> A getAnnotation(Method method, Class<A> annotationType) {<FILL_FUNCTION_BODY>}
/**
* 获取Annotation
* @param handlerMethod HandlerMethod
* @param annotationType 注解类
* @param <A> 泛型标记
* @return {Annotation}
*/
public <A extends Annotation> A getAnnotation(HandlerMethod handlerMethod, Class<A> annotationType) {
// 先找方法,再找方法上的类
A annotation = handlerMethod.getMethodAnnotation(annotationType);
if (null != annotation) {
return annotation;
}
// 获取类上面的Annotation,可能包含组合注解,故采用spring的工具类
Class<?> beanType = handlerMethod.getBeanType();
return AnnotatedElementUtils.findMergedAnnotation(beanType, annotationType);
}
}
|
Class<?> targetClass = method.getDeclaringClass();
// The method may be on an interface, but we need attributes from the target
// class.
// If the target class is null, the method will be unchanged.
Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
// If we are dealing with method with generic parameters, find the original
// method.
specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
// 先找方法,再找方法上的类
A annotation = AnnotatedElementUtils.findMergedAnnotation(specificMethod, annotationType);
;
if (null != annotation) {
return annotation;
}
// 获取类上面的Annotation,可能包含组合注解,故采用spring的工具类
return AnnotatedElementUtils.findMergedAnnotation(specificMethod.getDeclaringClass(), annotationType);
| 546
| 227
| 773
|
<methods>public void <init>() ,public static java.lang.String addResourcePathToPackagePath(Class<?>, java.lang.String) ,public static transient java.lang.String classNamesToString(Class<?>[]) ,public static java.lang.String classNamesToString(Collection<Class<?>>) ,public static java.lang.String classPackageAsResourcePath(Class<?>) ,public static java.lang.String convertClassNameToResourcePath(java.lang.String) ,public static java.lang.String convertResourcePathToClassName(java.lang.String) ,public static Class<?> createCompositeInterface(Class<?>[], java.lang.ClassLoader) ,public static Class<?> determineCommonAncestor(Class<?>, Class<?>) ,public static Class<?> forName(java.lang.String, java.lang.ClassLoader) throws java.lang.ClassNotFoundException, java.lang.LinkageError,public static Class<?>[] getAllInterfaces(java.lang.Object) ,public static Set<Class<?>> getAllInterfacesAsSet(java.lang.Object) ,public static Class<?>[] getAllInterfacesForClass(Class<?>) ,public static Class<?>[] getAllInterfacesForClass(Class<?>, java.lang.ClassLoader) ,public static Set<Class<?>> getAllInterfacesForClassAsSet(Class<?>) ,public static Set<Class<?>> getAllInterfacesForClassAsSet(Class<?>, java.lang.ClassLoader) ,public static java.lang.String getClassFileName(Class<?>) ,public static transient Constructor<T> getConstructorIfAvailable(Class<T>, Class<?>[]) ,public static java.lang.ClassLoader getDefaultClassLoader() ,public static java.lang.String getDescriptiveType(java.lang.Object) ,public static java.lang.reflect.Method getInterfaceMethodIfPossible(java.lang.reflect.Method) ,public static java.lang.reflect.Method getInterfaceMethodIfPossible(java.lang.reflect.Method, Class<?>) ,public static transient java.lang.reflect.Method getMethod(Class<?>, java.lang.String, Class<?>[]) ,public static int getMethodCountForName(Class<?>, java.lang.String) ,public static transient java.lang.reflect.Method getMethodIfAvailable(Class<?>, java.lang.String, Class<?>[]) ,public static java.lang.reflect.Method getMostSpecificMethod(java.lang.reflect.Method, Class<?>) ,public static java.lang.String getPackageName(Class<?>) ,public static java.lang.String getPackageName(java.lang.String) ,public static java.lang.String getQualifiedMethodName(java.lang.reflect.Method) ,public static java.lang.String getQualifiedMethodName(java.lang.reflect.Method, Class<?>) ,public static java.lang.String getQualifiedName(Class<?>) ,public static java.lang.String getShortName(java.lang.String) ,public static java.lang.String getShortName(Class<?>) ,public static java.lang.String getShortNameAsProperty(Class<?>) ,public static transient java.lang.reflect.Method getStaticMethod(Class<?>, java.lang.String, Class<?>[]) ,public static Class<?> getUserClass(java.lang.Object) ,public static Class<?> getUserClass(Class<?>) ,public static boolean hasAtLeastOneMethodWithName(Class<?>, java.lang.String) ,public static transient boolean hasConstructor(Class<?>, Class<?>[]) ,public static boolean hasMethod(Class<?>, java.lang.reflect.Method) ,public static transient boolean hasMethod(Class<?>, java.lang.String, Class<?>[]) ,public static boolean isAssignable(Class<?>, Class<?>) ,public static boolean isAssignableValue(Class<?>, java.lang.Object) ,public static boolean isCacheSafe(Class<?>, java.lang.ClassLoader) ,public static boolean isCglibProxy(java.lang.Object) ,public static boolean isCglibProxyClass(Class<?>) ,public static boolean isCglibProxyClassName(java.lang.String) ,public static boolean isInnerClass(Class<?>) ,public static boolean isJavaLanguageInterface(Class<?>) ,public static boolean isLambdaClass(Class<?>) ,public static boolean isPresent(java.lang.String, java.lang.ClassLoader) ,public static boolean isPrimitiveArray(Class<?>) ,public static boolean isPrimitiveOrWrapper(Class<?>) ,public static boolean isPrimitiveWrapper(Class<?>) ,public static boolean isPrimitiveWrapperArray(Class<?>) ,public static boolean isSimpleValueType(Class<?>) ,public static boolean isStaticClass(Class<?>) ,public static boolean isUserLevelMethod(java.lang.reflect.Method) ,public static boolean isVisible(Class<?>, java.lang.ClassLoader) ,public static boolean isVoidType(Class<?>) ,public static boolean matchesTypeName(Class<?>, java.lang.String) ,public static java.lang.ClassLoader overrideThreadContextClassLoader(java.lang.ClassLoader) ,public static Class<?> resolveClassName(java.lang.String, java.lang.ClassLoader) throws java.lang.IllegalArgumentException,public static Class<?> resolvePrimitiveClassName(java.lang.String) ,public static Class<?> resolvePrimitiveIfNecessary(Class<?>) ,public static Class<?>[] toClassArray(Collection<Class<?>>) <variables>public static final java.lang.String ARRAY_SUFFIX,public static final java.lang.String CGLIB_CLASS_SEPARATOR,public static final java.lang.String CLASS_FILE_SUFFIX,private static final Class<?>[] EMPTY_CLASS_ARRAY,private static final java.lang.String INTERNAL_ARRAY_PREFIX,private static final char NESTED_CLASS_SEPARATOR,private static final int NON_OVERRIDABLE_MODIFIER,private static final java.lang.String NON_PRIMITIVE_ARRAY_PREFIX,private static final int OVERRIDABLE_MODIFIER,private static final char PACKAGE_SEPARATOR,private static final char PATH_SEPARATOR,private static final Map<java.lang.String,Class<?>> commonClassCache,private static final Map<java.lang.reflect.Method,java.lang.reflect.Method> interfaceMethodCache,private static final Set<Class<?>> javaLanguageInterfaces,private static final Map<java.lang.String,Class<?>> primitiveTypeNameMap,private static final Map<Class<?>,Class<?>> primitiveTypeToWrapperMap,private static final Map<Class<?>,Class<?>> primitiveWrapperTypeMap
|
pig-mesh_pig
|
pig/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/util/R.java
|
R
|
restResult
|
class R<T> implements Serializable {
private static final long serialVersionUID = 1L;
@Getter
@Setter
private int code;
@Getter
@Setter
private String msg;
@Getter
@Setter
private T data;
public static <T> R<T> ok() {
return restResult(null, CommonConstants.SUCCESS, null);
}
public static <T> R<T> ok(T data) {
return restResult(data, CommonConstants.SUCCESS, null);
}
public static <T> R<T> ok(T data, String msg) {
return restResult(data, CommonConstants.SUCCESS, msg);
}
public static <T> R<T> failed() {
return restResult(null, CommonConstants.FAIL, null);
}
public static <T> R<T> failed(String msg) {
return restResult(null, CommonConstants.FAIL, msg);
}
public static <T> R<T> failed(T data) {
return restResult(data, CommonConstants.FAIL, null);
}
public static <T> R<T> failed(T data, String msg) {
return restResult(data, CommonConstants.FAIL, msg);
}
public static <T> R<T> restResult(T data, int code, String msg) {<FILL_FUNCTION_BODY>}
}
|
R<T> apiResult = new R<>();
apiResult.setCode(code);
apiResult.setData(data);
apiResult.setMsg(msg);
return apiResult;
| 352
| 56
| 408
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/util/SpringContextHolder.java
|
SpringContextHolder
|
clearHolder
|
class SpringContextHolder implements ApplicationContextAware, DisposableBean {
private static ApplicationContext applicationContext = null;
/**
* 取得存储在静态变量中的ApplicationContext.
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 实现ApplicationContextAware接口, 注入Context到静态变量中.
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
SpringContextHolder.applicationContext = applicationContext;
}
/**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
return (T) applicationContext.getBean(name);
}
/**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
public static <T> T getBean(Class<T> requiredType) {
return applicationContext.getBean(requiredType);
}
/**
* 清除SpringContextHolder中的ApplicationContext为Null.
*/
public static void clearHolder() {<FILL_FUNCTION_BODY>}
/**
* 发布事件
* @param event
*/
public static void publishEvent(ApplicationEvent event) {
if (applicationContext == null) {
return;
}
applicationContext.publishEvent(event);
}
/**
* 实现DisposableBean接口, 在Context关闭时清理静态变量.
*/
@Override
@SneakyThrows
public void destroy() {
SpringContextHolder.clearHolder();
}
}
|
if (log.isDebugEnabled()) {
log.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext);
}
applicationContext = null;
| 430
| 46
| 476
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/util/WebUtils.java
|
WebUtils
|
splitClient
|
class WebUtils extends org.springframework.web.util.WebUtils {
private final String BASIC_ = "Basic ";
private final String UNKNOWN = "unknown";
/**
* 判断是否ajax请求 spring ajax 返回含有 ResponseBody 或者 RestController注解
* @param handlerMethod HandlerMethod
* @return 是否ajax请求
*/
public boolean isBody(HandlerMethod handlerMethod) {
ResponseBody responseBody = ClassUtils.getAnnotation(handlerMethod, ResponseBody.class);
return responseBody != null;
}
/**
* 读取cookie
* @param name cookie name
* @return cookie value
*/
public String getCookieVal(String name) {
if (WebUtils.getRequest().isPresent()) {
return getCookieVal(WebUtils.getRequest().get(), name);
}
return null;
}
/**
* 读取cookie
* @param request HttpServletRequest
* @param name cookie name
* @return cookie value
*/
public String getCookieVal(HttpServletRequest request, String name) {
Cookie cookie = getCookie(request, name);
return cookie != null ? cookie.getValue() : null;
}
/**
* 清除 某个指定的cookie
* @param response HttpServletResponse
* @param key cookie key
*/
public void removeCookie(HttpServletResponse response, String key) {
setCookie(response, key, null, 0);
}
/**
* 设置cookie
* @param response HttpServletResponse
* @param name cookie name
* @param value cookie value
* @param maxAgeInSeconds maxage
*/
public void setCookie(HttpServletResponse response, String name, String value, int maxAgeInSeconds) {
Cookie cookie = new Cookie(name, value);
cookie.setPath("/");
cookie.setMaxAge(maxAgeInSeconds);
cookie.setHttpOnly(true);
response.addCookie(cookie);
}
/**
* 获取 HttpServletRequest
* @return {HttpServletRequest}
*/
public Optional<HttpServletRequest> getRequest() {
return Optional
.ofNullable(((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
}
/**
* 获取 HttpServletResponse
* @return {HttpServletResponse}
*/
public HttpServletResponse getResponse() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
}
/**
* 从request 获取CLIENT_ID
* @return
*/
@SneakyThrows
public String getClientId(ServerHttpRequest request) {
String header = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
return splitClient(header)[0];
}
@SneakyThrows
public String getClientId() {
if (WebUtils.getRequest().isPresent()) {
String header = WebUtils.getRequest().get().getHeader(HttpHeaders.AUTHORIZATION);
return splitClient(header)[0];
}
return null;
}
@NotNull
private static String[] splitClient(String header) {<FILL_FUNCTION_BODY>}
}
|
if (header == null || !header.startsWith(BASIC_)) {
throw new CheckedException("请求头中client信息为空");
}
byte[] base64Token = header.substring(6).getBytes(StandardCharsets.UTF_8);
byte[] decoded;
try {
decoded = Base64.decode(base64Token);
}
catch (IllegalArgumentException e) {
throw new CheckedException("Failed to decode basic authentication token");
}
String token = new String(decoded, StandardCharsets.UTF_8);
int delim = token.indexOf(":");
if (delim == -1) {
throw new CheckedException("Invalid basic authentication token");
}
return new String[] { token.substring(0, delim), token.substring(delim + 1) };
| 823
| 226
| 1,049
|
<methods>public void <init>() ,public static void clearErrorRequestAttributes(jakarta.servlet.http.HttpServletRequest) ,public static void exposeErrorRequestAttributes(jakarta.servlet.http.HttpServletRequest, java.lang.Throwable, java.lang.String) ,public static java.lang.String findParameterValue(jakarta.servlet.ServletRequest, java.lang.String) ,public static java.lang.String findParameterValue(Map<java.lang.String,?>, java.lang.String) ,public static jakarta.servlet.http.Cookie getCookie(jakarta.servlet.http.HttpServletRequest, java.lang.String) ,public static java.lang.Boolean getDefaultHtmlEscape(jakarta.servlet.ServletContext) ,public static T getNativeRequest(jakarta.servlet.ServletRequest, Class<T>) ,public static T getNativeResponse(jakarta.servlet.ServletResponse, Class<T>) ,public static Map<java.lang.String,java.lang.Object> getParametersStartingWith(jakarta.servlet.ServletRequest, java.lang.String) ,public static java.lang.String getRealPath(jakarta.servlet.ServletContext, java.lang.String) throws java.io.FileNotFoundException,public static java.lang.Object getRequiredSessionAttribute(jakarta.servlet.http.HttpServletRequest, java.lang.String) throws java.lang.IllegalStateException,public static java.lang.Boolean getResponseEncodedHtmlEscape(jakarta.servlet.ServletContext) ,public static java.lang.Object getSessionAttribute(jakarta.servlet.http.HttpServletRequest, java.lang.String) ,public static java.lang.String getSessionId(jakarta.servlet.http.HttpServletRequest) ,public static java.lang.Object getSessionMutex(jakarta.servlet.http.HttpSession) ,public static java.io.File getTempDir(jakarta.servlet.ServletContext) ,public static boolean hasSubmitParameter(jakarta.servlet.ServletRequest, java.lang.String) ,public static boolean isIncludeRequest(jakarta.servlet.ServletRequest) ,public static boolean isSameOrigin(org.springframework.http.HttpRequest) ,public static boolean isValidOrigin(org.springframework.http.HttpRequest, Collection<java.lang.String>) ,public static MultiValueMap<java.lang.String,java.lang.String> parseMatrixVariables(java.lang.String) ,public static void removeWebAppRootSystemProperty(jakarta.servlet.ServletContext) ,public static void setSessionAttribute(jakarta.servlet.http.HttpServletRequest, java.lang.String, java.lang.Object) ,public static void setWebAppRootSystemProperty(jakarta.servlet.ServletContext) throws java.lang.IllegalStateException<variables>public static final java.lang.String CONTENT_TYPE_CHARSET_PREFIX,public static final java.lang.String DEFAULT_CHARACTER_ENCODING,public static final java.lang.String DEFAULT_WEB_APP_ROOT_KEY,public static final java.lang.String ERROR_EXCEPTION_ATTRIBUTE,public static final java.lang.String ERROR_EXCEPTION_TYPE_ATTRIBUTE,public static final java.lang.String ERROR_MESSAGE_ATTRIBUTE,public static final java.lang.String ERROR_REQUEST_URI_ATTRIBUTE,public static final java.lang.String ERROR_SERVLET_NAME_ATTRIBUTE,public static final java.lang.String ERROR_STATUS_CODE_ATTRIBUTE,public static final java.lang.String FORWARD_CONTEXT_PATH_ATTRIBUTE,public static final java.lang.String FORWARD_PATH_INFO_ATTRIBUTE,public static final java.lang.String FORWARD_QUERY_STRING_ATTRIBUTE,public static final java.lang.String FORWARD_REQUEST_URI_ATTRIBUTE,public static final java.lang.String FORWARD_SERVLET_PATH_ATTRIBUTE,public static final java.lang.String HTML_ESCAPE_CONTEXT_PARAM,public static final java.lang.String INCLUDE_CONTEXT_PATH_ATTRIBUTE,public static final java.lang.String INCLUDE_PATH_INFO_ATTRIBUTE,public static final java.lang.String INCLUDE_QUERY_STRING_ATTRIBUTE,public static final java.lang.String INCLUDE_REQUEST_URI_ATTRIBUTE,public static final java.lang.String INCLUDE_SERVLET_PATH_ATTRIBUTE,public static final java.lang.String RESPONSE_ENCODED_HTML_ESCAPE_CONTEXT_PARAM,public static final java.lang.String SESSION_MUTEX_ATTRIBUTE,public static final java.lang.String[] SUBMIT_IMAGE_SUFFIXES,public static final java.lang.String TEMP_DIR_CONTEXT_ATTRIBUTE,public static final java.lang.String WEB_APP_ROOT_KEY_PARAM
|
pig-mesh_pig
|
pig/pig-common/pig-common-datasource/src/main/java/com/pig4cloud/pig/common/datasource/DynamicDataSourceAutoConfiguration.java
|
DynamicDataSourceAutoConfiguration
|
dsProcessor
|
class DynamicDataSourceAutoConfiguration {
/**
* 动态数据源提供者
* @param defaultDataSourceCreator 默认数据源创建器
* @param stringEncryptor 字符串加密器
* @param properties 数据源配置属性
* @return 动态数据源提供者
*/
@Bean
public DynamicDataSourceProvider dynamicDataSourceProvider(DefaultDataSourceCreator defaultDataSourceCreator,
StringEncryptor stringEncryptor, DataSourceProperties properties) {
return new JdbcDynamicDataSourceProvider(defaultDataSourceCreator, stringEncryptor, properties);
}
/**
* 获取数据源处理器
* @return 数据源处理器
*/
@Bean
public DsProcessor dsProcessor(BeanFactory beanFactory) {<FILL_FUNCTION_BODY>}
/**
* 默认数据源创建器
* @param hikariDataSourceCreator Hikari数据源创建器
* @return 默认数据源创建器
*/
@Bean
public DefaultDataSourceCreator defaultDataSourceCreator(HikariDataSourceCreator hikariDataSourceCreator) {
DefaultDataSourceCreator defaultDataSourceCreator = new DefaultDataSourceCreator();
List<DataSourceCreator> creators = new ArrayList<>();
creators.add(hikariDataSourceCreator);
defaultDataSourceCreator.setCreators(creators);
return defaultDataSourceCreator;
}
/**
* 清除Ttl数据源过滤器
* @return 清除Ttl数据源过滤器
*/
@Bean
public ClearTtlDataSourceFilter clearTtlDsFilter() {
return new ClearTtlDataSourceFilter();
}
}
|
DsProcessor lastParamDsProcessor = new LastParamDsProcessor();
DsProcessor headerProcessor = new DsJakartaHeaderProcessor();
DsProcessor sessionProcessor = new DsJakartaSessionProcessor();
DsSpelExpressionProcessor spelExpressionProcessor = new DsSpelExpressionProcessor();
spelExpressionProcessor.setBeanResolver(new BeanFactoryResolver(beanFactory));
lastParamDsProcessor.setNextProcessor(headerProcessor);
headerProcessor.setNextProcessor(sessionProcessor);
sessionProcessor.setNextProcessor(spelExpressionProcessor);
return lastParamDsProcessor;
| 432
| 156
| 588
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-datasource/src/main/java/com/pig4cloud/pig/common/datasource/config/JdbcDynamicDataSourceProvider.java
|
JdbcDynamicDataSourceProvider
|
executeStmt
|
class JdbcDynamicDataSourceProvider extends AbstractJdbcDataSourceProvider {
private final DataSourceProperties properties;
private final StringEncryptor stringEncryptor;
public JdbcDynamicDataSourceProvider(DefaultDataSourceCreator defaultDataSourceCreator,
StringEncryptor stringEncryptor, DataSourceProperties properties) {
super(defaultDataSourceCreator, properties.getDriverClassName(), properties.getUrl(), properties.getUsername(),
properties.getPassword());
this.stringEncryptor = stringEncryptor;
this.properties = properties;
}
/**
* 执行语句获得数据源参数
* @param statement 语句
* @return 数据源参数
* @throws SQLException sql异常
*/
@Override
protected Map<String, DataSourceProperty> executeStmt(Statement statement) throws SQLException {<FILL_FUNCTION_BODY>}
}
|
ResultSet rs = statement.executeQuery(properties.getQueryDsSql());
Map<String, DataSourceProperty> map = new HashMap<>(8);
while (rs.next()) {
String name = rs.getString(DataSourceConstants.DS_NAME);
String username = rs.getString(DataSourceConstants.DS_USER_NAME);
String password = rs.getString(DataSourceConstants.DS_USER_PWD);
String url = rs.getString(DataSourceConstants.DS_JDBC_URL);
DataSourceProperty property = new DataSourceProperty();
property.setUsername(username);
property.setLazy(true);
property.setPassword(stringEncryptor.decrypt(password));
property.setUrl(url);
map.put(name, property);
}
// 添加默认主数据源
DataSourceProperty property = new DataSourceProperty();
property.setUsername(properties.getUsername());
property.setPassword(properties.getPassword());
property.setUrl(properties.getUrl());
property.setLazy(true);
map.put(DataSourceConstants.DS_MASTER, property);
return map;
| 221
| 312
| 533
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-datasource/src/main/java/com/pig4cloud/pig/common/datasource/config/LastParamDsProcessor.java
|
LastParamDsProcessor
|
matches
|
class LastParamDsProcessor extends DsProcessor {
private static final String LAST_PREFIX = "#last";
/**
* 抽象匹配条件 匹配才会走当前执行器否则走下一级执行器
* @param key DS注解里的内容
* @return 是否匹配
*/
@Override
public boolean matches(String key) {<FILL_FUNCTION_BODY>}
/**
* 抽象最终决定数据源
* @param invocation 方法执行信息
* @param key DS注解里的内容
* @return 数据源名称
*/
@Override
public String doDetermineDatasource(MethodInvocation invocation, String key) {
Object[] arguments = invocation.getArguments();
return String.valueOf(arguments[arguments.length - 1]);
}
}
|
if (key.startsWith(LAST_PREFIX)) {
// https://github.com/baomidou/dynamic-datasource-spring-boot-starter/issues/213
DynamicDataSourceContextHolder.clear();
return true;
}
return false;
| 208
| 76
| 284
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-feign/src/main/java/com/pig4cloud/pig/common/feign/sentinel/ext/PigSentinelFeign.java
|
Builder
|
internalBuild
|
class Builder extends Feign.Builder implements ApplicationContextAware {
private Contract contract = new Contract.Default();
private ApplicationContext applicationContext;
private FeignClientFactory feignClientFactory;
@Override
public Feign.Builder invocationHandlerFactory(InvocationHandlerFactory invocationHandlerFactory) {
throw new UnsupportedOperationException();
}
@Override
public PigSentinelFeign.Builder contract(Contract contract) {
this.contract = contract;
return this;
}
@Override
public Feign internalBuild() {<FILL_FUNCTION_BODY>}
private Object getFieldValue(Object instance, String fieldName) {
Field field = ReflectionUtils.findField(instance.getClass(), fieldName);
field.setAccessible(true);
try {
return field.get(instance);
}
catch (IllegalAccessException e) {
// ignore
}
return null;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
this.feignClientFactory = this.applicationContext.getBean(FeignClientFactory.class);
}
}
|
super.invocationHandlerFactory(new InvocationHandlerFactory() {
@Override
public InvocationHandler create(Target target, Map<Method, MethodHandler> dispatch) {
// 查找 FeignClient 上的 降级策略
FeignClient feignClient = AnnotationUtils.findAnnotation(target.type(), FeignClient.class);
Class<?> fallback = feignClient.fallback();
Class<?> fallbackFactory = feignClient.fallbackFactory();
String beanName = feignClient.contextId();
if (!StringUtils.hasText(beanName)) {
beanName = feignClient.name();
}
Object fallbackInstance;
FallbackFactory<?> fallbackFactoryInstance;
if (void.class != fallback) {
fallbackInstance = getFromContext(beanName, "fallback", fallback, target.type());
return new PigSentinelInvocationHandler(target, dispatch,
new FallbackFactory.Default(fallbackInstance));
}
if (void.class != fallbackFactory) {
fallbackFactoryInstance = (FallbackFactory<?>) getFromContext(beanName, "fallbackFactory",
fallbackFactory, FallbackFactory.class);
return new PigSentinelInvocationHandler(target, dispatch, fallbackFactoryInstance);
}
return new PigSentinelInvocationHandler(target, dispatch);
}
private Object getFromContext(String name, String type, Class<?> fallbackType, Class<?> targetType) {
Object fallbackInstance = feignClientFactory.getInstance(name, fallbackType);
if (fallbackInstance == null) {
throw new IllegalStateException(String
.format("No %s instance of type %s found for feign client %s", type, fallbackType, name));
}
if (!targetType.isAssignableFrom(fallbackType)) {
throw new IllegalStateException(String.format(
"Incompatible %s instance. Fallback/fallbackFactory of type %s is not assignable to %s for feign client %s",
type, fallbackType, targetType, name));
}
return fallbackInstance;
}
});
super.contract(new SentinelContractHolder(contract));
return super.internalBuild();
| 310
| 592
| 902
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-feign/src/main/java/com/pig4cloud/pig/common/feign/sentinel/ext/PigSentinelInvocationHandler.java
|
PigSentinelInvocationHandler
|
invoke
|
class PigSentinelInvocationHandler implements InvocationHandler {
public static final String EQUALS = "equals";
public static final String HASH_CODE = "hashCode";
public static final String TO_STRING = "toString";
private final Target<?> target;
private final Map<Method, InvocationHandlerFactory.MethodHandler> dispatch;
private FallbackFactory<?> fallbackFactory;
private Map<Method, Method> fallbackMethodMap;
PigSentinelInvocationHandler(Target<?> target, Map<Method, InvocationHandlerFactory.MethodHandler> dispatch,
FallbackFactory<?> fallbackFactory) {
this.target = checkNotNull(target, "target");
this.dispatch = checkNotNull(dispatch, "dispatch");
this.fallbackFactory = fallbackFactory;
this.fallbackMethodMap = toFallbackMethod(dispatch);
}
PigSentinelInvocationHandler(Target<?> target, Map<Method, InvocationHandlerFactory.MethodHandler> dispatch) {
this.target = checkNotNull(target, "target");
this.dispatch = checkNotNull(dispatch, "dispatch");
}
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {<FILL_FUNCTION_BODY>}
@Override
public boolean equals(Object obj) {
if (obj instanceof SentinelInvocationHandler) {
PigSentinelInvocationHandler other = (PigSentinelInvocationHandler) obj;
return target.equals(other.target);
}
return false;
}
@Override
public int hashCode() {
return target.hashCode();
}
@Override
public String toString() {
return target.toString();
}
static Map<Method, Method> toFallbackMethod(Map<Method, InvocationHandlerFactory.MethodHandler> dispatch) {
Map<Method, Method> result = new LinkedHashMap<>();
for (Method method : dispatch.keySet()) {
method.setAccessible(true);
result.put(method, method);
}
return result;
}
}
|
if (EQUALS.equals(method.getName())) {
try {
Object otherHandler = args.length > 0 && args[0] != null ? Proxy.getInvocationHandler(args[0]) : null;
return equals(otherHandler);
}
catch (IllegalArgumentException e) {
return false;
}
}
else if (HASH_CODE.equals(method.getName())) {
return hashCode();
}
else if (TO_STRING.equals(method.getName())) {
return toString();
}
Object result;
InvocationHandlerFactory.MethodHandler methodHandler = this.dispatch.get(method);
// only handle by HardCodedTarget
if (target instanceof Target.HardCodedTarget) {
Target.HardCodedTarget<?> hardCodedTarget = (Target.HardCodedTarget) target;
MethodMetadata methodMetadata = SentinelContractHolder.METADATA_MAP
.get(hardCodedTarget.type().getName() + Feign.configKey(hardCodedTarget.type(), method));
// resource default is HttpMethod:protocol://url
if (methodMetadata == null) {
result = methodHandler.invoke(args);
}
else {
String resourceName = methodMetadata.template().method().toUpperCase() + ':' + hardCodedTarget.url()
+ methodMetadata.template().path();
Entry entry = null;
try {
ContextUtil.enter(resourceName);
entry = SphU.entry(resourceName, EntryType.OUT, 1, args);
result = methodHandler.invoke(args);
}
catch (Throwable ex) {
// fallback handle
if (!BlockException.isBlockException(ex)) {
Tracer.trace(ex);
}
if (fallbackFactory != null) {
try {
return fallbackMethodMap.get(method).invoke(fallbackFactory.create(ex), args);
}
catch (IllegalAccessException e) {
// shouldn't happen as method is public due to being an
// interface
throw new AssertionError(e);
}
catch (InvocationTargetException e) {
throw new AssertionError(e.getCause());
}
}
else {
// 若是R类型 执行自动降级返回R
if (R.class == method.getReturnType()) {
log.error("feign 服务间调用异常", ex);
return R.failed(ex.getLocalizedMessage());
}
else {
throw ex;
}
}
}
finally {
if (entry != null) {
entry.exit(1, args);
}
ContextUtil.exit();
}
}
}
else {
// other target type using default strategy
result = methodHandler.invoke(args);
}
return result;
| 530
| 751
| 1,281
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-feign/src/main/java/com/pig4cloud/pig/common/feign/sentinel/handle/GlobalBizExceptionHandler.java
|
GlobalBizExceptionHandler
|
handleBodyValidException
|
class GlobalBizExceptionHandler {
/**
* 全局异常.
* @param e the e
* @return R
*/
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public R handleGlobalException(Exception e) {
log.error("全局异常信息 ex={}", e.getMessage(), e);
// 业务异常交由 sentinel 记录
Tracer.trace(e);
return R.failed(e.getLocalizedMessage());
}
/**
* 处理业务校验过程中碰到的非法参数异常 该异常基本由{@link org.springframework.util.Assert}抛出
* @param exception 参数校验异常
* @return API返回结果对象包装后的错误输出结果
* @see Assert#hasLength(String, String)
* @see Assert#hasText(String, String)
* @see Assert#isTrue(boolean, String)
* @see Assert#isNull(Object, String)
* @see Assert#notNull(Object, String)
*/
@ExceptionHandler(IllegalArgumentException.class)
@ResponseStatus(HttpStatus.OK)
public R handleIllegalArgumentException(IllegalArgumentException exception) {
log.error("非法参数,ex = {}", exception.getMessage(), exception);
return R.failed(exception.getMessage());
}
/**
* AccessDeniedException
* @param e the e
* @return R
*/
@ExceptionHandler(AccessDeniedException.class)
@ResponseStatus(HttpStatus.FORBIDDEN)
public R handleAccessDeniedException(AccessDeniedException e) {
String msg = SpringSecurityMessageSource.getAccessor()
.getMessage("AbstractAccessDecisionManager.accessDenied", e.getMessage());
log.warn("拒绝授权异常信息 ex={}", msg);
return R.failed(e.getLocalizedMessage());
}
/**
* validation Exception
* @param exception
* @return R
*/
@ExceptionHandler({ MethodArgumentNotValidException.class })
@ResponseStatus(HttpStatus.BAD_REQUEST)
public R handleBodyValidException(MethodArgumentNotValidException exception) {<FILL_FUNCTION_BODY>}
/**
* validation Exception (以form-data形式传参)
* @param exception
* @return R
*/
@ExceptionHandler({ BindException.class })
@ResponseStatus(HttpStatus.BAD_REQUEST)
public R bindExceptionHandler(BindException exception) {
List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors();
log.warn("参数绑定异常,ex = {}", fieldErrors.get(0).getDefaultMessage());
return R.failed(fieldErrors.get(0).getDefaultMessage());
}
/**
* 保持和低版本请求路径不存在的行为一致
* <p>
* <a href="https://github.com/spring-projects/spring-boot/issues/38733">[Spring Boot
* 3.2.0] 404 Not Found behavior #38733</a>
* @param exception
* @return R
*/
@ExceptionHandler({ NoResourceFoundException.class })
@ResponseStatus(HttpStatus.NOT_FOUND)
public R bindExceptionHandler(NoResourceFoundException exception) {
log.debug("请求路径 404 {}", exception.getMessage());
return R.failed(exception.getMessage());
}
}
|
List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors();
log.warn("参数绑定异常,ex = {}", fieldErrors.get(0).getDefaultMessage());
return R.failed(String.format("%s %s", fieldErrors.get(0).getField(), fieldErrors.get(0).getDefaultMessage()));
| 862
| 88
| 950
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-log/src/main/java/com/pig4cloud/pig/common/log/aspect/SysLogAspect.java
|
SysLogAspect
|
around
|
class SysLogAspect {
@Around("@annotation(sysLog)")
@SneakyThrows
public Object around(ProceedingJoinPoint point, com.pig4cloud.pig.common.log.annotation.SysLog sysLog) {<FILL_FUNCTION_BODY>}
}
|
String strClassName = point.getTarget().getClass().getName();
String strMethodName = point.getSignature().getName();
log.debug("[类名]:{},[方法]:{}", strClassName, strMethodName);
String value = sysLog.value();
String expression = sysLog.expression();
// 当前表达式存在 SPEL,会覆盖 value 的值
if (StrUtil.isNotBlank(expression)) {
// 解析SPEL
MethodSignature signature = (MethodSignature) point.getSignature();
EvaluationContext context = SysLogUtils.getContext(point.getArgs(), signature.getMethod());
try {
value = SysLogUtils.getValue(context, expression, String.class);
}
catch (Exception e) {
// SPEL 表达式异常,获取 value 的值
log.error("@SysLog 解析SPEL {} 异常", expression);
}
}
SysLogEventSource logVo = SysLogUtils.getSysLog();
logVo.setTitle(value);
// 获取请求body参数
if (StrUtil.isBlank(logVo.getParams())) {
logVo.setBody(point.getArgs());
}
// 发送异步日志事件
Long startTime = System.currentTimeMillis();
Object obj;
try {
obj = point.proceed();
}
catch (Exception e) {
logVo.setLogType(LogTypeEnum.ERROR.getType());
logVo.setException(e.getMessage());
throw e;
}
finally {
Long endTime = System.currentTimeMillis();
logVo.setTime(endTime - startTime);
SpringContextHolder.publishEvent(new SysLogEvent(logVo));
}
return obj;
| 78
| 496
| 574
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-log/src/main/java/com/pig4cloud/pig/common/log/event/SysLogListener.java
|
SysLogListener
|
saveSysLog
|
class SysLogListener implements InitializingBean {
// new 一个 避免日志脱敏策略影响全局ObjectMapper
private final static ObjectMapper objectMapper = new ObjectMapper();
private final RemoteLogService remoteLogService;
private final PigLogProperties logProperties;
@SneakyThrows
@Async
@Order
@EventListener(SysLogEvent.class)
public void saveSysLog(SysLogEvent event) {<FILL_FUNCTION_BODY>}
@Override
public void afterPropertiesSet() {
objectMapper.addMixIn(Object.class, PropertyFilterMixIn.class);
String[] ignorableFieldNames = logProperties.getExcludeFields().toArray(new String[0]);
FilterProvider filters = new SimpleFilterProvider().addFilter("filter properties by name",
SimpleBeanPropertyFilter.serializeAllExcept(ignorableFieldNames));
objectMapper.setFilterProvider(filters);
objectMapper.registerModule(new PigJavaTimeModule());
}
@JsonFilter("filter properties by name")
class PropertyFilterMixIn {
}
}
|
SysLogEventSource source = (SysLogEventSource) event.getSource();
SysLog sysLog = new SysLog();
BeanUtils.copyProperties(source, sysLog);
// json 格式刷参数放在异步中处理,提升性能
if (Objects.nonNull(source.getBody())) {
String params = objectMapper.writeValueAsString(source.getBody());
sysLog.setParams(StrUtil.subPre(params, logProperties.getMaxLength()));
}
remoteLogService.saveLog(sysLog, SecurityConstants.FROM_IN);
| 270
| 152
| 422
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-log/src/main/java/com/pig4cloud/pig/common/log/init/ApplicationLoggerInitializer.java
|
ApplicationLoggerInitializer
|
postProcessEnvironment
|
class ApplicationLoggerInitializer implements EnvironmentPostProcessor, Ordered {
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {<FILL_FUNCTION_BODY>}
@Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
}
|
String appName = environment.getProperty("spring.application.name");
String logBase = environment.getProperty("LOGGING_PATH", "logs");
// spring boot admin 直接加载日志
System.setProperty("logging.file.name", String.format("%s/%s/debug.log", logBase, appName));
// 避免各种依赖的地方组件造成 BeanPostProcessorChecker 警告
System.setProperty("logging.level.org.springframework.context.support.PostProcessorRegistrationDelegate",
"ERROR");
// 避免 sentinel 1.8.4+ 心跳日志过大
System.setProperty("csp.sentinel.log.level", "OFF");
| 78
| 185
| 263
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-log/src/main/java/com/pig4cloud/pig/common/log/util/SysLogUtils.java
|
SysLogUtils
|
getContext
|
class SysLogUtils {
public SysLogEventSource getSysLog() {
HttpServletRequest request = ((ServletRequestAttributes) Objects
.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
SysLogEventSource sysLog = new SysLogEventSource();
sysLog.setLogType(LogTypeEnum.NORMAL.getType());
sysLog.setRequestUri(URLUtil.getPath(request.getRequestURI()));
sysLog.setMethod(request.getMethod());
sysLog.setRemoteAddr(JakartaServletUtil.getClientIP(request));
sysLog.setUserAgent(request.getHeader(HttpHeaders.USER_AGENT));
sysLog.setCreateBy(getUsername());
sysLog.setServiceId(SpringUtil.getProperty("spring.application.name"));
// get 参数脱敏
PigLogProperties logProperties = SpringContextHolder.getBean(PigLogProperties.class);
Map<String, String[]> paramsMap = MapUtil.removeAny(request.getParameterMap(),
ArrayUtil.toArray(logProperties.getExcludeFields(), String.class));
sysLog.setParams(HttpUtil.toParams(paramsMap));
return sysLog;
}
/**
* 获取用户名称
* @return username
*/
private String getUsername() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
return null;
}
return authentication.getName();
}
/**
* 获取spel 定义的参数值
* @param context 参数容器
* @param key key
* @param clazz 需要返回的类型
* @param <T> 返回泛型
* @return 参数值
*/
public <T> T getValue(EvaluationContext context, String key, Class<T> clazz) {
SpelExpressionParser spelExpressionParser = new SpelExpressionParser();
Expression expression = spelExpressionParser.parseExpression(key);
return expression.getValue(context, clazz);
}
/**
* 获取参数容器
* @param arguments 方法的参数列表
* @param signatureMethod 被执行的方法体
* @return 装载参数的容器
*/
public EvaluationContext getContext(Object[] arguments, Method signatureMethod) {<FILL_FUNCTION_BODY>}
}
|
String[] parameterNames = new StandardReflectionParameterNameDiscoverer().getParameterNames(signatureMethod);
EvaluationContext context = new StandardEvaluationContext();
if (parameterNames == null) {
return context;
}
for (int i = 0; i < arguments.length; i++) {
context.setVariable(parameterNames[i], arguments[i]);
}
return context;
| 614
| 103
| 717
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-mybatis/src/main/java/com/pig4cloud/pig/common/mybatis/MybatisAutoConfiguration.java
|
MybatisAutoConfiguration
|
mybatisPlusInterceptor
|
class MybatisAutoConfiguration implements WebMvcConfigurer {
/**
* SQL 过滤器避免SQL 注入
* @param argumentResolvers
*/
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(new SqlFilterArgumentResolver());
}
/**
* 分页插件, 对于单一数据库类型来说,都建议配置该值,避免每次分页都去抓取数据库类型
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {<FILL_FUNCTION_BODY>}
/**
* 审计字段自动填充
* @return {@link MetaObjectHandler}
*/
@Bean
public MybatisPlusMetaObjectHandler mybatisPlusMetaObjectHandler() {
return new MybatisPlusMetaObjectHandler();
}
}
|
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PigPaginationInnerInterceptor());
return interceptor;
| 223
| 57
| 280
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-mybatis/src/main/java/com/pig4cloud/pig/common/mybatis/config/MybatisPlusMetaObjectHandler.java
|
MybatisPlusMetaObjectHandler
|
getUserName
|
class MybatisPlusMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
log.debug("mybatis plus start insert fill ....");
LocalDateTime now = LocalDateTime.now();
fillValIfNullByName("createTime", now, metaObject, true);
fillValIfNullByName("updateTime", now, metaObject, true);
fillValIfNullByName("createBy", getUserName(), metaObject, true);
fillValIfNullByName("updateBy", getUserName(), metaObject, true);
// 删除标记自动填充
fillValIfNullByName("delFlag", CommonConstants.STATUS_NORMAL, metaObject, true);
}
@Override
public void updateFill(MetaObject metaObject) {
log.debug("mybatis plus start update fill ....");
fillValIfNullByName("updateTime", LocalDateTime.now(), metaObject, true);
fillValIfNullByName("updateBy", getUserName(), metaObject, true);
}
/**
* 填充值,先判断是否有手动设置,优先手动设置的值,例如:job必须手动设置
* @param fieldName 属性名
* @param fieldVal 属性值
* @param metaObject MetaObject
* @param isCover 是否覆盖原有值,避免更新操作手动入参
*/
private static void fillValIfNullByName(String fieldName, Object fieldVal, MetaObject metaObject, boolean isCover) {
// 0. 如果填充值为空
if (fieldVal == null) {
return;
}
// 1. 没有 set 方法
if (!metaObject.hasSetter(fieldName)) {
return;
}
// 2. 如果用户有手动设置的值
Object userSetValue = metaObject.getValue(fieldName);
String setValueStr = StrUtil.str(userSetValue, Charset.defaultCharset());
if (StrUtil.isNotBlank(setValueStr) && !isCover) {
return;
}
// 3. field 类型相同时设置
Class<?> getterType = metaObject.getGetterType(fieldName);
if (ClassUtils.isAssignableValue(getterType, fieldVal)) {
metaObject.setValue(fieldName, fieldVal);
}
}
/**
* 获取 spring security 当前的用户名
* @return 当前用户名
*/
private String getUserName() {<FILL_FUNCTION_BODY>}
}
|
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
// 匿名接口直接返回
if (authentication instanceof AnonymousAuthenticationToken) {
return null;
}
if (Optional.ofNullable(authentication).isPresent()) {
return authentication.getName();
}
return null;
| 659
| 85
| 744
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-mybatis/src/main/java/com/pig4cloud/pig/common/mybatis/plugins/PigPaginationInnerInterceptor.java
|
PigPaginationInnerInterceptor
|
beforeQuery
|
class PigPaginationInnerInterceptor extends PaginationInnerInterceptor {
/**
* 数据库类型
* <p>
* 查看 {@link #findIDialect(Executor)} 逻辑
*/
private DbType dbType;
/**
* 方言实现类
* <p>
* 查看 {@link #findIDialect(Executor)} 逻辑
*/
private IDialect dialect;
public PigPaginationInnerInterceptor(DbType dbType) {
this.dbType = dbType;
}
public PigPaginationInnerInterceptor(IDialect dialect) {
this.dialect = dialect;
}
@Override
public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds,
ResultHandler resultHandler, BoundSql boundSql) throws SQLException {<FILL_FUNCTION_BODY>}
}
|
IPage<?> page = ParameterUtils.findPage(parameter).orElse(null);
// size 小于 0 直接设置为 0 , 即不查询任何数据
if (null != page && page.getSize() < 0) {
page.setSize(0);
}
super.beforeQuery(executor, ms, page, rowBounds, resultHandler, boundSql);
| 230
| 106
| 336
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-mybatis/src/main/java/com/pig4cloud/pig/common/mybatis/resolver/SqlFilterArgumentResolver.java
|
SqlFilterArgumentResolver
|
resolveArgument
|
class SqlFilterArgumentResolver implements HandlerMethodArgumentResolver {
/**
* 判断Controller是否包含page 参数
* @param parameter 参数
* @return 是否过滤
*/
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.getParameterType().equals(Page.class);
}
/**
* @param parameter 入参集合
* @param mavContainer model 和 view
* @param webRequest web相关
* @param binderFactory 入参解析
* @return 检查后新的page对象
* <p>
* page 只支持查询 GET .如需解析POST获取请求报文体处理
*/
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {<FILL_FUNCTION_BODY>}
}
|
HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
String[] ascs = request.getParameterValues("ascs");
String[] descs = request.getParameterValues("descs");
String current = request.getParameter("current");
String size = request.getParameter("size");
Page<?> page = new Page<>();
if (StrUtil.isNotBlank(current)) {
page.setCurrent(Long.parseLong(current));
}
if (StrUtil.isNotBlank(size)) {
page.setSize(Long.parseLong(size));
}
List<OrderItem> orderItemList = new ArrayList<>();
Optional.ofNullable(ascs)
.ifPresent(s -> orderItemList.addAll(Arrays.stream(s)
.filter(asc -> !SqlInjectionUtils.check(asc))
.map(OrderItem::asc)
.collect(Collectors.toList())));
Optional.ofNullable(descs)
.ifPresent(s -> orderItemList.addAll(Arrays.stream(s)
.filter(desc -> !SqlInjectionUtils.check(desc))
.map(OrderItem::desc)
.collect(Collectors.toList())));
page.addOrder(orderItemList);
return page;
| 223
| 346
| 569
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-oss/src/main/java/com/pig4cloud/pig/common/file/local/LocalFileTemplate.java
|
LocalFileTemplate
|
removeObject
|
class LocalFileTemplate implements FileTemplate {
private final FileProperties properties;
/**
* 创建bucket
* @param bucketName bucket名称
*/
@Override
public void createBucket(String bucketName) {
FileUtil.mkdir(properties.getLocal().getBasePath() + FileUtil.FILE_SEPARATOR + bucketName);
}
/**
* 获取全部bucket
* <p>
* <p>
* API Documentation</a>
*/
@Override
public List<Bucket> getAllBuckets() {
return Arrays.stream(FileUtil.ls(properties.getLocal().getBasePath()))
.filter(FileUtil::isDirectory)
.map(dir -> new Bucket(dir.getName()))
.collect(Collectors.toList());
}
/**
* @param bucketName bucket名称
* @see <a href= Documentation</a>
*/
@Override
public void removeBucket(String bucketName) {
FileUtil.del(properties.getLocal().getBasePath() + FileUtil.FILE_SEPARATOR + bucketName);
}
/**
* 上传文件
* @param bucketName bucket名称
* @param objectName 文件名称
* @param stream 文件流
* @param contextType 文件类型
*/
@Override
public void putObject(String bucketName, String objectName, InputStream stream, String contextType) {
// 当 Bucket 不存在时创建
String dir = properties.getLocal().getBasePath() + FileUtil.FILE_SEPARATOR + bucketName;
if (!FileUtil.isDirectory(properties.getLocal().getBasePath() + FileUtil.FILE_SEPARATOR + bucketName)) {
createBucket(bucketName);
}
// 写入文件
File file = FileUtil.file(dir + FileUtil.FILE_SEPARATOR + objectName);
FileUtil.writeFromStream(stream, file);
}
/**
* 获取文件
* @param bucketName bucket名称
* @param objectName 文件名称
* @return 二进制流 API Documentation</a>
*/
@Override
@SneakyThrows
public S3Object getObject(String bucketName, String objectName) {
String dir = properties.getLocal().getBasePath() + FileUtil.FILE_SEPARATOR + bucketName;
S3Object s3Object = new S3Object();
s3Object.setObjectContent(FileUtil.getInputStream(dir + FileUtil.FILE_SEPARATOR + objectName));
return s3Object;
}
/**
* @param bucketName
* @param objectName
* @throws Exception
*/
@Override
public void removeObject(String bucketName, String objectName) throws Exception {<FILL_FUNCTION_BODY>}
/**
* 上传文件
* @param bucketName bucket名称
* @param objectName 文件名称
* @param stream 文件流
* @throws Exception
*/
@Override
public void putObject(String bucketName, String objectName, InputStream stream) throws Exception {
putObject(bucketName, objectName, stream, null);
}
/**
* 根据文件前置查询文件
* @param bucketName bucket名称
* @param prefix 前缀
* @param recursive 是否递归查询
* @return S3ObjectSummary 列表
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjects">AWS
* API Documentation</a>
*/
@Override
public List<S3ObjectSummary> getAllObjectsByPrefix(String bucketName, String prefix, boolean recursive) {
String dir = properties.getLocal().getBasePath() + FileUtil.FILE_SEPARATOR + bucketName;
return Arrays.stream(FileUtil.ls(dir)).filter(file -> file.getName().startsWith(prefix)).map(file -> {
S3ObjectSummary summary = new S3ObjectSummary();
summary.setKey(file.getName());
return summary;
}).collect(Collectors.toList());
}
}
|
String dir = properties.getLocal().getBasePath() + FileUtil.FILE_SEPARATOR + bucketName;
FileUtil.del(dir + FileUtil.FILE_SEPARATOR + objectName);
| 1,063
| 52
| 1,115
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-oss/src/main/java/com/pig4cloud/pig/common/file/oss/http/OssEndpoint.java
|
OssEndpoint
|
createObject
|
class OssEndpoint {
private final OssTemplate template;
/**
* Bucket Endpoints
*/
@SneakyThrows
@PostMapping("/bucket/{bucketName}")
public Bucket createBucket(@PathVariable String bucketName) {
template.createBucket(bucketName);
return template.getBucket(bucketName).get();
}
@SneakyThrows
@GetMapping("/bucket")
public List<Bucket> getBuckets() {
return template.getAllBuckets();
}
@SneakyThrows
@GetMapping("/bucket/{bucketName}")
public Bucket getBucket(@PathVariable String bucketName) {
return template.getBucket(bucketName).orElseThrow(() -> new IllegalArgumentException("Bucket Name not found!"));
}
@SneakyThrows
@DeleteMapping("/bucket/{bucketName}")
@ResponseStatus(HttpStatus.ACCEPTED)
public void deleteBucket(@PathVariable String bucketName) {
template.removeBucket(bucketName);
}
/**
* Object Endpoints
*/
@SneakyThrows
@PostMapping("/object/{bucketName}")
public S3Object createObject(@RequestBody MultipartFile object, @PathVariable String bucketName) {
String name = object.getOriginalFilename();
@Cleanup
InputStream inputStream = object.getInputStream();
template.putObject(bucketName, name, inputStream, object.getSize(), object.getContentType());
return template.getObjectInfo(bucketName, name);
}
@SneakyThrows
@PostMapping("/object/{bucketName}/{objectName}")
public S3Object createObject(@RequestBody MultipartFile object, @PathVariable String bucketName,
@PathVariable String objectName) {<FILL_FUNCTION_BODY>}
@SneakyThrows
@GetMapping("/object/{bucketName}/{objectName}")
public List<S3ObjectSummary> filterObject(@PathVariable String bucketName, @PathVariable String objectName) {
return template.getAllObjectsByPrefix(bucketName, objectName, true);
}
@SneakyThrows
@GetMapping("/object/{bucketName}/{objectName}/{expires}")
public Map<String, Object> getObject(@PathVariable String bucketName, @PathVariable String objectName,
@PathVariable Integer expires) {
Map<String, Object> responseBody = new HashMap<>(8);
// Put Object info
responseBody.put("bucket", bucketName);
responseBody.put("object", objectName);
responseBody.put("url", template.getObjectURL(bucketName, objectName, expires));
responseBody.put("expires", expires);
return responseBody;
}
@SneakyThrows
@ResponseStatus(HttpStatus.ACCEPTED)
@DeleteMapping("/object/{bucketName}/{objectName}/")
public void deleteObject(@PathVariable String bucketName, @PathVariable String objectName) {
template.removeObject(bucketName, objectName);
}
}
|
@Cleanup
InputStream inputStream = object.getInputStream();
template.putObject(bucketName, objectName, inputStream, object.getSize(), object.getContentType());
return template.getObjectInfo(bucketName, objectName);
| 778
| 66
| 844
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-oss/src/main/java/com/pig4cloud/pig/common/file/oss/service/OssTemplate.java
|
OssTemplate
|
putObject
|
class OssTemplate implements InitializingBean, FileTemplate {
private final FileProperties properties;
private AmazonS3 amazonS3;
/**
* 创建bucket
* @param bucketName bucket名称
*/
@SneakyThrows
public void createBucket(String bucketName) {
if (!amazonS3.doesBucketExistV2(bucketName)) {
amazonS3.createBucket((bucketName));
}
}
/**
* 获取全部bucket
* <p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBuckets">AWS
* API Documentation</a>
*/
@SneakyThrows
public List<Bucket> getAllBuckets() {
return amazonS3.listBuckets();
}
/**
* @param bucketName bucket名称
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBuckets">AWS
* API Documentation</a>
*/
@SneakyThrows
public Optional<Bucket> getBucket(String bucketName) {
return amazonS3.listBuckets().stream().filter(b -> b.getName().equals(bucketName)).findFirst();
}
/**
* @param bucketName bucket名称
* @see <a href=
* "http://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucket">AWS API
* Documentation</a>
*/
@SneakyThrows
public void removeBucket(String bucketName) {
amazonS3.deleteBucket(bucketName);
}
/**
* 根据文件前置查询文件
* @param bucketName bucket名称
* @param prefix 前缀
* @param recursive 是否递归查询
* @return S3ObjectSummary 列表
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjects">AWS
* API Documentation</a>
*/
@SneakyThrows
public List<S3ObjectSummary> getAllObjectsByPrefix(String bucketName, String prefix, boolean recursive) {
ObjectListing objectListing = amazonS3.listObjects(bucketName, prefix);
return new ArrayList<>(objectListing.getObjectSummaries());
}
/**
* 获取文件外链
* @param bucketName bucket名称
* @param objectName 文件名称
* @param expires 过期时间 <=7
* @return url
* @see AmazonS3#generatePresignedUrl(String bucketName, String key, Date expiration)
*/
@SneakyThrows
public String getObjectURL(String bucketName, String objectName, Integer expires) {
Date date = new Date();
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, expires);
URL url = amazonS3.generatePresignedUrl(bucketName, objectName, calendar.getTime());
return url.toString();
}
/**
* 获取文件
* @param bucketName bucket名称
* @param objectName 文件名称
* @return 二进制流
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObject">AWS
* API Documentation</a>
*/
@SneakyThrows
public S3Object getObject(String bucketName, String objectName) {
return amazonS3.getObject(bucketName, objectName);
}
/**
* 上传文件
* @param bucketName bucket名称
* @param objectName 文件名称
* @param stream 文件流
* @throws Exception
*/
public void putObject(String bucketName, String objectName, InputStream stream) throws Exception {
putObject(bucketName, objectName, stream, stream.available(), "application/octet-stream");
}
/**
* 上传文件
* @param bucketName bucket名称
* @param objectName 文件名称
* @param stream 文件流
* @param contextType 文件类型
* @throws Exception
*/
public void putObject(String bucketName, String objectName, InputStream stream, String contextType)
throws Exception {
putObject(bucketName, objectName, stream, stream.available(), contextType);
}
/**
* 上传文件
* @param bucketName bucket名称
* @param objectName 文件名称
* @param stream 文件流
* @param size 大小
* @param contextType 类型
* @throws Exception
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObject">AWS
* API Documentation</a>
*/
public PutObjectResult putObject(String bucketName, String objectName, InputStream stream, long size,
String contextType) throws Exception {<FILL_FUNCTION_BODY>}
/**
* 获取文件信息
* @param bucketName bucket名称
* @param objectName 文件名称
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObject">AWS
* API Documentation</a>
*/
public S3Object getObjectInfo(String bucketName, String objectName) throws Exception {
@Cleanup
S3Object object = amazonS3.getObject(bucketName, objectName);
return object;
}
/**
* 删除文件
* @param bucketName bucket名称
* @param objectName 文件名称
* @throws Exception
* @see <a href=
* "http://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObject">AWS API
* Documentation</a>
*/
public void removeObject(String bucketName, String objectName) throws Exception {
amazonS3.deleteObject(bucketName, objectName);
}
@Override
public void afterPropertiesSet() {
ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setMaxConnections(properties.getOss().getMaxConnections());
AwsClientBuilder.EndpointConfiguration endpointConfiguration = new AwsClientBuilder.EndpointConfiguration(
properties.getOss().getEndpoint(), properties.getOss().getRegion());
AWSCredentials awsCredentials = new BasicAWSCredentials(properties.getOss().getAccessKey(),
properties.getOss().getSecretKey());
AWSCredentialsProvider awsCredentialsProvider = new AWSStaticCredentialsProvider(awsCredentials);
this.amazonS3 = AmazonS3Client.builder()
.withEndpointConfiguration(endpointConfiguration)
.withClientConfiguration(clientConfiguration)
.withCredentials(awsCredentialsProvider)
.disableChunkedEncoding()
.withPathStyleAccessEnabled(properties.getOss().getPathStyleAccess())
.build();
}
}
|
// String fileName = getFileName(objectName);
byte[] bytes = IOUtils.toByteArray(stream);
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(size);
objectMetadata.setContentType(contextType);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
// 上传
return amazonS3.putObject(bucketName, objectName, byteArrayInputStream, objectMetadata);
| 1,900
| 118
| 2,018
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PermissionService.java
|
PermissionService
|
hasPermission
|
class PermissionService {
/**
* 判断接口是否有任意xxx,xxx权限
* @param permissions 权限
* @return {boolean}
*/
public boolean hasPermission(String... permissions) {<FILL_FUNCTION_BODY>}
}
|
if (ArrayUtil.isEmpty(permissions)) {
return false;
}
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
return false;
}
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
return authorities.stream()
.map(GrantedAuthority::getAuthority)
.filter(StringUtils::hasText)
.anyMatch(x -> PatternMatchUtils.simpleMatch(permissions, x));
| 71
| 132
| 203
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PermitAllUrlProperties.java
|
PermitAllUrlProperties
|
afterPropertiesSet
|
class PermitAllUrlProperties implements InitializingBean {
private static final Pattern PATTERN = Pattern.compile("\\{(.*?)\\}");
private static final String[] DEFAULT_IGNORE_URLS = new String[] { "/actuator/**", "/error", "/v3/api-docs" };
@Getter
@Setter
private List<String> urls = new ArrayList<>();
@Override
public void afterPropertiesSet() {<FILL_FUNCTION_BODY>}
}
|
urls.addAll(Arrays.asList(DEFAULT_IGNORE_URLS));
RequestMappingHandlerMapping mapping = SpringUtil.getBean("requestMappingHandlerMapping");
Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
map.keySet().forEach(info -> {
HandlerMethod handlerMethod = map.get(info);
// 获取方法上边的注解 替代path variable 为 *
Inner method = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), Inner.class);
Optional.ofNullable(method)
.ifPresent(inner -> Objects.requireNonNull(info.getPathPatternsCondition())
.getPatternValues()
.forEach(url -> urls.add(ReUtil.replaceAll(url, PATTERN, "*"))));
// 获取类上边的注解, 替代path variable 为 *
Inner controller = AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), Inner.class);
Optional.ofNullable(controller)
.ifPresent(inner -> Objects.requireNonNull(info.getPathPatternsCondition())
.getPatternValues()
.forEach(url -> urls.add(ReUtil.replaceAll(url, PATTERN, "*"))));
});
| 122
| 328
| 450
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PigBearerTokenExtractor.java
|
PigBearerTokenExtractor
|
resolveFromRequestParameters
|
class PigBearerTokenExtractor implements BearerTokenResolver {
private static final Pattern authorizationPattern = Pattern.compile("^Bearer (?<token>[a-zA-Z0-9-:._~+/]+=*)$",
Pattern.CASE_INSENSITIVE);
private boolean allowFormEncodedBodyParameter = false;
private boolean allowUriQueryParameter = true;
private String bearerTokenHeaderName = HttpHeaders.AUTHORIZATION;
private final PathMatcher pathMatcher = new AntPathMatcher();
private final PermitAllUrlProperties urlProperties;
public PigBearerTokenExtractor(PermitAllUrlProperties urlProperties) {
this.urlProperties = urlProperties;
}
@Override
public String resolve(HttpServletRequest request) {
boolean match = urlProperties.getUrls()
.stream()
.anyMatch(url -> pathMatcher.match(url, request.getRequestURI()));
if (match) {
return null;
}
final String authorizationHeaderToken = resolveFromAuthorizationHeader(request);
final String parameterToken = isParameterTokenSupportedForRequest(request)
? resolveFromRequestParameters(request) : null;
if (authorizationHeaderToken != null) {
if (parameterToken != null) {
final BearerTokenError error = BearerTokenErrors
.invalidRequest("Found multiple bearer tokens in the request");
throw new OAuth2AuthenticationException(error);
}
return authorizationHeaderToken;
}
if (parameterToken != null && isParameterTokenEnabledForRequest(request)) {
return parameterToken;
}
return null;
}
private String resolveFromAuthorizationHeader(HttpServletRequest request) {
String authorization = request.getHeader(this.bearerTokenHeaderName);
if (!StringUtils.startsWithIgnoreCase(authorization, "bearer")) {
return null;
}
Matcher matcher = authorizationPattern.matcher(authorization);
if (!matcher.matches()) {
BearerTokenError error = BearerTokenErrors.invalidToken("Bearer token is malformed");
throw new OAuth2AuthenticationException(error);
}
return matcher.group("token");
}
private static String resolveFromRequestParameters(HttpServletRequest request) {<FILL_FUNCTION_BODY>}
private boolean isParameterTokenSupportedForRequest(final HttpServletRequest request) {
return (("POST".equals(request.getMethod())
&& MediaType.APPLICATION_FORM_URLENCODED_VALUE.equals(request.getContentType()))
|| "GET".equals(request.getMethod()));
}
private boolean isParameterTokenEnabledForRequest(final HttpServletRequest request) {
return ((this.allowFormEncodedBodyParameter && "POST".equals(request.getMethod())
&& MediaType.APPLICATION_FORM_URLENCODED_VALUE.equals(request.getContentType()))
|| (this.allowUriQueryParameter && "GET".equals(request.getMethod())));
}
}
|
String[] values = request.getParameterValues("access_token");
if (values == null || values.length == 0) {
return null;
}
if (values.length == 1) {
return values[0];
}
BearerTokenError error = BearerTokenErrors.invalidRequest("Found multiple bearer tokens in the request");
throw new OAuth2AuthenticationException(error);
| 761
| 102
| 863
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PigCustomOAuth2AccessTokenResponseHttpMessageConverter.java
|
PigCustomOAuth2AccessTokenResponseHttpMessageConverter
|
writeInternal
|
class PigCustomOAuth2AccessTokenResponseHttpMessageConverter
extends OAuth2AccessTokenResponseHttpMessageConverter {
private static final ParameterizedTypeReference<Map<String, Object>> STRING_OBJECT_MAP = new ParameterizedTypeReference<Map<String, Object>>() {
};
private Converter<OAuth2AccessTokenResponse, Map<String, Object>> accessTokenResponseParametersConverter = new DefaultOAuth2AccessTokenResponseMapConverter();
@Override
protected void writeInternal(OAuth2AccessTokenResponse tokenResponse, HttpOutputMessage outputMessage)
throws HttpMessageNotWritableException {<FILL_FUNCTION_BODY>}
}
|
try {
Map<String, Object> tokenResponseParameters = this.accessTokenResponseParametersConverter
.convert(tokenResponse);
ObjectMapper objectMapper = SpringContextHolder.getBean(ObjectMapper.class);
GenericHttpMessageConverter<Object> jsonMessageConverter = new MappingJackson2HttpMessageConverter(
objectMapper);
jsonMessageConverter.write(tokenResponseParameters, STRING_OBJECT_MAP.getType(), MediaType.APPLICATION_JSON,
outputMessage);
}
catch (Exception ex) {
throw new HttpMessageNotWritableException(
"An error occurred writing the OAuth 2.0 Access Token Response: " + ex.getMessage(), ex);
}
| 160
| 181
| 341
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PigCustomOpaqueTokenIntrospector.java
|
PigCustomOpaqueTokenIntrospector
|
introspect
|
class PigCustomOpaqueTokenIntrospector implements OpaqueTokenIntrospector {
private final OAuth2AuthorizationService authorizationService;
@Override
public OAuth2AuthenticatedPrincipal introspect(String token) {<FILL_FUNCTION_BODY>}
}
|
OAuth2Authorization oldAuthorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN);
if (Objects.isNull(oldAuthorization)) {
throw new InvalidBearerTokenException(token);
}
// 客户端模式默认返回
if (AuthorizationGrantType.CLIENT_CREDENTIALS.equals(oldAuthorization.getAuthorizationGrantType())) {
return new DefaultOAuth2AuthenticatedPrincipal(oldAuthorization.getPrincipalName(),
Objects.requireNonNull(oldAuthorization.getAccessToken().getClaims()),
AuthorityUtils.NO_AUTHORITIES);
}
Map<String, PigUserDetailsService> userDetailsServiceMap = SpringUtil
.getBeansOfType(PigUserDetailsService.class);
Optional<PigUserDetailsService> optional = userDetailsServiceMap.values()
.stream()
.filter(service -> service.support(Objects.requireNonNull(oldAuthorization).getRegisteredClientId(),
oldAuthorization.getAuthorizationGrantType().getValue()))
.max(Comparator.comparingInt(Ordered::getOrder));
UserDetails userDetails = null;
try {
Object principal = Objects.requireNonNull(oldAuthorization).getAttributes().get(Principal.class.getName());
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = (UsernamePasswordAuthenticationToken) principal;
Object tokenPrincipal = usernamePasswordAuthenticationToken.getPrincipal();
userDetails = optional.get().loadUserByUser((PigUser) tokenPrincipal);
}
catch (UsernameNotFoundException notFoundException) {
log.warn("用户不不存在 {}", notFoundException.getLocalizedMessage());
throw notFoundException;
}
catch (Exception ex) {
log.error("资源服务器 introspect Token error {}", ex.getLocalizedMessage());
}
// 注入客户端信息,方便上下文中获取
PigUser pigxUser = (PigUser) userDetails;
Objects.requireNonNull(pigxUser)
.getAttributes()
.put(SecurityConstants.CLIENT_ID, oldAuthorization.getRegisteredClientId());
return pigxUser;
| 72
| 580
| 652
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PigResourceServerConfiguration.java
|
PigResourceServerConfiguration
|
securityFilterChain
|
class PigResourceServerConfiguration {
protected final ResourceAuthExceptionEntryPoint resourceAuthExceptionEntryPoint;
private final PermitAllUrlProperties permitAllUrl;
private final PigBearerTokenExtractor pigBearerTokenExtractor;
private final OpaqueTokenIntrospector customOpaqueTokenIntrospector;
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {<FILL_FUNCTION_BODY>}
}
|
AntPathRequestMatcher[] requestMatchers = permitAllUrl.getUrls()
.stream()
.map(AntPathRequestMatcher::new)
.toList()
.toArray(new AntPathRequestMatcher[] {});
http.authorizeHttpRequests(authorizeRequests -> authorizeRequests.requestMatchers(requestMatchers)
.permitAll()
.anyRequest()
.authenticated())
.oauth2ResourceServer(
oauth2 -> oauth2.opaqueToken(token -> token.introspector(customOpaqueTokenIntrospector))
.authenticationEntryPoint(resourceAuthExceptionEntryPoint)
.bearerTokenResolver(pigBearerTokenExtractor))
.headers(headers -> headers.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable))
.csrf(AbstractHttpConfigurer::disable);
return http.build();
| 127
| 233
| 360
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PigSecurityInnerAspect.java
|
PigSecurityInnerAspect
|
around
|
class PigSecurityInnerAspect implements Ordered {
private final HttpServletRequest request;
@SneakyThrows
@Before("@within(inner) || @annotation(inner)")
public void around(JoinPoint point, Inner inner) {<FILL_FUNCTION_BODY>}
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE + 1;
}
}
|
// 实际注入的inner实体由表达式后一个注解决定,即是方法上的@Inner注解实体,若方法上无@Inner注解,则获取类上的
if (inner == null) {
Class<?> clazz = point.getTarget().getClass();
inner = AnnotationUtils.findAnnotation(clazz, Inner.class);
}
String header = request.getHeader(SecurityConstants.FROM);
if (inner.value() && !StrUtil.equals(SecurityConstants.FROM_IN, header)) {
log.warn("访问接口 {} 没有权限", point.getSignature().getName());
throw new AccessDeniedException("Access is denied");
}
| 105
| 176
| 281
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PigSecurityMessageSourceConfiguration.java
|
PigSecurityMessageSourceConfiguration
|
securityMessageSource
|
class PigSecurityMessageSourceConfiguration implements WebMvcConfigurer {
@Bean
public MessageSource securityMessageSource() {<FILL_FUNCTION_BODY>}
}
|
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.addBasenames("classpath:i18n/errors/messages");
messageSource.setDefaultLocale(Locale.CHINA);
return messageSource;
| 44
| 72
| 116
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/ResourceAuthExceptionEntryPoint.java
|
ResourceAuthExceptionEntryPoint
|
commence
|
class ResourceAuthExceptionEntryPoint implements AuthenticationEntryPoint {
private final ObjectMapper objectMapper;
private final MessageSource messageSource;
@Override
@SneakyThrows
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) {<FILL_FUNCTION_BODY>}
}
|
response.setCharacterEncoding(CommonConstants.UTF8);
response.setContentType(CommonConstants.CONTENT_TYPE);
R<String> result = new R<>();
result.setCode(CommonConstants.FAIL);
response.setStatus(HttpStatus.UNAUTHORIZED.value());
if (authException != null) {
result.setMsg("error");
result.setData(authException.getMessage());
}
// 针对令牌过期返回特殊的 424
if (authException instanceof InvalidBearerTokenException
|| authException instanceof InsufficientAuthenticationException) {
response.setStatus(org.springframework.http.HttpStatus.FAILED_DEPENDENCY.value());
result.setMsg(this.messageSource.getMessage("OAuth2ResourceOwnerBaseAuthenticationProvider.tokenExpired",
null, LocaleContextHolder.getLocale()));
}
PrintWriter printWriter = response.getWriter();
printWriter.append(objectMapper.writeValueAsString(result));
| 81
| 266
| 347
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/feign/PigOAuthRequestInterceptor.java
|
PigOAuthRequestInterceptor
|
apply
|
class PigOAuthRequestInterceptor implements RequestInterceptor {
private final BearerTokenResolver tokenResolver;
/**
* Create a template with the header of provided name and extracted extract </br>
*
* 1. 如果使用 非web 请求,header 区别 </br>
*
* 2. 根据authentication 还原请求token
* @param template
*/
@Override
public void apply(RequestTemplate template) {<FILL_FUNCTION_BODY>}
}
|
Collection<String> fromHeader = template.headers().get(SecurityConstants.FROM);
// 带from 请求直接跳过
if (CollUtil.isNotEmpty(fromHeader) && fromHeader.contains(SecurityConstants.FROM_IN)) {
return;
}
// 非web 请求直接跳过
if (!WebUtils.getRequest().isPresent()) {
return;
}
HttpServletRequest request = WebUtils.getRequest().get();
// 避免请求参数的 query token 无法传递
String token = tokenResolver.resolve(request);
if (StrUtil.isBlank(token)) {
return;
}
template.header(HttpHeaders.AUTHORIZATION,
String.format("%s %s", OAuth2AccessToken.TokenType.BEARER.getValue(), token));
| 129
| 210
| 339
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/service/PigAppUserDetailsServiceImpl.java
|
PigAppUserDetailsServiceImpl
|
loadUserByUsername
|
class PigAppUserDetailsServiceImpl implements PigUserDetailsService {
private final RemoteUserService remoteUserService;
private final CacheManager cacheManager;
/**
* 手机号登录
* @param phone 手机号
* @return
*/
@Override
@SneakyThrows
public UserDetails loadUserByUsername(String phone) {<FILL_FUNCTION_BODY>}
/**
* check-token 使用
* @param pigUser user
* @return
*/
@Override
public UserDetails loadUserByUser(PigUser pigUser) {
return this.loadUserByUsername(pigUser.getPhone());
}
/**
* 是否支持此客户端校验
* @param clientId 目标客户端
* @return true/false
*/
@Override
public boolean support(String clientId, String grantType) {
return SecurityConstants.MOBILE.equals(grantType);
}
}
|
Cache cache = cacheManager.getCache(CacheConstants.USER_DETAILS);
if (cache != null && cache.get(phone) != null) {
return (PigUser) cache.get(phone).get();
}
UserDTO userDTO = new UserDTO();
userDTO.setPhone(phone);
R<UserInfo> result = remoteUserService.info(userDTO, SecurityConstants.FROM_IN);
UserDetails userDetails = getUserDetails(result);
if (cache != null) {
cache.put(phone, userDetails);
}
return userDetails;
| 240
| 165
| 405
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/service/PigRedisOAuth2AuthorizationConsentService.java
|
PigRedisOAuth2AuthorizationConsentService
|
findById
|
class PigRedisOAuth2AuthorizationConsentService implements OAuth2AuthorizationConsentService {
private final RedisTemplate<String, Object> redisTemplate;
private final static Long TIMEOUT = 10L;
@Override
public void save(OAuth2AuthorizationConsent authorizationConsent) {
Assert.notNull(authorizationConsent, "authorizationConsent cannot be null");
redisTemplate.opsForValue()
.set(buildKey(authorizationConsent), authorizationConsent, TIMEOUT, TimeUnit.MINUTES);
}
@Override
public void remove(OAuth2AuthorizationConsent authorizationConsent) {
Assert.notNull(authorizationConsent, "authorizationConsent cannot be null");
redisTemplate.delete(buildKey(authorizationConsent));
}
@Override
public OAuth2AuthorizationConsent findById(String registeredClientId, String principalName) {<FILL_FUNCTION_BODY>}
private static String buildKey(String registeredClientId, String principalName) {
return "token:consent:" + registeredClientId + ":" + principalName;
}
private static String buildKey(OAuth2AuthorizationConsent authorizationConsent) {
return buildKey(authorizationConsent.getRegisteredClientId(), authorizationConsent.getPrincipalName());
}
}
|
Assert.hasText(registeredClientId, "registeredClientId cannot be empty");
Assert.hasText(principalName, "principalName cannot be empty");
return (OAuth2AuthorizationConsent) redisTemplate.opsForValue()
.get(buildKey(registeredClientId, principalName));
| 336
| 81
| 417
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/service/PigRedisOAuth2AuthorizationService.java
|
PigRedisOAuth2AuthorizationService
|
save
|
class PigRedisOAuth2AuthorizationService implements OAuth2AuthorizationService {
private final static Long TIMEOUT = 10L;
private static final String AUTHORIZATION = "token";
private final RedisTemplate<String, Object> redisTemplate;
@Override
public void save(OAuth2Authorization authorization) {<FILL_FUNCTION_BODY>}
@Override
public void remove(OAuth2Authorization authorization) {
Assert.notNull(authorization, "authorization cannot be null");
List<String> keys = new ArrayList<>();
if (isState(authorization)) {
String token = authorization.getAttribute("state");
keys.add(buildKey(OAuth2ParameterNames.STATE, token));
}
if (isCode(authorization)) {
OAuth2Authorization.Token<OAuth2AuthorizationCode> authorizationCode = authorization
.getToken(OAuth2AuthorizationCode.class);
OAuth2AuthorizationCode authorizationCodeToken = authorizationCode.getToken();
keys.add(buildKey(OAuth2ParameterNames.CODE, authorizationCodeToken.getTokenValue()));
}
if (isRefreshToken(authorization)) {
OAuth2RefreshToken refreshToken = authorization.getRefreshToken().getToken();
keys.add(buildKey(OAuth2ParameterNames.REFRESH_TOKEN, refreshToken.getTokenValue()));
}
if (isAccessToken(authorization)) {
OAuth2AccessToken accessToken = authorization.getAccessToken().getToken();
keys.add(buildKey(OAuth2ParameterNames.ACCESS_TOKEN, accessToken.getTokenValue()));
}
redisTemplate.delete(keys);
}
@Override
@Nullable
public OAuth2Authorization findById(String id) {
throw new UnsupportedOperationException();
}
@Override
@Nullable
public OAuth2Authorization findByToken(String token, @Nullable OAuth2TokenType tokenType) {
Assert.hasText(token, "token cannot be empty");
Assert.notNull(tokenType, "tokenType cannot be empty");
redisTemplate.setValueSerializer(RedisSerializer.java());
return (OAuth2Authorization) redisTemplate.opsForValue().get(buildKey(tokenType.getValue(), token));
}
private String buildKey(String type, String id) {
return String.format("%s::%s::%s", AUTHORIZATION, type, id);
}
private static boolean isState(OAuth2Authorization authorization) {
return Objects.nonNull(authorization.getAttribute("state"));
}
private static boolean isCode(OAuth2Authorization authorization) {
OAuth2Authorization.Token<OAuth2AuthorizationCode> authorizationCode = authorization
.getToken(OAuth2AuthorizationCode.class);
return Objects.nonNull(authorizationCode);
}
private static boolean isRefreshToken(OAuth2Authorization authorization) {
return Objects.nonNull(authorization.getRefreshToken());
}
private static boolean isAccessToken(OAuth2Authorization authorization) {
return Objects.nonNull(authorization.getAccessToken());
}
}
|
Assert.notNull(authorization, "authorization cannot be null");
if (isState(authorization)) {
String token = authorization.getAttribute("state");
redisTemplate.setValueSerializer(RedisSerializer.java());
redisTemplate.opsForValue()
.set(buildKey(OAuth2ParameterNames.STATE, token), authorization, TIMEOUT, TimeUnit.MINUTES);
}
if (isCode(authorization)) {
OAuth2Authorization.Token<OAuth2AuthorizationCode> authorizationCode = authorization
.getToken(OAuth2AuthorizationCode.class);
OAuth2AuthorizationCode authorizationCodeToken = authorizationCode.getToken();
long between = ChronoUnit.MINUTES.between(authorizationCodeToken.getIssuedAt(),
authorizationCodeToken.getExpiresAt());
redisTemplate.setValueSerializer(RedisSerializer.java());
redisTemplate.opsForValue()
.set(buildKey(OAuth2ParameterNames.CODE, authorizationCodeToken.getTokenValue()), authorization,
between, TimeUnit.MINUTES);
}
if (isRefreshToken(authorization)) {
OAuth2RefreshToken refreshToken = authorization.getRefreshToken().getToken();
long between = ChronoUnit.SECONDS.between(refreshToken.getIssuedAt(), refreshToken.getExpiresAt());
redisTemplate.setValueSerializer(RedisSerializer.java());
redisTemplate.opsForValue()
.set(buildKey(OAuth2ParameterNames.REFRESH_TOKEN, refreshToken.getTokenValue()), authorization, between,
TimeUnit.SECONDS);
}
if (isAccessToken(authorization)) {
OAuth2AccessToken accessToken = authorization.getAccessToken().getToken();
long between = ChronoUnit.SECONDS.between(accessToken.getIssuedAt(), accessToken.getExpiresAt());
redisTemplate.setValueSerializer(RedisSerializer.java());
redisTemplate.opsForValue()
.set(buildKey(OAuth2ParameterNames.ACCESS_TOKEN, accessToken.getTokenValue()), authorization, between,
TimeUnit.SECONDS);
}
| 818
| 576
| 1,394
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/service/PigRemoteRegisteredClientRepository.java
|
PigRemoteRegisteredClientRepository
|
findByClientId
|
class PigRemoteRegisteredClientRepository implements RegisteredClientRepository {
/**
* 刷新令牌有效期默认 30 天
*/
private final static int refreshTokenValiditySeconds = 60 * 60 * 24 * 30;
/**
* 请求令牌有效期默认 12 小时
*/
private final static int accessTokenValiditySeconds = 60 * 60 * 12;
private final RemoteClientDetailsService clientDetailsService;
/**
* Saves the registered client.
*
* <p>
* IMPORTANT: Sensitive information should be encoded externally from the
* implementation, e.g. {@link RegisteredClient#getClientSecret()}
* @param registeredClient the {@link RegisteredClient}
*/
@Override
public void save(RegisteredClient registeredClient) {
}
/**
* Returns the registered client identified by the provided {@code id}, or
* {@code null} if not found.
* @param id the registration identifier
* @return the {@link RegisteredClient} if found, otherwise {@code null}
*/
@Override
public RegisteredClient findById(String id) {
throw new UnsupportedOperationException();
}
/**
* Returns the registered client identified by the provided {@code clientId}, or
* {@code null} if not found.
* @param clientId the client identifier
* @return the {@link RegisteredClient} if found, otherwise {@code null}
*/
/**
* 重写原生方法支持redis缓存
* @param clientId
* @return
*/
@Override
@SneakyThrows
@Cacheable(value = CacheConstants.CLIENT_DETAILS_KEY, key = "#clientId", unless = "#result == null")
public RegisteredClient findByClientId(String clientId) {<FILL_FUNCTION_BODY>}
}
|
SysOauthClientDetails clientDetails = RetOps
.of(clientDetailsService.getClientDetailsById(clientId, SecurityConstants.FROM_IN))
.getData()
.orElseThrow(() -> new OAuth2AuthorizationCodeRequestAuthenticationException(
new OAuth2Error("客户端查询异常,请检查数据库链接"), null));
RegisteredClient.Builder builder = RegisteredClient.withId(clientDetails.getClientId())
.clientId(clientDetails.getClientId())
.clientSecret(SecurityConstants.NOOP + clientDetails.getClientSecret())
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC);
for (String authorizedGrantType : clientDetails.getAuthorizedGrantTypes()) {
builder.authorizationGrantType(new AuthorizationGrantType(authorizedGrantType));
}
// 回调地址
Optional.ofNullable(clientDetails.getWebServerRedirectUri())
.ifPresent(redirectUri -> Arrays.stream(redirectUri.split(StrUtil.COMMA))
.filter(StrUtil::isNotBlank)
.forEach(builder::redirectUri));
// scope
Optional.ofNullable(clientDetails.getScope())
.ifPresent(scope -> Arrays.stream(scope.split(StrUtil.COMMA))
.filter(StrUtil::isNotBlank)
.forEach(builder::scope));
return builder
.tokenSettings(TokenSettings.builder()
.accessTokenFormat(OAuth2TokenFormat.REFERENCE)
.accessTokenTimeToLive(Duration.ofSeconds(
Optional.ofNullable(clientDetails.getAccessTokenValidity()).orElse(accessTokenValiditySeconds)))
.refreshTokenTimeToLive(Duration.ofSeconds(Optional.ofNullable(clientDetails.getRefreshTokenValidity())
.orElse(refreshTokenValiditySeconds)))
.build())
.clientSettings(ClientSettings.builder()
.requireAuthorizationConsent(!BooleanUtil.toBoolean(clientDetails.getAutoapprove()))
.build())
.build();
| 473
| 537
| 1,010
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/service/PigUserDetailsServiceImpl.java
|
PigUserDetailsServiceImpl
|
loadUserByUsername
|
class PigUserDetailsServiceImpl implements PigUserDetailsService {
private final RemoteUserService remoteUserService;
private final CacheManager cacheManager;
/**
* 用户名密码登录
* @param username 用户名
* @return
*/
@Override
@SneakyThrows
public UserDetails loadUserByUsername(String username) {<FILL_FUNCTION_BODY>}
@Override
public int getOrder() {
return Integer.MIN_VALUE;
}
}
|
Cache cache = cacheManager.getCache(CacheConstants.USER_DETAILS);
if (cache != null && cache.get(username) != null) {
return (PigUser) cache.get(username).get();
}
UserDTO userDTO = new UserDTO();
userDTO.setUsername(username);
R<UserInfo> result = remoteUserService.info(userDTO, SecurityConstants.FROM_IN);
UserDetails userDetails = getUserDetails(result);
if (cache != null) {
cache.put(username, userDetails);
}
return userDetails;
| 126
| 165
| 291
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/util/OAuth2EndpointUtils.java
|
OAuth2EndpointUtils
|
getParameters
|
class OAuth2EndpointUtils {
public final String ACCESS_TOKEN_REQUEST_ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc6749#section-5.2";
public MultiValueMap<String, String> getParameters(HttpServletRequest request) {<FILL_FUNCTION_BODY>}
public boolean matchesPkceTokenRequest(HttpServletRequest request) {
return AuthorizationGrantType.AUTHORIZATION_CODE.getValue()
.equals(request.getParameter(OAuth2ParameterNames.GRANT_TYPE))
&& request.getParameter(OAuth2ParameterNames.CODE) != null
&& request.getParameter(PkceParameterNames.CODE_VERIFIER) != null;
}
public void throwError(String errorCode, String parameterName, String errorUri) {
OAuth2Error error = new OAuth2Error(errorCode, "OAuth 2.0 Parameter: " + parameterName, errorUri);
throw new OAuth2AuthenticationException(error);
}
/**
* 格式化输出token 信息
* @param authentication 用户认证信息
* @param claims 扩展信息
* @return
* @throws IOException
*/
public OAuth2AccessTokenResponse sendAccessTokenResponse(OAuth2Authorization authentication,
Map<String, Object> claims) {
OAuth2AccessToken accessToken = authentication.getAccessToken().getToken();
OAuth2RefreshToken refreshToken = authentication.getRefreshToken().getToken();
OAuth2AccessTokenResponse.Builder builder = OAuth2AccessTokenResponse.withToken(accessToken.getTokenValue())
.tokenType(accessToken.getTokenType())
.scopes(accessToken.getScopes());
if (accessToken.getIssuedAt() != null && accessToken.getExpiresAt() != null) {
builder.expiresIn(ChronoUnit.SECONDS.between(accessToken.getIssuedAt(), accessToken.getExpiresAt()));
}
if (refreshToken != null) {
builder.refreshToken(refreshToken.getTokenValue());
}
if (MapUtil.isNotEmpty(claims)) {
builder.additionalParameters(claims);
}
return builder.build();
}
}
|
Map<String, String[]> parameterMap = request.getParameterMap();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(parameterMap.size());
parameterMap.forEach((key, values) -> {
if (values.length > 0) {
for (String value : values) {
parameters.add(key, value);
}
}
});
return parameters;
| 583
| 108
| 691
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/util/SecurityUtils.java
|
SecurityUtils
|
getUser
|
class SecurityUtils {
/**
* 获取Authentication
*/
public Authentication getAuthentication() {
return SecurityContextHolder.getContext().getAuthentication();
}
/**
* 获取用户
*/
public PigUser getUser(Authentication authentication) {
Object principal = authentication.getPrincipal();
if (principal instanceof PigUser) {
return (PigUser) principal;
}
return null;
}
/**
* 获取用户
*/
public PigUser getUser() {<FILL_FUNCTION_BODY>}
/**
* 获取用户角色信息
* @return 角色集合
*/
public List<Long> getRoles() {
Authentication authentication = getAuthentication();
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
List<Long> roleIds = new ArrayList<>();
authorities.stream()
.filter(granted -> StrUtil.startWith(granted.getAuthority(), SecurityConstants.ROLE))
.forEach(granted -> {
String id = StrUtil.removePrefix(granted.getAuthority(), SecurityConstants.ROLE);
roleIds.add(Long.parseLong(id));
});
return roleIds;
}
}
|
Authentication authentication = getAuthentication();
if (authentication == null) {
return null;
}
return getUser(authentication);
| 318
| 39
| 357
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-swagger/src/main/java/com/pig4cloud/pig/common/swagger/config/OpenAPIDefinition.java
|
OpenAPIDefinition
|
securityScheme
|
class OpenAPIDefinition extends OpenAPI implements InitializingBean, ApplicationContextAware {
@Setter
private String path;
private ApplicationContext applicationContext;
private SecurityScheme securityScheme(SwaggerProperties swaggerProperties) {<FILL_FUNCTION_BODY>}
@Override
public void afterPropertiesSet() throws Exception {
SwaggerProperties swaggerProperties = applicationContext.getBean(SwaggerProperties.class);
this.info(new Info().title(swaggerProperties.getTitle()));
// oauth2.0 password
this.schemaRequirement(HttpHeaders.AUTHORIZATION, this.securityScheme(swaggerProperties));
// servers
List<Server> serverList = new ArrayList<>();
serverList.add(new Server().url(swaggerProperties.getGateway() + "/" + path));
this.servers(serverList);
// 支持参数平铺
SpringDocUtils.getConfig().addSimpleTypesForParameterObject(Class.class);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
|
OAuthFlow clientCredential = new OAuthFlow();
clientCredential.setTokenUrl(swaggerProperties.getTokenUrl());
clientCredential.setScopes(new Scopes().addString(swaggerProperties.getScope(), swaggerProperties.getScope()));
OAuthFlows oauthFlows = new OAuthFlows();
oauthFlows.password(clientCredential);
SecurityScheme securityScheme = new SecurityScheme();
securityScheme.setType(SecurityScheme.Type.OAUTH2);
securityScheme.setFlows(oauthFlows);
return securityScheme;
| 281
| 160
| 441
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-swagger/src/main/java/com/pig4cloud/pig/common/swagger/config/OpenAPIDefinitionImportSelector.java
|
OpenAPIDefinitionImportSelector
|
registerBeanDefinitions
|
class OpenAPIDefinitionImportSelector implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {<FILL_FUNCTION_BODY>}
}
|
Map<String, Object> annotationAttributes = metadata.getAnnotationAttributes(EnablePigDoc.class.getName(), true);
Object value = annotationAttributes.get("value");
if (Objects.isNull(value)) {
return;
}
BeanDefinitionBuilder definition = BeanDefinitionBuilder.genericBeanDefinition(OpenAPIDefinition.class);
definition.addPropertyValue("path", value);
definition.setPrimary(true);
registry.registerBeanDefinition("openAPIDefinition", definition.getBeanDefinition());
// 如果是微服务架构则,引入了服务发现声明相关的元数据配置
Object isMicro = annotationAttributes.getOrDefault("isMicro", true);
if (isMicro.equals(false)) {
return;
}
BeanDefinitionBuilder openAPIMetadata = BeanDefinitionBuilder
.genericBeanDefinition(OpenAPIMetadataConfiguration.class);
openAPIMetadata.addPropertyValue("path", value);
registry.registerBeanDefinition("openAPIMetadata", openAPIMetadata.getBeanDefinition());
| 56
| 277
| 333
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-swagger/src/main/java/com/pig4cloud/pig/common/swagger/config/OpenAPIMetadataConfiguration.java
|
OpenAPIMetadataConfiguration
|
afterPropertiesSet
|
class OpenAPIMetadataConfiguration implements InitializingBean, ApplicationContextAware {
private ApplicationContext applicationContext;
@Setter
private String path;
@Override
public void afterPropertiesSet() throws Exception {<FILL_FUNCTION_BODY>}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
|
String[] beanNamesForType = applicationContext.getBeanNamesForType(ServiceInstance.class);
if (beanNamesForType.length == 0) {
return;
}
ServiceInstance serviceInstance = applicationContext.getBean(ServiceInstance.class);
serviceInstance.getMetadata().put("spring-doc", path);
| 98
| 86
| 184
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-xss/src/main/java/com/pig4cloud/pig/common/xss/PigXssAutoConfiguration.java
|
PigXssAutoConfiguration
|
addInterceptors
|
class PigXssAutoConfiguration implements WebMvcConfigurer {
private final com.pig4cloud.pig.common.xss.config.PigXssProperties xssProperties;
@Bean
@ConditionalOnMissingBean
public XssCleaner xssCleaner(com.pig4cloud.pig.common.xss.config.PigXssProperties properties) {
return new DefaultXssCleaner(properties);
}
@Bean
public FormXssClean formXssClean(com.pig4cloud.pig.common.xss.config.PigXssProperties properties,
XssCleaner xssCleaner) {
return new FormXssClean(properties, xssCleaner);
}
@Bean
public Jackson2ObjectMapperBuilderCustomizer xssJacksonCustomizer(
com.pig4cloud.pig.common.xss.config.PigXssProperties properties, XssCleaner xssCleaner) {
return builder -> builder.deserializerByType(String.class, new JacksonXssClean(properties, xssCleaner));
}
@Override
public void addInterceptors(InterceptorRegistry registry) {<FILL_FUNCTION_BODY>}
}
|
List<String> patterns = xssProperties.getPathPatterns();
if (patterns.isEmpty()) {
patterns.add("/**");
}
com.pig4cloud.pig.common.xss.core.XssCleanInterceptor interceptor = new com.pig4cloud.pig.common.xss.core.XssCleanInterceptor(
xssProperties);
registry.addInterceptor(interceptor)
.addPathPatterns(patterns)
.excludePathPatterns(xssProperties.getPathExcludePatterns())
.order(Ordered.LOWEST_PRECEDENCE);
| 301
| 169
| 470
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-xss/src/main/java/com/pig4cloud/pig/common/xss/core/DefaultXssCleaner.java
|
DefaultXssCleaner
|
clean
|
class DefaultXssCleaner implements XssCleaner {
private final PigXssProperties properties;
public DefaultXssCleaner(PigXssProperties properties) {
this.properties = properties;
}
private static Document.OutputSettings getOutputSettings(PigXssProperties properties) {
return new Document.OutputSettings()
// 2. 转义,没找到关闭的方法,目前这个规则最少
.escapeMode(Entities.EscapeMode.xhtml)
// 3. 保留换行
.prettyPrint(properties.isPrettyPrint());
}
@Override
public String clean(String bodyHtml, XssType type) {<FILL_FUNCTION_BODY>}
}
|
// 1. 为空直接返回
if (StringUtil.isBlank(bodyHtml)) {
return bodyHtml;
}
PigXssProperties.Mode mode = properties.getMode();
if (PigXssProperties.Mode.escape == mode) {
// html 转义
return HtmlUtils.htmlEscape(bodyHtml, CharsetUtil.UTF_8);
}
else if (PigXssProperties.Mode.validate == mode) {
// 校验
if (Jsoup.isValid(bodyHtml, XssUtil.WHITE_LIST)) {
return bodyHtml;
}
throw type.getXssException(bodyHtml, "Xss validate fail, input value:" + bodyHtml);
}
else {
// 4. 清理后的 html
String escapedHtml = Jsoup.clean(bodyHtml, "", XssUtil.WHITE_LIST, getOutputSettings(properties));
if (properties.isEnableEscape()) {
return escapedHtml;
}
// 5. 反转义
return Entities.unescape(escapedHtml);
}
| 175
| 286
| 461
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-xss/src/main/java/com/pig4cloud/pig/common/xss/core/FormXssClean.java
|
StringPropertiesEditor
|
setAsText
|
class StringPropertiesEditor extends PropertyEditorSupport {
private final XssCleaner xssCleaner;
private final PigXssProperties properties;
@Override
public String getAsText() {
Object value = getValue();
return value != null ? value.toString() : StrUtil.EMPTY;
}
@Override
public void setAsText(String text) throws IllegalArgumentException {<FILL_FUNCTION_BODY>}
}
|
if (text == null) {
setValue(null);
}
else if (XssHolder.isEnabled()) {
String value = xssCleaner.clean(XssUtil.trim(text, properties.isTrimText()));
setValue(value);
log.debug("Request parameter value:{} cleaned up by mica-xss, current value is:{}.", text, value);
}
else {
setValue(XssUtil.trim(text, properties.isTrimText()));
}
| 117
| 132
| 249
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-xss/src/main/java/com/pig4cloud/pig/common/xss/core/JacksonXssClean.java
|
JacksonXssClean
|
clean
|
class JacksonXssClean extends XssCleanDeserializerBase {
private final PigXssProperties properties;
private final XssCleaner xssCleaner;
@Override
public String clean(String name, String text) throws IOException {<FILL_FUNCTION_BODY>}
}
|
if (XssHolder.isEnabled() && Objects.isNull(XssHolder.getXssCleanIgnore())) {
String value = xssCleaner.clean(XssUtil.trim(text, properties.isTrimText()));
log.debug("Json property value:{} cleaned up by mica-xss, current value is:{}.", text, value);
return value;
}
else if (XssHolder.isEnabled() && Objects.nonNull(XssHolder.getXssCleanIgnore())) {
XssCleanIgnore xssCleanIgnore = XssHolder.getXssCleanIgnore();
if (ArrayUtil.contains(xssCleanIgnore.value(), name)) {
return XssUtil.trim(text, properties.isTrimText());
}
String value = xssCleaner.clean(XssUtil.trim(text, properties.isTrimText()));
log.debug("Json property value:{} cleaned up by mica-xss, current value is:{}.", text, value);
return value;
}
else {
return XssUtil.trim(text, properties.isTrimText());
}
| 72
| 280
| 352
|
<methods>public non-sealed void <init>() ,public abstract java.lang.String clean(java.lang.String, java.lang.String) throws java.io.IOException,public java.lang.String deserialize(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.DeserializationContext) throws java.io.IOException<variables>
|
pig-mesh_pig
|
pig/pig-common/pig-common-xss/src/main/java/com/pig4cloud/pig/common/xss/core/XssCleanDeserializer.java
|
XssCleanDeserializer
|
clean
|
class XssCleanDeserializer extends XssCleanDeserializerBase {
@Override
public String clean(String name, String text) throws IOException {<FILL_FUNCTION_BODY>}
}
|
// 读取 xss 配置
PigXssProperties properties = SpringContextHolder.getBean(PigXssProperties.class);
// 读取 XssCleaner bean
XssCleaner xssCleaner = SpringContextHolder.getBean(XssCleaner.class);
if (xssCleaner != null) {
String value = xssCleaner.clean(XssUtil.trim(text, properties.isTrimText()));
log.debug("Json property value:{} cleaned up by mica-xss, current value is:{}.", text, value);
return value;
}
else {
return XssUtil.trim(text, properties.isTrimText());
}
| 50
| 178
| 228
|
<methods>public non-sealed void <init>() ,public abstract java.lang.String clean(java.lang.String, java.lang.String) throws java.io.IOException,public java.lang.String deserialize(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.DeserializationContext) throws java.io.IOException<variables>
|
pig-mesh_pig
|
pig/pig-common/pig-common-xss/src/main/java/com/pig4cloud/pig/common/xss/core/XssCleanDeserializerBase.java
|
XssCleanDeserializerBase
|
deserialize
|
class XssCleanDeserializerBase extends JsonDeserializer<String> {
@Override
public String deserialize(JsonParser p, DeserializationContext ctx) throws IOException {<FILL_FUNCTION_BODY>}
/**
* 清理 xss
* @param name name
* @param text text
* @return String
*/
public abstract String clean(String name, String text) throws IOException;
}
|
JsonToken jsonToken = p.getCurrentToken();
if (JsonToken.VALUE_STRING != jsonToken) {
throw MismatchedInputException.from(p, String.class,
"mica-xss: can't deserialize value of type java.lang.String from " + jsonToken);
}
// 解析字符串
String text = p.getValueAsString();
if (text == null) {
return null;
}
// xss 配置
return this.clean(p.getCurrentName(), text);
| 105
| 144
| 249
|
<methods>public void <init>() ,public abstract java.lang.String deserialize(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.DeserializationContext) throws java.io.IOException, com.fasterxml.jackson.core.JacksonException,public java.lang.String deserialize(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.DeserializationContext, java.lang.String) throws java.io.IOException, com.fasterxml.jackson.core.JacksonException,public java.lang.Object deserializeWithType(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.DeserializationContext, com.fasterxml.jackson.databind.jsontype.TypeDeserializer) throws java.io.IOException, com.fasterxml.jackson.core.JacksonException,public java.lang.Object deserializeWithType(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.DeserializationContext, com.fasterxml.jackson.databind.jsontype.TypeDeserializer, java.lang.String) throws java.io.IOException, com.fasterxml.jackson.core.JacksonException,public com.fasterxml.jackson.databind.deser.SettableBeanProperty findBackReference(java.lang.String) ,public java.lang.Object getAbsentValue(com.fasterxml.jackson.databind.DeserializationContext) throws com.fasterxml.jackson.databind.JsonMappingException,public JsonDeserializer<?> getDelegatee() ,public com.fasterxml.jackson.databind.util.AccessPattern getEmptyAccessPattern() ,public java.lang.Object getEmptyValue() ,public java.lang.Object getEmptyValue(com.fasterxml.jackson.databind.DeserializationContext) throws com.fasterxml.jackson.databind.JsonMappingException,public Collection<java.lang.Object> getKnownPropertyNames() ,public com.fasterxml.jackson.databind.util.AccessPattern getNullAccessPattern() ,public java.lang.String getNullValue() ,public java.lang.String getNullValue(com.fasterxml.jackson.databind.DeserializationContext) throws com.fasterxml.jackson.databind.JsonMappingException,public com.fasterxml.jackson.databind.deser.impl.ObjectIdReader getObjectIdReader() ,public Class<?> handledType() ,public boolean isCachable() ,public com.fasterxml.jackson.databind.type.LogicalType logicalType() ,public JsonDeserializer<?> replaceDelegatee(JsonDeserializer<?>) ,public java.lang.Boolean supportsUpdate(com.fasterxml.jackson.databind.DeserializationConfig) ,public JsonDeserializer<java.lang.String> unwrappingDeserializer(com.fasterxml.jackson.databind.util.NameTransformer) <variables>
|
pig-mesh_pig
|
pig/pig-common/pig-common-xss/src/main/java/com/pig4cloud/pig/common/xss/core/XssCleanInterceptor.java
|
XssCleanInterceptor
|
preHandle
|
class XssCleanInterceptor implements AsyncHandlerInterceptor {
private final PigXssProperties xssProperties;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {<FILL_FUNCTION_BODY>}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
XssHolder.remove();
}
@Override
public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
XssHolder.remove();
}
}
|
// 1. 非控制器请求直接跳出
if (!(handler instanceof HandlerMethod)) {
return true;
}
// 2. 没有开启
if (!xssProperties.isEnabled()) {
return true;
}
// 3. 处理 XssIgnore 注解
HandlerMethod handlerMethod = (HandlerMethod) handler;
XssCleanIgnore xssCleanIgnore = AnnotationUtils.getAnnotation(handlerMethod.getMethod(), XssCleanIgnore.class);
if (xssCleanIgnore == null) {
XssHolder.setEnable();
}
else if (ArrayUtil.isNotEmpty(xssCleanIgnore.value())) {
XssHolder.setEnable();
XssHolder.setXssCleanIgnore(xssCleanIgnore);
}
return true;
| 162
| 207
| 369
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-common/pig-common-xss/src/main/java/com/pig4cloud/pig/common/xss/utils/XssUtil.java
|
XssUtil
|
clean
|
class XssUtil {
public static final HtmlSafeList WHITE_LIST = HtmlSafeList.INSTANCE;
/**
* trim 字符串
* @param text text
* @return 清理后的 text
*/
public static String trim(String text, boolean trim) {
return trim ? StringUtils.trimWhitespace(text) : text;
}
/**
* xss 清理
* @param html html
* @return 清理后的 html
*/
public static String clean(String html) {<FILL_FUNCTION_BODY>}
/**
* 做自己的白名单,允许base64的图片通过等
*
* @author michael
*/
public static class HtmlSafeList extends org.jsoup.safety.Safelist {
public static final HtmlSafeList INSTANCE = new HtmlSafeList();
public HtmlSafeList() {
addTags("a", "b", "blockquote", "br", "caption", "cite", "code", "col", "colgroup", "dd", "div", "span",
"embed", "object", "dl", "dt", "em", "h1", "h2", "h3", "h4", "h5", "h6", "i", "img", "li", "ol",
"p", "pre", "q", "small", "strike", "strong", "sub", "sup", "table", "tbody", "td", "tfoot", "th",
"thead", "tr", "u", "ul");
addAttributes("a", "href", "title", "target");
addAttributes("blockquote", "cite");
addAttributes("col", "span");
addAttributes("colgroup", "span");
addAttributes("img", "align", "alt", "src", "title");
addAttributes("ol", "start");
addAttributes("q", "cite");
addAttributes("table", "summary");
addAttributes("td", "abbr", "axis", "colspan", "rowspan", "width");
addAttributes("th", "abbr", "axis", "colspan", "rowspan", "scope", "width");
addAttributes("video", "src", "autoplay", "controls", "loop", "muted", "poster", "preload");
addAttributes("object", "width", "height", "classid", "codebase");
addAttributes("param", "name", "value");
addAttributes("embed", "src", "quality", "width", "height", "allowFullScreen", "allowScriptAccess",
"flashvars", "name", "type", "pluginspage");
addAttributes(":all", "class", "style", "height", "width", "type", "id", "name");
addProtocols("blockquote", "cite", "http", "https");
addProtocols("cite", "cite", "http", "https");
addProtocols("q", "cite", "http", "https");
// 如果添加以下的协议,那么href 必须是http、 https 等开头,相对路径则被过滤掉了
// addProtocols("a", "href", "ftp", "http", "https", "mailto", "tel");
// 如果添加以下的协议,那么src必须是http 或者 https 开头,相对路径则被过滤掉了,
// 所以必须注释掉,允许相对路径的图片资源
// addProtocols("img", "src", "http", "https");
}
@Override
public boolean isSafeAttribute(String tagName, Element el, Attribute attr) {
// 不允许 javascript 开头的 src 和 href
if ("src".equalsIgnoreCase(attr.getKey()) || "href".equalsIgnoreCase(attr.getKey())) {
String value = attr.getValue();
if (StringUtils.hasText(value) && value.toLowerCase().startsWith("javascript")) {
return false;
}
}
// 允许 base64 的图片内容
if ("img".equals(tagName) && "src".equals(attr.getKey()) && attr.getValue().startsWith("data:;base64")) {
return true;
}
return super.isSafeAttribute(tagName, el, attr);
}
}
}
|
if (StringUtils.hasText(html)) {
return Jsoup.clean(html, WHITE_LIST);
}
return html;
| 1,085
| 41
| 1,126
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-gateway/src/main/java/com/pig4cloud/pig/gateway/config/SpringDocConfiguration.java
|
SwaggerDocRegister
|
onEvent
|
class SwaggerDocRegister extends Subscriber<InstancesChangeEvent> {
private final SwaggerUiConfigProperties swaggerUiConfigProperties;
private final DiscoveryClient discoveryClient;
/**
* 事件回调方法,处理InstancesChangeEvent事件
* @param event 事件对象
*/
@Override
public void onEvent(InstancesChangeEvent event) {<FILL_FUNCTION_BODY>}
/**
* 订阅类型方法,返回订阅的事件类型
* @return 订阅的事件类型
*/
@Override
public Class<? extends Event> subscribeType() {
return InstancesChangeEvent.class;
}
}
|
Set<AbstractSwaggerUiConfigProperties.SwaggerUrl> swaggerUrlSet = discoveryClient.getServices()
.stream()
.flatMap(serviceId -> discoveryClient.getInstances(serviceId).stream())
.filter(instance -> StringUtils.isNotBlank(instance.getMetadata().get("spring-doc")))
.map(instance -> {
AbstractSwaggerUiConfigProperties.SwaggerUrl swaggerUrl = new AbstractSwaggerUiConfigProperties.SwaggerUrl();
swaggerUrl.setName(instance.getServiceId());
swaggerUrl.setUrl(String.format("/%s/v3/api-docs", instance.getMetadata().get("spring-doc")));
return swaggerUrl;
})
.collect(Collectors.toSet());
swaggerUiConfigProperties.setUrls(swaggerUrlSet);
| 165
| 220
| 385
|
<methods>public void <init>() ,public java.util.concurrent.Executor executor() ,public boolean ignoreExpireEvent() ,public abstract void onEvent(com.alibaba.nacos.client.naming.event.InstancesChangeEvent) ,public boolean scopeMatches(com.alibaba.nacos.client.naming.event.InstancesChangeEvent) ,public abstract Class<? extends com.alibaba.nacos.common.notify.Event> subscribeType() <variables>
|
pig-mesh_pig
|
pig/pig-gateway/src/main/java/com/pig4cloud/pig/gateway/filter/PigRequestGlobalFilter.java
|
PigRequestGlobalFilter
|
filter
|
class PigRequestGlobalFilter implements GlobalFilter, Ordered {
/**
* Process the Web request and (optionally) delegate to the next {@code WebFilter}
* through the given {@link GatewayFilterChain}.
* @param exchange the current server exchange
* @param chain provides a way to delegate to the next filter
* @return {@code Mono<Void>} to indicate when request processing is complete
*/
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {<FILL_FUNCTION_BODY>}
@Override
public int getOrder() {
return 10;
}
}
|
// 1. 清洗请求头中from 参数
ServerHttpRequest request = exchange.getRequest().mutate().headers(httpHeaders -> {
httpHeaders.remove(SecurityConstants.FROM);
// 设置请求时间
httpHeaders.put(CommonConstants.REQUEST_START_TIME,
Collections.singletonList(String.valueOf(System.currentTimeMillis())));
}).build();
// 2. 重写StripPrefix
addOriginalRequestUrl(exchange, request.getURI());
String rawPath = request.getURI().getRawPath();
String newPath = "/" + Arrays.stream(StringUtils.tokenizeToStringArray(rawPath, "/"))
.skip(1L)
.collect(Collectors.joining("/"));
ServerHttpRequest newRequest = request.mutate().path(newPath).build();
exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, newRequest.getURI());
return chain.filter(exchange.mutate().request(newRequest.mutate().build()).build());
| 161
| 273
| 434
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-gateway/src/main/java/com/pig4cloud/pig/gateway/handler/GlobalExceptionHandler.java
|
GlobalExceptionHandler
|
handle
|
class GlobalExceptionHandler implements ErrorWebExceptionHandler {
private final ObjectMapper objectMapper;
@Override
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {<FILL_FUNCTION_BODY>}
}
|
ServerHttpResponse response = exchange.getResponse();
if (response.isCommitted()) {
return Mono.error(ex);
}
// header set
response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
if (ex instanceof ResponseStatusException) {
response.setStatusCode(((ResponseStatusException) ex).getStatusCode());
}
return response.writeWith(Mono.fromSupplier(() -> {
DataBufferFactory bufferFactory = response.bufferFactory();
try {
log.debug("Error Spring Cloud Gateway : {} {}", exchange.getRequest().getPath(), ex.getMessage());
return bufferFactory.wrap(objectMapper.writeValueAsBytes(R.failed(ex.getMessage())));
}
catch (JsonProcessingException e) {
log.error("Error writing response", ex);
return bufferFactory.wrap(new byte[0]);
}
}));
| 61
| 242
| 303
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-register/src/main/java/com/alibaba/nacos/PigNacosApplication.java
|
PigNacosApplication
|
initEnv
|
class PigNacosApplication {
public static void main(String[] args) {
if (initEnv()) {
SpringApplication.run(PigNacosApplication.class, args);
}
}
/**
* 初始化运行环境
*/
private static boolean initEnv() {<FILL_FUNCTION_BODY>}
}
|
System.setProperty(ConfigConstants.STANDALONE_MODE, "true");
System.setProperty(ConfigConstants.AUTH_ENABLED, "true");
System.setProperty(ConfigConstants.LOG_BASEDIR, "logs");
System.setProperty(ConfigConstants.LOG_ENABLED, "false");
System.setProperty(ConfigConstants.NACOS_CONTEXT_PATH, "/nacos");
return true;
| 92
| 113
| 205
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-register/src/main/java/com/alibaba/nacos/config/ConsoleConfig.java
|
ConsoleConfig
|
corsFilter
|
class ConsoleConfig {
@Autowired
private ControllerMethodsCache methodsCache;
/**
* Init.
*/
@PostConstruct
public void init() {
methodsCache.initClassMethod("com.alibaba.nacos.core.controller");
methodsCache.initClassMethod("com.alibaba.nacos.naming.controllers");
methodsCache.initClassMethod("com.alibaba.nacos.config.server.controller");
methodsCache.initClassMethod("com.alibaba.nacos.controller");
}
@Bean
public CorsFilter corsFilter() {<FILL_FUNCTION_BODY>}
@Bean
public Jackson2ObjectMapperBuilderCustomizer jacksonObjectMapperCustomization() {
return jacksonObjectMapperBuilder -> jacksonObjectMapperBuilder.timeZone(ZoneId.systemDefault().toString());
}
}
|
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.setMaxAge(18000L);
config.addAllowedMethod("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
| 219
| 125
| 344
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-register/src/main/java/com/alibaba/nacos/console/controller/HealthController.java
|
HealthController
|
readiness
|
class HealthController {
private static final Logger LOGGER = LoggerFactory.getLogger(HealthController.class);
private final ConfigInfoPersistService configInfoPersistService;
private final OperatorController apiCommands;
@Autowired
public HealthController(ConfigInfoPersistService configInfoPersistService, OperatorController apiCommands) {
this.configInfoPersistService = configInfoPersistService;
this.apiCommands = apiCommands;
}
/**
* Whether the Nacos is in broken states or not, and cannot recover except by being
* restarted.
* @return HTTP code equal to 200 indicates that Nacos is in right states. HTTP code
* equal to 500 indicates that Nacos is in broken states.
*/
@GetMapping("/liveness")
public ResponseEntity<String> liveness() {
return ResponseEntity.ok().body("OK");
}
/**
* Ready to receive the request or not.
* @return HTTP code equal to 200 indicates that Nacos is ready. HTTP code equal to
* 500 indicates that Nacos is not ready.
*/
@GetMapping("/readiness")
public ResponseEntity<String> readiness(HttpServletRequest request) {<FILL_FUNCTION_BODY>}
private boolean isConfigReadiness() {
// check db
try {
configInfoPersistService.configInfoCount("");
return true;
}
catch (Exception e) {
LOGGER.error("Config health check fail.", e);
}
return false;
}
private boolean isNamingReadiness(HttpServletRequest request) {
try {
apiCommands.metrics(request);
return true;
}
catch (Exception e) {
LOGGER.error("Naming health check fail.", e);
}
return false;
}
}
|
boolean isConfigReadiness = isConfigReadiness();
boolean isNamingReadiness = isNamingReadiness(request);
if (isConfigReadiness && isNamingReadiness) {
return ResponseEntity.ok().body("OK");
}
if (!isConfigReadiness && !isNamingReadiness) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("Config and Naming are not in readiness");
}
if (!isConfigReadiness) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Config is not in readiness");
}
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Naming is not in readiness");
| 473
| 194
| 667
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-register/src/main/java/com/alibaba/nacos/console/controller/NamespaceController.java
|
NamespaceController
|
createNamespace
|
class NamespaceController {
@Autowired
private CommonPersistService commonPersistService;
@Autowired
private NamespaceOperationService namespaceOperationService;
private final Pattern namespaceIdCheckPattern = Pattern.compile("^[\\w-]+");
private static final int NAMESPACE_ID_MAX_LENGTH = 128;
/**
* Get namespace list.
* @return namespace list
*/
@GetMapping
public RestResult<List<Namespace>> getNamespaces() {
return RestResultUtils.success(namespaceOperationService.getNamespaceList());
}
/**
* get namespace all info by namespace id.
* @param namespaceId namespaceId
* @return namespace all info
*/
@GetMapping(params = "show=all")
public NamespaceAllInfo getNamespace(@RequestParam("namespaceId") String namespaceId) throws NacosException {
return namespaceOperationService.getNamespace(namespaceId);
}
/**
* create namespace.
* @param namespaceName namespace Name
* @param namespaceDesc namespace Desc
* @return whether create ok
*/
@PostMapping
@Secured(resource = AuthConstants.CONSOLE_RESOURCE_NAME_PREFIX + "namespaces", action = ActionTypes.WRITE)
public Boolean createNamespace(@RequestParam("customNamespaceId") String namespaceId,
@RequestParam("namespaceName") String namespaceName,
@RequestParam(value = "namespaceDesc", required = false) String namespaceDesc) {<FILL_FUNCTION_BODY>}
/**
* check namespaceId exist.
* @param namespaceId namespace id
* @return true if exist, otherwise false
*/
@GetMapping(params = "checkNamespaceIdExist=true")
public Boolean checkNamespaceIdExist(@RequestParam("customNamespaceId") String namespaceId) {
if (StringUtils.isBlank(namespaceId)) {
return false;
}
return (commonPersistService.tenantInfoCountByTenantId(namespaceId) > 0);
}
/**
* edit namespace.
* @param namespace namespace
* @param namespaceShowName namespace ShowName
* @param namespaceDesc namespace Desc
* @return whether edit ok
*/
@PutMapping
@Secured(resource = AuthConstants.CONSOLE_RESOURCE_NAME_PREFIX + "namespaces", action = ActionTypes.WRITE)
public Boolean editNamespace(@RequestParam("namespace") String namespace,
@RequestParam("namespaceShowName") String namespaceShowName,
@RequestParam(value = "namespaceDesc", required = false) String namespaceDesc) {
return namespaceOperationService.editNamespace(namespace, namespaceShowName, namespaceDesc);
}
/**
* del namespace by id.
* @param namespaceId namespace Id
* @return whether del ok
*/
@DeleteMapping
@Secured(resource = AuthConstants.CONSOLE_RESOURCE_NAME_PREFIX + "namespaces", action = ActionTypes.WRITE)
public Boolean deleteNamespace(@RequestParam("namespaceId") String namespaceId) {
return namespaceOperationService.removeNamespace(namespaceId);
}
}
|
if (StringUtils.isBlank(namespaceId)) {
namespaceId = UUID.randomUUID().toString();
}
else {
namespaceId = namespaceId.trim();
if (!namespaceIdCheckPattern.matcher(namespaceId).matches()) {
return false;
}
if (namespaceId.length() > NAMESPACE_ID_MAX_LENGTH) {
return false;
}
}
try {
return namespaceOperationService.createNamespace(namespaceId, namespaceName, namespaceDesc);
}
catch (NacosException e) {
return false;
}
| 750
| 157
| 907
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-register/src/main/java/com/alibaba/nacos/console/controller/ServerStateController.java
|
ServerStateController
|
serverState
|
class ServerStateController {
private static final String ANNOUNCEMENT_FILE = "conf/announcement.conf";
/**
* Get server state of current server.
* @return state json.
*/
@GetMapping("/state")
public ResponseEntity<Map<String, String>> serverState() {<FILL_FUNCTION_BODY>}
@SneakyThrows
@GetMapping("/announcement")
public RestResult<String> getAnnouncement() {
return RestResultUtils.success();
}
}
|
Map<String, String> serverState = new HashMap<>(4);
for (ModuleState each : ModuleStateHolder.getInstance().getAllModuleStates()) {
each.getStates().forEach((s, o) -> serverState.put(s, null == o ? null : o.toString()));
}
return ResponseEntity.ok().body(serverState);
| 131
| 93
| 224
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-register/src/main/java/com/alibaba/nacos/console/controller/v2/NamespaceControllerV2.java
|
NamespaceControllerV2
|
createNamespace
|
class NamespaceControllerV2 {
private final NamespaceOperationService namespaceOperationService;
public NamespaceControllerV2(NamespaceOperationService namespaceOperationService) {
this.namespaceOperationService = namespaceOperationService;
}
private final Pattern namespaceIdCheckPattern = Pattern.compile("^[\\w-]+");
private static final int NAMESPACE_ID_MAX_LENGTH = 128;
/**
* Get namespace list.
* @return namespace list
*/
@GetMapping("/list")
public Result<List<Namespace>> getNamespaceList() {
return Result.success(namespaceOperationService.getNamespaceList());
}
/**
* get namespace all info by namespace id.
* @param namespaceId namespaceId
* @return namespace all info
*/
@GetMapping()
@Secured(resource = AuthConstants.CONSOLE_RESOURCE_NAME_PREFIX + "namespaces", action = ActionTypes.READ,
signType = SignType.CONSOLE)
public Result<NamespaceAllInfo> getNamespace(@RequestParam("namespaceId") String namespaceId)
throws NacosException {
return Result.success(namespaceOperationService.getNamespace(namespaceId));
}
/**
* create namespace.
* @param namespaceForm namespaceForm.
* @return whether create ok
*/
@PostMapping
@Secured(resource = AuthConstants.CONSOLE_RESOURCE_NAME_PREFIX + "namespaces", action = ActionTypes.WRITE,
signType = SignType.CONSOLE)
public Result<Boolean> createNamespace(NamespaceForm namespaceForm) throws NacosException {<FILL_FUNCTION_BODY>}
/**
* edit namespace.
* @param namespaceForm namespace params
* @return whether edit ok
*/
@PutMapping
@Secured(resource = AuthConstants.CONSOLE_RESOURCE_NAME_PREFIX + "namespaces", action = ActionTypes.WRITE,
signType = SignType.CONSOLE)
public Result<Boolean> editNamespace(NamespaceForm namespaceForm) throws NacosException {
namespaceForm.validate();
return Result.success(namespaceOperationService.editNamespace(namespaceForm.getNamespaceId(),
namespaceForm.getNamespaceName(), namespaceForm.getNamespaceDesc()));
}
/**
* delete namespace by id.
* @param namespaceId namespace ID
* @return whether delete ok
*/
@DeleteMapping
@Secured(resource = AuthConstants.CONSOLE_RESOURCE_NAME_PREFIX + "namespaces", action = ActionTypes.WRITE,
signType = SignType.CONSOLE)
public Result<Boolean> deleteNamespace(@RequestParam("namespaceId") String namespaceId) {
return Result.success(namespaceOperationService.removeNamespace(namespaceId));
}
}
|
namespaceForm.validate();
String namespaceId = namespaceForm.getNamespaceId();
String namespaceName = namespaceForm.getNamespaceName();
String namespaceDesc = namespaceForm.getNamespaceDesc();
if (StringUtils.isBlank(namespaceId)) {
namespaceId = UUID.randomUUID().toString();
}
else {
namespaceId = namespaceId.trim();
if (!namespaceIdCheckPattern.matcher(namespaceId).matches()) {
throw new NacosApiException(HttpStatus.BAD_REQUEST.value(), ErrorCode.ILLEGAL_NAMESPACE,
"namespaceId [" + namespaceId + "] mismatch the pattern");
}
if (namespaceId.length() > NAMESPACE_ID_MAX_LENGTH) {
throw new NacosApiException(HttpStatus.BAD_REQUEST.value(), ErrorCode.ILLEGAL_NAMESPACE,
"too long namespaceId, over " + NAMESPACE_ID_MAX_LENGTH);
}
}
return Result.success(namespaceOperationService.createNamespace(namespaceId, namespaceName, namespaceDesc));
| 677
| 281
| 958
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-register/src/main/java/com/alibaba/nacos/console/exception/ConsoleExceptionHandler.java
|
ConsoleExceptionHandler
|
handleException
|
class ConsoleExceptionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(ConsoleExceptionHandler.class);
@ExceptionHandler(AccessException.class)
private ResponseEntity<String> handleAccessException(AccessException e) {
LOGGER.error("got exception. {}", e.getErrMsg());
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(e.getErrMsg());
}
@ExceptionHandler(IllegalArgumentException.class)
private ResponseEntity<String> handleIllegalArgumentException(IllegalArgumentException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ExceptionUtil.getAllExceptionMsg(e));
}
@ExceptionHandler(Exception.class)
private ResponseEntity<Object> handleException(HttpServletRequest request, Exception e) {<FILL_FUNCTION_BODY>}
}
|
String uri = request.getRequestURI();
LOGGER.error("CONSOLE {}", uri, e);
if (uri.contains(Commons.NACOS_SERVER_VERSION_V2)) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(RestResultUtils.failed(ExceptionUtil.getAllExceptionMsg(e)));
}
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ExceptionUtil.getAllExceptionMsg(e));
| 206
| 128
| 334
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-register/src/main/java/com/alibaba/nacos/console/exception/NacosApiExceptionHandler.java
|
NacosApiExceptionHandler
|
handleIllegalArgumentException
|
class NacosApiExceptionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(NacosApiExceptionHandler.class);
@ExceptionHandler(NacosApiException.class)
public ResponseEntity<Result<String>> handleNacosApiException(NacosApiException e) {
LOGGER.error("got exception. {} {}", e.getErrAbstract(), e.getErrMsg());
return ResponseEntity.status(e.getErrCode())
.body(new Result<>(e.getDetailErrCode(), e.getErrAbstract(), e.getErrMsg()));
}
@ExceptionHandler(NacosException.class)
public ResponseEntity<Result<String>> handleNacosException(NacosException e) {
LOGGER.error("got exception. {}", e.getErrMsg());
return ResponseEntity.status(e.getErrCode()).body(Result.failure(ErrorCode.SERVER_ERROR, e.getErrMsg()));
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(HttpMessageNotReadableException.class)
public Result<String> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
LOGGER.error("got exception. {} {}", e.getMessage(), ExceptionUtil.getAllExceptionMsg(e));
return Result.failure(ErrorCode.PARAMETER_MISSING, e.getMessage());
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(HttpMessageConversionException.class)
public Result<String> handleHttpMessageConversionException(HttpMessageConversionException e) {
LOGGER.error("got exception. {} {}", e.getMessage(), ExceptionUtil.getAllExceptionMsg(e));
return Result.failure(ErrorCode.PARAMETER_VALIDATE_ERROR, e.getMessage());
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(NumberFormatException.class)
public Result<String> handleNumberFormatException(NumberFormatException e) {
LOGGER.error("got exception. {} {}", e.getMessage(), ExceptionUtil.getAllExceptionMsg(e));
return Result.failure(ErrorCode.PARAMETER_VALIDATE_ERROR, e.getMessage());
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(IllegalArgumentException.class)
public Result<String> handleIllegalArgumentException(IllegalArgumentException e) {<FILL_FUNCTION_BODY>}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MissingServletRequestParameterException.class)
public Result<String> handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
LOGGER.error("got exception. {} {}", e.getMessage(), ExceptionUtil.getAllExceptionMsg(e));
return Result.failure(ErrorCode.PARAMETER_MISSING, e.getMessage());
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(HttpMediaTypeException.class)
public Result<String> handleHttpMediaTypeException(HttpMediaTypeException e) {
LOGGER.error("got exception. {} {}", e.getMessage(), ExceptionUtil.getAllExceptionMsg(e));
return Result.failure(ErrorCode.MEDIA_TYPE_ERROR, e.getMessage());
}
@ResponseStatus(HttpStatus.FORBIDDEN)
@ExceptionHandler(AccessException.class)
public Result<String> handleAccessException(AccessException e) {
LOGGER.error("got exception. {} {}", e.getMessage(), ExceptionUtil.getAllExceptionMsg(e));
return Result.failure(ErrorCode.ACCESS_DENIED, e.getErrMsg());
}
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(value = { DataAccessException.class, ServletException.class, IOException.class })
public Result<String> handleDataAccessException(Exception e) {
LOGGER.error("got exception. {} {}", e.getMessage(), ExceptionUtil.getAllExceptionMsg(e));
return Result.failure(ErrorCode.DATA_ACCESS_ERROR, e.getMessage());
}
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Exception.class)
public Result<String> handleOtherException(Exception e) {
LOGGER.error("got exception. {} {}", e.getMessage(), ExceptionUtil.getAllExceptionMsg(e));
return Result.failure(e.getMessage());
}
}
|
LOGGER.error("got exception. {} {}", e.getMessage(), ExceptionUtil.getAllExceptionMsg(e));
return Result.failure(ErrorCode.PARAMETER_VALIDATE_ERROR, e.getMessage());
| 1,076
| 55
| 1,131
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-register/src/main/java/com/alibaba/nacos/console/model/form/NamespaceForm.java
|
NamespaceForm
|
equals
|
class NamespaceForm implements Serializable {
private static final long serialVersionUID = -1078976569495343487L;
private String namespaceId;
private String namespaceName;
private String namespaceDesc;
public NamespaceForm() {
}
public NamespaceForm(String namespaceId, String namespaceName, String namespaceDesc) {
this.namespaceId = namespaceId;
this.namespaceName = namespaceName;
this.namespaceDesc = namespaceDesc;
}
public String getNamespaceId() {
return namespaceId;
}
public void setNamespaceId(String namespaceId) {
this.namespaceId = namespaceId;
}
public String getNamespaceName() {
return namespaceName;
}
public void setNamespaceName(String namespaceName) {
this.namespaceName = namespaceName;
}
public String getNamespaceDesc() {
return namespaceDesc;
}
public void setNamespaceDesc(String namespaceDesc) {
this.namespaceDesc = namespaceDesc;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(namespaceId, namespaceName, namespaceDesc);
}
@Override
public String toString() {
return "NamespaceVo{" + "namespaceId='" + namespaceId + '\'' + ", namespaceName='" + namespaceName + '\''
+ ", namespaceDesc='" + namespaceDesc + '\'' + '}';
}
/**
* check required param.
* @throws NacosException NacosException
*/
public void validate() throws NacosException {
if (null == namespaceId) {
throw new NacosApiException(HttpStatus.BAD_REQUEST.value(), ErrorCode.PARAMETER_MISSING,
"required parameter 'namespaceId' is missing");
}
if (null == namespaceName) {
throw new NacosApiException(HttpStatus.BAD_REQUEST.value(), ErrorCode.PARAMETER_MISSING,
"required parameter 'namespaceName' is missing");
}
}
}
|
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
NamespaceForm that = (NamespaceForm) o;
return Objects.equals(namespaceId, that.namespaceId) && Objects.equals(namespaceName, that.namespaceName)
&& Objects.equals(namespaceDesc, that.namespaceDesc);
| 524
| 106
| 630
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-register/src/main/java/com/alibaba/nacos/console/service/NamespaceOperationService.java
|
NamespaceOperationService
|
getNamespace
|
class NamespaceOperationService {
private final ConfigInfoPersistService configInfoPersistService;
private final CommonPersistService commonPersistService;
private static final String DEFAULT_NAMESPACE = "public";
private static final String DEFAULT_NAMESPACE_SHOW_NAME = "Public";
private static final String DEFAULT_NAMESPACE_DESCRIPTION = "Public Namespace";
private static final int DEFAULT_QUOTA = 200;
private static final String DEFAULT_CREATE_SOURCE = "nacos";
private static final String DEFAULT_TENANT = "";
private static final String DEFAULT_KP = "1";
public NamespaceOperationService(ConfigInfoPersistService configInfoPersistService,
CommonPersistService commonPersistService) {
this.configInfoPersistService = configInfoPersistService;
this.commonPersistService = commonPersistService;
}
public List<Namespace> getNamespaceList() {
// TODO 获取用kp
List<TenantInfo> tenantInfos = commonPersistService.findTenantByKp(DEFAULT_KP);
Namespace namespace0 = new Namespace(NamespaceUtil.getNamespaceDefaultId(), DEFAULT_NAMESPACE, DEFAULT_QUOTA,
configInfoPersistService.configInfoCount(DEFAULT_TENANT), NamespaceTypeEnum.GLOBAL.getType());
List<Namespace> namespaceList = new ArrayList<>();
namespaceList.add(namespace0);
for (TenantInfo tenantInfo : tenantInfos) {
int configCount = configInfoPersistService.configInfoCount(tenantInfo.getTenantId());
Namespace namespaceTmp = new Namespace(tenantInfo.getTenantId(), tenantInfo.getTenantName(),
tenantInfo.getTenantDesc(), DEFAULT_QUOTA, configCount, NamespaceTypeEnum.CUSTOM.getType());
namespaceList.add(namespaceTmp);
}
return namespaceList;
}
/**
* query namespace by namespace id.
* @param namespaceId namespace Id.
* @return NamespaceAllInfo.
*/
public NamespaceAllInfo getNamespace(String namespaceId) throws NacosException {<FILL_FUNCTION_BODY>}
/**
* create namespace.
* @param namespaceId namespace ID
* @param namespaceName namespace Name
* @param namespaceDesc namespace Desc
* @return whether create ok
*/
public Boolean createNamespace(String namespaceId, String namespaceName, String namespaceDesc)
throws NacosException {
// TODO 获取用kp
if (commonPersistService.tenantInfoCountByTenantId(namespaceId) > 0) {
throw new NacosApiException(HttpStatus.INTERNAL_SERVER_ERROR.value(), ErrorCode.NAMESPACE_ALREADY_EXIST,
"namespaceId [" + namespaceId + "] already exist");
}
commonPersistService.insertTenantInfoAtomic(DEFAULT_KP, namespaceId, namespaceName, namespaceDesc,
DEFAULT_CREATE_SOURCE, System.currentTimeMillis());
return true;
}
/**
* edit namespace.
*/
public Boolean editNamespace(String namespaceId, String namespaceName, String namespaceDesc) {
// TODO 获取用kp
commonPersistService.updateTenantNameAtomic(DEFAULT_KP, namespaceId, namespaceName, namespaceDesc);
return true;
}
/**
* remove namespace.
*/
public Boolean removeNamespace(String namespaceId) {
commonPersistService.removeTenantInfoAtomic(DEFAULT_KP, namespaceId);
return true;
}
}
|
// TODO 获取用kp
if (StringUtils.isBlank(namespaceId) || namespaceId.equals(NamespaceUtil.getNamespaceDefaultId())) {
return new NamespaceAllInfo(namespaceId, DEFAULT_NAMESPACE_SHOW_NAME, DEFAULT_QUOTA,
configInfoPersistService.configInfoCount(DEFAULT_TENANT), NamespaceTypeEnum.GLOBAL.getType(),
DEFAULT_NAMESPACE_DESCRIPTION);
}
else {
TenantInfo tenantInfo = commonPersistService.findTenantByKp(DEFAULT_KP, namespaceId);
if (null == tenantInfo) {
throw new NacosApiException(HttpStatus.NOT_FOUND.value(), ErrorCode.NAMESPACE_NOT_EXIST,
"namespaceId [ " + namespaceId + " ] not exist");
}
int configCount = configInfoPersistService.configInfoCount(namespaceId);
return new NamespaceAllInfo(namespaceId, tenantInfo.getTenantName(), DEFAULT_QUOTA, configCount,
NamespaceTypeEnum.CUSTOM.getType(), tenantInfo.getTenantDesc());
}
| 902
| 288
| 1,190
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/util/DictResolver.java
|
DictResolver
|
getDictItemByItemLabel
|
class DictResolver {
/**
* 根据字典类型获取所有字典项
* @param type 字典类型
* @return 字典数据项集合
*/
public List<SysDictItem> getDictItemsByType(String type) {
Assert.isTrue(StringUtils.isNotBlank(type), "参数不合法");
RemoteDictService remoteDictService = SpringContextHolder.getBean(RemoteDictService.class);
return remoteDictService.getDictByType(type).getData();
}
/**
* 根据字典类型以及字典项字典值获取字典标签
* @param type 字典类型
* @param itemValue 字典项字典值
* @return 字典项标签值
*/
public String getDictItemLabel(String type, String itemValue) {
Assert.isTrue(StringUtils.isNotBlank(type) && StringUtils.isNotBlank(itemValue), "参数不合法");
SysDictItem sysDictItem = getDictItemByItemValue(type, itemValue);
return ObjectUtils.isNotEmpty(sysDictItem) ? sysDictItem.getLabel() : StringPool.EMPTY;
}
/**
* 根据字典类型以及字典标签获取字典值
* @param type 字典类型
* @param itemLabel 字典数据标签
* @return 字典数据项值
*/
public String getDictItemValue(String type, String itemLabel) {
Assert.isTrue(StringUtils.isNotBlank(type) && StringUtils.isNotBlank(itemLabel), "参数不合法");
SysDictItem sysDictItem = getDictItemByItemLabel(type, itemLabel);
return ObjectUtils.isNotEmpty(sysDictItem) ? sysDictItem.getItemValue() : StringPool.EMPTY;
}
/**
* 根据字典类型以及字典值获取字典项
* @param type 字典类型
* @param itemValue 字典数据值
* @return 字典数据项
*/
public SysDictItem getDictItemByItemValue(String type, String itemValue) {
Assert.isTrue(StringUtils.isNotBlank(type) && StringUtils.isNotBlank(itemValue), "参数不合法");
List<SysDictItem> dictItemList = getDictItemsByType(type);
if (CollectionUtils.isNotEmpty(dictItemList)) {
return dictItemList.stream().filter(item -> itemValue.equals(item.getItemValue())).findFirst().orElse(null);
}
return null;
}
/**
* 根据字典类型以及字典标签获取字典项
* @param type 字典类型
* @param itemLabel 字典数据项标签
* @return 字典数据项
*/
public SysDictItem getDictItemByItemLabel(String type, String itemLabel) {<FILL_FUNCTION_BODY>}
}
|
Assert.isTrue(StringUtils.isNotBlank(type) && StringUtils.isNotBlank(itemLabel), "参数不合法");
List<SysDictItem> dictItemList = getDictItemsByType(type);
if (CollectionUtils.isNotEmpty(dictItemList)) {
return dictItemList.stream().filter(item -> itemLabel.equals(item.getLabel())).findFirst().orElse(null);
}
return null;
| 783
| 123
| 906
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/util/ParamResolver.java
|
ParamResolver
|
checkAndGet
|
class ParamResolver {
/**
* 根据key 查询value 配置
* @param key key
* @param defaultVal 默认值
* @return value
*/
public Long getLong(String key, Long... defaultVal) {
return checkAndGet(key, Long.class, defaultVal);
}
/**
* 根据key 查询value 配置
* @param key key
* @param defaultVal 默认值
* @return value
*/
public String getStr(String key, String... defaultVal) {
return checkAndGet(key, String.class, defaultVal);
}
private <T> T checkAndGet(String key, Class<T> clazz, T... defaultVal) {<FILL_FUNCTION_BODY>}
}
|
// 校验入参是否合法
if (StrUtil.isBlank(key) || defaultVal.length > 1) {
throw new IllegalArgumentException("参数不合法");
}
RemoteParamService remoteParamService = SpringContextHolder.getBean(RemoteParamService.class);
String result = remoteParamService.getByKey(key, SecurityConstants.FROM_IN).getData();
if (StrUtil.isNotBlank(result)) {
return Convert.convert(clazz, result);
}
if (defaultVal.length == 1) {
return Convert.convert(clazz, defaultVal.clone()[0]);
}
return null;
| 198
| 171
| 369
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/SysClientController.java
|
SysClientController
|
getOauthClientDetailsPage
|
class SysClientController {
private final SysOauthClientDetailsService clientDetailsService;
/**
* 通过ID查询
* @param clientId clientId
* @return SysOauthClientDetails
*/
@GetMapping("/{clientId}")
public R getByClientId(@PathVariable String clientId) {
SysOauthClientDetails details = clientDetailsService
.getOne(Wrappers.<SysOauthClientDetails>lambdaQuery().eq(SysOauthClientDetails::getClientId, clientId));
return R.ok(details);
}
/**
* 简单分页查询
* @param page 分页对象
* @param sysOauthClientDetails 系统终端
* @return
*/
@GetMapping("/page")
public R getOauthClientDetailsPage(@ParameterObject Page page,
@ParameterObject SysOauthClientDetails sysOauthClientDetails) {<FILL_FUNCTION_BODY>}
/**
* 添加
* @param clientDetails 实体
* @return success/false
*/
@SysLog("添加终端")
@PostMapping
@PreAuthorize("@pms.hasPermission('sys_client_add')")
public R add(@Valid @RequestBody SysOauthClientDetails clientDetails) {
return R.ok(clientDetailsService.saveClient(clientDetails));
}
/**
* 删除
* @param ids ID 列表
* @return success/false
*/
@SysLog("删除终端")
@DeleteMapping
@PreAuthorize("@pms.hasPermission('sys_client_del')")
public R removeById(@RequestBody Long[] ids) {
clientDetailsService.removeBatchByIds(CollUtil.toList(ids));
return R.ok();
}
/**
* 编辑
* @param clientDetails 实体
* @return success/false
*/
@SysLog("编辑终端")
@PutMapping
@PreAuthorize("@pms.hasPermission('sys_client_edit')")
public R update(@Valid @RequestBody SysOauthClientDetails clientDetails) {
return R.ok(clientDetailsService.updateClientById(clientDetails));
}
@Inner(false)
@GetMapping("/getClientDetailsById/{clientId}")
public R getClientDetailsById(@PathVariable String clientId) {
return R.ok(clientDetailsService.getOne(
Wrappers.<SysOauthClientDetails>lambdaQuery().eq(SysOauthClientDetails::getClientId, clientId), false));
}
/**
* 查询全部客户端
* @return
*/
@Inner(false)
@GetMapping("/list")
public R listClients() {
return R.ok(clientDetailsService.list());
}
/**
* 同步缓存字典
* @return R
*/
@SysLog("同步终端")
@PutMapping("/sync")
public R sync() {
return clientDetailsService.syncClientCache();
}
/**
* 导出所有客户端
* @return excel
*/
@ResponseExcel
@SysLog("导出excel")
@GetMapping("/export")
public List<SysOauthClientDetails> export(SysOauthClientDetails sysOauthClientDetails) {
return clientDetailsService.list(Wrappers.query(sysOauthClientDetails));
}
}
|
LambdaQueryWrapper<SysOauthClientDetails> wrapper = Wrappers.<SysOauthClientDetails>lambdaQuery()
.like(StrUtil.isNotBlank(sysOauthClientDetails.getClientId()), SysOauthClientDetails::getClientId,
sysOauthClientDetails.getClientId())
.like(StrUtil.isNotBlank(sysOauthClientDetails.getClientSecret()), SysOauthClientDetails::getClientSecret,
sysOauthClientDetails.getClientSecret());
return R.ok(clientDetailsService.page(page, wrapper));
| 849
| 145
| 994
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/SysDictController.java
|
SysDictController
|
getDictList
|
class SysDictController {
private final SysDictService sysDictService;
private final SysDictItemService sysDictItemService;
/**
* 通过ID查询字典信息
* @param id ID
* @return 字典信息
*/
@GetMapping("/details/{id}")
public R getById(@PathVariable Long id) {
return R.ok(sysDictService.getById(id));
}
/**
* 查询字典信息
* @param query 查询信息
* @return 字典信息
*/
@GetMapping("/details")
public R getDetails(@ParameterObject SysDict query) {
return R.ok(sysDictService.getOne(Wrappers.query(query), false));
}
/**
* 分页查询字典信息
* @param page 分页对象
* @return 分页对象
*/
@GetMapping("/page")
public R<IPage> getDictPage(@ParameterObject Page page, @ParameterObject SysDict sysDict) {
return R.ok(sysDictService.page(page,
Wrappers.<SysDict>lambdaQuery()
.eq(StrUtil.isNotBlank(sysDict.getSystemFlag()), SysDict::getSystemFlag, sysDict.getSystemFlag())
.like(StrUtil.isNotBlank(sysDict.getDictType()), SysDict::getDictType, sysDict.getDictType())));
}
/**
* 通过字典类型查找字典
* @param type 类型
* @return 同类型字典
*/
@GetMapping("/type/{type}")
@Cacheable(value = CacheConstants.DICT_DETAILS, key = "#type", unless = "#result.data.isEmpty()")
public R<List<SysDictItem>> getDictByType(@PathVariable String type) {
return R.ok(sysDictItemService.list(Wrappers.<SysDictItem>query().lambda().eq(SysDictItem::getDictType, type)));
}
/**
* 添加字典
* @param sysDict 字典信息
* @return success、false
*/
@SysLog("添加字典")
@PostMapping
@PreAuthorize("@pms.hasPermission('sys_dict_add')")
public R save(@Valid @RequestBody SysDict sysDict) {
sysDictService.save(sysDict);
return R.ok(sysDict);
}
/**
* 删除字典,并且清除字典缓存
* @param ids ID
* @return R
*/
@SysLog("删除字典")
@DeleteMapping
@PreAuthorize("@pms.hasPermission('sys_dict_del')")
@CacheEvict(value = CacheConstants.DICT_DETAILS, allEntries = true)
public R removeById(@RequestBody Long[] ids) {
return R.ok(sysDictService.removeDictByIds(ids));
}
/**
* 修改字典
* @param sysDict 字典信息
* @return success/false
*/
@PutMapping
@SysLog("修改字典")
@PreAuthorize("@pms.hasPermission('sys_dict_edit')")
public R updateById(@Valid @RequestBody SysDict sysDict) {
return sysDictService.updateDict(sysDict);
}
/**
* 分页查询
* @param name 名称或者字典项
* @return
*/
@GetMapping("/list")
public R getDictList(String name) {<FILL_FUNCTION_BODY>}
/**
* 分页查询
* @param page 分页对象
* @param sysDictItem 字典项
* @return
*/
@GetMapping("/item/page")
public R getSysDictItemPage(Page page, SysDictItem sysDictItem) {
return R.ok(sysDictItemService.page(page, Wrappers.query(sysDictItem)));
}
/**
* 通过id查询字典项
* @param id id
* @return R
*/
@GetMapping("/item/details/{id}")
public R getDictItemById(@PathVariable("id") Long id) {
return R.ok(sysDictItemService.getById(id));
}
/**
* 查询字典项详情
* @param query 查询条件
* @return R
*/
@GetMapping("/item/details")
public R getDictItemDetails(SysDictItem query) {
return R.ok(sysDictItemService.getOne(Wrappers.query(query), false));
}
/**
* 新增字典项
* @param sysDictItem 字典项
* @return R
*/
@SysLog("新增字典项")
@PostMapping("/item")
@CacheEvict(value = CacheConstants.DICT_DETAILS, allEntries = true)
public R save(@RequestBody SysDictItem sysDictItem) {
return R.ok(sysDictItemService.save(sysDictItem));
}
/**
* 修改字典项
* @param sysDictItem 字典项
* @return R
*/
@SysLog("修改字典项")
@PutMapping("/item")
public R updateById(@RequestBody SysDictItem sysDictItem) {
return sysDictItemService.updateDictItem(sysDictItem);
}
/**
* 通过id删除字典项
* @param id id
* @return R
*/
@SysLog("删除字典项")
@DeleteMapping("/item/{id}")
public R removeDictItemById(@PathVariable Long id) {
return sysDictItemService.removeDictItem(id);
}
/**
* 同步缓存字典
* @return R
*/
@SysLog("同步字典")
@PutMapping("/sync")
public R sync() {
return sysDictService.syncDictCache();
}
@ResponseExcel
@GetMapping("/export")
public List<SysDictItem> export(SysDictItem sysDictItem) {
return sysDictItemService.list(Wrappers.query(sysDictItem));
}
}
|
return R.ok(sysDictService.list(Wrappers.<SysDict>lambdaQuery()
.like(StrUtil.isNotBlank(name), SysDict::getDictType, name)
.or()
.like(StrUtil.isNotBlank(name), SysDict::getDescription, name)));
| 1,635
| 87
| 1,722
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/SysFileController.java
|
SysFileController
|
localFile
|
class SysFileController {
private final SysFileService sysFileService;
/**
* 分页查询
* @param page 分页对象
* @param sysFile 文件管理
* @return
*/
@Operation(summary = "分页查询", description = "分页查询")
@GetMapping("/page")
public R getSysFilePage(@ParameterObject Page page, @ParameterObject SysFile sysFile) {
LambdaQueryWrapper<SysFile> wrapper = Wrappers.<SysFile>lambdaQuery()
.like(StrUtil.isNotBlank(sysFile.getOriginal()), SysFile::getOriginal, sysFile.getOriginal());
return R.ok(sysFileService.page(page, wrapper));
}
/**
* 通过id删除文件管理
* @param ids id 列表
* @return R
*/
@Operation(summary = "通过id删除文件管理", description = "通过id删除文件管理")
@SysLog("删除文件管理")
@DeleteMapping
@PreAuthorize("@pms.hasPermission('sys_file_del')")
public R removeById(@RequestBody Long[] ids) {
for (Long id : ids) {
sysFileService.deleteFile(id);
}
return R.ok();
}
/**
* 上传文件 文件名采用uuid,避免原始文件名中带"-"符号导致下载的时候解析出现异常
* @param file 资源
* @return R(/ admin / bucketName / filename)
*/
@PostMapping(value = "/upload")
public R upload(@RequestPart("file") MultipartFile file) {
return sysFileService.uploadFile(file);
}
/**
* 获取文件
* @param bucket 桶名称
* @param fileName 文件空间/名称
* @param response
* @return
*/
@Inner(false)
@GetMapping("/{bucket}/{fileName}")
public void file(@PathVariable String bucket, @PathVariable String fileName, HttpServletResponse response) {
sysFileService.getFile(bucket, fileName, response);
}
/**
* 获取本地(resources)文件
* @param fileName 文件名称
* @param response 本地文件
*/
@SneakyThrows
@GetMapping("/local/file/{fileName}")
public void localFile(@PathVariable String fileName, HttpServletResponse response) {<FILL_FUNCTION_BODY>}
}
|
ClassPathResource resource = new ClassPathResource("file/" + fileName);
response.setContentType("application/octet-stream; charset=UTF-8");
IoUtil.copy(resource.getInputStream(), response.getOutputStream());
| 628
| 63
| 691
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/SysMenuController.java
|
SysMenuController
|
getUserMenu
|
class SysMenuController {
private final SysMenuService sysMenuService;
/**
* 返回当前用户的树形菜单集合
* @param type 类型
* @param parentId 父节点ID
* @return 当前用户的树形菜单
*/
@GetMapping
public R getUserMenu(String type, Long parentId) {<FILL_FUNCTION_BODY>}
/**
* 返回树形菜单集合
* @param parentId 父节点ID
* @param menuName 菜单名称
* @return 树形菜单
*/
@GetMapping(value = "/tree")
public R getTree(Long parentId, String menuName, String type) {
return R.ok(sysMenuService.treeMenu(parentId, menuName, type));
}
/**
* 返回角色的菜单集合
* @param roleId 角色ID
* @return 属性集合
*/
@GetMapping("/tree/{roleId}")
public R getRoleTree(@PathVariable Long roleId) {
return R
.ok(sysMenuService.findMenuByRoleId(roleId).stream().map(SysMenu::getMenuId).collect(Collectors.toList()));
}
/**
* 通过ID查询菜单的详细信息
* @param id 菜单ID
* @return 菜单详细信息
*/
@GetMapping("/{id}")
public R getById(@PathVariable Long id) {
return R.ok(sysMenuService.getById(id));
}
/**
* 新增菜单
* @param sysMenu 菜单信息
* @return success/false
*/
@SysLog("新增菜单")
@PostMapping
@PreAuthorize("@pms.hasPermission('sys_menu_add')")
public R save(@Valid @RequestBody SysMenu sysMenu) {
sysMenuService.save(sysMenu);
return R.ok(sysMenu);
}
/**
* 删除菜单
* @param id 菜单ID
* @return success/false
*/
@SysLog("删除菜单")
@DeleteMapping("/{id}")
@PreAuthorize("@pms.hasPermission('sys_menu_del')")
public R removeById(@PathVariable Long id) {
return sysMenuService.removeMenuById(id);
}
/**
* 更新菜单
* @param sysMenu
* @return
*/
@SysLog("更新菜单")
@PutMapping
@PreAuthorize("@pms.hasPermission('sys_menu_edit')")
public R update(@Valid @RequestBody SysMenu sysMenu) {
return R.ok(sysMenuService.updateMenuById(sysMenu));
}
}
|
// 获取符合条件的菜单
Set<SysMenu> all = new HashSet<>();
SecurityUtils.getRoles().forEach(roleId -> all.addAll(sysMenuService.findMenuByRoleId(roleId)));
return R.ok(sysMenuService.filterMenu(all, type, parentId));
| 696
| 84
| 780
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/SysPublicParamController.java
|
SysPublicParamController
|
getSysPublicParamPage
|
class SysPublicParamController {
private final SysPublicParamService sysPublicParamService;
/**
* 通过key查询公共参数值
* @param publicKey
* @return
*/
@Inner(value = false)
@Operation(description = "查询公共参数值", summary = "根据key查询公共参数值")
@GetMapping("/publicValue/{publicKey}")
public R publicKey(@PathVariable("publicKey") String publicKey) {
return R.ok(sysPublicParamService.getSysPublicParamKeyToValue(publicKey));
}
/**
* 分页查询
* @param page 分页对象
* @param sysPublicParam 公共参数
* @return
*/
@Operation(description = "分页查询", summary = "分页查询")
@GetMapping("/page")
public R getSysPublicParamPage(@ParameterObject Page page, @ParameterObject SysPublicParam sysPublicParam) {<FILL_FUNCTION_BODY>}
/**
* 通过id查询公共参数
* @param publicId id
* @return R
*/
@Operation(description = "通过id查询公共参数", summary = "通过id查询公共参数")
@GetMapping("/details/{publicId}")
public R getById(@PathVariable("publicId") Long publicId) {
return R.ok(sysPublicParamService.getById(publicId));
}
@GetMapping("/details")
public R getDetail(@ParameterObject SysPublicParam param) {
return R.ok(sysPublicParamService.getOne(Wrappers.query(param), false));
}
/**
* 新增公共参数
* @param sysPublicParam 公共参数
* @return R
*/
@Operation(description = "新增公共参数", summary = "新增公共参数")
@SysLog("新增公共参数")
@PostMapping
@PreAuthorize("@pms.hasPermission('sys_syspublicparam_add')")
public R save(@RequestBody SysPublicParam sysPublicParam) {
return R.ok(sysPublicParamService.save(sysPublicParam));
}
/**
* 修改公共参数
* @param sysPublicParam 公共参数
* @return R
*/
@Operation(description = "修改公共参数", summary = "修改公共参数")
@SysLog("修改公共参数")
@PutMapping
@PreAuthorize("@pms.hasPermission('sys_syspublicparam_edit')")
public R updateById(@RequestBody SysPublicParam sysPublicParam) {
return sysPublicParamService.updateParam(sysPublicParam);
}
/**
* 通过id删除公共参数
* @param ids ids
* @return R
*/
@Operation(description = "删除公共参数", summary = "删除公共参数")
@SysLog("删除公共参数")
@DeleteMapping
@PreAuthorize("@pms.hasPermission('sys_syspublicparam_del')")
public R removeById(@RequestBody Long[] ids) {
return R.ok(sysPublicParamService.removeParamByIds(ids));
}
/**
* 导出excel 表格
* @return
*/
@ResponseExcel
@GetMapping("/export")
@PreAuthorize("@pms.hasPermission('sys_syspublicparam_edit')")
public List<SysPublicParam> export() {
return sysPublicParamService.list();
}
/**
* 同步参数
* @return R
*/
@SysLog("同步参数")
@PutMapping("/sync")
@PreAuthorize("@pms.hasPermission('sys_syspublicparam_edit')")
public R sync() {
return sysPublicParamService.syncParamCache();
}
}
|
LambdaUpdateWrapper<SysPublicParam> wrapper = Wrappers.<SysPublicParam>lambdaUpdate()
.like(StrUtil.isNotBlank(sysPublicParam.getPublicName()), SysPublicParam::getPublicName,
sysPublicParam.getPublicName())
.like(StrUtil.isNotBlank(sysPublicParam.getPublicKey()), SysPublicParam::getPublicKey,
sysPublicParam.getPublicKey())
.eq(StrUtil.isNotBlank(sysPublicParam.getSystemFlag()), SysPublicParam::getSystemFlag,
sysPublicParam.getSystemFlag());
return R.ok(sysPublicParamService.page(page, wrapper));
| 927
| 172
| 1,099
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/SysSystemInfoController.java
|
SysSystemInfoController
|
cache
|
class SysSystemInfoController {
private final RedisTemplate<String, String> redisTemplate;
/**
* 缓存监控
* @return R<Object>
*/
@GetMapping("/cache")
public R cache() {<FILL_FUNCTION_BODY>}
}
|
Properties info = (Properties) redisTemplate.execute((RedisCallback<Object>) RedisServerCommands::info);
Properties commandStats = (Properties) redisTemplate
.execute((RedisCallback<Object>) connection -> connection.serverCommands().info("commandstats"));
Object dbSize = redisTemplate.execute((RedisCallback<Object>) RedisServerCommands::dbSize);
if (commandStats == null) {
return R.failed("获取异常");
}
Map<String, Object> result = new HashMap<>(3);
result.put("info", info);
result.put("dbSize", dbSize);
List<Map<String, String>> pieList = new ArrayList<>();
commandStats.stringPropertyNames().forEach(key -> {
Map<String, String> data = new HashMap<>(2);
String property = commandStats.getProperty(key);
data.put("name", StringUtils.removeStart(key, "cmdstat_"));
data.put("value", StringUtils.substringBetween(property, "calls=", ",usec"));
pieList.add(data);
});
result.put("commandStats", pieList);
return R.ok(result);
| 74
| 320
| 394
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/SysTokenController.java
|
SysTokenController
|
removeById
|
class SysTokenController {
private final RemoteTokenService remoteTokenService;
/**
* 分页token 信息
* @param params 参数集
* @return token集合
*/
@RequestMapping("/page")
public R getTokenPage(@RequestBody Map<String, Object> params) {
return remoteTokenService.getTokenPage(params, SecurityConstants.FROM_IN);
}
/**
* 删除
* @param tokens tokens
* @return success/false
*/
@SysLog("删除用户token")
@DeleteMapping("/delete")
@PreAuthorize("@pms.hasPermission('sys_token_del')")
public R removeById(@RequestBody String[] tokens) {<FILL_FUNCTION_BODY>}
}
|
for (String token : tokens) {
remoteTokenService.removeTokenById(token, SecurityConstants.FROM_IN);
}
return R.ok();
| 190
| 43
| 233
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/SysUserController.java
|
SysUserController
|
info
|
class SysUserController {
private final SysUserService userService;
/**
* 获取指定用户全部信息
* @return 用户信息
*/
@Inner
@GetMapping(value = { "/info/query" })
public R info(@RequestParam(required = false) String username, @RequestParam(required = false) String phone) {
SysUser user = userService.getOne(Wrappers.<SysUser>query()
.lambda()
.eq(StrUtil.isNotBlank(username), SysUser::getUsername, username)
.eq(StrUtil.isNotBlank(phone), SysUser::getPhone, phone));
if (user == null) {
return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_USER_USERINFO_EMPTY, username));
}
return R.ok(userService.findUserInfo(user));
}
/**
* 获取当前用户全部信息
* @return 用户信息
*/
@GetMapping(value = { "/info" })
public R info() {<FILL_FUNCTION_BODY>}
/**
* 通过ID查询用户信息
* @param id ID
* @return 用户信息
*/
@GetMapping("/details/{id}")
public R user(@PathVariable Long id) {
return R.ok(userService.selectUserVoById(id));
}
/**
* 查询用户信息
* @param query 查询条件
* @return 不为空返回用户名
*/
@Inner(value = false)
@GetMapping("/details")
public R getDetails(@ParameterObject SysUser query) {
SysUser sysUser = userService.getOne(Wrappers.query(query), false);
return R.ok(sysUser == null ? null : CommonConstants.SUCCESS);
}
/**
* 删除用户信息
* @param ids ID
* @return R
*/
@SysLog("删除用户信息")
@DeleteMapping
@PreAuthorize("@pms.hasPermission('sys_user_del')")
@Operation(summary = "删除用户", description = "根据ID删除用户")
public R userDel(@RequestBody Long[] ids) {
return R.ok(userService.deleteUserByIds(ids));
}
/**
* 添加用户
* @param userDto 用户信息
* @return success/false
*/
@SysLog("添加用户")
@PostMapping
@PreAuthorize("@pms.hasPermission('sys_user_add')")
public R user(@RequestBody UserDTO userDto) {
return R.ok(userService.saveUser(userDto));
}
/**
* 更新用户信息
* @param userDto 用户信息
* @return R
*/
@SysLog("更新用户信息")
@PutMapping
@PreAuthorize("@pms.hasPermission('sys_user_edit')")
public R updateUser(@Valid @RequestBody UserDTO userDto) {
return R.ok(userService.updateUser(userDto));
}
/**
* 分页查询用户
* @param page 参数集
* @param userDTO 查询参数列表
* @return 用户集合
*/
@GetMapping("/page")
public R getUserPage(@ParameterObject Page page, @ParameterObject UserDTO userDTO) {
return R.ok(userService.getUsersWithRolePage(page, userDTO));
}
/**
* 修改个人信息
* @param userDto userDto
* @return success/false
*/
@SysLog("修改个人信息")
@PutMapping("/edit")
public R updateUserInfo(@Valid @RequestBody UserDTO userDto) {
return userService.updateUserInfo(userDto);
}
/**
* 导出excel 表格
* @param userDTO 查询条件
* @return
*/
@ResponseExcel
@GetMapping("/export")
@PreAuthorize("@pms.hasPermission('sys_user_export')")
public List export(UserDTO userDTO) {
return userService.listUser(userDTO);
}
/**
* 导入用户
* @param excelVOList 用户列表
* @param bindingResult 错误信息列表
* @return R
*/
@PostMapping("/import")
@PreAuthorize("@pms.hasPermission('sys_user_export')")
public R importUser(@RequestExcel List<UserExcelVO> excelVOList, BindingResult bindingResult) {
return userService.importUser(excelVOList, bindingResult);
}
/**
* 锁定指定用户
* @param username 用户名
* @return R
*/
@Inner
@PutMapping("/lock/{username}")
public R lockUser(@PathVariable String username) {
return userService.lockUser(username);
}
@PutMapping("/password")
public R password(@RequestBody UserDTO userDto) {
String username = SecurityUtils.getUser().getUsername();
userDto.setUsername(username);
return userService.changePassword(userDto);
}
@PostMapping("/check")
public R check(String password) {
return userService.checkPassword(password);
}
}
|
String username = SecurityUtils.getUser().getUsername();
SysUser user = userService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getUsername, username));
if (user == null) {
return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_USER_QUERY_ERROR));
}
return R.ok(userService.findUserInfo(user));
| 1,343
| 111
| 1,454
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysDeptServiceImpl.java
|
SysDeptServiceImpl
|
importDept
|
class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {
private final SysDeptMapper deptMapper;
/**
* 删除部门
* @param id 部门 ID
* @return 成功、失败
*/
@Override
@Transactional(rollbackFor = Exception.class)
public Boolean removeDeptById(Long id) {
// 级联删除部门
List<Long> idList = this.listDescendant(id).stream().map(SysDept::getDeptId).collect(Collectors.toList());
Optional.ofNullable(idList).filter(CollUtil::isNotEmpty).ifPresent(this::removeByIds);
return Boolean.TRUE;
}
/**
* 查询全部部门树
* @param deptName
* @return 树 部门名称
*/
@Override
public List<Tree<Long>> selectTree(String deptName) {
// 查询全部部门
List<SysDept> deptAllList = deptMapper
.selectList(Wrappers.<SysDept>lambdaQuery().like(StrUtil.isNotBlank(deptName), SysDept::getName, deptName));
// 权限内部门
List<TreeNode<Long>> collect = deptAllList.stream()
.filter(dept -> dept.getDeptId().intValue() != dept.getParentId())
.sorted(Comparator.comparingInt(SysDept::getSortOrder))
.map(dept -> {
TreeNode<Long> treeNode = new TreeNode();
treeNode.setId(dept.getDeptId());
treeNode.setParentId(dept.getParentId());
treeNode.setName(dept.getName());
treeNode.setWeight(dept.getSortOrder());
// 有权限不返回标识
Map<String, Object> extra = new HashMap<>(8);
extra.put("createTime", dept.getCreateTime());
treeNode.setExtra(extra);
return treeNode;
})
.collect(Collectors.toList());
// 模糊查询 不组装树结构 直接返回 表格方便编辑
if (StrUtil.isNotBlank(deptName)) {
return collect.stream().map(node -> {
Tree<Long> tree = new Tree<>();
tree.putAll(node.getExtra());
BeanUtils.copyProperties(node, tree);
return tree;
}).collect(Collectors.toList());
}
return TreeUtil.build(collect, 0L);
}
/**
* 导出部门
* @return
*/
@Override
public List<DeptExcelVo> listExcelVo() {
List<SysDept> list = this.list();
List<DeptExcelVo> deptExcelVos = list.stream().map(item -> {
DeptExcelVo deptExcelVo = new DeptExcelVo();
deptExcelVo.setName(item.getName());
Optional<String> first = this.list()
.stream()
.filter(it -> item.getParentId().equals(it.getDeptId()))
.map(SysDept::getName)
.findFirst();
deptExcelVo.setParentName(first.orElse("根部门"));
deptExcelVo.setSortOrder(item.getSortOrder());
return deptExcelVo;
}).collect(Collectors.toList());
return deptExcelVos;
}
@Override
public R importDept(List<DeptExcelVo> excelVOList, BindingResult bindingResult) {<FILL_FUNCTION_BODY>}
/**
* 查询所有子节点 (包含当前节点)
* @param deptId 部门ID 目标部门ID
* @return ID
*/
@Override
public List<SysDept> listDescendant(Long deptId) {
// 查询全部部门
List<SysDept> allDeptList = baseMapper.selectList(Wrappers.emptyWrapper());
// 递归查询所有子节点
List<SysDept> resDeptList = new ArrayList<>();
recursiveDept(allDeptList, deptId, resDeptList);
// 添加当前节点
resDeptList.addAll(allDeptList.stream()
.filter(sysDept -> deptId.equals(sysDept.getDeptId()))
.collect(Collectors.toList()));
return resDeptList;
}
/**
* 递归查询所有子节点。
* @param allDeptList 所有部门列表
* @param parentId 父部门ID
* @param resDeptList 结果集合
*/
private void recursiveDept(List<SysDept> allDeptList, Long parentId, List<SysDept> resDeptList) {
// 使用 Stream API 进行筛选和遍历
allDeptList.stream().filter(sysDept -> sysDept.getParentId().equals(parentId)).forEach(sysDept -> {
resDeptList.add(sysDept);
recursiveDept(allDeptList, sysDept.getDeptId(), resDeptList);
});
}
}
|
List<ErrorMessage> errorMessageList = (List<ErrorMessage>) bindingResult.getTarget();
List<SysDept> deptList = this.list();
for (DeptExcelVo item : excelVOList) {
Set<String> errorMsg = new HashSet<>();
boolean exsitUsername = deptList.stream().anyMatch(sysDept -> item.getName().equals(sysDept.getName()));
if (exsitUsername) {
errorMsg.add("部门名称已经存在");
}
SysDept one = this.getOne(Wrappers.<SysDept>lambdaQuery().eq(SysDept::getName, item.getParentName()));
if (item.getParentName().equals("根部门")) {
one = new SysDept();
one.setDeptId(0L);
}
if (one == null) {
errorMsg.add("上级部门不存在");
}
if (CollUtil.isEmpty(errorMsg)) {
SysDept sysDept = new SysDept();
sysDept.setName(item.getName());
sysDept.setParentId(one.getDeptId());
sysDept.setSortOrder(item.getSortOrder());
baseMapper.insert(sysDept);
}
else {
// 数据不合法情况
errorMessageList.add(new ErrorMessage(item.getLineNum(), errorMsg));
}
}
if (CollUtil.isNotEmpty(errorMessageList)) {
return R.failed(errorMessageList);
}
return R.ok(null, "部门导入成功");
| 1,426
| 431
| 1,857
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysDictItemServiceImpl.java
|
SysDictItemServiceImpl
|
removeDictItem
|
class SysDictItemServiceImpl extends ServiceImpl<SysDictItemMapper, SysDictItem> implements SysDictItemService {
private final SysDictService dictService;
/**
* 删除字典项
* @param id 字典项ID
* @return
*/
@Override
@CacheEvict(value = CacheConstants.DICT_DETAILS, allEntries = true)
public R removeDictItem(Long id) {<FILL_FUNCTION_BODY>}
/**
* 更新字典项
* @param item 字典项
* @return
*/
@Override
@CacheEvict(value = CacheConstants.DICT_DETAILS, key = "#item.dictType")
public R updateDictItem(SysDictItem item) {
// 查询字典
SysDict dict = dictService.getById(item.getDictId());
// 系统内置
if (DictTypeEnum.SYSTEM.getType().equals(dict.getSystemFlag())) {
return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_DICT_UPDATE_SYSTEM));
}
return R.ok(this.updateById(item));
}
}
|
// 根据ID查询字典ID
SysDictItem dictItem = this.getById(id);
SysDict dict = dictService.getById(dictItem.getDictId());
// 系统内置
if (DictTypeEnum.SYSTEM.getType().equals(dict.getSystemFlag())) {
return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_DICT_DELETE_SYSTEM));
}
return R.ok(this.removeById(id));
| 314
| 131
| 445
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysDictServiceImpl.java
|
SysDictServiceImpl
|
removeDictByIds
|
class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict> implements SysDictService {
private final SysDictItemMapper dictItemMapper;
/**
* 根据ID 删除字典
* @param ids 字典ID 列表
* @return
*/
@Override
@Transactional(rollbackFor = Exception.class)
@CacheEvict(value = CacheConstants.DICT_DETAILS, allEntries = true)
public R removeDictByIds(Long[] ids) {<FILL_FUNCTION_BODY>}
/**
* 更新字典
* @param dict 字典
* @return
*/
@Override
@CacheEvict(value = CacheConstants.DICT_DETAILS, key = "#dict.dictType")
public R updateDict(SysDict dict) {
SysDict sysDict = this.getById(dict.getId());
// 系统内置
if (DictTypeEnum.SYSTEM.getType().equals(sysDict.getSystemFlag())) {
return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_DICT_UPDATE_SYSTEM));
}
this.updateById(dict);
return R.ok(dict);
}
/**
* 同步缓存 (清空缓存)
* @return R
*/
@Override
@CacheEvict(value = CacheConstants.DICT_DETAILS, allEntries = true)
public R syncDictCache() {
return R.ok();
}
}
|
List<Long> dictIdList = baseMapper.selectBatchIds(CollUtil.toList(ids))
.stream()
.filter(sysDict -> !sysDict.getSystemFlag().equals(DictTypeEnum.SYSTEM.getType()))// 系统内置类型不删除
.map(SysDict::getId)
.collect(Collectors.toList());
baseMapper.deleteBatchIds(dictIdList);
dictItemMapper.delete(Wrappers.<SysDictItem>lambdaQuery().in(SysDictItem::getDictId, dictIdList));
return R.ok();
| 400
| 162
| 562
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysFileServiceImpl.java
|
SysFileServiceImpl
|
getFile
|
class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFile> implements SysFileService {
private final FileTemplate fileTemplate;
private final FileProperties properties;
/**
* 上传文件
* @param file
* @return
*/
@Override
public R uploadFile(MultipartFile file) {
String fileName = IdUtil.simpleUUID() + StrUtil.DOT + FileUtil.extName(file.getOriginalFilename());
Map<String, String> resultMap = new HashMap<>(4);
resultMap.put("bucketName", properties.getBucketName());
resultMap.put("fileName", fileName);
resultMap.put("url", String.format("/admin/sys-file/%s/%s", properties.getBucketName(), fileName));
try (InputStream inputStream = file.getInputStream()) {
fileTemplate.putObject(properties.getBucketName(), fileName, inputStream, file.getContentType());
// 文件管理数据记录,收集管理追踪文件
fileLog(file, fileName);
}
catch (Exception e) {
log.error("上传失败", e);
return R.failed(e.getLocalizedMessage());
}
return R.ok(resultMap);
}
/**
* 读取文件
* @param bucket
* @param fileName
* @param response
*/
@Override
public void getFile(String bucket, String fileName, HttpServletResponse response) {<FILL_FUNCTION_BODY>}
/**
* 删除文件
* @param id
* @return
*/
@Override
@SneakyThrows
@Transactional(rollbackFor = Exception.class)
public Boolean deleteFile(Long id) {
SysFile file = this.getById(id);
if (Objects.isNull(file)) {
return Boolean.FALSE;
}
fileTemplate.removeObject(properties.getBucketName(), file.getFileName());
return this.removeById(id);
}
/**
* 文件管理数据记录,收集管理追踪文件
* @param file 上传文件格式
* @param fileName 文件名
*/
private void fileLog(MultipartFile file, String fileName) {
SysFile sysFile = new SysFile();
sysFile.setFileName(fileName);
sysFile.setOriginal(file.getOriginalFilename());
sysFile.setFileSize(file.getSize());
sysFile.setType(FileUtil.extName(file.getOriginalFilename()));
sysFile.setBucketName(properties.getBucketName());
this.save(sysFile);
}
}
|
try (S3Object s3Object = fileTemplate.getObject(bucket, fileName)) {
response.setContentType("application/octet-stream; charset=UTF-8");
IoUtil.copy(s3Object.getObjectContent(), response.getOutputStream());
}
catch (Exception e) {
log.error("文件读取异常: {}", e.getLocalizedMessage());
}
| 689
| 108
| 797
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysLogServiceImpl.java
|
SysLogServiceImpl
|
buildQuery
|
class SysLogServiceImpl extends ServiceImpl<SysLogMapper, SysLog> implements SysLogService {
@Override
public Page getLogByPage(Page page, SysLogDTO sysLog) {
return baseMapper.selectPage(page, buildQuery(sysLog));
}
/**
* 插入日志
* @param sysLog 日志对象
* @return true/false
*/
@Override
@Transactional(rollbackFor = Exception.class)
public Boolean saveLog(SysLog sysLog) {
baseMapper.insert(sysLog);
return Boolean.TRUE;
}
/**
* 查询日志列表
* @param sysLog 查询条件
* @return List<SysLog>
*/
@Override
public List<SysLog> getList(SysLogDTO sysLog) {
return baseMapper.selectList(buildQuery(sysLog));
}
/**
* 构建查询条件
* @param sysLog 前端条件
* @return LambdaQueryWrapper
*/
private LambdaQueryWrapper buildQuery(SysLogDTO sysLog) {<FILL_FUNCTION_BODY>}
}
|
LambdaQueryWrapper<SysLog> wrapper = Wrappers.lambdaQuery();
if (StrUtil.isNotBlank(sysLog.getLogType())) {
wrapper.eq(SysLog::getLogType, sysLog.getLogType());
}
if (ArrayUtil.isNotEmpty(sysLog.getCreateTime())) {
wrapper.ge(SysLog::getCreateTime, sysLog.getCreateTime()[0])
.le(SysLog::getCreateTime, sysLog.getCreateTime()[1]);
}
return wrapper;
| 296
| 145
| 441
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysMenuServiceImpl.java
|
SysMenuServiceImpl
|
getNodeFunction
|
class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {
private final SysRoleMenuMapper sysRoleMenuMapper;
@Override
@Cacheable(value = CacheConstants.MENU_DETAILS, key = "#roleId", unless = "#result.isEmpty()")
public List<SysMenu> findMenuByRoleId(Long roleId) {
return baseMapper.listMenusByRoleId(roleId);
}
@Override
@Transactional(rollbackFor = Exception.class)
@CacheEvict(value = CacheConstants.MENU_DETAILS, allEntries = true)
public R removeMenuById(Long id) {
// 查询父节点为当前节点的节点
List<SysMenu> menuList = this.list(Wrappers.<SysMenu>query().lambda().eq(SysMenu::getParentId, id));
if (CollUtil.isNotEmpty(menuList)) {
return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_MENU_DELETE_EXISTING));
}
sysRoleMenuMapper.delete(Wrappers.<SysRoleMenu>query().lambda().eq(SysRoleMenu::getMenuId, id));
// 删除当前菜单及其子菜单
return R.ok(this.removeById(id));
}
@Override
@CacheEvict(value = CacheConstants.MENU_DETAILS, allEntries = true)
public Boolean updateMenuById(SysMenu sysMenu) {
return this.updateById(sysMenu);
}
/**
* 构建树查询 1. 不是懒加载情况,查询全部 2. 是懒加载,根据parentId 查询 2.1 父节点为空,则查询ID -1
* @param parentId 父节点ID
* @param menuName 菜单名称
* @return
*/
@Override
public List<Tree<Long>> treeMenu(Long parentId, String menuName, String type) {
Long parent = parentId == null ? CommonConstants.MENU_TREE_ROOT_ID : parentId;
List<TreeNode<Long>> collect = baseMapper
.selectList(Wrappers.<SysMenu>lambdaQuery()
.like(StrUtil.isNotBlank(menuName), SysMenu::getName, menuName)
.eq(StrUtil.isNotBlank(type), SysMenu::getMenuType, type)
.orderByAsc(SysMenu::getSortOrder))
.stream()
.map(getNodeFunction())
.collect(Collectors.toList());
// 模糊查询 不组装树结构 直接返回 表格方便编辑
if (StrUtil.isNotBlank(menuName)) {
return collect.stream().map(node -> {
Tree<Long> tree = new Tree<>();
tree.putAll(node.getExtra());
BeanUtils.copyProperties(node, tree);
return tree;
}).collect(Collectors.toList());
}
return TreeUtil.build(collect, parent);
}
/**
* 查询菜单
* @param all 全部菜单
* @param type 类型
* @param parentId 父节点ID
* @return
*/
@Override
public List<Tree<Long>> filterMenu(Set<SysMenu> all, String type, Long parentId) {
List<TreeNode<Long>> collect = all.stream()
.filter(menuTypePredicate(type))
.map(getNodeFunction())
.collect(Collectors.toList());
Long parent = parentId == null ? CommonConstants.MENU_TREE_ROOT_ID : parentId;
return TreeUtil.build(collect, parent);
}
@NotNull
private Function<SysMenu, TreeNode<Long>> getNodeFunction() {<FILL_FUNCTION_BODY>}
/**
* menu 类型断言
* @param type 类型
* @return Predicate
*/
private Predicate<SysMenu> menuTypePredicate(String type) {
return vo -> {
if (MenuTypeEnum.TOP_MENU.getDescription().equals(type)) {
return MenuTypeEnum.TOP_MENU.getType().equals(vo.getMenuType());
}
// 其他查询 左侧 + 顶部
return !MenuTypeEnum.BUTTON.getType().equals(vo.getMenuType());
};
}
}
|
return menu -> {
TreeNode<Long> node = new TreeNode<>();
node.setId(menu.getMenuId());
node.setName(menu.getName());
node.setParentId(menu.getParentId());
node.setWeight(menu.getSortOrder());
// 扩展属性
Map<String, Object> extra = new HashMap<>();
extra.put("path", menu.getPath());
extra.put("menuType", menu.getMenuType());
extra.put("permission", menu.getPermission());
extra.put("sortOrder", menu.getSortOrder());
// 适配 vue3
Map<String, Object> meta = new HashMap<>();
meta.put("title", menu.getName());
meta.put("isLink", menu.getPath() != null && menu.getPath().startsWith("http") ? menu.getPath() : "");
meta.put("isHide", !BooleanUtil.toBooleanObject(menu.getVisible()));
meta.put("isKeepAlive", BooleanUtil.toBooleanObject(menu.getKeepAlive()));
meta.put("isAffix", false);
meta.put("isIframe", BooleanUtil.toBooleanObject(menu.getEmbedded()));
meta.put("icon", menu.getIcon());
// 增加英文
meta.put("enName", menu.getEnName());
extra.put("meta", meta);
node.setExtra(extra);
return node;
};
| 1,145
| 399
| 1,544
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysMobileServiceImpl.java
|
SysMobileServiceImpl
|
sendSmsCode
|
class SysMobileServiceImpl implements SysMobileService {
private final RedisTemplate redisTemplate;
private final SysUserMapper userMapper;
/**
* 发送手机验证码 TODO: 调用短信网关发送验证码,测试返回前端
* @param mobile mobile
* @return code
*/
@Override
public R<Boolean> sendSmsCode(String mobile) {<FILL_FUNCTION_BODY>}
}
|
List<SysUser> userList = userMapper
.selectList(Wrappers.<SysUser>query().lambda().eq(SysUser::getPhone, mobile));
if (CollUtil.isEmpty(userList)) {
log.info("手机号未注册:{}", mobile);
return R.ok(Boolean.FALSE, MsgUtils.getMessage(ErrorCodes.SYS_APP_PHONE_UNREGISTERED, mobile));
}
Object codeObj = redisTemplate.opsForValue().get(CacheConstants.DEFAULT_CODE_KEY + mobile);
if (codeObj != null) {
log.info("手机号验证码未过期:{},{}", mobile, codeObj);
return R.ok(Boolean.FALSE, MsgUtils.getMessage(ErrorCodes.SYS_APP_SMS_OFTEN));
}
String code = RandomUtil.randomNumbers(Integer.parseInt(SecurityConstants.CODE_SIZE));
log.debug("手机号生成验证码成功:{},{}", mobile, code);
redisTemplate.opsForValue()
.set(CacheConstants.DEFAULT_CODE_KEY + mobile, code, SecurityConstants.CODE_TIME, TimeUnit.SECONDS);
return R.ok(Boolean.TRUE, code);
| 117
| 324
| 441
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysPostServiceImpl.java
|
SysPostServiceImpl
|
listPost
|
class SysPostServiceImpl extends ServiceImpl<SysPostMapper, SysPost> implements SysPostService {
/**
* 导入岗位
* @param excelVOList 岗位列表
* @param bindingResult 错误信息列表
* @return ok fail
*/
@Override
public R importPost(List<PostExcelVO> excelVOList, BindingResult bindingResult) {
// 通用校验获取失败的数据
List<ErrorMessage> errorMessageList = (List<ErrorMessage>) bindingResult.getTarget();
// 个性化校验逻辑
List<SysPost> postList = this.list();
// 执行数据插入操作 组装 PostDto
for (PostExcelVO excel : excelVOList) {
Set<String> errorMsg = new HashSet<>();
// 检验岗位名称或者岗位编码是否存在
boolean existPost = postList.stream()
.anyMatch(post -> excel.getPostName().equals(post.getPostName())
|| excel.getPostCode().equals(post.getPostCode()));
if (existPost) {
errorMsg.add(MsgUtils.getMessage(ErrorCodes.SYS_POST_NAMEORCODE_EXISTING, excel.getPostName(),
excel.getPostCode()));
}
// 数据合法情况
if (CollUtil.isEmpty(errorMsg)) {
insertExcelPost(excel);
}
else {
// 数据不合法
errorMessageList.add(new ErrorMessage(excel.getLineNum(), errorMsg));
}
}
if (CollUtil.isNotEmpty(errorMessageList)) {
return R.failed(errorMessageList);
}
return R.ok();
}
/**
* 导出excel 表格
* @return
*/
@Override
public List<PostExcelVO> listPost() {<FILL_FUNCTION_BODY>}
/**
* 插入excel Post
*/
private void insertExcelPost(PostExcelVO excel) {
SysPost sysPost = new SysPost();
BeanUtil.copyProperties(excel, sysPost);
this.save(sysPost);
}
}
|
List<SysPost> postList = this.list(Wrappers.emptyWrapper());
// 转换成execl 对象输出
return postList.stream().map(post -> {
PostExcelVO postExcelVO = new PostExcelVO();
BeanUtil.copyProperties(post, postExcelVO);
return postExcelVO;
}).collect(Collectors.toList());
| 567
| 106
| 673
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysPublicParamServiceImpl.java
|
SysPublicParamServiceImpl
|
updateParam
|
class SysPublicParamServiceImpl extends ServiceImpl<SysPublicParamMapper, SysPublicParam>
implements SysPublicParamService {
@Override
@Cacheable(value = CacheConstants.PARAMS_DETAILS, key = "#publicKey", unless = "#result == null ")
public String getSysPublicParamKeyToValue(String publicKey) {
SysPublicParam sysPublicParam = this.baseMapper
.selectOne(Wrappers.<SysPublicParam>lambdaQuery().eq(SysPublicParam::getPublicKey, publicKey));
if (sysPublicParam != null) {
return sysPublicParam.getPublicValue();
}
return null;
}
/**
* 更新参数
* @param sysPublicParam
* @return
*/
@Override
@CacheEvict(value = CacheConstants.PARAMS_DETAILS, key = "#sysPublicParam.publicKey")
public R updateParam(SysPublicParam sysPublicParam) {<FILL_FUNCTION_BODY>}
/**
* 删除参数
* @param publicIds 参数ID列表
* @return
*/
@Override
@CacheEvict(value = CacheConstants.PARAMS_DETAILS, allEntries = true)
public R removeParamByIds(Long[] publicIds) {
List<Long> idList = this.baseMapper.selectBatchIds(CollUtil.toList(publicIds))
.stream()
.filter(p -> !p.getSystemFlag().equals(DictTypeEnum.SYSTEM.getType()))// 系统内置的跳过不能删除
.map(SysPublicParam::getPublicId)
.collect(Collectors.toList());
return R.ok(this.removeBatchByIds(idList));
}
/**
* 同步缓存
* @return R
*/
@Override
@CacheEvict(value = CacheConstants.PARAMS_DETAILS, allEntries = true)
public R syncParamCache() {
return R.ok();
}
}
|
SysPublicParam param = this.getById(sysPublicParam.getPublicId());
// 系统内置
if (DictTypeEnum.SYSTEM.getType().equals(param.getSystemFlag())) {
return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_PARAM_DELETE_SYSTEM));
}
return R.ok(this.updateById(sysPublicParam));
| 508
| 102
| 610
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysRoleMenuServiceImpl.java
|
SysRoleMenuServiceImpl
|
saveRoleMenus
|
class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements SysRoleMenuService {
private final CacheManager cacheManager;
/**
* @param roleId 角色
* @param menuIds 菜单ID拼成的字符串,每个id之间根据逗号分隔
* @return
*/
@Override
@Transactional(rollbackFor = Exception.class)
@CacheEvict(value = CacheConstants.MENU_DETAILS, key = "#roleId")
public Boolean saveRoleMenus(Long roleId, String menuIds) {<FILL_FUNCTION_BODY>}
}
|
this.remove(Wrappers.<SysRoleMenu>query().lambda().eq(SysRoleMenu::getRoleId, roleId));
if (StrUtil.isBlank(menuIds)) {
return Boolean.TRUE;
}
List<SysRoleMenu> roleMenuList = Arrays.stream(menuIds.split(StrUtil.COMMA)).map(menuId -> {
SysRoleMenu roleMenu = new SysRoleMenu();
roleMenu.setRoleId(roleId);
roleMenu.setMenuId(Long.valueOf(menuId));
return roleMenu;
}).collect(Collectors.toList());
// 清空userinfo
cacheManager.getCache(CacheConstants.USER_DETAILS).clear();
this.saveBatch(roleMenuList);
return Boolean.TRUE;
| 159
| 213
| 372
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysRoleServiceImpl.java
|
SysRoleServiceImpl
|
listRole
|
class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {
private SysRoleMenuService roleMenuService;
/**
* 通过用户ID,查询角色信息
* @param userId
* @return
*/
@Override
public List findRolesByUserId(Long userId) {
return baseMapper.listRolesByUserId(userId);
}
/**
* 根据角色ID 查询角色列表,注意缓存删除
* @param roleIdList 角色ID列表
* @param key 缓存key
* @return
*/
@Override
@Cacheable(value = CacheConstants.ROLE_DETAILS, key = "#key", unless = "#result.isEmpty()")
public List<SysRole> findRolesByRoleIds(List<Long> roleIdList, String key) {
return baseMapper.selectBatchIds(roleIdList);
}
/**
* 通过角色ID,删除角色,并清空角色菜单缓存
* @param ids
* @return
*/
@Override
@Transactional(rollbackFor = Exception.class)
public Boolean removeRoleByIds(Long[] ids) {
roleMenuService
.remove(Wrappers.<SysRoleMenu>update().lambda().in(SysRoleMenu::getRoleId, CollUtil.toList(ids)));
return this.removeBatchByIds(CollUtil.toList(ids));
}
/**
* 根据角色菜单列表
* @param roleVo 角色&菜单列表
* @return
*/
@Override
public Boolean updateRoleMenus(RoleVO roleVo) {
return roleMenuService.saveRoleMenus(roleVo.getRoleId(), roleVo.getMenuIds());
}
/**
* 导入角色
* @param excelVOList 角色列表
* @param bindingResult 错误信息列表
* @return ok fail
*/
@Override
public R importRole(List<RoleExcelVO> excelVOList, BindingResult bindingResult) {
// 通用校验获取失败的数据
List<ErrorMessage> errorMessageList = (List<ErrorMessage>) bindingResult.getTarget();
// 个性化校验逻辑
List<SysRole> roleList = this.list();
// 执行数据插入操作 组装 RoleDto
for (RoleExcelVO excel : excelVOList) {
Set<String> errorMsg = new HashSet<>();
// 检验角色名称或者角色编码是否存在
boolean existRole = roleList.stream()
.anyMatch(sysRole -> excel.getRoleName().equals(sysRole.getRoleName())
|| excel.getRoleCode().equals(sysRole.getRoleCode()));
if (existRole) {
errorMsg.add(MsgUtils.getMessage(ErrorCodes.SYS_ROLE_NAMEORCODE_EXISTING, excel.getRoleName(),
excel.getRoleCode()));
}
// 数据合法情况
if (CollUtil.isEmpty(errorMsg)) {
insertExcelRole(excel);
}
else {
// 数据不合法情况
errorMessageList.add(new ErrorMessage(excel.getLineNum(), errorMsg));
}
}
if (CollUtil.isNotEmpty(errorMessageList)) {
return R.failed(errorMessageList);
}
return R.ok();
}
/**
* 查询全部的角色
* @return list
*/
@Override
public List<RoleExcelVO> listRole() {<FILL_FUNCTION_BODY>}
/**
* 插入excel Role
*/
private void insertExcelRole(RoleExcelVO excel) {
SysRole sysRole = new SysRole();
sysRole.setRoleName(excel.getRoleName());
sysRole.setRoleDesc(excel.getRoleDesc());
sysRole.setRoleCode(excel.getRoleCode());
this.save(sysRole);
}
}
|
List<SysRole> roleList = this.list(Wrappers.emptyWrapper());
// 转换成execl 对象输出
return roleList.stream().map(role -> {
RoleExcelVO roleExcelVO = new RoleExcelVO();
BeanUtil.copyProperties(role, roleExcelVO);
return roleExcelVO;
}).collect(Collectors.toList());
| 1,033
| 107
| 1,140
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/GenDsConfController.java
|
GenDsConfController
|
generatorDoc
|
class GenDsConfController {
private final GenDatasourceConfService datasourceConfService;
private final Screw screw;
/**
* 分页查询
* @param page 分页对象
* @param datasourceConf 数据源表
* @return
*/
@GetMapping("/page")
public R getSysDatasourceConfPage(Page page, GenDatasourceConf datasourceConf) {
return R.ok(datasourceConfService.page(page,
Wrappers.<GenDatasourceConf>lambdaQuery()
.like(StrUtil.isNotBlank(datasourceConf.getDsName()), GenDatasourceConf::getDsName,
datasourceConf.getDsName())));
}
/**
* 查询全部数据源
* @return
*/
@GetMapping("/list")
@Inner(value = false)
public R list() {
return R.ok(datasourceConfService.list());
}
/**
* 通过id查询数据源表
* @param id id
* @return R
*/
@GetMapping("/{id}")
public R getById(@PathVariable("id") Long id) {
return R.ok(datasourceConfService.getById(id));
}
/**
* 新增数据源表
* @param datasourceConf 数据源表
* @return R
*/
@PostMapping
public R save(@RequestBody GenDatasourceConf datasourceConf) {
return R.ok(datasourceConfService.saveDsByEnc(datasourceConf));
}
/**
* 修改数据源表
* @param conf 数据源表
* @return R
*/
@PutMapping
public R updateById(@RequestBody GenDatasourceConf conf) {
return R.ok(datasourceConfService.updateDsByEnc(conf));
}
/**
* 通过id删除数据源表
* @param ids id
* @return R
*/
@DeleteMapping
public R removeById(@RequestBody Long[] ids) {
return R.ok(datasourceConfService.removeByDsId(ids));
}
/**
* 查询数据源对应的文档
* @param dsName 数据源名称
*/
@SneakyThrows
@GetMapping("/doc")
public void generatorDoc(String dsName, HttpServletResponse response) {<FILL_FUNCTION_BODY>}
}
|
// 设置指定的数据源
DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class);
DynamicDataSourceContextHolder.push(dsName);
DataSource dataSource = dynamicRoutingDataSource.determineDataSource();
// 设置指定的目标表
ScrewProperties screwProperties = SpringContextHolder.getBean(ScrewProperties.class);
// 生成
byte[] data = screw.documentGeneration(dataSource, screwProperties).toByteArray();
response.reset();
response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
response.setContentType(ContentType.OCTET_STREAM.getValue());
IoUtil.write(response.getOutputStream(), Boolean.TRUE, data);
| 622
| 213
| 835
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/GenGroupController.java
|
GenGroupController
|
getgenGroupPage
|
class GenGroupController {
private final GenGroupService genGroupService;
/**
* 分页查询
* @param page 分页对象
* @param genGroup 模板分组
* @return
*/
@Operation(summary = "分页查询", description = "分页查询")
@GetMapping("/page")
@PreAuthorize("@pms.hasPermission('codegen_group_view')")
public R getgenGroupPage(Page page, GenGroupEntity genGroup) {<FILL_FUNCTION_BODY>}
/**
* 通过id查询模板分组
* @param id id
* @return R
*/
@Operation(summary = "通过id查询", description = "通过id查询")
@GetMapping("/{id}")
@PreAuthorize("@pms.hasPermission('codegen_group_view')")
public R getById(@PathVariable("id") Long id) {
return R.ok(genGroupService.getGroupVoById(id));
}
/**
* 新增模板分组
* @param genTemplateGroup 模板分组
* @return R
*/
@Operation(summary = "新增模板分组", description = "新增模板分组")
@SysLog("新增模板分组")
@PostMapping
@PreAuthorize("@pms.hasPermission('codegen_group_add')")
public R save(@RequestBody TemplateGroupDTO genTemplateGroup) {
genGroupService.saveGenGroup(genTemplateGroup);
return R.ok();
}
/**
* 修改模板分组
* @param groupVo 模板分组
* @return R
*/
@Operation(summary = "修改模板分组", description = "修改模板分组")
@SysLog("修改模板分组")
@PutMapping
@PreAuthorize("@pms.hasPermission('codegen_group_edit')")
public R updateById(@RequestBody GroupVo groupVo) {
genGroupService.updateGroupAndTemplateById(groupVo);
return R.ok();
}
/**
* 通过id删除模板分组
* @param ids id列表
* @return R
*/
@Operation(summary = "通过id删除模板分组", description = "通过id删除模板分组")
@SysLog("通过id删除模板分组")
@DeleteMapping
@PreAuthorize("@pms.hasPermission('codegen_group_del')")
public R removeById(@RequestBody Long[] ids) {
genGroupService.delGroupAndTemplate(ids);
return R.ok();
}
/**
* 导出excel 表格
* @param genGroup 查询条件
* @return excel 文件流
*/
@ResponseExcel
@GetMapping("/export")
@PreAuthorize("@pms.hasPermission('codegen_group_export')")
public List<GenGroupEntity> export(GenGroupEntity genGroup) {
return genGroupService.list(Wrappers.query(genGroup));
}
@GetMapping("/list")
@Operation(summary = "查询列表", description = "查询列表")
public R list() {
List<GenGroupEntity> list = genGroupService.list();
return R.ok(list);
}
}
|
LambdaQueryWrapper<GenGroupEntity> wrapper = Wrappers.<GenGroupEntity>lambdaQuery()
.like(genGroup.getId() != null, GenGroupEntity::getId, genGroup.getId())
.like(StrUtil.isNotEmpty(genGroup.getGroupName()), GenGroupEntity::getGroupName, genGroup.getGroupName());
return R.ok(genGroupService.page(page, wrapper));
| 842
| 101
| 943
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/GenTableController.java
|
GenTableController
|
sync
|
class GenTableController {
private final GenTableColumnService tableColumnService;
private final GenTableService tableService;
/**
* 分页查询
* @param page 分页对象
* @param table 列属性
* @return
*/
@Operation(summary = "分页查询", description = "分页查询")
@GetMapping("/page")
public R getTablePage(Page page, GenTable table) {
return R.ok(tableService.list(page, table));
}
/**
* 通过id查询列属性
* @param id id
* @return R
*/
@Operation(summary = "通过id查询", description = "通过id查询")
@GetMapping("/{id}")
public R getById(@PathVariable("id") Long id) {
return R.ok(tableService.getById(id));
}
/**
* 新增列属性
* @param table 列属性
* @return R
*/
@Operation(summary = "新增列属性", description = "新增列属性")
@SysLog("新增列属性")
@PostMapping
public R save(@RequestBody GenTable table) {
return R.ok(tableService.save(table));
}
/**
* 修改列属性
* @param table 列属性
* @return R
*/
@Operation(summary = "修改列属性", description = "修改列属性")
@SysLog("修改列属性")
@PutMapping
public R updateById(@RequestBody GenTable table) {
return R.ok(tableService.updateById(table));
}
/**
* 通过id删除列属性
* @param id id
* @return R
*/
@Operation(summary = "通过id删除列属性", description = "通过id删除列属性")
@SysLog("通过id删除列属性")
@DeleteMapping("/{id}")
public R removeById(@PathVariable Long id) {
return R.ok(tableService.removeById(id));
}
/**
* 导出excel 表格
* @param table 查询条件
* @return excel 文件流
*/
@ResponseExcel
@GetMapping("/export")
public List<GenTable> export(GenTable table) {
return tableService.list(Wrappers.query(table));
}
@GetMapping("/list/{dsName}")
public R listTable(@PathVariable("dsName") String dsName) {
return R.ok(tableService.queryDsAllTable(dsName));
}
@GetMapping("/column/{dsName}/{tableName}")
public R column(@PathVariable("dsName") String dsName, @PathVariable String tableName) {
return R.ok(tableService.queryColumn(dsName, tableName));
}
/**
* 获取表信息
* @param dsName 数据源
* @param tableName 表名称
*/
@GetMapping("/{dsName}/{tableName}")
public R<GenTable> info(@PathVariable("dsName") String dsName, @PathVariable String tableName) {
return R.ok(tableService.queryOrBuildTable(dsName, tableName));
}
/**
* 同步表信息
* @param dsName 数据源
* @param tableName 表名称
*/
@GetMapping("/sync/{dsName}/{tableName}")
public R<GenTable> sync(@PathVariable("dsName") String dsName, @PathVariable String tableName) {<FILL_FUNCTION_BODY>}
/**
* 修改表字段数据
* @param dsName 数据源
* @param tableName 表名称
* @param tableFieldList 字段列表
*/
@PutMapping("/field/{dsName}/{tableName}")
public R<String> updateTableField(@PathVariable("dsName") String dsName, @PathVariable String tableName,
@RequestBody List<GenTableColumnEntity> tableFieldList) {
tableColumnService.updateTableField(dsName, tableName, tableFieldList);
return R.ok();
}
}
|
// 表配置删除
tableService.remove(
Wrappers.<GenTable>lambdaQuery().eq(GenTable::getDsName, dsName).eq(GenTable::getTableName, tableName));
// 字段配置删除
tableColumnService.remove(Wrappers.<GenTableColumnEntity>lambdaQuery()
.eq(GenTableColumnEntity::getDsName, dsName)
.eq(GenTableColumnEntity::getTableName, tableName));
return R.ok(tableService.queryOrBuildTable(dsName, tableName));
| 1,038
| 145
| 1,183
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/GenTemplateController.java
|
GenTemplateController
|
getgenTemplatePage
|
class GenTemplateController {
private final GenTemplateService genTemplateService;
/**
* 分页查询
* @param page 分页对象
* @param genTemplate 模板
* @return
*/
@Operation(summary = "分页查询", description = "分页查询")
@GetMapping("/page")
@PreAuthorize("@pms.hasPermission('codegen_template_view')")
public R getgenTemplatePage(Page page, GenTemplateEntity genTemplate) {<FILL_FUNCTION_BODY>}
/**
* 查询全部模板
* @return
*/
@Operation(summary = "查询全部", description = "查询全部")
@GetMapping("/list")
@PreAuthorize("@pms.hasPermission('codegen_template_view')")
public R list() {
return R.ok(genTemplateService.list(Wrappers.emptyWrapper()));
}
/**
* 通过id查询模板
* @param id id
* @return R
*/
@Operation(summary = "通过id查询", description = "通过id查询")
@GetMapping("/{id}")
@PreAuthorize("@pms.hasPermission('codegen_template_view')")
public R getById(@PathVariable("id") Long id) {
return R.ok(genTemplateService.getById(id));
}
/**
* 新增模板
* @param genTemplate 模板
* @return R
*/
@Operation(summary = "新增模板", description = "新增模板")
@SysLog("新增模板")
@PostMapping
@PreAuthorize("@pms.hasPermission('codegen_template_add')")
public R save(@RequestBody GenTemplateEntity genTemplate) {
return R.ok(genTemplateService.save(genTemplate));
}
/**
* 修改模板
* @param genTemplate 模板
* @return R
*/
@Operation(summary = "修改模板", description = "修改模板")
@SysLog("修改模板")
@PutMapping
@PreAuthorize("@pms.hasPermission('codegen_template_edit')")
public R updateById(@RequestBody GenTemplateEntity genTemplate) {
return R.ok(genTemplateService.updateById(genTemplate));
}
/**
* 通过id删除模板
* @param ids id列表
* @return R
*/
@Operation(summary = "通过id删除模板", description = "通过id删除模板")
@SysLog("通过id删除模板")
@DeleteMapping
@PreAuthorize("@pms.hasPermission('codegen_template_del')")
public R removeById(@RequestBody Long[] ids) {
return R.ok(genTemplateService.removeBatchByIds(CollUtil.toList(ids)));
}
/**
* 导出excel 表格
* @param genTemplate 查询条件
* @return excel 文件流
*/
@ResponseExcel
@GetMapping("/export")
@PreAuthorize("@pms.hasPermission('codegen_template_export')")
public List<GenTemplateEntity> export(GenTemplateEntity genTemplate) {
return genTemplateService.list(Wrappers.query(genTemplate));
}
}
|
LambdaQueryWrapper<GenTemplateEntity> wrapper = Wrappers.<GenTemplateEntity>lambdaQuery()
.like(genTemplate.getId() != null, GenTemplateEntity::getId, genTemplate.getId())
.like(StrUtil.isNotEmpty(genTemplate.getTemplateName()), GenTemplateEntity::getTemplateName,
genTemplate.getTemplateName());
return R.ok(genTemplateService.page(page, wrapper));
| 825
| 107
| 932
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/GeneratorController.java
|
GeneratorController
|
code
|
class GeneratorController {
private final GeneratorService generatorService;
/**
* ZIP 下载生成代码
* @param tableIds 数据表ID
* @param response 流输出对象
*/
@SneakyThrows
@GetMapping("/download")
public void download(String tableIds, HttpServletResponse response) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
// 生成代码
for (String tableId : tableIds.split(StrUtil.COMMA)) {
generatorService.downloadCode(Long.parseLong(tableId), zip);
}
IoUtil.close(zip);
// zip压缩包数据
byte[] data = outputStream.toByteArray();
response.reset();
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment; filename=%s.zip", tableIds));
response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
response.setContentType("application/octet-stream; charset=UTF-8");
IoUtil.write(response.getOutputStream(), false, data);
}
/**
* 目标目录生成代码
*/
@ResponseBody
@GetMapping("/code")
public R<String> code(String tableIds) throws Exception {<FILL_FUNCTION_BODY>}
/**
* 预览代码
* @param tableId 表ID
* @return
*/
@SneakyThrows
@GetMapping("/preview")
public List<Map<String, String>> preview(Long tableId) {
return generatorService.preview(tableId);
}
}
|
// 生成代码
for (String tableId : tableIds.split(StrUtil.COMMA)) {
generatorService.generatorCode(Long.valueOf(tableId));
}
return R.ok();
| 444
| 59
| 503
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GenDatasourceConfServiceImpl.java
|
GenDatasourceConfServiceImpl
|
saveDsByEnc
|
class GenDatasourceConfServiceImpl extends ServiceImpl<GenDatasourceConfMapper, GenDatasourceConf>
implements GenDatasourceConfService {
private final StringEncryptor stringEncryptor;
private final DefaultDataSourceCreator druidDataSourceCreator;
/**
* 保存数据源并且加密
* @param conf
* @return
*/
@Override
public Boolean saveDsByEnc(GenDatasourceConf conf) {<FILL_FUNCTION_BODY>}
/**
* 更新数据源
* @param conf 数据源信息
* @return
*/
@Override
public Boolean updateDsByEnc(GenDatasourceConf conf) {
if (!checkDataSource(conf)) {
return Boolean.FALSE;
}
// 先移除
DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class);
dynamicRoutingDataSource.removeDataSource(baseMapper.selectById(conf.getId()).getName());
// 再添加
addDynamicDataSource(conf);
// 更新数据库配置
if (StrUtil.isNotBlank(conf.getPassword())) {
conf.setPassword(stringEncryptor.encrypt(conf.getPassword()));
}
this.baseMapper.updateById(conf);
return Boolean.TRUE;
}
/**
* 通过数据源名称删除
* @param dsIds 数据源ID
* @return
*/
@Override
public Boolean removeByDsId(Long[] dsIds) {
DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class);
this.baseMapper.selectBatchIds(CollUtil.toList(dsIds))
.forEach(ds -> dynamicRoutingDataSource.removeDataSource(ds.getName()));
this.baseMapper.deleteBatchIds(CollUtil.toList(dsIds));
return Boolean.TRUE;
}
/**
* 添加动态数据源
* @param conf 数据源信息
*/
@Override
public void addDynamicDataSource(GenDatasourceConf conf) {
DataSourceProperty dataSourceProperty = new DataSourceProperty();
dataSourceProperty.setPoolName(conf.getName());
dataSourceProperty.setUrl(conf.getUrl());
dataSourceProperty.setUsername(conf.getUsername());
dataSourceProperty.setPassword(conf.getPassword());
// 增加 ValidationQuery 参数
DruidConfig druidConfig = new DruidConfig();
dataSourceProperty.setDruid(druidConfig);
DataSource dataSource = druidDataSourceCreator.createDataSource(dataSourceProperty);
DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class);
dynamicRoutingDataSource.addDataSource(dataSourceProperty.getPoolName(), dataSource);
}
/**
* 校验数据源配置是否有效
* @param conf 数据源信息
* @return 有效/无效
*/
@Override
public Boolean checkDataSource(GenDatasourceConf conf) {
String url;
// JDBC 配置形式
if (DsConfTypeEnum.JDBC.getType().equals(conf.getConfType())) {
url = conf.getUrl();
}
else if (DsJdbcUrlEnum.MSSQL.getDbName().equals(conf.getDsType())) {
// 主机形式 sql server 特殊处理
DsJdbcUrlEnum urlEnum = DsJdbcUrlEnum.get(conf.getDsType());
url = String.format(urlEnum.getUrl(), conf.getHost(), conf.getPort(), conf.getDsName());
}
else {
DsJdbcUrlEnum urlEnum = DsJdbcUrlEnum.get(conf.getDsType());
url = String.format(urlEnum.getUrl(), conf.getHost(), conf.getPort(), conf.getDsName());
}
conf.setUrl(url);
try (Connection connection = DriverManager.getConnection(url, conf.getUsername(), conf.getPassword())) {
}
catch (SQLException e) {
log.error("数据源配置 {} , 获取链接失败", conf.getName(), e);
throw new RuntimeException("数据库配置错误,链接失败");
}
return Boolean.TRUE;
}
}
|
// 校验配置合法性
if (!checkDataSource(conf)) {
return Boolean.FALSE;
}
// 添加动态数据源
addDynamicDataSource(conf);
// 更新数据库配置
conf.setPassword(stringEncryptor.encrypt(conf.getPassword()));
this.baseMapper.insert(conf);
return Boolean.TRUE;
| 1,130
| 100
| 1,230
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GenGroupServiceImpl.java
|
GenGroupServiceImpl
|
updateGroupAndTemplateById
|
class GenGroupServiceImpl extends ServiceImpl<GenGroupMapper, GenGroupEntity> implements GenGroupService {
private final GenTemplateGroupService genTemplateGroupService;
/**
* 新增模板分组
* @param genTemplateGroup
*/
@Override
public void saveGenGroup(TemplateGroupDTO genTemplateGroup) {
// 1.保存group
GenGroupEntity groupEntity = new GenGroupEntity();
BeanUtil.copyProperties(genTemplateGroup, groupEntity);
baseMapper.insert(groupEntity);
// 2.保存关系
List<GenTemplateGroupEntity> goals = new LinkedList<>();
for (Long TemplateId : genTemplateGroup.getTemplateId()) {
GenTemplateGroupEntity templateGroup = new GenTemplateGroupEntity();
templateGroup.setTemplateId(TemplateId).setGroupId(groupEntity.getId());
goals.add(templateGroup);
}
genTemplateGroupService.saveBatch(goals);
}
/**
* 按照ids删除
* @param ids groupIds
*/
@Override
public void delGroupAndTemplate(Long[] ids) {
// 删除分组
this.removeBatchByIds(CollUtil.toList(ids));
// 删除关系
genTemplateGroupService
.remove(Wrappers.<GenTemplateGroupEntity>lambdaQuery().in(GenTemplateGroupEntity::getGroupId, ids));
}
/**
* 按照id查询
* @param id
* @return
*/
@Override
public GroupVo getGroupVoById(Long id) {
return baseMapper.getGroupVoById(id);
}
/**
* 根据id更新
* @param groupVo
*/
@Override
public void updateGroupAndTemplateById(GroupVo groupVo) {<FILL_FUNCTION_BODY>}
}
|
// 1.更新自身
GenGroupEntity groupEntity = new GenGroupEntity();
BeanUtil.copyProperties(groupVo, groupEntity);
this.updateById(groupEntity);
// 2.更新模板
// 2.1根据id删除之前的模板
genTemplateGroupService.remove(
Wrappers.<GenTemplateGroupEntity>lambdaQuery().eq(GenTemplateGroupEntity::getGroupId, groupVo.getId()));
// 2.2根据ids创建新的模板分组赋值
List<GenTemplateGroupEntity> goals = new LinkedList<>();
for (Long templateId : groupVo.getTemplateId()) {
goals.add(new GenTemplateGroupEntity().setGroupId(groupVo.getId()).setTemplateId(templateId));
}
genTemplateGroupService.saveBatch(goals);
| 468
| 217
| 685
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GenTableColumnServiceImpl.java
|
GenTableColumnServiceImpl
|
initFieldList
|
class GenTableColumnServiceImpl extends ServiceImpl<GenTableColumnMapper, GenTableColumnEntity>
implements GenTableColumnService {
private final GenFieldTypeMapper fieldTypeMapper;
/**
* 初始化表单字段列表,主要是将数据库表中的字段转化为表单需要的字段数据格式,并为审计字段排序
* @param tableFieldList 表单字段列表
*/
public void initFieldList(List<GenTableColumnEntity> tableFieldList) {<FILL_FUNCTION_BODY>}
/**
* 更新指定数据源和表名的表单字段信息
* @param dsName 数据源名称
* @param tableName 表名
* @param tableFieldList 表单字段列表
*/
@Override
public void updateTableField(String dsName, String tableName, List<GenTableColumnEntity> tableFieldList) {
AtomicInteger sort = new AtomicInteger();
this.updateBatchById(tableFieldList.stream()
.peek(field -> field.setSort(sort.getAndIncrement()))
.collect(Collectors.toList()));
}
}
|
// 字段类型、属性类型映射
List<GenFieldType> list = fieldTypeMapper.selectList(Wrappers.emptyWrapper());
Map<String, GenFieldType> fieldTypeMap = new LinkedHashMap<>(list.size());
list.forEach(
fieldTypeMapping -> fieldTypeMap.put(fieldTypeMapping.getColumnType().toLowerCase(), fieldTypeMapping));
// 索引计数器
AtomicInteger index = new AtomicInteger(0);
tableFieldList.forEach(field -> {
// 将字段名转化为驼峰格式
field.setAttrName(NamingCase.toCamelCase(field.getFieldName()));
// 获取字段对应的类型
GenFieldType fieldTypeMapping = fieldTypeMap.getOrDefault(field.getFieldType().toLowerCase(), null);
if (fieldTypeMapping == null) {
// 没找到对应的类型,则为Object类型
field.setAttrType("Object");
}
else {
field.setAttrType(fieldTypeMapping.getAttrType());
field.setPackageName(fieldTypeMapping.getPackageName());
}
// 设置查询类型和表单查询类型都为“=”
field.setQueryType("=");
field.setQueryFormType("text");
// 设置表单类型为文本框类型
field.setFormType("text");
// 保证审计字段最后显示
field.setSort(Objects.isNull(field.getSort()) ? index.getAndIncrement() : field.getSort());
});
| 292
| 419
| 711
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GenTableServiceImpl.java
|
GenTableServiceImpl
|
tableImport
|
class GenTableServiceImpl extends ServiceImpl<GenTableMapper, GenTable> implements GenTableService {
/**
* 默认配置信息
*/
private static final String CONFIG_PATH = "template/config.json";
private final GenTableColumnService columnService;
private final GenGroupService genGroupService;
/**
* 获取配置信息
* @return
*/
@Override
public Map<String, Object> getGeneratorConfig() {
ClassPathResource classPathResource = new ClassPathResource(CONFIG_PATH);
JSONObject jsonObject = JSONUtil.parseObj(IoUtil.readUtf8(classPathResource.getStream()));
return jsonObject.getRaw();
}
@Override
public List<Map<String, Object>> queryDsAllTable(String dsName) {
GeneratorMapper mapper = GenKit.getMapper(dsName);
// 手动切换数据源
DynamicDataSourceContextHolder.push(dsName);
return mapper.queryTable();
}
@Override
public List<Map<String, String>> queryColumn(String dsName, String tableName) {
GeneratorMapper mapper = GenKit.getMapper(dsName);
return mapper.selectMapTableColumn(tableName, dsName);
}
@Override
public IPage list(Page<GenTable> page, GenTable table) {
GeneratorMapper mapper = GenKit.getMapper(table.getDsName());
// 手动切换数据源
DynamicDataSourceContextHolder.push(table.getDsName());
return mapper.queryTable(page, table.getTableName());
}
/**
* 获取表信息
* @param dsName
* @param tableName
* @return
*/
@Override
public GenTable queryOrBuildTable(String dsName, String tableName) {
GenTable genTable = baseMapper.selectOne(
Wrappers.<GenTable>lambdaQuery().eq(GenTable::getTableName, tableName).eq(GenTable::getDsName, dsName));
// 如果 genTable 为空, 执行导入
if (Objects.isNull(genTable)) {
genTable = this.tableImport(dsName, tableName);
}
List<GenTableColumnEntity> fieldList = columnService.list(Wrappers.<GenTableColumnEntity>lambdaQuery()
.eq(GenTableColumnEntity::getDsName, dsName)
.eq(GenTableColumnEntity::getTableName, tableName)
.orderByAsc(GenTableColumnEntity::getSort));
genTable.setFieldList(fieldList);
// 查询模板分组信息
List<GenGroupEntity> groupEntities = genGroupService.list();
genTable.setGroupList(groupEntities);
return genTable;
}
@Transactional(rollbackFor = Exception.class)
public GenTable tableImport(String dsName, String tableName) {<FILL_FUNCTION_BODY>}
}
|
GeneratorMapper mapper = GenKit.getMapper(dsName);
// 手动切换数据源
DynamicDataSourceContextHolder.push(dsName);
// 查询表是否存在
GenTable table = new GenTable();
// 从数据库获取表信息
Map<String, String> queryTable = mapper.queryTable(tableName, dsName);
// 获取默认表配置信息 ()
Map<String, Object> generatorConfig = getGeneratorConfig();
JSONObject project = (JSONObject) generatorConfig.get("project");
JSONObject developer = (JSONObject) generatorConfig.get("developer");
table.setPackageName(project.getStr("packageName"));
table.setVersion(project.getStr("version"));
table.setBackendPath(project.getStr("backendPath"));
table.setFrontendPath(project.getStr("frontendPath"));
table.setAuthor(developer.getStr("author"));
table.setEmail(developer.getStr("email"));
table.setTableName(tableName);
table.setDsName(dsName);
table.setTableComment(MapUtil.getStr(queryTable, "tableComment"));
table.setDbType(MapUtil.getStr(queryTable, "dbType"));
table.setFormLayout(2);
table.setGeneratorType(GeneratorTypeEnum.ZIP_DOWNLOAD.getValue());
table.setClassName(NamingCase.toPascalCase(tableName));
table.setModuleName(GenKit.getModuleName(table.getPackageName()));
table.setFunctionName(GenKit.getFunctionName(tableName));
table.setCreateTime(LocalDateTime.now());
this.save(table);
// 获取原生字段数据
List<Map<String, String>> queryColumnList = mapper.selectMapTableColumn(tableName, dsName);
List<GenTableColumnEntity> tableFieldList = new ArrayList<>();
for (Map<String, String> columnMap : queryColumnList) {
String columnName = MapUtil.getStr(columnMap, "columnName");
GenTableColumnEntity genTableColumnEntity = new GenTableColumnEntity();
genTableColumnEntity.setTableName(tableName);
genTableColumnEntity.setDsName(dsName);
genTableColumnEntity.setFieldName(MapUtil.getStr(columnMap, "columnName"));
genTableColumnEntity.setFieldComment(MapUtil.getStr(columnMap, "comments"));
genTableColumnEntity.setFieldType(MapUtil.getStr(columnMap, "dataType"));
String columnKey = MapUtil.getStr(columnMap, "columnKey");
genTableColumnEntity.setAutoFill("DEFAULT");
genTableColumnEntity.setPrimaryPk((StringUtils.isNotBlank(columnKey) && "PRI".equalsIgnoreCase(columnKey))
? BoolFillEnum.TRUE.getValue() : BoolFillEnum.FALSE.getValue());
genTableColumnEntity.setAutoFill("DEFAULT");
genTableColumnEntity.setFormItem(BoolFillEnum.TRUE.getValue());
genTableColumnEntity.setGridItem(BoolFillEnum.TRUE.getValue());
// 审计字段处理
if (EnumUtil.contains(CommonColumnFiledEnum.class, columnName)) {
CommonColumnFiledEnum commonColumnFiledEnum = CommonColumnFiledEnum.valueOf(columnName);
genTableColumnEntity.setFormItem(commonColumnFiledEnum.getFormItem());
genTableColumnEntity.setGridItem(commonColumnFiledEnum.getGridItem());
genTableColumnEntity.setAutoFill(commonColumnFiledEnum.getAutoFill());
genTableColumnEntity.setSort(commonColumnFiledEnum.getSort());
}
tableFieldList.add(genTableColumnEntity);
}
// 初始化字段数据
columnService.initFieldList(tableFieldList);
// 保存列数据
columnService.saveOrUpdateBatch(tableFieldList);
table.setFieldList(tableFieldList);
return table;
| 746
| 1,053
| 1,799
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/GenKit.java
|
GenKit
|
getMapper
|
class GenKit {
/**
* 获取功能名 sys_a_b sysAb
* @param tableName 表名
* @return 功能名
*/
public String getFunctionName(String tableName) {
return StrUtil.toCamelCase(tableName);
}
/**
* 获取模块名称
* @param packageName 包名
* @return 功能名
*/
public String getModuleName(String packageName) {
return StrUtil.subAfter(packageName, ".", true);
}
/**
* 获取数据源对应方言的mapper
* @param dsName 数据源名称
* @return GeneratorMapper
*/
public GeneratorMapper getMapper(String dsName) {<FILL_FUNCTION_BODY>}
}
|
// 获取目标数据源数据库类型
GenDatasourceConfMapper datasourceConfMapper = SpringContextHolder.getBean(GenDatasourceConfMapper.class);
GenDatasourceConf datasourceConf = datasourceConfMapper
.selectOne(Wrappers.<GenDatasourceConf>lambdaQuery().eq(GenDatasourceConf::getName, dsName));
String dbConfType;
// 默认MYSQL 数据源
if (datasourceConf == null) {
dbConfType = DsJdbcUrlEnum.MYSQL.getDbName();
}
else {
dbConfType = datasourceConf.getDsType();
}
// 获取全部数据实现
ApplicationContext context = SpringContextHolder.getApplicationContext();
Map<String, GeneratorMapper> beansOfType = context.getBeansOfType(GeneratorMapper.class);
// 根据数据类型选择mapper
for (String key : beansOfType.keySet()) {
if (StrUtil.containsIgnoreCase(key, dbConfType)) {
return beansOfType.get(key);
}
}
throw new IllegalArgumentException("dsName 不合法: " + dsName);
| 202
| 303
| 505
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.