diff --git a/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/PigxAuthApplication.java b/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/PigxAuthApplication.java index 2e41ffa7c..7cb973006 100644 --- a/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/PigxAuthApplication.java +++ b/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/PigxAuthApplication.java @@ -19,15 +19,13 @@ package com.pig4cloud.pigx.auth; - import com.pig4cloud.pigx.common.feign.annotation.EnablePigxFeignClients; import org.springframework.boot.SpringApplication; import org.springframework.cloud.client.SpringCloudApplication; /** * @author lengleng - * @date 2020-02-08 - * 认证授权中心 + * @date 2020-02-08 认证授权中心 */ @SpringCloudApplication @EnablePigxFeignClients @@ -36,4 +34,5 @@ public class PigxAuthApplication { public static void main(String[] args) { SpringApplication.run(PigxAuthApplication.class, args); } + } diff --git a/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/config/AuthorizationServerConfig.java b/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/config/AuthorizationServerConfig.java index cf771def3..e70336773 100644 --- a/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/config/AuthorizationServerConfig.java +++ b/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/config/AuthorizationServerConfig.java @@ -45,17 +45,21 @@ import org.springframework.security.oauth2.provider.token.store.redis.RedisToken /** * @author lengleng - * @date 2018/6/22 - * 认证服务器配置 + * @date 2018/6/22 认证服务器配置 */ @Configuration @AllArgsConstructor @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { + private final ClientDetailsService pigxClientDetailsServiceImpl; + private final AuthenticationManager authenticationManagerBean; + private final RedisConnectionFactory redisConnectionFactory; + private final UserDetailsService pigxUserDetailsService; + private final TokenEnhancer pigxTokenEnhancer; @Override @@ -66,25 +70,18 @@ public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdap @Override public void configure(AuthorizationServerSecurityConfigurer oauthServer) { - oauthServer - .allowFormAuthenticationForClients() - .checkTokenAccess("isAuthenticated()"); + oauthServer.allowFormAuthenticationForClients().checkTokenAccess("isAuthenticated()"); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) { - endpoints - .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST) - .tokenStore(tokenStore()) - .tokenEnhancer(pigxTokenEnhancer) - .userDetailsService(pigxUserDetailsService) - .authenticationManager(authenticationManagerBean) - .reuseRefreshTokens(false) + endpoints.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST).tokenStore(tokenStore()) + .tokenEnhancer(pigxTokenEnhancer).userDetailsService(pigxUserDetailsService) + .authenticationManager(authenticationManagerBean).reuseRefreshTokens(false) .pathMapping("/oauth/confirm_access", "/token/confirm_access") .exceptionTranslator(new PigxWebResponseExceptionTranslator()); } - @Bean public TokenStore tokenStore() { RedisTokenStore tokenStore = new RedisTokenStore(redisConnectionFactory); @@ -97,5 +94,5 @@ public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdap }); return tokenStore; } -} +} diff --git a/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/config/WebSecurityConfigurer.java b/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/config/WebSecurityConfigurer.java index f104bf9dc..644b38b60 100644 --- a/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/config/WebSecurityConfigurer.java +++ b/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/config/WebSecurityConfigurer.java @@ -39,43 +39,28 @@ import org.springframework.security.web.authentication.AuthenticationSuccessHand /** * @author lengleng - * @date 2018/6/22 - * 认证相关配置 + * @date 2018/6/22 认证相关配置 */ @Primary @Order(90) @Configuration public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter { + @Override @SneakyThrows protected void configure(HttpSecurity http) { - http - .formLogin() - .loginPage("/token/login") - .loginProcessingUrl("/token/form") - .failureHandler(authenticationFailureHandler()) - .and() - .logout() + http.formLogin().loginPage("/token/login").loginProcessingUrl("/token/form") + .failureHandler(authenticationFailureHandler()).and().logout() .logoutSuccessHandler((request, response, authentication) -> { String referer = request.getHeader(HttpHeaders.REFERER); response.sendRedirect(referer); - }) - .deleteCookies("JSESSIONID") - .invalidateHttpSession(true) - .and() - .authorizeRequests() - .antMatchers( - "/token/**", - "/actuator/**", - "/mobile/**").permitAll() - .anyRequest().authenticated() - .and().csrf().disable() - .apply(mobileSecurityConfigurer()); + }).deleteCookies("JSESSIONID").invalidateHttpSession(true).and().authorizeRequests() + .antMatchers("/token/**", "/actuator/**", "/mobile/**").permitAll().anyRequest().authenticated().and() + .csrf().disable().apply(mobileSecurityConfigurer()); } /** * 不拦截静态资源 - * * @param web */ @Override @@ -105,11 +90,9 @@ public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter { return new MobileSecurityConfigurer(); } - /** * https://spring.io/blog/2017/11/01/spring-security-5-0-0-rc1-released#password-storage-updated * Encoded password does not look like BCrypt - * * @return PasswordEncoder */ @Bean diff --git a/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/endpoint/PigxTokenEndpoint.java b/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/endpoint/PigxTokenEndpoint.java index 148f5103d..da534e297 100644 --- a/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/endpoint/PigxTokenEndpoint.java +++ b/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/endpoint/PigxTokenEndpoint.java @@ -59,25 +59,29 @@ import java.util.Map; /** * @author lengleng - * @date 2018/6/24 - * 删除token端点 + * @date 2018/6/24 删除token端点 */ @Slf4j @RestController @AllArgsConstructor @RequestMapping("/token") public class PigxTokenEndpoint { - private static final String PIGX_OAUTH_ACCESS = SecurityConstants.PIGX_PREFIX + SecurityConstants.OAUTH_PREFIX + "auth_to_access:"; + + private static final String PIGX_OAUTH_ACCESS = SecurityConstants.PIGX_PREFIX + SecurityConstants.OAUTH_PREFIX + + "auth_to_access:"; + private final ClientDetailsService clientDetailsService; + private final RedisTemplate redisTemplate; + private final TokenStore tokenStore; + private final CacheManager cacheManager; /** * 认证页面 - * * @param modelAndView - * @param error 表单登录失败处理回调的错误信息 + * @param error 表单登录失败处理回调的错误信息 * @return ModelAndView */ @GetMapping("/login") @@ -89,7 +93,6 @@ public class PigxTokenEndpoint { /** * 确认授权页面 - * * @param request * @param session * @param modelAndView @@ -114,7 +117,6 @@ public class PigxTokenEndpoint { /** * 退出token - * * @param authHeader Authorization */ @DeleteMapping("/logout") @@ -129,7 +131,6 @@ public class PigxTokenEndpoint { /** * 令牌管理调用 - * * @param token token * @return */ @@ -143,8 +144,7 @@ public class PigxTokenEndpoint { OAuth2Authentication auth2Authentication = tokenStore.readAuthentication(accessToken); // 清空用户信息 - cacheManager.getCache(CacheConstants.USER_DETAILS) - .evict(auth2Authentication.getName()); + cacheManager.getCache(CacheConstants.USER_DETAILS).evict(auth2Authentication.getName()); // 清空access token tokenStore.removeAccessToken(accessToken); @@ -155,35 +155,33 @@ public class PigxTokenEndpoint { return R.ok(); } - /** * 查询token - * * @param params 分页参数 * @return */ @Inner @PostMapping("/page") public R tokenList(@RequestBody Map params) { - //根据分页参数获取对应数据 + // 根据分页参数获取对应数据 String key = String.format("%s*:%s", PIGX_OAUTH_ACCESS, TenantContextHolder.getTenantId()); - List pages = findKeysForPage(key, MapUtil.getInt(params, PaginationConstants.CURRENT) - , MapUtil.getInt(params, PaginationConstants.SIZE)); + List pages = findKeysForPage(key, MapUtil.getInt(params, PaginationConstants.CURRENT), + MapUtil.getInt(params, PaginationConstants.SIZE)); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer()); - Page result = new Page(MapUtil.getInt(params, PaginationConstants.CURRENT), MapUtil.getInt(params, PaginationConstants.SIZE)); + Page result = new Page(MapUtil.getInt(params, PaginationConstants.CURRENT), + MapUtil.getInt(params, PaginationConstants.SIZE)); result.setRecords(redisTemplate.opsForValue().multiGet(pages)); result.setTotal(redisTemplate.keys(key).size()); return R.ok(result); } - private List findKeysForPage(String patternKey, int pageNum, int pageSize) { - ScanOptions options = ScanOptions.scanOptions().count(1000L) - .match(patternKey).build(); + ScanOptions options = ScanOptions.scanOptions().count(1000L).match(patternKey).build(); RedisSerializer redisSerializer = (RedisSerializer) redisTemplate.getKeySerializer(); - Cursor cursor = (Cursor) redisTemplate.executeWithStickyConnection(redisConnection -> new ConvertingCursor<>(redisConnection.scan(options), redisSerializer::deserialize)); + Cursor cursor = (Cursor) redisTemplate.executeWithStickyConnection( + redisConnection -> new ConvertingCursor<>(redisConnection.scan(options), redisSerializer::deserialize)); List result = new ArrayList<>(); int tmpIndex = 0; int startIndex = (pageNum - 1) * pageSize; @@ -205,9 +203,11 @@ public class PigxTokenEndpoint { try { cursor.close(); - } catch (IOException e) { + } + catch (IOException e) { log.error("关闭cursor 失败"); } return result; } + } diff --git a/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/handler/PigxAuthenticationFailureEventHandler.java b/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/handler/PigxAuthenticationFailureEventHandler.java index 8087197ed..505375995 100644 --- a/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/handler/PigxAuthenticationFailureEventHandler.java +++ b/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/handler/PigxAuthenticationFailureEventHandler.java @@ -44,21 +44,22 @@ import javax.servlet.http.HttpServletResponse; @Component @AllArgsConstructor public class PigxAuthenticationFailureEventHandler implements AuthenticationFailureHandler { + private final RemoteLogService logService; /** * 异步处理,登录失败方法 *

- * * @param authenticationException 登录的authentication 对象 - * @param authentication 登录的authenticationException 对象 - * @param request 请求 - * @param response 响应 + * @param authentication 登录的authenticationException 对象 + * @param request 请求 + * @param response 响应 */ @Async @Override @SneakyThrows - public void handle(AuthenticationException authenticationException, Authentication authentication, HttpServletRequest request, HttpServletResponse response) { + public void handle(AuthenticationException authenticationException, Authentication authentication, + HttpServletRequest request, HttpServletResponse response) { String username = authentication.getName(); SysLog sysLog = SysLogUtils.getSysLog(request, username); sysLog.setTitle(username + "用户登录"); @@ -72,4 +73,5 @@ public class PigxAuthenticationFailureEventHandler implements AuthenticationFail log.info("用户:{} 登录失败,异常:{}", username, authenticationException.getLocalizedMessage()); } + } diff --git a/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/handler/PigxAuthenticationSuccessEventHandler.java b/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/handler/PigxAuthenticationSuccessEventHandler.java index d3e5dfbc6..964da8ac9 100644 --- a/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/handler/PigxAuthenticationSuccessEventHandler.java +++ b/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/handler/PigxAuthenticationSuccessEventHandler.java @@ -41,16 +41,16 @@ import javax.servlet.http.HttpServletResponse; @Component @AllArgsConstructor public class PigxAuthenticationSuccessEventHandler implements AuthenticationSuccessHandler { + private final RemoteLogService logService; /** * 处理登录成功方法 *

* 获取到登录的authentication 对象 - * * @param authentication 登录对象 - * @param request 请求 - * @param response 返回 + * @param request 请求 + * @param response 返回 */ @Async @Override @@ -65,4 +65,5 @@ public class PigxAuthenticationSuccessEventHandler implements AuthenticationSucc logService.saveLog(sysLog, SecurityConstants.FROM_IN); log.info("用户:{} 登录成功", username); } + } diff --git a/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/service/PigxClientDetailsServiceImpl.java b/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/service/PigxClientDetailsServiceImpl.java index bbb8e0d51..5b0177ee7 100644 --- a/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/service/PigxClientDetailsServiceImpl.java +++ b/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/service/PigxClientDetailsServiceImpl.java @@ -19,14 +19,13 @@ import javax.sql.DataSource; */ @Service public class PigxClientDetailsServiceImpl extends JdbcClientDetailsService { + public PigxClientDetailsServiceImpl(DataSource dataSource) { super(dataSource); } - /** * 重写原生方法支持redis缓存 - * * @param clientId * @return ClientDetails * @throws InvalidClientException @@ -34,8 +33,9 @@ public class PigxClientDetailsServiceImpl extends JdbcClientDetailsService { @Override @Cacheable(value = CacheConstants.CLIENT_DETAILS_KEY, key = "#clientId", unless = "#result == null") public ClientDetails loadClientByClientId(String clientId) { - super.setSelectClientDetailsSql(String.format(SecurityConstants.DEFAULT_SELECT_STATEMENT - , TenantContextHolder.getTenantId())); + super.setSelectClientDetailsSql( + String.format(SecurityConstants.DEFAULT_SELECT_STATEMENT, TenantContextHolder.getTenantId())); return super.loadClientByClientId(clientId); } + } diff --git a/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/service/PigxUserDetailsServiceImpl.java b/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/service/PigxUserDetailsServiceImpl.java index f8abe6dbe..6d674fd50 100644 --- a/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/service/PigxUserDetailsServiceImpl.java +++ b/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/service/PigxUserDetailsServiceImpl.java @@ -53,12 +53,13 @@ import java.util.Set; @Service @AllArgsConstructor public class PigxUserDetailsServiceImpl implements PigxUserDetailsService { + private final RemoteUserService remoteUserService; + private final CacheManager cacheManager; /** * 用户密码登录 - * * @param username 用户名 * @return * @throws UsernameNotFoundException @@ -77,10 +78,8 @@ public class PigxUserDetailsServiceImpl implements PigxUserDetailsService { return userDetails; } - /** * 根据社交登录code 登录 - * * @param inStr TYPE@CODE * @return UserDetails * @throws UsernameNotFoundException @@ -93,7 +92,6 @@ public class PigxUserDetailsServiceImpl implements PigxUserDetailsService { /** * 构建userdetails - * * @param result 用户信息 * @return */ @@ -111,15 +109,15 @@ public class PigxUserDetailsServiceImpl implements PigxUserDetailsService { dbAuthsSet.addAll(Arrays.asList(info.getPermissions())); } - Collection authorities - = AuthorityUtils.createAuthorityList(dbAuthsSet.toArray(new String[0])); + Collection authorities = AuthorityUtils + .createAuthorityList(dbAuthsSet.toArray(new String[0])); SysUser user = info.getSysUser(); boolean enabled = StrUtil.equals(user.getLockFlag(), CommonConstants.STATUS_NORMAL); // 构造security用户 - return new PigxUser(user.getUserId(), user.getDeptId(), user.getPhone(), user.getAvatar(), user.getTenantId() - , user.getUsername(), SecurityConstants.BCRYPT + user.getPassword() - , enabled, true, true - , !CommonConstants.STATUS_LOCK.equals(user.getLockFlag()), authorities); + return new PigxUser(user.getUserId(), user.getDeptId(), user.getPhone(), user.getAvatar(), user.getTenantId(), + user.getUsername(), SecurityConstants.BCRYPT + user.getPassword(), enabled, true, true, + !CommonConstants.STATUS_LOCK.equals(user.getLockFlag()), authorities); } + } diff --git a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/config/JacksonConfig.java b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/config/JacksonConfig.java index 045fb81e2..d3c932a39 100644 --- a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/config/JacksonConfig.java +++ b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/config/JacksonConfig.java @@ -37,4 +37,5 @@ public class JacksonConfig { builder.modules(new PigxJavaTimeModule()); }; } + } diff --git a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/config/MessageSourceConfig.java b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/config/MessageSourceConfig.java index a86f8f6c2..2eac2fb6b 100644 --- a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/config/MessageSourceConfig.java +++ b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/config/MessageSourceConfig.java @@ -33,9 +33,9 @@ public class MessageSourceConfig { @Bean public MessageSource messageSource() { - ReloadableResourceBundleMessageSource messageSource - = new ReloadableResourceBundleMessageSource(); + ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); messageSource.setBasename("classpath:i18n/messages"); return messageSource; } + } diff --git a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/config/RestTemplateConfig.java b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/config/RestTemplateConfig.java index b4f844ddd..64d71428a 100644 --- a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/config/RestTemplateConfig.java +++ b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/config/RestTemplateConfig.java @@ -23,13 +23,14 @@ import org.springframework.web.client.RestTemplate; /** * @author lengleng - * @date 2018/8/16 - * RestTemplate + * @date 2018/8/16 RestTemplate */ @Configuration public class RestTemplateConfig { + @Bean public RestTemplate restTemplate() { return new RestTemplate(); } + } diff --git a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/CacheConstants.java b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/CacheConstants.java index dc7dcfbce..fc560ca2c 100644 --- a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/CacheConstants.java +++ b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/CacheConstants.java @@ -20,7 +20,6 @@ public interface CacheConstants { */ String DEFAULT_CODE_KEY = "DEFAULT_CODE_KEY:"; - /** * 菜单信息缓存 */ @@ -36,13 +35,11 @@ public interface CacheConstants { */ String DICT_DETAILS = "dict_details"; - /** * oauth 客户端信息 */ String CLIENT_DETAILS_KEY = "pigx_oauth:client:details"; - /** * spring boot admin 事件key */ @@ -68,13 +65,11 @@ public interface CacheConstants { */ String MP_REDIS_RELOAD_TOPIC = "mp_redis_reload_topic"; - /** * 支付 reload 事件 */ String PAY_REDIS_RELOAD_TOPIC = "pay_redis_reload_topic"; - /** * 参数缓存 */ @@ -84,4 +79,5 @@ public interface CacheConstants { * 租户缓存 (不区分租户) */ String TENANT_DETAILS = GLOBALLY + "tenant_details"; + } diff --git a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/CommonConstants.java b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/CommonConstants.java index 2fff0f48d..909d31dc7 100644 --- a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/CommonConstants.java +++ b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/CommonConstants.java @@ -24,6 +24,7 @@ package com.pig4cloud.pigx.common.core.constant; * @date 2017/10/29 */ public interface CommonConstants { + /** * header 中租户ID */ @@ -43,6 +44,7 @@ public interface CommonConstants { * 删除 */ String STATUS_DEL = "1"; + /** * 正常 */ @@ -82,6 +84,7 @@ public interface CommonConstants { * 成功标记 */ Integer SUCCESS = 0; + /** * 失败标记 */ @@ -96,4 +99,5 @@ public interface CommonConstants { * 滑块验证码 */ String IMAGE_CODE_TYPE = "blockPuzzle"; + } diff --git a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/PaginationConstants.java b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/PaginationConstants.java index 3aaea25f1..e1802fe7c 100644 --- a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/PaginationConstants.java +++ b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/PaginationConstants.java @@ -2,16 +2,20 @@ package com.pig4cloud.pigx.common.core.constant; /** * 分页相关的参数 + * * @author lishangbu * @date 2018/11/22 */ public interface PaginationConstants { + /** * 当前页 */ - String CURRENT="current"; + String CURRENT = "current"; + /** * 每页大小 */ - String SIZE="size"; + String SIZE = "size"; + } diff --git a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/SecurityConstants.java b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/SecurityConstants.java index 4c72a9eb2..162625f10 100644 --- a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/SecurityConstants.java +++ b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/SecurityConstants.java @@ -24,22 +24,27 @@ package com.pig4cloud.pigx.common.core.constant; * @date 2017-12-18 */ public interface SecurityConstants { + /** * 刷新 */ String REFRESH_TOKEN = "refresh_token"; + /** * 验证码有效期 */ int CODE_TIME = 60; + /** * 验证码长度 */ String CODE_SIZE = "4"; + /** * 角色前缀 */ String ROLE = "ROLE_"; + /** * 前缀 */ @@ -49,6 +54,7 @@ public interface SecurityConstants { * oauth 相关前缀 */ String OAUTH_PREFIX = "oauth:"; + /** * 项目的license */ @@ -78,6 +84,7 @@ public interface SecurityConstants { * 社交登录URL */ String SOCIAL_TOKEN_URL = "/mobile/token/social"; + /** * 自定义登录URL */ @@ -86,21 +93,20 @@ public interface SecurityConstants { /** * 微信获取OPENID */ - String WX_AUTHORIZATION_CODE_URL = "https://api.weixin.qq.com/sns/oauth2/access_token" + - "?appid=%s&secret=%s&code=%s&grant_type=authorization_code"; + String WX_AUTHORIZATION_CODE_URL = "https://api.weixin.qq.com/sns/oauth2/access_token" + + "?appid=%s&secret=%s&code=%s&grant_type=authorization_code"; /** * 微信小程序OPENID */ - String MINI_APP_AUTHORIZATION_CODE_URL = "https://api.weixin.qq.com/sns/jscode2session" + - "?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code"; + String MINI_APP_AUTHORIZATION_CODE_URL = "https://api.weixin.qq.com/sns/jscode2session" + + "?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code"; /** * 码云获取token */ - String GITEE_AUTHORIZATION_CODE_URL = "https://gitee.com/oauth/token?grant_type=" + - "authorization_code&code=%S&client_id=%s&redirect_uri=" + - "%s&client_secret=%s"; + String GITEE_AUTHORIZATION_CODE_URL = "https://gitee.com/oauth/token?grant_type=" + + "authorization_code&code=%S&client_id=%s&redirect_uri=" + "%s&client_secret=%s"; /** * 开源中国获取token @@ -121,6 +127,7 @@ public interface SecurityConstants { * {bcrypt} 加密的特征码 */ String BCRYPT = "{bcrypt}"; + /** * sys_oauth_client_details 表的字段,不包括client_id、client_secret */ @@ -131,8 +138,7 @@ public interface SecurityConstants { /** * JdbcClientDetailsService 查询语句 */ - String BASE_FIND_STATEMENT = "select " + CLIENT_FIELDS - + " from sys_oauth_client_details"; + String BASE_FIND_STATEMENT = "select " + CLIENT_FIELDS + " from sys_oauth_client_details"; /** * 按条件client_id 查询 @@ -173,6 +179,7 @@ public interface SecurityConstants { * 头像 */ String DETAILS_AVATAR = "avatar"; + /** * 用户部门字段 */ @@ -197,4 +204,5 @@ public interface SecurityConstants { * AES 加密 */ String AES = "aes"; + } diff --git a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/ServiceNameConstants.java b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/ServiceNameConstants.java index 2d9855dd9..ff006a16a 100644 --- a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/ServiceNameConstants.java +++ b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/ServiceNameConstants.java @@ -21,10 +21,10 @@ package com.pig4cloud.pigx.common.core.constant; /** * @author lengleng - * @date 2018年06月22日16:41:01 - * 服务名称 + * @date 2018年06月22日16:41:01 服务名称 */ public interface ServiceNameConstants { + /** * 认证中心 */ @@ -39,4 +39,5 @@ public interface ServiceNameConstants { * 分布式事务协调服务 */ String TX_MANAGER = "pigx-tx-manager"; + } diff --git a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/enums/DictTypeEnum.java b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/enums/DictTypeEnum.java index cf7b27f6c..bf7fa6c29 100644 --- a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/enums/DictTypeEnum.java +++ b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/enums/DictTypeEnum.java @@ -12,6 +12,7 @@ import lombok.Getter; @Getter @AllArgsConstructor public enum DictTypeEnum { + /** * 字典类型-系统内置(不可修改) */ @@ -26,8 +27,10 @@ public enum DictTypeEnum { * 类型 */ private String type; + /** * 描述 */ private String description; + } diff --git a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/enums/LoginTypeEnum.java b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/enums/LoginTypeEnum.java index 8688d0539..464d19629 100644 --- a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/enums/LoginTypeEnum.java +++ b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/enums/LoginTypeEnum.java @@ -22,12 +22,12 @@ import lombok.Getter; /** * @author lengleng - * @date 2018/8/15 - * 社交登录类型 + * @date 2018/8/15 社交登录类型 */ @Getter @AllArgsConstructor public enum LoginTypeEnum { + /** * 账号密码登录 */ @@ -67,8 +67,10 @@ public enum LoginTypeEnum { * 类型 */ private String type; + /** * 描述 */ private String description; + } diff --git a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/enums/MenuTypeEnum.java b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/enums/MenuTypeEnum.java index 84dce2c54..9f0241a77 100644 --- a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/enums/MenuTypeEnum.java +++ b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/enums/MenuTypeEnum.java @@ -32,8 +32,10 @@ public enum MenuTypeEnum { * 类型 */ private String type; + /** * 描述 */ private String description; + } diff --git a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/enums/ProcessStatusEnum.java b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/enums/ProcessStatusEnum.java index 14790b8e4..a14b2daa1 100644 --- a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/enums/ProcessStatusEnum.java +++ b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/enums/ProcessStatusEnum.java @@ -22,12 +22,12 @@ import lombok.Getter; /** * @author lengleng - * @date 2018/9/30 - * 流程状态 + * @date 2018/9/30 流程状态 */ @Getter @AllArgsConstructor public enum ProcessStatusEnum { + /** * 图片资源 */ @@ -42,8 +42,10 @@ public enum ProcessStatusEnum { * 类型 */ private final String status; + /** * 描述 */ private final String description; + } diff --git a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/enums/ResourceTypeEnum.java b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/enums/ResourceTypeEnum.java index 91142681d..5a8a3fb97 100644 --- a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/enums/ResourceTypeEnum.java +++ b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/enums/ResourceTypeEnum.java @@ -22,12 +22,12 @@ import lombok.Getter; /** * @author lengleng - * @date 2018/9/30 - * 资源类型 + * @date 2018/9/30 资源类型 */ @Getter @AllArgsConstructor public enum ResourceTypeEnum { + /** * 图片资源 */ @@ -42,8 +42,10 @@ public enum ResourceTypeEnum { * 类型 */ private final String type; + /** * 描述 */ private final String description; + } diff --git a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/enums/StyleTypeEnum.java b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/enums/StyleTypeEnum.java index 0e776f828..b92180589 100644 --- a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/enums/StyleTypeEnum.java +++ b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/enums/StyleTypeEnum.java @@ -12,6 +12,7 @@ import lombok.Getter; @Getter @AllArgsConstructor public enum StyleTypeEnum { + /** * 前端类型-avue 风格 */ @@ -26,8 +27,10 @@ public enum StyleTypeEnum { * 类型 */ private String style; + /** * 描述 */ private String description; + } diff --git a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/enums/TaskStatusEnum.java b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/enums/TaskStatusEnum.java index 7e0f2af77..cbf55d9e5 100644 --- a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/enums/TaskStatusEnum.java +++ b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/constant/enums/TaskStatusEnum.java @@ -22,12 +22,12 @@ import lombok.Getter; /** * @author lengleng - * @date 2018/9/30 - * 流程状态 + * @date 2018/9/30 流程状态 */ @Getter @AllArgsConstructor public enum TaskStatusEnum { + /** * 未提交 */ @@ -52,8 +52,10 @@ public enum TaskStatusEnum { * 类型 */ private final String status; + /** * 描述 */ private final String description; + } diff --git a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/exception/CheckedException.java b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/exception/CheckedException.java index 36201eb47..d194559a4 100644 --- a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/exception/CheckedException.java +++ b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/exception/CheckedException.java @@ -27,6 +27,7 @@ import lombok.NoArgsConstructor; */ @NoArgsConstructor public class CheckedException extends RuntimeException { + private static final long serialVersionUID = 1L; public CheckedException(String message) { diff --git a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/exception/ValidateCodeException.java b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/exception/ValidateCodeException.java index 896878ea8..c58dac5fd 100644 --- a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/exception/ValidateCodeException.java +++ b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/exception/ValidateCodeException.java @@ -24,6 +24,7 @@ package com.pig4cloud.pigx.common.core.exception; * @date 2018年06月22日16:22:15 */ public class ValidateCodeException extends RuntimeException { + private static final long serialVersionUID = -7285211528095468156L; public ValidateCodeException() { @@ -32,4 +33,5 @@ public class ValidateCodeException extends RuntimeException { public ValidateCodeException(String msg) { super(msg); } + } diff --git a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/jackson/PigxJavaTimeModule.java b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/jackson/PigxJavaTimeModule.java index 96defbfae..53f1d04f1 100644 --- a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/jackson/PigxJavaTimeModule.java +++ b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/jackson/PigxJavaTimeModule.java @@ -25,11 +25,18 @@ public class PigxJavaTimeModule extends SimpleModule { public PigxJavaTimeModule() { super(PackageVersion.VERSION); - this.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN))); - this.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN))); - this.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_TIME_PATTERN))); - this.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN))); - this.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN))); - this.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_TIME_PATTERN))); + this.addSerializer(LocalDateTime.class, + new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN))); + this.addSerializer(LocalDate.class, + new LocalDateSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN))); + this.addSerializer(LocalTime.class, + new LocalTimeSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_TIME_PATTERN))); + this.addDeserializer(LocalDateTime.class, + new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN))); + this.addDeserializer(LocalDate.class, + new LocalDateDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN))); + this.addDeserializer(LocalTime.class, + new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_TIME_PATTERN))); } + } diff --git a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/sensitive/SensitiveSerialize.java b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/sensitive/SensitiveSerialize.java index 1b19b03e0..440346049 100644 --- a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/sensitive/SensitiveSerialize.java +++ b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/sensitive/SensitiveSerialize.java @@ -41,52 +41,55 @@ import java.util.Objects; public class SensitiveSerialize extends JsonSerializer implements ContextualSerializer { private SensitiveTypeEnum type; + private Integer prefixNoMaskLen; + private Integer suffixNoMaskLen; + private String maskStr; @Override public void serialize(final String origin, final JsonGenerator jsonGenerator, - final SerializerProvider serializerProvider) throws IOException { + final SerializerProvider serializerProvider) throws IOException { switch (type) { - case CHINESE_NAME: - jsonGenerator.writeString(DesensitizedUtils.chineseName(origin)); - break; - case ID_CARD: - jsonGenerator.writeString(DesensitizedUtils.idCardNum(origin)); - break; - case FIXED_PHONE: - jsonGenerator.writeString(DesensitizedUtils.fixedPhone(origin)); - break; - case MOBILE_PHONE: - jsonGenerator.writeString(DesensitizedUtils.mobilePhone(origin)); - break; - case ADDRESS: - jsonGenerator.writeString(DesensitizedUtils.address(origin)); - break; - case EMAIL: - jsonGenerator.writeString(DesensitizedUtils.email(origin)); - break; - case BANK_CARD: - jsonGenerator.writeString(DesensitizedUtils.bankCard(origin)); - break; - case PASSWORD: - jsonGenerator.writeString(DesensitizedUtils.password(origin)); - break; - case KEY: - jsonGenerator.writeString(DesensitizedUtils.key(origin)); - break; - case CUSTOMER: - jsonGenerator.writeString(DesensitizedUtils.desValue(origin, prefixNoMaskLen, suffixNoMaskLen, maskStr)); - break; - default: - throw new IllegalArgumentException("Unknow sensitive type enum " + type); + case CHINESE_NAME: + jsonGenerator.writeString(DesensitizedUtils.chineseName(origin)); + break; + case ID_CARD: + jsonGenerator.writeString(DesensitizedUtils.idCardNum(origin)); + break; + case FIXED_PHONE: + jsonGenerator.writeString(DesensitizedUtils.fixedPhone(origin)); + break; + case MOBILE_PHONE: + jsonGenerator.writeString(DesensitizedUtils.mobilePhone(origin)); + break; + case ADDRESS: + jsonGenerator.writeString(DesensitizedUtils.address(origin)); + break; + case EMAIL: + jsonGenerator.writeString(DesensitizedUtils.email(origin)); + break; + case BANK_CARD: + jsonGenerator.writeString(DesensitizedUtils.bankCard(origin)); + break; + case PASSWORD: + jsonGenerator.writeString(DesensitizedUtils.password(origin)); + break; + case KEY: + jsonGenerator.writeString(DesensitizedUtils.key(origin)); + break; + case CUSTOMER: + jsonGenerator.writeString(DesensitizedUtils.desValue(origin, prefixNoMaskLen, suffixNoMaskLen, maskStr)); + break; + default: + throw new IllegalArgumentException("Unknow sensitive type enum " + type); } } @Override public JsonSerializer createContextual(final SerializerProvider serializerProvider, - final BeanProperty beanProperty) throws JsonMappingException { + final BeanProperty beanProperty) throws JsonMappingException { if (beanProperty != null) { if (Objects.equals(beanProperty.getType().getRawClass(), String.class)) { Sensitive sensitive = beanProperty.getAnnotation(Sensitive.class); @@ -94,12 +97,13 @@ public class SensitiveSerialize extends JsonSerializer implements Contex sensitive = beanProperty.getContextAnnotation(Sensitive.class); } if (sensitive != null) { - return new SensitiveSerialize(sensitive.type(), sensitive.prefixNoMaskLen(), sensitive.suffixNoMaskLen(), sensitive.maskStr()); + return new SensitiveSerialize(sensitive.type(), sensitive.prefixNoMaskLen(), + sensitive.suffixNoMaskLen(), sensitive.maskStr()); } } return serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty); } return serializerProvider.findNullValueSerializer(null); } -} +} diff --git a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/sensitive/SensitiveTypeEnum.java b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/sensitive/SensitiveTypeEnum.java index 7eff50469..9da0bba13 100644 --- a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/sensitive/SensitiveTypeEnum.java +++ b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/sensitive/SensitiveTypeEnum.java @@ -25,46 +25,45 @@ package com.pig4cloud.pigx.common.core.sensitive; **/ public enum SensitiveTypeEnum { - /** - * 自定义 - */ - CUSTOMER, - /** - * 用户名, 刘*华, 徐* - */ - CHINESE_NAME, - /** - * 身份证号, 110110********1234 - */ - ID_CARD, - /** - * 座机号, ****1234 - */ - FIXED_PHONE, - /** - * 手机号, 176****1234 - */ - MOBILE_PHONE, - /** - * 地址, 北京******** - */ - ADDRESS, - /** - * 电子邮件, s*****o@xx.com - */ - EMAIL, - /** - * 银行卡, 622202************1234 - */ - BANK_CARD, - /** - * 密码, 永远是 ******, 与长度无关 - */ - PASSWORD, - /** - * 密钥, 永远是 ******, 与长度无关 - */ - KEY - + /** + * 自定义 + */ + CUSTOMER, + /** + * 用户名, 刘*华, 徐* + */ + CHINESE_NAME, + /** + * 身份证号, 110110********1234 + */ + ID_CARD, + /** + * 座机号, ****1234 + */ + FIXED_PHONE, + /** + * 手机号, 176****1234 + */ + MOBILE_PHONE, + /** + * 地址, 北京******** + */ + ADDRESS, + /** + * 电子邮件, s*****o@xx.com + */ + EMAIL, + /** + * 银行卡, 622202************1234 + */ + BANK_CARD, + /** + * 密码, 永远是 ******, 与长度无关 + */ + PASSWORD, + /** + * 密钥, 永远是 ******, 与长度无关 + */ + KEY } diff --git a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/util/ClassUtils.java b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/util/ClassUtils.java index 75187e045..83e1cc5dd 100644 --- a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/util/ClassUtils.java +++ b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/util/ClassUtils.java @@ -39,12 +39,12 @@ import java.lang.reflect.Method; */ @UtilityClass public class ClassUtils extends org.springframework.util.ClassUtils { + private final ParameterNameDiscoverer PARAMETERNAMEDISCOVERER = new DefaultParameterNameDiscoverer(); /** * 获取方法参数信息 - * - * @param constructor 构造器 + * @param constructor 构造器 * @param parameterIndex 参数序号 * @return {MethodParameter} */ @@ -56,8 +56,7 @@ public class ClassUtils extends org.springframework.util.ClassUtils { /** * 获取方法参数信息 - * - * @param method 方法 + * @param method 方法 * @param parameterIndex 参数序号 * @return {MethodParameter} */ @@ -69,18 +68,19 @@ public class ClassUtils extends org.springframework.util.ClassUtils { /** * 获取Annotation - * - * @param method Method + * @param method Method * @param annotationType 注解类 - * @param 泛型标记 + * @param 泛型标记 * @return {Annotation} */ public A getAnnotation(Method method, Class annotationType) { Class targetClass = method.getDeclaringClass(); - // The method may be on an interface, but we need attributes from the target class. + // 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. + // If we are dealing with method with generic parameters, find the original + // method. specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod); // 先找方法,再找方法上的类 A annotation = AnnotatedElementUtils.findMergedAnnotation(specificMethod, annotationType); @@ -94,10 +94,9 @@ public class ClassUtils extends org.springframework.util.ClassUtils { /** * 获取Annotation - * - * @param handlerMethod HandlerMethod + * @param handlerMethod HandlerMethod * @param annotationType 注解类 - * @param 泛型标记 + * @param 泛型标记 * @return {Annotation} */ public A getAnnotation(HandlerMethod handlerMethod, Class annotationType) { diff --git a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/util/DesensitizedUtils.java b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/util/DesensitizedUtils.java index ce9d83a8b..43e6a1c64 100644 --- a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/util/DesensitizedUtils.java +++ b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/util/DesensitizedUtils.java @@ -17,7 +17,6 @@ package com.pig4cloud.pigx.common.core.util; - import cn.hutool.core.util.StrUtil; /** @@ -30,11 +29,10 @@ public class DesensitizedUtils { /** * 对字符串进行脱敏操作 - * - * @param origin 原始字符串 + * @param origin 原始字符串 * @param prefixNoMaskLen 左侧需要保留几位明文字段 * @param suffixNoMaskLen 右侧需要保留几位明文字段 - * @param maskStr 用于遮罩的字符串, 如'*' + * @param maskStr 用于遮罩的字符串, 如'*' * @return 脱敏后结果 */ public static String desValue(String origin, int prefixNoMaskLen, int suffixNoMaskLen, String maskStr) { @@ -59,7 +57,6 @@ public class DesensitizedUtils { /** * 【中文姓名】只显示最后一个汉字,其他隐藏为星号,比如:**梦 - * * @param fullName 姓名 * @return 结果 */ @@ -72,7 +69,6 @@ public class DesensitizedUtils { /** * 【身份证号】显示前六位, 四位,其他隐藏。共计18位或者15位,比如:340304*******1234 - * * @param id 身份证号码 * @return 结果 */ @@ -82,7 +78,6 @@ public class DesensitizedUtils { /** * 【固定电话】后四位,其他隐藏,比如 ****1234 - * * @param num 固定电话 * @return 结果 */ @@ -92,7 +87,6 @@ public class DesensitizedUtils { /** * 【手机号码】前三位,后四位,其他隐藏,比如135****6810 - * * @param num 手机号码 * @return 结果 */ @@ -102,7 +96,6 @@ public class DesensitizedUtils { /** * 【地址】只显示到地区,不显示详细地址,比如:北京市海淀区**** - * * @param address 地址 * @return 结果 */ @@ -112,7 +105,6 @@ public class DesensitizedUtils { /** * 【电子邮箱 邮箱前缀仅显示第一个字母,前缀其他隐藏,用星号代替,@及后面的地址显示,比如:d**@126.com - * * @param email 电子邮箱 * @return 结果 */ @@ -131,7 +123,6 @@ public class DesensitizedUtils { /** * 【银行卡号】前六位,后四位,其他用星号隐藏每位1个星号,比如:622260**********1234 - * * @param cardNum 银行卡号 * @return 结果 */ @@ -141,7 +132,6 @@ public class DesensitizedUtils { /** * 【密码】密码的全部字符都用*代替,比如:****** - * * @param password 密码 * @return 结果 */ @@ -153,9 +143,7 @@ public class DesensitizedUtils { } /** - * 【密钥】密钥除了最后三位,全部都用*代替,比如:***xdS - * 脱敏后长度为6,如果明文长度不足三位,则按实际长度显示,剩余位置补* - * + * 【密钥】密钥除了最后三位,全部都用*代替,比如:***xdS 脱敏后长度为6,如果明文长度不足三位,则按实际长度显示,剩余位置补* * @param key 密钥 * @return 结果 */ @@ -167,13 +155,15 @@ public class DesensitizedUtils { StringBuilder tmpKey = new StringBuilder(desValue(key, 0, 3, "*")); if (tmpKey.length() > viewLength) { return tmpKey.substring(tmpKey.length() - viewLength); - } else if (tmpKey.length() < viewLength) { + } + else if (tmpKey.length() < viewLength) { int buffLength = viewLength - tmpKey.length(); for (int i = 0; i < buffLength; i++) { tmpKey.insert(0, "*"); } return tmpKey.toString(); - } else { + } + else { return tmpKey.toString(); } } diff --git a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/util/R.java b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/util/R.java index 82fe04b54..cc5a6ef4d 100644 --- a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/util/R.java +++ b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/util/R.java @@ -40,6 +40,7 @@ import java.io.Serializable; @Accessors(chain = true) @ApiModel(value = "响应信息主体") public class R implements Serializable { + private static final long serialVersionUID = 1L; @Getter @@ -52,7 +53,6 @@ public class R implements Serializable { @ApiModelProperty(value = "返回信息") private String msg; - @Getter @Setter @ApiModelProperty(value = "数据") @@ -93,4 +93,5 @@ public class R implements Serializable { apiResult.setMsg(msg); return apiResult; } + } diff --git a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/util/SpringContextHolder.java b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/util/SpringContextHolder.java index f06f87615..9385274b4 100644 --- a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/util/SpringContextHolder.java +++ b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/util/SpringContextHolder.java @@ -29,8 +29,7 @@ import org.springframework.stereotype.Service; /** * @author lengleng - * @date 2018/6/27 - * Spring 工具类 + * @date 2018/6/27 Spring 工具类 */ @Slf4j @Service @@ -81,7 +80,6 @@ public class SpringContextHolder implements ApplicationContextAware, DisposableB /** * 发布事件 - * * @param event */ public static void publishEvent(ApplicationEvent event) { diff --git a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/util/WebUtils.java b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/util/WebUtils.java index cd380d483..0760c2b82 100644 --- a/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/util/WebUtils.java +++ b/pigx-common/pigx-common-core/src/main/java/com/pig4cloud/pigx/common/core/util/WebUtils.java @@ -41,7 +41,6 @@ import java.io.PrintWriter; import java.nio.charset.StandardCharsets; import java.util.Optional; - /** * Miscellaneous utilities for web applications. * @@ -50,13 +49,13 @@ import java.util.Optional; @Slf4j @UtilityClass public class WebUtils extends org.springframework.web.util.WebUtils { + private final String BASIC_ = "Basic "; + private final String UNKNOWN = "unknown"; /** - * 判断是否ajax请求 - * spring ajax 返回含有 ResponseBody 或者 RestController注解 - * + * 判断是否ajax请求 spring ajax 返回含有 ResponseBody 或者 RestController注解 * @param handlerMethod HandlerMethod * @return 是否ajax请求 */ @@ -67,7 +66,6 @@ public class WebUtils extends org.springframework.web.util.WebUtils { /** * 读取cookie - * * @param name cookie name * @return cookie value */ @@ -79,9 +77,8 @@ public class WebUtils extends org.springframework.web.util.WebUtils { /** * 读取cookie - * * @param request HttpServletRequest - * @param name cookie name + * @param name cookie name * @return cookie value */ public String getCookieVal(HttpServletRequest request, String name) { @@ -91,9 +88,8 @@ public class WebUtils extends org.springframework.web.util.WebUtils { /** * 清除 某个指定的cookie - * * @param response HttpServletResponse - * @param key cookie key + * @param key cookie key */ public void removeCookie(HttpServletResponse response, String key) { setCookie(response, key, null, 0); @@ -101,10 +97,9 @@ public class WebUtils extends org.springframework.web.util.WebUtils { /** * 设置cookie - * - * @param response HttpServletResponse - * @param name cookie name - * @param value cookie value + * @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) { @@ -117,21 +112,20 @@ public class WebUtils extends org.springframework.web.util.WebUtils { /** * 获取 HttpServletRequest - * * @return {HttpServletRequest} */ public HttpServletRequest getRequest() { try { RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes(); return ((ServletRequestAttributes) requestAttributes).getRequest(); - } catch (IllegalStateException e) { + } + catch (IllegalStateException e) { return null; } } /** * 获取 HttpServletResponse - * * @return {HttpServletResponse} */ public HttpServletResponse getResponse() { @@ -140,9 +134,8 @@ public class WebUtils extends org.springframework.web.util.WebUtils { /** * 返回json - * * @param response HttpServletResponse - * @param result 结果对象 + * @param result 结果对象 */ public void renderJson(HttpServletResponse response, Object result) { renderJson(response, result, MediaType.APPLICATION_JSON_VALUE); @@ -150,9 +143,8 @@ public class WebUtils extends org.springframework.web.util.WebUtils { /** * 返回json - * - * @param response HttpServletResponse - * @param result 结果对象 + * @param response HttpServletResponse + * @param result 结果对象 * @param contentType contentType */ public void renderJson(HttpServletResponse response, Object result, String contentType) { @@ -160,14 +152,14 @@ public class WebUtils extends org.springframework.web.util.WebUtils { response.setContentType(contentType); try (PrintWriter out = response.getWriter()) { out.append(JSONUtil.toJsonStr(result)); - } catch (IOException e) { + } + catch (IOException e) { log.error(e.getMessage(), e); } } /** * 获取ip - * * @return {String} */ public String getIP() { @@ -176,7 +168,6 @@ public class WebUtils extends org.springframework.web.util.WebUtils { /** * 获取ip - * * @param request HttpServletRequest * @return {String} */ @@ -210,18 +201,19 @@ public class WebUtils extends org.springframework.web.util.WebUtils { * @param defVal * @return 如果解析失败返回默认值 */ - public String extractClientId(String header,final String defVal) { + public String extractClientId(String header, final String defVal) { if (header == null || !header.startsWith(BASIC_)) { - log.debug("请求头中client信息为空: {}",header); + log.debug("请求头中client信息为空: {}", header); return defVal; } byte[] base64Token = header.substring(6).getBytes(StandardCharsets.UTF_8); byte[] decoded; try { decoded = Base64.decode(base64Token); - } catch (IllegalArgumentException e) { - log.debug("Failed to decode basic authentication token: {}",header); + } + catch (IllegalArgumentException e) { + log.debug("Failed to decode basic authentication token: {}", header); return defVal; } @@ -230,7 +222,7 @@ public class WebUtils extends org.springframework.web.util.WebUtils { int delim = token.indexOf(":"); if (delim == -1) { - log.debug("Invalid basic authentication token: {}",header); + log.debug("Invalid basic authentication token: {}", header); return defVal; } return token.substring(0, delim); @@ -241,19 +233,20 @@ public class WebUtils extends org.springframework.web.util.WebUtils { * @param header * @return */ - public Optional extractClientId(String header){ - return Optional.ofNullable(extractClientId(header,null)); + public Optional extractClientId(String header) { + return Optional.ofNullable(extractClientId(header, null)); } + /** * 从request 获取CLIENT_ID - * * @return */ public String getClientId(String header) { - String clientId = extractClientId(header,null); - if(clientId == null){ + String clientId = extractClientId(header, null); + if (clientId == null) { throw new CheckedException("Invalid basic authentication token"); } return clientId; } + } diff --git a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/cache/DefaultRedisCacheWriter.java b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/cache/DefaultRedisCacheWriter.java index 44b62faa9..8152f6564 100644 --- a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/cache/DefaultRedisCacheWriter.java +++ b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/cache/DefaultRedisCacheWriter.java @@ -35,16 +35,17 @@ import java.util.function.Consumer; import java.util.function.Function; /** - * {@link RedisCacheWriter} implementation capable of reading/writing binary data from/to Redis in {@literal standalone} - * and {@literal cluster} environments. Works upon a given {@link RedisConnectionFactory} to obtain the actual - * {@link RedisConnection}.
+ * {@link RedisCacheWriter} implementation capable of reading/writing binary data from/to + * Redis in {@literal standalone} and {@literal cluster} environments. Works upon a given + * {@link RedisConnectionFactory} to obtain the actual {@link RedisConnection}.
* {@link DefaultRedisCacheWriter} can be used in * {@link RedisCacheWriter#lockingRedisCacheWriter(RedisConnectionFactory) locking} or - * {@link RedisCacheWriter#nonLockingRedisCacheWriter(RedisConnectionFactory) non-locking} mode. While - * {@literal non-locking} aims for maximum performance it may result in overlapping, non atomic, command execution for - * operations spanning multiple Redis interactions like {@code putIfAbsent}. The {@literal locking} counterpart prevents - * command overlap by setting an explicit lock key and checking against presence of this key which leads to additional - * requests and potential command wait times. + * {@link RedisCacheWriter#nonLockingRedisCacheWriter(RedisConnectionFactory) non-locking} + * mode. While {@literal non-locking} aims for maximum performance it may result in + * overlapping, non atomic, command execution for operations spanning multiple Redis + * interactions like {@code putIfAbsent}. The {@literal locking} counterpart prevents + * command overlap by setting an explicit lock key and checking against presence of this + * key which leads to additional requests and potential command wait times. * * @author Christoph Strobl * @author Mark Paluch @@ -53,6 +54,7 @@ import java.util.function.Function; class DefaultRedisCacheWriter implements RedisCacheWriter { private final RedisConnectionFactory connectionFactory; + private final Duration sleepTime; /** @@ -64,8 +66,8 @@ class DefaultRedisCacheWriter implements RedisCacheWriter { /** * @param connectionFactory must not be {@literal null}. - * @param sleepTime sleep time between lock request attempts. Must not be {@literal null}. Use {@link Duration#ZERO} - * to disable locking. + * @param sleepTime sleep time between lock request attempts. Must not be + * {@literal null}. Use {@link Duration#ZERO} to disable locking. */ private DefaultRedisCacheWriter(RedisConnectionFactory connectionFactory, Duration sleepTime) { @@ -87,7 +89,8 @@ class DefaultRedisCacheWriter implements RedisCacheWriter { if (shouldExpireWithin(ttl)) { connection.set(key, value, Expiration.from(ttl.toMillis(), TimeUnit.MILLISECONDS), SetOption.upsert()); - } else { + } + else { connection.set(key, value); } @@ -95,7 +98,6 @@ class DefaultRedisCacheWriter implements RedisCacheWriter { }); } - @Override public byte[] get(String name, byte[] key) { @@ -105,7 +107,6 @@ class DefaultRedisCacheWriter implements RedisCacheWriter { return execute(name, connection -> connection.get(key)); } - @Override public byte[] putIfAbsent(String name, byte[] key, byte[] value, @Nullable Duration ttl) { @@ -129,7 +130,8 @@ class DefaultRedisCacheWriter implements RedisCacheWriter { } return connection.get(key); - } finally { + } + finally { if (isLockingCacheWriter()) { doUnlock(name, connection); @@ -138,7 +140,6 @@ class DefaultRedisCacheWriter implements RedisCacheWriter { }); } - @Override public void remove(String name, byte[] key) { @@ -148,7 +149,6 @@ class DefaultRedisCacheWriter implements RedisCacheWriter { execute(name, connection -> connection.del(key)); } - @Override public void clean(String name, byte[] pattern) { @@ -167,12 +167,13 @@ class DefaultRedisCacheWriter implements RedisCacheWriter { } byte[][] keys = Optional.ofNullable(connection.keys(pattern)).orElse(Collections.emptySet()) - .toArray(new byte[0][]); + .toArray(new byte[0][]); if (keys.length > 0) { connection.del(keys); } - } finally { + } + finally { if (wasLocked && isLockingCacheWriter()) { doUnlock(name, connection); @@ -185,7 +186,6 @@ class DefaultRedisCacheWriter implements RedisCacheWriter { /** * Explicitly set a write lock on a cache. - * * @param name the name of the cache to lock. */ void lock(String name) { @@ -194,7 +194,6 @@ class DefaultRedisCacheWriter implements RedisCacheWriter { /** * Explicitly remove a write lock from a cache. - * * @param name the name of the cache to unlock. */ void unlock(String name) { @@ -227,7 +226,8 @@ class DefaultRedisCacheWriter implements RedisCacheWriter { checkAndPotentiallyWaitUntilUnlocked(name, connection); return callback.apply(connection); - } finally { + } + finally { connection.close(); } } @@ -238,7 +238,8 @@ class DefaultRedisCacheWriter implements RedisCacheWriter { try { callback.accept(connection); - } finally { + } + finally { connection.close(); } } @@ -254,13 +255,14 @@ class DefaultRedisCacheWriter implements RedisCacheWriter { while (doCheckLock(name, connection)) { Thread.sleep(sleepTime.toMillis()); } - } catch (InterruptedException ex) { + } + catch (InterruptedException ex) { // Re-interrupt current thread, to allow other participants to react. Thread.currentThread().interrupt(); - throw new PessimisticLockingFailureException(String.format("Interrupted while waiting to unlock cache %s", name), - ex); + throw new PessimisticLockingFailureException( + String.format("Interrupted while waiting to unlock cache %s", name), ex); } } @@ -271,5 +273,5 @@ class DefaultRedisCacheWriter implements RedisCacheWriter { private static byte[] createCacheLockKey(String name) { return (name + "~lock").getBytes(StandardCharsets.UTF_8); } -} +} diff --git a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/cache/RedisAutoCacheManager.java b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/cache/RedisAutoCacheManager.java index 628442488..b98bd0afd 100644 --- a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/cache/RedisAutoCacheManager.java +++ b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/cache/RedisAutoCacheManager.java @@ -43,11 +43,13 @@ import java.util.Map; */ @Slf4j public class RedisAutoCacheManager extends RedisCacheManager { + private static final String SPLIT_FLAG = "#"; + private static final int CACHE_LENGTH = 2; RedisAutoCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration, - Map initialCacheConfigurations, boolean allowInFlightCacheCreation) { + Map initialCacheConfigurations, boolean allowInFlightCacheCreation) { super(cacheWriter, defaultCacheConfiguration, initialCacheConfigurations, allowInFlightCacheCreation); } @@ -71,7 +73,6 @@ public class RedisAutoCacheManager extends RedisCacheManager { /** * 从上下文中获取租户ID,重写@Cacheable value 值 - * * @param name * @return */ @@ -83,4 +84,5 @@ public class RedisAutoCacheManager extends RedisCacheManager { } return super.getCache(TenantContextHolder.getTenantId() + StrUtil.COLON + name); } + } diff --git a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/cache/RedisCacheAutoConfiguration.java b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/cache/RedisCacheAutoConfiguration.java index 6858ebcc2..a7b6e18e6 100644 --- a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/cache/RedisCacheAutoConfiguration.java +++ b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/cache/RedisCacheAutoConfiguration.java @@ -46,19 +46,21 @@ import java.util.Map; * @author L.cm */ @Configuration -@AutoConfigureAfter({RedisAutoConfiguration.class}) -@ConditionalOnBean({RedisConnectionFactory.class}) -@ConditionalOnMissingBean({CacheManager.class}) +@AutoConfigureAfter({ RedisAutoConfiguration.class }) +@ConditionalOnBean({ RedisConnectionFactory.class }) +@ConditionalOnMissingBean({ CacheManager.class }) @EnableConfigurationProperties(CacheProperties.class) public class RedisCacheAutoConfiguration { + private final CacheProperties cacheProperties; + private final CacheManagerCustomizers customizerInvoker; + @Nullable private final RedisCacheConfiguration redisCacheConfiguration; - RedisCacheAutoConfiguration(CacheProperties cacheProperties, - CacheManagerCustomizers customizerInvoker, - ObjectProvider redisCacheConfiguration) { + RedisCacheAutoConfiguration(CacheProperties cacheProperties, CacheManagerCustomizers customizerInvoker, + ObjectProvider redisCacheConfiguration) { this.cacheProperties = cacheProperties; this.customizerInvoker = customizerInvoker; this.redisCacheConfiguration = redisCacheConfiguration.getIfAvailable(); @@ -76,7 +78,7 @@ public class RedisCacheAutoConfiguration { initialCaches.putAll(cacheConfigMap); } RedisAutoCacheManager cacheManager = new RedisAutoCacheManager(redisCacheWriter, cacheConfiguration, - initialCaches, true); + initialCaches, true); cacheManager.setTransactionAware(false); return this.customizerInvoker.customize(cacheManager); } @@ -84,10 +86,12 @@ public class RedisCacheAutoConfiguration { private RedisCacheConfiguration determineConfiguration(ClassLoader classLoader) { if (this.redisCacheConfiguration != null) { return this.redisCacheConfiguration; - } else { + } + else { CacheProperties.Redis redisProperties = this.cacheProperties.getRedis(); RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig(); - config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new JdkSerializationRedisSerializer(classLoader))); + config = config.serializeValuesWith(RedisSerializationContext.SerializationPair + .fromSerializer(new JdkSerializationRedisSerializer(classLoader))); if (redisProperties.getTimeToLive() != null) { config = config.entryTtl(redisProperties.getTimeToLive()); } @@ -107,4 +111,5 @@ public class RedisCacheAutoConfiguration { return config; } } + } diff --git a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/cache/RedisCacheManagerConfig.java b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/cache/RedisCacheManagerConfig.java index bf92ed86b..c87b1c91f 100644 --- a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/cache/RedisCacheManagerConfig.java +++ b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/cache/RedisCacheManagerConfig.java @@ -37,7 +37,8 @@ public class RedisCacheManagerConfig { @Bean public CacheManagerCustomizers cacheManagerCustomizers( - ObjectProvider>> customizers) { + ObjectProvider>> customizers) { return new CacheManagerCustomizers(customizers.getIfAvailable()); } + } diff --git a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/cache/RedisTemplateConfig.java b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/cache/RedisTemplateConfig.java index 25204ce9d..bbcc9560d 100644 --- a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/cache/RedisTemplateConfig.java +++ b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/cache/RedisTemplateConfig.java @@ -29,7 +29,7 @@ import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer import org.springframework.data.redis.serializer.StringRedisSerializer; /** - * RedisTemplate 配置 + * RedisTemplate 配置 * * @author L.cm */ @@ -49,4 +49,5 @@ public class RedisTemplateConfig { redisTemplate.setConnectionFactory(redisConnectionFactory); return redisTemplate; } + } diff --git a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/datascope/DataScope.java b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/datascope/DataScope.java index 8b36f7dc6..fd5f8dbcf 100644 --- a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/datascope/DataScope.java +++ b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/datascope/DataScope.java @@ -26,12 +26,12 @@ import java.util.List; /** * @author lengleng - * @date 2018/8/30 - * 数据权限查询参数 + * @date 2018/8/30 数据权限查询参数 */ @Data @EqualsAndHashCode(callSuper = true) public class DataScope extends HashMap { + /** * 限制范围的字段名称 */ @@ -46,4 +46,5 @@ public class DataScope extends HashMap { * 是否只查询本部门 */ private Boolean isOnly = false; + } diff --git a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/datascope/DataScopeHandle.java b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/datascope/DataScopeHandle.java index bdcd56dc7..414d9058b 100644 --- a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/datascope/DataScopeHandle.java +++ b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/datascope/DataScopeHandle.java @@ -29,9 +29,9 @@ public interface DataScopeHandle { /** * 计算用户数据权限 - * * @param deptList 部门ID,如果为空表示没有任何数据权限。 * @return 返回true表示无需进行数据过滤处理,返回false表示需要进行数据过滤 */ Boolean calcScope(List deptList); + } diff --git a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/datascope/DataScopeInterceptor.java b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/datascope/DataScopeInterceptor.java index 05c786a98..7c25ba50e 100644 --- a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/datascope/DataScopeInterceptor.java +++ b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/datascope/DataScopeInterceptor.java @@ -37,7 +37,6 @@ import java.util.List; import java.util.Map; import java.util.Properties; - /** * @author lengleng * @date 2020/5/27 @@ -46,8 +45,10 @@ import java.util.Properties; */ @Slf4j @AllArgsConstructor -@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})}) +@Intercepts({ + @Signature(type = StatementHandler.class, method = "prepare", args = { Connection.class, Integer.class }) }) public class DataScopeInterceptor extends AbstractSqlParserHandler implements Interceptor { + private final DataScopeHandle dataScopeHandle; @Override @@ -66,7 +67,7 @@ public class DataScopeInterceptor extends AbstractSqlParserHandler implements In String originalSql = boundSql.getSql(); Object parameterObject = boundSql.getParameterObject(); - //查找参数中包含DataScope类型的参数 + // 查找参数中包含DataScope类型的参数 DataScope dataScope = findDataScopeObject(parameterObject); if (dataScope == null) { return invocation.proceed(); @@ -79,20 +80,20 @@ public class DataScopeInterceptor extends AbstractSqlParserHandler implements In return invocation.proceed(); } - if(deptIds.isEmpty()){ + if (deptIds.isEmpty()) { originalSql = "select * from (" + originalSql + ") temp_data_scope where 1 = 2"; - }else{ + } + else { String join = CollectionUtil.join(deptIds, ","); - originalSql = "select * from (" + originalSql + ") temp_data_scope where temp_data_scope." + scopeName + " in (" + join + ")"; + originalSql = "select * from (" + originalSql + ") temp_data_scope where temp_data_scope." + scopeName + + " in (" + join + ")"; } metaObject.setValue("delegate.boundSql.sql", originalSql); return invocation.proceed(); } - /** * 生成拦截对象的代理 - * * @param target 目标对象 * @return 代理对象 */ @@ -106,7 +107,6 @@ public class DataScopeInterceptor extends AbstractSqlParserHandler implements In /** * mybatis配置的属性 - * * @param properties mybatis配置的属性 */ @Override @@ -116,14 +116,14 @@ public class DataScopeInterceptor extends AbstractSqlParserHandler implements In /** * 查找参数是否包括DataScope对象 - * * @param parameterObj 参数列表 * @return DataScope */ private DataScope findDataScopeObject(Object parameterObj) { if (parameterObj instanceof DataScope) { return (DataScope) parameterObj; - } else if (parameterObj instanceof Map) { + } + else if (parameterObj instanceof Map) { for (Object val : ((Map) parameterObj).values()) { if (val instanceof DataScope) { return (DataScope) val; diff --git a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/datascope/DataScopeMapper.java b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/datascope/DataScopeMapper.java index 8d3b41ec1..f7b1d0216 100644 --- a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/datascope/DataScopeMapper.java +++ b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/datascope/DataScopeMapper.java @@ -16,23 +16,20 @@ public interface DataScopeMapper extends BaseMapper { /** * 根据 entity 条件,查询全部记录 - * * @param queryWrapper 实体对象封装操作类(可以为 null) - * @param scope 数据权限范围 + * @param scope 数据权限范围 * @return List */ List selectListByScope(@Param(Constants.WRAPPER) Wrapper queryWrapper, DataScope scope); - /** * 根据 entity 条件,查询全部记录(并翻页) - * - * @param page 分页查询条件(可以为 RowBounds.DEFAULT) + * @param page 分页查询条件(可以为 RowBounds.DEFAULT) * @param queryWrapper 实体对象封装操作类(可以为 null) - * @param scope 数据权限范围 + * @param scope 数据权限范围 * @return Page */ - > E selectPageByScope(E page, @Param(Constants.WRAPPER) Wrapper queryWrapper, DataScope scope); - + > E selectPageByScope(E page, @Param(Constants.WRAPPER) Wrapper queryWrapper, + DataScope scope); } diff --git a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/datascope/DataScopeSqlInjector.java b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/datascope/DataScopeSqlInjector.java index 5c65ed32c..900b098b2 100644 --- a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/datascope/DataScopeSqlInjector.java +++ b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/datascope/DataScopeSqlInjector.java @@ -18,4 +18,5 @@ public class DataScopeSqlInjector extends DefaultSqlInjector { methodList.add(new SelectPageByScope()); return methodList; } + } diff --git a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/datascope/DataScopeTypeEnum.java b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/datascope/DataScopeTypeEnum.java index a65ee61e7..08be66d9f 100644 --- a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/datascope/DataScopeTypeEnum.java +++ b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/datascope/DataScopeTypeEnum.java @@ -29,6 +29,7 @@ import lombok.Getter; @Getter @AllArgsConstructor public enum DataScopeTypeEnum { + /** * 查询全部数据 */ @@ -53,8 +54,10 @@ public enum DataScopeTypeEnum { * 类型 */ private final int type; + /** * 描述 */ private final String description; + } diff --git a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/datascope/PigxDefaultDatascopeHandle.java b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/datascope/PigxDefaultDatascopeHandle.java index 820e7f46f..23e44eef1 100644 --- a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/datascope/PigxDefaultDatascopeHandle.java +++ b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/datascope/PigxDefaultDatascopeHandle.java @@ -40,31 +40,29 @@ import java.util.stream.Collectors; * 默认data scope 判断处理器 */ public class PigxDefaultDatascopeHandle implements DataScopeHandle { + @Autowired private RemoteDataScopeService dataScopeService; /** * 计算用户数据权限 - * * @param deptList * @return */ @Override public Boolean calcScope(List deptList) { PigxUser user = SecurityUtils.getUser(); - List roleIdList = user.getAuthorities() - .stream().map(GrantedAuthority::getAuthority) + List roleIdList = user.getAuthorities().stream().map(GrantedAuthority::getAuthority) .filter(authority -> authority.startsWith(SecurityConstants.ROLE)) - .map(authority -> authority.split(StrUtil.UNDERLINE)[1]) - .collect(Collectors.toList()); + .map(authority -> authority.split(StrUtil.UNDERLINE)[1]).collect(Collectors.toList()); // 当前用户的角色为空 - if(CollectionUtil.isEmpty(roleIdList)){ + if (CollectionUtil.isEmpty(roleIdList)) { return false; } SysRole role = dataScopeService.getRoleList(roleIdList).getData().stream() .min(Comparator.comparingInt(SysRole::getDsType)).orElse(null); // 角色有可能已经删除了 - if(role == null){ + if (role == null) { return false; } Integer dsType = role.getDsType(); @@ -75,14 +73,13 @@ public class PigxDefaultDatascopeHandle implements DataScopeHandle { // 自定义 if (DataScopeTypeEnum.CUSTOM.getType() == dsType) { String dsScope = role.getDsScope(); - deptList.addAll(Arrays.stream(dsScope.split(StrUtil.COMMA)) - .map(Integer::parseInt).collect(Collectors.toList())); + deptList.addAll( + Arrays.stream(dsScope.split(StrUtil.COMMA)).map(Integer::parseInt).collect(Collectors.toList())); } // 查询本级及其下级 if (DataScopeTypeEnum.OWN_CHILD_LEVEL.getType() == dsType) { - List deptIdList = dataScopeService.getDescendantList(user.getDeptId()) - .getData().stream().map(SysDeptRelation::getDescendant) - .collect(Collectors.toList()); + List deptIdList = dataScopeService.getDescendantList(user.getDeptId()).getData().stream() + .map(SysDeptRelation::getDescendant).collect(Collectors.toList()); deptList.addAll(deptIdList); } // 只查询本级 @@ -91,4 +88,5 @@ public class PigxDefaultDatascopeHandle implements DataScopeHandle { } return false; } + } diff --git a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/datascope/SelectListByScope.java b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/datascope/SelectListByScope.java index e349e4d2d..807dad371 100644 --- a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/datascope/SelectListByScope.java +++ b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/datascope/SelectListByScope.java @@ -11,12 +11,14 @@ import org.apache.ibatis.mapping.SqlSource; * @date 2020/4/26 */ public class SelectListByScope extends AbstractMethod { + @Override public MappedStatement injectMappedStatement(Class mapperClass, Class modelClass, TableInfo tableInfo) { SqlMethod sqlMethod = SqlMethod.SELECT_LIST; - String sql = String.format(sqlMethod.getSql(), sqlFirst(), sqlSelectColumns(tableInfo, true), tableInfo.getTableName(), - sqlWhereEntityWrapper(true, tableInfo), sqlComment()); + String sql = String.format(sqlMethod.getSql(), sqlFirst(), sqlSelectColumns(tableInfo, true), + tableInfo.getTableName(), sqlWhereEntityWrapper(true, tableInfo), sqlComment()); SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass); return this.addSelectMappedStatementForTable(mapperClass, "selectListByScope", sqlSource, tableInfo); } + } diff --git a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/handler/JsonStringArrayTypeHandler.java b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/handler/JsonStringArrayTypeHandler.java index 3f5dafd60..9b48eb709 100644 --- a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/handler/JsonStringArrayTypeHandler.java +++ b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/handler/JsonStringArrayTypeHandler.java @@ -17,13 +17,12 @@ import java.sql.SQLException; /** * Mybatis数组,符串互转 *

- * MappedJdbcTypes 数据库中的数据类型 - * MappedTypes java中的的数据类型 + * MappedJdbcTypes 数据库中的数据类型 MappedTypes java中的的数据类型 * * @author xuzihui * @date 2019-11-20 */ -@MappedTypes(value = {String[].class}) +@MappedTypes(value = { String[].class }) @MappedJdbcTypes(value = JdbcType.VARCHAR) public class JsonStringArrayTypeHandler extends BaseTypeHandler { diff --git a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/mybatis/MybatisPlusConfiguration.java b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/mybatis/MybatisPlusConfiguration.java index bb94b7c4d..55cacd397 100644 --- a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/mybatis/MybatisPlusConfiguration.java +++ b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/mybatis/MybatisPlusConfiguration.java @@ -48,7 +48,6 @@ public class MybatisPlusConfiguration { /** * 创建租户维护处理器对象 - * * @return 处理后的租户维护处理器 */ @Bean @@ -59,7 +58,6 @@ public class MybatisPlusConfiguration { /** * 分页插件 - * * @param tenantHandler 租户处理器 * @return PaginationInterceptor */ @@ -78,7 +76,6 @@ public class MybatisPlusConfiguration { /** * pigx 默认数据权限处理 - * * @return */ @Bean @@ -89,7 +86,6 @@ public class MybatisPlusConfiguration { /** * 数据权限插件 - * * @return DataScopeInterceptor */ @Bean @@ -104,4 +100,5 @@ public class MybatisPlusConfiguration { public DataScopeSqlInjector dataScopeSqlInjector() { return new DataScopeSqlInjector(); } + } diff --git a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/resolver/ParamResolver.java b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/resolver/ParamResolver.java index 36c2927f4..1696dd95e 100644 --- a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/resolver/ParamResolver.java +++ b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/resolver/ParamResolver.java @@ -17,8 +17,7 @@ public class ParamResolver { /** * 根据key 查询value 配置 - * - * @param key key + * @param key key * @param defaultVal 默认值 * @return value */ @@ -26,11 +25,9 @@ public class ParamResolver { return checkAndGet(key, defaultVal); } - /** * 根据key 查询value 配置 - * - * @param key key + * @param key key * @param defaultVal 默认值 * @return value */ @@ -38,7 +35,6 @@ public class ParamResolver { return checkAndGet(key, defaultVal); } - private T checkAndGet(String key, Object... defaultVal) { // 校验入参是否合法 if (StrUtil.isBlank(key) || defaultVal.length > 1) { @@ -58,4 +54,5 @@ public class ParamResolver { } return null; } + } diff --git a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/resolver/SqlFilterArgumentResolver.java b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/resolver/SqlFilterArgumentResolver.java index 44acbbb7a..6eec6dc11 100644 --- a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/resolver/SqlFilterArgumentResolver.java +++ b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/resolver/SqlFilterArgumentResolver.java @@ -43,12 +43,12 @@ import java.util.stream.Collectors; */ @Slf4j public class SqlFilterArgumentResolver implements HandlerMethodArgumentResolver { - private final static String[] KEYWORDS = {"master", "truncate", "insert", "select" - , "delete", "update", "declare", "alter", "drop", "sleep"}; + + private final static String[] KEYWORDS = { "master", "truncate", "insert", "select", "delete", "update", "declare", + "alter", "drop", "sleep" }; /** * 判断Controller是否包含page 参数 - * * @param parameter 参数 * @return 是否过滤 */ @@ -58,17 +58,17 @@ public class SqlFilterArgumentResolver implements HandlerMethodArgumentResolver } /** - * @param parameter 入参集合 - * @param mavContainer model 和 view - * @param webRequest web相关 + * @param parameter 入参集合 + * @param mavContainer model 和 view + * @param webRequest web相关 * @param binderFactory 入参解析 * @return 检查后新的page对象 *

* page 只支持查询 GET .如需解析POST获取请求报文体处理 */ @Override - public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer - , NativeWebRequest webRequest, WebDataBinderFactory binderFactory) { + public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, + NativeWebRequest webRequest, WebDataBinderFactory binderFactory) { HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class); @@ -87,29 +87,28 @@ public class SqlFilterArgumentResolver implements HandlerMethodArgumentResolver } List orderItemList = new ArrayList<>(); - Optional.ofNullable(ascs).ifPresent(s -> orderItemList.addAll(Arrays.stream(s) - .filter(sqlInjectPredicate()) - .map(OrderItem::asc).collect(Collectors.toList()))); - Optional.ofNullable(descs).ifPresent(s -> orderItemList.addAll(Arrays.stream(s) - .filter(sqlInjectPredicate()) - .map(OrderItem::desc).collect(Collectors.toList()))); + Optional.ofNullable(ascs).ifPresent(s -> orderItemList.addAll( + Arrays.stream(s).filter(sqlInjectPredicate()).map(OrderItem::asc).collect(Collectors.toList()))); + Optional.ofNullable(descs).ifPresent(s -> orderItemList.addAll( + Arrays.stream(s).filter(sqlInjectPredicate()).map(OrderItem::desc).collect(Collectors.toList()))); page.addOrder(orderItemList); return page; } /** - * 判断用户输入里面有没有关键字 + * 判断用户输入里面有没有关键字 * @return Predicate */ private Predicate sqlInjectPredicate() { return sql -> { for (String keyword : KEYWORDS) { - if (StrUtil.containsIgnoreCase(sql, keyword)){ + if (StrUtil.containsIgnoreCase(sql, keyword)) { return false; } } return true; }; } + } diff --git a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/resolver/WebMvcConfig.java b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/resolver/WebMvcConfig.java index 278c92c8e..2561f0f07 100644 --- a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/resolver/WebMvcConfig.java +++ b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/resolver/WebMvcConfig.java @@ -29,8 +29,10 @@ import java.util.List; */ @Configuration public class WebMvcConfig implements WebMvcConfigurer { + @Override public void addArgumentResolvers(List argumentResolvers) { argumentResolvers.add(new SqlFilterArgumentResolver()); } + } diff --git a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/tenant/PigxFeignTenantInterceptor.java b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/tenant/PigxFeignTenantInterceptor.java index e8f3dc5b7..6a15e357b 100644 --- a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/tenant/PigxFeignTenantInterceptor.java +++ b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/tenant/PigxFeignTenantInterceptor.java @@ -28,6 +28,7 @@ import lombok.extern.slf4j.Slf4j; */ @Slf4j public class PigxFeignTenantInterceptor implements RequestInterceptor { + @Override public void apply(RequestTemplate requestTemplate) { if (TenantContextHolder.getTenantId() == null) { @@ -36,4 +37,5 @@ public class PigxFeignTenantInterceptor implements RequestInterceptor { } requestTemplate.header(CommonConstants.TENANT_ID, TenantContextHolder.getTenantId().toString()); } + } diff --git a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/tenant/PigxTenantConfigProperties.java b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/tenant/PigxTenantConfigProperties.java index 16c3a22f9..11a33ee34 100644 --- a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/tenant/PigxTenantConfigProperties.java +++ b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/tenant/PigxTenantConfigProperties.java @@ -28,4 +28,5 @@ public class PigxTenantConfigProperties { * 多租户的数据表集合 */ private List tables = new ArrayList<>(); + } diff --git a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/tenant/PigxTenantConfiguration.java b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/tenant/PigxTenantConfiguration.java index 49c26dac5..959ae79c8 100644 --- a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/tenant/PigxTenantConfiguration.java +++ b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/tenant/PigxTenantConfiguration.java @@ -30,6 +30,7 @@ import org.springframework.http.client.ClientHttpRequestInterceptor; */ @Configuration public class PigxTenantConfiguration { + @Bean public RequestInterceptor pigxFeignTenantInterceptor() { return new PigxFeignTenantInterceptor(); @@ -39,4 +40,5 @@ public class PigxTenantConfiguration { public ClientHttpRequestInterceptor pigxTenantRequestInterceptor() { return new TenantRequestInterceptor(); } + } diff --git a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/tenant/PigxTenantHandler.java b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/tenant/PigxTenantHandler.java index ea4bd908f..0e106b5de 100644 --- a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/tenant/PigxTenantHandler.java +++ b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/tenant/PigxTenantHandler.java @@ -32,6 +32,7 @@ import org.springframework.beans.factory.annotation.Autowired; */ @Slf4j public class PigxTenantHandler implements TenantHandler { + @Autowired private PigxTenantConfigProperties properties; @@ -39,7 +40,6 @@ public class PigxTenantHandler implements TenantHandler { * 获取租户值 *

* TODO 校验租户状态 - * * @return 租户值 */ @Override @@ -55,7 +55,6 @@ public class PigxTenantHandler implements TenantHandler { /** * 获取租户字段名 - * * @return 租户字段名 */ @Override @@ -65,7 +64,6 @@ public class PigxTenantHandler implements TenantHandler { /** * 根据表名判断是否进行过滤 - * * @param tableName 表名 * @return 是否进行过滤 */ @@ -79,4 +77,5 @@ public class PigxTenantHandler implements TenantHandler { return !properties.getTables().contains(tableName); } + } diff --git a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/tenant/TenantBroker.java b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/tenant/TenantBroker.java index 40650bf08..4461abda4 100644 --- a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/tenant/TenantBroker.java +++ b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/tenant/TenantBroker.java @@ -8,8 +8,7 @@ import java.util.function.Supplier; /** * 租户运行时代理
* 这是一个工具类,用于切换租户运行时,保护租户ID上下文
- * 下面这段代码演示问题所在 - *

+ * 下面这段代码演示问题所在 
  *     void methodA(){
  *         // 因为某些特殊原因,需要手动指定租户
  *         TenantContextHolder.setTenantId(1);
@@ -22,10 +21,7 @@ import java.util.function.Supplier;
  *         // 此时租户ID已经变成 1
  *         // do something ...
  *     }
- * 
- * 嵌套设置租户ID会导致租户上下文难以维护,并且很难察觉,容易导致数据错乱。 - * 推荐的写法: - *
+ * 
嵌套设置租户ID会导致租户上下文难以维护,并且很难察觉,容易导致数据错乱。 推荐的写法:
  *     void methodA(){
  *         TenantBroker.RunAs(1,() -> {
  *             // do something ...
@@ -49,16 +45,19 @@ public class TenantBroker {
 
 	@FunctionalInterface
 	public interface RunAs {
+
 		/**
 		 * 执行业务逻辑
 		 * @param tenantId
 		 * @throws Exception
 		 */
 		void run(T tenantId) throws Exception;
+
 	}
 
 	@FunctionalInterface
-	public interface ApplyAs {
+	public interface ApplyAs {
+
 		/**
 		 * 执行业务逻辑,返回一个值
 		 * @param tenantId
@@ -66,6 +65,7 @@ public class TenantBroker {
 		 * @throws Exception
 		 */
 		R apply(T tenantId) throws Exception;
+
 	}
 
 	/**
@@ -73,16 +73,18 @@ public class TenantBroker {
 	 * @param tenant 租户ID
 	 * @param func
 	 */
-	public  void runAs(Integer tenant,RunAs func){
+	public void runAs(Integer tenant, RunAs func) {
 		final Integer pre = TenantContextHolder.getTenantId();
 		try {
-			log.trace("TenantBroker 切换租户{} -> {}",pre,tenant);
+			log.trace("TenantBroker 切换租户{} -> {}", pre, tenant);
 			TenantContextHolder.setTenantId(tenant);
 			func.run(tenant);
-		} catch (Exception e){
-			throw new TenantBrokerExceptionWrapper(e.getMessage(),e);
-		} finally {
-			log.trace("TenantBroker 还原租户{} <- {}",pre,tenant);
+		}
+		catch (Exception e) {
+			throw new TenantBrokerExceptionWrapper(e.getMessage(), e);
+		}
+		finally {
+			log.trace("TenantBroker 还原租户{} <- {}", pre, tenant);
 			TenantContextHolder.setTenantId(pre);
 		}
 	}
@@ -94,16 +96,18 @@ public class TenantBroker {
 	 * @param  返回数据类型
 	 * @return
 	 */
-	public  T applyAs(Integer tenant, ApplyAs func){
+	public  T applyAs(Integer tenant, ApplyAs func) {
 		final Integer pre = TenantContextHolder.getTenantId();
 		try {
-			log.trace("TenantBroker 切换租户{} -> {}",pre,tenant);
+			log.trace("TenantBroker 切换租户{} -> {}", pre, tenant);
 			TenantContextHolder.setTenantId(tenant);
 			return func.apply(tenant);
-		} catch (Exception e){
-			throw new TenantBrokerExceptionWrapper(e.getMessage(),e);
-		} finally {
-			log.trace("TenantBroker 还原租户{} <- {}",pre,tenant);
+		}
+		catch (Exception e) {
+			throw new TenantBrokerExceptionWrapper(e.getMessage(), e);
+		}
+		finally {
+			log.trace("TenantBroker 还原租户{} <- {}", pre, tenant);
 			TenantContextHolder.setTenantId(pre);
 		}
 	}
@@ -113,8 +117,8 @@ public class TenantBroker {
 	 * @param supplier
 	 * @param func
 	 */
-	public  void runAs(Supplier supplier, RunAs func){
-		runAs(supplier.get(),func);
+	public void runAs(Supplier supplier, RunAs func) {
+		runAs(supplier.get(), func);
 	}
 
 	/**
@@ -124,16 +128,20 @@ public class TenantBroker {
 	 * @param  返回数据类型
 	 * @return
 	 */
-	public  T applyAs(Supplier supplier, ApplyAs func){
-		return applyAs(supplier.get(),func);
+	public  T applyAs(Supplier supplier, ApplyAs func) {
+		return applyAs(supplier.get(), func);
 	}
 
 	public static class TenantBrokerExceptionWrapper extends RuntimeException {
+
 		public TenantBrokerExceptionWrapper(String message, Throwable cause) {
 			super(message, cause);
 		}
+
 		public TenantBrokerExceptionWrapper(Throwable cause) {
 			super(cause);
 		}
+
 	}
+
 }
diff --git a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/tenant/TenantContextHolder.java b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/tenant/TenantContextHolder.java
index da42e70f5..fe55ca771 100644
--- a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/tenant/TenantContextHolder.java
+++ b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/tenant/TenantContextHolder.java
@@ -22,15 +22,13 @@ import lombok.experimental.UtilityClass;
 
 /**
  * @author lengleng
- * @date 2018/10/4
- * 租户工具类
+ * @date 2018/10/4 租户工具类
  */
 @UtilityClass
 public class TenantContextHolder {
 
 	private final ThreadLocal THREAD_LOCAL_TENANT = new TransmittableThreadLocal<>();
 
-
 	/**
 	 * TTL 设置租户ID
* 谨慎使用此方法,避免嵌套调用。尽量使用 {@code TenantBroker} @@ -43,7 +41,6 @@ public class TenantContextHolder { /** * 获取TTL中的租户ID - * * @return */ public Integer getTenantId() { @@ -53,4 +50,5 @@ public class TenantContextHolder { public void clear() { THREAD_LOCAL_TENANT.remove(); } + } diff --git a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/tenant/TenantContextHolderFilter.java b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/tenant/TenantContextHolderFilter.java index 1bb60a77c..2313b319c 100644 --- a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/tenant/TenantContextHolderFilter.java +++ b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/tenant/TenantContextHolderFilter.java @@ -52,11 +52,13 @@ public class TenantContextHolderFilter extends GenericFilterBean { if (StrUtil.isNotBlank(tenantId)) { TenantContextHolder.setTenantId(Integer.parseInt(tenantId)); - } else { + } + else { TenantContextHolder.setTenantId(CommonConstants.TENANT_ID_1); } filterChain.doFilter(request, response); TenantContextHolder.clear(); } + } diff --git a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/tenant/TenantRequestInterceptor.java b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/tenant/TenantRequestInterceptor.java index daf093793..7196f9397 100644 --- a/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/tenant/TenantRequestInterceptor.java +++ b/pigx-common/pigx-common-data/src/main/java/com/pig4cloud/pigx/common/data/tenant/TenantRequestInterceptor.java @@ -15,9 +15,12 @@ import java.io.IOException; * 传递 RestTemplate 请求的租户ID */ public class TenantRequestInterceptor implements ClientHttpRequestInterceptor { + @Override - public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { + public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) + throws IOException { request.getHeaders().set(CommonConstants.TENANT_ID, String.valueOf(TenantContextHolder.getTenantId())); return execution.execute(request, body); } + } diff --git a/pigx-common/pigx-common-datasource/src/main/java/com/pig4cloud/pigx/common/datasource/DynamicDataSourceAutoConfiguration.java b/pigx-common/pigx-common-datasource/src/main/java/com/pig4cloud/pigx/common/datasource/DynamicDataSourceAutoConfiguration.java index 0e7dbd146..cde3b1811 100644 --- a/pigx-common/pigx-common-datasource/src/main/java/com/pig4cloud/pigx/common/datasource/DynamicDataSourceAutoConfiguration.java +++ b/pigx-common/pigx-common-datasource/src/main/java/com/pig4cloud/pigx/common/datasource/DynamicDataSourceAutoConfiguration.java @@ -41,7 +41,9 @@ import org.springframework.context.annotation.Configuration; @AutoConfigureAfter(DataSourceAutoConfiguration.class) @EnableConfigurationProperties(DruidDataSourceProperties.class) public class DynamicDataSourceAutoConfiguration { + private final StringEncryptor stringEncryptor; + private final DruidDataSourceProperties properties; @Bean @@ -53,4 +55,5 @@ public class DynamicDataSourceAutoConfiguration { public DsProcessor dsProcessor() { return new LastParamDsProcessor(); } + } diff --git a/pigx-common/pigx-common-datasource/src/main/java/com/pig4cloud/pigx/common/datasource/annotation/EnableDynamicDataSource.java b/pigx-common/pigx-common-datasource/src/main/java/com/pig4cloud/pigx/common/datasource/annotation/EnableDynamicDataSource.java index c04d6a105..887ceaf77 100644 --- a/pigx-common/pigx-common-datasource/src/main/java/com/pig4cloud/pigx/common/datasource/annotation/EnableDynamicDataSource.java +++ b/pigx-common/pigx-common-datasource/src/main/java/com/pig4cloud/pigx/common/datasource/annotation/EnableDynamicDataSource.java @@ -13,11 +13,12 @@ import java.lang.annotation.*; *

* 开启动态数据源 */ -@Target({ElementType.TYPE}) +@Target({ ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited -@EnableAutoConfiguration(exclude = {DruidDataSourceAutoConfigure.class}) +@EnableAutoConfiguration(exclude = { DruidDataSourceAutoConfigure.class }) @Import(DynamicDataSourceAutoConfiguration.class) public @interface EnableDynamicDataSource { + } diff --git a/pigx-common/pigx-common-datasource/src/main/java/com/pig4cloud/pigx/common/datasource/config/DruidDataSourceProperties.java b/pigx-common/pigx-common-datasource/src/main/java/com/pig4cloud/pigx/common/datasource/config/DruidDataSourceProperties.java index 5c9164b7f..d09802f4e 100644 --- a/pigx-common/pigx-common-datasource/src/main/java/com/pig4cloud/pigx/common/datasource/config/DruidDataSourceProperties.java +++ b/pigx-common/pigx-common-datasource/src/main/java/com/pig4cloud/pigx/common/datasource/config/DruidDataSourceProperties.java @@ -39,4 +39,5 @@ public class DruidDataSourceProperties { * 查询数据源的SQL */ private String queryDsSql = "select * from gen_datasource_conf where del_flag = 0"; + } diff --git a/pigx-common/pigx-common-datasource/src/main/java/com/pig4cloud/pigx/common/datasource/config/JdbcDynamicDataSourceProvider.java b/pigx-common/pigx-common-datasource/src/main/java/com/pig4cloud/pigx/common/datasource/config/JdbcDynamicDataSourceProvider.java index 3881d21ef..38a235d56 100644 --- a/pigx-common/pigx-common-datasource/src/main/java/com/pig4cloud/pigx/common/datasource/config/JdbcDynamicDataSourceProvider.java +++ b/pigx-common/pigx-common-datasource/src/main/java/com/pig4cloud/pigx/common/datasource/config/JdbcDynamicDataSourceProvider.java @@ -35,7 +35,9 @@ import java.util.Map; * 从数据源中获取 配置信息 */ public class JdbcDynamicDataSourceProvider extends AbstractJdbcDataSourceProvider { + private final DruidDataSourceProperties properties; + private final StringEncryptor stringEncryptor; public JdbcDynamicDataSourceProvider(StringEncryptor stringEncryptor, DruidDataSourceProperties properties) { @@ -46,7 +48,6 @@ public class JdbcDynamicDataSourceProvider extends AbstractJdbcDataSourceProvide /** * 执行语句获得数据源参数 - * * @param statement 语句 * @return 数据源参数 * @throws SQLException sql异常 @@ -76,4 +77,5 @@ public class JdbcDynamicDataSourceProvider extends AbstractJdbcDataSourceProvide map.put(DataSourceConstants.DS_MASTER, property); return map; } + } diff --git a/pigx-common/pigx-common-datasource/src/main/java/com/pig4cloud/pigx/common/datasource/config/LastParamDsProcessor.java b/pigx-common/pigx-common-datasource/src/main/java/com/pig4cloud/pigx/common/datasource/config/LastParamDsProcessor.java index 10953abc9..a1883d484 100644 --- a/pigx-common/pigx-common-datasource/src/main/java/com/pig4cloud/pigx/common/datasource/config/LastParamDsProcessor.java +++ b/pigx-common/pigx-common-datasource/src/main/java/com/pig4cloud/pigx/common/datasource/config/LastParamDsProcessor.java @@ -24,16 +24,14 @@ import org.aopalliance.intercept.MethodInvocation; * @author lengleng * @date 2020/2/6 *

- * 参数数据源解析 @DS("#last) + * 参数数据源解析 @DS("#last) */ public class LastParamDsProcessor extends DsProcessor { private static final String LAST_PREFIX = "#last"; - /** * 抽象匹配条件 匹配才会走当前执行器否则走下一级执行器 - * * @param key DS注解里的内容 * @return 是否匹配 */ @@ -44,9 +42,8 @@ public class LastParamDsProcessor extends DsProcessor { /** * 抽象最终决定数据源 - * * @param invocation 方法执行信息 - * @param key DS注解里的内容 + * @param key DS注解里的内容 * @return 数据源名称 */ @Override @@ -54,4 +51,5 @@ public class LastParamDsProcessor extends DsProcessor { Object[] arguments = invocation.getArguments(); return String.valueOf(arguments[arguments.length - 1]); } + } diff --git a/pigx-common/pigx-common-feign/src/main/java/com/pig4cloud/pigx/common/feign/annotation/EnablePigxFeignClients.java b/pigx-common/pigx-common-feign/src/main/java/com/pig4cloud/pigx/common/feign/annotation/EnablePigxFeignClients.java index 9075c216b..86fc3a8bb 100644 --- a/pigx-common/pigx-common-feign/src/main/java/com/pig4cloud/pigx/common/feign/annotation/EnablePigxFeignClients.java +++ b/pigx-common/pigx-common-feign/src/main/java/com/pig4cloud/pigx/common/feign/annotation/EnablePigxFeignClients.java @@ -33,11 +33,11 @@ import java.lang.annotation.*; @EnableFeignClients @Import(PigxFeignClientsRegistrar.class) public @interface EnablePigxFeignClients { + /** * Alias for the {@link #basePackages()} attribute. Allows for more concise annotation * declarations e.g.: {@code @ComponentScan("org.my.pkg")} instead of * {@code @ComponentScan(basePackages="org.my.pkg")}. - * * @return the array of 'basePackages'. */ String[] value() default {}; @@ -49,10 +49,9 @@ public @interface EnablePigxFeignClients { *

* Use {@link #basePackageClasses()} for a type-safe alternative to String-based * package names. - * * @return the array of 'basePackages'. */ - String[] basePackages() default {"com.pig4cloud.pigx"}; + String[] basePackages() default { "com.pig4cloud.pigx" }; /** * Type-safe alternative to {@link #basePackages()} for specifying the packages to @@ -60,7 +59,6 @@ public @interface EnablePigxFeignClients { *

* Consider creating a special no-op marker class or interface in each package that * serves no purpose other than being referenced by this attribute. - * * @return the array of 'basePackageClasses'. */ Class[] basePackageClasses() default {}; @@ -75,9 +73,10 @@ public @interface EnablePigxFeignClients { Class[] defaultConfiguration() default {}; /** - * List of classes annotated with @FeignClient. If not empty, disables classpath scanning. - * + * List of classes annotated with @FeignClient. If not empty, disables classpath + * scanning. * @return */ Class[] clients() default {}; + } diff --git a/pigx-common/pigx-common-feign/src/main/java/com/pig4cloud/pigx/common/feign/endpoint/FeignClientEndpoint.java b/pigx-common/pigx-common-feign/src/main/java/com/pig4cloud/pigx/common/feign/endpoint/FeignClientEndpoint.java index 60d6f0986..204d8e1bc 100644 --- a/pigx-common/pigx-common-feign/src/main/java/com/pig4cloud/pigx/common/feign/endpoint/FeignClientEndpoint.java +++ b/pigx-common/pigx-common-feign/src/main/java/com/pig4cloud/pigx/common/feign/endpoint/FeignClientEndpoint.java @@ -26,7 +26,9 @@ import java.util.Set; */ @Endpoint(id = "feign") public class FeignClientEndpoint implements SmartInitializingSingleton { + private final ApplicationContext context; + private final List clientList; public FeignClientEndpoint(ApplicationContext context) { @@ -80,7 +82,8 @@ public class FeignClientEndpoint implements SmartInitializingSingleton { if (method.isDefault()) { continue; } - RequestMapping requestMapping = AnnotatedElementUtils.getMergedAnnotation(method, RequestMapping.class); + RequestMapping requestMapping = AnnotatedElementUtils.getMergedAnnotation(method, + RequestMapping.class); if (requestMapping == null) { continue; } @@ -96,19 +99,29 @@ public class FeignClientEndpoint implements SmartInitializingSingleton { @Getter @Setter public static class FeignClientInfo { + private String beanName; + private String serviceId; + private String contextId; + private String url; + private String path; + private List clientList; + } @Getter @AllArgsConstructor public static class ClientInfo { + private final RequestMethod[] methods; + private final String[] mappings; + } } \ No newline at end of file diff --git a/pigx-common/pigx-common-feign/src/main/java/org/springframework/cloud/openfeign/PigxFeignClientsRegistrar.java b/pigx-common/pigx-common-feign/src/main/java/org/springframework/cloud/openfeign/PigxFeignClientsRegistrar.java index 5585de580..b6187cd55 100644 --- a/pigx-common/pigx-common-feign/src/main/java/org/springframework/cloud/openfeign/PigxFeignClientsRegistrar.java +++ b/pigx-common/pigx-common-feign/src/main/java/org/springframework/cloud/openfeign/PigxFeignClientsRegistrar.java @@ -44,9 +44,12 @@ import java.util.Map; *

* feign 自动配置功能 from mica */ -public class PigxFeignClientsRegistrar implements ImportBeanDefinitionRegistrar, BeanClassLoaderAware, EnvironmentAware { +public class PigxFeignClientsRegistrar + implements ImportBeanDefinitionRegistrar, BeanClassLoaderAware, EnvironmentAware { + @Getter private ClassLoader beanClassLoader; + @Getter private Environment environment; @@ -61,7 +64,8 @@ public class PigxFeignClientsRegistrar implements ImportBeanDefinitionRegistrar, } private void registerFeignClients(BeanDefinitionRegistry registry) { - List feignClients = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader()); + List feignClients = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(), + getBeanClassLoader()); // 如果 spring.factories 里为空 if (feignClients.isEmpty()) { return; @@ -69,7 +73,8 @@ public class PigxFeignClientsRegistrar implements ImportBeanDefinitionRegistrar, for (String className : feignClients) { try { Class clazz = beanClassLoader.loadClass(className); - AnnotationAttributes attributes = AnnotatedElementUtils.getMergedAnnotationAttributes(clazz, FeignClient.class); + AnnotationAttributes attributes = AnnotatedElementUtils.getMergedAnnotationAttributes(clazz, + FeignClient.class); if (attributes == null) { continue; } @@ -80,7 +85,8 @@ public class PigxFeignClientsRegistrar implements ImportBeanDefinitionRegistrar, registerClientConfiguration(registry, getClientName(attributes), attributes.get("configuration")); validate(attributes); - BeanDefinitionBuilder definition = BeanDefinitionBuilder.genericBeanDefinition(FeignClientFactoryBean.class); + BeanDefinitionBuilder definition = BeanDefinitionBuilder + .genericBeanDefinition(FeignClientFactoryBean.class); definition.addPropertyValue("url", getUrl(attributes)); definition.addPropertyValue("path", getPath(attributes)); String name = getName(attributes); @@ -92,7 +98,8 @@ public class PigxFeignClientsRegistrar implements ImportBeanDefinitionRegistrar, String contextId = getContextId(attributes); aliasBuilder.append(contextId); definition.addPropertyValue("contextId", contextId); - } else { + } + else { aliasBuilder.append(name); } @@ -117,10 +124,12 @@ public class PigxFeignClientsRegistrar implements ImportBeanDefinitionRegistrar, alias = qualifier; } - BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition, className, new String[]{alias}); + BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition, className, + new String[] { alias }); BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry); - } catch (ClassNotFoundException e) { + } + catch (ClassNotFoundException e) { e.printStackTrace(); } } @@ -129,7 +138,6 @@ public class PigxFeignClientsRegistrar implements ImportBeanDefinitionRegistrar, /** * Return the class used by {@link SpringFactoriesLoader} to load configuration * candidates. - * * @return the factory class */ private Class getSpringFactoriesLoaderFactoryClass() { @@ -213,14 +221,16 @@ public class PigxFeignClientsRegistrar implements ImportBeanDefinitionRegistrar, return value; } - throw new IllegalStateException("Either 'name' or 'value' must be provided in @" + FeignClient.class.getSimpleName()); + throw new IllegalStateException( + "Either 'name' or 'value' must be provided in @" + FeignClient.class.getSimpleName()); } private void registerClientConfiguration(BeanDefinitionRegistry registry, Object name, Object configuration) { BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(FeignClientSpecification.class); builder.addConstructorArgValue(name); builder.addConstructorArgValue(configuration); - registry.registerBeanDefinition(name + "." + FeignClientSpecification.class.getSimpleName(), builder.getBeanDefinition()); + registry.registerBeanDefinition(name + "." + FeignClientSpecification.class.getSimpleName(), + builder.getBeanDefinition()); } @Override diff --git a/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/annotation/EnablePigxDynamicRoute.java b/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/annotation/EnablePigxDynamicRoute.java index c608b6652..388c2b12a 100644 --- a/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/annotation/EnablePigxDynamicRoute.java +++ b/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/annotation/EnablePigxDynamicRoute.java @@ -28,10 +28,11 @@ import java.lang.annotation.*; *

* 开启pigx 动态路由 */ -@Target({ElementType.TYPE}) +@Target({ ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @Import(DynamicRouteAutoConfiguration.class) public @interface EnablePigxDynamicRoute { + } diff --git a/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/configuration/DynamicRouteAutoConfiguration.java b/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/configuration/DynamicRouteAutoConfiguration.java index cb875d46c..fe7ee2c81 100644 --- a/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/configuration/DynamicRouteAutoConfiguration.java +++ b/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/configuration/DynamicRouteAutoConfiguration.java @@ -51,10 +51,9 @@ import java.time.Duration; @ComponentScan("com.pig4cloud.pigx.common.gateway") @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE) public class DynamicRouteAutoConfiguration { + /** - * 配置文件设置为空 - * redis 加载为准 - * + * 配置文件设置为空 redis 加载为准 * @return */ @Bean @@ -64,14 +63,12 @@ public class DynamicRouteAutoConfiguration { /** * redis 监听配置 - * * @param redisConnectionFactory redis 配置 * @return */ @Bean public RedisMessageListenerContainer redisContainer(RedisConnectionFactory redisConnectionFactory) { - RedisMessageListenerContainer container - = new RedisMessageListenerContainer(); + RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(redisConnectionFactory); container.addMessageListener((message, bytes) -> { log.warn("接收到重新JVM 重新加载路由事件"); @@ -80,17 +77,15 @@ public class DynamicRouteAutoConfiguration { return container; } - @Bean - @ConditionalOnProperty(value = "spring.redis.cluster.enable",havingValue = "true") + @ConditionalOnProperty(value = "spring.redis.cluster.enable", havingValue = "true") public LettuceConnectionFactory redisConnectionFactory(RedisProperties redisProperties) { - RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration(redisProperties.getCluster().getNodes()); + RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration( + redisProperties.getCluster().getNodes()); // https://github.com/lettuce-io/lettuce-core/wiki/Redis-Cluster#user-content-refreshing-the-cluster-topology-view ClusterTopologyRefreshOptions clusterTopologyRefreshOptions = ClusterTopologyRefreshOptions.builder() - .enablePeriodicRefresh() - .enableAllAdaptiveRefreshTriggers() - .refreshPeriod(Duration.ofSeconds(5)) + .enablePeriodicRefresh().enableAllAdaptiveRefreshTriggers().refreshPeriod(Duration.ofSeconds(5)) .build(); ClusterClientOptions clusterClientOptions = ClusterClientOptions.builder() @@ -98,9 +93,9 @@ public class DynamicRouteAutoConfiguration { // https://github.com/lettuce-io/lettuce-core/wiki/ReadFrom-Settings LettuceClientConfiguration lettuceClientConfiguration = LettuceClientConfiguration.builder() - .readFrom(ReadFrom.REPLICA_PREFERRED) - .clientOptions(clusterClientOptions).build(); + .readFrom(ReadFrom.REPLICA_PREFERRED).clientOptions(clusterClientOptions).build(); return new LettuceConnectionFactory(redisClusterConfiguration, lettuceClientConfiguration); } + } diff --git a/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/configuration/GlobalExceptionConfiguration.java b/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/configuration/GlobalExceptionConfiguration.java index cf154bfa0..37b6c91c3 100644 --- a/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/configuration/GlobalExceptionConfiguration.java +++ b/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/configuration/GlobalExceptionConfiguration.java @@ -26,6 +26,7 @@ import reactor.core.publisher.Mono; @Configuration @RequiredArgsConstructor public class GlobalExceptionConfiguration implements ErrorWebExceptionHandler { + private final ObjectMapper objectMapper; @Override @@ -42,16 +43,16 @@ public class GlobalExceptionConfiguration implements ErrorWebExceptionHandler { response.setStatusCode(((ResponseStatusException) ex).getStatus()); } - return response - .writeWith(Mono.fromSupplier(() -> { - DataBufferFactory bufferFactory = response.bufferFactory(); - try { - return bufferFactory.wrap(objectMapper.writeValueAsBytes(R.failed(ex.getMessage()))); - } catch (JsonProcessingException e) { - log.warn("Error writing response", ex); - return bufferFactory.wrap(new byte[0]); - } - })); + return response.writeWith(Mono.fromSupplier(() -> { + DataBufferFactory bufferFactory = response.bufferFactory(); + try { + return bufferFactory.wrap(objectMapper.writeValueAsBytes(R.failed(ex.getMessage()))); + } + catch (JsonProcessingException e) { + log.warn("Error writing response", ex); + return bufferFactory.wrap(new byte[0]); + } + })); } } diff --git a/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/configuration/GrayLoadBalancerClientConfiguration.java b/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/configuration/GrayLoadBalancerClientConfiguration.java index e7fd0051e..a33e65f6f 100755 --- a/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/configuration/GrayLoadBalancerClientConfiguration.java +++ b/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/configuration/GrayLoadBalancerClientConfiguration.java @@ -46,7 +46,7 @@ public class GrayLoadBalancerClientConfiguration { @Bean public ReactiveLoadBalancerClientFilter gatewayLoadBalancerClientFilter(GrayLoadBalancer grayLoadBalancer, - LoadBalancerProperties properties) { + LoadBalancerProperties properties) { return new GrayReactiveLoadBalancerClientFilter(properties, grayLoadBalancer); } @@ -54,4 +54,5 @@ public class GrayLoadBalancerClientConfiguration { public GrayLoadBalancer grayLoadBalancer(DiscoveryClient discoveryClient) { return new VersionGrayLoadBalancer(discoveryClient); } + } diff --git a/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/filter/GrayReactiveLoadBalancerClientFilter.java b/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/filter/GrayReactiveLoadBalancerClientFilter.java index 248f2e5ea..1110e4575 100644 --- a/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/filter/GrayReactiveLoadBalancerClientFilter.java +++ b/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/filter/GrayReactiveLoadBalancerClientFilter.java @@ -40,7 +40,9 @@ import java.net.URI; */ @Slf4j public class GrayReactiveLoadBalancerClientFilter extends ReactiveLoadBalancerClientFilter { + private static final int LOAD_BALANCER_CLIENT_FILTER_ORDER = 10150; + private LoadBalancerProperties properties; private GrayLoadBalancer grayLoadBalancer; @@ -60,23 +62,20 @@ public class GrayReactiveLoadBalancerClientFilter extends ReactiveLoadBalancerCl public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { URI url = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR); String schemePrefix = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR); - if (url == null - || (!"lb".equals(url.getScheme()) && !"lb".equals(schemePrefix))) { + if (url == null || (!"lb".equals(url.getScheme()) && !"lb".equals(schemePrefix))) { return chain.filter(exchange); } // preserve the original url ServerWebExchangeUtils.addOriginalRequestUrl(exchange, url); if (log.isTraceEnabled()) { - log.trace(ReactiveLoadBalancerClientFilter.class.getSimpleName() - + " url before: " + url); + log.trace(ReactiveLoadBalancerClientFilter.class.getSimpleName() + " url before: " + url); } return choose(exchange).doOnNext(response -> { if (!response.hasServer()) { - throw NotFoundException.create(properties.isUse404(), - "Unable to find instance for " + url.getHost()); + throw NotFoundException.create(properties.isUse404(), "Unable to find instance for " + url.getHost()); } URI uri = exchange.getRequest().getURI(); @@ -88,8 +87,8 @@ public class GrayReactiveLoadBalancerClientFilter extends ReactiveLoadBalancerCl overrideScheme = url.getScheme(); } - DelegatingServiceInstance serviceInstance = new DelegatingServiceInstance( - response.getServer(), overrideScheme); + DelegatingServiceInstance serviceInstance = new DelegatingServiceInstance(response.getServer(), + overrideScheme); URI requestUrl = LoadBalancerUriTools.reconstructURI(serviceInstance, uri); @@ -102,7 +101,8 @@ public class GrayReactiveLoadBalancerClientFilter extends ReactiveLoadBalancerCl private Mono> choose(ServerWebExchange exchange) { URI uri = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR); - ServiceInstance serviceInstance = grayLoadBalancer.choose(uri.getHost(),exchange.getRequest()); + ServiceInstance serviceInstance = grayLoadBalancer.choose(uri.getHost(), exchange.getRequest()); return Mono.just(new DefaultResponse(serviceInstance)); } + } diff --git a/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/rule/GrayLoadBalancer.java b/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/rule/GrayLoadBalancer.java index ad2efe0eb..85a76428e 100644 --- a/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/rule/GrayLoadBalancer.java +++ b/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/rule/GrayLoadBalancer.java @@ -30,10 +30,10 @@ public interface GrayLoadBalancer { /** * 根据serviceId 筛选可用服务 - * * @param serviceId 服务ID - * @param request 当前请求 + * @param request 当前请求 * @return */ ServiceInstance choose(String serviceId, ServerHttpRequest request); + } diff --git a/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/rule/VersionGrayLoadBalancer.java b/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/rule/VersionGrayLoadBalancer.java index 07c69a1e9..6beb2fb9f 100644 --- a/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/rule/VersionGrayLoadBalancer.java +++ b/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/rule/VersionGrayLoadBalancer.java @@ -41,21 +41,20 @@ import java.util.Map; @Slf4j @AllArgsConstructor public class VersionGrayLoadBalancer implements GrayLoadBalancer { - private DiscoveryClient discoveryClient; + private DiscoveryClient discoveryClient; /** * 根据serviceId 筛选可用服务 - * * @param serviceId 服务ID - * @param request 当前请求 + * @param request 当前请求 * @return */ @Override public ServiceInstance choose(String serviceId, ServerHttpRequest request) { List instances = discoveryClient.getInstances(serviceId); - //注册中心无实例 抛出异常 + // 注册中心无实例 抛出异常 if (CollUtil.isEmpty(instances)) { log.warn("No instance available for {}", serviceId); throw new NotFoundException("No instance available for " + serviceId); @@ -78,4 +77,5 @@ public class VersionGrayLoadBalancer implements GrayLoadBalancer { } return instances.get(RandomUtil.randomInt(instances.size())); } + } diff --git a/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/support/DynamicRouteInitEvent.java b/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/support/DynamicRouteInitEvent.java index 0dacfa92c..a2a7cd244 100644 --- a/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/support/DynamicRouteInitEvent.java +++ b/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/support/DynamicRouteInitEvent.java @@ -26,7 +26,9 @@ import org.springframework.context.ApplicationEvent; * 路由初始化事件 */ public class DynamicRouteInitEvent extends ApplicationEvent { + public DynamicRouteInitEvent(Object source) { super(source); } + } diff --git a/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/support/PigxRibbonRuleProperties.java b/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/support/PigxRibbonRuleProperties.java index e0d3a5aa9..eb6360135 100755 --- a/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/support/PigxRibbonRuleProperties.java +++ b/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/support/PigxRibbonRuleProperties.java @@ -35,16 +35,20 @@ import java.util.List; @RefreshScope @ConfigurationProperties("ribbon.rule") public class PigxRibbonRuleProperties { + /** * 是否开启,默认:true */ private boolean enabled = Boolean.TRUE; + /** * 是否开启灰度路由,默认:false */ private boolean grayEnabled; + /** * 优先的ip列表,支持通配符,例如:10.20.0.8*、10.20.0.* */ private List priorIpPattern = new ArrayList<>(); + } diff --git a/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/support/RedisRouteDefinitionWriter.java b/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/support/RedisRouteDefinitionWriter.java index 0b3f1edfb..52b9f8eb7 100644 --- a/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/support/RedisRouteDefinitionWriter.java +++ b/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/support/RedisRouteDefinitionWriter.java @@ -44,6 +44,7 @@ import java.util.List; @Component @AllArgsConstructor public class RedisRouteDefinitionWriter implements RouteDefinitionRepository { + private final RedisTemplate redisTemplate; @Override @@ -70,14 +71,10 @@ public class RedisRouteDefinitionWriter implements RouteDefinitionRepository { return Mono.empty(); } - /** * 动态路由入口 *

- * 1. 先从内存中获取 - * 2. 为空加载Redis中数据 - * 3. 更新内存 - * + * 1. 先从内存中获取 2. 为空加载Redis中数据 3. 更新内存 * @return */ @Override @@ -96,4 +93,5 @@ public class RedisRouteDefinitionWriter implements RouteDefinitionRepository { RouteCacheHolder.setRouteList(values); return Flux.fromIterable(values); } + } diff --git a/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/support/RouteCacheHolder.java b/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/support/RouteCacheHolder.java index 8c344d97b..900200fc2 100644 --- a/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/support/RouteCacheHolder.java +++ b/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/support/RouteCacheHolder.java @@ -33,11 +33,11 @@ import java.util.List; */ @UtilityClass public class RouteCacheHolder { + private Cache cache = CacheUtil.newLFUCache(50); /** * 获取缓存的全部对象 - * * @return routeList */ public List getRouteList() { @@ -48,7 +48,6 @@ public class RouteCacheHolder { /** * 更新缓存 - * * @param routeList 缓存列表 */ public void setRouteList(List routeList) { diff --git a/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/vo/RouteDefinitionVo.java b/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/vo/RouteDefinitionVo.java index 082d638e7..563001bb5 100644 --- a/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/vo/RouteDefinitionVo.java +++ b/pigx-common/pigx-common-gateway/src/main/java/com/pig4cloud/pigx/common/gateway/vo/RouteDefinitionVo.java @@ -15,8 +15,7 @@ * Author: lengleng (wangiegie@gmail.com) */ -package com.pig4cloud.pigx.common.gateway.vo - ; +package com.pig4cloud.pigx.common.gateway.vo; import lombok.Data; import lombok.EqualsAndHashCode; @@ -28,14 +27,15 @@ import java.io.Serializable; * @author lengleng * @date 2018/10/31 *

- * 扩展此类支持序列化a - * See RouteDefinition.class + * 扩展此类支持序列化a See RouteDefinition.class */ @Data @EqualsAndHashCode(callSuper = false) public class RouteDefinitionVo extends RouteDefinition implements Serializable { + /** * 路由名称 */ private String routeName; + } diff --git a/pigx-common/pigx-common-gray/src/main/java/com/pig4cloud/pigx/common/gray/GrayRibbonLoadBalancerConfiguration.java b/pigx-common/pigx-common-gray/src/main/java/com/pig4cloud/pigx/common/gray/GrayRibbonLoadBalancerConfiguration.java index 5d686f858..5c004b24b 100644 --- a/pigx-common/pigx-common-gray/src/main/java/com/pig4cloud/pigx/common/gray/GrayRibbonLoadBalancerConfiguration.java +++ b/pigx-common/pigx-common-gray/src/main/java/com/pig4cloud/pigx/common/gray/GrayRibbonLoadBalancerConfiguration.java @@ -46,4 +46,5 @@ public class GrayRibbonLoadBalancerConfiguration { public RequestInterceptor grayFeignRequestInterceptor() { return new GrayFeignRequestInterceptor(); } + } diff --git a/pigx-common/pigx-common-gray/src/main/java/com/pig4cloud/pigx/common/gray/feign/GrayFeignRequestInterceptor.java b/pigx-common/pigx-common-gray/src/main/java/com/pig4cloud/pigx/common/gray/feign/GrayFeignRequestInterceptor.java index 1d261750f..77747f2e2 100644 --- a/pigx-common/pigx-common-gray/src/main/java/com/pig4cloud/pigx/common/gray/feign/GrayFeignRequestInterceptor.java +++ b/pigx-common/pigx-common-gray/src/main/java/com/pig4cloud/pigx/common/gray/feign/GrayFeignRequestInterceptor.java @@ -32,19 +32,21 @@ import lombok.extern.slf4j.Slf4j; */ @Slf4j public class GrayFeignRequestInterceptor implements RequestInterceptor { + /** - * Called for every request. Add data using methods on the supplied {@link RequestTemplate}. - * + * Called for every request. Add data using methods on the supplied + * {@link RequestTemplate}. * @param template */ @Override public void apply(RequestTemplate template) { - String reqVersion = WebUtils.getRequest() != null - ? WebUtils.getRequest().getHeader(CommonConstants.VERSION) : null; + String reqVersion = WebUtils.getRequest() != null ? WebUtils.getRequest().getHeader(CommonConstants.VERSION) + : null; if (StrUtil.isNotBlank(reqVersion)) { log.debug("feign gray add header version :{}", reqVersion); template.header(CommonConstants.VERSION, reqVersion); } } + } diff --git a/pigx-common/pigx-common-gray/src/main/java/com/pig4cloud/pigx/common/gray/rule/GrayRibbonLoadBalancerRule.java b/pigx-common/pigx-common-gray/src/main/java/com/pig4cloud/pigx/common/gray/rule/GrayRibbonLoadBalancerRule.java index a4c553515..01d650d38 100644 --- a/pigx-common/pigx-common-gray/src/main/java/com/pig4cloud/pigx/common/gray/rule/GrayRibbonLoadBalancerRule.java +++ b/pigx-common/pigx-common-gray/src/main/java/com/pig4cloud/pigx/common/gray/rule/GrayRibbonLoadBalancerRule.java @@ -39,6 +39,7 @@ import java.util.Map; */ @Slf4j public class GrayRibbonLoadBalancerRule extends AbstractLoadBalancerRule { + @Override public void initWithNiwsConfig(IClientConfig iClientConfig) { } @@ -48,19 +49,18 @@ public class GrayRibbonLoadBalancerRule extends AbstractLoadBalancerRule { return choose(getLoadBalancer(), key); } - public Server choose(ILoadBalancer lb, Object key) { List reachableServers = lb.getReachableServers(); - //注册中心无可用实例 抛出异常 + // 注册中心无可用实例 抛出异常 if (CollUtil.isEmpty(reachableServers)) { log.warn("No instance available for {}", key); return null; } // 获取请求version,无则随机返回可用实例 - String reqVersion = WebUtils.getRequest() != null - ? WebUtils.getRequest().getHeader(CommonConstants.VERSION) : null; + String reqVersion = WebUtils.getRequest() != null ? WebUtils.getRequest().getHeader(CommonConstants.VERSION) + : null; if (StrUtil.isBlank(reqVersion)) { return reachableServers.get(RandomUtil.randomInt(reachableServers.size())); } diff --git a/pigx-common/pigx-common-job/src/main/java/com/pig4cloud/pigx/common/job/XxlJobAutoConfiguration.java b/pigx-common/pigx-common-job/src/main/java/com/pig4cloud/pigx/common/job/XxlJobAutoConfiguration.java index 8f6361b95..342e07c78 100644 --- a/pigx-common/pigx-common-job/src/main/java/com/pig4cloud/pigx/common/job/XxlJobAutoConfiguration.java +++ b/pigx-common/pigx-common-job/src/main/java/com/pig4cloud/pigx/common/job/XxlJobAutoConfiguration.java @@ -48,4 +48,5 @@ public class XxlJobAutoConfiguration { xxlJobSpringExecutor.setLogRetentionDays(xxlJobProperties.getExecutor().getLogRetentionDays()); return xxlJobSpringExecutor; } + } diff --git a/pigx-common/pigx-common-job/src/main/java/com/pig4cloud/pigx/common/job/annotation/EnablePigxXxlJob.java b/pigx-common/pigx-common-job/src/main/java/com/pig4cloud/pigx/common/job/annotation/EnablePigxXxlJob.java index aa40052aa..f6d2278a3 100644 --- a/pigx-common/pigx-common-job/src/main/java/com/pig4cloud/pigx/common/job/annotation/EnablePigxXxlJob.java +++ b/pigx-common/pigx-common-job/src/main/java/com/pig4cloud/pigx/common/job/annotation/EnablePigxXxlJob.java @@ -28,10 +28,11 @@ import java.lang.annotation.*; *

* 开启支持XXL */ -@Target({ElementType.TYPE}) +@Target({ ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited -@Import({XxlJobAutoConfiguration.class}) +@Import({ XxlJobAutoConfiguration.class }) public @interface EnablePigxXxlJob { + } diff --git a/pigx-common/pigx-common-job/src/main/java/com/pig4cloud/pigx/common/job/properties/XxlAdminProperties.java b/pigx-common/pigx-common-job/src/main/java/com/pig4cloud/pigx/common/job/properties/XxlAdminProperties.java index eda15b774..f795f4c25 100644 --- a/pigx-common/pigx-common-job/src/main/java/com/pig4cloud/pigx/common/job/properties/XxlAdminProperties.java +++ b/pigx-common/pigx-common-job/src/main/java/com/pig4cloud/pigx/common/job/properties/XxlAdminProperties.java @@ -27,9 +27,10 @@ import lombok.Data; */ @Data public class XxlAdminProperties { + /** - * 调度中心部署跟地址 [选填]:如调度中心集群部署存在多个地址则用逗号分隔。 - * 执行器将会使用该地址进行"执行器心跳注册"和"任务结果回调";为空则关闭自动注册; + * 调度中心部署跟地址 [选填]:如调度中心集群部署存在多个地址则用逗号分隔。 执行器将会使用该地址进行"执行器心跳注册"和"任务结果回调";为空则关闭自动注册; */ private String addresses = "http://127.0.0.1:8080/xxl-job-admin"; + } diff --git a/pigx-common/pigx-common-job/src/main/java/com/pig4cloud/pigx/common/job/properties/XxlExecutorProperties.java b/pigx-common/pigx-common-job/src/main/java/com/pig4cloud/pigx/common/job/properties/XxlExecutorProperties.java index 405998b14..aa7172c10 100644 --- a/pigx-common/pigx-common-job/src/main/java/com/pig4cloud/pigx/common/job/properties/XxlExecutorProperties.java +++ b/pigx-common/pigx-common-job/src/main/java/com/pig4cloud/pigx/common/job/properties/XxlExecutorProperties.java @@ -25,21 +25,20 @@ import lombok.Data; */ @Data public class XxlExecutorProperties { + /** * 执行器AppName [选填]:执行器心跳注册分组依据;为空则关闭自动注册 */ private String appname = "xxl-job-executor"; /** - * 服务注册地址,优先使用该配置作为注册地址 - * 为空时使用内嵌服务 ”IP:PORT“ 作为注册地址 - * 从而更灵活的支持容器类型执行器动态IP和动态映射端口问题 + * 服务注册地址,优先使用该配置作为注册地址 为空时使用内嵌服务 ”IP:PORT“ 作为注册地址 从而更灵活的支持容器类型执行器动态IP和动态映射端口问题 */ private String address; /** - * 执行器IP [选填]:默认为空表示自动获取IP,多网卡时可手动设置指定IP - * ,该IP不会绑定Host仅作为通讯实用;地址信息用于 "执行器注册" 和 "调度中心请求并触发任务" + * 执行器IP [选填]:默认为空表示自动获取IP,多网卡时可手动设置指定IP ,该IP不会绑定Host仅作为通讯实用;地址信息用于 "执行器注册" 和 + * "调度中心请求并触发任务" */ private String ip; @@ -62,4 +61,5 @@ public class XxlExecutorProperties { * 执行器日志保存天数 [选填] :值大于3时生效,启用执行器Log文件定期清理功能,否则不生效; */ private Integer logRetentionDays = 30; + } diff --git a/pigx-common/pigx-common-job/src/main/java/com/pig4cloud/pigx/common/job/properties/XxlJobProperties.java b/pigx-common/pigx-common-job/src/main/java/com/pig4cloud/pigx/common/job/properties/XxlJobProperties.java index a45e0a475..87b84b1da 100644 --- a/pigx-common/pigx-common-job/src/main/java/com/pig4cloud/pigx/common/job/properties/XxlJobProperties.java +++ b/pigx-common/pigx-common-job/src/main/java/com/pig4cloud/pigx/common/job/properties/XxlJobProperties.java @@ -29,7 +29,9 @@ import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix = "xxl.job") public class XxlJobProperties { + private XxlAdminProperties admin = new XxlAdminProperties(); private XxlExecutorProperties executor = new XxlExecutorProperties(); + } \ No newline at end of file diff --git a/pigx-common/pigx-common-log/src/main/java/com/pig4cloud/pigx/common/log/LogAutoConfiguration.java b/pigx-common/pigx-common-log/src/main/java/com/pig4cloud/pigx/common/log/LogAutoConfiguration.java index 2452dff1c..ad889f1f2 100644 --- a/pigx-common/pigx-common-log/src/main/java/com/pig4cloud/pigx/common/log/LogAutoConfiguration.java +++ b/pigx-common/pigx-common-log/src/main/java/com/pig4cloud/pigx/common/log/LogAutoConfiguration.java @@ -40,6 +40,7 @@ import org.springframework.scheduling.annotation.EnableAsync; @AllArgsConstructor @ConditionalOnWebApplication public class LogAutoConfiguration { + private final RemoteLogService remoteLogService; @Bean @@ -51,4 +52,5 @@ public class LogAutoConfiguration { public SysLogAspect sysLogAspect(ApplicationEventPublisher publisher) { return new SysLogAspect(publisher); } + } diff --git a/pigx-common/pigx-common-log/src/main/java/com/pig4cloud/pigx/common/log/annotation/SysLog.java b/pigx-common/pigx-common-log/src/main/java/com/pig4cloud/pigx/common/log/annotation/SysLog.java index 8fcd4bf1a..884991e32 100644 --- a/pigx-common/pigx-common-log/src/main/java/com/pig4cloud/pigx/common/log/annotation/SysLog.java +++ b/pigx-common/pigx-common-log/src/main/java/com/pig4cloud/pigx/common/log/annotation/SysLog.java @@ -23,8 +23,7 @@ import java.lang.annotation.*; /** * @author lengleng - * @date 2018/6/28 - * 操作日志注解 + * @date 2018/6/28 操作日志注解 */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @@ -33,8 +32,8 @@ public @interface SysLog { /** * 描述 - * * @return {String} */ String value(); + } diff --git a/pigx-common/pigx-common-log/src/main/java/com/pig4cloud/pigx/common/log/aspect/SysLogAspect.java b/pigx-common/pigx-common-log/src/main/java/com/pig4cloud/pigx/common/log/aspect/SysLogAspect.java index e25d67a8e..1dbf019ef 100644 --- a/pigx-common/pigx-common-log/src/main/java/com/pig4cloud/pigx/common/log/aspect/SysLogAspect.java +++ b/pigx-common/pigx-common-log/src/main/java/com/pig4cloud/pigx/common/log/aspect/SysLogAspect.java @@ -39,6 +39,7 @@ import org.springframework.context.ApplicationEventPublisher; @Aspect @AllArgsConstructor public class SysLogAspect { + private final ApplicationEventPublisher publisher; @SneakyThrows diff --git a/pigx-common/pigx-common-log/src/main/java/com/pig4cloud/pigx/common/log/event/SysLogEvent.java b/pigx-common/pigx-common-log/src/main/java/com/pig4cloud/pigx/common/log/event/SysLogEvent.java index f5a781670..990b9844d 100644 --- a/pigx-common/pigx-common-log/src/main/java/com/pig4cloud/pigx/common/log/event/SysLogEvent.java +++ b/pigx-common/pigx-common-log/src/main/java/com/pig4cloud/pigx/common/log/event/SysLogEvent.java @@ -24,11 +24,12 @@ import lombok.AllArgsConstructor; import lombok.Getter; /** - * @author lengleng - * 系统日志事件 + * @author lengleng 系统日志事件 */ @Getter @AllArgsConstructor public class SysLogEvent { + private final SysLog sysLog; + } diff --git a/pigx-common/pigx-common-log/src/main/java/com/pig4cloud/pigx/common/log/event/SysLogListener.java b/pigx-common/pigx-common-log/src/main/java/com/pig4cloud/pigx/common/log/event/SysLogListener.java index bb0c9181f..3c8c49a18 100644 --- a/pigx-common/pigx-common-log/src/main/java/com/pig4cloud/pigx/common/log/event/SysLogListener.java +++ b/pigx-common/pigx-common-log/src/main/java/com/pig4cloud/pigx/common/log/event/SysLogListener.java @@ -29,12 +29,12 @@ import org.springframework.core.annotation.Order; import org.springframework.scheduling.annotation.Async; /** - * @author lengleng - * 异步监听日志事件 + * @author lengleng 异步监听日志事件 */ @Slf4j @AllArgsConstructor public class SysLogListener { + private final RemoteLogService remoteLogService; @Async @@ -44,4 +44,5 @@ public class SysLogListener { SysLog sysLog = event.getSysLog(); remoteLogService.saveLog(sysLog, SecurityConstants.FROM_IN); } + } diff --git a/pigx-common/pigx-common-log/src/main/java/com/pig4cloud/pigx/common/log/init/ApplicationLoggerInitializer.java b/pigx-common/pigx-common-log/src/main/java/com/pig4cloud/pigx/common/log/init/ApplicationLoggerInitializer.java index 7ea897d6a..8a1f8fe56 100644 --- a/pigx-common/pigx-common-log/src/main/java/com/pig4cloud/pigx/common/log/init/ApplicationLoggerInitializer.java +++ b/pigx-common/pigx-common-log/src/main/java/com/pig4cloud/pigx/common/log/init/ApplicationLoggerInitializer.java @@ -11,6 +11,7 @@ import org.springframework.core.env.ConfigurableEnvironment; * 初始化日志路径 */ public class ApplicationLoggerInitializer implements ApplicationContextInitializer { + @Override public void initialize(ConfigurableApplicationContext applicationContext) { ConfigurableEnvironment environment = applicationContext.getEnvironment(); @@ -21,4 +22,5 @@ public class ApplicationLoggerInitializer implements ApplicationContextInitializ // spring boot admin 直接加载日志 System.setProperty("logging.file.name", String.format("%s/%s/debug.log", logBase, appName)); } + } diff --git a/pigx-common/pigx-common-log/src/main/java/com/pig4cloud/pigx/common/log/util/SysLogUtils.java b/pigx-common/pigx-common-log/src/main/java/com/pig4cloud/pigx/common/log/util/SysLogUtils.java index d3d0ee4ad..e2830baf3 100644 --- a/pigx-common/pigx-common-log/src/main/java/com/pig4cloud/pigx/common/log/util/SysLogUtils.java +++ b/pigx-common/pigx-common-log/src/main/java/com/pig4cloud/pigx/common/log/util/SysLogUtils.java @@ -41,6 +41,7 @@ import java.util.Objects; */ @UtilityClass public class SysLogUtils { + public SysLog getSysLog() { HttpServletRequest request = ((ServletRequestAttributes) Objects .requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest(); @@ -71,7 +72,6 @@ public class SysLogUtils { /** * 获取客户端 - * * @return clientId */ private String getClientId() { @@ -85,7 +85,6 @@ public class SysLogUtils { /** * 获取用户名称 - * * @return username */ private String getUsername() { diff --git a/pigx-common/pigx-common-oss/src/main/java/com/pig4cloud/pigx/common/oss/OssAutoConfiguration.java b/pigx-common/pigx-common-oss/src/main/java/com/pig4cloud/pigx/common/oss/OssAutoConfiguration.java index 67c1001fc..6d569efa8 100755 --- a/pigx-common/pigx-common-oss/src/main/java/com/pig4cloud/pigx/common/oss/OssAutoConfiguration.java +++ b/pigx-common/pigx-common-oss/src/main/java/com/pig4cloud/pigx/common/oss/OssAutoConfiguration.java @@ -32,8 +32,9 @@ import org.springframework.context.annotation.Bean; * @author 858695266 */ @AllArgsConstructor -@EnableConfigurationProperties({OssProperties.class}) +@EnableConfigurationProperties({ OssProperties.class }) public class OssAutoConfiguration { + private final OssProperties properties; @Bean diff --git a/pigx-common/pigx-common-oss/src/main/java/com/pig4cloud/pigx/common/oss/OssProperties.java b/pigx-common/pigx-common-oss/src/main/java/com/pig4cloud/pigx/common/oss/OssProperties.java index bd4189f84..6bb899824 100755 --- a/pigx-common/pigx-common-oss/src/main/java/com/pig4cloud/pigx/common/oss/OssProperties.java +++ b/pigx-common/pigx-common-oss/src/main/java/com/pig4cloud/pigx/common/oss/OssProperties.java @@ -24,24 +24,17 @@ import org.springframework.boot.context.properties.ConfigurationProperties; * aws 配置信息 * * @author lengleng - * @author 858695266 - * 配置文件添加: - * oss: - * enable: true - * endpoint: http://127.0.0.1:9000 - * # pathStyleAccess 采用nginx反向代理或者AWS S3 配置成true,支持第三方云存储配置成false - * pathStyleAccess: false - * access-key: lengleng - * secret-key: lengleng - * bucket-name: lengleng - * region: - * custom-domain: https://oss.xxx.com/lengleng + * @author 858695266 配置文件添加: oss: enable: true endpoint: http://127.0.0.1:9000 # + * pathStyleAccess 采用nginx反向代理或者AWS S3 配置成true,支持第三方云存储配置成false pathStyleAccess: false + * access-key: lengleng secret-key: lengleng bucket-name: lengleng region: custom-domain: + * https://oss.xxx.com/lengleng *

* bucket 设置公共读权限 */ @Data @ConfigurationProperties(prefix = "oss") public class OssProperties { + /** * 对象存储服务的URL */ @@ -53,10 +46,9 @@ public class OssProperties { private String customDomain; /** - * true path-style - * nginx 反向代理和S3默认支持 pathStyle {http://endpoint/bucketname} - * false supports virtual-hosted-style 阿里云等需要配置为 - * virtual-hosted-style 模式{http://bucketname.endpoint} + * true path-style nginx 反向代理和S3默认支持 pathStyle {http://endpoint/bucketname} false + * supports virtual-hosted-style 阿里云等需要配置为 virtual-hosted-style + * 模式{http://bucketname.endpoint} */ private Boolean pathStyleAccess = true; diff --git a/pigx-common/pigx-common-oss/src/main/java/com/pig4cloud/pigx/common/oss/http/OssEndpoint.java b/pigx-common/pigx-common-oss/src/main/java/com/pig4cloud/pigx/common/oss/http/OssEndpoint.java index b92be556f..4b1f911e4 100755 --- a/pigx-common/pigx-common-oss/src/main/java/com/pig4cloud/pigx/common/oss/http/OssEndpoint.java +++ b/pigx-common/pigx-common-oss/src/main/java/com/pig4cloud/pigx/common/oss/http/OssEndpoint.java @@ -43,6 +43,7 @@ import java.util.Map; @AllArgsConstructor @RequestMapping("/aws") public class OssEndpoint { + private final OssTemplate template; /** @@ -90,7 +91,8 @@ public class OssEndpoint { @SneakyThrows @PostMapping("/object/{bucketName}/{objectName}") - public S3Object createObject(@RequestBody MultipartFile object, @PathVariable String bucketName, @PathVariable String objectName) { + public S3Object createObject(@RequestBody MultipartFile object, @PathVariable String bucketName, + @PathVariable String objectName) { template.putObject(bucketName, objectName, object.getInputStream(), object.getSize(), object.getContentType()); return template.getObjectInfo(bucketName, objectName); @@ -106,7 +108,8 @@ public class OssEndpoint { @SneakyThrows @GetMapping("/object/{bucketName}/{objectName}/{expires}") - public Map getObject(@PathVariable String bucketName, @PathVariable String objectName, @PathVariable Integer expires) { + public Map getObject(@PathVariable String bucketName, @PathVariable String objectName, + @PathVariable Integer expires) { Map responseBody = new HashMap<>(8); // Put Object info responseBody.put("bucket", bucketName); @@ -124,5 +127,4 @@ public class OssEndpoint { template.removeObject(bucketName, objectName); } - } diff --git a/pigx-common/pigx-common-oss/src/main/java/com/pig4cloud/pigx/common/oss/service/OssTemplate.java b/pigx-common/pigx-common-oss/src/main/java/com/pig4cloud/pigx/common/oss/service/OssTemplate.java index 72ffbdc3e..7c2158d54 100755 --- a/pigx-common/pigx-common-oss/src/main/java/com/pig4cloud/pigx/common/oss/service/OssTemplate.java +++ b/pigx-common/pigx-common-oss/src/main/java/com/pig4cloud/pigx/common/oss/service/OssTemplate.java @@ -37,10 +37,8 @@ import java.io.InputStream; import java.net.URL; import java.util.*; - /** - * aws-s3 通用存储操作 - * 支持所有兼容s3协议的云存储: {阿里云OSS,腾讯云COS,七牛云,京东云,minio 等} + * aws-s3 通用存储操作 支持所有兼容s3协议的云存储: {阿里云OSS,腾讯云COS,七牛云,京东云,minio 等} * * @author lengleng * @author 858695266 @@ -49,13 +47,13 @@ import java.util.*; */ @RequiredArgsConstructor public class OssTemplate implements InitializingBean { + private final OssProperties ossProperties; private AmazonS3 amazonS3; /** * 创建bucket - * * @param bucketName bucket名称 */ @SneakyThrows @@ -69,7 +67,8 @@ public class OssTemplate implements InitializingBean { * 获取全部bucket *

* - * @see AWS API Documentation + * @see AWS + * API Documentation */ @SneakyThrows public List getAllBuckets() { @@ -78,7 +77,8 @@ public class OssTemplate implements InitializingBean { /** * @param bucketName bucket名称 - * @see AWS API Documentation + * @see AWS + * API Documentation */ @SneakyThrows public Optional getBucket(String bucketName) { @@ -87,7 +87,9 @@ public class OssTemplate implements InitializingBean { /** * @param bucketName bucket名称 - * @see AWS API Documentation + * @see AWS API + * Documentation */ @SneakyThrows public void removeBucket(String bucketName) { @@ -96,12 +98,12 @@ public class OssTemplate implements InitializingBean { /** * 根据文件前置查询文件 - * * @param bucketName bucket名称 - * @param prefix 前缀 - * @param recursive 是否递归查询 + * @param prefix 前缀 + * @param recursive 是否递归查询 * @return S3ObjectSummary 列表 - * @see AWS API Documentation + * @see AWS + * API Documentation */ @SneakyThrows public List getAllObjectsByPrefix(String bucketName, String prefix, boolean recursive) { @@ -111,10 +113,9 @@ public class OssTemplate implements InitializingBean { /** * 获取文件外链 - * * @param bucketName bucket名称 * @param objectName 文件名称 - * @param expires 过期时间 <=7 + * @param expires 过期时间 <=7 * @return url * @see AmazonS3#generatePresignedUrl(String bucketName, String key, Date expiration) */ @@ -130,11 +131,11 @@ public class OssTemplate implements InitializingBean { /** * 获取文件 - * * @param bucketName bucket名称 * @param objectName 文件名称 * @return 二进制流 - * @see AWS API Documentation + * @see AWS + * API Documentation */ @SneakyThrows public InputStream getObject(String bucketName, String objectName) { @@ -143,10 +144,9 @@ public class OssTemplate implements InitializingBean { /** * 上传文件 - * * @param bucketName bucket名称 * @param objectName 文件名称 - * @param stream 文件流 + * @param stream 文件流 * @throws Exception */ public void putObject(String bucketName, String objectName, InputStream stream) throws Exception { @@ -155,17 +155,18 @@ public class OssTemplate implements InitializingBean { /** * 上传文件 - * - * @param bucketName bucket名称 - * @param objectName 文件名称 - * @param stream 文件流 - * @param size 大小 + * @param bucketName bucket名称 + * @param objectName 文件名称 + * @param stream 文件流 + * @param size 大小 * @param contextType 类型 * @throws Exception - * @see AWS API Documentation + * @see AWS + * API Documentation */ - public PutObjectResult putObject(String bucketName, String objectName, InputStream stream, long size, String contextType) throws Exception { -// String fileName = getFileName(objectName); + public PutObjectResult putObject(String bucketName, String objectName, InputStream stream, long size, + String contextType) throws Exception { + // String fileName = getFileName(objectName); byte[] bytes = IOUtils.toByteArray(stream); ObjectMetadata objectMetadata = new ObjectMetadata(); objectMetadata.setContentLength(size); @@ -178,11 +179,11 @@ public class OssTemplate implements InitializingBean { /** * 获取文件信息 - * * @param bucketName bucket名称 * @param objectName 文件名称 * @throws Exception - * @see AWS API Documentation + * @see AWS + * API Documentation */ public S3Object getObjectInfo(String bucketName, String objectName) throws Exception { return amazonS3.getObject(bucketName, objectName); @@ -190,11 +191,12 @@ public class OssTemplate implements InitializingBean { /** * 删除文件 - * * @param bucketName bucket名称 * @param objectName 文件名称 * @throws Exception - * @see AWS API Documentation + * @see AWS API + * Documentation */ public void removeObject(String bucketName, String objectName) throws Exception { amazonS3.deleteObject(bucketName, objectName); @@ -205,14 +207,12 @@ public class OssTemplate implements InitializingBean { ClientConfiguration clientConfiguration = new ClientConfiguration(); AwsClientBuilder.EndpointConfiguration endpointConfiguration = new AwsClientBuilder.EndpointConfiguration( ossProperties.getEndpoint(), ossProperties.getRegion()); - AWSCredentials awsCredentials = new BasicAWSCredentials(ossProperties.getAccessKey(), ossProperties.getSecretKey()); + AWSCredentials awsCredentials = new BasicAWSCredentials(ossProperties.getAccessKey(), + ossProperties.getSecretKey()); AWSCredentialsProvider awsCredentialsProvider = new AWSStaticCredentialsProvider(awsCredentials); - this.amazonS3 = AmazonS3Client.builder() - .withEndpointConfiguration(endpointConfiguration) - .withClientConfiguration(clientConfiguration) - .withCredentials(awsCredentialsProvider) - .disableChunkedEncoding() - .withPathStyleAccessEnabled(ossProperties.getPathStyleAccess()) - .build(); + this.amazonS3 = AmazonS3Client.builder().withEndpointConfiguration(endpointConfiguration) + .withClientConfiguration(clientConfiguration).withCredentials(awsCredentialsProvider) + .disableChunkedEncoding().withPathStyleAccessEnabled(ossProperties.getPathStyleAccess()).build(); } + } diff --git a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/annotation/EnablePigxResourceServer.java b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/annotation/EnablePigxResourceServer.java index fca972cff..d951467b8 100644 --- a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/annotation/EnablePigxResourceServer.java +++ b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/annotation/EnablePigxResourceServer.java @@ -34,10 +34,10 @@ import java.lang.annotation.*; @Documented @Inherited @EnableResourceServer -@Target({ElementType.TYPE}) +@Target({ ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) @EnableGlobalMethodSecurity(prePostEnabled = true) -@Import({PigxResourceServerAutoConfiguration.class, PigxSecurityBeanDefinitionRegistrar.class}) +@Import({ PigxResourceServerAutoConfiguration.class, PigxSecurityBeanDefinitionRegistrar.class }) public @interface EnablePigxResourceServer { } diff --git a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/annotation/Inner.java b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/annotation/Inner.java index 1ac962247..b90b8a634 100644 --- a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/annotation/Inner.java +++ b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/annotation/Inner.java @@ -25,22 +25,21 @@ import java.lang.annotation.*; *

* 服务调用鉴权注解 */ -@Target({ElementType.METHOD, ElementType.TYPE}) +@Target({ ElementType.METHOD, ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Inner { /** * 是否AOP统一处理 - * * @return false, true */ boolean value() default true; /** * 需要特殊判空的字段(预留) - * * @return {} */ String[] field() default {}; + } diff --git a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/GlobalExceptionHandlerResolver.java b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/GlobalExceptionHandlerResolver.java index dbb8fe397..0077ae585 100644 --- a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/GlobalExceptionHandlerResolver.java +++ b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/GlobalExceptionHandlerResolver.java @@ -33,8 +33,7 @@ import java.util.List; /** * @author lengleng - * @date 2018/8/30 - * 全局异常处理器 + * @date 2018/8/30 全局异常处理器 */ @Slf4j @RestControllerAdvice @@ -42,7 +41,6 @@ public class GlobalExceptionHandlerResolver { /** * 全局异常. - * * @param e the e * @return R */ @@ -55,27 +53,24 @@ public class GlobalExceptionHandlerResolver { /** * 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()); + String msg = SpringSecurityMessageSource.getAccessor().getMessage("AbstractAccessDecisionManager.accessDenied", + e.getMessage()); log.error("拒绝授权异常信息 ex={}", msg, e); return R.failed(e.getLocalizedMessage()); } /** * validation Exception - * * @param exception * @return R */ - @ExceptionHandler({MethodArgumentNotValidException.class}) + @ExceptionHandler({ MethodArgumentNotValidException.class }) @ResponseStatus(HttpStatus.BAD_REQUEST) public R handleBodyValidException(MethodArgumentNotValidException exception) { List fieldErrors = exception.getBindingResult().getFieldErrors(); @@ -85,15 +80,15 @@ public class GlobalExceptionHandlerResolver { /** * validation Exception (以form-data形式传参) - * * @param exception * @return R */ - @ExceptionHandler({BindException.class}) + @ExceptionHandler({ BindException.class }) @ResponseStatus(HttpStatus.BAD_REQUEST) public R bindExceptionHandler(BindException exception) { List fieldErrors = exception.getBindingResult().getFieldErrors(); log.warn("参数绑定异常,ex = {}", fieldErrors.get(0).getDefaultMessage()); return R.failed(fieldErrors.get(0).getDefaultMessage()); } + } diff --git a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PermissionService.java b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PermissionService.java index 345d0c502..cb0591870 100644 --- a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PermissionService.java +++ b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PermissionService.java @@ -30,15 +30,14 @@ import java.util.Collection; /** * @author lengleng - * @date 2018/6/22 - * 接口权限判断工具 + * @date 2018/6/22 接口权限判断工具 */ @Slf4j @Component("pms") public class PermissionService { + /** * 判断接口是否有任意xxx,xxx权限 - * * @param permissions 权限 * @return {boolean} */ @@ -51,9 +50,8 @@ public class PermissionService { return false; } Collection authorities = authentication.getAuthorities(); - return authorities.stream() - .map(GrantedAuthority::getAuthority) - .filter(StringUtils::hasText) + return authorities.stream().map(GrantedAuthority::getAuthority).filter(StringUtils::hasText) .anyMatch(x -> PatternMatchUtils.simpleMatch(permissions, x)); } + } diff --git a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PermitAllUrlProperties.java b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PermitAllUrlProperties.java index 9daf24abb..29b37a658 100644 --- a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PermitAllUrlProperties.java +++ b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PermitAllUrlProperties.java @@ -51,7 +51,9 @@ import java.util.regex.Pattern; @ConditionalOnExpression("!'${security.oauth2.client.ignore-urls}'.isEmpty()") @ConfigurationProperties(prefix = "security.oauth2.client") public class PermitAllUrlProperties implements InitializingBean { + private static final Pattern PATTERN = Pattern.compile("\\{(.*?)\\}"); + private final WebApplicationContext applicationContext; @Getter @@ -68,16 +70,15 @@ public class PermitAllUrlProperties implements InitializingBean { // 获取方法上边的注解 替代path variable 为 * Inner method = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), Inner.class); - Optional.ofNullable(method) - .ifPresent(inner -> info.getPatternsCondition().getPatterns() - .forEach(url -> ignoreUrls.add(ReUtil.replaceAll(url, PATTERN, "*")))); + Optional.ofNullable(method).ifPresent(inner -> info.getPatternsCondition().getPatterns() + .forEach(url -> ignoreUrls.add(ReUtil.replaceAll(url, PATTERN, "*")))); // 获取类上边的注解, 替代path variable 为 * Inner controller = AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), Inner.class); - Optional.ofNullable(controller) - .ifPresent(inner -> info.getPatternsCondition().getPatterns() - .forEach(url -> ignoreUrls.add(ReUtil.replaceAll(url, PATTERN, "*")))); + Optional.ofNullable(controller).ifPresent(inner -> info.getPatternsCondition().getPatterns() + .forEach(url -> ignoreUrls.add(ReUtil.replaceAll(url, PATTERN, "*")))); }); } + } diff --git a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxAuth2ExceptionSerializer.java b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxAuth2ExceptionSerializer.java index 8b86b6022..0a2a12b66 100644 --- a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxAuth2ExceptionSerializer.java +++ b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxAuth2ExceptionSerializer.java @@ -31,6 +31,7 @@ import lombok.SneakyThrows; * OAuth2 异常格式化 */ public class PigxAuth2ExceptionSerializer extends StdSerializer { + public PigxAuth2ExceptionSerializer() { super(PigxAuth2Exception.class); } @@ -44,4 +45,5 @@ public class PigxAuth2ExceptionSerializer extends StdSerializer pathMatcher.match(url, request.getRequestURI())); + .anyMatch(url -> pathMatcher.match(url, request.getRequestURI())); return match ? null : super.extract(request); } + } diff --git a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxPreAuthenticationChecks.java b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxPreAuthenticationChecks.java index f46e7c4ea..4eedb3aab 100644 --- a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxPreAuthenticationChecks.java +++ b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxPreAuthenticationChecks.java @@ -32,6 +32,7 @@ import org.springframework.security.core.userdetails.UserDetailsChecker; */ @Slf4j public class PigxPreAuthenticationChecks implements UserDetailsChecker { + private MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor(); @Override @@ -39,25 +40,23 @@ public class PigxPreAuthenticationChecks implements UserDetailsChecker { if (!user.isAccountNonLocked()) { log.debug("User account is locked"); - throw new LockedException(messages.getMessage( - "AbstractUserDetailsAuthenticationProvider.locked", - "User account is locked")); + throw new LockedException( + messages.getMessage("AbstractUserDetailsAuthenticationProvider.locked", "User account is locked")); } if (!user.isEnabled()) { log.debug("User account is disabled"); - throw new DisabledException(messages.getMessage( - "AbstractUserDetailsAuthenticationProvider.disabled", - "User is disabled")); + throw new DisabledException( + messages.getMessage("AbstractUserDetailsAuthenticationProvider.disabled", "User is disabled")); } if (!user.isAccountNonExpired()) { log.debug("User account is expired"); - throw new AccountExpiredException(messages.getMessage( - "AbstractUserDetailsAuthenticationProvider.expired", + throw new AccountExpiredException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.expired", "User account has expired")); } } + } diff --git a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxResourceServerAutoConfiguration.java b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxResourceServerAutoConfiguration.java index 22777f4fc..818e98bd7 100644 --- a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxResourceServerAutoConfiguration.java +++ b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxResourceServerAutoConfiguration.java @@ -37,6 +37,7 @@ import java.util.Map; */ @ComponentScan("com.pig4cloud.pigx.common.security") public class PigxResourceServerAutoConfiguration implements ApplicationContextAware { + private ApplicationContext applicationContext; @Bean @@ -52,9 +53,9 @@ public class PigxResourceServerAutoConfiguration implements ApplicationContextAw return restTemplate; } - @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } + } diff --git a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxResourceServerConfigurerAdapter.java b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxResourceServerConfigurerAdapter.java index f5d7b0af1..a80257059 100644 --- a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxResourceServerConfigurerAdapter.java +++ b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxResourceServerConfigurerAdapter.java @@ -34,39 +34,39 @@ import org.springframework.web.client.RestTemplate; * @author lengleng * @date 2018/6/22 *

- * 1. 支持remoteTokenServices 负载均衡 - * 2. 支持 获取用户全部信息 + * 1. 支持remoteTokenServices 负载均衡 2. 支持 获取用户全部信息 */ @Slf4j public class PigxResourceServerConfigurerAdapter extends ResourceServerConfigurerAdapter { + @Autowired protected ResourceAuthExceptionEntryPoint resourceAuthExceptionEntryPoint; + @Autowired protected RemoteTokenServices remoteTokenServices; + @Autowired private PermitAllUrlProperties permitAllUrlProperties; + @Autowired private TokenExtractor tokenExtractor; + @Autowired private RestTemplate lbRestTemplate; /** * 默认的配置,对外暴露 - * * @param httpSecurity */ @Override @SneakyThrows public void configure(HttpSecurity httpSecurity) { - //允许使用iframe 嵌套,避免swagger-ui 不被加载的问题 + // 允许使用iframe 嵌套,避免swagger-ui 不被加载的问题 httpSecurity.headers().frameOptions().disable(); - ExpressionUrlAuthorizationConfigurer - .ExpressionInterceptUrlRegistry registry = httpSecurity + ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry registry = httpSecurity .authorizeRequests(); - permitAllUrlProperties.getIgnoreUrls() - .forEach(url -> registry.antMatchers(url).permitAll()); - registry.anyRequest().authenticated() - .and().csrf().disable(); + permitAllUrlProperties.getIgnoreUrls().forEach(url -> registry.antMatchers(url).permitAll()); + registry.anyRequest().authenticated().and().csrf().disable(); } @Override @@ -77,8 +77,8 @@ public class PigxResourceServerConfigurerAdapter extends ResourceServerConfigure remoteTokenServices.setRestTemplate(lbRestTemplate); remoteTokenServices.setAccessTokenConverter(accessTokenConverter); - resources.authenticationEntryPoint(resourceAuthExceptionEntryPoint) - .tokenExtractor(tokenExtractor) + resources.authenticationEntryPoint(resourceAuthExceptionEntryPoint).tokenExtractor(tokenExtractor) .tokenServices(remoteTokenServices); } + } diff --git a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxResourceServerTokenRelayAutoConfiguration.java b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxResourceServerTokenRelayAutoConfiguration.java index 9214749db..f6c5a7c6e 100644 --- a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxResourceServerTokenRelayAutoConfiguration.java +++ b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxResourceServerTokenRelayAutoConfiguration.java @@ -35,8 +35,7 @@ import java.lang.annotation.*; /** * @author lengleng - * @date 2019/4/14 - * 注入AccessTokenContextRelay 解决feign 传递token 为空问题 + * @date 2019/4/14 注入AccessTokenContextRelay 解决feign 传递token 为空问题 */ @Configuration @AutoConfigureAfter(OAuth2AutoConfiguration.class) @@ -49,7 +48,7 @@ public class PigxResourceServerTokenRelayAutoConfiguration { return new AccessTokenContextRelay(context); } - @Target({ElementType.TYPE, ElementType.METHOD}) + @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Documented @Conditional(OAuth2OnClientInResourceServerCondition.class) @@ -57,8 +56,7 @@ public class PigxResourceServerTokenRelayAutoConfiguration { } - private static class OAuth2OnClientInResourceServerCondition - extends AllNestedConditions { + private static class OAuth2OnClientInResourceServerCondition extends AllNestedConditions { public OAuth2OnClientInResourceServerCondition() { super(ConfigurationPhase.REGISTER_BEAN); @@ -66,11 +64,14 @@ public class PigxResourceServerTokenRelayAutoConfiguration { @ConditionalOnBean(ResourceServerConfiguration.class) static class Server { + } @ConditionalOnBean(OAuth2ClientConfiguration.class) static class Client { + } } + } diff --git a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxSecurityBeanDefinitionRegistrar.java b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxSecurityBeanDefinitionRegistrar.java index 97fa0547d..4c861fe69 100644 --- a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxSecurityBeanDefinitionRegistrar.java +++ b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxSecurityBeanDefinitionRegistrar.java @@ -30,9 +30,9 @@ import org.springframework.core.type.AnnotationMetadata; */ @Slf4j public class PigxSecurityBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar { + /** * 根据注解值动态注入资源服务器的相关属性 - * * @param metadata 注解信息 * @param registry 注册器 */ @@ -48,4 +48,5 @@ public class PigxSecurityBeanDefinitionRegistrar implements ImportBeanDefinition registry.registerBeanDefinition(SecurityConstants.RESOURCE_SERVER_CONFIGURER, beanDefinition); } + } diff --git a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxSecurityInnerAspect.java b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxSecurityInnerAspect.java index 31990661c..90894835a 100644 --- a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxSecurityInnerAspect.java +++ b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxSecurityInnerAspect.java @@ -40,6 +40,7 @@ import javax.servlet.http.HttpServletRequest; @Aspect @AllArgsConstructor public class PigxSecurityInnerAspect { + private final HttpServletRequest request; @SneakyThrows diff --git a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxTokenEnhancer.java b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxTokenEnhancer.java index c23931c4b..8d7b4ce2a 100644 --- a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxTokenEnhancer.java +++ b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxTokenEnhancer.java @@ -34,18 +34,18 @@ import java.util.Map; * token增强,客户端模式不增强。 */ public class PigxTokenEnhancer implements TokenEnhancer { + /** - * Provides an opportunity for customization of an access token (e.g. through its additional information map) during - * the process of creating a new token for use by a client. - * - * @param accessToken the current access token with its expiration and refresh token + * Provides an opportunity for customization of an access token (e.g. through its + * additional information map) during the process of creating a new token for use by a + * client. + * @param accessToken the current access token with its expiration and refresh token * @param authentication the current authentication including client and user details * @return a new token enhanced with additional information */ @Override public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { - if (SecurityConstants.CLIENT_CREDENTIALS - .equals(authentication.getOAuth2Request().getGrantType())) { + if (SecurityConstants.CLIENT_CREDENTIALS.equals(authentication.getOAuth2Request().getGrantType())) { return accessToken; } @@ -57,4 +57,5 @@ public class PigxTokenEnhancer implements TokenEnhancer { ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo); return accessToken; } + } diff --git a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxUserAuthenticationConverter.java b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxUserAuthenticationConverter.java index e32beeece..9f29c7635 100644 --- a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxUserAuthenticationConverter.java +++ b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxUserAuthenticationConverter.java @@ -48,11 +48,12 @@ import java.util.Optional; */ @Slf4j public class PigxUserAuthenticationConverter implements UserAuthenticationConverter { + private static final String N_A = "N/A"; /** - * Extract information about the user to be used in an access token (i.e. for resource servers). - * + * Extract information about the user to be used in an access token (i.e. for resource + * servers). * @param authentication an authentication representing a user * @return a map of key values representing the unique information about the user */ @@ -67,8 +68,8 @@ public class PigxUserAuthenticationConverter implements UserAuthenticationConver } /** - * Inverse of {@link #convertUserAuthentication(Authentication)}. Extracts an Authentication from a map. - * + * Inverse of {@link #convertUserAuthentication(Authentication)}. Extracts an + * Authentication from a map. * @param responseMap a map of user information * @return an Authentication representing the user or null if there is none */ @@ -84,8 +85,8 @@ public class PigxUserAuthenticationConverter implements UserAuthenticationConver Integer tenantId = MapUtil.getInt(map, SecurityConstants.DETAILS_TENANT_ID); String phone = MapUtil.getStr(map, SecurityConstants.DETAILS_PHONE); String avatar = MapUtil.getStr(map, SecurityConstants.DETAILS_AVATAR); - PigxUser user = new PigxUser(id, deptId, phone, avatar, tenantId, username, N_A, true - , true, true, true, authorities); + PigxUser user = new PigxUser(id, deptId, phone, avatar, tenantId, username, N_A, true, true, true, true, + authorities); return new UsernamePasswordAuthenticationToken(user, N_A, authorities); } return null; @@ -97,8 +98,8 @@ public class PigxUserAuthenticationConverter implements UserAuthenticationConver return AuthorityUtils.commaSeparatedStringToAuthorityList((String) authorities); } if (authorities instanceof Collection) { - return AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils - .collectionToCommaDelimitedString((Collection) authorities)); + return AuthorityUtils.commaSeparatedStringToAuthorityList( + StringUtils.collectionToCommaDelimitedString((Collection) authorities)); } return AuthorityUtils.NO_AUTHORITIES; } @@ -109,18 +110,21 @@ public class PigxUserAuthenticationConverter implements UserAuthenticationConver if (StrUtil.isNotBlank(headerValue) && !userValue.toString().equals(headerValue)) { log.warn("请求头中的租户ID({})和用户的租户ID({})不一致", headerValue, userValue); // TODO: 不要提示租户ID不对,可能被穷举 - throw new PigxAuth2Exception(SpringSecurityMessageSource.getAccessor().getMessage("AbstractUserDetailsAuthenticationProvider.badTenantId", "Bad tenant ID")); + throw new PigxAuth2Exception(SpringSecurityMessageSource.getAccessor() + .getMessage("AbstractUserDetailsAuthenticationProvider.badTenantId", "Bad tenant ID")); } } private Optional getCurrentHttpRequest() { - return Optional.ofNullable(RequestContextHolder.getRequestAttributes()) - .filter(requestAttributes -> ServletRequestAttributes.class.isAssignableFrom(requestAttributes.getClass())) + return Optional.ofNullable(RequestContextHolder.getRequestAttributes()).filter( + requestAttributes -> ServletRequestAttributes.class.isAssignableFrom(requestAttributes.getClass())) .map(requestAttributes -> ((ServletRequestAttributes) requestAttributes)) .map(ServletRequestAttributes::getRequest); } private String getCurrentTenantId() { - return getCurrentHttpRequest().map(httpServletRequest -> httpServletRequest.getHeader(CommonConstants.TENANT_ID)).orElse(null); + return getCurrentHttpRequest() + .map(httpServletRequest -> httpServletRequest.getHeader(CommonConstants.TENANT_ID)).orElse(null); } + } diff --git a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxWebResponseExceptionTranslator.java b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxWebResponseExceptionTranslator.java index 92bd4d4de..8d1d7f015 100644 --- a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxWebResponseExceptionTranslator.java +++ b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxWebResponseExceptionTranslator.java @@ -36,8 +36,7 @@ import org.springframework.web.HttpRequestMethodNotSupportedException; /** * @author lengleng - * @date 2018/7/8 - * 异常处理,重写oauth 默认实现 + * @date 2018/7/8 异常处理,重写oauth 默认实现 */ @Slf4j public class PigxWebResponseExceptionTranslator implements WebResponseExceptionTranslator { @@ -50,20 +49,20 @@ public class PigxWebResponseExceptionTranslator implements WebResponseExceptionT // Try to extract a SpringSecurityException from the stacktrace Throwable[] causeChain = throwableAnalyzer.determineCauseChain(e); - Exception ase = (AuthenticationException) throwableAnalyzer.getFirstThrowableOfType(AuthenticationException.class, - causeChain); + Exception ase = (AuthenticationException) throwableAnalyzer + .getFirstThrowableOfType(AuthenticationException.class, causeChain); if (ase != null) { return handleOAuth2Exception(new UnauthorizedException(e.getMessage(), e)); } - ase = (AccessDeniedException) throwableAnalyzer - .getFirstThrowableOfType(AccessDeniedException.class, causeChain); + ase = (AccessDeniedException) throwableAnalyzer.getFirstThrowableOfType(AccessDeniedException.class, + causeChain); if (ase != null) { return handleOAuth2Exception(new ForbiddenException(ase.getMessage(), ase)); } - ase = (InvalidGrantException) throwableAnalyzer - .getFirstThrowableOfType(InvalidGrantException.class, causeChain); + ase = (InvalidGrantException) throwableAnalyzer.getFirstThrowableOfType(InvalidGrantException.class, + causeChain); if (ase != null) { return handleOAuth2Exception(new InvalidException(ase.getMessage(), ase)); } @@ -74,8 +73,7 @@ public class PigxWebResponseExceptionTranslator implements WebResponseExceptionT return handleOAuth2Exception(new MethodNotAllowedException(ase.getMessage(), ase)); } - ase = (OAuth2Exception) throwableAnalyzer.getFirstThrowableOfType( - OAuth2Exception.class, causeChain); + ase = (OAuth2Exception) throwableAnalyzer.getFirstThrowableOfType(OAuth2Exception.class, causeChain); if (ase != null) { return handleOAuth2Exception((OAuth2Exception) ase); @@ -92,16 +90,17 @@ public class PigxWebResponseExceptionTranslator implements WebResponseExceptionT headers.set(HttpHeaders.CACHE_CONTROL, "no-store"); headers.set(HttpHeaders.PRAGMA, "no-cache"); if (status == HttpStatus.UNAUTHORIZED.value() || (e instanceof InsufficientScopeException)) { - headers.set(HttpHeaders.WWW_AUTHENTICATE, String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, e.getSummary())); + headers.set(HttpHeaders.WWW_AUTHENTICATE, + String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, e.getSummary())); } // 客户端异常直接返回客户端,不然无法解析 if (e instanceof ClientAuthenticationException) { - return new ResponseEntity<>(e, headers, - HttpStatus.valueOf(status)); + return new ResponseEntity<>(e, headers, HttpStatus.valueOf(status)); } return new ResponseEntity<>(new PigxAuth2Exception(e.getMessage(), e.getOAuth2ErrorCode()), headers, HttpStatus.valueOf(status)); } + } diff --git a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/ResourceAuthExceptionEntryPoint.java b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/ResourceAuthExceptionEntryPoint.java index 8fb2f9e61..2dc4de309 100644 --- a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/ResourceAuthExceptionEntryPoint.java +++ b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/ResourceAuthExceptionEntryPoint.java @@ -39,7 +39,7 @@ import java.io.PrintWriter; import java.util.Locale; /** - * 客户端异常处理 {@link org.springframework.security.core.AuthenticationException } 不同细化异常处理 + * 客户端异常处理 {@link org.springframework.security.core.AuthenticationException } 不同细化异常处理 * * @author lengleng * @date 2020-06-14 @@ -48,12 +48,13 @@ import java.util.Locale; @Component @AllArgsConstructor public class ResourceAuthExceptionEntryPoint implements AuthenticationEntryPoint { + private final ObjectMapper objectMapper; @Override @SneakyThrows public void commence(HttpServletRequest request, HttpServletResponse response, - AuthenticationException authException) { + AuthenticationException authException) { response.setCharacterEncoding(CommonConstants.UTF8); response.setContentType(MediaType.APPLICATION_JSON_VALUE); R result = new R<>(); @@ -64,15 +65,15 @@ public class ResourceAuthExceptionEntryPoint implements AuthenticationEntryPoint if (authException instanceof CredentialsExpiredException || authException instanceof InsufficientAuthenticationException) { String msg = SpringSecurityMessageSource.getAccessor().getMessage( - "AbstractUserDetailsAuthenticationProvider.credentialsExpired" - , authException.getMessage(), Locale.CHINA); + "AbstractUserDetailsAuthenticationProvider.credentialsExpired", authException.getMessage(), + Locale.CHINA); result.setMsg(msg); } if (authException instanceof UsernameNotFoundException) { String msg = SpringSecurityMessageSource.getAccessor().getMessage( - "AbstractUserDetailsAuthenticationProvider.noopBindAccount" - , authException.getMessage(), Locale.CHINA); + "AbstractUserDetailsAuthenticationProvider.noopBindAccount", authException.getMessage(), + Locale.CHINA); result.setMsg(msg); } @@ -80,4 +81,5 @@ public class ResourceAuthExceptionEntryPoint implements AuthenticationEntryPoint PrintWriter printWriter = response.getWriter(); printWriter.append(objectMapper.writeValueAsString(result)); } + } diff --git a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/exception/ForbiddenException.java b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/exception/ForbiddenException.java index 9cbe6a55f..1d3e87ba9 100644 --- a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/exception/ForbiddenException.java +++ b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/exception/ForbiddenException.java @@ -27,11 +27,13 @@ import org.springframework.http.HttpStatus; */ @JsonSerialize(using = PigxAuth2ExceptionSerializer.class) public class ForbiddenException extends PigxAuth2Exception { + public ForbiddenException(String msg) { super(msg); } + public ForbiddenException(String msg, Throwable t) { - super(msg,t); + super(msg, t); } @Override @@ -45,4 +47,3 @@ public class ForbiddenException extends PigxAuth2Exception { } } - diff --git a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/exception/PigxAuth2Exception.java b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/exception/PigxAuth2Exception.java index bd6b6cd05..c83c1aa47 100644 --- a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/exception/PigxAuth2Exception.java +++ b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/exception/PigxAuth2Exception.java @@ -24,11 +24,11 @@ import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; /** * @author lengleng - * @date 2018/7/8 - * 自定义OAuth2Exception + * @date 2018/7/8 自定义OAuth2Exception */ @JsonSerialize(using = PigxAuth2ExceptionSerializer.class) public class PigxAuth2Exception extends OAuth2Exception { + @Getter private String errorCode; @@ -37,11 +37,12 @@ public class PigxAuth2Exception extends OAuth2Exception { } public PigxAuth2Exception(String msg, Throwable t) { - super(msg,t); + super(msg, t); } public PigxAuth2Exception(String msg, String errorCode) { super(msg); this.errorCode = errorCode; } + } diff --git a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/handler/AuthenticationFailureHandler.java b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/handler/AuthenticationFailureHandler.java index 9b07e5f33..849628719 100644 --- a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/handler/AuthenticationFailureHandler.java +++ b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/handler/AuthenticationFailureHandler.java @@ -8,18 +8,18 @@ import javax.servlet.http.HttpServletResponse; /** * @author lengleng - * @date 2020/03/25 - * token 发放失败处理 + * @date 2020/03/25 token 发放失败处理 */ public interface AuthenticationFailureHandler { /** * 业务处理 - * * @param authenticationException 错误信息 - * @param authentication 认证信息 - * @param request 请求信息 - * @param response 响应信息 + * @param authentication 认证信息 + * @param request 请求信息 + * @param response 响应信息 */ - void handle(AuthenticationException authenticationException, Authentication authentication, HttpServletRequest request, HttpServletResponse response); + void handle(AuthenticationException authenticationException, Authentication authentication, + HttpServletRequest request, HttpServletResponse response); + } diff --git a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/handler/AuthenticationSuccessHandler.java b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/handler/AuthenticationSuccessHandler.java index 594f96a6b..cb244c666 100644 --- a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/handler/AuthenticationSuccessHandler.java +++ b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/handler/AuthenticationSuccessHandler.java @@ -7,17 +7,16 @@ import javax.servlet.http.HttpServletResponse; /** * @author lengleng - * @date 2020/03/25 - * token 发放成功处理 + * @date 2020/03/25 token 发放成功处理 */ public interface AuthenticationSuccessHandler { /** * 业务处理 - * * @param authentication 认证信息 - * @param request 请求信息 - * @param response 响应信息 + * @param request 请求信息 + * @param response 响应信息 */ void handle(Authentication authentication, HttpServletRequest request, HttpServletResponse response); + } diff --git a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/handler/FormAuthenticationFailureHandler.java b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/handler/FormAuthenticationFailureHandler.java index 356e81248..5b9a5ac09 100644 --- a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/handler/FormAuthenticationFailureHandler.java +++ b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/handler/FormAuthenticationFailureHandler.java @@ -36,18 +36,21 @@ import javax.servlet.http.HttpServletResponse; */ @Slf4j public class FormAuthenticationFailureHandler implements AuthenticationFailureHandler { + /** * Called when an authentication attempt fails. - * - * @param request the request during which the authentication attempt occurred. - * @param response the response. + * @param request the request during which the authentication attempt occurred. + * @param response the response. * @param exception the exception which was thrown to reject the authentication */ @Override @SneakyThrows - public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) { + public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, + AuthenticationException exception) { log.debug("表单登录失败:{}", exception.getLocalizedMessage()); - String url = HttpUtil.encodeParams(String.format("/token/login?error=%s", exception.getMessage()), CharsetUtil.CHARSET_UTF_8); + String url = HttpUtil.encodeParams(String.format("/token/login?error=%s", exception.getMessage()), + CharsetUtil.CHARSET_UTF_8); WebUtils.getResponse().sendRedirect(url); } + } \ No newline at end of file diff --git a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/handler/MobileLoginSuccessHandler.java b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/handler/MobileLoginSuccessHandler.java index 7206fa6b8..4c1cb6b59 100644 --- a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/handler/MobileLoginSuccessHandler.java +++ b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/handler/MobileLoginSuccessHandler.java @@ -43,32 +43,36 @@ import java.io.PrintWriter; /** * @author lengleng - * @date 2018/8/5 - * 手机号登录成功,返回oauth token + * @date 2018/8/5 手机号登录成功,返回oauth token */ @Slf4j public class MobileLoginSuccessHandler implements AuthenticationSuccessHandler { + private static final String BASIC_ = "Basic "; + @Autowired private ObjectMapper objectMapper; + @Autowired private PasswordEncoder passwordEncoder; + @Autowired private ClientDetailsService clientDetailsService; + @Lazy @Autowired private AuthorizationServerTokenServices defaultAuthorizationServerTokenServices; /** - * Called when a user has been successfully authenticated. - * 调用spring security oauth API 生成 oAuth2AccessToken - * - * @param request the request which caused the successful authentication - * @param response the response + * Called when a user has been successfully authenticated. 调用spring security oauth API + * 生成 oAuth2AccessToken + * @param request the request which caused the successful authentication + * @param response the response * @param authentication the Authentication object which was created during */ @Override - public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { + public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, + Authentication authentication) { String header = request.getHeader(HttpHeaders.AUTHORIZATION); if (header == null || !header.startsWith(BASIC_)) { @@ -82,31 +86,32 @@ public class MobileLoginSuccessHandler implements AuthenticationSuccessHandler { ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId); - //校验secret + // 校验secret if (!passwordEncoder.matches(tokens[1], clientDetails.getClientSecret())) { throw new InvalidClientException("Given client ID does not match authenticated client"); } - TokenRequest tokenRequest = new TokenRequest(MapUtil.newHashMap(), clientId, clientDetails.getScope(), "mobile"); + TokenRequest tokenRequest = new TokenRequest(MapUtil.newHashMap(), clientId, clientDetails.getScope(), + "mobile"); - //校验scope + // 校验scope new DefaultOAuth2RequestValidator().validateScope(tokenRequest, clientDetails); OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails); OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication); - OAuth2AccessToken oAuth2AccessToken = defaultAuthorizationServerTokenServices.createAccessToken(oAuth2Authentication); + OAuth2AccessToken oAuth2AccessToken = defaultAuthorizationServerTokenServices + .createAccessToken(oAuth2Authentication); log.info("获取token 成功:{}", oAuth2AccessToken.getValue()); response.setCharacterEncoding(CharsetUtil.UTF_8); response.setContentType(MediaType.APPLICATION_JSON_VALUE); PrintWriter printWriter = response.getWriter(); printWriter.append(objectMapper.writeValueAsString(oAuth2AccessToken)); - } catch (IOException e) { - throw new BadCredentialsException( - "Failed to decode basic authentication token"); + } + catch (IOException e) { + throw new BadCredentialsException("Failed to decode basic authentication token"); } } - } diff --git a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/handler/RestResponseErrorHandler.java b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/handler/RestResponseErrorHandler.java index ebf06c30e..284724640 100644 --- a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/handler/RestResponseErrorHandler.java +++ b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/handler/RestResponseErrorHandler.java @@ -13,10 +13,12 @@ import java.io.IOException; * 重写默认的 响应失败处理器,400 不作为异常 */ public class RestResponseErrorHandler extends DefaultResponseErrorHandler { + @Override public void handleError(ClientHttpResponse response) throws IOException { if (response.getRawStatusCode() != HttpStatus.BAD_REQUEST.value()) { super.handleError(response); } } + } diff --git a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/interceptor/AccpetRequestInterceptor.java b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/interceptor/AccpetRequestInterceptor.java index 340cb4cac..ec60fab21 100644 --- a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/interceptor/AccpetRequestInterceptor.java +++ b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/interceptor/AccpetRequestInterceptor.java @@ -18,9 +18,12 @@ import java.io.IOException; */ @Component public class AccpetRequestInterceptor implements ClientHttpRequestInterceptor { + @Override - public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { + public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) + throws IOException { request.getHeaders().set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE); return execution.execute(request, body); } + } diff --git a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/interceptor/PigxFeignClientInterceptor.java b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/interceptor/PigxFeignClientInterceptor.java index 8b84ebfd6..4eae454c1 100644 --- a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/interceptor/PigxFeignClientInterceptor.java +++ b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/interceptor/PigxFeignClientInterceptor.java @@ -30,35 +30,32 @@ import java.util.Collection; /** * @author lengleng - * @date 2018/8/13 - * 扩展OAuth2FeignRequestInterceptor + * @date 2018/8/13 扩展OAuth2FeignRequestInterceptor */ @Slf4j public class PigxFeignClientInterceptor extends OAuth2FeignRequestInterceptor { + private final OAuth2ClientContext oAuth2ClientContext; + private final AccessTokenContextRelay accessTokenContextRelay; /** * Default constructor which uses the provided OAuth2ClientContext and Bearer tokens * within Authorization header - * - * @param oAuth2ClientContext provided context - * @param resource type of resource to be accessed + * @param oAuth2ClientContext provided context + * @param resource type of resource to be accessed * @param accessTokenContextRelay */ - public PigxFeignClientInterceptor(OAuth2ClientContext oAuth2ClientContext - , OAuth2ProtectedResourceDetails resource, AccessTokenContextRelay accessTokenContextRelay) { + public PigxFeignClientInterceptor(OAuth2ClientContext oAuth2ClientContext, OAuth2ProtectedResourceDetails resource, + AccessTokenContextRelay accessTokenContextRelay) { super(oAuth2ClientContext, resource); this.oAuth2ClientContext = oAuth2ClientContext; this.accessTokenContextRelay = accessTokenContextRelay; } - /** - * Create a template with the header of provided name and extracted extract - * 1. 如果使用 非web 请求,header 区别 - * 2. 根据authentication 还原请求token - * + * Create a template with the header of provided name and extracted extract 1. 如果使用 + * 非web 请求,header 区别 2. 根据authentication 还原请求token * @param template */ @Override @@ -69,9 +66,9 @@ public class PigxFeignClientInterceptor extends OAuth2FeignRequestInterceptor { } accessTokenContextRelay.copyToken(); - if (oAuth2ClientContext != null - && oAuth2ClientContext.getAccessToken() != null) { + if (oAuth2ClientContext != null && oAuth2ClientContext.getAccessToken() != null) { super.apply(template); } } + } diff --git a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/interceptor/PigxFeignConfiguration.java b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/interceptor/PigxFeignConfiguration.java index 4a225f17d..aba968279 100644 --- a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/interceptor/PigxFeignConfiguration.java +++ b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/interceptor/PigxFeignConfiguration.java @@ -39,8 +39,7 @@ public class PigxFeignConfiguration { @Bean @ConditionalOnProperty("security.oauth2.client.client-id") public RequestInterceptor oauth2FeignRequestInterceptor(OAuth2ClientContext oAuth2ClientContext, - OAuth2ProtectedResourceDetails resource, - AccessTokenContextRelay accessTokenContextRelay) { + OAuth2ProtectedResourceDetails resource, AccessTokenContextRelay accessTokenContextRelay) { return new PigxFeignClientInterceptor(oAuth2ClientContext, resource, accessTokenContextRelay); } diff --git a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/listener/AuthenticationFailureEventListener.java b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/listener/AuthenticationFailureEventListener.java index f77093500..14c185f7b 100644 --- a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/listener/AuthenticationFailureEventListener.java +++ b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/listener/AuthenticationFailureEventListener.java @@ -31,22 +31,21 @@ import javax.servlet.http.HttpServletResponse; /** * @author lengleng - * @date 2020/03/25 - * 认证失败事件监听器 + * @date 2020/03/25 认证失败事件监听器 */ public class AuthenticationFailureEventListener implements ApplicationListener { + @Autowired(required = false) private AuthenticationFailureHandler failureHandler; /** * Handle an application event. - * * @param event the event to respond to */ @Override public void onApplicationEvent(AbstractAuthenticationFailureEvent event) { - ServletRequestAttributes requestAttributes = (ServletRequestAttributes) - RequestContextHolder.getRequestAttributes(); + ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder + .getRequestAttributes(); HttpServletRequest request = requestAttributes.getRequest(); HttpServletResponse response = requestAttributes.getResponse(); @@ -58,4 +57,5 @@ public class AuthenticationFailureEventListener implements ApplicationListener { + @Autowired(required = false) private AuthenticationSuccessHandler successHandler; /** * Handle an application event. - * * @param event the event to respond to */ @Override public void onApplicationEvent(AuthenticationSuccessEvent event) { Authentication authentication = (Authentication) event.getSource(); if (successHandler != null && isUserAuthentication(authentication)) { - ServletRequestAttributes requestAttributes = (ServletRequestAttributes) - RequestContextHolder.getRequestAttributes(); + ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder + .getRequestAttributes(); HttpServletRequest request = requestAttributes.getRequest(); HttpServletResponse response = requestAttributes.getResponse(); @@ -57,8 +56,9 @@ public class AuthenticationSuccessEventListener implements ApplicationListener authentication) { return MobileAuthenticationToken.class.isAssignableFrom(authentication); } + } diff --git a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/mobile/MobileAuthenticationToken.java b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/mobile/MobileAuthenticationToken.java index be56bf8d9..5a870888c 100644 --- a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/mobile/MobileAuthenticationToken.java +++ b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/mobile/MobileAuthenticationToken.java @@ -26,8 +26,7 @@ import java.util.Collection; /** * @author lengleng - * @date 2018/1/9 - * 手机号登录令牌 + * @date 2018/1/9 手机号登录令牌 */ public class MobileAuthenticationToken extends AbstractAuthenticationToken { @@ -41,8 +40,7 @@ public class MobileAuthenticationToken extends AbstractAuthenticationToken { setAuthenticated(false); } - public MobileAuthenticationToken(Object principal, - Collection authorities) { + public MobileAuthenticationToken(Object principal, Collection authorities) { super(authorities); this.principal = principal; super.setAuthenticated(true); @@ -73,5 +71,5 @@ public class MobileAuthenticationToken extends AbstractAuthenticationToken { public void eraseCredentials() { super.eraseCredentials(); } -} +} diff --git a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/mobile/MobileSecurityConfigurer.java b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/mobile/MobileSecurityConfigurer.java index d09f45cbd..94a0bdbba 100644 --- a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/mobile/MobileSecurityConfigurer.java +++ b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/mobile/MobileSecurityConfigurer.java @@ -33,18 +33,21 @@ import org.springframework.security.web.authentication.UsernamePasswordAuthentic /** * @author lengleng - * @date 2018/8/5 - * 手机号登录配置入口 + * @date 2018/8/5 手机号登录配置入口 */ @Getter @Setter public class MobileSecurityConfigurer extends SecurityConfigurerAdapter { + @Autowired private ObjectMapper objectMapper; + @Autowired private AuthenticationEventPublisher defaultAuthenticationEventPublisher; + @Autowired private AuthenticationSuccessHandler mobileLoginSuccessHandler; + @Autowired private PigxUserDetailsService userDetailsService; @@ -58,7 +61,8 @@ public class MobileSecurityConfigurer extends SecurityConfigurerAdapterUser with the details required by * {@link DaoAuthenticationProvider}. - * - * @param id 用户ID - * @param deptId 部门ID - * @param tenantId 租户ID - * @param username the username presented to the - * DaoAuthenticationProvider - * @param password the password that should be presented to the - * DaoAuthenticationProvider - * @param enabled set to true if the user is enabled - * @param accountNonExpired set to true if the account has not expired + * @param id 用户ID + * @param deptId 部门ID + * @param tenantId 租户ID + * @param username the username presented to the + * DaoAuthenticationProvider + * @param password the password that should be presented to the + * DaoAuthenticationProvider + * @param enabled set to true if the user is enabled + * @param accountNonExpired set to true if the account has not expired * @param credentialsNonExpired set to true if the credentials have not - * expired - * @param accountNonLocked set to true if the account is not locked - * @param authorities the authorities that should be granted to the caller if they - * presented the correct username and password and the user is enabled. Not null. + * expired + * @param accountNonLocked set to true if the account is not locked + * @param authorities the authorities that should be granted to the caller if they + * presented the correct username and password and the user is enabled. Not null. * @throws IllegalArgumentException if a null value was passed either as - * a parameter or as an element in the GrantedAuthority collection + * a parameter or as an element in the GrantedAuthority collection */ - public PigxUser(Integer id, Integer deptId, String phone, String avatar, Integer tenantId, String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection authorities) { + public PigxUser(Integer id, Integer deptId, String phone, String avatar, Integer tenantId, String username, + String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, + boolean accountNonLocked, Collection authorities) { super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); this.id = id; this.deptId = deptId; @@ -93,4 +93,5 @@ public class PigxUser extends User { this.avatar = avatar; this.tenantId = tenantId; } + } diff --git a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/service/PigxUserDetailsService.java b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/service/PigxUserDetailsService.java index 58778add3..0fc4cbdb5 100644 --- a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/service/PigxUserDetailsService.java +++ b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/service/PigxUserDetailsService.java @@ -28,10 +28,10 @@ public interface PigxUserDetailsService extends UserDetailsService { /** * 根据社交登录code 登录 - * * @param code TYPE@CODE * @return UserDetails * @throws UsernameNotFoundException */ UserDetails loadUserBySocial(String code) throws UsernameNotFoundException; + } diff --git a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/social/QqSocialConfig.java b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/social/QqSocialConfig.java index 25f48c835..4685a9ae9 100644 --- a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/social/QqSocialConfig.java +++ b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/social/QqSocialConfig.java @@ -23,13 +23,15 @@ import org.springframework.context.annotation.Configuration; /** * @author lengleng - * @date 2018/8/16 - * qq登录配置信息 + * @date 2018/8/16 qq登录配置信息 */ @Data @Configuration @ConfigurationProperties(prefix = "social.qq") public class QqSocialConfig { + private String appid; + private String secret; + } diff --git a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/social/WxSocialConfig.java b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/social/WxSocialConfig.java index 988ecf7fb..6df159978 100644 --- a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/social/WxSocialConfig.java +++ b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/social/WxSocialConfig.java @@ -23,13 +23,15 @@ import org.springframework.context.annotation.Configuration; /** * @author lengleng - * @date 2018/8/16 - * 微信登录配置 + * @date 2018/8/16 微信登录配置 */ @Data @Configuration @ConfigurationProperties(prefix = "social.wx") public class WxSocialConfig { + private String appid; + private String secret; + } diff --git a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/util/AuthUtils.java b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/util/AuthUtils.java index 6856a6baf..d980c78a4 100644 --- a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/util/AuthUtils.java +++ b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/util/AuthUtils.java @@ -28,20 +28,18 @@ import java.nio.charset.StandardCharsets; /** * @author lengleng - * @date 2018/5/13 - * 认证授权相关工具类 + * @date 2018/5/13 认证授权相关工具类 */ @Slf4j @UtilityClass public class AuthUtils { + private final String BASIC_ = "Basic "; /** * 从header 请求中的clientId/clientsecect - * * @param header header中的参数 - * @throws RuntimeException if the Basic header is not present or is not valid - * Base64 + * @throws RuntimeException if the Basic header is not present or is not valid Base64 */ @SneakyThrows public String[] extractAndDecodeHeader(String header) { @@ -50,9 +48,9 @@ public class AuthUtils { byte[] decoded; try { decoded = Base64.decode(base64Token); - } catch (IllegalArgumentException e) { - throw new RuntimeException( - "Failed to decode basic authentication token"); + } + catch (IllegalArgumentException e) { + throw new RuntimeException("Failed to decode basic authentication token"); } String token = new String(decoded, StandardCharsets.UTF_8); @@ -62,12 +60,11 @@ public class AuthUtils { if (delim == -1) { throw new RuntimeException("Invalid basic authentication token"); } - return new String[]{token.substring(0, delim), token.substring(delim + 1)}; + return new String[] { token.substring(0, delim), token.substring(delim + 1) }; } /** * *从header 请求中的clientId/clientsecect - * * @param request * @return */ @@ -81,4 +78,5 @@ public class AuthUtils { return extractAndDecodeHeader(header); } + } diff --git a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/util/SecurityUtils.java b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/util/SecurityUtils.java index 6ba0e3419..5c19f084e 100644 --- a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/util/SecurityUtils.java +++ b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/util/SecurityUtils.java @@ -17,7 +17,6 @@ package com.pig4cloud.pigx.common.security.util; - import cn.hutool.core.util.StrUtil; import com.pig4cloud.pigx.common.core.constant.SecurityConstants; import com.pig4cloud.pigx.common.security.service.PigxUser; @@ -37,6 +36,7 @@ import java.util.List; */ @UtilityClass public class SecurityUtils { + /** * 获取Authentication */ @@ -46,7 +46,6 @@ public class SecurityUtils { /** * 获取用户 - * * @param authentication * @return PigxUser *

@@ -69,7 +68,6 @@ public class SecurityUtils { /** * 获取用户角色信息 - * * @return 角色集合 */ public List getRoles() { @@ -77,8 +75,7 @@ public class SecurityUtils { Collection authorities = authentication.getAuthorities(); List roleIds = new ArrayList<>(); - authorities.stream() - .filter(granted -> StrUtil.startWith(granted.getAuthority(), SecurityConstants.ROLE)) + authorities.stream().filter(granted -> StrUtil.startWith(granted.getAuthority(), SecurityConstants.ROLE)) .forEach(granted -> { String id = StrUtil.removePrefix(granted.getAuthority(), SecurityConstants.ROLE); roleIds.add(Integer.parseInt(id)); diff --git a/pigx-common/pigx-common-sentinel/src/main/java/com/pig4cloud/pigx/common/sentinel/SentinelAutoConfiguration.java b/pigx-common/pigx-common-sentinel/src/main/java/com/pig4cloud/pigx/common/sentinel/SentinelAutoConfiguration.java index 9456fe645..42866075a 100755 --- a/pigx-common/pigx-common-sentinel/src/main/java/com/pig4cloud/pigx/common/sentinel/SentinelAutoConfiguration.java +++ b/pigx-common/pigx-common-sentinel/src/main/java/com/pig4cloud/pigx/common/sentinel/SentinelAutoConfiguration.java @@ -60,4 +60,5 @@ public class SentinelAutoConfiguration { public RequestOriginParser requestOriginParser() { return new PigxHeaderRequestOriginParser(); } + } diff --git a/pigx-common/pigx-common-sentinel/src/main/java/com/pig4cloud/pigx/common/sentinel/feign/PigxSentinelFeign.java b/pigx-common/pigx-common-sentinel/src/main/java/com/pig4cloud/pigx/common/sentinel/feign/PigxSentinelFeign.java index 8546b0401..4ce9ec894 100644 --- a/pigx-common/pigx-common-sentinel/src/main/java/com/pig4cloud/pigx/common/sentinel/feign/PigxSentinelFeign.java +++ b/pigx-common/pigx-common-sentinel/src/main/java/com/pig4cloud/pigx/common/sentinel/feign/PigxSentinelFeign.java @@ -19,13 +19,13 @@ import java.lang.reflect.Method; import java.util.Map; /** - * 重写 {@link com.alibaba.cloud.sentinel.feign.SentinelFeign} - * 支持自动降级注入 + * 重写 {@link com.alibaba.cloud.sentinel.feign.SentinelFeign} 支持自动降级注入 * * @author lengleng * @date 2020/6/9 */ public final class PigxSentinelFeign { + private PigxSentinelFeign() { } @@ -34,8 +34,7 @@ public final class PigxSentinelFeign { return new PigxSentinelFeign.Builder(); } - public static final class Builder extends Feign.Builder - implements ApplicationContextAware { + public static final class Builder extends Feign.Builder implements ApplicationContextAware { private Contract contract = new Contract.Default(); @@ -44,8 +43,7 @@ public final class PigxSentinelFeign { private FeignContext feignContext; @Override - public Feign.Builder invocationHandlerFactory( - InvocationHandlerFactory invocationHandlerFactory) { + public Feign.Builder invocationHandlerFactory(InvocationHandlerFactory invocationHandlerFactory) { throw new UnsupportedOperationException(); } @@ -59,20 +57,16 @@ public final class PigxSentinelFeign { public Feign build() { super.invocationHandlerFactory(new InvocationHandlerFactory() { @Override - public InvocationHandler create(Target target, - Map dispatch) { + public InvocationHandler create(Target target, Map dispatch) { // using reflect get fallback and fallbackFactory properties from // FeignClientFactoryBean because FeignClientFactoryBean is a package // level class, we can not use it in our package Object feignClientFactoryBean = PigxSentinelFeign.Builder.this.applicationContext .getBean("&" + target.type().getName()); - Class fallback = (Class) getFieldValue(feignClientFactoryBean, - "fallback"); - Class fallbackFactory = (Class) getFieldValue(feignClientFactoryBean, - "fallbackFactory"); - String beanName = (String) getFieldValue(feignClientFactoryBean, - "contextId"); + Class fallback = (Class) getFieldValue(feignClientFactoryBean, "fallback"); + Class fallbackFactory = (Class) getFieldValue(feignClientFactoryBean, "fallbackFactory"); + String beanName = (String) getFieldValue(feignClientFactoryBean, "contextId"); if (!StringUtils.hasText(beanName)) { beanName = (String) getFieldValue(feignClientFactoryBean, "name"); } @@ -81,29 +75,23 @@ public final class PigxSentinelFeign { FallbackFactory fallbackFactoryInstance; // check fallback and fallbackFactory properties if (void.class != fallback) { - fallbackInstance = getFromContext(beanName, "fallback", fallback, - target.type()); + fallbackInstance = getFromContext(beanName, "fallback", fallback, target.type()); return new PigxSentinelInvocationHandler(target, dispatch, new FallbackFactory.Default(fallbackInstance)); } if (void.class != fallbackFactory) { - fallbackFactoryInstance = (FallbackFactory) getFromContext( - beanName, "fallbackFactory", fallbackFactory, - FallbackFactory.class); - return new PigxSentinelInvocationHandler(target, dispatch, - fallbackFactoryInstance); + fallbackFactoryInstance = (FallbackFactory) getFromContext(beanName, "fallbackFactory", + fallbackFactory, FallbackFactory.class); + return new PigxSentinelInvocationHandler(target, dispatch, fallbackFactoryInstance); } return new PigxSentinelInvocationHandler(target, dispatch); } - private Object getFromContext(String name, String type, - Class fallbackType, Class targetType) { - Object fallbackInstance = feignContext.getInstance(name, - fallbackType); + private Object getFromContext(String name, String type, Class fallbackType, Class targetType) { + Object fallbackInstance = feignContext.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)); + "No %s instance of type %s found for feign client %s", type, fallbackType, name)); } if (!targetType.isAssignableFrom(fallbackType)) { @@ -124,15 +112,15 @@ public final class PigxSentinelFeign { field.setAccessible(true); try { return field.get(instance); - } catch (IllegalAccessException e) { + } + catch (IllegalAccessException e) { // ignore } return null; } @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; feignContext = this.applicationContext.getBean(FeignContext.class); } diff --git a/pigx-common/pigx-common-sentinel/src/main/java/com/pig4cloud/pigx/common/sentinel/feign/PigxSentinelInvocationHandler.java b/pigx-common/pigx-common-sentinel/src/main/java/com/pig4cloud/pigx/common/sentinel/feign/PigxSentinelInvocationHandler.java index c8ebfb8ef..76c9236b8 100644 --- a/pigx-common/pigx-common-sentinel/src/main/java/com/pig4cloud/pigx/common/sentinel/feign/PigxSentinelInvocationHandler.java +++ b/pigx-common/pigx-common-sentinel/src/main/java/com/pig4cloud/pigx/common/sentinel/feign/PigxSentinelInvocationHandler.java @@ -26,17 +26,20 @@ import java.util.Map; import static feign.Util.checkNotNull; /** - * 重写 {@link com.alibaba.cloud.sentinel.feign.SentinelInvocationHandler} - * 支持自动降级注入 + * 重写 {@link com.alibaba.cloud.sentinel.feign.SentinelInvocationHandler} 支持自动降级注入 * * @author lengleng * @date 2020/6/9 */ @Slf4j public class PigxSentinelInvocationHandler 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 dispatch; @@ -46,7 +49,7 @@ public class PigxSentinelInvocationHandler implements InvocationHandler { private Map fallbackMethodMap; PigxSentinelInvocationHandler(Target target, Map dispatch, - FallbackFactory fallbackFactory) { + FallbackFactory fallbackFactory) { this.target = checkNotNull(target, "target"); this.dispatch = checkNotNull(dispatch, "dispatch"); this.fallbackFactory = fallbackFactory; @@ -59,19 +62,20 @@ public class PigxSentinelInvocationHandler implements InvocationHandler { } @Override - public Object invoke(final Object proxy, final Method method, final Object[] args) - throws Throwable { + public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { if (EQUALS.equals(method.getName())) { try { - Object otherHandler = args.length > 0 && args[0] != null - ? Proxy.getInvocationHandler(args[0]) : null; + Object otherHandler = args.length > 0 && args[0] != null ? Proxy.getInvocationHandler(args[0]) : null; return equals(otherHandler); - } catch (IllegalArgumentException e) { + } + catch (IllegalArgumentException e) { return false; } - } else if (HASH_CODE.equals(method.getName())) { + } + else if (HASH_CODE.equals(method.getName())) { return hashCode(); - } else if (TO_STRING.equals(method.getName())) { + } + else if (TO_STRING.equals(method.getName())) { return toString(); } @@ -81,53 +85,60 @@ public class PigxSentinelInvocationHandler implements InvocationHandler { 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)); + .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(); + } + 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) { + } + catch (Throwable ex) { // fallback handle if (!BlockException.isBlockException(ex)) { Tracer.trace(ex); } if (fallbackFactory != null) { try { - Object fallbackResult = fallbackMethodMap.get(method) - .invoke(fallbackFactory.create(ex), args); + Object fallbackResult = fallbackMethodMap.get(method).invoke(fallbackFactory.create(ex), + args); return fallbackResult; - } catch (IllegalAccessException e) { + } + catch (IllegalAccessException e) { // shouldn't happen as method is public due to being an // interface throw new AssertionError(e); - } catch (InvocationTargetException e) { + } + catch (InvocationTargetException e) { throw new AssertionError(e.getCause()); } - } else { + } + else { // 若是R类型 执行自动降级返回R if (R.class == method.getReturnType()) { log.error("feign 服务间调用异常", ex); return R.failed(ex.getLocalizedMessage()); - } else { + } + else { throw ex; } } - } finally { + } + finally { if (entry != null) { entry.exit(1, args); } ContextUtil.exit(); } } - } else { + } + else { // other target type using default strategy result = methodHandler.invoke(args); } @@ -162,4 +173,5 @@ public class PigxSentinelInvocationHandler implements InvocationHandler { } return result; } + } diff --git a/pigx-common/pigx-common-sentinel/src/main/java/com/pig4cloud/pigx/common/sentinel/handle/PigxUrlBlockHandler.java b/pigx-common/pigx-common-sentinel/src/main/java/com/pig4cloud/pigx/common/sentinel/handle/PigxUrlBlockHandler.java index 691e2c618..96cc62432 100644 --- a/pigx-common/pigx-common-sentinel/src/main/java/com/pig4cloud/pigx/common/sentinel/handle/PigxUrlBlockHandler.java +++ b/pigx-common/pigx-common-sentinel/src/main/java/com/pig4cloud/pigx/common/sentinel/handle/PigxUrlBlockHandler.java @@ -43,7 +43,7 @@ public class PigxUrlBlockHandler implements BlockExceptionHandler { response.setContentType(ContentType.JSON.toString()); response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value()); - response.getWriter().print( - JSONUtil.toJsonStr(R.failed(e.getMessage()))); + response.getWriter().print(JSONUtil.toJsonStr(R.failed(e.getMessage()))); } + } diff --git a/pigx-common/pigx-common-sentinel/src/main/java/com/pig4cloud/pigx/common/sentinel/parser/PigxHeaderRequestOriginParser.java b/pigx-common/pigx-common-sentinel/src/main/java/com/pig4cloud/pigx/common/sentinel/parser/PigxHeaderRequestOriginParser.java index 2b4308f56..e9b6337bf 100644 --- a/pigx-common/pigx-common-sentinel/src/main/java/com/pig4cloud/pigx/common/sentinel/parser/PigxHeaderRequestOriginParser.java +++ b/pigx-common/pigx-common-sentinel/src/main/java/com/pig4cloud/pigx/common/sentinel/parser/PigxHeaderRequestOriginParser.java @@ -28,6 +28,7 @@ import javax.servlet.http.HttpServletRequest; * sentinel 请求头解析判断 */ public class PigxHeaderRequestOriginParser implements RequestOriginParser { + /** * 请求头获取allow */ @@ -35,7 +36,6 @@ public class PigxHeaderRequestOriginParser implements RequestOriginParser { /** * Parse the origin from given HTTP request. - * * @param request HTTP request * @return parsed origin */ @@ -43,4 +43,5 @@ public class PigxHeaderRequestOriginParser implements RequestOriginParser { public String parseOrigin(HttpServletRequest request) { return request.getHeader(ALLOW); } + } diff --git a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/SequenceAutoConfiguration.java b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/SequenceAutoConfiguration.java index d668df866..79656edbd 100644 --- a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/SequenceAutoConfiguration.java +++ b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/SequenceAutoConfiguration.java @@ -37,17 +37,14 @@ public class SequenceAutoConfiguration { /** * snowflak 算法作为发号器实现 - * * @param properties * @return */ @Bean @ConditionalOnBean(SequenceSnowflakeProperties.class) public Sequence snowflakeSequence(SequenceSnowflakeProperties properties) { - return SnowflakeSeqBuilder - .create() - .datacenterId(properties.getDatacenterId()) - .workerId(properties.getWorkerId()) - .build(); + return SnowflakeSeqBuilder.create().datacenterId(properties.getDatacenterId()) + .workerId(properties.getWorkerId()).build(); } + } \ No newline at end of file diff --git a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/builder/DbSeqBuilder.java b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/builder/DbSeqBuilder.java index c0cd8bb4a..3da766a6c 100755 --- a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/builder/DbSeqBuilder.java +++ b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/builder/DbSeqBuilder.java @@ -1,6 +1,5 @@ package com.pig4cloud.pigx.common.sequence.builder; - import com.pig4cloud.pigx.common.sequence.range.BizName; import com.pig4cloud.pigx.common.sequence.range.impl.db.DbSeqRangeMgr; import com.pig4cloud.pigx.common.sequence.sequence.Sequence; @@ -24,14 +23,17 @@ public class DbSeqBuilder implements SeqBuilder { * 业务名称[必选] */ private BizName bizName; + /** * 存放序列号步长的表[可选:默认:sequence] */ private String tableName = "sequence"; + /** * 并发是数据使用了乐观策略,这个是失败重试的次数[可选:默认:100] */ private int retryTimes = 100; + /** * 获取range步长[可选:默认:1000] */ @@ -49,7 +51,7 @@ public class DbSeqBuilder implements SeqBuilder { @Override public Sequence build() { - //利用DB获取区间管理器 + // 利用DB获取区间管理器 DbSeqRangeMgr dbSeqRangeMgr = new DbSeqRangeMgr(); dbSeqRangeMgr.setDataSource(this.dataSource); dbSeqRangeMgr.setTableName(this.tableName); @@ -57,7 +59,7 @@ public class DbSeqBuilder implements SeqBuilder { dbSeqRangeMgr.setStep(this.step); dbSeqRangeMgr.setStepStart(stepStart); dbSeqRangeMgr.init(); - //构建序列号生成器 + // 构建序列号生成器 DefaultRangeSequence sequence = new DefaultRangeSequence(); sequence.setName(this.bizName); sequence.setSeqRangeMgr(dbSeqRangeMgr); @@ -94,5 +96,4 @@ public class DbSeqBuilder implements SeqBuilder { return this; } - } diff --git a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/builder/RedisSeqBuilder.java b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/builder/RedisSeqBuilder.java index efed9b976..657390b7c 100755 --- a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/builder/RedisSeqBuilder.java +++ b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/builder/RedisSeqBuilder.java @@ -1,6 +1,5 @@ package com.pig4cloud.pigx.common.sequence.builder; - import com.pig4cloud.pigx.common.sequence.range.BizName; import com.pig4cloud.pigx.common.sequence.range.impl.redis.RedisSeqRangeMgr; import com.pig4cloud.pigx.common.sequence.sequence.Sequence; @@ -17,18 +16,22 @@ public class RedisSeqBuilder implements SeqBuilder { * 连接redis的IP[必选] */ private String ip; + /** * 连接redis的port[必选] */ private int port; + /** * 业务名称[必选] */ private BizName bizName; + /** * 认证权限,看redis是否配置了需要密码auth[可选] */ private String auth; + /** * 获取range步长[可选,默认:1000] */ @@ -46,7 +49,7 @@ public class RedisSeqBuilder implements SeqBuilder { @Override public Sequence build() { - //利用Redis获取区间管理器 + // 利用Redis获取区间管理器 RedisSeqRangeMgr redisSeqRangeMgr = new RedisSeqRangeMgr(); redisSeqRangeMgr.setIp(this.ip); redisSeqRangeMgr.setPort(this.port); @@ -54,7 +57,7 @@ public class RedisSeqBuilder implements SeqBuilder { redisSeqRangeMgr.setStep(this.step); redisSeqRangeMgr.setStepStart(stepStart); redisSeqRangeMgr.init(); - //构建序列号生成器 + // 构建序列号生成器 DefaultRangeSequence sequence = new DefaultRangeSequence(); sequence.setName(this.bizName); sequence.setSeqRangeMgr(redisSeqRangeMgr); diff --git a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/builder/SeqBuilder.java b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/builder/SeqBuilder.java index e5eb05254..c5d2954d9 100755 --- a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/builder/SeqBuilder.java +++ b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/builder/SeqBuilder.java @@ -1,17 +1,16 @@ package com.pig4cloud.pigx.common.sequence.builder; - import com.pig4cloud.pigx.common.sequence.sequence.Sequence; /** * 序列号生成器构建者 + * * @author xuan on 2018/5/30. */ public interface SeqBuilder { /** * 构建一个序列号生成器 - * * @return 序列号生成器 */ Sequence build(); diff --git a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/builder/SnowflakeSeqBuilder.java b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/builder/SnowflakeSeqBuilder.java index eabb641c0..b4b9ba74f 100755 --- a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/builder/SnowflakeSeqBuilder.java +++ b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/builder/SnowflakeSeqBuilder.java @@ -1,11 +1,11 @@ package com.pig4cloud.pigx.common.sequence.builder; - import com.pig4cloud.pigx.common.sequence.sequence.Sequence; import com.pig4cloud.pigx.common.sequence.sequence.impl.SnowflakeSequence; /** * 基于雪花算法,序列号生成器构建者 + * * @author xuan on 2018/5/30. */ public class SnowflakeSeqBuilder implements SeqBuilder { @@ -14,6 +14,7 @@ public class SnowflakeSeqBuilder implements SeqBuilder { * 数据中心ID,值的范围在[0,31]之间,一般可以设置机房的IDC[必选] */ private long datacenterId; + /** * 工作机器ID,值的范围在[0,31]之间,一般可以设置机器编号[必选] */ diff --git a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/exception/SeqException.java b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/exception/SeqException.java index b60093432..3575211cc 100755 --- a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/exception/SeqException.java +++ b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/exception/SeqException.java @@ -2,6 +2,7 @@ package com.pig4cloud.pigx.common.sequence.exception; /** * 序列号生成异常 + * * @author xuan on 2018/1/10. */ public class SeqException extends RuntimeException { diff --git a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/properties/BaseSequenceProperties.java b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/properties/BaseSequenceProperties.java index 05c23e836..443ca0e27 100644 --- a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/properties/BaseSequenceProperties.java +++ b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/properties/BaseSequenceProperties.java @@ -10,6 +10,7 @@ import lombok.Data; */ @Data class BaseSequenceProperties { + /** * 获取range步长[可选,默认:1000] */ @@ -24,4 +25,5 @@ class BaseSequenceProperties { * 业务名称 */ private String bizName = "pigx"; + } diff --git a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/properties/SequenceDbProperties.java b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/properties/SequenceDbProperties.java index e2f1c333f..9c1fc3231 100644 --- a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/properties/SequenceDbProperties.java +++ b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/properties/SequenceDbProperties.java @@ -19,10 +19,12 @@ import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix = "pigx.xsequence.db") public class SequenceDbProperties extends BaseSequenceProperties { + /** * 表名称 */ private String tableName = "pigx_sequence"; + /** * 重试次数 */ diff --git a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/properties/SequenceSnowflakeProperties.java b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/properties/SequenceSnowflakeProperties.java index ee6d90bb8..489f713a4 100644 --- a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/properties/SequenceSnowflakeProperties.java +++ b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/properties/SequenceSnowflakeProperties.java @@ -19,8 +19,10 @@ public class SequenceSnowflakeProperties extends BaseSequenceProperties { * 数据中心ID,值的范围在[0,31]之间,一般可以设置机房的IDC[必选] */ private long datacenterId; + /** * 工作机器ID,值的范围在[0,31]之间,一般可以设置机器编号[必选] */ private long workerId; + } diff --git a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/range/BizName.java b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/range/BizName.java index 04d0ba57a..831947790 100644 --- a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/range/BizName.java +++ b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/range/BizName.java @@ -7,9 +7,9 @@ package com.pig4cloud.pigx.common.sequence.range; * 名称生成器 */ public interface BizName { + /** * 生成名称 - * * @return 返回文本序号 */ String create(); diff --git a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/range/SeqRange.java b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/range/SeqRange.java index 4ab04926c..cb9a408af 100755 --- a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/range/SeqRange.java +++ b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/range/SeqRange.java @@ -4,6 +4,7 @@ import java.util.concurrent.atomic.AtomicLong; /** * 序列号区间对象模型 + * * @author xuan on 2018/1/10. */ public class SeqRange { @@ -12,14 +13,17 @@ public class SeqRange { * 区间的序列号开始值 */ private final long min; + /** * 区间的序列号结束值 */ private final long max; + /** * 区间的序列号当前值 */ private final AtomicLong value; + /** * 区间的序列号是否分配完毕,每次分配完毕就会去重新获取一个新的区间 */ @@ -33,7 +37,6 @@ public class SeqRange { /** * 返回并递增下一个序列号 - * * @return 下一个序列号,如果返回-1表示序列号分配完毕 */ public long getAndIncrement() { diff --git a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/range/SeqRangeMgr.java b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/range/SeqRangeMgr.java index 7590461fe..4bffead00 100755 --- a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/range/SeqRangeMgr.java +++ b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/range/SeqRangeMgr.java @@ -1,17 +1,16 @@ package com.pig4cloud.pigx.common.sequence.range; - import com.pig4cloud.pigx.common.sequence.exception.SeqException; /** * 区间管理器 + * * @author xuan on 2018/1/10. */ public interface SeqRangeMgr { /** * 获取指定区间名的下一个区间 - * * @param name 区间名 * @return 返回区间 * @throws SeqException 异常 @@ -22,4 +21,5 @@ public interface SeqRangeMgr { * 初始化 */ void init(); + } diff --git a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/range/impl/db/BaseDbHelper.java b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/range/impl/db/BaseDbHelper.java index a413b8c34..3385e97e2 100755 --- a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/range/impl/db/BaseDbHelper.java +++ b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/range/impl/db/BaseDbHelper.java @@ -1,6 +1,5 @@ package com.pig4cloud.pigx.common.sequence.range.impl.db; - import com.pig4cloud.pigx.common.sequence.exception.SeqException; import javax.sql.DataSource; @@ -8,27 +7,30 @@ import java.sql.*; /** * 操作DB帮助类 + * * @author xuan on 2018/4/29. */ abstract class BaseDbHelper { private static final long DELTA = 100000000L; - private final static String SQL_CREATE_TABLE = - "CREATE TABLE IF NOT EXISTS #tableName(" + "id bigint(20) NOT NULL AUTO_INCREMENT," - + "value bigint(20) NOT NULL," + "name varchar(32) NOT NULL," + "gmt_create DATETIME NOT NULL," - + "gmt_modified DATETIME NOT NULL," + "PRIMARY KEY (`id`),UNIQUE uk_name (`name`)" + ")"; - private final static String SQL_INSERT_RANGE = - "INSERT IGNORE INTO #tableName(name,value,gmt_create,gmt_modified)" + " VALUE(?,?,?,?)"; - private final static String SQL_UPDATE_RANGE = - "UPDATE #tableName SET value=?,gmt_modified=? WHERE name=? AND " + "value=?"; + private final static String SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS #tableName(" + + "id bigint(20) NOT NULL AUTO_INCREMENT," + "value bigint(20) NOT NULL," + "name varchar(32) NOT NULL," + + "gmt_create DATETIME NOT NULL," + "gmt_modified DATETIME NOT NULL," + + "PRIMARY KEY (`id`),UNIQUE uk_name (`name`)" + ")"; + + private final static String SQL_INSERT_RANGE = "INSERT IGNORE INTO #tableName(name,value,gmt_create,gmt_modified)" + + " VALUE(?,?,?,?)"; + + private final static String SQL_UPDATE_RANGE = "UPDATE #tableName SET value=?,gmt_modified=? WHERE name=? AND " + + "value=?"; + private final static String SQL_SELECT_RANGE = "SELECT value FROM #tableName WHERE name=?"; /** * 创建表 - * * @param dataSource DB来源 - * @param tableName 表名 + * @param tableName 表名 */ static void createTable(DataSource dataSource, String tableName) { @@ -39,9 +41,11 @@ abstract class BaseDbHelper { conn = dataSource.getConnection(); stmt = conn.createStatement(); stmt.executeUpdate(SQL_CREATE_TABLE.replace("#tableName", tableName)); - } catch (SQLException e) { + } + catch (SQLException e) { throw new SeqException(e); - } finally { + } + finally { closeQuietly(stmt); closeQuietly(conn); } @@ -49,11 +53,10 @@ abstract class BaseDbHelper { /** * 插入数据区间 - * * @param dataSource DB来源 - * @param tableName 表名 - * @param name 区间名称 - * @param stepStart 初始位置 + * @param tableName 表名 + * @param name 区间名称 + * @param stepStart 初始位置 */ private static void insertRange(DataSource dataSource, String tableName, String name, long stepStart) { @@ -68,9 +71,11 @@ abstract class BaseDbHelper { stmt.setTimestamp(3, new Timestamp(System.currentTimeMillis())); stmt.setTimestamp(4, new Timestamp(System.currentTimeMillis())); stmt.executeUpdate(); - } catch (SQLException e) { + } + catch (SQLException e) { throw new SeqException(e); - } finally { + } + finally { closeQuietly(stmt); closeQuietly(conn); } @@ -78,12 +83,11 @@ abstract class BaseDbHelper { /** * 更新区间,乐观策略 - * * @param dataSource DB来源 - * @param tableName 表名 - * @param newValue 更新新数据 - * @param oldValue 更新旧数据 - * @param name 区间名称 + * @param tableName 表名 + * @param newValue 更新新数据 + * @param oldValue 更新旧数据 + * @param name 区间名称 * @return 成功/失败 */ static boolean updateRange(DataSource dataSource, String tableName, Long newValue, Long oldValue, String name) { @@ -100,9 +104,11 @@ abstract class BaseDbHelper { stmt.setLong(4, oldValue); int affectedRows = stmt.executeUpdate(); return affectedRows > 0; - } catch (SQLException e) { + } + catch (SQLException e) { throw new SeqException(e); - } finally { + } + finally { closeQuietly(stmt); closeQuietly(conn); } @@ -110,11 +116,10 @@ abstract class BaseDbHelper { /** * 查询区间,如果区间不存在,会新增一个区间,并返回null,由上层重新执行 - * * @param dataSource DB来源 - * @param tableName 来源 - * @param name 区间名称 - * @param stepStart 初始位置 + * @param tableName 来源 + * @param name 区间名称 + * @param stepStart 初始位置 * @return 区间值 */ static Long selectRange(DataSource dataSource, String tableName, String name, long stepStart) { @@ -130,29 +135,30 @@ abstract class BaseDbHelper { rs = stmt.executeQuery(); if (!rs.next()) { - //没有此类型数据,需要初始化 + // 没有此类型数据,需要初始化 insertRange(dataSource, tableName, name, stepStart); return null; } oldValue = rs.getLong(1); if (oldValue < 0) { - String msg = - "Sequence value cannot be less than zero, value = " + oldValue + ", please check table sequence" - + tableName; + String msg = "Sequence value cannot be less than zero, value = " + oldValue + + ", please check table sequence" + tableName; throw new SeqException(msg); } if (oldValue > Long.MAX_VALUE - DELTA) { - String msg = - "Sequence value overflow, value = " + oldValue + ", please check table sequence" + tableName; + String msg = "Sequence value overflow, value = " + oldValue + ", please check table sequence" + + tableName; throw new SeqException(msg); } return oldValue; - } catch (SQLException e) { + } + catch (SQLException e) { throw new SeqException(e); - } finally { + } + finally { closeQuietly(rs); closeQuietly(stmt); closeQuietly(conn); @@ -163,8 +169,9 @@ abstract class BaseDbHelper { if (null != closeable) { try { closeable.close(); - } catch (Throwable e) { - //Ignore + } + catch (Throwable e) { + // Ignore } } } diff --git a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/range/impl/db/DbSeqRangeMgr.java b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/range/impl/db/DbSeqRangeMgr.java index ca9ee099d..efcddb55d 100755 --- a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/range/impl/db/DbSeqRangeMgr.java +++ b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/range/impl/db/DbSeqRangeMgr.java @@ -1,6 +1,5 @@ package com.pig4cloud.pigx.common.sequence.range.impl.db; - import com.pig4cloud.pigx.common.sequence.exception.SeqException; import com.pig4cloud.pigx.common.sequence.range.SeqRange; import com.pig4cloud.pigx.common.sequence.range.SeqRangeMgr; @@ -9,6 +8,7 @@ import javax.sql.DataSource; /** * DB区间管理器 + * * @author xuan on 2018/4/29. */ public class DbSeqRangeMgr implements SeqRangeMgr { @@ -17,18 +17,22 @@ public class DbSeqRangeMgr implements SeqRangeMgr { * 区间步长 */ private int step = 1000; + /** * 区间起始位置,真实从stepStart+1开始 */ private long stepStart = 0; + /** * 获取区间失败重试次数 */ private int retryTimes = 100; + /** * DB来源 */ private DataSource dataSource; + /** * 表名,默认range */ @@ -47,7 +51,7 @@ public class DbSeqRangeMgr implements SeqRangeMgr { oldValue = BaseDbHelper.selectRange(getDataSource(), getRealTableName(), name, getStepStart()); if (null == oldValue) { - //区间不存在,重试 + // 区间不存在,重试 continue; } @@ -56,7 +60,7 @@ public class DbSeqRangeMgr implements SeqRangeMgr { if (BaseDbHelper.updateRange(getDataSource(), getRealTableName(), newValue, oldValue, name)) { return new SeqRange(oldValue + 1, newValue); } - //else 失败重试 + // else 失败重试 } throw new SeqException("Retried too many times, retryTimes = " + getRetryTimes()); @@ -94,7 +98,7 @@ public class DbSeqRangeMgr implements SeqRangeMgr { } } - ////////getter and setter + //////// getter and setter public int getStep() { return step; diff --git a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/range/impl/name/DateBizName.java b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/range/impl/name/DateBizName.java index ee78d136c..97cf51f23 100644 --- a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/range/impl/name/DateBizName.java +++ b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/range/impl/name/DateBizName.java @@ -14,6 +14,7 @@ import lombok.NoArgsConstructor; @NoArgsConstructor @AllArgsConstructor public class DateBizName implements BizName { + private String bizName; /** @@ -23,4 +24,5 @@ public class DateBizName implements BizName { public String create() { return bizName + DateUtil.today(); } + } \ No newline at end of file diff --git a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/range/impl/name/DefaultBizName.java b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/range/impl/name/DefaultBizName.java index 3c7e160c3..38433605e 100644 --- a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/range/impl/name/DefaultBizName.java +++ b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/range/impl/name/DefaultBizName.java @@ -5,8 +5,7 @@ import lombok.AllArgsConstructor; /** * @author lengleng - * @date 2019-05-26 - * 根据传入返回bizname + * @date 2019-05-26 根据传入返回bizname */ @AllArgsConstructor public class DefaultBizName implements BizName { diff --git a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/range/impl/redis/RedisSeqRangeMgr.java b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/range/impl/redis/RedisSeqRangeMgr.java index 38bc4d48c..8f3a24c6a 100755 --- a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/range/impl/redis/RedisSeqRangeMgr.java +++ b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/range/impl/redis/RedisSeqRangeMgr.java @@ -27,6 +27,7 @@ public class RedisSeqRangeMgr implements SeqRangeMgr { * IP */ private String ip; + /** * PORT */ @@ -48,8 +49,7 @@ public class RedisSeqRangeMgr implements SeqRangeMgr { private long stepStart = 0; /** - * 标记业务key是否存在,如果false,在取nextRange时,会取check一把 - * 这个boolean只为提高性能,不用每次都取redis check + * 标记业务key是否存在,如果false,在取nextRange时,会取check一把 这个boolean只为提高性能,不用每次都取redis check */ private volatile boolean keyAlreadyExist; @@ -58,7 +58,7 @@ public class RedisSeqRangeMgr implements SeqRangeMgr { if (!keyAlreadyExist) { Boolean isExists = jedis.exists(getRealKey(name)); if (!isExists) { - //第一次不存在,进行初始化,setnx不存在就set,存在就忽略 + // 第一次不存在,进行初始化,setnx不存在就set,存在就忽略 jedis.setnx(getRealKey(name), String.valueOf(stepStart)); } keyAlreadyExist = true; @@ -134,4 +134,5 @@ public class RedisSeqRangeMgr implements SeqRangeMgr { public void setStepStart(long stepStart) { this.stepStart = stepStart; } + } diff --git a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/sequence/RangeSequence.java b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/sequence/RangeSequence.java index a1576830b..eeecb7a6a 100755 --- a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/sequence/RangeSequence.java +++ b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/sequence/RangeSequence.java @@ -1,26 +1,25 @@ package com.pig4cloud.pigx.common.sequence.sequence; - import com.pig4cloud.pigx.common.sequence.range.BizName; import com.pig4cloud.pigx.common.sequence.range.SeqRangeMgr; /** * 序列号区间生成器接口 + * * @author xuan on 2018/5/6. */ public interface RangeSequence extends Sequence { /** * 设置区间管理器 - * * @param seqRangeMgr 区间管理器 */ void setSeqRangeMgr(SeqRangeMgr seqRangeMgr); /** * 设置获取序列号名称 - * * @param name 名称 */ void setName(BizName name); + } diff --git a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/sequence/Sequence.java b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/sequence/Sequence.java index 63594bf6f..30266eaac 100755 --- a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/sequence/Sequence.java +++ b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/sequence/Sequence.java @@ -1,6 +1,5 @@ package com.pig4cloud.pigx.common.sequence.sequence; - import com.pig4cloud.pigx.common.sequence.exception.SeqException; /** @@ -12,7 +11,6 @@ public interface Sequence { /** * 生成下一个序列号 - * * @return 序列号 * @throws SeqException 序列号异常 */ @@ -20,9 +18,9 @@ public interface Sequence { /** * 下一个生成序号(带格式) - * * @return * @throws SeqException */ String nextNo() throws SeqException; + } diff --git a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/sequence/impl/DefaultRangeSequence.java b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/sequence/impl/DefaultRangeSequence.java index 63b99a707..38c39e7be 100755 --- a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/sequence/impl/DefaultRangeSequence.java +++ b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/sequence/impl/DefaultRangeSequence.java @@ -1,6 +1,5 @@ package com.pig4cloud.pigx.common.sequence.sequence.impl; - import cn.hutool.core.date.DatePattern; import cn.hutool.core.date.DateUtil; import com.pig4cloud.pigx.common.sequence.exception.SeqException; @@ -51,7 +50,7 @@ public class DefaultRangeSequence implements RangeSequence { String name = bizName.create(); currentRange = seqRangeMap.get(name); - //当前区间不存在,重新获取一个区间 + // 当前区间不存在,重新获取一个区间 if (null == currentRange) { lock.lock(); try { @@ -59,17 +58,18 @@ public class DefaultRangeSequence implements RangeSequence { currentRange = seqRangeMgr.nextRange(name); seqRangeMap.put(name, currentRange); } - } finally { + } + finally { lock.unlock(); } } - //当value值为-1时,表明区间的序列号已经分配完,需要重新获取区间 + // 当value值为-1时,表明区间的序列号已经分配完,需要重新获取区间 long value = currentRange.getAndIncrement(); if (value == -1) { lock.lock(); try { - for (; ; ) { + for (;;) { if (currentRange.isOver()) { currentRange = seqRangeMgr.nextRange(name); } @@ -81,7 +81,8 @@ public class DefaultRangeSequence implements RangeSequence { break; } - } finally { + } + finally { lock.unlock(); } } @@ -95,7 +96,6 @@ public class DefaultRangeSequence implements RangeSequence { /** * 下一个生成序号(带格式) - * * @return * @throws SeqException */ @@ -115,4 +115,3 @@ public class DefaultRangeSequence implements RangeSequence { } } - diff --git a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/sequence/impl/SnowflakeSequence.java b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/sequence/impl/SnowflakeSequence.java index d2355cb1d..a6b4ca5fb 100755 --- a/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/sequence/impl/SnowflakeSequence.java +++ b/pigx-common/pigx-common-sequence/src/main/java/com/pig4cloud/pigx/common/sequence/sequence/impl/SnowflakeSequence.java @@ -1,24 +1,16 @@ package com.pig4cloud.pigx.common.sequence.sequence.impl; - import com.pig4cloud.pigx.common.sequence.exception.SeqException; import com.pig4cloud.pigx.common.sequence.sequence.Sequence; /** - * 使用雪花算法 - * 一个long类型的数据,64位。以下是每位的具体含义。 - *
- * snowflake的结构如下(每部分用-分开): - *
- * 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 - *
- * (1)第一位为未使用 - * (2)接下来的41位为毫秒级时间(41位的长度可以使用69年) - * (3)然后是5位datacenterId - * (4)5位workerId - * (5)最后12位是毫秒内的计数(12位的计数顺序号支持每个节点每毫秒产生4096个ID序号) - *
+ * 使用雪花算法 一个long类型的数据,64位。以下是每位的具体含义。
+ * snowflake的结构如下(每部分用-分开):
+ * 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000
+ * (1)第一位为未使用 (2)接下来的41位为毫秒级时间(41位的长度可以使用69年) (3)然后是5位datacenterId (4)5位workerId + * (5)最后12位是毫秒内的计数(12位的计数顺序号支持每个节点每毫秒产生4096个ID序号)
* 一共加起来刚好64位,为一个Long型。(转换成字符串长度为18) + * * @author xuan on 2018/5/9. */ public class SnowflakeSequence implements Sequence { @@ -97,37 +89,35 @@ public class SnowflakeSequence implements Sequence { public synchronized long nextValue() throws SeqException { long timestamp = timeGen(); - //如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过这个时候应当抛出异常 + // 如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过这个时候应当抛出异常 if (timestamp < lastTimestamp) { throw new SeqException("[SnowflakeSequence-nextValue] 当前时间小于上次生成序列号的时间,时间被回退了,请确认服务器时间的设置."); } - //如果是同一时间生成的,则进行毫秒内序列 + // 如果是同一时间生成的,则进行毫秒内序列 if (lastTimestamp == timestamp) { sequence = (sequence + 1) & sequenceMask; - //毫秒内序列溢出 + // 毫秒内序列溢出 if (sequence == 0) { - //阻塞到下一个毫秒,获得新的时间戳 + // 阻塞到下一个毫秒,获得新的时间戳 timestamp = tilNextMillis(lastTimestamp); } - } else { - //时间戳改变,毫秒内序列重置 + } + else { + // 时间戳改变,毫秒内序列重置 sequence = 0L; } - //上次生成ID的时间截 + // 上次生成ID的时间截 lastTimestamp = timestamp; - //移位并通过或运算拼到一起组成64位的ID - return ((timestamp - twepoch) << timestampLeftShift) - | (datacenterId << datacenterIdShift) - | (workerId << workerIdShift) - | sequence; + // 移位并通过或运算拼到一起组成64位的ID + return ((timestamp - twepoch) << timestampLeftShift) | (datacenterId << datacenterIdShift) + | (workerId << workerIdShift) | sequence; } /** * 阻塞到下一个毫秒,直到获得新的时间戳 - * * @param lastTimestamp 上次生成ID的时间截 * @return 当前时间戳 */ @@ -141,7 +131,6 @@ public class SnowflakeSequence implements Sequence { /** * 返回以毫秒为单位的当前时间 - * * @return 当前时间(毫秒) */ private long timeGen() { @@ -166,7 +155,6 @@ public class SnowflakeSequence implements Sequence { /** * 下一个生成序号(带格式) - * * @return * @throws SeqException */ @@ -174,4 +162,5 @@ public class SnowflakeSequence implements Sequence { public String nextNo() throws SeqException { return String.valueOf(nextValue()); } + } diff --git a/pigx-common/pigx-common-swagger/src/main/java/com/pig4cloud/pigx/common/swagger/annotation/EnablePigxSwagger2.java b/pigx-common/pigx-common-swagger/src/main/java/com/pig4cloud/pigx/common/swagger/annotation/EnablePigxSwagger2.java index 9285ad651..ed708ac7d 100644 --- a/pigx-common/pigx-common-swagger/src/main/java/com/pig4cloud/pigx/common/swagger/annotation/EnablePigxSwagger2.java +++ b/pigx-common/pigx-common-swagger/src/main/java/com/pig4cloud/pigx/common/swagger/annotation/EnablePigxSwagger2.java @@ -24,13 +24,13 @@ import java.lang.annotation.*; /** * @author lengleng - * @date 2018/7/21 - * 开启pigx swagger + * @date 2018/7/21 开启pigx swagger */ -@Target({ElementType.TYPE}) +@Target({ ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited -@Import({SwaggerAutoConfiguration.class}) +@Import({ SwaggerAutoConfiguration.class }) public @interface EnablePigxSwagger2 { + } diff --git a/pigx-common/pigx-common-swagger/src/main/java/com/pig4cloud/pigx/common/swagger/config/SwaggerAutoConfiguration.java b/pigx-common/pigx-common-swagger/src/main/java/com/pig4cloud/pigx/common/swagger/config/SwaggerAutoConfiguration.java index 3d46d4af7..0558d7699 100644 --- a/pigx-common/pigx-common-swagger/src/main/java/com/pig4cloud/pigx/common/swagger/config/SwaggerAutoConfiguration.java +++ b/pigx-common/pigx-common-swagger/src/main/java/com/pig4cloud/pigx/common/swagger/config/SwaggerAutoConfiguration.java @@ -16,7 +16,6 @@ */ package com.pig4cloud.pigx.common.swagger.config; - import com.google.common.base.Predicate; import com.google.common.base.Predicates; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -41,10 +40,9 @@ import java.util.Collections; import java.util.List; /** - * @author lengleng - * swagger配置 - * 禁用方法1:使用注解@Profile({"dev","test"}) 表示在开发或测试环境开启,而在生产关闭。(推荐使用) - * 禁用方法2:使用注解@ConditionalOnProperty(name = "swagger.enable", havingValue = "true") 然后在测试配置或者开发配置中添加swagger.enable=true即可开启,生产环境不填则默认关闭Swagger. + * @author lengleng swagger配置 禁用方法1:使用注解@Profile({"dev","test"}) + * 表示在开发或测试环境开启,而在生产关闭。(推荐使用) 禁用方法2:使用注解@ConditionalOnProperty(name = "swagger.enable", + * havingValue = "true") 然后在测试配置或者开发配置中添加swagger.enable=true即可开启,生产环境不填则默认关闭Swagger. */ @Configuration @EnableSwagger2 @@ -56,6 +54,7 @@ public class SwaggerAutoConfiguration { * 默认的排除路径,排除Spring Boot默认的错误处理路径和端点 */ private static final List DEFAULT_EXCLUDE_PATH = Arrays.asList("/error", "/actuator/**"); + private static final String BASE_PATH = "/**"; @Bean @@ -70,7 +69,7 @@ public class SwaggerAutoConfiguration { if (swaggerProperties.getBasePath().isEmpty()) { swaggerProperties.getBasePath().add(BASE_PATH); } - //noinspection unchecked + // noinspection unchecked List> basePath = new ArrayList(); swaggerProperties.getBasePath().forEach(path -> basePath.add(PathSelectors.ant(path))); @@ -84,71 +83,61 @@ public class SwaggerAutoConfiguration { // 版本请求头处理 ParameterBuilder versionPar = new ParameterBuilder(); List pars = new ArrayList<>(); - versionPar.name("VERSION").description("灰度路由版本信息") - .modelRef(new ModelRef("string")).parameterType("header") + versionPar.name("VERSION").description("灰度路由版本信息").modelRef(new ModelRef("string")).parameterType("header") .required(false).build(); pars.add(versionPar.build()); - //noinspection Guava - return new Docket(DocumentationType.SWAGGER_2) - .host(swaggerProperties.getHost()) - .apiInfo(apiInfo(swaggerProperties)) - .globalOperationParameters(pars) - .select() + // noinspection Guava + return new Docket(DocumentationType.SWAGGER_2).host(swaggerProperties.getHost()) + .apiInfo(apiInfo(swaggerProperties)).globalOperationParameters(pars).select() .apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage())) - .paths(Predicates.and(Predicates.not(Predicates.or(excludePath)), Predicates.or(basePath))) - .build() + .paths(Predicates.and(Predicates.not(Predicates.or(excludePath)), Predicates.or(basePath))).build() .securitySchemes(Collections.singletonList(securitySchema())) - .securityContexts(Collections.singletonList(securityContext())) - .pathMapping("/"); + .securityContexts(Collections.singletonList(securityContext())).pathMapping("/"); } /** * 配置默认的全局鉴权策略的开关,通过正则表达式进行匹配;默认匹配所有URL - * * @return */ private SecurityContext securityContext() { - return SecurityContext.builder() - .securityReferences(defaultAuth()) - .forPaths(PathSelectors.regex(swaggerProperties().getAuthorization().getAuthRegex())) - .build(); + return SecurityContext.builder().securityReferences(defaultAuth()) + .forPaths(PathSelectors.regex(swaggerProperties().getAuthorization().getAuthRegex())).build(); } /** * 默认的全局鉴权策略 - * * @return */ private List defaultAuth() { ArrayList authorizationScopeList = new ArrayList<>(); - swaggerProperties().getAuthorization().getAuthorizationScopeList().forEach(authorizationScope -> authorizationScopeList.add(new AuthorizationScope(authorizationScope.getScope(), authorizationScope.getDescription()))); + swaggerProperties().getAuthorization().getAuthorizationScopeList() + .forEach(authorizationScope -> authorizationScopeList.add( + new AuthorizationScope(authorizationScope.getScope(), authorizationScope.getDescription()))); AuthorizationScope[] authorizationScopes = new AuthorizationScope[authorizationScopeList.size()]; - return Collections.singletonList(SecurityReference.builder() - .reference(swaggerProperties().getAuthorization().getName()) - .scopes(authorizationScopeList.toArray(authorizationScopes)) - .build()); + return Collections + .singletonList(SecurityReference.builder().reference(swaggerProperties().getAuthorization().getName()) + .scopes(authorizationScopeList.toArray(authorizationScopes)).build()); } - private OAuth securitySchema() { ArrayList authorizationScopeList = new ArrayList<>(); - swaggerProperties().getAuthorization().getAuthorizationScopeList().forEach(authorizationScope -> authorizationScopeList.add(new AuthorizationScope(authorizationScope.getScope(), authorizationScope.getDescription()))); + swaggerProperties().getAuthorization().getAuthorizationScopeList() + .forEach(authorizationScope -> authorizationScopeList.add( + new AuthorizationScope(authorizationScope.getScope(), authorizationScope.getDescription()))); ArrayList grantTypes = new ArrayList<>(); - swaggerProperties().getAuthorization().getTokenUrlList().forEach(tokenUrl -> grantTypes.add(new ResourceOwnerPasswordCredentialsGrant(tokenUrl))); + swaggerProperties().getAuthorization().getTokenUrlList() + .forEach(tokenUrl -> grantTypes.add(new ResourceOwnerPasswordCredentialsGrant(tokenUrl))); return new OAuth(swaggerProperties().getAuthorization().getName(), authorizationScopeList, grantTypes); } private ApiInfo apiInfo(SwaggerProperties swaggerProperties) { - return new ApiInfoBuilder() - .title(swaggerProperties.getTitle()) - .description(swaggerProperties.getDescription()) - .license(swaggerProperties.getLicense()) - .licenseUrl(swaggerProperties.getLicenseUrl()) + return new ApiInfoBuilder().title(swaggerProperties.getTitle()).description(swaggerProperties.getDescription()) + .license(swaggerProperties.getLicense()).licenseUrl(swaggerProperties.getLicenseUrl()) .termsOfServiceUrl(swaggerProperties.getTermsOfServiceUrl()) - .contact(new Contact(swaggerProperties.getContact().getName(), swaggerProperties.getContact().getUrl(), swaggerProperties.getContact().getEmail())) - .version(swaggerProperties.getVersion()) - .build(); + .contact(new Contact(swaggerProperties.getContact().getName(), swaggerProperties.getContact().getUrl(), + swaggerProperties.getContact().getEmail())) + .version(swaggerProperties.getVersion()).build(); } } diff --git a/pigx-common/pigx-common-swagger/src/main/java/com/pig4cloud/pigx/common/swagger/config/SwaggerProperties.java b/pigx-common/pigx-common-swagger/src/main/java/com/pig4cloud/pigx/common/swagger/config/SwaggerProperties.java index 384682314..a9ef3dd1e 100644 --- a/pigx-common/pigx-common-swagger/src/main/java/com/pig4cloud/pigx/common/swagger/config/SwaggerProperties.java +++ b/pigx-common/pigx-common-swagger/src/main/java/com/pig4cloud/pigx/common/swagger/config/SwaggerProperties.java @@ -27,47 +27,57 @@ import java.util.List; * SwaggerProperties * * @author: lengleng - * @date: 2018/7/25 14:00 + * @date: 2018/7/25 14:00 */ @Data @ConfigurationProperties("swagger") public class SwaggerProperties { + /** * 是否开启swagger */ private Boolean enabled; + /** * swagger会解析的包路径 **/ private String basePackage = ""; + /** * swagger会解析的url规则 **/ private List basePath = new ArrayList<>(); + /** * 在basePath基础上需要排除的url规则 **/ private List excludePath = new ArrayList<>(); + /** * 标题 **/ private String title = ""; + /** * 描述 **/ private String description = ""; + /** * 版本 **/ private String version = ""; + /** * 许可证 **/ private String license = ""; + /** * 许可证URL **/ private String licenseUrl = ""; + /** * 服务条款URL **/ @@ -77,10 +87,12 @@ public class SwaggerProperties { * host信息 **/ private String host = ""; + /** * 联系人信息 */ private Contact contact = new Contact(); + /** * 全局统一鉴权配置 **/ @@ -94,10 +106,12 @@ public class SwaggerProperties { * 联系人 **/ private String name = ""; + /** * 联系人url **/ private String url = ""; + /** * 联系人email **/ @@ -125,6 +139,7 @@ public class SwaggerProperties { private List authorizationScopeList = new ArrayList<>(); private List tokenUrlList = new ArrayList<>(); + } @Data @@ -142,4 +157,5 @@ public class SwaggerProperties { private String description = ""; } + } diff --git a/pigx-common/pigx-common-transaction/src/main/java/com/pig4cloud/pigx/common/transaction/TransactionConfiguration.java b/pigx-common/pigx-common-transaction/src/main/java/com/pig4cloud/pigx/common/transaction/TransactionConfiguration.java index c6676d76c..cdec744b7 100755 --- a/pigx-common/pigx-common-transaction/src/main/java/com/pig4cloud/pigx/common/transaction/TransactionConfiguration.java +++ b/pigx-common/pigx-common-transaction/src/main/java/com/pig4cloud/pigx/common/transaction/TransactionConfiguration.java @@ -27,8 +27,7 @@ import org.springframework.context.annotation.Configuration; */ @Configuration -@ComponentScan({"com.codingapi.tx", "com.pig4cloud.pigx.common.transaction"}) +@ComponentScan({ "com.codingapi.tx", "com.pig4cloud.pigx.common.transaction" }) public class TransactionConfiguration { - } diff --git a/pigx-common/pigx-common-transaction/src/main/java/com/pig4cloud/pigx/common/transaction/rewrite/TxManagerHttpRequestServiceImpl.java b/pigx-common/pigx-common-transaction/src/main/java/com/pig4cloud/pigx/common/transaction/rewrite/TxManagerHttpRequestServiceImpl.java index 0c606db99..325594aac 100644 --- a/pigx-common/pigx-common-transaction/src/main/java/com/pig4cloud/pigx/common/transaction/rewrite/TxManagerHttpRequestServiceImpl.java +++ b/pigx-common/pigx-common-transaction/src/main/java/com/pig4cloud/pigx/common/transaction/rewrite/TxManagerHttpRequestServiceImpl.java @@ -24,8 +24,7 @@ import org.springframework.stereotype.Service; /** * @author lengleng - * @date 2018/8/19 - * 请求tx-manager接口实现 + * @date 2018/8/19 请求tx-manager接口实现 */ @Slf4j @Service @@ -44,4 +43,5 @@ public class TxManagerHttpRequestServiceImpl implements TxManagerHttpRequestServ log.debug("请求接口 {},响应报文:{}", url, res); return res; } + } diff --git a/pigx-common/pigx-common-transaction/src/main/java/com/pig4cloud/pigx/common/transaction/rewrite/TxManagerTxUrlServiceImpl.java b/pigx-common/pigx-common-transaction/src/main/java/com/pig4cloud/pigx/common/transaction/rewrite/TxManagerTxUrlServiceImpl.java index ee7b861f5..84f2e1461 100644 --- a/pigx-common/pigx-common-transaction/src/main/java/com/pig4cloud/pigx/common/transaction/rewrite/TxManagerTxUrlServiceImpl.java +++ b/pigx-common/pigx-common-transaction/src/main/java/com/pig4cloud/pigx/common/transaction/rewrite/TxManagerTxUrlServiceImpl.java @@ -27,13 +27,13 @@ import org.springframework.stereotype.Service; /** * @author lengleng - * @date 2018/8/19 - * 使用服务发现重写 Txmanager 获取规则 + * @date 2018/8/19 使用服务发现重写 Txmanager 获取规则 */ @Slf4j @Service @AllArgsConstructor public class TxManagerTxUrlServiceImpl implements TxManagerTxUrlService { + private final LoadBalancerClient loadBalancerClient; @Override @@ -45,4 +45,5 @@ public class TxManagerTxUrlServiceImpl implements TxManagerTxUrlService { log.info("tm.manager.url -> {}", url); return url; } + } diff --git a/pigx-common/pigx-common-transaction/src/main/java/com/pig4cloud/pigx/common/transaction/tx/RequestInterceptorConfiguration.java b/pigx-common/pigx-common-transaction/src/main/java/com/pig4cloud/pigx/common/transaction/tx/RequestInterceptorConfiguration.java index 3ff0cbdc4..c61f3d0a1 100755 --- a/pigx-common/pigx-common-transaction/src/main/java/com/pig4cloud/pigx/common/transaction/tx/RequestInterceptorConfiguration.java +++ b/pigx-common/pigx-common-transaction/src/main/java/com/pig4cloud/pigx/common/transaction/tx/RequestInterceptorConfiguration.java @@ -24,7 +24,6 @@ import org.springframework.context.annotation.Configuration; /** * @author LCN on 2018/1/18 - * * @author LCN * @since 4.1.0 */ @@ -35,4 +34,5 @@ public class RequestInterceptorConfiguration { public RequestInterceptor requestInterceptor() { return new TransactionRestTemplateInterceptor(); } + } diff --git a/pigx-common/pigx-common-transaction/src/main/java/com/pig4cloud/pigx/common/transaction/tx/springcloud/feign/TransactionRestTemplateInterceptor.java b/pigx-common/pigx-common-transaction/src/main/java/com/pig4cloud/pigx/common/transaction/tx/springcloud/feign/TransactionRestTemplateInterceptor.java index 4b20d6c68..91985a294 100755 --- a/pigx-common/pigx-common-transaction/src/main/java/com/pig4cloud/pigx/common/transaction/tx/springcloud/feign/TransactionRestTemplateInterceptor.java +++ b/pigx-common/pigx-common-transaction/src/main/java/com/pig4cloud/pigx/common/transaction/tx/springcloud/feign/TransactionRestTemplateInterceptor.java @@ -23,8 +23,7 @@ import feign.RequestTemplate; import lombok.extern.slf4j.Slf4j; /** - *@author LCN on 2017/6/26. - * + * @author LCN on 2017/6/26. * @author LCN * @since 4.1.0 */ diff --git a/pigx-common/pigx-common-transaction/src/main/java/com/pig4cloud/pigx/common/transaction/tx/springcloud/http/TransactionHttpRequestInterceptor.java b/pigx-common/pigx-common-transaction/src/main/java/com/pig4cloud/pigx/common/transaction/tx/springcloud/http/TransactionHttpRequestInterceptor.java index c477d9dfd..5842f6d9d 100755 --- a/pigx-common/pigx-common-transaction/src/main/java/com/pig4cloud/pigx/common/transaction/tx/springcloud/http/TransactionHttpRequestInterceptor.java +++ b/pigx-common/pigx-common-transaction/src/main/java/com/pig4cloud/pigx/common/transaction/tx/springcloud/http/TransactionHttpRequestInterceptor.java @@ -26,8 +26,7 @@ import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.ClientHttpResponse; /** - *@author LCN on 2017/7/3. - * + * @author LCN on 2017/7/3. * @author LCN * @since 4.1.0 */ @@ -48,4 +47,5 @@ public class TransactionHttpRequestInterceptor implements ClientHttpRequestInter } return execution.execute(request, body); } + } diff --git a/pigx-common/pigx-common-transaction/src/main/java/com/pig4cloud/pigx/common/transaction/tx/springcloud/interceptor/TransactionAspect.java b/pigx-common/pigx-common-transaction/src/main/java/com/pig4cloud/pigx/common/transaction/tx/springcloud/interceptor/TransactionAspect.java index e0433b356..4636d0d39 100755 --- a/pigx-common/pigx-common-transaction/src/main/java/com/pig4cloud/pigx/common/transaction/tx/springcloud/interceptor/TransactionAspect.java +++ b/pigx-common/pigx-common-transaction/src/main/java/com/pig4cloud/pigx/common/transaction/tx/springcloud/interceptor/TransactionAspect.java @@ -28,8 +28,8 @@ import org.springframework.stereotype.Component; /** * LCN 事务拦截器 - * @author LCN on 2018/1/5 * + * @author LCN on 2018/1/5 * @author LCN * @since 4.1.0 */ @@ -60,11 +60,9 @@ public class TransactionAspect implements Ordered { return obj; } - @Override public int getOrder() { return HIGHEST_PRECEDENCE; } - } diff --git a/pigx-common/pigx-common-transaction/src/main/java/com/pig4cloud/pigx/common/transaction/tx/springcloud/interceptor/TxManagerInterceptor.java b/pigx-common/pigx-common-transaction/src/main/java/com/pig4cloud/pigx/common/transaction/tx/springcloud/interceptor/TxManagerInterceptor.java index 8d40d51dd..c7a5ffd77 100755 --- a/pigx-common/pigx-common-transaction/src/main/java/com/pig4cloud/pigx/common/transaction/tx/springcloud/interceptor/TxManagerInterceptor.java +++ b/pigx-common/pigx-common-transaction/src/main/java/com/pig4cloud/pigx/common/transaction/tx/springcloud/interceptor/TxManagerInterceptor.java @@ -39,6 +39,7 @@ import javax.servlet.http.HttpServletRequest; @Component @AllArgsConstructor public class TxManagerInterceptor { + private final AspectBeforeService aspectBeforeService; @SneakyThrows @@ -49,9 +50,11 @@ public class TxManagerInterceptor { requestAttributes = RequestContextHolder.currentRequestAttributes(); HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest(); groupId = request.getHeader("tx-group"); - } catch (IllegalStateException e) { + } + catch (IllegalStateException e) { log.info("非web 环境调用 不包含请求上下文"); } return aspectBeforeService.around(groupId, point); } + } diff --git a/pigx-common/pigx-common-transaction/src/main/java/com/pig4cloud/pigx/common/transaction/tx/springcloud/listener/ServerListener.java b/pigx-common/pigx-common-transaction/src/main/java/com/pig4cloud/pigx/common/transaction/tx/springcloud/listener/ServerListener.java index 7cd9694fa..0df8fbeeb 100755 --- a/pigx-common/pigx-common-transaction/src/main/java/com/pig4cloud/pigx/common/transaction/tx/springcloud/listener/ServerListener.java +++ b/pigx-common/pigx-common-transaction/src/main/java/com/pig4cloud/pigx/common/transaction/tx/springcloud/listener/ServerListener.java @@ -49,4 +49,5 @@ public class ServerListener implements ApplicationListener clients = new ArrayList<>(); - private List swaggerProviders=new ArrayList<>(); + + private List swaggerProviders = new ArrayList<>(); + } diff --git a/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/config/RateLimiterConfiguration.java b/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/config/RateLimiterConfiguration.java index e5d1c2af3..7b1d2463e 100644 --- a/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/config/RateLimiterConfiguration.java +++ b/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/config/RateLimiterConfiguration.java @@ -26,13 +26,14 @@ import reactor.core.publisher.Mono; /** * @author lengleng - * @date 2018/7/1 - * 路由限流配置 + * @date 2018/7/1 路由限流配置 */ @Configuration public class RateLimiterConfiguration { + @Bean(value = "remoteAddrKeyResolver") public KeyResolver remoteAddrKeyResolver() { return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress()); } + } diff --git a/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/config/RouterFunctionConfiguration.java b/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/config/RouterFunctionConfiguration.java index 56bfad7da..8e75f4a2e 100644 --- a/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/config/RouterFunctionConfiguration.java +++ b/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/config/RouterFunctionConfiguration.java @@ -29,28 +29,32 @@ import org.springframework.web.reactive.function.server.RouterFunctions; /** * @author lengleng - * @date 2018/7/5 - * 路由配置信息 + * @date 2018/7/5 路由配置信息 */ @Slf4j @Configuration @AllArgsConstructor public class RouterFunctionConfiguration { + private final ImageCodeCheckHandler imageCodeCheckHandler; + private final ImageCodeCreateHandler imageCodeCreateHandler; + private final SwaggerResourceHandler swaggerResourceHandler; + private final SwaggerSecurityHandler swaggerSecurityHandler; + private final SwaggerUiHandler swaggerUiHandler; @Bean public RouterFunction routerFunction() { - return RouterFunctions.route( - RequestPredicates.path("/code") - .and(RequestPredicates.accept(MediaType.TEXT_PLAIN)), imageCodeCreateHandler) - .andRoute(RequestPredicates.POST("/code/check") - .and(RequestPredicates.accept(MediaType.ALL)), imageCodeCheckHandler) - .andRoute(RequestPredicates.GET("/swagger-resources") - .and(RequestPredicates.accept(MediaType.ALL)), swaggerResourceHandler) + return RouterFunctions + .route(RequestPredicates.path("/code").and(RequestPredicates.accept(MediaType.TEXT_PLAIN)), + imageCodeCreateHandler) + .andRoute(RequestPredicates.POST("/code/check").and(RequestPredicates.accept(MediaType.ALL)), + imageCodeCheckHandler) + .andRoute(RequestPredicates.GET("/swagger-resources").and(RequestPredicates.accept(MediaType.ALL)), + swaggerResourceHandler) .andRoute(RequestPredicates.GET("/swagger-resources/configuration/ui") .and(RequestPredicates.accept(MediaType.ALL)), swaggerUiHandler) .andRoute(RequestPredicates.GET("/swagger-resources/configuration/security") diff --git a/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/config/SwaggerProvider.java b/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/config/SwaggerProvider.java index 159ab0420..a00367142 100644 --- a/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/config/SwaggerProvider.java +++ b/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/config/SwaggerProvider.java @@ -32,28 +32,32 @@ import java.util.List; import java.util.stream.Collectors; /** - * @author Sywd - * 聚合接口文档注册,和zuul实现类似 + * @author Sywd 聚合接口文档注册,和zuul实现类似 */ @Component @Primary @AllArgsConstructor public class SwaggerProvider implements SwaggerResourcesProvider { + private static final String API_URI = "/v2/api-docs"; + private final RouteDefinitionRepository routeDefinitionRepository; + private final FilterIgnorePropertiesConfig filterIgnorePropertiesConfig; @Override public List get() { List routes = new ArrayList<>(); routeDefinitionRepository.getRouteDefinitions().subscribe(routes::add); - return routes.stream().flatMap(routeDefinition -> routeDefinition.getPredicates().stream() - .filter(predicateDefinition -> "Path".equalsIgnoreCase(predicateDefinition.getName())) - .filter(predicateDefinition -> !filterIgnorePropertiesConfig.getSwaggerProviders().contains(routeDefinition.getId())) - .map(predicateDefinition -> - swaggerResource(routeDefinition.getId(), predicateDefinition.getArgs().get(NameUtils.GENERATED_NAME_PREFIX + "0").replace("/**", API_URI)) - )).sorted(Comparator.comparing(SwaggerResource::getName)) - .collect(Collectors.toList()); + return routes.stream() + .flatMap(routeDefinition -> routeDefinition.getPredicates().stream() + .filter(predicateDefinition -> "Path".equalsIgnoreCase(predicateDefinition.getName())) + .filter(predicateDefinition -> !filterIgnorePropertiesConfig.getSwaggerProviders() + .contains(routeDefinition.getId())) + .map(predicateDefinition -> swaggerResource(routeDefinition.getId(), + predicateDefinition.getArgs().get(NameUtils.GENERATED_NAME_PREFIX + "0").replace("/**", + API_URI)))) + .sorted(Comparator.comparing(SwaggerResource::getName)).collect(Collectors.toList()); } private static SwaggerResource swaggerResource(String name, String location) { @@ -63,4 +67,5 @@ public class SwaggerProvider implements SwaggerResourcesProvider { swaggerResource.setSwaggerVersion("2.0"); return swaggerResource; } + } diff --git a/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/filter/HttpBasicGatewayFilter.java b/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/filter/HttpBasicGatewayFilter.java index c4f106975..052aeb18e 100644 --- a/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/filter/HttpBasicGatewayFilter.java +++ b/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/filter/HttpBasicGatewayFilter.java @@ -36,12 +36,14 @@ import org.springframework.web.server.ServerWebExchange; @Slf4j @Component public class HttpBasicGatewayFilter extends AbstractGatewayFilterFactory { + @Override public GatewayFilter apply(Object config) { return (exchange, chain) -> { if (hasAuth(exchange)) { return chain.filter(exchange); - } else { + } + else { ServerHttpResponse response = exchange.getResponse(); response.setStatusCode(HttpStatus.UNAUTHORIZED); response.getHeaders().add(HttpHeaders.WWW_AUTHENTICATE, "Basic Realm=\"pigx\""); @@ -52,7 +54,6 @@ public class HttpBasicGatewayFilter extends AbstractGatewayFilterFactory { /** * 简单的basic认证 - * * @param exchange 上下文 * @return 是否有权限 */ diff --git a/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/filter/PasswordDecoderFilter.java b/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/filter/PasswordDecoderFilter.java index 9c9e2ed65..9406abb3e 100644 --- a/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/filter/PasswordDecoderFilter.java +++ b/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/filter/PasswordDecoderFilter.java @@ -55,22 +55,23 @@ import java.util.function.Function; /** * @author lengleng - * @date 2020/1/8 - * 密码解密工具类 + * @date 2020/1/8 密码解密工具类 *

* 参考 ModifyRequestBodyGatewayFilterFactory 实现 */ @Slf4j @Component public class PasswordDecoderFilter extends AbstractGatewayFilterFactory { + private final List> messageReaders = HandlerStrategies.withDefaults().messageReaders(); private static final String PASSWORD = "password"; + private static final String KEY_ALGORITHM = "AES"; + @Value("${security.encode.key:1234567812345678}") private String encodeKey; - @Override public GatewayFilter apply(Object config) { return (exchange, chain) -> { @@ -88,12 +89,10 @@ public class PasswordDecoderFilter extends AbstractGatewayFilterFactory { Class inClass = String.class; Class outClass = String.class; - ServerRequest serverRequest = ServerRequest.create(exchange, - messageReaders); + ServerRequest serverRequest = ServerRequest.create(exchange, messageReaders); // 解密生成新的报文 - Mono modifiedBody = serverRequest.bodyToMono(inClass) - .flatMap(decryptAES()); + Mono modifiedBody = serverRequest.bodyToMono(inClass).flatMap(decryptAES()); BodyInserter bodyInserter = BodyInserters.fromPublisher(modifiedBody, outClass); HttpHeaders headers = new HttpHeaders(); @@ -101,41 +100,35 @@ public class PasswordDecoderFilter extends AbstractGatewayFilterFactory { headers.remove(HttpHeaders.CONTENT_LENGTH); headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE); - CachedBodyOutputMessage outputMessage = new CachedBodyOutputMessage( - exchange, headers); - return bodyInserter.insert(outputMessage, new BodyInserterContext()) - .then(Mono.defer(() -> { - ServerHttpRequest decorator = decorate(exchange, headers, - outputMessage); - return chain - .filter(exchange.mutate().request(decorator).build()); - })); + CachedBodyOutputMessage outputMessage = new CachedBodyOutputMessage(exchange, headers); + return bodyInserter.insert(outputMessage, new BodyInserterContext()).then(Mono.defer(() -> { + ServerHttpRequest decorator = decorate(exchange, headers, outputMessage); + return chain.filter(exchange.mutate().request(decorator).build()); + })); }; } /** * 原文解密 - * * @return */ private Function decryptAES() { return s -> { // 构建前端对应解密AES 因子 - AES aes = new AES(Mode.CBC, Padding.NoPadding, - new SecretKeySpec(encodeKey.getBytes(), KEY_ALGORITHM), + AES aes = new AES(Mode.CBC, Padding.NoPadding, new SecretKeySpec(encodeKey.getBytes(), KEY_ALGORITHM), new IvParameterSpec(encodeKey.getBytes())); // 获取请求密码并解密 Map inParamsMap = HttpUtil.decodeParamMap((String) s, CharsetUtil.CHARSET_UTF_8); - if(inParamsMap.containsKey(PASSWORD)){ - byte[] result = aes.decrypt(Base64.decode(inParamsMap.get(PASSWORD) - .getBytes(StandardCharsets.UTF_8))); + if (inParamsMap.containsKey(PASSWORD)) { + byte[] result = aes.decrypt(Base64.decode(inParamsMap.get(PASSWORD).getBytes(StandardCharsets.UTF_8))); String password = new String(result, StandardCharsets.UTF_8); // 返回修改后报文字符 inParamsMap.put(PASSWORD, password.trim()); - } else { - log.error("非法请求数据:{}",s); + } + else { + log.error("非法请求数据:{}", s); } return Mono.just(HttpUtil.toParams(inParamsMap)); }; @@ -143,11 +136,10 @@ public class PasswordDecoderFilter extends AbstractGatewayFilterFactory { /** * 报文转换 - * * @return */ private ServerHttpRequestDecorator decorate(ServerWebExchange exchange, HttpHeaders headers, - CachedBodyOutputMessage outputMessage) { + CachedBodyOutputMessage outputMessage) { return new ServerHttpRequestDecorator(exchange.getRequest()) { @Override public HttpHeaders getHeaders() { @@ -156,7 +148,8 @@ public class PasswordDecoderFilter extends AbstractGatewayFilterFactory { httpHeaders.putAll(super.getHeaders()); if (contentLength > 0) { httpHeaders.setContentLength(contentLength); - } else { + } + else { httpHeaders.set(HttpHeaders.TRANSFER_ENCODING, "chunked"); } return httpHeaders; @@ -168,4 +161,5 @@ public class PasswordDecoderFilter extends AbstractGatewayFilterFactory { } }; } + } diff --git a/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/filter/PigxRequestGlobalFilter.java b/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/filter/PigxRequestGlobalFilter.java index afc78f275..e3574325f 100644 --- a/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/filter/PigxRequestGlobalFilter.java +++ b/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/filter/PigxRequestGlobalFilter.java @@ -39,46 +39,40 @@ import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.a *

* 全局拦截器,作用所有的微服务 *

- * 1. 对请求头中参数进行处理 from 参数进行清洗 - * 2. 重写StripPrefix = 1,支持全局 + * 1. 对请求头中参数进行处理 from 参数进行清洗 2. 重写StripPrefix = 1,支持全局 *

- * 支持swagger添加X-Forwarded-Prefix header (F SR2 已经支持,不需要自己维护) + * 支持swagger添加X-Forwarded-Prefix header (F SR2 已经支持,不需要自己维护) */ @Component public class PigxRequestGlobalFilter implements GlobalFilter, Ordered { /** - * Process the Web request and (optionally) delegate to the next - * {@code WebFilter} through the given {@link GatewayFilterChain}. - * + * 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 + * @param chain provides a way to delegate to the next filter * @return {@code Mono} to indicate when request processing is complete */ @Override public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { // 1. 清洗请求头中from 参数 ServerHttpRequest request = exchange.getRequest().mutate() - .headers(httpHeaders -> httpHeaders.remove(SecurityConstants.FROM)) - .build(); + .headers(httpHeaders -> httpHeaders.remove(SecurityConstants.FROM)).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(); + 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()); + return chain.filter(exchange.mutate().request(newRequest.mutate().build()).build()); } @Override public int getOrder() { return -1000; } + } diff --git a/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/filter/PreviewGatewayFilter.java b/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/filter/PreviewGatewayFilter.java index d1578ddc7..a829f5ad1 100644 --- a/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/filter/PreviewGatewayFilter.java +++ b/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/filter/PreviewGatewayFilter.java @@ -29,14 +29,13 @@ import org.springframework.stereotype.Component; /** * @author lengleng - * @date 2018/8/21 - * 演示环境过滤处理 + * @date 2018/8/21 演示环境过滤处理 */ @Slf4j @Component public class PreviewGatewayFilter extends AbstractGatewayFilterFactory { - private static final String TOKEN = "token"; + private static final String TOKEN = "token"; @Override public GatewayFilter apply(Object config) { @@ -44,8 +43,8 @@ public class PreviewGatewayFilter extends AbstractGatewayFilterFactory { ServerHttpRequest request = exchange.getRequest(); // GET,直接向下执行 - if (StrUtil.equalsIgnoreCase(request.getMethodValue(), HttpMethod.GET.name()) || - StrUtil.containsIgnoreCase(request.getURI().getPath(), TOKEN)) { + if (StrUtil.equalsIgnoreCase(request.getMethodValue(), HttpMethod.GET.name()) + || StrUtil.containsIgnoreCase(request.getURI().getPath(), TOKEN)) { return chain.filter(exchange); } @@ -55,4 +54,5 @@ public class PreviewGatewayFilter extends AbstractGatewayFilterFactory { return response.setComplete(); }; } + } diff --git a/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/filter/ValidateCodeGatewayFilter.java b/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/filter/ValidateCodeGatewayFilter.java index 28da83469..1aec02eaa 100644 --- a/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/filter/ValidateCodeGatewayFilter.java +++ b/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/filter/ValidateCodeGatewayFilter.java @@ -48,15 +48,17 @@ import reactor.core.publisher.Mono; /** * @author lengleng - * @date 2020/5/19 - * 登录逻辑验证码处理 + * @date 2020/5/19 登录逻辑验证码处理 */ @Slf4j @Component @AllArgsConstructor public class ValidateCodeGatewayFilter extends AbstractGatewayFilterFactory { + private final ObjectMapper objectMapper; + private final RedisTemplate redisTemplate; + private final FilterIgnorePropertiesConfig filterIgnorePropertiesConfig; @Override @@ -65,9 +67,8 @@ public class ValidateCodeGatewayFilter extends AbstractGatewayFilterFactory { ServerHttpRequest request = exchange.getRequest(); // 不是登录请求,直接向下执行 - if (!StrUtil.containsAnyIgnoreCase(request.getURI().getPath() - , SecurityConstants.OAUTH_TOKEN_URL, SecurityConstants.SMS_TOKEN_URL - , SecurityConstants.SOCIAL_TOKEN_URL)) { + if (!StrUtil.containsAnyIgnoreCase(request.getURI().getPath(), SecurityConstants.OAUTH_TOKEN_URL, + SecurityConstants.SMS_TOKEN_URL, SecurityConstants.SOCIAL_TOKEN_URL)) { return chain.filter(exchange); } @@ -90,22 +91,24 @@ public class ValidateCodeGatewayFilter extends AbstractGatewayFilterFactory { String mobile = request.getQueryParams().getFirst("mobile"); if (StrUtil.containsAny(mobile, LoginTypeEnum.SMS.getType())) { throw new ValidateCodeException("验证码不合法"); - } else { + } + else { return chain.filter(exchange); } } - //校验验证码 + // 校验验证码 checkCode(request); - } catch (Exception e) { + } + catch (Exception e) { ServerHttpResponse response = exchange.getResponse(); response.getHeaders().setContentType(MediaType.APPLICATION_JSON); response.setStatusCode(HttpStatus.PRECONDITION_REQUIRED); try { - return response.writeWith(Mono.just(response.bufferFactory() - .wrap(objectMapper.writeValueAsBytes( - R.failed(e.getMessage()))))); - } catch (JsonProcessingException e1) { + return response.writeWith(Mono.just( + response.bufferFactory().wrap(objectMapper.writeValueAsBytes(R.failed(e.getMessage()))))); + } + catch (JsonProcessingException e1) { log.error("对象输出异常", e1); } } @@ -116,7 +119,6 @@ public class ValidateCodeGatewayFilter extends AbstractGatewayFilterFactory { /** * 检查code - * * @param request */ @SneakyThrows @@ -141,7 +143,7 @@ public class ValidateCodeGatewayFilter extends AbstractGatewayFilterFactory { return; } - //https://gitee.com/log4j/pig/issues/IWA0D + // https://gitee.com/log4j/pig/issues/IWA0D String mobile = request.getQueryParams().getFirst("mobile"); if (StrUtil.isNotBlank(mobile)) { randomStr = mobile; @@ -173,4 +175,5 @@ public class ValidateCodeGatewayFilter extends AbstractGatewayFilterFactory { redisTemplate.delete(key); } + } diff --git a/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/handler/ImageCodeCheckHandler.java b/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/handler/ImageCodeCheckHandler.java index 4de706ce3..81fdc12f3 100644 --- a/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/handler/ImageCodeCheckHandler.java +++ b/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/handler/ImageCodeCheckHandler.java @@ -38,15 +38,14 @@ import reactor.core.publisher.Mono; /** * @author lengleng - * @date 2020/5/19 - * 验证码生成逻辑处理类 + * @date 2020/5/19 验证码生成逻辑处理类 */ @Slf4j @Component @AllArgsConstructor public class ImageCodeCheckHandler implements HandlerFunction { - private final ObjectMapper objectMapper; + private final ObjectMapper objectMapper; @Override @SneakyThrows @@ -59,8 +58,8 @@ public class ImageCodeCheckHandler implements HandlerFunction { CaptchaService captchaService = SpringContextHolder.getBean(CaptchaService.class); ResponseModel responseModel = captchaService.check(vo); - return ServerResponse.status(HttpStatus.OK) - .contentType(MediaType.APPLICATION_JSON) + return ServerResponse.status(HttpStatus.OK).contentType(MediaType.APPLICATION_JSON) .body(BodyInserters.fromValue(objectMapper.writeValueAsString(R.ok(responseModel)))); } + } diff --git a/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/handler/ImageCodeCreateHandler.java b/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/handler/ImageCodeCreateHandler.java index 6840c48e0..76c4c2376 100644 --- a/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/handler/ImageCodeCreateHandler.java +++ b/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/handler/ImageCodeCreateHandler.java @@ -38,15 +38,14 @@ import reactor.core.publisher.Mono; /** * @author lengleng - * @date 2020/5/19 - * 验证码生成逻辑处理类 + * @date 2020/5/19 验证码生成逻辑处理类 */ @Slf4j @Component @AllArgsConstructor public class ImageCodeCreateHandler implements HandlerFunction { - private final ObjectMapper objectMapper; + private final ObjectMapper objectMapper; @Override @SneakyThrows @@ -56,8 +55,8 @@ public class ImageCodeCreateHandler implements HandlerFunction { CaptchaService captchaService = SpringContextHolder.getBean(CaptchaService.class); ResponseModel responseModel = captchaService.get(vo); - return ServerResponse.status(HttpStatus.OK) - .contentType(MediaType.APPLICATION_JSON) + return ServerResponse.status(HttpStatus.OK).contentType(MediaType.APPLICATION_JSON) .body(BodyInserters.fromValue(objectMapper.writeValueAsString(R.ok(responseModel)))); } + } diff --git a/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/handler/SwaggerResourceHandler.java b/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/handler/SwaggerResourceHandler.java index bc45175b6..b29f1418c 100644 --- a/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/handler/SwaggerResourceHandler.java +++ b/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/handler/SwaggerResourceHandler.java @@ -31,25 +31,24 @@ import springfox.documentation.swagger.web.SwaggerResourcesProvider; /** * @author lengleng - * @date 2018-07-19 - * SwaggerResourceHandler + * @date 2018-07-19 SwaggerResourceHandler */ @Slf4j @Component @AllArgsConstructor public class SwaggerResourceHandler implements HandlerFunction { + private final SwaggerResourcesProvider swaggerResources; /** * Handle the given request. - * * @param request the request to handler * @return the response */ @Override public Mono handle(ServerRequest request) { - return ServerResponse.status(HttpStatus.OK) - .contentType(MediaType.APPLICATION_JSON) - .body(BodyInserters.fromValue(swaggerResources.get())); + return ServerResponse.status(HttpStatus.OK).contentType(MediaType.APPLICATION_JSON) + .body(BodyInserters.fromValue(swaggerResources.get())); } + } diff --git a/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/handler/SwaggerSecurityHandler.java b/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/handler/SwaggerSecurityHandler.java index df243f960..8721553d9 100644 --- a/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/handler/SwaggerSecurityHandler.java +++ b/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/handler/SwaggerSecurityHandler.java @@ -34,27 +34,25 @@ import java.util.Optional; /** * @author lengleng - * @date 2018-07-19 - * SwaggerSecurityHandler + * @date 2018-07-19 SwaggerSecurityHandler */ @Slf4j @Component public class SwaggerSecurityHandler implements HandlerFunction { + @Autowired(required = false) private SecurityConfiguration securityConfiguration; /** * Handle the given request. - * * @param request the request to handler * @return the response */ @Override public Mono handle(ServerRequest request) { - return ServerResponse.status(HttpStatus.OK) - .contentType(MediaType.APPLICATION_JSON) - .body(BodyInserters.fromValue( - Optional.ofNullable(securityConfiguration) - .orElse(SecurityConfigurationBuilder.builder().build()))); + return ServerResponse.status(HttpStatus.OK).contentType(MediaType.APPLICATION_JSON) + .body(BodyInserters.fromValue(Optional.ofNullable(securityConfiguration) + .orElse(SecurityConfigurationBuilder.builder().build()))); } + } diff --git a/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/handler/SwaggerUiHandler.java b/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/handler/SwaggerUiHandler.java index 0d7756a03..47ba2ff13 100644 --- a/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/handler/SwaggerUiHandler.java +++ b/pigx-gateway/src/main/java/com/pig4cloud/pigx/gateway/handler/SwaggerUiHandler.java @@ -34,27 +34,24 @@ import java.util.Optional; /** * @author lengleng - * @date 2018-07-19 - * SwaggerUiHandler + * @date 2018-07-19 SwaggerUiHandler */ @Slf4j @Component public class SwaggerUiHandler implements HandlerFunction { + @Autowired(required = false) private UiConfiguration uiConfiguration; /** * Handle the given request. - * * @param request the request to handler * @return the response */ @Override public Mono handle(ServerRequest request) { - return ServerResponse.status(HttpStatus.OK) - .contentType(MediaType.APPLICATION_JSON) - .body(BodyInserters.fromValue( - Optional.ofNullable(uiConfiguration) - .orElse(UiConfigurationBuilder.builder().build()))); + return ServerResponse.status(HttpStatus.OK).contentType(MediaType.APPLICATION_JSON).body(BodyInserters + .fromValue(Optional.ofNullable(uiConfiguration).orElse(UiConfigurationBuilder.builder().build()))); } + } diff --git a/pigx-register/src/main/java/com/alibaba/nacos/PigxNacosApplication.java b/pigx-register/src/main/java/com/alibaba/nacos/PigxNacosApplication.java index 51f509698..ee4135c17 100755 --- a/pigx-register/src/main/java/com/alibaba/nacos/PigxNacosApplication.java +++ b/pigx-register/src/main/java/com/alibaba/nacos/PigxNacosApplication.java @@ -24,8 +24,7 @@ import org.springframework.scheduling.annotation.EnableScheduling; /** * @author nacos *

- * nacos console 源码运行,方便开发 - * 生产建议从官网下载最新版配置运行 + * nacos console 源码运行,方便开发 生产建议从官网下载最新版配置运行 */ @EnableScheduling @SpringBootApplication @@ -36,4 +35,5 @@ public class PigxNacosApplication { System.setProperty(ConfigConstants.AUTH_ENABLED, "false"); SpringApplication.run(PigxNacosApplication.class, args); } + } diff --git a/pigx-register/src/main/java/com/alibaba/nacos/console/config/ConfigConstants.java b/pigx-register/src/main/java/com/alibaba/nacos/console/config/ConfigConstants.java index 4572491d4..ec8abcfa7 100644 --- a/pigx-register/src/main/java/com/alibaba/nacos/console/config/ConfigConstants.java +++ b/pigx-register/src/main/java/com/alibaba/nacos/console/config/ConfigConstants.java @@ -24,8 +24,9 @@ package com.alibaba.nacos.console.config; * 覆盖nacos 默认配置 */ public interface ConfigConstants { + /** - * The System property name of Standalone mode + * The System property name of Standalone mode */ String STANDALONE_MODE = "nacos.standalone"; @@ -33,4 +34,5 @@ public interface ConfigConstants { * 是否开启认证 */ String AUTH_ENABLED = "nacos.core.auth.enabled"; + } diff --git a/pigx-register/src/main/java/com/alibaba/nacos/console/config/ConsoleConfig.java b/pigx-register/src/main/java/com/alibaba/nacos/console/config/ConsoleConfig.java index 0a47b45b6..de6c99793 100755 --- a/pigx-register/src/main/java/com/alibaba/nacos/console/config/ConsoleConfig.java +++ b/pigx-register/src/main/java/com/alibaba/nacos/console/config/ConsoleConfig.java @@ -15,7 +15,6 @@ */ package com.alibaba.nacos.console.config; - import com.alibaba.nacos.core.code.ControllerMethodsCache; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; @@ -38,26 +37,27 @@ import javax.annotation.PostConstruct; @PropertySource("/application.properties") public class ConsoleConfig { - @Autowired - private ControllerMethodsCache methodsCache; + @Autowired + private ControllerMethodsCache methodsCache; - @PostConstruct - public void init() { - methodsCache.initClassMethod("com.alibaba.nacos.naming.controllers"); - methodsCache.initClassMethod("com.alibaba.nacos.console.controller"); - methodsCache.initClassMethod("com.alibaba.nacos.config.server.controller"); - } + @PostConstruct + public void init() { + methodsCache.initClassMethod("com.alibaba.nacos.naming.controllers"); + methodsCache.initClassMethod("com.alibaba.nacos.console.controller"); + methodsCache.initClassMethod("com.alibaba.nacos.config.server.controller"); + } + + @Bean + public CorsFilter corsFilter() { + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + CorsConfiguration config = new CorsConfiguration(); + config.setAllowCredentials(true); + config.addAllowedOrigin("*"); + config.addAllowedHeader("*"); + config.setMaxAge(18000L); + config.addAllowedMethod("*"); + source.registerCorsConfiguration("/**", config); + return new CorsFilter(source); + } - @Bean - public CorsFilter corsFilter() { - UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); - CorsConfiguration config = new CorsConfiguration(); - config.setAllowCredentials(true); - config.addAllowedOrigin("*"); - config.addAllowedHeader("*"); - config.setMaxAge(18000L); - config.addAllowedMethod("*"); - source.registerCorsConfiguration("/**", config); - return new CorsFilter(source); - } } diff --git a/pigx-register/src/main/java/com/alibaba/nacos/console/controller/HealthController.java b/pigx-register/src/main/java/com/alibaba/nacos/console/controller/HealthController.java index 05006ce55..8c43f5a7d 100755 --- a/pigx-register/src/main/java/com/alibaba/nacos/console/controller/HealthController.java +++ b/pigx-register/src/main/java/com/alibaba/nacos/console/controller/HealthController.java @@ -34,72 +34,75 @@ import javax.servlet.http.HttpServletRequest; @RequestMapping("/v1/console/health") public class HealthController { - private static final Logger logger = LoggerFactory.getLogger(HealthController.class); + private static final Logger logger = LoggerFactory.getLogger(HealthController.class); - private final PersistService persistService; - private final OperatorController apiCommands; + private final PersistService persistService; - @Autowired - public HealthController(PersistService persistService, OperatorController apiCommands) { - this.persistService = persistService; - this.apiCommands = apiCommands; - } + private final OperatorController 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 liveness() { - return ResponseEntity.ok().body("OK"); - } + @Autowired + public HealthController(PersistService persistService, OperatorController apiCommands) { + this.persistService = persistService; + this.apiCommands = apiCommands; + } - /** - * 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 readiness(HttpServletRequest request) { - boolean isConfigReadiness = isConfigReadiness(); - boolean isNamingReadiness = isNamingReadiness(request); + /** + * 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 liveness() { + return ResponseEntity.ok().body("OK"); + } - if (isConfigReadiness && isNamingReadiness) { - 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 readiness(HttpServletRequest request) { + boolean isConfigReadiness = isConfigReadiness(); + boolean isNamingReadiness = isNamingReadiness(request); - if (!isConfigReadiness && !isNamingReadiness) { - return ResponseEntity.status(500).body("Config and Naming are not in readiness"); - } + if (isConfigReadiness && isNamingReadiness) { + return ResponseEntity.ok().body("OK"); + } - if (!isConfigReadiness) { - return ResponseEntity.status(500).body("Config is not in readiness"); - } + if (!isConfigReadiness && !isNamingReadiness) { + return ResponseEntity.status(500).body("Config and Naming are not in readiness"); + } - return ResponseEntity.status(500).body("Naming is not in readiness"); - } + if (!isConfigReadiness) { + return ResponseEntity.status(500).body("Config is not in readiness"); + } - private boolean isConfigReadiness() { - // check db - try { - persistService.configInfoCount(""); - return true; - } catch (Exception e) { - logger.error("Config health check fail.", e); - } - return false; - } + return ResponseEntity.status(500).body("Naming is not in readiness"); + } + + private boolean isConfigReadiness() { + // check db + try { + persistService.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; + } - private boolean isNamingReadiness(HttpServletRequest request) { - try { - apiCommands.metrics(request); - return true; - } catch (Exception e) { - logger.error("Naming health check fail.", e); - } - return false; - } } diff --git a/pigx-register/src/main/java/com/alibaba/nacos/console/controller/NamespaceController.java b/pigx-register/src/main/java/com/alibaba/nacos/console/controller/NamespaceController.java index 0e24b58a3..92fe9e0be 100755 --- a/pigx-register/src/main/java/com/alibaba/nacos/console/controller/NamespaceController.java +++ b/pigx-register/src/main/java/com/alibaba/nacos/console/controller/NamespaceController.java @@ -43,144 +43,140 @@ import java.util.regex.Pattern; @RequestMapping("/v1/console/namespaces") public class NamespaceController { - @Autowired - private PersistService persistService; + @Autowired + private PersistService persistService; - private Pattern namespaceIdCheckPattern = Pattern.compile("^[\\w-]+"); + private Pattern namespaceIdCheckPattern = Pattern.compile("^[\\w-]+"); - private static final int NAMESPACE_ID_MAX_LENGTH = 128; + private static final int NAMESPACE_ID_MAX_LENGTH = 128; - /** - * Get namespace list - * - * @param request request - * @param response response - * @return namespace list - */ - @GetMapping - public RestResult> getNamespaces(HttpServletRequest request, HttpServletResponse response) { - RestResult> rr = new RestResult>(); - rr.setCode(200); - // TODO 获取用kp - List tenantInfos = persistService.findTenantByKp("1"); - Namespace namespace0 = new Namespace("", "public", 200, persistService.configInfoCount(""), 0); - List namespaces = new ArrayList(); - namespaces.add(namespace0); - for (TenantInfo tenantInfo : tenantInfos) { - int configCount = persistService.configInfoCount(tenantInfo.getTenantId()); - Namespace namespaceTmp = new Namespace(tenantInfo.getTenantId(), tenantInfo.getTenantName(), 200, - configCount, 2); - namespaces.add(namespaceTmp); - } - rr.setData(namespaces); - return rr; - } + /** + * Get namespace list + * @param request request + * @param response response + * @return namespace list + */ + @GetMapping + public RestResult> getNamespaces(HttpServletRequest request, HttpServletResponse response) { + RestResult> rr = new RestResult>(); + rr.setCode(200); + // TODO 获取用kp + List tenantInfos = persistService.findTenantByKp("1"); + Namespace namespace0 = new Namespace("", "public", 200, persistService.configInfoCount(""), 0); + List namespaces = new ArrayList(); + namespaces.add(namespace0); + for (TenantInfo tenantInfo : tenantInfos) { + int configCount = persistService.configInfoCount(tenantInfo.getTenantId()); + Namespace namespaceTmp = new Namespace(tenantInfo.getTenantId(), tenantInfo.getTenantName(), 200, + configCount, 2); + namespaces.add(namespaceTmp); + } + rr.setData(namespaces); + return rr; + } - /** - * get namespace all info by namespace id - * - * @param request request - * @param response response - * @param namespaceId namespaceId - * @return namespace all info - */ - @GetMapping(params = "show=all") - public NamespaceAllInfo getNamespace(HttpServletRequest request, HttpServletResponse response, - @RequestParam("namespaceId") String namespaceId) { - // TODO 获取用kp - if (StringUtils.isBlank(namespaceId)) { - return new NamespaceAllInfo(namespaceId, "Public", 200, - persistService.configInfoCount(""), 0, "Public Namespace"); - } else { - TenantInfo tenantInfo = persistService.findTenantByKp("1", namespaceId); - int configCount = persistService.configInfoCount(namespaceId); - return new NamespaceAllInfo(namespaceId, tenantInfo.getTenantName(), 200, - configCount, 2, tenantInfo.getTenantDesc()); - } - } + /** + * get namespace all info by namespace id + * @param request request + * @param response response + * @param namespaceId namespaceId + * @return namespace all info + */ + @GetMapping(params = "show=all") + public NamespaceAllInfo getNamespace(HttpServletRequest request, HttpServletResponse response, + @RequestParam("namespaceId") String namespaceId) { + // TODO 获取用kp + if (StringUtils.isBlank(namespaceId)) { + return new NamespaceAllInfo(namespaceId, "Public", 200, persistService.configInfoCount(""), 0, + "Public Namespace"); + } + else { + TenantInfo tenantInfo = persistService.findTenantByKp("1", namespaceId); + int configCount = persistService.configInfoCount(namespaceId); + return new NamespaceAllInfo(namespaceId, tenantInfo.getTenantName(), 200, configCount, 2, + tenantInfo.getTenantDesc()); + } + } - /** - * create namespace - * - * @param request request - * @param response response - * @param namespaceName namespace Name - * @param namespaceDesc namespace Desc - * @return whether create ok - */ - @PostMapping - @Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "namespaces", action = ActionTypes.WRITE) - public Boolean createNamespace(HttpServletRequest request, HttpServletResponse response, - @RequestParam("customNamespaceId") String namespaceId, - @RequestParam("namespaceName") String namespaceName, - @RequestParam(value = "namespaceDesc", required = false) String namespaceDesc) { - // TODO 获取用kp - 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; - } - if(persistService.tenantInfoCountByTenantId(namespaceId) > 0){ - return false; - } - } - persistService.insertTenantInfoAtomic("1", namespaceId, namespaceName, namespaceDesc, "nacos", - System.currentTimeMillis()); - return true; - } + /** + * create namespace + * @param request request + * @param response response + * @param namespaceName namespace Name + * @param namespaceDesc namespace Desc + * @return whether create ok + */ + @PostMapping + @Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "namespaces", action = ActionTypes.WRITE) + public Boolean createNamespace(HttpServletRequest request, HttpServletResponse response, + @RequestParam("customNamespaceId") String namespaceId, @RequestParam("namespaceName") String namespaceName, + @RequestParam(value = "namespaceDesc", required = false) String namespaceDesc) { + // TODO 获取用kp + 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; + } + if (persistService.tenantInfoCountByTenantId(namespaceId) > 0) { + return false; + } + } + persistService.insertTenantInfoAtomic("1", namespaceId, namespaceName, namespaceDesc, "nacos", + System.currentTimeMillis()); + return true; + } - /** - * @author klw(213539@qq.com) - * @Description: check namespaceId exist - * @Date 2019/12/10 21:41 - * @param: namespaceId - * @return java.lang.Boolean - */ - @GetMapping(params = "checkNamespaceIdExist=true") - public Boolean checkNamespaceIdExist(@RequestParam("customNamespaceId") String namespaceId){ - if(StringUtils.isBlank(namespaceId)){ - return false; - } - return (persistService.tenantInfoCountByTenantId(namespaceId) > 0); - } + /** + * @author klw(213539@qq.com) + * @Description: check namespaceId exist + * @Date 2019/12/10 21:41 + * @param: namespaceId + * @return java.lang.Boolean + */ + @GetMapping(params = "checkNamespaceIdExist=true") + public Boolean checkNamespaceIdExist(@RequestParam("customNamespaceId") String namespaceId) { + if (StringUtils.isBlank(namespaceId)) { + return false; + } + return (persistService.tenantInfoCountByTenantId(namespaceId) > 0); + } - /** - * edit namespace - * - * @param namespace namespace - * @param namespaceShowName namespace ShowName - * @param namespaceDesc namespace Desc - * @return whether edit ok - */ - @PutMapping - @Secured(resource = NacosAuthConfig.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) { - // TODO 获取用kp - persistService.updateTenantNameAtomic("1", namespace, namespaceShowName, namespaceDesc); - return true; - } + /** + * edit namespace + * @param namespace namespace + * @param namespaceShowName namespace ShowName + * @param namespaceDesc namespace Desc + * @return whether edit ok + */ + @PutMapping + @Secured(resource = NacosAuthConfig.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) { + // TODO 获取用kp + persistService.updateTenantNameAtomic("1", namespace, namespaceShowName, namespaceDesc); + return true; + } - /** - * del namespace by id - * - * @param request request - * @param response response - * @param namespaceId namespace Id - * @return whether del ok - */ - @DeleteMapping - @Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "namespaces", action = ActionTypes.WRITE) - public Boolean deleteConfig(HttpServletRequest request, HttpServletResponse response, - @RequestParam("namespaceId") String namespaceId) { - persistService.removeTenantInfoAtomic("1", namespaceId); - return true; - } + /** + * del namespace by id + * @param request request + * @param response response + * @param namespaceId namespace Id + * @return whether del ok + */ + @DeleteMapping + @Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "namespaces", action = ActionTypes.WRITE) + public Boolean deleteConfig(HttpServletRequest request, HttpServletResponse response, + @RequestParam("namespaceId") String namespaceId) { + persistService.removeTenantInfoAtomic("1", namespaceId); + return true; + } } diff --git a/pigx-register/src/main/java/com/alibaba/nacos/console/controller/PermissionController.java b/pigx-register/src/main/java/com/alibaba/nacos/console/controller/PermissionController.java index 71339d4c5..79d95aa83 100755 --- a/pigx-register/src/main/java/com/alibaba/nacos/console/controller/PermissionController.java +++ b/pigx-register/src/main/java/com/alibaba/nacos/console/controller/PermissionController.java @@ -15,7 +15,6 @@ */ package com.alibaba.nacos.console.controller; - import com.alibaba.nacos.config.server.model.RestResult; import com.alibaba.nacos.console.security.nacos.NacosAuthConfig; import com.alibaba.nacos.console.security.nacos.roles.NacosRoleServiceImpl; @@ -25,7 +24,6 @@ import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; - /** * Permission operation controller * @@ -36,51 +34,50 @@ import org.springframework.web.bind.annotation.*; @RequestMapping("/v1/auth/permissions") public class PermissionController { - @Autowired - private NacosRoleServiceImpl nacosRoleService; + @Autowired + private NacosRoleServiceImpl nacosRoleService; - /** - * Query permissions of a role - * - * @param role the role - * @param pageNo page index - * @param pageSize page size - * @return permission of a role - */ - @GetMapping - @Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "permissions", action = ActionTypes.READ) - public Object getPermissions(@RequestParam int pageNo, @RequestParam int pageSize, - @RequestParam(name = "role", defaultValue = StringUtils.EMPTY) String role) { - return nacosRoleService.getPermissionsFromDatabase(role, pageNo, pageSize); - } + /** + * Query permissions of a role + * @param role the role + * @param pageNo page index + * @param pageSize page size + * @return permission of a role + */ + @GetMapping + @Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "permissions", action = ActionTypes.READ) + public Object getPermissions(@RequestParam int pageNo, @RequestParam int pageSize, + @RequestParam(name = "role", defaultValue = StringUtils.EMPTY) String role) { + return nacosRoleService.getPermissionsFromDatabase(role, pageNo, pageSize); + } - /** - * Add a permission to a role - * - * @param role the role - * @param resource the related resource - * @param action the related action - * @return ok if succeed - */ - @PostMapping - @Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "permissions", action = ActionTypes.WRITE) - public Object addPermission(@RequestParam String role, @RequestParam String resource, @RequestParam String action) { - nacosRoleService.addPermission(role, resource, action); - return new RestResult<>(200, "add permission ok!"); - } + /** + * Add a permission to a role + * @param role the role + * @param resource the related resource + * @param action the related action + * @return ok if succeed + */ + @PostMapping + @Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "permissions", action = ActionTypes.WRITE) + public Object addPermission(@RequestParam String role, @RequestParam String resource, @RequestParam String action) { + nacosRoleService.addPermission(role, resource, action); + return new RestResult<>(200, "add permission ok!"); + } + + /** + * Delete a permission from a role + * @param role the role + * @param resource the related resource + * @param action the related action + * @return ok if succeed + */ + @DeleteMapping + @Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "permissions", action = ActionTypes.WRITE) + public Object deletePermission(@RequestParam String role, @RequestParam String resource, + @RequestParam String action) { + nacosRoleService.deletePermission(role, resource, action); + return new RestResult<>(200, "delete permission ok!"); + } - /** - * Delete a permission from a role - * - * @param role the role - * @param resource the related resource - * @param action the related action - * @return ok if succeed - */ - @DeleteMapping - @Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "permissions", action = ActionTypes.WRITE) - public Object deletePermission(@RequestParam String role, @RequestParam String resource, @RequestParam String action) { - nacosRoleService.deletePermission(role, resource, action); - return new RestResult<>(200, "delete permission ok!"); - } } diff --git a/pigx-register/src/main/java/com/alibaba/nacos/console/controller/RoleController.java b/pigx-register/src/main/java/com/alibaba/nacos/console/controller/RoleController.java index 69d720f5c..aba9a98fe 100755 --- a/pigx-register/src/main/java/com/alibaba/nacos/console/controller/RoleController.java +++ b/pigx-register/src/main/java/com/alibaba/nacos/console/controller/RoleController.java @@ -15,7 +15,6 @@ */ package com.alibaba.nacos.console.controller; - import com.alibaba.nacos.config.server.model.RestResult; import com.alibaba.nacos.console.security.nacos.NacosAuthConfig; import com.alibaba.nacos.console.security.nacos.roles.NacosRoleServiceImpl; @@ -35,59 +34,56 @@ import org.springframework.web.bind.annotation.*; @RequestMapping("/v1/auth/roles") public class RoleController { - @Autowired - private NacosRoleServiceImpl roleService; + @Autowired + private NacosRoleServiceImpl roleService; - /** - * Get roles list - * - * @param pageNo number index of page - * @param pageSize page size - * @param username optional, username of user - * @return role list - */ - @GetMapping - @Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "roles", action = ActionTypes.READ) - public Object getRoles(@RequestParam int pageNo, @RequestParam int pageSize, - @RequestParam(name = "username", defaultValue = "") String username) { - return roleService.getRolesFromDatabase(username, pageNo, pageSize); - } + /** + * Get roles list + * @param pageNo number index of page + * @param pageSize page size + * @param username optional, username of user + * @return role list + */ + @GetMapping + @Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "roles", action = ActionTypes.READ) + public Object getRoles(@RequestParam int pageNo, @RequestParam int pageSize, + @RequestParam(name = "username", defaultValue = "") String username) { + return roleService.getRolesFromDatabase(username, pageNo, pageSize); + } - /** - * Add a role to a user - *

- * This method is used for 2 functions: - * 1. create a role and bind it to GLOBAL_ADMIN. - * 2. bind a role to an user. - * - * @param role - * @param username - * @return - */ - @PostMapping - @Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "roles", action = ActionTypes.WRITE) - public Object addRole(@RequestParam String role, @RequestParam String username) { - roleService.addRole(role, username); - return new RestResult<>(200, "add role ok!"); - } + /** + * Add a role to a user + *

+ * This method is used for 2 functions: 1. create a role and bind it to GLOBAL_ADMIN. + * 2. bind a role to an user. + * @param role + * @param username + * @return + */ + @PostMapping + @Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "roles", action = ActionTypes.WRITE) + public Object addRole(@RequestParam String role, @RequestParam String username) { + roleService.addRole(role, username); + return new RestResult<>(200, "add role ok!"); + } - /** - * Delete a role. If no username is specified, all users under this role are deleted - * - * @param role role - * @param username username - * @return ok if succeed - */ - @DeleteMapping - @Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "roles", action = ActionTypes.WRITE) - public Object deleteRole(@RequestParam String role, - @RequestParam(name = "username", defaultValue = StringUtils.EMPTY) String username) { - if (StringUtils.isBlank(username)) { - roleService.deleteRole(role); - } else { - roleService.deleteRole(role, username); - } - return new RestResult<>(200, "delete role of user " + username + " ok!"); - } + /** + * Delete a role. If no username is specified, all users under this role are deleted + * @param role role + * @param username username + * @return ok if succeed + */ + @DeleteMapping + @Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "roles", action = ActionTypes.WRITE) + public Object deleteRole(@RequestParam String role, + @RequestParam(name = "username", defaultValue = StringUtils.EMPTY) String username) { + if (StringUtils.isBlank(username)) { + roleService.deleteRole(role); + } + else { + roleService.deleteRole(role, username); + } + return new RestResult<>(200, "delete role of user " + username + " ok!"); + } } diff --git a/pigx-register/src/main/java/com/alibaba/nacos/console/controller/ServerStateController.java b/pigx-register/src/main/java/com/alibaba/nacos/console/controller/ServerStateController.java index 80e04d5ed..728bab1a6 100755 --- a/pigx-register/src/main/java/com/alibaba/nacos/console/controller/ServerStateController.java +++ b/pigx-register/src/main/java/com/alibaba/nacos/console/controller/ServerStateController.java @@ -15,7 +15,6 @@ */ package com.alibaba.nacos.console.controller; - import com.alibaba.nacos.common.utils.VersionUtils; import com.alibaba.nacos.core.utils.SystemUtils; import org.springframework.http.ResponseEntity; @@ -27,23 +26,22 @@ import java.util.HashMap; import java.util.Map; /** - * @author xingxuechao - * on:2019/2/27 11:17 AM + * @author xingxuechao on:2019/2/27 11:17 AM */ @RestController @RequestMapping("/v1/console/server") public class ServerStateController { - @GetMapping("/state") - public ResponseEntity serverState() { - Map serverState = new HashMap<>(3); - serverState.put("standalone_mode",SystemUtils.STANDALONE_MODE ? - SystemUtils.STANDALONE_MODE_ALONE : SystemUtils.STANDALONE_MODE_CLUSTER); + @GetMapping("/state") + public ResponseEntity serverState() { + Map serverState = new HashMap<>(3); + serverState.put("standalone_mode", + SystemUtils.STANDALONE_MODE ? SystemUtils.STANDALONE_MODE_ALONE : SystemUtils.STANDALONE_MODE_CLUSTER); - serverState.put("function_mode", SystemUtils.FUNCTION_MODE); - serverState.put("version", VersionUtils.VERSION); + serverState.put("function_mode", SystemUtils.FUNCTION_MODE); + serverState.put("version", VersionUtils.VERSION); - return ResponseEntity.ok().body(serverState); - } + return ResponseEntity.ok().body(serverState); + } } diff --git a/pigx-register/src/main/java/com/alibaba/nacos/console/controller/UserController.java b/pigx-register/src/main/java/com/alibaba/nacos/console/controller/UserController.java index 2daef8690..55b357fc4 100755 --- a/pigx-register/src/main/java/com/alibaba/nacos/console/controller/UserController.java +++ b/pigx-register/src/main/java/com/alibaba/nacos/console/controller/UserController.java @@ -48,185 +48,184 @@ import java.util.List; * @author nkorange */ @RestController("user") -@RequestMapping({"/v1/auth", "/v1/auth/users"}) +@RequestMapping({ "/v1/auth", "/v1/auth/users" }) public class UserController { - @Autowired - private JwtTokenUtils jwtTokenUtils; + @Autowired + private JwtTokenUtils jwtTokenUtils; - @Autowired - private AuthenticationManager authenticationManager; + @Autowired + private AuthenticationManager authenticationManager; - @Autowired - private NacosUserDetailsServiceImpl userDetailsService; + @Autowired + private NacosUserDetailsServiceImpl userDetailsService; - @Autowired - private NacosRoleServiceImpl roleService; + @Autowired + private NacosRoleServiceImpl roleService; - @Autowired - private AuthConfigs authConfigs; + @Autowired + private AuthConfigs authConfigs; - @Autowired - private NacosAuthManager authManager; + @Autowired + private NacosAuthManager authManager; - /** - * Create a new user - * - * @param username username - * @param password password - * @return ok if create succeed - * @throws IllegalArgumentException if user already exist - * @since 1.2.0 - */ - @Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "users", action = ActionTypes.WRITE) - @PostMapping - public Object createUser(@RequestParam String username, @RequestParam String password) { + /** + * Create a new user + * @param username username + * @param password password + * @return ok if create succeed + * @throws IllegalArgumentException if user already exist + * @since 1.2.0 + */ + @Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "users", action = ActionTypes.WRITE) + @PostMapping + public Object createUser(@RequestParam String username, @RequestParam String password) { - User user = userDetailsService.getUserFromDatabase(username); - if (user != null) { - throw new IllegalArgumentException("user '" + username + "' already exist!"); - } - userDetailsService.createUser(username, PasswordEncoderUtil.encode(password)); - return new RestResult<>(200, "create user ok!"); - } + User user = userDetailsService.getUserFromDatabase(username); + if (user != null) { + throw new IllegalArgumentException("user '" + username + "' already exist!"); + } + userDetailsService.createUser(username, PasswordEncoderUtil.encode(password)); + return new RestResult<>(200, "create user ok!"); + } - /** - * Delete an existed user - * - * @param username username of user - * @return ok if deleted succeed, keep silent if user not exist - * @since 1.2.0 - */ - @DeleteMapping - @Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "users", action = ActionTypes.WRITE) - public Object deleteUser(@RequestParam String username) { - List roleInfoList = roleService.getRoles(username); - if (roleInfoList != null) { - for (RoleInfo roleInfo : roleInfoList) { - if (roleInfo.getRole().equals(NacosRoleServiceImpl.GLOBAL_ADMIN_ROLE)) { - throw new IllegalArgumentException("cannot delete admin: " + username); - } - } - } - userDetailsService.deleteUser(username); - return new RestResult<>(200, "delete user ok!"); - } + /** + * Delete an existed user + * @param username username of user + * @return ok if deleted succeed, keep silent if user not exist + * @since 1.2.0 + */ + @DeleteMapping + @Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "users", action = ActionTypes.WRITE) + public Object deleteUser(@RequestParam String username) { + List roleInfoList = roleService.getRoles(username); + if (roleInfoList != null) { + for (RoleInfo roleInfo : roleInfoList) { + if (roleInfo.getRole().equals(NacosRoleServiceImpl.GLOBAL_ADMIN_ROLE)) { + throw new IllegalArgumentException("cannot delete admin: " + username); + } + } + } + userDetailsService.deleteUser(username); + return new RestResult<>(200, "delete user ok!"); + } - /** - * Update an user - * - * @param username username of user - * @param newPassword new password of user - * @return ok if update succeed - * @throws IllegalArgumentException if user not exist or oldPassword is incorrect - * @since 1.2.0 - */ - @PutMapping - @Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "users", action = ActionTypes.WRITE) - public Object updateUser(@RequestParam String username, @RequestParam String newPassword) { + /** + * Update an user + * @param username username of user + * @param newPassword new password of user + * @return ok if update succeed + * @throws IllegalArgumentException if user not exist or oldPassword is incorrect + * @since 1.2.0 + */ + @PutMapping + @Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "users", action = ActionTypes.WRITE) + public Object updateUser(@RequestParam String username, @RequestParam String newPassword) { - User user = userDetailsService.getUserFromDatabase(username); - if (user == null) { - throw new IllegalArgumentException("user " + username + " not exist!"); - } + User user = userDetailsService.getUserFromDatabase(username); + if (user == null) { + throw new IllegalArgumentException("user " + username + " not exist!"); + } - userDetailsService.updateUserPassword(username, PasswordEncoderUtil.encode(newPassword)); + userDetailsService.updateUserPassword(username, PasswordEncoderUtil.encode(newPassword)); - return new RestResult<>(200, "update user ok!"); - } + return new RestResult<>(200, "update user ok!"); + } - /** - * Get paged users - * - * @param pageNo number index of page - * @param pageSize size of page - * @return A collection of users, empty set if no user is found - * @since 1.2.0 - */ - @GetMapping - @Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "users", action = ActionTypes.READ) - public Object getUsers(@RequestParam int pageNo, @RequestParam int pageSize) { - return userDetailsService.getUsersFromDatabase(pageNo, pageSize); - } + /** + * Get paged users + * @param pageNo number index of page + * @param pageSize size of page + * @return A collection of users, empty set if no user is found + * @since 1.2.0 + */ + @GetMapping + @Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "users", action = ActionTypes.READ) + public Object getUsers(@RequestParam int pageNo, @RequestParam int pageSize) { + return userDetailsService.getUsersFromDatabase(pageNo, pageSize); + } - /** - * Login to Nacos - *

- * This methods uses username and password to require a new token. - * - * @param username username of user - * @param password password - * @param response http response - * @param request http request - * @return new token of the user - * @throws AccessException if user info is incorrect - */ - @PostMapping("/login") - public Object login(@RequestParam String username, @RequestParam String password, - HttpServletResponse response, HttpServletRequest request) throws AccessException { + /** + * Login to Nacos + *

+ * This methods uses username and password to require a new token. + * @param username username of user + * @param password password + * @param response http response + * @param request http request + * @return new token of the user + * @throws AccessException if user info is incorrect + */ + @PostMapping("/login") + public Object login(@RequestParam String username, @RequestParam String password, HttpServletResponse response, + HttpServletRequest request) throws AccessException { + if (AuthSystemTypes.NACOS.name().equalsIgnoreCase(authConfigs.getNacosAuthSystemType())) { + NacosUser user = (NacosUser) authManager.login(request); - if (AuthSystemTypes.NACOS.name().equalsIgnoreCase(authConfigs.getNacosAuthSystemType())) { - NacosUser user = (NacosUser) authManager.login(request); + response.addHeader(NacosAuthConfig.AUTHORIZATION_HEADER, NacosAuthConfig.TOKEN_PREFIX + user.getToken()); - response.addHeader(NacosAuthConfig.AUTHORIZATION_HEADER, - NacosAuthConfig.TOKEN_PREFIX + user.getToken()); + JSONObject result = new JSONObject(); + result.put(Constants.ACCESS_TOKEN, user.getToken()); + result.put(Constants.TOKEN_TTL, authConfigs.getTokenValidityInSeconds()); + result.put(Constants.GLOBAL_ADMIN, user.isGlobalAdmin()); + return result; + } - JSONObject result = new JSONObject(); - result.put(Constants.ACCESS_TOKEN, user.getToken()); - result.put(Constants.TOKEN_TTL, authConfigs.getTokenValidityInSeconds()); - result.put(Constants.GLOBAL_ADMIN, user.isGlobalAdmin()); - return result; - } + // 通过用户名和密码创建一个 Authentication 认证对象,实现类为 UsernamePasswordAuthenticationToken + UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, + password); - // 通过用户名和密码创建一个 Authentication 认证对象,实现类为 UsernamePasswordAuthenticationToken - UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password); + RestResult rr = new RestResult(); + try { + // 通过 AuthenticationManager(默认实现为ProviderManager)的authenticate方法验证 + // Authentication 对象 + Authentication authentication = authenticationManager.authenticate(authenticationToken); + // 将 Authentication 绑定到 SecurityContext + SecurityContextHolder.getContext().setAuthentication(authentication); + // 生成Token + String token = jwtTokenUtils.createToken(authentication); + // 将Token写入到Http头部 + response.addHeader(NacosAuthConfig.AUTHORIZATION_HEADER, "Bearer " + token); + rr.setCode(200); + rr.setData("Bearer " + token); + return rr; + } + catch (BadCredentialsException authentication) { + rr.setCode(401); + rr.setMessage("Login failed"); + return rr; + } + } - RestResult rr = new RestResult(); - try { - //通过 AuthenticationManager(默认实现为ProviderManager)的authenticate方法验证 Authentication 对象 - Authentication authentication = authenticationManager.authenticate(authenticationToken); - //将 Authentication 绑定到 SecurityContext - SecurityContextHolder.getContext().setAuthentication(authentication); - //生成Token - String token = jwtTokenUtils.createToken(authentication); - //将Token写入到Http头部 - response.addHeader(NacosAuthConfig.AUTHORIZATION_HEADER, "Bearer " + token); - rr.setCode(200); - rr.setData("Bearer " + token); - return rr; - } catch (BadCredentialsException authentication) { - rr.setCode(401); - rr.setMessage("Login failed"); - return rr; - } - } + @PutMapping("/password") + @Deprecated + public RestResult updatePassword(@RequestParam(value = "oldPassword") String oldPassword, + @RequestParam(value = "newPassword") String newPassword) { - @PutMapping("/password") - @Deprecated - public RestResult updatePassword(@RequestParam(value = "oldPassword") String oldPassword, - @RequestParam(value = "newPassword") String newPassword) { + RestResult rr = new RestResult(); + Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); + String username = ((UserDetails) principal).getUsername(); + User user = userDetailsService.getUserFromDatabase(username); + String password = user.getPassword(); - RestResult rr = new RestResult(); - Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); - String username = ((UserDetails) principal).getUsername(); - User user = userDetailsService.getUserFromDatabase(username); - String password = user.getPassword(); + // TODO: throw out more fine grained exceptions + try { + if (PasswordEncoderUtil.matches(oldPassword, password)) { + userDetailsService.updateUserPassword(username, PasswordEncoderUtil.encode(newPassword)); + rr.setCode(200); + rr.setMessage("Update password success"); + } + else { + rr.setCode(401); + rr.setMessage("Old password is invalid"); + } + } + catch (Exception e) { + rr.setCode(500); + rr.setMessage("Update userpassword failed"); + } + return rr; + } - // TODO: throw out more fine grained exceptions - try { - if (PasswordEncoderUtil.matches(oldPassword, password)) { - userDetailsService.updateUserPassword(username, PasswordEncoderUtil.encode(newPassword)); - rr.setCode(200); - rr.setMessage("Update password success"); - } else { - rr.setCode(401); - rr.setMessage("Old password is invalid"); - } - } catch (Exception e) { - rr.setCode(500); - rr.setMessage("Update userpassword failed"); - } - return rr; - } } diff --git a/pigx-register/src/main/java/com/alibaba/nacos/console/exception/ConsoleExceptionHandler.java b/pigx-register/src/main/java/com/alibaba/nacos/console/exception/ConsoleExceptionHandler.java index 9d9d285a3..65b9a7362 100755 --- a/pigx-register/src/main/java/com/alibaba/nacos/console/exception/ConsoleExceptionHandler.java +++ b/pigx-register/src/main/java/com/alibaba/nacos/console/exception/ConsoleExceptionHandler.java @@ -32,21 +32,22 @@ import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice public class ConsoleExceptionHandler { - private static final Logger logger = LoggerFactory.getLogger(ConsoleExceptionHandler.class); + private static final Logger logger = LoggerFactory.getLogger(ConsoleExceptionHandler.class); - @ExceptionHandler(AccessException.class) - private ResponseEntity handleAccessException(AccessException e) { - return ResponseEntity.status(HttpStatus.FORBIDDEN).body(e.getErrMsg()); - } + @ExceptionHandler(AccessException.class) + private ResponseEntity handleAccessException(AccessException e) { + return ResponseEntity.status(HttpStatus.FORBIDDEN).body(e.getErrMsg()); + } - @ExceptionHandler(IllegalArgumentException.class) - private ResponseEntity handleIllegalArgumentException(IllegalArgumentException e) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.toString()); - } + @ExceptionHandler(IllegalArgumentException.class) + private ResponseEntity handleIllegalArgumentException(IllegalArgumentException e) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.toString()); + } + + @ExceptionHandler(Exception.class) + private ResponseEntity handleException(Exception e) { + logger.error("CONSOLE", e); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.toString()); + } - @ExceptionHandler(Exception.class) - private ResponseEntity handleException(Exception e) { - logger.error("CONSOLE", e); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.toString()); - } } diff --git a/pigx-register/src/main/java/com/alibaba/nacos/console/filter/JwtAuthenticationTokenFilter.java b/pigx-register/src/main/java/com/alibaba/nacos/console/filter/JwtAuthenticationTokenFilter.java index e4ba2c547..3a1bb882d 100755 --- a/pigx-register/src/main/java/com/alibaba/nacos/console/filter/JwtAuthenticationTokenFilter.java +++ b/pigx-register/src/main/java/com/alibaba/nacos/console/filter/JwtAuthenticationTokenFilter.java @@ -36,40 +36,41 @@ import java.io.IOException; */ public class JwtAuthenticationTokenFilter extends OncePerRequestFilter { - private static final String TOKEN_PREFIX = "Bearer "; + private static final String TOKEN_PREFIX = "Bearer "; - private JwtTokenManager tokenManager; + private JwtTokenManager tokenManager; - public JwtAuthenticationTokenFilter(JwtTokenManager tokenManager) { - this.tokenManager = tokenManager; - } + public JwtAuthenticationTokenFilter(JwtTokenManager tokenManager) { + this.tokenManager = tokenManager; + } - @Override - protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) - throws IOException, ServletException { + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws IOException, ServletException { - String jwt = resolveToken(request); + String jwt = resolveToken(request); - if (StringUtils.isNotBlank(jwt) && SecurityContextHolder.getContext().getAuthentication() == null) { - this.tokenManager.validateToken(jwt); - Authentication authentication = this.tokenManager.getAuthentication(jwt); - SecurityContextHolder.getContext().setAuthentication(authentication); - } - chain.doFilter(request, response); - } + if (StringUtils.isNotBlank(jwt) && SecurityContextHolder.getContext().getAuthentication() == null) { + this.tokenManager.validateToken(jwt); + Authentication authentication = this.tokenManager.getAuthentication(jwt); + SecurityContextHolder.getContext().setAuthentication(authentication); + } + chain.doFilter(request, response); + } + + /** + * Get token from header + */ + private String resolveToken(HttpServletRequest request) { + String bearerToken = request.getHeader(NacosAuthConfig.AUTHORIZATION_HEADER); + if (StringUtils.isNotBlank(bearerToken) && bearerToken.startsWith(TOKEN_PREFIX)) { + return bearerToken.substring(7); + } + String jwt = request.getParameter(Constants.ACCESS_TOKEN); + if (StringUtils.isNotBlank(jwt)) { + return jwt; + } + return null; + } - /** - * Get token from header - */ - private String resolveToken(HttpServletRequest request) { - String bearerToken = request.getHeader(NacosAuthConfig.AUTHORIZATION_HEADER); - if (StringUtils.isNotBlank(bearerToken) && bearerToken.startsWith(TOKEN_PREFIX)) { - return bearerToken.substring(7); - } - String jwt = request.getParameter(Constants.ACCESS_TOKEN); - if (StringUtils.isNotBlank(jwt)) { - return jwt; - } - return null; - } } diff --git a/pigx-register/src/main/java/com/alibaba/nacos/console/model/Namespace.java b/pigx-register/src/main/java/com/alibaba/nacos/console/model/Namespace.java index c617f10c0..6323eaa21 100755 --- a/pigx-register/src/main/java/com/alibaba/nacos/console/model/Namespace.java +++ b/pigx-register/src/main/java/com/alibaba/nacos/console/model/Namespace.java @@ -22,72 +22,73 @@ package com.alibaba.nacos.console.model; */ public class Namespace { - private String namespace; + private String namespace; - private String namespaceShowName; + private String namespaceShowName; - private int quota; + private int quota; - private int configCount; - /** - * 0 : Global configuration, 1 : Default private namespace ,2 : Custom namespace - */ - private int type; + private int configCount; - public String getNamespaceShowName() { - return namespaceShowName; - } + /** + * 0 : Global configuration, 1 : Default private namespace ,2 : Custom namespace + */ + private int type; - public void setNamespaceShowName(String namespaceShowName) { - this.namespaceShowName = namespaceShowName; - } + public String getNamespaceShowName() { + return namespaceShowName; + } - public String getNamespace() { - return namespace; - } + public void setNamespaceShowName(String namespaceShowName) { + this.namespaceShowName = namespaceShowName; + } - public void setNamespace(String namespace) { - this.namespace = namespace; - } + public String getNamespace() { + return namespace; + } - public Namespace() { - } + public void setNamespace(String namespace) { + this.namespace = namespace; + } - public Namespace(String namespace, String namespaceShowName) { - this.namespace = namespace; - this.namespaceShowName = namespaceShowName; - } + public Namespace() { + } - public Namespace(String namespace, String namespaceShowName, int quota, int configCount, int type) { - this.namespace = namespace; - this.namespaceShowName = namespaceShowName; - this.quota = quota; - this.configCount = configCount; - this.type = type; - } + public Namespace(String namespace, String namespaceShowName) { + this.namespace = namespace; + this.namespaceShowName = namespaceShowName; + } - public int getQuota() { - return quota; - } + public Namespace(String namespace, String namespaceShowName, int quota, int configCount, int type) { + this.namespace = namespace; + this.namespaceShowName = namespaceShowName; + this.quota = quota; + this.configCount = configCount; + this.type = type; + } - public void setQuota(int quota) { - this.quota = quota; - } + public int getQuota() { + return quota; + } - public int getConfigCount() { - return configCount; - } + public void setQuota(int quota) { + this.quota = quota; + } - public void setConfigCount(int configCount) { - this.configCount = configCount; - } + public int getConfigCount() { + return configCount; + } - public int getType() { - return type; - } + public void setConfigCount(int configCount) { + this.configCount = configCount; + } - public void setType(int type) { - this.type = type; - } + public int getType() { + return type; + } + + public void setType(int type) { + this.type = type; + } } diff --git a/pigx-register/src/main/java/com/alibaba/nacos/console/model/NamespaceAllInfo.java b/pigx-register/src/main/java/com/alibaba/nacos/console/model/NamespaceAllInfo.java index bbd63ce38..5368b815d 100755 --- a/pigx-register/src/main/java/com/alibaba/nacos/console/model/NamespaceAllInfo.java +++ b/pigx-register/src/main/java/com/alibaba/nacos/console/model/NamespaceAllInfo.java @@ -22,23 +22,23 @@ package com.alibaba.nacos.console.model; */ public class NamespaceAllInfo extends Namespace { - private String namespaceDesc; + private String namespaceDesc; - public String getNamespaceDesc() { - return namespaceDesc; - } + public String getNamespaceDesc() { + return namespaceDesc; + } - public void setNamespaceDesc(String namespaceDesc) { - this.namespaceDesc = namespaceDesc; - } + public void setNamespaceDesc(String namespaceDesc) { + this.namespaceDesc = namespaceDesc; + } - public NamespaceAllInfo() { - } + public NamespaceAllInfo() { + } - public NamespaceAllInfo(String namespace, String namespaceShowName, int quota, int configCount, int type, - String namespaceDesc) { - super(namespace, namespaceShowName, quota, configCount, type); - this.namespaceDesc = namespaceDesc; - } + public NamespaceAllInfo(String namespace, String namespaceShowName, int quota, int configCount, int type, + String namespaceDesc) { + super(namespace, namespaceShowName, quota, configCount, type); + this.namespaceDesc = namespaceDesc; + } } diff --git a/pigx-register/src/main/java/com/alibaba/nacos/console/security/nacos/CustomAuthenticationProvider.java b/pigx-register/src/main/java/com/alibaba/nacos/console/security/nacos/CustomAuthenticationProvider.java index c54db33f7..51ac1afb0 100755 --- a/pigx-register/src/main/java/com/alibaba/nacos/console/security/nacos/CustomAuthenticationProvider.java +++ b/pigx-register/src/main/java/com/alibaba/nacos/console/security/nacos/CustomAuthenticationProvider.java @@ -32,25 +32,25 @@ import org.springframework.stereotype.Component; @Component public class CustomAuthenticationProvider implements AuthenticationProvider { - @Autowired - private NacosUserDetailsServiceImpl userDetailsService; + @Autowired + private NacosUserDetailsServiceImpl userDetailsService; - @Override - public Authentication authenticate(Authentication authentication) throws AuthenticationException { + @Override + public Authentication authenticate(Authentication authentication) throws AuthenticationException { - String username = (String) authentication.getPrincipal(); - String password = (String) authentication.getCredentials(); - UserDetails userDetails = userDetailsService.loadUserByUsername(username); + String username = (String) authentication.getPrincipal(); + String password = (String) authentication.getCredentials(); + UserDetails userDetails = userDetailsService.loadUserByUsername(username); - if (!password.equals(userDetails.getPassword())) { - return new UsernamePasswordAuthenticationToken(username, null, null); - } - return null; - } + if (!password.equals(userDetails.getPassword())) { + return new UsernamePasswordAuthenticationToken(username, null, null); + } + return null; + } - @Override - public boolean supports(Class aClass) { - return aClass.equals(UsernamePasswordAuthenticationToken.class); - } + @Override + public boolean supports(Class aClass) { + return aClass.equals(UsernamePasswordAuthenticationToken.class); + } } diff --git a/pigx-register/src/main/java/com/alibaba/nacos/console/security/nacos/JwtAuthenticationEntryPoint.java b/pigx-register/src/main/java/com/alibaba/nacos/console/security/nacos/JwtAuthenticationEntryPoint.java index dad99758c..3cb0a7f7b 100755 --- a/pigx-register/src/main/java/com/alibaba/nacos/console/security/nacos/JwtAuthenticationEntryPoint.java +++ b/pigx-register/src/main/java/com/alibaba/nacos/console/security/nacos/JwtAuthenticationEntryPoint.java @@ -34,13 +34,13 @@ import java.io.IOException; @Component public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint { - private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationEntryPoint.class); + private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationEntryPoint.class); + + @Override + public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) + throws IOException, ServletException { + logger.error("Responding with unauthorized error. Message:{}, url:{}", e.getMessage(), request.getRequestURI()); + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); + } - @Override - public void commence(HttpServletRequest request, - HttpServletResponse response, - AuthenticationException e) throws IOException, ServletException { - logger.error("Responding with unauthorized error. Message:{}, url:{}", e.getMessage(), request.getRequestURI()); - response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); - } } diff --git a/pigx-register/src/main/java/com/alibaba/nacos/console/security/nacos/JwtTokenManager.java b/pigx-register/src/main/java/com/alibaba/nacos/console/security/nacos/JwtTokenManager.java index 0ef8fce1f..c66bfec09 100755 --- a/pigx-register/src/main/java/com/alibaba/nacos/console/security/nacos/JwtTokenManager.java +++ b/pigx-register/src/main/java/com/alibaba/nacos/console/security/nacos/JwtTokenManager.java @@ -40,65 +40,58 @@ import java.util.List; @Component public class JwtTokenManager { - private static final String AUTHORITIES_KEY = "auth"; + private static final String AUTHORITIES_KEY = "auth"; - @Autowired - private AuthConfigs authConfigs; + @Autowired + private AuthConfigs authConfigs; - /** - * Create token - * - * @param authentication auth info - * @return token - */ - public String createToken(Authentication authentication) { - return createToken(authentication.getName()); - } + /** + * Create token + * @param authentication auth info + * @return token + */ + public String createToken(Authentication authentication) { + return createToken(authentication.getName()); + } - public String createToken(String userName) { + public String createToken(String userName) { - long now = (new Date()).getTime(); + long now = (new Date()).getTime(); - Date validity; - validity = new Date(now + authConfigs.getTokenValidityInSeconds() * 1000L); + Date validity; + validity = new Date(now + authConfigs.getTokenValidityInSeconds() * 1000L); - Claims claims = Jwts.claims().setSubject(userName); + Claims claims = Jwts.claims().setSubject(userName); - return Jwts.builder() - .setClaims(claims) - .setExpiration(validity) - .signWith(SignatureAlgorithm.HS256, authConfigs.getSecretKey()) - .compact(); - } + return Jwts.builder().setClaims(claims).setExpiration(validity) + .signWith(SignatureAlgorithm.HS256, authConfigs.getSecretKey()).compact(); + } - /** - * Get auth Info - * - * @param token token - * @return auth info - */ - public Authentication getAuthentication(String token) { - /** - * parse the payload of token - */ - Claims claims = Jwts.parser() - .setSigningKey(authConfigs.getSecretKey()) - .parseClaimsJws(token) - .getBody(); + /** + * Get auth Info + * @param token token + * @return auth info + */ + public Authentication getAuthentication(String token) { + /** + * parse the payload of token + */ + Claims claims = Jwts.parser().setSigningKey(authConfigs.getSecretKey()).parseClaimsJws(token).getBody(); - List authorities = AuthorityUtils.commaSeparatedStringToAuthorityList((String) claims.get(AUTHORITIES_KEY)); + List authorities = AuthorityUtils + .commaSeparatedStringToAuthorityList((String) claims.get(AUTHORITIES_KEY)); - User principal = new User(claims.getSubject(), "", authorities); - return new UsernamePasswordAuthenticationToken(principal, "", authorities); - } + User principal = new User(claims.getSubject(), "", authorities); + return new UsernamePasswordAuthenticationToken(principal, "", authorities); + } + + /** + * validate token + * @param token token + * @return whether valid + */ + public void validateToken(String token) { + Jwts.parser().setSigningKey(authConfigs.getSecretKey()).parseClaimsJws(token); + } - /** - * validate token - * - * @param token token - * @return whether valid - */ - public void validateToken(String token) { - Jwts.parser().setSigningKey(authConfigs.getSecretKey()).parseClaimsJws(token); - } } diff --git a/pigx-register/src/main/java/com/alibaba/nacos/console/security/nacos/NacosAuthConfig.java b/pigx-register/src/main/java/com/alibaba/nacos/console/security/nacos/NacosAuthConfig.java index 78fe636b5..b9c778f2d 100755 --- a/pigx-register/src/main/java/com/alibaba/nacos/console/security/nacos/NacosAuthConfig.java +++ b/pigx-register/src/main/java/com/alibaba/nacos/console/security/nacos/NacosAuthConfig.java @@ -15,7 +15,6 @@ */ package com.alibaba.nacos.console.security.nacos; - import com.alibaba.nacos.console.filter.JwtAuthenticationTokenFilter; import com.alibaba.nacos.console.security.nacos.users.NacosUserDetailsServiceImpl; import com.alibaba.nacos.core.auth.AuthConfigs; @@ -48,99 +47,92 @@ import org.springframework.web.cors.CorsUtils; @EnableGlobalMethodSecurity(prePostEnabled = true) public class NacosAuthConfig extends WebSecurityConfigurerAdapter { - public static final String AUTHORIZATION_HEADER = "Authorization"; + public static final String AUTHORIZATION_HEADER = "Authorization"; - public static final String SECURITY_IGNORE_URLS_SPILT_CHAR = ","; + public static final String SECURITY_IGNORE_URLS_SPILT_CHAR = ","; - public static final String LOGIN_ENTRY_POINT = "/v1/auth/login"; + public static final String LOGIN_ENTRY_POINT = "/v1/auth/login"; - public static final String TOKEN_BASED_AUTH_ENTRY_POINT = "/v1/auth/**"; + public static final String TOKEN_BASED_AUTH_ENTRY_POINT = "/v1/auth/**"; - public static final String TOKEN_PREFIX = "Bearer "; + public static final String TOKEN_PREFIX = "Bearer "; - public static final String CONSOLE_RESOURCE_NAME_PREFIX = "console/"; + public static final String CONSOLE_RESOURCE_NAME_PREFIX = "console/"; - @Autowired - private Environment env; + @Autowired + private Environment env; - @Autowired - private JwtTokenManager tokenProvider; + @Autowired + private JwtTokenManager tokenProvider; - @Autowired - private AuthConfigs authConfigs; + @Autowired + private AuthConfigs authConfigs; - @Autowired - private NacosUserDetailsServiceImpl userDetailsService; + @Autowired + private NacosUserDetailsServiceImpl userDetailsService; - @Value("${nacos.security.ignore.urls}") + @Value("${nacos.security.ignore.urls}") private String ignoreURLs; - @Bean(name = BeanIds.AUTHENTICATION_MANAGER) - @Override - public AuthenticationManager authenticationManagerBean() throws Exception { - return super.authenticationManagerBean(); - } + @Bean(name = BeanIds.AUTHENTICATION_MANAGER) + @Override + public AuthenticationManager authenticationManagerBean() throws Exception { + return super.authenticationManagerBean(); + } - @Override - public void configure(WebSecurity web) { + @Override + public void configure(WebSecurity web) { - if (AuthSystemTypes.NACOS.name().equalsIgnoreCase(authConfigs.getNacosAuthSystemType())) { - ignoreURLs = "/**"; - } -// - if (StringUtils.isBlank(authConfigs.getNacosAuthSystemType())) { - ignoreURLs = env.getProperty("nacos.security.ignore.urls", "/**"); - } + if (AuthSystemTypes.NACOS.name().equalsIgnoreCase(authConfigs.getNacosAuthSystemType())) { + ignoreURLs = "/**"; + } + // + if (StringUtils.isBlank(authConfigs.getNacosAuthSystemType())) { + ignoreURLs = env.getProperty("nacos.security.ignore.urls", "/**"); + } - if (StringUtils.isNotBlank(ignoreURLs)) { - for (String ignoreURL : ignoreURLs.trim().split(SECURITY_IGNORE_URLS_SPILT_CHAR)) { - web.ignoring().antMatchers(ignoreURL.trim()); - } - } + if (StringUtils.isNotBlank(ignoreURLs)) { + for (String ignoreURL : ignoreURLs.trim().split(SECURITY_IGNORE_URLS_SPILT_CHAR)) { + web.ignoring().antMatchers(ignoreURL.trim()); + } + } - } + } - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); - } + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); + } - @Override - protected void configure(HttpSecurity http) throws Exception { + @Override + protected void configure(HttpSecurity http) throws Exception { - if (StringUtils.isBlank(authConfigs.getNacosAuthSystemType())) { - http + if (StringUtils.isBlank(authConfigs.getNacosAuthSystemType())) { + http - .csrf().disable() - .cors() // We don't need CSRF for JWT based authentication + .csrf().disable().cors() // We don't need CSRF for JWT based + // authentication - .and() - .sessionManagement() - .sessionCreationPolicy(SessionCreationPolicy.STATELESS) + .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) - .and() - .authorizeRequests() - .requestMatchers(CorsUtils::isPreFlightRequest).permitAll() - .antMatchers(LOGIN_ENTRY_POINT).permitAll() + .and().authorizeRequests().requestMatchers(CorsUtils::isPreFlightRequest).permitAll() + .antMatchers(LOGIN_ENTRY_POINT).permitAll() - .and() - .authorizeRequests() - .antMatchers(TOKEN_BASED_AUTH_ENTRY_POINT).authenticated() + .and().authorizeRequests().antMatchers(TOKEN_BASED_AUTH_ENTRY_POINT).authenticated() - .and() - .exceptionHandling() - .authenticationEntryPoint(new JwtAuthenticationEntryPoint()); + .and().exceptionHandling().authenticationEntryPoint(new JwtAuthenticationEntryPoint()); - // disable cache - http.headers().cacheControl(); + // disable cache + http.headers().cacheControl(); - http.addFilterBefore(new JwtAuthenticationTokenFilter(tokenProvider), UsernamePasswordAuthenticationFilter.class); - } - } + http.addFilterBefore(new JwtAuthenticationTokenFilter(tokenProvider), + UsernamePasswordAuthenticationFilter.class); + } + } - @Bean - public PasswordEncoder passwordEncoder() { - return new BCryptPasswordEncoder(); - } + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } } diff --git a/pigx-register/src/main/java/com/alibaba/nacos/console/security/nacos/NacosAuthManager.java b/pigx-register/src/main/java/com/alibaba/nacos/console/security/nacos/NacosAuthManager.java index bd6d12293..4b04539ed 100755 --- a/pigx-register/src/main/java/com/alibaba/nacos/console/security/nacos/NacosAuthManager.java +++ b/pigx-register/src/main/java/com/alibaba/nacos/console/security/nacos/NacosAuthManager.java @@ -46,91 +46,96 @@ import java.util.List; @Component public class NacosAuthManager implements AuthManager { - private static final String TOKEN_PREFIX = "Bearer "; + private static final String TOKEN_PREFIX = "Bearer "; - @Autowired - private JwtTokenManager tokenManager; + @Autowired + private JwtTokenManager tokenManager; - @Autowired - private AuthenticationManager authenticationManager; + @Autowired + private AuthenticationManager authenticationManager; - @Autowired - private NacosRoleServiceImpl roleService; + @Autowired + private NacosRoleServiceImpl roleService; - @Override - public User login(Object request) throws AccessException { - HttpServletRequest req = (HttpServletRequest) request; - String token = resolveToken(req); - if (StringUtils.isBlank(token)) { - throw new AccessException("user not found!"); - } + @Override + public User login(Object request) throws AccessException { + HttpServletRequest req = (HttpServletRequest) request; + String token = resolveToken(req); + if (StringUtils.isBlank(token)) { + throw new AccessException("user not found!"); + } - try { - tokenManager.validateToken(token); - } catch (ExpiredJwtException e) { - throw new AccessException("token expired!"); - } catch (Exception e) { - throw new AccessException("token invalid!"); - } + try { + tokenManager.validateToken(token); + } + catch (ExpiredJwtException e) { + throw new AccessException("token expired!"); + } + catch (Exception e) { + throw new AccessException("token invalid!"); + } - Authentication authentication = tokenManager.getAuthentication(token); - SecurityContextHolder.getContext().setAuthentication(authentication); + Authentication authentication = tokenManager.getAuthentication(token); + SecurityContextHolder.getContext().setAuthentication(authentication); - String username = authentication.getName(); - NacosUser user = new NacosUser(); - user.setUserName(username); - user.setToken(token); - List roleInfoList = roleService.getRoles(username); - if (roleInfoList != null) { - for (RoleInfo roleInfo : roleInfoList) { - if (roleInfo.getRole().equals(NacosRoleServiceImpl.GLOBAL_ADMIN_ROLE)) { - user.setGlobalAdmin(true); - break; - } - } - } + String username = authentication.getName(); + NacosUser user = new NacosUser(); + user.setUserName(username); + user.setToken(token); + List roleInfoList = roleService.getRoles(username); + if (roleInfoList != null) { + for (RoleInfo roleInfo : roleInfoList) { + if (roleInfo.getRole().equals(NacosRoleServiceImpl.GLOBAL_ADMIN_ROLE)) { + user.setGlobalAdmin(true); + break; + } + } + } - return user; - } + return user; + } - @Override - public void auth(Permission permission, User user) throws AccessException { - if (Loggers.AUTH.isDebugEnabled()) { - Loggers.AUTH.debug("auth permission: {}, user: {}", permission, user); - } + @Override + public void auth(Permission permission, User user) throws AccessException { + if (Loggers.AUTH.isDebugEnabled()) { + Loggers.AUTH.debug("auth permission: {}, user: {}", permission, user); + } - if (!roleService.hasPermission(user.getUserName(), permission)) { - throw new AccessException("authorization failed!"); - } - } + if (!roleService.hasPermission(user.getUserName(), permission)) { + throw new AccessException("authorization failed!"); + } + } - /** - * Get token from header - */ - private String resolveToken(HttpServletRequest request) throws AccessException { - String bearerToken = request.getHeader(NacosAuthConfig.AUTHORIZATION_HEADER); - if (StringUtils.isNotBlank(bearerToken) && bearerToken.startsWith(TOKEN_PREFIX)) { - return bearerToken.substring(7); - } - bearerToken = request.getParameter(Constants.ACCESS_TOKEN); - if (StringUtils.isBlank(bearerToken)) { - String userName = request.getParameter("username"); - String password = request.getParameter("password"); - bearerToken = resolveTokenFromUser(userName, password); - } + /** + * Get token from header + */ + private String resolveToken(HttpServletRequest request) throws AccessException { + String bearerToken = request.getHeader(NacosAuthConfig.AUTHORIZATION_HEADER); + if (StringUtils.isNotBlank(bearerToken) && bearerToken.startsWith(TOKEN_PREFIX)) { + return bearerToken.substring(7); + } + bearerToken = request.getParameter(Constants.ACCESS_TOKEN); + if (StringUtils.isBlank(bearerToken)) { + String userName = request.getParameter("username"); + String password = request.getParameter("password"); + bearerToken = resolveTokenFromUser(userName, password); + } - return bearerToken; - } + return bearerToken; + } - private String resolveTokenFromUser(String userName, String rawPassword) throws AccessException { + private String resolveTokenFromUser(String userName, String rawPassword) throws AccessException { - try { - UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userName, rawPassword); - authenticationManager.authenticate(authenticationToken); - } catch (AuthenticationException e) { - throw new AccessException("unknown user!"); - } + try { + UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userName, + rawPassword); + authenticationManager.authenticate(authenticationToken); + } + catch (AuthenticationException e) { + throw new AccessException("unknown user!"); + } + + return tokenManager.createToken(userName); + } - return tokenManager.createToken(userName); - } } diff --git a/pigx-register/src/main/java/com/alibaba/nacos/console/security/nacos/roles/NacosRoleServiceImpl.java b/pigx-register/src/main/java/com/alibaba/nacos/console/security/nacos/roles/NacosRoleServiceImpl.java index 0799c1f31..706f52150 100755 --- a/pigx-register/src/main/java/com/alibaba/nacos/console/security/nacos/roles/NacosRoleServiceImpl.java +++ b/pigx-register/src/main/java/com/alibaba/nacos/console/security/nacos/roles/NacosRoleServiceImpl.java @@ -15,7 +15,6 @@ */ package com.alibaba.nacos.console.security.nacos.roles; - import com.alibaba.nacos.config.server.auth.PermissionInfo; import com.alibaba.nacos.config.server.auth.PermissionPersistService; import com.alibaba.nacos.config.server.auth.RoleInfo; @@ -46,174 +45,177 @@ import java.util.regex.Pattern; @Service public class NacosRoleServiceImpl { - public static final String GLOBAL_ADMIN_ROLE = "ROLE_ADMIN"; + public static final String GLOBAL_ADMIN_ROLE = "ROLE_ADMIN"; - @Autowired - private AuthConfigs authConfigs; + @Autowired + private AuthConfigs authConfigs; - @Autowired - private RolePersistService rolePersistService; + @Autowired + private RolePersistService rolePersistService; - @Autowired - private NacosUserDetailsServiceImpl userDetailsService; + @Autowired + private NacosUserDetailsServiceImpl userDetailsService; - @Autowired - private PermissionPersistService permissionPersistService; + @Autowired + private PermissionPersistService permissionPersistService; - private Set roleSet = new ConcurrentHashSet<>(); + private Set roleSet = new ConcurrentHashSet<>(); - private Map> roleInfoMap = new ConcurrentHashMap<>(); + private Map> roleInfoMap = new ConcurrentHashMap<>(); - private Map> permissionInfoMap = new ConcurrentHashMap<>(); + private Map> permissionInfoMap = new ConcurrentHashMap<>(); - @Scheduled(initialDelay = 5000, fixedDelay = 15000) - private void reload() { - try { - Page roleInfoPage = rolePersistService.getRolesByUserName(StringUtils.EMPTY, 1, Integer.MAX_VALUE); - if (roleInfoPage == null) { - return; - } - Set tmpRoleSet = new HashSet<>(16); - Map> tmpRoleInfoMap = new ConcurrentHashMap<>(16); - for (RoleInfo roleInfo : roleInfoPage.getPageItems()) { - if (!tmpRoleInfoMap.containsKey(roleInfo.getUsername())) { - tmpRoleInfoMap.put(roleInfo.getUsername(), new ArrayList<>()); - } - tmpRoleInfoMap.get(roleInfo.getUsername()).add(roleInfo); - tmpRoleSet.add(roleInfo.getRole()); - } + @Scheduled(initialDelay = 5000, fixedDelay = 15000) + private void reload() { + try { + Page roleInfoPage = rolePersistService.getRolesByUserName(StringUtils.EMPTY, 1, + Integer.MAX_VALUE); + if (roleInfoPage == null) { + return; + } + Set tmpRoleSet = new HashSet<>(16); + Map> tmpRoleInfoMap = new ConcurrentHashMap<>(16); + for (RoleInfo roleInfo : roleInfoPage.getPageItems()) { + if (!tmpRoleInfoMap.containsKey(roleInfo.getUsername())) { + tmpRoleInfoMap.put(roleInfo.getUsername(), new ArrayList<>()); + } + tmpRoleInfoMap.get(roleInfo.getUsername()).add(roleInfo); + tmpRoleSet.add(roleInfo.getRole()); + } - Map> tmpPermissionInfoMap = new ConcurrentHashMap<>(16); - for (String role : tmpRoleSet) { - Page permissionInfoPage = permissionPersistService.getPermissions(role, 1, Integer.MAX_VALUE); - tmpPermissionInfoMap.put(role, permissionInfoPage.getPageItems()); - } + Map> tmpPermissionInfoMap = new ConcurrentHashMap<>(16); + for (String role : tmpRoleSet) { + Page permissionInfoPage = permissionPersistService.getPermissions(role, 1, + Integer.MAX_VALUE); + tmpPermissionInfoMap.put(role, permissionInfoPage.getPageItems()); + } - roleSet = tmpRoleSet; - roleInfoMap = tmpRoleInfoMap; - permissionInfoMap = tmpPermissionInfoMap; - } catch (Exception e) { - Loggers.AUTH.warn("[LOAD-ROLES] load failed", e); - } - } + roleSet = tmpRoleSet; + roleInfoMap = tmpRoleInfoMap; + permissionInfoMap = tmpPermissionInfoMap; + } + catch (Exception e) { + Loggers.AUTH.warn("[LOAD-ROLES] load failed", e); + } + } - /** - * Determine if the user has permission of the resource. - *

- * Note if the user has many roles, this method returns true if any one role of the user has the - * desired permission. - * - * @param username user info - * @param permission permission to auth - * @return true if granted, false otherwise - */ - public boolean hasPermission(String username, Permission permission) { + /** + * Determine if the user has permission of the resource. + *

+ * Note if the user has many roles, this method returns true if any one role of the + * user has the desired permission. + * @param username user info + * @param permission permission to auth + * @return true if granted, false otherwise + */ + public boolean hasPermission(String username, Permission permission) { - List roleInfoList = getRoles(username); - if (Collections.isEmpty(roleInfoList)) { - return false; - } + List roleInfoList = getRoles(username); + if (Collections.isEmpty(roleInfoList)) { + return false; + } - // Global admin pass: - for (RoleInfo roleInfo : roleInfoList) { - if (GLOBAL_ADMIN_ROLE.equals(roleInfo.getRole())) { - return true; - } - } + // Global admin pass: + for (RoleInfo roleInfo : roleInfoList) { + if (GLOBAL_ADMIN_ROLE.equals(roleInfo.getRole())) { + return true; + } + } - // Old global admin can pass resource 'console/': - if (permission.getResource().startsWith(NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX)) { - return false; - } + // Old global admin can pass resource 'console/': + if (permission.getResource().startsWith(NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX)) { + return false; + } - // For other roles, use a pattern match to decide if pass or not. - for (RoleInfo roleInfo : roleInfoList) { - List permissionInfoList = getPermissions(roleInfo.getRole()); - if (Collections.isEmpty(permissionInfoList)) { - continue; - } - for (PermissionInfo permissionInfo : permissionInfoList) { - String permissionResource = permissionInfo.getResource().replaceAll("\\*", ".*"); - String permissionAction = permissionInfo.getAction(); - if (permissionAction.contains(permission.getAction()) && - Pattern.matches(permissionResource, permission.getResource())) { - return true; - } - } - } - return false; - } + // For other roles, use a pattern match to decide if pass or not. + for (RoleInfo roleInfo : roleInfoList) { + List permissionInfoList = getPermissions(roleInfo.getRole()); + if (Collections.isEmpty(permissionInfoList)) { + continue; + } + for (PermissionInfo permissionInfo : permissionInfoList) { + String permissionResource = permissionInfo.getResource().replaceAll("\\*", ".*"); + String permissionAction = permissionInfo.getAction(); + if (permissionAction.contains(permission.getAction()) + && Pattern.matches(permissionResource, permission.getResource())) { + return true; + } + } + } + return false; + } - public List getRoles(String username) { - List roleInfoList = roleInfoMap.get(username); - if (!authConfigs.isCachingEnabled()) { - Page roleInfoPage = getRolesFromDatabase(username, 1, Integer.MAX_VALUE); - if (roleInfoPage != null) { - roleInfoList = roleInfoPage.getPageItems(); - } - } - return roleInfoList; - } + public List getRoles(String username) { + List roleInfoList = roleInfoMap.get(username); + if (!authConfigs.isCachingEnabled()) { + Page roleInfoPage = getRolesFromDatabase(username, 1, Integer.MAX_VALUE); + if (roleInfoPage != null) { + roleInfoList = roleInfoPage.getPageItems(); + } + } + return roleInfoList; + } - public Page getRolesFromDatabase(String userName, int pageNo, int pageSize) { - Page roles = rolePersistService.getRolesByUserName(userName, pageNo, pageSize); - if (roles == null) { - return new Page<>(); - } - return roles; - } + public Page getRolesFromDatabase(String userName, int pageNo, int pageSize) { + Page roles = rolePersistService.getRolesByUserName(userName, pageNo, pageSize); + if (roles == null) { + return new Page<>(); + } + return roles; + } - public List getPermissions(String role) { - List permissionInfoList = permissionInfoMap.get(role); - if (!authConfigs.isCachingEnabled()) { - Page permissionInfoPage = getPermissionsFromDatabase(role, 1, Integer.MAX_VALUE); - if (permissionInfoPage != null) { - permissionInfoList = permissionInfoPage.getPageItems(); - } - } - return permissionInfoList; - } + public List getPermissions(String role) { + List permissionInfoList = permissionInfoMap.get(role); + if (!authConfigs.isCachingEnabled()) { + Page permissionInfoPage = getPermissionsFromDatabase(role, 1, Integer.MAX_VALUE); + if (permissionInfoPage != null) { + permissionInfoList = permissionInfoPage.getPageItems(); + } + } + return permissionInfoList; + } - public Page getPermissionsByRoleFromDatabase(String role, int pageNo, int pageSize) { - return permissionPersistService.getPermissions(role, pageNo, pageSize); - } + public Page getPermissionsByRoleFromDatabase(String role, int pageNo, int pageSize) { + return permissionPersistService.getPermissions(role, pageNo, pageSize); + } - public void addRole(String role, String username) { - if (userDetailsService.getUser(username) == null) { - throw new IllegalArgumentException("user '" + username + "' not found!"); - } - if (GLOBAL_ADMIN_ROLE.equals(role)) { - throw new IllegalArgumentException("role '" + GLOBAL_ADMIN_ROLE + "' is not permitted to create!"); - } - rolePersistService.addRole(role, username); - roleSet.add(role); - } + public void addRole(String role, String username) { + if (userDetailsService.getUser(username) == null) { + throw new IllegalArgumentException("user '" + username + "' not found!"); + } + if (GLOBAL_ADMIN_ROLE.equals(role)) { + throw new IllegalArgumentException("role '" + GLOBAL_ADMIN_ROLE + "' is not permitted to create!"); + } + rolePersistService.addRole(role, username); + roleSet.add(role); + } - public void deleteRole(String role, String userName) { - rolePersistService.deleteRole(role, userName); - } + public void deleteRole(String role, String userName) { + rolePersistService.deleteRole(role, userName); + } - public void deleteRole(String role) { - rolePersistService.deleteRole(role); - roleSet.remove(role); - } + public void deleteRole(String role) { + rolePersistService.deleteRole(role); + roleSet.remove(role); + } - public Page getPermissionsFromDatabase(String role, int pageNo, int pageSize) { - Page pageInfo = permissionPersistService.getPermissions(role, pageNo, pageSize); - if (pageInfo == null) { - return new Page<>(); - } - return pageInfo; - } + public Page getPermissionsFromDatabase(String role, int pageNo, int pageSize) { + Page pageInfo = permissionPersistService.getPermissions(role, pageNo, pageSize); + if (pageInfo == null) { + return new Page<>(); + } + return pageInfo; + } - public void addPermission(String role, String resource, String action) { - if (!roleSet.contains(role)) { - throw new IllegalArgumentException("role " + role + " not found!"); - } - permissionPersistService.addPermission(role, resource, action); - } + public void addPermission(String role, String resource, String action) { + if (!roleSet.contains(role)) { + throw new IllegalArgumentException("role " + role + " not found!"); + } + permissionPersistService.addPermission(role, resource, action); + } + + public void deletePermission(String role, String resource, String action) { + permissionPersistService.deletePermission(role, resource, action); + } - public void deletePermission(String role, String resource, String action) { - permissionPersistService.deletePermission(role, resource, action); - } } diff --git a/pigx-register/src/main/java/com/alibaba/nacos/console/security/nacos/users/NacosUser.java b/pigx-register/src/main/java/com/alibaba/nacos/console/security/nacos/users/NacosUser.java index f2f519c58..ede0308bd 100755 --- a/pigx-register/src/main/java/com/alibaba/nacos/console/security/nacos/users/NacosUser.java +++ b/pigx-register/src/main/java/com/alibaba/nacos/console/security/nacos/users/NacosUser.java @@ -25,28 +25,29 @@ import com.alibaba.nacos.core.auth.User; */ public class NacosUser extends User { - private String token; + private String token; - private boolean globalAdmin = false; + private boolean globalAdmin = false; - public String getToken() { - return token; - } + public String getToken() { + return token; + } - public void setToken(String token) { - this.token = token; - } + public void setToken(String token) { + this.token = token; + } - public boolean isGlobalAdmin() { - return globalAdmin; - } + public boolean isGlobalAdmin() { + return globalAdmin; + } - public void setGlobalAdmin(boolean globalAdmin) { - this.globalAdmin = globalAdmin; - } + public void setGlobalAdmin(boolean globalAdmin) { + this.globalAdmin = globalAdmin; + } + + @Override + public String toString() { + return JSON.toJSONString(this); + } - @Override - public String toString() { - return JSON.toJSONString(this); - } } diff --git a/pigx-register/src/main/java/com/alibaba/nacos/console/security/nacos/users/NacosUserDetails.java b/pigx-register/src/main/java/com/alibaba/nacos/console/security/nacos/users/NacosUserDetails.java index 3390a2ce2..d90bcfd24 100755 --- a/pigx-register/src/main/java/com/alibaba/nacos/console/security/nacos/users/NacosUserDetails.java +++ b/pigx-register/src/main/java/com/alibaba/nacos/console/security/nacos/users/NacosUserDetails.java @@ -29,45 +29,46 @@ import java.util.Collection; */ public class NacosUserDetails implements UserDetails { - private User user; + private User user; - public NacosUserDetails(User user) { - this.user = user; - } + public NacosUserDetails(User user) { + this.user = user; + } - @Override - public Collection getAuthorities() { - // TODO: get authorities - return AuthorityUtils.commaSeparatedStringToAuthorityList(""); - } + @Override + public Collection getAuthorities() { + // TODO: get authorities + return AuthorityUtils.commaSeparatedStringToAuthorityList(""); + } - @Override - public String getPassword() { - return user.getPassword(); - } + @Override + public String getPassword() { + return user.getPassword(); + } - @Override - public String getUsername() { - return user.getUsername(); - } + @Override + public String getUsername() { + return user.getUsername(); + } - @Override - public boolean isAccountNonExpired() { - return true; - } + @Override + public boolean isAccountNonExpired() { + return true; + } - @Override - public boolean isAccountNonLocked() { - return true; - } + @Override + public boolean isAccountNonLocked() { + return true; + } - @Override - public boolean isCredentialsNonExpired() { - return true; - } + @Override + public boolean isCredentialsNonExpired() { + return true; + } + + @Override + public boolean isEnabled() { + return true; + } - @Override - public boolean isEnabled() { - return true; - } } diff --git a/pigx-register/src/main/java/com/alibaba/nacos/console/security/nacos/users/NacosUserDetailsServiceImpl.java b/pigx-register/src/main/java/com/alibaba/nacos/console/security/nacos/users/NacosUserDetailsServiceImpl.java index 7c9b66ceb..f081f82c0 100755 --- a/pigx-register/src/main/java/com/alibaba/nacos/console/security/nacos/users/NacosUserDetailsServiceImpl.java +++ b/pigx-register/src/main/java/com/alibaba/nacos/console/security/nacos/users/NacosUserDetailsServiceImpl.java @@ -15,7 +15,6 @@ */ package com.alibaba.nacos.console.security.nacos.users; - import com.alibaba.nacos.config.server.auth.UserPersistService; import com.alibaba.nacos.config.server.model.Page; import com.alibaba.nacos.config.server.model.User; @@ -40,71 +39,73 @@ import java.util.concurrent.ConcurrentHashMap; @Service public class NacosUserDetailsServiceImpl implements UserDetailsService { - private Map userMap = new ConcurrentHashMap<>(); + private Map userMap = new ConcurrentHashMap<>(); - @Autowired - private UserPersistService userPersistService; + @Autowired + private UserPersistService userPersistService; - @Autowired - private AuthConfigs authConfigs; + @Autowired + private AuthConfigs authConfigs; - @Scheduled(initialDelay = 5000, fixedDelay = 15000) - private void reload() { - try { - Page users = getUsersFromDatabase(1, Integer.MAX_VALUE); - if (users == null) { - return; - } + @Scheduled(initialDelay = 5000, fixedDelay = 15000) + private void reload() { + try { + Page users = getUsersFromDatabase(1, Integer.MAX_VALUE); + if (users == null) { + return; + } - Map map = new ConcurrentHashMap<>(16); - for (User user : users.getPageItems()) { - map.put(user.getUsername(), user); - } - userMap = map; - } catch (Exception e) { - Loggers.AUTH.warn("[LOAD-USERS] load failed", e); - } - } + Map map = new ConcurrentHashMap<>(16); + for (User user : users.getPageItems()) { + map.put(user.getUsername(), user); + } + userMap = map; + } + catch (Exception e) { + Loggers.AUTH.warn("[LOAD-USERS] load failed", e); + } + } - @Override - public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + @Override + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { - User user = userMap.get(username); - if (!authConfigs.isCachingEnabled()) { - user = userPersistService.findUserByUsername(username); - } + User user = userMap.get(username); + if (!authConfigs.isCachingEnabled()) { + user = userPersistService.findUserByUsername(username); + } - if (user == null) { - throw new UsernameNotFoundException(username); - } - return new NacosUserDetails(user); - } + if (user == null) { + throw new UsernameNotFoundException(username); + } + return new NacosUserDetails(user); + } - public void updateUserPassword(String username, String password) { - userPersistService.updateUserPassword(username, password); - } + public void updateUserPassword(String username, String password) { + userPersistService.updateUserPassword(username, password); + } - public Page getUsersFromDatabase(int pageNo, int pageSize) { - return userPersistService.getUsers(pageNo, pageSize); - } + public Page getUsersFromDatabase(int pageNo, int pageSize) { + return userPersistService.getUsers(pageNo, pageSize); + } - public User getUser(String username) { - User user = userMap.get(username); - if (!authConfigs.isCachingEnabled()) { - user = getUserFromDatabase(username); - } - return user; - } + public User getUser(String username) { + User user = userMap.get(username); + if (!authConfigs.isCachingEnabled()) { + user = getUserFromDatabase(username); + } + return user; + } - public User getUserFromDatabase(String username) { - return userPersistService.findUserByUsername(username); - } + public User getUserFromDatabase(String username) { + return userPersistService.findUserByUsername(username); + } - public void createUser(String username, String password) { - userPersistService.createUser(username, password); - } + public void createUser(String username, String password) { + userPersistService.createUser(username, password); + } + + public void deleteUser(String username) { + userPersistService.deleteUser(username); + } - public void deleteUser(String username) { - userPersistService.deleteUser(username); - } } diff --git a/pigx-register/src/main/java/com/alibaba/nacos/console/utils/JwtTokenUtils.java b/pigx-register/src/main/java/com/alibaba/nacos/console/utils/JwtTokenUtils.java index 55b32401e..d2e8a0728 100755 --- a/pigx-register/src/main/java/com/alibaba/nacos/console/utils/JwtTokenUtils.java +++ b/pigx-register/src/main/java/com/alibaba/nacos/console/utils/JwtTokenUtils.java @@ -32,7 +32,6 @@ import javax.crypto.SecretKey; import java.util.Date; import java.util.List; - /** * Jwt token tool * @@ -41,135 +40,133 @@ import java.util.List; @Component public class JwtTokenUtils { - private final Logger log = LoggerFactory.getLogger(JwtTokenUtils.class); + private final Logger log = LoggerFactory.getLogger(JwtTokenUtils.class); - private static final String AUTHORITIES_KEY = "auth"; + private static final String AUTHORITIES_KEY = "auth"; - /** - * minimum SHA_256 secretKey string length - */ - private static final int SHA_256_SECRET_CHAR_SIZE = 256 / 8; + /** + * minimum SHA_256 secretKey string length + */ + private static final int SHA_256_SECRET_CHAR_SIZE = 256 / 8; - /** - * default SHA_256 secretKey flag - */ - private static final String DEFAULT_SECRET_FLAG = "default"; + /** + * default SHA_256 secretKey flag + */ + private static final String DEFAULT_SECRET_FLAG = "default"; - /** - * custom SHA_256 secretKey from config property - */ - @Value("${nacos.security.token.secret-key:default}") - private String customSecretKeyStr; + /** + * custom SHA_256 secretKey from config property + */ + @Value("${nacos.security.token.secret-key:default}") + private String customSecretKeyStr; - /** - * secret key - */ - private SecretKey secretKey; + /** + * secret key + */ + private SecretKey secretKey; - /** - * Token validity time(ms) - */ - private long tokenValidityInMilliseconds; + /** + * Token validity time(ms) + */ + private long tokenValidityInMilliseconds; - @PostConstruct - public void init() { - //use default secretKey for SHA-256 - if (customSecretKeyStr == null || DEFAULT_SECRET_FLAG.equals(customSecretKeyStr)) { - this.secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS256); - } else { - //use custom secretKey - int size = customSecretKeyStr.length(); - int left = SHA_256_SECRET_CHAR_SIZE - size; - if (left > 0) { - //character for padding - StringBuilder stringBuilder = new StringBuilder(customSecretKeyStr); - for (int i = 0 ;i < left ; i ++){ - stringBuilder.append(i%10); - } - this.secretKey = Keys.hmacShaKeyFor(stringBuilder.toString().getBytes()); - }else { - this.secretKey = Keys.hmacShaKeyFor(customSecretKeyStr.getBytes()); - } - } - this.tokenValidityInMilliseconds = 1000 * 60 * 30L; - } + @PostConstruct + public void init() { + // use default secretKey for SHA-256 + if (customSecretKeyStr == null || DEFAULT_SECRET_FLAG.equals(customSecretKeyStr)) { + this.secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS256); + } + else { + // use custom secretKey + int size = customSecretKeyStr.length(); + int left = SHA_256_SECRET_CHAR_SIZE - size; + if (left > 0) { + // character for padding + StringBuilder stringBuilder = new StringBuilder(customSecretKeyStr); + for (int i = 0; i < left; i++) { + stringBuilder.append(i % 10); + } + this.secretKey = Keys.hmacShaKeyFor(stringBuilder.toString().getBytes()); + } + else { + this.secretKey = Keys.hmacShaKeyFor(customSecretKeyStr.getBytes()); + } + } + this.tokenValidityInMilliseconds = 1000 * 60 * 30L; + } - /** - * Create token - * - * @param authentication auth info - * @return token - */ - public String createToken(Authentication authentication) { - /** - * Current time - */ - long now = (new Date()).getTime(); - /** - * Validity date - */ - Date validity; - validity = new Date(now + this.tokenValidityInMilliseconds); + /** + * Create token + * @param authentication auth info + * @return token + */ + public String createToken(Authentication authentication) { + /** + * Current time + */ + long now = (new Date()).getTime(); + /** + * Validity date + */ + Date validity; + validity = new Date(now + this.tokenValidityInMilliseconds); - /** - * create token - */ - return Jwts.builder() - .setSubject(authentication.getName()) - .claim(AUTHORITIES_KEY, "") - .setExpiration(validity) - .signWith(secretKey, SignatureAlgorithm.HS256) - .compact(); - } + /** + * create token + */ + return Jwts.builder().setSubject(authentication.getName()).claim(AUTHORITIES_KEY, "").setExpiration(validity) + .signWith(secretKey, SignatureAlgorithm.HS256).compact(); + } - /** - * Get auth Info - * - * @param token token - * @return auth info - */ - public Authentication getAuthentication(String token) { - /** - * parse the payload of token - */ - Claims claims = Jwts.parser() - .setSigningKey(secretKey) - .parseClaimsJws(token) - .getBody(); + /** + * Get auth Info + * @param token token + * @return auth info + */ + public Authentication getAuthentication(String token) { + /** + * parse the payload of token + */ + Claims claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody(); - List authorities = AuthorityUtils.commaSeparatedStringToAuthorityList((String) claims.get(AUTHORITIES_KEY)); + List authorities = AuthorityUtils + .commaSeparatedStringToAuthorityList((String) claims.get(AUTHORITIES_KEY)); + User principal = new User(claims.getSubject(), "", authorities); + return new UsernamePasswordAuthenticationToken(principal, "", authorities); + } - User principal = new User(claims.getSubject(), "", authorities); - return new UsernamePasswordAuthenticationToken(principal, "", authorities); - } + /** + * validate token + * @param token token + * @return whether valid + */ + public boolean validateToken(String token) { + try { + Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token); + return true; + } + catch (SignatureException e) { + log.info("Invalid JWT signature."); + log.trace("Invalid JWT signature trace: {}", e); + } + catch (MalformedJwtException e) { + log.info("Invalid JWT token."); + log.trace("Invalid JWT token trace: {}", e); + } + catch (ExpiredJwtException e) { + log.info("Expired JWT token."); + log.trace("Expired JWT token trace: {}", e); + } + catch (UnsupportedJwtException e) { + log.info("Unsupported JWT token."); + log.trace("Unsupported JWT token trace: {}", e); + } + catch (IllegalArgumentException e) { + log.info("JWT token compact of handler are invalid."); + log.trace("JWT token compact of handler are invalid trace: {}", e); + } + return false; + } - /** - * validate token - * - * @param token token - * @return whether valid - */ - public boolean validateToken(String token) { - try { - Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token); - return true; - } catch (SignatureException e) { - log.info("Invalid JWT signature."); - log.trace("Invalid JWT signature trace: {}", e); - } catch (MalformedJwtException e) { - log.info("Invalid JWT token."); - log.trace("Invalid JWT token trace: {}", e); - } catch (ExpiredJwtException e) { - log.info("Expired JWT token."); - log.trace("Expired JWT token trace: {}", e); - } catch (UnsupportedJwtException e) { - log.info("Unsupported JWT token."); - log.trace("Unsupported JWT token trace: {}", e); - } catch (IllegalArgumentException e) { - log.info("JWT token compact of handler are invalid."); - log.trace("JWT token compact of handler are invalid trace: {}", e); - } - return false; - } } diff --git a/pigx-register/src/main/java/com/alibaba/nacos/console/utils/PasswordEncoderUtil.java b/pigx-register/src/main/java/com/alibaba/nacos/console/utils/PasswordEncoderUtil.java index 67585d024..0fd24107d 100755 --- a/pigx-register/src/main/java/com/alibaba/nacos/console/utils/PasswordEncoderUtil.java +++ b/pigx-register/src/main/java/com/alibaba/nacos/console/utils/PasswordEncoderUtil.java @@ -24,15 +24,16 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; */ public class PasswordEncoderUtil { - public static void main(String[] args) { - System.out.println(new BCryptPasswordEncoder().encode("nacos")); - } + public static void main(String[] args) { + System.out.println(new BCryptPasswordEncoder().encode("nacos")); + } - public static Boolean matches(String raw, String encoded) { - return new BCryptPasswordEncoder().matches(raw, encoded); - } + public static Boolean matches(String raw, String encoded) { + return new BCryptPasswordEncoder().matches(raw, encoded); + } + + public static String encode(String raw) { + return new BCryptPasswordEncoder().encode(raw); + } - public static String encode(String raw) { - return new BCryptPasswordEncoder().encode(raw); - } } diff --git a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/dto/DeptTree.java b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/dto/DeptTree.java index 0a0b4d0e3..fee58aecc 100644 --- a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/dto/DeptTree.java +++ b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/dto/DeptTree.java @@ -26,13 +26,14 @@ import lombok.EqualsAndHashCode; /** * @author lengleng - * @date 2018/1/20 - * 部门树 + * @date 2018/1/20 部门树 */ @Data @ApiModel(value = "部门树") @EqualsAndHashCode(callSuper = true) public class DeptTree extends TreeNode { + @ApiModelProperty(value = "部门名称") private String name; + } diff --git a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/dto/MenuTree.java b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/dto/MenuTree.java index f85261485..617e6e111 100644 --- a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/dto/MenuTree.java +++ b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/dto/MenuTree.java @@ -35,42 +35,51 @@ import java.io.Serializable; @ApiModel(value = "菜单树") @EqualsAndHashCode(callSuper = true) public class MenuTree extends TreeNode implements Serializable { + /** * 菜单图标 */ @ApiModelProperty(value = "菜单图标") private String icon; + /** * 菜单名称 */ @ApiModelProperty(value = "菜单名称") private String name; + private boolean spread = false; + /** * 前端路由标识路径 */ @ApiModelProperty(value = "前端路由标识路径") private String path; + /** * 路由缓冲 */ @ApiModelProperty(value = "路由缓冲") private String keepAlive; + /** * 权限编码 */ @ApiModelProperty(value = "权限编码") private String permission; + /** * 菜单类型 (0菜单 1按钮) */ @ApiModelProperty(value = "菜单类型,0:菜单 1:按钮") private String type; + /** * 菜单标签 */ @ApiModelProperty(value = "菜单标签") private String label; + /** * 排序值 */ @@ -113,4 +122,5 @@ public class MenuTree extends TreeNode implements Serializable { this.sort = menuVo.getSort(); this.keepAlive = menuVo.getKeepAlive(); } + } diff --git a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/dto/TreeNode.java b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/dto/TreeNode.java index 6685aab07..e0022f4cb 100644 --- a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/dto/TreeNode.java +++ b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/dto/TreeNode.java @@ -33,14 +33,18 @@ import java.util.List; @Data @ApiModel(value = "树形节点") public class TreeNode { + @ApiModelProperty(value = "当前节点id") protected int id; + @ApiModelProperty(value = "父节点id") protected int parentId; + @ApiModelProperty(value = "子节点列表") protected List children = new ArrayList(); public void add(TreeNode node) { children.add(node); } + } diff --git a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/dto/UserDTO.java b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/dto/UserDTO.java index c1ed082a3..14881baee 100644 --- a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/dto/UserDTO.java +++ b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/dto/UserDTO.java @@ -35,19 +35,23 @@ import java.util.List; @ApiModel(value = "系统用户传输对象") @EqualsAndHashCode(callSuper = true) public class UserDTO extends SysUser { + /** * 角色ID */ @ApiModelProperty(value = "角色id集合") private List role; + /** * 部门id */ @ApiModelProperty(value = "部门id") private Integer deptId; + /** * 新密码 */ @ApiModelProperty(value = "新密码") private String newpassword1; + } diff --git a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/dto/UserInfo.java b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/dto/UserInfo.java index b67d03c13..a05cc1269 100644 --- a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/dto/UserInfo.java +++ b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/dto/UserInfo.java @@ -33,19 +33,23 @@ import java.io.Serializable; @Data @ApiModel(value = "用户信息") public class UserInfo implements Serializable { + /** * 用户基本信息 */ @ApiModelProperty(value = "用户基本信息") private SysUser sysUser; + /** * 权限标识集合 */ @ApiModelProperty(value = "权限标识集合") private String[] permissions; + /** * 角色集合 */ @ApiModelProperty(value = "角色标识集合") private Integer[] roles; + } diff --git a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysDept.java b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysDept.java index a5687865e..11618928a 100644 --- a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysDept.java +++ b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysDept.java @@ -50,35 +50,41 @@ public class SysDept extends Model { @TableId(value = "dept_id", type = IdType.AUTO) @ApiModelProperty(value = "部门id") private Integer deptId; + /** * 部门名称 */ @NotBlank(message = "部门名称不能为空") @ApiModelProperty(value = "部门名称") private String name; + /** * 排序 */ @NotNull(message = "排序值不能为空") @ApiModelProperty(value = "排序值") private Integer sort; + /** * 创建时间 */ @ApiModelProperty(value = "创建时间") private LocalDateTime createTime; + /** * 修改时间 */ @ApiModelProperty(value = "修改时间") private LocalDateTime updateTime; + /** * 父级部门id */ @ApiModelProperty(value = "父级部门id") private Integer parentId; + /** - * 是否删除 1:已删除 0:正常 + * 是否删除 1:已删除 0:正常 */ @TableLogic @ApiModelProperty(value = "删除标记,1:已删除,0:正常") diff --git a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysDeptRelation.java b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysDeptRelation.java index c5e1aae08..63b3ab8a9 100644 --- a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysDeptRelation.java +++ b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysDeptRelation.java @@ -39,16 +39,17 @@ import lombok.EqualsAndHashCode; public class SysDeptRelation extends Model { private static final long serialVersionUID = 1L; + /** * 祖先节点 */ @ApiModelProperty(value = "祖先节点") private Integer ancestor; + /** * 后代节点 */ @ApiModelProperty(value = "后代节点") private Integer descendant; - } diff --git a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysDict.java b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysDict.java index 5730e6597..dfd84649c 100755 --- a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysDict.java +++ b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysDict.java @@ -37,6 +37,7 @@ import java.time.LocalDateTime; @ApiModel(value = "字典类型") @EqualsAndHashCode(callSuper = true) public class SysDict extends Model { + private static final long serialVersionUID = 1L; /** @@ -45,41 +46,49 @@ public class SysDict extends Model { @TableId @ApiModelProperty(value = "字典编号") private Integer id; + /** * 类型 */ @ApiModelProperty(value = "字典类型") private String type; + /** * 描述 */ @ApiModelProperty(value = "字典描述") private String description; + /** * 创建时间 */ @ApiModelProperty(value = "创建时间") private LocalDateTime createTime; + /** * 更新时间 */ @ApiModelProperty(value = "更新时间") private LocalDateTime updateTime; + /** * 是否是系统内置 */ @TableField(value = "`system`") @ApiModelProperty(value = "是否系统内置") private String system; + /** * 备注信息 */ - @ApiModelProperty (value = "备注信息") + @ApiModelProperty(value = "备注信息") private String remarks; + /** * 删除标记 */ @TableLogic @ApiModelProperty(value = "删除标记,1:已删除,0:正常") private String delFlag; + } diff --git a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysDictItem.java b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysDictItem.java index a3582c5ea..397b87625 100755 --- a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysDictItem.java +++ b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysDictItem.java @@ -36,62 +36,75 @@ import java.time.LocalDateTime; @ApiModel(value = "字典项") @EqualsAndHashCode(callSuper = true) public class SysDictItem extends Model { + private static final long serialVersionUID = 1L; + /** * 编号 */ @TableId @ApiModelProperty(value = "字典项id") private Integer id; + /** * 所属字典类id */ @ApiModelProperty(value = "所属字典类id") private Integer dictId; + /** * 数据值 */ @ApiModelProperty(value = "数据值") private String value; + /** * 标签名 */ @ApiModelProperty(value = "标签名") private String label; + /** * 类型 */ @ApiModelProperty(value = "类型") private String type; + /** * 描述 */ @ApiModelProperty(value = "描述") private String description; + /** * 排序(升序) */ @ApiModelProperty(value = "排序值,默认升序") private Integer sort; + /** * 创建时间 */ @ApiModelProperty(value = "创建时间") private LocalDateTime createTime; + /** * 更新时间 */ @ApiModelProperty(value = "更新时间") private LocalDateTime updateTime; + /** * 备注信息 */ @ApiModelProperty(value = "备注信息") private String remarks; + /** * 删除标记 */ @TableLogic @ApiModelProperty(value = "删除标记,1:已删除,0:正常") private String delFlag; + } diff --git a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysFile.java b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysFile.java index 9597c9513..975842522 100644 --- a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysFile.java +++ b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysFile.java @@ -38,6 +38,7 @@ import java.time.LocalDateTime; @ApiModel(value = "文件") @EqualsAndHashCode(callSuper = true) public class SysFile extends Model { + private static final long serialVersionUID = 1L; /** @@ -46,55 +47,66 @@ public class SysFile extends Model { @TableId(type = IdType.AUTO) @ApiModelProperty(value = "文件编号") private Long id; + /** * 文件名 */ @ApiModelProperty(value = "文件名") private String fileName; + /** * 原文件名 */ @ApiModelProperty(value = "原始文件名") private String original; + /** * 容器名称 */ @ApiModelProperty(value = "存储桶名称") private String bucketName; + /** * 文件类型 */ @ApiModelProperty(value = "文件类型") private String type; + /** * 文件大小 */ @ApiModelProperty(value = "文件大小") private Long fileSize; + /** * 上传人 */ @ApiModelProperty(value = "创建者") private String createUser; + /** * 上传时间 */ @ApiModelProperty(value = "创建时间") private LocalDateTime createTime; + /** * 更新人 */ @ApiModelProperty(value = "更新者") private String updateUser; + /** * 更新时间 */ @ApiModelProperty(value = "更新时间") private LocalDateTime updateTime; + /** * 删除标识:1-删除,0-正常 */ @TableLogic @ApiModelProperty(value = "删除标记,1:已删除,0:正常") private Integer delFlag; + } diff --git a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysLog.java b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysLog.java index 3fe6fc18a..e1a468752 100644 --- a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysLog.java +++ b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysLog.java @@ -50,73 +50,87 @@ public class SysLog implements Serializable { @TableId(type = IdType.AUTO) @ApiModelProperty(value = "日志编号") private Long id; + /** * 日志类型 */ @NotBlank(message = "日志类型不能为空") @ApiModelProperty(value = "日志类型") private String type; + /** * 日志标题 */ @NotBlank(message = "日志标题不能为空") @ApiModelProperty(value = "日志标题") private String title; + /** * 创建者 */ @ApiModelProperty(value = "创建人") private String createBy; + /** * 创建时间 */ @ApiModelProperty(value = "创建时间") private LocalDateTime createTime; + /** * 更新时间 */ @ApiModelProperty(value = "更新时间") private LocalDateTime updateTime; + /** * 操作IP地址 */ @ApiModelProperty(value = "操作ip地址") private String remoteAddr; + /** * 用户代理 */ @ApiModelProperty(value = "用户代理") private String userAgent; + /** * 请求URI */ @ApiModelProperty(value = "请求uri") private String requestUri; + /** * 操作方式 */ @ApiModelProperty(value = "操作方式") private String method; + /** * 操作提交的数据 */ @ApiModelProperty(value = "提交数据") private String params; + /** * 执行时间 */ @ApiModelProperty(value = "方法执行时间") private Long time; + /** * 异常信息 */ @ApiModelProperty(value = "异常信息") private String exception; + /** * 服务ID */ @ApiModelProperty(value = "应用标识") private String serviceId; + /** * 删除标记 */ diff --git a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysMenu.java b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysMenu.java index bebafc7f9..51f8149cc 100644 --- a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysMenu.java +++ b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysMenu.java @@ -46,70 +46,82 @@ import java.time.LocalDateTime; public class SysMenu extends Model { private static final long serialVersionUID = 1L; + /** * 菜单ID */ @TableId(value = "menu_id", type = IdType.AUTO) @ApiModelProperty(value = "菜单id") private Integer menuId; + /** * 菜单名称 */ @NotBlank(message = "菜单名称不能为空") @ApiModelProperty(value = "菜单名称") private String name; + /** * 菜单权限标识 */ @ApiModelProperty(value = "菜单权限标识") private String permission; + /** * 父菜单ID */ @NotNull(message = "菜单父ID不能为空") @ApiModelProperty(value = "菜单父id") private Integer parentId; + /** * 图标 */ @ApiModelProperty(value = "菜单图标") private String icon; + /** - * 前端路由标识路径,默认和 comment 保持一致 - * 过期 + * 前端路由标识路径,默认和 comment 保持一致 过期 */ @ApiModelProperty(value = "前端路由标识路径") private String path; + /** * 排序值 */ @ApiModelProperty(value = "排序值") private Integer sort; + /** * 菜单类型 (0菜单 1按钮) */ @NotNull(message = "菜单类型不能为空") @ApiModelProperty(value = "菜单类型,0:菜单 1:按钮") private String type; + /** * 路由缓冲 */ @ApiModelProperty(value = "路由缓冲") private String keepAlive; + /** * 创建时间 */ @ApiModelProperty(value = "创建时间") private LocalDateTime createTime; + /** * 更新时间 */ @ApiModelProperty(value = "更新时间") private LocalDateTime updateTime; + /** * 0--正常 1--删除 */ @TableLogic @ApiModelProperty(value = "删除标记,1:已删除,0:正常") private String delFlag; + } diff --git a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysOauthClientDetails.java b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysOauthClientDetails.java index 18b4f4518..42acda534 100644 --- a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysOauthClientDetails.java +++ b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysOauthClientDetails.java @@ -55,62 +55,74 @@ public class SysOauthClientDetails extends Model { @NotBlank(message = "client_id 不能为空") @ApiModelProperty(value = "客户端id") private String clientId; + /** * 客户端密钥 */ @NotBlank(message = "client_secret 不能为空") @ApiModelProperty(value = "客户端密钥") private String clientSecret; + /** * 资源ID */ @ApiModelProperty(value = "资源id列表") private String resourceIds; + /** * 作用域 */ @NotBlank(message = "scope 不能为空") @ApiModelProperty(value = "作用域") private String scope; + /** * 授权方式[A,B,C] */ @ApiModelProperty(value = "授权方式") private String[] authorizedGrantTypes; + /** * 回调地址 */ @ApiModelProperty(value = "回调地址") private String webServerRedirectUri; + /** * 权限 */ @ApiModelProperty(value = "权限列表") private String authorities; + /** * 请求令牌有效时间 */ @ApiModelProperty(value = "请求令牌有效时间") private Integer accessTokenValidity; + /** * 刷新令牌有效时间 */ @ApiModelProperty(value = "刷新令牌有效时间") private Integer refreshTokenValidity; + /** * 扩展信息 */ @ApiModelProperty(value = "扩展信息") private String additionalInformation; + /** * 是否自动放行 */ @ApiModelProperty(value = "是否自动放行") private String autoapprove; + /** * 删除标记 */ @TableLogic @ApiModelProperty(value = "删除标记,1:已删除,0:正常") private String delFlag; + } diff --git a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysPublicParam.java b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysPublicParam.java index 338fc6633..f0e9e6983 100644 --- a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysPublicParam.java +++ b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysPublicParam.java @@ -38,60 +38,72 @@ import java.util.Date; @ApiModel(value = "公共参数") @EqualsAndHashCode(callSuper = true) public class SysPublicParam extends Model { + private static final long serialVersionUID = 1L; + /** * 编号 */ @TableId @ApiModelProperty(value = "公共参数编号") private Long publicId; + /** * 公共参数名称 */ @ApiModelProperty(value = "公共参数名称", required = true, example = "公共参数名称") private String publicName; + /** * 公共参数地址值,英文大写+下划线 */ @ApiModelProperty(value = "键[英文大写+下划线]", required = true, example = "PIGX_PUBLIC_KEY") private String publicKey; + /** * 值 */ @ApiModelProperty(value = "值", required = true, example = "999") private String publicValue; + /** * 状态(1有效;2无效;) */ @ApiModelProperty(value = "标识[1有效;2无效]", example = "1") private String status; + /** * 删除状态(0:正常 1:已删除) */ @TableLogic @ApiModelProperty(value = "状态[0-正常,1-删除]", example = "0") private String delFlag; + /** * 公共参数编码 */ @ApiModelProperty(value = "编码", example = "^(PIG|PIGX)$") private String validateCode; + /** * 创建时间 */ @ApiModelProperty(value = "创建时间", example = "2019-03-21 12:28:48") private Date createTime; + /** * 修改时间 */ @ApiModelProperty(value = "修改时间", example = "2019-03-21 12:28:48") private Date updateTime; + /** * 是否是系统内置 */ @TableField(value = "`system`") @ApiModelProperty(value = "是否是系统内置") private String system; + /** * 配置类型:0-默认;1-检索;2-原文;3-报表;4-安全;5-文档;6-消息;9-其他 */ diff --git a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysRole.java b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysRole.java index 7ed7a7cc7..49dfdb09c 100644 --- a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysRole.java +++ b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysRole.java @@ -65,21 +65,25 @@ public class SysRole extends Model { @NotNull(message = "数据权限类型不能为空") @ApiModelProperty(value = "数据权限类型") private Integer dsType; + /** * 数据权限作用范围 */ @ApiModelProperty(value = "数据权限作用范围") private String dsScope; + /** * 创建时间 */ @ApiModelProperty(value = "创建时间") private LocalDateTime createTime; + /** * 修改时间 */ @ApiModelProperty(value = "修改时间") private LocalDateTime updateTime; + /** * 删除标识(0-正常,1-删除) */ diff --git a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysRoleMenu.java b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysRoleMenu.java index 7e4c058a8..5a9cefdf6 100644 --- a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysRoleMenu.java +++ b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysRoleMenu.java @@ -39,14 +39,17 @@ import lombok.EqualsAndHashCode; public class SysRoleMenu extends Model { private static final long serialVersionUID = 1L; + /** * 角色ID */ @ApiModelProperty(value = "角色id") private Integer roleId; + /** * 菜单ID */ @ApiModelProperty(value = "菜单id") private Integer menuId; + } diff --git a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysRouteConf.java b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysRouteConf.java index 84e5fb880..6c7d33c18 100755 --- a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysRouteConf.java +++ b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysRouteConf.java @@ -40,56 +40,68 @@ import java.time.LocalDateTime; @ApiModel(value = "网关路由信息") @EqualsAndHashCode(callSuper = true) public class SysRouteConf extends Model { + private static final long serialVersionUID = 1L; + @JsonIgnore @TableId(type = IdType.AUTO) @ApiModelProperty(value = "主键") private Integer id; + /** * 路由ID */ @ApiModelProperty(value = "路由id") private String routeId; + /** * 路由名称 */ @ApiModelProperty(value = "路由名称") private String routeName; + /** * 断言 */ @ApiModelProperty(value = "断言") private String predicates; + /** * 过滤器 */ @ApiModelProperty(value = "过滤器") private String filters; + /** * uri */ @ApiModelProperty(value = "请求uri") private String uri; + /** * 排序 */ @TableField(value = "`order`") @ApiModelProperty(value = "排序值") private Integer order; + /** * 创建时间 */ @ApiModelProperty(value = "创建时间") private LocalDateTime createTime; + /** * 修改时间 */ @ApiModelProperty(value = "修改时间") private LocalDateTime updateTime; + /** * 删除标识(0-正常,1-删除) */ @TableLogic @ApiModelProperty(value = "删除标记,1:已删除,0:正常") private String delFlag; + } diff --git a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysSocialDetails.java b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysSocialDetails.java index abe7342d7..a9a7263f2 100755 --- a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysSocialDetails.java +++ b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysSocialDetails.java @@ -38,6 +38,7 @@ import java.time.LocalDateTime; @ApiModel(value = "第三方账号信息") @EqualsAndHashCode(callSuper = true) public class SysSocialDetails extends Model { + private static final long serialVersionUID = 1L; /** @@ -46,48 +47,57 @@ public class SysSocialDetails extends Model { @TableId @ApiModelProperty(value = "主键") private Integer id; + /** * 类型 */ @NotBlank(message = "类型不能为空") @ApiModelProperty(value = "账号类型") private String type; + /** * 描述 */ @ApiModelProperty(value = "描述") private String remark; + /** * appid */ @NotBlank(message = "账号不能为空") @ApiModelProperty(value = "appId") private String appId; + /** * app_secret */ @NotBlank(message = "密钥不能为空") @ApiModelProperty(value = "app secret") private String appSecret; + /** * 回调地址 */ @ApiModelProperty(value = "回调地址") private String redirectUrl; + /** * 创建时间 */ @ApiModelProperty(value = "创建时间") private LocalDateTime createTime; + /** * 更新时间 */ @ApiModelProperty(value = "更新时间") private LocalDateTime updateTime; + /** * 删除标记 */ @TableLogic @ApiModelProperty(value = "删除标记,1:已删除,0:正常") private String delFlag; + } diff --git a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysTenant.java b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysTenant.java index e49a50fbd..e21aaf8ad 100755 --- a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysTenant.java +++ b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysTenant.java @@ -38,49 +38,59 @@ import java.time.LocalDateTime; @ApiModel(value = "租户信息") @EqualsAndHashCode(callSuper = true) public class SysTenant extends Model { + private static final long serialVersionUID = 1L; + /** * 租户id */ @TableId @ApiModelProperty(value = "租户id") private Integer id; + /** * 租户名称 */ @ApiModelProperty(value = "租户名称") private String name; + /** * 租户编号 */ @ApiModelProperty(value = "租户编号") private String code; + /** * 开始时间 */ @ApiModelProperty(value = "开始时间") private LocalDate startTime; + /** * 结束时间 */ @ApiModelProperty(value = "结束时间") private LocalDate endTime; + /** * 0正常 9-冻结 */ @ApiModelProperty(value = "租户冻结标记,9:冻结,0:正常") private String status; + /** * 删除标记 */ @TableLogic @ApiModelProperty(value = "删除标记,1:已删除,0:正常") private String delFlag; + /** * 创建时间 */ @ApiModelProperty(value = "创建时间") private LocalDateTime createTime; + /** * 更新时间 */ diff --git a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysUser.java b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysUser.java index bf3adf2fd..6b1f32c17 100644 --- a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysUser.java +++ b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysUser.java @@ -50,86 +50,103 @@ public class SysUser implements Serializable { @TableId(value = "user_id", type = IdType.AUTO) @ApiModelProperty(value = "主键id") private Integer userId; + /** * 用户名 */ @ApiModelProperty(value = "用户名") private String username; + /** * 密码 */ @ApiModelProperty(value = "密码") private String password; + /** * 随机盐 */ @JsonIgnore @ApiModelProperty(value = "随机盐") private String salt; + /** * 创建时间 */ @ApiModelProperty(value = "创建时间") private LocalDateTime createTime; + /** * 修改时间 */ @ApiModelProperty(value = "修改时间") private LocalDateTime updateTime; + /** * 0-正常,1-删除 */ @TableLogic @ApiModelProperty(value = "删除标记,1:已删除,0:正常") private String delFlag; + /** * 锁定标记 */ @ApiModelProperty(value = "锁定标记") private String lockFlag; + /** * 手机号 */ @ApiModelProperty(value = "手机号") private String phone; + /** * 头像 */ @ApiModelProperty(value = "头像地址") private String avatar; + /** * 部门ID */ @ApiModelProperty(value = "用户所属部门id") private Integer deptId; + /** * 租户ID */ @ApiModelProperty(value = "用户所属租户id") private Integer tenantId; + /** * 微信openid */ @ApiModelProperty(value = "微信openid") private String wxOpenid; + /** * 微信小程序openId */ @ApiModelProperty(value = "微信小程序openid") private String miniOpenid; + /** * QQ openid */ @ApiModelProperty(value = "QQ openid") private String qqOpenid; + /** * 码云唯一标识 */ @ApiModelProperty(value = "码云唯一标识") private String giteeLogin; + /** * 开源中国唯一标识 */ @ApiModelProperty(value = "开源中国唯一标识") private String oscId; + } diff --git a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysUserRole.java b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysUserRole.java index 47322e372..83f7b6c78 100644 --- a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysUserRole.java +++ b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/entity/SysUserRole.java @@ -39,11 +39,13 @@ import lombok.EqualsAndHashCode; public class SysUserRole extends Model { private static final long serialVersionUID = 1L; + /** * 用户ID */ @ApiModelProperty(value = "用户id") private Integer userId; + /** * 角色ID */ diff --git a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/feign/RemoteDataScopeService.java b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/feign/RemoteDataScopeService.java index 4070e4f9a..b0d745428 100644 --- a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/feign/RemoteDataScopeService.java +++ b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/feign/RemoteDataScopeService.java @@ -40,7 +40,6 @@ public interface RemoteDataScopeService { /** * 通过角色ID 查询角色列表 - * * @param roleIdList 角色ID * @return */ @@ -49,10 +48,10 @@ public interface RemoteDataScopeService { /** * 获取子级部门 - * * @param deptId 部门ID * @return */ @GetMapping("/dept/getDescendantList/{deptId}") R> getDescendantList(@PathVariable("deptId") Integer deptId); + } diff --git a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/feign/RemoteLogService.java b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/feign/RemoteLogService.java index 08e2a0093..10ba2bf4a 100644 --- a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/feign/RemoteLogService.java +++ b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/feign/RemoteLogService.java @@ -34,13 +34,14 @@ import org.springframework.web.bind.annotation.RequestHeader; */ @FeignClient(contextId = "remoteLogService", value = ServiceNameConstants.UPMS_SERVICE) public interface RemoteLogService { + /** * 保存日志 - * * @param sysLog 日志实体 - * @param from 是否内部调用 + * @param from 是否内部调用 * @return succes、false */ @PostMapping("/log/save") R saveLog(@RequestBody SysLog sysLog, @RequestHeader(SecurityConstants.FROM) String from); + } diff --git a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/feign/RemoteParamService.java b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/feign/RemoteParamService.java index 6f9a6f211..de21f9f67 100644 --- a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/feign/RemoteParamService.java +++ b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/feign/RemoteParamService.java @@ -19,11 +19,11 @@ public interface RemoteParamService { /** * 通过key 查询参数配置 - * - * @param key key + * @param key key * @param from 声明成内部调用,避免MQ 等无法调用 * @return */ @GetMapping("/param/publicValue/{key}") R getByKey(@PathVariable("key") String key, @RequestHeader(SecurityConstants.FROM) String from); + } diff --git a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/feign/RemoteTenantService.java b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/feign/RemoteTenantService.java index b1066f5f7..41d6ed6d0 100644 --- a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/feign/RemoteTenantService.java +++ b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/feign/RemoteTenantService.java @@ -37,9 +37,9 @@ import java.util.List; */ @FeignClient(contextId = "remoteTenantService", value = ServiceNameConstants.UPMS_SERVICE) public interface RemoteTenantService { + /** * 查询全部有效租户 - * * @param from 内部标志 * @return */ diff --git a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/feign/RemoteTokenService.java b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/feign/RemoteTokenService.java index 72b6bd4a8..259c7a206 100644 --- a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/feign/RemoteTokenService.java +++ b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/feign/RemoteTokenService.java @@ -32,12 +32,12 @@ import java.util.Map; */ @FeignClient(contextId = "remoteTokenService", value = ServiceNameConstants.AUTH_SERVICE) public interface RemoteTokenService { + /** * 分页查询token 信息 - * - * @param from 内部调用标志 + * @param from 内部调用标志 * @param params 分页参数 - * @param from 内部调用标志 + * @param from 内部调用标志 * @return page */ @PostMapping("/token/page") @@ -45,12 +45,12 @@ public interface RemoteTokenService { /** * 删除token - * - * @param from 内部调用标志 + * @param from 内部调用标志 * @param token token - * @param from 内部调用标志 + * @param from 内部调用标志 * @return */ @DeleteMapping("/token/{token}") R removeTokenById(@PathVariable("token") String token, @RequestHeader(SecurityConstants.FROM) String from); + } diff --git a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/feign/RemoteUserService.java b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/feign/RemoteUserService.java index f1493b4a7..b7fc90263 100644 --- a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/feign/RemoteUserService.java +++ b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/feign/RemoteUserService.java @@ -37,34 +37,31 @@ import java.util.List; */ @FeignClient(contextId = "remoteUserService", value = ServiceNameConstants.UPMS_SERVICE) public interface RemoteUserService { + /** * 通过用户名查询用户、角色信息 - * * @param username 用户名 - * @param from 调用标志 + * @param from 调用标志 * @return R */ @GetMapping("/user/info/{username}") - R info(@PathVariable("username") String username - , @RequestHeader(SecurityConstants.FROM) String from); + R info(@PathVariable("username") String username, @RequestHeader(SecurityConstants.FROM) String from); /** * 通过社交账号或手机号查询用户、角色信息 - * * @param inStr appid@code - * @param from 调用标志 + * @param from 调用标志 * @return */ @GetMapping("/social/info/{inStr}") - R social(@PathVariable("inStr") String inStr - , @RequestHeader(SecurityConstants.FROM) String from); + R social(@PathVariable("inStr") String inStr, @RequestHeader(SecurityConstants.FROM) String from); /** * 查询上级部门的用户信息 - * * @param username 用户名 * @return R */ @GetMapping("/user/ancestor/{username}") R> ancestorUsers(@PathVariable("username") String username); + } diff --git a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/vo/MenuVO.java b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/vo/MenuVO.java index bd4a268fe..e059ef0c3 100644 --- a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/vo/MenuVO.java +++ b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/vo/MenuVO.java @@ -45,63 +45,73 @@ public class MenuVO implements Serializable { */ @ApiModelProperty(value = "菜单id") private Integer menuId; + /** * 菜单名称 */ @ApiModelProperty(value = "菜单名称") private String name; + /** * 菜单权限标识 */ @ApiModelProperty(value = "菜单权限标识") private String permission; + /** * 父菜单ID */ @ApiModelProperty(value = "父菜单id") private Integer parentId; + /** * 图标 */ @ApiModelProperty(value = "图标") private String icon; + /** * 前端路由标识路径 */ @ApiModelProperty(value = "前端路由标识路径") private String path; + /** * 排序值 */ @ApiModelProperty(value = "排序值") private Integer sort; + /** * 菜单类型 (0菜单 1按钮) */ @ApiModelProperty(value = "菜单类型,0:菜单 1:按钮") private String type; + /** * 是否缓冲 */ @ApiModelProperty(value = "路由缓冲") private String keepAlive; + /** * 创建时间 */ @ApiModelProperty(value = "创建时间") private LocalDateTime createTime; + /** * 更新时间 */ @ApiModelProperty(value = "更新时间") private LocalDateTime updateTime; + /** * 0--正常 1--删除 */ @ApiModelProperty(value = "删除标记,1:已删除,0:正常") private String delFlag; - @Override public int hashCode() { return menuId.hashCode(); @@ -109,7 +119,6 @@ public class MenuVO implements Serializable { /** * menuId 相同则相同 - * * @param obj * @return */ @@ -121,4 +130,5 @@ public class MenuVO implements Serializable { } return super.equals(obj); } + } diff --git a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/vo/PreLogVO.java b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/vo/PreLogVO.java index 3ec106877..9ffd22d68 100644 --- a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/vo/PreLogVO.java +++ b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/vo/PreLogVO.java @@ -23,45 +23,52 @@ import lombok.Data; /** * @author lengleng - * @date 2018/8/27 - * 前端日志vo + * @date 2018/8/27 前端日志vo */ @Data @ApiModel(value = "前端日志展示对象") public class PreLogVO { + /** * 请求url */ @ApiModelProperty(value = "请求url") private String url; + /** * 请求耗时 */ @ApiModelProperty(value = "请求耗时") private String time; + /** * 请求用户 */ @ApiModelProperty(value = "请求用户") private String user; + /** * 请求结果 */ @ApiModelProperty(value = "请求结果0:成功9:失败") private String type; + /** * 请求传递参数 */ @ApiModelProperty(value = "请求传递参数") private String message; + /** * 异常信息 */ @ApiModelProperty(value = "异常信息") private String stack; + /** * 日志标题 */ @ApiModelProperty(value = "日志标题") private String info; + } diff --git a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/vo/RoleVO.java b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/vo/RoleVO.java index 8e3b4c63e..565fa8cc9 100644 --- a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/vo/RoleVO.java +++ b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/vo/RoleVO.java @@ -27,6 +27,7 @@ import lombok.Data; @Data @ApiModel(value = "前端角色展示对象") public class RoleVO { + /** * 角色id */ @@ -36,4 +37,5 @@ public class RoleVO { * 菜单列表 */ private String menuIds; + } diff --git a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/vo/TreeUtil.java b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/vo/TreeUtil.java index 8f6ad7d08..257cf8e6d 100644 --- a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/vo/TreeUtil.java +++ b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/vo/TreeUtil.java @@ -19,7 +19,6 @@ package com.pig4cloud.pigx.admin.api.vo; - import com.pig4cloud.pigx.admin.api.dto.MenuTree; import com.pig4cloud.pigx.admin.api.dto.TreeNode; import com.pig4cloud.pigx.admin.api.entity.SysMenu; @@ -34,9 +33,9 @@ import java.util.List; */ @UtilityClass public class TreeUtil { + /** * 两层循环实现建树 - * * @param treeNodes 传入的树节点列表 * @return */ @@ -64,7 +63,6 @@ public class TreeUtil { /** * 使用递归方法建树 - * * @param treeNodes * @return */ @@ -80,7 +78,6 @@ public class TreeUtil { /** * 递归查找子节点 - * * @param treeNodes * @return */ @@ -98,7 +95,6 @@ public class TreeUtil { /** * 通过sysMenu创建树形节点 - * * @param menus * @param root * @return @@ -123,4 +119,5 @@ public class TreeUtil { } return TreeUtil.build(trees, root); } + } diff --git a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/vo/UserVO.java b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/vo/UserVO.java index a3543e856..5215d3b51 100644 --- a/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/vo/UserVO.java +++ b/pigx-upms/pigx-upms-api/src/main/java/com/pig4cloud/pigx/admin/api/vo/UserVO.java @@ -37,6 +37,7 @@ import java.util.List; @Data @ApiModel(value = "前端用户展示对象") public class UserVO implements Serializable { + private static final long serialVersionUID = 1L; /** @@ -44,80 +45,96 @@ public class UserVO implements Serializable { */ @ApiModelProperty(value = "主键") private Integer userId; + /** * 用户名 */ @ApiModelProperty(value = "用户名") private String username; + /** * 密码 */ @ApiModelProperty(value = "密码") private String password; + /** * 随机盐 */ @ApiModelProperty(value = "随机盐") private String salt; + /** * 微信openid */ @ApiModelProperty(value = "微信open id") private String wxOpenid; + /** * QQ openid */ @ApiModelProperty(value = "qq open id") private String qqOpenid; + /** * 创建时间 */ @ApiModelProperty(value = "创建时间") private LocalDateTime createTime; + /** * 修改时间 */ @ApiModelProperty(value = "修改时间") private LocalDateTime updateTime; + /** * 0-正常,1-删除 */ @ApiModelProperty(value = "删除标记,1:已删除,0:正常") private String delFlag; + /** * 锁定标记 */ @ApiModelProperty(value = "锁定标记,0:正常,9:已锁定") private String lockFlag; + /** * 手机号 */ @Sensitive(type = SensitiveTypeEnum.MOBILE_PHONE) @ApiModelProperty(value = "手机号") private String phone; + /** * 头像 */ @ApiModelProperty(value = "头像") private String avatar; + /** * 部门ID */ @ApiModelProperty(value = "所属部门") private Integer deptId; + /** * 租户ID */ @ApiModelProperty(value = "所属租户") private Integer tenantId; + /** * 部门名称 */ @ApiModelProperty(value = "所属部门名称") private String deptName; + /** * 角色列表 */ @ApiModelProperty(value = "拥有的角色列表") private List roleList; + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/PigxAdminApplication.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/PigxAdminApplication.java index 99affce47..dd11172f8 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/PigxAdminApplication.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/PigxAdminApplication.java @@ -19,7 +19,6 @@ package com.pig4cloud.pigx.admin; - import com.pig4cloud.pigx.common.feign.annotation.EnablePigxFeignClients; import com.pig4cloud.pigx.common.security.annotation.EnablePigxResourceServer; import com.pig4cloud.pigx.common.swagger.annotation.EnablePigxSwagger2; @@ -37,6 +36,7 @@ import org.springframework.cloud.client.SpringCloudApplication; @EnablePigxFeignClients @EnablePigxResourceServer public class PigxAdminApplication { + public static void main(String[] args) { SpringApplication.run(PigxAdminApplication.class, args); } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/config/DynamicRouteInitRunner.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/config/DynamicRouteInitRunner.java index 9e71e54f5..90538cbcd 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/config/DynamicRouteInitRunner.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/config/DynamicRouteInitRunner.java @@ -51,12 +51,14 @@ import java.net.URI; @Configuration @AllArgsConstructor public class DynamicRouteInitRunner { + private final RedisTemplate redisTemplate; + private final SysRouteConfService routeConfService; @Async @Order - @EventListener({WebServerInitializedEvent.class, DynamicRouteInitEvent.class}) + @EventListener({ WebServerInitializedEvent.class, DynamicRouteInitEvent.class }) public void initRoute() { Boolean result = redisTemplate.delete(CacheConstants.ROUTE_KEY); log.info("初始化网关路由 {} ", result); @@ -82,14 +84,12 @@ public class DynamicRouteInitRunner { /** * redis 监听配置,监听 gateway_redis_route_reload_topic,重新加载Redis - * * @param redisConnectionFactory redis 配置 * @return */ @Bean public RedisMessageListenerContainer redisContainer(RedisConnectionFactory redisConnectionFactory) { - RedisMessageListenerContainer container - = new RedisMessageListenerContainer(); + RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(redisConnectionFactory); container.addMessageListener((message, bytes) -> { log.warn("接收到重新Redis 重新加载路由事件"); @@ -97,4 +97,5 @@ public class DynamicRouteInitRunner { }, new ChannelTopic(CacheConstants.ROUTE_REDIS_RELOAD_TOPIC)); return container; } + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/MobileController.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/MobileController.java index e6d6d4e06..99d231004 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/MobileController.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/MobileController.java @@ -38,6 +38,7 @@ import org.springframework.web.bind.annotation.RestController; @RequestMapping("/mobile") @Api(value = "mobile", tags = "手机管理模块") public class MobileController { + private final MobileService mobileService; @Inner(value = false) @@ -45,4 +46,5 @@ public class MobileController { public R sendSmsCode(@PathVariable String mobile) { return mobileService.sendSmsCode(mobile); } + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysClientController.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysClientController.java index 5326cea0c..c31f1fc8b 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysClientController.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysClientController.java @@ -45,26 +45,23 @@ import javax.validation.Valid; @RequestMapping("/client") @Api(value = "client", tags = "客户端管理模块") public class SysClientController { + private final SysOauthClientDetailsService clientDetailsService; /** * 通过ID查询 - * * @param clientId clientId * @return SysOauthClientDetails */ @GetMapping("/{clientId}") public R getByClientId(@PathVariable String clientId) { - return R.ok(clientDetailsService.list(Wrappers - .lambdaQuery() - .eq(SysOauthClientDetails::getClientId, clientId))); + return R.ok(clientDetailsService + .list(Wrappers.lambdaQuery().eq(SysOauthClientDetails::getClientId, clientId))); } - /** * 简单分页查询 - * - * @param page 分页对象 + * @param page 分页对象 * @param sysOauthClientDetails 系统终端 * @return */ @@ -75,7 +72,6 @@ public class SysClientController { /** * 添加 - * * @param sysOauthClientDetails 实体 * @return success/false */ @@ -88,7 +84,6 @@ public class SysClientController { /** * 删除 - * * @param clientId ID * @return success/false */ @@ -101,7 +96,6 @@ public class SysClientController { /** * 编辑 - * * @param sysOauthClientDetails 实体 * @return success/false */ @@ -111,4 +105,5 @@ public class SysClientController { public R update(@Valid @RequestBody SysOauthClientDetails sysOauthClientDetails) { return R.ok(clientDetailsService.updateClientById(sysOauthClientDetails)); } + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysDeptController.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysDeptController.java index 7f164c7e5..98c2ef075 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysDeptController.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysDeptController.java @@ -47,12 +47,13 @@ import java.time.LocalDateTime; @RequestMapping("/dept") @Api(value = "dept", tags = "部门管理模块") public class SysDeptController { + private final SysDeptRelationService relationService; + private final SysDeptService sysDeptService; /** * 通过ID查询 - * * @param id ID * @return SysDept */ @@ -61,10 +62,8 @@ public class SysDeptController { return R.ok(sysDeptService.getById(id)); } - /** * 返回树形菜单集合 - * * @return 树形菜单 */ @GetMapping(value = "/tree") @@ -74,7 +73,6 @@ public class SysDeptController { /** * 添加 - * * @param sysDept 实体 * @return success/false */ @@ -87,7 +85,6 @@ public class SysDeptController { /** * 删除 - * * @param id ID * @return success/false */ @@ -100,7 +97,6 @@ public class SysDeptController { /** * 编辑 - * * @param sysDept 实体 * @return success/false */ @@ -114,13 +110,12 @@ public class SysDeptController { /** * 查收子级列表 - * * @return 返回子级 */ @GetMapping(value = "/getDescendantList/{deptId}") public R getDescendantList(@PathVariable Integer deptId) { - return R.ok(relationService.list(Wrappers.lambdaQuery() - .eq(SysDeptRelation::getAncestor, deptId))); + return R.ok( + relationService.list(Wrappers.lambdaQuery().eq(SysDeptRelation::getAncestor, deptId))); } } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysDictController.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysDictController.java index 92608c884..4267f7444 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysDictController.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysDictController.java @@ -19,7 +19,6 @@ package com.pig4cloud.pigx.admin.controller; - import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; @@ -52,12 +51,13 @@ import javax.validation.Valid; @RequestMapping("/dict") @Api(value = "dict", tags = "字典管理模块") public class SysDictController { + private final SysDictService sysDictService; + private final SysDictItemService sysDictItemService; /** * 通过ID查询字典信息 - * * @param id ID * @return 字典信息 */ @@ -68,7 +68,6 @@ public class SysDictController { /** * 分页查询字典信息 - * * @param page 分页对象 * @return 分页对象 */ @@ -79,21 +78,17 @@ public class SysDictController { /** * 通过字典类型查找字典 - * * @param type 类型 * @return 同类型字典 */ @GetMapping("/type/{type}") @Cacheable(value = CacheConstants.DICT_DETAILS, key = "#type", unless = "#result.data.isEmpty()") public R getDictByType(@PathVariable String type) { - return R.ok(sysDictItemService.list(Wrappers - .query().lambda() - .eq(SysDictItem::getType, type))); + return R.ok(sysDictItemService.list(Wrappers.query().lambda().eq(SysDictItem::getType, type))); } /** * 添加字典 - * * @param sysDict 字典信息 * @return success、false */ @@ -106,7 +101,6 @@ public class SysDictController { /** * 删除字典,并且清除字典缓存 - * * @param id ID * @return R */ @@ -119,7 +113,6 @@ public class SysDictController { /** * 修改字典 - * * @param sysDict 字典信息 * @return success/false */ @@ -132,8 +125,7 @@ public class SysDictController { /** * 分页查询 - * - * @param page 分页对象 + * @param page 分页对象 * @param sysDictItem 字典项 * @return */ @@ -142,10 +134,8 @@ public class SysDictController { return R.ok(sysDictItemService.page(page, Wrappers.query(sysDictItem))); } - /** * 通过id查询字典项 - * * @param id id * @return R */ @@ -156,7 +146,6 @@ public class SysDictController { /** * 新增字典项 - * * @param sysDictItem 字典项 * @return R */ @@ -169,7 +158,6 @@ public class SysDictController { /** * 修改字典项 - * * @param sysDictItem 字典项 * @return R */ @@ -181,7 +169,6 @@ public class SysDictController { /** * 通过id删除字典项 - * * @param id id * @return R */ @@ -190,4 +177,5 @@ public class SysDictController { public R removeDictItemById(@PathVariable Integer id) { return sysDictItemService.removeDictItem(id); } + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysFileController.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysFileController.java index fced25c22..4c947a9c3 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysFileController.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysFileController.java @@ -33,7 +33,6 @@ import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; - /** * 文件管理 * @@ -45,12 +44,12 @@ import javax.servlet.http.HttpServletResponse; @RequestMapping("/sys-file") @Api(value = "sys-file", tags = "文件管理") public class SysFileController { + private final SysFileService sysFileService; /** * 分页查询 - * - * @param page 分页对象 + * @param page 分页对象 * @param sysFile 文件管理 * @return */ @@ -60,10 +59,8 @@ public class SysFileController { return R.ok(sysFileService.page(page, Wrappers.query(sysFile))); } - /** * 通过id删除文件管理 - * * @param id id * @return R */ @@ -76,9 +73,7 @@ public class SysFileController { } /** - * 上传文件 - * 文件名采用uuid,避免原始文件名中带"-"符号导致下载的时候解析出现异常 - * + * 上传文件 文件名采用uuid,避免原始文件名中带"-"符号导致下载的时候解析出现异常 * @param file 资源 * @return R(/ admin / bucketName / filename) */ @@ -89,8 +84,7 @@ public class SysFileController { /** * 获取文件 - * - * @param bucket 桶名称 + * @param bucket 桶名称 * @param fileName 文件空间/名称 * @param response * @return diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysLogController.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysLogController.java index 213d1760a..2cce54b1d 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysLogController.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysLogController.java @@ -19,7 +19,6 @@ package com.pig4cloud.pigx.admin.controller; - import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.pig4cloud.pigx.admin.api.entity.SysLog; @@ -48,12 +47,12 @@ import java.util.List; @RequestMapping("/log") @Api(value = "log", tags = "日志管理模块") public class SysLogController { + private final SysLogService sysLogService; /** * 简单分页查询 - * - * @param page 分页对象 + * @param page 分页对象 * @param sysLog 系统日志 * @return */ @@ -64,7 +63,6 @@ public class SysLogController { /** * 删除日志 - * * @param id ID * @return success/false */ @@ -76,7 +74,6 @@ public class SysLogController { /** * 插入日志 - * * @param sysLog 日志实体 * @return success/false */ @@ -88,7 +85,6 @@ public class SysLogController { /** * 批量插入前端异常日志 - * * @param preLogVoList 日志实体 * @return success/false */ @@ -96,4 +92,5 @@ public class SysLogController { public R saveBatchLogs(@RequestBody List preLogVoList) { return R.ok(sysLogService.saveBatchLogs(preLogVoList)); } + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysMenuController.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysMenuController.java index 6e1a9a773..c51bc6afe 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysMenuController.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysMenuController.java @@ -44,12 +44,12 @@ import java.util.stream.Collectors; @RequestMapping("/menu") @Api(value = "menu", tags = "菜单管理模块") public class SysMenuController { + private final SysMenuService sysMenuService; /** * 返回当前用户的树形菜单集合 - * - * @param type 类型 + * @param type 类型 * @param parentId 父节点ID * @return 当前用户的树形菜单 */ @@ -58,15 +58,13 @@ public class SysMenuController { // 获取符合条件的菜单 Set all = new HashSet<>(); - SecurityUtils.getRoles() - .forEach(roleId -> all.addAll(sysMenuService.findMenuByRoleId(roleId))); - return R.ok(sysMenuService.filterMenu(all,type,parentId)); + SecurityUtils.getRoles().forEach(roleId -> all.addAll(sysMenuService.findMenuByRoleId(roleId))); + return R.ok(sysMenuService.filterMenu(all, type, parentId)); } /** * 返回树形菜单集合 - * - * @param lazy 是否是懒加载 + * @param lazy 是否是懒加载 * @param parentId 父节点ID * @return 树形菜单 */ @@ -77,21 +75,17 @@ public class SysMenuController { /** * 返回角色的菜单集合 - * * @param roleId 角色ID * @return 属性集合 */ @GetMapping("/tree/{roleId}") public R getRoleTree(@PathVariable Integer roleId) { - return R.ok(sysMenuService.findMenuByRoleId(roleId) - .stream() - .map(MenuVO::getMenuId) - .collect(Collectors.toList())); + return R.ok( + sysMenuService.findMenuByRoleId(roleId).stream().map(MenuVO::getMenuId).collect(Collectors.toList())); } /** * 通过ID查询菜单的详细信息 - * * @param id 菜单ID * @return 菜单详细信息 */ @@ -102,7 +96,6 @@ public class SysMenuController { /** * 新增菜单 - * * @param sysMenu 菜单信息 * @return success/false */ @@ -116,7 +109,6 @@ public class SysMenuController { /** * 删除菜单 - * * @param id 菜单ID * @return success/false */ @@ -129,7 +121,6 @@ public class SysMenuController { /** * 更新菜单 - * * @param sysMenu * @return */ diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysPublicParamController.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysPublicParamController.java index f995e7071..fa7f47a71 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysPublicParamController.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysPublicParamController.java @@ -30,7 +30,6 @@ import lombok.AllArgsConstructor; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; - /** * 公共参数 * @@ -47,7 +46,6 @@ public class SysPublicParamController { /** * 通过key查询公共参数值 - * * @param publicKey * @return */ @@ -60,8 +58,7 @@ public class SysPublicParamController { /** * 分页查询 - * - * @param page 分页对象 + * @param page 分页对象 * @param sysPublicParam 公共参数 * @return */ @@ -71,10 +68,8 @@ public class SysPublicParamController { return R.ok(sysPublicParamService.page(page, Wrappers.query(sysPublicParam))); } - /** * 通过id查询公共参数 - * * @param publicId id * @return R */ @@ -86,7 +81,6 @@ public class SysPublicParamController { /** * 新增公共参数 - * * @param sysPublicParam 公共参数 * @return R */ @@ -100,7 +94,6 @@ public class SysPublicParamController { /** * 修改公共参数 - * * @param sysPublicParam 公共参数 * @return R */ @@ -114,7 +107,6 @@ public class SysPublicParamController { /** * 通过id删除公共参数 - * * @param publicId id * @return R */ diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysRoleController.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysRoleController.java index 839daf9b8..922b0a4f0 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysRoleController.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysRoleController.java @@ -44,12 +44,13 @@ import java.util.List; @RequestMapping("/role") @Api(value = "role", tags = "角色管理模块") public class SysRoleController { + private final SysRoleService sysRoleService; + private final SysRoleMenuService sysRoleMenuService; /** * 通过ID查询角色信息 - * * @param id ID * @return 角色信息 */ @@ -60,7 +61,6 @@ public class SysRoleController { /** * 添加角色 - * * @param sysRole 角色信息 * @return success、false */ @@ -73,7 +73,6 @@ public class SysRoleController { /** * 修改角色 - * * @param sysRole 角色信息 * @return success/false */ @@ -86,7 +85,6 @@ public class SysRoleController { /** * 删除角色 - * * @param id * @return */ @@ -99,7 +97,6 @@ public class SysRoleController { /** * 获取角色列表 - * * @return 角色列表 */ @GetMapping("/list") @@ -109,7 +106,6 @@ public class SysRoleController { /** * 分页查询角色信息 - * * @param page 分页对象 * @return 分页对象 */ @@ -120,7 +116,6 @@ public class SysRoleController { /** * 更新角色菜单 - * * @param roleVo 角色对象 * @return success、false */ @@ -129,13 +124,11 @@ public class SysRoleController { @PreAuthorize("@pms.hasPermission('sys_role_perm')") public R saveRoleMenus(@RequestBody RoleVO roleVo) { SysRole sysRole = sysRoleService.getById(roleVo.getRoleId()); - return R.ok(sysRoleMenuService.saveRoleMenus(sysRole.getRoleCode() - , roleVo.getRoleId(), roleVo.getMenuIds())); + return R.ok(sysRoleMenuService.saveRoleMenus(sysRole.getRoleCode(), roleVo.getRoleId(), roleVo.getMenuIds())); } /** * 通过角色ID 查询角色列表 - * * @param roleIdList 角色ID * @return */ @@ -143,4 +136,5 @@ public class SysRoleController { public R getRoleList(@RequestBody List roleIdList) { return R.ok(sysRoleService.listByIds(roleIdList)); } + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysRouteConfController.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysRouteConfController.java index 3c97b09a4..47b46635e 100755 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysRouteConfController.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysRouteConfController.java @@ -25,7 +25,6 @@ import io.swagger.annotations.Api; import lombok.AllArgsConstructor; import org.springframework.web.bind.annotation.*; - /** * 路由 * @@ -35,14 +34,13 @@ import org.springframework.web.bind.annotation.*; @RestController @AllArgsConstructor @RequestMapping("/route") -@Api(value = "route",tags = "动态路由管理模块") +@Api(value = "route", tags = "动态路由管理模块") public class SysRouteConfController { - private final SysRouteConfService sysRouteConfService; + private final SysRouteConfService sysRouteConfService; /** * 获取当前定义的路由信息 - * * @return */ @GetMapping @@ -52,7 +50,6 @@ public class SysRouteConfController { /** * 修改路由 - * * @param routes 路由定义 * @return */ diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysSocialDetailsController.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysSocialDetailsController.java index 4b5175d94..0b94a8dc7 100755 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysSocialDetailsController.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysSocialDetailsController.java @@ -31,7 +31,6 @@ import org.springframework.web.bind.annotation.*; import javax.validation.Valid; - /** * 系统社交登录账号表 * @@ -43,13 +42,12 @@ import javax.validation.Valid; @AllArgsConstructor @Api(value = "social", tags = "三方账号管理模块") public class SysSocialDetailsController { - private final SysSocialDetailsService sysSocialDetailsService; + private final SysSocialDetailsService sysSocialDetailsService; /** * 社交登录账户简单分页查询 - * - * @param page 分页对象 + * @param page 分页对象 * @param sysSocialDetails 社交登录 * @return */ @@ -58,23 +56,19 @@ public class SysSocialDetailsController { return R.ok(sysSocialDetailsService.page(page, Wrappers.query(sysSocialDetails))); } - /** * 信息 - * * @param type 类型 * @return R */ @GetMapping("/{type}") public R getByType(@PathVariable("type") String type) { return R.ok(sysSocialDetailsService - .list(Wrappers.lambdaQuery() - .eq(SysSocialDetails::getType, type))); + .list(Wrappers.lambdaQuery().eq(SysSocialDetails::getType, type))); } /** * 保存 - * * @param sysSocialDetails * @return R */ @@ -87,7 +81,6 @@ public class SysSocialDetailsController { /** * 修改 - * * @param sysSocialDetails * @return R */ @@ -101,7 +94,6 @@ public class SysSocialDetailsController { /** * 删除 - * * @param id * @return R */ @@ -114,7 +106,6 @@ public class SysSocialDetailsController { /** * 通过社交账号、手机号查询用户、角色信息 - * * @param inStr appid@code * @return */ @@ -126,13 +117,13 @@ public class SysSocialDetailsController { /** * 绑定社交账号 - * * @param state 类型 - * @param code code + * @param code code * @return */ @PostMapping("/bind") public R bindSocial(String state, String code) { return R.ok(sysSocialDetailsService.bindSocial(state, code)); } + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysTenantController.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysTenantController.java index 16f87caed..3cf81bdb2 100755 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysTenantController.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysTenantController.java @@ -35,7 +35,6 @@ import java.time.LocalDate; import java.util.List; import java.util.stream.Collectors; - /** * 租户管理 * @@ -52,8 +51,7 @@ public class SysTenantController { /** * 分页查询 - * - * @param page 分页对象 + * @param page 分页对象 * @param sysTenant 租户 * @return */ @@ -62,10 +60,8 @@ public class SysTenantController { return R.ok(sysTenantService.page(page, Wrappers.query(sysTenant))); } - /** * 通过id查询租户 - * * @param id id * @return R */ @@ -76,7 +72,6 @@ public class SysTenantController { /** * 新增租户 - * * @param sysTenant 租户 * @return R */ @@ -90,7 +85,6 @@ public class SysTenantController { /** * 修改租户 - * * @param sysTenant 租户 * @return R */ @@ -104,7 +98,6 @@ public class SysTenantController { /** * 通过id删除租户 - * * @param id id * @return R */ @@ -118,17 +111,14 @@ public class SysTenantController { /** * 查询全部有效的租户 - * * @return */ @Inner(value = false) @GetMapping("/list") public R list() { - List tenants = sysTenantService.getNormalTenant() - .stream() + List tenants = sysTenantService.getNormalTenant().stream() .filter(tenant -> tenant.getStartTime().isBefore(LocalDate.now())) - .filter(tenant -> tenant.getEndTime().isAfter(LocalDate.now())) - .collect(Collectors.toList()); + .filter(tenant -> tenant.getEndTime().isAfter(LocalDate.now())).collect(Collectors.toList()); return R.ok(tenants); } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysTokenController.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysTokenController.java index 983bdbff5..bb0ee273d 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysTokenController.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysTokenController.java @@ -30,19 +30,18 @@ import java.util.Map; /** * @author lengleng - * @date 2018/9/4 - * getTokenPage 管理 + * @date 2018/9/4 getTokenPage 管理 */ @RestController @AllArgsConstructor @RequestMapping("/token") @Api(value = "token", tags = "令牌管理模块") public class SysTokenController { + private final RemoteTokenService remoteTokenService; /** * 分页token 信息 - * * @param params 参数集 * @return token集合 */ @@ -53,7 +52,6 @@ public class SysTokenController { /** * 删除 - * * @param token getTokenPage * @return success/false */ @@ -63,4 +61,5 @@ public class SysTokenController { public R removeById(@PathVariable String token) { return remoteTokenService.removeTokenById(token, SecurityConstants.FROM_IN); } + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysUserController.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysUserController.java index 5bcb769cf..cd1795964 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysUserController.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/controller/SysUserController.java @@ -46,18 +46,17 @@ import javax.validation.Valid; @RequestMapping("/user") @Api(value = "user", tags = "用户管理模块") public class SysUserController { + private final SysUserService userService; /** * 获取指定用户全部信息 - * * @return 用户信息 */ @Inner @GetMapping("/info/{username}") public R info(@PathVariable String username) { - SysUser user = userService.getOne(Wrappers.query() - .lambda().eq(SysUser::getUsername, username)); + SysUser user = userService.getOne(Wrappers.query().lambda().eq(SysUser::getUsername, username)); if (user == null) { return R.failed(null, String.format("用户信息为空 %s", username)); } @@ -66,7 +65,6 @@ public class SysUserController { /** * 通过ID查询用户信息 - * * @param id ID * @return 用户信息 */ @@ -77,7 +75,6 @@ public class SysUserController { /** * 根据用户名查询用户信息 - * * @param username 用户名 * @return */ @@ -90,7 +87,6 @@ public class SysUserController { /** * 删除用户信息 - * * @param id ID * @return R */ @@ -106,7 +102,6 @@ public class SysUserController { /** * 添加用户 - * * @param userDto 用户信息 * @return success/false */ @@ -119,7 +114,6 @@ public class SysUserController { /** * 更新用户信息 - * * @param userDto 用户信息 * @return R */ @@ -132,8 +126,7 @@ public class SysUserController { /** * 分页查询用户 - * - * @param page 参数集 + * @param page 参数集 * @param userDTO 查询参数列表 * @return 用户集合 */ @@ -144,7 +137,6 @@ public class SysUserController { /** * 修改个人信息 - * * @param userDto userDto * @return success/false */ @@ -162,4 +154,5 @@ public class SysUserController { public R listAncestorUsers(@PathVariable String username) { return R.ok(userService.listAncestorUsers(username)); } + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/handler/AbstractLoginHandler.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/handler/AbstractLoginHandler.java index 696b03cc1..f11ba6efd 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/handler/AbstractLoginHandler.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/handler/AbstractLoginHandler.java @@ -37,7 +37,6 @@ public abstract class AbstractLoginHandler implements LoginHandler { /** * 处理方法 - * * @param loginStr 登录参数 * @return */ @@ -50,4 +49,5 @@ public abstract class AbstractLoginHandler implements LoginHandler { String identify = identify(loginStr); return info(identify); } + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/handler/GiteeLoginHandler.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/handler/GiteeLoginHandler.java index 09e6322a1..8412deccf 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/handler/GiteeLoginHandler.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/handler/GiteeLoginHandler.java @@ -46,15 +46,15 @@ import java.util.HashMap; @Component("GITEE") @AllArgsConstructor public class GiteeLoginHandler extends AbstractLoginHandler { - private final SysSocialDetailsMapper sysSocialDetailsMapper; - private final SysUserService sysUserService; + private final SysSocialDetailsMapper sysSocialDetailsMapper; + + private final SysUserService sysUserService; /** * 码云登录传入code *

* 通过code 调用qq 获取唯一标识 - * * @param code * @return */ @@ -64,8 +64,8 @@ public class GiteeLoginHandler extends AbstractLoginHandler { condition.setType(LoginTypeEnum.GITEE.getType()); SysSocialDetails socialDetails = sysSocialDetailsMapper.selectOne(new QueryWrapper<>(condition)); - String url = String.format(SecurityConstants.GITEE_AUTHORIZATION_CODE_URL, code - , socialDetails.getAppId(), URLUtil.encode(socialDetails.getRedirectUrl()), socialDetails.getAppSecret()); + String url = String.format(SecurityConstants.GITEE_AUTHORIZATION_CODE_URL, code, socialDetails.getAppId(), + URLUtil.encode(socialDetails.getRedirectUrl()), socialDetails.getAppSecret()); String result = HttpUtil.post(url, new HashMap<>(0)); log.debug("码云响应报文:{}", result); @@ -75,24 +75,20 @@ public class GiteeLoginHandler extends AbstractLoginHandler { log.debug("码云获取个人信息返回报文{}", resp); JSONObject userInfo = JSONUtil.parseObj(resp); - //码云唯一标识 + // 码云唯一标识 String login = userInfo.getStr("login"); return login; } /** * identify 获取用户信息 - * * @param identify identify * @return */ @Override public UserInfo info(String identify) { - - SysUser user = sysUserService - .getOne(Wrappers.query() - .lambda().eq(SysUser::getGiteeLogin, identify)); + SysUser user = sysUserService.getOne(Wrappers.query().lambda().eq(SysUser::getGiteeLogin, identify)); if (user == null) { log.info("码云未绑定:{}", identify); @@ -100,4 +96,5 @@ public class GiteeLoginHandler extends AbstractLoginHandler { } return sysUserService.findUserInfo(user); } + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/handler/LoginHandler.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/handler/LoginHandler.java index 29ef48d3d..3db227aee 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/handler/LoginHandler.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/handler/LoginHandler.java @@ -36,7 +36,6 @@ public interface LoginHandler { /** * 通过用户传入获取唯一标识 - * * @param loginStr * @return */ @@ -44,7 +43,6 @@ public interface LoginHandler { /** * 通过openId 获取用户信息 - * * @param identify * @return */ @@ -52,9 +50,9 @@ public interface LoginHandler { /** * 处理方法 - * * @param loginStr 登录参数 * @return */ UserInfo handle(String loginStr); + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/handler/MiniAppLoginHandler.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/handler/MiniAppLoginHandler.java index a6d7acd08..b662a6858 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/handler/MiniAppLoginHandler.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/handler/MiniAppLoginHandler.java @@ -42,14 +42,15 @@ import org.springframework.stereotype.Component; @Component("MINI") @AllArgsConstructor public class MiniAppLoginHandler extends AbstractLoginHandler { + private final SysUserService sysUserService; + private final SysSocialDetailsMapper sysSocialDetailsMapper; /** * 小程序登录传入code *

* 通过code 调用qq 获取唯一标识 - * * @param code * @return */ @@ -59,8 +60,8 @@ public class MiniAppLoginHandler extends AbstractLoginHandler { condition.setType(LoginTypeEnum.MINI_APP.getType()); SysSocialDetails socialDetails = sysSocialDetailsMapper.selectOne(new QueryWrapper<>(condition)); - String url = String.format(SecurityConstants.MINI_APP_AUTHORIZATION_CODE_URL - , socialDetails.getAppId(), socialDetails.getAppSecret(), code); + String url = String.format(SecurityConstants.MINI_APP_AUTHORIZATION_CODE_URL, socialDetails.getAppId(), + socialDetails.getAppSecret(), code); String result = HttpUtil.get(url); log.debug("微信小程序响应报文:{}", result); @@ -70,15 +71,12 @@ public class MiniAppLoginHandler extends AbstractLoginHandler { /** * openId 获取用户信息 - * * @param openId * @return */ @Override public UserInfo info(String openId) { - SysUser user = sysUserService - .getOne(Wrappers.query() - .lambda().eq(SysUser::getMiniOpenid, openId)); + SysUser user = sysUserService.getOne(Wrappers.query().lambda().eq(SysUser::getMiniOpenid, openId)); if (user == null) { log.info("微信小程序未绑定:{}", openId); @@ -86,4 +84,5 @@ public class MiniAppLoginHandler extends AbstractLoginHandler { } return sysUserService.findUserInfo(user); } + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/handler/OscChinaLoginHandler.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/handler/OscChinaLoginHandler.java index 06a7a8f44..4435894f4 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/handler/OscChinaLoginHandler.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/handler/OscChinaLoginHandler.java @@ -46,15 +46,15 @@ import java.util.Map; @Component("OSC") @AllArgsConstructor public class OscChinaLoginHandler extends AbstractLoginHandler { - private final SysSocialDetailsMapper sysSocialDetailsMapper; - private final SysUserService sysUserService; + private final SysSocialDetailsMapper sysSocialDetailsMapper; + + private final SysUserService sysUserService; /** * 开源中国传入code *

* 通过code 调用qq 获取唯一标识 - * * @param code * @return */ @@ -83,24 +83,20 @@ public class OscChinaLoginHandler extends AbstractLoginHandler { log.debug("开源中国获取个人信息返回报文{}", resp); JSONObject userInfo = JSONUtil.parseObj(resp); - //开源中国唯一标识 + // 开源中国唯一标识 String id = userInfo.getStr("id"); return id; } /** * identify 获取用户信息 - * * @param identify 开源中国表示 * @return */ @Override public UserInfo info(String identify) { - - SysUser user = sysUserService - .getOne(Wrappers.query() - .lambda().eq(SysUser::getOscId, identify)); + SysUser user = sysUserService.getOne(Wrappers.query().lambda().eq(SysUser::getOscId, identify)); if (user == null) { log.info("开源中国未绑定:{}", identify); @@ -108,4 +104,5 @@ public class OscChinaLoginHandler extends AbstractLoginHandler { } return sysUserService.findUserInfo(user); } + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/handler/SmsLoginHandler.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/handler/SmsLoginHandler.java index ef57c406c..3096041bc 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/handler/SmsLoginHandler.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/handler/SmsLoginHandler.java @@ -33,13 +33,11 @@ import org.springframework.stereotype.Component; @Component("SMS") @AllArgsConstructor public class SmsLoginHandler extends AbstractLoginHandler { + private final SysUserService sysUserService; - /** - * 验证码登录传入为手机号 - * 不用不处理 - * + * 验证码登录传入为手机号 不用不处理 * @param mobile * @return */ @@ -50,15 +48,12 @@ public class SmsLoginHandler extends AbstractLoginHandler { /** * 通过mobile 获取用户信息 - * * @param identify * @return */ @Override public UserInfo info(String identify) { - SysUser user = sysUserService - .getOne(Wrappers.query() - .lambda().eq(SysUser::getPhone, identify)); + SysUser user = sysUserService.getOne(Wrappers.query().lambda().eq(SysUser::getPhone, identify)); if (user == null) { log.info("手机号未注册:{}", identify); @@ -66,4 +61,5 @@ public class SmsLoginHandler extends AbstractLoginHandler { } return sysUserService.findUserInfo(user); } + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/handler/WeChatLoginHandler.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/handler/WeChatLoginHandler.java index 9190bf657..1245a1f4d 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/handler/WeChatLoginHandler.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/handler/WeChatLoginHandler.java @@ -40,14 +40,15 @@ import org.springframework.stereotype.Component; @Component("WX") @AllArgsConstructor public class WeChatLoginHandler extends AbstractLoginHandler { + private final SysUserService sysUserService; + private final SysSocialDetailsMapper sysSocialDetailsMapper; /** * 微信登录传入code *

* 通过code 调用qq 获取唯一标识 - * * @param code * @return */ @@ -57,8 +58,8 @@ public class WeChatLoginHandler extends AbstractLoginHandler { condition.setType(LoginTypeEnum.WECHAT.getType()); SysSocialDetails socialDetails = sysSocialDetailsMapper.selectOne(new QueryWrapper<>(condition)); - String url = String.format(SecurityConstants.WX_AUTHORIZATION_CODE_URL - , socialDetails.getAppId(), socialDetails.getAppSecret(), code); + String url = String.format(SecurityConstants.WX_AUTHORIZATION_CODE_URL, socialDetails.getAppId(), + socialDetails.getAppSecret(), code); String result = HttpUtil.get(url); log.debug("微信响应报文:{}", result); @@ -68,15 +69,12 @@ public class WeChatLoginHandler extends AbstractLoginHandler { /** * openId 获取用户信息 - * * @param openId * @return */ @Override public UserInfo info(String openId) { - SysUser user = sysUserService - .getOne(Wrappers.query() - .lambda().eq(SysUser::getWxOpenid, openId)); + SysUser user = sysUserService.getOne(Wrappers.query().lambda().eq(SysUser::getWxOpenid, openId)); if (user == null) { log.info("微信未绑定:{}", openId); @@ -84,4 +82,5 @@ public class WeChatLoginHandler extends AbstractLoginHandler { } return sysUserService.findUserInfo(user); } + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/mapper/SysDeptMapper.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/mapper/SysDeptMapper.java index a7e56d269..bf32f7df0 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/mapper/SysDeptMapper.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/mapper/SysDeptMapper.java @@ -33,4 +33,5 @@ import org.apache.ibatis.annotations.Mapper; */ @Mapper public interface SysDeptMapper extends DataScopeMapper { + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/mapper/SysDeptRelationMapper.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/mapper/SysDeptRelationMapper.java index 823279ce2..de75977df 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/mapper/SysDeptRelationMapper.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/mapper/SysDeptRelationMapper.java @@ -33,16 +33,15 @@ import org.apache.ibatis.annotations.Mapper; */ @Mapper public interface SysDeptRelationMapper extends BaseMapper { + /** * 删除部门关系表数据 - * * @param id 部门ID */ void deleteDeptRelationsById(Integer id); /** * 更改部分关系表数据 - * * @param deptRelation */ void updateDeptRelations(SysDeptRelation deptRelation); diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/mapper/SysLogMapper.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/mapper/SysLogMapper.java index f33f904cc..523e0f74f 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/mapper/SysLogMapper.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/mapper/SysLogMapper.java @@ -33,4 +33,5 @@ import org.apache.ibatis.annotations.Mapper; */ @Mapper public interface SysLogMapper extends BaseMapper { + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/mapper/SysMenuMapper.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/mapper/SysMenuMapper.java index 75d752ca6..c2baeb7f1 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/mapper/SysMenuMapper.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/mapper/SysMenuMapper.java @@ -39,7 +39,6 @@ public interface SysMenuMapper extends BaseMapper { /** * 通过角色编号查询菜单 - * * @param roleId 角色ID * @return */ @@ -47,9 +46,9 @@ public interface SysMenuMapper extends BaseMapper { /** * 通过角色ID查询权限 - * * @param roleIds Ids * @return */ List listPermissionsByRoleIds(String roleIds); + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/mapper/SysOauthClientDetailsMapper.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/mapper/SysOauthClientDetailsMapper.java index c5184776e..883345d90 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/mapper/SysOauthClientDetailsMapper.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/mapper/SysOauthClientDetailsMapper.java @@ -19,7 +19,6 @@ package com.pig4cloud.pigx.admin.mapper; - import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.pig4cloud.pigx.admin.api.entity.SysOauthClientDetails; import org.apache.ibatis.annotations.Mapper; diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/mapper/SysRoleMapper.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/mapper/SysRoleMapper.java index 730ae8002..a52223f3c 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/mapper/SysRoleMapper.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/mapper/SysRoleMapper.java @@ -35,11 +35,12 @@ import java.util.List; */ @Mapper public interface SysRoleMapper extends BaseMapper { + /** * 通过用户ID,查询角色信息 - * * @param userId * @return */ List listRolesByUserId(Integer userId); + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/mapper/SysRoleMenuMapper.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/mapper/SysRoleMenuMapper.java index e853335f0..a5c91f008 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/mapper/SysRoleMenuMapper.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/mapper/SysRoleMenuMapper.java @@ -19,7 +19,6 @@ package com.pig4cloud.pigx.admin.mapper; - import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.pig4cloud.pigx.admin.api.entity.SysRoleMenu; import org.apache.ibatis.annotations.Mapper; diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/mapper/SysUserMapper.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/mapper/SysUserMapper.java index 4a311b8ef..bd6cfe6d1 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/mapper/SysUserMapper.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/mapper/SysUserMapper.java @@ -41,9 +41,9 @@ import java.util.List; */ @Mapper public interface SysUserMapper extends BaseMapper { + /** * 通过用户名查询用户信息(含有角色信息) - * * @param username 用户名 * @return userVo */ @@ -51,9 +51,8 @@ public interface SysUserMapper extends BaseMapper { /** * 分页查询用户信息(含角色) - * - * @param page 分页 - * @param userDTO 查询参数 + * @param page 分页 + * @param userDTO 查询参数 * @param dataScope * @return list */ @@ -61,9 +60,9 @@ public interface SysUserMapper extends BaseMapper { /** * 通过ID查询用户信息 - * * @param id 用户ID * @return userVo */ UserVO getUserVoById(Integer id); + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/mapper/SysUserRoleMapper.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/mapper/SysUserRoleMapper.java index a419f769f..503d04b92 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/mapper/SysUserRoleMapper.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/mapper/SysUserRoleMapper.java @@ -19,7 +19,6 @@ package com.pig4cloud.pigx.admin.mapper; - import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.pig4cloud.pigx.admin.api.entity.SysUserRole; import org.apache.ibatis.annotations.Mapper; @@ -35,13 +34,14 @@ import org.apache.ibatis.annotations.Param; */ @Mapper public interface SysUserRoleMapper extends BaseMapper { + /** * 根据用户Id删除该用户的角色关系 - * * @param userId 用户ID * @return boolean * @author 寻欢·李 * @date 2017年12月7日 16:31:38 */ Boolean deleteByUserId(@Param("userId") Integer userId); + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/MobileService.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/MobileService.java index 2c6297e7e..684446dc7 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/MobileService.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/MobileService.java @@ -24,11 +24,12 @@ import com.pig4cloud.pigx.common.core.util.R; * @date 2018/11/14 */ public interface MobileService { + /** * 发送手机验证码 - * * @param mobile mobile * @return code */ R sendSmsCode(String mobile); + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysDeptRelationService.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysDeptRelationService.java index 89d6c1a43..5623a9788 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysDeptRelationService.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysDeptRelationService.java @@ -35,22 +35,20 @@ public interface SysDeptRelationService extends IService { /** * 新建部门关系 - * * @param sysDept 部门 */ void insertDeptRelation(SysDept sysDept); /** * 通过ID删除部门关系 - * * @param id */ void deleteAllDeptRealtion(Integer id); /** * 更新部门关系 - * * @param relation */ void updateDeptRealtion(SysDeptRelation relation); + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysDeptService.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysDeptService.java index 54417a797..477ed9173 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysDeptService.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysDeptService.java @@ -37,14 +37,12 @@ public interface SysDeptService extends IService { /** * 查询部门树菜单 - * * @return 树 */ List selectTree(); /** * 添加信息部门 - * * @param sysDept * @return */ @@ -52,7 +50,6 @@ public interface SysDeptService extends IService { /** * 删除部门 - * * @param id 部门 ID * @return 成功、失败 */ @@ -60,7 +57,6 @@ public interface SysDeptService extends IService { /** * 更新部门 - * * @param sysDept 部门信息 * @return 成功、失败 */ diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysDictItemService.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysDictItemService.java index 9732bc56d..96989135f 100755 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysDictItemService.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysDictItemService.java @@ -30,7 +30,6 @@ public interface SysDictItemService extends IService { /** * 删除字典项 - * * @param id 字典项ID * @return */ @@ -38,9 +37,9 @@ public interface SysDictItemService extends IService { /** * 更新字典项 - * * @param item 字典项 * @return */ R updateDictItem(SysDictItem item); + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysDictService.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysDictService.java index 7655f2ba5..20e87c2aa 100755 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysDictService.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysDictService.java @@ -30,7 +30,6 @@ public interface SysDictService extends IService { /** * 根据ID 删除字典 - * * @param id * @return */ @@ -38,9 +37,9 @@ public interface SysDictService extends IService { /** * 更新字典 - * * @param sysDict 字典 * @return */ R updateDict(SysDict sysDict); + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysFileService.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysFileService.java index 292670ee4..5a175d3aa 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysFileService.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysFileService.java @@ -34,7 +34,6 @@ public interface SysFileService extends IService { /** * 上传文件 - * * @param file * @return */ @@ -42,8 +41,7 @@ public interface SysFileService extends IService { /** * 读取文件 - * - * @param bucket 桶名称 + * @param bucket 桶名称 * @param fileName 文件名称 * @param response 输出流 */ @@ -51,9 +49,9 @@ public interface SysFileService extends IService { /** * 删除文件 - * * @param id * @return */ Boolean deleteFile(Long id); + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysLogService.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysLogService.java index 81651d4df..78201659a 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysLogService.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysLogService.java @@ -35,12 +35,11 @@ import java.util.List; */ public interface SysLogService extends IService { - /** * 批量插入前端错误日志 - * * @param preLogVoList 日志信息 * @return true/false */ Boolean saveBatchLogs(List preLogVoList); + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysMenuService.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysMenuService.java index 726114ede..2dc6f6a58 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysMenuService.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysMenuService.java @@ -19,7 +19,6 @@ package com.pig4cloud.pigx.admin.service; - import com.baomidou.mybatisplus.extension.service.IService; import com.pig4cloud.pigx.admin.api.dto.MenuTree; import com.pig4cloud.pigx.admin.api.entity.SysMenu; @@ -38,9 +37,9 @@ import java.util.Set; * @since 2017-10-29 */ public interface SysMenuService extends IService { + /** * 通过角色编号查询URL 权限 - * * @param roleId 角色ID * @return 菜单列表 */ @@ -48,7 +47,6 @@ public interface SysMenuService extends IService { /** * 级联删除菜单 - * * @param id 菜单ID * @return 成功、失败 */ @@ -56,7 +54,6 @@ public interface SysMenuService extends IService { /** * 更新菜单信息 - * * @param sysMenu 菜单信息 * @return 成功、失败 */ @@ -64,8 +61,7 @@ public interface SysMenuService extends IService { /** * 构建树 - * - * @param lazy 是否是懒加载 + * @param lazy 是否是懒加载 * @param parentId 父节点ID * @return */ @@ -73,10 +69,10 @@ public interface SysMenuService extends IService { /** * 查询菜单 - * * @param voSet * @param parentId * @return */ List filterMenu(Set voSet, String type, Integer parentId); + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysOauthClientDetailsService.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysOauthClientDetailsService.java index 21256f9d2..cbf4a0a92 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysOauthClientDetailsService.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysOauthClientDetailsService.java @@ -31,9 +31,9 @@ import com.pig4cloud.pigx.admin.api.entity.SysOauthClientDetails; * @since 2018-05-15 */ public interface SysOauthClientDetailsService extends IService { + /** * 通过ID删除客户端 - * * @param clientId * @return */ @@ -41,9 +41,9 @@ public interface SysOauthClientDetailsService extends IService { /** * 通过key查询公共参数指定值 - * * @param publicKey * @return */ @@ -39,7 +38,6 @@ public interface SysPublicParamService extends IService { /** * 更新参数 - * * @param sysPublicParam * @return */ @@ -47,9 +45,9 @@ public interface SysPublicParamService extends IService { /** * 删除参数 - * * @param publicId * @return */ R removeParam(Long publicId); + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysRoleMenuService.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysRoleMenuService.java index a236b73ef..af2a190c1 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysRoleMenuService.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysRoleMenuService.java @@ -19,7 +19,6 @@ package com.pig4cloud.pigx.admin.service; - import com.baomidou.mybatisplus.extension.service.IService; import com.pig4cloud.pigx.admin.api.entity.SysRoleMenu; @@ -35,11 +34,11 @@ public interface SysRoleMenuService extends IService { /** * 更新角色菜单 - * * @param role - * @param roleId 角色 + * @param roleId 角色 * @param menuIds 菜单ID拼成的字符串,每个id之间根据逗号分隔 * @return */ Boolean saveRoleMenus(String role, Integer roleId, String menuIds); + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysRoleService.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysRoleService.java index 30d52d600..d5448e5a9 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysRoleService.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysRoleService.java @@ -36,7 +36,6 @@ public interface SysRoleService extends IService { /** * 通过用户ID,查询角色信息 - * * @param userId * @return */ @@ -44,9 +43,9 @@ public interface SysRoleService extends IService { /** * 通过角色ID,删除角色 - * * @param id * @return */ Boolean removeRoleById(Integer id); + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysRouteConfService.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysRouteConfService.java index af835d58e..c4b8ccc72 100755 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysRouteConfService.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysRouteConfService.java @@ -32,10 +32,9 @@ public interface SysRouteConfService extends IService { /** * 更新路由信息 - * * @param routes 路由信息 * @return */ Mono updateRoutes(JSONArray routes); -} +} diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysSocialDetailsService.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysSocialDetailsService.java index a9110b6b1..2541e569f 100755 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysSocialDetailsService.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysSocialDetailsService.java @@ -31,19 +31,17 @@ public interface SysSocialDetailsService extends IService { /** * 绑定社交账号 - * * @param state 类型 - * @param code code + * @param code code * @return */ Boolean bindSocial(String state, String code); /** * 根据入参查询用户信息 - * * @param inStr * @return */ UserInfo getUserInfo(String inStr); -} +} diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysTenantService.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysTenantService.java index b787d0722..0e49b037c 100755 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysTenantService.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysTenantService.java @@ -32,16 +32,15 @@ public interface SysTenantService extends IService { /** * 获取正常的租户 - * * @return */ List getNormalTenant(); /** * 保存租户 - * * @param sysTenant * @return */ Boolean saveTenant(SysTenant sysTenant); + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysUserRoleService.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysUserRoleService.java index d32763167..1b0362282 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysUserRoleService.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysUserRoleService.java @@ -19,7 +19,6 @@ package com.pig4cloud.pigx.admin.service; - import com.baomidou.mybatisplus.extension.service.IService; import com.pig4cloud.pigx.admin.api.entity.SysUserRole; @@ -35,11 +34,11 @@ public interface SysUserRoleService extends IService { /** * 根据用户Id删除该用户的角色关系 - * * @param userId 用户ID * @return boolean * @author 寻欢·李 * @date 2017年12月7日 16:31:38 */ Boolean deleteByUserId(Integer userId); + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysUserService.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysUserService.java index 506e4d30c..62462338a 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysUserService.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/SysUserService.java @@ -35,9 +35,9 @@ import java.util.List; * @date 2017/10/31 */ public interface SysUserService extends IService { + /** * 查询用户信息 - * * @param sysUser 用户 * @return userInfo */ @@ -45,8 +45,7 @@ public interface SysUserService extends IService { /** * 分页查询用户信息(含有角色信息) - * - * @param page 分页对象 + * @param page 分页对象 * @param userDTO 参数列表 * @return */ @@ -54,7 +53,6 @@ public interface SysUserService extends IService { /** * 删除用户 - * * @param sysUser 用户 * @return boolean */ @@ -62,7 +60,6 @@ public interface SysUserService extends IService { /** * 更新当前用户基本信息 - * * @param userDto 用户信息 * @return Boolean */ @@ -70,7 +67,6 @@ public interface SysUserService extends IService { /** * 更新指定用户信息 - * * @param userDto 用户信息 * @return */ @@ -78,7 +74,6 @@ public interface SysUserService extends IService { /** * 通过ID查询用户信息 - * * @param id 用户ID * @return 用户信息 */ @@ -86,7 +81,6 @@ public interface SysUserService extends IService { /** * 查询上级部门的用户信息 - * * @param username 用户名 * @return R */ @@ -94,9 +88,9 @@ public interface SysUserService extends IService { /** * 保存用户信息 - * * @param userDto DTO 对象 * @return success/fail */ Boolean saveUser(UserDTO userDto); + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/MobileServiceImpl.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/MobileServiceImpl.java index 6abaac157..82dfdd456 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/MobileServiceImpl.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/MobileServiceImpl.java @@ -46,29 +46,28 @@ import java.util.concurrent.TimeUnit; @Service @AllArgsConstructor public class MobileServiceImpl implements MobileService { + private final RedisTemplate redisTemplate; + private final SysUserMapper userMapper; - /** - * 发送手机验证码 - * TODO: 调用短信网关发送验证码,测试返回前端 - * + * 发送手机验证码 TODO: 调用短信网关发送验证码,测试返回前端 * @param mobile mobile * @return code */ @Override public R sendSmsCode(String mobile) { - List userList = userMapper.selectList(Wrappers - .query().lambda() - .eq(SysUser::getPhone, mobile)); + List userList = userMapper + .selectList(Wrappers.query().lambda().eq(SysUser::getPhone, mobile)); if (CollUtil.isEmpty(userList)) { log.info("手机号未注册:{}", mobile); return R.ok(Boolean.FALSE, "手机号未注册"); } - Object codeObj = redisTemplate.opsForValue().get(CacheConstants.DEFAULT_CODE_KEY + LoginTypeEnum.SMS.getType() + StringPool.AT + mobile); + Object codeObj = redisTemplate.opsForValue() + .get(CacheConstants.DEFAULT_CODE_KEY + LoginTypeEnum.SMS.getType() + StringPool.AT + mobile); if (codeObj != null) { log.info("手机号验证码未过期:{},{}", mobile, codeObj); @@ -78,8 +77,9 @@ public class MobileServiceImpl implements MobileService { String code = RandomUtil.randomNumbers(Integer.parseInt(SecurityConstants.CODE_SIZE)); log.debug("手机号生成验证码成功:{},{}", mobile, code); redisTemplate.opsForValue().set( - CacheConstants.DEFAULT_CODE_KEY + LoginTypeEnum.SMS.getType() + StringPool.AT + mobile - , code, SecurityConstants.CODE_TIME, TimeUnit.SECONDS); + CacheConstants.DEFAULT_CODE_KEY + LoginTypeEnum.SMS.getType() + StringPool.AT + mobile, code, + SecurityConstants.CODE_TIME, TimeUnit.SECONDS); return R.ok(Boolean.TRUE, code); } + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/SysDeptRelationServiceImpl.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/SysDeptRelationServiceImpl.java index 07eaaf39e..9b34266ab 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/SysDeptRelationServiceImpl.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/SysDeptRelationServiceImpl.java @@ -43,32 +43,32 @@ import java.util.stream.Collectors; */ @Service @AllArgsConstructor -public class SysDeptRelationServiceImpl extends ServiceImpl implements SysDeptRelationService { +public class SysDeptRelationServiceImpl extends ServiceImpl + implements SysDeptRelationService { + private final SysDeptRelationMapper sysDeptRelationMapper; /** * 维护部门关系 - * * @param sysDept 部门 */ @Override @Transactional(rollbackFor = Exception.class) public void insertDeptRelation(SysDept sysDept) { - //增加部门关系表 + // 增加部门关系表 SysDeptRelation condition = new SysDeptRelation(); condition.setDescendant(sysDept.getParentId()); - List relationList = sysDeptRelationMapper - .selectList(Wrappers.query().lambda() - .eq(SysDeptRelation::getDescendant, sysDept.getParentId())) - .stream().map(relation -> { - relation.setDescendant(sysDept.getDeptId()); - return relation; - }).collect(Collectors.toList()); + List relationList = sysDeptRelationMapper.selectList( + Wrappers.query().lambda().eq(SysDeptRelation::getDescendant, sysDept.getParentId())) + .stream().map(relation -> { + relation.setDescendant(sysDept.getDeptId()); + return relation; + }).collect(Collectors.toList()); if (CollUtil.isNotEmpty(relationList)) { this.saveBatch(relationList); } - //自己也要维护到关系表中 + // 自己也要维护到关系表中 SysDeptRelation own = new SysDeptRelation(); own.setDescendant(sysDept.getDeptId()); own.setAncestor(sysDept.getDeptId()); @@ -77,7 +77,6 @@ public class SysDeptRelationServiceImpl extends ServiceImpl implements SysDeptService { + private final SysDeptRelationService sysDeptRelationService; + private final SysDeptMapper deptMapper; /** * 添加信息部门 - * * @param dept 部门 * @return */ @@ -68,45 +69,39 @@ public class SysDeptServiceImpl extends ServiceImpl impl return Boolean.TRUE; } - /** * 删除部门 - * * @param id 部门 ID * @return 成功、失败 */ @Override @Transactional(rollbackFor = Exception.class) public Boolean removeDeptById(Integer id) { - //级联删除部门 + // 级联删除部门 List idList = sysDeptRelationService - .list(Wrappers.query().lambda() - .eq(SysDeptRelation::getAncestor, id)) - .stream() - .map(SysDeptRelation::getDescendant) - .collect(Collectors.toList()); + .list(Wrappers.query().lambda().eq(SysDeptRelation::getAncestor, id)).stream() + .map(SysDeptRelation::getDescendant).collect(Collectors.toList()); if (CollUtil.isNotEmpty(idList)) { this.removeByIds(idList); } - //删除部门级联关系 + // 删除部门级联关系 sysDeptRelationService.deleteAllDeptRealtion(id); return Boolean.TRUE; } /** * 更新部门 - * * @param sysDept 部门信息 * @return 成功、失败 */ @Override @Transactional(rollbackFor = Exception.class) public Boolean updateDeptById(SysDept sysDept) { - //更新部门状态 + // 更新部门状态 this.updateById(sysDept); - //更新部门关系 + // 更新部门关系 SysDeptRelation relation = new SysDeptRelation(); relation.setAncestor(sysDept.getParentId()); relation.setDescendant(sysDept.getDeptId()); @@ -116,7 +111,6 @@ public class SysDeptServiceImpl extends ServiceImpl impl /** * 查询全部部门树 - * * @return 树 */ @Override @@ -124,26 +118,22 @@ public class SysDeptServiceImpl extends ServiceImpl impl return getDeptTree(deptMapper.selectList(Wrappers.emptyWrapper())); } - /** * 构建部门树 - * * @param depts 部门 * @return */ private List getDeptTree(List depts) { - List treeList = depts.stream() - .filter(dept -> !dept.getDeptId().equals(dept.getParentId())) - .sorted(Comparator.comparingInt(SysDept::getSort)) - .map(dept -> { + List treeList = depts.stream().filter(dept -> !dept.getDeptId().equals(dept.getParentId())) + .sorted(Comparator.comparingInt(SysDept::getSort)).map(dept -> { DeptTree node = new DeptTree(); node.setId(dept.getDeptId()); node.setParentId(dept.getParentId()); node.setName(dept.getName()); return node; }).collect(Collectors.toList()); - return TreeUtil.build(treeList, depts.stream() - .sorted(Comparator.comparingInt(SysDept::getDeptId)) - .findFirst().get().getParentId()); + return TreeUtil.build(treeList, + depts.stream().sorted(Comparator.comparingInt(SysDept::getDeptId)).findFirst().get().getParentId()); } + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/SysDictItemServiceImpl.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/SysDictItemServiceImpl.java index 2e24ca10f..729ff17bf 100755 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/SysDictItemServiceImpl.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/SysDictItemServiceImpl.java @@ -38,18 +38,18 @@ import org.springframework.stereotype.Service; @Service @AllArgsConstructor public class SysDictItemServiceImpl extends ServiceImpl implements SysDictItemService { + private final SysDictService dictService; /** * 删除字典项 - * * @param id 字典项ID * @return */ @Override @CacheEvict(value = CacheConstants.DICT_DETAILS, allEntries = true) public R removeDictItem(Integer id) { - //根据ID查询字典ID + // 根据ID查询字典ID SysDictItem dictItem = this.getById(id); SysDict dict = dictService.getById(dictItem.getDictId()); // 系统内置 @@ -61,14 +61,13 @@ public class SysDictItemServiceImpl extends ServiceImpl implements SysDictService { + private final SysDictItemMapper dictItemMapper; /** * 根据ID 删除字典 - * * @param id 字典ID * @return */ @@ -59,14 +59,12 @@ public class SysDictServiceImpl extends ServiceImpl impl } baseMapper.deleteById(id); - dictItemMapper.delete(Wrappers.lambdaQuery() - .eq(SysDictItem::getDictId, id)); + dictItemMapper.delete(Wrappers.lambdaQuery().eq(SysDictItem::getDictId, id)); return R.ok(); } /** * 更新字典 - * * @param dict 字典 * @return */ @@ -79,4 +77,5 @@ public class SysDictServiceImpl extends ServiceImpl impl } return R.ok(this.updateById(dict)); } + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/SysFileServiceImpl.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/SysFileServiceImpl.java index fa1f942da..f3fa118c9 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/SysFileServiceImpl.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/SysFileServiceImpl.java @@ -50,13 +50,13 @@ import java.util.Map; @Service @AllArgsConstructor public class SysFileServiceImpl extends ServiceImpl implements SysFileService { - private final OssProperties ossProperties; - private final OssTemplate minioTemplate; + private final OssProperties ossProperties; + + private final OssTemplate minioTemplate; /** * 上传文件 - * * @param file * @return */ @@ -70,9 +70,10 @@ public class SysFileServiceImpl extends ServiceImpl impl try { minioTemplate.putObject(ossProperties.getBucketName(), fileName, file.getInputStream()); - //文件管理数据记录,收集管理追踪文件 + // 文件管理数据记录,收集管理追踪文件 fileLog(file, fileName); - } catch (Exception e) { + } + catch (Exception e) { log.error("上传失败", e); return R.failed(e.getLocalizedMessage()); } @@ -81,7 +82,6 @@ public class SysFileServiceImpl extends ServiceImpl impl /** * 读取文件 - * * @param bucket * @param fileName * @param response @@ -91,15 +91,14 @@ public class SysFileServiceImpl extends ServiceImpl impl try (InputStream inputStream = minioTemplate.getObject(bucket, fileName)) { response.setContentType("application/octet-stream; charset=UTF-8"); IoUtil.copy(inputStream, response.getOutputStream()); - } catch (Exception e) { + } + catch (Exception e) { log.error("文件读取异常: {}", e.getLocalizedMessage()); } } - /** * 删除文件 - * * @param id * @return */ @@ -114,13 +113,12 @@ public class SysFileServiceImpl extends ServiceImpl impl /** * 文件管理数据记录,收集管理追踪文件 - * - * @param file 上传文件格式 + * @param file 上传文件格式 * @param fileName 文件名 */ private void fileLog(MultipartFile file, String fileName) { SysFile sysFile = new SysFile(); - //原文件名 + // 原文件名 String original = file.getOriginalFilename(); sysFile.setFileName(fileName); sysFile.setOriginal(original); diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/SysLogServiceImpl.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/SysLogServiceImpl.java index 02c518e38..c3e622393 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/SysLogServiceImpl.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/SysLogServiceImpl.java @@ -44,25 +44,23 @@ public class SysLogServiceImpl extends ServiceImpl impleme /** * 批量插入前端错误日志 - * * @param preLogVoList 日志信息 * @return true/false */ @Override public Boolean saveBatchLogs(List preLogVoList) { - List sysLogs = preLogVoList.stream() - .map(pre -> { - SysLog log = new SysLog(); - log.setType(CommonConstants.STATUS_LOCK); - log.setTitle(pre.getInfo()); - log.setException(pre.getStack()); - log.setParams(pre.getMessage()); - log.setCreateTime(LocalDateTime.now()); - log.setRequestUri(pre.getUrl()); - log.setCreateBy(pre.getUser()); - return log; - }) - .collect(Collectors.toList()); + List sysLogs = preLogVoList.stream().map(pre -> { + SysLog log = new SysLog(); + log.setType(CommonConstants.STATUS_LOCK); + log.setTitle(pre.getInfo()); + log.setException(pre.getStack()); + log.setParams(pre.getMessage()); + log.setCreateTime(LocalDateTime.now()); + log.setRequestUri(pre.getUrl()); + log.setCreateBy(pre.getUser()); + return log; + }).collect(Collectors.toList()); return this.saveBatch(sysLogs); } + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/SysMenuServiceImpl.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/SysMenuServiceImpl.java index afac06805..3c07abe7f 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/SysMenuServiceImpl.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/SysMenuServiceImpl.java @@ -57,6 +57,7 @@ import java.util.stream.Collectors; @Service @AllArgsConstructor public class SysMenuServiceImpl extends ServiceImpl implements SysMenuService { + private final SysRoleMenuMapper sysRoleMenuMapper; @Override @@ -70,15 +71,13 @@ public class SysMenuServiceImpl extends ServiceImpl impl @CacheEvict(value = CacheConstants.MENU_DETAILS, allEntries = true) public R removeMenuById(Integer id) { // 查询父节点为当前节点的节点 - List menuList = this.list(Wrappers.query() - .lambda().eq(SysMenu::getParentId, id)); + List menuList = this.list(Wrappers.query().lambda().eq(SysMenu::getParentId, id)); if (CollUtil.isNotEmpty(menuList)) { return R.failed("菜单含有下级不能删除"); } - sysRoleMenuMapper.delete(Wrappers.query() - .lambda().eq(SysRoleMenu::getMenuId, id)); - //删除当前菜单及其子菜单 + sysRoleMenuMapper.delete(Wrappers.query().lambda().eq(SysRoleMenu::getMenuId, id)); + // 删除当前菜单及其子菜单 return R.ok(this.removeById(id)); } @@ -89,50 +88,43 @@ public class SysMenuServiceImpl extends ServiceImpl impl } /** - * 构建树查询 - * 1. 不是懒加载情况,查询全部 - * 2. 是懒加载,根据parentId 查询 - * 2.1 父节点为空,则查询ID -1 - * - * @param lazy 是否是懒加载 + * 构建树查询 1. 不是懒加载情况,查询全部 2. 是懒加载,根据parentId 查询 2.1 父节点为空,则查询ID -1 + * @param lazy 是否是懒加载 * @param parentId 父节点ID * @return */ @Override public List treeMenu(boolean lazy, Integer parentId) { if (!lazy) { - return TreeUtil.buildTree(baseMapper.selectList(Wrappers.lambdaQuery() - .orderByAsc(SysMenu::getSort)), CommonConstants.MENU_TREE_ROOT_ID); + return TreeUtil.buildTree( + baseMapper.selectList(Wrappers.lambdaQuery().orderByAsc(SysMenu::getSort)), + CommonConstants.MENU_TREE_ROOT_ID); } Integer parent = parentId == null ? CommonConstants.MENU_TREE_ROOT_ID : parentId; - return TreeUtil.buildTree(baseMapper - .selectList(Wrappers.lambdaQuery().eq(SysMenu::getParentId, parent) - .orderByAsc(SysMenu::getSort)), parent); + return TreeUtil.buildTree( + baseMapper.selectList( + Wrappers.lambdaQuery().eq(SysMenu::getParentId, parent).orderByAsc(SysMenu::getSort)), + parent); } /** * 查询菜单 - * - * @param all 全部菜单 - * @param type 类型 + * @param all 全部菜单 + * @param type 类型 * @param parentId 父节点ID * @return */ @Override public List filterMenu(Set all, String type, Integer parentId) { - List menuTreeList = all.stream() - .filter(menuTypePredicate(type)) - .map(MenuTree::new) - .sorted(Comparator.comparingInt(MenuTree::getSort)) - .collect(Collectors.toList()); + List menuTreeList = all.stream().filter(menuTypePredicate(type)).map(MenuTree::new) + .sorted(Comparator.comparingInt(MenuTree::getSort)).collect(Collectors.toList()); Integer parent = parentId == null ? CommonConstants.MENU_TREE_ROOT_ID : parentId; return TreeUtil.build(menuTreeList, parent); } /** * menu 类型断言 - * * @param type 类型 * @return Predicate */ @@ -145,4 +137,5 @@ public class SysMenuServiceImpl extends ServiceImpl impl return !MenuTypeEnum.BUTTON.getType().equals(vo.getType()); }; } + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/SysOauthClientDetailsServiceImpl.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/SysOauthClientDetailsServiceImpl.java index 17d70a451..3f2d54380 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/SysOauthClientDetailsServiceImpl.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/SysOauthClientDetailsServiceImpl.java @@ -37,24 +37,23 @@ import org.springframework.stereotype.Service; * @since 2018-05-15 */ @Service -public class SysOauthClientDetailsServiceImpl extends ServiceImpl implements SysOauthClientDetailsService { +public class SysOauthClientDetailsServiceImpl extends ServiceImpl + implements SysOauthClientDetailsService { /** * 通过ID删除客户端 - * * @param clientId * @return */ @Override @CacheEvict(value = CacheConstants.CLIENT_DETAILS_KEY, key = "#clientId") public Boolean removeByClientId(String clientId) { - return this.remove(Wrappers.lambdaQuery() - .eq(SysOauthClientDetails::getClientId, clientId)); + return this + .remove(Wrappers.lambdaQuery().eq(SysOauthClientDetails::getClientId, clientId)); } /** * 根据客户端信息 - * * @param clientDetails * @return */ @@ -63,4 +62,5 @@ public class SysOauthClientDetailsServiceImpl extends ServiceImpl implements SysPublicParamService { +public class SysPublicParamServiceImpl extends ServiceImpl + implements SysPublicParamService { @Override @Cacheable(value = CacheConstants.PARAMS_DETAILS, key = "#publicKey", unless = "#result == null ") public String getSysPublicParamKeyToValue(String publicKey) { SysPublicParam sysPublicParam = this.baseMapper - .selectOne(Wrappers.lambdaQuery() - .eq(SysPublicParam::getPublicKey, publicKey)); + .selectOne(Wrappers.lambdaQuery().eq(SysPublicParam::getPublicKey, publicKey)); if (sysPublicParam != null) { return sysPublicParam.getPublicValue(); @@ -55,7 +55,6 @@ public class SysPublicParamServiceImpl extends ServiceImpl implements SysRoleMenuService { + private final CacheManager cacheManager; /** * @param role - * @param roleId 角色 + * @param roleId 角色 * @param menuIds 菜单ID拼成的字符串,每个id之间根据逗号分隔 * @return */ @@ -59,23 +60,21 @@ public class SysRoleMenuServiceImpl extends ServiceImplquery().lambda() - .eq(SysRoleMenu::getRoleId, roleId)); + this.remove(Wrappers.query().lambda().eq(SysRoleMenu::getRoleId, roleId)); if (StrUtil.isBlank(menuIds)) { return Boolean.TRUE; } - List roleMenuList = Arrays - .stream(menuIds.split(",")) - .map(menuId -> { - SysRoleMenu roleMenu = new SysRoleMenu(); - roleMenu.setRoleId(roleId); - roleMenu.setMenuId(Integer.valueOf(menuId)); - return roleMenu; - }).collect(Collectors.toList()); + List roleMenuList = Arrays.stream(menuIds.split(",")).map(menuId -> { + SysRoleMenu roleMenu = new SysRoleMenu(); + roleMenu.setRoleId(roleId); + roleMenu.setMenuId(Integer.valueOf(menuId)); + return roleMenu; + }).collect(Collectors.toList()); - //清空userinfo + // 清空userinfo cacheManager.getCache(CacheConstants.USER_DETAILS).clear(); return this.saveBatch(roleMenuList); } + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/SysRoleServiceImpl.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/SysRoleServiceImpl.java index 2ec3d0df3..94d28d4e5 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/SysRoleServiceImpl.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/SysRoleServiceImpl.java @@ -43,11 +43,11 @@ import java.util.List; @Service @AllArgsConstructor public class SysRoleServiceImpl extends ServiceImpl implements SysRoleService { + private SysRoleMenuMapper sysRoleMenuMapper; /** * 通过用户ID,查询角色信息 - * * @param userId * @return */ @@ -58,16 +58,14 @@ public class SysRoleServiceImpl extends ServiceImpl impl /** * 通过角色ID,删除角色,并清空角色菜单缓存 - * * @param id * @return */ @Override @Transactional(rollbackFor = Exception.class) public Boolean removeRoleById(Integer id) { - sysRoleMenuMapper.delete(Wrappers - .update().lambda() - .eq(SysRoleMenu::getRoleId, id)); + sysRoleMenuMapper.delete(Wrappers.update().lambda().eq(SysRoleMenu::getRoleId, id)); return this.removeById(id); } + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/SysRouteConfServiceImpl.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/SysRouteConfServiceImpl.java index 399f887b1..eae902f43 100755 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/SysRouteConfServiceImpl.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/SysRouteConfServiceImpl.java @@ -55,14 +55,15 @@ import java.util.stream.Collectors; @Slf4j @AllArgsConstructor @Service("sysRouteConfService") -public class SysRouteConfServiceImpl extends ServiceImpl implements SysRouteConfService { - private final RedisTemplate redisTemplate; - private final ApplicationEventPublisher applicationEventPublisher; +public class SysRouteConfServiceImpl extends ServiceImpl + implements SysRouteConfService { + private final RedisTemplate redisTemplate; + + private final ApplicationEventPublisher applicationEventPublisher; /** * 更新路由信息 - * * @param routes 路由信息 * @return */ @@ -95,16 +96,15 @@ public class SysRouteConfServiceImpl extends ServiceImpl predicateDefinitionList = - predicatesArray.toList(PredicateDefinition.class); + List predicateDefinitionList = predicatesArray + .toList(PredicateDefinition.class); vo.setPredicates(predicateDefinitionList); } Object filters = map.get("filters"); if (filters != null) { JSONArray filtersArray = (JSONArray) filters; - List filterDefinitionList - = filtersArray.toList(FilterDefinition.class); + List filterDefinitionList = filtersArray.toList(FilterDefinition.class); vo.setFilters(filterDefinitionList); } @@ -127,7 +127,7 @@ public class SysRouteConfServiceImpl extends ServiceImpl(condition)); - //插入生效路由 + // 插入生效路由 List routeConfList = routeDefinitionVoList.stream().map(vo -> { SysRouteConf routeConf = new SysRouteConf(); routeConf.setRouteId(vo.getId()); @@ -143,7 +143,8 @@ public class SysRouteConfServiceImpl extends ServiceImpl implements SysSocialDetailsService { +public class SysSocialDetailsServiceImpl extends ServiceImpl + implements SysSocialDetailsService { + private final Map loginHandlerMap; + private final CacheManager cacheManager; + private final SysUserMapper sysUserMapper; /** * 绑定社交账号 - * * @param type type * @param code code * @return @@ -62,25 +65,28 @@ public class SysSocialDetailsServiceImpl extends ServiceImpl implements SysTenantService { + private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder(); + private final SysOauthClientDetailsService clientServices; + private final SysDeptRelationService deptRelationService; + private final SysUserRoleService userRoleService; + private final SysRoleMenuService roleMenuService; + private final SysDictItemService dictItemService; + private final SysPublicParamService paramService; + private final SysUserService userService; + private final SysRoleService roleService; + private final SysMenuService menuService; + private final SysDeptService deptService; + private final SysDictService dictService; /** * 获取正常状态租户 *

- * 1. 状态正常 - * 2. 开始时间小于等于当前时间 - * 3. 结束时间大于等于当前时间 - * + * 1. 状态正常 2. 开始时间小于等于当前时间 3. 结束时间大于等于当前时间 * @return */ @Override @Cacheable(value = CacheConstants.TENANT_DETAILS) public List getNormalTenant() { - return baseMapper.selectList(Wrappers.lambdaQuery() - .eq(SysTenant::getStatus, CommonConstants.STATUS_NORMAL)); + return baseMapper + .selectList(Wrappers.lambdaQuery().eq(SysTenant::getStatus, CommonConstants.STATUS_NORMAL)); } /** * 保存租户 *

- * 1. 保存租户 - * 2. 初始化权限相关表 - * - sys_user - * - sys_role - * - sys_menu - * - sys_user_role - * - sys_role_menu - * - sys_dict - * - sys_dict_item - * - sys_client_details - * - sys_public_params - * + * 1. 保存租户 2. 初始化权限相关表 - sys_user - sys_role - sys_menu - sys_user_role - + * sys_role_menu - sys_dict - sys_dict_item - sys_client_details - sys_public_params * @param sysTenant 租户实体 * @return */ @@ -117,15 +116,13 @@ public class SysTenantServiceImpl extends ServiceImpl clientDetailsList = new ArrayList<>(16); List publicParamList = new ArrayList<>(64); - TenantBroker.runAs(defaultId,(id) -> { + TenantBroker.runAs(defaultId, (id) -> { // 查询系统内置字典 dictList.addAll(dictService.list()); // 查询系统内置字典项目 - dictIdList.addAll(dictList.stream().map(SysDict::getId) - .collect(Collectors.toList())); - dictItemList.addAll(dictItemService - .list(Wrappers.lambdaQuery() - .in(SysDictItem::getDictId, dictIdList))); + dictIdList.addAll(dictList.stream().map(SysDict::getId).collect(Collectors.toList())); + dictItemList.addAll( + dictItemService.list(Wrappers.lambdaQuery().in(SysDictItem::getDictId, dictIdList))); // 查询当前租户菜单 menuList.addAll(menuService.list()); // 查询客户端配置 @@ -135,14 +132,14 @@ public class SysTenantServiceImpl extends ServiceImpl { + return TenantBroker.applyAs(sysTenant.getId(), (id -> { // 插入部门 SysDept dept = new SysDept(); dept.setName(defaultDeptName); dept.setParentId(0); deptService.save(dept); - //维护部门关系 + // 维护部门关系 deptRelationService.insertDeptRelation(dept); // 构造初始化用户 SysUser user = new SysUser(); @@ -161,7 +158,8 @@ public class SysTenantServiceImpl extends ServiceImpl newMenuList = menuService.list(); // 查询全部菜单,构造角色菜单关系 @@ -175,13 +173,11 @@ public class SysTenantServiceImpl extends ServiceImpl itemList = dictList.stream() - .flatMap(dict -> dictItemList.stream() - .filter(item -> item.getType().equals(dict.getType())) - .peek(item -> item.setDictId(dict.getId()))) + List itemList = dictList.stream().flatMap(dict -> dictItemList.stream() + .filter(item -> item.getType().equals(dict.getType())).peek(item -> item.setDictId(dict.getId()))) .collect(Collectors.toList()); - //插入客户端 + // 插入客户端 clientServices.saveBatch(clientDetailsList); // 插入系统配置 paramService.saveBatch(publicParamList); @@ -192,9 +188,8 @@ public class SysTenantServiceImpl extends ServiceImpl nodeList, Integer parent) { for (MenuTree node : nodeList) { @@ -203,10 +198,11 @@ public class SysTenantServiceImpl extends ServiceImpl childrenList = node.getChildren().stream() - .map(treeNode -> (MenuTree) treeNode).collect(Collectors.toList()); + List childrenList = node.getChildren().stream().map(treeNode -> (MenuTree) treeNode) + .collect(Collectors.toList()); saveTenantMenu(childrenList, menu.getMenuId()); } } } + } diff --git a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/SysUserRoleServiceImpl.java b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/SysUserRoleServiceImpl.java index 3da2ab3ca..d7fb253a5 100644 --- a/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/SysUserRoleServiceImpl.java +++ b/pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/impl/SysUserRoleServiceImpl.java @@ -38,7 +38,6 @@ public class SysUserRoleServiceImpl extends ServiceImpl implements SysUserService { + private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder(); + private final SysMenuService sysMenuService; + private final SysRoleService sysRoleService; + private final SysDeptService sysDeptService; + private final SysUserRoleService sysUserRoleService; + private final SysDeptRelationService sysDeptRelationService; /** * 保存用户信息 - * * @param userDto DTO 对象 * @return success/fail */ @@ -82,19 +87,17 @@ public class SysUserServiceImpl extends ServiceImpl impl sysUser.setDelFlag(CommonConstants.STATUS_NORMAL); sysUser.setPassword(ENCODER.encode(userDto.getPassword())); baseMapper.insert(sysUser); - List userRoleList = userDto.getRole() - .stream().map(roleId -> { - SysUserRole userRole = new SysUserRole(); - userRole.setUserId(sysUser.getUserId()); - userRole.setRoleId(roleId); - return userRole; - }).collect(Collectors.toList()); + List userRoleList = userDto.getRole().stream().map(roleId -> { + SysUserRole userRole = new SysUserRole(); + userRole.setUserId(sysUser.getUserId()); + userRole.setRoleId(roleId); + return userRole; + }).collect(Collectors.toList()); return sysUserRoleService.saveBatch(userRoleList); } /** * 通过查用户的全部信息 - * * @param sysUser 用户 * @return */ @@ -102,20 +105,16 @@ public class SysUserServiceImpl extends ServiceImpl impl public UserInfo findUserInfo(SysUser sysUser) { UserInfo userInfo = new UserInfo(); userInfo.setSysUser(sysUser); - //设置角色列表 (ID) - List roleIds = sysRoleService.findRolesByUserId(sysUser.getUserId()) - .stream() - .map(SysRole::getRoleId) + // 设置角色列表 (ID) + List roleIds = sysRoleService.findRolesByUserId(sysUser.getUserId()).stream().map(SysRole::getRoleId) .collect(Collectors.toList()); userInfo.setRoles(ArrayUtil.toArray(roleIds, Integer.class)); - //设置权限列表(menu.permission) + // 设置权限列表(menu.permission) Set permissions = new HashSet<>(); roleIds.forEach(roleId -> { - List permissionList = sysMenuService.findMenuByRoleId(roleId) - .stream() - .filter(menuVo -> StringUtils.isNotEmpty(menuVo.getPermission())) - .map(MenuVO::getPermission) + List permissionList = sysMenuService.findMenuByRoleId(roleId).stream() + .filter(menuVo -> StringUtils.isNotEmpty(menuVo.getPermission())).map(MenuVO::getPermission) .collect(Collectors.toList()); permissions.addAll(permissionList); }); @@ -125,8 +124,7 @@ public class SysUserServiceImpl extends ServiceImpl impl /** * 分页查询用户信息(含有角色信息) - * - * @param page 分页对象 + * @param page 分页对象 * @param userDTO 参数列表 * @return */ @@ -137,7 +135,6 @@ public class SysUserServiceImpl extends ServiceImpl impl /** * 通过ID查询用户信息 - * * @param id 用户ID * @return 用户信息 */ @@ -148,7 +145,6 @@ public class SysUserServiceImpl extends ServiceImpl impl /** * 删除用户 - * * @param sysUser 用户 * @return Boolean */ @@ -165,11 +161,11 @@ public class SysUserServiceImpl extends ServiceImpl impl public R updateUserInfo(UserDTO userDto) { UserVO userVO = baseMapper.getUserVoByUsername(userDto.getUsername()); SysUser sysUser = new SysUser(); - if (StrUtil.isNotBlank(userDto.getPassword()) - && StrUtil.isNotBlank(userDto.getNewpassword1())) { + if (StrUtil.isNotBlank(userDto.getPassword()) && StrUtil.isNotBlank(userDto.getNewpassword1())) { if (ENCODER.matches(userDto.getPassword(), userVO.getPassword())) { sysUser.setPassword(ENCODER.encode(userDto.getNewpassword1())); - } else { + } + else { log.info("原密码错误,修改密码失败:{}", userDto.getUsername()); return R.failed("原密码错误,修改失败"); } @@ -192,8 +188,8 @@ public class SysUserServiceImpl extends ServiceImpl impl } this.updateById(sysUser); - sysUserRoleService.remove(Wrappers.update().lambda() - .eq(SysUserRole::getUserId, userDto.getUserId())); + sysUserRoleService + .remove(Wrappers.update().lambda().eq(SysUserRole::getUserId, userDto.getUserId())); userDto.getRole().forEach(roleId -> { SysUserRole userRole = new SysUserRole(); userRole.setUserId(sysUser.getUserId()); @@ -205,14 +201,12 @@ public class SysUserServiceImpl extends ServiceImpl impl /** * 查询上级部门的用户信息 - * * @param username 用户名 * @return R */ @Override public List listAncestorUsers(String username) { - SysUser sysUser = this.getOne(Wrappers.query().lambda() - .eq(SysUser::getUsername, username)); + SysUser sysUser = this.getOne(Wrappers.query().lambda().eq(SysUser::getUsername, username)); SysDept sysDept = sysDeptService.getById(sysUser.getDeptId()); if (sysDept == null) { @@ -220,24 +214,19 @@ public class SysUserServiceImpl extends ServiceImpl impl } Integer parentId = sysDept.getParentId(); - return this.list(Wrappers.query().lambda() - .eq(SysUser::getDeptId, parentId)); + return this.list(Wrappers.query().lambda().eq(SysUser::getDeptId, parentId)); } /** * 获取当前用户的子部门信息 - * * @return 子部门列表 */ private List getChildDepts() { Integer deptId = SecurityUtils.getUser().getDeptId(); - //获取当前部门的子部门 + // 获取当前部门的子部门 return sysDeptRelationService - .list(Wrappers.query().lambda() - .eq(SysDeptRelation::getAncestor, deptId)) - .stream() - .map(SysDeptRelation::getDescendant) - .collect(Collectors.toList()); + .list(Wrappers.query().lambda().eq(SysDeptRelation::getAncestor, deptId)).stream() + .map(SysDeptRelation::getDescendant).collect(Collectors.toList()); } } diff --git a/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/PigxCodeGenApplication.java b/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/PigxCodeGenApplication.java index ccd8bb432..cab4eda46 100755 --- a/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/PigxCodeGenApplication.java +++ b/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/PigxCodeGenApplication.java @@ -26,8 +26,7 @@ import org.springframework.cloud.client.SpringCloudApplication; /** * @author lengleng - * @date 2018/07/29 - * 代码生成模块 + * @date 2018/07/29 代码生成模块 */ @EnableDynamicDataSource @EnablePigxSwagger2 @@ -36,8 +35,8 @@ import org.springframework.cloud.client.SpringCloudApplication; @EnablePigxResourceServer public class PigxCodeGenApplication { - public static void main(String[] args) { SpringApplication.run(PigxCodeGenApplication.class, args); } + } diff --git a/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/controller/GenDsConfController.java b/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/controller/GenDsConfController.java index 9cc3e6f80..625770821 100755 --- a/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/controller/GenDsConfController.java +++ b/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/controller/GenDsConfController.java @@ -25,7 +25,6 @@ import com.pig4cloud.pigx.common.log.annotation.SysLog; import lombok.AllArgsConstructor; import org.springframework.web.bind.annotation.*; - /** * 数据源管理 * @@ -36,13 +35,12 @@ import org.springframework.web.bind.annotation.*; @AllArgsConstructor @RequestMapping("/dsconf") public class GenDsConfController { - private final GenDatasourceConfService datasourceConfService; + private final GenDatasourceConfService datasourceConfService; /** * 分页查询 - * - * @param page 分页对象 + * @param page 分页对象 * @param datasourceConf 数据源表 * @return */ @@ -53,7 +51,6 @@ public class GenDsConfController { /** * 查询全部数据源 - * * @return */ @GetMapping("/list") @@ -61,10 +58,8 @@ public class GenDsConfController { return R.ok(datasourceConfService.list()); } - /** * 通过id查询数据源表 - * * @param id id * @return R */ @@ -75,7 +70,6 @@ public class GenDsConfController { /** * 新增数据源表 - * * @param datasourceConf 数据源表 * @return R */ @@ -87,7 +81,6 @@ public class GenDsConfController { /** * 修改数据源表 - * * @param conf 数据源表 * @return R */ @@ -99,7 +92,6 @@ public class GenDsConfController { /** * 通过id删除数据源表 - * * @param id id * @return R */ @@ -108,4 +100,5 @@ public class GenDsConfController { public R removeById(@PathVariable Integer id) { return R.ok(datasourceConfService.removeByDsId(id)); } + } diff --git a/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/controller/GenFormConfController.java b/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/controller/GenFormConfController.java index a9feaa99c..e8e9c7a36 100755 --- a/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/controller/GenFormConfController.java +++ b/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/controller/GenFormConfController.java @@ -29,7 +29,6 @@ import lombok.AllArgsConstructor; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; - /** * 表单管理 * @@ -41,12 +40,12 @@ import org.springframework.web.bind.annotation.*; @RequestMapping("/form") @Api(value = "form", tags = "表单管理") public class GenFormConfController { + private final GenFormConfService genRecordService; /** * 分页查询 - * - * @param page 分页对象 + * @param page 分页对象 * @param formConf 生成记录 * @return */ @@ -56,10 +55,8 @@ public class GenFormConfController { return R.ok(genRecordService.page(page, Wrappers.query(formConf))); } - /** * 通过id查询生成记录 - * * @param id id * @return R */ @@ -71,8 +68,7 @@ public class GenFormConfController { /** * 通过id查询生成记录 - * - * @param dsName 数据源ID + * @param dsName 数据源ID * @param tableName tableName * @return R */ @@ -84,7 +80,6 @@ public class GenFormConfController { /** * 新增生成记录 - * * @param formConf 生成记录 * @return R */ @@ -98,7 +93,6 @@ public class GenFormConfController { /** * 修改生成记录 - * * @param formConf 生成记录 * @return R */ @@ -112,7 +106,6 @@ public class GenFormConfController { /** * 通过id删除生成记录 - * * @param id id * @return R */ diff --git a/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/controller/GeneratorController.java b/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/controller/GeneratorController.java index 2d4949ad0..38d7b5d93 100755 --- a/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/controller/GeneratorController.java +++ b/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/controller/GeneratorController.java @@ -40,14 +40,15 @@ import javax.servlet.http.HttpServletResponse; @AllArgsConstructor @RequestMapping("/generator") public class GeneratorController { + private final GeneratorService generatorService; + private final GenTableColumnService columnService; /** * 列表 - * * @param tableName 参数集 - * @param dsName 数据源编号 + * @param dsName 数据源编号 * @return 数据库表 */ @GetMapping("/page") @@ -57,7 +58,6 @@ public class GeneratorController { /** * 预览代码 - * * @param genConfig 数据表配置 * @return */ @@ -68,8 +68,7 @@ public class GeneratorController { /** * 查询表的列信息 - * - * @param page 分页 + * @param page 分页 * @param genConfig 数据表配置 * @return */ @@ -78,10 +77,8 @@ public class GeneratorController { return R.ok(columnService.listTable(page, genConfig)); } - /** * 生成代码 - * * @param genConfig 数据表配置 */ @SneakyThrows @@ -89,10 +86,12 @@ public class GeneratorController { public void generatorCode(@RequestBody GenConfig genConfig, HttpServletResponse response) { byte[] data = generatorService.generatorCode(genConfig); response.reset(); - response.setHeader(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment; filename=%s.zip", genConfig.getTableName())); + response.setHeader(HttpHeaders.CONTENT_DISPOSITION, + String.format("attachment; filename=%s.zip", genConfig.getTableName())); response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length)); response.setContentType("application/octet-stream; charset=UTF-8"); IoUtil.write(response.getOutputStream(), Boolean.TRUE, data); } + } diff --git a/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/entity/ColumnEntity.java b/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/entity/ColumnEntity.java index 6e676c27e..7f916b221 100755 --- a/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/entity/ColumnEntity.java +++ b/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/entity/ColumnEntity.java @@ -21,23 +21,26 @@ import lombok.Data; /** * @author lengleng - * @date 2018/07/29 - * 列属性: https://blog.csdn.net/lkforce/article/details/79557482 + * @date 2018/07/29 列属性: https://blog.csdn.net/lkforce/article/details/79557482 */ @Data public class ColumnEntity { + /** * 列表 */ private String columnName; + /** * 数据类型 */ private String dataType; + /** * JAVA 数据类型 */ private String javaType; + /** * 备注 */ @@ -47,28 +50,35 @@ public class ColumnEntity { * 驼峰属性 */ private String caseAttrName; + /** * 普通属性 */ private String lowerAttrName; + /** * 属性类型 */ private String attrType; + /** * 其他信息 */ private String extra; + /** * 字段类型 */ private String columnType; + /** * 是否可以为空 */ private Boolean nullable; + /** * 是否隐藏 */ private Boolean hidden; + } diff --git a/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/entity/GenConfig.java b/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/entity/GenConfig.java index 6fafa2f1c..dd6bf91a9 100644 --- a/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/entity/GenConfig.java +++ b/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/entity/GenConfig.java @@ -21,27 +21,31 @@ import lombok.Data; /** * @author lengleng - * @date 2018/8/2 - * 生成配置 + * @date 2018/8/2 生成配置 */ @Data public class GenConfig { + /** * 数据源name */ private String dsName; + /** * 包名 */ private String packageName; + /** * 作者 */ private String author; + /** * 模块名称 */ private String moduleName; + /** * 表前缀 */ @@ -58,9 +62,8 @@ public class GenConfig { private String comments; /** - * 代码风格 - * 0 - avue - * 1 - element + * 代码风格 0 - avue 1 - element */ private String style; + } diff --git a/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/entity/GenDatasourceConf.java b/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/entity/GenDatasourceConf.java index e47696200..a74dbc59a 100755 --- a/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/entity/GenDatasourceConf.java +++ b/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/entity/GenDatasourceConf.java @@ -35,6 +35,7 @@ import java.time.LocalDateTime; @TableName("gen_datasource_conf") @EqualsAndHashCode(callSuper = true) public class GenDatasourceConf extends Model { + private static final long serialVersionUID = 1L; /** @@ -42,35 +43,43 @@ public class GenDatasourceConf extends Model { */ @TableId private Integer id; + /** * 名称 */ private String name; + /** * jdbcurl */ private String url; + /** * 用户名 */ private String username; + /** * 密码 */ private String password; + /** * 创建时间 */ private LocalDateTime createDate; + /** * 更新 */ private LocalDateTime updateDate; + /** * 删除标记 */ @TableLogic private String delFlag; + /** * 租户ID */ diff --git a/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/entity/GenFormConf.java b/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/entity/GenFormConf.java index e109d480c..219aaa8a3 100755 --- a/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/entity/GenFormConf.java +++ b/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/entity/GenFormConf.java @@ -38,6 +38,7 @@ import java.time.LocalDateTime; @EqualsAndHashCode(callSuper = true) @ApiModel(value = "生成记录") public class GenFormConf extends Model { + private static final long serialVersionUID = 1L; /** @@ -46,34 +47,41 @@ public class GenFormConf extends Model { @TableId @ApiModelProperty(value = "ID") private Integer id; + /** * 表名称 */ @ApiModelProperty(value = "表名称") private String tableName; + /** * 表单信息 */ @ApiModelProperty(value = "表单信息") private String formInfo; + /** * 创建时间 */ @ApiModelProperty(value = "创建时间") private LocalDateTime createTime; + /** * 修改时间 */ @ApiModelProperty(value = "修改时间") private LocalDateTime updateTime; + /** * 删除标记 */ @ApiModelProperty(value = "删除标记") private String delFlag; + /** * 所属租户 */ @ApiModelProperty(value = "所属租户", hidden = true) private Integer tenantId; + } diff --git a/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/entity/TableEntity.java b/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/entity/TableEntity.java index d5f1bda66..59bbe048c 100755 --- a/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/entity/TableEntity.java +++ b/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/entity/TableEntity.java @@ -23,33 +23,39 @@ import java.util.List; /** * @author lengleng - * @date 2018/07/29 - * 表属性: https://blog.csdn.net/lkforce/article/details/79557482 + * @date 2018/07/29 表属性: https://blog.csdn.net/lkforce/article/details/79557482 */ @Data public class TableEntity { + /** * 名称 */ private String tableName; + /** * 备注 */ private String comments; + /** * 主键 */ private ColumnEntity pk; + /** * 列名 */ private List columns; + /** * 驼峰类型 */ private String caseClassName; + /** * 普通类型 */ private String lowerClassName; + } diff --git a/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/mapper/GenTableColumnMapper.java b/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/mapper/GenTableColumnMapper.java index 9541de956..f707fc3d4 100644 --- a/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/mapper/GenTableColumnMapper.java +++ b/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/mapper/GenTableColumnMapper.java @@ -20,18 +20,17 @@ public interface GenTableColumnMapper extends BaseMapper { /** * 分页查询表分页信息 - * * @param page * @param tableName * @param dsName * @return */ @DS("#last") - IPage selectTableColumn(Page page, @Param("tableName") String tableName, @Param("dsName") String dsName); + IPage selectTableColumn(Page page, @Param("tableName") String tableName, + @Param("dsName") String dsName); /** * 查询表全部列信息 - * * @param tableName * @param dsName * @return @@ -39,14 +38,13 @@ public interface GenTableColumnMapper extends BaseMapper { @DS("#last") List selectTableColumn(@Param("tableName") String tableName, @Param("dsName") String dsName); - /** * 查询表全部列信息 - * * @param tableName 表名称 - * @param dsName 数据源名称 + * @param dsName 数据源名称 * @return */ @DS("#last") List> selectMapTableColumn(@Param("tableName") String tableName, String dsName); + } diff --git a/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/mapper/GeneratorMapper.java b/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/mapper/GeneratorMapper.java index fafbc2125..b6fc50401 100755 --- a/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/mapper/GeneratorMapper.java +++ b/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/mapper/GeneratorMapper.java @@ -37,8 +37,7 @@ public interface GeneratorMapper { /** * 分页查询表格 - * - * @param page 分页信息 + * @param page 分页信息 * @param tableName 表名称 * @return */ @@ -46,11 +45,11 @@ public interface GeneratorMapper { /** * 查询表信息 - * * @param tableName 表名称 - * @param dsName 数据源名称 + * @param dsName 数据源名称 * @return */ @DS("#last") Map queryTable(@Param("tableName") String tableName, String dsName); + } diff --git a/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/service/GenDatasourceConfService.java b/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/service/GenDatasourceConfService.java index 3b842f18f..91e6a5482 100755 --- a/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/service/GenDatasourceConfService.java +++ b/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/service/GenDatasourceConfService.java @@ -26,9 +26,9 @@ import com.pig4cloud.pigx.codegen.entity.GenDatasourceConf; * @date 2019-03-31 16:00:20 */ public interface GenDatasourceConfService extends IService { + /** * 保存数据源并且加密 - * * @param genDatasourceConf * @return */ @@ -36,7 +36,6 @@ public interface GenDatasourceConfService extends IService { /** * 更新数据源 - * * @param genDatasourceConf * @return */ @@ -44,16 +43,13 @@ public interface GenDatasourceConfService extends IService { /** * 更新动态数据的数据源列表 - * * @param datasourceConf * @return */ void addDynamicDataSource(GenDatasourceConf datasourceConf); - /** * 校验数据源配置是否有效 - * * @param datasourceConf 数据源信息 * @return 有效/无效 */ @@ -61,9 +57,9 @@ public interface GenDatasourceConfService extends IService { /** * 通过数据源名称删除 - * * @param dsId 数据源ID * @return */ Boolean removeByDsId(Integer dsId); + } diff --git a/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/service/GenFormConfService.java b/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/service/GenFormConfService.java index 695830b3d..d7546ac82 100755 --- a/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/service/GenFormConfService.java +++ b/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/service/GenFormConfService.java @@ -30,8 +30,7 @@ public interface GenFormConfService extends IService { /** * 获取表单信息 - * - * @param dsName 数据源ID + * @param dsName 数据源ID * @param tableName 表名称 * @return */ diff --git a/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/service/GenTableColumnService.java b/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/service/GenTableColumnService.java index 6be08d4c5..2c755124f 100755 --- a/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/service/GenTableColumnService.java +++ b/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/service/GenTableColumnService.java @@ -33,10 +33,10 @@ public interface GenTableColumnService extends IService { /** * 查询表的字段信息 - * * @param page * @param genConfig 查询条件 * @return */ IPage listTable(Page page, GenConfig genConfig); + } diff --git a/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/service/GeneratorService.java b/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/service/GeneratorService.java index 4651e9a43..38bf432d0 100644 --- a/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/service/GeneratorService.java +++ b/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/service/GeneratorService.java @@ -29,9 +29,9 @@ import java.util.Map; * @date 2018/7/29 */ public interface GeneratorService { + /** * 生成代码 - * * @param genConfig 生成信息 * @return */ @@ -39,19 +39,18 @@ public interface GeneratorService { /** * 分页查询表 - * - * @param page 分页信息 + * @param page 分页信息 * @param tableName 表名 - * @param name 数据源ID + * @param name 数据源ID * @return */ IPage>> getPage(Page page, String tableName, String name); /** * 预览代码 - * * @param genConfig 生成信息 * @return */ Map previewCode(GenConfig genConfig); + } diff --git a/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/service/impl/GenDatasourceConfServiceImpl.java b/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/service/impl/GenDatasourceConfServiceImpl.java index 987824199..41ac0a1d5 100755 --- a/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/service/impl/GenDatasourceConfServiceImpl.java +++ b/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/service/impl/GenDatasourceConfServiceImpl.java @@ -44,13 +44,15 @@ import java.sql.SQLException; @Slf4j @Service @AllArgsConstructor -public class GenDatasourceConfServiceImpl extends ServiceImpl implements GenDatasourceConfService { +public class GenDatasourceConfServiceImpl extends ServiceImpl + implements GenDatasourceConfService { + private final StringEncryptor stringEncryptor; + private final DataSourceCreator dataSourceCreator; /** * 保存数据源并且加密 - * * @param conf * @return */ @@ -61,7 +63,7 @@ public class GenDatasourceConfServiceImpl extends ServiceImpl implements GenFormConfService { + private final GenTableColumnMapper tableColumnMapper; /** - * 1. 根据数据源、表名称,查询已配置表单信息 - * 2. 不存在调用模板生成 - * - * @param dsName 数据源ID + * 1. 根据数据源、表名称,查询已配置表单信息 2. 不存在调用模板生成 + * @param dsName 数据源ID * @param tableName 表名称 * @return */ @Override @SneakyThrows public String getForm(String dsName, String tableName) { - GenFormConf form = getOne(Wrappers.lambdaQuery() - .eq(GenFormConf::getTableName, tableName) + GenFormConf form = getOne(Wrappers.lambdaQuery().eq(GenFormConf::getTableName, tableName) .orderByDesc(GenFormConf::getCreateTime), false); if (form != null) { @@ -71,7 +69,7 @@ public class GenFormConfServiceImpl extends ServiceImpl columns = tableColumnMapper.selectTableColumn(tableName, dsName); - //设置velocity资源加载器 + // 设置velocity资源加载器 Properties prop = new Properties(); prop.put("file.resource.loader.class", ClasspathResourceLoader.class.getName()); Velocity.init(prop); diff --git a/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/service/impl/GenTableColumnServiceImpl.java b/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/service/impl/GenTableColumnServiceImpl.java index 43079eeb2..f3c07c4da 100644 --- a/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/service/impl/GenTableColumnServiceImpl.java +++ b/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/service/impl/GenTableColumnServiceImpl.java @@ -21,10 +21,13 @@ import org.springframework.stereotype.Service; */ @Service @AllArgsConstructor -public class GenTableColumnServiceImpl extends ServiceImpl implements GenTableColumnService { +public class GenTableColumnServiceImpl extends ServiceImpl + implements GenTableColumnService { + @Override public IPage listTable(Page page, GenConfig genConfig) { - IPage columnPage = baseMapper.selectTableColumn(page, genConfig.getTableName(), genConfig.getDsName()); + IPage columnPage = baseMapper.selectTableColumn(page, genConfig.getTableName(), + genConfig.getDsName()); // 处理 数据库类型和 Java 类型关系 Configuration config = GenUtils.getConfig(); @@ -35,4 +38,5 @@ public class GenTableColumnServiceImpl extends ServiceImpl previewCode(GenConfig genConfig) { - //根据tableName 查询最新的表单配置 + // 根据tableName 查询最新的表单配置 List formConfList = genFormConfMapper.selectList(Wrappers.lambdaQuery() - .eq(GenFormConf::getTableName, genConfig.getTableName()) - .orderByDesc(GenFormConf::getCreateTime)); + .eq(GenFormConf::getTableName, genConfig.getTableName()).orderByDesc(GenFormConf::getCreateTime)); DynamicDataSourceContextHolder.push(genConfig.getDsName()); String tableNames = genConfig.getTableName(); for (String tableName : StrUtil.split(tableNames, StrUtil.DASHED)) { - //查询表信息 + // 查询表信息 Map table = generatorMapper.queryTable(tableName, genConfig.getDsName()); - //查询列信息 - List> columns = tableColumnMapper.selectMapTableColumn(tableName, genConfig.getDsName()); - //生成代码 + // 查询列信息 + List> columns = tableColumnMapper.selectMapTableColumn(tableName, + genConfig.getDsName()); + // 生成代码 if (CollUtil.isNotEmpty(formConfList)) { return GenUtils.generatorCode(genConfig, table, columns, null, formConfList.get(0)); - } else { + } + else { return GenUtils.generatorCode(genConfig, table, columns, null, null); } } @@ -94,16 +97,14 @@ public class GeneratorServiceImpl implements GeneratorService { /** * 生成代码 - * * @param genConfig 生成配置 * @return */ @Override public byte[] generatorCode(GenConfig genConfig) { - //根据tableName 查询最新的表单配置 + // 根据tableName 查询最新的表单配置 List formConfList = genFormConfMapper.selectList(Wrappers.lambdaQuery() - .eq(GenFormConf::getTableName, genConfig.getTableName()) - .orderByDesc(GenFormConf::getCreateTime)); + .eq(GenFormConf::getTableName, genConfig.getTableName()).orderByDesc(GenFormConf::getCreateTime)); DynamicDataSourceContextHolder.push(genConfig.getDsName()); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); @@ -111,18 +112,21 @@ public class GeneratorServiceImpl implements GeneratorService { String tableNames = genConfig.getTableName(); for (String tableName : StrUtil.split(tableNames, StrUtil.DASHED)) { - //查询表信息 + // 查询表信息 Map table = generatorMapper.queryTable(tableName, genConfig.getDsName()); - //查询列信息 - List> columns = tableColumnMapper.selectMapTableColumn(tableName, genConfig.getDsName()); - //生成代码 + // 查询列信息 + List> columns = tableColumnMapper.selectMapTableColumn(tableName, + genConfig.getDsName()); + // 生成代码 if (CollUtil.isNotEmpty(formConfList)) { GenUtils.generatorCode(genConfig, table, columns, zip, formConfList.get(0)); - } else { + } + else { GenUtils.generatorCode(genConfig, table, columns, zip, null); } } IoUtil.close(zip); return outputStream.toByteArray(); } + } diff --git a/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/util/GenUtils.java b/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/util/GenUtils.java index 25efb0120..da0b7de09 100644 --- a/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/util/GenUtils.java +++ b/pigx-visual/pigx-codegen/src/main/java/com/pig4cloud/pigx/codegen/util/GenUtils.java @@ -49,7 +49,7 @@ import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** - * 代码生成器 工具类 + * 代码生成器 工具类 * * @author lengleng * @date 2018-07-30 @@ -57,23 +57,35 @@ import java.util.zip.ZipOutputStream; @Slf4j @UtilityClass public class GenUtils { + public final String CRUD_PREFIX = "export const tableOption ="; + private final String ENTITY_JAVA_VM = "Entity.java.vm"; + private final String MAPPER_JAVA_VM = "Mapper.java.vm"; + private final String SERVICE_JAVA_VM = "Service.java.vm"; + private final String SERVICE_IMPL_JAVA_VM = "ServiceImpl.java.vm"; + private final String CONTROLLER_JAVA_VM = "Controller.java.vm"; + private final String MAPPER_XML_VM = "Mapper.xml.vm"; + private final String MENU_SQL_VM = "menu.sql.vm"; + private final String AVUE_INDEX_VUE_VM = "avue/index.vue.vm"; + private final String ELE_INDEX_VUE_VM = "element/index.vue.vm"; + private final String ELE_ADD_UPDATE_VUE_VM = "element/form.vue.vm"; + private final String AVUE_API_JS_VM = "avue/api.js.vm"; + private final String AVUE_CRUD_JS_VM = "avue/crud.js.vm"; /** * 配置 - * * @param config * @return */ @@ -91,7 +103,8 @@ public class GenUtils { if (StyleTypeEnum.ELEMENT.getStyle().equals(config.getStyle())) { templates.add("template/element/index.vue.vm"); templates.add("template/element/form.vue.vm"); - } else { + } + else { templates.add("template/avue/index.vue.vm"); templates.add("template/avue/crud.js.vm"); } @@ -101,39 +114,40 @@ public class GenUtils { /** * 生成代码 - * * @return */ @SneakyThrows public Map generatorCode(GenConfig genConfig, Map table, - List> columns, ZipOutputStream zip, GenFormConf formConf) { - //配置信息 + List> columns, ZipOutputStream zip, GenFormConf formConf) { + // 配置信息 Configuration config = getConfig(); boolean hasBigDecimal = false; - //表信息 + // 表信息 TableEntity tableEntity = new TableEntity(); tableEntity.setTableName(table.get("tableName")); if (StrUtil.isNotBlank(genConfig.getComments())) { tableEntity.setComments(genConfig.getComments()); - } else { + } + else { tableEntity.setComments(table.get("tableComment")); } String tablePrefix; if (StrUtil.isNotBlank(genConfig.getTablePrefix())) { tablePrefix = genConfig.getTablePrefix(); - } else { + } + else { tablePrefix = config.getString("tablePrefix"); } - //表名转换成Java类名 + // 表名转换成Java类名 String className = tableToJava(tableEntity.getTableName(), tablePrefix); tableEntity.setCaseClassName(className); tableEntity.setLowerClassName(StringUtils.uncapitalize(className)); - //获取需要在swagger文档中隐藏的属性字段 + // 获取需要在swagger文档中隐藏的属性字段 List hiddenColumns = config.getList("hiddenColumn"); - //列信息 + // 列信息 List columnList = new ArrayList<>(); for (Map column : columns) { ColumnEntity columnEntity = new ColumnEntity(); @@ -143,24 +157,25 @@ public class GenUtils { columnEntity.setExtra(column.get("extra")); columnEntity.setNullable("NO".equals(column.get("isNullable"))); columnEntity.setColumnType(column.get("columnType")); - //隐藏不需要的在接口文档中展示的字段 + // 隐藏不需要的在接口文档中展示的字段 if (hiddenColumns.contains(column.get("columnName"))) { columnEntity.setHidden(Boolean.TRUE); - } else { + } + else { columnEntity.setHidden(Boolean.FALSE); } - //列名转换成Java属性名 + // 列名转换成Java属性名 String attrName = columnToJava(columnEntity.getColumnName()); columnEntity.setCaseAttrName(attrName); columnEntity.setLowerAttrName(StringUtils.uncapitalize(attrName)); - //列的数据类型,转换成Java类型 + // 列的数据类型,转换成Java类型 String attrType = config.getString(columnEntity.getDataType(), "unknowType"); columnEntity.setAttrType(attrType); if (!hasBigDecimal && "BigDecimal".equals(attrType)) { hasBigDecimal = true; } - //是否主键 + // 是否主键 if ("PRI".equalsIgnoreCase(column.get("columnKey")) && tableEntity.getPk() == null) { tableEntity.setPk(columnEntity); } @@ -169,13 +184,12 @@ public class GenUtils { } tableEntity.setColumns(columnList); - //没主键,则第一个字段为主键 + // 没主键,则第一个字段为主键 if (tableEntity.getPk() == null) { tableEntity.setPk(tableEntity.getColumns().get(0)); } - - //封装模板数据 + // 封装模板数据 Map map = new HashMap<>(16); map.put("tableName", tableEntity.getTableName()); map.put("pk", tableEntity.getPk()); @@ -188,26 +202,30 @@ public class GenUtils { if (StrUtil.isNotBlank(genConfig.getComments())) { map.put("comments", genConfig.getComments()); - } else { + } + else { map.put("comments", tableEntity.getComments()); } if (StrUtil.isNotBlank(genConfig.getAuthor())) { map.put("author", genConfig.getAuthor()); - } else { + } + else { map.put("author", config.getString("author")); } if (StrUtil.isNotBlank(genConfig.getModuleName())) { map.put("moduleName", genConfig.getModuleName()); - } else { + } + else { map.put("moduleName", config.getString("moduleName")); } if (StrUtil.isNotBlank(genConfig.getPackageName())) { map.put("package", genConfig.getPackageName()); map.put("mainPath", genConfig.getPackageName()); - } else { + } + else { map.put("package", config.getString("package")); map.put("mainPath", config.getString("mainPath")); } @@ -218,23 +236,23 @@ public class GenUtils { /** * 渲染数据 - * - * @param genConfig 配置信息 - * @param zip 流 (为空,直接返回Map) - * @param formConf 表单信息 + * @param genConfig 配置信息 + * @param zip 流 (为空,直接返回Map) + * @param formConf 表单信息 * @param tableEntity 表基本信息 - * @param map 模板参数 + * @param map 模板参数 * @return map key-filename value-contents * @throws IOException */ - private Map renderData(GenConfig genConfig, ZipOutputStream zip, GenFormConf formConf, TableEntity tableEntity, Map map) throws IOException { - //设置velocity资源加载器 + private Map renderData(GenConfig genConfig, ZipOutputStream zip, GenFormConf formConf, + TableEntity tableEntity, Map map) throws IOException { + // 设置velocity资源加载器 Properties prop = new Properties(); prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); Velocity.init(prop); VelocityContext context = new VelocityContext(map); - //获取模板列表 + // 获取模板列表 List templates = getTemplates(genConfig); Map resultMap = new HashMap<>(8); @@ -242,13 +260,12 @@ public class GenUtils { // 如果是crud if (template.contains(AVUE_CRUD_JS_VM) && formConf != null) { - String fileName = getFileName(template, tableEntity.getCaseClassName() - , map.get("package").toString(), map.get("moduleName").toString()); + String fileName = getFileName(template, tableEntity.getCaseClassName(), map.get("package").toString(), + map.get("moduleName").toString()); String contents = CRUD_PREFIX + formConf.getFormInfo(); if (zip != null) { - zip.putNextEntry(new ZipEntry(Objects - .requireNonNull(fileName))); + zip.putNextEntry(new ZipEntry(Objects.requireNonNull(fileName))); IoUtil.write(zip, StandardCharsets.UTF_8, false, contents); zip.closeEntry(); } @@ -257,19 +274,17 @@ public class GenUtils { continue; } - - //渲染模板 + // 渲染模板 StringWriter sw = new StringWriter(); Template tpl = Velocity.getTemplate(template, CharsetUtil.UTF_8); tpl.merge(context, sw); - //添加到zip - String fileName = getFileName(template, tableEntity.getCaseClassName() - , map.get("package").toString(), map.get("moduleName").toString()); + // 添加到zip + String fileName = getFileName(template, tableEntity.getCaseClassName(), map.get("package").toString(), + map.get("moduleName").toString()); if (zip != null) { - zip.putNextEntry(new ZipEntry(Objects - .requireNonNull(fileName))); + zip.putNextEntry(new ZipEntry(Objects.requireNonNull(fileName))); IoUtil.write(zip, StandardCharsets.UTF_8, false, sw.toString()); IoUtil.close(sw); zip.closeEntry(); @@ -280,12 +295,11 @@ public class GenUtils { return resultMap; } - /** * 列名转换成Java属性名 */ public String columnToJava(String columnName) { - return WordUtils.capitalizeFully(columnName, new char[]{'_'}).replace("_", ""); + return WordUtils.capitalizeFully(columnName, new char[] { '_' }).replace("_", ""); } /** @@ -304,7 +318,8 @@ public class GenUtils { public Configuration getConfig() { try { return new PropertiesConfiguration("generator.properties"); - } catch (ConfigurationException e) { + } + catch (ConfigurationException e) { throw new CheckedException("获取配置文件失败,", e); } } @@ -313,8 +328,8 @@ public class GenUtils { * 获取文件名 */ private String getFileName(String template, String className, String packageName, String moduleName) { - String packagePath = CommonConstants.BACK_END_PROJECT + File.separator + "src" - + File.separator + "main" + File.separator + "java" + File.separator; + String packagePath = CommonConstants.BACK_END_PROJECT + File.separator + "src" + File.separator + "main" + + File.separator + "java" + File.separator; if (StringUtils.isNotBlank(packageName)) { packagePath += packageName.replace(".", File.separator) + File.separator + moduleName + File.separator; @@ -341,8 +356,8 @@ public class GenUtils { } if (template.contains(MAPPER_XML_VM)) { - return CommonConstants.BACK_END_PROJECT + File.separator + "src" + File.separator + "main" - + File.separator + "resources" + File.separator + "mapper" + File.separator + className + "Mapper.xml"; + return CommonConstants.BACK_END_PROJECT + File.separator + "src" + File.separator + "main" + File.separator + + "resources" + File.separator + "mapper" + File.separator + className + "Mapper.xml"; } if (template.contains(MENU_SQL_VM)) { @@ -350,13 +365,14 @@ public class GenUtils { } if (template.contains(AVUE_INDEX_VUE_VM) || template.contains(ELE_INDEX_VUE_VM)) { - return CommonConstants.FRONT_END_PROJECT + File.separator + "src" + File.separator + "views" + - File.separator + moduleName + File.separator + className.toLowerCase() + File.separator + "index.vue"; + return CommonConstants.FRONT_END_PROJECT + File.separator + "src" + File.separator + "views" + + File.separator + moduleName + File.separator + className.toLowerCase() + File.separator + + "index.vue"; } if (template.contains(AVUE_API_JS_VM)) { - return CommonConstants.FRONT_END_PROJECT + File.separator + "src" + File.separator + "api" - + File.separator + className.toLowerCase() + ".js"; + return CommonConstants.FRONT_END_PROJECT + File.separator + "src" + File.separator + "api" + File.separator + + className.toLowerCase() + ".js"; } if (template.contains(AVUE_CRUD_JS_VM)) { @@ -366,10 +382,11 @@ public class GenUtils { if (template.contains(ELE_ADD_UPDATE_VUE_VM)) { return CommonConstants.FRONT_END_PROJECT + File.separator + "src" + File.separator + "views" - + File.separator + moduleName + File.separator + className.toLowerCase() - + File.separator + className.toLowerCase() + "-form.vue"; + + File.separator + moduleName + File.separator + className.toLowerCase() + File.separator + + className.toLowerCase() + "-form.vue"; } return null; } + } diff --git a/pigx-visual/pigx-daemon-elastic-job/src/main/java/com/pig4cloud/pigx/daemon/elastic/PigxDaemonElasticJobApplication.java b/pigx-visual/pigx-daemon-elastic-job/src/main/java/com/pig4cloud/pigx/daemon/elastic/PigxDaemonElasticJobApplication.java index 926f25833..46ed04473 100644 --- a/pigx-visual/pigx-daemon-elastic-job/src/main/java/com/pig4cloud/pigx/daemon/elastic/PigxDaemonElasticJobApplication.java +++ b/pigx-visual/pigx-daemon-elastic-job/src/main/java/com/pig4cloud/pigx/daemon/elastic/PigxDaemonElasticJobApplication.java @@ -26,8 +26,7 @@ import org.springframework.cloud.client.SpringCloudApplication; /** * @author lengleng - * @date 2018/7/24 - * 分布式任务调度模块 + * @date 2018/7/24 分布式任务调度模块 */ @EnablePigxXxlJob @EnablePigxSwagger2 diff --git a/pigx-visual/pigx-daemon-elastic-job/src/main/java/com/pig4cloud/pigx/daemon/elastic/job/DemoJob.java b/pigx-visual/pigx-daemon-elastic-job/src/main/java/com/pig4cloud/pigx/daemon/elastic/job/DemoJob.java index fc3ca49a6..bda44b5d2 100644 --- a/pigx-visual/pigx-daemon-elastic-job/src/main/java/com/pig4cloud/pigx/daemon/elastic/job/DemoJob.java +++ b/pigx-visual/pigx-daemon-elastic-job/src/main/java/com/pig4cloud/pigx/daemon/elastic/job/DemoJob.java @@ -40,4 +40,5 @@ public class DemoJob { XxlJobLogger.log("This is a demo job." + shardingVO); return SUCCESS; } + } \ No newline at end of file diff --git a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/PigxDaemonQuartzApplication.java b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/PigxDaemonQuartzApplication.java index 7c2d03d6e..1e0d67446 100644 --- a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/PigxDaemonQuartzApplication.java +++ b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/PigxDaemonQuartzApplication.java @@ -8,8 +8,7 @@ import org.springframework.cloud.client.SpringCloudApplication; /** * @author frwcloud - * @date 2019/01/23 - * 定时任务模块 + * @date 2019/01/23 定时任务模块 */ @EnablePigxSwagger2 @EnablePigxFeignClients @@ -20,4 +19,5 @@ public class PigxDaemonQuartzApplication { public static void main(String[] args) { SpringApplication.run(PigxDaemonQuartzApplication.class, args); } + } diff --git a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/config/AutowireCapableBeanJobFactory.java b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/config/AutowireCapableBeanJobFactory.java index 5cfbe3ac3..4c98d4840 100644 --- a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/config/AutowireCapableBeanJobFactory.java +++ b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/config/AutowireCapableBeanJobFactory.java @@ -27,6 +27,7 @@ import org.springframework.util.Assert; * @author 郑健楠 */ class AutowireCapableBeanJobFactory extends SpringBeanJobFactory { + private final AutowireCapableBeanFactory beanFactory; AutowireCapableBeanJobFactory(AutowireCapableBeanFactory beanFactory) { @@ -45,4 +46,5 @@ class AutowireCapableBeanJobFactory extends SpringBeanJobFactory { this.beanFactory.initializeBean(jobInstance, beanName); return jobInstance; } + } diff --git a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/config/PigxInitQuartzJob.java b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/config/PigxInitQuartzJob.java index 7c75af8d9..e1771c80b 100644 --- a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/config/PigxInitQuartzJob.java +++ b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/config/PigxInitQuartzJob.java @@ -17,7 +17,6 @@ package com.pig4cloud.pigx.daemon.quartz.config; - import com.pig4cloud.pigx.daemon.quartz.constants.PigxQuartzEnum; import com.pig4cloud.pigx.daemon.quartz.service.SysJobService; import com.pig4cloud.pigx.daemon.quartz.util.TaskUtil; @@ -27,7 +26,6 @@ import org.quartz.Scheduler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; - /** * @author 郑健楠 *

@@ -37,8 +35,11 @@ import org.springframework.context.annotation.Configuration; @Configuration @AllArgsConstructor public class PigxInitQuartzJob { + private final SysJobService sysJobService; + private final TaskUtil taskUtil; + private final Scheduler scheduler; @Bean @@ -46,13 +47,17 @@ public class PigxInitQuartzJob { sysJobService.list().forEach(sysjob -> { if (PigxQuartzEnum.JOB_STATUS_RELEASE.getType().equals(sysjob.getJobStatus())) { taskUtil.removeJob(sysjob, scheduler); - } else if (PigxQuartzEnum.JOB_STATUS_RUNNING.getType().equals(sysjob.getJobStatus())) { + } + else if (PigxQuartzEnum.JOB_STATUS_RUNNING.getType().equals(sysjob.getJobStatus())) { taskUtil.resumeJob(sysjob, scheduler); - } else if (PigxQuartzEnum.JOB_STATUS_NOT_RUNNING.getType().equals(sysjob.getJobStatus())) { + } + else if (PigxQuartzEnum.JOB_STATUS_NOT_RUNNING.getType().equals(sysjob.getJobStatus())) { taskUtil.pauseJob(sysjob, scheduler); - } else { + } + else { taskUtil.removeJob(sysjob, scheduler); } }); } + } diff --git a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/config/PigxQuartzConfig.java b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/config/PigxQuartzConfig.java index c926f1a5b..7e5cb2b27 100644 --- a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/config/PigxQuartzConfig.java +++ b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/config/PigxQuartzConfig.java @@ -42,20 +42,26 @@ import java.util.Properties; * @author 郑健楠 */ @Configuration -@ConditionalOnClass({Scheduler.class, SchedulerFactoryBean.class}) -@EnableConfigurationProperties({QuartzProperties.class}) +@ConditionalOnClass({ Scheduler.class, SchedulerFactoryBean.class }) +@EnableConfigurationProperties({ QuartzProperties.class }) public class PigxQuartzConfig { + private final QuartzProperties properties; + private final List customizers; + private final JobDetail[] jobDetails; + private final Map calendars; + private final Trigger[] triggers; + private final ApplicationContext applicationContext; public PigxQuartzConfig(QuartzProperties properties, - ObjectProvider> customizers, - ObjectProvider jobDetails, ObjectProvider> calendars - , ObjectProvider triggers, ApplicationContext applicationContext) { + ObjectProvider> customizers, ObjectProvider jobDetails, + ObjectProvider> calendars, ObjectProvider triggers, + ApplicationContext applicationContext) { this.properties = properties; this.customizers = customizers.getIfAvailable(); this.jobDetails = jobDetails.getIfAvailable(); @@ -68,8 +74,8 @@ public class PigxQuartzConfig { @ConditionalOnMissingBean public SchedulerFactoryBean quartzScheduler() { SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean(); - schedulerFactoryBean.setJobFactory(new AutowireCapableBeanJobFactory( - this.applicationContext.getAutowireCapableBeanFactory())); + schedulerFactoryBean.setJobFactory( + new AutowireCapableBeanJobFactory(this.applicationContext.getAutowireCapableBeanFactory())); if (!this.properties.getProperties().isEmpty()) { schedulerFactoryBean.setQuartzProperties(this.asProperties(this.properties.getProperties())); } @@ -110,7 +116,6 @@ public class PigxQuartzConfig { /** * 初始化监听器 - * * @return */ @Bean @@ -120,11 +125,11 @@ public class PigxQuartzConfig { /** * 通过SchedulerFactoryBean获取Scheduler的实例 - * * @return */ @Bean public Scheduler scheduler() { return quartzScheduler().getScheduler(); } + } diff --git a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/config/PigxQuartzCustomizerConfig.java b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/config/PigxQuartzCustomizerConfig.java index ffb2a7820..8982d28fe 100644 --- a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/config/PigxQuartzCustomizerConfig.java +++ b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/config/PigxQuartzCustomizerConfig.java @@ -26,8 +26,10 @@ import org.springframework.scheduling.quartz.SchedulerFactoryBean; */ @Configuration public class PigxQuartzCustomizerConfig implements SchedulerFactoryBeanCustomizer { + @Override public void customize(SchedulerFactoryBean schedulerFactoryBean) { schedulerFactoryBean.setWaitForJobsToCompleteOnShutdown(true); } + } diff --git a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/config/PigxQuartzFactory.java b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/config/PigxQuartzFactory.java index afd545bda..333eb6ba0 100644 --- a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/config/PigxQuartzFactory.java +++ b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/config/PigxQuartzFactory.java @@ -39,11 +39,12 @@ public class PigxQuartzFactory implements Job { @Autowired private PigxQuartzInvokeFactory pigxQuartzInvokeFactory; - @Override @SneakyThrows public void execute(JobExecutionContext jobExecutionContext) { - SysJob sysJob = (SysJob) jobExecutionContext.getMergedJobDataMap().get(PigxQuartzEnum.SCHEDULE_JOB_KEY.getType()); + SysJob sysJob = (SysJob) jobExecutionContext.getMergedJobDataMap() + .get(PigxQuartzEnum.SCHEDULE_JOB_KEY.getType()); pigxQuartzInvokeFactory.init(sysJob, jobExecutionContext.getTrigger()); } + } diff --git a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/config/PigxQuartzInvokeFactory.java b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/config/PigxQuartzInvokeFactory.java index a34e5c9c1..bbd761893 100644 --- a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/config/PigxQuartzInvokeFactory.java +++ b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/config/PigxQuartzInvokeFactory.java @@ -40,4 +40,5 @@ public class PigxQuartzInvokeFactory { void init(SysJob sysJob, Trigger trigger) { publisher.publishEvent(new SysJobEvent(sysJob, trigger)); } + } diff --git a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/constants/JobTypeQuartzEnum.java b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/constants/JobTypeQuartzEnum.java index abad19731..5e66bea08 100644 --- a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/constants/JobTypeQuartzEnum.java +++ b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/constants/JobTypeQuartzEnum.java @@ -29,6 +29,7 @@ import lombok.Getter; @Getter @AllArgsConstructor public enum JobTypeQuartzEnum { + /** * 反射java类 */ @@ -53,8 +54,10 @@ public enum JobTypeQuartzEnum { * 类型 */ private final String type; + /** * 描述 */ private final String description; + } diff --git a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/constants/PigxQuartzEnum.java b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/constants/PigxQuartzEnum.java index 77e1c53fb..fa0c61a24 100644 --- a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/constants/PigxQuartzEnum.java +++ b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/constants/PigxQuartzEnum.java @@ -29,6 +29,7 @@ import lombok.Getter; @Getter @AllArgsConstructor public enum PigxQuartzEnum { + /** * 错失执行策略默认 */ @@ -84,8 +85,10 @@ public enum PigxQuartzEnum { * 类型 */ private final String type; + /** * 描述 */ private final String description; + } diff --git a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/controller/SysJobController.java b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/controller/SysJobController.java index f7c778a88..c3e9d46c9 100644 --- a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/controller/SysJobController.java +++ b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/controller/SysJobController.java @@ -38,7 +38,6 @@ import org.springframework.web.bind.annotation.*; import static com.pig4cloud.pigx.daemon.quartz.constants.PigxQuartzEnum.*; - /** * @author frwcloud * @date 2019-01-27 10:04:42 @@ -50,15 +49,18 @@ import static com.pig4cloud.pigx.daemon.quartz.constants.PigxQuartzEnum.*; @RequestMapping("/sys-job") @Api(value = "sys-job", tags = "定时任务") public class SysJobController { + private final SysJobService sysJobService; + private final SysJobLogService sysJobLogService; + private final TaskUtil taskUtil; + private final Scheduler scheduler; /** * 定时任务分页查询 - * - * @param page 分页对象 + * @param page 分页对象 * @param sysJob 定时任务调度表 * @return */ @@ -68,10 +70,8 @@ public class SysJobController { return R.ok(sysJobService.page(page, Wrappers.query(sysJob))); } - /** * 通过id查询定时任务 - * * @param id id * @return R */ @@ -83,7 +83,6 @@ public class SysJobController { /** * 新增定时任务 - * * @param sysJob 定时任务调度表 * @return R */ @@ -99,7 +98,6 @@ public class SysJobController { /** * 修改定时任务 - * * @param sysJob 定时任务调度表 * @return R */ @@ -113,7 +111,8 @@ public class SysJobController { if (JOB_STATUS_NOT_RUNNING.getType().equals(querySysJob.getJobStatus())) { this.taskUtil.addOrUpateJob(sysJob, scheduler); sysJobService.updateById(sysJob); - } else if (JOB_STATUS_RELEASE.getType().equals(querySysJob.getJobStatus())) { + } + else if (JOB_STATUS_RELEASE.getType().equals(querySysJob.getJobStatus())) { sysJobService.updateById(sysJob); } return R.ok(); @@ -121,7 +120,6 @@ public class SysJobController { /** * 通过id删除定时任务 - * * @param id id * @return R */ @@ -134,7 +132,8 @@ public class SysJobController { if (JOB_STATUS_NOT_RUNNING.getType().equals(querySysJob.getJobStatus())) { this.taskUtil.removeJob(querySysJob, scheduler); this.sysJobService.removeById(id); - } else if (JOB_STATUS_RELEASE.getType().equals(querySysJob.getJobStatus())) { + } + else if (JOB_STATUS_RELEASE.getType().equals(querySysJob.getJobStatus())) { this.sysJobService.removeById(id); } return R.ok(); @@ -142,7 +141,6 @@ public class SysJobController { /** * 暂停全部定时任务 - * * @return */ @SysLog("暂停全部定时任务") @@ -151,22 +149,21 @@ public class SysJobController { @ApiOperation(value = "暂停全部定时任务") public R shutdownJobs() { taskUtil.pauseJobs(scheduler); - int count = this.sysJobService.count(new LambdaQueryWrapper() - .eq(SysJob::getJobStatus, JOB_STATUS_RUNNING.getType())); + int count = this.sysJobService + .count(new LambdaQueryWrapper().eq(SysJob::getJobStatus, JOB_STATUS_RUNNING.getType())); if (count <= 0) { return R.ok("无正在运行定时任务"); - } else { - //更新定时任务状态条件,运行状态2更新为暂停状态2 - this.sysJobService.update(SysJob.builder() - .jobStatus(JOB_STATUS_NOT_RUNNING.getType()).build(), new UpdateWrapper() - .lambda().eq(SysJob::getJobStatus, JOB_STATUS_RUNNING.getType())); + } + else { + // 更新定时任务状态条件,运行状态2更新为暂停状态2 + this.sysJobService.update(SysJob.builder().jobStatus(JOB_STATUS_NOT_RUNNING.getType()).build(), + new UpdateWrapper().lambda().eq(SysJob::getJobStatus, JOB_STATUS_RUNNING.getType())); return R.ok("暂停成功"); } } /** * 启动全部定时任务 - * * @return */ @SysLog("启动全部定时任务") @@ -174,17 +171,15 @@ public class SysJobController { @PreAuthorize("@pms.hasPermission('job_sys_job_start_job')") @ApiOperation(value = "启动全部定时任务") public R startJobs() { - //更新定时任务状态条件,暂停状态3更新为运行状态2 - this.sysJobService.update(SysJob.builder().jobStatus(JOB_STATUS_RUNNING - .getType()).build(), new UpdateWrapper().lambda() - .eq(SysJob::getJobStatus, JOB_STATUS_NOT_RUNNING.getType())); + // 更新定时任务状态条件,暂停状态3更新为运行状态2 + this.sysJobService.update(SysJob.builder().jobStatus(JOB_STATUS_RUNNING.getType()).build(), + new UpdateWrapper().lambda().eq(SysJob::getJobStatus, JOB_STATUS_NOT_RUNNING.getType())); taskUtil.startJobs(scheduler); return R.ok(); } /** * 刷新全部定时任务 - * * @return */ @SysLog("刷新全部定时任务") @@ -196,10 +191,12 @@ public class SysJobController { if (JOB_STATUS_RELEASE.getType().equals(sysjob.getJobStatus()) || JOB_STATUS_DEL.getType().equals(sysjob.getJobStatus())) { taskUtil.removeJob(sysjob, scheduler); - } else if (JOB_STATUS_RUNNING.getType().equals(sysjob.getJobStatus()) + } + else if (JOB_STATUS_RUNNING.getType().equals(sysjob.getJobStatus()) || JOB_STATUS_NOT_RUNNING.getType().equals(sysjob.getJobStatus())) { taskUtil.addOrUpateJob(sysjob, scheduler); - } else { + } + else { taskUtil.removeJob(sysjob, scheduler); } }); @@ -208,7 +205,6 @@ public class SysJobController { /** * 启动定时任务 - * * @param jobId * @return */ @@ -218,22 +214,19 @@ public class SysJobController { @ApiOperation(value = "启动定时任务") public R startJob(@PathVariable("id") Integer jobId) { SysJob querySysJob = this.sysJobService.getById(jobId); - if (querySysJob != null && JOB_LOG_STATUS_FAIL.getType() - .equals(querySysJob.getJobStatus())) { + if (querySysJob != null && JOB_LOG_STATUS_FAIL.getType().equals(querySysJob.getJobStatus())) { taskUtil.addOrUpateJob(querySysJob, scheduler); - } else { + } + else { taskUtil.resumeJob(querySysJob, scheduler); } - //更新定时任务状态条件,暂停状态3更新为运行状态2 - this.sysJobService.updateById(SysJob.builder().jobId(jobId) - .jobStatus(JOB_STATUS_RUNNING.getType()).build()); + // 更新定时任务状态条件,暂停状态3更新为运行状态2 + this.sysJobService.updateById(SysJob.builder().jobId(jobId).jobStatus(JOB_STATUS_RUNNING.getType()).build()); return R.ok(); } - /** * 启动定时任务 - * * @param jobId * @return */ @@ -243,14 +236,11 @@ public class SysJobController { @ApiOperation(value = "立刻执行定时任务") public R runJob(@PathVariable("id") Integer jobId) { SysJob querySysJob = this.sysJobService.getById(jobId); - return TaskUtil.runOnce(scheduler, querySysJob)? R.ok(): R.failed(); + return TaskUtil.runOnce(scheduler, querySysJob) ? R.ok() : R.failed(); } - - /** * 暂停定时任务 - * * @return */ @SysLog("暂停定时任务") @@ -259,16 +249,15 @@ public class SysJobController { @ApiOperation(value = "暂停定时任务") public R shutdownJob(@PathVariable("id") Integer id) { SysJob querySysJob = this.sysJobService.getById(id); - //更新定时任务状态条件,运行状态2更新为暂停状态3 - this.sysJobService.updateById(SysJob.builder().jobId(querySysJob.getJobId()) - .jobStatus(JOB_STATUS_NOT_RUNNING.getType()).build()); + // 更新定时任务状态条件,运行状态2更新为暂停状态3 + this.sysJobService.updateById( + SysJob.builder().jobId(querySysJob.getJobId()).jobStatus(JOB_STATUS_NOT_RUNNING.getType()).build()); taskUtil.pauseJob(querySysJob, scheduler); return R.ok(); } /** * 唯一标识查询定时执行日志 - * * @return */ @GetMapping("/job-log") @@ -279,14 +268,14 @@ public class SysJobController { /** * 检验任务名称和任务组联合是否唯一 - * * @return */ @GetMapping("/is-valid-task-name") @ApiOperation(value = "检验任务名称和任务组联合是否唯一") public R isValidTaskName(@RequestParam String jobName, @RequestParam String jobGroup) { return this.sysJobService - .count(Wrappers.query(SysJob.builder().jobName(jobName).jobGroup(jobGroup).build())) > 0 - ? R.failed() : R.ok(); + .count(Wrappers.query(SysJob.builder().jobName(jobName).jobGroup(jobGroup).build())) > 0 ? R.failed() + : R.ok(); } + } diff --git a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/controller/SysJobLogController.java b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/controller/SysJobLogController.java index 0ace3572b..46c55f93d 100644 --- a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/controller/SysJobLogController.java +++ b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/controller/SysJobLogController.java @@ -29,7 +29,6 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; - /** * @author frwcloud *

@@ -40,12 +39,12 @@ import org.springframework.web.bind.annotation.RestController; @RequestMapping("/sys-job-log") @Api(value = "sys-job-log", tags = "定时任务日志") public class SysJobLogController { + private final SysJobLogService sysJobLogService; /** * 分页查询 - * - * @param page 分页对象 + * @param page 分页对象 * @param sysJobLog 定时任务执行日志表 * @return */ @@ -54,4 +53,5 @@ public class SysJobLogController { public R getSysJobLogPage(Page page, SysJobLog sysJobLog) { return R.ok(sysJobLogService.page(page, Wrappers.query(sysJobLog))); } + } diff --git a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/entity/SysJob.java b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/entity/SysJob.java index 26fb702c3..880404e06 100644 --- a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/entity/SysJob.java +++ b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/entity/SysJob.java @@ -39,6 +39,7 @@ import java.time.LocalDateTime; @AllArgsConstructor @ApiModel(value = "定时任务") public class SysJob extends Model { + private static final long serialVersionUID = 1L; /** @@ -46,90 +47,112 @@ public class SysJob extends Model { */ @TableId(value = "job_id", type = IdType.AUTO) private Integer jobId; + /** * 任务名称 */ private String jobName; + /** * 任务组名 */ private String jobGroup; + /** * 组内执行顺利,值越大执行优先级越高,最大值9,最小值1 */ private String jobOrder; + /** * 1、java类;2、spring bean名称;3、rest调用;4、jar调用;9其他 */ private String jobType; + /** * job_type=3时,rest调用地址,仅支持rest get协议,需要增加String返回值,0成功,1失败;job_type=4时,jar路径;其它值为空 */ private String executePath; + /** * job_type=1时,类完整路径;job_type=2时,spring bean名称;其它值为空 */ private String className; + /** * 任务方法 */ private String methodName; + /** * 参数值 */ private String methodParamsValue; + /** * cron执行表达式 */ private String cronExpression; + /** * 错失执行策略(1错失周期立即执行 2错失周期执行一次 3下周期执行) */ private String misfirePolicy; + /** * 1、多租户任务;2、非多租户任务 */ private String jobTenantType; + /** * 状态(0、未发布;1、已发布;2、运行中;3、暂停;4、删除;) */ private String jobStatus; + /** * 状态(0正常 1异常) */ private String jobExecuteStatus; + /** * 创建者 */ private String createBy; + /** * 创建时间 */ private LocalDateTime createTime; + /** * 更新者 */ private String updateBy; + /** * 更新时间 */ private LocalDateTime updateTime; + /** * 首次执行时间 */ private LocalDateTime startTime; + /** * 上次执行时间 */ private LocalDateTime previousTime; + /** * 下次执行时间 */ private LocalDateTime nextTime; + /** * 租户id */ private Integer tenantId; + /** * 备注信息 */ diff --git a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/entity/SysJobLog.java b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/entity/SysJobLog.java index f5173c466..e30146c83 100644 --- a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/entity/SysJobLog.java +++ b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/entity/SysJobLog.java @@ -40,6 +40,7 @@ import java.time.LocalDateTime; @AllArgsConstructor @ApiModel(value = "定时任务日志") public class SysJobLog extends Model { + private static final long serialVersionUID = 1L; /** @@ -47,66 +48,82 @@ public class SysJobLog extends Model { */ @TableId(value = "job_log_id", type = IdType.AUTO) private Integer jobLogId; + /** * 任务id */ private Integer jobId; + /** * 任务名称 */ private String jobName; + /** * 任务组名 */ private String jobGroup; + /** * 组内执行顺利,值越大执行优先级越高,最大值9,最小值1 */ private String jobOrder; + /** * 1、java类;2、spring bean名称;3、rest调用;4、jar调用;9其他 */ private String jobType; + /** * job_type=3时,rest调用地址,仅支持post协议;job_type=4时,jar路径;其它值为空 */ private String executePath; + /** * job_type=1时,类完整路径;job_type=2时,spring bean名称;其它值为空 */ private String className; + /** * 任务方法 */ private String methodName; + /** * 参数值 */ private String methodParamsValue; + /** * cron执行表达式 */ private String cronExpression; + /** * 日志信息 */ private String jobMessage; + /** * 执行状态(0正常 1失败) */ private String jobLogStatus; + /** * 执行时间 */ private String executeTime; + /** * 异常信息 */ private String exceptionInfo; + /** * 创建时间 */ private LocalDateTime createTime; + /** * 租户id */ diff --git a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/event/EventAutoConfiguration.java b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/event/EventAutoConfiguration.java index 7878228f7..cb871c7d8 100644 --- a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/event/EventAutoConfiguration.java +++ b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/event/EventAutoConfiguration.java @@ -37,8 +37,10 @@ import org.springframework.scheduling.annotation.EnableAsync; @Configuration @ConditionalOnWebApplication public class EventAutoConfiguration { + @Autowired private TaskInvokUtil taskInvokUtil; + @Autowired private SysJobLogService sysJobLogService; diff --git a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/event/SysJobEvent.java b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/event/SysJobEvent.java index 33bb60153..2b9b2b61e 100644 --- a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/event/SysJobEvent.java +++ b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/event/SysJobEvent.java @@ -23,8 +23,7 @@ import lombok.Getter; import org.quartz.Trigger; /** - * @author frwcloud - * 定时任务多线程事件 + * @author frwcloud 定时任务多线程事件 */ @Getter @AllArgsConstructor @@ -33,4 +32,5 @@ public class SysJobEvent { private final SysJob sysJob; private final Trigger trigger; + } diff --git a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/event/SysJobListener.java b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/event/SysJobListener.java index 44483b374..245537901 100644 --- a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/event/SysJobListener.java +++ b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/event/SysJobListener.java @@ -26,10 +26,8 @@ import org.springframework.context.event.EventListener; import org.springframework.core.annotation.Order; import org.springframework.scheduling.annotation.Async; - /** - * @author frwcloud - * 异步监听定时任务事件 + * @author frwcloud 异步监听定时任务事件 */ @Slf4j @AllArgsConstructor @@ -45,4 +43,5 @@ public class SysJobListener { Trigger trigger = event.getTrigger(); taskInvokUtil.invokMethod(sysJob, trigger); } + } diff --git a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/event/SysJobLogEvent.java b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/event/SysJobLogEvent.java index dec575d8b..34343b6e1 100644 --- a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/event/SysJobLogEvent.java +++ b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/event/SysJobLogEvent.java @@ -22,11 +22,12 @@ import lombok.AllArgsConstructor; import lombok.Getter; /** - * @author frwcloud - * 定时任务日志多线程事件 + * @author frwcloud 定时任务日志多线程事件 */ @Getter @AllArgsConstructor public class SysJobLogEvent { + private final SysJobLog sysJobLog; + } diff --git a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/event/SysJobLogListener.java b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/event/SysJobLogListener.java index 4a21d0417..b7cd500d6 100644 --- a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/event/SysJobLogListener.java +++ b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/event/SysJobLogListener.java @@ -17,7 +17,6 @@ package com.pig4cloud.pigx.daemon.quartz.event; - import com.pig4cloud.pigx.daemon.quartz.entity.SysJobLog; import com.pig4cloud.pigx.daemon.quartz.service.SysJobLogService; import lombok.AllArgsConstructor; @@ -27,8 +26,7 @@ import org.springframework.core.annotation.Order; import org.springframework.scheduling.annotation.Async; /** - * @author frwcloud - * 异步监听定时任务日志事件 + * @author frwcloud 异步监听定时任务日志事件 */ @Slf4j @AllArgsConstructor @@ -44,4 +42,5 @@ public class SysJobLogListener { sysJobLogService.save(sysJobLog); log.info("执行定时任务日志"); } + } diff --git a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/exception/TaskException.java b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/exception/TaskException.java index f3ce4e729..4359ae568 100644 --- a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/exception/TaskException.java +++ b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/exception/TaskException.java @@ -31,4 +31,5 @@ public class TaskException extends Exception { public TaskException(String msg) { super(msg); } + } diff --git a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/task/RestTaskDemo.java b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/task/RestTaskDemo.java index 0f9839d84..73cf8c743 100644 --- a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/task/RestTaskDemo.java +++ b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/task/RestTaskDemo.java @@ -20,6 +20,7 @@ import java.time.LocalDateTime; @RestController @RequestMapping("/inner-job") public class RestTaskDemo { + /** * 测试REST风格调用定时任务的演示方法 */ @@ -29,4 +30,5 @@ public class RestTaskDemo { log.info("测试于:{},传入参数{}", LocalDateTime.now(), param); return R.ok(); } + } diff --git a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/task/SpringBeanTaskDemo.java b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/task/SpringBeanTaskDemo.java index 0338b5c89..c6dc78f0d 100644 --- a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/task/SpringBeanTaskDemo.java +++ b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/task/SpringBeanTaskDemo.java @@ -30,6 +30,7 @@ import java.time.LocalDateTime; @Slf4j @Component("demo") public class SpringBeanTaskDemo { + /** * 测试Spring Bean的演示方法 */ @@ -38,4 +39,5 @@ public class SpringBeanTaskDemo { log.info("测试于:{},输入参数{}", LocalDateTime.now(), para); return PigxQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType(); } + } diff --git a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/util/ITaskInvok.java b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/util/ITaskInvok.java index 237daa5a3..37f0d0bae 100644 --- a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/util/ITaskInvok.java +++ b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/util/ITaskInvok.java @@ -29,9 +29,9 @@ public interface ITaskInvok { /** * 执行反射方法 - * * @param sysJob 配置类 * @throws TaskException */ void invokMethod(SysJob sysJob) throws TaskException; + } diff --git a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/util/JarTaskInvok.java b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/util/JarTaskInvok.java index f2a694a08..fe85d87f2 100644 --- a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/util/JarTaskInvok.java +++ b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/util/JarTaskInvok.java @@ -17,7 +17,6 @@ package com.pig4cloud.pigx.daemon.quartz.util; - import cn.hutool.core.util.StrUtil; import com.pig4cloud.pigx.daemon.quartz.entity.SysJob; import com.pig4cloud.pigx.daemon.quartz.exception.TaskException; @@ -53,9 +52,11 @@ public class JarTaskInvok implements ITaskInvok { processBuilder.command(commands); try { processBuilder.start(); - } catch (IOException e) { + } + catch (IOException e) { log.error("定时任务jar反射执行异常,执行任务:{}", sysJob.getExecutePath()); throw new TaskException("定时任务jar反射执行异常,执行任务:" + sysJob.getExecutePath()); } } + } diff --git a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/util/JavaClassTaskInvok.java b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/util/JavaClassTaskInvok.java index 0ddc6e26f..a6e2ad75f 100644 --- a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/util/JavaClassTaskInvok.java +++ b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/util/JavaClassTaskInvok.java @@ -35,6 +35,7 @@ import java.lang.reflect.Method; @Component("javaClassTaskInvok") @Slf4j public class JavaClassTaskInvok implements ITaskInvok { + @Override public void invokMethod(SysJob sysJob) throws TaskException { Object obj; @@ -47,32 +48,40 @@ public class JavaClassTaskInvok implements ITaskInvok { obj = clazz.newInstance(); method = clazz.getDeclaredMethod(sysJob.getMethodName(), String.class); returnValue = method.invoke(obj, sysJob.getMethodParamsValue()); - } else { + } + else { clazz = Class.forName(sysJob.getClassName()); obj = clazz.newInstance(); method = clazz.getDeclaredMethod(sysJob.getMethodName()); returnValue = method.invoke(obj); } - if (StrUtil.isEmpty(returnValue.toString()) || PigxQuartzEnum.JOB_LOG_STATUS_FAIL.getType().equals(returnValue.toString())) { + if (StrUtil.isEmpty(returnValue.toString()) + || PigxQuartzEnum.JOB_LOG_STATUS_FAIL.getType().equals(returnValue.toString())) { log.error("定时任务javaClassTaskInvok异常,执行任务:{}", sysJob.getClassName()); throw new TaskException("定时任务javaClassTaskInvok业务执行失败,任务:" + sysJob.getClassName()); } - } catch (ClassNotFoundException e) { + } + catch (ClassNotFoundException e) { log.error("定时任务java反射类没有找到,执行任务:{}", sysJob.getClassName()); throw new TaskException("定时任务java反射类没有找到,执行任务:" + sysJob.getClassName()); - } catch (IllegalAccessException e) { + } + catch (IllegalAccessException e) { log.error("定时任务java反射类异常,执行任务:{}", sysJob.getClassName()); throw new TaskException("定时任务java反射类异常,执行任务:" + sysJob.getClassName()); - } catch (InstantiationException e) { + } + catch (InstantiationException e) { log.error("定时任务java反射类异常,执行任务:{}", sysJob.getClassName()); throw new TaskException("定时任务java反射类异常,执行任务:" + sysJob.getClassName()); - } catch (NoSuchMethodException e) { + } + catch (NoSuchMethodException e) { log.error("定时任务java反射执行方法名异常,执行任务:{}", sysJob.getClassName()); throw new TaskException("定时任务java反射执行方法名异常,执行任务:" + sysJob.getClassName()); - } catch (InvocationTargetException e) { + } + catch (InvocationTargetException e) { log.error("定时任务java反射执行异常,执行任务:{}", sysJob.getClassName()); throw new TaskException("定时任务java反射执行异常,执行任务:" + sysJob.getClassName()); } } + } diff --git a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/util/RestTaskInvok.java b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/util/RestTaskInvok.java index 1afacf2eb..e062b71a0 100644 --- a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/util/RestTaskInvok.java +++ b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/util/RestTaskInvok.java @@ -40,13 +40,15 @@ public class RestTaskInvok implements ITaskInvok { public void invokMethod(SysJob sysJob) throws TaskException { try { HttpRequest request = HttpUtil.createGet(sysJob.getExecutePath()); - if(sysJob.getTenantId() != null){ + if (sysJob.getTenantId() != null) { request.header(CommonConstants.TENANT_ID, sysJob.getTenantId().toString()); } request.execute(); - } catch (Exception e) { + } + catch (Exception e) { log.error("定时任务restTaskInvok异常,执行任务:{}", sysJob.getExecutePath()); throw new TaskException("定时任务restTaskInvok业务执行失败,任务:" + sysJob.getExecutePath()); } } + } diff --git a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/util/SpringBeanTaskInvok.java b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/util/SpringBeanTaskInvok.java index 7712a2bd3..0ec04a490 100644 --- a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/util/SpringBeanTaskInvok.java +++ b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/util/SpringBeanTaskInvok.java @@ -29,7 +29,6 @@ import org.springframework.util.ReflectionUtils; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; - /** * 定时任务spring bean反射实现 * @@ -38,37 +37,43 @@ import java.lang.reflect.Method; @Component("springBeanTaskInvok") @Slf4j public class SpringBeanTaskInvok implements ITaskInvok { + @Override public void invokMethod(SysJob sysJob) throws TaskException { Object target; Method method; Object returnValue; - //通过Spring上下文去找 也有可能找不到 + // 通过Spring上下文去找 也有可能找不到 target = SpringContextHolder.getBean(sysJob.getClassName()); try { if (StrUtil.isNotEmpty(sysJob.getMethodParamsValue())) { method = target.getClass().getDeclaredMethod(sysJob.getMethodName(), String.class); ReflectionUtils.makeAccessible(method); returnValue = method.invoke(target, sysJob.getMethodParamsValue()); - } else { + } + else { method = target.getClass().getDeclaredMethod(sysJob.getMethodName()); ReflectionUtils.makeAccessible(method); returnValue = method.invoke(target); } - if (StrUtil.isEmpty(returnValue.toString()) || PigxQuartzEnum.JOB_LOG_STATUS_FAIL.getType() - .equals(returnValue.toString())) { + if (StrUtil.isEmpty(returnValue.toString()) + || PigxQuartzEnum.JOB_LOG_STATUS_FAIL.getType().equals(returnValue.toString())) { log.error("定时任务springBeanTaskInvok异常,执行任务:{}", sysJob.getClassName()); throw new TaskException("定时任务springBeanTaskInvok业务执行失败,任务:" + sysJob.getClassName()); } - } catch (NoSuchMethodException e) { + } + catch (NoSuchMethodException e) { log.error("定时任务spring bean反射异常方法未找到,执行任务:{}", sysJob.getClassName()); throw new TaskException("定时任务spring bean反射异常方法未找到,执行任务:" + sysJob.getClassName()); - } catch (IllegalAccessException e) { + } + catch (IllegalAccessException e) { log.error("定时任务spring bean反射异常,执行任务:{}", sysJob.getClassName()); throw new TaskException("定时任务spring bean反射异常,执行任务:" + sysJob.getClassName()); - } catch (InvocationTargetException e) { + } + catch (InvocationTargetException e) { log.error("定时任务spring bean反射执行异常,执行任务:{}", sysJob.getClassName()); throw new TaskException("定时任务spring bean反射执行异常,执行任务:" + sysJob.getClassName()); } } + } diff --git a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/util/TaskInvokFactory.java b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/util/TaskInvokFactory.java index 825dca5c5..5b2575f95 100644 --- a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/util/TaskInvokFactory.java +++ b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/util/TaskInvokFactory.java @@ -9,8 +9,7 @@ import lombok.extern.slf4j.Slf4j; /** * @author Hccake * @version 1.0 - * @date 2019/8/8 15:40 - * TaskInvok工厂类 + * @date 2019/8/8 15:40 TaskInvok工厂类 */ @Slf4j public class TaskInvokFactory { @@ -30,17 +29,22 @@ public class TaskInvokFactory { ITaskInvok iTaskInvok = null; if (JobTypeQuartzEnum.JAVA.getType().equals(jobType)) { iTaskInvok = SpringContextHolder.getBean("javaClassTaskInvok"); - } else if (JobTypeQuartzEnum.SPRING_BEAN.getType().equals(jobType)) { + } + else if (JobTypeQuartzEnum.SPRING_BEAN.getType().equals(jobType)) { iTaskInvok = SpringContextHolder.getBean("springBeanTaskInvok"); - } else if (JobTypeQuartzEnum.REST.getType().equals(jobType)) { + } + else if (JobTypeQuartzEnum.REST.getType().equals(jobType)) { iTaskInvok = SpringContextHolder.getBean("restTaskInvok"); - } else if (JobTypeQuartzEnum.JAR.getType().equals(jobType)) { + } + else if (JobTypeQuartzEnum.JAR.getType().equals(jobType)) { iTaskInvok = SpringContextHolder.getBean("jarTaskInvok"); - } else if (StrUtil.isBlank(jobType)) { + } + else if (StrUtil.isBlank(jobType)) { log.info("定时任务类型无对应反射方式,反射类型:{}", jobType); throw new TaskException(""); } return iTaskInvok; } + } diff --git a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/util/TaskInvokUtil.java b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/util/TaskInvokUtil.java index cdf444e41..1655b09c3 100644 --- a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/util/TaskInvokUtil.java +++ b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/util/TaskInvokUtil.java @@ -17,7 +17,6 @@ package com.pig4cloud.pigx.daemon.quartz.util; - import cn.hutool.core.util.StrUtil; import com.pig4cloud.pigx.common.data.tenant.TenantBroker; import com.pig4cloud.pigx.daemon.quartz.constants.PigxQuartzEnum; @@ -46,6 +45,7 @@ import java.util.Date; @Aspect @RequiredArgsConstructor public class TaskInvokUtil { + private final ApplicationEventPublisher publisher; @Autowired @@ -54,16 +54,16 @@ public class TaskInvokUtil { @SneakyThrows public void invokMethod(SysJob sysJob, Trigger trigger) { - //执行开始时间 + // 执行开始时间 long startTime; - //执行结束时间 + // 执行结束时间 long endTime; - //获取执行开始时间 + // 获取执行开始时间 startTime = System.currentTimeMillis(); - //更新定时任务表内的状态、执行时间、上次执行时间、下次执行时间等信息 + // 更新定时任务表内的状态、执行时间、上次执行时间、下次执行时间等信息 SysJob updateSysjob = new SysJob(); updateSysjob.setJobId(sysJob.getJobId()); - //日志 + // 日志 SysJobLog sysJobLog = new SysJobLog(); sysJobLog.setJobId(sysJob.getJobId()); sysJobLog.setJobName(sysJob.getJobName()); @@ -80,29 +80,36 @@ public class TaskInvokUtil { // 执行任务 ITaskInvok iTaskInvok = TaskInvokFactory.getInvoker(sysJob.getJobType()); // 确保租户上下文有值,使得当前线程中的多租户特性生效。 - TenantBroker.runAs(sysJob.getTenantId(),tenantId -> iTaskInvok.invokMethod(sysJob)); ; + TenantBroker.runAs(sysJob.getTenantId(), tenantId -> iTaskInvok.invokMethod(sysJob)); + ; - //记录成功状态 + // 记录成功状态 sysJobLog.setJobMessage(PigxQuartzEnum.JOB_LOG_STATUS_SUCCESS.getDescription()); sysJobLog.setJobLogStatus(PigxQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType()); - //任务表信息更新 + // 任务表信息更新 updateSysjob.setJobExecuteStatus(PigxQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType()); - } catch (Throwable e) { - log.error("定时任务执行失败,任务名称:{};任务组名:{},cron执行表达式:{},执行时间:{}", sysJob.getJobName(), sysJob.getJobGroup(), sysJob.getCronExpression(), new Date()); - //记录失败状态 + } + catch (Throwable e) { + log.error("定时任务执行失败,任务名称:{};任务组名:{},cron执行表达式:{},执行时间:{}", sysJob.getJobName(), sysJob.getJobGroup(), + sysJob.getCronExpression(), new Date()); + // 记录失败状态 sysJobLog.setJobMessage(PigxQuartzEnum.JOB_LOG_STATUS_FAIL.getDescription()); sysJobLog.setJobLogStatus(PigxQuartzEnum.JOB_LOG_STATUS_FAIL.getType()); sysJobLog.setExceptionInfo(StrUtil.sub(e.getMessage(), 0, 2000)); - //任务表信息更新 + // 任务表信息更新 updateSysjob.setJobExecuteStatus(PigxQuartzEnum.JOB_LOG_STATUS_FAIL.getType()); - } finally { - //记录执行时间 立刻执行使用的是simpleTeigger - if(trigger instanceof CronTrigger){ - updateSysjob.setStartTime(trigger.getStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime()); - updateSysjob.setPreviousTime(trigger.getPreviousFireTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime()); - updateSysjob.setNextTime(trigger.getNextFireTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime()); + } + finally { + // 记录执行时间 立刻执行使用的是simpleTeigger + if (trigger instanceof CronTrigger) { + updateSysjob.setStartTime( + trigger.getStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime()); + updateSysjob.setPreviousTime( + trigger.getPreviousFireTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime()); + updateSysjob.setNextTime( + trigger.getNextFireTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime()); } - //记录执行时长 + // 记录执行时长 endTime = System.currentTimeMillis(); sysJobLog.setExecuteTime(String.valueOf(endTime - startTime)); @@ -110,4 +117,5 @@ public class TaskInvokUtil { sysJobService.updateById(updateSysjob); } } + } diff --git a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/util/TaskUtil.java b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/util/TaskUtil.java index 256ccd324..6ec4809c2 100644 --- a/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/util/TaskUtil.java +++ b/pigx-visual/pigx-daemon-quartz/src/main/java/com/pig4cloud/pigx/daemon/quartz/util/TaskUtil.java @@ -36,7 +36,6 @@ public class TaskUtil { /** * 获取定时任务的唯一key - * * @param sysjob * @return */ @@ -46,7 +45,6 @@ public class TaskUtil { /** * 获取定时任务触发器cron的唯一key - * * @param sysjob * @return */ @@ -56,7 +54,6 @@ public class TaskUtil { /** * 添加或更新定时任务 - * * @param sysjob * @param scheduler */ @@ -64,53 +61,57 @@ public class TaskUtil { CronTrigger trigger = null; try { JobKey jobKey = getJobKey(sysjob); - //获得触发器 + // 获得触发器 TriggerKey triggerKey = getTriggerKey(sysjob); trigger = (CronTrigger) scheduler.getTrigger(triggerKey); - //判断触发器是否存在(如果存在说明之前运行过但是在当前被禁用了,如果不存在说明一次都没运行过) + // 判断触发器是否存在(如果存在说明之前运行过但是在当前被禁用了,如果不存在说明一次都没运行过) if (trigger == null) { - //新建一个工作任务 指定任务类型为串接进行的 + // 新建一个工作任务 指定任务类型为串接进行的 JobDetail jobDetail = JobBuilder.newJob(PigxQuartzFactory.class).withIdentity(jobKey).build(); - //将任务信息添加到任务信息中 + // 将任务信息添加到任务信息中 jobDetail.getJobDataMap().put(SCHEDULE_JOB_KEY.getType(), sysjob); - //将cron表达式进行转换 + // 将cron表达式进行转换 CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(sysjob.getCronExpression()); cronScheduleBuilder = this.handleCronScheduleMisfirePolicy(sysjob, cronScheduleBuilder); - //创建触发器并将cron表达式对象给塞入 - trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey).withSchedule(cronScheduleBuilder).build(); - //在调度器中将触发器和任务进行组合 + // 创建触发器并将cron表达式对象给塞入 + trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey).withSchedule(cronScheduleBuilder) + .build(); + // 在调度器中将触发器和任务进行组合 scheduler.scheduleJob(jobDetail, trigger); - } else { + } + else { CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(sysjob.getCronExpression()); cronScheduleBuilder = this.handleCronScheduleMisfirePolicy(sysjob, cronScheduleBuilder); - //按照新的规则进行 - trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(cronScheduleBuilder).build(); - //将任务信息更新到任务信息中 + // 按照新的规则进行 + trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(cronScheduleBuilder) + .build(); + // 将任务信息更新到任务信息中 trigger.getJobDataMap().put(SCHEDULE_JOB_KEY.getType(), sysjob); - //重启 + // 重启 scheduler.rescheduleJob(triggerKey, trigger); } // 如任务状态为暂停 if (sysjob.getJobStatus().equals(JOB_STATUS_NOT_RUNNING.getType())) { this.pauseJob(sysjob, scheduler); } - } catch (SchedulerException e) { + } + catch (SchedulerException e) { log.error("添加或更新定时任务,失败信息:{}", e.getMessage()); } } - /** * 立即执行一次任务 */ public static boolean runOnce(Scheduler scheduler, SysJob sysJob) { try { - //参数 + // 参数 JobDataMap dataMap = new JobDataMap(); dataMap.put(SCHEDULE_JOB_KEY.getType(), sysJob); scheduler.triggerJob(getJobKey(sysJob), dataMap); - } catch (SchedulerException e) { + } + catch (SchedulerException e) { log.error("立刻执行定时任务,失败信息:{}", e.getMessage()); return false; } @@ -118,11 +119,8 @@ public class TaskUtil { return true; } - - /** * 暂停定时任务 - * * @param sysjob * @param scheduler */ @@ -131,7 +129,8 @@ public class TaskUtil { if (scheduler != null) { scheduler.pauseJob(getJobKey(sysjob)); } - } catch (SchedulerException e) { + } + catch (SchedulerException e) { log.error("暂停任务失败,失败信息:{}", e.getMessage()); } @@ -139,7 +138,6 @@ public class TaskUtil { /** * 恢复定时任务 - * * @param sysjob * @param scheduler */ @@ -148,7 +146,8 @@ public class TaskUtil { if (scheduler != null) { scheduler.resumeJob(getJobKey(sysjob)); } - } catch (SchedulerException e) { + } + catch (SchedulerException e) { log.error("恢复任务失败,失败信息:{}", e.getMessage()); } @@ -156,7 +155,6 @@ public class TaskUtil { /** * 移除定时任务 - * * @param sysjob * @param scheduler */ @@ -165,19 +163,19 @@ public class TaskUtil { if (scheduler != null) { // 停止触发器 scheduler.pauseTrigger(getTriggerKey(sysjob)); - //移除触发器 + // 移除触发器 scheduler.unscheduleJob(getTriggerKey(sysjob)); - //删除任务 + // 删除任务 scheduler.deleteJob(getJobKey(sysjob)); } - } catch (Exception e) { + } + catch (Exception e) { log.error("移除定时任务失败,失败信息:{}", e.getMessage()); } } /** * 启动所有运行定时任务 - * * @param scheduler */ public void startJobs(Scheduler scheduler) { @@ -185,14 +183,14 @@ public class TaskUtil { if (scheduler != null) { scheduler.resumeAll(); } - } catch (SchedulerException e) { + } + catch (SchedulerException e) { log.error("启动所有运行定时任务失败,失败信息:{}", e.getMessage()); } } /** * 停止所有运行定时任务 - * * @param scheduler */ public void pauseJobs(Scheduler scheduler) { @@ -200,39 +198,44 @@ public class TaskUtil { if (scheduler != null) { scheduler.pauseAll(); } - } catch (Exception e) { + } + catch (Exception e) { log.error("暂停所有运行定时任务失败,失败信息:{}", e.getMessage()); } } /** * 获取错失执行策略方法 - * * @param sysJob * @param cronScheduleBuilder * @return */ - private CronScheduleBuilder handleCronScheduleMisfirePolicy(SysJob sysJob, CronScheduleBuilder cronScheduleBuilder) { + private CronScheduleBuilder handleCronScheduleMisfirePolicy(SysJob sysJob, + CronScheduleBuilder cronScheduleBuilder) { if (MISFIRE_DEFAULT.getType().equals(sysJob.getMisfirePolicy())) { return cronScheduleBuilder; - } else if (MISFIRE_IGNORE_MISFIRES.getType().equals(sysJob.getMisfirePolicy())) { + } + else if (MISFIRE_IGNORE_MISFIRES.getType().equals(sysJob.getMisfirePolicy())) { return cronScheduleBuilder.withMisfireHandlingInstructionIgnoreMisfires(); - } else if (MISFIRE_FIRE_AND_PROCEED.getType().equals(sysJob.getMisfirePolicy())) { + } + else if (MISFIRE_FIRE_AND_PROCEED.getType().equals(sysJob.getMisfirePolicy())) { return cronScheduleBuilder.withMisfireHandlingInstructionFireAndProceed(); - } else if (MISFIRE_DO_NOTHING.getType().equals(sysJob.getMisfirePolicy())) { + } + else if (MISFIRE_DO_NOTHING.getType().equals(sysJob.getMisfirePolicy())) { return cronScheduleBuilder.withMisfireHandlingInstructionDoNothing(); - } else { + } + else { return cronScheduleBuilder; } } /** * 判断cron表达式是否正确 - * * @param cronExpression * @return */ public boolean isValidCron(String cronExpression) { return CronExpression.isValidExpression(cronExpression); } + } diff --git a/pigx-visual/pigx-monitor/src/main/java/com/pig4cloud/pigx/monitor/PigxMonitorApplication.java b/pigx-visual/pigx-monitor/src/main/java/com/pig4cloud/pigx/monitor/PigxMonitorApplication.java index b12fdb72f..6db12e333 100644 --- a/pigx-visual/pigx-monitor/src/main/java/com/pig4cloud/pigx/monitor/PigxMonitorApplication.java +++ b/pigx-visual/pigx-monitor/src/main/java/com/pig4cloud/pigx/monitor/PigxMonitorApplication.java @@ -19,15 +19,13 @@ package com.pig4cloud.pigx.monitor; - import de.codecentric.boot.admin.server.config.EnableAdminServer; import org.springframework.boot.SpringApplication; import org.springframework.cloud.client.SpringCloudApplication; /** * @author lengleng - * @date 2019年11月4日 - * 监控中心 + * @date 2019年11月4日 监控中心 */ @EnableAdminServer @SpringCloudApplication @@ -36,4 +34,5 @@ public class PigxMonitorApplication { public static void main(String[] args) { SpringApplication.run(PigxMonitorApplication.class, args); } + } diff --git a/pigx-visual/pigx-monitor/src/main/java/com/pig4cloud/pigx/monitor/config/JacksonConfig.java b/pigx-visual/pigx-monitor/src/main/java/com/pig4cloud/pigx/monitor/config/JacksonConfig.java index ed5200913..877876679 100644 --- a/pigx-visual/pigx-monitor/src/main/java/com/pig4cloud/pigx/monitor/config/JacksonConfig.java +++ b/pigx-visual/pigx-monitor/src/main/java/com/pig4cloud/pigx/monitor/config/JacksonConfig.java @@ -29,7 +29,6 @@ public class JacksonConfig { /** * 覆盖core 模块提供的序列方式,增加springboot admin 序列化 - * * @param adminJacksonModule spring boot admin 提供的序列化 * @return Jackson customizer */ @@ -42,4 +41,5 @@ public class JacksonConfig { builder.modules(new PigxJavaTimeModule(), adminJacksonModule); }; } + } diff --git a/pigx-visual/pigx-monitor/src/main/java/com/pig4cloud/pigx/monitor/config/WebSecurityConfigurer.java b/pigx-visual/pigx-monitor/src/main/java/com/pig4cloud/pigx/monitor/config/WebSecurityConfigurer.java index b255cd9e7..fbccb93ff 100755 --- a/pigx-visual/pigx-monitor/src/main/java/com/pig4cloud/pigx/monitor/config/WebSecurityConfigurer.java +++ b/pigx-visual/pigx-monitor/src/main/java/com/pig4cloud/pigx/monitor/config/WebSecurityConfigurer.java @@ -32,6 +32,7 @@ import org.springframework.security.web.authentication.SavedRequestAwareAuthenti */ @Configuration public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter { + private final String adminContextPath; public WebSecurityConfigurer(AdminServerProperties adminServerProperties) { @@ -65,4 +66,5 @@ public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter { .disable(); // @formatter:on } + } diff --git a/pigx-visual/pigx-monitor/src/main/java/com/pig4cloud/pigx/monitor/controller/RedisController.java b/pigx-visual/pigx-monitor/src/main/java/com/pig4cloud/pigx/monitor/controller/RedisController.java index 497dfd3d7..5fe9e9bc5 100644 --- a/pigx-visual/pigx-monitor/src/main/java/com/pig4cloud/pigx/monitor/controller/RedisController.java +++ b/pigx-visual/pigx-monitor/src/main/java/com/pig4cloud/pigx/monitor/controller/RedisController.java @@ -17,15 +17,16 @@ import org.springframework.web.bind.annotation.RestController; @AllArgsConstructor @RequestMapping("/redis") public class RedisController { + private final RedisService redisService; /** * 查询redis信息 - * * @return */ @GetMapping("/info") public R memory() { return R.ok(redisService.getInfo()); } + } diff --git a/pigx-visual/pigx-monitor/src/main/java/com/pig4cloud/pigx/monitor/service/RedisService.java b/pigx-visual/pigx-monitor/src/main/java/com/pig4cloud/pigx/monitor/service/RedisService.java index b8f56a134..68fe259da 100644 --- a/pigx-visual/pigx-monitor/src/main/java/com/pig4cloud/pigx/monitor/service/RedisService.java +++ b/pigx-visual/pigx-monitor/src/main/java/com/pig4cloud/pigx/monitor/service/RedisService.java @@ -9,10 +9,11 @@ import java.util.Map; * redis 监控 */ public interface RedisService { + /** * 获取内存信息 - * * @return */ Map getInfo(); + } diff --git a/pigx-visual/pigx-monitor/src/main/java/com/pig4cloud/pigx/monitor/service/impl/RedisServiceImpl.java b/pigx-visual/pigx-monitor/src/main/java/com/pig4cloud/pigx/monitor/service/impl/RedisServiceImpl.java index 1d3e3d292..22df8e8db 100644 --- a/pigx-visual/pigx-monitor/src/main/java/com/pig4cloud/pigx/monitor/service/impl/RedisServiceImpl.java +++ b/pigx-visual/pigx-monitor/src/main/java/com/pig4cloud/pigx/monitor/service/impl/RedisServiceImpl.java @@ -20,17 +20,18 @@ import java.util.*; @Service @AllArgsConstructor public class RedisServiceImpl implements RedisService { + private RedisTemplate redisTemplate; /** * 获取内存信息 - * * @return */ @Override public Map getInfo() { Properties info = (Properties) redisTemplate.execute((RedisCallback) redisConnection -> redisConnection.info()); - Properties commandStats = (Properties) redisTemplate.execute((RedisCallback) redisConnection -> redisConnection.info("commandstats")); + Properties commandStats = (Properties) redisTemplate + .execute((RedisCallback) redisConnection -> redisConnection.info("commandstats")); Object dbSize = redisTemplate.execute((RedisCallback) redisConnection -> redisConnection.dbSize()); Map result = new HashMap<>(4); @@ -49,4 +50,5 @@ public class RedisServiceImpl implements RedisService { result.put("commandStats", pieList); return result; } + } diff --git a/pigx-visual/pigx-monitor/src/main/java/com/pig4cloud/pigx/monitor/support/RedisEventStore.java b/pigx-visual/pigx-monitor/src/main/java/com/pig4cloud/pigx/monitor/support/RedisEventStore.java index 6142feade..7549b40c1 100644 --- a/pigx-visual/pigx-monitor/src/main/java/com/pig4cloud/pigx/monitor/support/RedisEventStore.java +++ b/pigx-visual/pigx-monitor/src/main/java/com/pig4cloud/pigx/monitor/support/RedisEventStore.java @@ -35,13 +35,13 @@ import java.util.List; * @author lengleng * @date 2018/11/12 *

- * redis store event - * default 100 + * redis store event default 100 */ @Slf4j @Configuration @AllArgsConstructor public class RedisEventStore extends InMemoryEventStore { + private final RedisTemplate redisTemplate; @Override @@ -55,4 +55,5 @@ public class RedisEventStore extends InMemoryEventStore { }); return super.append(events); } + } diff --git a/pigx-visual/pigx-monitor/src/main/java/com/pig4cloud/pigx/monitor/support/StatusChangeNotifier.java b/pigx-visual/pigx-monitor/src/main/java/com/pig4cloud/pigx/monitor/support/StatusChangeNotifier.java index 2d3596e62..f1a7c1f9c 100644 --- a/pigx-visual/pigx-monitor/src/main/java/com/pig4cloud/pigx/monitor/support/StatusChangeNotifier.java +++ b/pigx-visual/pigx-monitor/src/main/java/com/pig4cloud/pigx/monitor/support/StatusChangeNotifier.java @@ -18,6 +18,7 @@ import reactor.core.publisher.Mono; @Slf4j @Component public class StatusChangeNotifier extends AbstractEventNotifier { + protected StatusChangeNotifier(InstanceRepository repository) { super(repository); } @@ -28,10 +29,12 @@ public class StatusChangeNotifier extends AbstractEventNotifier { if (event instanceof InstanceStatusChangedEvent) { log.info("Instance {} ({}) is {}", instance.getRegistration().getName(), event.getInstance(), ((InstanceStatusChangedEvent) event).getStatusInfo().getStatus()); - } else { + } + else { log.info("Instance {} ({}) {}", instance.getRegistration().getName(), event.getInstance(), event.getType()); } }); } + } \ No newline at end of file diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/PigxMpPlatformApplication.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/PigxMpPlatformApplication.java index f43c3df59..91e78c709 100755 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/PigxMpPlatformApplication.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/PigxMpPlatformApplication.java @@ -25,8 +25,7 @@ import org.springframework.cloud.client.SpringCloudApplication; /** * @author lengleng - * @date 2019/03/25 - * 微信公众号管理模块 + * @date 2019/03/25 微信公众号管理模块 */ @EnablePigxSwagger2 @EnablePigxFeignClients @@ -37,4 +36,5 @@ public class PigxMpPlatformApplication { public static void main(String[] args) { SpringApplication.run(PigxMpPlatformApplication.class, args); } + } diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/builder/AbstractBuilder.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/builder/AbstractBuilder.java index 7a94beb73..0ff80ed57 100755 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/builder/AbstractBuilder.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/builder/AbstractBuilder.java @@ -8,14 +8,14 @@ import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage; * @author Binary Wang(https://github.com/binarywang) */ public abstract class AbstractBuilder { + /** * 构建返回微信消息报文 - * * @param content * @param wxMessage * @param service * @return */ - public abstract WxMpXmlOutMessage build(String content, - WxMpXmlMessage wxMessage, WxMpService service); + public abstract WxMpXmlOutMessage build(String content, WxMpXmlMessage wxMessage, WxMpService service); + } diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/builder/ImageBuilder.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/builder/ImageBuilder.java index 07d8686f6..9ffca3dc9 100755 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/builder/ImageBuilder.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/builder/ImageBuilder.java @@ -10,15 +10,13 @@ import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage; */ public class ImageBuilder extends AbstractBuilder { - @Override - public WxMpXmlOutMessage build(String content, WxMpXmlMessage wxMessage, - WxMpService service) { + @Override + public WxMpXmlOutMessage build(String content, WxMpXmlMessage wxMessage, WxMpService service) { - WxMpXmlOutImageMessage m = WxMpXmlOutMessage.IMAGE().mediaId(content) - .fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()) - .build(); + WxMpXmlOutImageMessage m = WxMpXmlOutMessage.IMAGE().mediaId(content).fromUser(wxMessage.getToUser()) + .toUser(wxMessage.getFromUser()).build(); - return m; - } + return m; + } } diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/builder/TextBuilder.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/builder/TextBuilder.java index a212ddc27..66d3943e1 100755 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/builder/TextBuilder.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/builder/TextBuilder.java @@ -11,11 +11,9 @@ import me.chanjar.weixin.mp.bean.message.WxMpXmlOutTextMessage; public class TextBuilder extends AbstractBuilder { @Override - public WxMpXmlOutMessage build(String content, WxMpXmlMessage wxMessage, - WxMpService service) { - WxMpXmlOutTextMessage m = WxMpXmlOutMessage.TEXT().content(content) - .fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()) - .build(); + public WxMpXmlOutMessage build(String content, WxMpXmlMessage wxMessage, WxMpService service) { + WxMpXmlOutTextMessage m = WxMpXmlOutMessage.TEXT().content(content).fromUser(wxMessage.getToUser()) + .toUser(wxMessage.getFromUser()).build(); return m; } diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/config/WxMpContextHolder.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/config/WxMpContextHolder.java index 9f73e4a01..eb7a481db 100644 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/config/WxMpContextHolder.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/config/WxMpContextHolder.java @@ -22,18 +22,15 @@ import lombok.experimental.UtilityClass; /** * @author lengleng - * @date 2019/03/27 - * 微信上下文工具类 + * @date 2019/03/27 微信上下文工具类 */ @UtilityClass public class WxMpContextHolder { private final ThreadLocal THREAD_LOCAL_APPID = new TransmittableThreadLocal<>(); - /** * TTL 设置appId - * * @param appId */ public void setAppId(String appId) { @@ -42,7 +39,6 @@ public class WxMpContextHolder { /** * 获取TTL中的appId - * * @return */ public String getAppId() { @@ -52,4 +48,5 @@ public class WxMpContextHolder { public void clear() { THREAD_LOCAL_APPID.remove(); } + } diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/config/WxMpInRedisConfigStorage.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/config/WxMpInRedisConfigStorage.java index 728404a67..0b7b883af 100644 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/config/WxMpInRedisConfigStorage.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/config/WxMpInRedisConfigStorage.java @@ -50,7 +50,6 @@ public class WxMpInRedisConfigStorage extends WxMpDefaultConfigImpl { /** * 每个公众号生成独有的存储key - * * @param appId */ @Override @@ -86,13 +85,11 @@ public class WxMpInRedisConfigStorage extends WxMpDefaultConfigImpl { return redisTemplate.opsForValue().get(this.jsapiTicketKey); } - @Override public String getCardApiTicket() { return redisTemplate.opsForValue().get(cardapiTicketKey); } - @Override public String getTicket(TicketType type) { return redisTemplate.opsForValue().get(getTicketRedisKey(type)); diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/config/WxMpInitConfigRunner.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/config/WxMpInitConfigRunner.java index 614d0c5f9..ee27396fe 100755 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/config/WxMpInitConfigRunner.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/config/WxMpInitConfigRunner.java @@ -39,6 +39,7 @@ import static me.chanjar.weixin.common.api.WxConsts.*; @Configuration @RequiredArgsConstructor public class WxMpInitConfigRunner { + /** * 保存 appid-router 的对应关系 */ @@ -55,25 +56,37 @@ public class WxMpInitConfigRunner { private static Map tenants = Maps.newHashMap(); private final RemoteTenantService tenantService; + private final WxAccountService accountService; + private final LogHandler logHandler; + private final NullHandler nullHandler; + private final KfSessionHandler kfSessionHandler; + private final StoreCheckNotifyHandler storeCheckNotifyHandler; + private final LocationHandler locationHandler; + private final MenuHandler menuHandler; + private final MsgHandler msgHandler; + private final UnsubscribeHandler unsubscribeHandler; + private final SubscribeHandler subscribeHandler; + private final ScanHandler scanHandler; + private final RedisTemplate redisTemplate; @PostConstruct public void initServices() { // 获取全部租户 遍历所有租户对应的公众号列表 List accountList = new ArrayList<>(); - tenantService.list(SecurityConstants.FROM_IN).getData() - .forEach( tenant -> TenantBroker.runAs(tenant.getId(), (id) -> accountList.addAll(accountService.list()))); + tenantService.list(SecurityConstants.FROM_IN).getData().forEach( + tenant -> TenantBroker.runAs(tenant.getId(), (id) -> accountList.addAll(accountService.list()))); mpServices = accountList.stream().map(a -> { WxMpInRedisConfigStorage configStorage = new WxMpInRedisConfigStorage(redisTemplate); @@ -98,51 +111,41 @@ public class WxMpInitConfigRunner { // 接收客服会话管理事件 newRouter.rule().async(false).msgType(XmlMsgType.EVENT) - .event(WxMpEventConstants.CustomerService.KF_CREATE_SESSION) - .handler(this.kfSessionHandler).end(); + .event(WxMpEventConstants.CustomerService.KF_CREATE_SESSION).handler(this.kfSessionHandler).end(); newRouter.rule().async(false).msgType(XmlMsgType.EVENT) - .event(WxMpEventConstants.CustomerService.KF_CLOSE_SESSION) - .handler(this.kfSessionHandler) - .end(); + .event(WxMpEventConstants.CustomerService.KF_CLOSE_SESSION).handler(this.kfSessionHandler).end(); newRouter.rule().async(false).msgType(XmlMsgType.EVENT) - .event(WxMpEventConstants.CustomerService.KF_SWITCH_SESSION) - .handler(this.kfSessionHandler).end(); + .event(WxMpEventConstants.CustomerService.KF_SWITCH_SESSION).handler(this.kfSessionHandler).end(); // 门店审核事件 - newRouter.rule().async(false).msgType(XmlMsgType.EVENT) - .event(WxMpEventConstants.POI_CHECK_NOTIFY) + newRouter.rule().async(false).msgType(XmlMsgType.EVENT).event(WxMpEventConstants.POI_CHECK_NOTIFY) .handler(this.storeCheckNotifyHandler).end(); // 自定义菜单事件 - newRouter.rule().async(false).msgType(XmlMsgType.EVENT) - .event(MenuButtonType.CLICK).handler(this.menuHandler).end(); - - // 点击菜单连接事件 - newRouter.rule().async(false).msgType(XmlMsgType.EVENT) - .event(MenuButtonType.VIEW).handler(this.nullHandler).end(); - - // 关注事件 - newRouter.rule().async(false).msgType(XmlMsgType.EVENT) - .event(EventType.SUBSCRIBE).handler(this.subscribeHandler) + newRouter.rule().async(false).msgType(XmlMsgType.EVENT).event(MenuButtonType.CLICK).handler(this.menuHandler) .end(); + // 点击菜单连接事件 + newRouter.rule().async(false).msgType(XmlMsgType.EVENT).event(MenuButtonType.VIEW).handler(this.nullHandler) + .end(); + + // 关注事件 + newRouter.rule().async(false).msgType(XmlMsgType.EVENT).event(EventType.SUBSCRIBE) + .handler(this.subscribeHandler).end(); + // 取消关注事件 - newRouter.rule().async(false).msgType(XmlMsgType.EVENT) - .event(EventType.UNSUBSCRIBE) + newRouter.rule().async(false).msgType(XmlMsgType.EVENT).event(EventType.UNSUBSCRIBE) .handler(this.unsubscribeHandler).end(); // 上报地理位置事件 - newRouter.rule().async(false).msgType(XmlMsgType.EVENT) - .event(EventType.LOCATION).handler(this.locationHandler) + newRouter.rule().async(false).msgType(XmlMsgType.EVENT).event(EventType.LOCATION).handler(this.locationHandler) .end(); // 接收地理位置消息 - newRouter.rule().async(false).msgType(XmlMsgType.LOCATION) - .handler(this.locationHandler).end(); + newRouter.rule().async(false).msgType(XmlMsgType.LOCATION).handler(this.locationHandler).end(); // 扫码事件 - newRouter.rule().async(false).msgType(XmlMsgType.EVENT) - .event(EventType.SCAN).handler(this.scanHandler).end(); + newRouter.rule().async(false).msgType(XmlMsgType.EVENT).event(EventType.SCAN).handler(this.scanHandler).end(); // 默认 newRouter.rule().async(false).handler(this.msgHandler).end(); @@ -150,17 +153,14 @@ public class WxMpInitConfigRunner { return newRouter; } - /** * redis 监听配置,监听 mp_redis_reload_topic,重新加载配置 - * * @param redisConnectionFactory redis 配置 * @return */ @Bean public RedisMessageListenerContainer redisContainer(RedisConnectionFactory redisConnectionFactory) { - RedisMessageListenerContainer container - = new RedisMessageListenerContainer(); + RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(redisConnectionFactory); container.addMessageListener((message, bytes) -> { log.warn("接收到重新加载公众号配置事件"); @@ -180,4 +180,5 @@ public class WxMpInitConfigRunner { public static Map getMpServices() { return mpServices; } + } diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/constant/MsgTypeEnum.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/constant/MsgTypeEnum.java index 5a2c51fb5..481673c83 100644 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/constant/MsgTypeEnum.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/constant/MsgTypeEnum.java @@ -32,4 +32,5 @@ public enum MsgTypeEnum { * 描述 */ private String desc; + } diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/constant/ReplyMateEnum.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/constant/ReplyMateEnum.java index d5b7d39db..1fa0c1e41 100644 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/constant/ReplyMateEnum.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/constant/ReplyMateEnum.java @@ -23,7 +23,6 @@ public enum ReplyMateEnum { */ LIKE("2", "半匹配"); - /*** * 类型 */ @@ -33,4 +32,5 @@ public enum ReplyMateEnum { * 描述 */ private String desc; + } diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/constant/ReplyTypeEnum.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/constant/ReplyTypeEnum.java index ad3d92cca..0021f0ca2 100644 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/constant/ReplyTypeEnum.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/constant/ReplyTypeEnum.java @@ -38,10 +38,8 @@ public enum ReplyTypeEnum { */ private String desc; - /** * 根据 type 查找枚举 - * * @param type * @return */ @@ -53,4 +51,5 @@ public enum ReplyTypeEnum { } return null; } + } diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/constant/SubStatusEnum.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/constant/SubStatusEnum.java index 036f3d5dc..29bc62a2a 100644 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/constant/SubStatusEnum.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/constant/SubStatusEnum.java @@ -12,6 +12,7 @@ import lombok.Getter; @Getter @AllArgsConstructor public enum SubStatusEnum { + /** * 已关注 */ @@ -22,7 +23,6 @@ public enum SubStatusEnum { */ UNSUB("0", "关注"); - /*** * 类型 */ @@ -32,4 +32,5 @@ public enum SubStatusEnum { * 描述 */ private String desc; + } diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/controller/WxAccountController.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/controller/WxAccountController.java index 27a1853db..08b7fadf5 100755 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/controller/WxAccountController.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/controller/WxAccountController.java @@ -28,7 +28,6 @@ import org.springframework.data.redis.core.RedisTemplate; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; - /** * 公众号账户 * @@ -39,13 +38,14 @@ import org.springframework.web.bind.annotation.*; @AllArgsConstructor @RequestMapping("/wxaccount") public class WxAccountController { + private final WxAccountService wxAccountService; + private final RedisTemplate redisTemplate; /** * 分页查询 - * - * @param page 分页对象 + * @param page 分页对象 * @param wxAccount 公众号账户 * @return */ @@ -54,10 +54,8 @@ public class WxAccountController { return R.ok(wxAccountService.page(page, Wrappers.query(wxAccount))); } - /** * 通过id查询公众号账户 - * * @param id id * @return R */ @@ -68,7 +66,6 @@ public class WxAccountController { /** * 新增公众号账户 - * * @param wxAccount 公众号账户 * @return R */ @@ -77,13 +74,12 @@ public class WxAccountController { @PreAuthorize("@pms.hasPermission('mp_wxaccount_add')") public R save(@RequestBody WxAccount wxAccount) { wxAccountService.save(wxAccount); - redisTemplate.convertAndSend(CacheConstants.MP_REDIS_RELOAD_TOPIC,"重新加载公众号配置"); + redisTemplate.convertAndSend(CacheConstants.MP_REDIS_RELOAD_TOPIC, "重新加载公众号配置"); return R.ok(); } /** * 修改公众号账户 - * * @param wxAccount 公众号账户 * @return R */ @@ -92,13 +88,12 @@ public class WxAccountController { @PreAuthorize("@pms.hasPermission('mp_wxaccount_edit')") public R updateById(@RequestBody WxAccount wxAccount) { wxAccountService.updateById(wxAccount); - redisTemplate.convertAndSend(CacheConstants.MP_REDIS_RELOAD_TOPIC,"重新加载公众号配置"); + redisTemplate.convertAndSend(CacheConstants.MP_REDIS_RELOAD_TOPIC, "重新加载公众号配置"); return R.ok(); } /** * 通过id删除公众号账户 - * * @param id id * @return R */ @@ -107,13 +102,12 @@ public class WxAccountController { @PreAuthorize("@pms.hasPermission('mp_wxaccount_del')") public R removeById(@PathVariable Integer id) { wxAccountService.removeById(id); - redisTemplate.convertAndSend(CacheConstants.MP_REDIS_RELOAD_TOPIC,"重新加载公众号配置"); + redisTemplate.convertAndSend(CacheConstants.MP_REDIS_RELOAD_TOPIC, "重新加载公众号配置"); return R.ok(); } /** * 生成公众号二维码 - * * @param appId * @return */ @@ -126,7 +120,6 @@ public class WxAccountController { /** * 获取公众号列表 - * * @return */ @GetMapping("/list") @@ -136,8 +129,7 @@ public class WxAccountController { /** * 获取公众号接口数据 - * - * @param appId 公众号 + * @param appId 公众号 * @param interval 时间间隔 * @return */ @@ -145,4 +137,5 @@ public class WxAccountController { public R statistics(String appId, String interval) { return wxAccountService.statistics(appId, interval); } + } diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/controller/WxAccountFansController.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/controller/WxAccountFansController.java index 0f92fc5e4..f6ea79e42 100755 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/controller/WxAccountFansController.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/controller/WxAccountFansController.java @@ -26,7 +26,6 @@ import lombok.AllArgsConstructor; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; - /** * 微信公众号粉丝管理 * @@ -42,8 +41,7 @@ public class WxAccountFansController { /** * 分页查询 - * - * @param page 分页对象 + * @param page 分页对象 * @param wxAccountFans 微信公众号粉丝 * @return */ @@ -52,10 +50,8 @@ public class WxAccountFansController { return R.ok(wxAccountFansService.page(page, Wrappers.query(wxAccountFans))); } - /** * 通过id查询微信公众号粉丝 - * * @param id id * @return R */ @@ -66,7 +62,6 @@ public class WxAccountFansController { /** * 新增微信公众号粉丝 - * * @param wxAccountFans 微信公众号粉丝 * @return R */ @@ -79,7 +74,6 @@ public class WxAccountFansController { /** * 修改微信公众号粉丝 - * * @param wxAccountFans 微信公众号粉丝 * @return R */ @@ -92,7 +86,6 @@ public class WxAccountFansController { /** * 通过id删除微信公众号粉丝 - * * @param id id * @return R */ @@ -105,7 +98,6 @@ public class WxAccountFansController { /** * 同步粉丝 - * * @param appId * @return */ diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/controller/WxAutoReplyController.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/controller/WxAutoReplyController.java index 2c9c4f7e2..3738ceae5 100644 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/controller/WxAutoReplyController.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/controller/WxAutoReplyController.java @@ -28,8 +28,7 @@ public class WxAutoReplyController { /** * 分页查询 - * - * @param page 分页对象 + * @param page 分页对象 * @param wxAutoReply 消息自动回复 * @return */ @@ -38,10 +37,8 @@ public class WxAutoReplyController { return R.ok(wxAutoReplyService.page(page, Wrappers.query(wxAutoReply))); } - /** * 通过id查询消息自动回复 - * * @param id id * @return R */ @@ -52,7 +49,6 @@ public class WxAutoReplyController { /** * 新增消息自动回复 - * * @param wxAutoReply 消息自动回复 * @return R */ @@ -65,7 +61,6 @@ public class WxAutoReplyController { /** * 修改消息自动回复 - * * @param wxAutoReply 消息自动回复 * @return R */ @@ -78,7 +73,6 @@ public class WxAutoReplyController { /** * 通过id删除消息自动回复 - * * @param id id * @return R */ @@ -90,13 +84,12 @@ public class WxAutoReplyController { /** * //校验参数 - * * @param wxAutoReply */ public void jude(WxAutoReply wxAutoReply) { if (ReplyTypeEnum.MSG.getType().equals(wxAutoReply.getType())) { - Wrapper queryWrapper = Wrappers.lambdaQuery() - .eq(WxAutoReply::getReqType, wxAutoReply.getReqType()); + Wrapper queryWrapper = Wrappers.lambdaQuery().eq(WxAutoReply::getReqType, + wxAutoReply.getReqType()); List list = wxAutoReplyService.list(queryWrapper); if (wxAutoReply.getId() != null) { if (list != null && list.size() == 1) { @@ -124,4 +117,5 @@ public class WxAutoReplyController { } } } + } diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/controller/WxFansMsgController.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/controller/WxFansMsgController.java index 97ca42b39..a99854704 100755 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/controller/WxFansMsgController.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/controller/WxFansMsgController.java @@ -26,7 +26,6 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; - /** * 微信粉丝消息管理 * @@ -43,9 +42,8 @@ public class WxFansMsgController { /** * 分页查询 - * * @param page 分页对象 - * @param msg 查询条件 + * @param msg 查询条件 */ @GetMapping("/page") public R getWxMsgPage(Page page, WxMsg msg) { @@ -54,7 +52,6 @@ public class WxFansMsgController { /** * 通过id查询微信消息 - * * @param id id * @return R */ @@ -65,7 +62,6 @@ public class WxFansMsgController { /** * 新增微信消息 - * * @param wxMsg 微信消息 * @return R */ @@ -77,7 +73,6 @@ public class WxFansMsgController { /** * 修改微信消息 - * * @param wxMsg 微信消息 * @return R */ @@ -89,7 +84,6 @@ public class WxFansMsgController { /** * 通过id删除微信消息 - * * @param id id * @return R */ diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/controller/WxMaterialController.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/controller/WxMaterialController.java index 4c618e336..be253cbd8 100644 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/controller/WxMaterialController.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/controller/WxMaterialController.java @@ -43,18 +43,15 @@ public class WxMaterialController { /** * 上传非图文微信素材 - * * @param mulFile * @param mediaType * @return */ @PostMapping("/materialFileUpload") @PreAuthorize("@pms.hasPermission('mp_wxmaterial_add')") - public R materialFileUpload(@RequestParam("file") MultipartFile mulFile, - @RequestParam String appId, - @RequestParam("title") String title, - @RequestParam("introduction") String introduction, - @RequestParam("mediaType") String mediaType) { + public R materialFileUpload(@RequestParam("file") MultipartFile mulFile, @RequestParam String appId, + @RequestParam("title") String title, @RequestParam("introduction") String introduction, + @RequestParam("mediaType") String mediaType) { try { WxMpMaterial material = new WxMpMaterial(); material.setName(mulFile.getOriginalFilename()); @@ -69,17 +66,20 @@ public class WxMaterialController { WxMpService wxMpService = WxMpInitConfigRunner.getMpServices().get(appId); WxMpMaterialService wxMpMaterialService = wxMpService.getMaterialService(); - WxMpMaterialUploadResult wxMpMaterialUploadResult = wxMpMaterialService.materialFileUpload(mediaType, material); + WxMpMaterialUploadResult wxMpMaterialUploadResult = wxMpMaterialService.materialFileUpload(mediaType, + material); WxMpMaterialFileBatchGetResult.WxMaterialFileBatchGetNewsItem wxMpMaterialFileBatchGetResult = new WxMpMaterialFileBatchGetResult.WxMaterialFileBatchGetNewsItem(); wxMpMaterialFileBatchGetResult.setName(file.getName()); wxMpMaterialFileBatchGetResult.setMediaId(wxMpMaterialUploadResult.getMediaId()); wxMpMaterialFileBatchGetResult.setUrl(wxMpMaterialUploadResult.getUrl()); FileUtil.del(file); return R.ok(wxMpMaterialFileBatchGetResult); - } catch (WxErrorException e) { + } + catch (WxErrorException e) { log.warn("上传非图文微信素材失败: {}", e.getLocalizedMessage()); return R.failed(e.getLocalizedMessage()); - } catch (Exception e) { + } + catch (Exception e) { log.error("上传失败", e); return R.failed(e.getLocalizedMessage()); } @@ -87,7 +87,6 @@ public class WxMaterialController { /** * 新增图文消息 - * * @param data * @return */ @@ -96,7 +95,8 @@ public class WxMaterialController { public R materialNewsUpload(@RequestBody JSONObject data) { try { JSONArray jSONArray = data.getJSONArray("articles"); - List articles = jSONArray.toList(WxMpMaterialNews.WxMpMaterialNewsArticle.class); + List articles = jSONArray + .toList(WxMpMaterialNews.WxMpMaterialNewsArticle.class); WxMpMaterialNews news = new WxMpMaterialNews(); news.setArticles(articles); @@ -105,10 +105,12 @@ public class WxMaterialController { WxMpMaterialService wxMpMaterialService = wxMpService.getMaterialService(); WxMpMaterialUploadResult wxMpMaterialUploadResult = wxMpMaterialService.materialNewsUpload(news); return R.ok(wxMpMaterialUploadResult); - } catch (WxErrorException e) { + } + catch (WxErrorException e) { log.warn("新增图文失败: {}", e.getMessage()); return R.failed(e.getMessage()); - } catch (Exception e) { + } + catch (Exception e) { log.error("新增图文失败", e); return R.failed(e.getLocalizedMessage()); } @@ -116,7 +118,6 @@ public class WxMaterialController { /** * 修改图文消息 - * * @param data * @return */ @@ -126,7 +127,8 @@ public class WxMaterialController { try { String mediaId = data.getStr("mediaId"); JSONArray jSONArray = data.getJSONArray("articles"); - List articles = jSONArray.toList(WxMpMaterialNews.WxMpMaterialNewsArticle.class); + List articles = jSONArray + .toList(WxMpMaterialNews.WxMpMaterialNewsArticle.class); String appId = data.getStr("appId"); WxMpService wxMpService = WxMpInitConfigRunner.getMpServices().get(appId); WxMpMaterialService wxMpMaterialService = wxMpService.getMaterialService(); @@ -140,10 +142,12 @@ public class WxMaterialController { index++; } return R.ok(); - } catch (WxErrorException e) { + } + catch (WxErrorException e) { log.warn("修改图文失败:{}", e.getLocalizedMessage()); return R.failed(e.getLocalizedMessage()); - } catch (Exception e) { + } + catch (Exception e) { log.error("修改图文失败", e); return R.failed(e.getLocalizedMessage()); } @@ -151,13 +155,13 @@ public class WxMaterialController { /** * 上传图文消息内的图片获取URL - * * @param mulFile * @return */ @PostMapping("/newsImgUpload") @PreAuthorize("@pms.hasPermission('mp_wxmaterial_add')") - public String newsImgUpload(@RequestParam("file") MultipartFile mulFile, @RequestParam String appId) throws Exception { + public String newsImgUpload(@RequestParam("file") MultipartFile mulFile, @RequestParam String appId) + throws Exception { File file = FileUtil.createTempFile(FileUtil.getTmpDir()); mulFile.transferTo(file); WxMpService wxMpService = WxMpInitConfigRunner.getMpServices().get(appId); @@ -171,7 +175,6 @@ public class WxMaterialController { /** * 通过id删除微信素材 - * * @param * @return R */ @@ -182,7 +185,8 @@ public class WxMaterialController { WxMpMaterialService wxMpMaterialService = wxMpService.getMaterialService(); try { return R.ok(wxMpMaterialService.materialDelete(id)); - } catch (WxErrorException e) { + } + catch (WxErrorException e) { log.error("删除微信素材失败", e); return R.failed(e.getMessage()); } @@ -190,7 +194,6 @@ public class WxMaterialController { /** * 分页查询 - * * @param page 分页对象 * @param type * @return @@ -204,19 +207,19 @@ public class WxMaterialController { int offset = (int) page.getCurrent() * count - count; if (WxConsts.MaterialType.NEWS.equals(type)) { return R.ok(wxMpMaterialService.materialNewsBatchGet(offset, count)); - } else { + } + else { return R.ok(wxMpMaterialService.materialFileBatchGet(type, offset, count)); } - } catch (WxErrorException e) { + } + catch (WxErrorException e) { log.error("查询素材失败", e); return R.failed(e.getLocalizedMessage()); } } - /** * 获取微信视频素材 - * * @param * @return R */ @@ -226,7 +229,8 @@ public class WxMaterialController { WxMpMaterialService wxMpMaterialService = wxMpService.getMaterialService(); try { return R.ok(wxMpMaterialService.materialVideoInfo(mediaId)); - } catch (WxErrorException e) { + } + catch (WxErrorException e) { log.error("获取微信视频素材失败", e); return R.failed(e.getMessage()); } @@ -234,7 +238,6 @@ public class WxMaterialController { /** * 获取微信素材直接文件 - * * @param * @return R */ @@ -243,19 +246,20 @@ public class WxMaterialController { try { WxMpService wxMpService = WxMpInitConfigRunner.getMpServices().get(appId); WxMpMaterialService wxMpMaterialService = wxMpService.getMaterialService(); - //获取文件 + // 获取文件 InputStream is = wxMpMaterialService.materialImageOrVoiceDownload(mediaId); byte[] body = new byte[is.available()]; is.read(body); HttpHeaders headers = new HttpHeaders(); - //设置文件类型 + // 设置文件类型 headers.add("Content-Disposition", "attchement;filename=" + URLEncoder.encode(fileName, "UTF-8")); headers.add("Content-Type", "application/octet-stream"); HttpStatus statusCode = HttpStatus.OK; - //返回数据 + // 返回数据 ResponseEntity entity = new ResponseEntity<>(body, headers, statusCode); return entity; - } catch (WxErrorException e) { + } + catch (WxErrorException e) { e.printStackTrace(); log.error("获取微信素材直接文件失败", e); return null; @@ -264,7 +268,6 @@ public class WxMaterialController { /** * 获取微信临时素材直接文件 - * * @param * @return R */ @@ -273,22 +276,24 @@ public class WxMaterialController { try { WxMpService wxMpService = WxMpInitConfigRunner.getMpServices().get(appId); WxMpMaterialService wxMpMaterialService = wxMpService.getMaterialService(); - //获取文件 + // 获取文件 InputStream is = new FileInputStream(wxMpMaterialService.mediaDownload(mediaId)); byte[] body = new byte[is.available()]; is.read(body); HttpHeaders headers = new HttpHeaders(); - //设置文件类型 + // 设置文件类型 headers.add("Content-Disposition", "attchement;filename=" + URLEncoder.encode(fileName, "UTF-8")); headers.add("Content-Type", "application/octet-stream"); HttpStatus statusCode = HttpStatus.OK; - //返回数据 + // 返回数据 ResponseEntity entity = new ResponseEntity<>(body, headers, statusCode); return entity; - } catch (WxErrorException e) { + } + catch (WxErrorException e) { e.printStackTrace(); log.error("获取微信素材直接文件失败", e); return null; } } + } diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/controller/WxMenuController.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/controller/WxMenuController.java index c8bf0d33c..0c40b73ed 100755 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/controller/WxMenuController.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/controller/WxMenuController.java @@ -24,7 +24,6 @@ import lombok.AllArgsConstructor; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; - /** * 微信菜单管理 * @@ -38,10 +37,8 @@ public class WxMenuController { private final WxMenuService wxMenuService; - /** * 通过appid查询微信菜单 - * * @param appId 公众号 * @return R */ @@ -52,7 +49,6 @@ public class WxMenuController { /** * 新增微信菜单 - * * @param wxMenu 微信菜单列表 * @return R */ @@ -65,7 +61,6 @@ public class WxMenuController { /** * 发布微信菜单 - * * @param appId 公众号 * @return R */ @@ -81,4 +76,5 @@ public class WxMenuController { public R delete(@PathVariable("appId") String appId) { return wxMenuService.delete(appId); } + } diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/controller/WxPortalController.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/controller/WxPortalController.java index 19164b772..e4761b871 100755 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/controller/WxPortalController.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/controller/WxPortalController.java @@ -27,24 +27,24 @@ import org.springframework.web.bind.annotation.*; @AllArgsConstructor @RequestMapping("/{appId}/portal") public class WxPortalController { + private final WxAccountService accountService; /** * 微信接入校验处理 - * - * @param appId 多公众号标志位 + * @param appId 多公众号标志位 * @param signature 微信签名 * @param timestamp 时间戳 - * @param nonce 随机数 - * @param echostr 随机字符串 + * @param nonce 随机数 + * @param echostr 随机字符串 * @return */ @GetMapping(produces = "text/plain;charset=utf-8") public String authGet(@PathVariable("appId") String appId, - @RequestParam(name = "signature", required = false) String signature, - @RequestParam(name = "timestamp", required = false) String timestamp, - @RequestParam(name = "nonce", required = false) String nonce, - @RequestParam(name = "echostr", required = false) String echostr) { + @RequestParam(name = "signature", required = false) String signature, + @RequestParam(name = "timestamp", required = false) String timestamp, + @RequestParam(name = "nonce", required = false) String nonce, + @RequestParam(name = "echostr", required = false) String echostr) { log.info("接收到来自微信服务器的认证消息:[{}, {}, {}, {}]", signature, timestamp, nonce, echostr); @@ -67,57 +67,45 @@ public class WxPortalController { /** * 微信消息处理 - * - * @param appId 多公众号标志位 - * @param requestBody 请求报文体 - * @param signature 微信签名 - * @param encType 加签方式 + * @param appId 多公众号标志位 + * @param requestBody 请求报文体 + * @param signature 微信签名 + * @param encType 加签方式 * @param msgSignature 微信签名 - * @param timestamp 时间戳 - * @param nonce 随机数 + * @param timestamp 时间戳 + * @param nonce 随机数 * @return */ @PostMapping(produces = "application/xml; charset=UTF-8") - public String post(@PathVariable("appId") String appId, - @RequestBody String requestBody, - @RequestParam("signature") String signature, - @RequestParam("timestamp") String timestamp, - @RequestParam("nonce") String nonce, - @RequestParam("openid") String openid, - @RequestParam(name = "encrypt_type", required = false) String encType, - @RequestParam(name = "msg_signature", required = false) String msgSignature) { - return TenantBroker.applyAs( - () -> WxMpInitConfigRunner.getTenants().get(appId), - (id) -> handleMessage(appId,requestBody,signature,timestamp,nonce,openid,encType,msgSignature) - ); + public String post(@PathVariable("appId") String appId, @RequestBody String requestBody, + @RequestParam("signature") String signature, @RequestParam("timestamp") String timestamp, + @RequestParam("nonce") String nonce, @RequestParam("openid") String openid, + @RequestParam(name = "encrypt_type", required = false) String encType, + @RequestParam(name = "msg_signature", required = false) String msgSignature) { + return TenantBroker.applyAs(() -> WxMpInitConfigRunner.getTenants().get(appId), + (id) -> handleMessage(appId, requestBody, signature, timestamp, nonce, openid, encType, msgSignature)); } /** * 微信消息处理 - * - * @param appId 多公众号标志位 - * @param requestBody 请求报文体 - * @param signature 微信签名 - * @param encType 加签方式 + * @param appId 多公众号标志位 + * @param requestBody 请求报文体 + * @param signature 微信签名 + * @param encType 加签方式 * @param msgSignature 微信签名 - * @param timestamp 时间戳 - * @param nonce 随机数 + * @param timestamp 时间戳 + * @param nonce 随机数 * @return */ - public String handleMessage(String appId, - String requestBody, - String signature, - String timestamp, - String nonce, - String openid, - String encType, - String msgSignature) { + public String handleMessage(String appId, String requestBody, String signature, String timestamp, String nonce, + String openid, String encType, String msgSignature) { WxMpContextHolder.setAppId(appId); final WxMpService wxService = WxMpInitConfigRunner.getMpServices().get(appId); - log.info("接收微信请求:[openid=[{}], [signature=[{}], encType=[{}], msgSignature=[{}]," + log.info( + "接收微信请求:[openid=[{}], [signature=[{}], encType=[{}], msgSignature=[{}]," + " timestamp=[{}], nonce=[{}], requestBody=[{}] ", openid, signature, encType, msgSignature, timestamp, nonce, requestBody); diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/entity/WxAccount.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/entity/WxAccount.java index 0cd179e8c..6d1f750f7 100755 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/entity/WxAccount.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/entity/WxAccount.java @@ -33,6 +33,7 @@ import java.time.LocalDateTime; @Data @EqualsAndHashCode(callSuper = true) public class WxAccount extends Model { + private static final long serialVersionUID = 1L; /** @@ -40,49 +41,59 @@ public class WxAccount extends Model { */ @TableId private Integer id; + /** * 公众号名称 */ private String name; + /** * 公众号账户 */ private String account; + /** * 公众号appid */ private String appid; + /** * 公众号密钥 */ private String appsecret; + /** * 公众号url */ private String url; + /** * 公众号token */ private String token; + /** * 加密密钥 */ private String aeskey; + /** * 二维码图片URL */ private String qrUrl; + /** * 创建时间 */ private LocalDateTime createTime; + /** * 更新时间 */ private LocalDateTime updateTime; /** - * 是否删除 -1:已删除 0:正常 + * 是否删除 -1:已删除 0:正常 */ @TableLogic private String delFlag; @@ -91,4 +102,5 @@ public class WxAccount extends Model { * 租户 */ private Integer tenantId; + } diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/entity/WxAccountFans.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/entity/WxAccountFans.java index cad319aa8..2360203a4 100755 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/entity/WxAccountFans.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/entity/WxAccountFans.java @@ -33,6 +33,7 @@ import java.time.LocalDateTime; @Data @EqualsAndHashCode(callSuper = true) public class WxAccountFans extends Model { + private static final long serialVersionUID = 1L; /** @@ -40,54 +41,67 @@ public class WxAccountFans extends Model { */ @TableId private Integer id; + /** * 用户标识 */ private String openid; + /** * 订阅状态,0未关注,1已关注 */ private String subscribeStatus; + /** * 订阅时间 */ private LocalDateTime subscribeTime; + /** * 昵称 */ private String nickname; + /** * 性别,1男,2女,0未知 */ private String gender; + /** * 语言 */ private String language; + /** * 国家 */ private String country; + /** * 省份 */ private String province; + /** * 城市 */ private String city; + /** * 头像地址 */ private String headimgUrl; + /** * 备注 */ private String remark; + /** * 微信公众号ID */ private Integer wxAccountId; + /** * 微信公众号appid */ @@ -97,16 +111,19 @@ public class WxAccountFans extends Model { * 微信公众号名 */ private String wxAccountName; + /** * 创建时间 */ private LocalDateTime createTime; + /** * 更新时间 */ private LocalDateTime updateTime; + /** - * 是否删除 -1:已删除 0:正常 + * 是否删除 -1:已删除 0:正常 */ @TableLogic private String delFlag; diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/entity/WxAutoReply.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/entity/WxAutoReply.java index 20b6311fc..6163efbc1 100644 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/entity/WxAutoReply.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/entity/WxAutoReply.java @@ -19,6 +19,7 @@ import java.time.LocalDateTime; @TableName("wx_auto_reply") @EqualsAndHashCode(callSuper = true) public class WxAutoReply extends Model { + private static final long serialVersionUID = 1L; /** @@ -31,72 +32,89 @@ public class WxAutoReply extends Model { * 公众号ID */ private String appId; + /** * 创建时间 */ private LocalDateTime createTime; + /** * 更新时间 */ private LocalDateTime updateTime; + /** * 备注 */ private String remark; + /** * 逻辑删除标记(0:显示;1:隐藏) */ private String delFlag; + /** * 类型(1、关注时回复;2、消息回复;3、关键词回复) */ @NotNull(message = "类型不能为空") private String type; + /** * 关键词 */ private String reqKey; + /** * 请求消息类型(text:文本;image:图片;voice:语音;video:视频;shortvideo:小视频;location:地理位置) */ private String reqType; + /** * 回复消息类型(text:文本;image:图片;voice:语音;video:视频;music:音乐;news:图文) */ @NotNull(message = "回复消息类型不能为空") private String repType; + /** * 回复类型文本匹配类型(1、全匹配,2、半匹配) */ private String repMate; + /** * 回复类型文本保存文字 */ private String repContent; + /** * 回复的素材名、视频和音乐的标题 */ private String repName; + /** * 回复类型imge、voice、news、video的mediaID或音乐缩略图的媒体id */ private String repMediaId; + /** * 视频和音乐的描述 */ private String repDesc; + /** * 链接 */ private String repUrl; + /** * 高质量链接 */ private String repHqUrl; + /** * 缩略图的媒体id */ private String repThumbMediaId; + /** * 缩略图url */ @@ -106,4 +124,5 @@ public class WxAutoReply extends Model { * 图文消息的内容 */ private String content; + } diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/entity/WxFansMsgRes.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/entity/WxFansMsgRes.java index d39115982..9993114b1 100755 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/entity/WxFansMsgRes.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/entity/WxFansMsgRes.java @@ -32,6 +32,7 @@ import java.time.LocalDateTime; @Data @EqualsAndHashCode(callSuper = true) public class WxFansMsgRes extends Model { + private static final long serialVersionUID = 1L; /** @@ -39,26 +40,32 @@ public class WxFansMsgRes extends Model { */ @TableId private Integer id; + /** * 粉丝消息ID */ private Integer fansMsgId; + /** * 回复内容 */ private String resContent; + /** * 用户ID */ private Integer userId; + /** * 用户名 */ private String userName; + /** * 创建时间 */ private LocalDateTime createTime; + /** * 更新时间 */ diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/entity/WxMpMenu.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/entity/WxMpMenu.java index 2169c1a78..d565a81d0 100755 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/entity/WxMpMenu.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/entity/WxMpMenu.java @@ -33,6 +33,7 @@ import java.time.LocalDateTime; @Data @EqualsAndHashCode(callSuper = true) public class WxMpMenu extends Model { + private static final long serialVersionUID = 1L; /** @@ -50,6 +51,7 @@ public class WxMpMenu extends Model { * 微信公众号ID */ private Integer wxAccountId; + /** * 微信公众号appid */ @@ -64,13 +66,14 @@ public class WxMpMenu extends Model { * 创建时间 */ private LocalDateTime createTime; + /** * 更新时间 */ private LocalDateTime updateTime; /** - * 是否删除 -1:已删除 0:正常 + * 是否删除 -1:已删除 0:正常 */ @TableLogic private String delFlag; diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/entity/WxMsg.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/entity/WxMsg.java index 5915073df..16318de0c 100644 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/entity/WxMsg.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/entity/WxMsg.java @@ -20,6 +20,7 @@ import java.time.LocalDateTime; @EqualsAndHashCode(callSuper = true) @ApiModel(description = "微信消息") public class WxMsg extends Model { + private static final long serialVersionUID = 1L; /** @@ -27,18 +28,22 @@ public class WxMsg extends Model { */ @TableId private Integer id; + /** * 创建时间 */ private LocalDateTime createTime; + /** * 更新时间 */ private LocalDateTime updateTime; + /** * 备注 */ private String remark; + /** * 逻辑删除标记(0:显示;1:隐藏) */ @@ -48,22 +53,27 @@ public class WxMsg extends Model { * 公众号ID */ private String appId; + /** * 公众号名称 */ private String appName; + /** * 公众号logo */ private String appLogo; + /** * 微信用户ID */ private Integer wxUserId; + /** * 昵称 */ private String nickName; + /** * 头像 */ @@ -73,66 +83,82 @@ public class WxMsg extends Model { * 微信openId */ private String openId; + /** * 消息分类(1、用户发给公众号;2、公众号发给用户;) */ private String type; + /** * 消息类型(text:文本;image:图片;voice:语音;video:视频;shortvideo:小视频;location:地理位置;music:音乐;news:图文;event:推送事件) */ private String repType; + /** * 事件类型(subscribe:关注;unsubscribe:取关;CLICK、VIEW:菜单事件) */ private String repEvent; + /** * 回复类型文本保存文字 */ private String repContent; + /** * 回复类型imge、voice、news、video的mediaID或音乐缩略图的媒体id */ private String repMediaId; + /** * 回复的素材名、视频和音乐的标题 */ private String repName; + /** * 视频和音乐的描述 */ private String repDesc; + /** * 链接 */ private String repUrl; + /** * 高质量链接 */ private String repHqUrl; + /** * 图文消息的内容 */ private String content; + /** * 缩略图的媒体id */ private String repThumbMediaId; + /** * 缩略图url */ private String repThumbUrl; + /** * 地理位置维度 */ private Double repLocationX; + /** * 地理位置经度 */ private Double repLocationY; + /** * 地图缩放大小 */ private Double repScale; + /** * 已读标记(0:是;1:否) */ diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/AbstractHandler.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/AbstractHandler.java index c59c54c4e..34b8ca9a1 100755 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/AbstractHandler.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/AbstractHandler.java @@ -6,4 +6,5 @@ import me.chanjar.weixin.mp.api.WxMpMessageHandler; * @author Binary Wang(https://github.com/binarywang) */ public abstract class AbstractHandler implements WxMpMessageHandler { + } diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/KfSessionHandler.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/KfSessionHandler.java index a6792b40c..c13038ac1 100755 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/KfSessionHandler.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/KfSessionHandler.java @@ -14,11 +14,10 @@ import java.util.Map; @Component public class KfSessionHandler extends AbstractHandler { - @Override - public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, - Map context, WxMpService wxMpService, - WxSessionManager sessionManager) { - return null; - } + @Override + public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map context, WxMpService wxMpService, + WxSessionManager sessionManager) { + return null; + } } diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/LocationHandler.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/LocationHandler.java index d6e7b10ac..0aebc0c2e 100755 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/LocationHandler.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/LocationHandler.java @@ -28,32 +28,36 @@ import java.util.Map; @Component @AllArgsConstructor public class LocationHandler extends AbstractHandler { + private final WxAutoReplyService wxAutoReplyService; + private final WxAccountFansMapper wxAccountFansMapper; + private final WxAccountMapper wxAccountMapper; + private final WxMsgMapper msgMapper; @Override - public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, - Map context, WxMpService wxMpService, - WxSessionManager sessionManager) { - //上报地理位置事件 - log.info("上报地理位置,纬度 : {},经度 : {},精度 : {}", - wxMessage.getLatitude(), wxMessage.getLongitude(), wxMessage.getPrecision()); + public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map context, WxMpService wxMpService, + WxSessionManager sessionManager) { + // 上报地理位置事件 + log.info("上报地理位置,纬度 : {},经度 : {},精度 : {}", wxMessage.getLatitude(), wxMessage.getLongitude(), + wxMessage.getPrecision()); - //发送关注消息 - List listWxAutoReply = wxAutoReplyService.list(Wrappers.query().lambda() - .eq(WxAutoReply::getType, ReplyTypeEnum.MSG.getType()) - .eq(WxAutoReply::getAppId, WxMpContextHolder.getAppId()) - .eq(WxAutoReply::getReqType, wxMessage.getMsgType())); + // 发送关注消息 + List listWxAutoReply = wxAutoReplyService + .list(Wrappers.query().lambda().eq(WxAutoReply::getType, ReplyTypeEnum.MSG.getType()) + .eq(WxAutoReply::getAppId, WxMpContextHolder.getAppId()) + .eq(WxAutoReply::getReqType, wxMessage.getMsgType())); // 查询公众号 基本信息 - WxAccount wxAccount = wxAccountMapper.selectOne(Wrappers.lambdaQuery() - .eq(WxAccount::getAccount, wxMessage.getToUser())); + WxAccount wxAccount = wxAccountMapper + .selectOne(Wrappers.lambdaQuery().eq(WxAccount::getAccount, wxMessage.getToUser())); // 查询粉丝基本信息 - WxAccountFans fans = wxAccountFansMapper.selectOne(Wrappers.lambdaQuery() - .eq(WxAccountFans::getOpenid, wxMessage.getFromUser())); + WxAccountFans fans = wxAccountFansMapper + .selectOne(Wrappers.lambdaQuery().eq(WxAccountFans::getOpenid, wxMessage.getFromUser())); return MsgHandler.getWxMpXmlOutMessage(wxMessage, listWxAutoReply, fans, msgMapper, wxAccount); } + } diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/LogHandler.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/LogHandler.java index 43eead0fd..21219d64e 100755 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/LogHandler.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/LogHandler.java @@ -30,23 +30,24 @@ import java.util.Map; @AllArgsConstructor public class LogHandler extends AbstractHandler { + private final WxAccountFansMapper fansMapper; + private final WxAccountMapper accountMapper; + private final WxMsgMapper msgMapper; @Override @SneakyThrows - public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, - Map context, WxMpService wxMpService, - WxSessionManager sessionManager) { + public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map context, WxMpService wxMpService, + WxSessionManager sessionManager) { log.debug("接收到请求消息,内容:{}", wxMessage.getContent()); + WxAccount wxAccount = accountMapper + .selectOne(Wrappers.lambdaQuery().eq(WxAccount::getAccount, wxMessage.getToUser())); - WxAccount wxAccount = accountMapper.selectOne(Wrappers.lambdaQuery() - .eq(WxAccount::getAccount, wxMessage.getToUser())); - - WxAccountFans fans = fansMapper.selectOne(Wrappers.lambdaQuery() - .eq(WxAccountFans::getOpenid, wxMessage.getFromUser())); + WxAccountFans fans = fansMapper + .selectOne(Wrappers.lambdaQuery().eq(WxAccountFans::getOpenid, wxMessage.getFromUser())); WxMsg wxMsg = new WxMsg(); wxMsg.setWxUserId(fans.getId()); @@ -101,4 +102,5 @@ public class LogHandler extends AbstractHandler { log.debug("保存微信用户信息成功 {}", wxMsg); return null; } + } diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/MenuHandler.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/MenuHandler.java index b803c02b2..0321cea25 100755 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/MenuHandler.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/MenuHandler.java @@ -30,28 +30,27 @@ import java.util.Map; @Component @AllArgsConstructor public class MenuHandler extends AbstractHandler { + private final WxMenuMapper wxMenuMapper; @Override - public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, - Map context, WxMpService weixinService, - WxSessionManager sessionManager) throws WxErrorException { - //组装菜单回复消息 + public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map context, WxMpService weixinService, + WxSessionManager sessionManager) throws WxErrorException { + // 组装菜单回复消息 return getWxMpXmlOutMessage(wxMessage); } /** * 组装菜单回复消息 - * * @param wxMessage * @return */ public WxMpXmlOutMessage getWxMpXmlOutMessage(WxMpXmlMessage wxMessage) { - - WxMpMenu wxMpMenu = wxMenuMapper.selectOne(Wrappers.lambdaQuery() - .eq(WxMpMenu::getWxAccountAppid, WxMpContextHolder.getAppId())); - List buttons = JSONUtil.parseObj(wxMpMenu.getMenu()).getJSONArray("button").toList(JSONObject.class); + WxMpMenu wxMpMenu = wxMenuMapper.selectOne( + Wrappers.lambdaQuery().eq(WxMpMenu::getWxAccountAppid, WxMpContextHolder.getAppId())); + List buttons = JSONUtil.parseObj(wxMpMenu.getMenu()).getJSONArray("button") + .toList(JSONObject.class); String eventKey = wxMessage.getEventKey(); // 获取子集 @@ -81,20 +80,23 @@ public class MenuHandler extends AbstractHandler { String repMediaId = button.getStr("repMediaId"); String repDesc = button.getStr("repDesc"); if (WxConsts.KefuMsgType.TEXT.equals(repType)) { - wxMpXmlOutMessage = new TextBuilder().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).content(repContent).build(); + wxMpXmlOutMessage = new TextBuilder().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()) + .content(repContent).build(); } if (WxConsts.KefuMsgType.IMAGE.equals(repType)) { - wxMpXmlOutMessage = new ImageBuilder().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).mediaId(repMediaId).build(); + wxMpXmlOutMessage = new ImageBuilder().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()) + .mediaId(repMediaId).build(); } if (WxConsts.KefuMsgType.VOICE.equals(repType)) { - wxMpXmlOutMessage = new VoiceBuilder().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).mediaId(repMediaId).build(); + wxMpXmlOutMessage = new VoiceBuilder().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()) + .mediaId(repMediaId).build(); } if (WxConsts.KefuMsgType.VIDEO.equals(repType)) { - wxMpXmlOutMessage = new VideoBuilder().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).mediaId(repMediaId) - .title(repName).description(repDesc).build(); + wxMpXmlOutMessage = new VideoBuilder().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()) + .mediaId(repMediaId).title(repName).description(repDesc).build(); } if (WxConsts.KefuMsgType.MUSIC.equals(repType)) { @@ -103,16 +105,16 @@ public class MenuHandler extends AbstractHandler { String repHqUrl = button.getStr("repHqUrl"); wxMpXmlOutMessage = new MusicBuilder().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()) - .thumbMediaId(repThumbMediaId) - .title(repName).description(repDesc) - .musicUrl(repUrl).hqMusicUrl(repHqUrl).build(); + .thumbMediaId(repThumbMediaId).title(repName).description(repDesc).musicUrl(repUrl) + .hqMusicUrl(repHqUrl).build(); } if (WxConsts.KefuMsgType.NEWS.equals(repType)) { String content = button.getStr("content"); List list = new ArrayList<>(); - List articles = JSONUtil.parseObj(content).getJSONArray("articles").toList(JSONObject.class); + List articles = JSONUtil.parseObj(content).getJSONArray("articles") + .toList(JSONObject.class); WxMpXmlOutNewsMessage.Item t; for (JSONObject jsonObject : articles) { t = new WxMpXmlOutNewsMessage.Item(); @@ -122,7 +124,8 @@ public class MenuHandler extends AbstractHandler { t.setUrl(jsonObject.getStr("url")); list.add(t); } - wxMpXmlOutMessage = new NewsBuilder().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).articles(list).build(); + wxMpXmlOutMessage = new NewsBuilder().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()) + .articles(list).build(); } return wxMpXmlOutMessage; } @@ -130,4 +133,3 @@ public class MenuHandler extends AbstractHandler { } } - diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/MsgHandler.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/MsgHandler.java index 6e3fbc80a..e66a7aa29 100755 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/MsgHandler.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/MsgHandler.java @@ -38,45 +38,46 @@ import static me.chanjar.weixin.common.api.WxConsts.XmlMsgType; @Component @AllArgsConstructor public class MsgHandler extends AbstractHandler { + private final WxAutoReplyService wxAutoReplyService; + private final WxAccountFansMapper wxAccountFansMapper; + private final WxAccountMapper wxAccountMapper; + private final WxMsgMapper wxMsgMapper; @Override - public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, - Map context, WxMpService wxMpService, - WxSessionManager sessionManager) { - //组装回复消息 + public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map context, WxMpService wxMpService, + WxSessionManager sessionManager) { + // 组装回复消息 if (!wxMessage.getMsgType().equals(XmlMsgType.EVENT)) { WxMpXmlOutMessage rs; - WxAccountFans fans = wxAccountFansMapper.selectOne(Wrappers.lambdaQuery() - .eq(WxAccountFans::getOpenid, wxMessage.getFromUser())); + WxAccountFans fans = wxAccountFansMapper.selectOne( + Wrappers.lambdaQuery().eq(WxAccountFans::getOpenid, wxMessage.getFromUser())); // 查询公众号 基本信息 - WxAccount wxAccount = wxAccountMapper.selectOne(Wrappers.lambdaQuery() - .eq(WxAccount::getAccount, wxMessage.getToUser())); - //1、先处理是否有文本关键字回复 + WxAccount wxAccount = wxAccountMapper + .selectOne(Wrappers.lambdaQuery().eq(WxAccount::getAccount, wxMessage.getToUser())); + // 1、先处理是否有文本关键字回复 if (WxConsts.KefuMsgType.TEXT.equals(wxMessage.getMsgType())) { - //先全匹配 - List listWxAutoReply = wxAutoReplyService.list(Wrappers - .query().lambda() - .eq(WxAutoReply::getType, ReplyTypeEnum.KEYWORD.getType()) - .eq(WxAutoReply::getRepMate, ReplyMateEnum.ALL.getType()) - .eq(WxAutoReply::getAppId, WxMpContextHolder.getAppId()) - .eq(WxAutoReply::getReqKey, wxMessage.getContent())); + // 先全匹配 + List listWxAutoReply = wxAutoReplyService.list( + Wrappers.query().lambda().eq(WxAutoReply::getType, ReplyTypeEnum.KEYWORD.getType()) + .eq(WxAutoReply::getRepMate, ReplyMateEnum.ALL.getType()) + .eq(WxAutoReply::getAppId, WxMpContextHolder.getAppId()) + .eq(WxAutoReply::getReqKey, wxMessage.getContent())); if (listWxAutoReply != null && listWxAutoReply.size() > 0) { rs = getWxMpXmlOutMessage(wxMessage, listWxAutoReply, fans, wxMsgMapper, wxAccount); if (rs != null) { return rs; } } - //再半匹配 - listWxAutoReply = wxAutoReplyService.list(Wrappers - .query().lambda() - .eq(WxAutoReply::getType, ReplyTypeEnum.KEYWORD.getType()) - .eq(WxAutoReply::getAppId, WxMpContextHolder.getAppId()) - .eq(WxAutoReply::getRepMate, ReplyMateEnum.LIKE.getType()) - .like(WxAutoReply::getReqKey, wxMessage.getContent())); + // 再半匹配 + listWxAutoReply = wxAutoReplyService.list( + Wrappers.query().lambda().eq(WxAutoReply::getType, ReplyTypeEnum.KEYWORD.getType()) + .eq(WxAutoReply::getAppId, WxMpContextHolder.getAppId()) + .eq(WxAutoReply::getRepMate, ReplyMateEnum.LIKE.getType()) + .like(WxAutoReply::getReqKey, wxMessage.getContent())); if (listWxAutoReply != null && listWxAutoReply.size() > 0) { rs = getWxMpXmlOutMessage(wxMessage, listWxAutoReply, fans, wxMsgMapper, wxAccount); if (rs != null) { @@ -84,12 +85,11 @@ public class MsgHandler extends AbstractHandler { } } } - //2、再处理消息回复 - List listWxAutoReply = wxAutoReplyService.list(Wrappers - .query().lambda() - .eq(WxAutoReply::getAppId, WxMpContextHolder.getAppId()) - .eq(WxAutoReply::getType, ReplyTypeEnum.MSG.getType()) - .eq(WxAutoReply::getReqType, wxMessage.getMsgType())); + // 2、再处理消息回复 + List listWxAutoReply = wxAutoReplyService + .list(Wrappers.query().lambda().eq(WxAutoReply::getAppId, WxMpContextHolder.getAppId()) + .eq(WxAutoReply::getType, ReplyTypeEnum.MSG.getType()) + .eq(WxAutoReply::getReqType, wxMessage.getMsgType())); rs = getWxMpXmlOutMessage(wxMessage, listWxAutoReply, fans, wxMsgMapper, wxAccount); return rs; } @@ -99,21 +99,20 @@ public class MsgHandler extends AbstractHandler { /** * 组装回复消息,并记录消息 - * * @param wxMessage * @param listWxAutoReply * @param wxMsgMapper * @param wxAccount * @return */ - public static WxMpXmlOutMessage getWxMpXmlOutMessage(WxMpXmlMessage wxMessage - , List listWxAutoReply, WxAccountFans fans, WxMsgMapper wxMsgMapper, WxAccount wxAccount) { + public static WxMpXmlOutMessage getWxMpXmlOutMessage(WxMpXmlMessage wxMessage, List listWxAutoReply, + WxAccountFans fans, WxMsgMapper wxMsgMapper, WxAccount wxAccount) { WxMpXmlOutMessage wxMpXmlOutMessage = null; - //记录接收消息 + // 记录接收消息 if (listWxAutoReply != null && listWxAutoReply.size() > 0) { WxAutoReply wxAutoReply = listWxAutoReply.get(0); - //记录回复消息 + // 记录回复消息 WxMsg wxMsg = new WxMsg(); wxMsg.setWxUserId(fans.getId()); wxMsg.setNickName(fans.getNickname()); @@ -125,32 +124,36 @@ public class MsgHandler extends AbstractHandler { wxMsg.setAppName(wxAccount.getName()); wxMsg.setAppLogo(wxAccount.getQrUrl()); wxMsg.setAppId(wxAccount.getAppid()); - //文本 + // 文本 if (WxConsts.KefuMsgType.TEXT.equals(wxAutoReply.getRepType())) { wxMsg.setRepContent(wxAutoReply.getRepContent()); - wxMpXmlOutMessage = new TextBuilder().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).content(wxAutoReply.getRepContent()).build(); + wxMpXmlOutMessage = new TextBuilder().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()) + .content(wxAutoReply.getRepContent()).build(); } - //图片 + // 图片 if (WxConsts.KefuMsgType.IMAGE.equals(wxAutoReply.getRepType())) { wxMsg.setRepName(wxAutoReply.getRepName()); wxMsg.setRepUrl(wxAutoReply.getRepUrl()); wxMsg.setRepMediaId(wxAutoReply.getRepMediaId()); - wxMpXmlOutMessage = new ImageBuilder().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).mediaId(wxAutoReply.getRepMediaId()).build(); + wxMpXmlOutMessage = new ImageBuilder().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()) + .mediaId(wxAutoReply.getRepMediaId()).build(); } if (WxConsts.KefuMsgType.VOICE.equals(wxAutoReply.getRepType())) { wxMsg.setRepName(wxAutoReply.getRepName()); wxMsg.setRepUrl(wxAutoReply.getRepUrl()); wxMsg.setRepMediaId(wxAutoReply.getRepMediaId()); - wxMpXmlOutMessage = new VoiceBuilder().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).mediaId(wxAutoReply.getRepMediaId()).build(); + wxMpXmlOutMessage = new VoiceBuilder().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()) + .mediaId(wxAutoReply.getRepMediaId()).build(); } if (WxConsts.KefuMsgType.VIDEO.equals(wxAutoReply.getRepType())) { wxMsg.setRepName(wxAutoReply.getRepName()); wxMsg.setRepDesc(wxAutoReply.getRepDesc()); wxMsg.setRepUrl(wxAutoReply.getRepUrl()); wxMsg.setRepMediaId(wxAutoReply.getRepMediaId()); - wxMpXmlOutMessage = new VideoBuilder().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).mediaId(wxAutoReply.getRepMediaId()) - .title(wxAutoReply.getRepName()).description(wxAutoReply.getRepDesc()).build(); + wxMpXmlOutMessage = new VideoBuilder().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()) + .mediaId(wxAutoReply.getRepMediaId()).title(wxAutoReply.getRepName()) + .description(wxAutoReply.getRepDesc()).build(); } if (WxConsts.KefuMsgType.MUSIC.equals(wxAutoReply.getRepType())) { wxMsg.setRepName(wxAutoReply.getRepName()); @@ -160,9 +163,9 @@ public class MsgHandler extends AbstractHandler { wxMsg.setRepThumbMediaId(wxAutoReply.getRepThumbMediaId()); wxMsg.setRepThumbUrl(wxAutoReply.getRepThumbUrl()); wxMpXmlOutMessage = new MusicBuilder().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()) - .thumbMediaId(wxAutoReply.getRepThumbMediaId()) - .title(wxAutoReply.getRepName()).description(wxAutoReply.getRepDesc()) - .musicUrl(wxAutoReply.getRepUrl()).hqMusicUrl(wxAutoReply.getRepHqUrl()).build(); + .thumbMediaId(wxAutoReply.getRepThumbMediaId()).title(wxAutoReply.getRepName()) + .description(wxAutoReply.getRepDesc()).musicUrl(wxAutoReply.getRepUrl()) + .hqMusicUrl(wxAutoReply.getRepHqUrl()).build(); } if (WxConsts.KefuMsgType.NEWS.equals(wxAutoReply.getRepType())) { List list = new ArrayList<>(); @@ -183,10 +186,12 @@ public class MsgHandler extends AbstractHandler { wxMsg.setRepUrl(wxAutoReply.getRepUrl()); wxMsg.setRepMediaId(wxAutoReply.getRepMediaId()); wxMsg.setContent(wxAutoReply.getContent()); - wxMpXmlOutMessage = new NewsBuilder().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).articles(list).build(); + wxMpXmlOutMessage = new NewsBuilder().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()) + .articles(list).build(); } wxMsgMapper.insert(wxMsg); } return wxMpXmlOutMessage; } + } diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/NullHandler.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/NullHandler.java index 5f961b871..d92f3918c 100755 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/NullHandler.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/NullHandler.java @@ -14,11 +14,10 @@ import java.util.Map; @Component public class NullHandler extends AbstractHandler { - @Override - public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, - Map context, WxMpService wxMpService, - WxSessionManager sessionManager) { - return null; - } + @Override + public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map context, WxMpService wxMpService, + WxSessionManager sessionManager) { + return null; + } } diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/ScanHandler.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/ScanHandler.java index 0173764f6..a7c0c1108 100755 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/ScanHandler.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/ScanHandler.java @@ -15,10 +15,11 @@ import java.util.Map; @Component public class ScanHandler extends AbstractHandler { - @Override - public WxMpXmlOutMessage handle(WxMpXmlMessage wxMpXmlMessage, Map map, - WxMpService wxMpService, WxSessionManager wxSessionManager) throws WxErrorException { - // 扫码事件处理 - return null; - } + @Override + public WxMpXmlOutMessage handle(WxMpXmlMessage wxMpXmlMessage, Map map, WxMpService wxMpService, + WxSessionManager wxSessionManager) throws WxErrorException { + // 扫码事件处理 + return null; + } + } diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/StoreCheckNotifyHandler.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/StoreCheckNotifyHandler.java index 1d75ea153..f40b5431f 100755 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/StoreCheckNotifyHandler.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/StoreCheckNotifyHandler.java @@ -16,12 +16,11 @@ import java.util.Map; @Component public class StoreCheckNotifyHandler extends AbstractHandler { - @Override - public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, - Map context, WxMpService wxMpService, - WxSessionManager sessionManager) { - // TODO 处理门店审核事件 - return null; - } + @Override + public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map context, WxMpService wxMpService, + WxSessionManager sessionManager) { + // TODO 处理门店审核事件 + return null; + } } diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/SubscribeHandler.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/SubscribeHandler.java index 84ca137bf..4531c2c12 100755 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/SubscribeHandler.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/SubscribeHandler.java @@ -35,25 +35,26 @@ import java.util.Map; @Component @AllArgsConstructor public class SubscribeHandler extends AbstractHandler { + private final WxAutoReplyService wxAutoReplyService; + private final WxAccountFansMapper wxAccountFansMapper; + private final WxAccountMapper wxAccountMapper; + private final WxMsgMapper msgMapper; @Override - public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, - Map context, WxMpService weixinService, - WxSessionManager sessionManager) throws WxErrorException { + public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map context, WxMpService weixinService, + WxSessionManager sessionManager) throws WxErrorException { log.info("新关注用户 OPENID: " + wxMessage.getFromUser()); - // 获取微信用户基本信息 try { - WxMpUser wxMpUser = weixinService.getUserService() - .userInfo(wxMessage.getFromUser(), null); - WxAccountFans wxAccountFans = wxAccountFansMapper.selectOne(Wrappers - .lambdaUpdate().eq(WxAccountFans::getOpenid, wxMessage.getFromUser())); + WxMpUser wxMpUser = weixinService.getUserService().userInfo(wxMessage.getFromUser(), null); + WxAccountFans wxAccountFans = wxAccountFansMapper.selectOne( + Wrappers.lambdaUpdate().eq(WxAccountFans::getOpenid, wxMessage.getFromUser())); if (wxAccountFans != null) { wxAccountFansMapper.deleteById(wxAccountFans); @@ -62,8 +63,7 @@ public class SubscribeHandler extends AbstractHandler { wxAccountFans.setOpenid(wxMpUser.getOpenId()); wxAccountFans.setSubscribeStatus(String.valueOf(BooleanUtil.toInt(wxMpUser.getSubscribe()))); wxAccountFans.setSubscribeTime(LocalDateTime - .ofInstant(Instant.ofEpochMilli(wxMpUser.getSubscribeTime() * 1000L) - , ZoneId.systemDefault())); + .ofInstant(Instant.ofEpochMilli(wxMpUser.getSubscribeTime() * 1000L), ZoneId.systemDefault())); wxAccountFans.setNickname(wxMpUser.getNickname()); wxAccountFans.setGender(String.valueOf(wxMpUser.getSex())); wxAccountFans.setLanguage(wxMpUser.getLanguage()); @@ -73,15 +73,16 @@ public class SubscribeHandler extends AbstractHandler { wxAccountFans.setHeadimgUrl(wxMpUser.getHeadImgUrl()); wxAccountFans.setRemark(wxMpUser.getRemark()); - WxAccount wxAccount = wxAccountMapper.selectOne(Wrappers.lambdaQuery() - .eq(WxAccount::getAppid, WxMpContextHolder.getAppId())); + WxAccount wxAccount = wxAccountMapper + .selectOne(Wrappers.lambdaQuery().eq(WxAccount::getAppid, WxMpContextHolder.getAppId())); wxAccountFans.setWxAccountId(wxAccount.getId()); wxAccountFans.setWxAccountAppid(wxAccount.getAppid()); wxAccountFans.setWxAccountName(wxAccount.getName()); wxAccountFansMapper.insert(wxAccountFans); return this.handleSpecial(wxMessage, wxAccountFans); - } catch (WxErrorException e) { + } + catch (WxErrorException e) { log.error("该公众号没有获取用户信息失败!", e); } @@ -92,14 +93,15 @@ public class SubscribeHandler extends AbstractHandler { * 处理特殊请求,比如如果是扫码进来的,可以做相应处理 */ private WxMpXmlOutMessage handleSpecial(WxMpXmlMessage wxMessage, WxAccountFans fans) { - //发送关注消息 - List listWxAutoReply = wxAutoReplyService.list(Wrappers.query().lambda() - .eq(WxAutoReply::getType, ReplyTypeEnum.ATTENTION.getType()) - .eq(WxAutoReply::getAppId,WxMpContextHolder.getAppId())); + // 发送关注消息 + List listWxAutoReply = wxAutoReplyService + .list(Wrappers.query().lambda().eq(WxAutoReply::getType, ReplyTypeEnum.ATTENTION.getType()) + .eq(WxAutoReply::getAppId, WxMpContextHolder.getAppId())); // 查询公众号 基本信息 - WxAccount wxAccount = wxAccountMapper.selectOne(Wrappers.lambdaQuery() - .eq(WxAccount::getAccount, wxMessage.getToUser())); - WxMpXmlOutMessage wxMpXmlOutMessage = MsgHandler.getWxMpXmlOutMessage(wxMessage, listWxAutoReply, fans, msgMapper, wxAccount); + WxAccount wxAccount = wxAccountMapper + .selectOne(Wrappers.lambdaQuery().eq(WxAccount::getAccount, wxMessage.getToUser())); + WxMpXmlOutMessage wxMpXmlOutMessage = MsgHandler.getWxMpXmlOutMessage(wxMessage, listWxAutoReply, fans, + msgMapper, wxAccount); return wxMpXmlOutMessage; } diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/UnsubscribeHandler.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/UnsubscribeHandler.java index 2bc1d7c1c..3a6d4a30a 100755 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/UnsubscribeHandler.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/handler/UnsubscribeHandler.java @@ -21,19 +21,18 @@ import java.util.Map; @Component @AllArgsConstructor public class UnsubscribeHandler extends AbstractHandler { + private final WxAccountFansMapper wxAccountFansMapper; - @Override - public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, - Map context, WxMpService wxMpService, - WxSessionManager sessionManager) { - String openId = wxMessage.getFromUser(); - log.info("取消关注用户 OPENID: " + openId); + @Override + public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map context, WxMpService wxMpService, + WxSessionManager sessionManager) { + String openId = wxMessage.getFromUser(); + log.info("取消关注用户 OPENID: " + openId); WxAccountFans fans = new WxAccountFans(); fans.setSubscribeStatus(SubStatusEnum.UNSUB.getType()); - wxAccountFansMapper.update(fans, Wrappers - .lambdaUpdate().eq(WxAccountFans::getOpenid,openId)); - return null; - } + wxAccountFansMapper.update(fans, Wrappers.lambdaUpdate().eq(WxAccountFans::getOpenid, openId)); + return null; + } } diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/mapper/WxMsgMapper.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/mapper/WxMsgMapper.java index 6be2a0562..e1065e52c 100644 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/mapper/WxMsgMapper.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/mapper/WxMsgMapper.java @@ -12,4 +12,5 @@ import org.apache.ibatis.annotations.Mapper; */ @Mapper public interface WxMsgMapper extends BaseMapper { + } diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/service/WxAccountFansService.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/service/WxAccountFansService.java index 5094ba7dd..d855f560f 100755 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/service/WxAccountFansService.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/service/WxAccountFansService.java @@ -29,9 +29,9 @@ public interface WxAccountFansService extends IService { /** * 同步指定公众号粉丝 - * * @param appId * @return */ Boolean syncAccountFans(String appId); + } diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/service/WxAccountService.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/service/WxAccountService.java index ab59a9601..100958ef8 100755 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/service/WxAccountService.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/service/WxAccountService.java @@ -30,7 +30,6 @@ public interface WxAccountService extends IService { /** * 生成公众号二维码 - * * @param appId * @return */ @@ -38,10 +37,10 @@ public interface WxAccountService extends IService { /** * 获取公众号统计数据 - * * @param appId * @param interval * @return */ R statistics(String appId, String interval); + } diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/service/WxMenuService.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/service/WxMenuService.java index 2ac0956a3..a36e92b12 100755 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/service/WxMenuService.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/service/WxMenuService.java @@ -31,16 +31,14 @@ public interface WxMenuService extends IService { /** * 新增微信公众号按钮 - * * @param wxMenus json - * @param appId 公众号信息 + * @param appId 公众号信息 * @return */ Boolean save(JSONObject wxMenus, String appId); /** * 发布到微信 - * * @param appId 公众号信息 * @return */ @@ -48,7 +46,6 @@ public interface WxMenuService extends IService { /** * 通过appid 查询菜单信息 - * * @param appId * @return */ @@ -60,4 +57,5 @@ public interface WxMenuService extends IService { * @return */ R delete(String appId); + } diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/service/WxMsgService.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/service/WxMsgService.java index e39b92819..af7a5eb68 100644 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/service/WxMsgService.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/service/WxMsgService.java @@ -14,9 +14,9 @@ public interface WxMsgService extends IService { /** * 保存信息并向用户推送 - * * @param wxMsg * @return */ R saveAndPushMsg(WxMsg wxMsg); + } diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/service/impl/WxAccountFansServiceImpl.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/service/impl/WxAccountFansServiceImpl.java index 85d658864..bf9578464 100755 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/service/impl/WxAccountFansServiceImpl.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/service/impl/WxAccountFansServiceImpl.java @@ -54,13 +54,15 @@ import java.util.List; @Slf4j @Service @AllArgsConstructor -public class WxAccountFansServiceImpl extends ServiceImpl implements WxAccountFansService { +public class WxAccountFansServiceImpl extends ServiceImpl + implements WxAccountFansService { + private static final int SIZE = 100; + private final WxAccountMapper wxAccountMapper; /** * 获取公众号粉丝,生产建议异步 - * * @param appId * @return */ @@ -70,68 +72,65 @@ public class WxAccountFansServiceImpl extends ServiceImplquery().lambda() - .eq(WxAccount::getAppid, appId)); + .selectOne(Wrappers.query().lambda().eq(WxAccount::getAppid, appId)); // 获取操作微信接口类 WxMpService wxMpService = WxMpInitConfigRunner.getMpServices().get(appId); WxMpUserService wxMpUserService = wxMpService.getUserService(); - TenantBroker.runAs(()->WxMpInitConfigRunner.getTenants().get(appId),(id)->fetchUser(null, wxAccount, wxMpUserService)); + TenantBroker.runAs(() -> WxMpInitConfigRunner.getTenants().get(appId), + (id) -> fetchUser(null, wxAccount, wxMpUserService)); return Boolean.TRUE; } /** * 获取微信用户 - * * @param nextOpenid * @param wxAccount * @param wxMpUserService * @throws WxErrorException */ - private void fetchUser(String nextOpenid, WxAccount wxAccount, WxMpUserService wxMpUserService) throws WxErrorException { + private void fetchUser(String nextOpenid, WxAccount wxAccount, WxMpUserService wxMpUserService) + throws WxErrorException { WxMpUserList wxMpUserList = wxMpUserService.userList(nextOpenid); // openId 分组 每组 100个 openid - CollUtil.split(wxMpUserList.getOpenids(), SIZE) - .stream().filter(CollUtil::isNotEmpty) - .forEach(openIdList -> { - log.info("开始批量获取用户信息 {}", openIdList); - List wxAccountFansList = new ArrayList<>(); - try { - wxMpUserService.userInfoList(openIdList).forEach(wxMpUser -> { - WxAccountFans wxAccountFans = baseMapper - .selectOne(Wrappers.query().lambda() - .eq(WxAccountFans::getOpenid, wxMpUser.getOpenId())); - // 为空初始化一个新的对象 - if (wxAccountFans == null) { - wxAccountFans = new WxAccountFans(); - } - - wxAccountFans.setOpenid(wxMpUser.getOpenId()); - wxAccountFans.setSubscribeStatus(String.valueOf(BooleanUtil.toInt(wxMpUser.getSubscribe()))); - wxAccountFans.setSubscribeTime(LocalDateTime - .ofInstant(Instant.ofEpochMilli(wxMpUser.getSubscribeTime() * 1000L) - , ZoneId.systemDefault())); - wxAccountFans.setNickname(wxMpUser.getNickname()); - wxAccountFans.setGender(String.valueOf(wxMpUser.getSex())); - wxAccountFans.setLanguage(wxMpUser.getLanguage()); - wxAccountFans.setCountry(wxMpUser.getCountry()); - wxAccountFans.setProvince(wxMpUser.getProvince()); - wxAccountFans.setCity(wxMpUser.getCity()); - wxAccountFans.setHeadimgUrl(wxMpUser.getHeadImgUrl()); - wxAccountFans.setRemark(wxMpUser.getRemark()); - wxAccountFans.setWxAccountId(wxAccount.getId()); - wxAccountFans.setWxAccountAppid(wxAccount.getAppid()); - wxAccountFans.setWxAccountName(wxAccount.getName()); - wxAccountFansList.add(wxAccountFans); - }); - this.saveOrUpdateBatch(wxAccountFansList); - log.info("批量插入用户信息完成 {}", openIdList); - } catch (WxErrorException e) { - log.error("批量同步粉丝失败", e); + CollUtil.split(wxMpUserList.getOpenids(), SIZE).stream().filter(CollUtil::isNotEmpty).forEach(openIdList -> { + log.info("开始批量获取用户信息 {}", openIdList); + List wxAccountFansList = new ArrayList<>(); + try { + wxMpUserService.userInfoList(openIdList).forEach(wxMpUser -> { + WxAccountFans wxAccountFans = baseMapper.selectOne(Wrappers.query().lambda() + .eq(WxAccountFans::getOpenid, wxMpUser.getOpenId())); + // 为空初始化一个新的对象 + if (wxAccountFans == null) { + wxAccountFans = new WxAccountFans(); } + + wxAccountFans.setOpenid(wxMpUser.getOpenId()); + wxAccountFans.setSubscribeStatus(String.valueOf(BooleanUtil.toInt(wxMpUser.getSubscribe()))); + wxAccountFans.setSubscribeTime(LocalDateTime.ofInstant( + Instant.ofEpochMilli(wxMpUser.getSubscribeTime() * 1000L), ZoneId.systemDefault())); + wxAccountFans.setNickname(wxMpUser.getNickname()); + wxAccountFans.setGender(String.valueOf(wxMpUser.getSex())); + wxAccountFans.setLanguage(wxMpUser.getLanguage()); + wxAccountFans.setCountry(wxMpUser.getCountry()); + wxAccountFans.setProvince(wxMpUser.getProvince()); + wxAccountFans.setCity(wxMpUser.getCity()); + wxAccountFans.setHeadimgUrl(wxMpUser.getHeadImgUrl()); + wxAccountFans.setRemark(wxMpUser.getRemark()); + wxAccountFans.setWxAccountId(wxAccount.getId()); + wxAccountFans.setWxAccountAppid(wxAccount.getAppid()); + wxAccountFans.setWxAccountName(wxAccount.getName()); + wxAccountFansList.add(wxAccountFans); }); + this.saveOrUpdateBatch(wxAccountFansList); + log.info("批量插入用户信息完成 {}", openIdList); + } + catch (WxErrorException e) { + log.error("批量同步粉丝失败", e); + } + }); // 如果nextOpenId 不为空,则继续获取 if (StrUtil.isNotBlank(wxMpUserList.getNextOpenid())) { @@ -140,4 +139,5 @@ public class WxAccountFansServiceImpl extends ServiceImplquery().lambda() - .eq(WxAccount::getAppid, appId)); + .selectOne(Wrappers.query().lambda().eq(WxAccount::getAppid, appId)); wxAccount.setQrUrl(url); baseMapper.updateById(wxAccount); - } catch (WxErrorException e) { + } + catch (WxErrorException e) { log.error(" 获取公众号二维码失败", e); return R.failed("更新公众号二维码失败"); } @@ -79,8 +78,7 @@ public class WxAccountServiceImpl extends ServiceImpl cumulateList = cubeService.getUserCumulate(start, end).stream() - .map(WxDataCubeUserCumulate::getCumulateUser) - .collect(Collectors.toList()); + .map(WxDataCubeUserCumulate::getCumulateUser).collect(Collectors.toList()); result.add(cumulateList); // 获取用户分享数据 List shareList = cubeService.getUserShare(start, end).stream() - .map(WxDataCubeArticleResult::getShareCount) - .collect(Collectors.toList()); + .map(WxDataCubeArticleResult::getShareCount).collect(Collectors.toList()); result.add(shareList); // 获取消息发送概况数据 List upstreamList = cubeService.getUpstreamMsg(start, end).stream() - .map(WxDataCubeMsgResult::getMsgCount) - .collect(Collectors.toList()); + .map(WxDataCubeMsgResult::getMsgCount).collect(Collectors.toList()); result.add(upstreamList); // 获取接口调用概况数据 List interfaceSummaryList = cubeService.getInterfaceSummary(start, end); - List interfaceList = interfaceSummaryList.stream() - .map(WxDataCubeInterfaceResult::getCallbackCount) + List interfaceList = interfaceSummaryList.stream().map(WxDataCubeInterfaceResult::getCallbackCount) .collect(Collectors.toList()); result.add(interfaceList); // 接口日期保存 - List dateList = interfaceSummaryList.stream() - .map(WxDataCubeInterfaceResult::getRefDate) + List dateList = interfaceSummaryList.stream().map(WxDataCubeInterfaceResult::getRefDate) .collect(Collectors.toList()); result.add(dateList); - } catch (WxErrorException e) { + } + catch (WxErrorException e) { log.error(" 获取公众号统计数据报错", e); return R.failed("获取公众号数据失败:" + e.getError().getErrorMsg()); } return R.ok(); } + } diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/service/impl/WxMenuServiceImpl.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/service/impl/WxMenuServiceImpl.java index 40700d374..466760bce 100755 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/service/impl/WxMenuServiceImpl.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/service/impl/WxMenuServiceImpl.java @@ -47,25 +47,24 @@ import java.util.List; @Service @AllArgsConstructor public class WxMenuServiceImpl extends ServiceImpl implements WxMenuService { + private static final String PUB_ED = "1"; + private final WxAccountMapper wxAccountMapper; /** * 新增微信公众号按钮 - * * @param wxMenus json - * @param appId 公众号 + * @param appId 公众号 * @return */ @Override @Transactional(rollbackFor = Exception.class) public Boolean save(JSONObject wxMenus, String appId) { - baseMapper.delete(Wrappers.lambdaQuery() - .eq(WxMpMenu::getWxAccountAppid, appId)); + baseMapper.delete(Wrappers.lambdaQuery().eq(WxMpMenu::getWxAccountAppid, appId)); WxAccount wxAccount = wxAccountMapper - .selectOne(Wrappers.lambdaQuery() - .eq(WxAccount::getAppid, appId)); + .selectOne(Wrappers.lambdaQuery().eq(WxAccount::getAppid, appId)); WxMpMenu wxMpMenu = new WxMpMenu(); wxMpMenu.setMenu(wxMenus.toStringPretty()); wxMpMenu.setWxAccountId(wxAccount.getId()); @@ -77,14 +76,13 @@ public class WxMenuServiceImpl extends ServiceImpl imple /** * 发布到微信 - * * @param appId 公众号信息 * @return */ @Override public R push(String appId) { - List wxMpMenuList = baseMapper.selectList(Wrappers.lambdaQuery() - .eq(WxMpMenu::getWxAccountAppid, appId)); + List wxMpMenuList = baseMapper + .selectList(Wrappers.lambdaQuery().eq(WxMpMenu::getWxAccountAppid, appId)); if (CollUtil.isEmpty(wxMpMenuList)) { return R.failed("微信菜单配置未保存,不能发布"); @@ -100,12 +98,13 @@ public class WxMenuServiceImpl extends ServiceImpl imple // 给数据库保存的加一层 try { menuService.menuCreate(wxMpMenu.getMenu()); - } catch (WxErrorException e) { + } + catch (WxErrorException e) { log.error("发布微信菜单失败", e.getError().getErrorMsg()); return R.failed(e.getError().getErrorMsg()); } - //更新菜单发布标志 + // 更新菜单发布标志 wxMpMenu.setPubFlag(PUB_ED); baseMapper.updateById(wxMpMenu); return R.ok(); @@ -113,14 +112,13 @@ public class WxMenuServiceImpl extends ServiceImpl imple /** * 通过appid 查询菜单信息 - * * @param appId * @return */ @Override public R getByAppId(String appId) { - List wxMpMenuList = baseMapper.selectList(Wrappers.lambdaQuery() - .eq(WxMpMenu::getWxAccountAppid, appId)); + List wxMpMenuList = baseMapper + .selectList(Wrappers.lambdaQuery().eq(WxMpMenu::getWxAccountAppid, appId)); if (CollUtil.isEmpty(wxMpMenuList)) { return R.ok(); @@ -130,7 +128,6 @@ public class WxMenuServiceImpl extends ServiceImpl imple /** * 通过appid 删除菜单 - * * @param appId * @return */ @@ -140,13 +137,14 @@ public class WxMenuServiceImpl extends ServiceImpl imple WxMpMenuService menuService = wxMpService.getMenuService(); try { menuService.menuDelete(); - } catch (WxErrorException e) { + } + catch (WxErrorException e) { log.error("微信菜单删除失败", e.getError().getErrorMsg()); return R.failed(e.getError().getErrorMsg()); } - baseMapper.delete(Wrappers.lambdaQuery() - .eq(WxMpMenu::getWxAccountAppid, appId)); + baseMapper.delete(Wrappers.lambdaQuery().eq(WxMpMenu::getWxAccountAppid, appId)); return R.ok(); } + } diff --git a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/service/impl/WxMsgServiceImpl.java b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/service/impl/WxMsgServiceImpl.java index afd530986..c2d8a5c72 100644 --- a/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/service/impl/WxMsgServiceImpl.java +++ b/pigx-visual/pigx-mp-platform/src/main/java/com/pig4cloud/pigx/mp/service/impl/WxMsgServiceImpl.java @@ -37,12 +37,13 @@ import java.util.List; public class WxMsgServiceImpl extends ServiceImpl implements WxMsgService { private final WxAccountFansMapper accountFansMapper; + private final WxAccountMapper accountMapper; + private final WxMsgMapper msgMapper; /** * 保存信息并向用户推送 - * * @param wxMsg 推送消息内容 * @return */ @@ -50,15 +51,15 @@ public class WxMsgServiceImpl extends ServiceImpl implements public R saveAndPushMsg(WxMsg wxMsg) { // 查询用户详细 WxAccountFans wxUser = accountFansMapper.selectById(wxMsg.getWxUserId()); - WxAccount wxAccount = accountMapper.selectOne(Wrappers.lambdaQuery() - .eq(WxAccount::getAppid, wxMsg.getAppId())); + WxAccount wxAccount = accountMapper + .selectOne(Wrappers.lambdaQuery().eq(WxAccount::getAppid, wxMsg.getAppId())); - //维护消息-用户 + // 维护消息-用户 wxMsg.setNickName(wxUser.getNickname()); wxMsg.setHeadimgUrl(wxUser.getHeadimgUrl()); wxMsg.setType(MsgTypeEnum.MP2USER.getType()); - //维护消息-公众号 + // 维护消息-公众号 wxMsg.setAppLogo(wxAccount.getQrUrl()); wxMsg.setAppName(wxAccount.getName()); @@ -69,7 +70,7 @@ public class WxMsgServiceImpl extends ServiceImpl implements wxMpKefuMessage.setContent(wxMsg.getRepContent()); } - if (WxConsts.KefuMsgType.IMAGE.equals(wxMsg.getRepType())) {//图片 + if (WxConsts.KefuMsgType.IMAGE.equals(wxMsg.getRepType())) {// 图片 wxMsg.setRepName(wxMsg.getRepName()); wxMsg.setRepUrl(wxMsg.getRepUrl()); wxMsg.setRepMediaId(wxMsg.getRepMediaId()); @@ -135,7 +136,6 @@ public class WxMsgServiceImpl extends ServiceImpl implements return R.failed("非法消息类型"); } - WxMpService wxMpService = WxMpInitConfigRunner.getMpServices().get(wxMsg.getAppId()); WxMpKefuService wxMpKefuService = wxMpService.getKefuService(); wxMpKefuMessage.setToUser(wxUser.getOpenid()); @@ -143,8 +143,10 @@ public class WxMsgServiceImpl extends ServiceImpl implements wxMpKefuService.sendKefuMessage(wxMpKefuMessage); msgMapper.insert(wxMsg); return R.ok(wxMsg); - } catch (WxErrorException e) { + } + catch (WxErrorException e) { return R.failed(e.getError().getErrorMsg()); } } + } diff --git a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/PigxActivitiApplication.java b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/PigxActivitiApplication.java index e7af829dc..927fbd55e 100644 --- a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/PigxActivitiApplication.java +++ b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/PigxActivitiApplication.java @@ -25,8 +25,7 @@ import org.springframework.cloud.client.SpringCloudApplication; /** * @author lengleng - * @date 2018/9/25 - * 工作流管理模块 + * @date 2018/9/25 工作流管理模块 */ @EnablePigxSwagger2 @EnablePigxFeignClients diff --git a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/config/ActivitiConfig.java b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/config/ActivitiConfig.java index d3e35deb3..d29db9fd3 100644 --- a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/config/ActivitiConfig.java +++ b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/config/ActivitiConfig.java @@ -30,19 +30,19 @@ import javax.sql.DataSource; /** * @author lengleng - * @date 2018/9/25 - * Activiti 配置 + * @date 2018/9/25 Activiti 配置 */ @Configuration @AllArgsConstructor public class ActivitiConfig { + private final DataSource dataSource; + private final PlatformTransactionManager transactionManager; @Bean public SpringProcessEngineConfiguration getProcessEngineConfiguration() { - SpringProcessEngineConfiguration config = - new SpringProcessEngineConfiguration(); + SpringProcessEngineConfiguration config = new SpringProcessEngineConfiguration(); // 流程图字体设置 config.setActivityFontName("宋体"); config.setAnnotationFontName("宋体"); @@ -60,4 +60,5 @@ public class ActivitiConfig { public TaskExecutor primaryTaskExecutor() { return new ThreadPoolTaskExecutor(); } + } diff --git a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/config/WebSocketConfig.java b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/config/WebSocketConfig.java index 0ef236ba7..4cece5cc0 100644 --- a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/config/WebSocketConfig.java +++ b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/config/WebSocketConfig.java @@ -30,13 +30,12 @@ import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerCo @AllArgsConstructor @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { + private RemoteTokenServices tokenService; @Override public void registerStompEndpoints(StompEndpointRegistry registry) { - registry.addEndpoint("/ws") - .setAllowedOrigins("*") - .withSockJS(); + registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS(); } @Override @@ -63,13 +62,15 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { SecurityContextHolder.getContext().setAuthentication(auth2Authentication); accessor.setUser(() -> auth2Authentication.getName()); return message; - } else { + } + else { return null; } } - //不是首次连接,已经成功登陆 + // 不是首次连接,已经成功登陆 return message; } }); } + } diff --git a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/controller/EditorController.java b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/controller/EditorController.java index c66cb683f..353599e29 100644 --- a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/controller/EditorController.java +++ b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/controller/EditorController.java @@ -31,6 +31,7 @@ import org.springframework.web.bind.annotation.*; @AllArgsConstructor @RequestMapping("/service") public class EditorController { + private final EditorService editorService; @GetMapping("/editor/stencilset") @@ -45,7 +46,8 @@ public class EditorController { @PutMapping("/model/{modelId}/save") public void saveModel(@PathVariable(value = "modelId") String modelId, String name, String description, - @RequestParam("json_xml") String jsonXml, @RequestParam("svg_xml") String svgXml) { + @RequestParam("json_xml") String jsonXml, @RequestParam("svg_xml") String svgXml) { editorService.saveModel(modelId, name, description, jsonXml, svgXml); } + } diff --git a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/controller/LeaveBillController.java b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/controller/LeaveBillController.java index c547b8aeb..f1bd25bb2 100755 --- a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/controller/LeaveBillController.java +++ b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/controller/LeaveBillController.java @@ -28,7 +28,6 @@ import com.pig4cloud.pigx.common.security.util.SecurityUtils; import lombok.AllArgsConstructor; import org.springframework.web.bind.annotation.*; - /** * 请假流程 * @@ -39,13 +38,14 @@ import org.springframework.web.bind.annotation.*; @AllArgsConstructor @RequestMapping("/leave-bill") public class LeaveBillController { + private final LeaveBillService leaveBillService; + private final ProcessService processService; /** * 请假审批单简单分页查询 - * - * @param page 分页对象 + * @param page 分页对象 * @param leaveBill 请假审批单 * @return */ @@ -54,10 +54,8 @@ public class LeaveBillController { return R.ok(leaveBillService.page(page, Wrappers.query(leaveBill))); } - /** * 信息 - * * @param leaveId * @return R */ @@ -68,7 +66,6 @@ public class LeaveBillController { /** * 保存 - * * @param leaveBill * @return R */ @@ -81,7 +78,6 @@ public class LeaveBillController { /** * 修改 - * * @param leaveBill * @return R */ @@ -92,7 +88,6 @@ public class LeaveBillController { /** * 删除 - * * @param leaveId * @return R */ @@ -103,7 +98,6 @@ public class LeaveBillController { /** * 提交请假流程 - * * @param leaveId * @return R */ @@ -111,4 +105,5 @@ public class LeaveBillController { public R submit(@PathVariable("leaveId") Integer leaveId) { return R.ok(processService.saveStartProcess(leaveId)); } + } diff --git a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/controller/ModelController.java b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/controller/ModelController.java index b816fbc4a..47cff6f66 100644 --- a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/controller/ModelController.java +++ b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/controller/ModelController.java @@ -34,6 +34,7 @@ import java.util.Map; @RequestMapping("/model") @AllArgsConstructor public class ModelController { + private final ModelService modelService; @PostMapping(value = "/insert") @@ -43,8 +44,8 @@ public class ModelController { } @PostMapping - public R createModel(@RequestParam String name, @RequestParam String key, - @RequestParam String desc, @RequestParam String category) { + public R createModel(@RequestParam String name, @RequestParam String key, @RequestParam String desc, + @RequestParam String category) { return R.ok(modelService.create(name, key, desc, category)); } @@ -63,4 +64,5 @@ public class ModelController { public R deploy(@PathVariable("id") String id) { return modelService.deploy(id) ? R.ok() : R.failed(); } + } diff --git a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/controller/ProcessController.java b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/controller/ProcessController.java index c4d8648e6..28dce47ca 100644 --- a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/controller/ProcessController.java +++ b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/controller/ProcessController.java @@ -40,6 +40,7 @@ import java.util.Map; @AllArgsConstructor @RequestMapping("/process") public class ProcessController { + private final ProcessService processService; @GetMapping @@ -49,13 +50,15 @@ public class ProcessController { @Inner(value = false) @GetMapping(value = "/resource/{proInsId}/{procDefId}/{resType}") - public ResponseEntity resourceRead(@PathVariable String procDefId, @PathVariable String proInsId, @PathVariable String resType) { + public ResponseEntity resourceRead(@PathVariable String procDefId, @PathVariable String proInsId, + @PathVariable String resType) { HttpHeaders headers = new HttpHeaders(); if (ResourceTypeEnum.XML.getType().equals(resType)) { headers.setContentType(MediaType.APPLICATION_XML); - } else { + } + else { headers.setContentType(MediaType.IMAGE_PNG); } @@ -72,4 +75,5 @@ public class ProcessController { public R deleteProcIns(@PathVariable String deploymentId) { return R.ok(processService.removeProcIns(deploymentId)); } + } diff --git a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/controller/TaskController.java b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/controller/TaskController.java index 54334e10e..148544289 100644 --- a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/controller/TaskController.java +++ b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/controller/TaskController.java @@ -41,6 +41,7 @@ import java.util.Map; @AllArgsConstructor @RequestMapping("/task") public class TaskController { + private final ActTaskService actTaskService; @GetMapping("/todo") @@ -72,5 +73,4 @@ public class TaskController { return R.ok(actTaskService.getCommentByTaskId(id)); } - } diff --git a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/dto/CommentDto.java b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/dto/CommentDto.java index d3514cd50..5565caf30 100644 --- a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/dto/CommentDto.java +++ b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/dto/CommentDto.java @@ -23,11 +23,11 @@ import java.util.Date; /** * @author lengleng - * @date 2018/9/28 - * 批注Dto + * @date 2018/9/28 批注Dto */ @Data public class CommentDto { + /** * unique identifier for this comment */ @@ -62,4 +62,5 @@ public class CommentDto { * the full comment message the user had related to the task and/or process instance */ private String fullMessage; + } diff --git a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/dto/LeaveBillDto.java b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/dto/LeaveBillDto.java index 1b98c8cab..d446ffc8c 100644 --- a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/dto/LeaveBillDto.java +++ b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/dto/LeaveBillDto.java @@ -26,12 +26,12 @@ import java.util.List; /** * @author lengleng - * @date 2018/9/28 - * LeaveBillDto + * @date 2018/9/28 LeaveBillDto */ @Data @EqualsAndHashCode(callSuper = true) public class LeaveBillDto extends LeaveBill { + /** * 任务ID */ @@ -53,4 +53,5 @@ public class LeaveBillDto extends LeaveBill { private List flagList; private String taskFlag; + } diff --git a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/dto/ModelForm.java b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/dto/ModelForm.java index 08f026918..d860e23a1 100644 --- a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/dto/ModelForm.java +++ b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/dto/ModelForm.java @@ -17,7 +17,6 @@ package com.pig4cloud.pigx.act.dto; - import javax.validation.constraints.NotBlank; /** @@ -69,4 +68,5 @@ public class ModelForm { public void setDesc(String desc) { this.desc = desc; } + } diff --git a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/dto/ProcessDefDTO.java b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/dto/ProcessDefDTO.java index b8a7d0e08..0e2574355 100644 --- a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/dto/ProcessDefDTO.java +++ b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/dto/ProcessDefDTO.java @@ -27,26 +27,39 @@ import org.activiti.engine.repository.ProcessDefinition; */ @Data public class ProcessDefDTO { - private String category; - private String processonDefinitionId; - private String key; - private String name; - private Integer revision; - private Long deploymentTime; - private String xmlName; - private String picName; - private String deploymentId; - private Boolean suspend; - private String description; - private Integer xAxis; - private Integer yAxis; - private Integer width; - private Integer height; + private String category; + + private String processonDefinitionId; + + private String key; + + private String name; + + private Integer revision; + + private Long deploymentTime; + + private String xmlName; + + private String picName; + + private String deploymentId; + + private Boolean suspend; + + private String description; + + private Integer xAxis; + + private Integer yAxis; + + private Integer width; + + private Integer height; /** * 抽取流程定义需要返回的内容 - * * @param processDefinition * @param deployment * @return @@ -66,4 +79,5 @@ public class ProcessDefDTO { dto.setDescription(processDefinition.getDescription()); return dto; } + } diff --git a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/dto/StartTaskForm.java b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/dto/StartTaskForm.java index af6b25cd4..6302ff64a 100644 --- a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/dto/StartTaskForm.java +++ b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/dto/StartTaskForm.java @@ -27,10 +27,15 @@ import javax.validation.constraints.NotEmpty; */ @Data public class StartTaskForm { + @NotEmpty public String procDefKey; + public String entityId; + @NotEmpty public String title; + public String comment; + } diff --git a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/dto/TaskDTO.java b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/dto/TaskDTO.java index 82b374069..1521ecc5f 100644 --- a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/dto/TaskDTO.java +++ b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/dto/TaskDTO.java @@ -27,16 +27,29 @@ import java.util.Date; */ @Data public class TaskDTO { + private String applicant; + private String taskId; + private String taskName; + private String title; + private String pdName; + private String version; + private Date time; + private String processInstanceId; + private String status; + private String nodeKey; + private String processDefKey; + private String category; + } diff --git a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/entity/LeaveBill.java b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/entity/LeaveBill.java index bc5e5060f..43fcf0aa7 100755 --- a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/entity/LeaveBill.java +++ b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/entity/LeaveBill.java @@ -38,6 +38,7 @@ import java.time.LocalDateTime; @TableName("oa_leave_bill") @EqualsAndHashCode(callSuper = true) public class LeaveBill extends Model { + private static final long serialVersionUID = 1L; /** @@ -45,34 +46,42 @@ public class LeaveBill extends Model { */ @TableId(type = IdType.AUTO) private Integer leaveId; + /** * 申请人 */ private String username; + /** * 天数 */ private Integer days; + /** * 备注 */ private String content; + /** * 0-未提交,1-未审核,2-批准,9-驳回 */ private String state; + /** * 提交时间 */ private LocalDateTime leaveTime; + /** * 提交时间 */ private LocalDateTime createTime; + /** * 修改时间 */ private LocalDateTime updateTime; + /** * 删除标志 */ @@ -91,4 +100,5 @@ public class LeaveBill extends Model { protected Serializable pkVal() { return this.leaveId; } + } diff --git a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/listener/LeaveProcessTaskListener.java b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/listener/LeaveProcessTaskListener.java index 0384bdeb3..3537cfaea 100644 --- a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/listener/LeaveProcessTaskListener.java +++ b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/listener/LeaveProcessTaskListener.java @@ -35,15 +35,13 @@ import java.util.stream.Collectors; /** * @author lengleng - * @date 2018/9/27 - * 请假流程监听器 + * @date 2018/9/27 请假流程监听器 */ @Slf4j public class LeaveProcessTaskListener implements TaskListener { /** * 查询提交人的上级 - * * @param delegateTask */ @Override @@ -58,7 +56,8 @@ public class LeaveProcessTaskListener implements TaskListener { log.info("用户 {} 不存在上级,任务单由当前用户审批", SecurityUtils.getUser().getUsername()); delegateTask.addCandidateUser(SecurityUtils.getUser().getUsername()); remindUserList.add(SecurityUtils.getUser().getUsername()); - } else { + } + else { List userList = result.getData().stream().map(SysUser::getUsername).collect(Collectors.toList()); log.info("当前任务 {},由 {}处理", delegateTask.getId(), userList); delegateTask.addCandidateUsers(userList); @@ -66,8 +65,10 @@ public class LeaveProcessTaskListener implements TaskListener { } remindUserList.forEach(user -> { - String target = String.format("%s-%s", SecurityUtils.getUser().getUsername(), TenantContextHolder.getTenantId()); + String target = String.format("%s-%s", SecurityUtils.getUser().getUsername(), + TenantContextHolder.getTenantId()); simpMessagingTemplate.convertAndSendToUser(target, "/remind", delegateTask.getName()); }); } + } diff --git a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/service/ActTaskService.java b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/service/ActTaskService.java index 71d06191f..2ffeb0ea5 100644 --- a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/service/ActTaskService.java +++ b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/service/ActTaskService.java @@ -31,10 +31,8 @@ import java.util.Map; */ public interface ActTaskService { - /** * 获取用户代办列表 - * * @param params * @param name * @return @@ -43,7 +41,6 @@ public interface ActTaskService { /** * 通过任务ID查询任务信息关联申请单信息 - * * @param id * @return */ @@ -51,7 +48,6 @@ public interface ActTaskService { /** * 提交任务 - * * @param leaveBillDto * @return */ @@ -59,7 +55,6 @@ public interface ActTaskService { /** * 通过任务ID 查询批注信息 - * * @param taskId 任务ID * @return */ @@ -67,9 +62,9 @@ public interface ActTaskService { /** * 追踪图片节点 - * * @param id * @return */ InputStream viewByTaskId(String id); + } diff --git a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/service/EditorService.java b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/service/EditorService.java index 08ea962be..6cbad3659 100644 --- a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/service/EditorService.java +++ b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/service/EditorService.java @@ -22,16 +22,15 @@ package com.pig4cloud.pigx.act.service; * @date 2018/9/25 */ public interface EditorService { + /** * 获取设计器页面的json - * * @return */ Object getStencilset(); /** * 根据modelId获取model - * * @param modelId * @return */ @@ -46,4 +45,5 @@ public interface EditorService { * @param svgXml */ void saveModel(String modelId, String name, String description, String jsonXml, String svgXml); + } diff --git a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/service/LeaveBillService.java b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/service/LeaveBillService.java index 2132da649..57ac96b04 100755 --- a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/service/LeaveBillService.java +++ b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/service/LeaveBillService.java @@ -12,4 +12,3 @@ import com.pig4cloud.pigx.act.entity.LeaveBill; public interface LeaveBillService extends IService { } - diff --git a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/service/ModelService.java b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/service/ModelService.java index 510f382bc..b11aaec93 100644 --- a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/service/ModelService.java +++ b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/service/ModelService.java @@ -30,7 +30,6 @@ public interface ModelService { /** * 创建流程 - * * @param name * @param key * @param desc @@ -41,7 +40,6 @@ public interface ModelService { /** * 分页获取流程 - * * @param params * @return */ @@ -49,7 +47,6 @@ public interface ModelService { /** * 删除流程 - * * @param id * @return */ @@ -57,9 +54,9 @@ public interface ModelService { /** * 部署流程 - * * @param id * @return */ Boolean deploy(String id); + } diff --git a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/service/ProcessService.java b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/service/ProcessService.java index 93c29b17f..a714d3262 100644 --- a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/service/ProcessService.java +++ b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/service/ProcessService.java @@ -31,7 +31,6 @@ public interface ProcessService { /** * 分页流程列表 - * * @param params * @return */ @@ -39,7 +38,6 @@ public interface ProcessService { /** * 读取xml/image资源 - * * @param procDefId * @param proInsId * @param resType @@ -49,7 +47,6 @@ public interface ProcessService { /** * 更新状态 - * * @param status * @param procDefId * @return @@ -58,7 +55,6 @@ public interface ProcessService { /** * 删除流程实例 - * * @param deploymentId * @return */ @@ -66,9 +62,9 @@ public interface ProcessService { /** * 启动流程、更新请假单状态 - * * @param leaveId * @return */ Boolean saveStartProcess(Integer leaveId); + } diff --git a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/service/impl/ActTaskServiceImpl.java b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/service/impl/ActTaskServiceImpl.java index b8f822769..eaf92d7c5 100644 --- a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/service/impl/ActTaskServiceImpl.java +++ b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/service/impl/ActTaskServiceImpl.java @@ -62,12 +62,19 @@ import java.util.stream.Collectors; @Service @AllArgsConstructor public class ActTaskServiceImpl implements ActTaskService { + private static final String FLAG = "审批"; + private final LeaveBillMapper leaveBillMapper; + private final TaskService taskService; + private final RuntimeService runtimeService; + private final RepositoryService repositoryService; + private final HistoryService historyService; + private final ProcessEngineFactoryBean processEngine; @Override @@ -75,43 +82,38 @@ public class ActTaskServiceImpl implements ActTaskService { int page = MapUtil.getInt(params, PaginationConstants.CURRENT); int limit = MapUtil.getInt(params, PaginationConstants.SIZE); - TaskQuery taskQuery = taskService.createTaskQuery() - .taskCandidateOrAssigned(name) - .taskTenantId(String.valueOf(TenantContextHolder.getTenantId())); + TaskQuery taskQuery = taskService.createTaskQuery().taskCandidateOrAssigned(name) + .taskTenantId(String.valueOf(TenantContextHolder.getTenantId())); IPage result = new Page(page, limit); result.setTotal(taskQuery.count()); - List taskDTOList = taskQuery.orderByTaskCreateTime().desc() - .listPage((page - 1) * limit, limit).stream().map(task -> { - TaskDTO dto = new TaskDTO(); - dto.setTaskId(task.getId()); - dto.setTaskName(task.getName()); - dto.setProcessInstanceId(task.getProcessInstanceId()); - dto.setNodeKey(task.getTaskDefinitionKey()); - dto.setCategory(task.getCategory()); - dto.setTime(task.getCreateTime()); - return dto; - }).collect(Collectors.toList()); + List taskDTOList = taskQuery.orderByTaskCreateTime().desc().listPage((page - 1) * limit, limit) + .stream().map(task -> { + TaskDTO dto = new TaskDTO(); + dto.setTaskId(task.getId()); + dto.setTaskName(task.getName()); + dto.setProcessInstanceId(task.getProcessInstanceId()); + dto.setNodeKey(task.getTaskDefinitionKey()); + dto.setCategory(task.getCategory()); + dto.setTime(task.getCreateTime()); + return dto; + }).collect(Collectors.toList()); result.setRecords(taskDTOList); return result; } /** * 通过任务ID查询任务信息关联申请单信息 - * * @param taskId * @return */ @Override public LeaveBillDto getTaskById(String taskId) { - Task task = taskService.createTaskQuery() - .taskId(taskId) - .singleResult(); + Task task = taskService.createTaskQuery().taskId(taskId).singleResult(); - ProcessInstance pi = runtimeService.createProcessInstanceQuery() - .processInstanceId(task.getProcessInstanceId()) - .singleResult(); + ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()) + .singleResult(); String businessKey = pi.getBusinessKey(); if (StrUtil.isNotBlank(businessKey)) { @@ -131,7 +133,6 @@ public class ActTaskServiceImpl implements ActTaskService { /** * 提交任务 - * * @param leaveBillDto * @return */ @@ -141,9 +142,7 @@ public class ActTaskServiceImpl implements ActTaskService { String message = leaveBillDto.getComment(); Integer id = leaveBillDto.getLeaveId(); - Task task = taskService.createTaskQuery() - .taskId(taskId) - .singleResult(); + Task task = taskService.createTaskQuery().taskId(taskId).singleResult(); String processInstanceId = task.getProcessInstanceId(); Authentication.setAuthenticatedUserId(SecurityUtils.getUser().getUsername()); @@ -154,16 +153,14 @@ public class ActTaskServiceImpl implements ActTaskService { variables.put("days", leaveBillDto.getDays()); taskService.complete(taskId, variables); - ProcessInstance pi = runtimeService.createProcessInstanceQuery() - .processInstanceId(processInstanceId) - .singleResult(); + ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId) + .singleResult(); if (pi == null) { LeaveBill bill = new LeaveBill(); bill.setLeaveId(id); - bill.setState(StrUtil.equals(TaskStatusEnum.OVERRULE.getDescription() - , leaveBillDto.getTaskFlag()) ? TaskStatusEnum.OVERRULE.getStatus() - : TaskStatusEnum.COMPLETED.getStatus()); + bill.setState(StrUtil.equals(TaskStatusEnum.OVERRULE.getDescription(), leaveBillDto.getTaskFlag()) + ? TaskStatusEnum.OVERRULE.getStatus() : TaskStatusEnum.COMPLETED.getStatus()); leaveBillMapper.updateById(bill); } return null; @@ -171,15 +168,12 @@ public class ActTaskServiceImpl implements ActTaskService { @Override public List getCommentByTaskId(String taskId) { - //使用当前的任务ID,查询当前流程对应的历史任务ID - //使用当前任务ID,获取当前任务对象 - Task task = taskService.createTaskQuery() - .taskId(taskId) - .singleResult(); - //获取流程实例ID - List commentDtoList = taskService - .getProcessInstanceComments(task.getProcessInstanceId()) - .stream().map(comment -> { + // 使用当前的任务ID,查询当前流程对应的历史任务ID + // 使用当前任务ID,获取当前任务对象 + Task task = taskService.createTaskQuery().taskId(taskId).singleResult(); + // 获取流程实例ID + List commentDtoList = taskService.getProcessInstanceComments(task.getProcessInstanceId()).stream() + .map(comment -> { CommentDto commentDto = new CommentDto(); commentDto.setId(comment.getId()); commentDto.setTime(comment.getTime()); @@ -189,41 +183,35 @@ public class ActTaskServiceImpl implements ActTaskService { commentDto.setFullMessage(comment.getFullMessage()); commentDto.setProcessInstanceId(comment.getProcessInstanceId()); return commentDto; - } - ).collect(Collectors.toList()); + }).collect(Collectors.toList()); return commentDtoList; } /** * 追踪图片节点 - * * @param id */ @Override public InputStream viewByTaskId(String id) { - //使用当前任务ID,获取当前任务对象 - Task task = taskService.createTaskQuery() - .taskId(id) - .singleResult(); + // 使用当前任务ID,获取当前任务对象 + Task task = taskService.createTaskQuery().taskId(id).singleResult(); String processInstanceId = task.getProcessInstanceId(); ProcessInstance processInstance = runtimeService.createProcessInstanceQuery() - .processInstanceId(processInstanceId).singleResult(); - HistoricProcessInstance historicProcessInstance = - historyService.createHistoricProcessInstanceQuery() + .processInstanceId(processInstanceId).singleResult(); + HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery() .processInstanceId(processInstanceId).singleResult(); String processDefinitionId = null; List executedActivityIdList = new ArrayList<>(); if (processInstance != null) { processDefinitionId = processInstance.getProcessDefinitionId(); executedActivityIdList = this.runtimeService.getActiveActivityIds(processInstance.getId()); - } else if (historicProcessInstance != null) { + } + else if (historicProcessInstance != null) { processDefinitionId = historicProcessInstance.getProcessDefinitionId(); executedActivityIdList = historyService.createHistoricActivityInstanceQuery() - .processInstanceId(processInstanceId) - .orderByHistoricActivityInstanceId().asc().list() - .stream().map(HistoricActivityInstance::getActivityId) - .collect(Collectors.toList()); + .processInstanceId(processInstanceId).orderByHistoricActivityInstanceId().asc().list().stream() + .map(HistoricActivityInstance::getActivityId).collect(Collectors.toList()); } BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinitionId); @@ -231,28 +219,24 @@ public class ActTaskServiceImpl implements ActTaskService { Context.setProcessEngineConfiguration((ProcessEngineConfigurationImpl) processEngineConfiguration); ProcessDiagramGenerator diagramGenerator = processEngineConfiguration.getProcessDiagramGenerator(); - return diagramGenerator.generateDiagram( - bpmnModel, "png", - executedActivityIdList, Collections.emptyList(), - processEngine.getProcessEngineConfiguration().getActivityFontName(), - processEngine.getProcessEngineConfiguration().getLabelFontName(), - "宋体", - null, 1.0); + return diagramGenerator.generateDiagram(bpmnModel, "png", executedActivityIdList, Collections.emptyList(), + processEngine.getProcessEngineConfiguration().getActivityFontName(), + processEngine.getProcessEngineConfiguration().getLabelFontName(), "宋体", null, 1.0); } private List findOutFlagListByTaskId(Task task, ProcessInstance pi) { - //查询ProcessDefinitionEntiy对象 + // 查询ProcessDefinitionEntiy对象 ProcessDefinitionEntity processDefinitionEntity = (ProcessDefinitionEntity) repositoryService - .getProcessDefinition(task.getProcessDefinitionId()); + .getProcessDefinition(task.getProcessDefinitionId()); ActivityImpl activityImpl = processDefinitionEntity.findActivity(pi.getActivityId()); - //获取当前活动完成之后连线的名称 - List nameList = activityImpl.getOutgoingTransitions().stream() - .map(pvm -> { - String name = (String) pvm.getProperty("name"); - return StrUtil.isNotBlank(name) ? name : FLAG; - }).collect(Collectors.toList()); + // 获取当前活动完成之后连线的名称 + List nameList = activityImpl.getOutgoingTransitions().stream().map(pvm -> { + String name = (String) pvm.getProperty("name"); + return StrUtil.isNotBlank(name) ? name : FLAG; + }).collect(Collectors.toList()); return nameList; } + } diff --git a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/service/impl/EditorServiceImpl.java b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/service/impl/EditorServiceImpl.java index e543f4423..18f8b21e5 100644 --- a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/service/impl/EditorServiceImpl.java +++ b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/service/impl/EditorServiceImpl.java @@ -44,12 +44,13 @@ import static org.activiti.editor.constants.ModelDataJsonConstants.*; @Service @AllArgsConstructor public class EditorServiceImpl implements EditorService { + private final RepositoryService repositoryService; + private final ObjectMapper objectMapper; /** * 获取设计器页面的json - * * @return */ @Override @@ -57,7 +58,8 @@ public class EditorServiceImpl implements EditorService { InputStream stencilsetStream = this.getClass().getClassLoader().getResourceAsStream("stencilset.json"); try { return IOUtils.toString(stencilsetStream, StandardCharsets.UTF_8.name()); - } catch (Exception e) { + } + catch (Exception e) { log.error("Error while loading stencil set", e); throw new ActivitiException("Error while loading stencil set", e); } @@ -65,7 +67,6 @@ public class EditorServiceImpl implements EditorService { /** * 根据modelId获取model - * * @param modelId * @return */ @@ -77,16 +78,19 @@ public class EditorServiceImpl implements EditorService { try { if (StringUtils.isNotEmpty(model.getMetaInfo())) { modelNode = (ObjectNode) objectMapper.readTree(model.getMetaInfo()); - } else { + } + else { modelNode = objectMapper.createObjectNode(); modelNode.put(MODEL_NAME, model.getName()); } byte[] source = repositoryService.getModelEditorSource(model.getId()); modelNode.put(MODEL_ID, model.getId()); - ObjectNode editorJsonNode = (ObjectNode) objectMapper.readTree(new String(source, StandardCharsets.UTF_8)); + ObjectNode editorJsonNode = (ObjectNode) objectMapper + .readTree(new String(source, StandardCharsets.UTF_8)); modelNode.set("model", editorJsonNode); return modelNode; - } catch (Exception e) { + } + catch (Exception e) { log.error("Error creating model JSON", e); throw new ActivitiException("Error creating model JSON", e); } @@ -96,7 +100,6 @@ public class EditorServiceImpl implements EditorService { /** * 保存model信息 - * * @param modelId * @param name * @param description @@ -120,9 +123,11 @@ public class EditorServiceImpl implements EditorService { final byte[] result = outStream.toByteArray(); repositoryService.addModelEditorSourceExtra(model.getId(), result); outStream.close(); - } catch (Exception e) { + } + catch (Exception e) { log.error("Error saving model", e); throw new ActivitiException("Error saving model", e); } } + } diff --git a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/service/impl/ModelServiceImpl.java b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/service/impl/ModelServiceImpl.java index b4a9cba50..a1fe03802 100644 --- a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/service/impl/ModelServiceImpl.java +++ b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/service/impl/ModelServiceImpl.java @@ -51,13 +51,15 @@ import java.util.Map; @Service @AllArgsConstructor public class ModelServiceImpl implements ModelService { + private static final String BPMN20_XML = ".bpmn20.xml"; + private final RepositoryService repositoryService; + private final ObjectMapper objectMapper; /** * 创建流程 - * * @param name * @param key * @param desc @@ -72,8 +74,8 @@ public class ModelServiceImpl implements ModelService { editorNode.put("resourceId", "canvas"); ObjectNode properties = objectMapper.createObjectNode(); properties.put("process_author", SecurityConstants.PIGX_LICENSE); - properties.put("process_id",key); - properties.put("name",name); + properties.put("process_id", key); + properties.put("name", name); editorNode.set("properties", properties); ObjectNode stencilset = objectMapper.createObjectNode(); stencilset.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#"); @@ -84,8 +86,7 @@ public class ModelServiceImpl implements ModelService { model.setName(name); model.setCategory(category); model.setVersion(Integer.parseInt( - String.valueOf(repositoryService.createModelQuery() - .modelKey(model.getKey()).count() + 1))); + String.valueOf(repositoryService.createModelQuery().modelKey(model.getKey()).count() + 1))); ObjectNode modelObjectNode = objectMapper.createObjectNode(); modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME, name); @@ -97,7 +98,8 @@ public class ModelServiceImpl implements ModelService { repositoryService.saveModel(model); repositoryService.addModelEditorSource(model.getId(), editorNode.toString().getBytes("utf-8")); return model; - } catch (UnsupportedEncodingException e) { + } + catch (UnsupportedEncodingException e) { log.error("UnsupportedEncodingException", e); } return null; @@ -105,15 +107,14 @@ public class ModelServiceImpl implements ModelService { /** * 分页获取流程 - * * @param params * @return */ @Override public IPage getModelPage(Map params) { ModelQuery modelQuery = repositoryService.createModelQuery() - .modelTenantId(String.valueOf(TenantContextHolder.getTenantId())) - .latestVersion().orderByLastUpdateTime().desc(); + .modelTenantId(String.valueOf(TenantContextHolder.getTenantId())).latestVersion() + .orderByLastUpdateTime().desc(); String category = (String) params.get("category"); if (StrUtil.isNotBlank(category)) { modelQuery.modelCategory(category); @@ -130,7 +131,6 @@ public class ModelServiceImpl implements ModelService { /** * 删除流程 - * * @param id * @return */ @@ -142,7 +142,6 @@ public class ModelServiceImpl implements ModelService { /** * 部署流程 - * * @param id * @return */ @@ -151,7 +150,8 @@ public class ModelServiceImpl implements ModelService { try { // 获取模型 Model model = repositoryService.getModel(id); - ObjectNode objectNode = (ObjectNode) new ObjectMapper().readTree(repositoryService.getModelEditorSource(model.getId())); + ObjectNode objectNode = (ObjectNode) new ObjectMapper() + .readTree(repositoryService.getModelEditorSource(model.getId())); BpmnModel bpmnModel = new BpmnJsonConverter().convertToBpmnModel(objectNode); String processName = model.getName(); @@ -159,23 +159,22 @@ public class ModelServiceImpl implements ModelService { processName += BPMN20_XML; } // 部署流程 - Deployment deployment = repositoryService - .createDeployment().name(model.getName()) - .addBpmnModel(processName, bpmnModel) - .tenantId(String.valueOf(TenantContextHolder.getTenantId())) + Deployment deployment = repositoryService.createDeployment().name(model.getName()) + .addBpmnModel(processName, bpmnModel).tenantId(String.valueOf(TenantContextHolder.getTenantId())) .deploy(); // 设置流程分类 List list = repositoryService.createProcessDefinitionQuery() - .deploymentId(deployment.getId()) - .list(); + .deploymentId(deployment.getId()).list(); - list.stream().forEach(processDefinition -> - repositoryService.setProcessDefinitionCategory(processDefinition.getId(), model.getCategory())); - } catch (Exception e) { + list.stream().forEach(processDefinition -> repositoryService + .setProcessDefinitionCategory(processDefinition.getId(), model.getCategory())); + } + catch (Exception e) { log.error("部署失败,异常", e); return Boolean.FALSE; } return Boolean.TRUE; } + } diff --git a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/service/impl/ProcessServiceImpl.java b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/service/impl/ProcessServiceImpl.java index 1a0ab5010..d9f116c1c 100644 --- a/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/service/impl/ProcessServiceImpl.java +++ b/pigx-visual/pigx-oa-platform/src/main/java/com/pig4cloud/pigx/act/service/impl/ProcessServiceImpl.java @@ -52,20 +52,22 @@ import java.util.stream.Collectors; @Service @AllArgsConstructor public class ProcessServiceImpl implements ProcessService { + private final RepositoryService repositoryService; + private final RuntimeService runtimeService; + private final LeaveBillMapper leaveBillMapper; /** * 分页流程列表 - * * @param params * @return */ @Override public IPage getProcessByPage(Map params) { ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery() - .processDefinitionTenantId(String.valueOf(TenantContextHolder.getTenantId())).latestVersion(); + .processDefinitionTenantId(String.valueOf(TenantContextHolder.getTenantId())).latestVersion(); String category = MapUtil.getStr(params, "category"); if (StrUtil.isNotBlank(category)) { @@ -78,20 +80,18 @@ public class ProcessServiceImpl implements ProcessService { IPage result = new Page(page, limit); result.setTotal(query.count()); - List deploymentList = query.listPage((page - 1) * limit, limit) - .stream() - .map(processDefinition -> { - Deployment deployment = repositoryService.createDeploymentQuery() - .deploymentId(processDefinition.getDeploymentId()).singleResult(); - return ProcessDefDTO.toProcessDefDTO(processDefinition, deployment); - }).collect(Collectors.toList()); + List deploymentList = query.listPage((page - 1) * limit, limit).stream() + .map(processDefinition -> { + Deployment deployment = repositoryService.createDeploymentQuery() + .deploymentId(processDefinition.getDeploymentId()).singleResult(); + return ProcessDefDTO.toProcessDefDTO(processDefinition, deployment); + }).collect(Collectors.toList()); result.setRecords(deploymentList); return result; } /** * 读取xml/image资源 - * * @param procDefId * @param proInsId * @param resType @@ -101,32 +101,28 @@ public class ProcessServiceImpl implements ProcessService { public InputStream readResource(String procDefId, String proInsId, String resType) { if (StrUtil.isBlank(procDefId)) { - ProcessInstance processInstance = runtimeService - .createProcessInstanceQuery() - .processInstanceId(proInsId) - .singleResult(); + ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(proInsId) + .singleResult(); procDefId = processInstance.getProcessDefinitionId(); } - ProcessDefinition processDefinition = repositoryService - .createProcessDefinitionQuery() - .processDefinitionId(procDefId) - .singleResult(); + ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery() + .processDefinitionId(procDefId).singleResult(); String resourceName = ""; if (ResourceTypeEnum.IMAGE.getType().equals(resType)) { resourceName = processDefinition.getDiagramResourceName(); - } else if (ResourceTypeEnum.XML.getType().equals(resType)) { + } + else if (ResourceTypeEnum.XML.getType().equals(resType)) { resourceName = processDefinition.getResourceName(); } - InputStream resourceAsStream = repositoryService - .getResourceAsStream(processDefinition.getDeploymentId(), resourceName); + InputStream resourceAsStream = repositoryService.getResourceAsStream(processDefinition.getDeploymentId(), + resourceName); return resourceAsStream; } /** * 更新状态 - * * @param status * @param procDefId * @return @@ -135,7 +131,8 @@ public class ProcessServiceImpl implements ProcessService { public Boolean updateStatus(String status, String procDefId) { if (ProcessStatusEnum.ACTIVE.getStatus().equals(status)) { repositoryService.activateProcessDefinitionById(procDefId, true, null); - } else if (ProcessStatusEnum.SUSPEND.getStatus().equals(status)) { + } + else if (ProcessStatusEnum.SUSPEND.getStatus().equals(status)) { repositoryService.suspendProcessDefinitionById(procDefId, true, null); } return Boolean.TRUE; @@ -143,7 +140,6 @@ public class ProcessServiceImpl implements ProcessService { /** * 删除部署的流程,级联删除流程实例 - * * @param deploymentId * @return */ @@ -155,7 +151,6 @@ public class ProcessServiceImpl implements ProcessService { /** * 启动流程、更新请假单状态 - * * @param leaveId * @return */ @@ -167,7 +162,8 @@ public class ProcessServiceImpl implements ProcessService { String key = leaveBill.getClass().getSimpleName(); String businessKey = key + "_" + leaveBill.getLeaveId(); - runtimeService.startProcessInstanceByKeyAndTenantId(key, businessKey, String.valueOf(TenantContextHolder.getTenantId())); + runtimeService.startProcessInstanceByKeyAndTenantId(key, businessKey, + String.valueOf(TenantContextHolder.getTenantId())); leaveBillMapper.updateById(leaveBill); return Boolean.TRUE; } diff --git a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/PigxPayPlatformApplication.java b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/PigxPayPlatformApplication.java index cf7a6a08c..e689dcfd2 100755 --- a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/PigxPayPlatformApplication.java +++ b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/PigxPayPlatformApplication.java @@ -38,4 +38,5 @@ public class PigxPayPlatformApplication { public static void main(String[] args) { SpringApplication.run(PigxPayPlatformApplication.class, args); } + } diff --git a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/config/AliPayConfig.java b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/config/AliPayConfig.java index f1e484e88..3b932482b 100644 --- a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/config/AliPayConfig.java +++ b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/config/AliPayConfig.java @@ -8,6 +8,7 @@ import lombok.Data; */ @Data public class AliPayConfig { + /** * 订单过期时间 */ @@ -22,4 +23,5 @@ public class AliPayConfig { * 服务端回调地址 */ private String notifyUrl; + } \ No newline at end of file diff --git a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/config/PayCommonProperties.java b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/config/PayCommonProperties.java index df912b613..ac06c814d 100644 --- a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/config/PayCommonProperties.java +++ b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/config/PayCommonProperties.java @@ -14,6 +14,7 @@ import org.springframework.context.annotation.Configuration; @Configuration @ConfigurationProperties(prefix = "pigx.pay") public class PayCommonProperties { + /** * 支付宝支付参数 */ @@ -24,7 +25,6 @@ public class PayCommonProperties { */ private WxPayConfig wxPayConfig; - private String test; } \ No newline at end of file diff --git a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/config/PayConfigParmaInitRunner.java b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/config/PayConfigParmaInitRunner.java index ae14254c1..192da4a24 100644 --- a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/config/PayConfigParmaInitRunner.java +++ b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/config/PayConfigParmaInitRunner.java @@ -48,40 +48,37 @@ import java.util.Map; @Configuration @AllArgsConstructor public class PayConfigParmaInitRunner { - public static Map mpServiceMap = new HashMap<>(); - private final PayChannelService channelService; - private final RemoteTenantService tenantService; + public static Map mpServiceMap = new HashMap<>(); + + private final PayChannelService channelService; + + private final RemoteTenantService tenantService; @Async @Order @SqlParser(filter = true) - @EventListener({WebServerInitializedEvent.class}) + @EventListener({ WebServerInitializedEvent.class }) public void initPayConfig() { List channelList = new ArrayList<>(); tenantService.list(SecurityConstants.FROM_IN).getData() .forEach(tenant -> TenantBroker.runAs(tenant.getId(), (id) -> { - List payChannelList = channelService - .list(Wrappers.lambdaQuery() - .eq(PayChannel::getState, CommonConstants.STATUS_NORMAL)); + List payChannelList = channelService.list( + Wrappers.lambdaQuery().eq(PayChannel::getState, CommonConstants.STATUS_NORMAL)); channelList.addAll(payChannelList); })); channelList.forEach(channel -> { JSONObject params = JSONUtil.parseObj(channel.getParam()); - //支付宝支付 + // 支付宝支付 if (PayChannelNameEnum.ALIPAY_WAP.getName().equals(channel.getChannelId())) { - AliPayApiConfig aliPayApiConfig = AliPayApiConfig.New() - .setAppId(channel.getAppId()) - .setPrivateKey(params.getStr("privateKey")) - .setCharset(CharsetUtil.UTF_8) - .setAlipayPublicKey(params.getStr("publicKey")) - .setServiceUrl(params.getStr("serviceUrl")) - .setSignType("RSA2") - .build(); + AliPayApiConfig aliPayApiConfig = AliPayApiConfig.New().setAppId(channel.getAppId()) + .setPrivateKey(params.getStr("privateKey")).setCharset(CharsetUtil.UTF_8) + .setAlipayPublicKey(params.getStr("publicKey")).setServiceUrl(params.getStr("serviceUrl")) + .setSignType("RSA2").build(); AliPayApiConfigKit.putApiConfig(aliPayApiConfig); log.info("新增支付宝支付参数 {}", aliPayApiConfig); @@ -89,10 +86,8 @@ public class PayConfigParmaInitRunner { // 微信支付 if (PayChannelNameEnum.WEIXIN_MP.getName().equals(channel.getChannelId())) { - WxPayApiConfig wx = WxPayApiConfig.New() - .setAppId(channel.getAppId()) - .setMchId(channel.getChannelMchId()) - .setPaternerKey(params.getStr("paternerKey")) + WxPayApiConfig wx = WxPayApiConfig.New().setAppId(channel.getAppId()) + .setMchId(channel.getChannelMchId()).setPaternerKey(params.getStr("paternerKey")) .setPayModel(WxPayApiConfig.PayModel.BUSINESSMODEL); String subMchId = params.getStr("subMchId"); @@ -118,14 +113,12 @@ public class PayConfigParmaInitRunner { /** * redis 监听配置,监听 pay_redis_route_reload_topic,重新加载配置 - * * @param redisConnectionFactory redis 配置 * @return */ @Bean public RedisMessageListenerContainer redisContainer(RedisConnectionFactory redisConnectionFactory) { - RedisMessageListenerContainer container - = new RedisMessageListenerContainer(); + RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(redisConnectionFactory); container.addMessageListener((message, bytes) -> { log.warn("接收到Redis 事件 重新加载支付参数事件"); @@ -133,4 +126,5 @@ public class PayConfigParmaInitRunner { }, new ChannelTopic(CacheConstants.PAY_REDIS_RELOAD_TOPIC)); return container; } + } diff --git a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/config/SequenceConfig.java b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/config/SequenceConfig.java index f98771f2c..55ba4270b 100644 --- a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/config/SequenceConfig.java +++ b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/config/SequenceConfig.java @@ -21,41 +21,29 @@ public class SequenceConfig { /** * 订单流水号发号器 - * * @param dataSource * @param properties * @return */ @Bean - public Sequence paySequence(DataSource dataSource, - SequenceDbProperties properties) { - return DbSeqBuilder - .create() + public Sequence paySequence(DataSource dataSource, SequenceDbProperties properties) { + return DbSeqBuilder.create() .bizName(() -> String.format("pay_%s_%s", TenantContextHolder.getTenantId(), DateUtil.today())) - .dataSource(dataSource) - .step(properties.getStep()) - .retryTimes(properties.getRetryTimes()) - .tableName(properties.getTableName()) - .build(); + .dataSource(dataSource).step(properties.getStep()).retryTimes(properties.getRetryTimes()) + .tableName(properties.getTableName()).build(); } /** * 通道编号发号器 - * * @param dataSource * @param properties * @return */ @Bean - public Sequence channelSequence(DataSource dataSource, - SequenceDbProperties properties) { - return DbSeqBuilder - .create() - .bizName(() -> String.format("channel_%s", TenantContextHolder.getTenantId())) - .dataSource(dataSource) - .step(properties.getStep()) - .retryTimes(properties.getRetryTimes()) - .tableName(properties.getTableName()) - .build(); + public Sequence channelSequence(DataSource dataSource, SequenceDbProperties properties) { + return DbSeqBuilder.create().bizName(() -> String.format("channel_%s", TenantContextHolder.getTenantId())) + .dataSource(dataSource).step(properties.getStep()).retryTimes(properties.getRetryTimes()) + .tableName(properties.getTableName()).build(); } + } diff --git a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/config/WxPayConfig.java b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/config/WxPayConfig.java index 7c4da0b9d..e295def60 100644 --- a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/config/WxPayConfig.java +++ b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/config/WxPayConfig.java @@ -8,6 +8,7 @@ import lombok.Data; */ @Data public class WxPayConfig { + /** * 服务端回调地址 */ @@ -17,4 +18,5 @@ public class WxPayConfig { * 订单过期时间 */ private String expireTime; + } \ No newline at end of file diff --git a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/controller/PayChannelController.java b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/controller/PayChannelController.java index 8a6d578ae..1ff572d18 100755 --- a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/controller/PayChannelController.java +++ b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/controller/PayChannelController.java @@ -30,7 +30,6 @@ import org.springframework.data.redis.core.RedisTemplate; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; - /** * 渠道 * @@ -42,13 +41,14 @@ import org.springframework.web.bind.annotation.*; @RequestMapping("/paychannel") @Api(value = "paychannel", tags = "paychannel管理") public class PayChannelController { + private final PayChannelService payChannelService; + private final RedisTemplate redisTemplate; /** * 分页查询 - * - * @param page 分页对象 + * @param page 分页对象 * @param payChannel 渠道 * @return */ @@ -57,10 +57,8 @@ public class PayChannelController { return R.ok(payChannelService.page(page, Wrappers.query(payChannel))); } - /** * 通过id查询渠道 - * * @param id id * @return R */ @@ -71,7 +69,6 @@ public class PayChannelController { /** * 新增渠道 - * * @param payChannel 渠道 * @return R */ @@ -86,7 +83,6 @@ public class PayChannelController { /** * 修改渠道 - * * @param payChannel 渠道 * @return R */ @@ -101,7 +97,6 @@ public class PayChannelController { /** * 通过id删除渠道 - * * @param id id * @return R */ diff --git a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/controller/PayGoodsOrderController.java b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/controller/PayGoodsOrderController.java index 2726da320..e2aeb90ec 100755 --- a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/controller/PayGoodsOrderController.java +++ b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/controller/PayGoodsOrderController.java @@ -41,7 +41,6 @@ import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; - /** * 商品 * @@ -56,11 +55,9 @@ public class PayGoodsOrderController { private final PayGoodsOrderService payGoodsOrderService; - /** * 商品订单 - * - * @param goods 商品 + * @param goods 商品 * @param modelAndView * @return R */ @@ -71,9 +68,9 @@ public class PayGoodsOrderController { String ua = request.getHeader(HttpHeaders.USER_AGENT); if (ua.contains(PayConstants.MICRO_MESSENGER)) { String appId = WxPayApiConfigKit.getWxPayApiConfig().getAppId(); - modelAndView.setViewName("redirect:https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appId + - "&redirect_uri=http%3a%2f%2fadmin.pig4cloud.com%2fpay%2fgoods%2fwx%3famount%3d" + goods.getAmount() + - "&response_type=code&scope=snsapi_base&state=" + appId); + modelAndView.setViewName("redirect:https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appId + + "&redirect_uri=http%3a%2f%2fadmin.pig4cloud.com%2fpay%2fgoods%2fwx%3famount%3d" + + goods.getAmount() + "&response_type=code&scope=snsapi_base&state=" + appId); return modelAndView; } @@ -84,10 +81,9 @@ public class PayGoodsOrderController { /** * oauth - * - * @param goods 商品信息 - * @param state appid - * @param code 回调code + * @param goods 商品信息 + * @param state appid + * @param code 回调code * @param modelAndView * @return * @throws WxErrorException @@ -107,8 +103,7 @@ public class PayGoodsOrderController { /** * 分页查询 - * - * @param page 分页对象 + * @param page 分页对象 * @param payGoodsOrder 商品订单表 * @return */ @@ -118,10 +113,8 @@ public class PayGoodsOrderController { return R.ok(payGoodsOrderService.page(page, Wrappers.query(payGoodsOrder))); } - /** * 通过id查询商品订单表 - * * @param goodsOrderId id * @return R */ @@ -133,7 +126,6 @@ public class PayGoodsOrderController { /** * 新增商品订单表 - * * @param payGoodsOrder 商品订单表 * @return R */ @@ -147,7 +139,6 @@ public class PayGoodsOrderController { /** * 修改商品订单表 - * * @param payGoodsOrder 商品订单表 * @return R */ @@ -161,7 +152,6 @@ public class PayGoodsOrderController { /** * 通过id删除商品订单表 - * * @param goodsOrderId id * @return R */ diff --git a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/controller/PayNotifyRecordController.java b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/controller/PayNotifyRecordController.java index 1aab43e1b..82e06d4f8 100755 --- a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/controller/PayNotifyRecordController.java +++ b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/controller/PayNotifyRecordController.java @@ -39,7 +39,6 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Map; - /** * 异步通知记录 * @@ -52,14 +51,16 @@ import java.util.Map; @RequestMapping("/notify") @Api(value = "notify", tags = "notify管理") public class PayNotifyRecordController { + private final PayNotifyRecordService payNotifyRecordService; + private final PayNotifyCallbakHandler alipayCallback; + private final PayNotifyCallbakHandler weChatCallback; /** * 分页查询 - * - * @param page 分页对象 + * @param page 分页对象 * @param payNotifyRecord 异步通知记录 * @return */ @@ -68,10 +69,8 @@ public class PayNotifyRecordController { return R.ok(payNotifyRecordService.page(page, Wrappers.query(payNotifyRecord))); } - /** * 通过id查询异步通知记录 - * * @param id id * @return R */ @@ -82,7 +81,6 @@ public class PayNotifyRecordController { /** * 新增异步通知记录 - * * @param payNotifyRecord 异步通知记录 * @return R */ @@ -95,7 +93,6 @@ public class PayNotifyRecordController { /** * 修改异步通知记录 - * * @param payNotifyRecord 异步通知记录 * @return R */ @@ -108,7 +105,6 @@ public class PayNotifyRecordController { /** * 通过id删除异步通知记录 - * * @param id id * @return R */ @@ -121,7 +117,6 @@ public class PayNotifyRecordController { /** * 支付宝渠道异步回调 - * * @param request 渠道请求 * @return */ @@ -136,7 +131,6 @@ public class PayNotifyRecordController { /** * 微信渠道支付回调 - * * @param request * @return */ diff --git a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/controller/PayRefundOrderController.java b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/controller/PayRefundOrderController.java index 43e963634..7c0f35589 100755 --- a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/controller/PayRefundOrderController.java +++ b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/controller/PayRefundOrderController.java @@ -28,7 +28,6 @@ import lombok.AllArgsConstructor; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; - /** * 退款 * @@ -45,8 +44,7 @@ public class PayRefundOrderController { /** * 分页查询 - * - * @param page 分页对象 + * @param page 分页对象 * @param payRefundOrder 退款 * @return */ @@ -55,10 +53,8 @@ public class PayRefundOrderController { return R.ok(payRefundOrderService.page(page, Wrappers.query(payRefundOrder))); } - /** * 通过id查询退款 - * * @param refundOrderId id * @return R */ @@ -69,7 +65,6 @@ public class PayRefundOrderController { /** * 新增退款 - * * @param payRefundOrder 退款 * @return R */ @@ -82,7 +77,6 @@ public class PayRefundOrderController { /** * 修改退款 - * * @param payRefundOrder 退款 * @return R */ @@ -95,7 +89,6 @@ public class PayRefundOrderController { /** * 通过id删除退款 - * * @param refundOrderId refundOrderId * @return R */ diff --git a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/controller/PayTradeOrderController.java b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/controller/PayTradeOrderController.java index 56f795438..ba8114326 100755 --- a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/controller/PayTradeOrderController.java +++ b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/controller/PayTradeOrderController.java @@ -28,7 +28,6 @@ import lombok.AllArgsConstructor; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; - /** * 支付 * @@ -37,68 +36,67 @@ import org.springframework.web.bind.annotation.*; */ @RestController @AllArgsConstructor -@RequestMapping("/order" ) +@RequestMapping("/order") @Api(value = "order", tags = "订单") public class PayTradeOrderController { - private final PayTradeOrderService payTradeOrderService; + private final PayTradeOrderService payTradeOrderService; - /** - * 分页查询 - * @param page 分页对象 - * @param payTradeOrder 支付 - * @return - */ - @GetMapping("/page" ) - public R getPayTradeOrderPage(Page page, PayTradeOrder payTradeOrder) { - return R.ok(payTradeOrderService.page(page, Wrappers.query(payTradeOrder))); - } + /** + * 分页查询 + * @param page 分页对象 + * @param payTradeOrder 支付 + * @return + */ + @GetMapping("/page") + public R getPayTradeOrderPage(Page page, PayTradeOrder payTradeOrder) { + return R.ok(payTradeOrderService.page(page, Wrappers.query(payTradeOrder))); + } + /** + * 通过id查询支付 + * @param orderId id + * @return R + */ + @GetMapping("/{orderId}") + public R getById(@PathVariable("orderId") String orderId) { + return R.ok(payTradeOrderService.getById(orderId)); + } - /** - * 通过id查询支付 - * @param orderId id - * @return R - */ - @GetMapping("/{orderId}" ) - public R getById(@PathVariable("orderId" ) String orderId) { - return R.ok(payTradeOrderService.getById(orderId)); - } + /** + * 新增支付 + * @param payTradeOrder 支付 + * @return R + */ + @SysLog("新增支付") + @PostMapping + @PreAuthorize("@pms.hasPermission('pay_paytradeorder_add')") + public R save(@RequestBody PayTradeOrder payTradeOrder) { + return R.ok(payTradeOrderService.save(payTradeOrder)); + } - /** - * 新增支付 - * @param payTradeOrder 支付 - * @return R - */ - @SysLog("新增支付" ) - @PostMapping - @PreAuthorize("@pms.hasPermission('pay_paytradeorder_add')" ) - public R save(@RequestBody PayTradeOrder payTradeOrder) { - return R.ok(payTradeOrderService.save(payTradeOrder)); - } + /** + * 修改支付 + * @param payTradeOrder 支付 + * @return R + */ + @SysLog("修改支付") + @PutMapping + @PreAuthorize("@pms.hasPermission('pay_paytradeorder_edit')") + public R updateById(@RequestBody PayTradeOrder payTradeOrder) { + return R.ok(payTradeOrderService.updateById(payTradeOrder)); + } - /** - * 修改支付 - * @param payTradeOrder 支付 - * @return R - */ - @SysLog("修改支付" ) - @PutMapping - @PreAuthorize("@pms.hasPermission('pay_paytradeorder_edit')" ) - public R updateById(@RequestBody PayTradeOrder payTradeOrder) { - return R.ok(payTradeOrderService.updateById(payTradeOrder)); - } - - /** - * 通过id删除支付 - * @param orderId id - * @return R - */ - @SysLog("删除支付" ) - @DeleteMapping("/{orderId}" ) - @PreAuthorize("@pms.hasPermission('pay_paytradeorder_del')" ) - public R removeById(@PathVariable String orderId) { - return R.ok(payTradeOrderService.removeById(orderId)); - } + /** + * 通过id删除支付 + * @param orderId id + * @return R + */ + @SysLog("删除支付") + @DeleteMapping("/{orderId}") + @PreAuthorize("@pms.hasPermission('pay_paytradeorder_del')") + public R removeById(@PathVariable String orderId) { + return R.ok(payTradeOrderService.removeById(orderId)); + } } diff --git a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/entity/PayChannel.java b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/entity/PayChannel.java index 35c334e31..0bb4fbfe2 100755 --- a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/entity/PayChannel.java +++ b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/entity/PayChannel.java @@ -38,6 +38,7 @@ import java.time.LocalDateTime; @EqualsAndHashCode(callSuper = true) @ApiModel(description = "渠道") public class PayChannel extends Model { + private static final long serialVersionUID = 1L; /** @@ -45,47 +46,58 @@ public class PayChannel extends Model { */ @TableId private Integer id; + /** * 应用ID */ private String appId; + /** * 渠道ID */ private String channelId; + /** * 渠道名称,如:alipay,wechat */ private String channelName; + /** * 渠道商户ID */ private String channelMchId; + /** * 渠道状态 */ private String state; + /** * 配置参数,json字符串 */ private String param; + /** * 备注 */ private String remark; + /** * 删除标记 */ @TableLogic private String delFlag; + /** * 创建时间 */ private LocalDateTime createTime; + /** * 更新时间 */ private LocalDateTime updateTime; + /** * 租户ID */ diff --git a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/entity/PayGoodsOrder.java b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/entity/PayGoodsOrder.java index 077a82608..451af19ab 100755 --- a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/entity/PayGoodsOrder.java +++ b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/entity/PayGoodsOrder.java @@ -38,6 +38,7 @@ import java.time.LocalDateTime; @EqualsAndHashCode(callSuper = true) @ApiModel(description = "商品") public class PayGoodsOrder extends Model { + private static final long serialVersionUID = 1L; /** @@ -45,43 +46,53 @@ public class PayGoodsOrder extends Model { */ @TableId private String goodsOrderId; + /** * 商品ID */ private String goodsId; + /** * 商品名称 */ private String goodsName; + /** * 金额,单位分 */ private String amount; + /** * 用户ID */ private String userId; + /** * 订单状态,订单生成(0),支付成功(1),处理完成(2),处理失败(-1) */ private String status; + /** * 支付订单号 */ private String payOrderId; + /** * 0-正常,1-删除 */ @TableLogic private String delFlag; + /** * 创建时间 */ private LocalDateTime createTime; + /** * 更新时间 */ private LocalDateTime updateTime; + /** * 租户ID */ diff --git a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/entity/PayNotifyRecord.java b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/entity/PayNotifyRecord.java index f932965a8..ca75c202c 100755 --- a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/entity/PayNotifyRecord.java +++ b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/entity/PayNotifyRecord.java @@ -38,6 +38,7 @@ import java.time.LocalDateTime; @EqualsAndHashCode(callSuper = true) @ApiModel(description = "异步通知记录") public class PayNotifyRecord extends Model { + private static final long serialVersionUID = 1L; /** @@ -45,39 +46,48 @@ public class PayNotifyRecord extends Model { */ @TableId private Long id; + /** * 响应ID */ private String notifyId; + /** * 请求报文 */ private String request; + /** * 响应报文 */ private String response; + /** * 系统订单号 */ private String orderNo; + /** * http状态 */ private String httpStatus; + /** * 删除标记 */ @TableLogic private String delFlag; + /** * 创建时间 */ private LocalDateTime createTime; + /** * 更新时间 */ private LocalDateTime updateTime; + /** * 租户ID */ diff --git a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/entity/PayRefundOrder.java b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/entity/PayRefundOrder.java index 84afda9d9..54c7f3369 100755 --- a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/entity/PayRefundOrder.java +++ b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/entity/PayRefundOrder.java @@ -38,6 +38,7 @@ import java.time.LocalDateTime; @EqualsAndHashCode(callSuper = true) @ApiModel(description = "退款") public class PayRefundOrder extends Model { + private static final long serialVersionUID = 1L; /** @@ -45,119 +46,148 @@ public class PayRefundOrder extends Model { */ @TableId private String refundOrderId; + /** * 支付订单号 */ private String payOrderId; + /** * 渠道支付单号 */ private String channelPayOrderNo; + /** * 商户ID */ private String mchId; + /** * 商户退款单号 */ private String mchRefundNo; + /** * 渠道ID */ private String channelId; + /** * 支付金额,单位元 */ private String payAmount; + /** * 退款金额,单位分 */ private Long refundAmount; + /** * 三位货币代码,人民币:cny */ private String currency; + /** * 退款状态:0-订单生成,1-退款中,2-退款成功,3-退款失败,4-业务处理完成 */ private String status; + /** * 退款结果:0-不确认结果,1-等待手动处理,2-确认成功,3-确认失败 */ private String result; + /** * 客户端IP */ private String clientIp; + /** * 设备 */ private String device; + /** * 备注 */ private String remark; + /** * 渠道用户标识,如微信openId,支付宝账号 */ private String channelUser; + /** * 用户姓名 */ private String username; + /** * 渠道商户ID */ private String channelMchId; + /** * 渠道订单号 */ private String channelOrderNo; + /** * 渠道错误码 */ private String channelErrCode; + /** * 渠道错误描述 */ private String channelErrMsg; + /** * 特定渠道发起时额外参数 */ private String extra; + /** * 通知地址 */ private String notifyurl; + /** * 扩展参数1 */ private String param1; + /** * 扩展参数2 */ private String param2; + /** * 订单失效时间 */ private LocalDateTime expireTime; + /** * 订单退款成功时间 */ private LocalDateTime refundSuccTime; + /** * 删除标记 */ @TableLogic private String delFlag; + /** * 创建时间 */ private LocalDateTime createTime; + /** * 更新时间 */ private LocalDateTime updateTime; + /** * 租户ID */ diff --git a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/entity/PayTradeOrder.java b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/entity/PayTradeOrder.java index e59371281..31fd13587 100755 --- a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/entity/PayTradeOrder.java +++ b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/entity/PayTradeOrder.java @@ -39,6 +39,7 @@ import java.time.LocalDateTime; @EqualsAndHashCode(callSuper = true) @ApiModel(description = "支付") public class PayTradeOrder extends Model { + private static final long serialVersionUID = 1L; /** @@ -46,99 +47,123 @@ public class PayTradeOrder extends Model { */ @TableId(type = IdType.INPUT) private String orderId; + /** * 渠道ID */ private String channelId; + /** * 支付金额,单位元 */ private String amount; + /** * 三位货币代码,人民币:cny */ private String currency; + /** * 支付状态,0-订单生成,1-支付中(目前未使用),2-支付成功,3-业务处理完成 */ private String status; + /** * 客户端IP */ private String clientIp; + /** * 设备 */ private String device; + /** * 商品标题 */ private String subject; + /** * 商品描述信息 */ private String body; + /** * 特定渠道发起时额外参数 */ private String extra; + /** * 渠道商户ID */ private String channelMchId; + /** * 渠道订单号 */ private String channelOrderNo; + /** * 渠道支付错误码 */ private String errCode; + /** * 渠道支付错误描述 */ private String errMsg; + /** * 扩展参数1 */ private String param1; + /** * 扩展参数2 */ private String param2; + /** * 通知地址 */ private String notifyUrl; + /** * 通知次数 */ private Integer notifyCount; + /** * 最后一次通知时间 */ private Long lastNotifyTime; + /** * 订单失效时间 */ private Long expireTime; + /** * 订单支付成功时间 */ private Long paySuccTime; + /** * 创建时间 */ private LocalDateTime createTime; + /** * 更新时间 */ private LocalDateTime updateTime; + /** * 删除标记 */ @TableLogic private String delFlag; + /** * 租户ID */ diff --git a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/MessageDuplicateCheckerHandler.java b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/MessageDuplicateCheckerHandler.java index 6e09a707b..7bfea55d9 100644 --- a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/MessageDuplicateCheckerHandler.java +++ b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/MessageDuplicateCheckerHandler.java @@ -24,11 +24,12 @@ package com.pig4cloud.pigx.pay.handler; * 消息去重 */ public interface MessageDuplicateCheckerHandler { + /** * 判断回调消息是否重复. - * * @param messageId messageId需要根据上面讲的方式构造 * @return 如果是重复消息,返回false,否则返回true */ boolean isDuplicate(String messageId); + } diff --git a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/PayNotifyCallbakHandler.java b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/PayNotifyCallbakHandler.java index 574651357..d29df78b4 100644 --- a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/PayNotifyCallbakHandler.java +++ b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/PayNotifyCallbakHandler.java @@ -29,14 +29,12 @@ public interface PayNotifyCallbakHandler { /** * 初始化执行 - * * @param params */ void before(Map params); /** * 去重处理 - * * @param params 回调报文 * @return */ @@ -44,7 +42,6 @@ public interface PayNotifyCallbakHandler { /** * 验签逻辑 - * * @param params 回调报文 * @return */ @@ -52,7 +49,6 @@ public interface PayNotifyCallbakHandler { /** * 解析报文 - * * @param params * @return */ @@ -60,7 +56,6 @@ public interface PayNotifyCallbakHandler { /** * 调用入口 - * * @param params * @return */ @@ -68,9 +63,9 @@ public interface PayNotifyCallbakHandler { /** * 保存回调记录 - * * @param result 处理结果 * @param params 回调报文 */ void saveNotifyRecord(Map params, String result); + } diff --git a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/PayOrderHandler.java b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/PayOrderHandler.java index f65b8223d..ae093fe02 100644 --- a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/PayOrderHandler.java +++ b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/PayOrderHandler.java @@ -13,7 +13,6 @@ public interface PayOrderHandler { /** * 创建商品订单 - * * @param goodsOrder 金额 * @return */ @@ -21,7 +20,6 @@ public interface PayOrderHandler { /** * 创建交易订单 - * * @param goodsOrder 商品订单 * @return */ @@ -29,7 +27,6 @@ public interface PayOrderHandler { /** * 调起渠道支付 - * * @param goodsOrder 商品订单 * @param tradeOrder 交易订单 * @return obj @@ -38,7 +35,6 @@ public interface PayOrderHandler { /** * 更新订单信息 - * * @param goodsOrder 商品订单 * @param tradeOrder 交易订单 */ @@ -46,9 +42,9 @@ public interface PayOrderHandler { /** * 调用入口 - * * @param goodsOrde 商品订单 * @return */ Object handle(PayGoodsOrder goodsOrde); + } diff --git a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/impl/AbstractPayNotifyCallbakHandler.java b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/impl/AbstractPayNotifyCallbakHandler.java index 7eeafe680..a7a4ee32f 100644 --- a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/impl/AbstractPayNotifyCallbakHandler.java +++ b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/impl/AbstractPayNotifyCallbakHandler.java @@ -33,9 +33,9 @@ import java.util.Map; */ @Slf4j public abstract class AbstractPayNotifyCallbakHandler implements PayNotifyCallbakHandler { + /** * 调用入口 - * * @param params * @return */ @@ -69,8 +69,8 @@ public abstract class AbstractPayNotifyCallbakHandler implements PayNotifyCallba * @param notifyId * @param recordService */ - void saveRecord(Map params, String result, PayNotifyRecord record, String notifyId - , PayNotifyRecordService recordService) { + void saveRecord(Map params, String result, PayNotifyRecord record, String notifyId, + PayNotifyRecordService recordService) { record.setNotifyId(notifyId); String orderNo = params.get(PayConstants.OUT_TRADE_NO); record.setOrderNo(orderNo); @@ -78,4 +78,5 @@ public abstract class AbstractPayNotifyCallbakHandler implements PayNotifyCallba record.setResponse(result); recordService.save(record); } + } diff --git a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/impl/AbstractPayOrderHandler.java b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/impl/AbstractPayOrderHandler.java index ceea5d3a4..e69c6c323 100644 --- a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/impl/AbstractPayOrderHandler.java +++ b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/impl/AbstractPayOrderHandler.java @@ -30,15 +30,15 @@ import org.springframework.beans.factory.annotation.Autowired; * @date 2019-05-31 */ public abstract class AbstractPayOrderHandler implements PayOrderHandler { + @Autowired private PayGoodsOrderMapper goodsOrderMapper; + @Autowired private Sequence paySequence; - /** * 创建商品订单 - * * @param goodsOrder 商品订单 * @return */ @@ -51,7 +51,6 @@ public abstract class AbstractPayOrderHandler implements PayOrderHandler { /** * 调用入口 - * * @return */ @Override @@ -62,4 +61,5 @@ public abstract class AbstractPayOrderHandler implements PayOrderHandler { updateOrder(payGoodsOrder, tradeOrder); return result; } + } diff --git a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/impl/AlipayPayNotifyCallbackHandler.java b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/impl/AlipayPayNotifyCallbackHandler.java index cf6ce8aeb..b3f743418 100644 --- a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/impl/AlipayPayNotifyCallbackHandler.java +++ b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/impl/AlipayPayNotifyCallbackHandler.java @@ -52,14 +52,17 @@ import java.util.Map; @AllArgsConstructor @Service("alipayCallback") public class AlipayPayNotifyCallbackHandler extends AbstractPayNotifyCallbakHandler { + private final MessageDuplicateCheckerHandler duplicateCheckerHandler; + private final PayTradeOrderService tradeOrderService; + private final PayGoodsOrderService goodsOrderService; + private final PayNotifyRecordService recordService; /** * 维护租户信息 - * * @param params */ @Override @@ -70,13 +73,12 @@ public class AlipayPayNotifyCallbackHandler extends AbstractPayNotifyCallbakHand /** * 去重处理 - * * @param params 回调报文 * @return */ @Override public Boolean duplicateChecker(Map params) { - //判断是否是为支付中 + // 判断是否是为支付中 if (StrUtil.equals(TradeStatusEnum.WAIT_BUYER_PAY.getDescription(), params.get(PayConstants.TRADE_STATUS))) { log.info("支付宝订单待支付 {} 不做处理", params); return true; @@ -93,7 +95,6 @@ public class AlipayPayNotifyCallbackHandler extends AbstractPayNotifyCallbakHand /** * 验签逻辑 - * * @param params 回调报文 * @return */ @@ -115,9 +116,9 @@ public class AlipayPayNotifyCallbackHandler extends AbstractPayNotifyCallbakHand } try { - return AlipaySignature.rsaCheckV1(params, apiConfig.getAlipayPublicKey() - , CharsetUtil.UTF_8, "RSA2"); - } catch (AlipayApiException e) { + return AlipaySignature.rsaCheckV1(params, apiConfig.getAlipayPublicKey(), CharsetUtil.UTF_8, "RSA2"); + } + catch (AlipayApiException e) { log.error("支付宝验签失败", e); return false; } @@ -125,22 +126,22 @@ public class AlipayPayNotifyCallbackHandler extends AbstractPayNotifyCallbakHand /** * 解析报文 - * * @param params 回调报文 * @return */ @Override public String parse(Map params) { - String tradeStatus = EnumUtil.fromString(TradeStatusEnum.class, params.get(PayConstants.TRADE_STATUS)).getStatus(); + String tradeStatus = EnumUtil.fromString(TradeStatusEnum.class, params.get(PayConstants.TRADE_STATUS)) + .getStatus(); String orderNo = params.get(PayConstants.OUT_TRADE_NO); - PayGoodsOrder goodsOrder = goodsOrderService.getOne(Wrappers.lambdaQuery() - .eq(PayGoodsOrder::getPayOrderId, orderNo)); + PayGoodsOrder goodsOrder = goodsOrderService + .getOne(Wrappers.lambdaQuery().eq(PayGoodsOrder::getPayOrderId, orderNo)); goodsOrder.setStatus(tradeStatus); goodsOrderService.updateById(goodsOrder); - PayTradeOrder tradeOrder = tradeOrderService.getOne(Wrappers.lambdaQuery() - .eq(PayTradeOrder::getOrderId, orderNo)); + PayTradeOrder tradeOrder = tradeOrderService + .getOne(Wrappers.lambdaQuery().eq(PayTradeOrder::getOrderId, orderNo)); Long succTime = MapUtil.getLong(params, "time_end"); tradeOrder.setPaySuccTime(succTime); tradeOrder.setChannelOrderNo(params.get("trade_no")); @@ -153,7 +154,6 @@ public class AlipayPayNotifyCallbackHandler extends AbstractPayNotifyCallbakHand /** * 保存回调记录 - * * @param result 处理结果 * @param params 回调报文 */ diff --git a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/impl/AlipayWapPayOrderHandler.java b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/impl/AlipayWapPayOrderHandler.java index 5afa48a73..ec828685d 100644 --- a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/impl/AlipayWapPayOrderHandler.java +++ b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/impl/AlipayWapPayOrderHandler.java @@ -49,15 +49,19 @@ import java.io.IOException; @Service("ALIPAY_WAP") @AllArgsConstructor public class AlipayWapPayOrderHandler extends AbstractPayOrderHandler { + private final PayCommonProperties payCommonProperties; + private final PayTradeOrderMapper tradeOrderMapper; + private final PayGoodsOrderMapper goodsOrderMapper; + private final HttpServletRequest request; + private final HttpServletResponse response; /** * 创建交易订单 - * * @param goodsOrder * @return */ @@ -79,7 +83,6 @@ public class AlipayWapPayOrderHandler extends AbstractPayOrderHandler { /** * 调起渠道支付 - * * @param goodsOrder 商品订单 * @param tradeOrder 交易订单 */ @@ -91,20 +94,22 @@ public class AlipayWapPayOrderHandler extends AbstractPayOrderHandler { model.setOutTradeNo(tradeOrder.getOrderId()); model.setTimeoutExpress(payCommonProperties.getAliPayConfig().getExpireTime() + "m"); - //分转成元 并且保留两位 + // 分转成元 并且保留两位 model.setTotalAmount(NumberUtil.div(tradeOrder.getAmount(), "100", 2).toString()); model.setProductCode(goodsOrder.getGoodsId()); model.setPassbackParams(String.valueOf(TenantContextHolder.getTenantId())); try { - AliPayApi.wapPay(response, model, payCommonProperties.getAliPayConfig().getReturnUrl() - , payCommonProperties.getAliPayConfig().getNotifyUrl()); - } catch (AlipayApiException e) { + AliPayApi.wapPay(response, model, payCommonProperties.getAliPayConfig().getReturnUrl(), + payCommonProperties.getAliPayConfig().getNotifyUrl()); + } + catch (AlipayApiException e) { log.error("支付宝手机支付失败", e); tradeOrder.setErrMsg(e.getErrMsg()); tradeOrder.setErrCode(e.getErrCode()); tradeOrder.setStatus(OrderStatusEnum.FAIL.getStatus()); goodsOrder.setStatus(OrderStatusEnum.FAIL.getStatus()); - } catch (IOException e) { + } + catch (IOException e) { log.error("支付宝手机支付失败", e); tradeOrder.setErrMsg(e.getMessage()); tradeOrder.setStatus(OrderStatusEnum.FAIL.getStatus()); @@ -115,7 +120,6 @@ public class AlipayWapPayOrderHandler extends AbstractPayOrderHandler { /** * 更新订单信息 - * * @param goodsOrder 商品订单 * @param tradeOrder 交易订单 */ @@ -124,4 +128,5 @@ public class AlipayWapPayOrderHandler extends AbstractPayOrderHandler { tradeOrderMapper.updateById(tradeOrder); goodsOrderMapper.updateById(goodsOrder); } + } diff --git a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/impl/MessageRedisDuplicateCheckerHandler.java b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/impl/MessageRedisDuplicateCheckerHandler.java index b01f67de0..7f0bb1962 100644 --- a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/impl/MessageRedisDuplicateCheckerHandler.java +++ b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/impl/MessageRedisDuplicateCheckerHandler.java @@ -33,17 +33,17 @@ import java.time.Duration; @Service @AllArgsConstructor public class MessageRedisDuplicateCheckerHandler implements MessageDuplicateCheckerHandler { + private final RedisTemplate redisTemplate; /** * 判断回调消息是否重复. - * * @param messageId messageId需要根据上面讲的方式构造 * @return 如果是重复消息true,否则返回false */ @Override public boolean isDuplicate(String messageId) { - return !redisTemplate.opsForValue() - .setIfAbsent(messageId, messageId, Duration.ofSeconds(10L)); + return !redisTemplate.opsForValue().setIfAbsent(messageId, messageId, Duration.ofSeconds(10L)); } + } diff --git a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/impl/WeChatMpPayOrderHandler.java b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/impl/WeChatMpPayOrderHandler.java index 3dc0385b2..d9c54441a 100644 --- a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/impl/WeChatMpPayOrderHandler.java +++ b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/impl/WeChatMpPayOrderHandler.java @@ -45,18 +45,21 @@ import java.util.Map; @Slf4j @Service("WEIXIN_MP") public class WeChatMpPayOrderHandler extends AbstractPayOrderHandler { + @Autowired private PayCommonProperties payCommonProperties; + @Autowired private PayTradeOrderMapper tradeOrderMapper; + @Autowired private PayGoodsOrderMapper goodsOrderMapper; + @Autowired private HttpServletRequest request; /** * 创建交易订单 - * * @param goodsOrder * @return */ @@ -77,7 +80,6 @@ public class WeChatMpPayOrderHandler extends AbstractPayOrderHandler { /** * 调起渠道支付 - * * @param goodsOrder 商品订单 * @param tradeOrder 交易订单 */ @@ -85,15 +87,11 @@ public class WeChatMpPayOrderHandler extends AbstractPayOrderHandler { public Object pay(PayGoodsOrder goodsOrder, PayTradeOrder tradeOrder) { String ip = ServletUtil.getClientIP(request); Map params = WxPayApiConfigKit.getWxPayApiConfig() - .setAttach(TenantContextHolder.getTenantId().toString()) - .setBody(goodsOrder.getGoodsName()) - .setSpbillCreateIp(ip) - .setTotalFee(goodsOrder.getAmount()) - .setOpenId(goodsOrder.getUserId()) + .setAttach(TenantContextHolder.getTenantId().toString()).setBody(goodsOrder.getGoodsName()) + .setSpbillCreateIp(ip).setTotalFee(goodsOrder.getAmount()).setOpenId(goodsOrder.getUserId()) .setTradeType(WxPayApi.TradeType.JSAPI) .setNotifyUrl(payCommonProperties.getWxPayConfig().getNotifyUrl()) - .setOutTradeNo(tradeOrder.getOrderId()) - .build(); + .setOutTradeNo(tradeOrder.getOrderId()).build(); String xmlResult = WxPayApi.pushOrder(false, params); log.info(xmlResult); @@ -104,7 +102,6 @@ public class WeChatMpPayOrderHandler extends AbstractPayOrderHandler { /** * 更新订单信息 - * * @param goodsOrder 商品订单 * @param tradeOrder 交易订单 */ @@ -113,4 +110,5 @@ public class WeChatMpPayOrderHandler extends AbstractPayOrderHandler { tradeOrderMapper.updateById(tradeOrder); goodsOrderMapper.updateById(goodsOrder); } + } diff --git a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/impl/WeChatPayNotifyCallbackHandler.java b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/impl/WeChatPayNotifyCallbackHandler.java index 0397642d4..f92c72fdc 100644 --- a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/impl/WeChatPayNotifyCallbackHandler.java +++ b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/handler/impl/WeChatPayNotifyCallbackHandler.java @@ -49,14 +49,17 @@ import java.util.Map; @AllArgsConstructor @Service("weChatCallback") public class WeChatPayNotifyCallbackHandler extends AbstractPayNotifyCallbakHandler { + private final MessageDuplicateCheckerHandler duplicateCheckerHandler; + private final PayTradeOrderService tradeOrderService; + private final PayGoodsOrderService goodsOrderService; + private final PayNotifyRecordService recordService; /** * 维护租户信息 - * * @param params */ @Override @@ -67,7 +70,6 @@ public class WeChatPayNotifyCallbackHandler extends AbstractPayNotifyCallbakHand /** * 去重处理 - * * @param params 回调报文 * @return */ @@ -84,7 +86,6 @@ public class WeChatPayNotifyCallbackHandler extends AbstractPayNotifyCallbakHand /** * 验签逻辑 - * * @param params 回调报文 * @return */ @@ -100,22 +101,22 @@ public class WeChatPayNotifyCallbackHandler extends AbstractPayNotifyCallbakHand /** * 解析报文 - * * @param params * @return */ @Override public String parse(Map params) { - String tradeStatus = EnumUtil.fromString(TradeStatusEnum.class, params.get(PayConstants.RESULT_CODE)).getStatus(); + String tradeStatus = EnumUtil.fromString(TradeStatusEnum.class, params.get(PayConstants.RESULT_CODE)) + .getStatus(); String orderNo = params.get(PayConstants.OUT_TRADE_NO); - PayGoodsOrder goodsOrder = goodsOrderService.getOne(Wrappers.lambdaQuery() - .eq(PayGoodsOrder::getPayOrderId, orderNo)); + PayGoodsOrder goodsOrder = goodsOrderService + .getOne(Wrappers.lambdaQuery().eq(PayGoodsOrder::getPayOrderId, orderNo)); goodsOrder.setStatus(tradeStatus); goodsOrderService.updateById(goodsOrder); - PayTradeOrder tradeOrder = tradeOrderService.getOne(Wrappers.lambdaQuery() - .eq(PayTradeOrder::getOrderId, orderNo)); + PayTradeOrder tradeOrder = tradeOrderService + .getOne(Wrappers.lambdaQuery().eq(PayTradeOrder::getOrderId, orderNo)); Long succTime = MapUtil.getLong(params, "time_end"); tradeOrder.setPaySuccTime(succTime); tradeOrder.setStatus(tradeStatus); @@ -132,7 +133,6 @@ public class WeChatPayNotifyCallbackHandler extends AbstractPayNotifyCallbakHand /** * 保存回调记录 - * * @param result 处理结果 * @param params 回调报文 */ @@ -142,4 +142,5 @@ public class WeChatPayNotifyCallbackHandler extends AbstractPayNotifyCallbakHand String notifyId = params.get("transaction_id"); saveRecord(params, result, record, notifyId, recordService); } + } diff --git a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/service/PayChannelService.java b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/service/PayChannelService.java index 32a94c904..fcf26e2a8 100755 --- a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/service/PayChannelService.java +++ b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/service/PayChannelService.java @@ -30,9 +30,9 @@ public interface PayChannelService extends IService { /** * 新增支付渠道 - * * @param payChannel 支付渠道 * @return */ Boolean saveChannel(PayChannel payChannel); + } diff --git a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/service/PayGoodsOrderService.java b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/service/PayGoodsOrderService.java index c3a67f346..cbd141abc 100755 --- a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/service/PayGoodsOrderService.java +++ b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/service/PayGoodsOrderService.java @@ -32,7 +32,6 @@ public interface PayGoodsOrderService extends IService { /** * 购买商品 - * * @param goodsOrder goods * @return */ diff --git a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/service/impl/PayChannelServiceImpl.java b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/service/impl/PayChannelServiceImpl.java index b8231e00e..85f86f310 100755 --- a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/service/impl/PayChannelServiceImpl.java +++ b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/service/impl/PayChannelServiceImpl.java @@ -35,7 +35,6 @@ public class PayChannelServiceImpl extends ServiceImpl implements PayGoodsOrderService { - private final Map orderHandlerMap; - private final HttpServletRequest request; +public class PayGoodsOrderServiceImpl extends ServiceImpl + implements PayGoodsOrderService { + private final Map orderHandlerMap; + + private final HttpServletRequest request; /** * 下单购买 - * * @param goodsOrder * @return */ diff --git a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/service/impl/PayNotifyRecordServiceImpl.java b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/service/impl/PayNotifyRecordServiceImpl.java index 83bb6a80c..ddcdc74e3 100755 --- a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/service/impl/PayNotifyRecordServiceImpl.java +++ b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/service/impl/PayNotifyRecordServiceImpl.java @@ -33,6 +33,7 @@ import org.springframework.stereotype.Service; @Slf4j @Service @AllArgsConstructor -public class PayNotifyRecordServiceImpl extends ServiceImpl implements PayNotifyRecordService { +public class PayNotifyRecordServiceImpl extends ServiceImpl + implements PayNotifyRecordService { } diff --git a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/service/impl/PayRefundOrderServiceImpl.java b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/service/impl/PayRefundOrderServiceImpl.java index 0c580cedc..9f5f69bdd 100755 --- a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/service/impl/PayRefundOrderServiceImpl.java +++ b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/service/impl/PayRefundOrderServiceImpl.java @@ -29,6 +29,7 @@ import org.springframework.stereotype.Service; * @date 2019-05-28 23:58:11 */ @Service -public class PayRefundOrderServiceImpl extends ServiceImpl implements PayRefundOrderService { +public class PayRefundOrderServiceImpl extends ServiceImpl + implements PayRefundOrderService { } diff --git a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/service/impl/PayTradeOrderServiceImpl.java b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/service/impl/PayTradeOrderServiceImpl.java index 9b9042c79..4a346c3d8 100755 --- a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/service/impl/PayTradeOrderServiceImpl.java +++ b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/service/impl/PayTradeOrderServiceImpl.java @@ -29,6 +29,7 @@ import org.springframework.stereotype.Service; * @date 2019-05-28 23:58:18 */ @Service -public class PayTradeOrderServiceImpl extends ServiceImpl implements PayTradeOrderService { +public class PayTradeOrderServiceImpl extends ServiceImpl + implements PayTradeOrderService { } diff --git a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/utils/OrderStatusEnum.java b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/utils/OrderStatusEnum.java index dd5be2820..493fb1521 100644 --- a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/utils/OrderStatusEnum.java +++ b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/utils/OrderStatusEnum.java @@ -12,6 +12,7 @@ import lombok.Getter; @Getter @AllArgsConstructor public enum OrderStatusEnum { + /** * 订单初始 下单 */ @@ -32,13 +33,14 @@ public enum OrderStatusEnum { */ FAIL("-1", "失败"); - /** * 状态 */ private String status; + /** * 描述 */ private String description; + } diff --git a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/utils/PayChannelNameEnum.java b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/utils/PayChannelNameEnum.java index e4ae636dc..71bafdd61 100644 --- a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/utils/PayChannelNameEnum.java +++ b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/utils/PayChannelNameEnum.java @@ -11,6 +11,7 @@ import lombok.Getter; */ @AllArgsConstructor public enum PayChannelNameEnum { + /** * 支付宝wap支付 */ @@ -31,6 +32,7 @@ public enum PayChannelNameEnum { */ @Getter private String name; + /** * 描述 */ @@ -38,17 +40,19 @@ public enum PayChannelNameEnum { /** * 通过ua 判断所属渠道 - * * @param ua 浏览器类型 * @return */ public static Enum getChannel(String ua) { if (ua.contains(PayConstants.ALIPAY)) { return PayChannelNameEnum.ALIPAY_WAP; - } else if (ua.contains(PayConstants.MICRO_MESSENGER)) { + } + else if (ua.contains(PayConstants.MICRO_MESSENGER)) { return PayChannelNameEnum.WEIXIN_MP; - } else { + } + else { return PayChannelNameEnum.WEIXIN_WAP; } } + } diff --git a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/utils/PayConstants.java b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/utils/PayConstants.java index 400192bb9..db070ff0e 100644 --- a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/utils/PayConstants.java +++ b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/utils/PayConstants.java @@ -33,5 +33,4 @@ public interface PayConstants { */ String TRADE_STATUS = "trade_status"; - } diff --git a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/utils/TradeStatusEnum.java b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/utils/TradeStatusEnum.java index 83016cbca..da1d29679 100644 --- a/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/utils/TradeStatusEnum.java +++ b/pigx-visual/pigx-pay-platform/src/main/java/com/pig4cloud/pigx/pay/utils/TradeStatusEnum.java @@ -10,6 +10,7 @@ import lombok.Getter; @Getter @AllArgsConstructor public enum TradeStatusEnum { + /** * 交易完成 */ @@ -40,13 +41,14 @@ public enum TradeStatusEnum { */ FAIL("FAIL", OrderStatusEnum.FAIL.getStatus()); - /** * 描述 */ private String description; + /** * 描述 */ private String status; + } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/PigxSentinelApplication.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/PigxSentinelApplication.java index 9d87f81f0..e8c67fe19 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/PigxSentinelApplication.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/PigxSentinelApplication.java @@ -23,8 +23,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; /** * @author nacos *

- * sentinel console 源码运行,方便开发 - * 生产建议从官网下载最新版配置运行 + * sentinel console 源码运行,方便开发 生产建议从官网下载最新版配置运行 */ @SpringBootApplication public class PigxSentinelApplication { @@ -37,4 +36,5 @@ public class PigxSentinelApplication { private static void triggerSentinelInit() { new Thread(InitExecutor::doInit).start(); } + } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/auth/AuthAction.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/auth/AuthAction.java index f521c04df..641c17499 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/auth/AuthAction.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/auth/AuthAction.java @@ -27,21 +27,22 @@ import java.lang.annotation.Target; */ @Retention(RetentionPolicy.RUNTIME) @Documented -@Target({ElementType.METHOD}) +@Target({ ElementType.METHOD }) public @interface AuthAction { - /** - * @return the privilege type - */ - AuthService.PrivilegeType value(); + /** + * @return the privilege type + */ + AuthService.PrivilegeType value(); - /** - * @return the target name to control - */ - String targetName() default "app"; + /** + * @return the target name to control + */ + String targetName() default "app"; + + /** + * @return the message when permission is denied + */ + String message() default "Permission denied"; - /** - * @return the message when permission is denied - */ - String message() default "Permission denied"; } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/auth/AuthService.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/auth/AuthService.java index cdda6a3b9..2c60d8ffa 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/auth/AuthService.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/auth/AuthService.java @@ -23,91 +23,90 @@ package com.alibaba.csp.sentinel.dashboard.auth; */ public interface AuthService { - /** - * Get the authentication user. - * - * @param request the request contains the user information - * @return the auth user represent the current user, when the user is illegal, a null value will return. - */ - AuthUser getAuthUser(R request); + /** + * Get the authentication user. + * @param request the request contains the user information + * @return the auth user represent the current user, when the user is illegal, a null + * value will return. + */ + AuthUser getAuthUser(R request); - /** - * Privilege type. - */ - enum PrivilegeType { - /** - * Read rule - */ - READ_RULE, - /** - * Create or modify rule - */ - WRITE_RULE, - /** - * Delete rule - */ - DELETE_RULE, - /** - * Read metrics - */ - READ_METRIC, - /** - * Add machine - */ - ADD_MACHINE, - /** - * All privileges above are granted. - */ - ALL - } + /** + * Privilege type. + */ + enum PrivilegeType { - /** - * Represents the current user. - */ - interface AuthUser { + /** + * Read rule + */ + READ_RULE, + /** + * Create or modify rule + */ + WRITE_RULE, + /** + * Delete rule + */ + DELETE_RULE, + /** + * Read metrics + */ + READ_METRIC, + /** + * Add machine + */ + ADD_MACHINE, + /** + * All privileges above are granted. + */ + ALL - /** - * Query whether current user has the specific privilege to the target, the target - * may be an app name or an ip address, or other destination. - *

- * This method will use return value to represent whether user has the specific - * privileges to the target, but to throw a RuntimeException to represent no auth - * is also a good way. - *

- * - * @param target the target to check - * @param privilegeType the privilege type to check - * @return if current user has the specific privileges to the target, return true, - * otherwise return false. - */ - boolean authTarget(String target, PrivilegeType privilegeType); + } - /** - * Check whether current user is a super-user. - * - * @return if current user is super user return true, else return false. - */ - boolean isSuperUser(); + /** + * Represents the current user. + */ + interface AuthUser { - /** - * Get current user's nick name. - * - * @return current user's nick name. - */ - String getNickName(); + /** + * Query whether current user has the specific privilege to the target, the target + * may be an app name or an ip address, or other destination. + *

+ * This method will use return value to represent whether user has the specific + * privileges to the target, but to throw a RuntimeException to represent no auth + * is also a good way. + *

+ * @param target the target to check + * @param privilegeType the privilege type to check + * @return if current user has the specific privileges to the target, return true, + * otherwise return false. + */ + boolean authTarget(String target, PrivilegeType privilegeType); - /** - * Get current user's login name. - * - * @return current user's login name. - */ - String getLoginName(); + /** + * Check whether current user is a super-user. + * @return if current user is super user return true, else return false. + */ + boolean isSuperUser(); + + /** + * Get current user's nick name. + * @return current user's nick name. + */ + String getNickName(); + + /** + * Get current user's login name. + * @return current user's login name. + */ + String getLoginName(); + + /** + * Get current user's ID. + * @return ID of current user + */ + String getId(); + + } - /** - * Get current user's ID. - * - * @return ID of current user - */ - String getId(); - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/auth/AuthorizationInterceptor.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/auth/AuthorizationInterceptor.java index 19472521a..816f9d858 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/auth/AuthorizationInterceptor.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/auth/AuthorizationInterceptor.java @@ -36,37 +36,38 @@ import java.lang.reflect.Method; @Component public class AuthorizationInterceptor implements HandlerInterceptor { - @Autowired - private AuthService authService; + @Autowired + private AuthService authService; - @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) - throws Exception { - if (handler.getClass().isAssignableFrom(HandlerMethod.class)) { - Method method = ((HandlerMethod) handler).getMethod(); + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) + throws Exception { + if (handler.getClass().isAssignableFrom(HandlerMethod.class)) { + Method method = ((HandlerMethod) handler).getMethod(); - AuthAction authAction = method.getAnnotation(AuthAction.class); - if (authAction != null) { - AuthService.AuthUser authUser = authService.getAuthUser(request); - if (authUser == null) { - responseNoPrivilegeMsg(response, authAction.message()); - return false; - } - String target = request.getParameter(authAction.targetName()); + AuthAction authAction = method.getAnnotation(AuthAction.class); + if (authAction != null) { + AuthService.AuthUser authUser = authService.getAuthUser(request); + if (authUser == null) { + responseNoPrivilegeMsg(response, authAction.message()); + return false; + } + String target = request.getParameter(authAction.targetName()); - if (!authUser.authTarget(target, authAction.value())) { - responseNoPrivilegeMsg(response, authAction.message()); - return false; - } - } - } + if (!authUser.authTarget(target, authAction.value())) { + responseNoPrivilegeMsg(response, authAction.message()); + return false; + } + } + } - return true; - } + return true; + } + + private void responseNoPrivilegeMsg(HttpServletResponse response, String message) throws IOException { + Result result = Result.ofFail(-1, message); + response.addHeader("Content-Type", "application/json;charset=UTF-8"); + response.getOutputStream().write(JSON.toJSONBytes(result)); + } - private void responseNoPrivilegeMsg(HttpServletResponse response, String message) throws IOException { - Result result = Result.ofFail(-1, message); - response.addHeader("Content-Type", "application/json;charset=UTF-8"); - response.getOutputStream().write(JSON.toJSONBytes(result)); - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/auth/FakeAuthServiceImpl.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/auth/FakeAuthServiceImpl.java index b40ea5642..a90ce1c0d 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/auth/FakeAuthServiceImpl.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/auth/FakeAuthServiceImpl.java @@ -28,38 +28,40 @@ import org.springframework.stereotype.Component; @Component public class FakeAuthServiceImpl implements AuthService { - @Override - public AuthUser getAuthUser(HttpServletRequest request) { - return new AuthUserImpl(); - } + @Override + public AuthUser getAuthUser(HttpServletRequest request) { + return new AuthUserImpl(); + } - static final class AuthUserImpl implements AuthUser { + static final class AuthUserImpl implements AuthUser { - @Override - public boolean authTarget(String target, PrivilegeType privilegeType) { - // fake implementation, always return true - return true; - } + @Override + public boolean authTarget(String target, PrivilegeType privilegeType) { + // fake implementation, always return true + return true; + } - @Override - public boolean isSuperUser() { - // fake implementation, always return true - return true; - } + @Override + public boolean isSuperUser() { + // fake implementation, always return true + return true; + } - @Override - public String getNickName() { - return "FAKE_NICK_NAME"; - } + @Override + public String getNickName() { + return "FAKE_NICK_NAME"; + } - @Override - public String getLoginName() { - return "FAKE_LOGIN_NAME"; - } + @Override + public String getLoginName() { + return "FAKE_LOGIN_NAME"; + } + + @Override + public String getId() { + return "FAKE_EMP_ID"; + } + + } - @Override - public String getId() { - return "FAKE_EMP_ID"; - } - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/auth/LoginAuthenticationFilter.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/auth/LoginAuthenticationFilter.java index f489b48e7..aab3a5112 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/auth/LoginAuthenticationFilter.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/auth/LoginAuthenticationFilter.java @@ -34,9 +34,13 @@ import java.io.IOException; import java.util.List; /** - *

The Servlet filter for authentication.

+ *

+ * The Servlet filter for authentication. + *

* - *

Note: some urls are excluded as they needn't auth, such as:

+ *

+ * Note: some urls are excluded as they needn't auth, such as: + *

*
    *
  • index url: {@code /}
  • *
  • authentication request url: {@code /login}, {@code /logout}
  • @@ -44,7 +48,8 @@ import java.util.List; *
  • static resources
  • *
* - * The excluded urls and urlSuffixes could be configured in {@code application.properties} file. + * The excluded urls and urlSuffixes could be configured in {@code application.properties} + * file. * * @author cdfive * @since 1.6.0 @@ -52,74 +57,76 @@ import java.util.List; @Component public class LoginAuthenticationFilter implements Filter { - private static final String URL_SUFFIX_DOT = "."; + private static final String URL_SUFFIX_DOT = "."; - /** - * Some urls which needn't auth, such as /auth/login, /registry/machine and so on. - */ - @Value("#{'${auth.filter.exclude-urls}'.split(',')}") - private List authFilterExcludeUrls; + /** + * Some urls which needn't auth, such as /auth/login, /registry/machine and so on. + */ + @Value("#{'${auth.filter.exclude-urls}'.split(',')}") + private List authFilterExcludeUrls; - /** - * Some urls with suffixes which needn't auth, such as htm, html, js and so on. - */ - @Value("#{'${auth.filter.exclude-url-suffixes}'.split(',')}") - private List authFilterExcludeUrlSuffixes; + /** + * Some urls with suffixes which needn't auth, such as htm, html, js and so on. + */ + @Value("#{'${auth.filter.exclude-url-suffixes}'.split(',')}") + private List authFilterExcludeUrlSuffixes; - /** - * Authentication using AuthService interface. - */ - @Autowired - private AuthService authService; + /** + * Authentication using AuthService interface. + */ + @Autowired + private AuthService authService; - @Override - public void init(FilterConfig filterConfig) throws ServletException { + @Override + public void init(FilterConfig filterConfig) throws ServletException { - } + } - @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) - throws IOException, ServletException { - HttpServletRequest httpRequest = (HttpServletRequest) request; + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { + HttpServletRequest httpRequest = (HttpServletRequest) request; - String servletPath = httpRequest.getServletPath(); + String servletPath = httpRequest.getServletPath(); - // Exclude the urls which needn't auth - if (authFilterExcludeUrls.contains(servletPath)) { - chain.doFilter(request, response); - return; - } + // Exclude the urls which needn't auth + if (authFilterExcludeUrls.contains(servletPath)) { + chain.doFilter(request, response); + return; + } - // Exclude the urls with suffixes which needn't auth - for (String authFilterExcludeUrlSuffix : authFilterExcludeUrlSuffixes) { - if (StringUtils.isBlank(authFilterExcludeUrlSuffix)) { - continue; - } + // Exclude the urls with suffixes which needn't auth + for (String authFilterExcludeUrlSuffix : authFilterExcludeUrlSuffixes) { + if (StringUtils.isBlank(authFilterExcludeUrlSuffix)) { + continue; + } - // Add . for url suffix so that we needn't add . in property file - if (!authFilterExcludeUrlSuffix.startsWith(URL_SUFFIX_DOT)) { - authFilterExcludeUrlSuffix = URL_SUFFIX_DOT + authFilterExcludeUrlSuffix; - } + // Add . for url suffix so that we needn't add . in property file + if (!authFilterExcludeUrlSuffix.startsWith(URL_SUFFIX_DOT)) { + authFilterExcludeUrlSuffix = URL_SUFFIX_DOT + authFilterExcludeUrlSuffix; + } - if (servletPath.endsWith(authFilterExcludeUrlSuffix)) { - chain.doFilter(request, response); - return; - } - } + if (servletPath.endsWith(authFilterExcludeUrlSuffix)) { + chain.doFilter(request, response); + return; + } + } - AuthService.AuthUser authUser = authService.getAuthUser(httpRequest); + AuthService.AuthUser authUser = authService.getAuthUser(httpRequest); - HttpServletResponse httpResponse = (HttpServletResponse) response; - if (authUser == null) { - // If auth fail, set response status code to 401 - httpResponse.setStatus(HttpStatus.UNAUTHORIZED.value()); - } else { - chain.doFilter(request, response); - } - } + HttpServletResponse httpResponse = (HttpServletResponse) response; + if (authUser == null) { + // If auth fail, set response status code to 401 + httpResponse.setStatus(HttpStatus.UNAUTHORIZED.value()); + } + else { + chain.doFilter(request, response); + } + } - @Override - public void destroy() { + @Override + public void destroy() { + + } - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/auth/SimpleWebAuthServiceImpl.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/auth/SimpleWebAuthServiceImpl.java index 5d9599ee9..bf85b49e8 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/auth/SimpleWebAuthServiceImpl.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/auth/SimpleWebAuthServiceImpl.java @@ -31,50 +31,52 @@ import javax.servlet.http.HttpSession; @ConditionalOnProperty(name = "auth.enabled", matchIfMissing = true) public class SimpleWebAuthServiceImpl implements AuthService { - public static final String WEB_SESSION_KEY = "session_sentinel_admin"; + public static final String WEB_SESSION_KEY = "session_sentinel_admin"; - @Override - public AuthUser getAuthUser(HttpServletRequest request) { - HttpSession session = request.getSession(); - Object sentinelUserObj = session.getAttribute(SimpleWebAuthServiceImpl.WEB_SESSION_KEY); - if (sentinelUserObj != null && sentinelUserObj instanceof AuthUser) { - return (AuthUser) sentinelUserObj; - } + @Override + public AuthUser getAuthUser(HttpServletRequest request) { + HttpSession session = request.getSession(); + Object sentinelUserObj = session.getAttribute(SimpleWebAuthServiceImpl.WEB_SESSION_KEY); + if (sentinelUserObj != null && sentinelUserObj instanceof AuthUser) { + return (AuthUser) sentinelUserObj; + } - return null; - } + return null; + } - public static final class SimpleWebAuthUserImpl implements AuthUser { + public static final class SimpleWebAuthUserImpl implements AuthUser { - private String username; + private String username; - public SimpleWebAuthUserImpl(String username) { - this.username = username; - } + public SimpleWebAuthUserImpl(String username) { + this.username = username; + } - @Override - public boolean authTarget(String target, PrivilegeType privilegeType) { - return true; - } + @Override + public boolean authTarget(String target, PrivilegeType privilegeType) { + return true; + } - @Override - public boolean isSuperUser() { - return true; - } + @Override + public boolean isSuperUser() { + return true; + } - @Override - public String getNickName() { - return username; - } + @Override + public String getNickName() { + return username; + } - @Override - public String getLoginName() { - return username; - } + @Override + public String getLoginName() { + return username; + } + + @Override + public String getId() { + return username; + } + + } - @Override - public String getId() { - return username; - } - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/client/CommandFailedException.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/client/CommandFailedException.java index 76b6aeb10..7408a6b26 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/client/CommandFailedException.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/client/CommandFailedException.java @@ -20,14 +20,16 @@ package com.alibaba.csp.sentinel.dashboard.client; */ public class CommandFailedException extends RuntimeException { - public CommandFailedException() {} + public CommandFailedException() { + } - public CommandFailedException(String message) { - super(message); - } + public CommandFailedException(String message) { + super(message); + } + + @Override + public synchronized Throwable fillInStackTrace() { + return this; + } - @Override - public synchronized Throwable fillInStackTrace() { - return this; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/client/CommandNotFoundException.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/client/CommandNotFoundException.java index 0db956807..375af1107 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/client/CommandNotFoundException.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/client/CommandNotFoundException.java @@ -21,14 +21,16 @@ package com.alibaba.csp.sentinel.dashboard.client; */ public class CommandNotFoundException extends Exception { - public CommandNotFoundException() { } + public CommandNotFoundException() { + } - public CommandNotFoundException(String message) { - super(message); - } + public CommandNotFoundException(String message) { + super(message); + } + + @Override + public synchronized Throwable fillInStackTrace() { + return this; + } - @Override - public synchronized Throwable fillInStackTrace() { - return this; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/client/SentinelApiClient.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/client/SentinelApiClient.java index 008e67c1e..2fe43ef27 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/client/SentinelApiClient.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/client/SentinelApiClient.java @@ -90,729 +90,771 @@ import org.springframework.stereotype.Component; */ @Component public class SentinelApiClient { - private static Logger logger = LoggerFactory.getLogger(SentinelApiClient.class); - private static final Charset DEFAULT_CHARSET = Charset.forName(SentinelConfig.charset()); + private static Logger logger = LoggerFactory.getLogger(SentinelApiClient.class); - private static final String RESOURCE_URL_PATH = "jsonTree"; - private static final String CLUSTER_NODE_PATH = "clusterNode"; - private static final String GET_RULES_PATH = "getRules"; - private static final String SET_RULES_PATH = "setRules"; - private static final String GET_PARAM_RULE_PATH = "getParamFlowRules"; - private static final String SET_PARAM_RULE_PATH = "setParamFlowRules"; + private static final Charset DEFAULT_CHARSET = Charset.forName(SentinelConfig.charset()); - private static final String FETCH_CLUSTER_MODE_PATH = "getClusterMode"; - private static final String MODIFY_CLUSTER_MODE_PATH = "setClusterMode"; - private static final String FETCH_CLUSTER_CLIENT_CONFIG_PATH = "cluster/client/fetchConfig"; - private static final String MODIFY_CLUSTER_CLIENT_CONFIG_PATH = "cluster/client/modifyConfig"; + private static final String RESOURCE_URL_PATH = "jsonTree"; - private static final String FETCH_CLUSTER_SERVER_ALL_CONFIG_PATH = "cluster/server/fetchConfig"; - private static final String FETCH_CLUSTER_SERVER_BASIC_INFO_PATH = "cluster/server/info"; + private static final String CLUSTER_NODE_PATH = "clusterNode"; - private static final String MODIFY_CLUSTER_SERVER_TRANSPORT_CONFIG_PATH = "cluster/server/modifyTransportConfig"; - private static final String MODIFY_CLUSTER_SERVER_FLOW_CONFIG_PATH = "cluster/server/modifyFlowConfig"; - private static final String MODIFY_CLUSTER_SERVER_NAMESPACE_SET_PATH = "cluster/server/modifyNamespaceSet"; + private static final String GET_RULES_PATH = "getRules"; - private static final String FETCH_GATEWAY_API_PATH = "gateway/getApiDefinitions"; - private static final String MODIFY_GATEWAY_API_PATH = "gateway/updateApiDefinitions"; + private static final String SET_RULES_PATH = "setRules"; - private static final String FETCH_GATEWAY_FLOW_RULE_PATH = "gateway/getRules"; - private static final String MODIFY_GATEWAY_FLOW_RULE_PATH = "gateway/updateRules"; + private static final String GET_PARAM_RULE_PATH = "getParamFlowRules"; - private static final String FLOW_RULE_TYPE = "flow"; - private static final String DEGRADE_RULE_TYPE = "degrade"; - private static final String SYSTEM_RULE_TYPE = "system"; - private static final String AUTHORITY_TYPE = "authority"; + private static final String SET_PARAM_RULE_PATH = "setParamFlowRules"; - private CloseableHttpAsyncClient httpClient; + private static final String FETCH_CLUSTER_MODE_PATH = "getClusterMode"; - private static final SentinelVersion version160 = new SentinelVersion(1, 6, 0); - - @Autowired - private AppManagement appManagement; + private static final String MODIFY_CLUSTER_MODE_PATH = "setClusterMode"; - public SentinelApiClient() { - IOReactorConfig ioConfig = IOReactorConfig.custom().setConnectTimeout(3000).setSoTimeout(10000) - .setIoThreadCount(Runtime.getRuntime().availableProcessors() * 2).build(); - httpClient = HttpAsyncClients.custom().setRedirectStrategy(new DefaultRedirectStrategy() { - @Override - protected boolean isRedirectable(final String method) { - return false; - } - }).setMaxConnTotal(4000).setMaxConnPerRoute(1000).setDefaultIOReactorConfig(ioConfig).build(); - httpClient.start(); - } + private static final String FETCH_CLUSTER_CLIENT_CONFIG_PATH = "cluster/client/fetchConfig"; - private boolean isSuccess(int statusCode) { - return statusCode >= 200 && statusCode < 300; - } - - private boolean isCommandNotFound(int statusCode, String body) { - return statusCode == 400 && StringUtil.isNotEmpty(body) && body.contains(CommandConstants.MSG_UNKNOWN_COMMAND_PREFIX); - } - - private StringBuilder queryString(Map params) { - StringBuilder queryStringBuilder = new StringBuilder(); - for (Entry entry : params.entrySet()) { - if (StringUtil.isEmpty(entry.getValue())) { - continue; - } - String name = urlEncode(entry.getKey()); - String value = urlEncode(entry.getValue()); - if (name != null && value != null) { - if (queryStringBuilder.length() > 0) { - queryStringBuilder.append('&'); - } - queryStringBuilder.append(name).append('=').append(value); - } - } - return queryStringBuilder; - } - - private HttpUriRequest postRequest(String url, Map params) { - HttpPost httpPost = new HttpPost(url); - if (params != null && params.size() > 0) { - List list = new ArrayList<>(params.size()); - for (Entry entry : params.entrySet()) { - list.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); - } - httpPost.setEntity(new UrlEncodedFormEntity(list, Consts.UTF_8)); - } - return httpPost; - } - - private String urlEncode(String str) { - try { - return URLEncoder.encode(str, DEFAULT_CHARSET.name()); - } catch (UnsupportedEncodingException e) { - logger.info("encode string error: {}", str, e); - return null; - } - } - - private String getBody(HttpResponse response) throws Exception { - Charset charset = null; - try { - String contentTypeStr = response.getFirstHeader("Content-type").getValue(); - if (StringUtil.isNotEmpty(contentTypeStr)) { - ContentType contentType = ContentType.parse(contentTypeStr); - charset = contentType.getCharset(); - } - } catch (Exception ignore) { - } - return EntityUtils.toString(response.getEntity(), charset != null ? charset : DEFAULT_CHARSET); - } - - /** - * With no param - * - * @param ip - * @param port - * @param api - * @return - */ - private CompletableFuture executeCommand(String ip, int port, String api, boolean useHttpPost) { - return executeCommand(ip, port, api, null, useHttpPost); - } - - /** - * No app specified, force to GET - * - * @param ip - * @param port - * @param api - * @param params - * @return - */ - private CompletableFuture executeCommand(String ip, int port, String api, Map params, boolean useHttpPost) { - return executeCommand(null, ip, port, api, params, useHttpPost); - } + private static final String MODIFY_CLUSTER_CLIENT_CONFIG_PATH = "cluster/client/modifyConfig"; - /** - * Prefer to execute request using POST - * - * @param app - * @param ip - * @param port - * @param api - * @param params - * @return - */ - private CompletableFuture executeCommand(String app, String ip, int port, String api, Map params, boolean useHttpPost) { - CompletableFuture future = new CompletableFuture<>(); - if (StringUtil.isBlank(ip) || StringUtil.isBlank(api)) { - future.completeExceptionally(new IllegalArgumentException("Bad URL or command name")); - return future; - } - StringBuilder urlBuilder = new StringBuilder(); - urlBuilder.append("http://"); - urlBuilder.append(ip).append(':').append(port).append('/').append(api); - if (params == null) { - params = Collections.emptyMap(); - } - boolean supportPost = StringUtil.isNotEmpty(app) && Optional.ofNullable(appManagement.getDetailApp(app)) - .flatMap(e -> e.getMachine(ip, port)) - .flatMap(m -> VersionUtils.parseVersion(m.getVersion()) - .map(v -> v.greaterOrEqual(version160))) - .orElse(false); - if (!useHttpPost || !supportPost) { - // Using GET in older versions, append parameters after url - if (!params.isEmpty()) { - if (urlBuilder.indexOf("?") == -1) { - urlBuilder.append('?'); - } else { - urlBuilder.append('&'); - } - urlBuilder.append(queryString(params)); - } - return executeCommand(new HttpGet(urlBuilder.toString())); - } else { - // Using POST - return executeCommand(postRequest(urlBuilder.toString(), params)); - } - } - - private CompletableFuture executeCommand(HttpUriRequest request) { - CompletableFuture future = new CompletableFuture<>(); - httpClient.execute(request, new FutureCallback() { - @Override - public void completed(final HttpResponse response) { - int statusCode = response.getStatusLine().getStatusCode(); - try { - String value = getBody(response); - if (isSuccess(statusCode)) { - future.complete(value); - } else { - if (isCommandNotFound(statusCode, value)) { - future.completeExceptionally(new CommandNotFoundException(request.getURI().getPath())); - } else { - future.completeExceptionally(new CommandFailedException(value)); - } - } + private static final String FETCH_CLUSTER_SERVER_ALL_CONFIG_PATH = "cluster/server/fetchConfig"; - } catch (Exception ex) { - future.completeExceptionally(ex); - logger.error("HTTP request failed: {}", request.getURI().toString(), ex); - } - } + private static final String FETCH_CLUSTER_SERVER_BASIC_INFO_PATH = "cluster/server/info"; - @Override - public void failed(final Exception ex) { - future.completeExceptionally(ex); - logger.error("HTTP request failed: {}", request.getURI().toString(), ex); - } + private static final String MODIFY_CLUSTER_SERVER_TRANSPORT_CONFIG_PATH = "cluster/server/modifyTransportConfig"; - @Override - public void cancelled() { - future.complete(null); - } - }); - return future; - } - - public void close() throws Exception { - httpClient.close(); - } - - @Nullable - private CompletableFuture> fetchItemsAsync(String ip, int port, String api, String type, Class ruleType) { - AssertUtil.notEmpty(ip, "Bad machine IP"); - AssertUtil.isTrue(port > 0, "Bad machine port"); - Map params = null; - if (StringUtil.isNotEmpty(type)) { - params = new HashMap<>(1); - params.put("type", type); - } - return executeCommand(ip, port, api, params, false) - .thenApply(json -> JSON.parseArray(json, ruleType)); - } - - @Nullable - private List fetchItems(String ip, int port, String api, String type, Class ruleType) { - try { - AssertUtil.notEmpty(ip, "Bad machine IP"); - AssertUtil.isTrue(port > 0, "Bad machine port"); - Map params = null; - if (StringUtil.isNotEmpty(type)) { - params = new HashMap<>(1); - params.put("type", type); - } - return fetchItemsAsync(ip, port, api, type, ruleType).get(); - } catch (InterruptedException | ExecutionException e) { - logger.error("Error when fetching items from api: {} -> {}", api, type, e); - return null; - } catch (Exception e) { - logger.error("Error when fetching items: {} -> {}", api, type, e); - return null; - } - } - - private List fetchRules(String ip, int port, String type, Class ruleType) { - return fetchItems(ip, port, GET_RULES_PATH, type, ruleType); - } - - private boolean setRules(String app, String ip, int port, String type, List entities) { - if (entities == null) { - return true; - } - try { - AssertUtil.notEmpty(app, "Bad app name"); - AssertUtil.notEmpty(ip, "Bad machine IP"); - AssertUtil.isTrue(port > 0, "Bad machine port"); - String data = JSON.toJSONString( - entities.stream().map(r -> r.toRule()).collect(Collectors.toList())); - Map params = new HashMap<>(2); - params.put("type", type); - params.put("data", data); - String result = executeCommand(app, ip, port, SET_RULES_PATH, params, true).get(); - logger.info("setRules result: {}, type={}", result, type); - return true; - } catch (InterruptedException e) { - logger.warn("setRules API failed: {}", type, e); - return false; - } catch (ExecutionException e) { - logger.warn("setRules API failed: {}", type, e.getCause()); - return false; - } catch (Exception e) { - logger.error("setRules API failed, type={}", type, e); - return false; - } - } + private static final String MODIFY_CLUSTER_SERVER_FLOW_CONFIG_PATH = "cluster/server/modifyFlowConfig"; - private CompletableFuture setRulesAsync(String app, String ip, int port, String type, List entities) { - try { - AssertUtil.notNull(entities, "rules cannot be null"); - AssertUtil.notEmpty(app, "Bad app name"); - AssertUtil.notEmpty(ip, "Bad machine IP"); - AssertUtil.isTrue(port > 0, "Bad machine port"); - String data = JSON.toJSONString( - entities.stream().map(r -> r.toRule()).collect(Collectors.toList())); - Map params = new HashMap<>(2); - params.put("type", type); - params.put("data", data); - return executeCommand(app, ip, port, SET_RULES_PATH, params, true) - .thenCompose(r -> { - if ("success".equalsIgnoreCase(r.trim())) { - return CompletableFuture.completedFuture(null); - } - return AsyncUtils.newFailedFuture(new CommandFailedException(r)); - }); - } catch (Exception e) { - logger.error("setRulesAsync API failed, type={}", type, e); - return AsyncUtils.newFailedFuture(e); - } - } + private static final String MODIFY_CLUSTER_SERVER_NAMESPACE_SET_PATH = "cluster/server/modifyNamespaceSet"; - public List fetchResourceOfMachine(String ip, int port, String type) { - return fetchItems(ip, port, RESOURCE_URL_PATH, type, NodeVo.class); - } + private static final String FETCH_GATEWAY_API_PATH = "gateway/getApiDefinitions"; - /** - * Fetch cluster node. - * - * @param ip ip to fetch - * @param port port of the ip - * @param includeZero whether zero value should in the result list. - * @return - */ - public List fetchClusterNodeOfMachine(String ip, int port, boolean includeZero) { - String type = "notZero"; - if (includeZero) { - type = "zero"; - } - return fetchItems(ip, port, CLUSTER_NODE_PATH, type, NodeVo.class); - } + private static final String MODIFY_GATEWAY_API_PATH = "gateway/updateApiDefinitions"; - public List fetchFlowRuleOfMachine(String app, String ip, int port) { - List rules = fetchRules(ip, port, FLOW_RULE_TYPE, FlowRule.class); - if (rules != null) { - return rules.stream().map(rule -> FlowRuleEntity.fromFlowRule(app, ip, port, rule)) - .collect(Collectors.toList()); - } else { - return null; - } - } + private static final String FETCH_GATEWAY_FLOW_RULE_PATH = "gateway/getRules"; - public List fetchDegradeRuleOfMachine(String app, String ip, int port) { - List rules = fetchRules(ip, port, DEGRADE_RULE_TYPE, DegradeRule.class); - if (rules != null) { - return rules.stream().map(rule -> DegradeRuleEntity.fromDegradeRule(app, ip, port, rule)) - .collect(Collectors.toList()); - } else { - return null; - } - } + private static final String MODIFY_GATEWAY_FLOW_RULE_PATH = "gateway/updateRules"; - public List fetchSystemRuleOfMachine(String app, String ip, int port) { - List rules = fetchRules(ip, port, SYSTEM_RULE_TYPE, SystemRule.class); - if (rules != null) { - return rules.stream().map(rule -> SystemRuleEntity.fromSystemRule(app, ip, port, rule)) - .collect(Collectors.toList()); - } else { - return null; - } - } + private static final String FLOW_RULE_TYPE = "flow"; - /** - * Fetch all parameter flow rules from provided machine. - * - * @param app application name - * @param ip machine client IP - * @param port machine client port - * @return all retrieved parameter flow rules - * @since 0.2.1 - */ - public CompletableFuture> fetchParamFlowRulesOfMachine(String app, String ip, int port) { - try { - AssertUtil.notEmpty(app, "Bad app name"); - AssertUtil.notEmpty(ip, "Bad machine IP"); - AssertUtil.isTrue(port > 0, "Bad machine port"); - return fetchItemsAsync(ip, port, GET_PARAM_RULE_PATH, null, ParamFlowRule.class) - .thenApply(rules -> rules.stream() - .map(e -> ParamFlowRuleEntity.fromAuthorityRule(app, ip, port, e)) - .collect(Collectors.toList()) - ); - } catch (Exception e) { - logger.error("Error when fetching parameter flow rules", e); - return AsyncUtils.newFailedFuture(e); - } - } + private static final String DEGRADE_RULE_TYPE = "degrade"; - /** - * Fetch all authority rules from provided machine. - * - * @param app application name - * @param ip machine client IP - * @param port machine client port - * @return all retrieved authority rules - * @since 0.2.1 - */ - public List fetchAuthorityRulesOfMachine(String app, String ip, int port) { - AssertUtil.notEmpty(app, "Bad app name"); - AssertUtil.notEmpty(ip, "Bad machine IP"); - AssertUtil.isTrue(port > 0, "Bad machine port"); - Map params = new HashMap<>(1); - params.put("type", AUTHORITY_TYPE); - List rules = fetchRules(ip, port, AUTHORITY_TYPE, AuthorityRule.class); - return Optional.ofNullable(rules).map(r -> r.stream() - .map(e -> AuthorityRuleEntity.fromAuthorityRule(app, ip, port, e)) - .collect(Collectors.toList()) - ).orElse(null); - } + private static final String SYSTEM_RULE_TYPE = "system"; - /** - * set rules of the machine. rules == null will return immediately; - * rules.isEmpty() means setting the rules to empty. - * - * @param app - * @param ip - * @param port - * @param rules - * @return whether successfully set the rules. - */ - public boolean setFlowRuleOfMachine(String app, String ip, int port, List rules) { - return setRules(app, ip, port, FLOW_RULE_TYPE, rules); - } + private static final String AUTHORITY_TYPE = "authority"; - public CompletableFuture setFlowRuleOfMachineAsync(String app, String ip, int port, List rules) { - return setRulesAsync(app, ip, port, FLOW_RULE_TYPE, rules); - } + private CloseableHttpAsyncClient httpClient; - /** - * set rules of the machine. rules == null will return immediately; - * rules.isEmpty() means setting the rules to empty. - * - * @param app - * @param ip - * @param port - * @param rules - * @return whether successfully set the rules. - */ - public boolean setDegradeRuleOfMachine(String app, String ip, int port, List rules) { - return setRules(app, ip, port, DEGRADE_RULE_TYPE, rules); - } + private static final SentinelVersion version160 = new SentinelVersion(1, 6, 0); - /** - * set rules of the machine. rules == null will return immediately; - * rules.isEmpty() means setting the rules to empty. - * - * @param app - * @param ip - * @param port - * @param rules - * @return whether successfully set the rules. - */ - public boolean setSystemRuleOfMachine(String app, String ip, int port, List rules) { - return setRules(app, ip, port, SYSTEM_RULE_TYPE, rules); - } + @Autowired + private AppManagement appManagement; - public boolean setAuthorityRuleOfMachine(String app, String ip, int port, List rules) { - return setRules(app, ip, port, AUTHORITY_TYPE, rules); - } + public SentinelApiClient() { + IOReactorConfig ioConfig = IOReactorConfig.custom().setConnectTimeout(3000).setSoTimeout(10000) + .setIoThreadCount(Runtime.getRuntime().availableProcessors() * 2).build(); + httpClient = HttpAsyncClients.custom().setRedirectStrategy(new DefaultRedirectStrategy() { + @Override + protected boolean isRedirectable(final String method) { + return false; + } + }).setMaxConnTotal(4000).setMaxConnPerRoute(1000).setDefaultIOReactorConfig(ioConfig).build(); + httpClient.start(); + } - public CompletableFuture setParamFlowRuleOfMachine(String app, String ip, int port, List rules) { - if (rules == null) { - return CompletableFuture.completedFuture(null); - } - if (StringUtil.isBlank(ip) || port <= 0) { - return AsyncUtils.newFailedFuture(new IllegalArgumentException("Invalid parameter")); - } - try { - String data = JSON.toJSONString( - rules.stream().map(ParamFlowRuleEntity::getRule).collect(Collectors.toList()) - ); - Map params = new HashMap<>(1); - params.put("data", data); - return executeCommand(app, ip, port, SET_PARAM_RULE_PATH, params, true) - .thenCompose(e -> { - if (CommandConstants.MSG_SUCCESS.equals(e)) { - return CompletableFuture.completedFuture(null); - } else { - logger.warn("Push parameter flow rules to client failed: " + e); - return AsyncUtils.newFailedFuture(new RuntimeException(e)); - } - }); - } catch (Exception ex) { - logger.warn("Error when setting parameter flow rule", ex); - return AsyncUtils.newFailedFuture(ex); - } - } + private boolean isSuccess(int statusCode) { + return statusCode >= 200 && statusCode < 300; + } - // Cluster related + private boolean isCommandNotFound(int statusCode, String body) { + return statusCode == 400 && StringUtil.isNotEmpty(body) + && body.contains(CommandConstants.MSG_UNKNOWN_COMMAND_PREFIX); + } - public CompletableFuture fetchClusterMode(String ip, int port) { - if (StringUtil.isBlank(ip) || port <= 0) { - return AsyncUtils.newFailedFuture(new IllegalArgumentException("Invalid parameter")); - } - try { - return executeCommand(ip, port, FETCH_CLUSTER_MODE_PATH, false) - .thenApply(r -> JSON.parseObject(r, ClusterStateSimpleEntity.class)); - } catch (Exception ex) { - logger.warn("Error when fetching cluster mode", ex); - return AsyncUtils.newFailedFuture(ex); - } - } + private StringBuilder queryString(Map params) { + StringBuilder queryStringBuilder = new StringBuilder(); + for (Entry entry : params.entrySet()) { + if (StringUtil.isEmpty(entry.getValue())) { + continue; + } + String name = urlEncode(entry.getKey()); + String value = urlEncode(entry.getValue()); + if (name != null && value != null) { + if (queryStringBuilder.length() > 0) { + queryStringBuilder.append('&'); + } + queryStringBuilder.append(name).append('=').append(value); + } + } + return queryStringBuilder; + } - public CompletableFuture modifyClusterMode(String ip, int port, int mode) { - if (StringUtil.isBlank(ip) || port <= 0) { - return AsyncUtils.newFailedFuture(new IllegalArgumentException("Invalid parameter")); - } - try { - Map params = new HashMap<>(1); - params.put("mode", String.valueOf(mode)); - return executeCommand(ip, port, MODIFY_CLUSTER_MODE_PATH, params, false) - .thenCompose(e -> { - if (CommandConstants.MSG_SUCCESS.equals(e)) { - return CompletableFuture.completedFuture(null); - } else { - logger.warn("Error when modifying cluster mode: " + e); - return AsyncUtils.newFailedFuture(new RuntimeException(e)); - } - }); - } catch (Exception ex) { - logger.warn("Error when modifying cluster mode", ex); - return AsyncUtils.newFailedFuture(ex); - } - } + private HttpUriRequest postRequest(String url, Map params) { + HttpPost httpPost = new HttpPost(url); + if (params != null && params.size() > 0) { + List list = new ArrayList<>(params.size()); + for (Entry entry : params.entrySet()) { + list.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); + } + httpPost.setEntity(new UrlEncodedFormEntity(list, Consts.UTF_8)); + } + return httpPost; + } - public CompletableFuture fetchClusterClientInfoAndConfig(String ip, int port) { - if (StringUtil.isBlank(ip) || port <= 0) { - return AsyncUtils.newFailedFuture(new IllegalArgumentException("Invalid parameter")); - } - try { - return executeCommand(ip, port, FETCH_CLUSTER_CLIENT_CONFIG_PATH, false) - .thenApply(r -> JSON.parseObject(r, ClusterClientInfoVO.class)); - } catch (Exception ex) { - logger.warn("Error when fetching cluster client config", ex); - return AsyncUtils.newFailedFuture(ex); - } - } + private String urlEncode(String str) { + try { + return URLEncoder.encode(str, DEFAULT_CHARSET.name()); + } + catch (UnsupportedEncodingException e) { + logger.info("encode string error: {}", str, e); + return null; + } + } - public CompletableFuture modifyClusterClientConfig(String app, String ip, int port, ClusterClientConfig config) { - if (StringUtil.isBlank(ip) || port <= 0) { - return AsyncUtils.newFailedFuture(new IllegalArgumentException("Invalid parameter")); - } - try { - Map params = new HashMap<>(1); - params.put("data", JSON.toJSONString(config)); - return executeCommand(app, ip, port, MODIFY_CLUSTER_CLIENT_CONFIG_PATH, params, true) - .thenCompose(e -> { - if (CommandConstants.MSG_SUCCESS.equals(e)) { - return CompletableFuture.completedFuture(null); - } else { - logger.warn("Error when modifying cluster client config: " + e); - return AsyncUtils.newFailedFuture(new RuntimeException(e)); - } - }); - } catch (Exception ex) { - logger.warn("Error when modifying cluster client config", ex); - return AsyncUtils.newFailedFuture(ex); - } - } + private String getBody(HttpResponse response) throws Exception { + Charset charset = null; + try { + String contentTypeStr = response.getFirstHeader("Content-type").getValue(); + if (StringUtil.isNotEmpty(contentTypeStr)) { + ContentType contentType = ContentType.parse(contentTypeStr); + charset = contentType.getCharset(); + } + } + catch (Exception ignore) { + } + return EntityUtils.toString(response.getEntity(), charset != null ? charset : DEFAULT_CHARSET); + } - public CompletableFuture modifyClusterServerFlowConfig(String app, String ip, int port, ServerFlowConfig config) { - if (StringUtil.isBlank(ip) || port <= 0) { - return AsyncUtils.newFailedFuture(new IllegalArgumentException("Invalid parameter")); - } - try { - Map params = new HashMap<>(1); - params.put("data", JSON.toJSONString(config)); - return executeCommand(app, ip, port, MODIFY_CLUSTER_SERVER_FLOW_CONFIG_PATH, params, true) - .thenCompose(e -> { - if (CommandConstants.MSG_SUCCESS.equals(e)) { - return CompletableFuture.completedFuture(null); - } else { - logger.warn("Error when modifying cluster server flow config: " + e); - return AsyncUtils.newFailedFuture(new RuntimeException(e)); - } - }); - } catch (Exception ex) { - logger.warn("Error when modifying cluster server flow config", ex); - return AsyncUtils.newFailedFuture(ex); - } - } + /** + * With no param + * @param ip + * @param port + * @param api + * @return + */ + private CompletableFuture executeCommand(String ip, int port, String api, boolean useHttpPost) { + return executeCommand(ip, port, api, null, useHttpPost); + } - public CompletableFuture modifyClusterServerTransportConfig(String app, String ip, int port, ServerTransportConfig config) { - if (StringUtil.isBlank(ip) || port <= 0) { - return AsyncUtils.newFailedFuture(new IllegalArgumentException("Invalid parameter")); - } - try { - Map params = new HashMap<>(2); - params.put("port", config.getPort().toString()); - params.put("idleSeconds", config.getIdleSeconds().toString()); - return executeCommand(app, ip, port, MODIFY_CLUSTER_SERVER_TRANSPORT_CONFIG_PATH, params, false) - .thenCompose(e -> { - if (CommandConstants.MSG_SUCCESS.equals(e)) { - return CompletableFuture.completedFuture(null); - } else { - logger.warn("Error when modifying cluster server transport config: " + e); - return AsyncUtils.newFailedFuture(new RuntimeException(e)); - } - }); - } catch (Exception ex) { - logger.warn("Error when modifying cluster server transport config", ex); - return AsyncUtils.newFailedFuture(ex); - } - } + /** + * No app specified, force to GET + * @param ip + * @param port + * @param api + * @param params + * @return + */ + private CompletableFuture executeCommand(String ip, int port, String api, Map params, + boolean useHttpPost) { + return executeCommand(null, ip, port, api, params, useHttpPost); + } - public CompletableFuture modifyClusterServerNamespaceSet(String app, String ip, int port, Set set) { - if (StringUtil.isBlank(ip) || port <= 0) { - return AsyncUtils.newFailedFuture(new IllegalArgumentException("Invalid parameter")); - } - try { - Map params = new HashMap<>(1); - params.put("data", JSON.toJSONString(set)); - return executeCommand(app, ip, port, MODIFY_CLUSTER_SERVER_NAMESPACE_SET_PATH, params, true) - .thenCompose(e -> { - if (CommandConstants.MSG_SUCCESS.equals(e)) { - return CompletableFuture.completedFuture(null); - } else { - logger.warn("Error when modifying cluster server NamespaceSet", e); - return AsyncUtils.newFailedFuture(new RuntimeException(e)); - } - }); - } catch (Exception ex) { - logger.warn("Error when modifying cluster server NamespaceSet", ex); - return AsyncUtils.newFailedFuture(ex); - } - } + /** + * Prefer to execute request using POST + * @param app + * @param ip + * @param port + * @param api + * @param params + * @return + */ + private CompletableFuture executeCommand(String app, String ip, int port, String api, + Map params, boolean useHttpPost) { + CompletableFuture future = new CompletableFuture<>(); + if (StringUtil.isBlank(ip) || StringUtil.isBlank(api)) { + future.completeExceptionally(new IllegalArgumentException("Bad URL or command name")); + return future; + } + StringBuilder urlBuilder = new StringBuilder(); + urlBuilder.append("http://"); + urlBuilder.append(ip).append(':').append(port).append('/').append(api); + if (params == null) { + params = Collections.emptyMap(); + } + boolean supportPost = StringUtil.isNotEmpty(app) + && Optional.ofNullable(appManagement.getDetailApp(app)).flatMap(e -> e.getMachine(ip, port)) + .flatMap(m -> VersionUtils.parseVersion(m.getVersion()).map(v -> v.greaterOrEqual(version160))) + .orElse(false); + if (!useHttpPost || !supportPost) { + // Using GET in older versions, append parameters after url + if (!params.isEmpty()) { + if (urlBuilder.indexOf("?") == -1) { + urlBuilder.append('?'); + } + else { + urlBuilder.append('&'); + } + urlBuilder.append(queryString(params)); + } + return executeCommand(new HttpGet(urlBuilder.toString())); + } + else { + // Using POST + return executeCommand(postRequest(urlBuilder.toString(), params)); + } + } - public CompletableFuture fetchClusterServerBasicInfo(String ip, int port) { - if (StringUtil.isBlank(ip) || port <= 0) { - return AsyncUtils.newFailedFuture(new IllegalArgumentException("Invalid parameter")); - } - try { - return executeCommand(ip, port, FETCH_CLUSTER_SERVER_BASIC_INFO_PATH, false) - .thenApply(r -> JSON.parseObject(r, ClusterServerStateVO.class)); - } catch (Exception ex) { - logger.warn("Error when fetching cluster sever all config and basic info", ex); - return AsyncUtils.newFailedFuture(ex); - } - } + private CompletableFuture executeCommand(HttpUriRequest request) { + CompletableFuture future = new CompletableFuture<>(); + httpClient.execute(request, new FutureCallback() { + @Override + public void completed(final HttpResponse response) { + int statusCode = response.getStatusLine().getStatusCode(); + try { + String value = getBody(response); + if (isSuccess(statusCode)) { + future.complete(value); + } + else { + if (isCommandNotFound(statusCode, value)) { + future.completeExceptionally(new CommandNotFoundException(request.getURI().getPath())); + } + else { + future.completeExceptionally(new CommandFailedException(value)); + } + } - public CompletableFuture> fetchApis(String app, String ip, int port) { - if (StringUtil.isBlank(ip) || port <= 0) { - return AsyncUtils.newFailedFuture(new IllegalArgumentException("Invalid parameter")); - } + } + catch (Exception ex) { + future.completeExceptionally(ex); + logger.error("HTTP request failed: {}", request.getURI().toString(), ex); + } + } - try { - return executeCommand(ip, port, FETCH_GATEWAY_API_PATH, false) - .thenApply(r -> { - List entities = JSON.parseArray(r, ApiDefinitionEntity.class); - if (entities != null) { - for (ApiDefinitionEntity entity : entities) { - entity.setApp(app); - entity.setIp(ip); - entity.setPort(port); - } - } - return entities; - }); - } catch (Exception ex) { - logger.warn("Error when fetching gateway apis", ex); - return AsyncUtils.newFailedFuture(ex); - } - } + @Override + public void failed(final Exception ex) { + future.completeExceptionally(ex); + logger.error("HTTP request failed: {}", request.getURI().toString(), ex); + } - public boolean modifyApis(String app, String ip, int port, List apis) { - if (apis == null) { - return true; - } + @Override + public void cancelled() { + future.complete(null); + } + }); + return future; + } - try { - AssertUtil.notEmpty(app, "Bad app name"); - AssertUtil.notEmpty(ip, "Bad machine IP"); - AssertUtil.isTrue(port > 0, "Bad machine port"); - String data = JSON.toJSONString( - apis.stream().map(r -> r.toApiDefinition()).collect(Collectors.toList())); - Map params = new HashMap<>(2); - params.put("data", data); - String result = executeCommand(app, ip, port, MODIFY_GATEWAY_API_PATH, params, true).get(); - logger.info("Modify gateway apis: {}", result); - return true; - } catch (Exception e) { - logger.warn("Error when modifying gateway apis", e); - return false; - } - } + public void close() throws Exception { + httpClient.close(); + } - public CompletableFuture> fetchGatewayFlowRules(String app, String ip, int port) { - if (StringUtil.isBlank(ip) || port <= 0) { - return AsyncUtils.newFailedFuture(new IllegalArgumentException("Invalid parameter")); - } + @Nullable + private CompletableFuture> fetchItemsAsync(String ip, int port, String api, String type, + Class ruleType) { + AssertUtil.notEmpty(ip, "Bad machine IP"); + AssertUtil.isTrue(port > 0, "Bad machine port"); + Map params = null; + if (StringUtil.isNotEmpty(type)) { + params = new HashMap<>(1); + params.put("type", type); + } + return executeCommand(ip, port, api, params, false).thenApply(json -> JSON.parseArray(json, ruleType)); + } - try { - return executeCommand(ip, port, FETCH_GATEWAY_FLOW_RULE_PATH, false) - .thenApply(r -> { - List gatewayFlowRules = JSON.parseArray(r, GatewayFlowRule.class); - List entities = gatewayFlowRules.stream().map(rule -> GatewayFlowRuleEntity.fromGatewayFlowRule(app, ip, port, rule)).collect(Collectors.toList()); - return entities; - }); - } catch (Exception ex) { - logger.warn("Error when fetching gateway flow rules", ex); - return AsyncUtils.newFailedFuture(ex); - } - } + @Nullable + private List fetchItems(String ip, int port, String api, String type, Class ruleType) { + try { + AssertUtil.notEmpty(ip, "Bad machine IP"); + AssertUtil.isTrue(port > 0, "Bad machine port"); + Map params = null; + if (StringUtil.isNotEmpty(type)) { + params = new HashMap<>(1); + params.put("type", type); + } + return fetchItemsAsync(ip, port, api, type, ruleType).get(); + } + catch (InterruptedException | ExecutionException e) { + logger.error("Error when fetching items from api: {} -> {}", api, type, e); + return null; + } + catch (Exception e) { + logger.error("Error when fetching items: {} -> {}", api, type, e); + return null; + } + } - public boolean modifyGatewayFlowRules(String app, String ip, int port, List rules) { - if (rules == null) { - return true; - } + private List fetchRules(String ip, int port, String type, Class ruleType) { + return fetchItems(ip, port, GET_RULES_PATH, type, ruleType); + } + + private boolean setRules(String app, String ip, int port, String type, List entities) { + if (entities == null) { + return true; + } + try { + AssertUtil.notEmpty(app, "Bad app name"); + AssertUtil.notEmpty(ip, "Bad machine IP"); + AssertUtil.isTrue(port > 0, "Bad machine port"); + String data = JSON.toJSONString(entities.stream().map(r -> r.toRule()).collect(Collectors.toList())); + Map params = new HashMap<>(2); + params.put("type", type); + params.put("data", data); + String result = executeCommand(app, ip, port, SET_RULES_PATH, params, true).get(); + logger.info("setRules result: {}, type={}", result, type); + return true; + } + catch (InterruptedException e) { + logger.warn("setRules API failed: {}", type, e); + return false; + } + catch (ExecutionException e) { + logger.warn("setRules API failed: {}", type, e.getCause()); + return false; + } + catch (Exception e) { + logger.error("setRules API failed, type={}", type, e); + return false; + } + } + + private CompletableFuture setRulesAsync(String app, String ip, int port, String type, + List entities) { + try { + AssertUtil.notNull(entities, "rules cannot be null"); + AssertUtil.notEmpty(app, "Bad app name"); + AssertUtil.notEmpty(ip, "Bad machine IP"); + AssertUtil.isTrue(port > 0, "Bad machine port"); + String data = JSON.toJSONString(entities.stream().map(r -> r.toRule()).collect(Collectors.toList())); + Map params = new HashMap<>(2); + params.put("type", type); + params.put("data", data); + return executeCommand(app, ip, port, SET_RULES_PATH, params, true).thenCompose(r -> { + if ("success".equalsIgnoreCase(r.trim())) { + return CompletableFuture.completedFuture(null); + } + return AsyncUtils.newFailedFuture(new CommandFailedException(r)); + }); + } + catch (Exception e) { + logger.error("setRulesAsync API failed, type={}", type, e); + return AsyncUtils.newFailedFuture(e); + } + } + + public List fetchResourceOfMachine(String ip, int port, String type) { + return fetchItems(ip, port, RESOURCE_URL_PATH, type, NodeVo.class); + } + + /** + * Fetch cluster node. + * @param ip ip to fetch + * @param port port of the ip + * @param includeZero whether zero value should in the result list. + * @return + */ + public List fetchClusterNodeOfMachine(String ip, int port, boolean includeZero) { + String type = "notZero"; + if (includeZero) { + type = "zero"; + } + return fetchItems(ip, port, CLUSTER_NODE_PATH, type, NodeVo.class); + } + + public List fetchFlowRuleOfMachine(String app, String ip, int port) { + List rules = fetchRules(ip, port, FLOW_RULE_TYPE, FlowRule.class); + if (rules != null) { + return rules.stream().map(rule -> FlowRuleEntity.fromFlowRule(app, ip, port, rule)) + .collect(Collectors.toList()); + } + else { + return null; + } + } + + public List fetchDegradeRuleOfMachine(String app, String ip, int port) { + List rules = fetchRules(ip, port, DEGRADE_RULE_TYPE, DegradeRule.class); + if (rules != null) { + return rules.stream().map(rule -> DegradeRuleEntity.fromDegradeRule(app, ip, port, rule)) + .collect(Collectors.toList()); + } + else { + return null; + } + } + + public List fetchSystemRuleOfMachine(String app, String ip, int port) { + List rules = fetchRules(ip, port, SYSTEM_RULE_TYPE, SystemRule.class); + if (rules != null) { + return rules.stream().map(rule -> SystemRuleEntity.fromSystemRule(app, ip, port, rule)) + .collect(Collectors.toList()); + } + else { + return null; + } + } + + /** + * Fetch all parameter flow rules from provided machine. + * @param app application name + * @param ip machine client IP + * @param port machine client port + * @return all retrieved parameter flow rules + * @since 0.2.1 + */ + public CompletableFuture> fetchParamFlowRulesOfMachine(String app, String ip, int port) { + try { + AssertUtil.notEmpty(app, "Bad app name"); + AssertUtil.notEmpty(ip, "Bad machine IP"); + AssertUtil.isTrue(port > 0, "Bad machine port"); + return fetchItemsAsync(ip, port, GET_PARAM_RULE_PATH, null, ParamFlowRule.class) + .thenApply(rules -> rules.stream().map(e -> ParamFlowRuleEntity.fromAuthorityRule(app, ip, port, e)) + .collect(Collectors.toList())); + } + catch (Exception e) { + logger.error("Error when fetching parameter flow rules", e); + return AsyncUtils.newFailedFuture(e); + } + } + + /** + * Fetch all authority rules from provided machine. + * @param app application name + * @param ip machine client IP + * @param port machine client port + * @return all retrieved authority rules + * @since 0.2.1 + */ + public List fetchAuthorityRulesOfMachine(String app, String ip, int port) { + AssertUtil.notEmpty(app, "Bad app name"); + AssertUtil.notEmpty(ip, "Bad machine IP"); + AssertUtil.isTrue(port > 0, "Bad machine port"); + Map params = new HashMap<>(1); + params.put("type", AUTHORITY_TYPE); + List rules = fetchRules(ip, port, AUTHORITY_TYPE, AuthorityRule.class); + return Optional.ofNullable(rules).map(r -> r.stream() + .map(e -> AuthorityRuleEntity.fromAuthorityRule(app, ip, port, e)).collect(Collectors.toList())) + .orElse(null); + } + + /** + * set rules of the machine. rules == null will return immediately; rules.isEmpty() + * means setting the rules to empty. + * @param app + * @param ip + * @param port + * @param rules + * @return whether successfully set the rules. + */ + public boolean setFlowRuleOfMachine(String app, String ip, int port, List rules) { + return setRules(app, ip, port, FLOW_RULE_TYPE, rules); + } + + public CompletableFuture setFlowRuleOfMachineAsync(String app, String ip, int port, + List rules) { + return setRulesAsync(app, ip, port, FLOW_RULE_TYPE, rules); + } + + /** + * set rules of the machine. rules == null will return immediately; rules.isEmpty() + * means setting the rules to empty. + * @param app + * @param ip + * @param port + * @param rules + * @return whether successfully set the rules. + */ + public boolean setDegradeRuleOfMachine(String app, String ip, int port, List rules) { + return setRules(app, ip, port, DEGRADE_RULE_TYPE, rules); + } + + /** + * set rules of the machine. rules == null will return immediately; rules.isEmpty() + * means setting the rules to empty. + * @param app + * @param ip + * @param port + * @param rules + * @return whether successfully set the rules. + */ + public boolean setSystemRuleOfMachine(String app, String ip, int port, List rules) { + return setRules(app, ip, port, SYSTEM_RULE_TYPE, rules); + } + + public boolean setAuthorityRuleOfMachine(String app, String ip, int port, List rules) { + return setRules(app, ip, port, AUTHORITY_TYPE, rules); + } + + public CompletableFuture setParamFlowRuleOfMachine(String app, String ip, int port, + List rules) { + if (rules == null) { + return CompletableFuture.completedFuture(null); + } + if (StringUtil.isBlank(ip) || port <= 0) { + return AsyncUtils.newFailedFuture(new IllegalArgumentException("Invalid parameter")); + } + try { + String data = JSON + .toJSONString(rules.stream().map(ParamFlowRuleEntity::getRule).collect(Collectors.toList())); + Map params = new HashMap<>(1); + params.put("data", data); + return executeCommand(app, ip, port, SET_PARAM_RULE_PATH, params, true).thenCompose(e -> { + if (CommandConstants.MSG_SUCCESS.equals(e)) { + return CompletableFuture.completedFuture(null); + } + else { + logger.warn("Push parameter flow rules to client failed: " + e); + return AsyncUtils.newFailedFuture(new RuntimeException(e)); + } + }); + } + catch (Exception ex) { + logger.warn("Error when setting parameter flow rule", ex); + return AsyncUtils.newFailedFuture(ex); + } + } + + // Cluster related + + public CompletableFuture fetchClusterMode(String ip, int port) { + if (StringUtil.isBlank(ip) || port <= 0) { + return AsyncUtils.newFailedFuture(new IllegalArgumentException("Invalid parameter")); + } + try { + return executeCommand(ip, port, FETCH_CLUSTER_MODE_PATH, false) + .thenApply(r -> JSON.parseObject(r, ClusterStateSimpleEntity.class)); + } + catch (Exception ex) { + logger.warn("Error when fetching cluster mode", ex); + return AsyncUtils.newFailedFuture(ex); + } + } + + public CompletableFuture modifyClusterMode(String ip, int port, int mode) { + if (StringUtil.isBlank(ip) || port <= 0) { + return AsyncUtils.newFailedFuture(new IllegalArgumentException("Invalid parameter")); + } + try { + Map params = new HashMap<>(1); + params.put("mode", String.valueOf(mode)); + return executeCommand(ip, port, MODIFY_CLUSTER_MODE_PATH, params, false).thenCompose(e -> { + if (CommandConstants.MSG_SUCCESS.equals(e)) { + return CompletableFuture.completedFuture(null); + } + else { + logger.warn("Error when modifying cluster mode: " + e); + return AsyncUtils.newFailedFuture(new RuntimeException(e)); + } + }); + } + catch (Exception ex) { + logger.warn("Error when modifying cluster mode", ex); + return AsyncUtils.newFailedFuture(ex); + } + } + + public CompletableFuture fetchClusterClientInfoAndConfig(String ip, int port) { + if (StringUtil.isBlank(ip) || port <= 0) { + return AsyncUtils.newFailedFuture(new IllegalArgumentException("Invalid parameter")); + } + try { + return executeCommand(ip, port, FETCH_CLUSTER_CLIENT_CONFIG_PATH, false) + .thenApply(r -> JSON.parseObject(r, ClusterClientInfoVO.class)); + } + catch (Exception ex) { + logger.warn("Error when fetching cluster client config", ex); + return AsyncUtils.newFailedFuture(ex); + } + } + + public CompletableFuture modifyClusterClientConfig(String app, String ip, int port, + ClusterClientConfig config) { + if (StringUtil.isBlank(ip) || port <= 0) { + return AsyncUtils.newFailedFuture(new IllegalArgumentException("Invalid parameter")); + } + try { + Map params = new HashMap<>(1); + params.put("data", JSON.toJSONString(config)); + return executeCommand(app, ip, port, MODIFY_CLUSTER_CLIENT_CONFIG_PATH, params, true).thenCompose(e -> { + if (CommandConstants.MSG_SUCCESS.equals(e)) { + return CompletableFuture.completedFuture(null); + } + else { + logger.warn("Error when modifying cluster client config: " + e); + return AsyncUtils.newFailedFuture(new RuntimeException(e)); + } + }); + } + catch (Exception ex) { + logger.warn("Error when modifying cluster client config", ex); + return AsyncUtils.newFailedFuture(ex); + } + } + + public CompletableFuture modifyClusterServerFlowConfig(String app, String ip, int port, + ServerFlowConfig config) { + if (StringUtil.isBlank(ip) || port <= 0) { + return AsyncUtils.newFailedFuture(new IllegalArgumentException("Invalid parameter")); + } + try { + Map params = new HashMap<>(1); + params.put("data", JSON.toJSONString(config)); + return executeCommand(app, ip, port, MODIFY_CLUSTER_SERVER_FLOW_CONFIG_PATH, params, true) + .thenCompose(e -> { + if (CommandConstants.MSG_SUCCESS.equals(e)) { + return CompletableFuture.completedFuture(null); + } + else { + logger.warn("Error when modifying cluster server flow config: " + e); + return AsyncUtils.newFailedFuture(new RuntimeException(e)); + } + }); + } + catch (Exception ex) { + logger.warn("Error when modifying cluster server flow config", ex); + return AsyncUtils.newFailedFuture(ex); + } + } + + public CompletableFuture modifyClusterServerTransportConfig(String app, String ip, int port, + ServerTransportConfig config) { + if (StringUtil.isBlank(ip) || port <= 0) { + return AsyncUtils.newFailedFuture(new IllegalArgumentException("Invalid parameter")); + } + try { + Map params = new HashMap<>(2); + params.put("port", config.getPort().toString()); + params.put("idleSeconds", config.getIdleSeconds().toString()); + return executeCommand(app, ip, port, MODIFY_CLUSTER_SERVER_TRANSPORT_CONFIG_PATH, params, false) + .thenCompose(e -> { + if (CommandConstants.MSG_SUCCESS.equals(e)) { + return CompletableFuture.completedFuture(null); + } + else { + logger.warn("Error when modifying cluster server transport config: " + e); + return AsyncUtils.newFailedFuture(new RuntimeException(e)); + } + }); + } + catch (Exception ex) { + logger.warn("Error when modifying cluster server transport config", ex); + return AsyncUtils.newFailedFuture(ex); + } + } + + public CompletableFuture modifyClusterServerNamespaceSet(String app, String ip, int port, Set set) { + if (StringUtil.isBlank(ip) || port <= 0) { + return AsyncUtils.newFailedFuture(new IllegalArgumentException("Invalid parameter")); + } + try { + Map params = new HashMap<>(1); + params.put("data", JSON.toJSONString(set)); + return executeCommand(app, ip, port, MODIFY_CLUSTER_SERVER_NAMESPACE_SET_PATH, params, true) + .thenCompose(e -> { + if (CommandConstants.MSG_SUCCESS.equals(e)) { + return CompletableFuture.completedFuture(null); + } + else { + logger.warn("Error when modifying cluster server NamespaceSet", e); + return AsyncUtils.newFailedFuture(new RuntimeException(e)); + } + }); + } + catch (Exception ex) { + logger.warn("Error when modifying cluster server NamespaceSet", ex); + return AsyncUtils.newFailedFuture(ex); + } + } + + public CompletableFuture fetchClusterServerBasicInfo(String ip, int port) { + if (StringUtil.isBlank(ip) || port <= 0) { + return AsyncUtils.newFailedFuture(new IllegalArgumentException("Invalid parameter")); + } + try { + return executeCommand(ip, port, FETCH_CLUSTER_SERVER_BASIC_INFO_PATH, false) + .thenApply(r -> JSON.parseObject(r, ClusterServerStateVO.class)); + } + catch (Exception ex) { + logger.warn("Error when fetching cluster sever all config and basic info", ex); + return AsyncUtils.newFailedFuture(ex); + } + } + + public CompletableFuture> fetchApis(String app, String ip, int port) { + if (StringUtil.isBlank(ip) || port <= 0) { + return AsyncUtils.newFailedFuture(new IllegalArgumentException("Invalid parameter")); + } + + try { + return executeCommand(ip, port, FETCH_GATEWAY_API_PATH, false).thenApply(r -> { + List entities = JSON.parseArray(r, ApiDefinitionEntity.class); + if (entities != null) { + for (ApiDefinitionEntity entity : entities) { + entity.setApp(app); + entity.setIp(ip); + entity.setPort(port); + } + } + return entities; + }); + } + catch (Exception ex) { + logger.warn("Error when fetching gateway apis", ex); + return AsyncUtils.newFailedFuture(ex); + } + } + + public boolean modifyApis(String app, String ip, int port, List apis) { + if (apis == null) { + return true; + } + + try { + AssertUtil.notEmpty(app, "Bad app name"); + AssertUtil.notEmpty(ip, "Bad machine IP"); + AssertUtil.isTrue(port > 0, "Bad machine port"); + String data = JSON.toJSONString(apis.stream().map(r -> r.toApiDefinition()).collect(Collectors.toList())); + Map params = new HashMap<>(2); + params.put("data", data); + String result = executeCommand(app, ip, port, MODIFY_GATEWAY_API_PATH, params, true).get(); + logger.info("Modify gateway apis: {}", result); + return true; + } + catch (Exception e) { + logger.warn("Error when modifying gateway apis", e); + return false; + } + } + + public CompletableFuture> fetchGatewayFlowRules(String app, String ip, int port) { + if (StringUtil.isBlank(ip) || port <= 0) { + return AsyncUtils.newFailedFuture(new IllegalArgumentException("Invalid parameter")); + } + + try { + return executeCommand(ip, port, FETCH_GATEWAY_FLOW_RULE_PATH, false).thenApply(r -> { + List gatewayFlowRules = JSON.parseArray(r, GatewayFlowRule.class); + List entities = gatewayFlowRules.stream() + .map(rule -> GatewayFlowRuleEntity.fromGatewayFlowRule(app, ip, port, rule)) + .collect(Collectors.toList()); + return entities; + }); + } + catch (Exception ex) { + logger.warn("Error when fetching gateway flow rules", ex); + return AsyncUtils.newFailedFuture(ex); + } + } + + public boolean modifyGatewayFlowRules(String app, String ip, int port, List rules) { + if (rules == null) { + return true; + } + + try { + AssertUtil.notEmpty(app, "Bad app name"); + AssertUtil.notEmpty(ip, "Bad machine IP"); + AssertUtil.isTrue(port > 0, "Bad machine port"); + String data = JSON + .toJSONString(rules.stream().map(r -> r.toGatewayFlowRule()).collect(Collectors.toList())); + Map params = new HashMap<>(2); + params.put("data", data); + String result = executeCommand(app, ip, port, MODIFY_GATEWAY_FLOW_RULE_PATH, params, true).get(); + logger.info("Modify gateway flow rules: {}", result); + return true; + } + catch (Exception e) { + logger.warn("Error when modifying gateway apis", e); + return false; + } + } - try { - AssertUtil.notEmpty(app, "Bad app name"); - AssertUtil.notEmpty(ip, "Bad machine IP"); - AssertUtil.isTrue(port > 0, "Bad machine port"); - String data = JSON.toJSONString( - rules.stream().map(r -> r.toGatewayFlowRule()).collect(Collectors.toList())); - Map params = new HashMap<>(2); - params.put("data", data); - String result = executeCommand(app, ip, port, MODIFY_GATEWAY_FLOW_RULE_PATH, params, true).get(); - logger.info("Modify gateway flow rules: {}", result); - return true; - } catch (Exception e) { - logger.warn("Error when modifying gateway apis", e); - return false; - } - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/config/DashboardConfig.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/config/DashboardConfig.java index 92e0608ec..d80409764 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/config/DashboardConfig.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/config/DashboardConfig.java @@ -23,7 +23,9 @@ import org.apache.commons.lang.math.NumberUtils; import org.springframework.lang.NonNull; /** - *

Dashboard local config support.

+ *

+ * Dashboard local config support. + *

*

* Dashboard supports configuration loading by several ways by order:
* 1. System.properties
@@ -35,106 +37,113 @@ import org.springframework.lang.NonNull; */ public class DashboardConfig { - public static final int DEFAULT_MACHINE_HEALTHY_TIMEOUT_MS = 60_000; + public static final int DEFAULT_MACHINE_HEALTHY_TIMEOUT_MS = 60_000; - /** - * Login username - */ - public static final String CONFIG_AUTH_USERNAME = "sentinel.dashboard.auth.username"; + /** + * Login username + */ + public static final String CONFIG_AUTH_USERNAME = "sentinel.dashboard.auth.username"; - /** - * Login password - */ - public static final String CONFIG_AUTH_PASSWORD = "sentinel.dashboard.auth.password"; + /** + * Login password + */ + public static final String CONFIG_AUTH_PASSWORD = "sentinel.dashboard.auth.password"; - /** - * Hide application name in sidebar when it has no healthy machines after specific period in millisecond. - */ - public static final String CONFIG_HIDE_APP_NO_MACHINE_MILLIS = "sentinel.dashboard.app.hideAppNoMachineMillis"; - /** - * Remove application when it has no healthy machines after specific period in millisecond. - */ - public static final String CONFIG_REMOVE_APP_NO_MACHINE_MILLIS = "sentinel.dashboard.removeAppNoMachineMillis"; - /** - * Timeout - */ - public static final String CONFIG_UNHEALTHY_MACHINE_MILLIS = "sentinel.dashboard.unhealthyMachineMillis"; - /** - * Auto remove unhealthy machine after specific period in millisecond. - */ - public static final String CONFIG_AUTO_REMOVE_MACHINE_MILLIS = "sentinel.dashboard.autoRemoveMachineMillis"; + /** + * Hide application name in sidebar when it has no healthy machines after specific + * period in millisecond. + */ + public static final String CONFIG_HIDE_APP_NO_MACHINE_MILLIS = "sentinel.dashboard.app.hideAppNoMachineMillis"; - private static final ConcurrentMap cacheMap = new ConcurrentHashMap<>(); - - @NonNull - private static String getConfig(String name) { - // env - String val = System.getenv(name); - if (StringUtils.isNotEmpty(val)) { - return val; - } - // properties - val = System.getProperty(name); - if (StringUtils.isNotEmpty(val)) { - return val; - } - return ""; - } + /** + * Remove application when it has no healthy machines after specific period in + * millisecond. + */ + public static final String CONFIG_REMOVE_APP_NO_MACHINE_MILLIS = "sentinel.dashboard.removeAppNoMachineMillis"; - protected static String getConfigStr(String name) { - if (cacheMap.containsKey(name)) { - return (String) cacheMap.get(name); - } + /** + * Timeout + */ + public static final String CONFIG_UNHEALTHY_MACHINE_MILLIS = "sentinel.dashboard.unhealthyMachineMillis"; - String val = getConfig(name); + /** + * Auto remove unhealthy machine after specific period in millisecond. + */ + public static final String CONFIG_AUTO_REMOVE_MACHINE_MILLIS = "sentinel.dashboard.autoRemoveMachineMillis"; - if (StringUtils.isBlank(val)) { - return null; - } + private static final ConcurrentMap cacheMap = new ConcurrentHashMap<>(); - cacheMap.put(name, val); - return val; - } + @NonNull + private static String getConfig(String name) { + // env + String val = System.getenv(name); + if (StringUtils.isNotEmpty(val)) { + return val; + } + // properties + val = System.getProperty(name); + if (StringUtils.isNotEmpty(val)) { + return val; + } + return ""; + } - protected static int getConfigInt(String name, int defaultVal, int minVal) { - if (cacheMap.containsKey(name)) { - return (int)cacheMap.get(name); - } - int val = NumberUtils.toInt(getConfig(name)); - if (val == 0) { - val = defaultVal; - } else if (val < minVal) { - val = minVal; - } - cacheMap.put(name, val); - return val; - } + protected static String getConfigStr(String name) { + if (cacheMap.containsKey(name)) { + return (String) cacheMap.get(name); + } - public static String getAuthUsername() { - return getConfigStr(CONFIG_AUTH_USERNAME); - } + String val = getConfig(name); - public static String getAuthPassword() { - return getConfigStr(CONFIG_AUTH_PASSWORD); - } + if (StringUtils.isBlank(val)) { + return null; + } + + cacheMap.put(name, val); + return val; + } + + protected static int getConfigInt(String name, int defaultVal, int minVal) { + if (cacheMap.containsKey(name)) { + return (int) cacheMap.get(name); + } + int val = NumberUtils.toInt(getConfig(name)); + if (val == 0) { + val = defaultVal; + } + else if (val < minVal) { + val = minVal; + } + cacheMap.put(name, val); + return val; + } + + public static String getAuthUsername() { + return getConfigStr(CONFIG_AUTH_USERNAME); + } + + public static String getAuthPassword() { + return getConfigStr(CONFIG_AUTH_PASSWORD); + } + + public static int getHideAppNoMachineMillis() { + return getConfigInt(CONFIG_HIDE_APP_NO_MACHINE_MILLIS, 0, 60000); + } + + public static int getRemoveAppNoMachineMillis() { + return getConfigInt(CONFIG_REMOVE_APP_NO_MACHINE_MILLIS, 0, 120000); + } + + public static int getAutoRemoveMachineMillis() { + return getConfigInt(CONFIG_AUTO_REMOVE_MACHINE_MILLIS, 0, 300000); + } + + public static int getUnhealthyMachineMillis() { + return getConfigInt(CONFIG_UNHEALTHY_MACHINE_MILLIS, DEFAULT_MACHINE_HEALTHY_TIMEOUT_MS, 30000); + } + + public static void clearCache() { + cacheMap.clear(); + } - public static int getHideAppNoMachineMillis() { - return getConfigInt(CONFIG_HIDE_APP_NO_MACHINE_MILLIS, 0, 60000); - } - - public static int getRemoveAppNoMachineMillis() { - return getConfigInt(CONFIG_REMOVE_APP_NO_MACHINE_MILLIS, 0, 120000); - } - - public static int getAutoRemoveMachineMillis() { - return getConfigInt(CONFIG_AUTO_REMOVE_MACHINE_MILLIS, 0, 300000); - } - - public static int getUnhealthyMachineMillis() { - return getConfigInt(CONFIG_UNHEALTHY_MACHINE_MILLIS, DEFAULT_MACHINE_HEALTHY_TIMEOUT_MS, 30000); - } - - public static void clearCache() { - cacheMap.clear(); - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/config/WebConfig.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/config/WebConfig.java index 92e51e54a..7a1256d09 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/config/WebConfig.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/config/WebConfig.java @@ -45,72 +45,73 @@ import javax.servlet.Filter; @Configuration public class WebConfig implements WebMvcConfigurer { - private final Logger logger = LoggerFactory.getLogger(WebConfig.class); + private final Logger logger = LoggerFactory.getLogger(WebConfig.class); - @Autowired - private LoginAuthenticationFilter loginAuthenticationFilter; + @Autowired + private LoginAuthenticationFilter loginAuthenticationFilter; - @Autowired - private AuthorizationInterceptor authorizationInterceptor; + @Autowired + private AuthorizationInterceptor authorizationInterceptor; - @Override - public void addInterceptors(InterceptorRegistry registry) { - registry.addInterceptor(authorizationInterceptor).addPathPatterns("/**"); - } + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(authorizationInterceptor).addPathPatterns("/**"); + } - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry.addResourceHandler("/**").addResourceLocations("classpath:/resources/"); - } + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/**").addResourceLocations("classpath:/resources/"); + } - @Override - public void addViewControllers(ViewControllerRegistry registry) { - registry.addViewController("/").setViewName("forward:/index.htm"); - } + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addViewController("/").setViewName("forward:/index.htm"); + } - /** - * Add {@link CommonFilter} to the server, this is the simplest way to use Sentinel - * for Web application. - */ - @Bean - public FilterRegistrationBean sentinelFilterRegistration() { - FilterRegistrationBean registration = new FilterRegistrationBean<>(); - registration.setFilter(new CommonFilter()); - registration.addUrlPatterns("/*"); - registration.setName("sentinelFilter"); - registration.setOrder(1); - // If this is enabled, the entrance of all Web URL resources will be unified as a single context name. - // In most scenarios that's enough, and it could reduce the memory footprint. - registration.addInitParameter(CommonFilter.WEB_CONTEXT_UNIFY, "true"); + /** + * Add {@link CommonFilter} to the server, this is the simplest way to use Sentinel + * for Web application. + */ + @Bean + public FilterRegistrationBean sentinelFilterRegistration() { + FilterRegistrationBean registration = new FilterRegistrationBean<>(); + registration.setFilter(new CommonFilter()); + registration.addUrlPatterns("/*"); + registration.setName("sentinelFilter"); + registration.setOrder(1); + // If this is enabled, the entrance of all Web URL resources will be unified as a + // single context name. + // In most scenarios that's enough, and it could reduce the memory footprint. + registration.addInitParameter(CommonFilter.WEB_CONTEXT_UNIFY, "true"); - logger.info("Sentinel servlet CommonFilter registered"); + logger.info("Sentinel servlet CommonFilter registered"); - return registration; - } + return registration; + } - @PostConstruct - public void doInit() { - Set suffixSet = new HashSet<>(Arrays.asList(".js", ".css", ".html", ".ico", ".txt", - ".woff", ".woff2")); - // Example: register a UrlCleaner to exclude URLs of common static resources. - WebCallbackManager.setUrlCleaner(url -> { - if (StringUtil.isEmpty(url)) { - return url; - } - if (suffixSet.stream().anyMatch(url::endsWith)) { - return null; - } - return url; - }); - } + @PostConstruct + public void doInit() { + Set suffixSet = new HashSet<>(Arrays.asList(".js", ".css", ".html", ".ico", ".txt", ".woff", ".woff2")); + // Example: register a UrlCleaner to exclude URLs of common static resources. + WebCallbackManager.setUrlCleaner(url -> { + if (StringUtil.isEmpty(url)) { + return url; + } + if (suffixSet.stream().anyMatch(url::endsWith)) { + return null; + } + return url; + }); + } + + @Bean + public FilterRegistrationBean authenticationFilterRegistration() { + FilterRegistrationBean registration = new FilterRegistrationBean<>(); + registration.setFilter(loginAuthenticationFilter); + registration.addUrlPatterns("/*"); + registration.setName("authenticationFilter"); + registration.setOrder(0); + return registration; + } - @Bean - public FilterRegistrationBean authenticationFilterRegistration() { - FilterRegistrationBean registration = new FilterRegistrationBean<>(); - registration.setFilter(loginAuthenticationFilter); - registration.addUrlPatterns("/*"); - registration.setName("authenticationFilter"); - registration.setOrder(0); - return registration; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/AppController.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/AppController.java index 635489661..aa99b366a 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/AppController.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/AppController.java @@ -41,45 +41,46 @@ import org.springframework.web.bind.annotation.RestController; @RequestMapping(value = "/app") public class AppController { - @Autowired - private AppManagement appManagement; + @Autowired + private AppManagement appManagement; - @GetMapping("/names.json") - public Result> queryApps(HttpServletRequest request) { - return Result.ofSuccess(appManagement.getAppNames()); - } + @GetMapping("/names.json") + public Result> queryApps(HttpServletRequest request) { + return Result.ofSuccess(appManagement.getAppNames()); + } - @GetMapping("/briefinfos.json") - public Result> queryAppInfos(HttpServletRequest request) { - List list = new ArrayList<>(appManagement.getBriefApps()); - Collections.sort(list, Comparator.comparing(AppInfo::getApp)); - return Result.ofSuccess(list); - } + @GetMapping("/briefinfos.json") + public Result> queryAppInfos(HttpServletRequest request) { + List list = new ArrayList<>(appManagement.getBriefApps()); + Collections.sort(list, Comparator.comparing(AppInfo::getApp)); + return Result.ofSuccess(list); + } + + @GetMapping(value = "/{app}/machines.json") + public Result> getMachinesByApp(@PathVariable("app") String app) { + AppInfo appInfo = appManagement.getDetailApp(app); + if (appInfo == null) { + return Result.ofSuccess(null); + } + List list = new ArrayList<>(appInfo.getMachines()); + Collections.sort(list, Comparator.comparing(MachineInfo::getApp).thenComparing(MachineInfo::getIp) + .thenComparingInt(MachineInfo::getPort)); + return Result.ofSuccess(MachineInfoVo.fromMachineInfoList(list)); + } + + @RequestMapping(value = "/{app}/machine/remove.json") + public Result removeMachineById(@PathVariable("app") String app, @RequestParam(name = "ip") String ip, + @RequestParam(name = "port") int port) { + AppInfo appInfo = appManagement.getDetailApp(app); + if (appInfo == null) { + return Result.ofSuccess(null); + } + if (appManagement.removeMachine(app, ip, port)) { + return Result.ofSuccessMsg("success"); + } + else { + return Result.ofFail(1, "remove failed"); + } + } - @GetMapping(value = "/{app}/machines.json") - public Result> getMachinesByApp(@PathVariable("app") String app) { - AppInfo appInfo = appManagement.getDetailApp(app); - if (appInfo == null) { - return Result.ofSuccess(null); - } - List list = new ArrayList<>(appInfo.getMachines()); - Collections.sort(list, Comparator.comparing(MachineInfo::getApp).thenComparing(MachineInfo::getIp).thenComparingInt(MachineInfo::getPort)); - return Result.ofSuccess(MachineInfoVo.fromMachineInfoList(list)); - } - - @RequestMapping(value = "/{app}/machine/remove.json") - public Result removeMachineById( - @PathVariable("app") String app, - @RequestParam(name = "ip") String ip, - @RequestParam(name = "port") int port) { - AppInfo appInfo = appManagement.getDetailApp(app); - if (appInfo == null) { - return Result.ofSuccess(null); - } - if (appManagement.removeMachine(app, ip, port)) { - return Result.ofSuccessMsg("success"); - } else { - return Result.ofFail(1, "remove failed"); - } - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/AuthController.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/AuthController.java index 8b01aed23..0954f38ab 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/AuthController.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/AuthController.java @@ -38,55 +38,57 @@ import javax.servlet.http.HttpServletRequest; @RequestMapping("/auth") public class AuthController { - private static final Logger LOGGER = LoggerFactory.getLogger(AuthController.class); + private static final Logger LOGGER = LoggerFactory.getLogger(AuthController.class); - @Value("${auth.username:sentinel}") - private String authUsername; + @Value("${auth.username:sentinel}") + private String authUsername; - @Value("${auth.password:sentinel}") - private String authPassword; + @Value("${auth.password:sentinel}") + private String authPassword; - @Autowired - private AuthService authService; + @Autowired + private AuthService authService; - @PostMapping("/login") - public Result login(HttpServletRequest request, String username, String password) { - if (StringUtils.isNotBlank(DashboardConfig.getAuthUsername())) { - authUsername = DashboardConfig.getAuthUsername(); - } + @PostMapping("/login") + public Result login(HttpServletRequest request, String username, String password) { + if (StringUtils.isNotBlank(DashboardConfig.getAuthUsername())) { + authUsername = DashboardConfig.getAuthUsername(); + } - if (StringUtils.isNotBlank(DashboardConfig.getAuthPassword())) { - authPassword = DashboardConfig.getAuthPassword(); - } + if (StringUtils.isNotBlank(DashboardConfig.getAuthPassword())) { + authPassword = DashboardConfig.getAuthPassword(); + } - /* - * If auth.username or auth.password is blank(set in application.properties or VM arguments), - * auth will pass, as the front side validate the input which can't be blank, - * so user can input any username or password(both are not blank) to login in that case. - */ - if (StringUtils.isNotBlank(authUsername) && !authUsername.equals(username) - || StringUtils.isNotBlank(authPassword) && !authPassword.equals(password)) { - LOGGER.error("Login failed: Invalid username or password, username=" + username); - return Result.ofFail(-1, "Invalid username or password"); - } + /* + * If auth.username or auth.password is blank(set in application.properties or VM + * arguments), auth will pass, as the front side validate the input which can't be + * blank, so user can input any username or password(both are not blank) to login + * in that case. + */ + if (StringUtils.isNotBlank(authUsername) && !authUsername.equals(username) + || StringUtils.isNotBlank(authPassword) && !authPassword.equals(password)) { + LOGGER.error("Login failed: Invalid username or password, username=" + username); + return Result.ofFail(-1, "Invalid username or password"); + } - AuthService.AuthUser authUser = new SimpleWebAuthServiceImpl.SimpleWebAuthUserImpl(username); - request.getSession().setAttribute(SimpleWebAuthServiceImpl.WEB_SESSION_KEY, authUser); - return Result.ofSuccess(authUser); - } + AuthService.AuthUser authUser = new SimpleWebAuthServiceImpl.SimpleWebAuthUserImpl(username); + request.getSession().setAttribute(SimpleWebAuthServiceImpl.WEB_SESSION_KEY, authUser); + return Result.ofSuccess(authUser); + } - @PostMapping(value = "/logout") - public Result logout(HttpServletRequest request) { - request.getSession().invalidate(); - return Result.ofSuccess(null); - } + @PostMapping(value = "/logout") + public Result logout(HttpServletRequest request) { + request.getSession().invalidate(); + return Result.ofSuccess(null); + } + + @PostMapping(value = "/check") + public Result check(HttpServletRequest request) { + AuthService.AuthUser authUser = authService.getAuthUser(request); + if (authUser == null) { + return Result.ofFail(-1, "Not logged in"); + } + return Result.ofSuccess(authUser); + } - @PostMapping(value = "/check") - public Result check(HttpServletRequest request) { - AuthService.AuthUser authUser = authService.getAuthUser(request); - if (authUser == null) { - return Result.ofFail(-1, "Not logged in"); - } - return Result.ofSuccess(authUser); - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/AuthorityRuleController.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/AuthorityRuleController.java index 294455f02..ddffaa70d 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/AuthorityRuleController.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/AuthorityRuleController.java @@ -50,142 +50,147 @@ import org.springframework.web.bind.annotation.RestController; @RequestMapping(value = "/authority") public class AuthorityRuleController { - private final Logger logger = LoggerFactory.getLogger(AuthorityRuleController.class); + private final Logger logger = LoggerFactory.getLogger(AuthorityRuleController.class); - @Autowired - private SentinelApiClient sentinelApiClient; - @Autowired - private RuleRepository repository; + @Autowired + private SentinelApiClient sentinelApiClient; - @GetMapping("/rules") - @AuthAction(PrivilegeType.READ_RULE) - public Result> apiQueryAllRulesForMachine(@RequestParam String app, - @RequestParam String ip, - @RequestParam Integer port) { - if (StringUtil.isEmpty(app)) { - return Result.ofFail(-1, "app cannot be null or empty"); - } - if (StringUtil.isEmpty(ip)) { - return Result.ofFail(-1, "ip cannot be null or empty"); - } - if (port == null || port <= 0) { - return Result.ofFail(-1, "Invalid parameter: port"); - } - try { - List rules = sentinelApiClient.fetchAuthorityRulesOfMachine(app, ip, port); - rules = repository.saveAll(rules); - return Result.ofSuccess(rules); - } catch (Throwable throwable) { - logger.error("Error when querying authority rules", throwable); - return Result.ofFail(-1, throwable.getMessage()); - } - } + @Autowired + private RuleRepository repository; - private Result checkEntityInternal(AuthorityRuleEntity entity) { - if (entity == null) { - return Result.ofFail(-1, "bad rule body"); - } - if (StringUtil.isBlank(entity.getApp())) { - return Result.ofFail(-1, "app can't be null or empty"); - } - if (StringUtil.isBlank(entity.getIp())) { - return Result.ofFail(-1, "ip can't be null or empty"); - } - if (entity.getPort() == null || entity.getPort() <= 0) { - return Result.ofFail(-1, "port can't be null"); - } - if (entity.getRule() == null) { - return Result.ofFail(-1, "rule can't be null"); - } - if (StringUtil.isBlank(entity.getResource())) { - return Result.ofFail(-1, "resource name cannot be null or empty"); - } - if (StringUtil.isBlank(entity.getLimitApp())) { - return Result.ofFail(-1, "limitApp should be valid"); - } - if (entity.getStrategy() != RuleConstant.AUTHORITY_WHITE - && entity.getStrategy() != RuleConstant.AUTHORITY_BLACK) { - return Result.ofFail(-1, "Unknown strategy (must be blacklist or whitelist)"); - } - return null; - } + @GetMapping("/rules") + @AuthAction(PrivilegeType.READ_RULE) + public Result> apiQueryAllRulesForMachine(@RequestParam String app, + @RequestParam String ip, @RequestParam Integer port) { + if (StringUtil.isEmpty(app)) { + return Result.ofFail(-1, "app cannot be null or empty"); + } + if (StringUtil.isEmpty(ip)) { + return Result.ofFail(-1, "ip cannot be null or empty"); + } + if (port == null || port <= 0) { + return Result.ofFail(-1, "Invalid parameter: port"); + } + try { + List rules = sentinelApiClient.fetchAuthorityRulesOfMachine(app, ip, port); + rules = repository.saveAll(rules); + return Result.ofSuccess(rules); + } + catch (Throwable throwable) { + logger.error("Error when querying authority rules", throwable); + return Result.ofFail(-1, throwable.getMessage()); + } + } - @PostMapping("/rule") - @AuthAction(PrivilegeType.WRITE_RULE) - public Result apiAddAuthorityRule(@RequestBody AuthorityRuleEntity entity) { - Result checkResult = checkEntityInternal(entity); - if (checkResult != null) { - return checkResult; - } - entity.setId(null); - Date date = new Date(); - entity.setGmtCreate(date); - entity.setGmtModified(date); - try { - entity = repository.save(entity); - } catch (Throwable throwable) { - logger.error("Failed to add authority rule", throwable); - return Result.ofThrowable(-1, throwable); - } - if (!publishRules(entity.getApp(), entity.getIp(), entity.getPort())) { - logger.info("Publish authority rules failed after rule add"); - } - return Result.ofSuccess(entity); - } + private Result checkEntityInternal(AuthorityRuleEntity entity) { + if (entity == null) { + return Result.ofFail(-1, "bad rule body"); + } + if (StringUtil.isBlank(entity.getApp())) { + return Result.ofFail(-1, "app can't be null or empty"); + } + if (StringUtil.isBlank(entity.getIp())) { + return Result.ofFail(-1, "ip can't be null or empty"); + } + if (entity.getPort() == null || entity.getPort() <= 0) { + return Result.ofFail(-1, "port can't be null"); + } + if (entity.getRule() == null) { + return Result.ofFail(-1, "rule can't be null"); + } + if (StringUtil.isBlank(entity.getResource())) { + return Result.ofFail(-1, "resource name cannot be null or empty"); + } + if (StringUtil.isBlank(entity.getLimitApp())) { + return Result.ofFail(-1, "limitApp should be valid"); + } + if (entity.getStrategy() != RuleConstant.AUTHORITY_WHITE + && entity.getStrategy() != RuleConstant.AUTHORITY_BLACK) { + return Result.ofFail(-1, "Unknown strategy (must be blacklist or whitelist)"); + } + return null; + } - @PutMapping("/rule/{id}") - @AuthAction(PrivilegeType.WRITE_RULE) - public Result apiUpdateParamFlowRule(@PathVariable("id") Long id, - @RequestBody AuthorityRuleEntity entity) { - if (id == null || id <= 0) { - return Result.ofFail(-1, "Invalid id"); - } - Result checkResult = checkEntityInternal(entity); - if (checkResult != null) { - return checkResult; - } - entity.setId(id); - Date date = new Date(); - entity.setGmtCreate(null); - entity.setGmtModified(date); - try { - entity = repository.save(entity); - if (entity == null) { - return Result.ofFail(-1, "Failed to save authority rule"); - } - } catch (Throwable throwable) { - logger.error("Failed to save authority rule", throwable); - return Result.ofThrowable(-1, throwable); - } - if (!publishRules(entity.getApp(), entity.getIp(), entity.getPort())) { - logger.info("Publish authority rules failed after rule update"); - } - return Result.ofSuccess(entity); - } + @PostMapping("/rule") + @AuthAction(PrivilegeType.WRITE_RULE) + public Result apiAddAuthorityRule(@RequestBody AuthorityRuleEntity entity) { + Result checkResult = checkEntityInternal(entity); + if (checkResult != null) { + return checkResult; + } + entity.setId(null); + Date date = new Date(); + entity.setGmtCreate(date); + entity.setGmtModified(date); + try { + entity = repository.save(entity); + } + catch (Throwable throwable) { + logger.error("Failed to add authority rule", throwable); + return Result.ofThrowable(-1, throwable); + } + if (!publishRules(entity.getApp(), entity.getIp(), entity.getPort())) { + logger.info("Publish authority rules failed after rule add"); + } + return Result.ofSuccess(entity); + } - @DeleteMapping("/rule/{id}") - @AuthAction(PrivilegeType.DELETE_RULE) - public Result apiDeleteRule(@PathVariable("id") Long id) { - if (id == null) { - return Result.ofFail(-1, "id cannot be null"); - } - AuthorityRuleEntity oldEntity = repository.findById(id); - if (oldEntity == null) { - return Result.ofSuccess(null); - } - try { - repository.delete(id); - } catch (Exception e) { - return Result.ofFail(-1, e.getMessage()); - } - if (!publishRules(oldEntity.getApp(), oldEntity.getIp(), oldEntity.getPort())) { - logger.error("Publish authority rules failed after rule delete"); - } - return Result.ofSuccess(id); - } + @PutMapping("/rule/{id}") + @AuthAction(PrivilegeType.WRITE_RULE) + public Result apiUpdateParamFlowRule(@PathVariable("id") Long id, + @RequestBody AuthorityRuleEntity entity) { + if (id == null || id <= 0) { + return Result.ofFail(-1, "Invalid id"); + } + Result checkResult = checkEntityInternal(entity); + if (checkResult != null) { + return checkResult; + } + entity.setId(id); + Date date = new Date(); + entity.setGmtCreate(null); + entity.setGmtModified(date); + try { + entity = repository.save(entity); + if (entity == null) { + return Result.ofFail(-1, "Failed to save authority rule"); + } + } + catch (Throwable throwable) { + logger.error("Failed to save authority rule", throwable); + return Result.ofThrowable(-1, throwable); + } + if (!publishRules(entity.getApp(), entity.getIp(), entity.getPort())) { + logger.info("Publish authority rules failed after rule update"); + } + return Result.ofSuccess(entity); + } + + @DeleteMapping("/rule/{id}") + @AuthAction(PrivilegeType.DELETE_RULE) + public Result apiDeleteRule(@PathVariable("id") Long id) { + if (id == null) { + return Result.ofFail(-1, "id cannot be null"); + } + AuthorityRuleEntity oldEntity = repository.findById(id); + if (oldEntity == null) { + return Result.ofSuccess(null); + } + try { + repository.delete(id); + } + catch (Exception e) { + return Result.ofFail(-1, e.getMessage()); + } + if (!publishRules(oldEntity.getApp(), oldEntity.getIp(), oldEntity.getPort())) { + logger.error("Publish authority rules failed after rule delete"); + } + return Result.ofSuccess(id); + } + + private boolean publishRules(String app, String ip, Integer port) { + List rules = repository.findAllByMachine(MachineInfo.of(app, ip, port)); + return sentinelApiClient.setAuthorityRuleOfMachine(app, ip, port, rules); + } - private boolean publishRules(String app, String ip, Integer port) { - List rules = repository.findAllByMachine(MachineInfo.of(app, ip, port)); - return sentinelApiClient.setAuthorityRuleOfMachine(app, ip, port, rules); - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/DegradeController.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/DegradeController.java index 61aaee68a..0eea1aca7 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/DegradeController.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/DegradeController.java @@ -44,171 +44,177 @@ import org.springframework.web.bind.annotation.ResponseBody; @RequestMapping(value = "/degrade", produces = MediaType.APPLICATION_JSON_VALUE) public class DegradeController { - private final Logger logger = LoggerFactory.getLogger(DegradeController.class); + private final Logger logger = LoggerFactory.getLogger(DegradeController.class); - @Autowired - private InMemDegradeRuleStore repository; - @Autowired - private SentinelApiClient sentinelApiClient; + @Autowired + private InMemDegradeRuleStore repository; - @ResponseBody - @RequestMapping("/rules.json") - @AuthAction(PrivilegeType.READ_RULE) - public Result> queryMachineRules(String app, String ip, Integer port) { + @Autowired + private SentinelApiClient sentinelApiClient; - if (StringUtil.isEmpty(app)) { - return Result.ofFail(-1, "app can't be null or empty"); - } - if (StringUtil.isEmpty(ip)) { - return Result.ofFail(-1, "ip can't be null or empty"); - } - if (port == null) { - return Result.ofFail(-1, "port can't be null"); - } - try { - List rules = sentinelApiClient.fetchDegradeRuleOfMachine(app, ip, port); - rules = repository.saveAll(rules); - return Result.ofSuccess(rules); - } catch (Throwable throwable) { - logger.error("queryApps error:", throwable); - return Result.ofThrowable(-1, throwable); - } - } + @ResponseBody + @RequestMapping("/rules.json") + @AuthAction(PrivilegeType.READ_RULE) + public Result> queryMachineRules(String app, String ip, Integer port) { - @ResponseBody - @RequestMapping("/new.json") - @AuthAction(PrivilegeType.WRITE_RULE) - public Result add(String app, String ip, Integer port, String limitApp, String resource, - Double count, Integer timeWindow, Integer grade) { - if (StringUtil.isBlank(app)) { - return Result.ofFail(-1, "app can't be null or empty"); - } - if (StringUtil.isBlank(ip)) { - return Result.ofFail(-1, "ip can't be null or empty"); - } - if (port == null) { - return Result.ofFail(-1, "port can't be null"); - } - if (StringUtil.isBlank(limitApp)) { - return Result.ofFail(-1, "limitApp can't be null or empty"); - } - if (StringUtil.isBlank(resource)) { - return Result.ofFail(-1, "resource can't be null or empty"); - } - if (count == null) { - return Result.ofFail(-1, "count can't be null"); - } - if (timeWindow == null) { - return Result.ofFail(-1, "timeWindow can't be null"); - } - if (grade == null) { - return Result.ofFail(-1, "grade can't be null"); - } - if (grade < RuleConstant.DEGRADE_GRADE_RT || grade > RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT) { - return Result.ofFail(-1, "Invalid grade: " + grade); - } - DegradeRuleEntity entity = new DegradeRuleEntity(); - entity.setApp(app.trim()); - entity.setIp(ip.trim()); - entity.setPort(port); - entity.setLimitApp(limitApp.trim()); - entity.setResource(resource.trim()); - entity.setCount(count); - entity.setTimeWindow(timeWindow); - entity.setGrade(grade); - Date date = new Date(); - entity.setGmtCreate(date); - entity.setGmtModified(date); - try { - entity = repository.save(entity); - } catch (Throwable throwable) { - logger.error("add error:", throwable); - return Result.ofThrowable(-1, throwable); - } - if (!publishRules(app, ip, port)) { - logger.info("publish degrade rules fail after rule add"); - } - return Result.ofSuccess(entity); - } + if (StringUtil.isEmpty(app)) { + return Result.ofFail(-1, "app can't be null or empty"); + } + if (StringUtil.isEmpty(ip)) { + return Result.ofFail(-1, "ip can't be null or empty"); + } + if (port == null) { + return Result.ofFail(-1, "port can't be null"); + } + try { + List rules = sentinelApiClient.fetchDegradeRuleOfMachine(app, ip, port); + rules = repository.saveAll(rules); + return Result.ofSuccess(rules); + } + catch (Throwable throwable) { + logger.error("queryApps error:", throwable); + return Result.ofThrowable(-1, throwable); + } + } - @ResponseBody - @RequestMapping("/save.json") - @AuthAction(PrivilegeType.WRITE_RULE) - public Result updateIfNotNull(Long id, String app, String limitApp, String resource, - Double count, Integer timeWindow, Integer grade) { - if (id == null) { - return Result.ofFail(-1, "id can't be null"); - } - if (grade != null) { - if (grade < RuleConstant.DEGRADE_GRADE_RT || grade > RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT) { - return Result.ofFail(-1, "Invalid grade: " + grade); - } - } - DegradeRuleEntity entity = repository.findById(id); - if (entity == null) { - return Result.ofFail(-1, "id " + id + " dose not exist"); - } + @ResponseBody + @RequestMapping("/new.json") + @AuthAction(PrivilegeType.WRITE_RULE) + public Result add(String app, String ip, Integer port, String limitApp, String resource, + Double count, Integer timeWindow, Integer grade) { + if (StringUtil.isBlank(app)) { + return Result.ofFail(-1, "app can't be null or empty"); + } + if (StringUtil.isBlank(ip)) { + return Result.ofFail(-1, "ip can't be null or empty"); + } + if (port == null) { + return Result.ofFail(-1, "port can't be null"); + } + if (StringUtil.isBlank(limitApp)) { + return Result.ofFail(-1, "limitApp can't be null or empty"); + } + if (StringUtil.isBlank(resource)) { + return Result.ofFail(-1, "resource can't be null or empty"); + } + if (count == null) { + return Result.ofFail(-1, "count can't be null"); + } + if (timeWindow == null) { + return Result.ofFail(-1, "timeWindow can't be null"); + } + if (grade == null) { + return Result.ofFail(-1, "grade can't be null"); + } + if (grade < RuleConstant.DEGRADE_GRADE_RT || grade > RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT) { + return Result.ofFail(-1, "Invalid grade: " + grade); + } + DegradeRuleEntity entity = new DegradeRuleEntity(); + entity.setApp(app.trim()); + entity.setIp(ip.trim()); + entity.setPort(port); + entity.setLimitApp(limitApp.trim()); + entity.setResource(resource.trim()); + entity.setCount(count); + entity.setTimeWindow(timeWindow); + entity.setGrade(grade); + Date date = new Date(); + entity.setGmtCreate(date); + entity.setGmtModified(date); + try { + entity = repository.save(entity); + } + catch (Throwable throwable) { + logger.error("add error:", throwable); + return Result.ofThrowable(-1, throwable); + } + if (!publishRules(app, ip, port)) { + logger.info("publish degrade rules fail after rule add"); + } + return Result.ofSuccess(entity); + } - if (StringUtil.isNotBlank(app)) { - entity.setApp(app.trim()); - } + @ResponseBody + @RequestMapping("/save.json") + @AuthAction(PrivilegeType.WRITE_RULE) + public Result updateIfNotNull(Long id, String app, String limitApp, String resource, + Double count, Integer timeWindow, Integer grade) { + if (id == null) { + return Result.ofFail(-1, "id can't be null"); + } + if (grade != null) { + if (grade < RuleConstant.DEGRADE_GRADE_RT || grade > RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT) { + return Result.ofFail(-1, "Invalid grade: " + grade); + } + } + DegradeRuleEntity entity = repository.findById(id); + if (entity == null) { + return Result.ofFail(-1, "id " + id + " dose not exist"); + } - if (StringUtil.isNotBlank(limitApp)) { - entity.setLimitApp(limitApp.trim()); - } - if (StringUtil.isNotBlank(resource)) { - entity.setResource(resource.trim()); - } - if (count != null) { - entity.setCount(count); - } - if (timeWindow != null) { - entity.setTimeWindow(timeWindow); - } - if (grade != null) { - entity.setGrade(grade); - } - Date date = new Date(); - entity.setGmtModified(date); - try { - entity = repository.save(entity); - } catch (Throwable throwable) { - logger.error("save error:", throwable); - return Result.ofThrowable(-1, throwable); - } - if (!publishRules(entity.getApp(), entity.getIp(), entity.getPort())) { - logger.info("publish degrade rules fail after rule update"); - } - return Result.ofSuccess(entity); - } + if (StringUtil.isNotBlank(app)) { + entity.setApp(app.trim()); + } - @ResponseBody - @RequestMapping("/delete.json") - @AuthAction(PrivilegeType.DELETE_RULE) - public Result delete(Long id) { - if (id == null) { - return Result.ofFail(-1, "id can't be null"); - } + if (StringUtil.isNotBlank(limitApp)) { + entity.setLimitApp(limitApp.trim()); + } + if (StringUtil.isNotBlank(resource)) { + entity.setResource(resource.trim()); + } + if (count != null) { + entity.setCount(count); + } + if (timeWindow != null) { + entity.setTimeWindow(timeWindow); + } + if (grade != null) { + entity.setGrade(grade); + } + Date date = new Date(); + entity.setGmtModified(date); + try { + entity = repository.save(entity); + } + catch (Throwable throwable) { + logger.error("save error:", throwable); + return Result.ofThrowable(-1, throwable); + } + if (!publishRules(entity.getApp(), entity.getIp(), entity.getPort())) { + logger.info("publish degrade rules fail after rule update"); + } + return Result.ofSuccess(entity); + } - DegradeRuleEntity oldEntity = repository.findById(id); - if (oldEntity == null) { - return Result.ofSuccess(null); - } + @ResponseBody + @RequestMapping("/delete.json") + @AuthAction(PrivilegeType.DELETE_RULE) + public Result delete(Long id) { + if (id == null) { + return Result.ofFail(-1, "id can't be null"); + } - try { - repository.delete(id); - } catch (Throwable throwable) { - logger.error("delete error:", throwable); - return Result.ofThrowable(-1, throwable); - } - if (!publishRules(oldEntity.getApp(), oldEntity.getIp(), oldEntity.getPort())) { - logger.info("publish degrade rules fail after rule delete"); - } - return Result.ofSuccess(id); - } + DegradeRuleEntity oldEntity = repository.findById(id); + if (oldEntity == null) { + return Result.ofSuccess(null); + } + + try { + repository.delete(id); + } + catch (Throwable throwable) { + logger.error("delete error:", throwable); + return Result.ofThrowable(-1, throwable); + } + if (!publishRules(oldEntity.getApp(), oldEntity.getIp(), oldEntity.getPort())) { + logger.info("publish degrade rules fail after rule delete"); + } + return Result.ofSuccess(id); + } + + private boolean publishRules(String app, String ip, Integer port) { + List rules = repository.findAllByMachine(MachineInfo.of(app, ip, port)); + return sentinelApiClient.setDegradeRuleOfMachine(app, ip, port, rules); + } - private boolean publishRules(String app, String ip, Integer port) { - List rules = repository.findAllByMachine(MachineInfo.of(app, ip, port)); - return sentinelApiClient.setDegradeRuleOfMachine(app, ip, port, rules); - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/DemoController.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/DemoController.java index 91ae67122..9c77b7697 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/DemoController.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/DemoController.java @@ -15,9 +15,11 @@ */ package com.alibaba.csp.sentinel.dashboard.controller; -import java.util.Random; -import java.util.concurrent.TimeUnit; - +import com.alibaba.csp.sentinel.Entry; +import com.alibaba.csp.sentinel.EntryType; +import com.alibaba.csp.sentinel.SphU; +import com.alibaba.csp.sentinel.context.ContextUtil; +import com.alibaba.csp.sentinel.slots.block.BlockException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; @@ -25,111 +27,115 @@ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; -import com.alibaba.csp.sentinel.Entry; -import com.alibaba.csp.sentinel.EntryType; -import com.alibaba.csp.sentinel.SphU; -import com.alibaba.csp.sentinel.context.ContextUtil; -import com.alibaba.csp.sentinel.slots.block.BlockException; +import java.util.Random; +import java.util.concurrent.TimeUnit; @Controller @RequestMapping(value = "/demo", produces = MediaType.APPLICATION_JSON_VALUE) public class DemoController { - Logger logger = LoggerFactory.getLogger(MachineRegistryController.class); + Logger logger = LoggerFactory.getLogger(MachineRegistryController.class); - @RequestMapping("/greeting") - public String greeting() { - return "index"; - } + @RequestMapping("/greeting") + public String greeting() { + return "index"; + } - @RequestMapping("/link") - @ResponseBody - public String link() throws BlockException { + @RequestMapping("/link") + @ResponseBody + public String link() throws BlockException { - Entry entry = SphU.entry("head1", EntryType.IN); + Entry entry = SphU.entry("head1", EntryType.IN); - Entry entry1 = SphU.entry("head2", EntryType.IN); - Entry entry2 = SphU.entry("head3", EntryType.IN); - Entry entry3 = SphU.entry("head4", EntryType.IN); + Entry entry1 = SphU.entry("head2", EntryType.IN); + Entry entry2 = SphU.entry("head3", EntryType.IN); + Entry entry3 = SphU.entry("head4", EntryType.IN); - entry3.exit(); - entry2.exit(); - entry1.exit(); - entry.exit(); - return "successfully create a call link"; - } + entry3.exit(); + entry2.exit(); + entry1.exit(); + entry.exit(); + return "successfully create a call link"; + } - @RequestMapping("/loop") - @ResponseBody - public String loop(String name, int time) throws BlockException { - for (int i = 0; i < 10; i++) { - Thread timer = new Thread(new RunTask(name, time, false)); - timer.setName("false"); - timer.start(); - } - return "successfully create a loop thread"; - } + @RequestMapping("/loop") + @ResponseBody + public String loop(String name, int time) throws BlockException { + for (int i = 0; i < 10; i++) { + Thread timer = new Thread(new RunTask(name, time, false)); + timer.setName("false"); + timer.start(); + } + return "successfully create a loop thread"; + } - @RequestMapping("/slow") - @ResponseBody - public String slow(String name, int time) throws BlockException { - for (int i = 0; i < 10; i++) { - Thread timer = new Thread(new RunTask(name, time, true)); - timer.setName("false"); - timer.start(); - } - return "successfully create a loop thread"; - } + @RequestMapping("/slow") + @ResponseBody + public String slow(String name, int time) throws BlockException { + for (int i = 0; i < 10; i++) { + Thread timer = new Thread(new RunTask(name, time, true)); + timer.setName("false"); + timer.start(); + } + return "successfully create a loop thread"; + } - static class RunTask implements Runnable { - int time; - boolean stop = false; - String name; - boolean slow = false; + static class RunTask implements Runnable { - public RunTask(String name, int time, boolean slow) { - super(); - this.time = time; - this.name = name; - this.slow = slow; - } + int time; - @Override - public void run() { - long startTime = System.currentTimeMillis(); - ContextUtil.enter(String.valueOf(startTime)); - while (!stop) { + boolean stop = false; - long now = System.currentTimeMillis(); - if (now - startTime > time * 1000) { - stop = true; - } - Entry e1 = null; - try { - e1 = SphU.entry(name); + String name; - if (slow == true) { - TimeUnit.MILLISECONDS.sleep(3000); - } + boolean slow = false; - } catch (Exception e) { - } finally { - if (e1 != null) { - e1.exit(); - } - } - Random random2 = new Random(); - try { - TimeUnit.MILLISECONDS.sleep(random2.nextInt(200)); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + public RunTask(String name, int time, boolean slow) { + super(); + this.time = time; + this.name = name; + this.slow = slow; + } - } - ContextUtil.exit(); - } + @Override + public void run() { + long startTime = System.currentTimeMillis(); + ContextUtil.enter(String.valueOf(startTime)); + while (!stop) { - } + long now = System.currentTimeMillis(); + if (now - startTime > time * 1000) { + stop = true; + } + Entry e1 = null; + try { + e1 = SphU.entry(name); + + if (slow == true) { + TimeUnit.MILLISECONDS.sleep(3000); + } + + } + catch (Exception e) { + } + finally { + if (e1 != null) { + e1.exit(); + } + } + Random random2 = new Random(); + try { + TimeUnit.MILLISECONDS.sleep(random2.nextInt(200)); + } + catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + ContextUtil.exit(); + } + + } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/FlowControllerV1.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/FlowControllerV1.java index 50c4e32f6..9f4594c92 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/FlowControllerV1.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/FlowControllerV1.java @@ -53,221 +53,224 @@ import org.springframework.web.bind.annotation.RestController; @RequestMapping(value = "/v1/flow") public class FlowControllerV1 { - private final Logger logger = LoggerFactory.getLogger(FlowControllerV1.class); + private final Logger logger = LoggerFactory.getLogger(FlowControllerV1.class); - @Autowired - private InMemoryRuleRepositoryAdapter repository; + @Autowired + private InMemoryRuleRepositoryAdapter repository; - @Autowired - private SentinelApiClient sentinelApiClient; + @Autowired + private SentinelApiClient sentinelApiClient; - @GetMapping("/rules") - @AuthAction(PrivilegeType.READ_RULE) - public Result> apiQueryMachineRules(@RequestParam String app, - @RequestParam String ip, - @RequestParam Integer port) { + @GetMapping("/rules") + @AuthAction(PrivilegeType.READ_RULE) + public Result> apiQueryMachineRules(@RequestParam String app, @RequestParam String ip, + @RequestParam Integer port) { - if (StringUtil.isEmpty(app)) { - return Result.ofFail(-1, "app can't be null or empty"); - } - if (StringUtil.isEmpty(ip)) { - return Result.ofFail(-1, "ip can't be null or empty"); - } - if (port == null) { - return Result.ofFail(-1, "port can't be null"); - } - try { - List rules = sentinelApiClient.fetchFlowRuleOfMachine(app, ip, port); - rules = repository.saveAll(rules); - return Result.ofSuccess(rules); - } catch (Throwable throwable) { - logger.error("Error when querying flow rules", throwable); - return Result.ofThrowable(-1, throwable); - } - } + if (StringUtil.isEmpty(app)) { + return Result.ofFail(-1, "app can't be null or empty"); + } + if (StringUtil.isEmpty(ip)) { + return Result.ofFail(-1, "ip can't be null or empty"); + } + if (port == null) { + return Result.ofFail(-1, "port can't be null"); + } + try { + List rules = sentinelApiClient.fetchFlowRuleOfMachine(app, ip, port); + rules = repository.saveAll(rules); + return Result.ofSuccess(rules); + } + catch (Throwable throwable) { + logger.error("Error when querying flow rules", throwable); + return Result.ofThrowable(-1, throwable); + } + } - private Result checkEntityInternal(FlowRuleEntity entity) { - if (StringUtil.isBlank(entity.getApp())) { - return Result.ofFail(-1, "app can't be null or empty"); - } - if (StringUtil.isBlank(entity.getIp())) { - return Result.ofFail(-1, "ip can't be null or empty"); - } - if (entity.getPort() == null) { - return Result.ofFail(-1, "port can't be null"); - } - if (StringUtil.isBlank(entity.getLimitApp())) { - return Result.ofFail(-1, "limitApp can't be null or empty"); - } - if (StringUtil.isBlank(entity.getResource())) { - return Result.ofFail(-1, "resource can't be null or empty"); - } - if (entity.getGrade() == null) { - return Result.ofFail(-1, "grade can't be null"); - } - if (entity.getGrade() != 0 && entity.getGrade() != 1) { - return Result.ofFail(-1, "grade must be 0 or 1, but " + entity.getGrade() + " got"); - } - if (entity.getCount() == null || entity.getCount() < 0) { - return Result.ofFail(-1, "count should be at lease zero"); - } - if (entity.getStrategy() == null) { - return Result.ofFail(-1, "strategy can't be null"); - } - if (entity.getStrategy() != 0 && StringUtil.isBlank(entity.getRefResource())) { - return Result.ofFail(-1, "refResource can't be null or empty when strategy!=0"); - } - if (entity.getControlBehavior() == null) { - return Result.ofFail(-1, "controlBehavior can't be null"); - } - int controlBehavior = entity.getControlBehavior(); - if (controlBehavior == 1 && entity.getWarmUpPeriodSec() == null) { - return Result.ofFail(-1, "warmUpPeriodSec can't be null when controlBehavior==1"); - } - if (controlBehavior == 2 && entity.getMaxQueueingTimeMs() == null) { - return Result.ofFail(-1, "maxQueueingTimeMs can't be null when controlBehavior==2"); - } - if (entity.isClusterMode() && entity.getClusterConfig() == null) { - return Result.ofFail(-1, "cluster config should be valid"); - } - return null; - } + private Result checkEntityInternal(FlowRuleEntity entity) { + if (StringUtil.isBlank(entity.getApp())) { + return Result.ofFail(-1, "app can't be null or empty"); + } + if (StringUtil.isBlank(entity.getIp())) { + return Result.ofFail(-1, "ip can't be null or empty"); + } + if (entity.getPort() == null) { + return Result.ofFail(-1, "port can't be null"); + } + if (StringUtil.isBlank(entity.getLimitApp())) { + return Result.ofFail(-1, "limitApp can't be null or empty"); + } + if (StringUtil.isBlank(entity.getResource())) { + return Result.ofFail(-1, "resource can't be null or empty"); + } + if (entity.getGrade() == null) { + return Result.ofFail(-1, "grade can't be null"); + } + if (entity.getGrade() != 0 && entity.getGrade() != 1) { + return Result.ofFail(-1, "grade must be 0 or 1, but " + entity.getGrade() + " got"); + } + if (entity.getCount() == null || entity.getCount() < 0) { + return Result.ofFail(-1, "count should be at lease zero"); + } + if (entity.getStrategy() == null) { + return Result.ofFail(-1, "strategy can't be null"); + } + if (entity.getStrategy() != 0 && StringUtil.isBlank(entity.getRefResource())) { + return Result.ofFail(-1, "refResource can't be null or empty when strategy!=0"); + } + if (entity.getControlBehavior() == null) { + return Result.ofFail(-1, "controlBehavior can't be null"); + } + int controlBehavior = entity.getControlBehavior(); + if (controlBehavior == 1 && entity.getWarmUpPeriodSec() == null) { + return Result.ofFail(-1, "warmUpPeriodSec can't be null when controlBehavior==1"); + } + if (controlBehavior == 2 && entity.getMaxQueueingTimeMs() == null) { + return Result.ofFail(-1, "maxQueueingTimeMs can't be null when controlBehavior==2"); + } + if (entity.isClusterMode() && entity.getClusterConfig() == null) { + return Result.ofFail(-1, "cluster config should be valid"); + } + return null; + } - @PostMapping("/rule") - @AuthAction(PrivilegeType.WRITE_RULE) - public Result apiAddFlowRule(@RequestBody FlowRuleEntity entity) { - Result checkResult = checkEntityInternal(entity); - if (checkResult != null) { - return checkResult; - } - entity.setId(null); - Date date = new Date(); - entity.setGmtCreate(date); - entity.setGmtModified(date); - entity.setLimitApp(entity.getLimitApp().trim()); - entity.setResource(entity.getResource().trim()); - try { - entity = repository.save(entity); + @PostMapping("/rule") + @AuthAction(PrivilegeType.WRITE_RULE) + public Result apiAddFlowRule(@RequestBody FlowRuleEntity entity) { + Result checkResult = checkEntityInternal(entity); + if (checkResult != null) { + return checkResult; + } + entity.setId(null); + Date date = new Date(); + entity.setGmtCreate(date); + entity.setGmtModified(date); + entity.setLimitApp(entity.getLimitApp().trim()); + entity.setResource(entity.getResource().trim()); + try { + entity = repository.save(entity); - publishRules(entity.getApp(), entity.getIp(), entity.getPort()).get(5000, TimeUnit.MILLISECONDS); - return Result.ofSuccess(entity); - } catch (Throwable t) { - Throwable e = t instanceof ExecutionException ? t.getCause() : t; - logger.error("Failed to add new flow rule, app={}, ip={}", entity.getApp(), entity.getIp(), e); - return Result.ofFail(-1, e.getMessage()); - } - } + publishRules(entity.getApp(), entity.getIp(), entity.getPort()).get(5000, TimeUnit.MILLISECONDS); + return Result.ofSuccess(entity); + } + catch (Throwable t) { + Throwable e = t instanceof ExecutionException ? t.getCause() : t; + logger.error("Failed to add new flow rule, app={}, ip={}", entity.getApp(), entity.getIp(), e); + return Result.ofFail(-1, e.getMessage()); + } + } - @PutMapping("/save.json") - @AuthAction(PrivilegeType.WRITE_RULE) - public Result apiUpdateFlowRule(Long id, String app, - String limitApp, String resource, Integer grade, - Double count, Integer strategy, String refResource, - Integer controlBehavior, Integer warmUpPeriodSec, - Integer maxQueueingTimeMs) { - if (id == null) { - return Result.ofFail(-1, "id can't be null"); - } - FlowRuleEntity entity = repository.findById(id); - if (entity == null) { - return Result.ofFail(-1, "id " + id + " dose not exist"); - } - if (StringUtil.isNotBlank(app)) { - entity.setApp(app.trim()); - } - if (StringUtil.isNotBlank(limitApp)) { - entity.setLimitApp(limitApp.trim()); - } - if (StringUtil.isNotBlank(resource)) { - entity.setResource(resource.trim()); - } - if (grade != null) { - if (grade != 0 && grade != 1) { - return Result.ofFail(-1, "grade must be 0 or 1, but " + grade + " got"); - } - entity.setGrade(grade); - } - if (count != null) { - entity.setCount(count); - } - if (strategy != null) { - if (strategy != 0 && strategy != 1 && strategy != 2) { - return Result.ofFail(-1, "strategy must be in [0, 1, 2], but " + strategy + " got"); - } - entity.setStrategy(strategy); - if (strategy != 0) { - if (StringUtil.isBlank(refResource)) { - return Result.ofFail(-1, "refResource can't be null or empty when strategy!=0"); - } - entity.setRefResource(refResource.trim()); - } - } - if (controlBehavior != null) { - if (controlBehavior != 0 && controlBehavior != 1 && controlBehavior != 2) { - return Result.ofFail(-1, "controlBehavior must be in [0, 1, 2], but " + controlBehavior + " got"); - } - if (controlBehavior == 1 && warmUpPeriodSec == null) { - return Result.ofFail(-1, "warmUpPeriodSec can't be null when controlBehavior==1"); - } - if (controlBehavior == 2 && maxQueueingTimeMs == null) { - return Result.ofFail(-1, "maxQueueingTimeMs can't be null when controlBehavior==2"); - } - entity.setControlBehavior(controlBehavior); - if (warmUpPeriodSec != null) { - entity.setWarmUpPeriodSec(warmUpPeriodSec); - } - if (maxQueueingTimeMs != null) { - entity.setMaxQueueingTimeMs(maxQueueingTimeMs); - } - } - Date date = new Date(); - entity.setGmtModified(date); - try { - entity = repository.save(entity); - if (entity == null) { - return Result.ofFail(-1, "save entity fail: null"); - } + @PutMapping("/save.json") + @AuthAction(PrivilegeType.WRITE_RULE) + public Result apiUpdateFlowRule(Long id, String app, String limitApp, String resource, + Integer grade, Double count, Integer strategy, String refResource, Integer controlBehavior, + Integer warmUpPeriodSec, Integer maxQueueingTimeMs) { + if (id == null) { + return Result.ofFail(-1, "id can't be null"); + } + FlowRuleEntity entity = repository.findById(id); + if (entity == null) { + return Result.ofFail(-1, "id " + id + " dose not exist"); + } + if (StringUtil.isNotBlank(app)) { + entity.setApp(app.trim()); + } + if (StringUtil.isNotBlank(limitApp)) { + entity.setLimitApp(limitApp.trim()); + } + if (StringUtil.isNotBlank(resource)) { + entity.setResource(resource.trim()); + } + if (grade != null) { + if (grade != 0 && grade != 1) { + return Result.ofFail(-1, "grade must be 0 or 1, but " + grade + " got"); + } + entity.setGrade(grade); + } + if (count != null) { + entity.setCount(count); + } + if (strategy != null) { + if (strategy != 0 && strategy != 1 && strategy != 2) { + return Result.ofFail(-1, "strategy must be in [0, 1, 2], but " + strategy + " got"); + } + entity.setStrategy(strategy); + if (strategy != 0) { + if (StringUtil.isBlank(refResource)) { + return Result.ofFail(-1, "refResource can't be null or empty when strategy!=0"); + } + entity.setRefResource(refResource.trim()); + } + } + if (controlBehavior != null) { + if (controlBehavior != 0 && controlBehavior != 1 && controlBehavior != 2) { + return Result.ofFail(-1, "controlBehavior must be in [0, 1, 2], but " + controlBehavior + " got"); + } + if (controlBehavior == 1 && warmUpPeriodSec == null) { + return Result.ofFail(-1, "warmUpPeriodSec can't be null when controlBehavior==1"); + } + if (controlBehavior == 2 && maxQueueingTimeMs == null) { + return Result.ofFail(-1, "maxQueueingTimeMs can't be null when controlBehavior==2"); + } + entity.setControlBehavior(controlBehavior); + if (warmUpPeriodSec != null) { + entity.setWarmUpPeriodSec(warmUpPeriodSec); + } + if (maxQueueingTimeMs != null) { + entity.setMaxQueueingTimeMs(maxQueueingTimeMs); + } + } + Date date = new Date(); + entity.setGmtModified(date); + try { + entity = repository.save(entity); + if (entity == null) { + return Result.ofFail(-1, "save entity fail: null"); + } - publishRules(entity.getApp(), entity.getIp(), entity.getPort()).get(5000, TimeUnit.MILLISECONDS); - return Result.ofSuccess(entity); - } catch (Throwable t) { - Throwable e = t instanceof ExecutionException ? t.getCause() : t; - logger.error("Error when updating flow rules, app={}, ip={}, ruleId={}", entity.getApp(), - entity.getIp(), id, e); - return Result.ofFail(-1, e.getMessage()); - } - } + publishRules(entity.getApp(), entity.getIp(), entity.getPort()).get(5000, TimeUnit.MILLISECONDS); + return Result.ofSuccess(entity); + } + catch (Throwable t) { + Throwable e = t instanceof ExecutionException ? t.getCause() : t; + logger.error("Error when updating flow rules, app={}, ip={}, ruleId={}", entity.getApp(), entity.getIp(), + id, e); + return Result.ofFail(-1, e.getMessage()); + } + } - @DeleteMapping("/delete.json") - @AuthAction(PrivilegeType.WRITE_RULE) - public Result apiDeleteFlowRule(Long id) { + @DeleteMapping("/delete.json") + @AuthAction(PrivilegeType.WRITE_RULE) + public Result apiDeleteFlowRule(Long id) { - if (id == null) { - return Result.ofFail(-1, "id can't be null"); - } - FlowRuleEntity oldEntity = repository.findById(id); - if (oldEntity == null) { - return Result.ofSuccess(null); - } + if (id == null) { + return Result.ofFail(-1, "id can't be null"); + } + FlowRuleEntity oldEntity = repository.findById(id); + if (oldEntity == null) { + return Result.ofSuccess(null); + } - try { - repository.delete(id); - } catch (Exception e) { - return Result.ofFail(-1, e.getMessage()); - } - try { - publishRules(oldEntity.getApp(), oldEntity.getIp(), oldEntity.getPort()).get(5000, TimeUnit.MILLISECONDS); - return Result.ofSuccess(id); - } catch (Throwable t) { - Throwable e = t instanceof ExecutionException ? t.getCause() : t; - logger.error("Error when deleting flow rules, app={}, ip={}, id={}", oldEntity.getApp(), - oldEntity.getIp(), id, e); - return Result.ofFail(-1, e.getMessage()); - } - } + try { + repository.delete(id); + } + catch (Exception e) { + return Result.ofFail(-1, e.getMessage()); + } + try { + publishRules(oldEntity.getApp(), oldEntity.getIp(), oldEntity.getPort()).get(5000, TimeUnit.MILLISECONDS); + return Result.ofSuccess(id); + } + catch (Throwable t) { + Throwable e = t instanceof ExecutionException ? t.getCause() : t; + logger.error("Error when deleting flow rules, app={}, ip={}, id={}", oldEntity.getApp(), oldEntity.getIp(), + id, e); + return Result.ofFail(-1, e.getMessage()); + } + } + + private CompletableFuture publishRules(String app, String ip, Integer port) { + List rules = repository.findAllByMachine(MachineInfo.of(app, ip, port)); + return sentinelApiClient.setFlowRuleOfMachineAsync(app, ip, port, rules); + } - private CompletableFuture publishRules(String app, String ip, Integer port) { - List rules = repository.findAllByMachine(MachineInfo.of(app, ip, port)); - return sentinelApiClient.setFlowRuleOfMachineAsync(app, ip, port, rules); - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/MachineRegistryController.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/MachineRegistryController.java index 9a9a7f76a..83f5312c6 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/MachineRegistryController.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/MachineRegistryController.java @@ -34,44 +34,48 @@ import org.springframework.web.bind.annotation.ResponseBody; @RequestMapping(value = "/registry", produces = MediaType.APPLICATION_JSON_VALUE) public class MachineRegistryController { - private final Logger logger = LoggerFactory.getLogger(MachineRegistryController.class); + private final Logger logger = LoggerFactory.getLogger(MachineRegistryController.class); - @Autowired - private AppManagement appManagement; + @Autowired + private AppManagement appManagement; + + @ResponseBody + @RequestMapping("/machine") + public Result receiveHeartBeat(String app, + @RequestParam(value = "app_type", required = false, defaultValue = "0") Integer appType, Long version, + String v, String hostname, String ip, Integer port) { + if (app == null) { + app = MachineDiscovery.UNKNOWN_APP_NAME; + } + if (ip == null) { + return Result.ofFail(-1, "ip can't be null"); + } + if (port == null) { + return Result.ofFail(-1, "port can't be null"); + } + if (port == -1) { + logger.info("Receive heartbeat from " + ip + " but port not set yet"); + return Result.ofFail(-1, "your port not set yet"); + } + String sentinelVersion = StringUtil.isEmpty(v) ? "unknown" : v; + version = version == null ? System.currentTimeMillis() : version; + try { + MachineInfo machineInfo = new MachineInfo(); + machineInfo.setApp(app); + machineInfo.setAppType(appType); + machineInfo.setHostname(hostname); + machineInfo.setIp(ip); + machineInfo.setPort(port); + machineInfo.setHeartbeatVersion(version); + machineInfo.setLastHeartbeat(System.currentTimeMillis()); + machineInfo.setVersion(sentinelVersion); + appManagement.addMachine(machineInfo); + return Result.ofSuccessMsg("success"); + } + catch (Exception e) { + logger.error("Receive heartbeat error", e); + return Result.ofFail(-1, e.getMessage()); + } + } - @ResponseBody - @RequestMapping("/machine") - public Result receiveHeartBeat(String app, @RequestParam(value = "app_type", required = false, defaultValue = "0") Integer appType, Long version, String v, String hostname, String ip, Integer port) { - if (app == null) { - app = MachineDiscovery.UNKNOWN_APP_NAME; - } - if (ip == null) { - return Result.ofFail(-1, "ip can't be null"); - } - if (port == null) { - return Result.ofFail(-1, "port can't be null"); - } - if (port == -1) { - logger.info("Receive heartbeat from " + ip + " but port not set yet"); - return Result.ofFail(-1, "your port not set yet"); - } - String sentinelVersion = StringUtil.isEmpty(v) ? "unknown" : v; - version = version == null ? System.currentTimeMillis() : version; - try { - MachineInfo machineInfo = new MachineInfo(); - machineInfo.setApp(app); - machineInfo.setAppType(appType); - machineInfo.setHostname(hostname); - machineInfo.setIp(ip); - machineInfo.setPort(port); - machineInfo.setHeartbeatVersion(version); - machineInfo.setLastHeartbeat(System.currentTimeMillis()); - machineInfo.setVersion(sentinelVersion); - appManagement.addMachine(machineInfo); - return Result.ofSuccessMsg("success"); - } catch (Exception e) { - logger.error("Receive heartbeat error", e); - return Result.ofFail(-1, e.getMessage()); - } - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/MetricController.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/MetricController.java index ab90c0fc5..32e6e9621 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/MetricController.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/MetricController.java @@ -46,130 +46,126 @@ import com.alibaba.csp.sentinel.dashboard.domain.vo.MetricVo; @RequestMapping(value = "/metric", produces = MediaType.APPLICATION_JSON_VALUE) public class MetricController { - private static Logger logger = LoggerFactory.getLogger(MetricController.class); + private static Logger logger = LoggerFactory.getLogger(MetricController.class); - private static final long maxQueryIntervalMs = 1000 * 60 * 60; + private static final long maxQueryIntervalMs = 1000 * 60 * 60; - @Autowired - private MetricsRepository metricStore; + @Autowired + private MetricsRepository metricStore; - @ResponseBody - @RequestMapping("/queryTopResourceMetric.json") - public Result queryTopResourceMetric(final String app, - Integer pageIndex, - Integer pageSize, - Boolean desc, - Long startTime, Long endTime, String searchKey) { - if (StringUtil.isEmpty(app)) { - return Result.ofFail(-1, "app can't be null or empty"); - } - if (pageIndex == null || pageIndex <= 0) { - pageIndex = 1; - } - if (pageSize == null) { - pageSize = 6; - } - if (pageSize >= 20) { - pageSize = 20; - } - if (desc == null) { - desc = true; - } - if (endTime == null) { - endTime = System.currentTimeMillis(); - } - if (startTime == null) { - startTime = endTime - 1000 * 60 * 5; - } - if (endTime - startTime > maxQueryIntervalMs) { - return Result.ofFail(-1, "time intervalMs is too big, must <= 1h"); - } - List resources = metricStore.listResourcesOfApp(app); - logger.debug("queryTopResourceMetric(), resources.size()={}", resources.size()); + @ResponseBody + @RequestMapping("/queryTopResourceMetric.json") + public Result queryTopResourceMetric(final String app, Integer pageIndex, Integer pageSize, Boolean desc, + Long startTime, Long endTime, String searchKey) { + if (StringUtil.isEmpty(app)) { + return Result.ofFail(-1, "app can't be null or empty"); + } + if (pageIndex == null || pageIndex <= 0) { + pageIndex = 1; + } + if (pageSize == null) { + pageSize = 6; + } + if (pageSize >= 20) { + pageSize = 20; + } + if (desc == null) { + desc = true; + } + if (endTime == null) { + endTime = System.currentTimeMillis(); + } + if (startTime == null) { + startTime = endTime - 1000 * 60 * 5; + } + if (endTime - startTime > maxQueryIntervalMs) { + return Result.ofFail(-1, "time intervalMs is too big, must <= 1h"); + } + List resources = metricStore.listResourcesOfApp(app); + logger.debug("queryTopResourceMetric(), resources.size()={}", resources.size()); - if (resources == null || resources.isEmpty()) { - return Result.ofSuccess(null); - } - if (!desc) { - Collections.reverse(resources); - } - if (StringUtil.isNotEmpty(searchKey)) { - List searched = new ArrayList<>(); - for (String resource : resources) { - if (resource.contains(searchKey)) { - searched.add(resource); - } - } - resources = searched; - } - int totalPage = (resources.size() + pageSize - 1) / pageSize; - List topResource = new ArrayList<>(); - if (pageIndex <= totalPage) { - topResource = resources.subList((pageIndex - 1) * pageSize, - Math.min(pageIndex * pageSize, resources.size())); - } - final Map> map = new ConcurrentHashMap<>(); - logger.debug("topResource={}", topResource); - long time = System.currentTimeMillis(); - for (final String resource : topResource) { - List entities = metricStore.queryByAppAndResourceBetween( - app, resource, startTime, endTime); - logger.debug("resource={}, entities.size()={}", resource, entities == null ? "null" : entities.size()); - List vos = MetricVo.fromMetricEntities(entities, resource); - Iterable vosSorted = sortMetricVoAndDistinct(vos); - map.put(resource, vosSorted); - } - logger.debug("queryTopResourceMetric() total query time={} ms", System.currentTimeMillis() - time); - Map resultMap = new HashMap<>(16); - resultMap.put("totalCount", resources.size()); - resultMap.put("totalPage", totalPage); - resultMap.put("pageIndex", pageIndex); - resultMap.put("pageSize", pageSize); + if (resources == null || resources.isEmpty()) { + return Result.ofSuccess(null); + } + if (!desc) { + Collections.reverse(resources); + } + if (StringUtil.isNotEmpty(searchKey)) { + List searched = new ArrayList<>(); + for (String resource : resources) { + if (resource.contains(searchKey)) { + searched.add(resource); + } + } + resources = searched; + } + int totalPage = (resources.size() + pageSize - 1) / pageSize; + List topResource = new ArrayList<>(); + if (pageIndex <= totalPage) { + topResource = resources.subList((pageIndex - 1) * pageSize, + Math.min(pageIndex * pageSize, resources.size())); + } + final Map> map = new ConcurrentHashMap<>(); + logger.debug("topResource={}", topResource); + long time = System.currentTimeMillis(); + for (final String resource : topResource) { + List entities = metricStore.queryByAppAndResourceBetween(app, resource, startTime, endTime); + logger.debug("resource={}, entities.size()={}", resource, entities == null ? "null" : entities.size()); + List vos = MetricVo.fromMetricEntities(entities, resource); + Iterable vosSorted = sortMetricVoAndDistinct(vos); + map.put(resource, vosSorted); + } + logger.debug("queryTopResourceMetric() total query time={} ms", System.currentTimeMillis() - time); + Map resultMap = new HashMap<>(16); + resultMap.put("totalCount", resources.size()); + resultMap.put("totalPage", totalPage); + resultMap.put("pageIndex", pageIndex); + resultMap.put("pageSize", pageSize); - Map> map2 = new LinkedHashMap<>(); - // order matters. - for (String identity : topResource) { - map2.put(identity, map.get(identity)); - } - resultMap.put("metric", map2); - return Result.ofSuccess(resultMap); - } + Map> map2 = new LinkedHashMap<>(); + // order matters. + for (String identity : topResource) { + map2.put(identity, map.get(identity)); + } + resultMap.put("metric", map2); + return Result.ofSuccess(resultMap); + } - @ResponseBody - @RequestMapping("/queryByAppAndResource.json") - public Result queryByAppAndResource(String app, String identity, Long startTime, Long endTime) { - if (StringUtil.isEmpty(app)) { - return Result.ofFail(-1, "app can't be null or empty"); - } - if (StringUtil.isEmpty(identity)) { - return Result.ofFail(-1, "identity can't be null or empty"); - } - if (endTime == null) { - endTime = System.currentTimeMillis(); - } - if (startTime == null) { - startTime = endTime - 1000 * 60; - } - if (endTime - startTime > maxQueryIntervalMs) { - return Result.ofFail(-1, "time intervalMs is too big, must <= 1h"); - } - List entities = metricStore.queryByAppAndResourceBetween( - app, identity, startTime, endTime); - List vos = MetricVo.fromMetricEntities(entities, identity); - return Result.ofSuccess(sortMetricVoAndDistinct(vos)); - } + @ResponseBody + @RequestMapping("/queryByAppAndResource.json") + public Result queryByAppAndResource(String app, String identity, Long startTime, Long endTime) { + if (StringUtil.isEmpty(app)) { + return Result.ofFail(-1, "app can't be null or empty"); + } + if (StringUtil.isEmpty(identity)) { + return Result.ofFail(-1, "identity can't be null or empty"); + } + if (endTime == null) { + endTime = System.currentTimeMillis(); + } + if (startTime == null) { + startTime = endTime - 1000 * 60; + } + if (endTime - startTime > maxQueryIntervalMs) { + return Result.ofFail(-1, "time intervalMs is too big, must <= 1h"); + } + List entities = metricStore.queryByAppAndResourceBetween(app, identity, startTime, endTime); + List vos = MetricVo.fromMetricEntities(entities, identity); + return Result.ofSuccess(sortMetricVoAndDistinct(vos)); + } + + private Iterable sortMetricVoAndDistinct(List vos) { + if (vos == null) { + return null; + } + Map map = new TreeMap<>(); + for (MetricVo vo : vos) { + MetricVo oldVo = map.get(vo.getTimestamp()); + if (oldVo == null || vo.getGmtCreate() > oldVo.getGmtCreate()) { + map.put(vo.getTimestamp(), vo); + } + } + return map.values(); + } - private Iterable sortMetricVoAndDistinct(List vos) { - if (vos == null) { - return null; - } - Map map = new TreeMap<>(); - for (MetricVo vo : vos) { - MetricVo oldVo = map.get(vo.getTimestamp()); - if (oldVo == null || vo.getGmtCreate() > oldVo.getGmtCreate()) { - map.put(vo.getTimestamp(), vo); - } - } - return map.values(); - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/ParamFlowRuleController.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/ParamFlowRuleController.java index f03925eee..f81d64cd9 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/ParamFlowRuleController.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/ParamFlowRuleController.java @@ -47,213 +47,224 @@ import java.util.concurrent.ExecutionException; @RequestMapping(value = "/paramFlow") public class ParamFlowRuleController { - private final Logger logger = LoggerFactory.getLogger(ParamFlowRuleController.class); + private final Logger logger = LoggerFactory.getLogger(ParamFlowRuleController.class); - @Autowired - private SentinelApiClient sentinelApiClient; - @Autowired - private AppManagement appManagement; - @Autowired - private RuleRepository repository; + @Autowired + private SentinelApiClient sentinelApiClient; - private boolean checkIfSupported(String app, String ip, int port) { - try { - return Optional.ofNullable(appManagement.getDetailApp(app)) - .flatMap(e -> e.getMachine(ip, port)) - .flatMap(m -> VersionUtils.parseVersion(m.getVersion()) - .map(v -> v.greaterOrEqual(version020))) - .orElse(true); - // If error occurred or cannot retrieve machine info, return true. - } catch (Exception ex) { - return true; - } - } + @Autowired + private AppManagement appManagement; - @GetMapping("/rules") - @AuthAction(PrivilegeType.READ_RULE) - public Result> apiQueryAllRulesForMachine(@RequestParam String app, - @RequestParam String ip, - @RequestParam Integer port) { - if (StringUtil.isEmpty(app)) { - return Result.ofFail(-1, "app cannot be null or empty"); - } - if (StringUtil.isEmpty(ip)) { - return Result.ofFail(-1, "ip cannot be null or empty"); - } - if (port == null || port <= 0) { - return Result.ofFail(-1, "Invalid parameter: port"); - } - if (!checkIfSupported(app, ip, port)) { - return unsupportedVersion(); - } - try { - return sentinelApiClient.fetchParamFlowRulesOfMachine(app, ip, port) - .thenApply(repository::saveAll) - .thenApply(Result::ofSuccess) - .get(); - } catch (ExecutionException ex) { - logger.error("Error when querying parameter flow rules", ex.getCause()); - if (isNotSupported(ex.getCause())) { - return unsupportedVersion(); - } else { - return Result.ofThrowable(-1, ex.getCause()); - } - } catch (Throwable throwable) { - logger.error("Error when querying parameter flow rules", throwable); - return Result.ofFail(-1, throwable.getMessage()); - } - } + @Autowired + private RuleRepository repository; - private boolean isNotSupported(Throwable ex) { - return ex instanceof CommandNotFoundException; - } + private boolean checkIfSupported(String app, String ip, int port) { + try { + return Optional.ofNullable(appManagement.getDetailApp(app)).flatMap(e -> e.getMachine(ip, port)) + .flatMap(m -> VersionUtils.parseVersion(m.getVersion()).map(v -> v.greaterOrEqual(version020))) + .orElse(true); + // If error occurred or cannot retrieve machine info, return true. + } + catch (Exception ex) { + return true; + } + } - @PostMapping("/rule") - @AuthAction(PrivilegeType.WRITE_RULE) - public Result apiAddParamFlowRule(@RequestBody ParamFlowRuleEntity entity) { - Result checkResult = checkEntityInternal(entity); - if (checkResult != null) { - return checkResult; - } - if (!checkIfSupported(entity.getApp(), entity.getIp(), entity.getPort())) { - return unsupportedVersion(); - } - entity.setId(null); - entity.getRule().setResource(entity.getResource().trim()); - Date date = new Date(); - entity.setGmtCreate(date); - entity.setGmtModified(date); - try { - entity = repository.save(entity); - publishRules(entity.getApp(), entity.getIp(), entity.getPort()).get(); - return Result.ofSuccess(entity); - } catch (ExecutionException ex) { - logger.error("Error when adding new parameter flow rules", ex.getCause()); - if (isNotSupported(ex.getCause())) { - return unsupportedVersion(); - } else { - return Result.ofThrowable(-1, ex.getCause()); - } - } catch (Throwable throwable) { - logger.error("Error when adding new parameter flow rules", throwable); - return Result.ofFail(-1, throwable.getMessage()); - } - } + @GetMapping("/rules") + @AuthAction(PrivilegeType.READ_RULE) + public Result> apiQueryAllRulesForMachine(@RequestParam String app, + @RequestParam String ip, @RequestParam Integer port) { + if (StringUtil.isEmpty(app)) { + return Result.ofFail(-1, "app cannot be null or empty"); + } + if (StringUtil.isEmpty(ip)) { + return Result.ofFail(-1, "ip cannot be null or empty"); + } + if (port == null || port <= 0) { + return Result.ofFail(-1, "Invalid parameter: port"); + } + if (!checkIfSupported(app, ip, port)) { + return unsupportedVersion(); + } + try { + return sentinelApiClient.fetchParamFlowRulesOfMachine(app, ip, port).thenApply(repository::saveAll) + .thenApply(Result::ofSuccess).get(); + } + catch (ExecutionException ex) { + logger.error("Error when querying parameter flow rules", ex.getCause()); + if (isNotSupported(ex.getCause())) { + return unsupportedVersion(); + } + else { + return Result.ofThrowable(-1, ex.getCause()); + } + } + catch (Throwable throwable) { + logger.error("Error when querying parameter flow rules", throwable); + return Result.ofFail(-1, throwable.getMessage()); + } + } - private Result checkEntityInternal(ParamFlowRuleEntity entity) { - if (entity == null) { - return Result.ofFail(-1, "bad rule body"); - } - if (StringUtil.isBlank(entity.getApp())) { - return Result.ofFail(-1, "app can't be null or empty"); - } - if (StringUtil.isBlank(entity.getIp())) { - return Result.ofFail(-1, "ip can't be null or empty"); - } - if (entity.getPort() == null || entity.getPort() <= 0) { - return Result.ofFail(-1, "port can't be null"); - } - if (entity.getRule() == null) { - return Result.ofFail(-1, "rule can't be null"); - } - if (StringUtil.isBlank(entity.getResource())) { - return Result.ofFail(-1, "resource name cannot be null or empty"); - } - if (entity.getCount() < 0) { - return Result.ofFail(-1, "count should be valid"); - } - if (entity.getGrade() != RuleConstant.FLOW_GRADE_QPS) { - return Result.ofFail(-1, "Unknown mode (blockGrade) for parameter flow control"); - } - if (entity.getParamIdx() == null || entity.getParamIdx() < 0) { - return Result.ofFail(-1, "paramIdx should be valid"); - } - if (entity.getDurationInSec() <= 0) { - return Result.ofFail(-1, "durationInSec should be valid"); - } - if (entity.getControlBehavior() < 0) { - return Result.ofFail(-1, "controlBehavior should be valid"); - } - return null; - } + private boolean isNotSupported(Throwable ex) { + return ex instanceof CommandNotFoundException; + } - @PutMapping("/rule/{id}") - @AuthAction(PrivilegeType.WRITE_RULE) - public Result apiUpdateParamFlowRule(@PathVariable("id") Long id, - @RequestBody ParamFlowRuleEntity entity) { - if (id == null || id <= 0) { - return Result.ofFail(-1, "Invalid id"); - } - ParamFlowRuleEntity oldEntity = repository.findById(id); - if (oldEntity == null) { - return Result.ofFail(-1, "id " + id + " does not exist"); - } + @PostMapping("/rule") + @AuthAction(PrivilegeType.WRITE_RULE) + public Result apiAddParamFlowRule(@RequestBody ParamFlowRuleEntity entity) { + Result checkResult = checkEntityInternal(entity); + if (checkResult != null) { + return checkResult; + } + if (!checkIfSupported(entity.getApp(), entity.getIp(), entity.getPort())) { + return unsupportedVersion(); + } + entity.setId(null); + entity.getRule().setResource(entity.getResource().trim()); + Date date = new Date(); + entity.setGmtCreate(date); + entity.setGmtModified(date); + try { + entity = repository.save(entity); + publishRules(entity.getApp(), entity.getIp(), entity.getPort()).get(); + return Result.ofSuccess(entity); + } + catch (ExecutionException ex) { + logger.error("Error when adding new parameter flow rules", ex.getCause()); + if (isNotSupported(ex.getCause())) { + return unsupportedVersion(); + } + else { + return Result.ofThrowable(-1, ex.getCause()); + } + } + catch (Throwable throwable) { + logger.error("Error when adding new parameter flow rules", throwable); + return Result.ofFail(-1, throwable.getMessage()); + } + } - Result checkResult = checkEntityInternal(entity); - if (checkResult != null) { - return checkResult; - } - if (!checkIfSupported(entity.getApp(), entity.getIp(), entity.getPort())) { - return unsupportedVersion(); - } - entity.setId(id); - Date date = new Date(); - entity.setGmtCreate(oldEntity.getGmtCreate()); - entity.setGmtModified(date); - try { - entity = repository.save(entity); - publishRules(entity.getApp(), entity.getIp(), entity.getPort()).get(); - return Result.ofSuccess(entity); - } catch (ExecutionException ex) { - logger.error("Error when updating parameter flow rules, id=" + id, ex.getCause()); - if (isNotSupported(ex.getCause())) { - return unsupportedVersion(); - } else { - return Result.ofThrowable(-1, ex.getCause()); - } - } catch (Throwable throwable) { - logger.error("Error when updating parameter flow rules, id=" + id, throwable); - return Result.ofFail(-1, throwable.getMessage()); - } - } + private Result checkEntityInternal(ParamFlowRuleEntity entity) { + if (entity == null) { + return Result.ofFail(-1, "bad rule body"); + } + if (StringUtil.isBlank(entity.getApp())) { + return Result.ofFail(-1, "app can't be null or empty"); + } + if (StringUtil.isBlank(entity.getIp())) { + return Result.ofFail(-1, "ip can't be null or empty"); + } + if (entity.getPort() == null || entity.getPort() <= 0) { + return Result.ofFail(-1, "port can't be null"); + } + if (entity.getRule() == null) { + return Result.ofFail(-1, "rule can't be null"); + } + if (StringUtil.isBlank(entity.getResource())) { + return Result.ofFail(-1, "resource name cannot be null or empty"); + } + if (entity.getCount() < 0) { + return Result.ofFail(-1, "count should be valid"); + } + if (entity.getGrade() != RuleConstant.FLOW_GRADE_QPS) { + return Result.ofFail(-1, "Unknown mode (blockGrade) for parameter flow control"); + } + if (entity.getParamIdx() == null || entity.getParamIdx() < 0) { + return Result.ofFail(-1, "paramIdx should be valid"); + } + if (entity.getDurationInSec() <= 0) { + return Result.ofFail(-1, "durationInSec should be valid"); + } + if (entity.getControlBehavior() < 0) { + return Result.ofFail(-1, "controlBehavior should be valid"); + } + return null; + } - @DeleteMapping("/rule/{id}") - @AuthAction(PrivilegeType.DELETE_RULE) - public Result apiDeleteRule(@PathVariable("id") Long id) { - if (id == null) { - return Result.ofFail(-1, "id cannot be null"); - } - ParamFlowRuleEntity oldEntity = repository.findById(id); - if (oldEntity == null) { - return Result.ofSuccess(null); - } + @PutMapping("/rule/{id}") + @AuthAction(PrivilegeType.WRITE_RULE) + public Result apiUpdateParamFlowRule(@PathVariable("id") Long id, + @RequestBody ParamFlowRuleEntity entity) { + if (id == null || id <= 0) { + return Result.ofFail(-1, "Invalid id"); + } + ParamFlowRuleEntity oldEntity = repository.findById(id); + if (oldEntity == null) { + return Result.ofFail(-1, "id " + id + " does not exist"); + } - try { - repository.delete(id); - publishRules(oldEntity.getApp(), oldEntity.getIp(), oldEntity.getPort()).get(); - return Result.ofSuccess(id); - } catch (ExecutionException ex) { - logger.error("Error when deleting parameter flow rules", ex.getCause()); - if (isNotSupported(ex.getCause())) { - return unsupportedVersion(); - } else { - return Result.ofThrowable(-1, ex.getCause()); - } - } catch (Throwable throwable) { - logger.error("Error when deleting parameter flow rules", throwable); - return Result.ofFail(-1, throwable.getMessage()); - } - } + Result checkResult = checkEntityInternal(entity); + if (checkResult != null) { + return checkResult; + } + if (!checkIfSupported(entity.getApp(), entity.getIp(), entity.getPort())) { + return unsupportedVersion(); + } + entity.setId(id); + Date date = new Date(); + entity.setGmtCreate(oldEntity.getGmtCreate()); + entity.setGmtModified(date); + try { + entity = repository.save(entity); + publishRules(entity.getApp(), entity.getIp(), entity.getPort()).get(); + return Result.ofSuccess(entity); + } + catch (ExecutionException ex) { + logger.error("Error when updating parameter flow rules, id=" + id, ex.getCause()); + if (isNotSupported(ex.getCause())) { + return unsupportedVersion(); + } + else { + return Result.ofThrowable(-1, ex.getCause()); + } + } + catch (Throwable throwable) { + logger.error("Error when updating parameter flow rules, id=" + id, throwable); + return Result.ofFail(-1, throwable.getMessage()); + } + } - private CompletableFuture publishRules(String app, String ip, Integer port) { - List rules = repository.findAllByMachine(MachineInfo.of(app, ip, port)); - return sentinelApiClient.setParamFlowRuleOfMachine(app, ip, port, rules); - } + @DeleteMapping("/rule/{id}") + @AuthAction(PrivilegeType.DELETE_RULE) + public Result apiDeleteRule(@PathVariable("id") Long id) { + if (id == null) { + return Result.ofFail(-1, "id cannot be null"); + } + ParamFlowRuleEntity oldEntity = repository.findById(id); + if (oldEntity == null) { + return Result.ofSuccess(null); + } - private Result unsupportedVersion() { - return Result.ofFail(4041, - "Sentinel client not supported for parameter flow control (unsupported version or dependency absent)"); - } + try { + repository.delete(id); + publishRules(oldEntity.getApp(), oldEntity.getIp(), oldEntity.getPort()).get(); + return Result.ofSuccess(id); + } + catch (ExecutionException ex) { + logger.error("Error when deleting parameter flow rules", ex.getCause()); + if (isNotSupported(ex.getCause())) { + return unsupportedVersion(); + } + else { + return Result.ofThrowable(-1, ex.getCause()); + } + } + catch (Throwable throwable) { + logger.error("Error when deleting parameter flow rules", throwable); + return Result.ofFail(-1, throwable.getMessage()); + } + } + + private CompletableFuture publishRules(String app, String ip, Integer port) { + List rules = repository.findAllByMachine(MachineInfo.of(app, ip, port)); + return sentinelApiClient.setParamFlowRuleOfMachine(app, ip, port, rules); + } + + private Result unsupportedVersion() { + return Result.ofFail(4041, + "Sentinel client not supported for parameter flow control (unsupported version or dependency absent)"); + } + + private final SentinelVersion version020 = new SentinelVersion().setMinorVersion(2); - private final SentinelVersion version020 = new SentinelVersion().setMinorVersion(2); } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/ResourceController.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/ResourceController.java index 70382c7ea..da8988e3a 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/ResourceController.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/ResourceController.java @@ -40,52 +40,54 @@ import org.springframework.web.bind.annotation.RestController; @RequestMapping(value = "/resource") public class ResourceController { - private static Logger logger = LoggerFactory.getLogger(ResourceController.class); + private static Logger logger = LoggerFactory.getLogger(ResourceController.class); - @Autowired - private SentinelApiClient httpFetcher; + @Autowired + private SentinelApiClient httpFetcher; + + /** + * Fetch real time statistics info of the machine. + * @param ip ip to fetch + * @param port port of the ip + * @param type one of [root, default, cluster], 'root' means fetching from tree root + * node, 'default' means fetching from tree default node, 'cluster' means fetching + * from cluster node. + * @param searchKey key to search + * @return node statistics info. + */ + @GetMapping("/machineResource.json") + public Result> fetchResourceChainListOfMachine(String ip, Integer port, String type, + String searchKey) { + if (StringUtil.isEmpty(ip) || port == null) { + return Result.ofFail(-1, "invalid param, give ip, port"); + } + final String ROOT = "root"; + final String DEFAULT = "default"; + if (StringUtil.isEmpty(type)) { + type = ROOT; + } + if (ROOT.equalsIgnoreCase(type) || DEFAULT.equalsIgnoreCase(type)) { + List nodeVos = httpFetcher.fetchResourceOfMachine(ip, port, type); + if (nodeVos == null) { + return Result.ofSuccess(null); + } + ResourceTreeNode treeNode = ResourceTreeNode.fromNodeVoList(nodeVos); + treeNode.searchIgnoreCase(searchKey); + return Result.ofSuccess(ResourceVo.fromResourceTreeNode(treeNode)); + } + else { + // Normal (cluster node). + List nodeVos = httpFetcher.fetchClusterNodeOfMachine(ip, port, true); + if (nodeVos == null) { + return Result.ofSuccess(null); + } + if (StringUtil.isNotEmpty(searchKey)) { + nodeVos = nodeVos.stream() + .filter(node -> node.getResource().toLowerCase().contains(searchKey.toLowerCase())) + .collect(Collectors.toList()); + } + return Result.ofSuccess(ResourceVo.fromNodeVoList(nodeVos)); + } + } - /** - * Fetch real time statistics info of the machine. - * - * @param ip ip to fetch - * @param port port of the ip - * @param type one of [root, default, cluster], 'root' means fetching from tree root node, 'default' means - * fetching from tree default node, 'cluster' means fetching from cluster node. - * @param searchKey key to search - * @return node statistics info. - */ - @GetMapping("/machineResource.json") - public Result> fetchResourceChainListOfMachine(String ip, Integer port, String type, - String searchKey) { - if (StringUtil.isEmpty(ip) || port == null) { - return Result.ofFail(-1, "invalid param, give ip, port"); - } - final String ROOT = "root"; - final String DEFAULT = "default"; - if (StringUtil.isEmpty(type)) { - type = ROOT; - } - if (ROOT.equalsIgnoreCase(type) || DEFAULT.equalsIgnoreCase(type)) { - List nodeVos = httpFetcher.fetchResourceOfMachine(ip, port, type); - if (nodeVos == null) { - return Result.ofSuccess(null); - } - ResourceTreeNode treeNode = ResourceTreeNode.fromNodeVoList(nodeVos); - treeNode.searchIgnoreCase(searchKey); - return Result.ofSuccess(ResourceVo.fromResourceTreeNode(treeNode)); - } else { - // Normal (cluster node). - List nodeVos = httpFetcher.fetchClusterNodeOfMachine(ip, port, true); - if (nodeVos == null) { - return Result.ofSuccess(null); - } - if (StringUtil.isNotEmpty(searchKey)) { - nodeVos = nodeVos.stream().filter(node -> node.getResource() - .toLowerCase().contains(searchKey.toLowerCase())) - .collect(Collectors.toList()); - } - return Result.ofSuccess(ResourceVo.fromNodeVoList(nodeVos)); - } - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/SystemController.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/SystemController.java index daa0b98b5..ac23dea54 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/SystemController.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/SystemController.java @@ -42,209 +42,218 @@ import org.springframework.web.bind.annotation.RestController; @RequestMapping("/system") public class SystemController { - private final Logger logger = LoggerFactory.getLogger(SystemController.class); + private final Logger logger = LoggerFactory.getLogger(SystemController.class); - @Autowired - private RuleRepository repository; - @Autowired - private SentinelApiClient sentinelApiClient; + @Autowired + private RuleRepository repository; - private Result checkBasicParams(String app, String ip, Integer port) { - if (StringUtil.isEmpty(app)) { - return Result.ofFail(-1, "app can't be null or empty"); - } - if (StringUtil.isEmpty(ip)) { - return Result.ofFail(-1, "ip can't be null or empty"); - } - if (port == null) { - return Result.ofFail(-1, "port can't be null"); - } - if (port <= 0 || port > 65535) { - return Result.ofFail(-1, "port should be in (0, 65535)"); - } - return null; - } + @Autowired + private SentinelApiClient sentinelApiClient; - @GetMapping("/rules.json") - @AuthAction(PrivilegeType.READ_RULE) - public Result> apiQueryMachineRules(String app, String ip, - Integer port) { - Result> checkResult = checkBasicParams(app, ip, port); - if (checkResult != null) { - return checkResult; - } - try { - List rules = sentinelApiClient.fetchSystemRuleOfMachine(app, ip, port); - rules = repository.saveAll(rules); - return Result.ofSuccess(rules); - } catch (Throwable throwable) { - logger.error("Query machine system rules error", throwable); - return Result.ofThrowable(-1, throwable); - } - } + private Result checkBasicParams(String app, String ip, Integer port) { + if (StringUtil.isEmpty(app)) { + return Result.ofFail(-1, "app can't be null or empty"); + } + if (StringUtil.isEmpty(ip)) { + return Result.ofFail(-1, "ip can't be null or empty"); + } + if (port == null) { + return Result.ofFail(-1, "port can't be null"); + } + if (port <= 0 || port > 65535) { + return Result.ofFail(-1, "port should be in (0, 65535)"); + } + return null; + } - private int countNotNullAndNotNegative(Number... values) { - int notNullCount = 0; - for (int i = 0; i < values.length; i++) { - if (values[i] != null && values[i].doubleValue() >= 0) { - notNullCount++; - } - } - return notNullCount; - } + @GetMapping("/rules.json") + @AuthAction(PrivilegeType.READ_RULE) + public Result> apiQueryMachineRules(String app, String ip, Integer port) { + Result> checkResult = checkBasicParams(app, ip, port); + if (checkResult != null) { + return checkResult; + } + try { + List rules = sentinelApiClient.fetchSystemRuleOfMachine(app, ip, port); + rules = repository.saveAll(rules); + return Result.ofSuccess(rules); + } + catch (Throwable throwable) { + logger.error("Query machine system rules error", throwable); + return Result.ofThrowable(-1, throwable); + } + } - @RequestMapping("/new.json") - @AuthAction(PrivilegeType.WRITE_RULE) - public Result apiAdd(String app, String ip, Integer port, - Double highestSystemLoad, Double highestCpuUsage, Long avgRt, - Long maxThread, Double qps) { + private int countNotNullAndNotNegative(Number... values) { + int notNullCount = 0; + for (int i = 0; i < values.length; i++) { + if (values[i] != null && values[i].doubleValue() >= 0) { + notNullCount++; + } + } + return notNullCount; + } - Result checkResult = checkBasicParams(app, ip, port); - if (checkResult != null) { - return checkResult; - } + @RequestMapping("/new.json") + @AuthAction(PrivilegeType.WRITE_RULE) + public Result apiAdd(String app, String ip, Integer port, Double highestSystemLoad, + Double highestCpuUsage, Long avgRt, Long maxThread, Double qps) { - int notNullCount = countNotNullAndNotNegative(highestSystemLoad, avgRt, maxThread, qps, highestCpuUsage); - if (notNullCount != 1) { - return Result.ofFail(-1, "only one of [highestSystemLoad, avgRt, maxThread, qps,highestCpuUsage] " - + "value must be set > 0, but " + notNullCount + " values get"); - } - if (null != highestCpuUsage && highestCpuUsage > 1) { - return Result.ofFail(-1, "highestCpuUsage must between [0.0, 1.0]"); - } - SystemRuleEntity entity = new SystemRuleEntity(); - entity.setApp(app.trim()); - entity.setIp(ip.trim()); - entity.setPort(port); - // -1 is a fake value - if (null != highestSystemLoad) { - entity.setHighestSystemLoad(highestSystemLoad); - } else { - entity.setHighestSystemLoad(-1D); - } + Result checkResult = checkBasicParams(app, ip, port); + if (checkResult != null) { + return checkResult; + } - if (null != highestCpuUsage) { - entity.setHighestCpuUsage(highestCpuUsage); - } else { - entity.setHighestCpuUsage(-1D); - } + int notNullCount = countNotNullAndNotNegative(highestSystemLoad, avgRt, maxThread, qps, highestCpuUsage); + if (notNullCount != 1) { + return Result.ofFail(-1, "only one of [highestSystemLoad, avgRt, maxThread, qps,highestCpuUsage] " + + "value must be set > 0, but " + notNullCount + " values get"); + } + if (null != highestCpuUsage && highestCpuUsage > 1) { + return Result.ofFail(-1, "highestCpuUsage must between [0.0, 1.0]"); + } + SystemRuleEntity entity = new SystemRuleEntity(); + entity.setApp(app.trim()); + entity.setIp(ip.trim()); + entity.setPort(port); + // -1 is a fake value + if (null != highestSystemLoad) { + entity.setHighestSystemLoad(highestSystemLoad); + } + else { + entity.setHighestSystemLoad(-1D); + } - if (avgRt != null) { - entity.setAvgRt(avgRt); - } else { - entity.setAvgRt(-1L); - } - if (maxThread != null) { - entity.setMaxThread(maxThread); - } else { - entity.setMaxThread(-1L); - } - if (qps != null) { - entity.setQps(qps); - } else { - entity.setQps(-1D); - } - Date date = new Date(); - entity.setGmtCreate(date); - entity.setGmtModified(date); - try { - entity = repository.save(entity); - } catch (Throwable throwable) { - logger.error("Add SystemRule error", throwable); - return Result.ofThrowable(-1, throwable); - } - if (!publishRules(app, ip, port)) { - logger.warn("Publish system rules fail after rule add"); - } - return Result.ofSuccess(entity); - } + if (null != highestCpuUsage) { + entity.setHighestCpuUsage(highestCpuUsage); + } + else { + entity.setHighestCpuUsage(-1D); + } - @GetMapping("/save.json") - @AuthAction(PrivilegeType.WRITE_RULE) - public Result apiUpdateIfNotNull(Long id, String app, Double highestSystemLoad, - Double highestCpuUsage, Long avgRt, Long maxThread, Double qps) { - if (id == null) { - return Result.ofFail(-1, "id can't be null"); - } - SystemRuleEntity entity = repository.findById(id); - if (entity == null) { - return Result.ofFail(-1, "id " + id + " dose not exist"); - } + if (avgRt != null) { + entity.setAvgRt(avgRt); + } + else { + entity.setAvgRt(-1L); + } + if (maxThread != null) { + entity.setMaxThread(maxThread); + } + else { + entity.setMaxThread(-1L); + } + if (qps != null) { + entity.setQps(qps); + } + else { + entity.setQps(-1D); + } + Date date = new Date(); + entity.setGmtCreate(date); + entity.setGmtModified(date); + try { + entity = repository.save(entity); + } + catch (Throwable throwable) { + logger.error("Add SystemRule error", throwable); + return Result.ofThrowable(-1, throwable); + } + if (!publishRules(app, ip, port)) { + logger.warn("Publish system rules fail after rule add"); + } + return Result.ofSuccess(entity); + } - if (StringUtil.isNotBlank(app)) { - entity.setApp(app.trim()); - } - if (highestSystemLoad != null) { - if (highestSystemLoad < 0) { - return Result.ofFail(-1, "highestSystemLoad must >= 0"); - } - entity.setHighestSystemLoad(highestSystemLoad); - } - if (highestCpuUsage != null) { - if (highestCpuUsage < 0) { - return Result.ofFail(-1, "highestCpuUsage must >= 0"); - } - if (highestCpuUsage > 1) { - return Result.ofFail(-1, "highestCpuUsage must <= 1"); - } - entity.setHighestCpuUsage(highestCpuUsage); - } - if (avgRt != null) { - if (avgRt < 0) { - return Result.ofFail(-1, "avgRt must >= 0"); - } - entity.setAvgRt(avgRt); - } - if (maxThread != null) { - if (maxThread < 0) { - return Result.ofFail(-1, "maxThread must >= 0"); - } - entity.setMaxThread(maxThread); - } - if (qps != null) { - if (qps < 0) { - return Result.ofFail(-1, "qps must >= 0"); - } - entity.setQps(qps); - } - Date date = new Date(); - entity.setGmtModified(date); - try { - entity = repository.save(entity); - } catch (Throwable throwable) { - logger.error("save error:", throwable); - return Result.ofThrowable(-1, throwable); - } - if (!publishRules(entity.getApp(), entity.getIp(), entity.getPort())) { - logger.info("publish system rules fail after rule update"); - } - return Result.ofSuccess(entity); - } + @GetMapping("/save.json") + @AuthAction(PrivilegeType.WRITE_RULE) + public Result apiUpdateIfNotNull(Long id, String app, Double highestSystemLoad, + Double highestCpuUsage, Long avgRt, Long maxThread, Double qps) { + if (id == null) { + return Result.ofFail(-1, "id can't be null"); + } + SystemRuleEntity entity = repository.findById(id); + if (entity == null) { + return Result.ofFail(-1, "id " + id + " dose not exist"); + } - @RequestMapping("/delete.json") - @AuthAction(PrivilegeType.DELETE_RULE) - public Result delete(Long id) { - if (id == null) { - return Result.ofFail(-1, "id can't be null"); - } - SystemRuleEntity oldEntity = repository.findById(id); - if (oldEntity == null) { - return Result.ofSuccess(null); - } - try { - repository.delete(id); - } catch (Throwable throwable) { - logger.error("delete error:", throwable); - return Result.ofThrowable(-1, throwable); - } - if (!publishRules(oldEntity.getApp(), oldEntity.getIp(), oldEntity.getPort())) { - logger.info("publish system rules fail after rule delete"); - } - return Result.ofSuccess(id); - } + if (StringUtil.isNotBlank(app)) { + entity.setApp(app.trim()); + } + if (highestSystemLoad != null) { + if (highestSystemLoad < 0) { + return Result.ofFail(-1, "highestSystemLoad must >= 0"); + } + entity.setHighestSystemLoad(highestSystemLoad); + } + if (highestCpuUsage != null) { + if (highestCpuUsage < 0) { + return Result.ofFail(-1, "highestCpuUsage must >= 0"); + } + if (highestCpuUsage > 1) { + return Result.ofFail(-1, "highestCpuUsage must <= 1"); + } + entity.setHighestCpuUsage(highestCpuUsage); + } + if (avgRt != null) { + if (avgRt < 0) { + return Result.ofFail(-1, "avgRt must >= 0"); + } + entity.setAvgRt(avgRt); + } + if (maxThread != null) { + if (maxThread < 0) { + return Result.ofFail(-1, "maxThread must >= 0"); + } + entity.setMaxThread(maxThread); + } + if (qps != null) { + if (qps < 0) { + return Result.ofFail(-1, "qps must >= 0"); + } + entity.setQps(qps); + } + Date date = new Date(); + entity.setGmtModified(date); + try { + entity = repository.save(entity); + } + catch (Throwable throwable) { + logger.error("save error:", throwable); + return Result.ofThrowable(-1, throwable); + } + if (!publishRules(entity.getApp(), entity.getIp(), entity.getPort())) { + logger.info("publish system rules fail after rule update"); + } + return Result.ofSuccess(entity); + } + + @RequestMapping("/delete.json") + @AuthAction(PrivilegeType.DELETE_RULE) + public Result delete(Long id) { + if (id == null) { + return Result.ofFail(-1, "id can't be null"); + } + SystemRuleEntity oldEntity = repository.findById(id); + if (oldEntity == null) { + return Result.ofSuccess(null); + } + try { + repository.delete(id); + } + catch (Throwable throwable) { + logger.error("delete error:", throwable); + return Result.ofThrowable(-1, throwable); + } + if (!publishRules(oldEntity.getApp(), oldEntity.getIp(), oldEntity.getPort())) { + logger.info("publish system rules fail after rule delete"); + } + return Result.ofSuccess(id); + } + + private boolean publishRules(String app, String ip, Integer port) { + List rules = repository.findAllByMachine(MachineInfo.of(app, ip, port)); + return sentinelApiClient.setSystemRuleOfMachine(app, ip, port, rules); + } - private boolean publishRules(String app, String ip, Integer port) { - List rules = repository.findAllByMachine(MachineInfo.of(app, ip, port)); - return sentinelApiClient.setSystemRuleOfMachine(app, ip, port, rules); - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/VersionController.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/VersionController.java index 69d66ea13..892a9eeb1 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/VersionController.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/VersionController.java @@ -29,21 +29,23 @@ import org.springframework.web.bind.annotation.RestController; @RestController public class VersionController { - private static final String VERSION_PATTERN = "-"; + private static final String VERSION_PATTERN = "-"; - @Value("${sentinel.dashboard.version:}") - private String sentinelDashboardVersion; + @Value("${sentinel.dashboard.version:}") + private String sentinelDashboardVersion; + + @GetMapping("/version") + public Result apiGetVersion() { + if (StringUtil.isNotBlank(sentinelDashboardVersion)) { + String res = sentinelDashboardVersion; + if (sentinelDashboardVersion.contains(VERSION_PATTERN)) { + res = sentinelDashboardVersion.substring(0, sentinelDashboardVersion.indexOf(VERSION_PATTERN)); + } + return Result.ofSuccess(res); + } + else { + return Result.ofFail(1, "getVersion failed: empty version"); + } + } - @GetMapping("/version") - public Result apiGetVersion() { - if (StringUtil.isNotBlank(sentinelDashboardVersion)) { - String res = sentinelDashboardVersion; - if (sentinelDashboardVersion.contains(VERSION_PATTERN)) { - res = sentinelDashboardVersion.substring(0, sentinelDashboardVersion.indexOf(VERSION_PATTERN)); - } - return Result.ofSuccess(res); - } else { - return Result.ofFail(1, "getVersion failed: empty version"); - } - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/cluster/ClusterAssignController.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/cluster/ClusterAssignController.java index dc2e14f5b..6b43aa04f 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/cluster/ClusterAssignController.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/cluster/ClusterAssignController.java @@ -42,63 +42,66 @@ import org.springframework.web.bind.annotation.RestController; @RequestMapping("/cluster/assign") public class ClusterAssignController { - private final Logger logger = LoggerFactory.getLogger(ClusterAssignController.class); + private final Logger logger = LoggerFactory.getLogger(ClusterAssignController.class); - @Autowired - private ClusterAssignService clusterAssignService; + @Autowired + private ClusterAssignService clusterAssignService; - @PostMapping("/all_server/{app}") - public Result apiAssignAllClusterServersOfApp(@PathVariable String app, - @RequestBody - ClusterAppFullAssignRequest assignRequest) { - if (StringUtil.isEmpty(app)) { - return Result.ofFail(-1, "app cannot be null or empty"); - } - if (assignRequest == null || assignRequest.getClusterMap() == null - || assignRequest.getRemainingList() == null) { - return Result.ofFail(-1, "bad request body"); - } - try { - return Result.ofSuccess(clusterAssignService.applyAssignToApp(app, assignRequest.getClusterMap(), - assignRequest.getRemainingList())); - } catch (Throwable throwable) { - logger.error("Error when assigning full cluster servers for app: " + app, throwable); - return Result.ofFail(-1, throwable.getMessage()); - } - } + @PostMapping("/all_server/{app}") + public Result apiAssignAllClusterServersOfApp(@PathVariable String app, + @RequestBody ClusterAppFullAssignRequest assignRequest) { + if (StringUtil.isEmpty(app)) { + return Result.ofFail(-1, "app cannot be null or empty"); + } + if (assignRequest == null || assignRequest.getClusterMap() == null + || assignRequest.getRemainingList() == null) { + return Result.ofFail(-1, "bad request body"); + } + try { + return Result.ofSuccess(clusterAssignService.applyAssignToApp(app, assignRequest.getClusterMap(), + assignRequest.getRemainingList())); + } + catch (Throwable throwable) { + logger.error("Error when assigning full cluster servers for app: " + app, throwable); + return Result.ofFail(-1, throwable.getMessage()); + } + } - @PostMapping("/single_server/{app}") - public Result apiAssignSingleClusterServersOfApp(@PathVariable String app, - @RequestBody ClusterAppSingleServerAssignRequest assignRequest) { - if (StringUtil.isEmpty(app)) { - return Result.ofFail(-1, "app cannot be null or empty"); - } - if (assignRequest == null || assignRequest.getClusterMap() == null) { - return Result.ofFail(-1, "bad request body"); - } - try { - return Result.ofSuccess(clusterAssignService.applyAssignToApp(app, Collections.singletonList(assignRequest.getClusterMap()), - assignRequest.getRemainingList())); - } catch (Throwable throwable) { - logger.error("Error when assigning single cluster servers for app: " + app, throwable); - return Result.ofFail(-1, throwable.getMessage()); - } - } + @PostMapping("/single_server/{app}") + public Result apiAssignSingleClusterServersOfApp(@PathVariable String app, + @RequestBody ClusterAppSingleServerAssignRequest assignRequest) { + if (StringUtil.isEmpty(app)) { + return Result.ofFail(-1, "app cannot be null or empty"); + } + if (assignRequest == null || assignRequest.getClusterMap() == null) { + return Result.ofFail(-1, "bad request body"); + } + try { + return Result.ofSuccess(clusterAssignService.applyAssignToApp(app, + Collections.singletonList(assignRequest.getClusterMap()), assignRequest.getRemainingList())); + } + catch (Throwable throwable) { + logger.error("Error when assigning single cluster servers for app: " + app, throwable); + return Result.ofFail(-1, throwable.getMessage()); + } + } + + @PostMapping("/unbind_server/{app}") + public Result apiUnbindClusterServersOfApp(@PathVariable String app, + @RequestBody Set machineIds) { + if (StringUtil.isEmpty(app)) { + return Result.ofFail(-1, "app cannot be null or empty"); + } + if (machineIds == null || machineIds.isEmpty()) { + return Result.ofFail(-1, "bad request body"); + } + try { + return Result.ofSuccess(clusterAssignService.unbindClusterServers(app, machineIds)); + } + catch (Throwable throwable) { + logger.error("Error when unbinding cluster server {} for app <{}>", machineIds, app, throwable); + return Result.ofFail(-1, throwable.getMessage()); + } + } - @PostMapping("/unbind_server/{app}") - public Result apiUnbindClusterServersOfApp(@PathVariable String app, - @RequestBody Set machineIds) { - if (StringUtil.isEmpty(app)) { - return Result.ofFail(-1, "app cannot be null or empty"); - } - if (machineIds == null || machineIds.isEmpty()) { - return Result.ofFail(-1, "bad request body"); - } - try { - return Result.ofSuccess(clusterAssignService.unbindClusterServers(app, machineIds)); - } catch (Throwable throwable) { - logger.error("Error when unbinding cluster server {} for app <{}>", machineIds, app, throwable); - return Result.ofFail(-1, throwable.getMessage()); - } - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/cluster/ClusterConfigController.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/cluster/ClusterConfigController.java index e9b9aed0e..96b94963f 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/cluster/ClusterConfigController.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/cluster/ClusterConfigController.java @@ -57,189 +57,192 @@ import org.springframework.web.bind.annotation.RestController; @RequestMapping(value = "/cluster") public class ClusterConfigController { - private final Logger logger = LoggerFactory.getLogger(ClusterConfigController.class); + private final Logger logger = LoggerFactory.getLogger(ClusterConfigController.class); - private final SentinelVersion version140 = new SentinelVersion().setMajorVersion(1).setMinorVersion(4); + private final SentinelVersion version140 = new SentinelVersion().setMajorVersion(1).setMinorVersion(4); - @Autowired - private AppManagement appManagement; + @Autowired + private AppManagement appManagement; - @Autowired - private ClusterConfigService clusterConfigService; + @Autowired + private ClusterConfigService clusterConfigService; - @PostMapping("/config/modify_single") - public Result apiModifyClusterConfig(@RequestBody String payload) { - if (StringUtil.isBlank(payload)) { - return Result.ofFail(-1, "empty request body"); - } - try { - JSONObject body = JSON.parseObject(payload); - if (body.containsKey(KEY_MODE)) { - int mode = body.getInteger(KEY_MODE); - switch (mode) { - case ClusterStateManager.CLUSTER_CLIENT: - ClusterClientModifyRequest data = JSON.parseObject(payload, ClusterClientModifyRequest.class); - Result res = checkValidRequest(data); - if (res != null) { - return res; - } - clusterConfigService.modifyClusterClientConfig(data).get(); - return Result.ofSuccess(true); - case ClusterStateManager.CLUSTER_SERVER: - ClusterServerModifyRequest d = JSON.parseObject(payload, ClusterServerModifyRequest.class); - Result r = checkValidRequest(d); - if (r != null) { - return r; - } - // TODO: bad design here, should refactor! - clusterConfigService.modifyClusterServerConfig(d).get(); - return Result.ofSuccess(true); - default: - return Result.ofFail(-1, "invalid mode"); - } - } - return Result.ofFail(-1, "invalid parameter"); - } catch (ExecutionException ex) { - logger.error("Error when modifying cluster config", ex.getCause()); - return errorResponse(ex); - } catch (Throwable ex) { - logger.error("Error when modifying cluster config", ex); - return Result.ofFail(-1, ex.getMessage()); - } - } + @PostMapping("/config/modify_single") + public Result apiModifyClusterConfig(@RequestBody String payload) { + if (StringUtil.isBlank(payload)) { + return Result.ofFail(-1, "empty request body"); + } + try { + JSONObject body = JSON.parseObject(payload); + if (body.containsKey(KEY_MODE)) { + int mode = body.getInteger(KEY_MODE); + switch (mode) { + case ClusterStateManager.CLUSTER_CLIENT: + ClusterClientModifyRequest data = JSON.parseObject(payload, ClusterClientModifyRequest.class); + Result res = checkValidRequest(data); + if (res != null) { + return res; + } + clusterConfigService.modifyClusterClientConfig(data).get(); + return Result.ofSuccess(true); + case ClusterStateManager.CLUSTER_SERVER: + ClusterServerModifyRequest d = JSON.parseObject(payload, ClusterServerModifyRequest.class); + Result r = checkValidRequest(d); + if (r != null) { + return r; + } + // TODO: bad design here, should refactor! + clusterConfigService.modifyClusterServerConfig(d).get(); + return Result.ofSuccess(true); + default: + return Result.ofFail(-1, "invalid mode"); + } + } + return Result.ofFail(-1, "invalid parameter"); + } + catch (ExecutionException ex) { + logger.error("Error when modifying cluster config", ex.getCause()); + return errorResponse(ex); + } + catch (Throwable ex) { + logger.error("Error when modifying cluster config", ex); + return Result.ofFail(-1, ex.getMessage()); + } + } - private Result errorResponse(ExecutionException ex) { - if (isNotSupported(ex.getCause())) { - return unsupportedVersion(); - } else { - return Result.ofThrowable(-1, ex.getCause()); - } - } + private Result errorResponse(ExecutionException ex) { + if (isNotSupported(ex.getCause())) { + return unsupportedVersion(); + } + else { + return Result.ofThrowable(-1, ex.getCause()); + } + } - @GetMapping("/state_single") - public Result apiGetClusterState(@RequestParam String app, - @RequestParam String ip, - @RequestParam Integer port) { - if (StringUtil.isEmpty(app)) { - return Result.ofFail(-1, "app cannot be null or empty"); - } - if (StringUtil.isEmpty(ip)) { - return Result.ofFail(-1, "ip cannot be null or empty"); - } - if (port == null || port <= 0) { - return Result.ofFail(-1, "Invalid parameter: port"); - } - if (!checkIfSupported(app, ip, port)) { - return unsupportedVersion(); - } - try { - return clusterConfigService.getClusterUniversalState(app, ip, port) - .thenApply(Result::ofSuccess) - .get(); - } catch (ExecutionException ex) { - logger.error("Error when fetching cluster state", ex.getCause()); - return errorResponse(ex); - } catch (Throwable throwable) { - logger.error("Error when fetching cluster state", throwable); - return Result.ofFail(-1, throwable.getMessage()); - } - } + @GetMapping("/state_single") + public Result apiGetClusterState(@RequestParam String app, @RequestParam String ip, + @RequestParam Integer port) { + if (StringUtil.isEmpty(app)) { + return Result.ofFail(-1, "app cannot be null or empty"); + } + if (StringUtil.isEmpty(ip)) { + return Result.ofFail(-1, "ip cannot be null or empty"); + } + if (port == null || port <= 0) { + return Result.ofFail(-1, "Invalid parameter: port"); + } + if (!checkIfSupported(app, ip, port)) { + return unsupportedVersion(); + } + try { + return clusterConfigService.getClusterUniversalState(app, ip, port).thenApply(Result::ofSuccess).get(); + } + catch (ExecutionException ex) { + logger.error("Error when fetching cluster state", ex.getCause()); + return errorResponse(ex); + } + catch (Throwable throwable) { + logger.error("Error when fetching cluster state", throwable); + return Result.ofFail(-1, throwable.getMessage()); + } + } - @GetMapping("/server_state/{app}") - public Result> apiGetClusterServerStateOfApp(@PathVariable String app) { - if (StringUtil.isEmpty(app)) { - return Result.ofFail(-1, "app cannot be null or empty"); - } - try { - return clusterConfigService.getClusterUniversalState(app) - .thenApply(ClusterEntityUtils::wrapToAppClusterServerState) - .thenApply(Result::ofSuccess) - .get(); - } catch (ExecutionException ex) { - logger.error("Error when fetching cluster server state of app: " + app, ex.getCause()); - return errorResponse(ex); - } catch (Throwable throwable) { - logger.error("Error when fetching cluster server state of app: " + app, throwable); - return Result.ofFail(-1, throwable.getMessage()); - } - } + @GetMapping("/server_state/{app}") + public Result> apiGetClusterServerStateOfApp(@PathVariable String app) { + if (StringUtil.isEmpty(app)) { + return Result.ofFail(-1, "app cannot be null or empty"); + } + try { + return clusterConfigService.getClusterUniversalState(app) + .thenApply(ClusterEntityUtils::wrapToAppClusterServerState).thenApply(Result::ofSuccess).get(); + } + catch (ExecutionException ex) { + logger.error("Error when fetching cluster server state of app: " + app, ex.getCause()); + return errorResponse(ex); + } + catch (Throwable throwable) { + logger.error("Error when fetching cluster server state of app: " + app, throwable); + return Result.ofFail(-1, throwable.getMessage()); + } + } - @GetMapping("/client_state/{app}") - public Result> apiGetClusterClientStateOfApp(@PathVariable String app) { - if (StringUtil.isEmpty(app)) { - return Result.ofFail(-1, "app cannot be null or empty"); - } - try { - return clusterConfigService.getClusterUniversalState(app) - .thenApply(ClusterEntityUtils::wrapToAppClusterClientState) - .thenApply(Result::ofSuccess) - .get(); - } catch (ExecutionException ex) { - logger.error("Error when fetching cluster token client state of app: " + app, ex.getCause()); - return errorResponse(ex); - } catch (Throwable throwable) { - logger.error("Error when fetching cluster token client state of app: " + app, throwable); - return Result.ofFail(-1, throwable.getMessage()); - } - } + @GetMapping("/client_state/{app}") + public Result> apiGetClusterClientStateOfApp(@PathVariable String app) { + if (StringUtil.isEmpty(app)) { + return Result.ofFail(-1, "app cannot be null or empty"); + } + try { + return clusterConfigService.getClusterUniversalState(app) + .thenApply(ClusterEntityUtils::wrapToAppClusterClientState).thenApply(Result::ofSuccess).get(); + } + catch (ExecutionException ex) { + logger.error("Error when fetching cluster token client state of app: " + app, ex.getCause()); + return errorResponse(ex); + } + catch (Throwable throwable) { + logger.error("Error when fetching cluster token client state of app: " + app, throwable); + return Result.ofFail(-1, throwable.getMessage()); + } + } - @GetMapping("/state/{app}") - public Result> apiGetClusterStateOfApp(@PathVariable String app) { - if (StringUtil.isEmpty(app)) { - return Result.ofFail(-1, "app cannot be null or empty"); - } - try { - return clusterConfigService.getClusterUniversalState(app) - .thenApply(Result::ofSuccess) - .get(); - } catch (ExecutionException ex) { - logger.error("Error when fetching cluster state of app: " + app, ex.getCause()); - return errorResponse(ex); - } catch (Throwable throwable) { - logger.error("Error when fetching cluster state of app: " + app, throwable); - return Result.ofFail(-1, throwable.getMessage()); - } - } + @GetMapping("/state/{app}") + public Result> apiGetClusterStateOfApp(@PathVariable String app) { + if (StringUtil.isEmpty(app)) { + return Result.ofFail(-1, "app cannot be null or empty"); + } + try { + return clusterConfigService.getClusterUniversalState(app).thenApply(Result::ofSuccess).get(); + } + catch (ExecutionException ex) { + logger.error("Error when fetching cluster state of app: " + app, ex.getCause()); + return errorResponse(ex); + } + catch (Throwable throwable) { + logger.error("Error when fetching cluster state of app: " + app, throwable); + return Result.ofFail(-1, throwable.getMessage()); + } + } - private boolean isNotSupported(Throwable ex) { - return ex instanceof CommandNotFoundException; - } + private boolean isNotSupported(Throwable ex) { + return ex instanceof CommandNotFoundException; + } - private boolean checkIfSupported(String app, String ip, int port) { - try { - return Optional.ofNullable(appManagement.getDetailApp(app)) - .flatMap(e -> e.getMachine(ip, port)) - .flatMap(m -> VersionUtils.parseVersion(m.getVersion()) - .map(v -> v.greaterOrEqual(version140))) - .orElse(true); - // If error occurred or cannot retrieve machine info, return true. - } catch (Exception ex) { - return true; - } - } + private boolean checkIfSupported(String app, String ip, int port) { + try { + return Optional.ofNullable(appManagement.getDetailApp(app)).flatMap(e -> e.getMachine(ip, port)) + .flatMap(m -> VersionUtils.parseVersion(m.getVersion()).map(v -> v.greaterOrEqual(version140))) + .orElse(true); + // If error occurred or cannot retrieve machine info, return true. + } + catch (Exception ex) { + return true; + } + } - private Result checkValidRequest(ClusterModifyRequest request) { - if (StringUtil.isEmpty(request.getApp())) { - return Result.ofFail(-1, "app cannot be empty"); - } - if (StringUtil.isEmpty(request.getIp())) { - return Result.ofFail(-1, "ip cannot be empty"); - } - if (request.getPort() == null || request.getPort() < 0) { - return Result.ofFail(-1, "invalid port"); - } - if (request.getMode() == null || request.getMode() < 0) { - return Result.ofFail(-1, "invalid mode"); - } - if (!checkIfSupported(request.getApp(), request.getIp(), request.getPort())) { - return unsupportedVersion(); - } - return null; - } + private Result checkValidRequest(ClusterModifyRequest request) { + if (StringUtil.isEmpty(request.getApp())) { + return Result.ofFail(-1, "app cannot be empty"); + } + if (StringUtil.isEmpty(request.getIp())) { + return Result.ofFail(-1, "ip cannot be empty"); + } + if (request.getPort() == null || request.getPort() < 0) { + return Result.ofFail(-1, "invalid port"); + } + if (request.getMode() == null || request.getMode() < 0) { + return Result.ofFail(-1, "invalid mode"); + } + if (!checkIfSupported(request.getApp(), request.getIp(), request.getPort())) { + return unsupportedVersion(); + } + return null; + } - private Result unsupportedVersion() { - return Result.ofFail(4041, "Sentinel client not supported for cluster flow control (unsupported version or dependency absent)"); - } + private Result unsupportedVersion() { + return Result.ofFail(4041, + "Sentinel client not supported for cluster flow control (unsupported version or dependency absent)"); + } + + private static final String KEY_MODE = "mode"; - private static final String KEY_MODE = "mode"; } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/gateway/GatewayApiController.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/gateway/GatewayApiController.java index c7a405d9c..32e188827 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/gateway/GatewayApiController.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/gateway/GatewayApiController.java @@ -48,213 +48,220 @@ import static com.alibaba.csp.sentinel.adapter.gateway.common.SentinelGatewayCon @RequestMapping(value = "/gateway/api") public class GatewayApiController { - private final Logger logger = LoggerFactory.getLogger(GatewayApiController.class); + private final Logger logger = LoggerFactory.getLogger(GatewayApiController.class); - @Autowired - private InMemApiDefinitionStore repository; + @Autowired + private InMemApiDefinitionStore repository; - @Autowired - private SentinelApiClient sentinelApiClient; + @Autowired + private SentinelApiClient sentinelApiClient; - @GetMapping("/list.json") - @AuthAction(AuthService.PrivilegeType.READ_RULE) - public Result> queryApis(String app, String ip, Integer port) { + @GetMapping("/list.json") + @AuthAction(AuthService.PrivilegeType.READ_RULE) + public Result> queryApis(String app, String ip, Integer port) { - if (StringUtil.isEmpty(app)) { - return Result.ofFail(-1, "app can't be null or empty"); - } - if (StringUtil.isEmpty(ip)) { - return Result.ofFail(-1, "ip can't be null or empty"); - } - if (port == null) { - return Result.ofFail(-1, "port can't be null"); - } + if (StringUtil.isEmpty(app)) { + return Result.ofFail(-1, "app can't be null or empty"); + } + if (StringUtil.isEmpty(ip)) { + return Result.ofFail(-1, "ip can't be null or empty"); + } + if (port == null) { + return Result.ofFail(-1, "port can't be null"); + } - try { - List apis = sentinelApiClient.fetchApis(app, ip, port).get(); - repository.saveAll(apis); - return Result.ofSuccess(apis); - } catch (Throwable throwable) { - logger.error("queryApis error:", throwable); - return Result.ofThrowable(-1, throwable); - } - } + try { + List apis = sentinelApiClient.fetchApis(app, ip, port).get(); + repository.saveAll(apis); + return Result.ofSuccess(apis); + } + catch (Throwable throwable) { + logger.error("queryApis error:", throwable); + return Result.ofThrowable(-1, throwable); + } + } - @PostMapping("/new.json") - @AuthAction(AuthService.PrivilegeType.WRITE_RULE) - public Result addApi(HttpServletRequest request, @RequestBody AddApiReqVo reqVo) { + @PostMapping("/new.json") + @AuthAction(AuthService.PrivilegeType.WRITE_RULE) + public Result addApi(HttpServletRequest request, @RequestBody AddApiReqVo reqVo) { - String app = reqVo.getApp(); - if (StringUtil.isBlank(app)) { - return Result.ofFail(-1, "app can't be null or empty"); - } + String app = reqVo.getApp(); + if (StringUtil.isBlank(app)) { + return Result.ofFail(-1, "app can't be null or empty"); + } - ApiDefinitionEntity entity = new ApiDefinitionEntity(); - entity.setApp(app.trim()); + ApiDefinitionEntity entity = new ApiDefinitionEntity(); + entity.setApp(app.trim()); - String ip = reqVo.getIp(); - if (StringUtil.isBlank(ip)) { - return Result.ofFail(-1, "ip can't be null or empty"); - } - entity.setIp(ip.trim()); + String ip = reqVo.getIp(); + if (StringUtil.isBlank(ip)) { + return Result.ofFail(-1, "ip can't be null or empty"); + } + entity.setIp(ip.trim()); - Integer port = reqVo.getPort(); - if (port == null) { - return Result.ofFail(-1, "port can't be null"); - } - entity.setPort(port); + Integer port = reqVo.getPort(); + if (port == null) { + return Result.ofFail(-1, "port can't be null"); + } + entity.setPort(port); - // API名称 - String apiName = reqVo.getApiName(); - if (StringUtil.isBlank(apiName)) { - return Result.ofFail(-1, "apiName can't be null or empty"); - } - entity.setApiName(apiName.trim()); + // API名称 + String apiName = reqVo.getApiName(); + if (StringUtil.isBlank(apiName)) { + return Result.ofFail(-1, "apiName can't be null or empty"); + } + entity.setApiName(apiName.trim()); - // 匹配规则列表 - List predicateItems = reqVo.getPredicateItems(); - if (CollectionUtils.isEmpty(predicateItems)) { - return Result.ofFail(-1, "predicateItems can't empty"); - } + // 匹配规则列表 + List predicateItems = reqVo.getPredicateItems(); + if (CollectionUtils.isEmpty(predicateItems)) { + return Result.ofFail(-1, "predicateItems can't empty"); + } - List predicateItemEntities = new ArrayList<>(); - for (ApiPredicateItemVo predicateItem : predicateItems) { - ApiPredicateItemEntity predicateItemEntity = new ApiPredicateItemEntity(); + List predicateItemEntities = new ArrayList<>(); + for (ApiPredicateItemVo predicateItem : predicateItems) { + ApiPredicateItemEntity predicateItemEntity = new ApiPredicateItemEntity(); - // 匹配模式 - Integer matchStrategy = predicateItem.getMatchStrategy(); - if (!Arrays.asList(URL_MATCH_STRATEGY_EXACT, URL_MATCH_STRATEGY_PREFIX, URL_MATCH_STRATEGY_REGEX).contains(matchStrategy)) { - return Result.ofFail(-1, "invalid matchStrategy: " + matchStrategy); - } - predicateItemEntity.setMatchStrategy(matchStrategy); + // 匹配模式 + Integer matchStrategy = predicateItem.getMatchStrategy(); + if (!Arrays.asList(URL_MATCH_STRATEGY_EXACT, URL_MATCH_STRATEGY_PREFIX, URL_MATCH_STRATEGY_REGEX) + .contains(matchStrategy)) { + return Result.ofFail(-1, "invalid matchStrategy: " + matchStrategy); + } + predicateItemEntity.setMatchStrategy(matchStrategy); - // 匹配串 - String pattern = predicateItem.getPattern(); - if (StringUtil.isBlank(pattern)) { - return Result.ofFail(-1, "pattern can't be null or empty"); - } - predicateItemEntity.setPattern(pattern); + // 匹配串 + String pattern = predicateItem.getPattern(); + if (StringUtil.isBlank(pattern)) { + return Result.ofFail(-1, "pattern can't be null or empty"); + } + predicateItemEntity.setPattern(pattern); - predicateItemEntities.add(predicateItemEntity); - } - entity.setPredicateItems(new LinkedHashSet<>(predicateItemEntities)); + predicateItemEntities.add(predicateItemEntity); + } + entity.setPredicateItems(new LinkedHashSet<>(predicateItemEntities)); - // 检查API名称不能重复 - List allApis = repository.findAllByMachine(MachineInfo.of(app.trim(), ip.trim(), port)); - if (allApis.stream().map(o -> o.getApiName()).anyMatch(o -> o.equals(apiName.trim()))) { - return Result.ofFail(-1, "apiName exists: " + apiName); - } + // 检查API名称不能重复 + List allApis = repository.findAllByMachine(MachineInfo.of(app.trim(), ip.trim(), port)); + if (allApis.stream().map(o -> o.getApiName()).anyMatch(o -> o.equals(apiName.trim()))) { + return Result.ofFail(-1, "apiName exists: " + apiName); + } - Date date = new Date(); - entity.setGmtCreate(date); - entity.setGmtModified(date); + Date date = new Date(); + entity.setGmtCreate(date); + entity.setGmtModified(date); - try { - entity = repository.save(entity); - } catch (Throwable throwable) { - logger.error("add gateway api error:", throwable); - return Result.ofThrowable(-1, throwable); - } + try { + entity = repository.save(entity); + } + catch (Throwable throwable) { + logger.error("add gateway api error:", throwable); + return Result.ofThrowable(-1, throwable); + } - if (!publishApis(app, ip, port)) { - logger.warn("publish gateway apis fail after add"); - } + if (!publishApis(app, ip, port)) { + logger.warn("publish gateway apis fail after add"); + } - return Result.ofSuccess(entity); - } + return Result.ofSuccess(entity); + } - @PostMapping("/save.json") - @AuthAction(AuthService.PrivilegeType.WRITE_RULE) - public Result updateApi(@RequestBody UpdateApiReqVo reqVo) { - String app = reqVo.getApp(); - if (StringUtil.isBlank(app)) { - return Result.ofFail(-1, "app can't be null or empty"); - } + @PostMapping("/save.json") + @AuthAction(AuthService.PrivilegeType.WRITE_RULE) + public Result updateApi(@RequestBody UpdateApiReqVo reqVo) { + String app = reqVo.getApp(); + if (StringUtil.isBlank(app)) { + return Result.ofFail(-1, "app can't be null or empty"); + } - Long id = reqVo.getId(); - if (id == null) { - return Result.ofFail(-1, "id can't be null"); - } + Long id = reqVo.getId(); + if (id == null) { + return Result.ofFail(-1, "id can't be null"); + } - ApiDefinitionEntity entity = repository.findById(id); - if (entity == null) { - return Result.ofFail(-1, "api does not exist, id=" + id); - } + ApiDefinitionEntity entity = repository.findById(id); + if (entity == null) { + return Result.ofFail(-1, "api does not exist, id=" + id); + } - // 匹配规则列表 - List predicateItems = reqVo.getPredicateItems(); - if (CollectionUtils.isEmpty(predicateItems)) { - return Result.ofFail(-1, "predicateItems can't empty"); - } + // 匹配规则列表 + List predicateItems = reqVo.getPredicateItems(); + if (CollectionUtils.isEmpty(predicateItems)) { + return Result.ofFail(-1, "predicateItems can't empty"); + } - List predicateItemEntities = new ArrayList<>(); - for (ApiPredicateItemVo predicateItem : predicateItems) { - ApiPredicateItemEntity predicateItemEntity = new ApiPredicateItemEntity(); + List predicateItemEntities = new ArrayList<>(); + for (ApiPredicateItemVo predicateItem : predicateItems) { + ApiPredicateItemEntity predicateItemEntity = new ApiPredicateItemEntity(); - // 匹配模式 - int matchStrategy = predicateItem.getMatchStrategy(); - if (!Arrays.asList(URL_MATCH_STRATEGY_EXACT, URL_MATCH_STRATEGY_PREFIX, URL_MATCH_STRATEGY_REGEX).contains(matchStrategy)) { - return Result.ofFail(-1, "Invalid matchStrategy: " + matchStrategy); - } - predicateItemEntity.setMatchStrategy(matchStrategy); + // 匹配模式 + int matchStrategy = predicateItem.getMatchStrategy(); + if (!Arrays.asList(URL_MATCH_STRATEGY_EXACT, URL_MATCH_STRATEGY_PREFIX, URL_MATCH_STRATEGY_REGEX) + .contains(matchStrategy)) { + return Result.ofFail(-1, "Invalid matchStrategy: " + matchStrategy); + } + predicateItemEntity.setMatchStrategy(matchStrategy); - // 匹配串 - String pattern = predicateItem.getPattern(); - if (StringUtil.isBlank(pattern)) { - return Result.ofFail(-1, "pattern can't be null or empty"); - } - predicateItemEntity.setPattern(pattern); + // 匹配串 + String pattern = predicateItem.getPattern(); + if (StringUtil.isBlank(pattern)) { + return Result.ofFail(-1, "pattern can't be null or empty"); + } + predicateItemEntity.setPattern(pattern); - predicateItemEntities.add(predicateItemEntity); - } - entity.setPredicateItems(new LinkedHashSet<>(predicateItemEntities)); + predicateItemEntities.add(predicateItemEntity); + } + entity.setPredicateItems(new LinkedHashSet<>(predicateItemEntities)); - Date date = new Date(); - entity.setGmtModified(date); + Date date = new Date(); + entity.setGmtModified(date); - try { - entity = repository.save(entity); - } catch (Throwable throwable) { - logger.error("update gateway api error:", throwable); - return Result.ofThrowable(-1, throwable); - } + try { + entity = repository.save(entity); + } + catch (Throwable throwable) { + logger.error("update gateway api error:", throwable); + return Result.ofThrowable(-1, throwable); + } - if (!publishApis(app, entity.getIp(), entity.getPort())) { - logger.warn("publish gateway apis fail after update"); - } + if (!publishApis(app, entity.getIp(), entity.getPort())) { + logger.warn("publish gateway apis fail after update"); + } - return Result.ofSuccess(entity); - } + return Result.ofSuccess(entity); + } - @PostMapping("/delete.json") - @AuthAction(AuthService.PrivilegeType.DELETE_RULE) + @PostMapping("/delete.json") + @AuthAction(AuthService.PrivilegeType.DELETE_RULE) - public Result deleteApi(Long id) { - if (id == null) { - return Result.ofFail(-1, "id can't be null"); - } + public Result deleteApi(Long id) { + if (id == null) { + return Result.ofFail(-1, "id can't be null"); + } - ApiDefinitionEntity oldEntity = repository.findById(id); - if (oldEntity == null) { - return Result.ofSuccess(null); - } + ApiDefinitionEntity oldEntity = repository.findById(id); + if (oldEntity == null) { + return Result.ofSuccess(null); + } - try { - repository.delete(id); - } catch (Throwable throwable) { - logger.error("delete gateway api error:", throwable); - return Result.ofThrowable(-1, throwable); - } + try { + repository.delete(id); + } + catch (Throwable throwable) { + logger.error("delete gateway api error:", throwable); + return Result.ofThrowable(-1, throwable); + } - if (!publishApis(oldEntity.getApp(), oldEntity.getIp(), oldEntity.getPort())) { - logger.warn("publish gateway apis fail after delete"); - } + if (!publishApis(oldEntity.getApp(), oldEntity.getIp(), oldEntity.getPort())) { + logger.warn("publish gateway apis fail after delete"); + } - return Result.ofSuccess(id); - } + return Result.ofSuccess(id); + } + + private boolean publishApis(String app, String ip, Integer port) { + List apis = repository.findAllByMachine(MachineInfo.of(app, ip, port)); + return sentinelApiClient.modifyApis(app, ip, port, apis); + } - private boolean publishApis(String app, String ip, Integer port) { - List apis = repository.findAllByMachine(MachineInfo.of(app, ip, port)); - return sentinelApiClient.modifyApis(app, ip, port, apis); - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/gateway/GatewayFlowRuleController.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/gateway/GatewayFlowRuleController.java index 018916378..697dcd1b0 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/gateway/GatewayFlowRuleController.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/gateway/GatewayFlowRuleController.java @@ -15,7 +15,6 @@ */ package com.alibaba.csp.sentinel.dashboard.controller.gateway; - import com.alibaba.csp.sentinel.dashboard.auth.AuthAction; import com.alibaba.csp.sentinel.dashboard.auth.AuthService; import com.alibaba.csp.sentinel.dashboard.client.SentinelApiClient; @@ -51,383 +50,396 @@ import static com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.Gatew @RequestMapping(value = "/gateway/flow") public class GatewayFlowRuleController { - private final Logger logger = LoggerFactory.getLogger(GatewayFlowRuleController.class); + private final Logger logger = LoggerFactory.getLogger(GatewayFlowRuleController.class); - @Autowired - private InMemGatewayFlowRuleStore repository; + @Autowired + private InMemGatewayFlowRuleStore repository; - @Autowired - private SentinelApiClient sentinelApiClient; + @Autowired + private SentinelApiClient sentinelApiClient; - @GetMapping("/list.json") - @AuthAction(AuthService.PrivilegeType.READ_RULE) - public Result> queryFlowRules(String app, String ip, Integer port) { + @GetMapping("/list.json") + @AuthAction(AuthService.PrivilegeType.READ_RULE) + public Result> queryFlowRules(String app, String ip, Integer port) { - if (StringUtil.isEmpty(app)) { - return Result.ofFail(-1, "app can't be null or empty"); - } - if (StringUtil.isEmpty(ip)) { - return Result.ofFail(-1, "ip can't be null or empty"); - } - if (port == null) { - return Result.ofFail(-1, "port can't be null"); - } + if (StringUtil.isEmpty(app)) { + return Result.ofFail(-1, "app can't be null or empty"); + } + if (StringUtil.isEmpty(ip)) { + return Result.ofFail(-1, "ip can't be null or empty"); + } + if (port == null) { + return Result.ofFail(-1, "port can't be null"); + } - try { - List rules = sentinelApiClient.fetchGatewayFlowRules(app, ip, port).get(); - repository.saveAll(rules); - return Result.ofSuccess(rules); - } catch (Throwable throwable) { - logger.error("query gateway flow rules error:", throwable); - return Result.ofThrowable(-1, throwable); - } - } + try { + List rules = sentinelApiClient.fetchGatewayFlowRules(app, ip, port).get(); + repository.saveAll(rules); + return Result.ofSuccess(rules); + } + catch (Throwable throwable) { + logger.error("query gateway flow rules error:", throwable); + return Result.ofThrowable(-1, throwable); + } + } - @PostMapping("/new.json") - @AuthAction(AuthService.PrivilegeType.WRITE_RULE) - public Result addFlowRule(@RequestBody AddFlowRuleReqVo reqVo) { + @PostMapping("/new.json") + @AuthAction(AuthService.PrivilegeType.WRITE_RULE) + public Result addFlowRule(@RequestBody AddFlowRuleReqVo reqVo) { - String app = reqVo.getApp(); - if (StringUtil.isBlank(app)) { - return Result.ofFail(-1, "app can't be null or empty"); - } + String app = reqVo.getApp(); + if (StringUtil.isBlank(app)) { + return Result.ofFail(-1, "app can't be null or empty"); + } - GatewayFlowRuleEntity entity = new GatewayFlowRuleEntity(); - entity.setApp(app.trim()); + GatewayFlowRuleEntity entity = new GatewayFlowRuleEntity(); + entity.setApp(app.trim()); - String ip = reqVo.getIp(); - if (StringUtil.isBlank(ip)) { - return Result.ofFail(-1, "ip can't be null or empty"); - } - entity.setIp(ip.trim()); + String ip = reqVo.getIp(); + if (StringUtil.isBlank(ip)) { + return Result.ofFail(-1, "ip can't be null or empty"); + } + entity.setIp(ip.trim()); - Integer port = reqVo.getPort(); - if (port == null) { - return Result.ofFail(-1, "port can't be null"); - } - entity.setPort(port); + Integer port = reqVo.getPort(); + if (port == null) { + return Result.ofFail(-1, "port can't be null"); + } + entity.setPort(port); - // API类型, Route ID或API分组 - Integer resourceMode = reqVo.getResourceMode(); - if (resourceMode == null) { - return Result.ofFail(-1, "resourceMode can't be null"); - } - if (!Arrays.asList(RESOURCE_MODE_ROUTE_ID, RESOURCE_MODE_CUSTOM_API_NAME).contains(resourceMode)) { - return Result.ofFail(-1, "invalid resourceMode: " + resourceMode); - } - entity.setResourceMode(resourceMode); + // API类型, Route ID或API分组 + Integer resourceMode = reqVo.getResourceMode(); + if (resourceMode == null) { + return Result.ofFail(-1, "resourceMode can't be null"); + } + if (!Arrays.asList(RESOURCE_MODE_ROUTE_ID, RESOURCE_MODE_CUSTOM_API_NAME).contains(resourceMode)) { + return Result.ofFail(-1, "invalid resourceMode: " + resourceMode); + } + entity.setResourceMode(resourceMode); - // API名称 - String resource = reqVo.getResource(); - if (StringUtil.isBlank(resource)) { - return Result.ofFail(-1, "resource can't be null or empty"); - } - entity.setResource(resource.trim()); + // API名称 + String resource = reqVo.getResource(); + if (StringUtil.isBlank(resource)) { + return Result.ofFail(-1, "resource can't be null or empty"); + } + entity.setResource(resource.trim()); - // 针对请求属性 - GatewayParamFlowItemVo paramItem = reqVo.getParamItem(); - if (paramItem != null) { - GatewayParamFlowItemEntity itemEntity = new GatewayParamFlowItemEntity(); - entity.setParamItem(itemEntity); + // 针对请求属性 + GatewayParamFlowItemVo paramItem = reqVo.getParamItem(); + if (paramItem != null) { + GatewayParamFlowItemEntity itemEntity = new GatewayParamFlowItemEntity(); + entity.setParamItem(itemEntity); - // 参数属性 0-ClientIP 1-Remote Host 2-Header 3-URL参数 4-Cookie - Integer parseStrategy = paramItem.getParseStrategy(); - if (!Arrays.asList(PARAM_PARSE_STRATEGY_CLIENT_IP, PARAM_PARSE_STRATEGY_HOST, PARAM_PARSE_STRATEGY_HEADER - , PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) { - return Result.ofFail(-1, "invalid parseStrategy: " + parseStrategy); - } - itemEntity.setParseStrategy(paramItem.getParseStrategy()); + // 参数属性 0-ClientIP 1-Remote Host 2-Header 3-URL参数 4-Cookie + Integer parseStrategy = paramItem.getParseStrategy(); + if (!Arrays.asList(PARAM_PARSE_STRATEGY_CLIENT_IP, PARAM_PARSE_STRATEGY_HOST, PARAM_PARSE_STRATEGY_HEADER, + PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) { + return Result.ofFail(-1, "invalid parseStrategy: " + parseStrategy); + } + itemEntity.setParseStrategy(paramItem.getParseStrategy()); - // 当参数属性为2-Header 3-URL参数 4-Cookie时,参数名称必填 - if (Arrays.asList(PARAM_PARSE_STRATEGY_HEADER, PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) { - // 参数名称 - String fieldName = paramItem.getFieldName(); - if (StringUtil.isBlank(fieldName)) { - return Result.ofFail(-1, "fieldName can't be null or empty"); - } - itemEntity.setFieldName(paramItem.getFieldName()); + // 当参数属性为2-Header 3-URL参数 4-Cookie时,参数名称必填 + if (Arrays.asList(PARAM_PARSE_STRATEGY_HEADER, PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE) + .contains(parseStrategy)) { + // 参数名称 + String fieldName = paramItem.getFieldName(); + if (StringUtil.isBlank(fieldName)) { + return Result.ofFail(-1, "fieldName can't be null or empty"); + } + itemEntity.setFieldName(paramItem.getFieldName()); - String pattern = paramItem.getPattern(); - // 如果匹配串不为空,验证匹配模式 - if (StringUtil.isNotEmpty(pattern)) { - itemEntity.setPattern(pattern); + String pattern = paramItem.getPattern(); + // 如果匹配串不为空,验证匹配模式 + if (StringUtil.isNotEmpty(pattern)) { + itemEntity.setPattern(pattern); - Integer matchStrategy = paramItem.getMatchStrategy(); - if (!Arrays.asList(PARAM_MATCH_STRATEGY_EXACT, PARAM_MATCH_STRATEGY_CONTAINS, PARAM_MATCH_STRATEGY_REGEX).contains(matchStrategy)) { - return Result.ofFail(-1, "invalid matchStrategy: " + matchStrategy); - } - itemEntity.setMatchStrategy(matchStrategy); - } - } - } + Integer matchStrategy = paramItem.getMatchStrategy(); + if (!Arrays.asList(PARAM_MATCH_STRATEGY_EXACT, PARAM_MATCH_STRATEGY_CONTAINS, + PARAM_MATCH_STRATEGY_REGEX).contains(matchStrategy)) { + return Result.ofFail(-1, "invalid matchStrategy: " + matchStrategy); + } + itemEntity.setMatchStrategy(matchStrategy); + } + } + } - // 阈值类型 0-线程数 1-QPS - Integer grade = reqVo.getGrade(); - if (grade == null) { - return Result.ofFail(-1, "grade can't be null"); - } - if (!Arrays.asList(FLOW_GRADE_THREAD, FLOW_GRADE_QPS).contains(grade)) { - return Result.ofFail(-1, "invalid grade: " + grade); - } - entity.setGrade(grade); + // 阈值类型 0-线程数 1-QPS + Integer grade = reqVo.getGrade(); + if (grade == null) { + return Result.ofFail(-1, "grade can't be null"); + } + if (!Arrays.asList(FLOW_GRADE_THREAD, FLOW_GRADE_QPS).contains(grade)) { + return Result.ofFail(-1, "invalid grade: " + grade); + } + entity.setGrade(grade); - // QPS阈值 - Double count = reqVo.getCount(); - if (count == null) { - return Result.ofFail(-1, "count can't be null"); - } - if (count < 0) { - return Result.ofFail(-1, "count should be at lease zero"); - } - entity.setCount(count); + // QPS阈值 + Double count = reqVo.getCount(); + if (count == null) { + return Result.ofFail(-1, "count can't be null"); + } + if (count < 0) { + return Result.ofFail(-1, "count should be at lease zero"); + } + entity.setCount(count); - // 间隔 - Long interval = reqVo.getInterval(); - if (interval == null) { - return Result.ofFail(-1, "interval can't be null"); - } - if (interval <= 0) { - return Result.ofFail(-1, "interval should be greater than zero"); - } - entity.setInterval(interval); + // 间隔 + Long interval = reqVo.getInterval(); + if (interval == null) { + return Result.ofFail(-1, "interval can't be null"); + } + if (interval <= 0) { + return Result.ofFail(-1, "interval should be greater than zero"); + } + entity.setInterval(interval); - // 间隔单位 - Integer intervalUnit = reqVo.getIntervalUnit(); - if (intervalUnit == null) { - return Result.ofFail(-1, "intervalUnit can't be null"); - } - if (!Arrays.asList(INTERVAL_UNIT_SECOND, INTERVAL_UNIT_MINUTE, INTERVAL_UNIT_HOUR, INTERVAL_UNIT_DAY).contains(intervalUnit)) { - return Result.ofFail(-1, "Invalid intervalUnit: " + intervalUnit); - } - entity.setIntervalUnit(intervalUnit); + // 间隔单位 + Integer intervalUnit = reqVo.getIntervalUnit(); + if (intervalUnit == null) { + return Result.ofFail(-1, "intervalUnit can't be null"); + } + if (!Arrays.asList(INTERVAL_UNIT_SECOND, INTERVAL_UNIT_MINUTE, INTERVAL_UNIT_HOUR, INTERVAL_UNIT_DAY) + .contains(intervalUnit)) { + return Result.ofFail(-1, "Invalid intervalUnit: " + intervalUnit); + } + entity.setIntervalUnit(intervalUnit); - // 流控方式 0-快速失败 2-匀速排队 - Integer controlBehavior = reqVo.getControlBehavior(); - if (controlBehavior == null) { - return Result.ofFail(-1, "controlBehavior can't be null"); - } - if (!Arrays.asList(CONTROL_BEHAVIOR_DEFAULT, CONTROL_BEHAVIOR_RATE_LIMITER).contains(controlBehavior)) { - return Result.ofFail(-1, "invalid controlBehavior: " + controlBehavior); - } - entity.setControlBehavior(controlBehavior); + // 流控方式 0-快速失败 2-匀速排队 + Integer controlBehavior = reqVo.getControlBehavior(); + if (controlBehavior == null) { + return Result.ofFail(-1, "controlBehavior can't be null"); + } + if (!Arrays.asList(CONTROL_BEHAVIOR_DEFAULT, CONTROL_BEHAVIOR_RATE_LIMITER).contains(controlBehavior)) { + return Result.ofFail(-1, "invalid controlBehavior: " + controlBehavior); + } + entity.setControlBehavior(controlBehavior); - if (CONTROL_BEHAVIOR_DEFAULT == controlBehavior) { - // 0-快速失败, 则Burst size必填 - Integer burst = reqVo.getBurst(); - if (burst == null) { - return Result.ofFail(-1, "burst can't be null"); - } - if (burst < 0) { - return Result.ofFail(-1, "invalid burst: " + burst); - } - entity.setBurst(burst); - } else if (CONTROL_BEHAVIOR_RATE_LIMITER == controlBehavior) { - // 1-匀速排队, 则超时时间必填 - Integer maxQueueingTimeoutMs = reqVo.getMaxQueueingTimeoutMs(); - if (maxQueueingTimeoutMs == null) { - return Result.ofFail(-1, "maxQueueingTimeoutMs can't be null"); - } - if (maxQueueingTimeoutMs < 0) { - return Result.ofFail(-1, "invalid maxQueueingTimeoutMs: " + maxQueueingTimeoutMs); - } - entity.setMaxQueueingTimeoutMs(maxQueueingTimeoutMs); - } + if (CONTROL_BEHAVIOR_DEFAULT == controlBehavior) { + // 0-快速失败, 则Burst size必填 + Integer burst = reqVo.getBurst(); + if (burst == null) { + return Result.ofFail(-1, "burst can't be null"); + } + if (burst < 0) { + return Result.ofFail(-1, "invalid burst: " + burst); + } + entity.setBurst(burst); + } + else if (CONTROL_BEHAVIOR_RATE_LIMITER == controlBehavior) { + // 1-匀速排队, 则超时时间必填 + Integer maxQueueingTimeoutMs = reqVo.getMaxQueueingTimeoutMs(); + if (maxQueueingTimeoutMs == null) { + return Result.ofFail(-1, "maxQueueingTimeoutMs can't be null"); + } + if (maxQueueingTimeoutMs < 0) { + return Result.ofFail(-1, "invalid maxQueueingTimeoutMs: " + maxQueueingTimeoutMs); + } + entity.setMaxQueueingTimeoutMs(maxQueueingTimeoutMs); + } - Date date = new Date(); - entity.setGmtCreate(date); - entity.setGmtModified(date); + Date date = new Date(); + entity.setGmtCreate(date); + entity.setGmtModified(date); - try { - entity = repository.save(entity); - } catch (Throwable throwable) { - logger.error("add gateway flow rule error:", throwable); - return Result.ofThrowable(-1, throwable); - } + try { + entity = repository.save(entity); + } + catch (Throwable throwable) { + logger.error("add gateway flow rule error:", throwable); + return Result.ofThrowable(-1, throwable); + } - if (!publishRules(app, ip, port)) { - logger.warn("publish gateway flow rules fail after add"); - } + if (!publishRules(app, ip, port)) { + logger.warn("publish gateway flow rules fail after add"); + } - return Result.ofSuccess(entity); - } + return Result.ofSuccess(entity); + } - @PostMapping("/save.json") - @AuthAction(AuthService.PrivilegeType.WRITE_RULE) - public Result updateFlowRule(@RequestBody UpdateFlowRuleReqVo reqVo) { + @PostMapping("/save.json") + @AuthAction(AuthService.PrivilegeType.WRITE_RULE) + public Result updateFlowRule(@RequestBody UpdateFlowRuleReqVo reqVo) { - String app = reqVo.getApp(); - if (StringUtil.isBlank(app)) { - return Result.ofFail(-1, "app can't be null or empty"); - } + String app = reqVo.getApp(); + if (StringUtil.isBlank(app)) { + return Result.ofFail(-1, "app can't be null or empty"); + } - Long id = reqVo.getId(); - if (id == null) { - return Result.ofFail(-1, "id can't be null"); - } + Long id = reqVo.getId(); + if (id == null) { + return Result.ofFail(-1, "id can't be null"); + } - GatewayFlowRuleEntity entity = repository.findById(id); - if (entity == null) { - return Result.ofFail(-1, "gateway flow rule does not exist, id=" + id); - } + GatewayFlowRuleEntity entity = repository.findById(id); + if (entity == null) { + return Result.ofFail(-1, "gateway flow rule does not exist, id=" + id); + } - // 针对请求属性 - GatewayParamFlowItemVo paramItem = reqVo.getParamItem(); - if (paramItem != null) { - GatewayParamFlowItemEntity itemEntity = new GatewayParamFlowItemEntity(); - entity.setParamItem(itemEntity); + // 针对请求属性 + GatewayParamFlowItemVo paramItem = reqVo.getParamItem(); + if (paramItem != null) { + GatewayParamFlowItemEntity itemEntity = new GatewayParamFlowItemEntity(); + entity.setParamItem(itemEntity); - // 参数属性 0-ClientIP 1-Remote Host 2-Header 3-URL参数 4-Cookie - Integer parseStrategy = paramItem.getParseStrategy(); - if (!Arrays.asList(PARAM_PARSE_STRATEGY_CLIENT_IP, PARAM_PARSE_STRATEGY_HOST, PARAM_PARSE_STRATEGY_HEADER - , PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) { - return Result.ofFail(-1, "invalid parseStrategy: " + parseStrategy); - } - itemEntity.setParseStrategy(paramItem.getParseStrategy()); + // 参数属性 0-ClientIP 1-Remote Host 2-Header 3-URL参数 4-Cookie + Integer parseStrategy = paramItem.getParseStrategy(); + if (!Arrays.asList(PARAM_PARSE_STRATEGY_CLIENT_IP, PARAM_PARSE_STRATEGY_HOST, PARAM_PARSE_STRATEGY_HEADER, + PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) { + return Result.ofFail(-1, "invalid parseStrategy: " + parseStrategy); + } + itemEntity.setParseStrategy(paramItem.getParseStrategy()); - // 当参数属性为2-Header 3-URL参数 4-Cookie时,参数名称必填 - if (Arrays.asList(PARAM_PARSE_STRATEGY_HEADER, PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) { - // 参数名称 - String fieldName = paramItem.getFieldName(); - if (StringUtil.isBlank(fieldName)) { - return Result.ofFail(-1, "fieldName can't be null or empty"); - } - itemEntity.setFieldName(paramItem.getFieldName()); + // 当参数属性为2-Header 3-URL参数 4-Cookie时,参数名称必填 + if (Arrays.asList(PARAM_PARSE_STRATEGY_HEADER, PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE) + .contains(parseStrategy)) { + // 参数名称 + String fieldName = paramItem.getFieldName(); + if (StringUtil.isBlank(fieldName)) { + return Result.ofFail(-1, "fieldName can't be null or empty"); + } + itemEntity.setFieldName(paramItem.getFieldName()); - String pattern = paramItem.getPattern(); - // 如果匹配串不为空,验证匹配模式 - if (StringUtil.isNotEmpty(pattern)) { - itemEntity.setPattern(pattern); + String pattern = paramItem.getPattern(); + // 如果匹配串不为空,验证匹配模式 + if (StringUtil.isNotEmpty(pattern)) { + itemEntity.setPattern(pattern); - Integer matchStrategy = paramItem.getMatchStrategy(); - if (!Arrays.asList(PARAM_MATCH_STRATEGY_EXACT, PARAM_MATCH_STRATEGY_CONTAINS, PARAM_MATCH_STRATEGY_REGEX).contains(matchStrategy)) { - return Result.ofFail(-1, "invalid matchStrategy: " + matchStrategy); - } - itemEntity.setMatchStrategy(matchStrategy); - } - } - } else { - entity.setParamItem(null); - } + Integer matchStrategy = paramItem.getMatchStrategy(); + if (!Arrays.asList(PARAM_MATCH_STRATEGY_EXACT, PARAM_MATCH_STRATEGY_CONTAINS, + PARAM_MATCH_STRATEGY_REGEX).contains(matchStrategy)) { + return Result.ofFail(-1, "invalid matchStrategy: " + matchStrategy); + } + itemEntity.setMatchStrategy(matchStrategy); + } + } + } + else { + entity.setParamItem(null); + } - // 阈值类型 0-线程数 1-QPS - Integer grade = reqVo.getGrade(); - if (grade == null) { - return Result.ofFail(-1, "grade can't be null"); - } - if (!Arrays.asList(FLOW_GRADE_THREAD, FLOW_GRADE_QPS).contains(grade)) { - return Result.ofFail(-1, "invalid grade: " + grade); - } - entity.setGrade(grade); + // 阈值类型 0-线程数 1-QPS + Integer grade = reqVo.getGrade(); + if (grade == null) { + return Result.ofFail(-1, "grade can't be null"); + } + if (!Arrays.asList(FLOW_GRADE_THREAD, FLOW_GRADE_QPS).contains(grade)) { + return Result.ofFail(-1, "invalid grade: " + grade); + } + entity.setGrade(grade); - // QPS阈值 - Double count = reqVo.getCount(); - if (count == null) { - return Result.ofFail(-1, "count can't be null"); - } - if (count < 0) { - return Result.ofFail(-1, "count should be at lease zero"); - } - entity.setCount(count); + // QPS阈值 + Double count = reqVo.getCount(); + if (count == null) { + return Result.ofFail(-1, "count can't be null"); + } + if (count < 0) { + return Result.ofFail(-1, "count should be at lease zero"); + } + entity.setCount(count); - // 间隔 - Long interval = reqVo.getInterval(); - if (interval == null) { - return Result.ofFail(-1, "interval can't be null"); - } - if (interval <= 0) { - return Result.ofFail(-1, "interval should be greater than zero"); - } - entity.setInterval(interval); + // 间隔 + Long interval = reqVo.getInterval(); + if (interval == null) { + return Result.ofFail(-1, "interval can't be null"); + } + if (interval <= 0) { + return Result.ofFail(-1, "interval should be greater than zero"); + } + entity.setInterval(interval); - // 间隔单位 - Integer intervalUnit = reqVo.getIntervalUnit(); - if (intervalUnit == null) { - return Result.ofFail(-1, "intervalUnit can't be null"); - } - if (!Arrays.asList(INTERVAL_UNIT_SECOND, INTERVAL_UNIT_MINUTE, INTERVAL_UNIT_HOUR, INTERVAL_UNIT_DAY).contains(intervalUnit)) { - return Result.ofFail(-1, "Invalid intervalUnit: " + intervalUnit); - } - entity.setIntervalUnit(intervalUnit); + // 间隔单位 + Integer intervalUnit = reqVo.getIntervalUnit(); + if (intervalUnit == null) { + return Result.ofFail(-1, "intervalUnit can't be null"); + } + if (!Arrays.asList(INTERVAL_UNIT_SECOND, INTERVAL_UNIT_MINUTE, INTERVAL_UNIT_HOUR, INTERVAL_UNIT_DAY) + .contains(intervalUnit)) { + return Result.ofFail(-1, "Invalid intervalUnit: " + intervalUnit); + } + entity.setIntervalUnit(intervalUnit); - // 流控方式 0-快速失败 2-匀速排队 - Integer controlBehavior = reqVo.getControlBehavior(); - if (controlBehavior == null) { - return Result.ofFail(-1, "controlBehavior can't be null"); - } - if (!Arrays.asList(CONTROL_BEHAVIOR_DEFAULT, CONTROL_BEHAVIOR_RATE_LIMITER).contains(controlBehavior)) { - return Result.ofFail(-1, "invalid controlBehavior: " + controlBehavior); - } - entity.setControlBehavior(controlBehavior); + // 流控方式 0-快速失败 2-匀速排队 + Integer controlBehavior = reqVo.getControlBehavior(); + if (controlBehavior == null) { + return Result.ofFail(-1, "controlBehavior can't be null"); + } + if (!Arrays.asList(CONTROL_BEHAVIOR_DEFAULT, CONTROL_BEHAVIOR_RATE_LIMITER).contains(controlBehavior)) { + return Result.ofFail(-1, "invalid controlBehavior: " + controlBehavior); + } + entity.setControlBehavior(controlBehavior); - if (CONTROL_BEHAVIOR_DEFAULT == controlBehavior) { - // 0-快速失败, 则Burst size必填 - Integer burst = reqVo.getBurst(); - if (burst == null) { - return Result.ofFail(-1, "burst can't be null"); - } - if (burst < 0) { - return Result.ofFail(-1, "invalid burst: " + burst); - } - entity.setBurst(burst); - } else if (CONTROL_BEHAVIOR_RATE_LIMITER == controlBehavior) { - // 2-匀速排队, 则超时时间必填 - Integer maxQueueingTimeoutMs = reqVo.getMaxQueueingTimeoutMs(); - if (maxQueueingTimeoutMs == null) { - return Result.ofFail(-1, "maxQueueingTimeoutMs can't be null"); - } - if (maxQueueingTimeoutMs < 0) { - return Result.ofFail(-1, "invalid maxQueueingTimeoutMs: " + maxQueueingTimeoutMs); - } - entity.setMaxQueueingTimeoutMs(maxQueueingTimeoutMs); - } + if (CONTROL_BEHAVIOR_DEFAULT == controlBehavior) { + // 0-快速失败, 则Burst size必填 + Integer burst = reqVo.getBurst(); + if (burst == null) { + return Result.ofFail(-1, "burst can't be null"); + } + if (burst < 0) { + return Result.ofFail(-1, "invalid burst: " + burst); + } + entity.setBurst(burst); + } + else if (CONTROL_BEHAVIOR_RATE_LIMITER == controlBehavior) { + // 2-匀速排队, 则超时时间必填 + Integer maxQueueingTimeoutMs = reqVo.getMaxQueueingTimeoutMs(); + if (maxQueueingTimeoutMs == null) { + return Result.ofFail(-1, "maxQueueingTimeoutMs can't be null"); + } + if (maxQueueingTimeoutMs < 0) { + return Result.ofFail(-1, "invalid maxQueueingTimeoutMs: " + maxQueueingTimeoutMs); + } + entity.setMaxQueueingTimeoutMs(maxQueueingTimeoutMs); + } - Date date = new Date(); - entity.setGmtModified(date); + Date date = new Date(); + entity.setGmtModified(date); - try { - entity = repository.save(entity); - } catch (Throwable throwable) { - logger.error("update gateway flow rule error:", throwable); - return Result.ofThrowable(-1, throwable); - } + try { + entity = repository.save(entity); + } + catch (Throwable throwable) { + logger.error("update gateway flow rule error:", throwable); + return Result.ofThrowable(-1, throwable); + } - if (!publishRules(app, entity.getIp(), entity.getPort())) { - logger.warn("publish gateway flow rules fail after update"); - } + if (!publishRules(app, entity.getIp(), entity.getPort())) { + logger.warn("publish gateway flow rules fail after update"); + } - return Result.ofSuccess(entity); - } + return Result.ofSuccess(entity); + } + @PostMapping("/delete.json") + @AuthAction(AuthService.PrivilegeType.DELETE_RULE) + public Result deleteFlowRule(Long id) { - @PostMapping("/delete.json") - @AuthAction(AuthService.PrivilegeType.DELETE_RULE) - public Result deleteFlowRule(Long id) { + if (id == null) { + return Result.ofFail(-1, "id can't be null"); + } - if (id == null) { - return Result.ofFail(-1, "id can't be null"); - } + GatewayFlowRuleEntity oldEntity = repository.findById(id); + if (oldEntity == null) { + return Result.ofSuccess(null); + } - GatewayFlowRuleEntity oldEntity = repository.findById(id); - if (oldEntity == null) { - return Result.ofSuccess(null); - } + try { + repository.delete(id); + } + catch (Throwable throwable) { + logger.error("delete gateway flow rule error:", throwable); + return Result.ofThrowable(-1, throwable); + } - try { - repository.delete(id); - } catch (Throwable throwable) { - logger.error("delete gateway flow rule error:", throwable); - return Result.ofThrowable(-1, throwable); - } + if (!publishRules(oldEntity.getApp(), oldEntity.getIp(), oldEntity.getPort())) { + logger.warn("publish gateway flow rules fail after delete"); + } - if (!publishRules(oldEntity.getApp(), oldEntity.getIp(), oldEntity.getPort())) { - logger.warn("publish gateway flow rules fail after delete"); - } + return Result.ofSuccess(id); + } - return Result.ofSuccess(id); - } + private boolean publishRules(String app, String ip, Integer port) { + List rules = repository.findAllByMachine(MachineInfo.of(app, ip, port)); + return sentinelApiClient.modifyGatewayFlowRules(app, ip, port, rules); + } - private boolean publishRules(String app, String ip, Integer port) { - List rules = repository.findAllByMachine(MachineInfo.of(app, ip, port)); - return sentinelApiClient.modifyGatewayFlowRules(app, ip, port, rules); - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/v2/FlowControllerV2.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/v2/FlowControllerV2.java index c79261cdf..6df626022 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/v2/FlowControllerV2.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/v2/FlowControllerV2.java @@ -53,174 +53,179 @@ import org.springframework.web.bind.annotation.RestController; @RequestMapping(value = "/v2/flow") public class FlowControllerV2 { - private final Logger logger = LoggerFactory.getLogger(FlowControllerV2.class); + private final Logger logger = LoggerFactory.getLogger(FlowControllerV2.class); - @Autowired - private InMemoryRuleRepositoryAdapter repository; + @Autowired + private InMemoryRuleRepositoryAdapter repository; - @Autowired - @Qualifier("flowRuleDefaultProvider") - private DynamicRuleProvider> ruleProvider; - @Autowired - @Qualifier("flowRuleDefaultPublisher") - private DynamicRulePublisher> rulePublisher; + @Autowired + @Qualifier("flowRuleDefaultProvider") + private DynamicRuleProvider> ruleProvider; - @GetMapping("/rules") - @AuthAction(PrivilegeType.READ_RULE) - public Result> apiQueryMachineRules(@RequestParam String app) { + @Autowired + @Qualifier("flowRuleDefaultPublisher") + private DynamicRulePublisher> rulePublisher; - if (StringUtil.isEmpty(app)) { - return Result.ofFail(-1, "app can't be null or empty"); - } - try { - List rules = ruleProvider.getRules(app); - if (rules != null && !rules.isEmpty()) { - for (FlowRuleEntity entity : rules) { - entity.setApp(app); - if (entity.getClusterConfig() != null && entity.getClusterConfig().getFlowId() != null) { - entity.setId(entity.getClusterConfig().getFlowId()); - } - } - } - rules = repository.saveAll(rules); - return Result.ofSuccess(rules); - } catch (Throwable throwable) { - logger.error("Error when querying flow rules", throwable); - return Result.ofThrowable(-1, throwable); - } - } + @GetMapping("/rules") + @AuthAction(PrivilegeType.READ_RULE) + public Result> apiQueryMachineRules(@RequestParam String app) { - private Result checkEntityInternal(FlowRuleEntity entity) { - if (entity == null) { - return Result.ofFail(-1, "invalid body"); - } - if (StringUtil.isBlank(entity.getApp())) { - return Result.ofFail(-1, "app can't be null or empty"); - } - if (StringUtil.isBlank(entity.getLimitApp())) { - return Result.ofFail(-1, "limitApp can't be null or empty"); - } - if (StringUtil.isBlank(entity.getResource())) { - return Result.ofFail(-1, "resource can't be null or empty"); - } - if (entity.getGrade() == null) { - return Result.ofFail(-1, "grade can't be null"); - } - if (entity.getGrade() != 0 && entity.getGrade() != 1) { - return Result.ofFail(-1, "grade must be 0 or 1, but " + entity.getGrade() + " got"); - } - if (entity.getCount() == null || entity.getCount() < 0) { - return Result.ofFail(-1, "count should be at lease zero"); - } - if (entity.getStrategy() == null) { - return Result.ofFail(-1, "strategy can't be null"); - } - if (entity.getStrategy() != 0 && StringUtil.isBlank(entity.getRefResource())) { - return Result.ofFail(-1, "refResource can't be null or empty when strategy!=0"); - } - if (entity.getControlBehavior() == null) { - return Result.ofFail(-1, "controlBehavior can't be null"); - } - int controlBehavior = entity.getControlBehavior(); - if (controlBehavior == 1 && entity.getWarmUpPeriodSec() == null) { - return Result.ofFail(-1, "warmUpPeriodSec can't be null when controlBehavior==1"); - } - if (controlBehavior == 2 && entity.getMaxQueueingTimeMs() == null) { - return Result.ofFail(-1, "maxQueueingTimeMs can't be null when controlBehavior==2"); - } - if (entity.isClusterMode() && entity.getClusterConfig() == null) { - return Result.ofFail(-1, "cluster config should be valid"); - } - return null; - } + if (StringUtil.isEmpty(app)) { + return Result.ofFail(-1, "app can't be null or empty"); + } + try { + List rules = ruleProvider.getRules(app); + if (rules != null && !rules.isEmpty()) { + for (FlowRuleEntity entity : rules) { + entity.setApp(app); + if (entity.getClusterConfig() != null && entity.getClusterConfig().getFlowId() != null) { + entity.setId(entity.getClusterConfig().getFlowId()); + } + } + } + rules = repository.saveAll(rules); + return Result.ofSuccess(rules); + } + catch (Throwable throwable) { + logger.error("Error when querying flow rules", throwable); + return Result.ofThrowable(-1, throwable); + } + } - @PostMapping("/rule") - @AuthAction(value = PrivilegeType.WRITE_RULE) - public Result apiAddFlowRule(@RequestBody FlowRuleEntity entity) { + private Result checkEntityInternal(FlowRuleEntity entity) { + if (entity == null) { + return Result.ofFail(-1, "invalid body"); + } + if (StringUtil.isBlank(entity.getApp())) { + return Result.ofFail(-1, "app can't be null or empty"); + } + if (StringUtil.isBlank(entity.getLimitApp())) { + return Result.ofFail(-1, "limitApp can't be null or empty"); + } + if (StringUtil.isBlank(entity.getResource())) { + return Result.ofFail(-1, "resource can't be null or empty"); + } + if (entity.getGrade() == null) { + return Result.ofFail(-1, "grade can't be null"); + } + if (entity.getGrade() != 0 && entity.getGrade() != 1) { + return Result.ofFail(-1, "grade must be 0 or 1, but " + entity.getGrade() + " got"); + } + if (entity.getCount() == null || entity.getCount() < 0) { + return Result.ofFail(-1, "count should be at lease zero"); + } + if (entity.getStrategy() == null) { + return Result.ofFail(-1, "strategy can't be null"); + } + if (entity.getStrategy() != 0 && StringUtil.isBlank(entity.getRefResource())) { + return Result.ofFail(-1, "refResource can't be null or empty when strategy!=0"); + } + if (entity.getControlBehavior() == null) { + return Result.ofFail(-1, "controlBehavior can't be null"); + } + int controlBehavior = entity.getControlBehavior(); + if (controlBehavior == 1 && entity.getWarmUpPeriodSec() == null) { + return Result.ofFail(-1, "warmUpPeriodSec can't be null when controlBehavior==1"); + } + if (controlBehavior == 2 && entity.getMaxQueueingTimeMs() == null) { + return Result.ofFail(-1, "maxQueueingTimeMs can't be null when controlBehavior==2"); + } + if (entity.isClusterMode() && entity.getClusterConfig() == null) { + return Result.ofFail(-1, "cluster config should be valid"); + } + return null; + } - Result checkResult = checkEntityInternal(entity); - if (checkResult != null) { - return checkResult; - } - entity.setId(null); - Date date = new Date(); - entity.setGmtCreate(date); - entity.setGmtModified(date); - entity.setLimitApp(entity.getLimitApp().trim()); - entity.setResource(entity.getResource().trim()); - try { - entity = repository.save(entity); - publishRules(entity.getApp()); - } catch (Throwable throwable) { - logger.error("Failed to add flow rule", throwable); - return Result.ofThrowable(-1, throwable); - } - return Result.ofSuccess(entity); - } + @PostMapping("/rule") + @AuthAction(value = PrivilegeType.WRITE_RULE) + public Result apiAddFlowRule(@RequestBody FlowRuleEntity entity) { - @PutMapping("/rule/{id}") - @AuthAction(PrivilegeType.WRITE_RULE) + Result checkResult = checkEntityInternal(entity); + if (checkResult != null) { + return checkResult; + } + entity.setId(null); + Date date = new Date(); + entity.setGmtCreate(date); + entity.setGmtModified(date); + entity.setLimitApp(entity.getLimitApp().trim()); + entity.setResource(entity.getResource().trim()); + try { + entity = repository.save(entity); + publishRules(entity.getApp()); + } + catch (Throwable throwable) { + logger.error("Failed to add flow rule", throwable); + return Result.ofThrowable(-1, throwable); + } + return Result.ofSuccess(entity); + } - public Result apiUpdateFlowRule(@PathVariable("id") Long id, - @RequestBody FlowRuleEntity entity) { - if (id == null || id <= 0) { - return Result.ofFail(-1, "Invalid id"); - } - FlowRuleEntity oldEntity = repository.findById(id); - if (oldEntity == null) { - return Result.ofFail(-1, "id " + id + " does not exist"); - } - if (entity == null) { - return Result.ofFail(-1, "invalid body"); - } + @PutMapping("/rule/{id}") + @AuthAction(PrivilegeType.WRITE_RULE) - entity.setApp(oldEntity.getApp()); - entity.setIp(oldEntity.getIp()); - entity.setPort(oldEntity.getPort()); - Result checkResult = checkEntityInternal(entity); - if (checkResult != null) { - return checkResult; - } + public Result apiUpdateFlowRule(@PathVariable("id") Long id, @RequestBody FlowRuleEntity entity) { + if (id == null || id <= 0) { + return Result.ofFail(-1, "Invalid id"); + } + FlowRuleEntity oldEntity = repository.findById(id); + if (oldEntity == null) { + return Result.ofFail(-1, "id " + id + " does not exist"); + } + if (entity == null) { + return Result.ofFail(-1, "invalid body"); + } - entity.setId(id); - Date date = new Date(); - entity.setGmtCreate(oldEntity.getGmtCreate()); - entity.setGmtModified(date); - try { - entity = repository.save(entity); - if (entity == null) { - return Result.ofFail(-1, "save entity fail"); - } - publishRules(oldEntity.getApp()); - } catch (Throwable throwable) { - logger.error("Failed to update flow rule", throwable); - return Result.ofThrowable(-1, throwable); - } - return Result.ofSuccess(entity); - } + entity.setApp(oldEntity.getApp()); + entity.setIp(oldEntity.getIp()); + entity.setPort(oldEntity.getPort()); + Result checkResult = checkEntityInternal(entity); + if (checkResult != null) { + return checkResult; + } - @DeleteMapping("/rule/{id}") - @AuthAction(PrivilegeType.DELETE_RULE) - public Result apiDeleteRule(@PathVariable("id") Long id) { - if (id == null || id <= 0) { - return Result.ofFail(-1, "Invalid id"); - } - FlowRuleEntity oldEntity = repository.findById(id); - if (oldEntity == null) { - return Result.ofSuccess(null); - } + entity.setId(id); + Date date = new Date(); + entity.setGmtCreate(oldEntity.getGmtCreate()); + entity.setGmtModified(date); + try { + entity = repository.save(entity); + if (entity == null) { + return Result.ofFail(-1, "save entity fail"); + } + publishRules(oldEntity.getApp()); + } + catch (Throwable throwable) { + logger.error("Failed to update flow rule", throwable); + return Result.ofThrowable(-1, throwable); + } + return Result.ofSuccess(entity); + } - try { - repository.delete(id); - publishRules(oldEntity.getApp()); - } catch (Exception e) { - return Result.ofFail(-1, e.getMessage()); - } - return Result.ofSuccess(id); - } + @DeleteMapping("/rule/{id}") + @AuthAction(PrivilegeType.DELETE_RULE) + public Result apiDeleteRule(@PathVariable("id") Long id) { + if (id == null || id <= 0) { + return Result.ofFail(-1, "Invalid id"); + } + FlowRuleEntity oldEntity = repository.findById(id); + if (oldEntity == null) { + return Result.ofSuccess(null); + } + + try { + repository.delete(id); + publishRules(oldEntity.getApp()); + } + catch (Exception e) { + return Result.ofFail(-1, e.getMessage()); + } + return Result.ofSuccess(id); + } + + private void publishRules(/* @NonNull */ String app) throws Exception { + List rules = repository.findAllByApp(app); + rulePublisher.publish(app, rules); + } - private void publishRules(/*@NonNull*/ String app) throws Exception { - List rules = repository.findAllByApp(app); - rulePublisher.publish(app, rules); - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/ApplicationEntity.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/ApplicationEntity.java index 44c10daaf..cebe93ce1 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/ApplicationEntity.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/ApplicationEntity.java @@ -24,83 +24,85 @@ import com.alibaba.csp.sentinel.dashboard.discovery.AppInfo; */ public class ApplicationEntity { - private Long id; - private Date gmtCreate; - private Date gmtModified; - private String app; - private Integer appType; - private String activeConsole; - private Date lastFetch; + private Long id; - public long getId() { - return id; - } + private Date gmtCreate; - public void setId(long id) { - this.id = id; - } + private Date gmtModified; - public Date getGmtCreate() { - return gmtCreate; - } + private String app; - public void setGmtCreate(Date gmtCreate) { - this.gmtCreate = gmtCreate; - } + private Integer appType; - public Date getGmtModified() { - return gmtModified; - } + private String activeConsole; - public void setGmtModified(Date gmtModified) { - this.gmtModified = gmtModified; - } + private Date lastFetch; - public String getApp() { - return app; - } + public long getId() { + return id; + } - public void setApp(String app) { - this.app = app; - } + public void setId(long id) { + this.id = id; + } - public Integer getAppType() { - return appType; - } + public Date getGmtCreate() { + return gmtCreate; + } - public void setAppType(Integer appType) { - this.appType = appType; - } + public void setGmtCreate(Date gmtCreate) { + this.gmtCreate = gmtCreate; + } - public String getActiveConsole() { - return activeConsole; - } + public Date getGmtModified() { + return gmtModified; + } - public Date getLastFetch() { - return lastFetch; - } + public void setGmtModified(Date gmtModified) { + this.gmtModified = gmtModified; + } - public void setLastFetch(Date lastFetch) { - this.lastFetch = lastFetch; - } + public String getApp() { + return app; + } - public void setActiveConsole(String activeConsole) { - this.activeConsole = activeConsole; - } + public void setApp(String app) { + this.app = app; + } - public AppInfo toAppInfo() { - return new AppInfo(app, appType); - } + public Integer getAppType() { + return appType; + } + + public void setAppType(Integer appType) { + this.appType = appType; + } + + public String getActiveConsole() { + return activeConsole; + } + + public Date getLastFetch() { + return lastFetch; + } + + public void setLastFetch(Date lastFetch) { + this.lastFetch = lastFetch; + } + + public void setActiveConsole(String activeConsole) { + this.activeConsole = activeConsole; + } + + public AppInfo toAppInfo() { + return new AppInfo(app, appType); + } + + @Override + public String toString() { + return "ApplicationEntity{" + "id=" + id + ", gmtCreate=" + gmtCreate + ", gmtModified=" + gmtModified + + ", app='" + app + '\'' + ", activeConsole='" + activeConsole + '\'' + ", lastFetch=" + lastFetch + + '}'; + } - @Override - public String toString() { - return "ApplicationEntity{" + - "id=" + id + - ", gmtCreate=" + gmtCreate + - ", gmtModified=" + gmtModified + - ", app='" + app + '\'' + - ", activeConsole='" + activeConsole + '\'' + - ", lastFetch=" + lastFetch + - '}'; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/MachineEntity.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/MachineEntity.java index 5b91f3399..037be22db 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/MachineEntity.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/MachineEntity.java @@ -23,103 +23,105 @@ import com.alibaba.csp.sentinel.dashboard.discovery.MachineInfo; * @author leyou */ public class MachineEntity { - private Long id; - private Date gmtCreate; - private Date gmtModified; - private String app; - private String ip; - private String hostname; - private Date timestamp; - private Integer port; - public long getId() { - return id; - } + private Long id; - public void setId(long id) { - this.id = id; - } + private Date gmtCreate; - public Date getGmtCreate() { - return gmtCreate; - } + private Date gmtModified; - public void setGmtCreate(Date gmtCreate) { - this.gmtCreate = gmtCreate; - } + private String app; - public Date getGmtModified() { - return gmtModified; - } + private String ip; - public void setGmtModified(Date gmtModified) { - this.gmtModified = gmtModified; - } + private String hostname; - public String getApp() { - return app; - } + private Date timestamp; - public void setApp(String app) { - this.app = app; - } + private Integer port; - public String getIp() { - return ip; - } + public long getId() { + return id; + } - public void setIp(String ip) { - this.ip = ip; - } + public void setId(long id) { + this.id = id; + } - public String getHostname() { - return hostname; - } + public Date getGmtCreate() { + return gmtCreate; + } - public void setHostname(String hostname) { - this.hostname = hostname; - } + public void setGmtCreate(Date gmtCreate) { + this.gmtCreate = gmtCreate; + } - public Date getTimestamp() { - return timestamp; - } + public Date getGmtModified() { + return gmtModified; + } - public void setTimestamp(Date timestamp) { - this.timestamp = timestamp; - } + public void setGmtModified(Date gmtModified) { + this.gmtModified = gmtModified; + } - public Integer getPort() { - return port; - } + public String getApp() { + return app; + } - public void setPort(Integer port) { - this.port = port; - } + public void setApp(String app) { + this.app = app; + } - public MachineInfo toMachineInfo() { - MachineInfo machineInfo = new MachineInfo(); + public String getIp() { + return ip; + } - machineInfo.setApp(app); - machineInfo.setHostname(hostname); - machineInfo.setIp(ip); - machineInfo.setPort(port); - machineInfo.setLastHeartbeat(timestamp.getTime()); - machineInfo.setHeartbeatVersion(timestamp.getTime()); + public void setIp(String ip) { + this.ip = ip; + } - return machineInfo; - } + public String getHostname() { + return hostname; + } + + public void setHostname(String hostname) { + this.hostname = hostname; + } + + public Date getTimestamp() { + return timestamp; + } + + public void setTimestamp(Date timestamp) { + this.timestamp = timestamp; + } + + public Integer getPort() { + return port; + } + + public void setPort(Integer port) { + this.port = port; + } + + public MachineInfo toMachineInfo() { + MachineInfo machineInfo = new MachineInfo(); + + machineInfo.setApp(app); + machineInfo.setHostname(hostname); + machineInfo.setIp(ip); + machineInfo.setPort(port); + machineInfo.setLastHeartbeat(timestamp.getTime()); + machineInfo.setHeartbeatVersion(timestamp.getTime()); + + return machineInfo; + } + + @Override + public String toString() { + return "MachineEntity{" + "id=" + id + ", gmtCreate=" + gmtCreate + ", gmtModified=" + gmtModified + ", app='" + + app + '\'' + ", ip='" + ip + '\'' + ", hostname='" + hostname + '\'' + ", timestamp=" + timestamp + + ", port=" + port + '}'; + } - @Override - public String toString() { - return "MachineEntity{" + - "id=" + id + - ", gmtCreate=" + gmtCreate + - ", gmtModified=" + gmtModified + - ", app='" + app + '\'' + - ", ip='" + ip + '\'' + - ", hostname='" + hostname + '\'' + - ", timestamp=" + timestamp + - ", port=" + port + - '}'; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/MetricEntity.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/MetricEntity.java index f08a41a69..4e89b454f 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/MetricEntity.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/MetricEntity.java @@ -21,200 +21,198 @@ import java.util.Date; * @author leyou */ public class MetricEntity { - private Long id; - private Date gmtCreate; - private Date gmtModified; - private String app; - /** - * 监控信息的时间戳 - */ - private Date timestamp; - private String resource; - private Long passQps; - private Long successQps; - private Long blockQps; - private Long exceptionQps; - /** - * summary rt of all success exit qps. - */ - private double rt; + private Long id; - /** - * 本次聚合的总条数 - */ - private int count; + private Date gmtCreate; - private int resourceCode; + private Date gmtModified; - public static MetricEntity copyOf(MetricEntity oldEntity) { - MetricEntity entity = new MetricEntity(); - entity.setId(oldEntity.getId()); - entity.setGmtCreate(oldEntity.getGmtCreate()); - entity.setGmtModified(oldEntity.getGmtModified()); - entity.setApp(oldEntity.getApp()); - entity.setTimestamp(oldEntity.getTimestamp()); - entity.setResource(oldEntity.getResource()); - entity.setPassQps(oldEntity.getPassQps()); - entity.setBlockQps(oldEntity.getBlockQps()); - entity.setSuccessQps(oldEntity.getSuccessQps()); - entity.setExceptionQps(oldEntity.getExceptionQps()); - entity.setRt(oldEntity.getRt()); - entity.setCount(oldEntity.getCount()); - entity.setResource(oldEntity.getResource()); - return entity; - } + private String app; - public synchronized void addPassQps(Long passQps) { - this.passQps += passQps; - } + /** + * 监控信息的时间戳 + */ + private Date timestamp; - public synchronized void addBlockQps(Long blockQps) { - this.blockQps += blockQps; - } + private String resource; - public synchronized void addExceptionQps(Long exceptionQps) { - this.exceptionQps += exceptionQps; - } + private Long passQps; - public synchronized void addCount(int count) { - this.count += count; - } + private Long successQps; - public synchronized void addRtAndSuccessQps(double avgRt, Long successQps) { - this.rt += avgRt * successQps; - this.successQps += successQps; - } + private Long blockQps; - /** - * {@link #rt} = {@code avgRt * successQps} - * - * @param avgRt average rt of {@code successQps} - * @param successQps - */ - public synchronized void setRtAndSuccessQps(double avgRt, Long successQps) { - this.rt = avgRt * successQps; - this.successQps = successQps; - } + private Long exceptionQps; - public Long getId() { - return id; - } + /** + * summary rt of all success exit qps. + */ + private double rt; - public void setId(Long id) { - this.id = id; - } + /** + * 本次聚合的总条数 + */ + private int count; - public Date getGmtCreate() { - return gmtCreate; - } + private int resourceCode; - public void setGmtCreate(Date gmtCreate) { - this.gmtCreate = gmtCreate; - } + public static MetricEntity copyOf(MetricEntity oldEntity) { + MetricEntity entity = new MetricEntity(); + entity.setId(oldEntity.getId()); + entity.setGmtCreate(oldEntity.getGmtCreate()); + entity.setGmtModified(oldEntity.getGmtModified()); + entity.setApp(oldEntity.getApp()); + entity.setTimestamp(oldEntity.getTimestamp()); + entity.setResource(oldEntity.getResource()); + entity.setPassQps(oldEntity.getPassQps()); + entity.setBlockQps(oldEntity.getBlockQps()); + entity.setSuccessQps(oldEntity.getSuccessQps()); + entity.setExceptionQps(oldEntity.getExceptionQps()); + entity.setRt(oldEntity.getRt()); + entity.setCount(oldEntity.getCount()); + entity.setResource(oldEntity.getResource()); + return entity; + } - public Date getGmtModified() { - return gmtModified; - } + public synchronized void addPassQps(Long passQps) { + this.passQps += passQps; + } - public void setGmtModified(Date gmtModified) { - this.gmtModified = gmtModified; - } + public synchronized void addBlockQps(Long blockQps) { + this.blockQps += blockQps; + } - public String getApp() { - return app; - } + public synchronized void addExceptionQps(Long exceptionQps) { + this.exceptionQps += exceptionQps; + } - public void setApp(String app) { - this.app = app; - } + public synchronized void addCount(int count) { + this.count += count; + } - public Date getTimestamp() { - return timestamp; - } + public synchronized void addRtAndSuccessQps(double avgRt, Long successQps) { + this.rt += avgRt * successQps; + this.successQps += successQps; + } - public void setTimestamp(Date timestamp) { - this.timestamp = timestamp; - } + /** + * {@link #rt} = {@code avgRt * successQps} + * @param avgRt average rt of {@code successQps} + * @param successQps + */ + public synchronized void setRtAndSuccessQps(double avgRt, Long successQps) { + this.rt = avgRt * successQps; + this.successQps = successQps; + } - public String getResource() { - return resource; - } + public Long getId() { + return id; + } - public void setResource(String resource) { - this.resource = resource; - this.resourceCode = resource.hashCode(); - } + public void setId(Long id) { + this.id = id; + } - public Long getPassQps() { - return passQps; - } + public Date getGmtCreate() { + return gmtCreate; + } - public void setPassQps(Long passQps) { - this.passQps = passQps; - } + public void setGmtCreate(Date gmtCreate) { + this.gmtCreate = gmtCreate; + } - public Long getBlockQps() { - return blockQps; - } + public Date getGmtModified() { + return gmtModified; + } - public void setBlockQps(Long blockQps) { - this.blockQps = blockQps; - } + public void setGmtModified(Date gmtModified) { + this.gmtModified = gmtModified; + } - public Long getExceptionQps() { - return exceptionQps; - } + public String getApp() { + return app; + } - public void setExceptionQps(Long exceptionQps) { - this.exceptionQps = exceptionQps; - } + public void setApp(String app) { + this.app = app; + } - public double getRt() { - return rt; - } + public Date getTimestamp() { + return timestamp; + } - public void setRt(double rt) { - this.rt = rt; - } + public void setTimestamp(Date timestamp) { + this.timestamp = timestamp; + } - public int getCount() { - return count; - } + public String getResource() { + return resource; + } - public void setCount(int count) { - this.count = count; - } + public void setResource(String resource) { + this.resource = resource; + this.resourceCode = resource.hashCode(); + } - public int getResourceCode() { - return resourceCode; - } + public Long getPassQps() { + return passQps; + } - public Long getSuccessQps() { - return successQps; - } + public void setPassQps(Long passQps) { + this.passQps = passQps; + } - public void setSuccessQps(Long successQps) { - this.successQps = successQps; - } + public Long getBlockQps() { + return blockQps; + } - @Override - public String toString() { - return "MetricEntity{" + - "id=" + id + - ", gmtCreate=" + gmtCreate + - ", gmtModified=" + gmtModified + - ", app='" + app + '\'' + - ", timestamp=" + timestamp + - ", resource='" + resource + '\'' + - ", passQps=" + passQps + - ", blockQps=" + blockQps + - ", successQps=" + successQps + - ", exceptionQps=" + exceptionQps + - ", rt=" + rt + - ", count=" + count + - ", resourceCode=" + resourceCode + - '}'; - } + public void setBlockQps(Long blockQps) { + this.blockQps = blockQps; + } + + public Long getExceptionQps() { + return exceptionQps; + } + + public void setExceptionQps(Long exceptionQps) { + this.exceptionQps = exceptionQps; + } + + public double getRt() { + return rt; + } + + public void setRt(double rt) { + this.rt = rt; + } + + public int getCount() { + return count; + } + + public void setCount(int count) { + this.count = count; + } + + public int getResourceCode() { + return resourceCode; + } + + public Long getSuccessQps() { + return successQps; + } + + public void setSuccessQps(Long successQps) { + this.successQps = successQps; + } + + @Override + public String toString() { + return "MetricEntity{" + "id=" + id + ", gmtCreate=" + gmtCreate + ", gmtModified=" + gmtModified + ", app='" + + app + '\'' + ", timestamp=" + timestamp + ", resource='" + resource + '\'' + ", passQps=" + passQps + + ", blockQps=" + blockQps + ", successQps=" + successQps + ", exceptionQps=" + exceptionQps + ", rt=" + + rt + ", count=" + count + ", resourceCode=" + resourceCode + '}'; + } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/MetricPositionEntity.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/MetricPositionEntity.java index 2be29eb83..b01b68a64 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/MetricPositionEntity.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/MetricPositionEntity.java @@ -21,101 +21,101 @@ import java.util.Date; * @author leyou */ public class MetricPositionEntity { - private long id; - private Date gmtCreate; - private Date gmtModified; - private String app; - private String ip; - /** - * Sentinel在该应用上使用的端口 - */ - private int port; - /** - * 机器名,冗余字段 - */ - private String hostname; + private long id; - /** - * 上一次拉取的最晚时间戳 - */ - private Date lastFetch; + private Date gmtCreate; - public long getId() { - return id; - } + private Date gmtModified; - public void setId(long id) { - this.id = id; - } + private String app; - public Date getGmtCreate() { - return gmtCreate; - } + private String ip; - public void setGmtCreate(Date gmtCreate) { - this.gmtCreate = gmtCreate; - } + /** + * Sentinel在该应用上使用的端口 + */ + private int port; - public Date getGmtModified() { - return gmtModified; - } + /** + * 机器名,冗余字段 + */ + private String hostname; - public void setGmtModified(Date gmtModified) { - this.gmtModified = gmtModified; - } + /** + * 上一次拉取的最晚时间戳 + */ + private Date lastFetch; - public String getApp() { - return app; - } + public long getId() { + return id; + } - public void setApp(String app) { - this.app = app; - } + public void setId(long id) { + this.id = id; + } - public String getIp() { - return ip; - } + public Date getGmtCreate() { + return gmtCreate; + } - public void setIp(String ip) { - this.ip = ip; - } + public void setGmtCreate(Date gmtCreate) { + this.gmtCreate = gmtCreate; + } - public int getPort() { - return port; - } + public Date getGmtModified() { + return gmtModified; + } - public void setPort(int port) { - this.port = port; - } + public void setGmtModified(Date gmtModified) { + this.gmtModified = gmtModified; + } - public String getHostname() { - return hostname; - } + public String getApp() { + return app; + } - public void setHostname(String hostname) { - this.hostname = hostname; - } + public void setApp(String app) { + this.app = app; + } - public Date getLastFetch() { - return lastFetch; - } + public String getIp() { + return ip; + } - public void setLastFetch(Date lastFetch) { - this.lastFetch = lastFetch; - } + public void setIp(String ip) { + this.ip = ip; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + public String getHostname() { + return hostname; + } + + public void setHostname(String hostname) { + this.hostname = hostname; + } + + public Date getLastFetch() { + return lastFetch; + } + + public void setLastFetch(Date lastFetch) { + this.lastFetch = lastFetch; + } + + @Override + public String toString() { + return "MetricPositionEntity{" + "id=" + id + ", gmtCreate=" + gmtCreate + ", gmtModified=" + gmtModified + + ", app='" + app + '\'' + ", ip='" + ip + '\'' + ", port=" + port + ", hostname='" + hostname + '\'' + + ", lastFetch=" + lastFetch + '}'; + } - @Override - public String toString() { - return "MetricPositionEntity{" + - "id=" + id + - ", gmtCreate=" + gmtCreate + - ", gmtModified=" + gmtModified + - ", app='" + app + '\'' + - ", ip='" + ip + '\'' + - ", port=" + port + - ", hostname='" + hostname + '\'' + - ", lastFetch=" + lastFetch + - '}'; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/SentinelVersion.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/SentinelVersion.java index 08fcaf252..7dddb8f3f 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/SentinelVersion.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/SentinelVersion.java @@ -20,110 +20,117 @@ package com.alibaba.csp.sentinel.dashboard.datasource.entity; * @since 0.2.1 */ public class SentinelVersion { - private int majorVersion; - private int minorVersion; - private int fixVersion; - private String postfix; - - public SentinelVersion() { - this(0, 0, 0); - } - - public SentinelVersion(int major, int minor, int fix) { - this(major, minor, fix, null); - } - - public SentinelVersion(int major, int minor, int fix, String postfix) { - this.majorVersion = major; - this.minorVersion = minor; - this.fixVersion = fix; - this.postfix = postfix; - } - - /** - * 000, 000, 000 - */ - public int getFullVersion() { - return majorVersion * 1000000 + minorVersion * 1000 + fixVersion; - } - public int getMajorVersion() { - return majorVersion; - } + private int majorVersion; - public SentinelVersion setMajorVersion(int majorVersion) { - this.majorVersion = majorVersion; - return this; - } + private int minorVersion; - public int getMinorVersion() { - return minorVersion; - } + private int fixVersion; - public SentinelVersion setMinorVersion(int minorVersion) { - this.minorVersion = minorVersion; - return this; - } + private String postfix; - public int getFixVersion() { - return fixVersion; - } + public SentinelVersion() { + this(0, 0, 0); + } - public SentinelVersion setFixVersion(int fixVersion) { - this.fixVersion = fixVersion; - return this; - } + public SentinelVersion(int major, int minor, int fix) { + this(major, minor, fix, null); + } - public String getPostfix() { - return postfix; - } + public SentinelVersion(int major, int minor, int fix, String postfix) { + this.majorVersion = major; + this.minorVersion = minor; + this.fixVersion = fix; + this.postfix = postfix; + } - public SentinelVersion setPostfix(String postfix) { - this.postfix = postfix; - return this; - } + /** + * 000, 000, 000 + */ + public int getFullVersion() { + return majorVersion * 1000000 + minorVersion * 1000 + fixVersion; + } - public boolean greaterThan(SentinelVersion version) { - if (version == null) { - return true; - } - return getFullVersion() > version.getFullVersion(); - } + public int getMajorVersion() { + return majorVersion; + } - public boolean greaterOrEqual(SentinelVersion version) { - if (version == null) { - return true; - } - return getFullVersion() >= version.getFullVersion(); - } + public SentinelVersion setMajorVersion(int majorVersion) { + this.majorVersion = majorVersion; + return this; + } - @Override - public boolean equals(Object o) { - if (this == o) { return true; } - if (o == null || getClass() != o.getClass()) { return false; } + public int getMinorVersion() { + return minorVersion; + } - SentinelVersion that = (SentinelVersion)o; + public SentinelVersion setMinorVersion(int minorVersion) { + this.minorVersion = minorVersion; + return this; + } - if (getFullVersion() != that.getFullVersion()) { return false; } - return postfix != null ? postfix.equals(that.postfix) : that.postfix == null; - } + public int getFixVersion() { + return fixVersion; + } - @Override - public int hashCode() { - int result = majorVersion; - result = 31 * result + minorVersion; - result = 31 * result + fixVersion; - result = 31 * result + (postfix != null ? postfix.hashCode() : 0); - return result; - } + public SentinelVersion setFixVersion(int fixVersion) { + this.fixVersion = fixVersion; + return this; + } + + public String getPostfix() { + return postfix; + } + + public SentinelVersion setPostfix(String postfix) { + this.postfix = postfix; + return this; + } + + public boolean greaterThan(SentinelVersion version) { + if (version == null) { + return true; + } + return getFullVersion() > version.getFullVersion(); + } + + public boolean greaterOrEqual(SentinelVersion version) { + if (version == null) { + return true; + } + return getFullVersion() >= version.getFullVersion(); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + SentinelVersion that = (SentinelVersion) o; + + if (getFullVersion() != that.getFullVersion()) { + return false; + } + return postfix != null ? postfix.equals(that.postfix) : that.postfix == null; + } + + @Override + public int hashCode() { + int result = majorVersion; + result = 31 * result + minorVersion; + result = 31 * result + fixVersion; + result = 31 * result + (postfix != null ? postfix.hashCode() : 0); + return result; + } + + @Override + public String toString() { + return "SentinelVersion{" + "majorVersion=" + majorVersion + ", minorVersion=" + minorVersion + ", fixVersion=" + + fixVersion + ", postfix='" + postfix + '\'' + '}'; + } - @Override - public String toString() { - return "SentinelVersion{" + - "majorVersion=" + majorVersion + - ", minorVersion=" + minorVersion + - ", fixVersion=" + fixVersion + - ", postfix='" + postfix + '\'' + - '}'; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/gateway/ApiDefinitionEntity.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/gateway/ApiDefinitionEntity.java index b042e0ada..dde2b1934 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/gateway/ApiDefinitionEntity.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/gateway/ApiDefinitionEntity.java @@ -34,175 +34,175 @@ import java.util.Set; */ public class ApiDefinitionEntity implements RuleEntity { - private Long id; - private String app; - private String ip; - private Integer port; + private Long id; - private Date gmtCreate; - private Date gmtModified; + private String app; - private String apiName; - private Set predicateItems; + private String ip; - public static ApiDefinitionEntity fromApiDefinition(String app, String ip, Integer port, ApiDefinition apiDefinition) { - ApiDefinitionEntity entity = new ApiDefinitionEntity(); - entity.setApp(app); - entity.setIp(ip); - entity.setPort(port); - entity.setApiName(apiDefinition.getApiName()); + private Integer port; - Set predicateItems = new LinkedHashSet<>(); - entity.setPredicateItems(predicateItems); + private Date gmtCreate; - Set apiPredicateItems = apiDefinition.getPredicateItems(); - if (apiPredicateItems != null) { - for (ApiPredicateItem apiPredicateItem : apiPredicateItems) { - ApiPredicateItemEntity itemEntity = new ApiPredicateItemEntity(); - predicateItems.add(itemEntity); - ApiPathPredicateItem pathPredicateItem = (ApiPathPredicateItem) apiPredicateItem; - itemEntity.setPattern(pathPredicateItem.getPattern()); - itemEntity.setMatchStrategy(pathPredicateItem.getMatchStrategy()); - } - } + private Date gmtModified; - return entity; - } + private String apiName; - public ApiDefinition toApiDefinition() { - ApiDefinition apiDefinition = new ApiDefinition(); - apiDefinition.setApiName(apiName); + private Set predicateItems; - Set apiPredicateItems = new LinkedHashSet<>(); - apiDefinition.setPredicateItems(apiPredicateItems); + public static ApiDefinitionEntity fromApiDefinition(String app, String ip, Integer port, + ApiDefinition apiDefinition) { + ApiDefinitionEntity entity = new ApiDefinitionEntity(); + entity.setApp(app); + entity.setIp(ip); + entity.setPort(port); + entity.setApiName(apiDefinition.getApiName()); - if (predicateItems != null) { - for (ApiPredicateItemEntity predicateItem : predicateItems) { - ApiPathPredicateItem apiPredicateItem = new ApiPathPredicateItem(); - apiPredicateItems.add(apiPredicateItem); - apiPredicateItem.setMatchStrategy(predicateItem.getMatchStrategy()); - apiPredicateItem.setPattern(predicateItem.getPattern()); - } - } + Set predicateItems = new LinkedHashSet<>(); + entity.setPredicateItems(predicateItems); - return apiDefinition; - } + Set apiPredicateItems = apiDefinition.getPredicateItems(); + if (apiPredicateItems != null) { + for (ApiPredicateItem apiPredicateItem : apiPredicateItems) { + ApiPredicateItemEntity itemEntity = new ApiPredicateItemEntity(); + predicateItems.add(itemEntity); + ApiPathPredicateItem pathPredicateItem = (ApiPathPredicateItem) apiPredicateItem; + itemEntity.setPattern(pathPredicateItem.getPattern()); + itemEntity.setMatchStrategy(pathPredicateItem.getMatchStrategy()); + } + } - public ApiDefinitionEntity() { + return entity; + } - } + public ApiDefinition toApiDefinition() { + ApiDefinition apiDefinition = new ApiDefinition(); + apiDefinition.setApiName(apiName); - public ApiDefinitionEntity(String apiName, Set predicateItems) { - this.apiName = apiName; - this.predicateItems = predicateItems; - } + Set apiPredicateItems = new LinkedHashSet<>(); + apiDefinition.setPredicateItems(apiPredicateItems); - public String getApiName() { - return apiName; - } + if (predicateItems != null) { + for (ApiPredicateItemEntity predicateItem : predicateItems) { + ApiPathPredicateItem apiPredicateItem = new ApiPathPredicateItem(); + apiPredicateItems.add(apiPredicateItem); + apiPredicateItem.setMatchStrategy(predicateItem.getMatchStrategy()); + apiPredicateItem.setPattern(predicateItem.getPattern()); + } + } - public void setApiName(String apiName) { - this.apiName = apiName; - } + return apiDefinition; + } - public Set getPredicateItems() { - return predicateItems; - } + public ApiDefinitionEntity() { - public void setPredicateItems(Set predicateItems) { - this.predicateItems = predicateItems; - } + } - @Override - public Long getId() { - return id; - } + public ApiDefinitionEntity(String apiName, Set predicateItems) { + this.apiName = apiName; + this.predicateItems = predicateItems; + } - @Override - public void setId(Long id) { - this.id = id; - } + public String getApiName() { + return apiName; + } - @Override - public String getApp() { - return app; - } + public void setApiName(String apiName) { + this.apiName = apiName; + } - public void setApp(String app) { - this.app = app; - } + public Set getPredicateItems() { + return predicateItems; + } - @Override - public String getIp() { - return ip; - } + public void setPredicateItems(Set predicateItems) { + this.predicateItems = predicateItems; + } - public void setIp(String ip) { - this.ip = ip; - } + @Override + public Long getId() { + return id; + } - @Override - public Integer getPort() { - return port; - } + @Override + public void setId(Long id) { + this.id = id; + } - public void setPort(Integer port) { - this.port = port; - } + @Override + public String getApp() { + return app; + } - @Override - public Date getGmtCreate() { - return gmtCreate; - } + public void setApp(String app) { + this.app = app; + } - public void setGmtCreate(Date gmtCreate) { - this.gmtCreate = gmtCreate; - } + @Override + public String getIp() { + return ip; + } - public Date getGmtModified() { - return gmtModified; - } + public void setIp(String ip) { + this.ip = ip; + } - public void setGmtModified(Date gmtModified) { - this.gmtModified = gmtModified; - } + @Override + public Integer getPort() { + return port; + } - @Override - public Rule toRule() { - return null; - } + public void setPort(Integer port) { + this.port = port; + } - @Override - public boolean equals(Object o) { - if (this == o) { return true; } - if (o == null || getClass() != o.getClass()) { return false; } - ApiDefinitionEntity entity = (ApiDefinitionEntity) o; - return Objects.equals(id, entity.id) && - Objects.equals(app, entity.app) && - Objects.equals(ip, entity.ip) && - Objects.equals(port, entity.port) && - Objects.equals(gmtCreate, entity.gmtCreate) && - Objects.equals(gmtModified, entity.gmtModified) && - Objects.equals(apiName, entity.apiName) && - Objects.equals(predicateItems, entity.predicateItems); - } + @Override + public Date getGmtCreate() { + return gmtCreate; + } - @Override - public int hashCode() { - return Objects.hash(id, app, ip, port, gmtCreate, gmtModified, apiName, predicateItems); - } + public void setGmtCreate(Date gmtCreate) { + this.gmtCreate = gmtCreate; + } + + public Date getGmtModified() { + return gmtModified; + } + + public void setGmtModified(Date gmtModified) { + this.gmtModified = gmtModified; + } + + @Override + public Rule toRule() { + return null; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ApiDefinitionEntity entity = (ApiDefinitionEntity) o; + return Objects.equals(id, entity.id) && Objects.equals(app, entity.app) && Objects.equals(ip, entity.ip) + && Objects.equals(port, entity.port) && Objects.equals(gmtCreate, entity.gmtCreate) + && Objects.equals(gmtModified, entity.gmtModified) && Objects.equals(apiName, entity.apiName) + && Objects.equals(predicateItems, entity.predicateItems); + } + + @Override + public int hashCode() { + return Objects.hash(id, app, ip, port, gmtCreate, gmtModified, apiName, predicateItems); + } + + @Override + public String toString() { + return "ApiDefinitionEntity{" + "id=" + id + ", app='" + app + '\'' + ", ip='" + ip + '\'' + ", port=" + port + + ", gmtCreate=" + gmtCreate + ", gmtModified=" + gmtModified + ", apiName='" + apiName + '\'' + + ", predicateItems=" + predicateItems + '}'; + } - @Override - public String toString() { - return "ApiDefinitionEntity{" + - "id=" + id + - ", app='" + app + '\'' + - ", ip='" + ip + '\'' + - ", port=" + port + - ", gmtCreate=" + gmtCreate + - ", gmtModified=" + gmtModified + - ", apiName='" + apiName + '\'' + - ", predicateItems=" + predicateItems + - '}'; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/gateway/ApiPredicateItemEntity.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/gateway/ApiPredicateItemEntity.java index 1d6058cd0..62a93c34b 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/gateway/ApiPredicateItemEntity.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/gateway/ApiPredicateItemEntity.java @@ -27,53 +27,54 @@ import java.util.Objects; */ public class ApiPredicateItemEntity { - private String pattern; + private String pattern; - private Integer matchStrategy; + private Integer matchStrategy; - public ApiPredicateItemEntity() { - } + public ApiPredicateItemEntity() { + } - public ApiPredicateItemEntity(String pattern, int matchStrategy) { - this.pattern = pattern; - this.matchStrategy = matchStrategy; - } + public ApiPredicateItemEntity(String pattern, int matchStrategy) { + this.pattern = pattern; + this.matchStrategy = matchStrategy; + } - public String getPattern() { - return pattern; - } + public String getPattern() { + return pattern; + } - public void setPattern(String pattern) { - this.pattern = pattern; - } + public void setPattern(String pattern) { + this.pattern = pattern; + } - public Integer getMatchStrategy() { - return matchStrategy; - } + public Integer getMatchStrategy() { + return matchStrategy; + } - public void setMatchStrategy(Integer matchStrategy) { - this.matchStrategy = matchStrategy; - } + public void setMatchStrategy(Integer matchStrategy) { + this.matchStrategy = matchStrategy; + } - @Override - public boolean equals(Object o) { - if (this == o) { return true; } - if (o == null || getClass() != o.getClass()) { return false; } - ApiPredicateItemEntity that = (ApiPredicateItemEntity) o; - return Objects.equals(pattern, that.pattern) && - Objects.equals(matchStrategy, that.matchStrategy); - } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ApiPredicateItemEntity that = (ApiPredicateItemEntity) o; + return Objects.equals(pattern, that.pattern) && Objects.equals(matchStrategy, that.matchStrategy); + } - @Override - public int hashCode() { - return Objects.hash(pattern, matchStrategy); - } + @Override + public int hashCode() { + return Objects.hash(pattern, matchStrategy); + } + + @Override + public String toString() { + return "ApiPredicateItemEntity{" + "pattern='" + pattern + '\'' + ", matchStrategy=" + matchStrategy + '}'; + } - @Override - public String toString() { - return "ApiPredicateItemEntity{" + - "pattern='" + pattern + '\'' + - ", matchStrategy=" + matchStrategy + - '}'; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/gateway/GatewayFlowRuleEntity.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/gateway/GatewayFlowRuleEntity.java index 391ea41f1..a66a4fa66 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/gateway/GatewayFlowRuleEntity.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/gateway/GatewayFlowRuleEntity.java @@ -31,324 +31,322 @@ import java.util.Objects; */ public class GatewayFlowRuleEntity implements RuleEntity { - /**间隔单位*/ - /**0-秒*/ - public static final int INTERVAL_UNIT_SECOND = 0; - /**1-分*/ - public static final int INTERVAL_UNIT_MINUTE = 1; - /**2-时*/ - public static final int INTERVAL_UNIT_HOUR = 2; - /**3-天*/ - public static final int INTERVAL_UNIT_DAY = 3; + /** 间隔单位 */ + /** 0-秒 */ + public static final int INTERVAL_UNIT_SECOND = 0; - private Long id; - private String app; - private String ip; - private Integer port; + /** 1-分 */ + public static final int INTERVAL_UNIT_MINUTE = 1; - private Date gmtCreate; - private Date gmtModified; + /** 2-时 */ + public static final int INTERVAL_UNIT_HOUR = 2; - private String resource; - private Integer resourceMode; + /** 3-天 */ + public static final int INTERVAL_UNIT_DAY = 3; - private Integer grade; - private Double count; - private Long interval; - private Integer intervalUnit; + private Long id; - private Integer controlBehavior; - private Integer burst; + private String app; - private Integer maxQueueingTimeoutMs; + private String ip; - private GatewayParamFlowItemEntity paramItem; + private Integer port; - public static Long calIntervalSec(Long interval, Integer intervalUnit) { - switch (intervalUnit) { - case INTERVAL_UNIT_SECOND: - return interval; - case INTERVAL_UNIT_MINUTE: - return interval * 60; - case INTERVAL_UNIT_HOUR: - return interval * 60 * 60; - case INTERVAL_UNIT_DAY: - return interval * 60 * 60 * 24; - default: - break; - } + private Date gmtCreate; - throw new IllegalArgumentException("Invalid intervalUnit: " + intervalUnit); - } + private Date gmtModified; - public static Object[] parseIntervalSec(Long intervalSec) { - if (intervalSec % (60 * 60 * 24) == 0) { - return new Object[] {intervalSec / (60 * 60 * 24), INTERVAL_UNIT_DAY}; - } + private String resource; - if (intervalSec % (60 * 60 ) == 0) { - return new Object[] {intervalSec / (60 * 60), INTERVAL_UNIT_HOUR}; - } + private Integer resourceMode; - if (intervalSec % 60 == 0) { - return new Object[] {intervalSec / 60, INTERVAL_UNIT_MINUTE}; - } + private Integer grade; - return new Object[] {intervalSec, INTERVAL_UNIT_SECOND}; - } + private Double count; - public GatewayFlowRule toGatewayFlowRule() { - GatewayFlowRule rule = new GatewayFlowRule(); - rule.setResource(resource); - rule.setResourceMode(resourceMode); + private Long interval; - rule.setGrade(grade); - rule.setCount(count); - rule.setIntervalSec(calIntervalSec(interval, intervalUnit)); + private Integer intervalUnit; - rule.setControlBehavior(controlBehavior); + private Integer controlBehavior; - if (burst != null) { - rule.setBurst(burst); - } + private Integer burst; - if (maxQueueingTimeoutMs != null) { - rule.setMaxQueueingTimeoutMs(maxQueueingTimeoutMs); - } + private Integer maxQueueingTimeoutMs; - if (paramItem != null) { - GatewayParamFlowItem ruleItem = new GatewayParamFlowItem(); - rule.setParamItem(ruleItem); - ruleItem.setParseStrategy(paramItem.getParseStrategy()); - ruleItem.setFieldName(paramItem.getFieldName()); - ruleItem.setPattern(paramItem.getPattern()); + private GatewayParamFlowItemEntity paramItem; - if (paramItem.getMatchStrategy() != null) { - ruleItem.setMatchStrategy(paramItem.getMatchStrategy()); - } - } + public static Long calIntervalSec(Long interval, Integer intervalUnit) { + switch (intervalUnit) { + case INTERVAL_UNIT_SECOND: + return interval; + case INTERVAL_UNIT_MINUTE: + return interval * 60; + case INTERVAL_UNIT_HOUR: + return interval * 60 * 60; + case INTERVAL_UNIT_DAY: + return interval * 60 * 60 * 24; + default: + break; + } - return rule; - } + throw new IllegalArgumentException("Invalid intervalUnit: " + intervalUnit); + } - public static GatewayFlowRuleEntity fromGatewayFlowRule(String app, String ip, Integer port, GatewayFlowRule rule) { - GatewayFlowRuleEntity entity = new GatewayFlowRuleEntity(); - entity.setApp(app); - entity.setIp(ip); - entity.setPort(port); + public static Object[] parseIntervalSec(Long intervalSec) { + if (intervalSec % (60 * 60 * 24) == 0) { + return new Object[] { intervalSec / (60 * 60 * 24), INTERVAL_UNIT_DAY }; + } - entity.setResource(rule.getResource()); - entity.setResourceMode(rule.getResourceMode()); + if (intervalSec % (60 * 60) == 0) { + return new Object[] { intervalSec / (60 * 60), INTERVAL_UNIT_HOUR }; + } - entity.setGrade(rule.getGrade()); - entity.setCount(rule.getCount()); - Object[] intervalSecResult = parseIntervalSec(rule.getIntervalSec()); - entity.setInterval((Long) intervalSecResult[0]); - entity.setIntervalUnit((Integer) intervalSecResult[1]); + if (intervalSec % 60 == 0) { + return new Object[] { intervalSec / 60, INTERVAL_UNIT_MINUTE }; + } - entity.setControlBehavior(rule.getControlBehavior()); - entity.setBurst(rule.getBurst()); - entity.setMaxQueueingTimeoutMs(rule.getMaxQueueingTimeoutMs()); + return new Object[] { intervalSec, INTERVAL_UNIT_SECOND }; + } - GatewayParamFlowItem paramItem = rule.getParamItem(); - if (paramItem != null) { - GatewayParamFlowItemEntity itemEntity = new GatewayParamFlowItemEntity(); - entity.setParamItem(itemEntity); - itemEntity.setParseStrategy(paramItem.getParseStrategy()); - itemEntity.setFieldName(paramItem.getFieldName()); - itemEntity.setPattern(paramItem.getPattern()); - itemEntity.setMatchStrategy(paramItem.getMatchStrategy()); - } + public GatewayFlowRule toGatewayFlowRule() { + GatewayFlowRule rule = new GatewayFlowRule(); + rule.setResource(resource); + rule.setResourceMode(resourceMode); - return entity; - } + rule.setGrade(grade); + rule.setCount(count); + rule.setIntervalSec(calIntervalSec(interval, intervalUnit)); - @Override - public Long getId() { - return id; - } + rule.setControlBehavior(controlBehavior); - @Override - public void setId(Long id) { - this.id = id; - } + if (burst != null) { + rule.setBurst(burst); + } - @Override - public String getApp() { - return app; - } + if (maxQueueingTimeoutMs != null) { + rule.setMaxQueueingTimeoutMs(maxQueueingTimeoutMs); + } - public void setApp(String app) { - this.app = app; - } + if (paramItem != null) { + GatewayParamFlowItem ruleItem = new GatewayParamFlowItem(); + rule.setParamItem(ruleItem); + ruleItem.setParseStrategy(paramItem.getParseStrategy()); + ruleItem.setFieldName(paramItem.getFieldName()); + ruleItem.setPattern(paramItem.getPattern()); - @Override - public String getIp() { - return ip; - } + if (paramItem.getMatchStrategy() != null) { + ruleItem.setMatchStrategy(paramItem.getMatchStrategy()); + } + } - public void setIp(String ip) { - this.ip = ip; - } + return rule; + } - @Override - public Integer getPort() { - return port; - } + public static GatewayFlowRuleEntity fromGatewayFlowRule(String app, String ip, Integer port, GatewayFlowRule rule) { + GatewayFlowRuleEntity entity = new GatewayFlowRuleEntity(); + entity.setApp(app); + entity.setIp(ip); + entity.setPort(port); - public void setPort(Integer port) { - this.port = port; - } + entity.setResource(rule.getResource()); + entity.setResourceMode(rule.getResourceMode()); - @Override - public Date getGmtCreate() { - return gmtCreate; - } + entity.setGrade(rule.getGrade()); + entity.setCount(rule.getCount()); + Object[] intervalSecResult = parseIntervalSec(rule.getIntervalSec()); + entity.setInterval((Long) intervalSecResult[0]); + entity.setIntervalUnit((Integer) intervalSecResult[1]); - public void setGmtCreate(Date gmtCreate) { - this.gmtCreate = gmtCreate; - } + entity.setControlBehavior(rule.getControlBehavior()); + entity.setBurst(rule.getBurst()); + entity.setMaxQueueingTimeoutMs(rule.getMaxQueueingTimeoutMs()); - @Override - public Rule toRule() { - return null; - } + GatewayParamFlowItem paramItem = rule.getParamItem(); + if (paramItem != null) { + GatewayParamFlowItemEntity itemEntity = new GatewayParamFlowItemEntity(); + entity.setParamItem(itemEntity); + itemEntity.setParseStrategy(paramItem.getParseStrategy()); + itemEntity.setFieldName(paramItem.getFieldName()); + itemEntity.setPattern(paramItem.getPattern()); + itemEntity.setMatchStrategy(paramItem.getMatchStrategy()); + } - public Date getGmtModified() { - return gmtModified; - } + return entity; + } - public void setGmtModified(Date gmtModified) { - this.gmtModified = gmtModified; - } + @Override + public Long getId() { + return id; + } - public GatewayParamFlowItemEntity getParamItem() { - return paramItem; - } + @Override + public void setId(Long id) { + this.id = id; + } - public void setParamItem(GatewayParamFlowItemEntity paramItem) { - this.paramItem = paramItem; - } + @Override + public String getApp() { + return app; + } - public String getResource() { - return resource; - } + public void setApp(String app) { + this.app = app; + } - public void setResource(String resource) { - this.resource = resource; - } + @Override + public String getIp() { + return ip; + } - public Integer getResourceMode() { - return resourceMode; - } + public void setIp(String ip) { + this.ip = ip; + } - public void setResourceMode(Integer resourceMode) { - this.resourceMode = resourceMode; - } + @Override + public Integer getPort() { + return port; + } - public Integer getGrade() { - return grade; - } + public void setPort(Integer port) { + this.port = port; + } - public void setGrade(Integer grade) { - this.grade = grade; - } + @Override + public Date getGmtCreate() { + return gmtCreate; + } - public Double getCount() { - return count; - } + public void setGmtCreate(Date gmtCreate) { + this.gmtCreate = gmtCreate; + } - public void setCount(Double count) { - this.count = count; - } + @Override + public Rule toRule() { + return null; + } - public Long getInterval() { - return interval; - } + public Date getGmtModified() { + return gmtModified; + } - public void setInterval(Long interval) { - this.interval = interval; - } + public void setGmtModified(Date gmtModified) { + this.gmtModified = gmtModified; + } - public Integer getIntervalUnit() { - return intervalUnit; - } + public GatewayParamFlowItemEntity getParamItem() { + return paramItem; + } - public void setIntervalUnit(Integer intervalUnit) { - this.intervalUnit = intervalUnit; - } + public void setParamItem(GatewayParamFlowItemEntity paramItem) { + this.paramItem = paramItem; + } - public Integer getControlBehavior() { - return controlBehavior; - } + public String getResource() { + return resource; + } - public void setControlBehavior(Integer controlBehavior) { - this.controlBehavior = controlBehavior; - } + public void setResource(String resource) { + this.resource = resource; + } - public Integer getBurst() { - return burst; - } + public Integer getResourceMode() { + return resourceMode; + } - public void setBurst(Integer burst) { - this.burst = burst; - } + public void setResourceMode(Integer resourceMode) { + this.resourceMode = resourceMode; + } - public Integer getMaxQueueingTimeoutMs() { - return maxQueueingTimeoutMs; - } + public Integer getGrade() { + return grade; + } - public void setMaxQueueingTimeoutMs(Integer maxQueueingTimeoutMs) { - this.maxQueueingTimeoutMs = maxQueueingTimeoutMs; - } + public void setGrade(Integer grade) { + this.grade = grade; + } - @Override - public boolean equals(Object o) { - if (this == o) { return true; } - if (o == null || getClass() != o.getClass()) { return false; } - GatewayFlowRuleEntity that = (GatewayFlowRuleEntity) o; - return Objects.equals(id, that.id) && - Objects.equals(app, that.app) && - Objects.equals(ip, that.ip) && - Objects.equals(port, that.port) && - Objects.equals(gmtCreate, that.gmtCreate) && - Objects.equals(gmtModified, that.gmtModified) && - Objects.equals(resource, that.resource) && - Objects.equals(resourceMode, that.resourceMode) && - Objects.equals(grade, that.grade) && - Objects.equals(count, that.count) && - Objects.equals(interval, that.interval) && - Objects.equals(intervalUnit, that.intervalUnit) && - Objects.equals(controlBehavior, that.controlBehavior) && - Objects.equals(burst, that.burst) && - Objects.equals(maxQueueingTimeoutMs, that.maxQueueingTimeoutMs) && - Objects.equals(paramItem, that.paramItem); - } + public Double getCount() { + return count; + } - @Override - public int hashCode() { - return Objects.hash(id, app, ip, port, gmtCreate, gmtModified, resource, resourceMode, grade, count, interval, intervalUnit, controlBehavior, burst, maxQueueingTimeoutMs, paramItem); - } + public void setCount(Double count) { + this.count = count; + } + + public Long getInterval() { + return interval; + } + + public void setInterval(Long interval) { + this.interval = interval; + } + + public Integer getIntervalUnit() { + return intervalUnit; + } + + public void setIntervalUnit(Integer intervalUnit) { + this.intervalUnit = intervalUnit; + } + + public Integer getControlBehavior() { + return controlBehavior; + } + + public void setControlBehavior(Integer controlBehavior) { + this.controlBehavior = controlBehavior; + } + + public Integer getBurst() { + return burst; + } + + public void setBurst(Integer burst) { + this.burst = burst; + } + + public Integer getMaxQueueingTimeoutMs() { + return maxQueueingTimeoutMs; + } + + public void setMaxQueueingTimeoutMs(Integer maxQueueingTimeoutMs) { + this.maxQueueingTimeoutMs = maxQueueingTimeoutMs; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + GatewayFlowRuleEntity that = (GatewayFlowRuleEntity) o; + return Objects.equals(id, that.id) && Objects.equals(app, that.app) && Objects.equals(ip, that.ip) + && Objects.equals(port, that.port) && Objects.equals(gmtCreate, that.gmtCreate) + && Objects.equals(gmtModified, that.gmtModified) && Objects.equals(resource, that.resource) + && Objects.equals(resourceMode, that.resourceMode) && Objects.equals(grade, that.grade) + && Objects.equals(count, that.count) && Objects.equals(interval, that.interval) + && Objects.equals(intervalUnit, that.intervalUnit) + && Objects.equals(controlBehavior, that.controlBehavior) && Objects.equals(burst, that.burst) + && Objects.equals(maxQueueingTimeoutMs, that.maxQueueingTimeoutMs) + && Objects.equals(paramItem, that.paramItem); + } + + @Override + public int hashCode() { + return Objects.hash(id, app, ip, port, gmtCreate, gmtModified, resource, resourceMode, grade, count, interval, + intervalUnit, controlBehavior, burst, maxQueueingTimeoutMs, paramItem); + } + + @Override + public String toString() { + return "GatewayFlowRuleEntity{" + "id=" + id + ", app='" + app + '\'' + ", ip='" + ip + '\'' + ", port=" + port + + ", gmtCreate=" + gmtCreate + ", gmtModified=" + gmtModified + ", resource='" + resource + '\'' + + ", resourceMode=" + resourceMode + ", grade=" + grade + ", count=" + count + ", interval=" + interval + + ", intervalUnit=" + intervalUnit + ", controlBehavior=" + controlBehavior + ", burst=" + burst + + ", maxQueueingTimeoutMs=" + maxQueueingTimeoutMs + ", paramItem=" + paramItem + '}'; + } - @Override - public String toString() { - return "GatewayFlowRuleEntity{" + - "id=" + id + - ", app='" + app + '\'' + - ", ip='" + ip + '\'' + - ", port=" + port + - ", gmtCreate=" + gmtCreate + - ", gmtModified=" + gmtModified + - ", resource='" + resource + '\'' + - ", resourceMode=" + resourceMode + - ", grade=" + grade + - ", count=" + count + - ", interval=" + interval + - ", intervalUnit=" + intervalUnit + - ", controlBehavior=" + controlBehavior + - ", burst=" + burst + - ", maxQueueingTimeoutMs=" + maxQueueingTimeoutMs + - ", paramItem=" + paramItem + - '}'; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/gateway/GatewayParamFlowItemEntity.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/gateway/GatewayParamFlowItemEntity.java index 4da71c8ec..2f36601ec 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/gateway/GatewayParamFlowItemEntity.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/gateway/GatewayParamFlowItemEntity.java @@ -27,69 +27,68 @@ import java.util.Objects; */ public class GatewayParamFlowItemEntity { - private Integer parseStrategy; + private Integer parseStrategy; - private String fieldName; + private String fieldName; - private String pattern; + private String pattern; - private Integer matchStrategy; + private Integer matchStrategy; - public Integer getParseStrategy() { - return parseStrategy; - } + public Integer getParseStrategy() { + return parseStrategy; + } - public void setParseStrategy(Integer parseStrategy) { - this.parseStrategy = parseStrategy; - } + public void setParseStrategy(Integer parseStrategy) { + this.parseStrategy = parseStrategy; + } - public String getFieldName() { - return fieldName; - } + public String getFieldName() { + return fieldName; + } - public void setFieldName(String fieldName) { - this.fieldName = fieldName; - } + public void setFieldName(String fieldName) { + this.fieldName = fieldName; + } - public String getPattern() { - return pattern; - } + public String getPattern() { + return pattern; + } - public void setPattern(String pattern) { - this.pattern = pattern; - } + public void setPattern(String pattern) { + this.pattern = pattern; + } - public Integer getMatchStrategy() { - return matchStrategy; - } + public Integer getMatchStrategy() { + return matchStrategy; + } - public void setMatchStrategy(Integer matchStrategy) { - this.matchStrategy = matchStrategy; - } + public void setMatchStrategy(Integer matchStrategy) { + this.matchStrategy = matchStrategy; + } - @Override - public boolean equals(Object o) { - if (this == o) { return true; } - if (o == null || getClass() != o.getClass()) { return false; } - GatewayParamFlowItemEntity that = (GatewayParamFlowItemEntity) o; - return Objects.equals(parseStrategy, that.parseStrategy) && - Objects.equals(fieldName, that.fieldName) && - Objects.equals(pattern, that.pattern) && - Objects.equals(matchStrategy, that.matchStrategy); - } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + GatewayParamFlowItemEntity that = (GatewayParamFlowItemEntity) o; + return Objects.equals(parseStrategy, that.parseStrategy) && Objects.equals(fieldName, that.fieldName) + && Objects.equals(pattern, that.pattern) && Objects.equals(matchStrategy, that.matchStrategy); + } - @Override - public int hashCode() { - return Objects.hash(parseStrategy, fieldName, pattern, matchStrategy); - } + @Override + public int hashCode() { + return Objects.hash(parseStrategy, fieldName, pattern, matchStrategy); + } + + @Override + public String toString() { + return "GatewayParamFlowItemEntity{" + "parseStrategy=" + parseStrategy + ", fieldName='" + fieldName + '\'' + + ", pattern='" + pattern + '\'' + ", matchStrategy=" + matchStrategy + '}'; + } - @Override - public String toString() { - return "GatewayParamFlowItemEntity{" + - "parseStrategy=" + parseStrategy + - ", fieldName='" + fieldName + '\'' + - ", pattern='" + pattern + '\'' + - ", matchStrategy=" + matchStrategy + - '}'; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/rule/AbstractRuleEntity.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/rule/AbstractRuleEntity.java index 6f60647dc..9e5213b36 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/rule/AbstractRuleEntity.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/rule/AbstractRuleEntity.java @@ -26,87 +26,91 @@ import com.alibaba.csp.sentinel.slots.block.Rule; */ public abstract class AbstractRuleEntity implements RuleEntity { - protected Long id; + protected Long id; - protected String app; - protected String ip; - protected Integer port; + protected String app; - protected T rule; + protected String ip; - private Date gmtCreate; - private Date gmtModified; + protected Integer port; - @Override - public Long getId() { - return id; - } + protected T rule; - @Override - public void setId(Long id) { - this.id = id; - } + private Date gmtCreate; - @Override - public String getApp() { - return app; - } + private Date gmtModified; - public AbstractRuleEntity setApp(String app) { - this.app = app; - return this; - } + @Override + public Long getId() { + return id; + } - @Override - public String getIp() { - return ip; - } + @Override + public void setId(Long id) { + this.id = id; + } - public AbstractRuleEntity setIp(String ip) { - this.ip = ip; - return this; - } + @Override + public String getApp() { + return app; + } - @Override - public Integer getPort() { - return port; - } + public AbstractRuleEntity setApp(String app) { + this.app = app; + return this; + } - public AbstractRuleEntity setPort(Integer port) { - this.port = port; - return this; - } + @Override + public String getIp() { + return ip; + } - public T getRule() { - return rule; - } + public AbstractRuleEntity setIp(String ip) { + this.ip = ip; + return this; + } - public AbstractRuleEntity setRule(T rule) { - this.rule = rule; - return this; - } + @Override + public Integer getPort() { + return port; + } - @Override - public Date getGmtCreate() { - return gmtCreate; - } + public AbstractRuleEntity setPort(Integer port) { + this.port = port; + return this; + } - public AbstractRuleEntity setGmtCreate(Date gmtCreate) { - this.gmtCreate = gmtCreate; - return this; - } + public T getRule() { + return rule; + } - public Date getGmtModified() { - return gmtModified; - } + public AbstractRuleEntity setRule(T rule) { + this.rule = rule; + return this; + } - public AbstractRuleEntity setGmtModified(Date gmtModified) { - this.gmtModified = gmtModified; - return this; - } + @Override + public Date getGmtCreate() { + return gmtCreate; + } + + public AbstractRuleEntity setGmtCreate(Date gmtCreate) { + this.gmtCreate = gmtCreate; + return this; + } + + public Date getGmtModified() { + return gmtModified; + } + + public AbstractRuleEntity setGmtModified(Date gmtModified) { + this.gmtModified = gmtModified; + return this; + } + + @Override + public T toRule() { + return rule; + } - @Override - public T toRule() { - return rule; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/rule/AuthorityRuleEntity.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/rule/AuthorityRuleEntity.java index a085d898b..a66cb9ad7 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/rule/AuthorityRuleEntity.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/rule/AuthorityRuleEntity.java @@ -26,37 +26,38 @@ import com.fasterxml.jackson.annotation.JsonIgnore; */ public class AuthorityRuleEntity extends AbstractRuleEntity { - public AuthorityRuleEntity() { - } + public AuthorityRuleEntity() { + } - public AuthorityRuleEntity(AuthorityRule authorityRule) { - AssertUtil.notNull(authorityRule, "Authority rule should not be null"); - this.rule = authorityRule; - } + public AuthorityRuleEntity(AuthorityRule authorityRule) { + AssertUtil.notNull(authorityRule, "Authority rule should not be null"); + this.rule = authorityRule; + } - public static AuthorityRuleEntity fromAuthorityRule(String app, String ip, Integer port, AuthorityRule rule) { - AuthorityRuleEntity entity = new AuthorityRuleEntity(rule); - entity.setApp(app); - entity.setIp(ip); - entity.setPort(port); - return entity; - } + public static AuthorityRuleEntity fromAuthorityRule(String app, String ip, Integer port, AuthorityRule rule) { + AuthorityRuleEntity entity = new AuthorityRuleEntity(rule); + entity.setApp(app); + entity.setIp(ip); + entity.setPort(port); + return entity; + } - @JsonIgnore - @JSONField(serialize = false) - public String getLimitApp() { - return rule.getLimitApp(); - } + @JsonIgnore + @JSONField(serialize = false) + public String getLimitApp() { + return rule.getLimitApp(); + } - @JsonIgnore - @JSONField(serialize = false) - public String getResource() { - return rule.getResource(); - } + @JsonIgnore + @JSONField(serialize = false) + public String getResource() { + return rule.getResource(); + } + + @JsonIgnore + @JSONField(serialize = false) + public int getStrategy() { + return rule.getStrategy(); + } - @JsonIgnore - @JSONField(serialize = false) - public int getStrategy() { - return rule.getStrategy(); - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/rule/DegradeRuleEntity.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/rule/DegradeRuleEntity.java index 2b86a373a..1aa2fc299 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/rule/DegradeRuleEntity.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/rule/DegradeRuleEntity.java @@ -23,136 +23,148 @@ import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule; * @author leyou */ public class DegradeRuleEntity implements RuleEntity { - private Long id; - private String app; - private String ip; - private Integer port; - private String resource; - private String limitApp; - private Double count; - private Integer timeWindow; - /** - * 0 rt 限流; 1为异常; - */ - private Integer grade; - private Date gmtCreate; - private Date gmtModified; - public static DegradeRuleEntity fromDegradeRule(String app, String ip, Integer port, DegradeRule rule) { - DegradeRuleEntity entity = new DegradeRuleEntity(); - entity.setApp(app); - entity.setIp(ip); - entity.setPort(port); - entity.setResource(rule.getResource()); - entity.setLimitApp(rule.getLimitApp()); - entity.setCount(rule.getCount()); - entity.setTimeWindow(rule.getTimeWindow()); - entity.setGrade(rule.getGrade()); - return entity; - } + private Long id; - @Override - public String getIp() { - return ip; - } + private String app; - public void setIp(String ip) { - this.ip = ip; - } + private String ip; - @Override - public Integer getPort() { - return port; - } + private Integer port; - public void setPort(Integer port) { - this.port = port; - } + private String resource; - @Override - public Long getId() { - return id; - } + private String limitApp; - @Override - public void setId(Long id) { - this.id = id; - } + private Double count; - @Override - public String getApp() { - return app; - } + private Integer timeWindow; - public void setApp(String app) { - this.app = app; - } + /** + * 0 rt 限流; 1为异常; + */ + private Integer grade; - public String getResource() { - return resource; - } + private Date gmtCreate; - public void setResource(String resource) { - this.resource = resource; - } + private Date gmtModified; - public String getLimitApp() { - return limitApp; - } + public static DegradeRuleEntity fromDegradeRule(String app, String ip, Integer port, DegradeRule rule) { + DegradeRuleEntity entity = new DegradeRuleEntity(); + entity.setApp(app); + entity.setIp(ip); + entity.setPort(port); + entity.setResource(rule.getResource()); + entity.setLimitApp(rule.getLimitApp()); + entity.setCount(rule.getCount()); + entity.setTimeWindow(rule.getTimeWindow()); + entity.setGrade(rule.getGrade()); + return entity; + } - public void setLimitApp(String limitApp) { - this.limitApp = limitApp; - } + @Override + public String getIp() { + return ip; + } - public Double getCount() { - return count; - } + public void setIp(String ip) { + this.ip = ip; + } - public void setCount(Double count) { - this.count = count; - } + @Override + public Integer getPort() { + return port; + } - public Integer getTimeWindow() { - return timeWindow; - } + public void setPort(Integer port) { + this.port = port; + } - public void setTimeWindow(Integer timeWindow) { - this.timeWindow = timeWindow; - } + @Override + public Long getId() { + return id; + } - public Integer getGrade() { - return grade; - } + @Override + public void setId(Long id) { + this.id = id; + } - public void setGrade(Integer grade) { - this.grade = grade; - } + @Override + public String getApp() { + return app; + } - @Override - public Date getGmtCreate() { - return gmtCreate; - } + public void setApp(String app) { + this.app = app; + } - public void setGmtCreate(Date gmtCreate) { - this.gmtCreate = gmtCreate; - } + public String getResource() { + return resource; + } - public Date getGmtModified() { - return gmtModified; - } + public void setResource(String resource) { + this.resource = resource; + } - public void setGmtModified(Date gmtModified) { - this.gmtModified = gmtModified; - } + public String getLimitApp() { + return limitApp; + } + + public void setLimitApp(String limitApp) { + this.limitApp = limitApp; + } + + public Double getCount() { + return count; + } + + public void setCount(Double count) { + this.count = count; + } + + public Integer getTimeWindow() { + return timeWindow; + } + + public void setTimeWindow(Integer timeWindow) { + this.timeWindow = timeWindow; + } + + public Integer getGrade() { + return grade; + } + + public void setGrade(Integer grade) { + this.grade = grade; + } + + @Override + public Date getGmtCreate() { + return gmtCreate; + } + + public void setGmtCreate(Date gmtCreate) { + this.gmtCreate = gmtCreate; + } + + public Date getGmtModified() { + return gmtModified; + } + + public void setGmtModified(Date gmtModified) { + this.gmtModified = gmtModified; + } + + @Override + public DegradeRule toRule() { + DegradeRule rule = new DegradeRule(); + rule.setResource(resource); + rule.setLimitApp(limitApp); + rule.setCount(count); + rule.setTimeWindow(timeWindow); + rule.setGrade(grade); + return rule; + } - @Override - public DegradeRule toRule() { - DegradeRule rule = new DegradeRule(); - rule.setResource(resource); - rule.setLimitApp(limitApp); - rule.setCount(count); - rule.setTimeWindow(timeWindow); - rule.setGrade(grade); - return rule; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/rule/FlowRuleEntity.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/rule/FlowRuleEntity.java index a076bd429..e7b4e7380 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/rule/FlowRuleEntity.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/rule/FlowRuleEntity.java @@ -25,225 +25,239 @@ import com.alibaba.csp.sentinel.slots.block.flow.FlowRule; */ public class FlowRuleEntity implements RuleEntity { - private Long id; - private String app; - private String ip; - private Integer port; - private String limitApp; - private String resource; - /** - * 0为线程数;1为qps - */ - private Integer grade; - private Double count; - /** - * 0为直接限流;1为关联限流;2为链路限流 - ***/ - private Integer strategy; - private String refResource; - /** - * 0. default, 1. warm up, 2. rate limiter - */ - private Integer controlBehavior; - private Integer warmUpPeriodSec; - /** - * max queueing time in rate limiter behavior - */ - private Integer maxQueueingTimeMs; + private Long id; - private boolean clusterMode; - /** - * Flow rule config for cluster mode. - */ - private ClusterFlowConfig clusterConfig; + private String app; - private Date gmtCreate; - private Date gmtModified; + private String ip; - public static FlowRuleEntity fromFlowRule(String app, String ip, Integer port, FlowRule rule) { - FlowRuleEntity entity = new FlowRuleEntity(); - entity.setApp(app); - entity.setIp(ip); - entity.setPort(port); - entity.setLimitApp(rule.getLimitApp()); - entity.setResource(rule.getResource()); - entity.setGrade(rule.getGrade()); - entity.setCount(rule.getCount()); - entity.setStrategy(rule.getStrategy()); - entity.setRefResource(rule.getRefResource()); - entity.setControlBehavior(rule.getControlBehavior()); - entity.setWarmUpPeriodSec(rule.getWarmUpPeriodSec()); - entity.setMaxQueueingTimeMs(rule.getMaxQueueingTimeMs()); - entity.setClusterMode(rule.isClusterMode()); - entity.setClusterConfig(rule.getClusterConfig()); - return entity; - } + private Integer port; - @Override - public String getIp() { - return ip; - } + private String limitApp; - public void setIp(String ip) { - this.ip = ip; - } + private String resource; - @Override - public Integer getPort() { - return port; - } + /** + * 0为线程数;1为qps + */ + private Integer grade; - public void setPort(Integer port) { - this.port = port; - } + private Double count; - @Override - public String getApp() { - return app; - } + /** + * 0为直接限流;1为关联限流;2为链路限流 + ***/ + private Integer strategy; - public void setApp(String app) { - this.app = app; - } + private String refResource; - @Override - public Long getId() { - return id; - } + /** + * 0. default, 1. warm up, 2. rate limiter + */ + private Integer controlBehavior; - @Override - public void setId(Long id) { - this.id = id; - } + private Integer warmUpPeriodSec; - public String getLimitApp() { - return limitApp; - } + /** + * max queueing time in rate limiter behavior + */ + private Integer maxQueueingTimeMs; - public void setLimitApp(String limitApp) { - this.limitApp = limitApp; - } + private boolean clusterMode; - public String getResource() { - return resource; - } + /** + * Flow rule config for cluster mode. + */ + private ClusterFlowConfig clusterConfig; - public void setResource(String resource) { - this.resource = resource; - } + private Date gmtCreate; - public Integer getGrade() { - return grade; - } + private Date gmtModified; - public void setGrade(Integer grade) { - this.grade = grade; - } + public static FlowRuleEntity fromFlowRule(String app, String ip, Integer port, FlowRule rule) { + FlowRuleEntity entity = new FlowRuleEntity(); + entity.setApp(app); + entity.setIp(ip); + entity.setPort(port); + entity.setLimitApp(rule.getLimitApp()); + entity.setResource(rule.getResource()); + entity.setGrade(rule.getGrade()); + entity.setCount(rule.getCount()); + entity.setStrategy(rule.getStrategy()); + entity.setRefResource(rule.getRefResource()); + entity.setControlBehavior(rule.getControlBehavior()); + entity.setWarmUpPeriodSec(rule.getWarmUpPeriodSec()); + entity.setMaxQueueingTimeMs(rule.getMaxQueueingTimeMs()); + entity.setClusterMode(rule.isClusterMode()); + entity.setClusterConfig(rule.getClusterConfig()); + return entity; + } - public Double getCount() { - return count; - } + @Override + public String getIp() { + return ip; + } - public void setCount(Double count) { - this.count = count; - } + public void setIp(String ip) { + this.ip = ip; + } - public Integer getStrategy() { - return strategy; - } + @Override + public Integer getPort() { + return port; + } - public void setStrategy(Integer strategy) { - this.strategy = strategy; - } + public void setPort(Integer port) { + this.port = port; + } - public String getRefResource() { - return refResource; - } + @Override + public String getApp() { + return app; + } - public void setRefResource(String refResource) { - this.refResource = refResource; - } + public void setApp(String app) { + this.app = app; + } - public Integer getControlBehavior() { - return controlBehavior; - } + @Override + public Long getId() { + return id; + } - public void setControlBehavior(Integer controlBehavior) { - this.controlBehavior = controlBehavior; - } + @Override + public void setId(Long id) { + this.id = id; + } - public Integer getWarmUpPeriodSec() { - return warmUpPeriodSec; - } + public String getLimitApp() { + return limitApp; + } - public void setWarmUpPeriodSec(Integer warmUpPeriodSec) { - this.warmUpPeriodSec = warmUpPeriodSec; - } + public void setLimitApp(String limitApp) { + this.limitApp = limitApp; + } - public Integer getMaxQueueingTimeMs() { - return maxQueueingTimeMs; - } + public String getResource() { + return resource; + } - public void setMaxQueueingTimeMs(Integer maxQueueingTimeMs) { - this.maxQueueingTimeMs = maxQueueingTimeMs; - } + public void setResource(String resource) { + this.resource = resource; + } - public boolean isClusterMode() { - return clusterMode; - } + public Integer getGrade() { + return grade; + } - public FlowRuleEntity setClusterMode(boolean clusterMode) { - this.clusterMode = clusterMode; - return this; - } + public void setGrade(Integer grade) { + this.grade = grade; + } - public ClusterFlowConfig getClusterConfig() { - return clusterConfig; - } + public Double getCount() { + return count; + } - public FlowRuleEntity setClusterConfig(ClusterFlowConfig clusterConfig) { - this.clusterConfig = clusterConfig; - return this; - } + public void setCount(Double count) { + this.count = count; + } - @Override - public Date getGmtCreate() { - return gmtCreate; - } + public Integer getStrategy() { + return strategy; + } - public void setGmtCreate(Date gmtCreate) { - this.gmtCreate = gmtCreate; - } + public void setStrategy(Integer strategy) { + this.strategy = strategy; + } - public Date getGmtModified() { - return gmtModified; - } + public String getRefResource() { + return refResource; + } - public void setGmtModified(Date gmtModified) { - this.gmtModified = gmtModified; - } + public void setRefResource(String refResource) { + this.refResource = refResource; + } - @Override - public FlowRule toRule() { - FlowRule flowRule = new FlowRule(); - flowRule.setCount(this.count); - flowRule.setGrade(this.grade); - flowRule.setResource(this.resource); - flowRule.setLimitApp(this.limitApp); - flowRule.setRefResource(this.refResource); - flowRule.setStrategy(this.strategy); - if (this.controlBehavior != null) { - flowRule.setControlBehavior(controlBehavior); - } - if (this.warmUpPeriodSec != null) { - flowRule.setWarmUpPeriodSec(warmUpPeriodSec); - } - if (this.maxQueueingTimeMs != null) { - flowRule.setMaxQueueingTimeMs(maxQueueingTimeMs); - } - flowRule.setClusterMode(clusterMode); - flowRule.setClusterConfig(clusterConfig); - return flowRule; - } + public Integer getControlBehavior() { + return controlBehavior; + } + + public void setControlBehavior(Integer controlBehavior) { + this.controlBehavior = controlBehavior; + } + + public Integer getWarmUpPeriodSec() { + return warmUpPeriodSec; + } + + public void setWarmUpPeriodSec(Integer warmUpPeriodSec) { + this.warmUpPeriodSec = warmUpPeriodSec; + } + + public Integer getMaxQueueingTimeMs() { + return maxQueueingTimeMs; + } + + public void setMaxQueueingTimeMs(Integer maxQueueingTimeMs) { + this.maxQueueingTimeMs = maxQueueingTimeMs; + } + + public boolean isClusterMode() { + return clusterMode; + } + + public FlowRuleEntity setClusterMode(boolean clusterMode) { + this.clusterMode = clusterMode; + return this; + } + + public ClusterFlowConfig getClusterConfig() { + return clusterConfig; + } + + public FlowRuleEntity setClusterConfig(ClusterFlowConfig clusterConfig) { + this.clusterConfig = clusterConfig; + return this; + } + + @Override + public Date getGmtCreate() { + return gmtCreate; + } + + public void setGmtCreate(Date gmtCreate) { + this.gmtCreate = gmtCreate; + } + + public Date getGmtModified() { + return gmtModified; + } + + public void setGmtModified(Date gmtModified) { + this.gmtModified = gmtModified; + } + + @Override + public FlowRule toRule() { + FlowRule flowRule = new FlowRule(); + flowRule.setCount(this.count); + flowRule.setGrade(this.grade); + flowRule.setResource(this.resource); + flowRule.setLimitApp(this.limitApp); + flowRule.setRefResource(this.refResource); + flowRule.setStrategy(this.strategy); + if (this.controlBehavior != null) { + flowRule.setControlBehavior(controlBehavior); + } + if (this.warmUpPeriodSec != null) { + flowRule.setWarmUpPeriodSec(warmUpPeriodSec); + } + if (this.maxQueueingTimeMs != null) { + flowRule.setMaxQueueingTimeMs(maxQueueingTimeMs); + } + flowRule.setClusterMode(clusterMode); + flowRule.setClusterConfig(clusterConfig); + return flowRule; + } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/rule/ParamFlowRuleEntity.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/rule/ParamFlowRuleEntity.java index 56bd773c0..b5a2977d9 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/rule/ParamFlowRuleEntity.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/rule/ParamFlowRuleEntity.java @@ -30,91 +30,92 @@ import java.util.List; */ public class ParamFlowRuleEntity extends AbstractRuleEntity { - public ParamFlowRuleEntity() { - } + public ParamFlowRuleEntity() { + } - public ParamFlowRuleEntity(ParamFlowRule rule) { - AssertUtil.notNull(rule, "Authority rule should not be null"); - this.rule = rule; - } + public ParamFlowRuleEntity(ParamFlowRule rule) { + AssertUtil.notNull(rule, "Authority rule should not be null"); + this.rule = rule; + } - public static ParamFlowRuleEntity fromAuthorityRule(String app, String ip, Integer port, ParamFlowRule rule) { - ParamFlowRuleEntity entity = new ParamFlowRuleEntity(rule); - entity.setApp(app); - entity.setIp(ip); - entity.setPort(port); - return entity; - } + public static ParamFlowRuleEntity fromAuthorityRule(String app, String ip, Integer port, ParamFlowRule rule) { + ParamFlowRuleEntity entity = new ParamFlowRuleEntity(rule); + entity.setApp(app); + entity.setIp(ip); + entity.setPort(port); + return entity; + } - @JsonIgnore - @JSONField(serialize = false) - public String getLimitApp() { - return rule.getLimitApp(); - } + @JsonIgnore + @JSONField(serialize = false) + public String getLimitApp() { + return rule.getLimitApp(); + } - @JsonIgnore - @JSONField(serialize = false) - public String getResource() { - return rule.getResource(); - } + @JsonIgnore + @JSONField(serialize = false) + public String getResource() { + return rule.getResource(); + } - @JsonIgnore - @JSONField(serialize = false) - public int getGrade() { - return rule.getGrade(); - } + @JsonIgnore + @JSONField(serialize = false) + public int getGrade() { + return rule.getGrade(); + } - @JsonIgnore - @JSONField(serialize = false) - public Integer getParamIdx() { - return rule.getParamIdx(); - } + @JsonIgnore + @JSONField(serialize = false) + public Integer getParamIdx() { + return rule.getParamIdx(); + } - @JsonIgnore - @JSONField(serialize = false) - public double getCount() { - return rule.getCount(); - } + @JsonIgnore + @JSONField(serialize = false) + public double getCount() { + return rule.getCount(); + } - @JsonIgnore - @JSONField(serialize = false) - public List getParamFlowItemList() { - return rule.getParamFlowItemList(); - } + @JsonIgnore + @JSONField(serialize = false) + public List getParamFlowItemList() { + return rule.getParamFlowItemList(); + } - @JsonIgnore - @JSONField(serialize = false) - public int getControlBehavior() { - return rule.getControlBehavior(); - } + @JsonIgnore + @JSONField(serialize = false) + public int getControlBehavior() { + return rule.getControlBehavior(); + } - @JsonIgnore - @JSONField(serialize = false) - public int getMaxQueueingTimeMs() { - return rule.getMaxQueueingTimeMs(); - } + @JsonIgnore + @JSONField(serialize = false) + public int getMaxQueueingTimeMs() { + return rule.getMaxQueueingTimeMs(); + } - @JsonIgnore - @JSONField(serialize = false) - public int getBurstCount() { - return rule.getBurstCount(); - } + @JsonIgnore + @JSONField(serialize = false) + public int getBurstCount() { + return rule.getBurstCount(); + } - @JsonIgnore - @JSONField(serialize = false) - public long getDurationInSec() { - return rule.getDurationInSec(); - } + @JsonIgnore + @JSONField(serialize = false) + public long getDurationInSec() { + return rule.getDurationInSec(); + } - @JsonIgnore - @JSONField(serialize = false) - public boolean isClusterMode() { - return rule.isClusterMode(); - } + @JsonIgnore + @JSONField(serialize = false) + public boolean isClusterMode() { + return rule.isClusterMode(); + } + + @JsonIgnore + @JSONField(serialize = false) + public ParamFlowClusterConfig getClusterConfig() { + return rule.getClusterConfig(); + } - @JsonIgnore - @JSONField(serialize = false) - public ParamFlowClusterConfig getClusterConfig() { - return rule.getClusterConfig(); - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/rule/RuleEntity.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/rule/RuleEntity.java index 0ad764fe3..40ac6a0e4 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/rule/RuleEntity.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/rule/RuleEntity.java @@ -24,17 +24,18 @@ import com.alibaba.csp.sentinel.slots.block.Rule; */ public interface RuleEntity { - Long getId(); + Long getId(); - void setId(Long id); + void setId(Long id); - String getApp(); + String getApp(); - String getIp(); + String getIp(); - Integer getPort(); + Integer getPort(); + + Date getGmtCreate(); + + Rule toRule(); - Date getGmtCreate(); - - Rule toRule(); } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/rule/SystemRuleEntity.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/rule/SystemRuleEntity.java index 483ebcb52..a147d3faa 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/rule/SystemRuleEntity.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/datasource/entity/rule/SystemRuleEntity.java @@ -24,135 +24,144 @@ import java.util.Date; */ public class SystemRuleEntity implements RuleEntity { - private Long id; + private Long id; - private String app; - private String ip; - private Integer port; - private Double highestSystemLoad; - private Long avgRt; - private Long maxThread; - private Double qps; - private Double highestCpuUsage; + private String app; - private Date gmtCreate; - private Date gmtModified; + private String ip; - public static SystemRuleEntity fromSystemRule(String app, String ip, Integer port, SystemRule rule) { - SystemRuleEntity entity = new SystemRuleEntity(); - entity.setApp(app); - entity.setIp(ip); - entity.setPort(port); - entity.setHighestSystemLoad(rule.getHighestSystemLoad()); - entity.setHighestCpuUsage(rule.getHighestCpuUsage()); - entity.setAvgRt(rule.getAvgRt()); - entity.setMaxThread(rule.getMaxThread()); - entity.setQps(rule.getQps()); - return entity; - } + private Integer port; - @Override - public String getIp() { - return ip; - } + private Double highestSystemLoad; - public void setIp(String ip) { - this.ip = ip; - } + private Long avgRt; - @Override - public Integer getPort() { - return port; - } + private Long maxThread; - public void setPort(Integer port) { - this.port = port; - } + private Double qps; - @Override - public Long getId() { - return id; - } + private Double highestCpuUsage; - @Override - public void setId(Long id) { - this.id = id; - } + private Date gmtCreate; - @Override - public String getApp() { - return app; - } + private Date gmtModified; - public void setApp(String app) { - this.app = app; - } + public static SystemRuleEntity fromSystemRule(String app, String ip, Integer port, SystemRule rule) { + SystemRuleEntity entity = new SystemRuleEntity(); + entity.setApp(app); + entity.setIp(ip); + entity.setPort(port); + entity.setHighestSystemLoad(rule.getHighestSystemLoad()); + entity.setHighestCpuUsage(rule.getHighestCpuUsage()); + entity.setAvgRt(rule.getAvgRt()); + entity.setMaxThread(rule.getMaxThread()); + entity.setQps(rule.getQps()); + return entity; + } - public Double getHighestSystemLoad() { - return highestSystemLoad; - } + @Override + public String getIp() { + return ip; + } - public void setHighestSystemLoad(Double highestSystemLoad) { - this.highestSystemLoad = highestSystemLoad; - } + public void setIp(String ip) { + this.ip = ip; + } - public Long getAvgRt() { - return avgRt; - } + @Override + public Integer getPort() { + return port; + } - public void setAvgRt(Long avgRt) { - this.avgRt = avgRt; - } + public void setPort(Integer port) { + this.port = port; + } - public Long getMaxThread() { - return maxThread; - } + @Override + public Long getId() { + return id; + } - public void setMaxThread(Long maxThread) { - this.maxThread = maxThread; - } + @Override + public void setId(Long id) { + this.id = id; + } - public Double getQps() { - return qps; - } + @Override + public String getApp() { + return app; + } - public void setQps(Double qps) { - this.qps = qps; - } + public void setApp(String app) { + this.app = app; + } - public Double getHighestCpuUsage() { - return highestCpuUsage; - } + public Double getHighestSystemLoad() { + return highestSystemLoad; + } - public void setHighestCpuUsage(Double highestCpuUsage) { - this.highestCpuUsage = highestCpuUsage; - } + public void setHighestSystemLoad(Double highestSystemLoad) { + this.highestSystemLoad = highestSystemLoad; + } - @Override - public Date getGmtCreate() { - return gmtCreate; - } + public Long getAvgRt() { + return avgRt; + } - public void setGmtCreate(Date gmtCreate) { - this.gmtCreate = gmtCreate; - } + public void setAvgRt(Long avgRt) { + this.avgRt = avgRt; + } - public Date getGmtModified() { - return gmtModified; - } + public Long getMaxThread() { + return maxThread; + } - public void setGmtModified(Date gmtModified) { - this.gmtModified = gmtModified; - } + public void setMaxThread(Long maxThread) { + this.maxThread = maxThread; + } + + public Double getQps() { + return qps; + } + + public void setQps(Double qps) { + this.qps = qps; + } + + public Double getHighestCpuUsage() { + return highestCpuUsage; + } + + public void setHighestCpuUsage(Double highestCpuUsage) { + this.highestCpuUsage = highestCpuUsage; + } + + @Override + public Date getGmtCreate() { + return gmtCreate; + } + + public void setGmtCreate(Date gmtCreate) { + this.gmtCreate = gmtCreate; + } + + public Date getGmtModified() { + return gmtModified; + } + + public void setGmtModified(Date gmtModified) { + this.gmtModified = gmtModified; + } + + @Override + public SystemRule toRule() { + SystemRule rule = new SystemRule(); + rule.setHighestSystemLoad(highestSystemLoad); + rule.setAvgRt(avgRt); + rule.setMaxThread(maxThread); + rule.setQps(qps); + rule.setHighestCpuUsage(highestCpuUsage); + return rule; + } - @Override - public SystemRule toRule() { - SystemRule rule = new SystemRule(); - rule.setHighestSystemLoad(highestSystemLoad); - rule.setAvgRt(avgRt); - rule.setMaxThread(maxThread); - rule.setQps(qps); - rule.setHighestCpuUsage(highestCpuUsage); - return rule; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/discovery/AppInfo.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/discovery/AppInfo.java index f7697698c..3c69fd8b5 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/discovery/AppInfo.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/discovery/AppInfo.java @@ -26,110 +26,104 @@ import com.alibaba.csp.sentinel.dashboard.config.DashboardConfig; public class AppInfo { - private String app = ""; + private String app = ""; - private Integer appType = 0; + private Integer appType = 0; - private Set machines = ConcurrentHashMap.newKeySet(); + private Set machines = ConcurrentHashMap.newKeySet(); - public AppInfo() {} + public AppInfo() { + } - public AppInfo(String app) { - this.app = app; - } + public AppInfo(String app) { + this.app = app; + } - public AppInfo(String app, Integer appType) { - this.app = app; - this.appType = appType; - } + public AppInfo(String app, Integer appType) { + this.app = app; + this.appType = appType; + } - public String getApp() { - return app; - } + public String getApp() { + return app; + } - public void setApp(String app) { - this.app = app; - } + public void setApp(String app) { + this.app = app; + } - public Integer getAppType() { - return appType; - } + public Integer getAppType() { + return appType; + } - public void setAppType(Integer appType) { - this.appType = appType; - } + public void setAppType(Integer appType) { + this.appType = appType; + } - /** - * Get the current machines. - * - * @return a new copy of the current machines. - */ - public Set getMachines() { - return new HashSet<>(machines); - } + /** + * Get the current machines. + * @return a new copy of the current machines. + */ + public Set getMachines() { + return new HashSet<>(machines); + } - @Override - public String toString() { - return "AppInfo{" + "app='" + app + ", machines=" + machines + '}'; - } + @Override + public String toString() { + return "AppInfo{" + "app='" + app + ", machines=" + machines + '}'; + } - public boolean addMachine(MachineInfo machineInfo) { - machines.remove(machineInfo); - return machines.add(machineInfo); - } + public boolean addMachine(MachineInfo machineInfo) { + machines.remove(machineInfo); + return machines.add(machineInfo); + } - public synchronized boolean removeMachine(String ip, int port) { - Iterator it = machines.iterator(); - while (it.hasNext()) { - MachineInfo machine = it.next(); - if (machine.getIp().equals(ip) && machine.getPort() == port) { - it.remove(); - return true; - } - } - return false; - } + public synchronized boolean removeMachine(String ip, int port) { + Iterator it = machines.iterator(); + while (it.hasNext()) { + MachineInfo machine = it.next(); + if (machine.getIp().equals(ip) && machine.getPort() == port) { + it.remove(); + return true; + } + } + return false; + } - public Optional getMachine(String ip, int port) { - return machines.stream() - .filter(e -> e.getIp().equals(ip) && e.getPort().equals(port)) - .findFirst(); - } + public Optional getMachine(String ip, int port) { + return machines.stream().filter(e -> e.getIp().equals(ip) && e.getPort().equals(port)).findFirst(); + } - private boolean heartbeatJudge(final int threshold) { - if (machines.size() == 0) { - return false; - } - if (threshold > 0) { - long healthyCount = machines.stream() - .filter(MachineInfo::isHealthy) - .count(); - if (healthyCount == 0) { - // No healthy machines. - return machines.stream() - .max(Comparator.comparingLong(MachineInfo::getLastHeartbeat)) - .map(e -> System.currentTimeMillis() - e.getLastHeartbeat() < threshold) - .orElse(false); - } - } - return true; - } + private boolean heartbeatJudge(final int threshold) { + if (machines.size() == 0) { + return false; + } + if (threshold > 0) { + long healthyCount = machines.stream().filter(MachineInfo::isHealthy).count(); + if (healthyCount == 0) { + // No healthy machines. + return machines.stream().max(Comparator.comparingLong(MachineInfo::getLastHeartbeat)) + .map(e -> System.currentTimeMillis() - e.getLastHeartbeat() < threshold).orElse(false); + } + } + return true; + } - /** - * Check whether current application has no healthy machines and should not be displayed. - * - * @return true if the application should be displayed in the sidebar, otherwise false - */ - public boolean isShown() { - return heartbeatJudge(DashboardConfig.getHideAppNoMachineMillis()); - } + /** + * Check whether current application has no healthy machines and should not be + * displayed. + * @return true if the application should be displayed in the sidebar, otherwise false + */ + public boolean isShown() { + return heartbeatJudge(DashboardConfig.getHideAppNoMachineMillis()); + } + + /** + * Check whether current application has no healthy machines and should be removed. + * @return true if the application is dead and should be removed, otherwise false + */ + public boolean isDead() { + return !heartbeatJudge(DashboardConfig.getRemoveAppNoMachineMillis()); + } - /** - * Check whether current application has no healthy machines and should be removed. - * - * @return true if the application is dead and should be removed, otherwise false - */ - public boolean isDead() { - return !heartbeatJudge(DashboardConfig.getRemoveAppNoMachineMillis()); - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/discovery/AppManagement.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/discovery/AppManagement.java index 9e44336f1..79f4ad248 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/discovery/AppManagement.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/discovery/AppManagement.java @@ -27,44 +27,44 @@ import org.springframework.stereotype.Component; @Component public class AppManagement implements MachineDiscovery { - @Autowired - private ApplicationContext context; + @Autowired + private ApplicationContext context; - private MachineDiscovery machineDiscovery; + private MachineDiscovery machineDiscovery; - @PostConstruct - public void init() { - machineDiscovery = context.getBean(SimpleMachineDiscovery.class); - } + @PostConstruct + public void init() { + machineDiscovery = context.getBean(SimpleMachineDiscovery.class); + } - @Override - public Set getBriefApps() { - return machineDiscovery.getBriefApps(); - } + @Override + public Set getBriefApps() { + return machineDiscovery.getBriefApps(); + } - @Override - public long addMachine(MachineInfo machineInfo) { - return machineDiscovery.addMachine(machineInfo); - } - - @Override - public boolean removeMachine(String app, String ip, int port) { - return machineDiscovery.removeMachine(app, ip, port); - } + @Override + public long addMachine(MachineInfo machineInfo) { + return machineDiscovery.addMachine(machineInfo); + } - @Override - public List getAppNames() { - return machineDiscovery.getAppNames(); - } + @Override + public boolean removeMachine(String app, String ip, int port) { + return machineDiscovery.removeMachine(app, ip, port); + } - @Override - public AppInfo getDetailApp(String app) { - return machineDiscovery.getDetailApp(app); - } - - @Override - public void removeApp(String app) { - machineDiscovery.removeApp(app); - } + @Override + public List getAppNames() { + return machineDiscovery.getAppNames(); + } + + @Override + public AppInfo getDetailApp(String app) { + return machineDiscovery.getDetailApp(app); + } + + @Override + public void removeApp(String app) { + machineDiscovery.removeApp(app); + } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/discovery/MachineDiscovery.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/discovery/MachineDiscovery.java index 260b0d8c3..454e55a26 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/discovery/MachineDiscovery.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/discovery/MachineDiscovery.java @@ -20,32 +20,31 @@ import java.util.Set; public interface MachineDiscovery { - String UNKNOWN_APP_NAME = "CLUSTER_NOT_STARTED"; + String UNKNOWN_APP_NAME = "CLUSTER_NOT_STARTED"; - List getAppNames(); + List getAppNames(); - Set getBriefApps(); + Set getBriefApps(); - AppInfo getDetailApp(String app); + AppInfo getDetailApp(String app); - /** - * Remove the given app from the application registry. - * - * @param app application name - * @since 1.5.0 - */ - void removeApp(String app); + /** + * Remove the given app from the application registry. + * @param app application name + * @since 1.5.0 + */ + void removeApp(String app); - long addMachine(MachineInfo machineInfo); + long addMachine(MachineInfo machineInfo); + + /** + * Remove the given machine instance from the application registry. + * @param app the application name of the machine + * @param ip machine IP + * @param port machine port + * @return true if removed, otherwise false + * @since 1.5.0 + */ + boolean removeMachine(String app, String ip, int port); - /** - * Remove the given machine instance from the application registry. - * - * @param app the application name of the machine - * @param ip machine IP - * @param port machine port - * @return true if removed, otherwise false - * @since 1.5.0 - */ - boolean removeMachine(String app, String ip, int port); } \ No newline at end of file diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/discovery/MachineInfo.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/discovery/MachineInfo.java index afcc81243..8d390180f 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/discovery/MachineInfo.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/discovery/MachineInfo.java @@ -22,164 +22,165 @@ import com.alibaba.csp.sentinel.util.StringUtil; public class MachineInfo implements Comparable { - private String app = ""; - private Integer appType = 0; - private String hostname = ""; - private String ip = ""; - private Integer port = -1; - private long lastHeartbeat; - private long heartbeatVersion; + private String app = ""; - /** - * Indicates the version of Sentinel client (since 0.2.0). - */ - private String version; + private Integer appType = 0; - public static MachineInfo of(String app, String ip, Integer port) { - MachineInfo machineInfo = new MachineInfo(); - machineInfo.setApp(app); - machineInfo.setIp(ip); - machineInfo.setPort(port); - return machineInfo; - } + private String hostname = ""; - public String toHostPort() { - return ip + ":" + port; - } + private String ip = ""; - public Integer getPort() { - return port; - } + private Integer port = -1; - public void setPort(Integer port) { - this.port = port; - } + private long lastHeartbeat; - public String getApp() { - return app; - } + private long heartbeatVersion; - public void setApp(String app) { - this.app = app; - } + /** + * Indicates the version of Sentinel client (since 0.2.0). + */ + private String version; - public Integer getAppType() { - return appType; - } + public static MachineInfo of(String app, String ip, Integer port) { + MachineInfo machineInfo = new MachineInfo(); + machineInfo.setApp(app); + machineInfo.setIp(ip); + machineInfo.setPort(port); + return machineInfo; + } - public void setAppType(Integer appType) { - this.appType = appType; - } + public String toHostPort() { + return ip + ":" + port; + } - public String getHostname() { - return hostname; - } + public Integer getPort() { + return port; + } - public void setHostname(String hostname) { - this.hostname = hostname; - } + public void setPort(Integer port) { + this.port = port; + } - public String getIp() { - return ip; - } + public String getApp() { + return app; + } - public void setIp(String ip) { - this.ip = ip; - } + public void setApp(String app) { + this.app = app; + } - public long getHeartbeatVersion() { - return heartbeatVersion; - } - - public void setHeartbeatVersion(long heartbeatVersion) { - this.heartbeatVersion = heartbeatVersion; - } + public Integer getAppType() { + return appType; + } - public String getVersion() { - return version; - } + public void setAppType(Integer appType) { + this.appType = appType; + } - public MachineInfo setVersion(String version) { - this.version = version; - return this; - } - - public boolean isHealthy() { - long delta = System.currentTimeMillis() - lastHeartbeat; - return delta < DashboardConfig.getUnhealthyMachineMillis(); - } - - /** - * whether dead should be removed - * - * @return - */ - public boolean isDead() { - if (DashboardConfig.getAutoRemoveMachineMillis() > 0) { - long delta = System.currentTimeMillis() - lastHeartbeat; - return delta > DashboardConfig.getAutoRemoveMachineMillis(); - } - return false; - } - - public long getLastHeartbeat() { - return lastHeartbeat; - } - - public void setLastHeartbeat(long lastHeartbeat) { - this.lastHeartbeat = lastHeartbeat; - } + public String getHostname() { + return hostname; + } - @Override - public int compareTo(MachineInfo o) { - if (this == o) { - return 0; - } - if (!port.equals(o.getPort())) { - return port.compareTo(o.getPort()); - } - if (!StringUtil.equals(app, o.getApp())) { - return app.compareToIgnoreCase(o.getApp()); - } - return ip.compareToIgnoreCase(o.getIp()); - } + public void setHostname(String hostname) { + this.hostname = hostname; + } - @Override - public String toString() { - return new StringBuilder("MachineInfo {") - .append("app='").append(app).append('\'') - .append(",appType='").append(appType).append('\'') - .append(", hostname='").append(hostname).append('\'') - .append(", ip='").append(ip).append('\'') - .append(", port=").append(port) - .append(", heartbeatVersion=").append(heartbeatVersion) - .append(", lastHeartbeat=").append(lastHeartbeat) - .append(", version='").append(version).append('\'') - .append(", healthy=").append(isHealthy()) - .append('}').toString(); - } + public String getIp() { + return ip; + } - @Override - public boolean equals(Object o) { - if (this == o) { return true; } - if (!(o instanceof MachineInfo)) { return false; } - MachineInfo that = (MachineInfo)o; - return Objects.equals(app, that.app) && - Objects.equals(ip, that.ip) && - Objects.equals(port, that.port); - } + public void setIp(String ip) { + this.ip = ip; + } - @Override - public int hashCode() { - return Objects.hash(app, ip, port); - } + public long getHeartbeatVersion() { + return heartbeatVersion; + } + + public void setHeartbeatVersion(long heartbeatVersion) { + this.heartbeatVersion = heartbeatVersion; + } + + public String getVersion() { + return version; + } + + public MachineInfo setVersion(String version) { + this.version = version; + return this; + } + + public boolean isHealthy() { + long delta = System.currentTimeMillis() - lastHeartbeat; + return delta < DashboardConfig.getUnhealthyMachineMillis(); + } + + /** + * whether dead should be removed + * @return + */ + public boolean isDead() { + if (DashboardConfig.getAutoRemoveMachineMillis() > 0) { + long delta = System.currentTimeMillis() - lastHeartbeat; + return delta > DashboardConfig.getAutoRemoveMachineMillis(); + } + return false; + } + + public long getLastHeartbeat() { + return lastHeartbeat; + } + + public void setLastHeartbeat(long lastHeartbeat) { + this.lastHeartbeat = lastHeartbeat; + } + + @Override + public int compareTo(MachineInfo o) { + if (this == o) { + return 0; + } + if (!port.equals(o.getPort())) { + return port.compareTo(o.getPort()); + } + if (!StringUtil.equals(app, o.getApp())) { + return app.compareToIgnoreCase(o.getApp()); + } + return ip.compareToIgnoreCase(o.getIp()); + } + + @Override + public String toString() { + return new StringBuilder("MachineInfo {").append("app='").append(app).append('\'').append(",appType='") + .append(appType).append('\'').append(", hostname='").append(hostname).append('\'').append(", ip='") + .append(ip).append('\'').append(", port=").append(port).append(", heartbeatVersion=") + .append(heartbeatVersion).append(", lastHeartbeat=").append(lastHeartbeat).append(", version='") + .append(version).append('\'').append(", healthy=").append(isHealthy()).append('}').toString(); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof MachineInfo)) { + return false; + } + MachineInfo that = (MachineInfo) o; + return Objects.equals(app, that.app) && Objects.equals(ip, that.ip) && Objects.equals(port, that.port); + } + + @Override + public int hashCode() { + return Objects.hash(app, ip, port); + } + + /** + * Information for log + * @return + */ + public String toLogString() { + return app + "|" + ip + "|" + port + "|" + version; + } - /** - * Information for log - * - * @return - */ - public String toLogString() { - return app + "|" + ip + "|" + port + "|" + version; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/discovery/SimpleMachineDiscovery.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/discovery/SimpleMachineDiscovery.java index a4ab83acd..f437358c8 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/discovery/SimpleMachineDiscovery.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/discovery/SimpleMachineDiscovery.java @@ -32,46 +32,47 @@ import org.springframework.stereotype.Component; @Component public class SimpleMachineDiscovery implements MachineDiscovery { - private final ConcurrentMap apps = new ConcurrentHashMap<>(); + private final ConcurrentMap apps = new ConcurrentHashMap<>(); - @Override - public long addMachine(MachineInfo machineInfo) { - AssertUtil.notNull(machineInfo, "machineInfo cannot be null"); - AppInfo appInfo = apps.computeIfAbsent(machineInfo.getApp(), o -> new AppInfo(machineInfo.getApp(), machineInfo.getAppType())); - appInfo.addMachine(machineInfo); - return 1; - } + @Override + public long addMachine(MachineInfo machineInfo) { + AssertUtil.notNull(machineInfo, "machineInfo cannot be null"); + AppInfo appInfo = apps.computeIfAbsent(machineInfo.getApp(), + o -> new AppInfo(machineInfo.getApp(), machineInfo.getAppType())); + appInfo.addMachine(machineInfo); + return 1; + } - @Override - public boolean removeMachine(String app, String ip, int port) { - AssertUtil.assertNotBlank(app, "app name cannot be blank"); - AppInfo appInfo = apps.get(app); - if (appInfo != null) { - return appInfo.removeMachine(ip, port); - } - return false; - } + @Override + public boolean removeMachine(String app, String ip, int port) { + AssertUtil.assertNotBlank(app, "app name cannot be blank"); + AppInfo appInfo = apps.get(app); + if (appInfo != null) { + return appInfo.removeMachine(ip, port); + } + return false; + } - @Override - public List getAppNames() { - return new ArrayList<>(apps.keySet()); - } + @Override + public List getAppNames() { + return new ArrayList<>(apps.keySet()); + } - @Override - public AppInfo getDetailApp(String app) { - AssertUtil.assertNotBlank(app, "app name cannot be blank"); - return apps.get(app); - } + @Override + public AppInfo getDetailApp(String app) { + AssertUtil.assertNotBlank(app, "app name cannot be blank"); + return apps.get(app); + } - @Override - public Set getBriefApps() { - return new HashSet<>(apps.values()); - } + @Override + public Set getBriefApps() { + return new HashSet<>(apps.values()); + } - @Override - public void removeApp(String app) { - AssertUtil.assertNotBlank(app, "app name cannot be blank"); - apps.remove(app); - } + @Override + public void removeApp(String app) { + AssertUtil.assertNotBlank(app, "app name cannot be blank"); + apps.remove(app); + } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/ResourceTreeNode.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/ResourceTreeNode.java index be576160c..eb289c813 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/ResourceTreeNode.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/ResourceTreeNode.java @@ -26,217 +26,232 @@ import com.alibaba.csp.sentinel.command.vo.NodeVo; * @author leyou */ public class ResourceTreeNode { - private String id; - private String parentId; - private String resource; - private Integer threadNum; - private Long passQps; - private Long blockQps; - private Long totalQps; - private Long averageRt; - private Long successQps; - private Long exceptionQps; - private Long oneMinutePass; - private Long oneMinuteBlock; - private Long oneMinuteException; - private Long oneMinuteTotal; + private String id; - private boolean visible = true; + private String parentId; - private List children = new ArrayList<>(); + private String resource; - public static ResourceTreeNode fromNodeVoList(List nodeVos) { - if (nodeVos == null || nodeVos.isEmpty()) { - return null; - } - ResourceTreeNode root = null; - Map map = new HashMap<>(); - for (NodeVo vo : nodeVos) { - ResourceTreeNode node = fromNodeVo(vo); - map.put(node.id, node); - // real root - if (node.parentId == null || node.parentId.isEmpty()) { - root = node; - } else if (map.containsKey(node.parentId)) { - map.get(node.parentId).children.add(node); - } else { - // impossible - } - } - return root; - } + private Integer threadNum; - public static ResourceTreeNode fromNodeVo(NodeVo vo) { - ResourceTreeNode node = new ResourceTreeNode(); - node.id = vo.getId(); - node.parentId = vo.getParentId(); - node.resource = vo.getResource(); - node.threadNum = vo.getThreadNum(); - node.passQps = vo.getPassQps(); - node.blockQps = vo.getBlockQps(); - node.totalQps = vo.getTotalQps(); - node.averageRt = vo.getAverageRt(); - node.successQps = vo.getSuccessQps(); - node.exceptionQps = vo.getExceptionQps(); - node.oneMinutePass = vo.getOneMinutePass(); - node.oneMinuteBlock = vo.getOneMinuteBlock(); - node.oneMinuteException = vo.getOneMinuteException(); - node.oneMinuteTotal = vo.getOneMinuteTotal(); - return node; - } + private Long passQps; - public void searchIgnoreCase(String searchKey) { - search(this, searchKey); - } + private Long blockQps; - /** - * This node is visible only when searchKey matches this.resource or at least - * one of this's children is visible - */ - private boolean search(ResourceTreeNode node, String searchKey) { - // empty matches all - if (searchKey == null || searchKey.isEmpty() || - node.resource.toLowerCase().contains(searchKey.toLowerCase())) { - node.visible = true; - } else { - node.visible = false; - } + private Long totalQps; - boolean found = false; - for (ResourceTreeNode c : node.children) { - found |= search(c, searchKey); - } - node.visible |= found; - return node.visible; - } + private Long averageRt; - public String getId() { - return id; - } + private Long successQps; - public void setId(String id) { - this.id = id; - } + private Long exceptionQps; - public String getParentId() { - return parentId; - } + private Long oneMinutePass; - public void setParentId(String parentId) { - this.parentId = parentId; - } + private Long oneMinuteBlock; - public String getResource() { - return resource; - } + private Long oneMinuteException; - public void setResource(String resource) { - this.resource = resource; - } + private Long oneMinuteTotal; - public Integer getThreadNum() { - return threadNum; - } + private boolean visible = true; - public void setThreadNum(Integer threadNum) { - this.threadNum = threadNum; - } + private List children = new ArrayList<>(); - public Long getPassQps() { - return passQps; - } + public static ResourceTreeNode fromNodeVoList(List nodeVos) { + if (nodeVos == null || nodeVos.isEmpty()) { + return null; + } + ResourceTreeNode root = null; + Map map = new HashMap<>(); + for (NodeVo vo : nodeVos) { + ResourceTreeNode node = fromNodeVo(vo); + map.put(node.id, node); + // real root + if (node.parentId == null || node.parentId.isEmpty()) { + root = node; + } + else if (map.containsKey(node.parentId)) { + map.get(node.parentId).children.add(node); + } + else { + // impossible + } + } + return root; + } - public void setPassQps(Long passQps) { - this.passQps = passQps; - } + public static ResourceTreeNode fromNodeVo(NodeVo vo) { + ResourceTreeNode node = new ResourceTreeNode(); + node.id = vo.getId(); + node.parentId = vo.getParentId(); + node.resource = vo.getResource(); + node.threadNum = vo.getThreadNum(); + node.passQps = vo.getPassQps(); + node.blockQps = vo.getBlockQps(); + node.totalQps = vo.getTotalQps(); + node.averageRt = vo.getAverageRt(); + node.successQps = vo.getSuccessQps(); + node.exceptionQps = vo.getExceptionQps(); + node.oneMinutePass = vo.getOneMinutePass(); + node.oneMinuteBlock = vo.getOneMinuteBlock(); + node.oneMinuteException = vo.getOneMinuteException(); + node.oneMinuteTotal = vo.getOneMinuteTotal(); + return node; + } - public Long getBlockQps() { - return blockQps; - } + public void searchIgnoreCase(String searchKey) { + search(this, searchKey); + } - public void setBlockQps(Long blockQps) { - this.blockQps = blockQps; - } + /** + * This node is visible only when searchKey matches this.resource or at least one of + * this's children is visible + */ + private boolean search(ResourceTreeNode node, String searchKey) { + // empty matches all + if (searchKey == null || searchKey.isEmpty() || node.resource.toLowerCase().contains(searchKey.toLowerCase())) { + node.visible = true; + } + else { + node.visible = false; + } - public Long getTotalQps() { - return totalQps; - } + boolean found = false; + for (ResourceTreeNode c : node.children) { + found |= search(c, searchKey); + } + node.visible |= found; + return node.visible; + } - public void setTotalQps(Long totalQps) { - this.totalQps = totalQps; - } + public String getId() { + return id; + } - public Long getAverageRt() { - return averageRt; - } + public void setId(String id) { + this.id = id; + } - public void setAverageRt(Long averageRt) { - this.averageRt = averageRt; - } + public String getParentId() { + return parentId; + } - public Long getSuccessQps() { - return successQps; - } + public void setParentId(String parentId) { + this.parentId = parentId; + } - public void setSuccessQps(Long successQps) { - this.successQps = successQps; - } + public String getResource() { + return resource; + } - public Long getExceptionQps() { - return exceptionQps; - } + public void setResource(String resource) { + this.resource = resource; + } - public void setExceptionQps(Long exceptionQps) { - this.exceptionQps = exceptionQps; - } + public Integer getThreadNum() { + return threadNum; + } - public Long getOneMinutePass() { - return oneMinutePass; - } + public void setThreadNum(Integer threadNum) { + this.threadNum = threadNum; + } - public void setOneMinutePass(Long oneMinutePass) { - this.oneMinutePass = oneMinutePass; - } + public Long getPassQps() { + return passQps; + } - public Long getOneMinuteBlock() { - return oneMinuteBlock; - } + public void setPassQps(Long passQps) { + this.passQps = passQps; + } - public void setOneMinuteBlock(Long oneMinuteBlock) { - this.oneMinuteBlock = oneMinuteBlock; - } + public Long getBlockQps() { + return blockQps; + } - public Long getOneMinuteException() { - return oneMinuteException; - } + public void setBlockQps(Long blockQps) { + this.blockQps = blockQps; + } - public void setOneMinuteException(Long oneMinuteException) { - this.oneMinuteException = oneMinuteException; - } + public Long getTotalQps() { + return totalQps; + } - public Long getOneMinuteTotal() { - return oneMinuteTotal; - } + public void setTotalQps(Long totalQps) { + this.totalQps = totalQps; + } - public void setOneMinuteTotal(Long oneMinuteTotal) { - this.oneMinuteTotal = oneMinuteTotal; - } + public Long getAverageRt() { + return averageRt; + } - public boolean isVisible() { - return visible; - } + public void setAverageRt(Long averageRt) { + this.averageRt = averageRt; + } - public void setVisible(boolean visible) { - this.visible = visible; - } + public Long getSuccessQps() { + return successQps; + } - public List getChildren() { - return children; - } + public void setSuccessQps(Long successQps) { + this.successQps = successQps; + } + + public Long getExceptionQps() { + return exceptionQps; + } + + public void setExceptionQps(Long exceptionQps) { + this.exceptionQps = exceptionQps; + } + + public Long getOneMinutePass() { + return oneMinutePass; + } + + public void setOneMinutePass(Long oneMinutePass) { + this.oneMinutePass = oneMinutePass; + } + + public Long getOneMinuteBlock() { + return oneMinuteBlock; + } + + public void setOneMinuteBlock(Long oneMinuteBlock) { + this.oneMinuteBlock = oneMinuteBlock; + } + + public Long getOneMinuteException() { + return oneMinuteException; + } + + public void setOneMinuteException(Long oneMinuteException) { + this.oneMinuteException = oneMinuteException; + } + + public Long getOneMinuteTotal() { + return oneMinuteTotal; + } + + public void setOneMinuteTotal(Long oneMinuteTotal) { + this.oneMinuteTotal = oneMinuteTotal; + } + + public boolean isVisible() { + return visible; + } + + public void setVisible(boolean visible) { + this.visible = visible; + } + + public List getChildren() { + return children; + } + + public void setChildren(List children) { + this.children = children; + } - public void setChildren(List children) { - this.children = children; - } } - diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/Result.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/Result.java index 2dbf476f0..ca8246d4e 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/Result.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/Result.java @@ -21,83 +21,77 @@ package com.alibaba.csp.sentinel.dashboard.domain; */ public class Result { - private boolean success; - private int code; - private String msg; - private R data; + private boolean success; - public static Result ofSuccess(R data) { - return new Result() - .setSuccess(true) - .setMsg("success") - .setData(data); - } + private int code; - public static Result ofSuccessMsg(String msg) { - return new Result() - .setSuccess(true) - .setMsg(msg); - } + private String msg; - public static Result ofFail(int code, String msg) { - Result result = new Result<>(); - result.setSuccess(false); - result.setCode(code); - result.setMsg(msg); - return result; - } + private R data; - public static Result ofThrowable(int code, Throwable throwable) { - Result result = new Result<>(); - result.setSuccess(false); - result.setCode(code); - result.setMsg(throwable.getClass().getName() + ", " + throwable.getMessage()); - return result; - } + public static Result ofSuccess(R data) { + return new Result().setSuccess(true).setMsg("success").setData(data); + } - public boolean isSuccess() { - return success; - } + public static Result ofSuccessMsg(String msg) { + return new Result().setSuccess(true).setMsg(msg); + } - public Result setSuccess(boolean success) { - this.success = success; - return this; - } + public static Result ofFail(int code, String msg) { + Result result = new Result<>(); + result.setSuccess(false); + result.setCode(code); + result.setMsg(msg); + return result; + } - public int getCode() { - return code; - } + public static Result ofThrowable(int code, Throwable throwable) { + Result result = new Result<>(); + result.setSuccess(false); + result.setCode(code); + result.setMsg(throwable.getClass().getName() + ", " + throwable.getMessage()); + return result; + } - public Result setCode(int code) { - this.code = code; - return this; - } + public boolean isSuccess() { + return success; + } - public String getMsg() { - return msg; - } + public Result setSuccess(boolean success) { + this.success = success; + return this; + } - public Result setMsg(String msg) { - this.msg = msg; - return this; - } + public int getCode() { + return code; + } - public R getData() { - return data; - } + public Result setCode(int code) { + this.code = code; + return this; + } - public Result setData(R data) { - this.data = data; - return this; - } + public String getMsg() { + return msg; + } + + public Result setMsg(String msg) { + this.msg = msg; + return this; + } + + public R getData() { + return data; + } + + public Result setData(R data) { + this.data = data; + return this; + } + + @Override + public String toString() { + return "Result{" + "success=" + success + ", code=" + code + ", msg='" + msg + '\'' + ", data=" + data + '}'; + } - @Override - public String toString() { - return "Result{" + - "success=" + success + - ", code=" + code + - ", msg='" + msg + '\'' + - ", data=" + data + - '}'; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/ClusterAppAssignResultVO.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/ClusterAppAssignResultVO.java index b7b48ccf0..74467f7e0 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/ClusterAppAssignResultVO.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/ClusterAppAssignResultVO.java @@ -23,44 +23,43 @@ import java.util.Set; */ public class ClusterAppAssignResultVO { - private Set failedServerSet; - private Set failedClientSet; + private Set failedServerSet; - private Integer totalCount; + private Set failedClientSet; - public Set getFailedServerSet() { - return failedServerSet; - } + private Integer totalCount; - public ClusterAppAssignResultVO setFailedServerSet(Set failedServerSet) { - this.failedServerSet = failedServerSet; - return this; - } + public Set getFailedServerSet() { + return failedServerSet; + } - public Set getFailedClientSet() { - return failedClientSet; - } + public ClusterAppAssignResultVO setFailedServerSet(Set failedServerSet) { + this.failedServerSet = failedServerSet; + return this; + } - public ClusterAppAssignResultVO setFailedClientSet(Set failedClientSet) { - this.failedClientSet = failedClientSet; - return this; - } + public Set getFailedClientSet() { + return failedClientSet; + } - public Integer getTotalCount() { - return totalCount; - } + public ClusterAppAssignResultVO setFailedClientSet(Set failedClientSet) { + this.failedClientSet = failedClientSet; + return this; + } - public ClusterAppAssignResultVO setTotalCount(Integer totalCount) { - this.totalCount = totalCount; - return this; - } + public Integer getTotalCount() { + return totalCount; + } + + public ClusterAppAssignResultVO setTotalCount(Integer totalCount) { + this.totalCount = totalCount; + return this; + } + + @Override + public String toString() { + return "ClusterAppAssignResultVO{" + "failedServerSet=" + failedServerSet + ", failedClientSet=" + + failedClientSet + ", totalCount=" + totalCount + '}'; + } - @Override - public String toString() { - return "ClusterAppAssignResultVO{" + - "failedServerSet=" + failedServerSet + - ", failedClientSet=" + failedClientSet + - ", totalCount=" + totalCount + - '}'; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/ClusterAppFullAssignRequest.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/ClusterAppFullAssignRequest.java index 96a3dc933..629f0566b 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/ClusterAppFullAssignRequest.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/ClusterAppFullAssignRequest.java @@ -26,33 +26,31 @@ import com.alibaba.csp.sentinel.dashboard.domain.cluster.request.ClusterAppAssig */ public class ClusterAppFullAssignRequest { - private List clusterMap; - private Set remainingList; + private List clusterMap; - public List getClusterMap() { - return clusterMap; - } + private Set remainingList; - public ClusterAppFullAssignRequest setClusterMap( - List clusterMap) { - this.clusterMap = clusterMap; - return this; - } + public List getClusterMap() { + return clusterMap; + } - public Set getRemainingList() { - return remainingList; - } + public ClusterAppFullAssignRequest setClusterMap(List clusterMap) { + this.clusterMap = clusterMap; + return this; + } - public ClusterAppFullAssignRequest setRemainingList(Set remainingList) { - this.remainingList = remainingList; - return this; - } + public Set getRemainingList() { + return remainingList; + } + + public ClusterAppFullAssignRequest setRemainingList(Set remainingList) { + this.remainingList = remainingList; + return this; + } + + @Override + public String toString() { + return "ClusterAppFullAssignRequest{" + "clusterMap=" + clusterMap + ", remainingList=" + remainingList + '}'; + } - @Override - public String toString() { - return "ClusterAppFullAssignRequest{" + - "clusterMap=" + clusterMap + - ", remainingList=" + remainingList + - '}'; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/ClusterAppSingleServerAssignRequest.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/ClusterAppSingleServerAssignRequest.java index f9d9bbc0e..63aa1c35a 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/ClusterAppSingleServerAssignRequest.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/ClusterAppSingleServerAssignRequest.java @@ -25,32 +25,32 @@ import com.alibaba.csp.sentinel.dashboard.domain.cluster.request.ClusterAppAssig */ public class ClusterAppSingleServerAssignRequest { - private ClusterAppAssignMap clusterMap; - private Set remainingList; + private ClusterAppAssignMap clusterMap; - public ClusterAppAssignMap getClusterMap() { - return clusterMap; - } + private Set remainingList; - public ClusterAppSingleServerAssignRequest setClusterMap(ClusterAppAssignMap clusterMap) { - this.clusterMap = clusterMap; - return this; - } + public ClusterAppAssignMap getClusterMap() { + return clusterMap; + } - public Set getRemainingList() { - return remainingList; - } + public ClusterAppSingleServerAssignRequest setClusterMap(ClusterAppAssignMap clusterMap) { + this.clusterMap = clusterMap; + return this; + } - public ClusterAppSingleServerAssignRequest setRemainingList(Set remainingList) { - this.remainingList = remainingList; - return this; - } + public Set getRemainingList() { + return remainingList; + } + + public ClusterAppSingleServerAssignRequest setRemainingList(Set remainingList) { + this.remainingList = remainingList; + return this; + } + + @Override + public String toString() { + return "ClusterAppSingleServerAssignRequest{" + "clusterMap=" + clusterMap + ", remainingList=" + remainingList + + '}'; + } - @Override - public String toString() { - return "ClusterAppSingleServerAssignRequest{" + - "clusterMap=" + clusterMap + - ", remainingList=" + remainingList + - '}'; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/ClusterClientInfoVO.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/ClusterClientInfoVO.java index a9437e76f..b2c6299b1 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/ClusterClientInfoVO.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/ClusterClientInfoVO.java @@ -21,56 +21,54 @@ package com.alibaba.csp.sentinel.dashboard.domain.cluster; */ public class ClusterClientInfoVO { - private String serverHost; - private Integer serverPort; + private String serverHost; - private Integer clientState; + private Integer serverPort; - private Integer requestTimeout; + private Integer clientState; - public String getServerHost() { - return serverHost; - } + private Integer requestTimeout; - public ClusterClientInfoVO setServerHost(String serverHost) { - this.serverHost = serverHost; - return this; - } + public String getServerHost() { + return serverHost; + } - public Integer getServerPort() { - return serverPort; - } + public ClusterClientInfoVO setServerHost(String serverHost) { + this.serverHost = serverHost; + return this; + } - public ClusterClientInfoVO setServerPort(Integer serverPort) { - this.serverPort = serverPort; - return this; - } + public Integer getServerPort() { + return serverPort; + } - public Integer getClientState() { - return clientState; - } + public ClusterClientInfoVO setServerPort(Integer serverPort) { + this.serverPort = serverPort; + return this; + } - public ClusterClientInfoVO setClientState(Integer clientState) { - this.clientState = clientState; - return this; - } + public Integer getClientState() { + return clientState; + } - public Integer getRequestTimeout() { - return requestTimeout; - } + public ClusterClientInfoVO setClientState(Integer clientState) { + this.clientState = clientState; + return this; + } - public ClusterClientInfoVO setRequestTimeout(Integer requestTimeout) { - this.requestTimeout = requestTimeout; - return this; - } + public Integer getRequestTimeout() { + return requestTimeout; + } + + public ClusterClientInfoVO setRequestTimeout(Integer requestTimeout) { + this.requestTimeout = requestTimeout; + return this; + } + + @Override + public String toString() { + return "ClusterClientInfoVO{" + "serverHost='" + serverHost + '\'' + ", serverPort=" + serverPort + + ", clientState=" + clientState + ", requestTimeout=" + requestTimeout + '}'; + } - @Override - public String toString() { - return "ClusterClientInfoVO{" + - "serverHost='" + serverHost + '\'' + - ", serverPort=" + serverPort + - ", clientState=" + clientState + - ", requestTimeout=" + requestTimeout + - '}'; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/ClusterGroupEntity.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/ClusterGroupEntity.java index eef255215..99150f560 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/ClusterGroupEntity.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/ClusterGroupEntity.java @@ -24,68 +24,65 @@ import java.util.Set; */ public class ClusterGroupEntity { - private String machineId; + private String machineId; - private String ip; - private Integer port; + private String ip; - private Set clientSet = new HashSet<>(); + private Integer port; - private Boolean belongToApp; + private Set clientSet = new HashSet<>(); - public String getMachineId() { - return machineId; - } + private Boolean belongToApp; - public ClusterGroupEntity setMachineId(String machineId) { - this.machineId = machineId; - return this; - } + public String getMachineId() { + return machineId; + } - public String getIp() { - return ip; - } + public ClusterGroupEntity setMachineId(String machineId) { + this.machineId = machineId; + return this; + } - public ClusterGroupEntity setIp(String ip) { - this.ip = ip; - return this; - } + public String getIp() { + return ip; + } - public Integer getPort() { - return port; - } + public ClusterGroupEntity setIp(String ip) { + this.ip = ip; + return this; + } - public ClusterGroupEntity setPort(Integer port) { - this.port = port; - return this; - } + public Integer getPort() { + return port; + } - public Set getClientSet() { - return clientSet; - } + public ClusterGroupEntity setPort(Integer port) { + this.port = port; + return this; + } - public ClusterGroupEntity setClientSet(Set clientSet) { - this.clientSet = clientSet; - return this; - } + public Set getClientSet() { + return clientSet; + } - public Boolean getBelongToApp() { - return belongToApp; - } + public ClusterGroupEntity setClientSet(Set clientSet) { + this.clientSet = clientSet; + return this; + } - public ClusterGroupEntity setBelongToApp(Boolean belongToApp) { - this.belongToApp = belongToApp; - return this; - } + public Boolean getBelongToApp() { + return belongToApp; + } + + public ClusterGroupEntity setBelongToApp(Boolean belongToApp) { + this.belongToApp = belongToApp; + return this; + } + + @Override + public String toString() { + return "ClusterGroupEntity{" + "machineId='" + machineId + '\'' + ", ip='" + ip + '\'' + ", port=" + port + + ", clientSet=" + clientSet + ", belongToApp=" + belongToApp + '}'; + } - @Override - public String toString() { - return "ClusterGroupEntity{" + - "machineId='" + machineId + '\'' + - ", ip='" + ip + '\'' + - ", port=" + port + - ", clientSet=" + clientSet + - ", belongToApp=" + belongToApp + - '}'; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/ClusterStateSingleVO.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/ClusterStateSingleVO.java index 7678c5195..032efa0a9 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/ClusterStateSingleVO.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/ClusterStateSingleVO.java @@ -21,43 +21,43 @@ package com.alibaba.csp.sentinel.dashboard.domain.cluster; */ public class ClusterStateSingleVO { - private String address; - private Integer mode; - private String target; + private String address; - public String getAddress() { - return address; - } + private Integer mode; - public ClusterStateSingleVO setAddress(String address) { - this.address = address; - return this; - } + private String target; - public Integer getMode() { - return mode; - } + public String getAddress() { + return address; + } - public ClusterStateSingleVO setMode(Integer mode) { - this.mode = mode; - return this; - } + public ClusterStateSingleVO setAddress(String address) { + this.address = address; + return this; + } - public String getTarget() { - return target; - } + public Integer getMode() { + return mode; + } - public ClusterStateSingleVO setTarget(String target) { - this.target = target; - return this; - } + public ClusterStateSingleVO setMode(Integer mode) { + this.mode = mode; + return this; + } + + public String getTarget() { + return target; + } + + public ClusterStateSingleVO setTarget(String target) { + this.target = target; + return this; + } + + @Override + public String toString() { + return "ClusterStateSingleVO{" + "address='" + address + '\'' + ", mode=" + mode + ", target='" + target + '\'' + + '}'; + } - @Override - public String toString() { - return "ClusterStateSingleVO{" + - "address='" + address + '\'' + - ", mode=" + mode + - ", target='" + target + '\'' + - '}'; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/ConnectionDescriptorVO.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/ConnectionDescriptorVO.java index 71d9e74d8..3ac35a70e 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/ConnectionDescriptorVO.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/ConnectionDescriptorVO.java @@ -15,39 +15,37 @@ */ package com.alibaba.csp.sentinel.dashboard.domain.cluster; - /** * @author Eric Zhao * @since 1.4.0 */ public class ConnectionDescriptorVO { - private String address; - private String host; + private String address; - public String getAddress() { - return address; - } + private String host; - public ConnectionDescriptorVO setAddress(String address) { - this.address = address; - return this; - } + public String getAddress() { + return address; + } - public String getHost() { - return host; - } + public ConnectionDescriptorVO setAddress(String address) { + this.address = address; + return this; + } - public ConnectionDescriptorVO setHost(String host) { - this.host = host; - return this; - } + public String getHost() { + return host; + } + + public ConnectionDescriptorVO setHost(String host) { + this.host = host; + return this; + } + + @Override + public String toString() { + return "ConnectionDescriptorVO{" + "address='" + address + '\'' + ", host='" + host + '\'' + '}'; + } - @Override - public String toString() { - return "ConnectionDescriptorVO{" + - "address='" + address + '\'' + - ", host='" + host + '\'' + - '}'; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/ConnectionGroupVO.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/ConnectionGroupVO.java index af3aa9067..d75a07c43 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/ConnectionGroupVO.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/ConnectionGroupVO.java @@ -23,44 +23,43 @@ import java.util.List; */ public class ConnectionGroupVO { - private String namespace; - private List connectionSet; - private Integer connectedCount; + private String namespace; - public String getNamespace() { - return namespace; - } + private List connectionSet; - public ConnectionGroupVO setNamespace(String namespace) { - this.namespace = namespace; - return this; - } + private Integer connectedCount; - public List getConnectionSet() { - return connectionSet; - } + public String getNamespace() { + return namespace; + } - public ConnectionGroupVO setConnectionSet( - List connectionSet) { - this.connectionSet = connectionSet; - return this; - } + public ConnectionGroupVO setNamespace(String namespace) { + this.namespace = namespace; + return this; + } - public Integer getConnectedCount() { - return connectedCount; - } + public List getConnectionSet() { + return connectionSet; + } - public ConnectionGroupVO setConnectedCount(Integer connectedCount) { - this.connectedCount = connectedCount; - return this; - } + public ConnectionGroupVO setConnectionSet(List connectionSet) { + this.connectionSet = connectionSet; + return this; + } + + public Integer getConnectedCount() { + return connectedCount; + } + + public ConnectionGroupVO setConnectedCount(Integer connectedCount) { + this.connectedCount = connectedCount; + return this; + } + + @Override + public String toString() { + return "ConnectionGroupVO{" + "namespace='" + namespace + '\'' + ", connectionSet=" + connectionSet + + ", connectedCount=" + connectedCount + '}'; + } - @Override - public String toString() { - return "ConnectionGroupVO{" + - "namespace='" + namespace + '\'' + - ", connectionSet=" + connectionSet + - ", connectedCount=" + connectedCount + - '}'; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/config/ClusterClientConfig.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/config/ClusterClientConfig.java index 2cd6bb3bd..e626bac46 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/config/ClusterClientConfig.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/config/ClusterClientConfig.java @@ -21,55 +21,54 @@ package com.alibaba.csp.sentinel.dashboard.domain.cluster.config; */ public class ClusterClientConfig { - private String serverHost; - private Integer serverPort; + private String serverHost; - private Integer requestTimeout; - private Integer connectTimeout; + private Integer serverPort; - public String getServerHost() { - return serverHost; - } + private Integer requestTimeout; - public ClusterClientConfig setServerHost(String serverHost) { - this.serverHost = serverHost; - return this; - } + private Integer connectTimeout; - public Integer getServerPort() { - return serverPort; - } + public String getServerHost() { + return serverHost; + } - public ClusterClientConfig setServerPort(Integer serverPort) { - this.serverPort = serverPort; - return this; - } + public ClusterClientConfig setServerHost(String serverHost) { + this.serverHost = serverHost; + return this; + } - public Integer getRequestTimeout() { - return requestTimeout; - } + public Integer getServerPort() { + return serverPort; + } - public ClusterClientConfig setRequestTimeout(Integer requestTimeout) { - this.requestTimeout = requestTimeout; - return this; - } + public ClusterClientConfig setServerPort(Integer serverPort) { + this.serverPort = serverPort; + return this; + } - public Integer getConnectTimeout() { - return connectTimeout; - } + public Integer getRequestTimeout() { + return requestTimeout; + } - public ClusterClientConfig setConnectTimeout(Integer connectTimeout) { - this.connectTimeout = connectTimeout; - return this; - } + public ClusterClientConfig setRequestTimeout(Integer requestTimeout) { + this.requestTimeout = requestTimeout; + return this; + } + + public Integer getConnectTimeout() { + return connectTimeout; + } + + public ClusterClientConfig setConnectTimeout(Integer connectTimeout) { + this.connectTimeout = connectTimeout; + return this; + } + + @Override + public String toString() { + return "ClusterClientConfig{" + "serverHost='" + serverHost + '\'' + ", serverPort=" + serverPort + + ", requestTimeout=" + requestTimeout + ", connectTimeout=" + connectTimeout + '}'; + } - @Override - public String toString() { - return "ClusterClientConfig{" + - "serverHost='" + serverHost + '\'' + - ", serverPort=" + serverPort + - ", requestTimeout=" + requestTimeout + - ", connectTimeout=" + connectTimeout + - '}'; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/config/ServerFlowConfig.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/config/ServerFlowConfig.java index 3390ea14f..578266d26 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/config/ServerFlowConfig.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/config/ServerFlowConfig.java @@ -21,88 +21,90 @@ package com.alibaba.csp.sentinel.dashboard.domain.cluster.config; */ public class ServerFlowConfig { - public static final double DEFAULT_EXCEED_COUNT = 1.0d; - public static final double DEFAULT_MAX_OCCUPY_RATIO = 1.0d; + public static final double DEFAULT_EXCEED_COUNT = 1.0d; - public static final int DEFAULT_INTERVAL_MS = 1000; - public static final int DEFAULT_SAMPLE_COUNT= 10; - public static final double DEFAULT_MAX_ALLOWED_QPS= 30000; + public static final double DEFAULT_MAX_OCCUPY_RATIO = 1.0d; - private final String namespace; + public static final int DEFAULT_INTERVAL_MS = 1000; - private Double exceedCount = DEFAULT_EXCEED_COUNT; - private Double maxOccupyRatio = DEFAULT_MAX_OCCUPY_RATIO; - private Integer intervalMs = DEFAULT_INTERVAL_MS; - private Integer sampleCount = DEFAULT_SAMPLE_COUNT; + public static final int DEFAULT_SAMPLE_COUNT = 10; - private Double maxAllowedQps = DEFAULT_MAX_ALLOWED_QPS; + public static final double DEFAULT_MAX_ALLOWED_QPS = 30000; - public ServerFlowConfig() { - this("default"); - } + private final String namespace; - public ServerFlowConfig(String namespace) { - this.namespace = namespace; - } + private Double exceedCount = DEFAULT_EXCEED_COUNT; - public String getNamespace() { - return namespace; - } + private Double maxOccupyRatio = DEFAULT_MAX_OCCUPY_RATIO; - public Double getExceedCount() { - return exceedCount; - } + private Integer intervalMs = DEFAULT_INTERVAL_MS; - public ServerFlowConfig setExceedCount(Double exceedCount) { - this.exceedCount = exceedCount; - return this; - } + private Integer sampleCount = DEFAULT_SAMPLE_COUNT; - public Double getMaxOccupyRatio() { - return maxOccupyRatio; - } + private Double maxAllowedQps = DEFAULT_MAX_ALLOWED_QPS; - public ServerFlowConfig setMaxOccupyRatio(Double maxOccupyRatio) { - this.maxOccupyRatio = maxOccupyRatio; - return this; - } + public ServerFlowConfig() { + this("default"); + } - public Integer getIntervalMs() { - return intervalMs; - } + public ServerFlowConfig(String namespace) { + this.namespace = namespace; + } - public ServerFlowConfig setIntervalMs(Integer intervalMs) { - this.intervalMs = intervalMs; - return this; - } + public String getNamespace() { + return namespace; + } - public Integer getSampleCount() { - return sampleCount; - } + public Double getExceedCount() { + return exceedCount; + } - public ServerFlowConfig setSampleCount(Integer sampleCount) { - this.sampleCount = sampleCount; - return this; - } + public ServerFlowConfig setExceedCount(Double exceedCount) { + this.exceedCount = exceedCount; + return this; + } - public Double getMaxAllowedQps() { - return maxAllowedQps; - } + public Double getMaxOccupyRatio() { + return maxOccupyRatio; + } - public ServerFlowConfig setMaxAllowedQps(Double maxAllowedQps) { - this.maxAllowedQps = maxAllowedQps; - return this; - } + public ServerFlowConfig setMaxOccupyRatio(Double maxOccupyRatio) { + this.maxOccupyRatio = maxOccupyRatio; + return this; + } + + public Integer getIntervalMs() { + return intervalMs; + } + + public ServerFlowConfig setIntervalMs(Integer intervalMs) { + this.intervalMs = intervalMs; + return this; + } + + public Integer getSampleCount() { + return sampleCount; + } + + public ServerFlowConfig setSampleCount(Integer sampleCount) { + this.sampleCount = sampleCount; + return this; + } + + public Double getMaxAllowedQps() { + return maxAllowedQps; + } + + public ServerFlowConfig setMaxAllowedQps(Double maxAllowedQps) { + this.maxAllowedQps = maxAllowedQps; + return this; + } + + @Override + public String toString() { + return "ServerFlowConfig{" + "namespace='" + namespace + '\'' + ", exceedCount=" + exceedCount + + ", maxOccupyRatio=" + maxOccupyRatio + ", intervalMs=" + intervalMs + ", sampleCount=" + sampleCount + + ", maxAllowedQps=" + maxAllowedQps + '}'; + } - @Override - public String toString() { - return "ServerFlowConfig{" + - "namespace='" + namespace + '\'' + - ", exceedCount=" + exceedCount + - ", maxOccupyRatio=" + maxOccupyRatio + - ", intervalMs=" + intervalMs + - ", sampleCount=" + sampleCount + - ", maxAllowedQps=" + maxAllowedQps + - '}'; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/config/ServerTransportConfig.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/config/ServerTransportConfig.java index 58fe12a7d..76891ab74 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/config/ServerTransportConfig.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/config/ServerTransportConfig.java @@ -21,44 +21,44 @@ package com.alibaba.csp.sentinel.dashboard.domain.cluster.config; */ public class ServerTransportConfig { - public static final int DEFAULT_PORT = 18730; - public static final int DEFAULT_IDLE_SECONDS = 600; + public static final int DEFAULT_PORT = 18730; - private Integer port; - private Integer idleSeconds; + public static final int DEFAULT_IDLE_SECONDS = 600; - public ServerTransportConfig() { - this(DEFAULT_PORT, DEFAULT_IDLE_SECONDS); - } + private Integer port; - public ServerTransportConfig(Integer port, Integer idleSeconds) { - this.port = port; - this.idleSeconds = idleSeconds; - } + private Integer idleSeconds; - public Integer getPort() { - return port; - } + public ServerTransportConfig() { + this(DEFAULT_PORT, DEFAULT_IDLE_SECONDS); + } - public ServerTransportConfig setPort(Integer port) { - this.port = port; - return this; - } + public ServerTransportConfig(Integer port, Integer idleSeconds) { + this.port = port; + this.idleSeconds = idleSeconds; + } - public Integer getIdleSeconds() { - return idleSeconds; - } + public Integer getPort() { + return port; + } - public ServerTransportConfig setIdleSeconds(Integer idleSeconds) { - this.idleSeconds = idleSeconds; - return this; - } + public ServerTransportConfig setPort(Integer port) { + this.port = port; + return this; + } + + public Integer getIdleSeconds() { + return idleSeconds; + } + + public ServerTransportConfig setIdleSeconds(Integer idleSeconds) { + this.idleSeconds = idleSeconds; + return this; + } + + @Override + public String toString() { + return "ServerTransportConfig{" + "port=" + port + ", idleSeconds=" + idleSeconds + '}'; + } - @Override - public String toString() { - return "ServerTransportConfig{" + - "port=" + port + - ", idleSeconds=" + idleSeconds + - '}'; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/request/ClusterAppAssignMap.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/request/ClusterAppAssignMap.java index 3dbf96b1d..23c78c97d 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/request/ClusterAppAssignMap.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/request/ClusterAppAssignMap.java @@ -23,90 +23,88 @@ import java.util.Set; */ public class ClusterAppAssignMap { - private String machineId; - private String ip; - private Integer port; + private String machineId; - private Boolean belongToApp; + private String ip; - private Set clientSet; + private Integer port; - private Set namespaceSet; - private Double maxAllowedQps; + private Boolean belongToApp; - public String getMachineId() { - return machineId; - } + private Set clientSet; - public ClusterAppAssignMap setMachineId(String machineId) { - this.machineId = machineId; - return this; - } + private Set namespaceSet; - public String getIp() { - return ip; - } + private Double maxAllowedQps; - public ClusterAppAssignMap setIp(String ip) { - this.ip = ip; - return this; - } + public String getMachineId() { + return machineId; + } - public Integer getPort() { - return port; - } + public ClusterAppAssignMap setMachineId(String machineId) { + this.machineId = machineId; + return this; + } - public ClusterAppAssignMap setPort(Integer port) { - this.port = port; - return this; - } + public String getIp() { + return ip; + } - public Set getClientSet() { - return clientSet; - } + public ClusterAppAssignMap setIp(String ip) { + this.ip = ip; + return this; + } - public ClusterAppAssignMap setClientSet(Set clientSet) { - this.clientSet = clientSet; - return this; - } + public Integer getPort() { + return port; + } - public Set getNamespaceSet() { - return namespaceSet; - } + public ClusterAppAssignMap setPort(Integer port) { + this.port = port; + return this; + } - public ClusterAppAssignMap setNamespaceSet(Set namespaceSet) { - this.namespaceSet = namespaceSet; - return this; - } + public Set getClientSet() { + return clientSet; + } - public Boolean getBelongToApp() { - return belongToApp; - } + public ClusterAppAssignMap setClientSet(Set clientSet) { + this.clientSet = clientSet; + return this; + } - public ClusterAppAssignMap setBelongToApp(Boolean belongToApp) { - this.belongToApp = belongToApp; - return this; - } + public Set getNamespaceSet() { + return namespaceSet; + } - public Double getMaxAllowedQps() { - return maxAllowedQps; - } + public ClusterAppAssignMap setNamespaceSet(Set namespaceSet) { + this.namespaceSet = namespaceSet; + return this; + } - public ClusterAppAssignMap setMaxAllowedQps(Double maxAllowedQps) { - this.maxAllowedQps = maxAllowedQps; - return this; - } + public Boolean getBelongToApp() { + return belongToApp; + } + + public ClusterAppAssignMap setBelongToApp(Boolean belongToApp) { + this.belongToApp = belongToApp; + return this; + } + + public Double getMaxAllowedQps() { + return maxAllowedQps; + } + + public ClusterAppAssignMap setMaxAllowedQps(Double maxAllowedQps) { + this.maxAllowedQps = maxAllowedQps; + return this; + } + + @Override + public String toString() { + return "ClusterAppAssignMap{" + "machineId='" + machineId + '\'' + ", ip='" + ip + '\'' + ", port=" + port + + ", belongToApp=" + belongToApp + ", clientSet=" + clientSet + ", namespaceSet=" + namespaceSet + + ", maxAllowedQps=" + maxAllowedQps + '}'; + } - @Override - public String toString() { - return "ClusterAppAssignMap{" + - "machineId='" + machineId + '\'' + - ", ip='" + ip + '\'' + - ", port=" + port + - ", belongToApp=" + belongToApp + - ", clientSet=" + clientSet + - ", namespaceSet=" + namespaceSet + - ", maxAllowedQps=" + maxAllowedQps + - '}'; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/request/ClusterClientModifyRequest.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/request/ClusterClientModifyRequest.java index e6ff5610d..9a7608ae1 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/request/ClusterClientModifyRequest.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/request/ClusterClientModifyRequest.java @@ -23,60 +23,63 @@ import com.alibaba.csp.sentinel.dashboard.domain.cluster.config.ClusterClientCon */ public class ClusterClientModifyRequest implements ClusterModifyRequest { - private String app; - private String ip; - private Integer port; + private String app; - private Integer mode; - private ClusterClientConfig clientConfig; + private String ip; - @Override - public String getApp() { - return app; - } + private Integer port; - public ClusterClientModifyRequest setApp(String app) { - this.app = app; - return this; - } + private Integer mode; - @Override - public String getIp() { - return ip; - } + private ClusterClientConfig clientConfig; - public ClusterClientModifyRequest setIp(String ip) { - this.ip = ip; - return this; - } + @Override + public String getApp() { + return app; + } - @Override - public Integer getPort() { - return port; - } + public ClusterClientModifyRequest setApp(String app) { + this.app = app; + return this; + } - public ClusterClientModifyRequest setPort(Integer port) { - this.port = port; - return this; - } + @Override + public String getIp() { + return ip; + } - @Override - public Integer getMode() { - return mode; - } + public ClusterClientModifyRequest setIp(String ip) { + this.ip = ip; + return this; + } - public ClusterClientModifyRequest setMode(Integer mode) { - this.mode = mode; - return this; - } + @Override + public Integer getPort() { + return port; + } - public ClusterClientConfig getClientConfig() { - return clientConfig; - } + public ClusterClientModifyRequest setPort(Integer port) { + this.port = port; + return this; + } + + @Override + public Integer getMode() { + return mode; + } + + public ClusterClientModifyRequest setMode(Integer mode) { + this.mode = mode; + return this; + } + + public ClusterClientConfig getClientConfig() { + return clientConfig; + } + + public ClusterClientModifyRequest setClientConfig(ClusterClientConfig clientConfig) { + this.clientConfig = clientConfig; + return this; + } - public ClusterClientModifyRequest setClientConfig( - ClusterClientConfig clientConfig) { - this.clientConfig = clientConfig; - return this; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/request/ClusterModifyRequest.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/request/ClusterModifyRequest.java index 9f855ef7c..e0d48e6ba 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/request/ClusterModifyRequest.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/request/ClusterModifyRequest.java @@ -21,11 +21,12 @@ package com.alibaba.csp.sentinel.dashboard.domain.cluster.request; */ public interface ClusterModifyRequest { - String getApp(); + String getApp(); - String getIp(); + String getIp(); - Integer getPort(); + Integer getPort(); + + Integer getMode(); - Integer getMode(); } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/request/ClusterServerModifyRequest.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/request/ClusterServerModifyRequest.java index 9389f693f..216ab8fa0 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/request/ClusterServerModifyRequest.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/request/ClusterServerModifyRequest.java @@ -26,94 +26,92 @@ import com.alibaba.csp.sentinel.dashboard.domain.cluster.config.ServerTransportC */ public class ClusterServerModifyRequest implements ClusterModifyRequest { - private String app; - private String ip; - private Integer port; + private String app; - private Integer mode; - private ServerFlowConfig flowConfig; - private ServerTransportConfig transportConfig; - private Set namespaceSet; + private String ip; - @Override - public String getApp() { - return app; - } + private Integer port; - public ClusterServerModifyRequest setApp(String app) { - this.app = app; - return this; - } + private Integer mode; - @Override - public String getIp() { - return ip; - } + private ServerFlowConfig flowConfig; - public ClusterServerModifyRequest setIp(String ip) { - this.ip = ip; - return this; - } + private ServerTransportConfig transportConfig; - @Override - public Integer getPort() { - return port; - } + private Set namespaceSet; - public ClusterServerModifyRequest setPort(Integer port) { - this.port = port; - return this; - } + @Override + public String getApp() { + return app; + } - @Override - public Integer getMode() { - return mode; - } + public ClusterServerModifyRequest setApp(String app) { + this.app = app; + return this; + } - public ClusterServerModifyRequest setMode(Integer mode) { - this.mode = mode; - return this; - } + @Override + public String getIp() { + return ip; + } - public ServerFlowConfig getFlowConfig() { - return flowConfig; - } + public ClusterServerModifyRequest setIp(String ip) { + this.ip = ip; + return this; + } - public ClusterServerModifyRequest setFlowConfig( - ServerFlowConfig flowConfig) { - this.flowConfig = flowConfig; - return this; - } + @Override + public Integer getPort() { + return port; + } - public ServerTransportConfig getTransportConfig() { - return transportConfig; - } + public ClusterServerModifyRequest setPort(Integer port) { + this.port = port; + return this; + } - public ClusterServerModifyRequest setTransportConfig( - ServerTransportConfig transportConfig) { - this.transportConfig = transportConfig; - return this; - } + @Override + public Integer getMode() { + return mode; + } - public Set getNamespaceSet() { - return namespaceSet; - } + public ClusterServerModifyRequest setMode(Integer mode) { + this.mode = mode; + return this; + } - public ClusterServerModifyRequest setNamespaceSet(Set namespaceSet) { - this.namespaceSet = namespaceSet; - return this; - } + public ServerFlowConfig getFlowConfig() { + return flowConfig; + } + + public ClusterServerModifyRequest setFlowConfig(ServerFlowConfig flowConfig) { + this.flowConfig = flowConfig; + return this; + } + + public ServerTransportConfig getTransportConfig() { + return transportConfig; + } + + public ClusterServerModifyRequest setTransportConfig(ServerTransportConfig transportConfig) { + this.transportConfig = transportConfig; + return this; + } + + public Set getNamespaceSet() { + return namespaceSet; + } + + public ClusterServerModifyRequest setNamespaceSet(Set namespaceSet) { + this.namespaceSet = namespaceSet; + return this; + } + + @Override + public String toString() { + return "ClusterServerModifyRequest{" + "app='" + app + '\'' + ", ip='" + ip + '\'' + ", port=" + port + + ", mode=" + mode + ", flowConfig=" + flowConfig + ", transportConfig=" + transportConfig + + ", namespaceSet=" + namespaceSet + '}'; + } - @Override - public String toString() { - return "ClusterServerModifyRequest{" + - "app='" + app + '\'' + - ", ip='" + ip + '\'' + - ", port=" + port + - ", mode=" + mode + - ", flowConfig=" + flowConfig + - ", transportConfig=" + transportConfig + - ", namespaceSet=" + namespaceSet + - '}'; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/state/AppClusterClientStateWrapVO.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/state/AppClusterClientStateWrapVO.java index 4076d23b2..19daa9864 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/state/AppClusterClientStateWrapVO.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/state/AppClusterClientStateWrapVO.java @@ -21,59 +21,57 @@ package com.alibaba.csp.sentinel.dashboard.domain.cluster.state; */ public class AppClusterClientStateWrapVO { - /** - * {ip}@{transport_command_port}. - */ - private String id; + /** + * {ip}@{transport_command_port}. + */ + private String id; - private Integer commandPort; - private String ip; + private Integer commandPort; - private ClusterClientStateVO state; + private String ip; - public String getId() { - return id; - } + private ClusterClientStateVO state; - public AppClusterClientStateWrapVO setId(String id) { - this.id = id; - return this; - } + public String getId() { + return id; + } - public String getIp() { - return ip; - } + public AppClusterClientStateWrapVO setId(String id) { + this.id = id; + return this; + } - public AppClusterClientStateWrapVO setIp(String ip) { - this.ip = ip; - return this; - } + public String getIp() { + return ip; + } - public ClusterClientStateVO getState() { - return state; - } + public AppClusterClientStateWrapVO setIp(String ip) { + this.ip = ip; + return this; + } - public AppClusterClientStateWrapVO setState(ClusterClientStateVO state) { - this.state = state; - return this; - } + public ClusterClientStateVO getState() { + return state; + } - public Integer getCommandPort() { - return commandPort; - } + public AppClusterClientStateWrapVO setState(ClusterClientStateVO state) { + this.state = state; + return this; + } - public AppClusterClientStateWrapVO setCommandPort(Integer commandPort) { - this.commandPort = commandPort; - return this; - } + public Integer getCommandPort() { + return commandPort; + } + + public AppClusterClientStateWrapVO setCommandPort(Integer commandPort) { + this.commandPort = commandPort; + return this; + } + + @Override + public String toString() { + return "AppClusterClientStateWrapVO{" + "id='" + id + '\'' + ", commandPort=" + commandPort + ", ip='" + ip + + '\'' + ", state=" + state + '}'; + } - @Override - public String toString() { - return "AppClusterClientStateWrapVO{" + - "id='" + id + '\'' + - ", commandPort=" + commandPort + - ", ip='" + ip + '\'' + - ", state=" + state + - '}'; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/state/AppClusterServerStateWrapVO.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/state/AppClusterServerStateWrapVO.java index ed39e7bce..4f3bbb416 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/state/AppClusterServerStateWrapVO.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/state/AppClusterServerStateWrapVO.java @@ -21,82 +21,79 @@ package com.alibaba.csp.sentinel.dashboard.domain.cluster.state; */ public class AppClusterServerStateWrapVO { - /** - * {ip}@{transport_command_port}. - */ - private String id; + /** + * {ip}@{transport_command_port}. + */ + private String id; - private String ip; - private Integer port; + private String ip; - private Integer connectedCount; + private Integer port; - private Boolean belongToApp; + private Integer connectedCount; - private ClusterServerStateVO state; + private Boolean belongToApp; - public String getId() { - return id; - } + private ClusterServerStateVO state; - public AppClusterServerStateWrapVO setId(String id) { - this.id = id; - return this; - } + public String getId() { + return id; + } - public String getIp() { - return ip; - } + public AppClusterServerStateWrapVO setId(String id) { + this.id = id; + return this; + } - public AppClusterServerStateWrapVO setIp(String ip) { - this.ip = ip; - return this; - } + public String getIp() { + return ip; + } - public Integer getPort() { - return port; - } + public AppClusterServerStateWrapVO setIp(String ip) { + this.ip = ip; + return this; + } - public AppClusterServerStateWrapVO setPort(Integer port) { - this.port = port; - return this; - } + public Integer getPort() { + return port; + } - public Boolean getBelongToApp() { - return belongToApp; - } + public AppClusterServerStateWrapVO setPort(Integer port) { + this.port = port; + return this; + } - public AppClusterServerStateWrapVO setBelongToApp(Boolean belongToApp) { - this.belongToApp = belongToApp; - return this; - } + public Boolean getBelongToApp() { + return belongToApp; + } - public Integer getConnectedCount() { - return connectedCount; - } + public AppClusterServerStateWrapVO setBelongToApp(Boolean belongToApp) { + this.belongToApp = belongToApp; + return this; + } - public AppClusterServerStateWrapVO setConnectedCount(Integer connectedCount) { - this.connectedCount = connectedCount; - return this; - } + public Integer getConnectedCount() { + return connectedCount; + } - public ClusterServerStateVO getState() { - return state; - } + public AppClusterServerStateWrapVO setConnectedCount(Integer connectedCount) { + this.connectedCount = connectedCount; + return this; + } - public AppClusterServerStateWrapVO setState(ClusterServerStateVO state) { - this.state = state; - return this; - } + public ClusterServerStateVO getState() { + return state; + } + + public AppClusterServerStateWrapVO setState(ClusterServerStateVO state) { + this.state = state; + return this; + } + + @Override + public String toString() { + return "AppClusterServerStateWrapVO{" + "id='" + id + '\'' + ", ip='" + ip + '\'' + ", port='" + port + '\'' + + ", belongToApp=" + belongToApp + ", state=" + state + '}'; + } - @Override - public String toString() { - return "AppClusterServerStateWrapVO{" + - "id='" + id + '\'' + - ", ip='" + ip + '\'' + - ", port='" + port + '\'' + - ", belongToApp=" + belongToApp + - ", state=" + state + - '}'; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/state/ClusterClientStateVO.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/state/ClusterClientStateVO.java index ac61b0b97..fd2df5f47 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/state/ClusterClientStateVO.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/state/ClusterClientStateVO.java @@ -23,24 +23,23 @@ import com.alibaba.csp.sentinel.dashboard.domain.cluster.ClusterClientInfoVO; */ public class ClusterClientStateVO { - /** - * Cluster token client state. - */ - private ClusterClientInfoVO clientConfig; + /** + * Cluster token client state. + */ + private ClusterClientInfoVO clientConfig; - public ClusterClientInfoVO getClientConfig() { - return clientConfig; - } + public ClusterClientInfoVO getClientConfig() { + return clientConfig; + } - public ClusterClientStateVO setClientConfig(ClusterClientInfoVO clientConfig) { - this.clientConfig = clientConfig; - return this; - } + public ClusterClientStateVO setClientConfig(ClusterClientInfoVO clientConfig) { + this.clientConfig = clientConfig; + return this; + } + + @Override + public String toString() { + return "ClusterClientStateVO{" + "clientConfig=" + clientConfig + '}'; + } - @Override - public String toString() { - return "ClusterClientStateVO{" + - "clientConfig=" + clientConfig + - '}'; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/state/ClusterRequestLimitVO.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/state/ClusterRequestLimitVO.java index 6c5da420e..aaf10dc5d 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/state/ClusterRequestLimitVO.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/state/ClusterRequestLimitVO.java @@ -21,43 +21,43 @@ package com.alibaba.csp.sentinel.dashboard.domain.cluster.state; */ public class ClusterRequestLimitVO { - private String namespace; - private Double currentQps; - private Double maxAllowedQps; + private String namespace; - public String getNamespace() { - return namespace; - } + private Double currentQps; - public ClusterRequestLimitVO setNamespace(String namespace) { - this.namespace = namespace; - return this; - } + private Double maxAllowedQps; - public Double getCurrentQps() { - return currentQps; - } + public String getNamespace() { + return namespace; + } - public ClusterRequestLimitVO setCurrentQps(Double currentQps) { - this.currentQps = currentQps; - return this; - } + public ClusterRequestLimitVO setNamespace(String namespace) { + this.namespace = namespace; + return this; + } - public Double getMaxAllowedQps() { - return maxAllowedQps; - } + public Double getCurrentQps() { + return currentQps; + } - public ClusterRequestLimitVO setMaxAllowedQps(Double maxAllowedQps) { - this.maxAllowedQps = maxAllowedQps; - return this; - } + public ClusterRequestLimitVO setCurrentQps(Double currentQps) { + this.currentQps = currentQps; + return this; + } + + public Double getMaxAllowedQps() { + return maxAllowedQps; + } + + public ClusterRequestLimitVO setMaxAllowedQps(Double maxAllowedQps) { + this.maxAllowedQps = maxAllowedQps; + return this; + } + + @Override + public String toString() { + return "ClusterRequestLimitVO{" + "namespace='" + namespace + '\'' + ", currentQps=" + currentQps + + ", maxAllowedQps=" + maxAllowedQps + '}'; + } - @Override - public String toString() { - return "ClusterRequestLimitVO{" + - "namespace='" + namespace + '\'' + - ", currentQps=" + currentQps + - ", maxAllowedQps=" + maxAllowedQps + - '}'; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/state/ClusterServerStateVO.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/state/ClusterServerStateVO.java index a76a7ff06..1eabe4e39 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/state/ClusterServerStateVO.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/state/ClusterServerStateVO.java @@ -28,102 +28,99 @@ import com.alibaba.csp.sentinel.dashboard.domain.cluster.config.ServerTransportC */ public class ClusterServerStateVO { - private String appName; + private String appName; - private ServerTransportConfig transport; - private ServerFlowConfig flow; - private Set namespaceSet; + private ServerTransportConfig transport; - private Integer port; + private ServerFlowConfig flow; - private List connection; - private List requestLimitData; + private Set namespaceSet; - private Boolean embedded; + private Integer port; - public String getAppName() { - return appName; - } + private List connection; - public ClusterServerStateVO setAppName(String appName) { - this.appName = appName; - return this; - } + private List requestLimitData; - public ServerTransportConfig getTransport() { - return transport; - } + private Boolean embedded; - public ClusterServerStateVO setTransport(ServerTransportConfig transport) { - this.transport = transport; - return this; - } + public String getAppName() { + return appName; + } - public ServerFlowConfig getFlow() { - return flow; - } + public ClusterServerStateVO setAppName(String appName) { + this.appName = appName; + return this; + } - public ClusterServerStateVO setFlow(ServerFlowConfig flow) { - this.flow = flow; - return this; - } + public ServerTransportConfig getTransport() { + return transport; + } - public Set getNamespaceSet() { - return namespaceSet; - } + public ClusterServerStateVO setTransport(ServerTransportConfig transport) { + this.transport = transport; + return this; + } - public ClusterServerStateVO setNamespaceSet(Set namespaceSet) { - this.namespaceSet = namespaceSet; - return this; - } + public ServerFlowConfig getFlow() { + return flow; + } - public Integer getPort() { - return port; - } + public ClusterServerStateVO setFlow(ServerFlowConfig flow) { + this.flow = flow; + return this; + } - public ClusterServerStateVO setPort(Integer port) { - this.port = port; - return this; - } + public Set getNamespaceSet() { + return namespaceSet; + } - public List getConnection() { - return connection; - } + public ClusterServerStateVO setNamespaceSet(Set namespaceSet) { + this.namespaceSet = namespaceSet; + return this; + } - public ClusterServerStateVO setConnection(List connection) { - this.connection = connection; - return this; - } + public Integer getPort() { + return port; + } - public List getRequestLimitData() { - return requestLimitData; - } + public ClusterServerStateVO setPort(Integer port) { + this.port = port; + return this; + } - public ClusterServerStateVO setRequestLimitData(List requestLimitData) { - this.requestLimitData = requestLimitData; - return this; - } + public List getConnection() { + return connection; + } - public Boolean getEmbedded() { - return embedded; - } + public ClusterServerStateVO setConnection(List connection) { + this.connection = connection; + return this; + } - public ClusterServerStateVO setEmbedded(Boolean embedded) { - this.embedded = embedded; - return this; - } + public List getRequestLimitData() { + return requestLimitData; + } + + public ClusterServerStateVO setRequestLimitData(List requestLimitData) { + this.requestLimitData = requestLimitData; + return this; + } + + public Boolean getEmbedded() { + return embedded; + } + + public ClusterServerStateVO setEmbedded(Boolean embedded) { + this.embedded = embedded; + return this; + } + + @Override + public String toString() { + return "ClusterServerStateVO{" + "appName='" + appName + '\'' + ", transport=" + transport + ", flow=" + flow + + ", namespaceSet=" + namespaceSet + ", port=" + port + ", connection=" + connection + + ", requestLimitData=" + requestLimitData + ", embedded=" + embedded + '}'; + } - @Override - public String toString() { - return "ClusterServerStateVO{" + - "appName='" + appName + '\'' + - ", transport=" + transport + - ", flow=" + flow + - ", namespaceSet=" + namespaceSet + - ", port=" + port + - ", connection=" + connection + - ", requestLimitData=" + requestLimitData + - ", embedded=" + embedded + - '}'; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/state/ClusterStateSimpleEntity.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/state/ClusterStateSimpleEntity.java index c5537aab0..d0b285231 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/state/ClusterStateSimpleEntity.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/state/ClusterStateSimpleEntity.java @@ -21,54 +21,54 @@ package com.alibaba.csp.sentinel.dashboard.domain.cluster.state; */ public class ClusterStateSimpleEntity { - private Integer mode; - private Long lastModified; - private Boolean clientAvailable; - private Boolean serverAvailable; + private Integer mode; - public Integer getMode() { - return mode; - } + private Long lastModified; - public ClusterStateSimpleEntity setMode(Integer mode) { - this.mode = mode; - return this; - } + private Boolean clientAvailable; - public Long getLastModified() { - return lastModified; - } + private Boolean serverAvailable; - public ClusterStateSimpleEntity setLastModified(Long lastModified) { - this.lastModified = lastModified; - return this; - } + public Integer getMode() { + return mode; + } - public Boolean getClientAvailable() { - return clientAvailable; - } + public ClusterStateSimpleEntity setMode(Integer mode) { + this.mode = mode; + return this; + } - public ClusterStateSimpleEntity setClientAvailable(Boolean clientAvailable) { - this.clientAvailable = clientAvailable; - return this; - } + public Long getLastModified() { + return lastModified; + } - public Boolean getServerAvailable() { - return serverAvailable; - } + public ClusterStateSimpleEntity setLastModified(Long lastModified) { + this.lastModified = lastModified; + return this; + } - public ClusterStateSimpleEntity setServerAvailable(Boolean serverAvailable) { - this.serverAvailable = serverAvailable; - return this; - } + public Boolean getClientAvailable() { + return clientAvailable; + } + + public ClusterStateSimpleEntity setClientAvailable(Boolean clientAvailable) { + this.clientAvailable = clientAvailable; + return this; + } + + public Boolean getServerAvailable() { + return serverAvailable; + } + + public ClusterStateSimpleEntity setServerAvailable(Boolean serverAvailable) { + this.serverAvailable = serverAvailable; + return this; + } + + @Override + public String toString() { + return "ClusterStateSimpleEntity{" + "mode=" + mode + ", lastModified=" + lastModified + ", clientAvailable=" + + clientAvailable + ", serverAvailable=" + serverAvailable + '}'; + } - @Override - public String toString() { - return "ClusterStateSimpleEntity{" + - "mode=" + mode + - ", lastModified=" + lastModified + - ", clientAvailable=" + clientAvailable + - ", serverAvailable=" + serverAvailable + - '}'; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/state/ClusterUniversalStatePairVO.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/state/ClusterUniversalStatePairVO.java index 112765602..73af2841e 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/state/ClusterUniversalStatePairVO.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/state/ClusterUniversalStatePairVO.java @@ -21,52 +21,52 @@ package com.alibaba.csp.sentinel.dashboard.domain.cluster.state; */ public class ClusterUniversalStatePairVO { - private String ip; - private Integer commandPort; + private String ip; - private ClusterUniversalStateVO state; + private Integer commandPort; - public ClusterUniversalStatePairVO() {} + private ClusterUniversalStateVO state; - public ClusterUniversalStatePairVO(String ip, Integer commandPort, ClusterUniversalStateVO state) { - this.ip = ip; - this.commandPort = commandPort; - this.state = state; - } + public ClusterUniversalStatePairVO() { + } - public String getIp() { - return ip; - } + public ClusterUniversalStatePairVO(String ip, Integer commandPort, ClusterUniversalStateVO state) { + this.ip = ip; + this.commandPort = commandPort; + this.state = state; + } - public ClusterUniversalStatePairVO setIp(String ip) { - this.ip = ip; - return this; - } + public String getIp() { + return ip; + } - public Integer getCommandPort() { - return commandPort; - } + public ClusterUniversalStatePairVO setIp(String ip) { + this.ip = ip; + return this; + } - public ClusterUniversalStatePairVO setCommandPort(Integer commandPort) { - this.commandPort = commandPort; - return this; - } + public Integer getCommandPort() { + return commandPort; + } - public ClusterUniversalStateVO getState() { - return state; - } + public ClusterUniversalStatePairVO setCommandPort(Integer commandPort) { + this.commandPort = commandPort; + return this; + } - public ClusterUniversalStatePairVO setState(ClusterUniversalStateVO state) { - this.state = state; - return this; - } + public ClusterUniversalStateVO getState() { + return state; + } + + public ClusterUniversalStatePairVO setState(ClusterUniversalStateVO state) { + this.state = state; + return this; + } + + @Override + public String toString() { + return "ClusterUniversalStatePairVO{" + "ip='" + ip + '\'' + ", commandPort=" + commandPort + ", state=" + state + + '}'; + } - @Override - public String toString() { - return "ClusterUniversalStatePairVO{" + - "ip='" + ip + '\'' + - ", commandPort=" + commandPort + - ", state=" + state + - '}'; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/state/ClusterUniversalStateVO.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/state/ClusterUniversalStateVO.java index 3e9a787db..75ef4e3c9 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/state/ClusterUniversalStateVO.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/cluster/state/ClusterUniversalStateVO.java @@ -21,44 +21,43 @@ package com.alibaba.csp.sentinel.dashboard.domain.cluster.state; */ public class ClusterUniversalStateVO { - private ClusterStateSimpleEntity stateInfo; - private ClusterClientStateVO client; - private ClusterServerStateVO server; + private ClusterStateSimpleEntity stateInfo; - public ClusterClientStateVO getClient() { - return client; - } + private ClusterClientStateVO client; - public ClusterUniversalStateVO setClient(ClusterClientStateVO client) { - this.client = client; - return this; - } + private ClusterServerStateVO server; - public ClusterServerStateVO getServer() { - return server; - } + public ClusterClientStateVO getClient() { + return client; + } - public ClusterUniversalStateVO setServer(ClusterServerStateVO server) { - this.server = server; - return this; - } + public ClusterUniversalStateVO setClient(ClusterClientStateVO client) { + this.client = client; + return this; + } - public ClusterStateSimpleEntity getStateInfo() { - return stateInfo; - } + public ClusterServerStateVO getServer() { + return server; + } - public ClusterUniversalStateVO setStateInfo( - ClusterStateSimpleEntity stateInfo) { - this.stateInfo = stateInfo; - return this; - } + public ClusterUniversalStateVO setServer(ClusterServerStateVO server) { + this.server = server; + return this; + } + + public ClusterStateSimpleEntity getStateInfo() { + return stateInfo; + } + + public ClusterUniversalStateVO setStateInfo(ClusterStateSimpleEntity stateInfo) { + this.stateInfo = stateInfo; + return this; + } + + @Override + public String toString() { + return "ClusterUniversalStateVO{" + "stateInfo=" + stateInfo + ", client=" + client + ", server=" + server + + '}'; + } - @Override - public String toString() { - return "ClusterUniversalStateVO{" + - "stateInfo=" + stateInfo + - ", client=" + client + - ", server=" + server + - '}'; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/vo/MachineInfoVo.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/vo/MachineInfoVo.java index 66428c142..8378198a1 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/vo/MachineInfoVo.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/vo/MachineInfoVo.java @@ -25,99 +25,106 @@ import com.alibaba.csp.sentinel.dashboard.discovery.MachineInfo; */ public class MachineInfoVo { - private String app; - private String hostname; - private String ip; - private int port; - private long heartbeatVersion; - private long lastHeartbeat; - private boolean healthy; + private String app; - private String version; + private String hostname; - public static List fromMachineInfoList(List machines) { - List list = new ArrayList<>(); - for (MachineInfo machine : machines) { - list.add(fromMachineInfo(machine)); - } - return list; - } + private String ip; - public static MachineInfoVo fromMachineInfo(MachineInfo machine) { - MachineInfoVo vo = new MachineInfoVo(); - vo.setApp(machine.getApp()); - vo.setHostname(machine.getHostname()); - vo.setIp(machine.getIp()); - vo.setPort(machine.getPort()); - vo.setLastHeartbeat(machine.getLastHeartbeat()); - vo.setHeartbeatVersion(machine.getHeartbeatVersion()); - vo.setVersion(machine.getVersion()); - vo.setHealthy(machine.isHealthy()); - return vo; - } + private int port; - public String getApp() { - return app; - } + private long heartbeatVersion; - public void setApp(String app) { - this.app = app; - } + private long lastHeartbeat; - public String getHostname() { - return hostname; - } + private boolean healthy; - public void setHostname(String hostname) { - this.hostname = hostname; - } + private String version; - public String getIp() { - return ip; - } + public static List fromMachineInfoList(List machines) { + List list = new ArrayList<>(); + for (MachineInfo machine : machines) { + list.add(fromMachineInfo(machine)); + } + return list; + } - public void setIp(String ip) { - this.ip = ip; - } + public static MachineInfoVo fromMachineInfo(MachineInfo machine) { + MachineInfoVo vo = new MachineInfoVo(); + vo.setApp(machine.getApp()); + vo.setHostname(machine.getHostname()); + vo.setIp(machine.getIp()); + vo.setPort(machine.getPort()); + vo.setLastHeartbeat(machine.getLastHeartbeat()); + vo.setHeartbeatVersion(machine.getHeartbeatVersion()); + vo.setVersion(machine.getVersion()); + vo.setHealthy(machine.isHealthy()); + return vo; + } - public int getPort() { - return port; - } + public String getApp() { + return app; + } - public void setPort(int port) { - this.port = port; - } + public void setApp(String app) { + this.app = app; + } - public long getLastHeartbeat() { - return lastHeartbeat; - } - - public void setLastHeartbeat(long lastHeartbeat) { - this.lastHeartbeat = lastHeartbeat; - } - - public void setHeartbeatVersion(long heartbeatVersion) { - this.heartbeatVersion = heartbeatVersion; - } - - public long getHeartbeatVersion() { - return heartbeatVersion; - } + public String getHostname() { + return hostname; + } - public String getVersion() { - return version; - } + public void setHostname(String hostname) { + this.hostname = hostname; + } - public MachineInfoVo setVersion(String version) { - this.version = version; - return this; - } + public String getIp() { + return ip; + } - public boolean isHealthy() { - return healthy; - } + public void setIp(String ip) { + this.ip = ip; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + public long getLastHeartbeat() { + return lastHeartbeat; + } + + public void setLastHeartbeat(long lastHeartbeat) { + this.lastHeartbeat = lastHeartbeat; + } + + public void setHeartbeatVersion(long heartbeatVersion) { + this.heartbeatVersion = heartbeatVersion; + } + + public long getHeartbeatVersion() { + return heartbeatVersion; + } + + public String getVersion() { + return version; + } + + public MachineInfoVo setVersion(String version) { + this.version = version; + return this; + } + + public boolean isHealthy() { + return healthy; + } + + public void setHealthy(boolean healthy) { + this.healthy = healthy; + } - public void setHealthy(boolean healthy) { - this.healthy = healthy; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/vo/MetricVo.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/vo/MetricVo.java index af64941ee..68211955c 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/vo/MetricVo.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/vo/MetricVo.java @@ -25,184 +25,196 @@ import com.alibaba.csp.sentinel.dashboard.datasource.entity.MetricEntity; * @author leyou */ public class MetricVo implements Comparable { - private Long id; - private String app; - private Long timestamp; - private Long gmtCreate = System.currentTimeMillis(); - private String resource; - private Long passQps; - private Long blockQps; - private Long successQps; - private Long exceptionQps; - /** - * average rt - */ - private Double rt; - private Integer count; - public MetricVo() { - } + private Long id; - public static List fromMetricEntities(Collection entities) { - List list = new ArrayList<>(); - if (entities != null) { - for (MetricEntity entity : entities) { - list.add(fromMetricEntity(entity)); - } - } - return list; - } + private String app; - /** - * 保留资源名为identity的结果。 - * - * @param entities 通过hashCode查找到的MetricEntities - * @param identity 真正需要查找的资源名 - * @return - */ - public static List fromMetricEntities(Collection entities, String identity) { - List list = new ArrayList<>(); - if (entities != null) { - for (MetricEntity entity : entities) { - if (entity.getResource().equals(identity)) { - list.add(fromMetricEntity(entity)); - } - } - } - return list; - } + private Long timestamp; - public static MetricVo fromMetricEntity(MetricEntity entity) { - MetricVo vo = new MetricVo(); - vo.id = entity.getId(); - vo.app = entity.getApp(); - vo.timestamp = entity.getTimestamp().getTime(); - vo.gmtCreate = entity.getGmtCreate().getTime(); - vo.resource = entity.getResource(); - vo.passQps = entity.getPassQps(); - vo.blockQps = entity.getBlockQps(); - vo.successQps = entity.getSuccessQps(); - vo.exceptionQps = entity.getExceptionQps(); - if (entity.getSuccessQps() != 0) { - vo.rt = entity.getRt() / entity.getSuccessQps(); - } else { - vo.rt = 0D; - } - vo.count = entity.getCount(); - return vo; - } + private Long gmtCreate = System.currentTimeMillis(); - public static MetricVo parse(String line) { - String[] strs = line.split("\\|"); - long timestamp = Long.parseLong(strs[0]); - String identity = strs[1]; - long passQps = Long.parseLong(strs[2]); - long blockQps = Long.parseLong(strs[3]); - long exception = Long.parseLong(strs[4]); - double rt = Double.parseDouble(strs[5]); - long successQps = Long.parseLong(strs[6]); - MetricVo vo = new MetricVo(); - vo.timestamp = timestamp; - vo.resource = identity; - vo.passQps = passQps; - vo.blockQps = blockQps; - vo.successQps = successQps; - vo.exceptionQps = exception; - vo.rt = rt; - vo.count = 1; - return vo; - } + private String resource; - public Long getId() { - return id; - } + private Long passQps; - public void setId(Long id) { - this.id = id; - } + private Long blockQps; - public String getApp() { - return app; - } + private Long successQps; - public void setApp(String app) { - this.app = app; - } + private Long exceptionQps; - public Long getTimestamp() { - return timestamp; - } + /** + * average rt + */ + private Double rt; - public void setTimestamp(Long timestamp) { - this.timestamp = timestamp; - } + private Integer count; - public Long getGmtCreate() { - return gmtCreate; - } + public MetricVo() { + } - public void setGmtCreate(Long gmtCreate) { - this.gmtCreate = gmtCreate; - } + public static List fromMetricEntities(Collection entities) { + List list = new ArrayList<>(); + if (entities != null) { + for (MetricEntity entity : entities) { + list.add(fromMetricEntity(entity)); + } + } + return list; + } - public String getResource() { - return resource; - } + /** + * 保留资源名为identity的结果。 + * @param entities 通过hashCode查找到的MetricEntities + * @param identity 真正需要查找的资源名 + * @return + */ + public static List fromMetricEntities(Collection entities, String identity) { + List list = new ArrayList<>(); + if (entities != null) { + for (MetricEntity entity : entities) { + if (entity.getResource().equals(identity)) { + list.add(fromMetricEntity(entity)); + } + } + } + return list; + } - public void setResource(String resource) { - this.resource = resource; - } + public static MetricVo fromMetricEntity(MetricEntity entity) { + MetricVo vo = new MetricVo(); + vo.id = entity.getId(); + vo.app = entity.getApp(); + vo.timestamp = entity.getTimestamp().getTime(); + vo.gmtCreate = entity.getGmtCreate().getTime(); + vo.resource = entity.getResource(); + vo.passQps = entity.getPassQps(); + vo.blockQps = entity.getBlockQps(); + vo.successQps = entity.getSuccessQps(); + vo.exceptionQps = entity.getExceptionQps(); + if (entity.getSuccessQps() != 0) { + vo.rt = entity.getRt() / entity.getSuccessQps(); + } + else { + vo.rt = 0D; + } + vo.count = entity.getCount(); + return vo; + } - public Long getPassQps() { - return passQps; - } + public static MetricVo parse(String line) { + String[] strs = line.split("\\|"); + long timestamp = Long.parseLong(strs[0]); + String identity = strs[1]; + long passQps = Long.parseLong(strs[2]); + long blockQps = Long.parseLong(strs[3]); + long exception = Long.parseLong(strs[4]); + double rt = Double.parseDouble(strs[5]); + long successQps = Long.parseLong(strs[6]); + MetricVo vo = new MetricVo(); + vo.timestamp = timestamp; + vo.resource = identity; + vo.passQps = passQps; + vo.blockQps = blockQps; + vo.successQps = successQps; + vo.exceptionQps = exception; + vo.rt = rt; + vo.count = 1; + return vo; + } - public void setPassQps(Long passQps) { - this.passQps = passQps; - } + public Long getId() { + return id; + } - public Long getBlockQps() { - return blockQps; - } + public void setId(Long id) { + this.id = id; + } - public void setBlockQps(Long blockQps) { - this.blockQps = blockQps; - } + public String getApp() { + return app; + } - public Long getSuccessQps() { - return successQps; - } + public void setApp(String app) { + this.app = app; + } - public void setSuccessQps(Long successQps) { - this.successQps = successQps; - } + public Long getTimestamp() { + return timestamp; + } - public Long getExceptionQps() { - return exceptionQps; - } + public void setTimestamp(Long timestamp) { + this.timestamp = timestamp; + } - public void setExceptionQps(Long exceptionQps) { - this.exceptionQps = exceptionQps; - } + public Long getGmtCreate() { + return gmtCreate; + } - public Double getRt() { - return rt; - } + public void setGmtCreate(Long gmtCreate) { + this.gmtCreate = gmtCreate; + } - public void setRt(Double rt) { - this.rt = rt; - } + public String getResource() { + return resource; + } - public Integer getCount() { - return count; - } + public void setResource(String resource) { + this.resource = resource; + } - public void setCount(Integer count) { - this.count = count; - } + public Long getPassQps() { + return passQps; + } + + public void setPassQps(Long passQps) { + this.passQps = passQps; + } + + public Long getBlockQps() { + return blockQps; + } + + public void setBlockQps(Long blockQps) { + this.blockQps = blockQps; + } + + public Long getSuccessQps() { + return successQps; + } + + public void setSuccessQps(Long successQps) { + this.successQps = successQps; + } + + public Long getExceptionQps() { + return exceptionQps; + } + + public void setExceptionQps(Long exceptionQps) { + this.exceptionQps = exceptionQps; + } + + public Double getRt() { + return rt; + } + + public void setRt(Double rt) { + this.rt = rt; + } + + public Integer getCount() { + return count; + } + + public void setCount(Integer count) { + this.count = count; + } + + @Override + public int compareTo(MetricVo o) { + return Long.compare(this.timestamp, o.timestamp); + } - @Override - public int compareTo(MetricVo o) { - return Long.compare(this.timestamp, o.timestamp); - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/vo/ResourceVo.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/vo/ResourceVo.java index a8ffe24e9..512c34869 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/vo/ResourceVo.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/vo/ResourceVo.java @@ -26,211 +26,225 @@ import com.alibaba.csp.sentinel.dashboard.domain.ResourceTreeNode; * @author leyou */ public class ResourceVo { - private String parentTtId; - private String ttId; - private String resource; - private Integer threadNum; - private Long passQps; - private Long blockQps; - private Long totalQps; - private Long averageRt; - private Long passRequestQps; - private Long exceptionQps; - private Long oneMinutePass; - private Long oneMinuteBlock; - private Long oneMinuteException; - private Long oneMinuteTotal; + private String parentTtId; - private boolean visible = true; + private String ttId; - public ResourceVo() { - } + private String resource; - public static List fromNodeVoList(List nodeVos) { - if (nodeVos == null) { - return null; - } - List list = new ArrayList<>(); - for (NodeVo nodeVo : nodeVos) { - ResourceVo vo = new ResourceVo(); - vo.parentTtId = nodeVo.getParentId(); - vo.ttId = nodeVo.getId(); - vo.resource = nodeVo.getResource(); - vo.threadNum = nodeVo.getThreadNum(); - vo.passQps = nodeVo.getPassQps(); - vo.blockQps = nodeVo.getBlockQps(); - vo.totalQps = nodeVo.getTotalQps(); - vo.averageRt = nodeVo.getAverageRt(); - vo.exceptionQps = nodeVo.getExceptionQps(); - vo.oneMinutePass = nodeVo.getOneMinutePass(); - vo.oneMinuteBlock = nodeVo.getOneMinuteBlock(); - vo.oneMinuteException = nodeVo.getOneMinuteException(); - vo.oneMinuteTotal = nodeVo.getOneMinuteTotal(); - list.add(vo); - } - return list; - } + private Integer threadNum; - public static List fromResourceTreeNode(ResourceTreeNode root) { - if (root == null) { - return null; - } - List list = new ArrayList<>(); - visit(root, list, false, true); - //if(!list.isEmpty()){ - // list.remove(0); - //} - return list; - } + private Long passQps; - /** - * This node is visible when this.visible==true or one of this's parents is visible, - * root node is always invisible. - */ - private static void visit(ResourceTreeNode node, List list, boolean parentVisible, boolean isRoot) { - boolean visible = !isRoot && (node.isVisible() || parentVisible); - //boolean visible = node.isVisible(); - if (visible) { - ResourceVo vo = new ResourceVo(); - vo.parentTtId = node.getParentId(); - vo.ttId = node.getId(); - vo.resource = node.getResource(); - vo.threadNum = node.getThreadNum(); - vo.passQps = node.getPassQps(); - vo.blockQps = node.getBlockQps(); - vo.totalQps = node.getTotalQps(); - vo.averageRt = node.getAverageRt(); - vo.exceptionQps = node.getExceptionQps(); - vo.oneMinutePass = node.getOneMinutePass(); - vo.oneMinuteBlock = node.getOneMinuteBlock(); - vo.oneMinuteException = node.getOneMinuteException(); - vo.oneMinuteTotal = node.getOneMinuteTotal(); - vo.visible = node.isVisible(); - list.add(vo); - } - for (ResourceTreeNode c : node.getChildren()) { - visit(c, list, visible, false); - } - } + private Long blockQps; - public String getParentTtId() { - return parentTtId; - } + private Long totalQps; - public void setParentTtId(String parentTtId) { - this.parentTtId = parentTtId; - } + private Long averageRt; - public String getTtId() { - return ttId; - } + private Long passRequestQps; - public void setTtId(String ttId) { - this.ttId = ttId; - } + private Long exceptionQps; - public String getResource() { - return resource; - } + private Long oneMinutePass; - public void setResource(String resource) { - this.resource = resource; - } + private Long oneMinuteBlock; - public Integer getThreadNum() { - return threadNum; - } + private Long oneMinuteException; - public void setThreadNum(Integer threadNum) { - this.threadNum = threadNum; - } + private Long oneMinuteTotal; - public Long getPassQps() { - return passQps; - } + private boolean visible = true; - public void setPassQps(Long passQps) { - this.passQps = passQps; - } + public ResourceVo() { + } - public Long getBlockQps() { - return blockQps; - } + public static List fromNodeVoList(List nodeVos) { + if (nodeVos == null) { + return null; + } + List list = new ArrayList<>(); + for (NodeVo nodeVo : nodeVos) { + ResourceVo vo = new ResourceVo(); + vo.parentTtId = nodeVo.getParentId(); + vo.ttId = nodeVo.getId(); + vo.resource = nodeVo.getResource(); + vo.threadNum = nodeVo.getThreadNum(); + vo.passQps = nodeVo.getPassQps(); + vo.blockQps = nodeVo.getBlockQps(); + vo.totalQps = nodeVo.getTotalQps(); + vo.averageRt = nodeVo.getAverageRt(); + vo.exceptionQps = nodeVo.getExceptionQps(); + vo.oneMinutePass = nodeVo.getOneMinutePass(); + vo.oneMinuteBlock = nodeVo.getOneMinuteBlock(); + vo.oneMinuteException = nodeVo.getOneMinuteException(); + vo.oneMinuteTotal = nodeVo.getOneMinuteTotal(); + list.add(vo); + } + return list; + } - public void setBlockQps(Long blockQps) { - this.blockQps = blockQps; - } + public static List fromResourceTreeNode(ResourceTreeNode root) { + if (root == null) { + return null; + } + List list = new ArrayList<>(); + visit(root, list, false, true); + // if(!list.isEmpty()){ + // list.remove(0); + // } + return list; + } - public Long getTotalQps() { - return totalQps; - } + /** + * This node is visible when this.visible==true or one of this's parents is visible, + * root node is always invisible. + */ + private static void visit(ResourceTreeNode node, List list, boolean parentVisible, boolean isRoot) { + boolean visible = !isRoot && (node.isVisible() || parentVisible); + // boolean visible = node.isVisible(); + if (visible) { + ResourceVo vo = new ResourceVo(); + vo.parentTtId = node.getParentId(); + vo.ttId = node.getId(); + vo.resource = node.getResource(); + vo.threadNum = node.getThreadNum(); + vo.passQps = node.getPassQps(); + vo.blockQps = node.getBlockQps(); + vo.totalQps = node.getTotalQps(); + vo.averageRt = node.getAverageRt(); + vo.exceptionQps = node.getExceptionQps(); + vo.oneMinutePass = node.getOneMinutePass(); + vo.oneMinuteBlock = node.getOneMinuteBlock(); + vo.oneMinuteException = node.getOneMinuteException(); + vo.oneMinuteTotal = node.getOneMinuteTotal(); + vo.visible = node.isVisible(); + list.add(vo); + } + for (ResourceTreeNode c : node.getChildren()) { + visit(c, list, visible, false); + } + } - public void setTotalQps(Long totalQps) { - this.totalQps = totalQps; - } + public String getParentTtId() { + return parentTtId; + } - public Long getAverageRt() { - return averageRt; - } + public void setParentTtId(String parentTtId) { + this.parentTtId = parentTtId; + } - public void setAverageRt(Long averageRt) { - this.averageRt = averageRt; - } + public String getTtId() { + return ttId; + } - public Long getPassRequestQps() { - return passRequestQps; - } + public void setTtId(String ttId) { + this.ttId = ttId; + } - public void setPassRequestQps(Long passRequestQps) { - this.passRequestQps = passRequestQps; - } + public String getResource() { + return resource; + } - public Long getExceptionQps() { - return exceptionQps; - } + public void setResource(String resource) { + this.resource = resource; + } - public void setExceptionQps(Long exceptionQps) { - this.exceptionQps = exceptionQps; - } + public Integer getThreadNum() { + return threadNum; + } - public Long getOneMinuteException() { - return oneMinuteException; - } + public void setThreadNum(Integer threadNum) { + this.threadNum = threadNum; + } - public void setOneMinuteException(Long oneMinuteException) { - this.oneMinuteException = oneMinuteException; - } + public Long getPassQps() { + return passQps; + } - public Long getOneMinutePass() { - return oneMinutePass; - } + public void setPassQps(Long passQps) { + this.passQps = passQps; + } - public void setOneMinutePass(Long oneMinutePass) { - this.oneMinutePass = oneMinutePass; - } + public Long getBlockQps() { + return blockQps; + } - public Long getOneMinuteBlock() { - return oneMinuteBlock; - } + public void setBlockQps(Long blockQps) { + this.blockQps = blockQps; + } - public void setOneMinuteBlock(Long oneMinuteBlock) { - this.oneMinuteBlock = oneMinuteBlock; - } + public Long getTotalQps() { + return totalQps; + } - public Long getOneMinuteTotal() { - return oneMinuteTotal; - } + public void setTotalQps(Long totalQps) { + this.totalQps = totalQps; + } - public void setOneMinuteTotal(Long oneMinuteTotal) { - this.oneMinuteTotal = oneMinuteTotal; - } + public Long getAverageRt() { + return averageRt; + } - public boolean isVisible() { - return visible; - } + public void setAverageRt(Long averageRt) { + this.averageRt = averageRt; + } + + public Long getPassRequestQps() { + return passRequestQps; + } + + public void setPassRequestQps(Long passRequestQps) { + this.passRequestQps = passRequestQps; + } + + public Long getExceptionQps() { + return exceptionQps; + } + + public void setExceptionQps(Long exceptionQps) { + this.exceptionQps = exceptionQps; + } + + public Long getOneMinuteException() { + return oneMinuteException; + } + + public void setOneMinuteException(Long oneMinuteException) { + this.oneMinuteException = oneMinuteException; + } + + public Long getOneMinutePass() { + return oneMinutePass; + } + + public void setOneMinutePass(Long oneMinutePass) { + this.oneMinutePass = oneMinutePass; + } + + public Long getOneMinuteBlock() { + return oneMinuteBlock; + } + + public void setOneMinuteBlock(Long oneMinuteBlock) { + this.oneMinuteBlock = oneMinuteBlock; + } + + public Long getOneMinuteTotal() { + return oneMinuteTotal; + } + + public void setOneMinuteTotal(Long oneMinuteTotal) { + this.oneMinuteTotal = oneMinuteTotal; + } + + public boolean isVisible() { + return visible; + } + + public void setVisible(boolean visible) { + this.visible = visible; + } - public void setVisible(boolean visible) { - this.visible = visible; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/vo/gateway/api/AddApiReqVo.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/vo/gateway/api/AddApiReqVo.java index 445f445cb..22888f73b 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/vo/gateway/api/AddApiReqVo.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/vo/gateway/api/AddApiReqVo.java @@ -25,54 +25,54 @@ import java.util.List; */ public class AddApiReqVo { - private String app; + private String app; - private String ip; + private String ip; - private Integer port; + private Integer port; - private String apiName; + private String apiName; - private List predicateItems; + private List predicateItems; - public String getApp() { - return app; - } + public String getApp() { + return app; + } - public void setApp(String app) { - this.app = app; - } + public void setApp(String app) { + this.app = app; + } - public String getIp() { - return ip; - } + public String getIp() { + return ip; + } - public void setIp(String ip) { - this.ip = ip; - } + public void setIp(String ip) { + this.ip = ip; + } - public Integer getPort() { - return port; - } + public Integer getPort() { + return port; + } - public void setPort(Integer port) { - this.port = port; - } + public void setPort(Integer port) { + this.port = port; + } - public String getApiName() { - return apiName; - } + public String getApiName() { + return apiName; + } - public void setApiName(String apiName) { - this.apiName = apiName; - } + public void setApiName(String apiName) { + this.apiName = apiName; + } - public List getPredicateItems() { - return predicateItems; - } + public List getPredicateItems() { + return predicateItems; + } + + public void setPredicateItems(List predicateItems) { + this.predicateItems = predicateItems; + } - public void setPredicateItems(List predicateItems) { - this.predicateItems = predicateItems; - } } - diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/vo/gateway/api/ApiPredicateItemVo.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/vo/gateway/api/ApiPredicateItemVo.java index d621ddf58..a11cd7c16 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/vo/gateway/api/ApiPredicateItemVo.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/vo/gateway/api/ApiPredicateItemVo.java @@ -23,23 +23,24 @@ package com.alibaba.csp.sentinel.dashboard.domain.vo.gateway.api; */ public class ApiPredicateItemVo { - private String pattern; + private String pattern; - private Integer matchStrategy; + private Integer matchStrategy; - public String getPattern() { - return pattern; - } + public String getPattern() { + return pattern; + } - public void setPattern(String pattern) { - this.pattern = pattern; - } + public void setPattern(String pattern) { + this.pattern = pattern; + } - public Integer getMatchStrategy() { - return matchStrategy; - } + public Integer getMatchStrategy() { + return matchStrategy; + } + + public void setMatchStrategy(Integer matchStrategy) { + this.matchStrategy = matchStrategy; + } - public void setMatchStrategy(Integer matchStrategy) { - this.matchStrategy = matchStrategy; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/vo/gateway/api/UpdateApiReqVo.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/vo/gateway/api/UpdateApiReqVo.java index 3dfd96a28..f41e329c5 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/vo/gateway/api/UpdateApiReqVo.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/vo/gateway/api/UpdateApiReqVo.java @@ -25,33 +25,34 @@ import java.util.List; */ public class UpdateApiReqVo { - private Long id; + private Long id; - private String app; + private String app; - private List predicateItems; + private List predicateItems; - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getApp() { - return app; - } + public String getApp() { + return app; + } - public void setApp(String app) { - this.app = app; - } + public void setApp(String app) { + this.app = app; + } - public List getPredicateItems() { - return predicateItems; - } + public List getPredicateItems() { + return predicateItems; + } + + public void setPredicateItems(List predicateItems) { + this.predicateItems = predicateItems; + } - public void setPredicateItems(List predicateItems) { - this.predicateItems = predicateItems; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/vo/gateway/rule/AddFlowRuleReqVo.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/vo/gateway/rule/AddFlowRuleReqVo.java index 57cc9e2a6..08ac0c658 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/vo/gateway/rule/AddFlowRuleReqVo.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/vo/gateway/rule/AddFlowRuleReqVo.java @@ -23,133 +23,134 @@ package com.alibaba.csp.sentinel.dashboard.domain.vo.gateway.rule; */ public class AddFlowRuleReqVo { - private String app; + private String app; - private String ip; + private String ip; - private Integer port; + private Integer port; - private String resource; + private String resource; - private Integer resourceMode; + private Integer resourceMode; - private Integer grade; + private Integer grade; - private Double count; + private Double count; - private Long interval; + private Long interval; - private Integer intervalUnit; + private Integer intervalUnit; - private Integer controlBehavior; + private Integer controlBehavior; - private Integer burst; + private Integer burst; - private Integer maxQueueingTimeoutMs; + private Integer maxQueueingTimeoutMs; - private GatewayParamFlowItemVo paramItem; + private GatewayParamFlowItemVo paramItem; - public String getApp() { - return app; - } + public String getApp() { + return app; + } - public void setApp(String app) { - this.app = app; - } + public void setApp(String app) { + this.app = app; + } - public String getIp() { - return ip; - } + public String getIp() { + return ip; + } - public void setIp(String ip) { - this.ip = ip; - } + public void setIp(String ip) { + this.ip = ip; + } - public Integer getPort() { - return port; - } + public Integer getPort() { + return port; + } - public void setPort(Integer port) { - this.port = port; - } + public void setPort(Integer port) { + this.port = port; + } - public String getResource() { - return resource; - } + public String getResource() { + return resource; + } - public void setResource(String resource) { - this.resource = resource; - } + public void setResource(String resource) { + this.resource = resource; + } - public Integer getResourceMode() { - return resourceMode; - } + public Integer getResourceMode() { + return resourceMode; + } - public void setResourceMode(Integer resourceMode) { - this.resourceMode = resourceMode; - } + public void setResourceMode(Integer resourceMode) { + this.resourceMode = resourceMode; + } - public Integer getGrade() { - return grade; - } + public Integer getGrade() { + return grade; + } - public void setGrade(Integer grade) { - this.grade = grade; - } + public void setGrade(Integer grade) { + this.grade = grade; + } - public Double getCount() { - return count; - } + public Double getCount() { + return count; + } - public void setCount(Double count) { - this.count = count; - } + public void setCount(Double count) { + this.count = count; + } - public Long getInterval() { - return interval; - } + public Long getInterval() { + return interval; + } - public void setInterval(Long interval) { - this.interval = interval; - } + public void setInterval(Long interval) { + this.interval = interval; + } - public Integer getIntervalUnit() { - return intervalUnit; - } + public Integer getIntervalUnit() { + return intervalUnit; + } - public void setIntervalUnit(Integer intervalUnit) { - this.intervalUnit = intervalUnit; - } + public void setIntervalUnit(Integer intervalUnit) { + this.intervalUnit = intervalUnit; + } - public Integer getControlBehavior() { - return controlBehavior; - } + public Integer getControlBehavior() { + return controlBehavior; + } - public void setControlBehavior(Integer controlBehavior) { - this.controlBehavior = controlBehavior; - } + public void setControlBehavior(Integer controlBehavior) { + this.controlBehavior = controlBehavior; + } - public Integer getBurst() { - return burst; - } + public Integer getBurst() { + return burst; + } - public void setBurst(Integer burst) { - this.burst = burst; - } + public void setBurst(Integer burst) { + this.burst = burst; + } - public Integer getMaxQueueingTimeoutMs() { - return maxQueueingTimeoutMs; - } + public Integer getMaxQueueingTimeoutMs() { + return maxQueueingTimeoutMs; + } - public void setMaxQueueingTimeoutMs(Integer maxQueueingTimeoutMs) { - this.maxQueueingTimeoutMs = maxQueueingTimeoutMs; - } + public void setMaxQueueingTimeoutMs(Integer maxQueueingTimeoutMs) { + this.maxQueueingTimeoutMs = maxQueueingTimeoutMs; + } - public GatewayParamFlowItemVo getParamItem() { - return paramItem; - } + public GatewayParamFlowItemVo getParamItem() { + return paramItem; + } + + public void setParamItem(GatewayParamFlowItemVo paramItem) { + this.paramItem = paramItem; + } - public void setParamItem(GatewayParamFlowItemVo paramItem) { - this.paramItem = paramItem; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/vo/gateway/rule/GatewayParamFlowItemVo.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/vo/gateway/rule/GatewayParamFlowItemVo.java index af24fed96..07c5a91ab 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/vo/gateway/rule/GatewayParamFlowItemVo.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/vo/gateway/rule/GatewayParamFlowItemVo.java @@ -23,43 +23,44 @@ package com.alibaba.csp.sentinel.dashboard.domain.vo.gateway.rule; */ public class GatewayParamFlowItemVo { - private Integer parseStrategy; + private Integer parseStrategy; - private String fieldName; + private String fieldName; - private String pattern; + private String pattern; - private Integer matchStrategy; + private Integer matchStrategy; - public Integer getParseStrategy() { - return parseStrategy; - } + public Integer getParseStrategy() { + return parseStrategy; + } - public void setParseStrategy(Integer parseStrategy) { - this.parseStrategy = parseStrategy; - } + public void setParseStrategy(Integer parseStrategy) { + this.parseStrategy = parseStrategy; + } - public String getFieldName() { - return fieldName; - } + public String getFieldName() { + return fieldName; + } - public void setFieldName(String fieldName) { - this.fieldName = fieldName; - } + public void setFieldName(String fieldName) { + this.fieldName = fieldName; + } - public String getPattern() { - return pattern; - } + public String getPattern() { + return pattern; + } - public void setPattern(String pattern) { - this.pattern = pattern; - } + public void setPattern(String pattern) { + this.pattern = pattern; + } - public Integer getMatchStrategy() { - return matchStrategy; - } + public Integer getMatchStrategy() { + return matchStrategy; + } + + public void setMatchStrategy(Integer matchStrategy) { + this.matchStrategy = matchStrategy; + } - public void setMatchStrategy(Integer matchStrategy) { - this.matchStrategy = matchStrategy; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/vo/gateway/rule/UpdateFlowRuleReqVo.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/vo/gateway/rule/UpdateFlowRuleReqVo.java index 8d1988feb..ebc7b10ae 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/vo/gateway/rule/UpdateFlowRuleReqVo.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/domain/vo/gateway/rule/UpdateFlowRuleReqVo.java @@ -23,103 +23,104 @@ package com.alibaba.csp.sentinel.dashboard.domain.vo.gateway.rule; */ public class UpdateFlowRuleReqVo { - private Long id; + private Long id; - private String app; + private String app; - private Integer grade; + private Integer grade; - private Double count; + private Double count; - private Long interval; + private Long interval; - private Integer intervalUnit; + private Integer intervalUnit; - private Integer controlBehavior; + private Integer controlBehavior; - private Integer burst; + private Integer burst; - private Integer maxQueueingTimeoutMs; + private Integer maxQueueingTimeoutMs; - private GatewayParamFlowItemVo paramItem; + private GatewayParamFlowItemVo paramItem; - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getApp() { - return app; - } + public String getApp() { + return app; + } - public void setApp(String app) { - this.app = app; - } + public void setApp(String app) { + this.app = app; + } - public Integer getGrade() { - return grade; - } + public Integer getGrade() { + return grade; + } - public void setGrade(Integer grade) { - this.grade = grade; - } + public void setGrade(Integer grade) { + this.grade = grade; + } - public Double getCount() { - return count; - } + public Double getCount() { + return count; + } - public void setCount(Double count) { - this.count = count; - } + public void setCount(Double count) { + this.count = count; + } - public Long getInterval() { - return interval; - } + public Long getInterval() { + return interval; + } - public void setInterval(Long interval) { - this.interval = interval; - } + public void setInterval(Long interval) { + this.interval = interval; + } - public Integer getIntervalUnit() { - return intervalUnit; - } + public Integer getIntervalUnit() { + return intervalUnit; + } - public void setIntervalUnit(Integer intervalUnit) { - this.intervalUnit = intervalUnit; - } + public void setIntervalUnit(Integer intervalUnit) { + this.intervalUnit = intervalUnit; + } - public Integer getControlBehavior() { - return controlBehavior; - } + public Integer getControlBehavior() { + return controlBehavior; + } - public void setControlBehavior(Integer controlBehavior) { - this.controlBehavior = controlBehavior; - } + public void setControlBehavior(Integer controlBehavior) { + this.controlBehavior = controlBehavior; + } - public Integer getBurst() { - return burst; - } + public Integer getBurst() { + return burst; + } - public void setBurst(Integer burst) { - this.burst = burst; - } + public void setBurst(Integer burst) { + this.burst = burst; + } - public Integer getMaxQueueingTimeoutMs() { - return maxQueueingTimeoutMs; - } + public Integer getMaxQueueingTimeoutMs() { + return maxQueueingTimeoutMs; + } - public void setMaxQueueingTimeoutMs(Integer maxQueueingTimeoutMs) { - this.maxQueueingTimeoutMs = maxQueueingTimeoutMs; - } + public void setMaxQueueingTimeoutMs(Integer maxQueueingTimeoutMs) { + this.maxQueueingTimeoutMs = maxQueueingTimeoutMs; + } - public GatewayParamFlowItemVo getParamItem() { - return paramItem; - } + public GatewayParamFlowItemVo getParamItem() { + return paramItem; + } + + public void setParamItem(GatewayParamFlowItemVo paramItem) { + this.paramItem = paramItem; + } - public void setParamItem(GatewayParamFlowItemVo paramItem) { - this.paramItem = paramItem; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/metric/MetricFetcher.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/metric/MetricFetcher.java index 2c032249a..345c720e6 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/metric/MetricFetcher.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/metric/MetricFetcher.java @@ -69,308 +69,327 @@ import org.springframework.stereotype.Component; @Component public class MetricFetcher { - public static final String NO_METRICS = "No metrics"; - private static final int HTTP_OK = 200; - private static final long MAX_LAST_FETCH_INTERVAL_MS = 1000 * 15; - private static final long FETCH_INTERVAL_SECOND = 6; - private static final Charset DEFAULT_CHARSET = Charset.forName(SentinelConfig.charset()); - private final static String METRIC_URL_PATH = "metric"; - private static Logger logger = LoggerFactory.getLogger(MetricFetcher.class); - private final long intervalSecond = 1; + public static final String NO_METRICS = "No metrics"; - private Map appLastFetchTime = new ConcurrentHashMap<>(); + private static final int HTTP_OK = 200; - @Autowired - private MetricsRepository metricStore; - @Autowired - private AppManagement appManagement; + private static final long MAX_LAST_FETCH_INTERVAL_MS = 1000 * 15; - private CloseableHttpAsyncClient httpclient; + private static final long FETCH_INTERVAL_SECOND = 6; - @SuppressWarnings("PMD.ThreadPoolCreationRule") - private ScheduledExecutorService fetchScheduleService = Executors.newScheduledThreadPool(1, - new NamedThreadFactory("sentinel-dashboard-metrics-fetch-task")); - private ExecutorService fetchService; - private ExecutorService fetchWorker; + private static final Charset DEFAULT_CHARSET = Charset.forName(SentinelConfig.charset()); - public MetricFetcher() { - int cores = Runtime.getRuntime().availableProcessors() * 2; - long keepAliveTime = 0; - int queueSize = 2048; - RejectedExecutionHandler handler = new DiscardPolicy(); - fetchService = new ThreadPoolExecutor(cores, cores, - keepAliveTime, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(queueSize), - new NamedThreadFactory("sentinel-dashboard-metrics-fetchService"), handler); - fetchWorker = new ThreadPoolExecutor(cores, cores, - keepAliveTime, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(queueSize), - new NamedThreadFactory("sentinel-dashboard-metrics-fetchWorker"), handler); - IOReactorConfig ioConfig = IOReactorConfig.custom() - .setConnectTimeout(3000) - .setSoTimeout(3000) - .setIoThreadCount(Runtime.getRuntime().availableProcessors() * 2) - .build(); + private final static String METRIC_URL_PATH = "metric"; - httpclient = HttpAsyncClients.custom() - .setRedirectStrategy(new DefaultRedirectStrategy() { - @Override - protected boolean isRedirectable(final String method) { - return false; - } - }).setMaxConnTotal(4000) - .setMaxConnPerRoute(1000) - .setDefaultIOReactorConfig(ioConfig) - .build(); - httpclient.start(); - start(); - } + private static Logger logger = LoggerFactory.getLogger(MetricFetcher.class); - private void start() { - fetchScheduleService.scheduleAtFixedRate(() -> { - try { - fetchAllApp(); - } catch (Exception e) { - logger.info("fetchAllApp error:", e); - } - }, 10, intervalSecond, TimeUnit.SECONDS); - } + private final long intervalSecond = 1; - private void writeMetric(Map map) { - if (map.isEmpty()) { - return; - } - Date date = new Date(); - for (MetricEntity entity : map.values()) { - entity.setGmtCreate(date); - entity.setGmtModified(date); - } - metricStore.saveAll(map.values()); - } + private Map appLastFetchTime = new ConcurrentHashMap<>(); - /** - * Traverse each APP, and then pull the metric of all machines for that APP. - */ - private void fetchAllApp() { - List apps = appManagement.getAppNames(); - if (apps == null) { - return; - } - for (final String app : apps) { - fetchService.submit(() -> { - try { - doFetchAppMetric(app); - } catch (Exception e) { - logger.error("fetchAppMetric error", e); - } - }); - } - } + @Autowired + private MetricsRepository metricStore; - /** - * fetch metric between [startTime, endTime], both side inclusive - */ - private void fetchOnce(String app, long startTime, long endTime, int maxWaitSeconds) { - if (maxWaitSeconds <= 0) { - throw new IllegalArgumentException("maxWaitSeconds must > 0, but " + maxWaitSeconds); - } - AppInfo appInfo = appManagement.getDetailApp(app); - // auto remove for app - if (appInfo.isDead()) { - logger.info("Dead app removed: {}", app); - appManagement.removeApp(app); - return; - } - Set machines = appInfo.getMachines(); - logger.debug("enter fetchOnce(" + app + "), machines.size()=" + machines.size() - + ", time intervalMs [" + startTime + ", " + endTime + "]"); - if (machines.isEmpty()) { - return; - } - final String msg = "fetch"; - AtomicLong unhealthy = new AtomicLong(); - final AtomicLong success = new AtomicLong(); - final AtomicLong fail = new AtomicLong(); + @Autowired + private AppManagement appManagement; - long start = System.currentTimeMillis(); - /** app_resource_timeSecond -> metric */ - final Map metricMap = new ConcurrentHashMap<>(16); - final CountDownLatch latch = new CountDownLatch(machines.size()); - for (final MachineInfo machine : machines) { - // auto remove - if (machine.isDead()) { - latch.countDown(); - appManagement.getDetailApp(app).removeMachine(machine.getIp(), machine.getPort()); - logger.info("Dead machine removed: {}:{} of {}", machine.getIp(), machine.getPort(), app); - continue; - } - if (!machine.isHealthy()) { - latch.countDown(); - unhealthy.incrementAndGet(); - continue; - } - final String url = "http://" + machine.getIp() + ":" + machine.getPort() + "/" + METRIC_URL_PATH - + "?startTime=" + startTime + "&endTime=" + endTime + "&refetch=" + false; - final HttpGet httpGet = new HttpGet(url); - httpGet.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE); - httpclient.execute(httpGet, new FutureCallback() { - @Override - public void completed(final HttpResponse response) { - try { - handleResponse(response, machine, metricMap); - success.incrementAndGet(); - } catch (Exception e) { - logger.error(msg + " metric " + url + " error:", e); - } finally { - latch.countDown(); - } - } + private CloseableHttpAsyncClient httpclient; - @Override - public void failed(final Exception ex) { - latch.countDown(); - fail.incrementAndGet(); - httpGet.abort(); - if (ex instanceof SocketTimeoutException) { - logger.error("Failed to fetch metric from <{}>: socket timeout", url); - } else if (ex instanceof ConnectException) { - logger.error("Failed to fetch metric from <{}> (ConnectionException: {})", url, ex.getMessage()); - } else { - logger.error(msg + " metric " + url + " error", ex); - } - } + @SuppressWarnings("PMD.ThreadPoolCreationRule") + private ScheduledExecutorService fetchScheduleService = Executors.newScheduledThreadPool(1, + new NamedThreadFactory("sentinel-dashboard-metrics-fetch-task")); - @Override - public void cancelled() { - latch.countDown(); - fail.incrementAndGet(); - httpGet.abort(); - } - }); - } - try { - latch.await(maxWaitSeconds, TimeUnit.SECONDS); - } catch (Exception e) { - logger.info(msg + " metric, wait http client error:", e); - } - long cost = System.currentTimeMillis() - start; - //logger.info("finished " + msg + " metric for " + app + ", time intervalMs [" + startTime + ", " + endTime - // + "], total machines=" + machines.size() + ", dead=" + dead + ", fetch success=" - // + success + ", fetch fail=" + fail + ", time cost=" + cost + " ms"); - writeMetric(metricMap); - } + private ExecutorService fetchService; - private void doFetchAppMetric(final String app) { - long now = System.currentTimeMillis(); - long lastFetchMs = now - MAX_LAST_FETCH_INTERVAL_MS; - if (appLastFetchTime.containsKey(app)) { - lastFetchMs = Math.max(lastFetchMs, appLastFetchTime.get(app).get() + 1000); - } - // trim milliseconds - lastFetchMs = lastFetchMs / 1000 * 1000; - long endTime = lastFetchMs + FETCH_INTERVAL_SECOND * 1000; - if (endTime > now - 1000 * 2) { - // to near - return; - } - // update last_fetch in advance. - appLastFetchTime.computeIfAbsent(app, a -> new AtomicLong()).set(endTime); - final long finalLastFetchMs = lastFetchMs; - final long finalEndTime = endTime; - try { - // do real fetch async - fetchWorker.submit(() -> { - try { - fetchOnce(app, finalLastFetchMs, finalEndTime, 5); - } catch (Exception e) { - logger.info("fetchOnce(" + app + ") error", e); - } - }); - } catch (Exception e) { - logger.info("submit fetchOnce(" + app + ") fail, intervalMs [" + lastFetchMs + ", " + endTime + "]", e); - } - } + private ExecutorService fetchWorker; - private void handleResponse(final HttpResponse response, MachineInfo machine, - Map metricMap) throws Exception { - int code = response.getStatusLine().getStatusCode(); - if (code != HTTP_OK) { - return; - } - Charset charset = null; - try { - String contentTypeStr = response.getFirstHeader("Content-type").getValue(); - if (StringUtil.isNotEmpty(contentTypeStr)) { - ContentType contentType = ContentType.parse(contentTypeStr); - charset = contentType.getCharset(); - } - } catch (Exception ignore) { - } - String body = EntityUtils.toString(response.getEntity(), charset != null ? charset : DEFAULT_CHARSET); - if (StringUtil.isEmpty(body) || body.startsWith(NO_METRICS)) { - //logger.info(machine.getApp() + ":" + machine.getIp() + ":" + machine.getPort() + ", bodyStr is empty"); - return; - } - String[] lines = body.split("\n"); - //logger.info(machine.getApp() + ":" + machine.getIp() + ":" + machine.getPort() + - // ", bodyStr.length()=" + body.length() + ", lines=" + lines.length); - handleBody(lines, machine, metricMap); - } + public MetricFetcher() { + int cores = Runtime.getRuntime().availableProcessors() * 2; + long keepAliveTime = 0; + int queueSize = 2048; + RejectedExecutionHandler handler = new DiscardPolicy(); + fetchService = new ThreadPoolExecutor(cores, cores, keepAliveTime, TimeUnit.MILLISECONDS, + new ArrayBlockingQueue<>(queueSize), new NamedThreadFactory("sentinel-dashboard-metrics-fetchService"), + handler); + fetchWorker = new ThreadPoolExecutor(cores, cores, keepAliveTime, TimeUnit.MILLISECONDS, + new ArrayBlockingQueue<>(queueSize), new NamedThreadFactory("sentinel-dashboard-metrics-fetchWorker"), + handler); + IOReactorConfig ioConfig = IOReactorConfig.custom().setConnectTimeout(3000).setSoTimeout(3000) + .setIoThreadCount(Runtime.getRuntime().availableProcessors() * 2).build(); - private void handleBody(String[] lines, MachineInfo machine, Map map) { - //logger.info("handleBody() lines=" + lines.length + ", machine=" + machine); - if (lines.length < 1) { - return; - } + httpclient = HttpAsyncClients.custom().setRedirectStrategy(new DefaultRedirectStrategy() { + @Override + protected boolean isRedirectable(final String method) { + return false; + } + }).setMaxConnTotal(4000).setMaxConnPerRoute(1000).setDefaultIOReactorConfig(ioConfig).build(); + httpclient.start(); + start(); + } - for (String line : lines) { - try { - MetricNode node = MetricNode.fromThinString(line); - if (shouldFilterOut(node.getResource())) { - continue; - } - /* - * aggregation metrics by app_resource_timeSecond, ignore ip and port. - */ - String key = buildMetricKey(machine.getApp(), node.getResource(), node.getTimestamp()); - MetricEntity entity = map.get(key); - if (entity != null) { - entity.addPassQps(node.getPassQps()); - entity.addBlockQps(node.getBlockQps()); - entity.addRtAndSuccessQps(node.getRt(), node.getSuccessQps()); - entity.addExceptionQps(node.getExceptionQps()); - entity.addCount(1); - } else { - entity = new MetricEntity(); - entity.setApp(machine.getApp()); - entity.setTimestamp(new Date(node.getTimestamp())); - entity.setPassQps(node.getPassQps()); - entity.setBlockQps(node.getBlockQps()); - entity.setRtAndSuccessQps(node.getRt(), node.getSuccessQps()); - entity.setExceptionQps(node.getExceptionQps()); - entity.setCount(1); - entity.setResource(node.getResource()); - map.put(key, entity); - } - } catch (Exception e) { - logger.warn("handleBody line exception, machine: {}, line: {}", machine.toLogString(), line); - } - } - } + private void start() { + fetchScheduleService.scheduleAtFixedRate(() -> { + try { + fetchAllApp(); + } + catch (Exception e) { + logger.info("fetchAllApp error:", e); + } + }, 10, intervalSecond, TimeUnit.SECONDS); + } - private String buildMetricKey(String app, String resource, long timestamp) { - return app + "__" + resource + "__" + (timestamp / 1000); - } + private void writeMetric(Map map) { + if (map.isEmpty()) { + return; + } + Date date = new Date(); + for (MetricEntity entity : map.values()) { + entity.setGmtCreate(date); + entity.setGmtModified(date); + } + metricStore.saveAll(map.values()); + } - private boolean shouldFilterOut(String resource) { - return RES_EXCLUSION_SET.contains(resource); - } + /** + * Traverse each APP, and then pull the metric of all machines for that APP. + */ + private void fetchAllApp() { + List apps = appManagement.getAppNames(); + if (apps == null) { + return; + } + for (final String app : apps) { + fetchService.submit(() -> { + try { + doFetchAppMetric(app); + } + catch (Exception e) { + logger.error("fetchAppMetric error", e); + } + }); + } + } - private static final Set RES_EXCLUSION_SET = new HashSet() {{ - add(Constants.TOTAL_IN_RESOURCE_NAME); - add(Constants.SYSTEM_LOAD_RESOURCE_NAME); - add(Constants.CPU_USAGE_RESOURCE_NAME); - }}; + /** + * fetch metric between [startTime, endTime], both side inclusive + */ + private void fetchOnce(String app, long startTime, long endTime, int maxWaitSeconds) { + if (maxWaitSeconds <= 0) { + throw new IllegalArgumentException("maxWaitSeconds must > 0, but " + maxWaitSeconds); + } + AppInfo appInfo = appManagement.getDetailApp(app); + // auto remove for app + if (appInfo.isDead()) { + logger.info("Dead app removed: {}", app); + appManagement.removeApp(app); + return; + } + Set machines = appInfo.getMachines(); + logger.debug("enter fetchOnce(" + app + "), machines.size()=" + machines.size() + ", time intervalMs [" + + startTime + ", " + endTime + "]"); + if (machines.isEmpty()) { + return; + } + final String msg = "fetch"; + AtomicLong unhealthy = new AtomicLong(); + final AtomicLong success = new AtomicLong(); + final AtomicLong fail = new AtomicLong(); + + long start = System.currentTimeMillis(); + /** app_resource_timeSecond -> metric */ + final Map metricMap = new ConcurrentHashMap<>(16); + final CountDownLatch latch = new CountDownLatch(machines.size()); + for (final MachineInfo machine : machines) { + // auto remove + if (machine.isDead()) { + latch.countDown(); + appManagement.getDetailApp(app).removeMachine(machine.getIp(), machine.getPort()); + logger.info("Dead machine removed: {}:{} of {}", machine.getIp(), machine.getPort(), app); + continue; + } + if (!machine.isHealthy()) { + latch.countDown(); + unhealthy.incrementAndGet(); + continue; + } + final String url = "http://" + machine.getIp() + ":" + machine.getPort() + "/" + METRIC_URL_PATH + + "?startTime=" + startTime + "&endTime=" + endTime + "&refetch=" + false; + final HttpGet httpGet = new HttpGet(url); + httpGet.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE); + httpclient.execute(httpGet, new FutureCallback() { + @Override + public void completed(final HttpResponse response) { + try { + handleResponse(response, machine, metricMap); + success.incrementAndGet(); + } + catch (Exception e) { + logger.error(msg + " metric " + url + " error:", e); + } + finally { + latch.countDown(); + } + } + + @Override + public void failed(final Exception ex) { + latch.countDown(); + fail.incrementAndGet(); + httpGet.abort(); + if (ex instanceof SocketTimeoutException) { + logger.error("Failed to fetch metric from <{}>: socket timeout", url); + } + else if (ex instanceof ConnectException) { + logger.error("Failed to fetch metric from <{}> (ConnectionException: {})", url, + ex.getMessage()); + } + else { + logger.error(msg + " metric " + url + " error", ex); + } + } + + @Override + public void cancelled() { + latch.countDown(); + fail.incrementAndGet(); + httpGet.abort(); + } + }); + } + try { + latch.await(maxWaitSeconds, TimeUnit.SECONDS); + } + catch (Exception e) { + logger.info(msg + " metric, wait http client error:", e); + } + long cost = System.currentTimeMillis() - start; + // logger.info("finished " + msg + " metric for " + app + ", time intervalMs [" + + // startTime + ", " + endTime + // + "], total machines=" + machines.size() + ", dead=" + dead + ", fetch + // success=" + // + success + ", fetch fail=" + fail + ", time cost=" + cost + " ms"); + writeMetric(metricMap); + } + + private void doFetchAppMetric(final String app) { + long now = System.currentTimeMillis(); + long lastFetchMs = now - MAX_LAST_FETCH_INTERVAL_MS; + if (appLastFetchTime.containsKey(app)) { + lastFetchMs = Math.max(lastFetchMs, appLastFetchTime.get(app).get() + 1000); + } + // trim milliseconds + lastFetchMs = lastFetchMs / 1000 * 1000; + long endTime = lastFetchMs + FETCH_INTERVAL_SECOND * 1000; + if (endTime > now - 1000 * 2) { + // to near + return; + } + // update last_fetch in advance. + appLastFetchTime.computeIfAbsent(app, a -> new AtomicLong()).set(endTime); + final long finalLastFetchMs = lastFetchMs; + final long finalEndTime = endTime; + try { + // do real fetch async + fetchWorker.submit(() -> { + try { + fetchOnce(app, finalLastFetchMs, finalEndTime, 5); + } + catch (Exception e) { + logger.info("fetchOnce(" + app + ") error", e); + } + }); + } + catch (Exception e) { + logger.info("submit fetchOnce(" + app + ") fail, intervalMs [" + lastFetchMs + ", " + endTime + "]", e); + } + } + + private void handleResponse(final HttpResponse response, MachineInfo machine, Map metricMap) + throws Exception { + int code = response.getStatusLine().getStatusCode(); + if (code != HTTP_OK) { + return; + } + Charset charset = null; + try { + String contentTypeStr = response.getFirstHeader("Content-type").getValue(); + if (StringUtil.isNotEmpty(contentTypeStr)) { + ContentType contentType = ContentType.parse(contentTypeStr); + charset = contentType.getCharset(); + } + } + catch (Exception ignore) { + } + String body = EntityUtils.toString(response.getEntity(), charset != null ? charset : DEFAULT_CHARSET); + if (StringUtil.isEmpty(body) || body.startsWith(NO_METRICS)) { + // logger.info(machine.getApp() + ":" + machine.getIp() + ":" + + // machine.getPort() + ", bodyStr is empty"); + return; + } + String[] lines = body.split("\n"); + // logger.info(machine.getApp() + ":" + machine.getIp() + ":" + machine.getPort() + // + + // ", bodyStr.length()=" + body.length() + ", lines=" + lines.length); + handleBody(lines, machine, metricMap); + } + + private void handleBody(String[] lines, MachineInfo machine, Map map) { + // logger.info("handleBody() lines=" + lines.length + ", machine=" + machine); + if (lines.length < 1) { + return; + } + + for (String line : lines) { + try { + MetricNode node = MetricNode.fromThinString(line); + if (shouldFilterOut(node.getResource())) { + continue; + } + /* + * aggregation metrics by app_resource_timeSecond, ignore ip and port. + */ + String key = buildMetricKey(machine.getApp(), node.getResource(), node.getTimestamp()); + MetricEntity entity = map.get(key); + if (entity != null) { + entity.addPassQps(node.getPassQps()); + entity.addBlockQps(node.getBlockQps()); + entity.addRtAndSuccessQps(node.getRt(), node.getSuccessQps()); + entity.addExceptionQps(node.getExceptionQps()); + entity.addCount(1); + } + else { + entity = new MetricEntity(); + entity.setApp(machine.getApp()); + entity.setTimestamp(new Date(node.getTimestamp())); + entity.setPassQps(node.getPassQps()); + entity.setBlockQps(node.getBlockQps()); + entity.setRtAndSuccessQps(node.getRt(), node.getSuccessQps()); + entity.setExceptionQps(node.getExceptionQps()); + entity.setCount(1); + entity.setResource(node.getResource()); + map.put(key, entity); + } + } + catch (Exception e) { + logger.warn("handleBody line exception, machine: {}, line: {}", machine.toLogString(), line); + } + } + } + + private String buildMetricKey(String app, String resource, long timestamp) { + return app + "__" + resource + "__" + (timestamp / 1000); + } + + private boolean shouldFilterOut(String resource) { + return RES_EXCLUSION_SET.contains(resource); + } + + private static final Set RES_EXCLUSION_SET = new HashSet() { + { + add(Constants.TOTAL_IN_RESOURCE_NAME); + add(Constants.SYSTEM_LOAD_RESOURCE_NAME); + add(Constants.CPU_USAGE_RESOURCE_NAME); + } + }; } - - - diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/gateway/InMemApiDefinitionStore.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/gateway/InMemApiDefinitionStore.java index 844acbd51..2e516d857 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/gateway/InMemApiDefinitionStore.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/gateway/InMemApiDefinitionStore.java @@ -30,10 +30,11 @@ import java.util.concurrent.atomic.AtomicLong; @Component public class InMemApiDefinitionStore extends InMemoryRuleRepositoryAdapter { - private static AtomicLong ids = new AtomicLong(0); + private static AtomicLong ids = new AtomicLong(0); + + @Override + protected long nextId() { + return ids.incrementAndGet(); + } - @Override - protected long nextId() { - return ids.incrementAndGet(); - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/gateway/InMemGatewayFlowRuleStore.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/gateway/InMemGatewayFlowRuleStore.java index f1b63c422..a793ef633 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/gateway/InMemGatewayFlowRuleStore.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/gateway/InMemGatewayFlowRuleStore.java @@ -30,10 +30,11 @@ import java.util.concurrent.atomic.AtomicLong; @Component public class InMemGatewayFlowRuleStore extends InMemoryRuleRepositoryAdapter { - private static AtomicLong ids = new AtomicLong(0); + private static AtomicLong ids = new AtomicLong(0); + + @Override + protected long nextId() { + return ids.incrementAndGet(); + } - @Override - protected long nextId() { - return ids.incrementAndGet(); - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/metric/InMemoryMetricsRepository.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/metric/InMemoryMetricsRepository.java index bed4ea1c7..97409b748 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/metric/InMemoryMetricsRepository.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/metric/InMemoryMetricsRepository.java @@ -39,106 +39,106 @@ import org.springframework.stereotype.Component; @Component public class InMemoryMetricsRepository implements MetricsRepository { - private static final long MAX_METRIC_LIVE_TIME_MS = 1000 * 60 * 5; + private static final long MAX_METRIC_LIVE_TIME_MS = 1000 * 60 * 5; - /** - * {@code app -> resource -> timestamp -> metric} - */ - private Map>> allMetrics = new ConcurrentHashMap<>(); + /** + * {@code app -> resource -> timestamp -> metric} + */ + private Map>> allMetrics = new ConcurrentHashMap<>(); + @Override + public synchronized void save(MetricEntity entity) { + if (entity == null || StringUtil.isBlank(entity.getApp())) { + return; + } + allMetrics.computeIfAbsent(entity.getApp(), e -> new ConcurrentHashMap<>(16)) + .computeIfAbsent(entity.getResource(), + e -> new ConcurrentLinkedHashMap.Builder() + .maximumWeightedCapacity(MAX_METRIC_LIVE_TIME_MS).weigher((key, value) -> { + // Metric older than {@link #MAX_METRIC_LIVE_TIME_MS} + // will be removed. + int weight = (int) (System.currentTimeMillis() - key); + // weight must be a number greater than or equal to + // one + return Math.max(weight, 1); + }).build()) + .put(entity.getTimestamp().getTime(), entity); + } + @Override + public synchronized void saveAll(Iterable metrics) { + if (metrics == null) { + return; + } + metrics.forEach(this::save); + } - @Override - public synchronized void save(MetricEntity entity) { - if (entity == null || StringUtil.isBlank(entity.getApp())) { - return; - } - allMetrics.computeIfAbsent(entity.getApp(), e -> new ConcurrentHashMap<>(16)) - .computeIfAbsent(entity.getResource(), e -> new ConcurrentLinkedHashMap.Builder() - .maximumWeightedCapacity(MAX_METRIC_LIVE_TIME_MS).weigher((key, value) -> { - // Metric older than {@link #MAX_METRIC_LIVE_TIME_MS} will be removed. - int weight = (int)(System.currentTimeMillis() - key); - // weight must be a number greater than or equal to one - return Math.max(weight, 1); - }).build()).put(entity.getTimestamp().getTime(), entity); - } + @Override + public synchronized List queryByAppAndResourceBetween(String app, String resource, long startTime, + long endTime) { + List results = new ArrayList<>(); + if (StringUtil.isBlank(app)) { + return results; + } + Map> resourceMap = allMetrics.get(app); + if (resourceMap == null) { + return results; + } + ConcurrentLinkedHashMap metricsMap = resourceMap.get(resource); + if (metricsMap == null) { + return results; + } + for (Entry entry : metricsMap.entrySet()) { + if (entry.getKey() >= startTime && entry.getKey() <= endTime) { + results.add(entry.getValue()); + } + } + return results; + } - @Override - public synchronized void saveAll(Iterable metrics) { - if (metrics == null) { - return; - } - metrics.forEach(this::save); - } + @Override + public List listResourcesOfApp(String app) { + List results = new ArrayList<>(); + if (StringUtil.isBlank(app)) { + return results; + } + // resource -> timestamp -> metric + Map> resourceMap = allMetrics.get(app); + if (resourceMap == null) { + return results; + } + final long minTimeMs = System.currentTimeMillis() - 1000 * 60; + Map resourceCount = new ConcurrentHashMap<>(32); - @Override - public synchronized List queryByAppAndResourceBetween(String app, String resource, - long startTime, long endTime) { - List results = new ArrayList<>(); - if (StringUtil.isBlank(app)) { - return results; - } - Map> resourceMap = allMetrics.get(app); - if (resourceMap == null) { - return results; - } - ConcurrentLinkedHashMap metricsMap = resourceMap.get(resource); - if (metricsMap == null) { - return results; - } - for (Entry entry : metricsMap.entrySet()) { - if (entry.getKey() >= startTime && entry.getKey() <= endTime) { - results.add(entry.getValue()); - } - } - return results; - } + for (Entry> resourceMetrics : resourceMap.entrySet()) { + for (Entry metrics : resourceMetrics.getValue().entrySet()) { + if (metrics.getKey() < minTimeMs) { + continue; + } + MetricEntity newEntity = metrics.getValue(); + if (resourceCount.containsKey(resourceMetrics.getKey())) { + MetricEntity oldEntity = resourceCount.get(resourceMetrics.getKey()); + oldEntity.addPassQps(newEntity.getPassQps()); + oldEntity.addRtAndSuccessQps(newEntity.getRt(), newEntity.getSuccessQps()); + oldEntity.addBlockQps(newEntity.getBlockQps()); + oldEntity.addExceptionQps(newEntity.getExceptionQps()); + oldEntity.addCount(1); + } + else { + resourceCount.put(resourceMetrics.getKey(), MetricEntity.copyOf(newEntity)); + } + } + } + // Order by last minute b_qps DESC. + return resourceCount.entrySet().stream().sorted((o1, o2) -> { + MetricEntity e1 = o1.getValue(); + MetricEntity e2 = o2.getValue(); + int t = e2.getBlockQps().compareTo(e1.getBlockQps()); + if (t != 0) { + return t; + } + return e2.getPassQps().compareTo(e1.getPassQps()); + }).map(Entry::getKey).collect(Collectors.toList()); + } - @Override - public List listResourcesOfApp(String app) { - List results = new ArrayList<>(); - if (StringUtil.isBlank(app)) { - return results; - } - // resource -> timestamp -> metric - Map> resourceMap = allMetrics.get(app); - if (resourceMap == null) { - return results; - } - final long minTimeMs = System.currentTimeMillis() - 1000 * 60; - Map resourceCount = new ConcurrentHashMap<>(32); - - for (Entry> resourceMetrics : resourceMap.entrySet()) { - for (Entry metrics : resourceMetrics.getValue().entrySet()) { - if (metrics.getKey() < minTimeMs) { - continue; - } - MetricEntity newEntity = metrics.getValue(); - if (resourceCount.containsKey(resourceMetrics.getKey())) { - MetricEntity oldEntity = resourceCount.get(resourceMetrics.getKey()); - oldEntity.addPassQps(newEntity.getPassQps()); - oldEntity.addRtAndSuccessQps(newEntity.getRt(), newEntity.getSuccessQps()); - oldEntity.addBlockQps(newEntity.getBlockQps()); - oldEntity.addExceptionQps(newEntity.getExceptionQps()); - oldEntity.addCount(1); - } else { - resourceCount.put(resourceMetrics.getKey(), MetricEntity.copyOf(newEntity)); - } - } - } - // Order by last minute b_qps DESC. - return resourceCount.entrySet() - .stream() - .sorted((o1, o2) -> { - MetricEntity e1 = o1.getValue(); - MetricEntity e2 = o2.getValue(); - int t = e2.getBlockQps().compareTo(e1.getBlockQps()); - if (t != 0) { - return t; - } - return e2.getPassQps().compareTo(e1.getPassQps()); - }) - .map(Entry::getKey) - .collect(Collectors.toList()); - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/metric/MetricsRepository.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/metric/MetricsRepository.java index f54cc2090..6676145be 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/metric/MetricsRepository.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/metric/MetricsRepository.java @@ -25,36 +25,34 @@ import java.util.List; */ public interface MetricsRepository { - /** - * Save the metric to the storage repository. - * - * @param metric metric data to save - */ - void save(T metric); + /** + * Save the metric to the storage repository. + * @param metric metric data to save + */ + void save(T metric); - /** - * Save all metrics to the storage repository. - * - * @param metrics metrics to save - */ - void saveAll(Iterable metrics); + /** + * Save all metrics to the storage repository. + * @param metrics metrics to save + */ + void saveAll(Iterable metrics); - /** - * Get all metrics by {@code appName} and {@code resourceName} between a period of time. - * - * @param app application name for Sentinel - * @param resource resource name - * @param startTime start timestamp - * @param endTime end timestamp - * @return all metrics in query conditions - */ - List queryByAppAndResourceBetween(String app, String resource, long startTime, long endTime); + /** + * Get all metrics by {@code appName} and {@code resourceName} between a period of + * time. + * @param app application name for Sentinel + * @param resource resource name + * @param startTime start timestamp + * @param endTime end timestamp + * @return all metrics in query conditions + */ + List queryByAppAndResourceBetween(String app, String resource, long startTime, long endTime); + + /** + * List resource name of provided application name. + * @param app application name + * @return list of resources + */ + List listResourcesOfApp(String app); - /** - * List resource name of provided application name. - * - * @param app application name - * @return list of resources - */ - List listResourcesOfApp(String app); } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/rule/InMemAuthorityRuleStore.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/rule/InMemAuthorityRuleStore.java index bbeb88891..176577e41 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/rule/InMemAuthorityRuleStore.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/rule/InMemAuthorityRuleStore.java @@ -30,10 +30,11 @@ import org.springframework.stereotype.Component; @Component public class InMemAuthorityRuleStore extends InMemoryRuleRepositoryAdapter { - private static AtomicLong ids = new AtomicLong(0); + private static AtomicLong ids = new AtomicLong(0); + + @Override + protected long nextId() { + return ids.incrementAndGet(); + } - @Override - protected long nextId() { - return ids.incrementAndGet(); - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/rule/InMemDegradeRuleStore.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/rule/InMemDegradeRuleStore.java index 0b9bf7e1a..84ef08960 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/rule/InMemDegradeRuleStore.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/rule/InMemDegradeRuleStore.java @@ -27,10 +27,11 @@ import org.springframework.stereotype.Component; @Component public class InMemDegradeRuleStore extends InMemoryRuleRepositoryAdapter { - private static AtomicLong ids = new AtomicLong(0); + private static AtomicLong ids = new AtomicLong(0); + + @Override + protected long nextId() { + return ids.incrementAndGet(); + } - @Override - protected long nextId() { - return ids.incrementAndGet(); - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/rule/InMemFlowRuleStore.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/rule/InMemFlowRuleStore.java index c5a2a347d..2010b65f0 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/rule/InMemFlowRuleStore.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/rule/InMemFlowRuleStore.java @@ -30,24 +30,25 @@ import org.springframework.stereotype.Component; @Component public class InMemFlowRuleStore extends InMemoryRuleRepositoryAdapter { - private static AtomicLong ids = new AtomicLong(0); + private static AtomicLong ids = new AtomicLong(0); - @Override - protected long nextId() { - return ids.incrementAndGet(); - } + @Override + protected long nextId() { + return ids.incrementAndGet(); + } + + @Override + protected FlowRuleEntity preProcess(FlowRuleEntity entity) { + if (entity != null && entity.isClusterMode()) { + ClusterFlowConfig config = entity.getClusterConfig(); + if (config == null) { + config = new ClusterFlowConfig(); + entity.setClusterConfig(config); + } + // Set cluster rule id. + config.setFlowId(entity.getId()); + } + return entity; + } - @Override - protected FlowRuleEntity preProcess(FlowRuleEntity entity) { - if (entity != null && entity.isClusterMode()) { - ClusterFlowConfig config = entity.getClusterConfig(); - if (config == null) { - config = new ClusterFlowConfig(); - entity.setClusterConfig(config); - } - // Set cluster rule id. - config.setFlowId(entity.getId()); - } - return entity; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/rule/InMemParamFlowRuleStore.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/rule/InMemParamFlowRuleStore.java index 5a82f1387..bf764d19f 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/rule/InMemParamFlowRuleStore.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/rule/InMemParamFlowRuleStore.java @@ -29,23 +29,24 @@ import org.springframework.stereotype.Component; @Component public class InMemParamFlowRuleStore extends InMemoryRuleRepositoryAdapter { - private static AtomicLong ids = new AtomicLong(0); + private static AtomicLong ids = new AtomicLong(0); - @Override - protected long nextId() { - return ids.incrementAndGet(); - } + @Override + protected long nextId() { + return ids.incrementAndGet(); + } + + @Override + protected ParamFlowRuleEntity preProcess(ParamFlowRuleEntity entity) { + if (entity != null && entity.isClusterMode()) { + ParamFlowClusterConfig config = entity.getClusterConfig(); + if (config == null) { + config = new ParamFlowClusterConfig(); + } + // Set cluster rule id. + config.setFlowId(entity.getId()); + } + return entity; + } - @Override - protected ParamFlowRuleEntity preProcess(ParamFlowRuleEntity entity) { - if (entity != null && entity.isClusterMode()) { - ParamFlowClusterConfig config = entity.getClusterConfig(); - if (config == null) { - config = new ParamFlowClusterConfig(); - } - // Set cluster rule id. - config.setFlowId(entity.getId()); - } - return entity; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/rule/InMemSystemRuleStore.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/rule/InMemSystemRuleStore.java index 8d3949b41..a97b6e9ab 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/rule/InMemSystemRuleStore.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/rule/InMemSystemRuleStore.java @@ -27,10 +27,11 @@ import org.springframework.stereotype.Component; @Component public class InMemSystemRuleStore extends InMemoryRuleRepositoryAdapter { - private static AtomicLong ids = new AtomicLong(0); + private static AtomicLong ids = new AtomicLong(0); + + @Override + protected long nextId() { + return ids.incrementAndGet(); + } - @Override - protected long nextId() { - return ids.incrementAndGet(); - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/rule/InMemoryRuleRepositoryAdapter.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/rule/InMemoryRuleRepositoryAdapter.java index 08d623cc3..b97b297e8 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/rule/InMemoryRuleRepositoryAdapter.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/rule/InMemoryRuleRepositoryAdapter.java @@ -29,101 +29,103 @@ import com.alibaba.csp.sentinel.util.AssertUtil; */ public abstract class InMemoryRuleRepositoryAdapter implements RuleRepository { - /** - * {@code >} - */ - private Map> machineRules = new ConcurrentHashMap<>(16); - private Map allRules = new ConcurrentHashMap<>(16); + /** + * {@code >} + */ + private Map> machineRules = new ConcurrentHashMap<>(16); - private Map> appRules = new ConcurrentHashMap<>(16); + private Map allRules = new ConcurrentHashMap<>(16); - private static final int MAX_RULES_SIZE = 10000; + private Map> appRules = new ConcurrentHashMap<>(16); - @Override - public T save(T entity) { - if (entity.getId() == null) { - entity.setId(nextId()); - } - T processedEntity = preProcess(entity); - if (processedEntity != null) { - allRules.put(processedEntity.getId(), processedEntity); - machineRules.computeIfAbsent(MachineInfo.of(processedEntity.getApp(), processedEntity.getIp(), - processedEntity.getPort()), e -> new ConcurrentHashMap<>(32)) - .put(processedEntity.getId(), processedEntity); - appRules.computeIfAbsent(processedEntity.getApp(), v -> new ConcurrentHashMap<>(32)) - .put(processedEntity.getId(), processedEntity); - } + private static final int MAX_RULES_SIZE = 10000; - return processedEntity; - } + @Override + public T save(T entity) { + if (entity.getId() == null) { + entity.setId(nextId()); + } + T processedEntity = preProcess(entity); + if (processedEntity != null) { + allRules.put(processedEntity.getId(), processedEntity); + machineRules + .computeIfAbsent(MachineInfo.of(processedEntity.getApp(), processedEntity.getIp(), + processedEntity.getPort()), e -> new ConcurrentHashMap<>(32)) + .put(processedEntity.getId(), processedEntity); + appRules.computeIfAbsent(processedEntity.getApp(), v -> new ConcurrentHashMap<>(32)) + .put(processedEntity.getId(), processedEntity); + } - @Override - public List saveAll(List rules) { - // TODO: check here. - allRules.clear(); - machineRules.clear(); - appRules.clear(); + return processedEntity; + } - if (rules == null) { - return null; - } - List savedRules = new ArrayList<>(rules.size()); - for (T rule : rules) { - savedRules.add(save(rule)); - } - return savedRules; - } + @Override + public List saveAll(List rules) { + // TODO: check here. + allRules.clear(); + machineRules.clear(); + appRules.clear(); - @Override - public T delete(Long id) { - T entity = allRules.remove(id); - if (entity != null) { - if (appRules.get(entity.getApp()) != null) { - appRules.get(entity.getApp()).remove(id); - } - machineRules.get(MachineInfo.of(entity.getApp(), entity.getIp(), entity.getPort())).remove(id); - } - return entity; - } + if (rules == null) { + return null; + } + List savedRules = new ArrayList<>(rules.size()); + for (T rule : rules) { + savedRules.add(save(rule)); + } + return savedRules; + } - @Override - public T findById(Long id) { - return allRules.get(id); - } + @Override + public T delete(Long id) { + T entity = allRules.remove(id); + if (entity != null) { + if (appRules.get(entity.getApp()) != null) { + appRules.get(entity.getApp()).remove(id); + } + machineRules.get(MachineInfo.of(entity.getApp(), entity.getIp(), entity.getPort())).remove(id); + } + return entity; + } - @Override - public List findAllByMachine(MachineInfo machineInfo) { - Map entities = machineRules.get(machineInfo); - if (entities == null) { - return new ArrayList<>(); - } - return new ArrayList<>(entities.values()); - } + @Override + public T findById(Long id) { + return allRules.get(id); + } - @Override - public List findAllByApp(String appName) { - AssertUtil.notEmpty(appName, "appName cannot be empty"); - Map entities = appRules.get(appName); - if (entities == null) { - return new ArrayList<>(); - } - return new ArrayList<>(entities.values()); - } + @Override + public List findAllByMachine(MachineInfo machineInfo) { + Map entities = machineRules.get(machineInfo); + if (entities == null) { + return new ArrayList<>(); + } + return new ArrayList<>(entities.values()); + } - public void clearAll() { - allRules.clear(); - machineRules.clear(); - appRules.clear(); - } + @Override + public List findAllByApp(String appName) { + AssertUtil.notEmpty(appName, "appName cannot be empty"); + Map entities = appRules.get(appName); + if (entities == null) { + return new ArrayList<>(); + } + return new ArrayList<>(entities.values()); + } - protected T preProcess(T entity) { - return entity; - } + public void clearAll() { + allRules.clear(); + machineRules.clear(); + appRules.clear(); + } + + protected T preProcess(T entity) { + return entity; + } + + /** + * Get next unused id. + * @return next unused id + */ + abstract protected long nextId(); - /** - * Get next unused id. - * - * @return next unused id - */ - abstract protected long nextId(); } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/rule/RuleRepository.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/rule/RuleRepository.java index 266c2fab6..aa3bc2a28 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/rule/RuleRepository.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/rule/RuleRepository.java @@ -26,60 +26,55 @@ import com.alibaba.csp.sentinel.dashboard.discovery.MachineInfo; */ public interface RuleRepository { - /** - * Save one. - * - * @param entity - * @return - */ - T save(T entity); + /** + * Save one. + * @param entity + * @return + */ + T save(T entity); - /** - * Save all. - * - * @param rules - * @return rules saved. - */ - List saveAll(List rules); + /** + * Save all. + * @param rules + * @return rules saved. + */ + List saveAll(List rules); - /** - * Delete by id - * - * @param id - * @return entity deleted - */ - T delete(ID id); + /** + * Delete by id + * @param id + * @return entity deleted + */ + T delete(ID id); - /** - * Find by id. - * - * @param id - * @return - */ - T findById(ID id); + /** + * Find by id. + * @param id + * @return + */ + T findById(ID id); - /** - * Find all by machine. - * - * @param machineInfo - * @return - */ - List findAllByMachine(MachineInfo machineInfo); + /** + * Find all by machine. + * @param machineInfo + * @return + */ + List findAllByMachine(MachineInfo machineInfo); - /** - * Find all by application. - * - * @param appName valid app name - * @return all rules of the application - * @since 1.4.0 - */ - List findAllByApp(String appName); + /** + * Find all by application. + * @param appName valid app name + * @return all rules of the application + * @since 1.4.0 + */ + List findAllByApp(String appName); + + /// ** + // * Find all by app and enable switch. + // * @param app + // * @param enable + // * @return + // */ + // List findAllByAppAndEnable(String app, boolean enable); - ///** - // * Find all by app and enable switch. - // * @param app - // * @param enable - // * @return - // */ - //List findAllByAppAndEnable(String app, boolean enable); } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/DynamicRuleProvider.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/DynamicRuleProvider.java index 7ee38ad16..115449518 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/DynamicRuleProvider.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/DynamicRuleProvider.java @@ -21,5 +21,6 @@ package com.alibaba.csp.sentinel.dashboard.rule; */ public interface DynamicRuleProvider { - T getRules(String appName) throws Exception; + T getRules(String appName) throws Exception; + } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/DynamicRulePublisher.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/DynamicRulePublisher.java index 940d76af8..b49e0dff1 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/DynamicRulePublisher.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/DynamicRulePublisher.java @@ -21,12 +21,12 @@ package com.alibaba.csp.sentinel.dashboard.rule; */ public interface DynamicRulePublisher { - /** - * Publish rules to remote rule configuration center for given application name. - * - * @param app app name - * @param rules list of rules to push - * @throws Exception if some error occurs - */ - void publish(String app, T rules) throws Exception; + /** + * Publish rules to remote rule configuration center for given application name. + * @param app app name + * @param rules list of rules to push + * @throws Exception if some error occurs + */ + void publish(String app, T rules) throws Exception; + } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/FlowRuleApiProvider.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/FlowRuleApiProvider.java index 9f9ce5cc1..95e1e810d 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/FlowRuleApiProvider.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/FlowRuleApiProvider.java @@ -35,25 +35,28 @@ import org.springframework.stereotype.Component; @Component("flowRuleDefaultProvider") public class FlowRuleApiProvider implements DynamicRuleProvider> { - @Autowired - private SentinelApiClient sentinelApiClient; - @Autowired - private AppManagement appManagement; + @Autowired + private SentinelApiClient sentinelApiClient; + + @Autowired + private AppManagement appManagement; + + @Override + public List getRules(String appName) throws Exception { + if (StringUtil.isBlank(appName)) { + return new ArrayList<>(); + } + List list = appManagement.getDetailApp(appName).getMachines().stream() + .filter(MachineInfo::isHealthy) + .sorted((e1, e2) -> Long.compare(e2.getLastHeartbeat(), e1.getLastHeartbeat())) + .collect(Collectors.toList()); + if (list.isEmpty()) { + return new ArrayList<>(); + } + else { + MachineInfo machine = list.get(0); + return sentinelApiClient.fetchFlowRuleOfMachine(machine.getApp(), machine.getIp(), machine.getPort()); + } + } - @Override - public List getRules(String appName) throws Exception { - if (StringUtil.isBlank(appName)) { - return new ArrayList<>(); - } - List list = appManagement.getDetailApp(appName).getMachines() - .stream() - .filter(MachineInfo::isHealthy) - .sorted((e1, e2) -> Long.compare(e2.getLastHeartbeat(), e1.getLastHeartbeat())).collect(Collectors.toList()); - if (list.isEmpty()) { - return new ArrayList<>(); - } else { - MachineInfo machine = list.get(0); - return sentinelApiClient.fetchFlowRuleOfMachine(machine.getApp(), machine.getIp(), machine.getPort()); - } - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/FlowRuleApiPublisher.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/FlowRuleApiPublisher.java index 9afbcf346..74987ec16 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/FlowRuleApiPublisher.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/FlowRuleApiPublisher.java @@ -34,27 +34,29 @@ import org.springframework.stereotype.Component; @Component("flowRuleDefaultPublisher") public class FlowRuleApiPublisher implements DynamicRulePublisher> { - @Autowired - private SentinelApiClient sentinelApiClient; - @Autowired - private AppManagement appManagement; + @Autowired + private SentinelApiClient sentinelApiClient; - @Override - public void publish(String app, List rules) throws Exception { - if (StringUtil.isBlank(app)) { - return; - } - if (rules == null) { - return; - } - Set set = appManagement.getDetailApp(app).getMachines(); + @Autowired + private AppManagement appManagement; + + @Override + public void publish(String app, List rules) throws Exception { + if (StringUtil.isBlank(app)) { + return; + } + if (rules == null) { + return; + } + Set set = appManagement.getDetailApp(app).getMachines(); + + for (MachineInfo machine : set) { + if (!machine.isHealthy()) { + continue; + } + // TODO: parse the results + sentinelApiClient.setFlowRuleOfMachine(app, machine.getIp(), machine.getPort(), rules); + } + } - for (MachineInfo machine : set) { - if (!machine.isHealthy()) { - continue; - } - // TODO: parse the results - sentinelApiClient.setFlowRuleOfMachine(app, machine.getIp(), machine.getPort(), rules); - } - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/service/ClusterAssignService.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/service/ClusterAssignService.java index 79a796ed5..bd9c88aaa 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/service/ClusterAssignService.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/service/ClusterAssignService.java @@ -27,32 +27,30 @@ import com.alibaba.csp.sentinel.dashboard.domain.cluster.request.ClusterAppAssig */ public interface ClusterAssignService { - /** - * Unbind a specific cluster server and its clients. - * - * @param app app name - * @param machineId valid machine ID ({@code host@commandPort}) - * @return assign result - */ - ClusterAppAssignResultVO unbindClusterServer(String app, String machineId); + /** + * Unbind a specific cluster server and its clients. + * @param app app name + * @param machineId valid machine ID ({@code host@commandPort}) + * @return assign result + */ + ClusterAppAssignResultVO unbindClusterServer(String app, String machineId); - /** - * Unbind a set of cluster servers and its clients. - * - * @param app app name - * @param machineIdSet set of valid machine ID ({@code host@commandPort}) - * @return assign result - */ - ClusterAppAssignResultVO unbindClusterServers(String app, Set machineIdSet); + /** + * Unbind a set of cluster servers and its clients. + * @param app app name + * @param machineIdSet set of valid machine ID ({@code host@commandPort}) + * @return assign result + */ + ClusterAppAssignResultVO unbindClusterServers(String app, Set machineIdSet); + + /** + * Apply cluster server and client assignment for provided app. + * @param app app name + * @param clusterMap cluster assign map (server -> clients) + * @param remainingSet unassigned set of machine ID + * @return assign result + */ + ClusterAppAssignResultVO applyAssignToApp(String app, List clusterMap, + Set remainingSet); - /** - * Apply cluster server and client assignment for provided app. - * - * @param app app name - * @param clusterMap cluster assign map (server -> clients) - * @param remainingSet unassigned set of machine ID - * @return assign result - */ - ClusterAppAssignResultVO applyAssignToApp(String app, List clusterMap, - Set remainingSet); } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/service/ClusterAssignServiceImpl.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/service/ClusterAssignServiceImpl.java index 494e7afdb..c9e34fc1f 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/service/ClusterAssignServiceImpl.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/service/ClusterAssignServiceImpl.java @@ -50,221 +50,197 @@ import org.springframework.stereotype.Service; @Service public class ClusterAssignServiceImpl implements ClusterAssignService { - private final Logger LOGGER = LoggerFactory.getLogger(ClusterAssignServiceImpl.class); + private final Logger LOGGER = LoggerFactory.getLogger(ClusterAssignServiceImpl.class); - @Autowired - private SentinelApiClient sentinelApiClient; - @Autowired - private ClusterConfigService clusterConfigService; + @Autowired + private SentinelApiClient sentinelApiClient; - private boolean isMachineInApp(/*@NonEmpty*/ String machineId) { - return machineId.contains(":"); - } + @Autowired + private ClusterConfigService clusterConfigService; - private ClusterAppAssignResultVO handleUnbindClusterServerNotInApp(String app, String machineId) { - Set failedSet = new HashSet<>(); - try { - List list = clusterConfigService.getClusterUniversalState(app) - .get(10, TimeUnit.SECONDS); - Set toModifySet = list.stream() - .filter(e -> e.getState().getStateInfo().getMode() == ClusterStateManager.CLUSTER_CLIENT) - .filter(e -> machineId.equals(e.getState().getClient().getClientConfig().getServerHost() + ':' + - e.getState().getClient().getClientConfig().getServerPort())) - .map(e -> e.getIp() + '@' + e.getCommandPort()) - .collect(Collectors.toSet()); - // Modify mode to NOT-STARTED for all associated token clients. - modifyToNonStarted(toModifySet, failedSet); - } catch (Exception ex) { - Throwable e = ex instanceof ExecutionException ? ex.getCause() : ex; - LOGGER.error("Failed to unbind machine <{}>", machineId, e); - failedSet.add(machineId); - } - return new ClusterAppAssignResultVO() - .setFailedClientSet(failedSet) - .setFailedServerSet(new HashSet<>()); - } + private boolean isMachineInApp(/* @NonEmpty */ String machineId) { + return machineId.contains(":"); + } - private void modifyToNonStarted(Set toModifySet, Set failedSet) { - toModifySet.parallelStream() - .map(MachineUtils::parseCommandIpAndPort) - .filter(Optional::isPresent) - .map(Optional::get) - .map(e -> { - CompletableFuture f = modifyMode(e.r1, e.r2, ClusterStateManager.CLUSTER_NOT_STARTED); - return Tuple2.of(e.r1 + '@' + e.r2, f); - }) - .forEach(f -> handleFutureSync(f, failedSet)); - } + private ClusterAppAssignResultVO handleUnbindClusterServerNotInApp(String app, String machineId) { + Set failedSet = new HashSet<>(); + try { + List list = clusterConfigService.getClusterUniversalState(app).get(10, + TimeUnit.SECONDS); + Set toModifySet = list.stream() + .filter(e -> e.getState().getStateInfo().getMode() == ClusterStateManager.CLUSTER_CLIENT) + .filter(e -> machineId.equals(e.getState().getClient().getClientConfig().getServerHost() + ':' + + e.getState().getClient().getClientConfig().getServerPort())) + .map(e -> e.getIp() + '@' + e.getCommandPort()).collect(Collectors.toSet()); + // Modify mode to NOT-STARTED for all associated token clients. + modifyToNonStarted(toModifySet, failedSet); + } + catch (Exception ex) { + Throwable e = ex instanceof ExecutionException ? ex.getCause() : ex; + LOGGER.error("Failed to unbind machine <{}>", machineId, e); + failedSet.add(machineId); + } + return new ClusterAppAssignResultVO().setFailedClientSet(failedSet).setFailedServerSet(new HashSet<>()); + } - @Override - public ClusterAppAssignResultVO unbindClusterServer(String app, String machineId) { - AssertUtil.assertNotBlank(app, "app cannot be blank"); - AssertUtil.assertNotBlank(machineId, "machineId cannot be blank"); + private void modifyToNonStarted(Set toModifySet, Set failedSet) { + toModifySet.parallelStream().map(MachineUtils::parseCommandIpAndPort).filter(Optional::isPresent) + .map(Optional::get).map(e -> { + CompletableFuture f = modifyMode(e.r1, e.r2, ClusterStateManager.CLUSTER_NOT_STARTED); + return Tuple2.of(e.r1 + '@' + e.r2, f); + }).forEach(f -> handleFutureSync(f, failedSet)); + } - if (isMachineInApp(machineId)) { - return handleUnbindClusterServerNotInApp(app, machineId); - } - Set failedSet = new HashSet<>(); - try { - ClusterGroupEntity entity = clusterConfigService.getClusterUniversalStateForAppMachine(app, machineId) - .get(10, TimeUnit.SECONDS); - Set toModifySet = new HashSet<>(); - toModifySet.add(machineId); - if (entity.getClientSet() != null) { - toModifySet.addAll(entity.getClientSet()); - } - // Modify mode to NOT-STARTED for all chosen token servers and associated token clients. - modifyToNonStarted(toModifySet, failedSet); - } catch (Exception ex) { - Throwable e = ex instanceof ExecutionException ? ex.getCause() : ex; - LOGGER.error("Failed to unbind machine <{}>", machineId, e); - failedSet.add(machineId); - } - return new ClusterAppAssignResultVO() - .setFailedClientSet(failedSet) - .setFailedServerSet(new HashSet<>()); - } + @Override + public ClusterAppAssignResultVO unbindClusterServer(String app, String machineId) { + AssertUtil.assertNotBlank(app, "app cannot be blank"); + AssertUtil.assertNotBlank(machineId, "machineId cannot be blank"); - @Override - public ClusterAppAssignResultVO unbindClusterServers(String app, Set machineIdSet) { - AssertUtil.assertNotBlank(app, "app cannot be blank"); - AssertUtil.isTrue(machineIdSet != null && !machineIdSet.isEmpty(), "machineIdSet cannot be empty"); - ClusterAppAssignResultVO result = new ClusterAppAssignResultVO() - .setFailedClientSet(new HashSet<>()) - .setFailedServerSet(new HashSet<>()); - for (String machineId : machineIdSet) { - ClusterAppAssignResultVO resultVO = unbindClusterServer(app, machineId); - result.getFailedClientSet().addAll(resultVO.getFailedClientSet()); - result.getFailedServerSet().addAll(resultVO.getFailedServerSet()); - } - return result; - } + if (isMachineInApp(machineId)) { + return handleUnbindClusterServerNotInApp(app, machineId); + } + Set failedSet = new HashSet<>(); + try { + ClusterGroupEntity entity = clusterConfigService.getClusterUniversalStateForAppMachine(app, machineId) + .get(10, TimeUnit.SECONDS); + Set toModifySet = new HashSet<>(); + toModifySet.add(machineId); + if (entity.getClientSet() != null) { + toModifySet.addAll(entity.getClientSet()); + } + // Modify mode to NOT-STARTED for all chosen token servers and associated + // token clients. + modifyToNonStarted(toModifySet, failedSet); + } + catch (Exception ex) { + Throwable e = ex instanceof ExecutionException ? ex.getCause() : ex; + LOGGER.error("Failed to unbind machine <{}>", machineId, e); + failedSet.add(machineId); + } + return new ClusterAppAssignResultVO().setFailedClientSet(failedSet).setFailedServerSet(new HashSet<>()); + } - @Override - public ClusterAppAssignResultVO applyAssignToApp(String app, List clusterMap, - Set remainingSet) { - AssertUtil.assertNotBlank(app, "app cannot be blank"); - AssertUtil.notNull(clusterMap, "clusterMap cannot be null"); - Set failedServerSet = new HashSet<>(); - Set failedClientSet = new HashSet<>(); + @Override + public ClusterAppAssignResultVO unbindClusterServers(String app, Set machineIdSet) { + AssertUtil.assertNotBlank(app, "app cannot be blank"); + AssertUtil.isTrue(machineIdSet != null && !machineIdSet.isEmpty(), "machineIdSet cannot be empty"); + ClusterAppAssignResultVO result = new ClusterAppAssignResultVO().setFailedClientSet(new HashSet<>()) + .setFailedServerSet(new HashSet<>()); + for (String machineId : machineIdSet) { + ClusterAppAssignResultVO resultVO = unbindClusterServer(app, machineId); + result.getFailedClientSet().addAll(resultVO.getFailedClientSet()); + result.getFailedServerSet().addAll(resultVO.getFailedServerSet()); + } + return result; + } - // Assign server and apply config. - clusterMap.stream() - .filter(Objects::nonNull) - .filter(ClusterAppAssignMap::getBelongToApp) - .map(e -> { - String ip = e.getIp(); - int commandPort = parsePort(e); - CompletableFuture f = modifyMode(ip, commandPort, ClusterStateManager.CLUSTER_SERVER) - .thenCompose(v -> applyServerConfigChange(app, ip, commandPort, e)); - return Tuple2.of(e.getMachineId(), f); - }) - .forEach(t -> handleFutureSync(t, failedServerSet)); + @Override + public ClusterAppAssignResultVO applyAssignToApp(String app, List clusterMap, + Set remainingSet) { + AssertUtil.assertNotBlank(app, "app cannot be blank"); + AssertUtil.notNull(clusterMap, "clusterMap cannot be null"); + Set failedServerSet = new HashSet<>(); + Set failedClientSet = new HashSet<>(); - // Assign client of servers and apply config. - clusterMap.parallelStream() - .filter(Objects::nonNull) - .forEach(e -> applyAllClientConfigChange(app, e, failedClientSet)); + // Assign server and apply config. + clusterMap.stream().filter(Objects::nonNull).filter(ClusterAppAssignMap::getBelongToApp).map(e -> { + String ip = e.getIp(); + int commandPort = parsePort(e); + CompletableFuture f = modifyMode(ip, commandPort, ClusterStateManager.CLUSTER_SERVER) + .thenCompose(v -> applyServerConfigChange(app, ip, commandPort, e)); + return Tuple2.of(e.getMachineId(), f); + }).forEach(t -> handleFutureSync(t, failedServerSet)); - // Unbind remaining (unassigned) machines. - applyAllRemainingMachineSet(app, remainingSet, failedClientSet); + // Assign client of servers and apply config. + clusterMap.parallelStream().filter(Objects::nonNull) + .forEach(e -> applyAllClientConfigChange(app, e, failedClientSet)); - return new ClusterAppAssignResultVO() - .setFailedClientSet(failedClientSet) - .setFailedServerSet(failedServerSet); - } + // Unbind remaining (unassigned) machines. + applyAllRemainingMachineSet(app, remainingSet, failedClientSet); - private void applyAllRemainingMachineSet(String app, Set remainingSet, Set failedSet) { - if (remainingSet == null || remainingSet.isEmpty()) { - return; - } - remainingSet.parallelStream() - .filter(Objects::nonNull) - .map(MachineUtils::parseCommandIpAndPort) - .filter(Optional::isPresent) - .map(Optional::get) - .map(ipPort -> { - String ip = ipPort.r1; - int commandPort = ipPort.r2; - CompletableFuture f = modifyMode(ip, commandPort, ClusterStateManager.CLUSTER_NOT_STARTED); - return Tuple2.of(ip + '@' + commandPort, f); - }) - .forEach(t -> handleFutureSync(t, failedSet)); - } + return new ClusterAppAssignResultVO().setFailedClientSet(failedClientSet).setFailedServerSet(failedServerSet); + } - private void applyAllClientConfigChange(String app, ClusterAppAssignMap assignMap, - Set failedSet) { - Set clientSet = assignMap.getClientSet(); - if (clientSet == null || clientSet.isEmpty()) { - return; - } - final String serverIp = assignMap.getIp(); - final int serverPort = assignMap.getPort(); - clientSet.stream() - .map(MachineUtils::parseCommandIpAndPort) - .filter(Optional::isPresent) - .map(Optional::get) - .map(ipPort -> { - CompletableFuture f = sentinelApiClient - .modifyClusterMode(ipPort.r1, ipPort.r2, ClusterStateManager.CLUSTER_CLIENT) - .thenCompose(v -> sentinelApiClient.modifyClusterClientConfig(app, ipPort.r1, ipPort.r2, - new ClusterClientConfig().setRequestTimeout(20) - .setServerHost(serverIp) - .setServerPort(serverPort) - )); - return Tuple2.of(ipPort.r1 + '@' + ipPort.r2, f); - }) - .forEach(t -> handleFutureSync(t, failedSet)); - } + private void applyAllRemainingMachineSet(String app, Set remainingSet, Set failedSet) { + if (remainingSet == null || remainingSet.isEmpty()) { + return; + } + remainingSet.parallelStream().filter(Objects::nonNull).map(MachineUtils::parseCommandIpAndPort) + .filter(Optional::isPresent).map(Optional::get).map(ipPort -> { + String ip = ipPort.r1; + int commandPort = ipPort.r2; + CompletableFuture f = modifyMode(ip, commandPort, ClusterStateManager.CLUSTER_NOT_STARTED); + return Tuple2.of(ip + '@' + commandPort, f); + }).forEach(t -> handleFutureSync(t, failedSet)); + } - private void handleFutureSync(Tuple2> t, Set failedSet) { - try { - t.r2.get(10, TimeUnit.SECONDS); - } catch (Exception ex) { - if (ex instanceof ExecutionException) { - LOGGER.error("Request for <{}> failed", t.r1, ex.getCause()); - } else { - LOGGER.error("Request for <{}> failed", t.r1, ex); - } - failedSet.add(t.r1); - } - } + private void applyAllClientConfigChange(String app, ClusterAppAssignMap assignMap, Set failedSet) { + Set clientSet = assignMap.getClientSet(); + if (clientSet == null || clientSet.isEmpty()) { + return; + } + final String serverIp = assignMap.getIp(); + final int serverPort = assignMap.getPort(); + clientSet.stream().map(MachineUtils::parseCommandIpAndPort).filter(Optional::isPresent).map(Optional::get) + .map(ipPort -> { + CompletableFuture f = sentinelApiClient + .modifyClusterMode(ipPort.r1, ipPort.r2, ClusterStateManager.CLUSTER_CLIENT) + .thenCompose(v -> sentinelApiClient.modifyClusterClientConfig(app, ipPort.r1, ipPort.r2, + new ClusterClientConfig().setRequestTimeout(20).setServerHost(serverIp) + .setServerPort(serverPort))); + return Tuple2.of(ipPort.r1 + '@' + ipPort.r2, f); + }).forEach(t -> handleFutureSync(t, failedSet)); + } - private CompletableFuture applyServerConfigChange(String app, String ip, int commandPort, - ClusterAppAssignMap assignMap) { - ServerTransportConfig transportConfig = new ServerTransportConfig() - .setPort(assignMap.getPort()) - .setIdleSeconds(600); - return sentinelApiClient.modifyClusterServerTransportConfig(app, ip, commandPort, transportConfig) - .thenCompose(v -> applyServerFlowConfigChange(app, ip, commandPort, assignMap)) - .thenCompose(v -> applyServerNamespaceSetConfig(app, ip, commandPort, assignMap)); - } + private void handleFutureSync(Tuple2> t, Set failedSet) { + try { + t.r2.get(10, TimeUnit.SECONDS); + } + catch (Exception ex) { + if (ex instanceof ExecutionException) { + LOGGER.error("Request for <{}> failed", t.r1, ex.getCause()); + } + else { + LOGGER.error("Request for <{}> failed", t.r1, ex); + } + failedSet.add(t.r1); + } + } - private CompletableFuture applyServerFlowConfigChange(String app, String ip, int commandPort, - ClusterAppAssignMap assignMap) { - Double maxAllowedQps = assignMap.getMaxAllowedQps(); - if (maxAllowedQps == null || maxAllowedQps <= 0 || maxAllowedQps > 20_0000) { - return CompletableFuture.completedFuture(null); - } - return sentinelApiClient.modifyClusterServerFlowConfig(app, ip, commandPort, - new ServerFlowConfig().setMaxAllowedQps(maxAllowedQps)); - } + private CompletableFuture applyServerConfigChange(String app, String ip, int commandPort, + ClusterAppAssignMap assignMap) { + ServerTransportConfig transportConfig = new ServerTransportConfig().setPort(assignMap.getPort()) + .setIdleSeconds(600); + return sentinelApiClient.modifyClusterServerTransportConfig(app, ip, commandPort, transportConfig) + .thenCompose(v -> applyServerFlowConfigChange(app, ip, commandPort, assignMap)) + .thenCompose(v -> applyServerNamespaceSetConfig(app, ip, commandPort, assignMap)); + } - private CompletableFuture applyServerNamespaceSetConfig(String app, String ip, int commandPort, - ClusterAppAssignMap assignMap) { - Set namespaceSet = assignMap.getNamespaceSet(); - if (namespaceSet == null || namespaceSet.isEmpty()) { - return CompletableFuture.completedFuture(null); - } - return sentinelApiClient.modifyClusterServerNamespaceSet(app, ip, commandPort, namespaceSet); - } + private CompletableFuture applyServerFlowConfigChange(String app, String ip, int commandPort, + ClusterAppAssignMap assignMap) { + Double maxAllowedQps = assignMap.getMaxAllowedQps(); + if (maxAllowedQps == null || maxAllowedQps <= 0 || maxAllowedQps > 20_0000) { + return CompletableFuture.completedFuture(null); + } + return sentinelApiClient.modifyClusterServerFlowConfig(app, ip, commandPort, + new ServerFlowConfig().setMaxAllowedQps(maxAllowedQps)); + } - private CompletableFuture modifyMode(String ip, int port, int mode) { - return sentinelApiClient.modifyClusterMode(ip, port, mode); - } + private CompletableFuture applyServerNamespaceSetConfig(String app, String ip, int commandPort, + ClusterAppAssignMap assignMap) { + Set namespaceSet = assignMap.getNamespaceSet(); + if (namespaceSet == null || namespaceSet.isEmpty()) { + return CompletableFuture.completedFuture(null); + } + return sentinelApiClient.modifyClusterServerNamespaceSet(app, ip, commandPort, namespaceSet); + } + + private CompletableFuture modifyMode(String ip, int port, int mode) { + return sentinelApiClient.modifyClusterMode(ip, port, mode); + } + + private int parsePort(ClusterAppAssignMap assignMap) { + return MachineUtils.parseCommandPort(assignMap.getMachineId()).orElse(ServerTransportConfig.DEFAULT_PORT); + } - private int parsePort(ClusterAppAssignMap assignMap) { - return MachineUtils.parseCommandPort(assignMap.getMachineId()) - .orElse(ServerTransportConfig.DEFAULT_PORT); - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/service/ClusterConfigService.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/service/ClusterConfigService.java index 1691deb01..5ba46ddb2 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/service/ClusterConfigService.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/service/ClusterConfigService.java @@ -48,132 +48,126 @@ import org.springframework.stereotype.Service; @Service public class ClusterConfigService { - @Autowired - private SentinelApiClient sentinelApiClient; - @Autowired - private AppManagement appManagement; + @Autowired + private SentinelApiClient sentinelApiClient; - public CompletableFuture modifyClusterClientConfig(ClusterClientModifyRequest request) { - if (notClientRequestValid(request)) { - throw new IllegalArgumentException("Invalid request"); - } - String app = request.getApp(); - String ip = request.getIp(); - int port = request.getPort(); - return sentinelApiClient.modifyClusterClientConfig(app, ip, port, request.getClientConfig()) - .thenCompose(v -> sentinelApiClient.modifyClusterMode(ip, port, ClusterStateManager.CLUSTER_CLIENT)); - } + @Autowired + private AppManagement appManagement; - private boolean notClientRequestValid(/*@NonNull */ ClusterClientModifyRequest request) { - ClusterClientConfig config = request.getClientConfig(); - return config == null || StringUtil.isEmpty(config.getServerHost()) - || config.getServerPort() == null || config.getServerPort() <= 0 - || config.getRequestTimeout() == null || config.getRequestTimeout() <= 0; - } + public CompletableFuture modifyClusterClientConfig(ClusterClientModifyRequest request) { + if (notClientRequestValid(request)) { + throw new IllegalArgumentException("Invalid request"); + } + String app = request.getApp(); + String ip = request.getIp(); + int port = request.getPort(); + return sentinelApiClient.modifyClusterClientConfig(app, ip, port, request.getClientConfig()) + .thenCompose(v -> sentinelApiClient.modifyClusterMode(ip, port, ClusterStateManager.CLUSTER_CLIENT)); + } - public CompletableFuture modifyClusterServerConfig(ClusterServerModifyRequest request) { - ServerTransportConfig transportConfig = request.getTransportConfig(); - ServerFlowConfig flowConfig = request.getFlowConfig(); - Set namespaceSet = request.getNamespaceSet(); - if (invalidTransportConfig(transportConfig)) { - throw new IllegalArgumentException("Invalid transport config in request"); - } - if (invalidFlowConfig(flowConfig)) { - throw new IllegalArgumentException("Invalid flow config in request"); - } - if (namespaceSet == null) { - throw new IllegalArgumentException("namespace set cannot be null"); - } - String app = request.getApp(); - String ip = request.getIp(); - int port = request.getPort(); - return sentinelApiClient.modifyClusterServerNamespaceSet(app, ip, port, namespaceSet) - .thenCompose(v -> sentinelApiClient.modifyClusterServerTransportConfig(app, ip, port, transportConfig)) - .thenCompose(v -> sentinelApiClient.modifyClusterServerFlowConfig(app, ip, port, flowConfig)) - .thenCompose(v -> sentinelApiClient.modifyClusterMode(ip, port, ClusterStateManager.CLUSTER_SERVER)); - } + private boolean notClientRequestValid(/* @NonNull */ ClusterClientModifyRequest request) { + ClusterClientConfig config = request.getClientConfig(); + return config == null || StringUtil.isEmpty(config.getServerHost()) || config.getServerPort() == null + || config.getServerPort() <= 0 || config.getRequestTimeout() == null || config.getRequestTimeout() <= 0; + } - /** - * Get cluster state list of all available machines of provided application. - * - * @param app application name - * @return cluster state list of all available machines of the application - * @since 1.4.1 - */ - public CompletableFuture> getClusterUniversalState(String app) { - if (StringUtil.isBlank(app)) { - return AsyncUtils.newFailedFuture(new IllegalArgumentException("app cannot be empty")); - } - AppInfo appInfo = appManagement.getDetailApp(app); - if (appInfo == null || appInfo.getMachines() == null) { - return CompletableFuture.completedFuture(new ArrayList<>()); - } + public CompletableFuture modifyClusterServerConfig(ClusterServerModifyRequest request) { + ServerTransportConfig transportConfig = request.getTransportConfig(); + ServerFlowConfig flowConfig = request.getFlowConfig(); + Set namespaceSet = request.getNamespaceSet(); + if (invalidTransportConfig(transportConfig)) { + throw new IllegalArgumentException("Invalid transport config in request"); + } + if (invalidFlowConfig(flowConfig)) { + throw new IllegalArgumentException("Invalid flow config in request"); + } + if (namespaceSet == null) { + throw new IllegalArgumentException("namespace set cannot be null"); + } + String app = request.getApp(); + String ip = request.getIp(); + int port = request.getPort(); + return sentinelApiClient.modifyClusterServerNamespaceSet(app, ip, port, namespaceSet) + .thenCompose(v -> sentinelApiClient.modifyClusterServerTransportConfig(app, ip, port, transportConfig)) + .thenCompose(v -> sentinelApiClient.modifyClusterServerFlowConfig(app, ip, port, flowConfig)) + .thenCompose(v -> sentinelApiClient.modifyClusterMode(ip, port, ClusterStateManager.CLUSTER_SERVER)); + } - List> futures = appInfo.getMachines().stream() - .filter(e -> e.isHealthy()) - .map(machine -> getClusterUniversalState(app, machine.getIp(), machine.getPort()) - .thenApply(e -> new ClusterUniversalStatePairVO(machine.getIp(), machine.getPort(), e))) - .collect(Collectors.toList()); + /** + * Get cluster state list of all available machines of provided application. + * @param app application name + * @return cluster state list of all available machines of the application + * @since 1.4.1 + */ + public CompletableFuture> getClusterUniversalState(String app) { + if (StringUtil.isBlank(app)) { + return AsyncUtils.newFailedFuture(new IllegalArgumentException("app cannot be empty")); + } + AppInfo appInfo = appManagement.getDetailApp(app); + if (appInfo == null || appInfo.getMachines() == null) { + return CompletableFuture.completedFuture(new ArrayList<>()); + } - return AsyncUtils.sequenceSuccessFuture(futures); - } + List> futures = appInfo.getMachines().stream() + .filter(e -> e.isHealthy()) + .map(machine -> getClusterUniversalState(app, machine.getIp(), machine.getPort()) + .thenApply(e -> new ClusterUniversalStatePairVO(machine.getIp(), machine.getPort(), e))) + .collect(Collectors.toList()); - public CompletableFuture getClusterUniversalStateForAppMachine(String app, String machineId) { - if (StringUtil.isBlank(app)) { - return AsyncUtils.newFailedFuture(new IllegalArgumentException("app cannot be empty")); - } - AppInfo appInfo = appManagement.getDetailApp(app); - if (appInfo == null || appInfo.getMachines() == null) { - return AsyncUtils.newFailedFuture(new IllegalArgumentException("app does not have machines")); - } + return AsyncUtils.sequenceSuccessFuture(futures); + } - boolean machineOk = appInfo.getMachines().stream() - .filter(e -> e.isHealthy()) - .map(e -> e.getIp() + '@' + e.getPort()) - .anyMatch(e -> e.equals(machineId)); - if (!machineOk) { - return AsyncUtils.newFailedFuture(new IllegalStateException("machine does not exist or disconnected")); - } + public CompletableFuture getClusterUniversalStateForAppMachine(String app, String machineId) { + if (StringUtil.isBlank(app)) { + return AsyncUtils.newFailedFuture(new IllegalArgumentException("app cannot be empty")); + } + AppInfo appInfo = appManagement.getDetailApp(app); + if (appInfo == null || appInfo.getMachines() == null) { + return AsyncUtils.newFailedFuture(new IllegalArgumentException("app does not have machines")); + } - return getClusterUniversalState(app) - .thenApply(ClusterEntityUtils::wrapToClusterGroup) - .thenCompose(e -> e.stream() - .filter(e1 -> e1.getMachineId().equals(machineId)) - .findAny() - .map(CompletableFuture::completedFuture) - .orElse(AsyncUtils.newFailedFuture(new IllegalStateException("not a server: " + machineId))) - ); - } + boolean machineOk = appInfo.getMachines().stream().filter(e -> e.isHealthy()) + .map(e -> e.getIp() + '@' + e.getPort()).anyMatch(e -> e.equals(machineId)); + if (!machineOk) { + return AsyncUtils.newFailedFuture(new IllegalStateException("machine does not exist or disconnected")); + } - public CompletableFuture getClusterUniversalState(String app, String ip, int port) { - return sentinelApiClient.fetchClusterMode(ip, port) - .thenApply(e -> new ClusterUniversalStateVO().setStateInfo(e)) - .thenCompose(vo -> { - if (vo.getStateInfo().getClientAvailable()) { - return sentinelApiClient.fetchClusterClientInfoAndConfig(ip, port) - .thenApply(cc -> vo.setClient(new ClusterClientStateVO().setClientConfig(cc))); - } else { - return CompletableFuture.completedFuture(vo); - } - }).thenCompose(vo -> { - if (vo.getStateInfo().getServerAvailable()) { - return sentinelApiClient.fetchClusterServerBasicInfo(ip, port) - .thenApply(vo::setServer); - } else { - return CompletableFuture.completedFuture(vo); - } - }); - } + return getClusterUniversalState(app).thenApply(ClusterEntityUtils::wrapToClusterGroup) + .thenCompose(e -> e.stream().filter(e1 -> e1.getMachineId().equals(machineId)).findAny() + .map(CompletableFuture::completedFuture) + .orElse(AsyncUtils.newFailedFuture(new IllegalStateException("not a server: " + machineId)))); + } - private boolean invalidTransportConfig(ServerTransportConfig transportConfig) { - return transportConfig == null || transportConfig.getPort() == null || transportConfig.getPort() <= 0 - || transportConfig.getIdleSeconds() == null || transportConfig.getIdleSeconds() <= 0; - } + public CompletableFuture getClusterUniversalState(String app, String ip, int port) { + return sentinelApiClient.fetchClusterMode(ip, port) + .thenApply(e -> new ClusterUniversalStateVO().setStateInfo(e)).thenCompose(vo -> { + if (vo.getStateInfo().getClientAvailable()) { + return sentinelApiClient.fetchClusterClientInfoAndConfig(ip, port) + .thenApply(cc -> vo.setClient(new ClusterClientStateVO().setClientConfig(cc))); + } + else { + return CompletableFuture.completedFuture(vo); + } + }).thenCompose(vo -> { + if (vo.getStateInfo().getServerAvailable()) { + return sentinelApiClient.fetchClusterServerBasicInfo(ip, port).thenApply(vo::setServer); + } + else { + return CompletableFuture.completedFuture(vo); + } + }); + } + + private boolean invalidTransportConfig(ServerTransportConfig transportConfig) { + return transportConfig == null || transportConfig.getPort() == null || transportConfig.getPort() <= 0 + || transportConfig.getIdleSeconds() == null || transportConfig.getIdleSeconds() <= 0; + } + + private boolean invalidFlowConfig(ServerFlowConfig flowConfig) { + return flowConfig == null || flowConfig.getSampleCount() == null || flowConfig.getSampleCount() <= 0 + || flowConfig.getIntervalMs() == null || flowConfig.getIntervalMs() <= 0 + || flowConfig.getIntervalMs() % flowConfig.getSampleCount() != 0 + || flowConfig.getMaxAllowedQps() == null || flowConfig.getMaxAllowedQps() < 0; + } - private boolean invalidFlowConfig(ServerFlowConfig flowConfig) { - return flowConfig == null || flowConfig.getSampleCount() == null || flowConfig.getSampleCount() <= 0 - || flowConfig.getIntervalMs() == null || flowConfig.getIntervalMs() <= 0 - || flowConfig.getIntervalMs() % flowConfig.getSampleCount() != 0 - || flowConfig.getMaxAllowedQps() == null || flowConfig.getMaxAllowedQps() < 0; - } } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/util/AsyncUtils.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/util/AsyncUtils.java index 9881cdace..fdd98b2ed 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/util/AsyncUtils.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/util/AsyncUtils.java @@ -30,43 +30,39 @@ import org.slf4j.LoggerFactory; */ public final class AsyncUtils { - private static final Logger LOG = LoggerFactory.getLogger(AsyncUtils.class); + private static final Logger LOG = LoggerFactory.getLogger(AsyncUtils.class); - public static CompletableFuture newFailedFuture(Throwable ex) { - CompletableFuture future = new CompletableFuture<>(); - future.completeExceptionally(ex); - return future; - } + public static CompletableFuture newFailedFuture(Throwable ex) { + CompletableFuture future = new CompletableFuture<>(); + future.completeExceptionally(ex); + return future; + } - public static CompletableFuture> sequenceFuture(List> futures) { - return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])) - .thenApply(v -> futures.stream() - .map(AsyncUtils::getValue) - .filter(Objects::nonNull) - .collect(Collectors.toList()) - ); - } + public static CompletableFuture> sequenceFuture(List> futures) { + return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).thenApply( + v -> futures.stream().map(AsyncUtils::getValue).filter(Objects::nonNull).collect(Collectors.toList())); + } - public static CompletableFuture> sequenceSuccessFuture(List> futures) { - return CompletableFuture.supplyAsync(() -> futures.parallelStream() - .map(AsyncUtils::getValue) - .filter(Objects::nonNull) - .collect(Collectors.toList()) - ); - } + public static CompletableFuture> sequenceSuccessFuture(List> futures) { + return CompletableFuture.supplyAsync(() -> futures.parallelStream().map(AsyncUtils::getValue) + .filter(Objects::nonNull).collect(Collectors.toList())); + } - public static T getValue(CompletableFuture future) { - try { - return future.get(10, TimeUnit.SECONDS); - } catch (Exception ex) { - LOG.error("getValue for async result failed", ex); - } - return null; - } + public static T getValue(CompletableFuture future) { + try { + return future.get(10, TimeUnit.SECONDS); + } + catch (Exception ex) { + LOG.error("getValue for async result failed", ex); + } + return null; + } - public static boolean isSuccessFuture(CompletableFuture future) { - return future.isDone() && !future.isCompletedExceptionally() && !future.isCancelled(); - } + public static boolean isSuccessFuture(CompletableFuture future) { + return future.isDone() && !future.isCompletedExceptionally() && !future.isCancelled(); + } + + private AsyncUtils() { + } - private AsyncUtils() {} } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/util/ClusterEntityUtils.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/util/ClusterEntityUtils.java index ced801fa1..a50ffbeca 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/util/ClusterEntityUtils.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/util/ClusterEntityUtils.java @@ -39,130 +39,114 @@ import com.alibaba.csp.sentinel.dashboard.domain.cluster.state.ClusterUniversalS */ public final class ClusterEntityUtils { - public static List wrapToAppClusterServerState( - List list) { - if (list == null || list.isEmpty()) { - return new ArrayList<>(); - } - Map map = new HashMap<>(); - Set tokenServerSet = new HashSet<>(); - // Handle token servers that belong to current app. - for (ClusterUniversalStatePairVO stateVO : list) { - int mode = stateVO.getState().getStateInfo().getMode(); + public static List wrapToAppClusterServerState( + List list) { + if (list == null || list.isEmpty()) { + return new ArrayList<>(); + } + Map map = new HashMap<>(); + Set tokenServerSet = new HashSet<>(); + // Handle token servers that belong to current app. + for (ClusterUniversalStatePairVO stateVO : list) { + int mode = stateVO.getState().getStateInfo().getMode(); - if (mode == ClusterStateManager.CLUSTER_SERVER) { - String ip = stateVO.getIp(); - String serverId = ip + '@' + stateVO.getCommandPort(); - ClusterServerStateVO serverStateVO = stateVO.getState().getServer(); - map.computeIfAbsent(serverId, v -> new AppClusterServerStateWrapVO() - .setId(serverId) - .setIp(ip) - .setPort(serverStateVO.getPort()) - .setState(serverStateVO) - .setBelongToApp(true) - .setConnectedCount(serverStateVO.getConnection().stream() - .mapToInt(ConnectionGroupVO::getConnectedCount) - .sum() - ) - ); - tokenServerSet.add(ip + ":" + serverStateVO.getPort()); - } - } - // Handle token servers from other app. - for (ClusterUniversalStatePairVO stateVO : list) { - int mode = stateVO.getState().getStateInfo().getMode(); + if (mode == ClusterStateManager.CLUSTER_SERVER) { + String ip = stateVO.getIp(); + String serverId = ip + '@' + stateVO.getCommandPort(); + ClusterServerStateVO serverStateVO = stateVO.getState().getServer(); + map.computeIfAbsent(serverId, + v -> new AppClusterServerStateWrapVO().setId(serverId).setIp(ip) + .setPort(serverStateVO.getPort()).setState(serverStateVO).setBelongToApp(true) + .setConnectedCount(serverStateVO.getConnection().stream() + .mapToInt(ConnectionGroupVO::getConnectedCount).sum())); + tokenServerSet.add(ip + ":" + serverStateVO.getPort()); + } + } + // Handle token servers from other app. + for (ClusterUniversalStatePairVO stateVO : list) { + int mode = stateVO.getState().getStateInfo().getMode(); - if (mode == ClusterStateManager.CLUSTER_CLIENT) { - ClusterClientStateVO clientState = stateVO.getState().getClient(); - if (clientState == null) { - continue; - } - String serverIp = clientState.getClientConfig().getServerHost(); - int serverPort = clientState.getClientConfig().getServerPort(); - if (tokenServerSet.contains(serverIp + ":" + serverPort)) { - continue; - } - // We are not able to get the commandPort of foreign token server directly. - String serverId = String.format("%s:%d", serverIp, serverPort); - map.computeIfAbsent(serverId, v -> new AppClusterServerStateWrapVO() - .setId(serverId) - .setIp(serverIp) - .setPort(serverPort) - .setBelongToApp(false) - ); - } - } - return new ArrayList<>(map.values()); - } + if (mode == ClusterStateManager.CLUSTER_CLIENT) { + ClusterClientStateVO clientState = stateVO.getState().getClient(); + if (clientState == null) { + continue; + } + String serverIp = clientState.getClientConfig().getServerHost(); + int serverPort = clientState.getClientConfig().getServerPort(); + if (tokenServerSet.contains(serverIp + ":" + serverPort)) { + continue; + } + // We are not able to get the commandPort of foreign token server + // directly. + String serverId = String.format("%s:%d", serverIp, serverPort); + map.computeIfAbsent(serverId, v -> new AppClusterServerStateWrapVO().setId(serverId).setIp(serverIp) + .setPort(serverPort).setBelongToApp(false)); + } + } + return new ArrayList<>(map.values()); + } - public static List wrapToAppClusterClientState( - List list) { - if (list == null || list.isEmpty()) { - return new ArrayList<>(); - } - Map map = new HashMap<>(); - for (ClusterUniversalStatePairVO stateVO : list) { - int mode = stateVO.getState().getStateInfo().getMode(); + public static List wrapToAppClusterClientState( + List list) { + if (list == null || list.isEmpty()) { + return new ArrayList<>(); + } + Map map = new HashMap<>(); + for (ClusterUniversalStatePairVO stateVO : list) { + int mode = stateVO.getState().getStateInfo().getMode(); - if (mode == ClusterStateManager.CLUSTER_CLIENT) { - String ip = stateVO.getIp(); - String clientId = ip + '@' + stateVO.getCommandPort(); - ClusterClientStateVO clientStateVO = stateVO.getState().getClient(); - map.computeIfAbsent(clientId, v -> new AppClusterClientStateWrapVO() - .setId(clientId) - .setIp(ip) - .setState(clientStateVO) - .setCommandPort(stateVO.getCommandPort()) - ); - } - } - return new ArrayList<>(map.values()); - } + if (mode == ClusterStateManager.CLUSTER_CLIENT) { + String ip = stateVO.getIp(); + String clientId = ip + '@' + stateVO.getCommandPort(); + ClusterClientStateVO clientStateVO = stateVO.getState().getClient(); + map.computeIfAbsent(clientId, v -> new AppClusterClientStateWrapVO().setId(clientId).setIp(ip) + .setState(clientStateVO).setCommandPort(stateVO.getCommandPort())); + } + } + return new ArrayList<>(map.values()); + } - public static List wrapToClusterGroup(List list) { - if (list == null || list.isEmpty()) { - return new ArrayList<>(); - } - Map map = new HashMap<>(); - for (ClusterUniversalStatePairVO stateVO : list) { - int mode = stateVO.getState().getStateInfo().getMode(); - String ip = stateVO.getIp(); - if (mode == ClusterStateManager.CLUSTER_SERVER) { - String serverAddress = getIp(ip); - int port = stateVO.getState().getServer().getPort(); - map.computeIfAbsent(serverAddress, v -> new ClusterGroupEntity() - .setBelongToApp(true).setMachineId(ip + '@' + stateVO.getCommandPort()) - .setIp(ip).setPort(port) - ); - } - } - for (ClusterUniversalStatePairVO stateVO : list) { - int mode = stateVO.getState().getStateInfo().getMode(); - String ip = stateVO.getIp(); - if (mode == ClusterStateManager.CLUSTER_CLIENT) { - String targetServer = stateVO.getState().getClient().getClientConfig().getServerHost(); - Integer targetPort = stateVO.getState().getClient().getClientConfig().getServerPort(); - if (StringUtil.isBlank(targetServer) || targetPort == null || targetPort <= 0) { - continue; - } + public static List wrapToClusterGroup(List list) { + if (list == null || list.isEmpty()) { + return new ArrayList<>(); + } + Map map = new HashMap<>(); + for (ClusterUniversalStatePairVO stateVO : list) { + int mode = stateVO.getState().getStateInfo().getMode(); + String ip = stateVO.getIp(); + if (mode == ClusterStateManager.CLUSTER_SERVER) { + String serverAddress = getIp(ip); + int port = stateVO.getState().getServer().getPort(); + map.computeIfAbsent(serverAddress, v -> new ClusterGroupEntity().setBelongToApp(true) + .setMachineId(ip + '@' + stateVO.getCommandPort()).setIp(ip).setPort(port)); + } + } + for (ClusterUniversalStatePairVO stateVO : list) { + int mode = stateVO.getState().getStateInfo().getMode(); + String ip = stateVO.getIp(); + if (mode == ClusterStateManager.CLUSTER_CLIENT) { + String targetServer = stateVO.getState().getClient().getClientConfig().getServerHost(); + Integer targetPort = stateVO.getState().getClient().getClientConfig().getServerPort(); + if (StringUtil.isBlank(targetServer) || targetPort == null || targetPort <= 0) { + continue; + } - ClusterGroupEntity group = map.computeIfAbsent(targetServer, - v -> new ClusterGroupEntity() - .setBelongToApp(true).setMachineId(targetServer) - .setIp(targetServer).setPort(targetPort) - ); - group.getClientSet().add(ip + '@' + stateVO.getCommandPort()); - } - } - return new ArrayList<>(map.values()); - } + ClusterGroupEntity group = map.computeIfAbsent(targetServer, v -> new ClusterGroupEntity() + .setBelongToApp(true).setMachineId(targetServer).setIp(targetServer).setPort(targetPort)); + group.getClientSet().add(ip + '@' + stateVO.getCommandPort()); + } + } + return new ArrayList<>(map.values()); + } - private static String getIp(String str) { - if (str.contains(":")) { - return str.split(":")[0]; - } - return str; - } + private static String getIp(String str) { + if (str.contains(":")) { + return str.split(":")[0]; + } + return str; + } + + private ClusterEntityUtils() { + } - private ClusterEntityUtils() {} } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/util/MachineUtils.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/util/MachineUtils.java index 5b3073cfe..c21b781df 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/util/MachineUtils.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/util/MachineUtils.java @@ -25,35 +25,39 @@ import com.alibaba.csp.sentinel.util.function.Tuple2; */ public final class MachineUtils { - public static Optional parseCommandPort(String machineIp) { - try { - if (!machineIp.contains("@")) { - return Optional.empty(); - } - String[] str = machineIp.split("@"); - if (str.length <= 1) { - return Optional.empty(); - } - return Optional.of(Integer.parseInt(str[1])); - } catch (Exception ex) { - return Optional.empty(); - } - } + public static Optional parseCommandPort(String machineIp) { + try { + if (!machineIp.contains("@")) { + return Optional.empty(); + } + String[] str = machineIp.split("@"); + if (str.length <= 1) { + return Optional.empty(); + } + return Optional.of(Integer.parseInt(str[1])); + } + catch (Exception ex) { + return Optional.empty(); + } + } - public static Optional> parseCommandIpAndPort(String machineIp) { - try { - if (StringUtil.isEmpty(machineIp) || !machineIp.contains("@")) { - return Optional.empty(); - } - String[] str = machineIp.split("@"); - if (str.length <= 1) { - return Optional.empty(); - } - return Optional.of(Tuple2.of(str[0], Integer.parseInt(str[1]))); - } catch (Exception ex) { - return Optional.empty(); - } - } + public static Optional> parseCommandIpAndPort(String machineIp) { + try { + if (StringUtil.isEmpty(machineIp) || !machineIp.contains("@")) { + return Optional.empty(); + } + String[] str = machineIp.split("@"); + if (str.length <= 1) { + return Optional.empty(); + } + return Optional.of(Tuple2.of(str[0], Integer.parseInt(str[1]))); + } + catch (Exception ex) { + return Optional.empty(); + } + } + + private MachineUtils() { + } - private MachineUtils() {} } diff --git a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/util/VersionUtils.java b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/util/VersionUtils.java index cb013a124..d6d48c6be 100755 --- a/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/util/VersionUtils.java +++ b/pigx-visual/pigx-sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/util/VersionUtils.java @@ -29,67 +29,68 @@ import com.alibaba.csp.sentinel.dashboard.datasource.entity.SentinelVersion; */ public final class VersionUtils { - /** - * Parse version of Sentinel from raw string. - * - * @param versionFull version string - * @return parsed {@link SentinelVersion} if the version is valid; empty if - * there is something wrong with the format - */ - public static Optional parseVersion(String s) { - if (StringUtil.isBlank(s)) { - return Optional.empty(); - } - try { - String versionFull = s; - SentinelVersion version = new SentinelVersion(); - - // postfix - int index = versionFull.indexOf("-"); - if (index == 0) { - // Start with "-" - return Optional.empty(); - } - if (index == versionFull.length() - 1) { - // End with "-" - } else if (index > 0) { - version.setPostfix(versionFull.substring(index + 1)); - } - - if (index >= 0) { - versionFull = versionFull.substring(0, index); - } - - // x.x.x - int segment = 0; - int[] ver = new int[3]; - while (segment < ver.length) { - index = versionFull.indexOf('.'); - if (index < 0) { - if (versionFull.length() > 0) { - ver[segment] = Integer.valueOf(versionFull); - } - break; - } - ver[segment] = Integer.valueOf(versionFull.substring(0, index)); - versionFull = versionFull.substring(index + 1); - segment ++; - } - - if (ver[0] < 1) { - // Wrong format, return empty. - return Optional.empty(); - } else { - return Optional.of(version - .setMajorVersion(ver[0]) - .setMinorVersion(ver[1]) - .setFixVersion(ver[2])); - } - } catch (Exception ex) { - // Parse fail, return empty. - return Optional.empty(); - } - } + /** + * Parse version of Sentinel from raw string. + * @param versionFull version string + * @return parsed {@link SentinelVersion} if the version is valid; empty if there is + * something wrong with the format + */ + public static Optional parseVersion(String s) { + if (StringUtil.isBlank(s)) { + return Optional.empty(); + } + try { + String versionFull = s; + SentinelVersion version = new SentinelVersion(); + + // postfix + int index = versionFull.indexOf("-"); + if (index == 0) { + // Start with "-" + return Optional.empty(); + } + if (index == versionFull.length() - 1) { + // End with "-" + } + else if (index > 0) { + version.setPostfix(versionFull.substring(index + 1)); + } + + if (index >= 0) { + versionFull = versionFull.substring(0, index); + } + + // x.x.x + int segment = 0; + int[] ver = new int[3]; + while (segment < ver.length) { + index = versionFull.indexOf('.'); + if (index < 0) { + if (versionFull.length() > 0) { + ver[segment] = Integer.valueOf(versionFull); + } + break; + } + ver[segment] = Integer.valueOf(versionFull.substring(0, index)); + versionFull = versionFull.substring(index + 1); + segment++; + } + + if (ver[0] < 1) { + // Wrong format, return empty. + return Optional.empty(); + } + else { + return Optional.of(version.setMajorVersion(ver[0]).setMinorVersion(ver[1]).setFixVersion(ver[2])); + } + } + catch (Exception ex) { + // Parse fail, return empty. + return Optional.empty(); + } + } + + private VersionUtils() { + } - private VersionUtils() {} } diff --git a/pigx-visual/pigx-sso-client-demo/src/main/java/com/pig4cloud/pigx/sso/PigxSsoClientDemoApplication.java b/pigx-visual/pigx-sso-client-demo/src/main/java/com/pig4cloud/pigx/sso/PigxSsoClientDemoApplication.java index 418be74dc..94258cc10 100644 --- a/pigx-visual/pigx-sso-client-demo/src/main/java/com/pig4cloud/pigx/sso/PigxSsoClientDemoApplication.java +++ b/pigx-visual/pigx-sso-client-demo/src/main/java/com/pig4cloud/pigx/sso/PigxSsoClientDemoApplication.java @@ -25,9 +25,8 @@ import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth * @author lengleng * @date 2018年11月15日17:06:26 *

- * 单点登录客户端 - * 1. 启动实例访问:http://localhost:4040/sso1/ 提示登录,然后获取到用户信息 - * 2. 再启动一个实例: http://localhost:4041/sso1/ 不需要登录即可获取当前用户信息 + * 单点登录客户端 1. 启动实例访问:http://localhost:4040/sso1/ 提示登录,然后获取到用户信息 2. 再启动一个实例: + * http://localhost:4041/sso1/ 不需要登录即可获取当前用户信息 */ @EnableOAuth2Sso @SpringBootApplication diff --git a/pigx-visual/pigx-sso-client-demo/src/main/java/com/pig4cloud/pigx/sso/controller/DemoController.java b/pigx-visual/pigx-sso-client-demo/src/main/java/com/pig4cloud/pigx/sso/controller/DemoController.java index 0fc1b2d0c..8aa57b708 100644 --- a/pigx-visual/pigx-sso-client-demo/src/main/java/com/pig4cloud/pigx/sso/controller/DemoController.java +++ b/pigx-visual/pigx-sso-client-demo/src/main/java/com/pig4cloud/pigx/sso/controller/DemoController.java @@ -23,13 +23,14 @@ import org.springframework.web.bind.annotation.RestController; /** * @author lengleng - * @date 2018/1/27 - * demo controller + * @date 2018/1/27 demo controller */ @RestController public class DemoController { - @GetMapping("/user") - public Authentication user(Authentication authentication) { - return authentication; - } + + @GetMapping("/user") + public Authentication user(Authentication authentication) { + return authentication; + } + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/PigxTxManagerApplication.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/PigxTxManagerApplication.java index 21d07c7fc..f33c983ae 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/PigxTxManagerApplication.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/PigxTxManagerApplication.java @@ -22,13 +22,11 @@ import org.springframework.cloud.client.SpringCloudApplication; /** * @author LCN - * @author lengleng - * tx-manager ,进行了代码逻辑和代码规范重构 + * @author lengleng tx-manager ,进行了代码逻辑和代码规范重构 */ @SpringCloudApplication public class PigxTxManagerApplication { - public static void main(String[] args) { SpringApplication.run(PigxTxManagerApplication.class, args); } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/api/controller/AdminController.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/api/controller/AdminController.java index 13101c621..1624c804f 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/api/controller/AdminController.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/api/controller/AdminController.java @@ -42,22 +42,21 @@ import java.util.Map; @AllArgsConstructor @RequestMapping("/admin") public class AdminController { - private final ApiAdminService apiAdminService; - private final ApiModelService apiModelService; + private final ApiAdminService apiAdminService; + + private final ApiModelService apiModelService; @RequestMapping(value = "/onlines", method = RequestMethod.GET) public List onlines() { return apiModelService.onlines(); } - @RequestMapping(value = "/avueOnlines", method = RequestMethod.GET) public List avueOnlines() { return apiModelService.onlines(); } - @RequestMapping(value = "/setting", method = RequestMethod.GET) public TxState setting() { return apiAdminService.getState(); @@ -83,7 +82,6 @@ public class AdminController { return apiAdminService.modelTimes(model); } - @RequestMapping(value = "/modelInfos", method = RequestMethod.GET) public List modelInfos(@RequestParam("path") String path) { return apiAdminService.modelInfos(path); @@ -106,4 +104,5 @@ public class AdminController { public boolean hasCompensate() { return apiAdminService.hasCompensate(); } + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/api/controller/TxManagerController.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/api/controller/TxManagerController.java index 0dd42d2fe..5096c19be 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/api/controller/TxManagerController.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/api/controller/TxManagerController.java @@ -26,8 +26,7 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** - *@author LCN on 2017/7/1. - * + * @author LCN on 2017/7/1. * @author LCN * @author lengleng */ @@ -35,6 +34,7 @@ import org.springframework.web.bind.annotation.RestController; @AllArgsConstructor @RequestMapping("/tx/manager") public class TxManagerController { + private final ApiTxManagerService apiTxManagerService; @RequestMapping("/getServer") @@ -42,32 +42,29 @@ public class TxManagerController { return apiTxManagerService.getServer(); } - @RequestMapping("/cleanNotifyTransaction") public int cleanNotifyTransaction(@RequestParam("groupId") String groupId, @RequestParam("taskId") String taskId) { return apiTxManagerService.cleanNotifyTransaction(groupId, taskId); } - @RequestMapping("/sendMsg") public String sendMsg(@RequestParam("msg") String msg, @RequestParam("model") String model) { return apiTxManagerService.sendMsg(model, msg); } - @RequestMapping("/sendCompensateMsg") public boolean sendCompensateMsg(@RequestParam("model") String model, @RequestParam("uniqueKey") String uniqueKey, - @RequestParam("currentTime") long currentTime, - @RequestParam("groupId") String groupId, @RequestParam("className") String className, - @RequestParam("time") int time, @RequestParam("data") String data, - @RequestParam("methodStr") String methodStr, @RequestParam("address") String address, - @RequestParam("startError") int startError) { - return apiTxManagerService.sendCompensateMsg(currentTime, groupId, model, address, uniqueKey, className, methodStr, data, time, startError); + @RequestParam("currentTime") long currentTime, @RequestParam("groupId") String groupId, + @RequestParam("className") String className, @RequestParam("time") int time, + @RequestParam("data") String data, @RequestParam("methodStr") String methodStr, + @RequestParam("address") String address, @RequestParam("startError") int startError) { + return apiTxManagerService.sendCompensateMsg(currentTime, groupId, model, address, uniqueKey, className, + methodStr, data, time, startError); } - @RequestMapping("/state") public TxState state() { return apiTxManagerService.getState(); } + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/api/service/ApiAdminService.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/api/service/ApiAdminService.java index a9e22695f..d11a8e6f8 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/api/service/ApiAdminService.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/api/service/ApiAdminService.java @@ -35,7 +35,6 @@ public interface ApiAdminService { /** * k/v 获取 值封装成map - * * @return */ List> getMapState(); @@ -44,7 +43,6 @@ public interface ApiAdminService { List modelList(); - List modelTimes(String model); List modelInfos(String path); @@ -54,4 +52,5 @@ public interface ApiAdminService { boolean hasCompensate(); boolean delCompensate(String path); + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/api/service/ApiModelService.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/api/service/ApiModelService.java index 876f86d3d..4ab08af75 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/api/service/ApiModelService.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/api/service/ApiModelService.java @@ -29,5 +29,4 @@ public interface ApiModelService { List onlines(); - } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/api/service/ApiTxManagerService.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/api/service/ApiTxManagerService.java index 6bd651da7..5ecb3f129 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/api/service/ApiTxManagerService.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/api/service/ApiTxManagerService.java @@ -21,59 +21,52 @@ import com.pig4cloud.pigx.manager.model.TxServer; import com.pig4cloud.pigx.manager.model.TxState; /** - *@author LCN on 2017/7/1. + * @author LCN on 2017/7/1. */ public interface ApiTxManagerService { - /** * 获取本服务的信息 - * * @return 服务信息 */ TxServer getServer(); - /** * 给 tx模块发送指令 - * * @param model 模块名称 - * @param msg 指令 + * @param msg 指令 * @return 指令返回结果 */ String sendMsg(String model, String msg); /** * 检查并清理事务数据 - * * @param groupId 事务组Id - * @param taskId 任务Id + * @param taskId 任务Id * @param isGroup 是否合并事务 * @return 事务状态 */ int cleanNotifyTransaction(String groupId, String taskId); - /** * 保存事务补偿日志信息 - * * @param currentTime 时间 - * @param groupId 事务组id - * @param model 模块名称 - * @param address 模块地址 - * @param uniqueKey 唯一标示 - * @param className 事务启动类 - * @param methodStr 事务启动方法 - * @param data 切面数据 - * @param time 执行时间 - * @param startError 启动模块异常 + * @param groupId 事务组id + * @param model 模块名称 + * @param address 模块地址 + * @param uniqueKey 唯一标示 + * @param className 事务启动类 + * @param methodStr 事务启动方法 + * @param data 切面数据 + * @param time 执行时间 + * @param startError 启动模块异常 * @return 是否保存成功 */ - boolean sendCompensateMsg(long currentTime, String groupId, String model, String address, String uniqueKey, String className, String methodStr, String data, int time, int startError); + boolean sendCompensateMsg(long currentTime, String groupId, String model, String address, String uniqueKey, + String className, String methodStr, String data, int time, int startError); /** * 获取服务器状态 - * * @return 状态 */ TxState getState(); diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/api/service/impl/ApiAdminServiceImpl.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/api/service/impl/ApiAdminServiceImpl.java index d8b3844fb..1e7f7c3ac 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/api/service/impl/ApiAdminServiceImpl.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/api/service/impl/ApiAdminServiceImpl.java @@ -17,7 +17,6 @@ package com.pig4cloud.pigx.manager.api.service.impl; - import cn.hutool.core.util.StrUtil; import com.pig4cloud.pigx.manager.api.service.ApiAdminService; import com.pig4cloud.pigx.manager.compensate.model.TxModel; @@ -43,8 +42,11 @@ import java.util.Map; @Service @AllArgsConstructor public class ApiAdminServiceImpl implements ApiAdminService { + private final MicroService eurekaService; + private final RedisServerService redisServerService; + private final CompensateService compensateService; @Override @@ -54,7 +56,6 @@ public class ApiAdminServiceImpl implements ApiAdminService { /** * k/v 获取 值封装成map - * * @return */ @Override @@ -96,7 +97,6 @@ public class ApiAdminServiceImpl implements ApiAdminService { return compensateService.loadModelList(); } - @Override public List modelTimes(String model) { return compensateService.loadCompensateTimes(model); @@ -122,4 +122,5 @@ public class ApiAdminServiceImpl implements ApiAdminService { public boolean hasCompensate() { return compensateService.hasCompensate(); } + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/api/service/impl/ApiModelServiceImpl.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/api/service/impl/ApiModelServiceImpl.java index f0ba20bc7..15670bb26 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/api/service/impl/ApiModelServiceImpl.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/api/service/impl/ApiModelServiceImpl.java @@ -31,11 +31,9 @@ import java.util.List; @Service public class ApiModelServiceImpl implements ApiModelService { - @Override public List onlines() { return ModelInfoManager.getInstance().getOnlines(); } - } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/api/service/impl/ApiTxManagerServiceImpl.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/api/service/impl/ApiTxManagerServiceImpl.java index 5815d4d59..df4a27321 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/api/service/impl/ApiTxManagerServiceImpl.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/api/service/impl/ApiTxManagerServiceImpl.java @@ -17,7 +17,6 @@ package com.pig4cloud.pigx.manager.api.service.impl; - import com.pig4cloud.pigx.manager.api.service.ApiTxManagerService; import com.pig4cloud.pigx.manager.compensate.model.TransactionCompensateMsg; import com.pig4cloud.pigx.manager.compensate.service.CompensateService; @@ -31,8 +30,7 @@ import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; /** - *@author LCN on 2017/7/1. - * + * @author LCN on 2017/7/1. * @author LCN * @author lengleng */ @@ -50,22 +48,21 @@ public class ApiTxManagerServiceImpl implements ApiTxManagerService { private final ConfigReader configReader; - @Override public TxServer getServer() { return eurekaService.getServer(); } - @Override public int cleanNotifyTransaction(String groupId, String taskId) { return managerService.cleanNotifyTransaction(groupId, taskId); } - @Override - public boolean sendCompensateMsg(long currentTime, String groupId, String model, String address, String uniqueKey, String className, String methodStr, String data, int time, int startError) { - TransactionCompensateMsg transactionCompensateMsg = new TransactionCompensateMsg(currentTime, groupId, model, address, uniqueKey, className, methodStr, data, time, 0, startError); + public boolean sendCompensateMsg(long currentTime, String groupId, String model, String address, String uniqueKey, + String className, String methodStr, String data, int time, int startError) { + TransactionCompensateMsg transactionCompensateMsg = new TransactionCompensateMsg(currentTime, groupId, model, + address, uniqueKey, className, methodStr, data, time, 0, startError); return compensateService.saveCompensateMsg(transactionCompensateMsg); } @@ -74,9 +71,9 @@ public class ApiTxManagerServiceImpl implements ApiTxManagerService { return txManagerSenderService.sendMsg(model, msg, configReader.getTransactionNettyDelayTime()); } - @Override public TxState getState() { return eurekaService.getState(); } + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/compensate/dao/CompensateDao.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/compensate/dao/CompensateDao.java index 60e58f9ca..ea4c818ec 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/compensate/dao/CompensateDao.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/compensate/dao/CompensateDao.java @@ -43,4 +43,5 @@ public interface CompensateDao { void deleteCompensateByKey(String key); boolean hasCompensate(); + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/compensate/dao/impl/CompensateDaoImpl.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/compensate/dao/impl/CompensateDaoImpl.java index 60ce02c4f..d863736c4 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/compensate/dao/impl/CompensateDaoImpl.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/compensate/dao/impl/CompensateDaoImpl.java @@ -35,18 +35,18 @@ import java.util.List; @Service public class CompensateDaoImpl implements CompensateDao { - @Autowired private RedisServerService redisServerService; @Autowired private ConfigReader configReader; - @Override public String saveCompensateMsg(TransactionCompensateMsg transactionCompensateMsg) { - String name = String.format("%s%s:%s:%s.json", configReader.getKeyPrefixCompensate(), transactionCompensateMsg.getModel(), DateUtil.getCurrentDateFormat(), transactionCompensateMsg.getGroupId()); + String name = String.format("%s%s:%s:%s.json", configReader.getKeyPrefixCompensate(), + transactionCompensateMsg.getModel(), DateUtil.getCurrentDateFormat(), + transactionCompensateMsg.getGroupId()); String json = JSON.toJSONString(transactionCompensateMsg); @@ -55,14 +55,12 @@ public class CompensateDaoImpl implements CompensateDao { return name; } - @Override public List loadCompensateKeys() { String key = configReader.getKeyPrefixCompensate() + "*"; return redisServerService.getKeys(key); } - @Override public boolean hasCompensate() { String key = configReader.getKeyPrefixCompensate() + "*"; @@ -86,7 +84,6 @@ public class CompensateDaoImpl implements CompensateDao { return times; } - @Override public List loadCompensateByModelAndTime(String path) { String key = String.format("%s%s*", configReader.getKeyPrefixCompensate(), path); @@ -101,14 +98,12 @@ public class CompensateDaoImpl implements CompensateDao { return redisServerService.getValueByKey(key); } - @Override public void deleteCompensateByPath(String path) { String key = String.format("%s%s.json", configReader.getKeyPrefixCompensate(), path); redisServerService.deleteKey(key); } - @Override public void deleteCompensateByKey(String key) { redisServerService.deleteKey(key); @@ -124,4 +119,5 @@ public class CompensateDaoImpl implements CompensateDao { } return null; } + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/compensate/model/TransactionCompensateMsg.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/compensate/model/TransactionCompensateMsg.java index 84ff0c6d0..10d409f89 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/compensate/model/TransactionCompensateMsg.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/compensate/model/TransactionCompensateMsg.java @@ -25,24 +25,31 @@ import com.pig4cloud.pigx.manager.netty.model.TxGroup; public class TransactionCompensateMsg { private long currentTime; + private String groupId; + private String model; + private String address; + private String uniqueKey; + private String className; + private String methodStr; + private String data; + private int time; + private int startError; private TxGroup txGroup; private int state; - - public TransactionCompensateMsg(long currentTime, String groupId, String model, String address, - String uniqueKey, String className, - String methodStr, String data, int time, int state, int startError) { + public TransactionCompensateMsg(long currentTime, String groupId, String model, String address, String uniqueKey, + String className, String methodStr, String data, int time, int state, int startError) { this.currentTime = currentTime; this.groupId = groupId; this.model = model; @@ -128,7 +135,6 @@ public class TransactionCompensateMsg { this.className = className; } - public String getMethodStr() { return methodStr; } @@ -152,4 +158,5 @@ public class TransactionCompensateMsg { public void setTime(int time) { this.time = time; } + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/compensate/model/TxModel.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/compensate/model/TxModel.java index 493174f53..ef197a5bd 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/compensate/model/TxModel.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/compensate/model/TxModel.java @@ -101,4 +101,5 @@ public class TxModel { public void setState(int state) { this.state = state; } + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/compensate/service/CompensateService.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/compensate/service/CompensateService.java index 8900f3bdd..9abf35251 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/compensate/service/CompensateService.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/compensate/service/CompensateService.java @@ -49,4 +49,5 @@ public interface CompensateService { boolean delCompensate(String path); TxGroup getCompensateByGroupId(String groupId); + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/compensate/service/impl/CompensateServiceImpl.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/compensate/service/impl/CompensateServiceImpl.java index bfc371360..8588192d4 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/compensate/service/impl/CompensateServiceImpl.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/compensate/service/impl/CompensateServiceImpl.java @@ -51,8 +51,11 @@ import java.util.concurrent.Executor; */ @Service public class CompensateServiceImpl implements CompensateService { + private static final String SUCCESS = "success"; + private static final String SUCCESS1 = "SUCCESS"; + private Logger logger = LoggerFactory.getLogger(CompensateServiceImpl.class); @Autowired @@ -75,12 +78,13 @@ public class CompensateServiceImpl implements CompensateService { TxGroup txGroup = managerService.getTxGroup(transactionCompensateMsg.getGroupId()); if (txGroup == null) { - //仅发起方异常,其他模块正常 + // 仅发起方异常,其他模块正常 txGroup = new TxGroup(); txGroup.setNowTime(System.currentTimeMillis()); txGroup.setGroupId(transactionCompensateMsg.getGroupId()); txGroup.setIsCompensate(1); - } else { + } + else { managerService.deleteTxGroup(txGroup); } @@ -92,7 +96,7 @@ public class CompensateServiceImpl implements CompensateService { final String compensateKey = compensateDao.saveCompensateMsg(transactionCompensateMsg); - //调整自动补偿机制,若开启了自动补偿,需要通知业务返回success,方可执行自动补偿 + // 调整自动补偿机制,若开启了自动补偿,需要通知业务返回success,方可执行自动补偿 threadPool.execute(new Runnable() { @Override public void run() { @@ -108,13 +112,14 @@ public class CompensateServiceImpl implements CompensateService { String res = HttpUtils.postJson(url, requestJson.toJSONString()); logger.error("Compensate Callback Result->" + res); if (configReader.isCompensateAuto()) { - //自动补偿,是否自动执行补偿 + // 自动补偿,是否自动执行补偿 if (res.contains(SUCCESS) || res.contains(SUCCESS1)) { - //自动补偿 + // 自动补偿 autoCompensate(compensateKey, transactionCompensateMsg); } } - } catch (Exception e) { + } + catch (Exception e) { logger.error("Compensate Callback Fails->" + e.getMessage()); } } @@ -122,14 +127,13 @@ public class CompensateServiceImpl implements CompensateService { return StringUtils.isNotEmpty(compensateKey); - } @Override public void autoCompensate(final String compensateKey, TransactionCompensateMsg transactionCompensateMsg) { final String json = JSON.toJSONString(transactionCompensateMsg); logger.info("Auto Compensate->" + json); - //自动补偿业务执行... + // 自动补偿业务执行... final int tryTime = configReader.getCompensateTryTime(); boolean autoExecuteRes; try { @@ -145,24 +149,26 @@ public class CompensateServiceImpl implements CompensateService { } try { Thread.sleep(tryTime * 1000); - } catch (InterruptedException e) { + } + catch (InterruptedException e) { e.printStackTrace(); } autoExecuteRes = executeCompensateMethod(json); } - //执行成功删除数据 + // 执行成功删除数据 if (autoExecuteRes) { compensateDao.deleteCompensateByKey(compensateKey); } - } catch (Exception e) { + } + catch (Exception e) { logger.error("Auto Compensate Fails,msg:" + e.getLocalizedMessage()); - //推送数据给第三方通知 + // 推送数据给第三方通知 autoExecuteRes = false; } - //执行补偿以后通知给业务方 + // 执行补偿以后通知给业务方 String groupId = transactionCompensateMsg.getGroupId(); JSONObject requestJson = new JSONObject(); requestJson.put("action", "notify"); @@ -176,7 +182,6 @@ public class CompensateServiceImpl implements CompensateService { } - @Override public List loadModelList() { List keys = compensateDao.loadCompensateKeys(); @@ -239,7 +244,8 @@ public class CompensateServiceImpl implements CompensateService { public int compare(TxModel o1, TxModel o2) { if (o2.getOrder() > o1.getOrder()) { return 1; - } else { + } + else { return -1; } } @@ -264,31 +270,34 @@ public class CompensateServiceImpl implements CompensateService { if (compensateGroup != null) { if (compensateGroup.getList() != null && !compensateGroup.getList().isEmpty()) { - //引用集合 iterator,方便匹配后剔除列表 + // 引用集合 iterator,方便匹配后剔除列表 Iterator iterator = Lists.newArrayList(compensateGroup.getList()).iterator(); for (TxInfo txInfo : txGroup.getList()) { while (iterator.hasNext()) { TxInfo cinfo = iterator.next(); - if (cinfo.getModel().equals(txInfo.getModel()) && cinfo.getMethodStr().equals(txInfo.getMethodStr())) { - //根据之前的数据补偿现在的事务 + if (cinfo.getModel().equals(txInfo.getModel()) + && cinfo.getMethodStr().equals(txInfo.getMethodStr())) { + // 根据之前的数据补偿现在的事务 int oldNotify = cinfo.getNotify(); if (oldNotify == 1) { - //本次回滚 + // 本次回滚 txInfo.setIsCommit(0); - } else { - //本次提交 + } + else { + // 本次提交 txInfo.setIsCommit(1); } - //匹配后剔除列表 + // 匹配后剔除列表 iterator.remove(); break; } } } - } else {//当没有List数据只记录了补偿数据时,理解问仅发起方提交其他均回滚 + } + else {// 当没有List数据只记录了补偿数据时,理解问仅发起方提交其他均回滚 for (TxInfo txInfo : txGroup.getList()) { - //本次回滚 + // 本次回滚 txInfo.setIsCommit(0); } } @@ -307,7 +316,6 @@ public class CompensateServiceImpl implements CompensateService { return JSON.parseObject(txGroup, TxGroup.class); } - @Override @SneakyThrows public boolean executeCompensate(String path) { @@ -350,4 +358,5 @@ public class CompensateServiceImpl implements CompensateService { return "1".equals(res); } + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/config/ConfigReader.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/config/ConfigReader.java index 85b3c9837..ce2d50f2d 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/config/ConfigReader.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/config/ConfigReader.java @@ -30,30 +30,41 @@ public class ConfigReader { * 事务默认数据的位置,有最大时间 */ private static final String KEY_PREFIX = "tx:manager:default:"; + /** * 负载均衡模块存储信息 */ private static final String KEY_PREFIX_LOADBALANCE = "tx:manager:loadbalance:"; + /** * 补偿事务永久存储数据 */ private static final String TX_MANAGER_COMPENSATE = "tx:manager:compensate:"; + @Value("${tm.socket.port}") private int socketPort; + @Value("${tm.socket.maxconnection}") private int socketMaxConnection; + @Value("${tm.transaction.netty.hearttime}") private int transactionNettyHeartTime; + @Value("${tm.transaction.netty.delaytime}") private int transactionNettyDelayTime; + @Value("${tm.redis.savemaxtime}") private int redisSaveMaxTime; + @Value("${tm.compensate.notifyUrl}") private String compensateNotifyUrl; + @Value("${tm.compensate.auto}") private boolean isCompensateAuto; + @Value("${tm.compensate.tryTime}") private int compensateTryTime; + @Value("${tm.compensate.maxWaitTime}") private int compensateMaxWaitTime; @@ -105,5 +116,4 @@ public class ConfigReader { return compensateMaxWaitTime; } - } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/config/CorsConfig.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/config/CorsConfig.java index d863d4415..a4565953a 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/config/CorsConfig.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/config/CorsConfig.java @@ -31,7 +31,6 @@ public class CorsConfig { /** * 跨域过滤器 - * * @return */ private CorsConfiguration buildConfig() { @@ -42,10 +41,8 @@ public class CorsConfig { return corsConfiguration; } - /** * 跨域过滤器 - * * @return */ @Bean @@ -54,4 +51,5 @@ public class CorsConfig { source.registerCorsConfiguration("/**", buildConfig()); return new CorsFilter(source); } + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/config/ExecutorConfig.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/config/ExecutorConfig.java index 196ecb4fc..88e19c93f 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/config/ExecutorConfig.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/config/ExecutorConfig.java @@ -32,22 +32,24 @@ import java.util.concurrent.ThreadPoolExecutor; */ @Configuration public class ExecutorConfig { + private static final String LCN_SERVICE = "lcn-service-"; @Bean public Executor threadPoolTaskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); - //配置核心线程数 + // 配置核心线程数 executor.setCorePoolSize(10); - //配置最大线程数 + // 配置最大线程数 executor.setMaxPoolSize(50); - //配置队列大小 + // 配置队列大小 executor.setQueueCapacity(99999); - //配置线程池中的线程的名称前缀 + // 配置线程池中的线程的名称前缀 executor.setThreadNamePrefix(LCN_SERVICE); executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); - //执行初始化 + // 执行初始化 executor.initialize(); return executor; } + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/config/RestConfig.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/config/RestConfig.java index a90d65484..548578b85 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/config/RestConfig.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/config/RestConfig.java @@ -23,19 +23,17 @@ import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; /** - *@author LCN on 2017/7/5. + * @author LCN on 2017/7/5. */ @Configuration @EnableAutoConfiguration public class RestConfig { - @Bean public RestTemplate getRestTemplate() { RestTemplate restTemplate = new RestTemplate(); return restTemplate; } - } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/framework/utils/Constants.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/framework/utils/Constants.java index 21da813fb..f1f945f2e 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/framework/utils/Constants.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/framework/utils/Constants.java @@ -18,11 +18,10 @@ package com.pig4cloud.pigx.manager.framework.utils; /** - *@author LCN on 2017/6/8. + * @author LCN on 2017/6/8. */ public class Constants { - public static int maxConnection; public static int socketPort; diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/framework/utils/SocketManager.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/framework/utils/SocketManager.java index d551dad40..8f79ad745 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/framework/utils/SocketManager.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/framework/utils/SocketManager.java @@ -25,24 +25,29 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; /** - *@author LCN on 2017/6/30. + * @author LCN on 2017/6/30. */ public class SocketManager { private static SocketManager manager = null; + /** * 最大连接数 */ private int maxConnection = Constants.maxConnection; + /** * 当前连接数 */ private int nowConnection; + /** * 允许连接请求 true允许 false拒绝 */ private boolean allowConnection = true; + private List clients = null; + private Map lines = null; private SocketManager() { @@ -86,7 +91,6 @@ public class SocketManager { allowConnection = (maxConnection != nowConnection); } - public int getMaxConnection() { return maxConnection; } @@ -117,4 +121,5 @@ public class SocketManager { } return null; } + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/framework/utils/SocketUtils.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/framework/utils/SocketUtils.java index b4334d974..81f89f612 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/framework/utils/SocketUtils.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/framework/utils/SocketUtils.java @@ -37,7 +37,8 @@ public class SocketUtils { byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); json = new String(bytes); - } finally { + } + finally { ReferenceCountUtil.release(msg); } return json; @@ -48,8 +49,8 @@ public class SocketUtils { ctx.writeAndFlush(Unpooled.buffer().writeBytes(msg.getBytes())); } - public void sendMsg(Channel ctx, String msg) { ctx.writeAndFlush(Unpooled.buffer().writeBytes(msg.getBytes())); } + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/listener/ApplicationStartListener.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/listener/ApplicationStartListener.java index a054dd71e..1d585002f 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/listener/ApplicationStartListener.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/listener/ApplicationStartListener.java @@ -31,7 +31,6 @@ import java.net.UnknownHostException; @Component public class ApplicationStartListener implements ApplicationListener { - @Override public void onApplicationEvent(WebServerInitializedEvent event) { int serverPort = event.getWebServer().getPort(); @@ -39,14 +38,15 @@ public class ApplicationStartListener implements ApplicationListener modelInfos = new CopyOnWriteArrayList<>(); public static ModelInfoManager getInstance() { @@ -50,7 +50,6 @@ public class ModelInfoManager { } } - public void addModelInfo(ModelInfo minfo) { for (ModelInfo modelInfo : modelInfos) { if (minfo.getChannelName().equalsIgnoreCase(modelInfo.getChannelName())) { @@ -85,4 +84,5 @@ public class ModelInfoManager { } return null; } + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/manager/service/MicroService.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/manager/service/MicroService.java index 51f93e727..d7f09b1e1 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/manager/service/MicroService.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/manager/service/MicroService.java @@ -30,4 +30,5 @@ public interface MicroService { TxServer getServer(); TxState getState(); + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/manager/service/TxManagerSenderService.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/manager/service/TxManagerSenderService.java index 33de61355..e9752fbfd 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/manager/service/TxManagerSenderService.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/manager/service/TxManagerSenderService.java @@ -20,7 +20,7 @@ package com.pig4cloud.pigx.manager.manager.service; import com.pig4cloud.pigx.manager.netty.model.TxGroup; /** - *@author LCN on 2017/6/9. + * @author LCN on 2017/6/9. */ public interface TxManagerSenderService { @@ -29,4 +29,5 @@ public interface TxManagerSenderService { String sendMsg(String model, String msg, int delay); String sendCompensateMsg(String model, String groupId, String data, int startState); + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/manager/service/TxManagerService.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/manager/service/TxManagerService.java index f44f2c828..f61258934 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/manager/service/TxManagerService.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/manager/service/TxManagerService.java @@ -20,83 +20,67 @@ package com.pig4cloud.pigx.manager.manager.service; import com.pig4cloud.pigx.manager.netty.model.TxGroup; /** - *@author LCN on 2017/6/7. + * @author LCN on 2017/6/7. */ public interface TxManagerService { - /** * 创建事物组 - * * @param groupId 补偿事务组id */ TxGroup createTransactionGroup(String groupId); - /** * 添加事务组子对象 - * * @return */ TxGroup addTransactionGroup(String groupId, String taskId, int isGroup, String channelAddress, String methodStr); - /** * 关闭事务组 - * * @param groupId 事务组id - * @param state 事务状态 - * @return 0 事务存在补偿 1 事务正常 -1 事务强制回滚 + * @param state 事务状态 + * @return 0 事务存在补偿 1 事务正常 -1 事务强制回滚 */ int closeTransactionGroup(String groupId, int state); - void dealTxGroup(TxGroup txGroup, boolean hasOk); - /** * 删除事务组 - * * @param txGroup 事务组 */ void deleteTxGroup(TxGroup txGroup); - /** * 获取事务组信息 - * * @param groupId 事务组id * @return 事务组 */ TxGroup getTxGroup(String groupId); - /** * 获取事务组的key - * * @param groupId 事务组id * @return key */ String getTxGroupKey(String groupId); - /** * 检查事务组数据 - * * @param groupId 事务组id - * @param taskId 任务id + * @param taskId 任务id * @return 本次请求的是否提交 1提交 0回滚 */ int cleanNotifyTransaction(String groupId, String taskId); - /** * 设置强制回滚事务 - * * @param groupId 事务组id * @return true 成功 false 失败 */ boolean rollbackTransactionGroup(String groupId); + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/manager/service/impl/LoadBalanceServiceImpl.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/manager/service/impl/LoadBalanceServiceImpl.java index 4adcadbaf..4d03fda7f 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/manager/service/impl/LoadBalanceServiceImpl.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/manager/service/impl/LoadBalanceServiceImpl.java @@ -68,4 +68,5 @@ public class LoadBalanceServiceImpl implements LoadBalanceService { public String getLoadBalanceGroupName(String groupId) { return configReader.getKeyPrefixLoadbalance() + groupId; } + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/manager/service/impl/MicroServiceImpl.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/manager/service/impl/MicroServiceImpl.java index 9514c1dae..69fbb4243 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/manager/service/impl/MicroServiceImpl.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/manager/service/impl/MicroServiceImpl.java @@ -41,14 +41,12 @@ import java.util.regex.Pattern; @Service public class MicroServiceImpl implements MicroService { - @Autowired private RestTemplate restTemplate; @Autowired private ConfigReader configReader; - @Autowired private DiscoveryClient discoveryClient; @@ -62,7 +60,6 @@ public class MicroServiceImpl implements MicroService { return matcher.matches(); } - @Override public TxState getState() { TxState state = new TxState(); @@ -102,7 +99,8 @@ public class MicroServiceImpl implements MicroService { try { TxState state = restTemplate.getForObject(url + "/tx/manager/state", TxState.class); states.add(state); - } catch (Exception e) { + } + catch (Exception e) { } } @@ -110,14 +108,16 @@ public class MicroServiceImpl implements MicroService { TxState state = getState(); if (state.getMaxConnection() > state.getNowConnection()) { return TxServer.format(state); - } else { + } + else { return null; } - } else { - //找默认数据 + } + else { + // 找默认数据 TxState state = getDefault(states, 0); if (state == null) { - //没有满足的默认数据 + // 没有满足的默认数据 return null; } return TxServer.format(state); @@ -130,10 +130,12 @@ public class MicroServiceImpl implements MicroService { index++; if (states.size() - 1 >= index) { return getDefault(states, index); - } else { + } + else { return null; } - } else { + } + else { return state; } } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/manager/service/impl/TxManagerSenderServiceImpl.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/manager/service/impl/TxManagerSenderServiceImpl.java index a187a5595..0ea8975e0 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/manager/service/impl/TxManagerSenderServiceImpl.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/manager/service/impl/TxManagerSenderServiceImpl.java @@ -17,7 +17,6 @@ package com.pig4cloud.pigx.manager.manager.service.impl; - import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.lorne.core.framework.utils.KidUtils; @@ -45,14 +44,12 @@ import org.springframework.stereotype.Service; import java.util.List; import java.util.concurrent.*; - /** * @author LCN on 2017/6/9. */ @Service public class TxManagerSenderServiceImpl implements TxManagerSenderService { - private Logger logger = LoggerFactory.getLogger(TxManagerSenderServiceImpl.class); private ScheduledExecutorService executorService = Executors.newScheduledThreadPool(100); @@ -73,10 +70,10 @@ public class TxManagerSenderServiceImpl implements TxManagerSenderService { @Override public int confirm(TxGroup txGroup) { - //绑定管道对象,检查网络 + // 绑定管道对象,检查网络 setChannel(txGroup.getList()); - //事务不满足直接回滚事务 + // 事务不满足直接回滚事务 if (txGroup.getState() == 0) { transaction(txGroup, 0); return 0; @@ -92,10 +89,8 @@ public class TxManagerSenderServiceImpl implements TxManagerSenderService { return hasOk ? 1 : 0; } - /** * 匹配管道 - * * @param list */ private void setChannel(List list) { @@ -108,7 +103,8 @@ public class TxManagerSenderServiceImpl implements TxManagerSenderService { info.setChannel(sender); } - } else { + } + else { ChannelSender sender = new ChannelSender(); sender.setAddress(info.getAddress()); sender.setModelName(info.getChannelAddress()); @@ -118,18 +114,15 @@ public class TxManagerSenderServiceImpl implements TxManagerSenderService { } } - /** * 事务提交或回归 - * * @param checkSate */ private boolean transaction(final TxGroup txGroup, final int checkSate) { - if (checkSate == 1) { - //补偿请求,加载历史数据 + // 补偿请求,加载历史数据 if (txGroup.getIsCompensate() == 1) { compensateService.reloadCompensate(txGroup); } @@ -147,10 +140,11 @@ public class TxManagerSenderServiceImpl implements TxManagerSenderService { final JSONObject jsonObject = new JSONObject(); jsonObject.put("a", "t"); - //补偿请求 + // 补偿请求 if (txGroup.getIsCompensate() == 1) { jsonObject.put("c", txInfo.getIsCommit()); - } else { //正常业务 + } + else { // 正常业务 jsonObject.put("c", checkSate); } @@ -172,7 +166,7 @@ public class TxManagerSenderServiceImpl implements TxManagerSenderService { try { String data = (String) task.getBack().doing(); - // 1 成功 0 失败 -1 task为空 -2 超过 + // 1 成功 0 失败 -1 task为空 -2 超过 boolean res = "1".equals(data); if (res) { @@ -180,10 +174,12 @@ public class TxManagerSenderServiceImpl implements TxManagerSenderService { } return res; - } catch (Throwable throwable) { + } + catch (Throwable throwable) { throwable.printStackTrace(); return false; - } finally { + } + finally { task.remove(); } } @@ -203,10 +199,12 @@ public class TxManagerSenderServiceImpl implements TxManagerSenderService { break; } } - logger.info("--->" + hasOk + ",group:" + txGroup.getGroupId() + ",state:" + checkSate + ",list:" + txGroup.toJsonString()); + logger.info("--->" + hasOk + ",group:" + txGroup.getGroupId() + ",state:" + checkSate + ",list:" + + txGroup.toJsonString()); return hasOk; - } else { - //回滚操作只发送通过不需要等待确认 + } + else { + // 回滚操作只发送通过不需要等待确认 for (TxInfo txInfo : txGroup.getList()) { if (txInfo.getChannel() != null) { if (txInfo.getIsGroup() == 0) { @@ -242,14 +240,15 @@ public class TxManagerSenderServiceImpl implements TxManagerSenderService { JSONObject jsonObject = JSON.parseObject(msg); String key = jsonObject.getString("k"); - //创建Task + // 创建Task final Task task = ConditionUtils.getInstance().createTask(key); threadPool.execute(() -> { while (!task.isAwait() && !Thread.interrupted()) { try { Thread.sleep(1); - } catch (InterruptedException e) { + } + catch (InterruptedException e) { e.printStackTrace(); } } @@ -270,27 +269,30 @@ public class TxManagerSenderServiceImpl implements TxManagerSenderService { try { return (String) task.getBack().doing(); - } catch (Throwable throwable) { + } + catch (Throwable throwable) { return "-1"; - } finally { + } + finally { task.remove(); } } - private void threadAwaitSend(final Task task, final TxInfo txInfo, final String msg) { threadPool.execute(() -> { while (!task.isAwait() && !Thread.interrupted()) { try { Thread.sleep(1); - } catch (InterruptedException e) { + } + catch (InterruptedException e) { e.printStackTrace(); } } if (txInfo != null && txInfo.getChannel() != null) { txInfo.getChannel().send(msg, task); - } else { + } + else { task.setBack(objs -> "-2"); task.signalTask(); } @@ -298,7 +300,6 @@ public class TxManagerSenderServiceImpl implements TxManagerSenderService { } - private ScheduledFuture schedule(final String key, int delayTime) { ScheduledFuture future = executorService.schedule(() -> { Task task = ConditionUtils.getInstance().getTask(key); @@ -311,5 +312,4 @@ public class TxManagerSenderServiceImpl implements TxManagerSenderService { return future; } - } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/manager/service/impl/TxManagerServiceImpl.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/manager/service/impl/TxManagerServiceImpl.java index 76ecc6743..0898f3911 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/manager/service/impl/TxManagerServiceImpl.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/manager/service/impl/TxManagerServiceImpl.java @@ -17,7 +17,6 @@ package com.pig4cloud.pigx.manager.manager.service.impl; - import com.pig4cloud.pigx.manager.compensate.service.CompensateService; import com.pig4cloud.pigx.manager.config.ConfigReader; import com.pig4cloud.pigx.manager.framework.utils.Constants; @@ -35,30 +34,28 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** - *@author LCN on 2017/6/7. + * @author LCN on 2017/6/7. */ @Service public class TxManagerServiceImpl implements TxManagerService { + @Autowired private ConfigReader configReader; + @Autowired private RedisServerService redisServerService; - @Autowired private TxManagerSenderService transactionConfirmService; - @Autowired private LoadBalanceService loadBalanceService; @Autowired private CompensateService compensateService; - private Logger logger = LoggerFactory.getLogger(TxManagerServiceImpl.class); - @Override public TxGroup createTransactionGroup(String groupId) { TxGroup txGroup = new TxGroup(); @@ -75,9 +72,9 @@ public class TxManagerServiceImpl implements TxManagerService { return txGroup; } - @Override - public TxGroup addTransactionGroup(String groupId, String taskId, int isGroup, String channelAddress, String methodStr) { + public TxGroup addTransactionGroup(String groupId, String taskId, int isGroup, String channelAddress, + String methodStr) { String key = getTxGroupKey(groupId); TxGroup txGroup = getTxGroup(groupId); if (txGroup == null) { @@ -90,7 +87,6 @@ public class TxManagerServiceImpl implements TxManagerService { txInfo.setIsGroup(isGroup); txInfo.setMethodStr(methodStr); - ModelInfo modelInfo = ModelInfoManager.getInstance().getModelByChannelName(channelAddress); if (modelInfo != null) { txInfo.setUniqueKey(modelInfo.getUniqueKey()); @@ -130,7 +126,7 @@ public class TxManagerServiceImpl implements TxManagerService { if (txGroup.getHasOver() == 0) { - //整个事务回滚. + // 整个事务回滚. txGroup.setRollback(1); redisServerService.saveTransaction(key, txGroup.toJsonString()); @@ -143,7 +139,7 @@ public class TxManagerServiceImpl implements TxManagerService { return 0; } - //更新数据 + // 更新数据 boolean hasSet = false; for (TxInfo info : txGroup.getList()) { if (info.getKid().equals(taskId)) { @@ -157,7 +153,7 @@ public class TxManagerServiceImpl implements TxManagerService { } } - //判断是否都结束 + // 判断是否都结束 boolean isOver = true; for (TxInfo info : txGroup.getList()) { if (info.getIsGroup() == 0 && info.getNotify() == 0) { @@ -170,16 +166,16 @@ public class TxManagerServiceImpl implements TxManagerService { deleteTxGroup(txGroup); } - //有更新的数据,需要修改记录 + // 有更新的数据,需要修改记录 if (!isOver && hasSet) { redisServerService.saveTransaction(key, txGroup.toJsonString()); } - logger.info("end-cleanNotifyTransaction->groupId:" + groupId + ",taskId:" + taskId + ",res(1:commit,0:rollback):" + res); + logger.info("end-cleanNotifyTransaction->groupId:" + groupId + ",taskId:" + taskId + + ",res(1:commit,0:rollback):" + res); return res; } - @Override public int closeTransactionGroup(String groupId, int state) { String key = getTxGroupKey(groupId); @@ -193,7 +189,6 @@ public class TxManagerServiceImpl implements TxManagerService { return transactionConfirmService.confirm(txGroup); } - @Override public void dealTxGroup(TxGroup txGroup, boolean hasOk) { if (hasOk) { @@ -201,7 +196,6 @@ public class TxManagerServiceImpl implements TxManagerService { } } - @Override public void deleteTxGroup(TxGroup txGroup) { String groupId = txGroup.getGroupId(); @@ -212,7 +206,6 @@ public class TxManagerServiceImpl implements TxManagerService { loadBalanceService.remove(groupId); } - @Override public TxGroup getTxGroup(String groupId) { String key = getTxGroupKey(groupId); @@ -223,4 +216,5 @@ public class TxManagerServiceImpl implements TxManagerService { public String getTxGroupKey(String groupId) { return configReader.getKeyPrefix() + groupId; } + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/model/ChannelSender.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/model/ChannelSender.java index 85465d4b7..0273d8a1b 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/model/ChannelSender.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/model/ChannelSender.java @@ -28,7 +28,6 @@ import org.apache.commons.lang.StringUtils; */ public class ChannelSender { - private Channel channel; private String address; @@ -47,7 +46,6 @@ public class ChannelSender { this.address = address; } - public void send(String msg) { if (channel != null) { SocketUtils.sendMsg(channel, msg); @@ -58,7 +56,8 @@ public class ChannelSender { public void send(String msg, Task task) { if (channel != null) { SocketUtils.sendMsg(channel, msg); - } else { + } + else { String url = String.format("http://%s/tx/manager/sendMsg", address); final String res = HttpUtils.post(url, "msg=" + msg + "&model=" + modelName); if (StringUtils.isNotEmpty(res)) { @@ -66,7 +65,8 @@ public class ChannelSender { task.setBack(objs -> res); task.signalTask(); } - } else { + } + else { if (task != null) { task.setBack(objs -> "-2"); task.signalTask(); @@ -75,4 +75,5 @@ public class ChannelSender { } } + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/model/LoadBalanceInfo.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/model/LoadBalanceInfo.java index 750447d6e..db3ed3ff0 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/model/LoadBalanceInfo.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/model/LoadBalanceInfo.java @@ -19,6 +19,7 @@ package com.pig4cloud.pigx.manager.model; /** * 负载均衡模块信息 + * * @author LCN on 2017/12/5 */ public class LoadBalanceInfo { @@ -29,7 +30,6 @@ public class LoadBalanceInfo { private String data; - public String getGroupId() { return groupId; } @@ -53,4 +53,5 @@ public class LoadBalanceInfo { public void setData(String data) { this.data = data; } + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/model/ModelInfo.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/model/ModelInfo.java index 96a9b0366..c79e23794 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/model/ModelInfo.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/model/ModelInfo.java @@ -19,6 +19,7 @@ package com.pig4cloud.pigx.manager.model; /** * 模块信息 + * * @author LCN on 2017/11/13 */ public class ModelInfo { @@ -62,4 +63,5 @@ public class ModelInfo { public void setUniqueKey(String uniqueKey) { this.uniqueKey = uniqueKey; } + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/model/ModelName.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/model/ModelName.java index 443815cc6..c82ef64e4 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/model/ModelName.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/model/ModelName.java @@ -1,5 +1,4 @@ - /* * Copyright (c) 2018-2025, lengleng All rights reserved. * @@ -25,6 +24,7 @@ package com.pig4cloud.pigx.manager.model; public class ModelName { private String name; + private int count; public String getName() { @@ -42,4 +42,5 @@ public class ModelName { public void setCount(int count) { this.count = count; } + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/model/TxServer.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/model/TxServer.java index 9effb9f63..2996d1e9b 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/model/TxServer.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/model/TxServer.java @@ -18,14 +18,18 @@ package com.pig4cloud.pigx.manager.model; /** - *@author LCN on 2017/7/1. + * @author LCN on 2017/7/1. */ public class TxServer { private String ip; + private int port; + private int heart; + private int delay; + private int compensateMaxWaitTime; public static TxServer format(TxState state) { @@ -38,7 +42,6 @@ public class TxServer { return txServer; } - public String getIp() { return ip; } @@ -47,7 +50,6 @@ public class TxServer { this.ip = ip; } - public int getPort() { return port; } @@ -72,15 +74,12 @@ public class TxServer { this.delay = delay; } - public int getCompensateMaxWaitTime() { return compensateMaxWaitTime; } - public void setCompensateMaxWaitTime(int compensateMaxWaitTime) { this.compensateMaxWaitTime = compensateMaxWaitTime; } - } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/model/TxState.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/model/TxState.java index 978f035a5..7d61503d4 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/model/TxState.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/model/TxState.java @@ -20,7 +20,7 @@ package com.pig4cloud.pigx.manager.model; import java.util.List; /** - *@author LCN on 2017/7/1. + * @author LCN on 2017/7/1. */ public class TxState { @@ -28,6 +28,7 @@ public class TxState { * socket ip */ private String ip; + /** * socket port */ @@ -43,7 +44,6 @@ public class TxState { */ private int nowConnection; - /** * transaction_netty_heart_time */ @@ -54,13 +54,11 @@ public class TxState { */ private int transactionNettyDelayTime; - /** * redis_save_max_time */ private int redisSaveMaxTime; - /** * 回调地址 */ @@ -86,7 +84,6 @@ public class TxState { */ private int compensateMaxWaitTime; - public String getIp() { return ip; } @@ -183,5 +180,4 @@ public class TxState { this.compensateMaxWaitTime = compensateMaxWaitTime; } - } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/handler/TxCoreServerHandler.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/handler/TxCoreServerHandler.java index 1ee5e11d8..821ba60e9 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/handler/TxCoreServerHandler.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/handler/TxCoreServerHandler.java @@ -46,17 +46,16 @@ import java.util.concurrent.Executor; */ @ChannelHandler.Sharable -public class TxCoreServerHandler extends ChannelInboundHandlerAdapter { // (1) +public class TxCoreServerHandler extends ChannelInboundHandlerAdapter { + + // (1) private NettyService nettyService; - private Logger logger = LoggerFactory.getLogger(TxCoreServerHandler.class); - private Executor threadPool; - public TxCoreServerHandler(Executor threadPool, NettyService nettyService) { this.threadPool = threadPool; this.nettyService = nettyService; @@ -94,10 +93,11 @@ public class TxCoreServerHandler extends ChannelInboundHandlerAdapter { // (1) @SneakyThrows public void channelRegistered(ChannelHandlerContext ctx) { - //是否到达最大上线连接数 + // 是否到达最大上线连接数 if (SocketManager.getInstance().isAllowConnection()) { SocketManager.getInstance().addClient(ctx.channel()); - } else { + } + else { ctx.close(); } super.channelRegistered(ctx); @@ -123,12 +123,12 @@ public class TxCoreServerHandler extends ChannelInboundHandlerAdapter { // (1) @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); - //ctx.close(); + // ctx.close(); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) { - //心跳配置 + // 心跳配置 if (IdleStateEvent.class.isAssignableFrom(evt.getClass())) { IdleStateEvent event = (IdleStateEvent) evt; if (event.state() == IdleState.READER_IDLE) { diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/model/TxGroup.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/model/TxGroup.java index cec5f5766..9dbc19d23 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/model/TxGroup.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/model/TxGroup.java @@ -17,7 +17,6 @@ package com.pig4cloud.pigx.manager.netty.model; - import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; @@ -25,7 +24,7 @@ import java.util.ArrayList; import java.util.List; /** - *@author LCN on 2017/6/7. + * @author LCN on 2017/6/7. */ public class TxGroup { @@ -44,7 +43,6 @@ public class TxGroup { */ private int isCompensate; - /** * 是否强制回滚(1:开启,0:关闭) */ @@ -87,7 +85,8 @@ public class TxGroup { } return txGroup; - } catch (Exception e) { + } + catch (Exception e) { return null; } @@ -185,7 +184,6 @@ public class TxGroup { item.put("ip", info.getModelIpAddress()); item.put("ms", info.getMethodStr()); - jsonArray.add(item); } jsonObject.put("l", jsonArray); @@ -196,4 +194,5 @@ public class TxGroup { public String toJsonString() { return toJsonString(true); } + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/model/TxInfo.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/model/TxInfo.java index ac144128d..b44f498d6 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/model/TxInfo.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/model/TxInfo.java @@ -22,7 +22,7 @@ import com.lorne.core.framework.model.JsonModel; import com.pig4cloud.pigx.manager.model.ChannelSender; /** - *@author LCN on 2017/6/7. + * @author LCN on 2017/6/7. */ public class TxInfo extends JsonModel { @@ -42,8 +42,7 @@ public class TxInfo extends JsonModel { private int notify; /** - * 0 不组合 - * 1 组合 + * 0 不组合 1 组合 */ private int isGroup; @@ -57,13 +56,11 @@ public class TxInfo extends JsonModel { */ private String uniqueKey; - /** * 管道发送数据 */ private ChannelSender channel; - /** * 业务方法名称 */ @@ -188,4 +185,5 @@ public class TxInfo extends JsonModel { return jsonObject.toString(); } + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/IActionService.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/IActionService.java index 8cf41a60c..0fc19ba06 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/IActionService.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/IActionService.java @@ -24,7 +24,6 @@ import com.alibaba.fastjson.JSONObject; */ public interface IActionService { - String execute(String channelAddress, String key, JSONObject params); } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/NettyServerService.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/NettyServerService.java index c3a99389e..3807266de 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/NettyServerService.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/NettyServerService.java @@ -18,7 +18,7 @@ package com.pig4cloud.pigx.manager.netty.service; /** - *@author LCN on 2017/6/30. + * @author LCN on 2017/6/30. */ public interface NettyServerService { @@ -26,5 +26,4 @@ public interface NettyServerService { void close(); - } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/NettyService.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/NettyService.java index 7f78193a7..d557d6369 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/NettyService.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/NettyService.java @@ -22,6 +22,6 @@ package com.pig4cloud.pigx.manager.netty.service; */ public interface NettyService { - IActionService getActionService(String action); + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionATGServiceImpl.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionATGServiceImpl.java index f8cb230d3..884972996 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionATGServiceImpl.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionATGServiceImpl.java @@ -26,12 +26,12 @@ import org.springframework.stereotype.Service; /** * 添加事务组 + * * @author LCN on 2017/11/11 */ @Service(value = "atg") public class ActionATGServiceImpl implements IActionService { - @Autowired private TxManagerService txManagerService; @@ -48,9 +48,11 @@ public class ActionATGServiceImpl implements IActionService { if (txGroup != null) { txGroup.setNowTime(System.currentTimeMillis()); res = txGroup.toJsonString(false); - } else { + } + else { res = ""; } return res; } + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionCGServiceImpl.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionCGServiceImpl.java index 1c796842b..a50ef7a55 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionCGServiceImpl.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionCGServiceImpl.java @@ -26,12 +26,12 @@ import org.springframework.stereotype.Service; /** * 创建事务组 + * * @author LCN on 2017/11/11 */ @Service(value = "cg") public class ActionCGServiceImpl implements IActionService { - @Autowired private TxManagerService txManagerService; @@ -43,9 +43,11 @@ public class ActionCGServiceImpl implements IActionService { if (txGroup != null) { txGroup.setNowTime(System.currentTimeMillis()); res = txGroup.toJsonString(false); - } else { + } + else { res = ""; } return res; } + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionCKGServiceImpl.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionCKGServiceImpl.java index 8fc6e2f2e..9ab770385 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionCKGServiceImpl.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionCKGServiceImpl.java @@ -25,12 +25,12 @@ import org.springframework.stereotype.Service; /** * 检查事务组 + * * @author LCN on 2017/11/11 */ @Service(value = "ckg") public class ActionCKGServiceImpl implements IActionService { - @Autowired private TxManagerService txManagerService; @@ -44,4 +44,5 @@ public class ActionCKGServiceImpl implements IActionService { res = String.valueOf(bs); return res; } + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionCServiceImpl.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionCServiceImpl.java index e920c8baf..d449b8fe6 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionCServiceImpl.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionCServiceImpl.java @@ -22,10 +22,10 @@ import org.springframework.stereotype.Service; /** * 补偿回调 + * * @author LCN on 2017/11/11 */ @Service(value = "c") public class ActionCServiceImpl extends BaseSignalTaskService implements IActionService { - } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionCTGServiceImpl.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionCTGServiceImpl.java index 5d545ebe6..e2fc82212 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionCTGServiceImpl.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionCTGServiceImpl.java @@ -25,12 +25,12 @@ import org.springframework.stereotype.Service; /** * 关闭事务组 + * * @author LCN on 2017/11/11 */ @Service(value = "ctg") public class ActionCTGServiceImpl implements IActionService { - @Autowired private TxManagerService txManagerService; @@ -41,4 +41,5 @@ public class ActionCTGServiceImpl implements IActionService { String res = String.valueOf(txManagerService.closeTransactionGroup(groupId, state)); return res; } + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionGLBServiceImpl.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionGLBServiceImpl.java index f772b53b2..2106e9a60 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionGLBServiceImpl.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionGLBServiceImpl.java @@ -26,16 +26,15 @@ import org.springframework.stereotype.Service; /** * 获取负载模块信息 + * * @author LCN on 2017/11/11 */ @Service(value = "glb") public class ActionGLBServiceImpl implements IActionService { - @Autowired private LoadBalanceService loadBalanceService; - @Override public String execute(String channelAddress, String key, JSONObject params) { String res; @@ -45,9 +44,11 @@ public class ActionGLBServiceImpl implements IActionService { LoadBalanceInfo loadBalanceInfo = loadBalanceService.get(groupId, k); if (loadBalanceInfo == null) { res = ""; - } else { + } + else { res = loadBalanceInfo.getData(); } return res; } + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionHServiceImpl.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionHServiceImpl.java index aa234b345..577af3f41 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionHServiceImpl.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionHServiceImpl.java @@ -25,12 +25,12 @@ import org.springframework.stereotype.Service; /** * 心跳包 + * * @author LCN on 2017/11/11 */ @Service(value = "h") public class ActionHServiceImpl implements IActionService { - @Autowired private ConfigReader configReader; @@ -38,4 +38,5 @@ public class ActionHServiceImpl implements IActionService { public String execute(String channelAddress, String key, JSONObject params) { return String.valueOf(configReader.getTransactionNettyDelayTime()); } + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionPLBServiceImpl.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionPLBServiceImpl.java index ea86b49da..29d6148c3 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionPLBServiceImpl.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionPLBServiceImpl.java @@ -26,16 +26,15 @@ import org.springframework.stereotype.Service; /** * 添加负载模块信息 + * * @author LCN on 2017/11/11 */ @Service(value = "plb") public class ActionPLBServiceImpl implements IActionService { - @Autowired private LoadBalanceService loadBalanceService; - @Override public String execute(String channelAddress, String key, JSONObject params) { @@ -51,4 +50,5 @@ public class ActionPLBServiceImpl implements IActionService { return ok ? "1" : "0"; } + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionRGServiceImpl.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionRGServiceImpl.java index c3d63b4b0..ec0b7b725 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionRGServiceImpl.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionRGServiceImpl.java @@ -25,12 +25,12 @@ import org.springframework.stereotype.Service; /** * 强制回滚事务组 + * * @author LCN on 2017/11/11 */ @Service(value = "rg") public class ActionRGServiceImpl implements IActionService { - @Autowired private TxManagerService txManagerService; @@ -42,4 +42,5 @@ public class ActionRGServiceImpl implements IActionService { res = bs ? "1" : "0"; return res; } + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionTServiceImpl.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionTServiceImpl.java index d8d93079b..ccc036e32 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionTServiceImpl.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionTServiceImpl.java @@ -22,10 +22,10 @@ import org.springframework.stereotype.Service; /** * 通知事务回调 + * * @author LCN on 2017/11/11 */ @Service(value = "t") public class ActionTServiceImpl extends BaseSignalTaskService implements IActionService { - } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionUMIServiceImpl.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionUMIServiceImpl.java index b9f414411..ff9cbc9db 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionUMIServiceImpl.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/ActionUMIServiceImpl.java @@ -26,12 +26,12 @@ import org.springframework.stereotype.Service; /** * 上传模块信息 + * * @author LCN on 2017/11/11 */ @Service(value = "umi") public class ActionUMIServiceImpl implements IActionService { - @Override public String execute(String channelAddress, String key, JSONObject params) { String res = "1"; @@ -40,7 +40,6 @@ public class ActionUMIServiceImpl implements IActionService { String ipAddress = params.getString("i"); String model = params.getString("m"); - ModelInfo modelInfo = new ModelInfo(); modelInfo.setChannelName(channelAddress); modelInfo.setIpAddress(ipAddress); @@ -53,4 +52,5 @@ public class ActionUMIServiceImpl implements IActionService { return res; } + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/BaseSignalTaskService.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/BaseSignalTaskService.java index f4124ad49..b3a8cb817 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/BaseSignalTaskService.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/BaseSignalTaskService.java @@ -36,4 +36,5 @@ public class BaseSignalTaskService { } return res; } + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/NettyServerServiceImpl.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/NettyServerServiceImpl.java index e378b6a39..0334b9778 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/NettyServerServiceImpl.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/NettyServerServiceImpl.java @@ -48,18 +48,24 @@ import java.util.concurrent.TimeUnit; */ @Service public class NettyServerServiceImpl implements NettyServerService, DisposableBean { + private Logger logger = LoggerFactory.getLogger(NettyServerServiceImpl.class); + private EventLoopGroup bossGroup; + private EventLoopGroup workerGroup; + private TxCoreServerHandler txCoreServerHandler; + @Autowired private NettyService nettyService; + @Autowired private Executor threadPool; + @Autowired private ConfigReader configReader; - @Override public void start() { final int heartTime = configReader.getTransactionNettyHeartTime() + 10; @@ -68,14 +74,12 @@ public class NettyServerServiceImpl implements NettyServerService, DisposableBea workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); - b.group(bossGroup, workerGroup) - .channel(NioServerSocketChannel.class) - .option(ChannelOption.SO_BACKLOG, 100) - .handler(new LoggingHandler(LogLevel.INFO)) - .childHandler(new ChannelInitializer() { + b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100) + .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer() { @Override public void initChannel(SocketChannel ch) { - ch.pipeline().addLast("timeout", new IdleStateHandler(heartTime, heartTime, heartTime, TimeUnit.SECONDS)); + ch.pipeline().addLast("timeout", + new IdleStateHandler(heartTime, heartTime, heartTime, TimeUnit.SECONDS)); ch.pipeline().addLast(new LengthFieldPrepender(4, false)); ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4)); @@ -88,7 +92,8 @@ public class NettyServerServiceImpl implements NettyServerService, DisposableBea b.bind(Constants.socketPort); logger.info("Socket started on port(s): " + Constants.socketPort + " (socket)"); - } catch (Exception e) { + } + catch (Exception e) { // Shut down all event loops to terminate all threads. e.printStackTrace(); } @@ -109,4 +114,5 @@ public class NettyServerServiceImpl implements NettyServerService, DisposableBea public void destroy() { close(); } + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/NettyServiceImpl.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/NettyServiceImpl.java index 3382aca33..227207dfe 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/NettyServiceImpl.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/netty/service/impl/NettyServiceImpl.java @@ -36,4 +36,5 @@ public class NettyServiceImpl implements NettyService { public IActionService getActionService(String action) { return spring.getBean(action, IActionService.class); } + } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/redis/RedisServerService.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/redis/RedisServerService.java index d4d8e6384..ca32fec90 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/redis/RedisServerService.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/redis/RedisServerService.java @@ -17,7 +17,6 @@ package com.pig4cloud.pigx.manager.redis; - import com.pig4cloud.pigx.manager.netty.model.TxGroup; import java.util.List; @@ -45,8 +44,6 @@ public interface RedisServerService { void saveLoadBalance(String groupName, String key, String data); - String getLoadBalance(String groupName, String key); - } diff --git a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/redis/impl/RedisServerServiceImpl.java b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/redis/impl/RedisServerServiceImpl.java index 9cd1cc83b..8e38e6667 100644 --- a/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/redis/impl/RedisServerServiceImpl.java +++ b/pigx-visual/pigx-tx-manager/src/main/java/com/pig4cloud/pigx/manager/redis/impl/RedisServerServiceImpl.java @@ -67,7 +67,6 @@ public class RedisServerServiceImpl implements RedisServerService { value.set(key, json, configReader.getRedisSaveMaxTime(), TimeUnit.SECONDS); } - @Override public TxGroup getTxGroupByKey(String key) { ValueOperations value = redisTemplate.opsForValue(); @@ -78,7 +77,6 @@ public class RedisServerServiceImpl implements RedisServerService { return TxGroup.parser(json); } - @Override public void saveCompensateMsg(String name, String json) { ValueOperations value = redisTemplate.opsForValue(); @@ -123,10 +121,10 @@ public class RedisServerServiceImpl implements RedisServerService { value.put(groupName, key, data); } - @Override public String getLoadBalance(String groupName, String key) { HashOperations value = redisTemplate.opsForHash(); return value.get(groupName, key); } + } diff --git a/pom.xml b/pom.xml index 0ee013618..08951fd91 100644 --- a/pom.xml +++ b/pom.xml @@ -40,6 +40,7 @@ 1.8 1.8 3.8.1 + 0.0.22 2.2.5 2.2.3 5.3.7 @@ -170,6 +171,7 @@ + org.springframework.boot spring-boot-maven-plugin @@ -182,6 +184,7 @@ + io.fabric8 docker-maven-plugin @@ -208,6 +211,13 @@ + + + io.spring.javaformat + spring-javaformat-maven-plugin + ${spring.checkstyle.version} + + org.apache.maven.plugins maven-compiler-plugin @@ -219,6 +229,7 @@ true + pl.project13.maven git-commit-id-plugin