instruction
stringlengths
77
90.1k
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package com.strongdata.rill.core.security.server.service;import com.strongdata.rill.core.base.constant.CacheConstants;import lombok.SneakyThrows;import org.springframework.cache.annotation.Cacheable;import org.springframework.security.oauth2.provider.ClientDetails;import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;import javax.sql.DataSource;/** * @author wildwind * @date 2022/2/1 * <p> * see JdbcClientDetailsService */public class RillClientDetailsService extends JdbcClientDetailsService { public RillClientDetailsService(DataSource dataSource) { super(dataSource); } /** * 重写原生方法支持redis缓存 * @param clientId * @return */ @Override @SneakyThrows @Cacheable(value = CacheConstants.CLIENT_DETAILS_KEY, key = "#clientId", unless = "#result == null") public ClientDetails loadClientByClientId(String clientId) { return super.loadClientByClientId(clientId); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package com.strongdata.rill.core.security.server.service;import org.springframework.beans.factory.InitializingBean;import org.springframework.security.authentication.AuthenticationManager;import org.springframework.security.core.Authentication;import org.springframework.security.core.AuthenticationException;import org.springframework.security.oauth2.common.*;import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;import org.springframework.security.oauth2.common.exceptions.InvalidScopeException;import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;import org.springframework.security.oauth2.provider.*;import org.springframework.security.oauth2.provider.token.*;import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;import org.springframework.transaction.annotation.Transactional;import org.springframework.util.Assert;import java.util.Date;import java.util.Set;import java.util.UUID;/** * 自定义 token 放发处理逻辑 * * @author wildwind * @date 2022/3/15 */public class RillCustomTokenServices implements AuthorizationServerTokenServices, ResourceServerTokenServices, ConsumerTokenServices, InitializingBean { private int refreshTokenValiditySeconds = 60 * 60 * 24 * 30; // default 30 days. private int accessTokenValiditySeconds = 60 * 60 * 12; // default 12 hours. private boolean supportRefreshToken = false; private boolean reuseRefreshToken = true; private TokenStore tokenStore; private ClientDetailsService clientDetailsService; private TokenEnhancer accessTokenEnhancer; private AuthenticationManager authenticationManager; /** * Initialize these token services. If no random generator is set, one will be * created. */ public void afterPropertiesSet() { Assert.notNull(tokenStore, "tokenStore must be set"); } @Override public OAuth2AccessToken createAccessToken(OAuth2Authentication authentication) throws AuthenticationException { OAuth2AccessToken existingAccessToken = tokenStore.getAccessToken(authentication); OAuth2RefreshToken refreshToken = null; // 若已产生token , 过期时删除相关token,执行下边的重新生成逻辑 if (existingAccessToken != null) { tokenStore.removeAccessToken(existingAccessToken); if (existingAccessToken.getRefreshToken() != null) { refreshToken = existingAccessToken.getRefreshToken(); tokenStore.removeRefreshToken(refreshToken); } } if (refreshToken == null) { refreshToken = createRefreshToken(authentication); } else if (refreshToken instanceof ExpiringOAuth2RefreshToken) { ExpiringOAuth2RefreshToken expiring = (ExpiringOAuth2RefreshToken) refreshToken; if (System.currentTimeMillis() > expiring.getExpiration().getTime()) { refreshToken = createRefreshToken(authentication); } } OAuth2AccessToken accessToken = createAccessToken(authentication, refreshToken); tokenStore.storeAccessToken(accessToken, authentication); refreshToken = accessToken.getRefreshToken(); if (refreshToken != null) { tokenStore.storeRefreshToken(refreshToken, authentication); } return accessToken; } @Transactional(noRollbackFor = { InvalidTokenException.class, InvalidGrantException.class }) public OAuth2AccessToken refreshAccessToken(String refreshTokenValue, TokenRequest tokenRequest) throws AuthenticationException { if (!supportRefreshToken) { throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue); } OAuth2RefreshToken refreshToken = tokenStore.readRefreshToken(refreshTokenValue); if (refreshToken == null) { throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue); } OAuth2Authentication authentication = tokenStore.readAuthenticationForRefreshToken(refreshToken); if (this.authenticationManager != null && !authentication.isClientOnly()) { // The client has already been authenticated, but the user authentication // might be old now, so give it a // chance to re-authenticate. Authentication user = new PreAuthenticatedAuthenticationToken(authentication.getUserAuthentication(), "", authentication.getAuthorities()); user = authenticationManager.authenticate(user); Object details = authentication.getDetails(); authentication = new OAuth2Authentication(authentication.getOAuth2Request(), user); authentication.setDetails(details); } String clientId = authentication.getOAuth2Request().getClientId(); if (clientId == null || !clientId.equals(tokenRequest.getClientId())) { throw new InvalidGrantException("Wrong client for this refresh token: " + refreshTokenValue); } // clear out any access tokens already associated with the refresh // token. tokenStore.removeAccessTokenUsingRefreshToken(refreshToken); if (isExpired(refreshToken)) { tokenStore.removeRefreshToken(refreshToken); throw new InvalidTokenException("Invalid refresh token (expired): " + refreshToken); } authentication = createRefreshedAuthentication(authentication, tokenRequest); if (!reuseRefreshToken) { tokenStore.removeRefreshToken(refreshToken); refreshToken = createRefreshToken(authentication); } OAuth2AccessToken accessToken = createAccessToken(authentication, refreshToken); tokenStore.storeAccessToken(accessToken, authentication); if (!reuseRefreshToken) { tokenStore.storeRefreshToken(accessToken.getRefreshToken(), authentication); } return accessToken; } public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) { return tokenStore.getAccessToken(authentication); } /** * Create a refreshed authentication. * @param authentication The authentication. * @param request The scope for the refreshed token. * @return The refreshed authentication. * @throws InvalidScopeException If the scope requested is invalid or wider than the * original scope. */ private OAuth2Authentication createRefreshedAuthentication(OAuth2Authentication authentication, TokenRequest request) { OAuth2Authentication narrowed = authentication; Set<String> scope = request.getScope(); OAuth2Request clientAuth = authentication.getOAuth2Request().refresh(request); if (scope != null && !scope.isEmpty()) { Set<String> originalScope = clientAuth.getScope(); if (originalScope == null || !originalScope.containsAll(scope)) { throw new InvalidScopeException( "Unable to narrow the scope of the client authentication to " + scope + ".", originalScope); } else { clientAuth = clientAuth.narrowScope(scope); } } narrowed = new OAuth2Authentication(clientAuth, authentication.getUserAuthentication()); return narrowed; } protected boolean isExpired(OAuth2RefreshToken refreshToken) { if (refreshToken instanceof ExpiringOAuth2RefreshToken) { ExpiringOAuth2RefreshToken expiringToken = (ExpiringOAuth2RefreshToken) refreshToken; return expiringToken.getExpiration() == null || System.currentTimeMillis() > expiringToken.getExpiration().getTime(); } return false; } public OAuth2AccessToken readAccessToken(String accessToken) { return tokenStore.readAccessToken(accessToken); } public OAuth2Authentication loadAuthentication(String accessTokenValue) throws AuthenticationException, InvalidTokenException { OAuth2AccessToken accessToken = tokenStore.readAccessToken(accessTokenValue); if (accessToken == null) { throw new InvalidTokenException("Invalid access token: " + accessTokenValue); } else if (accessToken.isExpired()) { tokenStore.removeAccessToken(accessToken); throw new InvalidTokenException("Access token expired: " + accessTokenValue); } OAuth2Authentication result = tokenStore.readAuthentication(accessToken); if (result == null) { // in case of race condition throw new InvalidTokenException("Invalid access token: " + accessTokenValue); } if (clientDetailsService != null) { String clientId = result.getOAuth2Request().getClientId(); try { clientDetailsService.loadClientByClientId(clientId); } catch (ClientRegistrationException e) { throw new InvalidTokenException("Client not valid: " + clientId, e); } } return result; } public String getClientId(String tokenValue) { OAuth2Authentication authentication = tokenStore.readAuthentication(tokenValue); if (authentication == null) { throw new InvalidTokenException("Invalid access token: " + tokenValue); } OAuth2Request clientAuth = authentication.getOAuth2Request(); if (clientAuth == null) { throw new InvalidTokenException("Invalid access token (no client id): " + tokenValue); } return clientAuth.getClientId(); } public boolean revokeToken(String tokenValue) { OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue); if (accessToken == null) { return false; } if (accessToken.getRefreshToken() != null) { tokenStore.removeRefreshToken(accessToken.getRefreshToken()); } tokenStore.removeAccessToken(accessToken); return true; } private OAuth2RefreshToken createRefreshToken(OAuth2Authentication authentication) { if (!isSupportRefreshToken(authentication.getOAuth2Request())) { return null; } int validitySeconds = getRefreshTokenValiditySeconds(authentication.getOAuth2Request()); String value = UUID.randomUUID().toString(); if (validitySeconds > 0) { return new DefaultExpiringOAuth2RefreshToken(value, new Date(System.currentTimeMillis() + (validitySeconds * 1000L))); } return new DefaultOAuth2RefreshToken(value); } private OAuth2AccessToken createAccessToken(OAuth2Authentication authentication, OAuth2RefreshToken refreshToken) { DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(UUID.randomUUID().toString()); int validitySeconds = getAccessTokenValiditySeconds(authentication.getOAuth2Request()); if (validitySeconds > 0) { token.setExpiration(new Date(System.currentTimeMillis() + (validitySeconds * 1000L))); } token.setRefreshToken(refreshToken); token.setScope(authentication.getOAuth2Request().getScope()); return accessTokenEnhancer != null ? accessTokenEnhancer.enhance(token, authentication) : token; } /** * The access token validity period in seconds * @param clientAuth the current authorization request * @return the access token validity period in seconds */ protected int getAccessTokenValiditySeconds(OAuth2Request clientAuth) { if (clientDetailsService != null) { ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId()); Integer validity = client.getAccessTokenValiditySeconds(); if (validity != null) { return validity; } } return accessTokenValiditySeconds; } /** * The refresh token validity period in seconds * @param clientAuth the current authorization request * @return the refresh token validity period in seconds */ protected int getRefreshTokenValiditySeconds(OAuth2Request clientAuth) { if (clientDetailsService != null) { ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId()); Integer validity = client.getRefreshTokenValiditySeconds(); if (validity != null) { return validity; } } return refreshTokenValiditySeconds; } /** * Is a refresh token supported for this client (or the global setting if * {@link #setClientDetailsService(ClientDetailsService) clientDetailsService} is not * set. * @param clientAuth the current authorization request * @return boolean to indicate if refresh token is supported */ protected boolean isSupportRefreshToken(OAuth2Request clientAuth) { if (clientDetailsService != null) { ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId()); return client.getAuthorizedGrantTypes().contains("refresh_token"); } return this.supportRefreshToken; } /** * An access token enhancer that will be applied to a new token before it is saved in * the token store. * @param accessTokenEnhancer the access token enhancer to set */ public void setTokenEnhancer(TokenEnhancer accessTokenEnhancer) { this.accessTokenEnhancer = accessTokenEnhancer; } /** * The validity (in seconds) of the refresh token. If less than or equal to zero then * the tokens will be non-expiring. * @param refreshTokenValiditySeconds The validity (in seconds) of the refresh token. */ public void setRefreshTokenValiditySeconds(int refreshTokenValiditySeconds) { this.refreshTokenValiditySeconds = refreshTokenValiditySeconds; } /** * The default validity (in seconds) of the access token. Zero or negative for * non-expiring tokens. If a client details service is set the validity period will be * read from the client, defaulting to this value if not defined by the client. * @param accessTokenValiditySeconds The validity (in seconds) of the access token. */ public void setAccessTokenValiditySeconds(int accessTokenValiditySeconds) { this.accessTokenValiditySeconds = accessTokenValiditySeconds; } /** * Whether to support the refresh token. * @param supportRefreshToken Whether to support the refresh token. */ public void setSupportRefreshToken(boolean supportRefreshToken) { this.supportRefreshToken = supportRefreshToken; } /** * Whether to reuse refresh tokens (until expired). * @param reuseRefreshToken Whether to reuse refresh tokens (until expired). */ public void setReuseRefreshToken(boolean reuseRefreshToken) { this.reuseRefreshToken = reuseRefreshToken; } /** * The persistence strategy for token storage. * @param tokenStore the store for access and refresh tokens. */ public void setTokenStore(TokenStore tokenStore) { this.tokenStore = tokenStore; } /** * An authentication manager that will be used (if provided) to check the user * authentication when a token is refreshed. * @param authenticationManager the authenticationManager to set */ public void setAuthenticationManager(AuthenticationManager authenticationManager) { this.authenticationManager = authenticationManager; } /** * The client details service to use for looking up clients (if necessary). Optional * if the access token expiry is set globally via * {@link #setAccessTokenValiditySeconds(int)}. * @param clientDetailsService the client details service */ public void setClientDetailsService(ClientDetailsService clientDetailsService) { this.clientDetailsService = clientDetailsService; }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package com.strongdata.rill.core.security.server.token;import com.strongdata.rill.core.base.util.SpringContextHolder;import com.strongdata.rill.core.security.server.token.store.redis.RillRedisTokenStore;import lombok.extern.slf4j.Slf4j;import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;import org.springframework.scheduling.annotation.EnableScheduling;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;/** * @author wildwind * @date 2022/3/29 * <p> * redis token store 自动配置 */@Slf4j@EnableScheduling@ConditionalOnBean(AuthorizationServerConfigurerAdapter.class)public class RillTokenStoreAutoCleanSchedule { /** * 每小时执行一致,避免 redis zset 容量问题 */ @Scheduled(cron = "@hourly") public void doMaintenance() { RillRedisTokenStore tokenStore = SpringContextHolder.getBean(RillRedisTokenStore.class); long maintenance = tokenStore.doMaintenance(); log.debug("清理Redis ZADD 过期 token 数量: {}", maintenance); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package com.strongdata.rill.core.security.server.token;import com.strongdata.rill.core.base.constant.CacheConstants;import com.strongdata.rill.core.security.server.token.store.redis.RillRedisTokenStore;import org.springframework.context.annotation.Bean;import org.springframework.data.redis.connection.RedisConnectionFactory;import org.springframework.security.oauth2.provider.token.TokenStore;/** * @author wildwind * @date 2022/3/16 */public class RillTokenStoreAutoConfiguration { @Bean public TokenStore tokenStore(RedisConnectionFactory redisConnectionFactory) { RillRedisTokenStore tokenStore = new RillRedisTokenStore(redisConnectionFactory); tokenStore.setPrefix(CacheConstants.PROJECT_OAUTH_ACCESS); return tokenStore; }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package com.strongdata.rill.core.security.server.token.store.redis;import com.strongdata.rill.core.security.server.token.store.redis.serializer.json.FastJsonSerializationStrategy;import org.springframework.data.redis.connection.RedisConnection;import org.springframework.data.redis.connection.RedisConnectionFactory;import org.springframework.data.redis.connection.RedisZSetCommands;import org.springframework.data.redis.core.Cursor;import org.springframework.data.redis.core.ScanOptions;import org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken;import org.springframework.security.oauth2.common.OAuth2AccessToken;import org.springframework.security.oauth2.common.OAuth2RefreshToken;import org.springframework.security.oauth2.provider.OAuth2Authentication;import org.springframework.security.oauth2.provider.token.AuthenticationKeyGenerator;import org.springframework.security.oauth2.provider.token.DefaultAuthenticationKeyGenerator;import org.springframework.security.oauth2.provider.token.TokenStore;import org.springframework.security.oauth2.provider.token.store.redis.JdkSerializationStrategy;import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStoreSerializationStrategy;import org.springframework.util.ClassUtils;import org.springframework.util.ReflectionUtils;import java.lang.reflect.Method;import java.util.*;/** * @author efenderbosch * @date 2020/9/30 * <p> * @link https://github.com/spring-projects/spring-security-oauth/pull/1660 * 重写RedisTokenStore ,主要解决 #1814 oauth2中client_id_to_access数据膨胀问题 */public class RillRedisTokenStore implements TokenStore { private static final String ACCESS = "access:"; private static final String AUTH_TO_ACCESS = "auth_to_access:"; private static final String AUTH = "auth:"; private static final String REFRESH_AUTH = "refresh_auth:"; private static final String REFRESH = "refresh:"; private static final String REFRESH_TO_ACCESS = "refresh_to_access:"; private static final String CLIENT_ID_TO_ACCESS = "client_id_to_access_z:"; private static final String UNAME_TO_ACCESS = "uname_to_access_z:"; private static final boolean springDataRedis_2_0 = ClassUtils.isPresent( "org.springframework.data.redis.connection.RedisStandaloneConfiguration", RedisTokenStore.class.getClassLoader()); private final RedisConnectionFactory connectionFactory; private AuthenticationKeyGenerator authenticationKeyGenerator = new DefaultAuthenticationKeyGenerator(); private RedisTokenStoreSerializationStrategy serializationStrategy = new JdkSerializationStrategy(); private String prefix = ""; private Method redisConnectionSet_2_0; public RillRedisTokenStore(RedisConnectionFactory connectionFactory) { this.connectionFactory = connectionFactory; if (springDataRedis_2_0) { this.loadRedisConnectionMethods_2_0(); } } public void setAuthenticationKeyGenerator(AuthenticationKeyGenerator authenticationKeyGenerator) { this.authenticationKeyGenerator = authenticationKeyGenerator; } public void setSerializationStrategy(RedisTokenStoreSerializationStrategy serializationStrategy) { this.serializationStrategy = serializationStrategy; } public void setPrefix(String prefix) { this.prefix = prefix; } private void loadRedisConnectionMethods_2_0() { this.redisConnectionSet_2_0 = ReflectionUtils.findMethod(RedisConnection.class, "set", byte[].class, byte[].class); } private RedisConnection getConnection() { return connectionFactory.getConnection(); } private byte[] serialize(Object object) { return serializationStrategy.serialize(object); } private byte[] serializeKey(String object) { return serialize(prefix + object); } private OAuth2AccessToken deserializeAccessToken(byte[] bytes) { return serializationStrategy.deserialize(bytes, OAuth2AccessToken.class); } private OAuth2Authentication deserializeAuthentication(byte[] bytes) { return serializationStrategy.deserialize(bytes, OAuth2Authentication.class); } private OAuth2RefreshToken deserializeRefreshToken(byte[] bytes) { return serializationStrategy.deserialize(bytes, OAuth2RefreshToken.class); } private byte[] serialize(String string) { return serializationStrategy.serialize(string); } private String deserializeString(byte[] bytes) { return serializationStrategy.deserializeString(bytes); } @Override public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) { String key = authenticationKeyGenerator.extractKey(authentication); byte[] serializedKey = serializeKey(AUTH_TO_ACCESS + key); byte[] bytes; try (RedisConnection conn = getConnection()) { bytes = conn.get(serializedKey); } OAuth2AccessToken accessToken = deserializeAccessToken(bytes); if (accessToken != null) { OAuth2Authentication storedAuthentication = readAuthentication(accessToken.getValue()); if ((storedAuthentication == null || !key.equals(authenticationKeyGenerator.extractKey(storedAuthentication)))) { // Keep the stores consistent (maybe the same user is // represented by this authentication but the details have // changed) storeAccessToken(accessToken, authentication); } } return accessToken; } @Override public OAuth2Authentication readAuthentication(OAuth2AccessToken token) { return readAuthentication(token.getValue()); } @Override public OAuth2Authentication readAuthentication(String token) { byte[] bytes; try (RedisConnection conn = getConnection()) { bytes = conn.get(serializeKey(AUTH + token)); } return deserializeAuthentication(bytes); } @Override public OAuth2Authentication readAuthenticationForRefreshToken(OAuth2RefreshToken token) { return readAuthenticationForRefreshToken(token.getValue()); } public OAuth2Authentication readAuthenticationForRefreshToken(String token) { try (RedisConnection conn = getConnection()) { byte[] bytes = conn.get(serializeKey(REFRESH_AUTH + token)); return deserializeAuthentication(bytes); } } @Override public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) { byte[] serializedAccessToken = serialize(token); byte[] serializedAuth = serialize(authentication); byte[] accessKey = serializeKey(ACCESS + token.getValue()); byte[] authKey = serializeKey(AUTH + token.getValue()); byte[] authToAccessKey = serializeKey(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication)); byte[] approvalKey = serializeKey(UNAME_TO_ACCESS + getApprovalKey(authentication)); byte[] clientId = serializeKey(CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId()); try (RedisConnection conn = getConnection()) { conn.openPipeline(); if (springDataRedis_2_0) { try { this.redisConnectionSet_2_0.invoke(conn, accessKey, serializedAccessToken); this.redisConnectionSet_2_0.invoke(conn, authKey, serializedAuth); this.redisConnectionSet_2_0.invoke(conn, authToAccessKey, serializedAccessToken); } catch (Exception ex) { throw new RuntimeException(ex); } } else { conn.set(accessKey, serializedAccessToken); conn.set(authKey, serializedAuth); conn.set(authToAccessKey, serializedAccessToken); } if (token.getExpiration() != null) { int seconds = token.getExpiresIn(); long expirationTime = token.getExpiration().getTime(); if (!authentication.isClientOnly()) { conn.zAdd(approvalKey, expirationTime, serializedAccessToken); } conn.zAdd(clientId, expirationTime, serializedAccessToken); conn.expire(accessKey, seconds); conn.expire(authKey, seconds); conn.expire(authToAccessKey, seconds); conn.expire(clientId, seconds); conn.expire(approvalKey, seconds); } else { conn.zAdd(clientId, -1, serializedAccessToken); if (!authentication.isClientOnly()) { conn.zAdd(approvalKey, -1, serializedAccessToken); } } OAuth2RefreshToken refreshToken = token.getRefreshToken(); if (refreshToken != null && refreshToken.getValue() != null) { byte[] auth = serialize(token.getValue()); byte[] refreshToAccessKey = serializeKey(REFRESH_TO_ACCESS + token.getRefreshToken().getValue()); if (springDataRedis_2_0) { try { this.redisConnectionSet_2_0.invoke(conn, refreshToAccessKey, auth); } catch (Exception ex) { throw new RuntimeException(ex); } } else { conn.set(refreshToAccessKey, auth); } if (refreshToken instanceof ExpiringOAuth2RefreshToken) { ExpiringOAuth2RefreshToken expiringRefreshToken = (ExpiringOAuth2RefreshToken) refreshToken; Date expiration = expiringRefreshToken.getExpiration(); if (expiration != null) { int seconds = Long.valueOf((expiration.getTime() - System.currentTimeMillis()) / 1000L) .intValue(); conn.expire(refreshToAccessKey, seconds); } } } conn.closePipeline(); } } private static String getApprovalKey(OAuth2Authentication authentication) { String userName = authentication.getUserAuthentication() == null ? "" : authentication.getUserAuthentication().getName(); return getApprovalKey(authentication.getOAuth2Request().getClientId(), userName); } private static String getApprovalKey(String clientId, String userName) { return clientId + (userName == null ? "" : ":" + userName); } @Override public void removeAccessToken(OAuth2AccessToken accessToken) { removeAccessToken(accessToken.getValue()); } @Override public OAuth2AccessToken readAccessToken(String tokenValue) { byte[] key = serializeKey(ACCESS + tokenValue); byte[] bytes; try (RedisConnection conn = getConnection()) { bytes = conn.get(key); } return deserializeAccessToken(bytes); } public void removeAccessToken(String tokenValue) { byte[] accessKey = serializeKey(ACCESS + tokenValue); byte[] authKey = serializeKey(AUTH + tokenValue); try (RedisConnection conn = getConnection()) { conn.openPipeline(); conn.get(accessKey); conn.get(authKey); conn.del(accessKey); // Don't remove the refresh token - it's up to the caller to do that conn.del(authKey); List<Object> results = conn.closePipeline(); byte[] access = (byte[]) results.get(0); byte[] auth = (byte[]) results.get(1); OAuth2Authentication authentication = deserializeAuthentication(auth); if (authentication != null) { String key = authenticationKeyGenerator.extractKey(authentication); byte[] authToAccessKey = serializeKey(AUTH_TO_ACCESS + key); byte[] unameKey = serializeKey(UNAME_TO_ACCESS + getApprovalKey(authentication)); byte[] clientId = serializeKey(CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId()); conn.openPipeline(); conn.del(authToAccessKey); conn.zRem(unameKey, access); conn.zRem(clientId, access); conn.del(serialize(ACCESS + key)); conn.closePipeline(); } } } @Override public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) { byte[] refreshKey = serializeKey(REFRESH + refreshToken.getValue()); byte[] refreshAuthKey = serializeKey(REFRESH_AUTH + refreshToken.getValue()); byte[] serializedRefreshToken = serialize(refreshToken); try (RedisConnection conn = getConnection()) { conn.openPipeline(); if (springDataRedis_2_0) { try { this.redisConnectionSet_2_0.invoke(conn, refreshKey, serializedRefreshToken); this.redisConnectionSet_2_0.invoke(conn, refreshAuthKey, serialize(authentication)); } catch (Exception ex) { throw new RuntimeException(ex); } } else { conn.set(refreshKey, serializedRefreshToken); conn.set(refreshAuthKey, serialize(authentication)); } if (refreshToken instanceof ExpiringOAuth2RefreshToken) { ExpiringOAuth2RefreshToken expiringRefreshToken = (ExpiringOAuth2RefreshToken) refreshToken; Date expiration = expiringRefreshToken.getExpiration(); if (expiration != null) { int seconds = Long.valueOf((expiration.getTime() - System.currentTimeMillis()) / 1000L).intValue(); conn.expire(refreshKey, seconds); conn.expire(refreshAuthKey, seconds); } } conn.closePipeline(); } } @Override public OAuth2RefreshToken readRefreshToken(String tokenValue) { byte[] key = serializeKey(REFRESH + tokenValue); byte[] bytes; try (RedisConnection conn = getConnection()) { bytes = conn.get(key); } return deserializeRefreshToken(bytes); } @Override public void removeRefreshToken(OAuth2RefreshToken refreshToken) { removeRefreshToken(refreshToken.getValue()); } public void removeRefreshToken(String tokenValue) { byte[] refreshKey = serializeKey(REFRESH + tokenValue); byte[] refreshAuthKey = serializeKey(REFRESH_AUTH + tokenValue); byte[] refresh2AccessKey = serializeKey(REFRESH_TO_ACCESS + tokenValue); try (RedisConnection conn = getConnection()) { conn.openPipeline(); conn.del(refreshKey); conn.del(refreshAuthKey); conn.del(refresh2AccessKey); conn.closePipeline(); } } @Override public void removeAccessTokenUsingRefreshToken(OAuth2RefreshToken refreshToken) { removeAccessTokenUsingRefreshToken(refreshToken.getValue()); } private void removeAccessTokenUsingRefreshToken(String refreshToken) { byte[] key = serializeKey(REFRESH_TO_ACCESS + refreshToken); List<Object> results; try (RedisConnection conn = getConnection()) { conn.openPipeline(); conn.get(key); conn.del(key); results = conn.closePipeline(); } byte[] bytes = (byte[]) results.get(0); String accessToken = deserializeString(bytes); if (accessToken != null) { removeAccessToken(accessToken); } } private List<byte[]> getZByteLists(byte[] key, RedisConnection conn) { // Sorted Set expiration maintenance long currentTime = System.currentTimeMillis(); conn.zRemRangeByScore(key, 0, currentTime); List<byte[]> byteList; Long size = conn.zCard(key); assert size != null; byteList = new ArrayList<>(size.intValue()); Cursor<RedisZSetCommands.Tuple> cursor = conn.zScan(key, ScanOptions.NONE); while (cursor.hasNext()) { RedisZSetCommands.Tuple t = cursor.next(); // Probably not necessary because of the maintenance at the beginning but why // not... if (t.getScore() == -1 || t.getScore() > currentTime) { byteList.add(t.getValue()); } } return byteList; } /** * Runs a maintenance of the RedisTokenStore. * <p> * SortedSets UNAME_TO_ACCESS and CLIENT_ID_TO_ACCESS contains access tokens that can * expire. This expiration is set as a score of the Redis SortedSet data structure. * Redis does not support expiration of items in a container data structure. It * supports only expiration of whole key. In case there is still new access tokens * being stored into the RedisTokenStore before whole key gets expired, the expiration * is prolonged and the key is not effectively deleted. To do "garbage collection" * this method should be called once upon a time. * @return how many items were removed */ public long doMaintenance() { long removed = 0; try (RedisConnection conn = getConnection()) { // client_id_to_acccess maintenance Cursor<byte[]> clientToAccessKeys = conn .scan(ScanOptions.scanOptions().match(prefix + CLIENT_ID_TO_ACCESS + "*").build()); while (clientToAccessKeys.hasNext()) { byte[] clientIdToAccessKey = clientToAccessKeys.next(); removed += conn.zRemRangeByScore(clientIdToAccessKey, 0, System.currentTimeMillis()); } // uname_to_access maintenance Cursor<byte[]> unameToAccessKeys = conn .scan(ScanOptions.scanOptions().match(prefix + UNAME_TO_ACCESS + "*").build()); while (unameToAccessKeys.hasNext()) { byte[] unameToAccessKey = unameToAccessKeys.next(); removed += conn.zRemRangeByScore(unameToAccessKey, 0, System.currentTimeMillis()); } } return removed; } @Override public Collection<OAuth2AccessToken> findTokensByClientIdAndUserName(String clientId, String userName) { byte[] approvalKey = serializeKey(UNAME_TO_ACCESS + getApprovalKey(clientId, userName)); List<byte[]> byteList; try (RedisConnection conn = getConnection()) { byteList = getZByteLists(approvalKey, conn); } if (byteList.size() == 0) { return Collections.emptySet(); } List<OAuth2AccessToken> accessTokens = new ArrayList<>(byteList.size()); for (byte[] bytes : byteList) { OAuth2AccessToken accessToken = deserializeAccessToken(bytes); accessTokens.add(accessToken); } return Collections.unmodifiableCollection(accessTokens); } @Override public Collection<OAuth2AccessToken> findTokensByClientId(String clientId) { byte[] key = serializeKey(CLIENT_ID_TO_ACCESS + clientId); List<byte[]> byteList; try (RedisConnection conn = getConnection()) { byteList = getZByteLists(key, conn); } if (byteList.size() == 0) { return Collections.emptySet(); } List<OAuth2AccessToken> accessTokens = new ArrayList<>(byteList.size()); for (byte[] bytes : byteList) { OAuth2AccessToken accessToken = deserializeAccessToken(bytes); accessTokens.add(accessToken); } return Collections.unmodifiableCollection(accessTokens); }}
package com.strongdata.rill.core.security.server.token.store.redis.serializer.json;import com.alibaba.fastjson.JSONObject;import com.alibaba.fastjson.parser.DefaultJSONParser;import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;import org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken;import java.lang.reflect.Type;public class DefaultOauth2RefreshTokenSerializer implements ObjectDeserializer { @Override public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { if (type == DefaultOAuth2RefreshToken.class) { JSONObject jsonObject = parser.parseObject(); String tokenId = jsonObject.getString("value"); DefaultOAuth2RefreshToken refreshToken = new DefaultOAuth2RefreshToken(tokenId); return (T) refreshToken; } return null; } @Override public int getFastMatchToken() { return 0; }}
package com.strongdata.rill.core.security.server.token.store.redis.serializer.json;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.parser.ParserConfig;import com.alibaba.fastjson.serializer.SerializerFeature;import com.alibaba.fastjson.util.IOUtils;import com.alibaba.fastjson.util.TypeUtils;import com.strongdata.rill.core.security.RillUser;import org.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken;import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;import org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken;import org.springframework.security.oauth2.provider.OAuth2Authentication;import org.springframework.security.oauth2.provider.client.BaseClientDetails;import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStoreSerializationStrategy;import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;import java.nio.charset.Charset;public class FastJsonSerializationStrategy implements RedisTokenStoreSerializationStrategy { private static ParserConfig config = new ParserConfig(); static { init(); } protected static void init() { //自定义oauth2序列化:DefaultOAuth2RefreshToken 没有setValue方法,会导致JSON序列化为null config.setAutoTypeSupport(true);//开启AutoType //自定义DefaultOauth2RefreshTokenSerializer反序列化 config.putDeserializer(DefaultOAuth2RefreshToken.class, new DefaultOauth2RefreshTokenSerializer()); //自定义OAuth2Authentication反序列化 config.putDeserializer(OAuth2Authentication.class, new OAuth2AuthenticationSerializer()); //添加autotype白名单 config.addAccept("org.springframework.security.oauth2.provider."); config.addAccept("org.springframework.security.oauth2.provider.client"); TypeUtils.addMapping("org.springframework.security.oauth2.provider.OAuth2Authentication", OAuth2Authentication.class); TypeUtils.addMapping("org.springframework.security.oauth2.provider.client.BaseClientDetails", BaseClientDetails.class); config.addAccept("org.springframework.security.oauth2.common."); TypeUtils.addMapping("org.springframework.security.oauth2.common.DefaultOAuth2AccessToken", DefaultOAuth2AccessToken.class); TypeUtils.addMapping("org.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken", DefaultExpiringOAuth2RefreshToken.class); config.addAccept("com.strongdata.rill.core.security"); TypeUtils.addMapping("com.strongdata.rill.core.security.RillUser", RillUser.class); config.addAccept("org.springframework.security.web.authentication.preauth"); TypeUtils.addMapping("org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken", PreAuthenticatedAuthenticationToken.class); } @Override public <T> T deserialize(byte[] bytes, Class<T> aClass) {// Preconditions.checkArgument(aClass != null,// "clazz can't be null"); if (bytes == null || bytes.length == 0) { return null; } try { return JSON.parseObject(new String(bytes, IOUtils.UTF8), aClass, config); } catch (Exception ex) { throw new RuntimeException("Could not serialize: " + ex.getMessage(), ex); } } @Override public String deserializeString(byte[] bytes) { if (bytes == null || bytes.length == 0) { return null; } return new String(bytes, IOUtils.UTF8); } @Override public byte[] serialize(Object o) { if (o == null) { return new byte[0]; } try { return JSON.toJSONBytes(o, SerializerFeature.WriteClassName, SerializerFeature.DisableCircularReferenceDetect); } catch (Exception ex) { throw new RuntimeException("Could not serialize: " + ex.getMessage(), ex); } } @Override public byte[] serialize(String data) { if (data == null || data.length() == 0) { return new byte[0]; } return data.getBytes(Charset.forName("utf-8")); }}
package com.strongdata.rill.core.security.server.token.store.redis.serializer.json;import com.alibaba.fastjson.JSONObject;import com.alibaba.fastjson.TypeReference;import com.alibaba.fastjson.parser.DefaultJSONParser;import com.alibaba.fastjson.parser.Feature;import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;import org.springframework.security.core.GrantedAuthority;import org.springframework.security.core.authority.SimpleGrantedAuthority;import org.springframework.security.oauth2.provider.OAuth2Authentication;import org.springframework.security.oauth2.provider.OAuth2Request;import org.springframework.security.oauth2.provider.TokenRequest;import java.io.Serializable;import java.lang.reflect.Type;import java.util.HashMap;import java.util.HashSet;import java.util.Map;import java.util.Set;public class OAuth2AuthenticationSerializer implements ObjectDeserializer { @Override public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { if (type == OAuth2Authentication.class) { try { Object o = parse(parser); if (o == null) { return null; } else if (o instanceof OAuth2Authentication) { return (T) o; } JSONObject jsonObject = (JSONObject) o; OAuth2Request request = parseOAuth2Request(jsonObject); //Determine the type of userAuthentication of the json node, and dynamically obtain the value according to the type //UsernamePasswordAuthenticationToken password mode/authorization code mode, the storage type is UsernamePasswordAuthenticationToken //PreAuthenticatedAuthenticationToken refresh token mode, the storage type is PreAuthenticatedAuthenticationToken Object autoType = jsonObject.get("userAuthentication"); return (T) new OAuth2Authentication(request, jsonObject.getObject("userAuthentication", (Type) autoType.getClass())); } catch (Exception e) { e.printStackTrace(); } return null; } return null; } private OAuth2Request parseOAuth2Request(JSONObject jsonObject) { JSONObject json = jsonObject.getObject("oAuth2Request", JSONObject.class); Map<String, String> requestParameters = json.getObject("requestParameters", Map.class); String clientId = json.getString("clientId"); String grantType = json.getString("grantType"); String redirectUri = json.getString("redirectUri"); Boolean approved = json.getBoolean("approved"); Set<String> responseTypes = json.getObject("responseTypes", new TypeReference<HashSet<String>>() { }); Set<String> scope = json.getObject("scope", new TypeReference<HashSet<String>>() { }); Set<String> authorities = json.getObject("authorities", new TypeReference<HashSet<String>>() { }); Set<GrantedAuthority> grantedAuthorities = new HashSet<>(0); if (authorities != null && !authorities.isEmpty()) { authorities.forEach(s -> grantedAuthorities.add(new SimpleGrantedAuthority(s))); } Set<String> resourceIds = json.getObject("resourceIds", new TypeReference<HashSet<String>>() { }); Map<String, Serializable> extensions = json.getObject("extensions", new TypeReference<HashMap<String, Serializable>>() { }); OAuth2Request request = new OAuth2Request(requestParameters, clientId, grantedAuthorities, approved, scope, resourceIds, redirectUri, responseTypes, extensions); TokenRequest tokenRequest = new TokenRequest(requestParameters, clientId, scope, grantType); request.refresh(tokenRequest); return request; } @Override public int getFastMatchToken() { return 0; } private Object parse(DefaultJSONParser parse) { JSONObject object = new JSONObject(parse.lexer.isEnabled(Feature.OrderedField)); Object parsedObject = parse.parseObject((Map) object); if (parsedObject instanceof JSONObject) { return (JSONObject) parsedObject; } else if (parsedObject instanceof OAuth2Authentication) { return parsedObject; } else { return parsedObject == null ? null : new JSONObject((Map) parsedObject); } }}
package com.strongdata.rill.core.security.util;import cn.hutool.core.net.URLDecoder;import cn.hutool.crypto.Mode;import cn.hutool.crypto.Padding;import cn.hutool.crypto.symmetric.AES;import org.apache.commons.codec.binary.Base64;import org.springframework.util.Base64Utils;import javax.crypto.KeyGenerator;import javax.crypto.SecretKey;import javax.crypto.spec.IvParameterSpec;import javax.crypto.spec.SecretKeySpec;import java.nio.charset.StandardCharsets;import java.security.NoSuchAlgorithmException;import java.util.UUID;public class AESTest { public static void main(String[] args) { AES aes = new AES(Mode.CFB, Padding.NoPadding, new SecretKeySpec("rillisagoodstack".getBytes(), "AES"), new IvParameterSpec("rillisagoodstack".getBytes())); System.out.println(aes.decryptStr("WlzkRVRx")); System.out.println(URLDecoder.decode(aes.encrypt("123456"))); System.out.println(Base64.encodeBase64String(UUID.randomUUID().toString().replaceAll("-","").getBytes())); System.out.println(Base64Utils.encodeToString(("rill:rill").getBytes(StandardCharsets.UTF_8))); System.out.println(Base64Utils.encodeToString(("wechat_enterprise:wechat_enterprise").getBytes(StandardCharsets.UTF_8))); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package com.strongdata.rill.core.security.util;import cn.hutool.core.codec.Base64;import cn.hutool.core.util.CharsetUtil;import lombok.SneakyThrows;import lombok.experimental.UtilityClass;import lombok.extern.slf4j.Slf4j;import org.springframework.http.HttpHeaders;import javax.servlet.http.HttpServletRequest;/** * @author wildwind * @date 2022/2/1 认证授权相关工具类 */@Slf4j@UtilityClasspublic class AuthUtils { private final String BASIC_ = "Basic "; /** * 从header 请求中的clientId/clientsecect * @param header header中的参数 */ @SneakyThrows public String[] extractAndDecodeHeader(String header) { byte[] base64Token = header.substring(6).getBytes("UTF-8"); byte[] decoded; try { decoded = Base64.decode(base64Token); } catch (IllegalArgumentException e) { throw new RuntimeException("Failed to decode basic authentication token"); } String token = new String(decoded, CharsetUtil.UTF_8); int delim = token.indexOf(":"); if (delim == -1) { throw new RuntimeException("Invalid basic authentication token"); } return new String[] { token.substring(0, delim), token.substring(delim + 1) }; } /** * *从header 请求中的clientId/clientsecect * @param request * @return */ @SneakyThrows public String[] extractAndDecodeHeader(HttpServletRequest request) { String header = request.getHeader(HttpHeaders.AUTHORIZATION); if (header == null || !header.startsWith(BASIC_)) { throw new RuntimeException("请求头中client信息为空"); } return extractAndDecodeHeader(header); }}
package com.strongdata.rill.core.security.util;import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;import org.jasypt.salt.RandomSaltGenerator;public class PBEStringEncryptorTest { public static void main(String[] args) { StandardPBEStringEncryptor encryptor=new StandardPBEStringEncryptor(); encryptor.setAlgorithm("PBEWithMD5AndDES"); encryptor.setKeyObtentionIterations(1000); encryptor.setSaltGenerator(new RandomSaltGenerator()); encryptor.setPassword("rill"); String accessKey = encryptor.encrypt("rill1"); String secretKey = encryptor.encrypt("passwd"); System.out.println("加密后账号:"+ accessKey); System.out.println("加密后密码:"+ secretKey); System.out.println("解密后账号:"+ encryptor.decrypt(accessKey)); System.out.println("解密后密码:"+ encryptor.decrypt(accessKey)); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package com.strongdata.rill.core.security.util;import cn.hutool.core.util.StrUtil;import com.strongdata.rill.core.base.constant.SecurityConstants;import com.strongdata.rill.core.security.RillUser;import lombok.experimental.UtilityClass;import org.springframework.security.core.Authentication;import org.springframework.security.core.GrantedAuthority;import org.springframework.security.core.context.SecurityContextHolder;import java.util.ArrayList;import java.util.Collection;import java.util.List;/** * 安全工具类 * * @author wildwind */@UtilityClasspublic class SecurityUtils { /** * 获取Authentication */ public Authentication getAuthentication() { return SecurityContextHolder.getContext().getAuthentication(); } /** * 获取用户 */ public RillUser getUser(Authentication authentication) { Object principal = authentication.getPrincipal(); if (principal instanceof RillUser) { return (RillUser) principal; } return null; } /** * 获取用户 */ public RillUser getUser() { Authentication authentication = getAuthentication(); if (authentication == null) { return null; } return getUser(authentication); } /** * 获取用户角色信息 * @return 角色集合 */ public List<Long> getRoles() { Authentication authentication = getAuthentication(); Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); List<Long> roleIds = new ArrayList<>(); authorities.stream().filter(granted -> StrUtil.startWith(granted.getAuthority(), SecurityConstants.ROLE)) .forEach(granted -> { String id = StrUtil.removePrefix(granted.getAuthority(), SecurityConstants.ROLE); roleIds.add(Long.parseLong(id)); }); return roleIds; }}
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */package com.chinatower.product.monitoring.common;/** * @author peng-yongsheng */public class BooleanUtils { public static final int TRUE = 1; public static final int FALSE = 0; public static boolean valueToBoolean(int value) { if (TRUE == value) { return true; } else if (FALSE == value) { return false; } else { throw new RuntimeException("Boolean value error, must be 0 or 1"); } } public static int booleanToValue(Boolean booleanValue) { if (booleanValue) { return TRUE; } else { return FALSE; } }}
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */package com.chinatower.product.monitoring.common;/** * @author peng-yongsheng */public class Const { public static final int NONE = 0; public static final String ID_SPLIT = "_"; public static final String LINE = "-"; public static final String SPACE = " "; public static final String KEY_VALUE_SPLIT = ","; public static final String ARRAY_SPLIT = "|"; public static final String ARRAY_PARSER_SPLIT = "\\|"; public static final int USER_SERVICE_ID = 1; public static final int USER_INSTANCE_ID = 1; public static final int USER_ENDPOINT_ID = 1; public static final int INEXISTENCE_ENDPOINT_ID = -1; public static final String USER_CODE = "User"; public static final String SEGMENT_SPAN_SPLIT = "S"; public static final String UNKNOWN = "Unknown"; public static final String EMPTY_STRING = ""; public static final String EMPTY_JSON_OBJECT_STRING = "{}"; public static final String DOMAIN_OPERATION_NAME = "{domain}";}
package com.chinatower.product.monitoring.common;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import java.util.HashMap;import java.util.Map;public class DateUtils { /** * 时间转换 +8个小时 UTC->CST * * @param UTCStr * @param format * @return */ public static String UTCToCST(String UTCStr, String format) { Date date = null; SimpleDateFormat sdf = new SimpleDateFormat(format); try { date = sdf.parse(UTCStr); //System.out.println("UTC时间: " + date); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.HOUR, calendar.get(Calendar.HOUR) + 8); //calendar.getTime() 返回的是Date类型,也可以使用calendar.getTimeInMillis()获取时间戳 Date CSTDate = calendar.getTime(); return sdf.format(CSTDate); } catch (ParseException e) { throw new RuntimeException("时间转换错误"); } } /** * 时间long转字符串 * * @param dateLong * @param pattern * @return */ public static String longDate2String(Long dateLong, String pattern) { SimpleDateFormat sdf = new SimpleDateFormat(pattern); Date date = new Date(dateLong); String format = sdf.format(dateLong); return format; } //2020-4-30.12 => 2020-04-30T00:00:00.000Z //时间转换 -8个小时 CST->UTC public static String dateFormat(String dateString, String pattern) { try { SimpleDateFormat sdf = new SimpleDateFormat(pattern); Date date = sdf.parse(dateString); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.HOUR, calendar.get(Calendar.HOUR) - 8); //calendar.getTime() 返回的是Date类型,也可以使用calendar.getTimeInMillis()获取时间戳 Date UTCDate = calendar.getTime(); SimpleDateFormat sdfUTC = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); String format = sdfUTC.format(UTCDate); return format; } catch (ParseException e) { e.printStackTrace(); return null; } } /** * 字符串转long * * @param dateString * @param pattern * @return */ public static Long string2Date(String dateString, String pattern) { Long time = null; try { SimpleDateFormat sdf = new SimpleDateFormat(pattern); Date parse = sdf.parse(dateString); time = parse.getTime(); } catch (ParseException e) { e.printStackTrace(); } return time; } /** * 将long型时间(s)换算成最大时间单位的时间数据 多余的忽略 * @param mss * @return */ public static Map<Long, String> formatDateTime(long mss) { Map<Long, String> dateTimes = new HashMap<>(); long days = mss / ( 60 * 60 * 24); long hours = (mss % ( 60 * 60 * 24)) / (60 * 60); long minutes = (mss % ( 60 * 60)) /60; long seconds = mss % 60; if(days>0){ dateTimes.put(days,"d"); }else if(hours>0){ dateTimes.put(hours,"h"); }else if(minutes>0){ dateTimes.put(minutes,"m"); }else{ dateTimes.put(seconds,"s"); } return dateTimes; } /** * 把现有的时间格式转为指定格式string->string * @param dateString * @param patternOld * @param patternNew * @return */ public static String stringFormatString(String dateString, String patternOld, String patternNew) { try { SimpleDateFormat sdf = new SimpleDateFormat(patternOld); Date date = sdf.parse(dateString); SimpleDateFormat sdfUTC = new SimpleDateFormat(patternNew); String format = sdfUTC.format(date); return format; } catch (ParseException e) { e.printStackTrace(); return null; } } /** * 获取某年某月的最后一天 * @param year * @param month * @return */ public static String getLastDayOfMonth(int year, int month) { Calendar cal = Calendar.getInstance(); //设置年份 cal.set(Calendar.YEAR, year); //设置月份 cal.set(Calendar.MONTH, month - 1); //获取某月最大天数 int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH); //设置日历中月份的最大天数 cal.set(Calendar.DAY_OF_MONTH, lastDay); //格式化日期 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String lastDayOfMonth = sdf.format(cal.getTime()); String lastDayOfMonthTime = lastDayOfMonth+" 23:59:59"; return lastDayOfMonthTime; } /** * 获取本周的第一天 * @return String * **/ public static String getWeekStart(){ Calendar cal=Calendar.getInstance(); cal.add(Calendar.WEEK_OF_MONTH, 0); cal.set(Calendar.DAY_OF_WEEK, 2); Date time=cal.getTime(); return new SimpleDateFormat("yyyy-MM-dd").format(time)+" 00:00:00"; } /** * 获取本周的最后一天 * @return String * **/ public static String getWeekEnd(){ Calendar cal=Calendar.getInstance(); cal.set(Calendar.DAY_OF_WEEK, cal.getActualMaximum(Calendar.DAY_OF_WEEK)); cal.add(Calendar.DAY_OF_WEEK, 1); Date time=cal.getTime(); return new SimpleDateFormat("yyyy-MM-dd").format(time)+" 23:59:59"; }}
package com.chinatower.product.monitoring.common;/** * 记录业务交易日志 * @author hp * */public class InterfaceLogUtil { public static String reqTransLog(String body) { return new StringBuffer("REQ").append("#\n").append(body).toString(); } public static String rspTransLog(String body) { return new StringBuffer("RSP").append("#\n").append(body).toString(); }}
package com.chinatower.product.monitoring.common;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import com.chinatower.product.monitoring.entity.KafkaDto;import com.chinatower.product.monitoring.mapper.KafkaMonitorMapper;import lombok.extern.slf4j.Slf4j;import org.apache.commons.lang3.StringUtils;import org.apache.http.HttpEntity;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;import org.springframework.transaction.annotation.Transactional;import java.io.IOException;import java.math.BigDecimal;import java.net.URLEncoder;import java.util.*;import static java.math.BigDecimal.ROUND_HALF_UP;@Component@Slf4jpublic class KafkaUtils { @Value("${prometheus.ip}") private String ip; @Value("${prometheus.port}") private String port; @Autowired private KafkaMonitorMapper kafkaMonitorMapper; /** * 查询prometheus中的topic 发送数据 * * @param query * @return */ @Transactional(rollbackFor = Exception.class) public void readPrometheusTopicNum(String query) { try { query = URLEncoder.encode(query, "UTF-8"); String url = "http://" + ip + ":" + port + "/api/v1/query?query=" + query; System.out.println(url); String result = getUrl(url); if (StringUtils.isEmpty(result)) { throw new RuntimeException("访问prometheus出现异常"); } List resultJson = JsonResolve(result); if (resultJson.size() > 0) { List<KafkaDto> insertParamList = new ArrayList<KafkaDto>(); KafkaDto param = null; for (Object o : resultJson) { param = new KafkaDto(); Map<String, Object> map = (Map<String, Object>) o; Map<String, String> metric = (Map<String, String>) map.get("metric"); String topic = kafkaMonitorMapper.getAllTopicInfo(); if (topic.contains(metric.get("topic"))) { List values = (List) map.get("value"); String topicNum = (new BigDecimal(values.get(1).toString()).setScale(0, ROUND_HALF_UP)).toString(); if (!"0".equals(topicNum)) { param.setTopicNum(topicNum); param.setTopicName(metric.get("topic")); param.setCreateDate(new Date()); insertParamList.add(param); } } } if (insertParamList.size() > 0) { // 批量插入 kafkaMonitorMapper.insertKafkaTopicInfoBatch(insertParamList); } } } catch (Exception e) { log.info("插入数据报错:"+e); e.printStackTrace(); } } /** * 查询prometheus topic组积压数量 * * @param query * @return */ @Transactional(rollbackFor = Exception.class) public void readPrometheusTopicGroupNum(String query) { try { query = URLEncoder.encode(query, "UTF-8"); String url = "http://" + ip + ":" + port + "/api/v1/query?query=" + query; System.out.println(url); String result = getUrl(url); if (StringUtils.isEmpty(result)) { throw new RuntimeException("访问prometheus出现异常"); } List resultJson = JsonResolve(result); if (resultJson.size() > 0) { List<KafkaDto> insertParamList = new ArrayList<KafkaDto>(); KafkaDto param = null; for (Object o : resultJson) { param = new KafkaDto(); Map<String, Object> map = (Map<String, Object>) o; Map<String, String> metric = (Map<String, String>) map.get("metric"); param.setTopicName(metric.get("topic")); param.setGroupTopicName(metric.get("consumergroup")); List values = (List) map.get("value"); param.setGroupTopicNum((new BigDecimal(values.get(1).toString()).setScale(0, ROUND_HALF_UP)).toString()); param.setCreateDate(new Date()); insertParamList.add(param); } if (insertParamList.size() > 0) { // 先清空数据 int deleteFlg = kafkaMonitorMapper.deleteGroupTopicInfo(); // 重新批量插入 if (deleteFlg >= 0) { kafkaMonitorMapper.insertKafkaGroupTopicInfoBatch(insertParamList); } } } } catch (Exception e) { log.info("编码转换出现异常"); e.printStackTrace(); } } /** * 访问地址 * * @param url * @return */ public String getUrl(String url) { try { log.info("url: " + url); HttpGet get = new HttpGet(url); CloseableHttpClient httpClient = HttpClients.custom().build(); CloseableHttpResponse response = httpClient.execute(get); HttpEntity entity = response.getEntity(); String s = EntityUtils.toString(entity, "utf-8"); return s; } catch (IOException e) { e.printStackTrace(); log.info("访问prometheus出错"); return null; } } /** * 解析从prometheus中返回的数据 * * @param result * @return */ public List JsonResolve(String result) { JSONObject jsonObject = JSON.parseObject(result); String status = jsonObject.get("status").toString(); if ("error".equals(status)) { log.info("result: " + result); throw new RuntimeException("访问prometheus出现错误"); } JSONObject data = jsonObject.getJSONObject("data"); List resultJson = (List) data.get("result"); return resultJson; }}
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */package com.chinatower.product.monitoring.common;/** * @author peng-yongsheng */public enum MatchCNameBuilder { INSTANCE; public String build(String termCName) { return termCName + Const.ID_SPLIT + "match"; }}
package com.chinatower.product.monitoring.common;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import com.chinatower.product.monitoring.entity.RabbitMQLog;import com.chinatower.product.monitoring.entity.RabbitmqLogEs;import com.chinatower.product.monitoring.response.ResultPage;import lombok.extern.slf4j.Slf4j;import org.apache.commons.lang3.StringUtils;import org.apache.http.HttpEntity;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;import org.elasticsearch.index.query.Operator;import org.elasticsearch.index.query.QueryBuilder;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.data.domain.PageRequest;import org.springframework.data.domain.Sort;import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;import org.springframework.data.elasticsearch.core.query.FetchSourceFilter;import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;import org.springframework.stereotype.Component;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.net.URLEncoder;import java.util.*;import static org.elasticsearch.index.query.QueryBuilders.*;@Component@Slf4jpublic class RabbitMQUtils { @Autowired private ElasticsearchTemplate elasticsearchTemplate; @Value("${prometheus.ip}") private String ip; @Value("${prometheus.port}") private String port; /** * 根据所给参数查询es中的数据 * * @param start * @param end * @param page * @param size * @param queueName * @return */ public ResultPage<RabbitMQLog> readEs(String start, String end, Integer page, Integer size, String queueName) { QueryBuilder queryBuilder = null; queryBuilder = boolQuery() .must(matchQuery("type", "rabbit").operator(Operator.AND)) //传入时间,目标格式2020-01-02T03:17:37.638Z .must(rangeQuery("@timestamp").from(start).to(end)) //匹配队列 .must(matchQuery("message", queueName).operator(Operator.AND)); ResultPage resultPage = readEsUtils(queryBuilder, page, size); return resultPage; } /** * 根据所给参数查询es中的数据 * * @param start * @param end * @param page * @param size * @return */ public ResultPage<RabbitMQLog> readEsByTime(String start, String end, Integer page, Integer size) { QueryBuilder queryBuilder = null; queryBuilder = boolQuery() .must(matchQuery("type", "rabbit").operator(Operator.AND)) .must(rangeQuery("@timestamp").from(start).to(end)); ResultPage resultPage = readEsUtils(queryBuilder, page, size); return resultPage; } /** * 根据queryBuilder查询es中的数据 * * @param queryBuilderFind * @param page * @param size * @return */ public ResultPage readEsUtils(QueryBuilder queryBuilderFind, int page, int size) { Base64.Decoder decoder = Base64.getDecoder(); ArrayList<RabbitMQLog> list = new ArrayList<>(); //String time1 = "2020-04-30T00:00:00.000Z"; // 2020-04-30T01:00:30:00.000Z //String time2 = "2020-04-30T05:00:00.000Z"; // 原生查询构建器 NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder(); // 1.1 source过滤 queryBuilder.withSourceFilter(new FetchSourceFilter(new String[]{"total", "message", "@timestamp"}, null)); queryBuilder.withQuery(queryBuilderFind); // 1.3分页及排序条件 queryBuilder.withPageable( PageRequest.of((page - 1), size, Sort.by(Sort.Direction.ASC, "@timestamp"))); // 构建查询条件,并且查询 AggregatedPage<RabbitmqLogEs> result = (AggregatedPage<RabbitmqLogEs>) elasticsearchTemplate.queryForPage(queryBuilder.build(),RabbitmqLogEs.class); //总条数 long totalElements = result.getTotalElements(); //总页数 int totalPages = result.getTotalPages(); log.info("totalElements: " + totalElements); log.info("totalPages: " + totalPages); List<RabbitmqLogEs> content = result.getContent(); // System.out.println(content); //处理数据 io: for (RabbitmqLogEs s : content) { System.out.println(s.getMessage()); RabbitMQLog rabbitMQLog = null; try { rabbitMQLog = JSON.parseObject(s.getMessage(), RabbitMQLog.class); String timestamp = rabbitMQLog.getTimestamp(); log.info("timestamp: " + timestamp); String CSTTime = DateUtils.UTCToCST(timestamp, "yyyy-MM-dd HH:mm:ss:SSS"); log.info("北京时间: " + CSTTime); rabbitMQLog.setTimestamp(CSTTime); String payload = rabbitMQLog.getPayload(); byte[] decode = decoder.decode(payload); String message = null; try { message = new String(decode, "utf-8"); } catch (UnsupportedEncodingException e) { log.error("编码转换错误"); e.printStackTrace(); return null; } log.info("message: " + message); rabbitMQLog.setPayload(message); }catch (Exception e){ log.error("解析es返回数据异常"); continue io; } list.add(rabbitMQLog); System.out.println(s.getTimestamp()); }; System.out.println(content.size()); return new ResultPage(totalPages, totalElements, size, page, list); } /** * 根据所给时间查prometheus中的数据 * * @param query * @param time * @return */ public String readPrometheus(String query, String time) { String url = "http://" + ip + ":" + port + "/api/v1/query?query=" + query + "&time=" + time; String result = getUrl(url); if (StringUtils.isEmpty(result)) { throw new RuntimeException("访问prometheus出现异常"); } return result; } /** * 根据时间查询node信息 * @param query * @param timeUTC * @return */ public Map<String, Long> readPrometheusByNode(String query, String timeUTC) { Map<String, Long> resultMap = new TreeMap<>(); String url = "http://" + ip + ":" + port + "/api/v1/query?query=" + query + "&time=" + timeUTC; String result = getUrl(url); if (StringUtils.isEmpty(result)) { throw new RuntimeException("访问prometheus出现异常"); } List resultJson = JsonResolve(result); for (Object o : resultJson) { Map<String, Object> map = (Map<String, Object>) o; Map<String, String> metric = (Map<String, String>) map.get("metric"); String node = metric.get("node"); List values = (List) map.get("value"); for (int i = 0; i < values.size(); i++) { if (i == 0) { Long o1 = Long.parseLong(values.get(i).toString()); String s = DateUtils.longDate2String(o1 * 1000, "yyyy-MM-dd.HH"); values.set(i, s); } } resultMap.put(node, Long.parseLong(values.get(1).toString())); } return resultMap; } /** * 查询某一段时间的peometheus信息 * @param queues * @param query * @param start * @param end * @param step * @return */ public Map<String, Map<String, Long>> readPrometheusByTime(List<String> queues, String query, String start, String end, String step) { String result = null; Map<String, Map<String, Long>> queueResultMap = new HashMap<>(); //Map<String, List<Integer>> queueResultMap = new HashMap<>(); try { query = URLEncoder.encode(query, "UTF-8"); String url = "http://" + ip + ":" + port + "/api/v1/query_range?query=" + query + "&start=" + start + "&end=" + end + "&step=" + step; //String url = "http://" + "114.116.254.193:50602" + "/api/datasources/proxy/6/api/v1/query_range?query=" + query + "&start=" + start + "&end=" + end + "&step=" + step; result = getUrl(url); if (StringUtils.isEmpty(result)) { throw new RuntimeException("访问prometheus出现异常"); } } catch (UnsupportedEncodingException e) { log.info("编码转换出现异常"); e.printStackTrace(); return null; } List resultJson = JsonResolve(result); queues.forEach(queueName -> { for (Object o : resultJson) { Map<String, Object> map = (Map<String, Object>) o; Map<String, String> metric = (Map<String, String>) map.get("metric"); String queue = metric.get("queue"); if (queueName.equals(queue)) { Map<String, Long> resultMap = new TreeMap<>(); //List<Integer> resultList = new ArrayList<>(); List values = (List) map.get("values"); for (Object value : values) { List<Object> resultValue = (List<Object>) value; for (int i = 0; i < resultValue.size(); i++) { if (i == 0) { Long o1 = Long.parseLong(resultValue.get(i).toString()); String s = DateUtils.longDate2String(o1 * 1000, "yyyy-MM-dd HH:mm:ss"); resultValue.set(i, s); } } //resultList.add(Integer.parseInt(resultValue.get(1).toString())); resultMap.put(resultValue.get(0).toString(), Long.parseLong(resultValue.get(1).toString())); } queueResultMap.put(queueName, resultMap); //queueResultMap.put(queueName, resultList); } } }); log.info("queueResultMap: " + queueResultMap); return queueResultMap; } /** * 一年内发的消息列表 * @param queues * @param query * @param timeQuery * @return */ public Map<String, Map<String, Long>> readPrometheusByYear(List<String> queues, String query, String timeQuery) { Map<String, Map<String, Long>> queueResultMap = new HashMap<>(); String url = "http://" + ip + ":" + port + "/api/v1/query?query=" + query + "&time=" + timeQuery; //String url = "http://" + "114.116.254.193:50602" + "/api/datasources/proxy/6/api/v1/query?query=" + query + "&time=" + timeQuery; String result = getUrl(url); if (StringUtils.isEmpty(result)) { throw new RuntimeException("访问prometheus出现异常"); } List resultJson = JsonResolve(result); queues.forEach(queueName -> { for (Object o : resultJson) { Map<String, Object> map = (Map<String, Object>) o; Map<String, String> metric = (Map<String, String>) map.get("metric"); String queue = metric.get("queue"); if (queueName.equals(queue)) { TreeMap<String, Long> resultMap = new TreeMap<>(); //List<Integer> resultList = new ArrayList<>(); List values = (List) map.get("value"); for (int i = 0; i < values.size(); i++) { if (i == 0) { Long o1 = Long.parseLong(values.get(i).toString()); String s = DateUtils.longDate2String(o1 * 1000, "yyyy-MM-dd HH:mm:ss"); values.set(i, s); } resultMap.put(values.get(0).toString(), Long.parseLong(values.get(1).toString())); } queueResultMap.put(queueName, resultMap); //queueResultMap.put(queueName, resultList); } } }); return queueResultMap; } /** * 解析监控返回结果 * @param queues * @param resultList * @param resultMap */ public void analysisResult(List<String> queues, List<Map<String, Map<String, Long>>> resultList, Map<String, Map<String, Long>> resultMap) { for (String string : queues) { TreeMap<String, Long> results = new TreeMap<>(); for (Map<String, Map<String, Long>> map : resultList) { for (String s : map.keySet()) { if (string.equals(s)) { Map<String, Long> map1 = map.get(s); for (String s1 : map1.keySet()) { results.put(s1, map.get(s).get(s1)); } } resultMap.put(string, results); } } } System.out.println(JSONObject.toJSONString(resultMap)); } /** * 解析监控返回结果 * @param queues * @param resultList * @param resultMap */ public void analysisResultPost(List<Map<String, String>> queues, List<Map<String, Map<String, Long>>> resultList, Map<String, Map<String, Long>> resultMap) { for (Map<String, String> string : queues) { TreeMap<String, Long> results = new TreeMap<>(); for (Map<String, Map<String, Long>> map : resultList) { for (String s : map.keySet()) { if (string.get("queueDesc").equals(s)) { Map<String, Long> map1 = map.get(s); for (String s1 : map1.keySet()) { results.put(s1, map.get(s).get(s1)); } } resultMap.put(string.get("queueDesc"), results); } } } } /** * 访问地址 * * @param url * @return */ public String getUrl(String url) { try { log.info("url: " + url); HttpGet get = new HttpGet(url); CloseableHttpClient httpClient = HttpClients.custom().build(); CloseableHttpResponse response = httpClient.execute(get); HttpEntity entity = response.getEntity(); String s = EntityUtils.toString(entity, "utf-8"); return s; } catch (IOException e) { e.printStackTrace(); log.info("访问prometheus出错"); return null; } } /** * 解析从prometheus中返回的数据 * * @param result * @return */ public List JsonResolve(String result) { JSONObject jsonObject = JSON.parseObject(result); String status = jsonObject.get("status").toString(); if ("error".equals(status)) { log.info("result: " + result); throw new RuntimeException("访问prometheus出现错误"); } JSONObject data = jsonObject.getJSONObject("data"); List resultJson = (List) data.get("result"); return resultJson; } /** * 查询某一段时间的peometheus信息 -- 为了不影响接口使用复制方法修改返回值 * @param queues * @param query * @param start * @param end * @param step * @return */ public Map<String, Map<String, Long>> readPrometheusByTimeOfRabbitMonitoring(List<Map<String, String>> queues, String query, String start, String end, String step) { String result = null; Map<String, Map<String, Long>> queueResultMap = new HashMap<>(); //Map<String, List<Integer>> queueResultMap = new HashMap<>(); try { query = URLEncoder.encode(query, "UTF-8"); String url = "http://" + ip + ":" + port + "/api/v1/query_range?query=" + query + "&start=" + start + "&end=" + end + "&step=" + step; //String url = "http://" + "114.116.254.193:50602" + "/api/datasources/proxy/6/api/v1/query_range?query=" + query + "&start=" + start + "&end=" + end + "&step=" + step; result = getUrl(url); if (StringUtils.isEmpty(result)) { throw new RuntimeException("访问prometheus出现异常"); } log.info("Prometheus返回值:{}",result); } catch (UnsupportedEncodingException e) { log.info("编码转换出现异常"); e.printStackTrace(); return null; } List resultJson = JsonResolve(result); System.out.println(JSONObject.toJSONString(resultJson)); queues.forEach(queueMap -> { String queueName = ""; for (Object o : resultJson) { Map<String, Object> map = (Map<String, Object>) o; Map<String, String> metric = (Map<String, String>) map.get("metric"); String queue = metric.get("queue"); if (queueMap.get("queueName").equals(queue)) { String vhost = metric.get("vhost"); queueName = queueMap.get("vhostDesc") + "->" + queueMap.get("queueDesc"); Map<String, Long> resultMap = new TreeMap<>(); //List<Integer> resultList = new ArrayList<>(); List values = (List) map.get("values"); for (Object value : values) { List<Object> resultValue = (List<Object>) value; for (int i = 0; i < resultValue.size(); i++) { if (i == 0) { Long o1 = Long.parseLong(resultValue.get(i).toString()); String s = DateUtils.longDate2String(o1 * 1000, "yyyy-MM-dd HH:mm:ss"); resultValue.set(i, s); } } //resultList.add(Integer.parseInt(resultValue.get(1).toString())); resultMap.put(resultValue.get(0).toString(), Long.parseLong(resultValue.get(1).toString())); } queueResultMap.put(queueName, resultMap); //queueResultMap.put(queueName, resultList); } } }); log.info("queueResultMap: " + queueResultMap); return queueResultMap; } /** * 一年内发的消息列表 -- 为了不影响接口使用复制方法修改返回值 * @param queues * @param query * @param timeQuery * @return */ public Map<String, Map<String, Long>> readPrometheusByYearPost(List<Map<String, String>> queues, String query, String timeQuery) throws UnsupportedEncodingException { Map<String, Map<String, Long>> queueResultMap = new HashMap<>(); query = URLEncoder.encode(query, "UTF-8"); String url = "http://" + ip + ":" + port + "/api/v1/query?query=" + query + "&time=" + timeQuery; //String url = "http://" + "114.116.254.193:50602" + "/api/datasources/proxy/6/api/v1/query?query=" + query + "&time=" + timeQuery; String result = getUrl(url); System.out.println("返回值:"+result); if (StringUtils.isEmpty(result)) { throw new RuntimeException("访问prometheus出现异常"); } List resultJson = JsonResolve(result); queues.forEach(queueMap -> { String queueName = ""; for (Object o : resultJson) { Map<String, Object> map = (Map<String, Object>) o; Map<String, String> metric = (Map<String, String>) map.get("metric"); String queue = metric.get("queue"); if (queueMap.get("queueName").equals(queue)) { queueName = queueMap.get("vhostDesc") + "->" + queueMap.get("queueDesc"); TreeMap<String, Long> resultMap = new TreeMap<>(); //List<Integer> resultList = new ArrayList<>(); List values = (List) map.get("value"); for (int i = 0; i < values.size(); i++) { if (i == 0) { Long o1 = Long.parseLong(values.get(i).toString()); String s = DateUtils.longDate2String(o1 * 1000, "yyyy-MM-dd HH:mm:ss"); values.set(i, s); } resultMap.put(values.get(0).toString(), Long.parseLong(values.get(1).toString())); } queueResultMap.put(queueName, resultMap); //queueResultMap.put(queueName, resultList); } } }); return queueResultMap; }}
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */package com.chinatower.product.monitoring.common;import lombok.*;/** * @author peng-yongsheng */public abstract class Record implements StorageData { public static final String TIME_BUCKET = "time_bucket"; @Getter @Setter private long timeBucket;}
package com.chinatower.product.monitoring.common;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import com.chinatower.product.monitoring.entity.RabbitMQLog;import com.chinatower.product.monitoring.entity.RabbitmqLogEs;import com.chinatower.product.monitoring.entity.RedisLog;import com.chinatower.product.monitoring.entity.RedisLogEs;import com.chinatower.product.monitoring.response.ResultPage;import lombok.extern.slf4j.Slf4j;import org.apache.commons.lang3.StringUtils;import org.apache.http.HttpEntity;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;import org.elasticsearch.index.query.Operator;import org.elasticsearch.index.query.QueryBuilder;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.data.domain.PageRequest;import org.springframework.data.domain.Sort;import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;import org.springframework.data.elasticsearch.core.query.FetchSourceFilter;import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;import org.springframework.stereotype.Component;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.net.URLEncoder;import java.util.*;import static org.elasticsearch.index.query.QueryBuilders.*;@Component@Slf4jpublic class RedisUtils { @Autowired private ElasticsearchTemplate elasticsearchTemplate; /** * 根据所给参数查询es中的数据 * * @param start * @param end * @param page * @param size * @param queueName * @return */ public ResultPage<RedisLog> readEs(String start, String end, Integer page, Integer size, String queueName) { QueryBuilder queryBuilder = null; queryBuilder = boolQuery() .must(matchQuery("type", "rabbit").operator(Operator.AND)) //传入时间,目标格式2020-01-02T03:17:37.638Z .must(rangeQuery("@timestamp").from(start).to(end)) //匹配队列 .must(matchQuery("message", queueName).operator(Operator.AND)); ResultPage resultPage = readEsUtils(queryBuilder, page, size); return resultPage; } /** * 根据所给参数查询es中的数据 * * @param start * @param end * @param page * @param size * @return */ public ResultPage<RedisLog> readEsByTime(String start, String end, Integer page, Integer size) { QueryBuilder queryBuilder = null; queryBuilder = boolQuery() .must(matchQuery("type", "log_redis_server").operator(Operator.AND)) .must(rangeQuery("@timestamp").from(start).to(end)); ResultPage resultPage = readEsUtils(queryBuilder, page, size); return resultPage; } /** * 根据queryBuilder查询es中的数据 * * @param queryBuilderFind * @param page * @param size * @return */ public ResultPage readEsUtils(QueryBuilder queryBuilderFind, int page, int size) { Base64.Decoder decoder = Base64.getDecoder(); ArrayList<RedisLog> list = new ArrayList<>(); //String time1 = "2020-04-30T00:00:00.000Z"; // 2020-04-30T01:00:30:00.000Z //String time2 = "2020-04-30T05:00:00.000Z"; // 原生查询构建器 NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder(); // 1.1 source过滤 queryBuilder.withSourceFilter(new FetchSourceFilter(new String[]{"total", "message", "@timestamp"}, null)); queryBuilder.withQuery(queryBuilderFind); // 1.3分页及排序条件 queryBuilder.withPageable( PageRequest.of((page - 1), size, Sort.by(Sort.Direction.ASC, "@timestamp"))); // 构建查询条件,并且查询 AggregatedPage<RedisLogEs> result = (AggregatedPage<RedisLogEs>) elasticsearchTemplate.queryForPage(queryBuilder.build(), RedisLogEs.class); //总条数 long totalElements = result.getTotalElements(); //总页数 int totalPages = result.getTotalPages(); log.info("totalElements: " + totalElements); log.info("totalPages: " + totalPages); List<RedisLogEs> content = result.getContent(); // System.out.println(content); //处理数据 io: for (RedisLogEs s : content) { System.out.println(s.getMessage()); RedisLog redisLog = null; try { redisLog = JSON.parseObject(s.getMessage(), RedisLog.class); String timestamp = redisLog.getTimestamp(); log.info("timestamp: " + timestamp); String CSTTime = DateUtils.UTCToCST(timestamp, "yyyy-MM-dd HH:mm:ss:SSS"); log.info("北京时间: " + CSTTime); redisLog.setTimestamp(CSTTime); String payload = redisLog.getPayload(); byte[] decode = decoder.decode(payload); String message = null; try { message = new String(decode, "utf-8"); } catch (UnsupportedEncodingException e) { log.error("编码转换错误"); e.printStackTrace(); return null; } log.info("message: " + message); redisLog.setPayload(message); }catch (Exception e){ log.error("解析es返回数据异常"); continue io; } list.add(redisLog); System.out.println(s.getTimestamp()); }; System.out.println(content.size()); return new ResultPage(totalPages, totalElements, size, page, list); }}
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */package com.chinatower.product.monitoring.common;import com.chinatower.product.monitoring.common.trace.Column;import lombok.*;import org.springframework.data.elasticsearch.annotations.Document;import java.io.Serializable;/** * @author peng-yongsheng */@Data@NoArgsConstructor@AllArgsConstructor@Document(indexName = "segment-20200729", type = "type")public class SegmentRecord implements Serializable { public static final String TIME_BUCKET = "time_bucket"; public static final String INDEX_NAME = "segment"; public static final String SEGMENT_ID = "segment_id"; public static final String TRACE_ID = "trace_id"; public static final String SERVICE_ID = "service_id"; public static final String SERVICE_INSTANCE_ID = "service_instance_id"; public static final String ENDPOINT_NAME = "endpoint_name"; public static final String ENDPOINT_ID = "endpoint_id"; public static final String START_TIME = "start_time"; public static final String END_TIME = "end_time"; public static final String LATENCY = "latency"; public static final String IS_ERROR = "is_error"; public static final String DATA_BINARY = "data_binary"; public static final String VERSION = "version"; @Column(columnName = SEGMENT_ID) private String segmentId; @Column(columnName = TRACE_ID) private String traceId; @Column(columnName = SERVICE_ID) private int serviceId; @Column(columnName = SERVICE_INSTANCE_ID) private int serviceInstanceId; @Column(columnName = ENDPOINT_NAME, matchQuery = true) private String endpointName; @Column(columnName = ENDPOINT_ID) private int endpointId; @Column(columnName = START_TIME) private long startTime; @Column(columnName = END_TIME) private long endTime; @Column(columnName = LATENCY) private int latency; @Column(columnName = IS_ERROR) private int isError; @Column(columnName = DATA_BINARY) private byte[] dataBinary; @Column(columnName = VERSION) private int version;// private int serviceId;// private int serviceInstanceId;// private String endpointName;// private int endpointId;// private long startTime;// private long endTime;// private byte[] dataBinary;// public String id() {// return segmentId;// }}
package com.chinatower.product.monitoring.common;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import com.chinatower.product.monitoring.common.trace.*;import com.chinatower.product.monitoring.entity.RabbitMQLog;import com.chinatower.product.monitoring.response.ResultPage;import com.google.common.base.Strings;import lombok.extern.slf4j.Slf4j;import org.apache.commons.lang3.StringUtils;import org.apache.http.HttpEntity;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;import org.elasticsearch.action.ActionFuture;import org.elasticsearch.action.search.SearchRequest;import org.elasticsearch.action.search.SearchResponse;import org.elasticsearch.index.query.*;import org.elasticsearch.search.SearchHit;import org.elasticsearch.search.aggregations.Aggregation;import org.elasticsearch.search.aggregations.AggregationBuilder;import org.elasticsearch.search.aggregations.AggregationBuilders;import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;import org.elasticsearch.search.aggregations.metrics.avg.AvgAggregationBuilder;import org.elasticsearch.search.aggregations.metrics.max.MaxAggregationBuilder;import org.elasticsearch.search.aggregations.metrics.stats.StatsAggregationBuilder;import org.elasticsearch.search.builder.SearchSourceBuilder;import org.elasticsearch.search.sort.SortOrder;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;import org.springframework.stereotype.Component;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.net.URLEncoder;import java.rmi.UnexpectedException;import java.text.SimpleDateFormat;import java.util.*;import static java.util.Objects.nonNull;import static org.elasticsearch.index.query.QueryBuilders.*;@Component@Slf4jpublic class StatsUtils { @Autowired private ElasticsearchTemplate elasticsearchTemplate; @Value("${prometheus.ip}") private String ip; @Value("${prometheus.port}") private String port; public static final String TYPE = "type"; private String namespace=null; /** * 根据所给参数查询es中的数据 * * @return */ public ResultPage<SegmentRecord> readEs(Integer page, Integer size) { QueryBuilder queryBuilder = null; String a = null; Calendar instance = Calendar.getInstance(); instance.set(Calendar.HOUR_OF_DAY,-24);// queryBuilder = boolQuery()// .must(QueryBuilders.rangeQuery("start_time").from(instance.getTimeInMillis()).to(Calendar.getInstance().getTimeInMillis())); //传入时间,目标格式2020-01-02T03:17:37.638Z// .must(rangeQuery("@timestamp").from(start).to(end)) //匹配队列// .must(matchQuery("message", queueName).operator(Operator.AND)); ResultPage resultPage = null;// try {// resultPage = readEsUtils(condition, page, size);// resultPage = readEsUtils(condition,queryBuilder, page, size);// } catch (IOException e) {// e.printStackTrace();// } return resultPage; } /** * 根据所给参数查询es中的数据 * * @param start * @param end * @param page * @param size * @return */ public ResultPage<RabbitMQLog> readEsByTime(String start, String end, Integer page, Integer size) { QueryBuilder queryBuilder = null; queryBuilder = boolQuery() .must(matchQuery("type", "rabbit").operator(Operator.AND)) .must(rangeQuery("@timestamp").from(start).to(end)); TraceQueryCondition condition=new TraceQueryCondition(); ResultPage resultPage = null; try { resultPage = readEsUtils(condition,queryBuilder, page, size); } catch (IOException e) { e.printStackTrace(); } return resultPage; } public Map readTraceStatEsUtils(TraceQueryCondition condition) throws UnexpectedException { long startSecondTB = 0; long endSecondTB = 0; String traceId = Const.EMPTY_STRING; /* 开始时间和结束时间 */ if (!Strings.isNullOrEmpty(condition.getTraceId())) { traceId = condition.getTraceId(); } else if (nonNull(condition.getQueryDuration())) { startSecondTB = DurationUtils.INSTANCE.startTimeDurationToSecondTimeBucket(condition.getQueryDuration().getStep(), condition.getQueryDuration().getStart()); endSecondTB = DurationUtils.INSTANCE.endTimeDurationToSecondTimeBucket(condition.getQueryDuration().getStep(), condition.getQueryDuration().getEnd()); } else { throw new UnexpectedException("The condition must contains either queryDuration or traceId."); } long minDuration = condition.getMinTraceDuration(); long maxDuration = condition.getMaxTraceDuration(); String endpointName = condition.getEndpointName(); int serviceId = StringUtils.isEmpty(condition.getServiceId()) ? 0 : Integer.parseInt(condition.getServiceId()); int endpointId = StringUtils.isEmpty(condition.getEndpointId()) ? 0 : Integer.parseInt(condition.getEndpointId()); int serviceInstanceId = StringUtils.isEmpty(condition.getServiceInstanceId()) ? 0 : Integer.parseInt(condition.getServiceInstanceId()); TraceState traceState = condition.getTraceState(); QueryOrder queryOrder = condition.getQueryOrder(); Pagination pagination = condition.getPaging(); Map<String, Object> map = null; try {// map = queryBasicTraces(serviceId,// serviceInstanceId,// endpointId,// traceId, endpointName,// minDuration,// maxDuration,// traceState,// queryOrder,// pagination,// startSecondTB,// endSecondTB); map = queryBasicTraces(serviceId,serviceInstanceId,endpointId,traceId,endpointName,minDuration,maxDuration,traceState,queryOrder,pagination,startSecondTB,endSecondTB); } catch (IOException e) { e.printStackTrace(); } return map; } public Map readTraceStatEsUtils1(TraceQueryCondition condition) throws UnexpectedException { long startSecondTB = 0; long endSecondTB = 0; String traceId = Const.EMPTY_STRING; /* 开始时间和结束时间 */ if (!Strings.isNullOrEmpty(condition.getTraceId())) { traceId = condition.getTraceId(); } else if (nonNull(condition.getQueryDuration())) { startSecondTB = DurationUtils.INSTANCE.startTimeDurationToSecondTimeBucket(condition.getQueryDuration().getStep(), condition.getQueryDuration().getStart()); endSecondTB = DurationUtils.INSTANCE.endTimeDurationToSecondTimeBucket(condition.getQueryDuration().getStep(), condition.getQueryDuration().getEnd()); } else { throw new UnexpectedException("The condition must contains either queryDuration or traceId."); } long minDuration = condition.getMinTraceDuration(); long maxDuration = condition.getMaxTraceDuration(); String endpointName = condition.getEndpointName(); int serviceId = StringUtils.isEmpty(condition.getServiceId()) ? 0 : Integer.parseInt(condition.getServiceId()); int endpointId = StringUtils.isEmpty(condition.getEndpointId()) ? 0 : Integer.parseInt(condition.getEndpointId()); int serviceInstanceId = StringUtils.isEmpty(condition.getServiceInstanceId()) ? 0 : Integer.parseInt(condition.getServiceInstanceId()); TraceState traceState = condition.getTraceState(); QueryOrder queryOrder = condition.getQueryOrder(); Pagination pagination = condition.getPaging(); Map<String, Object> map = null; try { map = queryBasicTraces1(serviceId, serviceInstanceId, endpointId, traceId, endpointName, minDuration, maxDuration, traceState, queryOrder, pagination, startSecondTB, endSecondTB); } catch (IOException e) { e.printStackTrace(); } return map; } /** * 根据queryBuilder查询es中的数据 * * @param queryBuilderFind * @param page * @param size * @return */ public ResultPage readEsUtils(TraceQueryCondition condition, QueryBuilder queryBuilderFind, int page, int size) throws IOException { long startSecondTB = 0; long endSecondTB = 0; String traceId = Const.EMPTY_STRING; if (!Strings.isNullOrEmpty(condition.getTraceId())) { traceId = condition.getTraceId(); } else if (nonNull(condition.getQueryDuration())) { startSecondTB = DurationUtils.INSTANCE.startTimeDurationToSecondTimeBucket(condition.getQueryDuration().getStep(), condition.getQueryDuration().getStart()); endSecondTB = DurationUtils.INSTANCE.endTimeDurationToSecondTimeBucket(condition.getQueryDuration().getStep(), condition.getQueryDuration().getEnd()); } else { throw new UnexpectedException("The condition must contains either queryDuration or traceId."); } long minDuration = condition.getMinTraceDuration(); long maxDuration = condition.getMaxTraceDuration(); String endpointName = condition.getEndpointName(); int serviceId = StringUtils.isEmpty(condition.getServiceId()) ? 0 : Integer.parseInt(condition.getServiceId()); int endpointId = StringUtils.isEmpty(condition.getEndpointId()) ? 0 : Integer.parseInt(condition.getEndpointId()); int serviceInstanceId = StringUtils.isEmpty(condition.getServiceInstanceId()) ? 0 : Integer.parseInt(condition.getServiceInstanceId()); TraceState traceState = condition.getTraceState(); QueryOrder queryOrder = condition.getQueryOrder(); Pagination pagination = condition.getPaging();// TraceBrief traceBrief = queryBasicTraces(serviceId, serviceInstanceId, endpointId, traceId, endpointName, minDuration, maxDuration, traceState, queryOrder, pagination, startSecondTB, endSecondTB);// Base64.Decoder decoder = Base64.getDecoder();// ArrayList<RabbitMQLog> list = new ArrayList<>();// //String time1 = "2020-04-30T00:00:00.000Z";// // 2020-04-30T01:00:30:00.000Z//// //String time2 = "2020-04-30T05:00:00.000Z";// // 原生查询构建器// NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();// // 1.1 source过滤//// queryBuilder.withSourceFilter(new FetchSourceFilter(new String[]{"total", "message", "@timestamp"}, null));// queryBuilder.withQuery(queryBuilderFind);// // 1.3分页及排序条件//// queryBuilder.withPageable(//// PageRequest.of((page - 1), size, Sort.by(Sort.Direction.ASC, "@timestamp")));// System.out.println("1、"+queryBuilder.build());// System.out.println("2、"+queryBuilder.build().getQuery());// // 构建查询条件,并且查询// AggregatedPage<SegmentRecord> result = (AggregatedPage<SegmentRecord>) elasticsearchTemplate.queryForPage(queryBuilder.build(),SegmentRecord.class);// //总条数// long totalElements = result.getTotalElements();// //总页数// int totalPages = result.getTotalPages();// log.info("totalElements: " + totalElements);// log.info("totalPages: " + totalPages);//// List<SegmentRecord> content = result.getContent();// // System.out.println(content);// //处理数据// io: for (SegmentRecord s : content) {// byte[] encode = Base64.getEncoder().encode(s.getDataBinary());// String a=new String(encode);// System.out.println(a);//// RabbitMQLog rabbitMQLog = null;//// try {//// rabbitMQLog = JSON.parseObject(s.getMessage(), RabbitMQLog.class);//// String timestamp = rabbitMQLog.getTimestamp();//// log.info("timestamp: " + timestamp);//// String CSTTime = DateUtils.UTCToCST(timestamp, "yyyy-MM-dd HH:mm:ss:SSS");//// log.info("北京时间: " + CSTTime);//// rabbitMQLog.setTimestamp(CSTTime);//// String payload = rabbitMQLog.getPayload();//// byte[] decode = decoder.decode(payload);//// String message = null;//// try {//// message = new String(decode, "utf-8");//// } catch (UnsupportedEncodingException e) {//// log.error("编码转换错误");//// e.printStackTrace();//// return null;//// }//// log.info("message: " + message);//// rabbitMQLog.setPayload(message);//////// }catch (Exception e){//// log.error("解析es返回数据异常");//// continue io;//// }//////// list.add(rabbitMQLog);//// System.out.println(s.getTimestamp());//// };// System.out.println(content.size());// return new ResultPage(totalPages, totalElements, size, page, list); return null; } public Map<String, Object> queryBasicTraces(final int serviceId, final int serviceInstanceId, final int endpointId, final String traceId, final String endpointName, final long minTraceDuration, long maxTraceDuration, final TraceState traceState, final QueryOrder queryOrder, final Pagination paging, final long startTB, final long endTB) throws IOException { PaginationUtils.Page page = PaginationUtils.INSTANCE.exchange(paging); return queryBasicTraces(startTB, endTB, minTraceDuration, maxTraceDuration, endpointName, serviceId, serviceInstanceId, endpointId, traceId, page.getLimit(), page.getFrom(), traceState, queryOrder); } public Map<String, Object> queryBasicTraces1(final int serviceId, final int serviceInstanceId, final int endpointId, final String traceId, final String endpointName, final long minTraceDuration, long maxTraceDuration, final TraceState traceState, final QueryOrder queryOrder, final Pagination paging, final long startTB, final long endTB) throws IOException { PaginationUtils.Page page = PaginationUtils.INSTANCE.exchange(paging); return queryBasicTraces1(startTB, endTB, minTraceDuration, maxTraceDuration, endpointName, serviceId, serviceInstanceId, endpointId, traceId, page.getLimit(), page.getFrom(), traceState, queryOrder); } public Map<String, Object> queryBasicTraces1(long startSecondTB, long endSecondTB, long minDuration, long maxDuration, String endpointName, int serviceId, int serviceInstanceId, int endpointId, String traceId, int limit, int from, TraceState traceState, QueryOrder queryOrder) throws IOException { SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource();////由于是聚合,这里使用的是AggregationBuilder。maxSecond是自己定义的给查询出来的最大值起的名字,// second是elasticsearch中的index里面我们放进去的数据里面的字段名,也就是要在该字段中聚合出最大值// AggregationBuilder builder = AggregationBuilders.max("maxSecond").field("second");// //prepareSearch()传入要查询的index// SearchResponse response = client.prepareSearch("wyh-apache-log").addAggregation(builder).get();// //从查询结果中获取刚才定义的最大值的名称// Max max = response.getAggregations().get("maxSecond");// AggregationBuilder builder = AggregationBuilders.max("max-"+SegmentRecord.LATENCY).field(SegmentRecord.LATENCY);// TermsAggregationBuilder teamAgg = AggregationBuilders.terms("team");// AvgAggregationBuilder ageAgg = AggregationBuilders.avg("avg_age").field(SegmentRecord.LATENCY);// MaxAggregationBuilder salaryAgg = AggregationBuilders.max("total_salary ").field(SegmentRecord.LATENCY);// StatsAggregationBuilder stats = AggregationBuilders.stats("stats-"+SegmentRecord.LATENCY).field(SegmentRecord.LATENCY);// sourceBuilder.addAggregation(teamAgg.subAggregation(ageAgg).subAggregation(salaryAgg));// sourceBuilder.aggregation(teamAgg.subAggregation(ageAgg).subAggregation(salaryAgg));// sourceBuilder.aggregation(stats); BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); sourceBuilder.query(boolQueryBuilder); List<QueryBuilder> mustQueryList = boolQueryBuilder.must(); if (startSecondTB != 0 && endSecondTB != 0) { mustQueryList.add(QueryBuilders.rangeQuery(SegmentRecord.TIME_BUCKET).gte(startSecondTB).lte(endSecondTB)); } if (minDuration != 0 || maxDuration != 0) { RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery(SegmentRecord.LATENCY); if (minDuration != 0) { rangeQueryBuilder.gte(minDuration); } if (maxDuration != 0) { rangeQueryBuilder.lte(maxDuration); } boolQueryBuilder.must().add(rangeQueryBuilder); } if (!Strings.isNullOrEmpty(endpointName)) { String matchCName = MatchCNameBuilder.INSTANCE.build(SegmentRecord.ENDPOINT_NAME); mustQueryList.add(QueryBuilders.matchPhraseQuery(matchCName, endpointName)); } if (serviceId != 0) { boolQueryBuilder.must().add(QueryBuilders.termQuery(SegmentRecord.SERVICE_ID, serviceId)); } if (serviceInstanceId != 0) { boolQueryBuilder.must().add(QueryBuilders.termQuery(SegmentRecord.SERVICE_INSTANCE_ID, serviceInstanceId)); } if (endpointId != 0) { boolQueryBuilder.must().add(QueryBuilders.termQuery(SegmentRecord.ENDPOINT_ID, endpointId)); } if (!Strings.isNullOrEmpty(traceId)) { boolQueryBuilder.must().add(QueryBuilders.termQuery(SegmentRecord.TRACE_ID, traceId)); } switch (traceState) { case ERROR: mustQueryList.add(QueryBuilders.matchQuery(SegmentRecord.IS_ERROR, BooleanUtils.TRUE)); break; case SUCCESS: mustQueryList.add(QueryBuilders.matchQuery(SegmentRecord.IS_ERROR, BooleanUtils.FALSE)); break; } switch (queryOrder) { case BY_START_TIME: sourceBuilder.sort(SegmentRecord.START_TIME, SortOrder.DESC); break; case BY_DURATION: sourceBuilder.sort(SegmentRecord.LATENCY, SortOrder.DESC); break; } sourceBuilder.size(limit); sourceBuilder.from(from); System.out.println(sourceBuilder); SearchResponse response1 = search(SegmentRecord.INDEX_NAME, sourceBuilder); mustQueryList.add(QueryBuilders.matchQuery(SegmentRecord.IS_ERROR, BooleanUtils.TRUE)); System.out.println(sourceBuilder); SearchResponse response2 = search(SegmentRecord.INDEX_NAME, sourceBuilder); mustQueryList.remove(QueryBuilders.matchQuery(SegmentRecord.IS_ERROR, BooleanUtils.TRUE)); mustQueryList.add(QueryBuilders.matchQuery(SegmentRecord.IS_ERROR, BooleanUtils.FALSE)); System.out.println(sourceBuilder); SearchResponse response3 = search(SegmentRecord.INDEX_NAME, sourceBuilder); HashMap<String, Object> map = new HashMap<>(); map.put("allTaltal",response1.getHits().totalHits); map.put("errTaltal",response2.getHits().totalHits); map.put("sucTaltal",response3.getHits().totalHits);// org.elasticsearch.search.aggregations.metrics.stats.Stats statsAgg// = response1.getAggregations().get("stats-" + SegmentRecord.LATENCY);// double avg = statsAgg.getAvg();// double max = statsAgg.getMax();// double min = statsAgg.getMin();// long count = statsAgg.getCount();// map.put("avgLatency",avg);// map.put("maxLatency",max);// map.put("minLatency",min);// map.put("countLatency",count);// map.put("endpointName",endpointName);// System.out.println(avg+" "+max+" "+min+" "+count);// TraceBrief traceBrief = new TraceBrief();// traceBrief.setTotal((int)response.getHits().totalHits);// for (SearchHit searchHit : response.getHits().getHits()) {// BasicTrace basicTrace = new BasicTrace();//// basicTrace.setSegmentId((String)searchHit.getSourceAsMap().get(SegmentRecord.SEGMENT_ID));// basicTrace.setStart(String.valueOf(searchHit.getSourceAsMap().get(SegmentRecord.START_TIME)));// basicTrace.getEndpointNames().add((String)searchHit.getSourceAsMap().get(SegmentRecord.ENDPOINT_NAME));// basicTrace.setDuration(((Number)searchHit.getSourceAsMap().get(SegmentRecord.LATENCY)).intValue());// basicTrace.setError(BooleanUtils.valueToBoolean(((Number)searchHit.getSourceAsMap().get(SegmentRecord.IS_ERROR)).intValue()));// basicTrace.getTraceIds().add((String)searchHit.getSourceAsMap().get(SegmentRecord.TRACE_ID));// basicTrace.setTimeBack(String.valueOf(searchHit.getSourceAsMap().get(SegmentRecord.TIME_BUCKET)));// traceBrief.getTraces().add(basicTrace);// } return map; } public Map<String, Object> queryBasicTraces(long startSecondTB, long endSecondTB, long minDuration, long maxDuration, String endpointName, int serviceId, int serviceInstanceId, int endpointId, String traceId, int limit, int from, TraceState traceState, QueryOrder queryOrder) throws IOException { SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource();////由于是聚合,这里使用的是AggregationBuilder。maxSecond是自己定义的给查询出来的最大值起的名字,// second是elasticsearch中的index里面我们放进去的数据里面的字段名,也就是要在该字段中聚合出最大值// AggregationBuilder builder = AggregationBuilders.max("maxSecond").field("second");// //prepareSearch()传入要查询的index// SearchResponse response = client.prepareSearch("wyh-apache-log").addAggregation(builder).get();// //从查询结果中获取刚才定义的最大值的名称// Max max = response.getAggregations().get("maxSecond");// AggregationBuilder builder = AggregationBuilders.max("max-"+SegmentRecord.LATENCY).field(SegmentRecord.LATENCY);// TermsAggregationBuilder teamAgg = AggregationBuilders.terms("team");// AvgAggregationBuilder ageAgg = AggregationBuilders.avg("avg_age").field(SegmentRecord.LATENCY);// MaxAggregationBuilder salaryAgg = AggregationBuilders.max("total_salary ").field(SegmentRecord.LATENCY); StatsAggregationBuilder stats = AggregationBuilders.stats("stats-"+SegmentRecord.LATENCY).field(SegmentRecord.LATENCY);// sourceBuilder.addAggregation(teamAgg.subAggregation(ageAgg).subAggregation(salaryAgg));// sourceBuilder.aggregation(teamAgg.subAggregation(ageAgg).subAggregation(salaryAgg)); sourceBuilder.aggregation(stats); BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); sourceBuilder.query(boolQueryBuilder); List<QueryBuilder> mustQueryList = boolQueryBuilder.must(); if (startSecondTB != 0 && endSecondTB != 0) { mustQueryList.add(QueryBuilders.rangeQuery(SegmentRecord.TIME_BUCKET).gte(startSecondTB).lte(endSecondTB)); } if (minDuration != 0 || maxDuration != 0) { RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery(SegmentRecord.LATENCY); if (minDuration != 0) { rangeQueryBuilder.gte(minDuration); } if (maxDuration != 0) { rangeQueryBuilder.lte(maxDuration); } boolQueryBuilder.must().add(rangeQueryBuilder); } if (!Strings.isNullOrEmpty(endpointName)) { String matchCName = MatchCNameBuilder.INSTANCE.build(SegmentRecord.ENDPOINT_NAME); mustQueryList.add(QueryBuilders.matchPhraseQuery(matchCName, endpointName)); } if (serviceId != 0) { boolQueryBuilder.must().add(QueryBuilders.termQuery(SegmentRecord.SERVICE_ID, serviceId)); } if (serviceInstanceId != 0) { boolQueryBuilder.must().add(QueryBuilders.termQuery(SegmentRecord.SERVICE_INSTANCE_ID, serviceInstanceId)); } if (endpointId != 0) { boolQueryBuilder.must().add(QueryBuilders.termQuery(SegmentRecord.ENDPOINT_ID, endpointId)); } if (!Strings.isNullOrEmpty(traceId)) { boolQueryBuilder.must().add(QueryBuilders.termQuery(SegmentRecord.TRACE_ID, traceId)); } switch (traceState) { case ERROR: mustQueryList.add(QueryBuilders.matchQuery(SegmentRecord.IS_ERROR, BooleanUtils.TRUE)); break; case SUCCESS: mustQueryList.add(QueryBuilders.matchQuery(SegmentRecord.IS_ERROR, BooleanUtils.FALSE)); break; } switch (queryOrder) { case BY_START_TIME: sourceBuilder.sort(SegmentRecord.START_TIME, SortOrder.DESC); break; case BY_DURATION: sourceBuilder.sort(SegmentRecord.LATENCY, SortOrder.DESC); break; } sourceBuilder.size(limit); sourceBuilder.from(from); System.out.println(sourceBuilder); SearchResponse response1 = search(SegmentRecord.INDEX_NAME, sourceBuilder); mustQueryList.add(QueryBuilders.matchQuery(SegmentRecord.IS_ERROR, BooleanUtils.TRUE)); System.out.println(sourceBuilder); SearchResponse response2 = search(SegmentRecord.INDEX_NAME, sourceBuilder); mustQueryList.remove(QueryBuilders.matchQuery(SegmentRecord.IS_ERROR, BooleanUtils.TRUE)); mustQueryList.add(QueryBuilders.matchQuery(SegmentRecord.IS_ERROR, BooleanUtils.FALSE)); System.out.println(sourceBuilder); SearchResponse response3 = search(SegmentRecord.INDEX_NAME, sourceBuilder); HashMap<String, Object> map = new HashMap<>(); map.put("allTaltal",response1.getHits().totalHits); map.put("errTaltal",response2.getHits().totalHits); map.put("sucTaltal",response3.getHits().totalHits); org.elasticsearch.search.aggregations.metrics.stats.Stats statsAgg = response1.getAggregations().get("stats-" + SegmentRecord.LATENCY); double avg = statsAgg.getAvg(); double max = statsAgg.getMax(); double min = statsAgg.getMin(); long count = statsAgg.getCount(); map.put("avgLatency",avg); map.put("maxLatency",max); map.put("minLatency",min); map.put("countLatency",count); map.put("endpointName",endpointName); System.out.println(avg+" "+max+" "+min+" "+count);// TraceBrief traceBrief = new TraceBrief();// traceBrief.setTotal((int)response.getHits().totalHits);// for (SearchHit searchHit : response.getHits().getHits()) {// BasicTrace basicTrace = new BasicTrace();//// basicTrace.setSegmentId((String)searchHit.getSourceAsMap().get(SegmentRecord.SEGMENT_ID));// basicTrace.setStart(String.valueOf(searchHit.getSourceAsMap().get(SegmentRecord.START_TIME)));// basicTrace.getEndpointNames().add((String)searchHit.getSourceAsMap().get(SegmentRecord.ENDPOINT_NAME));// basicTrace.setDuration(((Number)searchHit.getSourceAsMap().get(SegmentRecord.LATENCY)).intValue());// basicTrace.setError(BooleanUtils.valueToBoolean(((Number)searchHit.getSourceAsMap().get(SegmentRecord.IS_ERROR)).intValue()));// basicTrace.getTraceIds().add((String)searchHit.getSourceAsMap().get(SegmentRecord.TRACE_ID));// basicTrace.setTimeBack(String.valueOf(searchHit.getSourceAsMap().get(SegmentRecord.TIME_BUCKET)));// traceBrief.getTraces().add(basicTrace);// } return map; } public SearchResponse search(String indexName, SearchSourceBuilder searchSourceBuilder) throws IOException { indexName = formatIndexName(indexName); SearchRequest searchRequest = new SearchRequest(indexName); searchRequest.types(TYPE); searchRequest.source(searchSourceBuilder); //client为RestHighLevelClient,但是我们的版本没有 ActionFuture<SearchResponse> future = elasticsearchTemplate.getClient().search(searchRequest); SearchResponse searchResponse = future.actionGet(); return searchResponse; } public String formatIndexName(String indexName) { if (StringUtils.isNotEmpty(namespace)) { return namespace + "_" + indexName; } return indexName; } /** * 根据所给时间查prometheus中的数据 * * @param query * @param time * @return */ public String readPrometheus(String query, String time) { String url = "http://" + ip + ":" + port + "/api/v1/query?query=" + query + "&time=" + time; String result = getUrl(url); if (StringUtils.isEmpty(result)) { throw new RuntimeException("访问prometheus出现异常"); } return result; } /** * 根据时间查询node信息 * @param query * @param timeUTC * @return */ public Map<String, Long> readPrometheusByNode(String query, String timeUTC) { Map<String, Long> resultMap = new TreeMap<>(); String url = "http://" + ip + ":" + port + "/api/v1/query?query=" + query + "&time=" + timeUTC; String result = getUrl(url); if (StringUtils.isEmpty(result)) { throw new RuntimeException("访问prometheus出现异常"); } List resultJson = JsonResolve(result); for (Object o : resultJson) { Map<String, Object> map = (Map<String, Object>) o; Map<String, String> metric = (Map<String, String>) map.get("metric"); String node = metric.get("node"); List values = (List) map.get("value"); for (int i = 0; i < values.size(); i++) { if (i == 0) { Long o1 = Long.parseLong(values.get(i).toString()); String s = DateUtils.longDate2String(o1 * 1000, "yyyy-MM-dd.HH"); values.set(i, s); } } resultMap.put(node, Long.parseLong(values.get(1).toString())); } return resultMap; } /** * 查询某一段时间的peometheus信息 * @param queues * @param query * @param start * @param end * @param step * @return */ public Map<String, Map<String, Long>> readPrometheusByTime(List<String> queues, String query, String start, String end, String step) { String result = null; Map<String, Map<String, Long>> queueResultMap = new HashMap<>(); //Map<String, List<Integer>> queueResultMap = new HashMap<>(); try { query = URLEncoder.encode(query, "UTF-8"); String url = "http://" + ip + ":" + port + "/api/v1/query_range?query=" + query + "&start=" + start + "&end=" + end + "&step=" + step; result = getUrl(url); if (StringUtils.isEmpty(result)) { throw new RuntimeException("访问prometheus出现异常"); } } catch (UnsupportedEncodingException e) { log.info("编码转换出现异常"); e.printStackTrace(); return null; } List resultJson = JsonResolve(result); queues.forEach(queueName -> { for (Object o : resultJson) { Map<String, Object> map = (Map<String, Object>) o; Map<String, String> metric = (Map<String, String>) map.get("metric"); String queue = metric.get("queue"); if (queueName.equals(queue)) { Map<String, Long> resultMap = new TreeMap<>(); //List<Integer> resultList = new ArrayList<>(); List values = (List) map.get("values"); for (Object value : values) { List<Object> resultValue = (List<Object>) value; for (int i = 0; i < resultValue.size(); i++) { if (i == 0) { Long o1 = Long.parseLong(resultValue.get(i).toString()); String s = DateUtils.longDate2String(o1 * 1000, "yyyy-MM-dd HH:mm:ss"); resultValue.set(i, s); } } //resultList.add(Integer.parseInt(resultValue.get(1).toString())); resultMap.put(resultValue.get(0).toString(), Long.parseLong(resultValue.get(1).toString())); } queueResultMap.put(queueName, resultMap); //queueResultMap.put(queueName, resultList); } } }); log.info("queueResultMap: " + queueResultMap); return queueResultMap; } /** * 一年内发的消息列表 * @param queues * @param query * @param timeQuery * @return */ public Map<String, Map<String, Long>> readPrometheusByYear(List<String> queues, String query, String timeQuery) { Map<String, Map<String, Long>> queueResultMap = new HashMap<>(); String url = "http://" + ip + ":" + port + "/api/v1/query?query=" + query + "&time=" + timeQuery; String result = getUrl(url); if (StringUtils.isEmpty(result)) { throw new RuntimeException("访问prometheus出现异常"); } List resultJson = JsonResolve(result); queues.forEach(queueName -> { for (Object o : resultJson) { Map<String, Object> map = (Map<String, Object>) o; Map<String, String> metric = (Map<String, String>) map.get("metric"); String queue = metric.get("queue"); if (queueName.equals(queue)) { TreeMap<String, Long> resultMap = new TreeMap<>(); //List<Integer> resultList = new ArrayList<>(); List values = (List) map.get("value"); for (int i = 0; i < values.size(); i++) { if (i == 0) { Long o1 = Long.parseLong(values.get(i).toString()); String s = DateUtils.longDate2String(o1 * 1000, "yyyy-MM-dd HH:mm:ss"); values.set(i, s); } resultMap.put(values.get(0).toString(), Long.parseLong(values.get(1).toString())); } queueResultMap.put(queueName, resultMap); //queueResultMap.put(queueName, resultList); } } }); return queueResultMap; } /** * 解析监控返回结果 * @param queues * @param resultList * @param resultMap */ public void analysisResult(List<String> queues, List<Map<String, Map<String, Long>>> resultList, Map<String, Map<String, Long>> resultMap) { for (String string : queues) { TreeMap<String, Long> results = new TreeMap<>(); for (Map<String, Map<String, Long>> map : resultList) { for (String s : map.keySet()) { if (string.equals(s)) { Map<String, Long> map1 = map.get(s); for (String s1 : map1.keySet()) { results.put(s1, map.get(s).get(s1)); } } resultMap.put(string, results); } } } } /** * 访问地址 * * @param url * @return */ public String getUrl(String url) { try { log.info("url: " + url); HttpGet get = new HttpGet(url); CloseableHttpClient httpClient = HttpClients.custom().build(); CloseableHttpResponse response = httpClient.execute(get); HttpEntity entity = response.getEntity(); String s = EntityUtils.toString(entity, "utf-8"); return s; } catch (IOException e) { e.printStackTrace(); log.info("访问prometheus出错"); return null; } } /** * 解析从prometheus中返回的数据 * * @param result * @return */ public List JsonResolve(String result) { JSONObject jsonObject = JSON.parseObject(result); String status = jsonObject.get("status").toString(); if ("error".equals(status)) { log.info("result: " + result); throw new RuntimeException("访问prometheus出现错误"); } JSONObject data = jsonObject.getJSONObject("data"); List resultJson = (List) data.get("result"); return resultJson; }}
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */package com.chinatower.product.monitoring.common;/** * @author peng-yongsheng */public interface StorageData { String id();}
package com.chinatower.product.monitoring.common;import com.alibaba.fastjson.JSON;import com.chinatower.product.monitoring.entity.*;import com.chinatower.product.monitoring.mapper.EurekaInstanceMapper;import com.google.common.util.concurrent.AtomicDouble;import io.micrometer.core.instrument.*;import kotlinx.coroutines.internal.AtomicDesc;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;import java.util.ArrayList;import java.util.List;import java.util.Optional;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.atomic.AtomicInteger;import java.util.concurrent.atomic.AtomicLong;import java.util.function.ToDoubleFunction;import java.util.regex.Matcher;import java.util.regex.Pattern;/** * Created by changzheng on 2020/4/2. */@Componentpublic class SWUtils { private static final Logger logger = LoggerFactory.getLogger(SWUtils.class); //指标类型,指标值对象引用 private static ConcurrentHashMap<String, AtomicDouble> concurrentHashMap1 = new ConcurrentHashMap<String, AtomicDouble>(); private static ConcurrentHashMap<String, AtomicDouble> concurrentHashMap2 = new ConcurrentHashMap<String, AtomicDouble>(); //服务实例id,服务实例 public static volatile ConcurrentHashMap<String, ServiceInstanceInventory> instanceMap = new ConcurrentHashMap<>(); //指标名称,指标值;目前只有一个 private static volatile ConcurrentHashMap<String, AtomicDouble> traceHashMap = new ConcurrentHashMap<String, AtomicDouble>(); //一个请求类型对应一个指标,key为所有请求类型,值为指标值的引用 private static ConcurrentHashMap<String,AtomicDouble> operationNameHashMap=new ConcurrentHashMap<>(); private static EurekaInstanceMapper eurekaInstanceMapper; @Autowired SWUtils(EurekaInstanceMapper eurekaInstanceMapper){ SWUtils.eurekaInstanceMapper=eurekaInstanceMapper; } static List<Tag> init(Metric metric, String ip,String name, String port) { ArrayList<Tag> list = new ArrayList() { }; list.add(new ImmutableTag("className", metric.getClassName())); list.add(new ImmutableTag("ip",ip)); list.add(new ImmutableTag("name", name.substring(0, name.indexOf("-pid"))));// addIpAndPort(ip, name,port, list); list.add(new ImmutableTag("ipAndPort",(ip.contains(",")?ip.split(",")[1]:ip)+":"+port)); return list; } static List<Tag> init(SpanObjectV2 spanObjectV2,String ip,String name,String port) { ArrayList<Tag> list = new ArrayList() { }; list.add(new ImmutableTag("ip",ip)); list.add(new ImmutableTag("name", name.substring(0, name.indexOf("-pid"))));// addIpAndPort(ip, name,port, list); list.add(new ImmutableTag("ipAndPort",(ip.contains(",")?ip.split(",")[1]:ip)+":"+port)); return list; } public static List<Tag> init(String Status) { ArrayList<Tag> list = new ArrayList() { }; list.add(new ImmutableTag("interface",Status)); return list; } static List<Tag> init(SpanObjectV2 spanObjectV2,String operationName,String ip,String name,String port) { ArrayList<Tag> list = new ArrayList() { }; list.add(new ImmutableTag("ip",ip)); list.add(new ImmutableTag("name", name.substring(0, name.indexOf("-pid")))); try{ if(operationName.contains("/")&&HasDigit(operationName)){ for(String str:operationName.split("/")){ if (HasDigit(str)) operationName=operationName.replace(str,"${param}"); } } }catch(Exception e){ e.printStackTrace(); } list.add(new ImmutableTag("operationName",operationName));// addIpAndPort(ip, name,port, list); list.add(new ImmutableTag("ipAndPort",(ip.contains(",")?ip.split(",")[1]:ip)+":"+port)); return list; }// private static void addIpAndPort(String ip, String name,String port, ArrayList<Tag> list) {// try{// list.add(new ImmutableTag("ipAndPort",(ip.contains(",")?ip.split(",")[1]:ip)+":"+port));//// else//// logger.info("数据库中找不到服务:ip="+ip+"、name="+name.substring(0, name.indexOf("-pid")));// }catch (Exception e){// e.printStackTrace();// }// } public static synchronized void addOrUpdateMetricVlue(Metric metric,MeterRegistry registry){ while (concurrentHashMap1.get(metric.getClassName())==null){ concurrentHashMap1.put(metric.getClassName(),new AtomicDouble()); } Optional<ServiceInstanceInventory> optional = Optional.ofNullable(instanceMap.get(metric.getServiceId())); if(optional.isPresent()){ try{ String ip=optional.isPresent() ? optional.get().getIpv4s() :null; String name=optional.isPresent() ? optional.get().getName() :null; EurekaInstanceBean eurekaInstanceBean = new EurekaInstanceBean(); eurekaInstanceBean.setIpAddr(ip.contains(",")?ip.split(",")[1]:ip); eurekaInstanceBean.setSkywalkingServiceName(name.substring(0, name.indexOf("-pid"))); EurekaInstanceBean bean = eurekaInstanceMapper.getByIpAndSwName(eurekaInstanceBean); if (bean!=null&&bean.getPort()!=null&&!"".equals(bean.getPort())&&!"null".equals(bean.getPort())){ AtomicDouble atomicDouble = concurrentHashMap1.get(metric.getClassName()); AtomicDouble gauge = Metrics.gauge("sw_metric_value", init(metric,ip,name,bean.getPort()),atomicDouble); gauge.set(metric.getValue()); } }catch(Exception e){ e.printStackTrace(); } }else{// logger.info("实例服务ID未获取到:"+metric.getServiceId()); } } public static synchronized void addOrUpdateMetricSum(Metric metric, MeterRegistry registry) { while (concurrentHashMap2.get(metric.getClassName())==null){ concurrentHashMap2.put(metric.getClassName(),new AtomicDouble()); } Optional<ServiceInstanceInventory> optional = Optional.ofNullable(instanceMap.get(metric.getServiceId())); if(optional.isPresent()) { try { String ip = optional.isPresent() ? optional.get().getIpv4s() : null; String name = optional.isPresent() ? optional.get().getName() : null; EurekaInstanceBean eurekaInstanceBean = new EurekaInstanceBean(); eurekaInstanceBean.setIpAddr(ip.contains(",") ? ip.split(",")[1] : ip); eurekaInstanceBean.setSkywalkingServiceName(name.substring(0, name.indexOf("-pid"))); EurekaInstanceBean bean = eurekaInstanceMapper.getByIpAndSwName(eurekaInstanceBean); if (bean != null && bean.getPort() != null && !"".equals(bean.getPort()) && !"null".equals(bean.getPort())) { AtomicDouble atomicDouble = concurrentHashMap2.get(metric.getClassName()); /** * Caused by: java.lang.IllegalArgumentException: Prometheus requires that all meters with the same name have the same set of tag keys. * There is already an existing meter containing tag keys [application, className, ip, ipAndPort, name]. * The meter you are attempting to register has keys [application, className, ip, name]. * :Prometheus要求所有同名的仪表都具有相同的标记键集。 * * 已经有一个包含标记键(application,className,ip,ipAndPort,name)的现有仪表。 * * 您试图注册的仪表具有键[application,className,ip,name]。所以会报异常,这样是不行的 */ AtomicDouble gauge = Metrics.gauge("sw_metric_summation", init(metric, ip,name,bean.getPort()), atomicDouble); gauge.set(metric.getSummation()); } }catch (Exception e){ e.printStackTrace(); } }else{// logger.info("实例服务ID未获取到:"+metric.getServiceId()); } } /** * @param segmentObject * @param registry */ public static synchronized void addOrUpdateTrace(SegmentObject segmentObject, MeterRegistry registry) { Optional<ServiceInstanceInventory> optional = Optional.ofNullable(instanceMap.get(segmentObject.getServiceId()+"")); if(optional.isPresent()) { UniqueId traceSegmentId = segmentObject.getTraceSegmentId(); List<SpanObjectV2> spansList = segmentObject.getSpans(); for (SpanObjectV2 spanObjectV2 : spansList) { String operationName = spanObjectV2.getOperationName() + ""; logger.info(operationName); if ( "".equals(operationName) ||"null".equals(operationName) ||!operationName.contains("/") || operationName.startsWith("PostgreSQL/JDBI/") || operationName.startsWith("Mysql/JDBI/") ) continue; try { String ip = optional.isPresent() ? optional.get().getIpv4s() : null; String name = optional.isPresent() ? optional.get().getName() : null; EurekaInstanceBean eurekaInstanceBean = new EurekaInstanceBean(); eurekaInstanceBean.setIpAddr(ip.contains(",") ? ip.split(",")[1] : ip); eurekaInstanceBean.setSkywalkingServiceName(name.substring(0, name.indexOf("-pid"))); EurekaInstanceBean bean = eurekaInstanceMapper.getByIpAndSwName(eurekaInstanceBean); if (bean != null && bean.getPort() != null && !"".equals(bean.getPort()) && !"null".equals(bean.getPort())) { while(traceHashMap.get("sw_span_all")==null){ traceHashMap.put("sw_span_all", new AtomicDouble()); } AtomicDouble monitoring_skywalking_trace_guage_time = traceHashMap.get("sw_span_all"); AtomicDouble monitoring_skywalking_trace_guage_time1 = Metrics.gauge("sw_span_all", init(spanObjectV2,ip,name,bean.getPort()), monitoring_skywalking_trace_guage_time); monitoring_skywalking_trace_guage_time1.set(spanObjectV2.getEndTime()-spanObjectV2.getStartTime()); while(operationNameHashMap.get(operationName)==null){ operationNameHashMap.put(operationName, new AtomicDouble()); } AtomicDouble atomicDouble = operationNameHashMap.get(operationName); //这里可以通过指标名称来区分不同的指标,同时也可以通过tag区分不同的指标,此处采用tag加入operationName AtomicDouble gauge = Metrics.gauge("sw_span_type", init(spanObjectV2,operationName,ip,name,bean.getPort()), atomicDouble); gauge.set(spanObjectV2.getEndTime()-spanObjectV2.getStartTime()); } }catch (Exception e){ e.printStackTrace(); } } }else{// logger.info("实例服务ID未获取到:"+segmentObject.getServiceId()); } } // 判断一个字符串是否含有数字 public static boolean HasDigit(String content) { boolean flag = false; Pattern p = Pattern.compile(".*\\d+.*"); Matcher m = p.matcher(content); if (m.matches()) { flag = true; } return flag; } // ArrayList<Tag> list = new ArrayList() { // }; // list.add(new ImmutableTag("traceSegmentId", JSON.toJSONString(traceSegmentId))); // list.add(new ImmutableTag("span", JSON.toJSONString(spanObjectV2).replaceAll("\\\\", ""))); // list.add(new ImmutableTag("ip", ip)); // list.add(new ImmutableTag("name", name.substring(0, name.indexOf("-pid")))); // registry.gauge("monitoring_skywalking_trace_guage_time",list,new AtomicLong(spanObjectV2.getEndTime()-spanObjectV2.getStartTime())); // gauge1 = Gauge.builder("monitoring_skywalking_trace_guage_time", spanObjectV2, s -> s.getEndTime() - s.getStartTime()) // .tag("ip", ip) // .tag("name", name.substring(0, name.indexOf("-pid"))) // .description(JSON.toJSONString(traceSegmentId)) // .register(registry);// public static void addOrUpdate(Metric metric,MeterRegistry registry){// Gauge gauge1 = Gauge.builder("monitoring.skywalking.metric.guage", atomicDouble,AtomicDouble::get)// .tag("className", metric.getClassName())// .register(registry);//// Metrics.gaugeMapSize()// AtomicDouble gauge = Metrics.gauge("monitoring.skywalking.metric.guage.value", init(metric), atomicDouble);// while(true){// gauge.addAndGet(10);// try {// Thread.sleep(1000);// } catch (InterruptedException e) {// e.printStackTrace();// }// System.out.println(gauge1.measure()+"\t\t"+atomicDouble);// }// }}
package com.chinatower.product.monitoring.common.trace;import lombok.Getter;import lombok.Setter;import java.util.ArrayList;import java.util.List;@Getterpublic class BasicTrace { @Setter private String segmentId; private final List<String> endpointNames; @Setter private int duration; @Setter private String start; @Setter private boolean isError; @Setter private String timeBack; private final List<String> traceIds; public BasicTrace() { this.endpointNames = new ArrayList<>(); this.traceIds = new ArrayList<>(); }}
package com.chinatower.product.monitoring.common.trace;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target({ElementType.FIELD})@Retention(RetentionPolicy.RUNTIME)public @interface Column { String columnName(); /** * The column value is used in metrics value query. */ boolean isValue() default false; /** * The function is used in aggregation query. */ Function function() default Function.None; /** * Match query means using analyzer(if storage have) to do key word match query. */ boolean matchQuery() default false; /** * The column is just saved, never used in query. */ boolean content() default false;}
package com.chinatower.product.monitoring.common.trace;public enum Downsampling { None(0, ""), Second(1, "second"), Minute(2, "minute"), Hour(3, "hour"), Day(4, "day"), Month(5, "month"); private final int value; private final String name; Downsampling(int value, String name) { this.value = value; this.name = name; } public int getValue() { return value; } public String getName() { return name; }}
package com.chinatower.product.monitoring.common.trace;import lombok.Data;import lombok.Getter;@Datapublic class Duration { private String start; private String end; private Step step;}
package com.chinatower.product.monitoring.common.trace;public class DurationPoint { private long point; private long secondsBetween; private long minutesBetween; public DurationPoint(long point, long secondsBetween, long minutesBetween) { this.point = point; this.secondsBetween = secondsBetween; this.minutesBetween = minutesBetween; } public long getPoint() { return point; } public long getSecondsBetween() { return secondsBetween; } public long getMinutesBetween() { return minutesBetween; }}
package com.chinatower.product.monitoring.common.trace;import com.chinatower.product.monitoring.common.Const;import org.joda.time.DateTime;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;import java.util.LinkedList;import java.util.List;public enum DurationUtils { INSTANCE; public long exchangeToTimeBucket(String dateStr) { dateStr = dateStr.replaceAll(Const.LINE, Const.EMPTY_STRING); dateStr = dateStr.replaceAll(Const.SPACE, Const.EMPTY_STRING); return Long.valueOf(dateStr); } public long startTimeDurationToSecondTimeBucket(Step step, String dateStr) { long secondTimeBucket = 0; switch (step) { case MONTH: secondTimeBucket = exchangeToTimeBucket(dateStr) * 100 * 100 * 100 * 100; break; case DAY: secondTimeBucket = exchangeToTimeBucket(dateStr) * 100 * 100 * 100; break; case HOUR: secondTimeBucket = exchangeToTimeBucket(dateStr) * 100 * 100; break; case MINUTE: secondTimeBucket = exchangeToTimeBucket(dateStr) * 100; break; case SECOND: secondTimeBucket = exchangeToTimeBucket(dateStr); break; } return secondTimeBucket; } public long endTimeDurationToSecondTimeBucket(Step step, String dateStr) { long secondTimeBucket = 0; switch (step) { case MONTH: secondTimeBucket = (((exchangeToTimeBucket(dateStr) * 100 + 99) * 100 + 99) * 100 + 99) * 100 + 99; break; case DAY: secondTimeBucket = ((exchangeToTimeBucket(dateStr) * 100 + 99) * 100 + 99) * 100 + 99; break; case HOUR: secondTimeBucket = (exchangeToTimeBucket(dateStr) * 100 + 99) * 100 + 99; break; case MINUTE: secondTimeBucket = exchangeToTimeBucket(dateStr) * 100 + 99; break; case SECOND: secondTimeBucket = exchangeToTimeBucket(dateStr); break; } return secondTimeBucket; } public long startTimeToTimestamp(Step step, String dateStr) throws ParseException { switch (step) { case MONTH: return new SimpleDateFormat("yyyy-MM").parse(dateStr).getTime(); case DAY: return new SimpleDateFormat("yyyy-MM-dd").parse(dateStr).getTime(); case HOUR: return new SimpleDateFormat("yyyy-MM-dd HH").parse(dateStr).getTime(); case MINUTE: return new SimpleDateFormat("yyyy-MM-dd HHmm").parse(dateStr).getTime(); case SECOND: return new SimpleDateFormat("yyyy-MM-dd HHmmss").parse(dateStr).getTime(); } throw new UnexpectedException("Unsupported step " + step.name()); } public long endTimeToTimestamp(Step step, String dateStr) throws ParseException { switch (step) { case MONTH: return new DateTime(new SimpleDateFormat("yyyy-MM").parse(dateStr)).plusMonths(1).getMillis(); case DAY: return new DateTime(new SimpleDateFormat("yyyy-MM-dd").parse(dateStr)).plusDays(1).getMillis(); case HOUR: return new DateTime(new SimpleDateFormat("yyyy-MM-dd HH").parse(dateStr)).plusHours(1).getMillis(); case MINUTE: return new DateTime(new SimpleDateFormat("yyyy-MM-dd HHmm").parse(dateStr)).plusMinutes(1).getMillis(); case SECOND: return new DateTime(new SimpleDateFormat("yyyy-MM-dd HHmmss").parse(dateStr)).plusSeconds(1).getMillis(); } throw new UnexpectedException("Unsupported step " + step.name()); } public int minutesBetween(Downsampling downsampling, DateTime dateTime) { switch (downsampling) { case Month: return dateTime.dayOfMonth().getMaximumValue() * 24 * 60; case Day: return 24 * 60; case Hour: return 60; default: return 1; } } public int secondsBetween(Downsampling downsampling, DateTime dateTime) { switch (downsampling) { case Month: return dateTime.dayOfMonth().getMaximumValue() * 24 * 60 * 60; case Day: return 24 * 60 * 60; case Hour: return 60 * 60; case Minute: return 60; default: return 1; } } public List<DurationPoint> getDurationPoints(Downsampling downsampling, long startTimeBucket, long endTimeBucket) throws ParseException { DateTime dateTime = parseToDateTime(downsampling, startTimeBucket); List<DurationPoint> durations = new LinkedList<>(); durations.add(new DurationPoint(startTimeBucket, secondsBetween(downsampling, dateTime), minutesBetween(downsampling, dateTime))); int i = 0; do { switch (downsampling) { case Month: dateTime = dateTime.plusMonths(1); String timeBucket = new SimpleDateFormat("yyyyMM").format(dateTime.toDate()); durations.add(new DurationPoint(Long.valueOf(timeBucket), secondsBetween(downsampling, dateTime), minutesBetween(downsampling, dateTime))); break; case Day: dateTime = dateTime.plusDays(1); timeBucket = new SimpleDateFormat("yyyyMMdd").format(dateTime.toDate()); durations.add(new DurationPoint(Long.valueOf(timeBucket), secondsBetween(downsampling, dateTime), minutesBetween(downsampling, dateTime))); break; case Hour: dateTime = dateTime.plusHours(1); timeBucket = new SimpleDateFormat("yyyyMMddHH").format(dateTime.toDate()); durations.add(new DurationPoint(Long.valueOf(timeBucket), secondsBetween(downsampling, dateTime), minutesBetween(downsampling, dateTime))); break; case Minute: dateTime = dateTime.plusMinutes(1); timeBucket = new SimpleDateFormat("yyyyMMddHHmm").format(dateTime.toDate()); durations.add(new DurationPoint(Long.valueOf(timeBucket), secondsBetween(downsampling, dateTime), minutesBetween(downsampling, dateTime))); break; case Second: dateTime = dateTime.plusSeconds(1); timeBucket = new SimpleDateFormat("yyyyMMddHHmmss").format(dateTime.toDate()); durations.add(new DurationPoint(Long.valueOf(timeBucket), secondsBetween(downsampling, dateTime), minutesBetween(downsampling, dateTime))); break; } i++; if (i > 500) { throw new UnexpectedException("Duration data error, step: " + downsampling.name() + ", start: " + startTimeBucket + ", end: " + endTimeBucket); } } while (endTimeBucket != durations.get(durations.size() - 1).getPoint()); return durations; } private DateTime parseToDateTime(Downsampling downsampling, long time) throws ParseException { DateTime dateTime = null; switch (downsampling) { case Month: Date date = new SimpleDateFormat("yyyyMM").parse(String.valueOf(time)); dateTime = new DateTime(date); break; case Day: date = new SimpleDateFormat("yyyyMMdd").parse(String.valueOf(time)); dateTime = new DateTime(date); break; case Hour: date = new SimpleDateFormat("yyyyMMddHH").parse(String.valueOf(time)); dateTime = new DateTime(date); break; case Minute: date = new SimpleDateFormat("yyyyMMddHHmm").parse(String.valueOf(time)); dateTime = new DateTime(date); break; case Second: date = new SimpleDateFormat("yyyyMMddHHmmss").parse(String.valueOf(time)); dateTime = new DateTime(date); break; } return dateTime; }}
package com.chinatower.product.monitoring.common.trace;public enum Function { None, Avg, Sum}
package com.chinatower.product.monitoring.common.trace;import lombok.Getter;import lombok.Setter;@Getter@Setterpublic class Pagination { private int pageNum; private int pageSize; private boolean needTotal;}
package com.chinatower.product.monitoring.common.trace;public enum PaginationUtils { INSTANCE; public Page exchange(Pagination paging) { int limit = paging.getPageSize(); int from = paging.getPageSize() * ((paging.getPageNum() == 0 ? 1 : paging.getPageNum()) - 1); return new Page(from, limit); } public class Page { private int from; private int limit; Page(int from, int limit) { this.from = from; this.limit = limit; } public int getFrom() { return from; } public int getLimit() { return limit; } }}
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */package com.chinatower.product.monitoring.common.trace;/** * @author peng-yongsheng */public enum QueryOrder { BY_START_TIME, BY_DURATION}
package com.chinatower.product.monitoring.common.trace;public enum Step { MONTH, DAY, HOUR, MINUTE, SECOND}
package com.chinatower.product.monitoring.common.trace;import lombok.Getter;import lombok.Setter;import java.util.ArrayList;import java.util.List;@Getterpublic class TraceBrief { private final List<BasicTrace> traces; @Setter private int total; public TraceBrief() { this.traces = new ArrayList<>(); }}
package com.chinatower.product.monitoring.common.trace;import lombok.Data;import lombok.Getter;import lombok.Setter;@Datapublic class TraceQueryCondition { private String serviceId; private String serviceInstanceId; private String traceId; private String endpointName; private String endpointId; private Duration queryDuration;//MINUTE private int minTraceDuration;//持续时间 private int maxTraceDuration; private TraceState traceState;//ALL private QueryOrder queryOrder;//BY_DURATION private Pagination paging;}
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */package com.chinatower.product.monitoring.common.trace;/** * @author peng-yongsheng */public enum TraceState { ALL, SUCCESS, ERROR,}
package com.chinatower.product.monitoring.common.trace;public class UnexpectedException extends RuntimeException { public UnexpectedException(String message) { super(message); } public UnexpectedException(String message, Exception cause) { super(message, cause); }}
package com.chinatower.product.monitoring.service;import com.chinatower.product.monitoring.common.KafkaUtils;import com.chinatower.product.monitoring.entity.KafkaDto;import com.chinatower.product.monitoring.mapper.KafkaMonitorMapper;import com.chinatower.product.monitoring.response.ProcessResult;import lombok.extern.slf4j.Slf4j;import org.apache.commons.collections.CollectionUtils;import org.apache.commons.lang.StringUtils;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.stream.Collectors;/** * @author lzt */@RestController@RequestMapping("kafkaMonitor")@Slf4jpublic class KafkaMonitorService { @Autowired private KafkaMonitorMapper monitorMapper; @Autowired private KafkaUtils kafkaUtils; /** * 根据登录人员查询kafka权限明细地址 * * @param topicName * @param groupTopicName * @return */ @PostMapping("/getDataPermission") public ProcessResult getDataPermission(@RequestParam(required = false) String topicName, String groupTopicName) { StringBuffer str = new StringBuffer(); ProcessResult result = new ProcessResult(); if (StringUtils.isNotBlank(topicName)) { // 拼接topic信息 for (String data : topicName.split(",")) { str.append("&var-topic=" + data); } } if (StringUtils.isNotBlank(groupTopicName)) { // topic组信息 if (StringUtils.isNotBlank(groupTopicName)) { for (String data : groupTopicName.split(",")) { str.append("&var-group=" + data); } } } str.append("&from=now%2Fd&to=now%2Fd&refresh=15m"); result.setData(str); result.setResultStat(ProcessResult.SUCCESS); return result; } /** * 分组查询kafka首页系统数据 * * @param empId * @return */ @PostMapping("/getProjectTopicGroupData") public ProcessResult getProjectTopicGroupData(@RequestParam(required = false) String empId) { List<KafkaDto> kafkaDtoList = new ArrayList<>(); List<KafkaDto> kafkaDtoList1 = new ArrayList<>(); ProcessResult result = new ProcessResult(); String topicSendData = ""; String topicLagData = ""; List<String> topicNameStr = null; List<String> groupTopicNameStr = null; if (StringUtils.isNotBlank(empId)) { try { // 分组查询系统对应的主题 kafkaDtoList = monitorMapper.getProjectTopicInfoList(empId); // 系统中独立注册过的使用kafka的用户 if (CollectionUtils.isNotEmpty(kafkaDtoList) && kafkaDtoList.size() > 0) { for (int i = 0; i < kafkaDtoList.size(); i++) { KafkaDto kafkaDto = new KafkaDto(); kafkaDto.setProjectName(kafkaDtoList.get(i).getProjectName()); topicNameStr = Arrays.asList(kafkaDtoList.get(i).getTopicName().split(",")).stream().map(s -> (s.trim())).collect( Collectors.toList()); // 查询系统topic发送数量 topicSendData = monitorMapper.getTopicSendData(topicNameStr); kafkaDto.setTopicSendNum(topicSendData); // 系统topic数量 kafkaDto.setTopicNum(String.valueOf(topicNameStr.size())); if (StringUtils.isNotBlank(kafkaDtoList.get(i).getGroupTopicName())) { groupTopicNameStr = Arrays.asList(kafkaDtoList.get(i).getGroupTopicName().split(",")).stream().map(s -> (s.trim())).collect( Collectors.toList()); } // 查询系统topic积压数量 topicLagData = monitorMapper.getConsumerGroupLag(topicNameStr, groupTopicNameStr); kafkaDto.setGroupTopicLag(topicLagData); kafkaDto.setTopicName(kafkaDtoList.get(i).getTopicName()); kafkaDto.setGroupTopicName(kafkaDtoList.get(i).getGroupTopicName()); kafkaDtoList1.add(kafkaDto); } } else { //如果为空看是不是管理员用户,admin全部展示数据,其他账号没有数据信息 String empAccount = monitorMapper.getSysEmpInfo(empId); if (StringUtils.isNotBlank(empAccount) && "admin".equals(empAccount)) { // 管理员查询全部数据 kafkaDtoList = monitorMapper.getProjectTopicInfoList(""); if (CollectionUtils.isNotEmpty(kafkaDtoList) && kafkaDtoList.size() > 0) { for (int i = 0; i < kafkaDtoList.size(); i++) { KafkaDto kafkaDto = new KafkaDto(); kafkaDto.setProjectName(kafkaDtoList.get(i).getProjectName()); topicNameStr = Arrays.asList(kafkaDtoList.get(i).getTopicName().split(",")).stream().map(s -> (s.trim())).collect( Collectors.toList()); // 查询系统topic发送数量 topicSendData = monitorMapper.getTopicSendData(topicNameStr); kafkaDto.setTopicSendNum(topicSendData); // 系统topic积压信息 if (StringUtils.isNotBlank(kafkaDtoList.get(i).getGroupTopicName())) { groupTopicNameStr = Arrays.asList(kafkaDtoList.get(i).getGroupTopicName().split(",")).stream().map(s -> (s.trim())).collect( Collectors.toList()); } // 查询系统topic积压数量 topicLagData = monitorMapper.getConsumerGroupLag(topicNameStr, groupTopicNameStr); kafkaDto.setGroupTopicLag(topicLagData); // 系统topic主题数量 groupTopicNameStr = Arrays.asList(kafkaDtoList.get(i).getTopicName().split(",")).stream().map(s -> (s.trim())).collect( Collectors.toList()); kafkaDto.setTopicNum(String.valueOf(groupTopicNameStr.size())); kafkaDto.setTopicName(kafkaDtoList.get(i).getTopicName()); kafkaDto.setGroupTopicName(kafkaDtoList.get(i).getGroupTopicName()); kafkaDtoList1.add(kafkaDto); } } } else { // 当前系统帐号没有数据展示 } } result.setData(kafkaDtoList1); } catch (Exception e) { result.setResultStat(ProcessResult.ERROR); result.setMess("根据人员信息查询数据权限出错!原因:" + e.getMessage()); } } else { result.setMess("登录人员信息异常!"); result.setResultStat(ProcessResult.ERROR); } return result; }// @Scheduled(cron = "0 18 15 * * ?")// public void readPrometheusTopicNum() {// String param = "1h";// kafkaUtils.readPrometheusTopicNum("increase(kafka_topic_partition_current_offset["+param+"])");// //kafkaUtils.readPrometheusTopicGroupNum("sum(kafka_consumergroup_lag) by (consumergroup, topic)");//// }}
package com.chinatower.product.monitoring.service;import com.alibaba.fastjson.JSONObject;import com.chinatower.product.monitoring.api.RabbitmqMonitorAPI;import com.chinatower.product.monitoring.common.DateUtils;import com.chinatower.product.monitoring.common.RabbitMQUtils;import com.chinatower.product.monitoring.entity.RabbitMQLog;import com.chinatower.product.monitoring.mapper.KafkaMonitorMapper;import com.chinatower.product.monitoring.mapper.RabbitmqMonitorMapper;import com.chinatower.product.monitoring.response.ProcessResult;import com.chinatower.product.monitoring.response.ResultPage;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.util.StringUtils;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.bind.annotation.RestController;import java.util.*;@RestController@Slf4jpublic class RabbitmqMonitorService implements RabbitmqMonitorAPI { @Autowired private RabbitMQUtils rabbitMQUtils; @Autowired private RabbitmqMonitorMapper rabbitmqMonitorMapper; @Override public ResultPage<RabbitMQLog> readEs(String startTime, String endTime, Integer page, Integer size, String queueName) { String pattern = "yyyy-MM-dd.HH"; if (startTime == null){ startTime = "2020-04-30.00"; } if (endTime == null){ Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); calendar.set(Calendar.HOUR, calendar.get(Calendar.HOUR) + 1); endTime = DateUtils.longDate2String(calendar.getTime().getTime(), pattern); } if (page == null){ page = 1; } if (size == null){ size = 20; }// if (page*size>10000){// throw new RuntimeException("ES返回数据错误,建议缩小粒度");// } String start = DateUtils.dateFormat(startTime,pattern); String end = DateUtils.dateFormat(endTime,pattern); log.info("startUTC: " + start); log.info("endUTC: " + end); if ("null".equals(queueName)){ return rabbitMQUtils.readEsByTime(start,end,page,size); } return rabbitMQUtils.readEs(start,end,page,size,queueName); } @Override public String readPrometheus(String query, String time) { String pattern = "yyyy-MM-dd HH:mm:ss"; String timeUTC = DateUtils.dateFormat(time, pattern); return rabbitMQUtils.readPrometheus(query, timeUTC); } @Override public Map<String, Long> readPrometheusByNode(String query) { Date date = new Date(); String pattern = "yyyy-MM-dd HH:mm:ss"; String s = DateUtils.longDate2String(date.getTime(), pattern); String timeUTC = DateUtils.dateFormat(s, pattern); return rabbitMQUtils.readPrometheusByNode(query, timeUTC); } @Override public JSONObject getRabbitProject(String empId) { JSONObject jo = new JSONObject(); try { jo.put("code","200"); jo.put("message","查询成功"); jo.put("data",rabbitmqMonitorMapper.getRabbitProject(empId)); }catch (Exception e){ jo.put("code","500"); jo.put("message","查询失败"); jo.put("data",new ArrayList<>()); log.error("查询rabbitMq监控项目出现异常!!",e); } return jo; } @Override public JSONObject getRabbitVhost(String projectId) { JSONObject jo = new JSONObject(); try { List<String> projectIds = Arrays.asList(projectId.split(",")); jo.put("code","200"); jo.put("message","查询成功"); jo.put("data",rabbitmqMonitorMapper.getRabbitVhost(projectIds)); }catch (Exception e){ jo.put("code","500"); jo.put("message","查询失败"); jo.put("data",new ArrayList<>()); log.error("查询rabbitMq监控VHOST出现异常!!",e); } return jo; } @Override public JSONObject getRabbitQueue(String vhostId) { JSONObject jo = new JSONObject(); try { List<String> vhostIds = Arrays.asList(vhostId.split(",")); jo.put("code","200"); jo.put("message","查询成功"); jo.put("data",rabbitmqMonitorMapper.getRabbitQueue(vhostIds)); }catch (Exception e){ jo.put("code","500"); jo.put("message","查询失败"); jo.put("data",new ArrayList<>()); log.error("查询rabbitMq监控队列出现异常!!",e); } return jo; } @Override public JSONObject getMonitorControlIndex() { JSONObject jo = new JSONObject(); try { jo.put("code","200"); jo.put("message","查询成功"); jo.put("data",rabbitmqMonitorMapper.getMonitorControlIndex()); }catch (Exception e){ jo.put("code","500"); jo.put("message","查询失败"); jo.put("data",new ArrayList<>()); log.error("查询rabbitMq监控指标出现异常!!",e); } return jo; } @Override public Map<String, Map<String, Long>> readPrometheusByTime(String[] queues, String query, String startTime, String endTime) { List<String> queuesList = Arrays.asList(queues); String pattern = "yyyy-MM-dd HH:mm:ss"; //开始结束时间都转为utc时间 String starUTC = DateUtils.dateFormat(startTime, pattern); String endUTC = DateUtils.dateFormat(endTime, pattern); Long startLong = DateUtils.string2Date(startTime, pattern); //解析步长 Long endLong = DateUtils.string2Date(endTime, pattern); Long stepLong = (endLong - startLong) / 1000; Map<Long, String> timeInterval = DateUtils.formatDateTime(stepLong); log.info("时间间隔: " + timeInterval); String step = null; for (Long timeIntervalLong: timeInterval.keySet()) { if("d".equals(timeInterval.get(timeIntervalLong))){ if (timeIntervalLong >= 60){ List<Map<String, Map<String,Long>>> list = new ArrayList<>(); Map<String, Map<String, Long>> resultMap = new HashMap<>(); // 处理年数据 String yearStringStart = DateUtils.stringFormatString(startTime, pattern, "yyyy"); String mouthStringStart = DateUtils.stringFormatString(startTime, pattern, "MM"); String yearStringEnd = DateUtils.stringFormatString(endTime, pattern, "yyyy"); String mouthStringEnd = DateUtils.stringFormatString(endTime, pattern, "MM"); int yearStart = Integer.parseInt(yearStringStart); int mouthStart = Integer.parseInt(mouthStringStart); int yearEnd = Integer.parseInt(yearStringEnd); int mouthEnd = Integer.parseInt(mouthStringEnd); for (int mouth = mouthStart; mouth < 13; mouth++) { //循环调用service 时间为每月最后一天 String lastDayOfMonth = DateUtils.getLastDayOfMonth(yearStart, mouth); String timeUTC = DateUtils.dateFormat(lastDayOfMonth, pattern); Map<String, Map<String, Long>> map = rabbitMQUtils.readPrometheusByYear(queuesList, query, timeUTC); list.add(map); } for (int mouth = 1; mouth < mouthEnd; mouth++) { //循环调用service 时间为每月最后一天 String lastDayOfMonth = DateUtils.getLastDayOfMonth(yearEnd, mouth); String timeUTC = DateUtils.dateFormat(lastDayOfMonth, pattern); Map<String, Map<String, Long>> map = rabbitMQUtils.readPrometheusByYear(queuesList, query, timeUTC); list.add(map); } rabbitMQUtils.analysisResult(queuesList, list, resultMap); return resultMap; }else if(timeIntervalLong>1){ step="1d"; }else { step = "1h"; } }else if ("h".equals(timeInterval.get(timeIntervalLong))){ step = "1h"; }else if ("m".equals(timeInterval.get(timeIntervalLong))){ step = "1m"; }else if ("s".equals(timeInterval.get(timeIntervalLong))){ step = "1s"; } } log.info("step: " + step); //调用service return rabbitMQUtils.readPrometheusByTime(queuesList, query, starUTC, endUTC, step); } @Override public ProcessResult readPrometheusByTimePost(@RequestBody Map<String, Object> param) { log.info("查询rabbitmq监控指标入参:{}", JSONObject.toJSONString(param)); ProcessResult processResult = new ProcessResult(); try { if (param == null || param.size() <= 0 || StringUtils.isEmpty(param.get("startTime")) || StringUtils.isEmpty(param.get("endTime")) || StringUtils.isEmpty(param.get("queues")) || StringUtils.isEmpty(param.get("query"))) { return null; } List<String> queueIdsList = Arrays.asList(param.get("queues").toString().split(",")); //将数据库中的队列和队列解释查询 List<Map<String,String>> queueResult = rabbitmqMonitorMapper.queryQueueResult(queueIdsList); String pattern = "yyyy-MM-dd HH:mm:ss"; //开始结束时间都转为utc时间 String starUTC = DateUtils.dateFormat(param.get("startTime").toString(), pattern); String endUTC = DateUtils.dateFormat(param.get("endTime").toString(), pattern); Long startLong = DateUtils.string2Date(param.get("startTime").toString(), pattern); //解析步长 Long endLong = DateUtils.string2Date(param.get("endTime").toString(), pattern); String queryQueue = "\""; for (Map<String, String> queue : queueResult) { queryQueue += (queue.get("queueName") + "|"); } queryQueue = "{queue=~" + queryQueue.substring(0, queryQueue.length() - 1) + "\"" + "}"; String query = param.get("query").toString() + queryQueue; log.info("query:{}", query); Long stepLong = (endLong - startLong) / 1000; Map<Long, String> timeInterval = DateUtils.formatDateTime(stepLong); log.info("时间间隔: " + timeInterval); String step = null; for (Long timeIntervalLong : timeInterval.keySet()) { if ("d".equals(timeInterval.get(timeIntervalLong))) { if (timeIntervalLong >= 60) { List<Map<String, Map<String, Long>>> list = new ArrayList<>(); Map<String, Map<String, Long>> resultMap = new HashMap<>(); // 处理年数据 String yearStringStart = DateUtils.stringFormatString(param.get("startTime").toString(), pattern, "yyyy"); String mouthStringStart = DateUtils.stringFormatString(param.get("startTime").toString(), pattern, "MM"); String yearStringEnd = DateUtils.stringFormatString(param.get("endTime").toString(), pattern, "yyyy"); String mouthStringEnd = DateUtils.stringFormatString(param.get("endTime").toString(), pattern, "MM"); int yearStart = Integer.parseInt(yearStringStart); int mouthStart = Integer.parseInt(mouthStringStart); int yearEnd = Integer.parseInt(yearStringEnd); int mouthEnd = Integer.parseInt(mouthStringEnd); for (int mouth = mouthStart; mouth < 13; mouth++) { //循环调用service 时间为每月最后一天 String lastDayOfMonth = DateUtils.getLastDayOfMonth(yearStart, mouth); String timeUTC = DateUtils.dateFormat(lastDayOfMonth, pattern); Map<String, Map<String, Long>> map = rabbitMQUtils.readPrometheusByYearPost(queueResult, query, timeUTC); list.add(map); } for (int mouth = 1; mouth < mouthEnd; mouth++) { //循环调用service 时间为每月最后一天 String lastDayOfMonth = DateUtils.getLastDayOfMonth(yearEnd, mouth); String timeUTC = DateUtils.dateFormat(lastDayOfMonth, pattern); Map<String, Map<String, Long>> map = rabbitMQUtils.readPrometheusByYearPost(queueResult, query, timeUTC); list.add(map); } rabbitMQUtils.analysisResultPost(queueResult, list, resultMap); processResult.setData(resultMap); return processResult; } else if (timeIntervalLong > 1) { step = "1d"; } else { step = "1h"; } } else if ("h".equals(timeInterval.get(timeIntervalLong))) { step = "1h"; } else if ("m".equals(timeInterval.get(timeIntervalLong))) { step = "1m"; } else if ("s".equals(timeInterval.get(timeIntervalLong))) { step = "1s"; } } log.info("step: " + step); //调用service processResult.setData(rabbitMQUtils.readPrometheusByTimeOfRabbitMonitoring(queueResult, query, starUTC, endUTC, step)); return processResult; }catch (Exception e){ log.error("查询rabbitMq监控{时间}发生异常!!",e); processResult.setResultStat(ProcessResult.ERROR); processResult.setMess("查询异常"); return processResult; } } @Override public Map<String, Map<String, Long>> readPrometheusByDay(String[] queues, String query, String time) { List<String> strings = Arrays.asList(queues); String pattern = "yyyy-MM-dd.HH"; String patternTime = "yyyy-MM-dd"; //根据给定的时间设置开始及结束时间 Long timeLong = DateUtils.string2Date(time, patternTime); Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date(timeLong)); //设置开始时间 从0点开始 calendar.set(Calendar.HOUR, 0); String startTime = DateUtils.longDate2String(calendar.getTime().getTime(), pattern); //到23点结束 calendar.set(Calendar.HOUR, 23); String endTime = DateUtils.longDate2String(calendar.getTime().getTime(), pattern); //转为utc时间 String starUTC = DateUtils.dateFormat(startTime, pattern); String endUTC = DateUtils.dateFormat(endTime, pattern); //设置步长 为一小时一次 String step = "1h"; log.info("step: " + step); return rabbitMQUtils.readPrometheusByTime(strings, query, starUTC, endUTC, step); } @Override public ProcessResult readPrometheusByDayPost(@RequestBody Map<String, Object> param) { log.info("查询rabbitmq监控指标入参:{}", JSONObject.toJSONString(param)); ProcessResult processResult = new ProcessResult(); try { if (param == null || param.size() <= 0 || StringUtils.isEmpty(param.get("time")) || StringUtils.isEmpty(param.get("queues")) || StringUtils.isEmpty(param.get("query"))) { return null; } List<String> strings = Arrays.asList(param.get("queues").toString().split(",")); //将数据库中的队列和队列解释查询 List<Map<String,String>> queueResult = rabbitmqMonitorMapper.queryQueueResult(strings); String pattern = "yyyy-MM-dd.HH"; String patternTime = "yyyy-MM-dd"; //根据给定的时间设置开始及结束时间 Long timeLong = DateUtils.string2Date(param.get("time").toString(), patternTime); Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date(timeLong)); //设置开始时间 从0点开始 calendar.set(Calendar.HOUR, 0); String startTime = DateUtils.longDate2String(calendar.getTime().getTime(), pattern); //到23点结束 calendar.set(Calendar.HOUR, 23); String endTime = DateUtils.longDate2String(calendar.getTime().getTime(), pattern); //转为utc时间 String starUTC = DateUtils.dateFormat(startTime, pattern); String endUTC = DateUtils.dateFormat(endTime, pattern); //设置步长 为一小时一次 String step; if (StringUtils.isEmpty(param.get("step"))) { step = "1h"; } else { step = param.get("step").toString(); } log.info("step: " + step); String queryQueue = "\""; for (Map<String, String> queue : queueResult) { queryQueue += (queue.get("queueName") + "|"); } queryQueue = "{queue=~" + queryQueue.substring(0, queryQueue.length() - 1) + "\"" + "}"; String query = param.get("query").toString() + queryQueue; log.info("query:{}", query); processResult.setData(rabbitMQUtils.readPrometheusByTimeOfRabbitMonitoring(queueResult, query, starUTC, endUTC, step)); return processResult; }catch (Exception e){ log.error("查询rabbitMq监控{每天}发生异常!!!",e); processResult.setMess("查询异常"); processResult.setResultStat(ProcessResult.ERROR); return processResult; } } @Override public Map<String, Map<String, Long>> readPrometheusByWeek(String[] queues, String query) { List<String> strings = Arrays.asList(queues); String pattern = "yyyy-MM-dd"; String startTime = null; String endTime = null; try { //本周第一天 startTime = DateUtils.getWeekStart(); //本周最后一天 endTime = DateUtils.getWeekEnd(); } catch (Exception e) { e.printStackTrace(); } log.info(startTime); log.info(endTime); //转为utc时间 String starUTC = DateUtils.dateFormat(startTime, pattern); String endUTC = DateUtils.dateFormat(endTime, pattern); //设置步长为一天一次 String step = "1d"; log.info("step: " + step); return rabbitMQUtils.readPrometheusByTime(strings, query, starUTC, endUTC, step); } @Override public ProcessResult readPrometheusByWeekPost(@RequestBody Map<String, Object> param) { log.info("查询rabbitmq监控指标入参:{}", JSONObject.toJSONString(param)); ProcessResult processResult = new ProcessResult(); try { if (param == null || param.size() <= 0 || StringUtils.isEmpty(param.get("queues")) || StringUtils.isEmpty(param.get("query"))) { return null; } List<String> strings = Arrays.asList(param.get("queues").toString().split(",")); //将数据库中的队列和队列解释查询 List<Map<String,String>> queueResult = rabbitmqMonitorMapper.queryQueueResult(strings); String pattern = "yyyy-MM-dd"; String startTime = null; String endTime = null; try { //本周第一天 startTime = DateUtils.getWeekStart(); //本周最后一天 endTime = DateUtils.getWeekEnd(); } catch (Exception e) { e.printStackTrace(); } log.info(startTime); log.info(endTime); //转为utc时间 String starUTC = DateUtils.dateFormat(startTime, pattern); String endUTC = DateUtils.dateFormat(endTime, pattern); //设置步长为一天一次 String step = "1d"; log.info("step: " + step); String queryQueue = "\""; for (Map<String, String> queue : queueResult) { queryQueue += (queue.get("queueName") + "|"); } queryQueue = "{queue=~" + queryQueue.substring(0, queryQueue.length() - 1) + "\"" + "}"; String query = param.get("query").toString() + queryQueue; log.info("query:{}", query); processResult.setData(rabbitMQUtils.readPrometheusByTimeOfRabbitMonitoring(queueResult, query, starUTC, endUTC, step)); return processResult; }catch (Exception e){ log.error("查询rabbitqm{每周}异常!!!",e); processResult.setResultStat(ProcessResult.ERROR); processResult.setMess("查询异常"); return processResult; } } @Override public Map<String, Map<String, Long>> readPrometheusByMouth(String[] queues, String query, String time) { List<String> strings = Arrays.asList(queues); String pattern = "yyyy-MM-dd HH:mm:ss"; String patternTime = "yyyy-MM"; //根据给定月份查询 Long timeLong = DateUtils.string2Date(time, patternTime); Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date(timeLong)); //设置开始时间为第一天 calendar.set(Calendar.HOUR, calendar.get(Calendar.HOUR) + 23); // 分 calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE)+59); // 秒 calendar.set(Calendar.SECOND, calendar.get(Calendar.SECOND)+59); calendar.set(Calendar.DAY_OF_MONTH, 1); String startTime = DateUtils.longDate2String(calendar.getTime().getTime(), pattern); //设置结束时间为当月最后一天 calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); //转为utc时间 String endTime = DateUtils.longDate2String(calendar.getTime().getTime(), pattern); String starUTC = DateUtils.dateFormat(startTime, pattern); String endUTC = DateUtils.dateFormat(endTime, pattern); //设置步长为一天一次 String step = "1d"; log.info("step: " + step); return rabbitMQUtils.readPrometheusByTime(strings, query, starUTC, endUTC, step); } @Override public ProcessResult readPrometheusByMouthPost(@RequestBody Map<String, Object> param) { log.info("查询rabbitmq监控指标入参:{}", JSONObject.toJSONString(param)); ProcessResult processResult = new ProcessResult(); try { if (param == null || param.size() <= 0 || StringUtils.isEmpty(param.get("time")) || StringUtils.isEmpty(param.get("queues")) || StringUtils.isEmpty(param.get("query"))) { return null; } List<String> strings = Arrays.asList(param.get("queues").toString().split(",")); //将数据库中的队列和队列解释查询 List<Map<String,String>> queueResult = rabbitmqMonitorMapper.queryQueueResult(strings); String pattern = "yyyy-MM-dd HH:mm:ss"; String patternTime = "yyyy-MM"; //根据给定月份查询 Long timeLong = DateUtils.string2Date(param.get("time").toString(), patternTime); Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date(timeLong)); //设置开始时间为第一天 calendar.set(Calendar.HOUR, calendar.get(Calendar.HOUR) + 23); // 分 calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE) + 59); // 秒 calendar.set(Calendar.SECOND, calendar.get(Calendar.SECOND) + 59); calendar.set(Calendar.DAY_OF_MONTH, 1); String startTime = DateUtils.longDate2String(calendar.getTime().getTime(), pattern); //设置结束时间为当月最后一天 calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); //转为utc时间 String endTime = DateUtils.longDate2String(calendar.getTime().getTime(), pattern); String starUTC = DateUtils.dateFormat(startTime, pattern); String endUTC = DateUtils.dateFormat(endTime, pattern); //设置步长为一天一次 String step = "1d"; log.info("step: " + step); String queryQueue = "\""; for (Map<String, String> queue : queueResult) { queryQueue += (queue.get("queueName") + "|"); } queryQueue = "{queue=~" + queryQueue.substring(0, queryQueue.length() - 1) + "\"" + "}"; String query = param.get("query").toString() + queryQueue; log.info("query:{}", query); processResult.setData(rabbitMQUtils.readPrometheusByTimeOfRabbitMonitoring(queueResult, query, starUTC, endUTC, step)); return processResult; }catch (Exception e){ log.error("查询rabbitmq监控{每月}异常!!!",e); processResult.setResultStat(ProcessResult.ERROR); processResult.setMess("查询异常"); return processResult; } } @Override public Map<String, Map<String, Long>> readPrometheusByYear(String[] queues, String query, String time) { List<Map<String, Map<String, Long>>> list = new ArrayList<>(); Map<String, Map<String, Long>> resultMap = new HashMap<>(); List<String> queuesList = Arrays.asList(queues); String pattern = "yyyy-MM-dd HH:mm:ss"; int year = Integer.parseInt(time); for (int mouth = 1; mouth < 13; mouth++) { //循环调用service 时间为每月最后一天 String lastDayOfMonth = DateUtils.getLastDayOfMonth(year, mouth); log.info("lastDayOfMonth: "+lastDayOfMonth); String timeUTC = DateUtils.dateFormat(lastDayOfMonth, pattern); Map<String, Map<String, Long>> map = rabbitMQUtils.readPrometheusByYear(queuesList, query, timeUTC); list.add(map); } rabbitMQUtils.analysisResult(queuesList, list, resultMap); //System.out.println(resultMap); return resultMap; } @Override public ProcessResult readPrometheusByYearPost(@RequestBody Map<String, Object> param) { log.info("查询rabbitmq监控指标入参:{}", JSONObject.toJSONString(param)); ProcessResult processResult = new ProcessResult(); try { if (param == null || param.size() <= 0 || StringUtils.isEmpty(param.get("time")) || StringUtils.isEmpty(param.get("queues")) || StringUtils.isEmpty(param.get("query"))) { return null; } List<Map<String, Map<String, Long>>> list = new ArrayList<>(); Map<String, Map<String, Long>> resultMap = new HashMap<>(); List<String> queuesList = Arrays.asList(param.get("queues").toString().split(",")); //将数据库中的队列和队列解释查询 List<Map<String,String>> queueResult = rabbitmqMonitorMapper.queryQueueResult(queuesList); String pattern = "yyyy-MM-dd HH:mm:ss"; int year = Integer.parseInt(param.get("time").toString()); String queryQueue = "\""; for (Map<String, String> queue : queueResult) { queryQueue += (queue.get("queueName") + "|"); } queryQueue = "{queue=~" + queryQueue.substring(0, queryQueue.length() - 1) + "\"" + "}"; String query = param.get("query").toString() + queryQueue; log.info("query:{}", query); for (int mouth = 1; mouth < 13; mouth++) { //循环调用service 时间为每月最后一天 String lastDayOfMonth = DateUtils.getLastDayOfMonth(year, mouth); log.info("lastDayOfMonth: " + lastDayOfMonth); String timeUTC = DateUtils.dateFormat(lastDayOfMonth, pattern); Map<String, Map<String, Long>> map = rabbitMQUtils.readPrometheusByYearPost(queueResult, query, timeUTC); list.add(map); } rabbitMQUtils.analysisResultPost(queueResult, list, resultMap); processResult.setData(resultMap); return processResult; }catch (Exception e){ log.error("查询rabbitmq{每年}发生异常!!!",e); processResult.setMess("查询异常"); processResult.setResultStat(ProcessResult.ERROR); return processResult; } }}
package com.chinatower.product.monitoring.service;import java.util.Calendar;import java.util.Date;import java.util.Map;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RestController;import com.alibaba.fastjson.JSONObject;import com.chinatower.product.monitoring.api.RedisMonitorAPI;import com.chinatower.product.monitoring.common.DateUtils;import com.chinatower.product.monitoring.common.RedisUtils;import com.chinatower.product.monitoring.entity.RedisLog;import com.chinatower.product.monitoring.response.ProcessResult;import com.chinatower.product.monitoring.response.ResultPage;import com.chinatower.provider.call.feign.redis.StringApi;import com.chinatower.provider.call.feign.redis.StringRedisModel;@RestController@Slf4jpublic class RedisMonitorService implements RedisMonitorAPI { @Autowired private RedisUtils redisUtils; @Autowired StringApi strApi; @Override public ResultPage<RedisLog> readEs(String startTime, String endTime, Integer page, Integer size, String queueName) { String pattern = "yyyy-MM-dd.HH"; if (startTime == null||startTime.equals("")){ startTime = "2020-04-30.00"; } if (endTime == null||endTime.equals("")){ Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); calendar.set(Calendar.HOUR, calendar.get(Calendar.HOUR) + 1); endTime = DateUtils.longDate2String(calendar.getTime().getTime(), pattern); } if (page == null){ page = 1; } if (size == null){ size = 20; }// if (page*size>10000){// throw new RuntimeException("ES返回数据错误,建议缩小粒度");// } String start = DateUtils.dateFormat(startTime,pattern); String end = DateUtils.dateFormat(endTime,pattern); log.info("startUTC: " + start); log.info("endUTC: " + end); if (queueName==null||"null".equals(queueName)||"".equals(queueName)){ return redisUtils.readEsByTime(start,end,page,size); } return redisUtils.readEs(start,end,page,size,queueName); } @Override public ProcessResult getRedisKeys( String pattern,String system) { ProcessResult result=new ProcessResult(ProcessResult.SUCCESS,"",null); StringRedisModel model =new StringRedisModel(); if(null!=system){ model.setSystem(system); } if(null!=pattern){ model.setPattern(pattern); } try { ModelMap map= strApi.getRedis(model); result.setData(map); } catch (Exception e) { result.setMess("操作失败"); result.setResultStat("ERROR"); e.printStackTrace(); } return result; } @Override public ProcessResult getValueByKeys(String key,String system) { ProcessResult result=new ProcessResult(ProcessResult.SUCCESS,"",null); StringRedisModel model =new StringRedisModel(); if(null!=key){ model.setKey(key); }else{ result.setMess("操作失败,key不能为空"); result.setResultStat("ERROR"); return result; } if(null!=system){ model.setSystem(system); } try {// ModelMap map= strApi.get(model); ModelMap map= strApi.getValueByKey(model); result.setData(map); } catch (Exception e) { result.setMess("操作失败"); result.setResultStat("ERROR"); e.printStackTrace(); } return result; } }
package com.chinatower.product.monitoring.service;import io.jsonwebtoken.Claims;import io.jsonwebtoken.Jws;import java.util.List;import java.util.Map;import javax.servlet.http.HttpServletRequest;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RestController;import com.chinatower.product.monitoring.api.ServiceEndpointAPI;import com.chinatower.product.monitoring.entity.ServiceEndpointBean;import com.chinatower.product.monitoring.jwt.JwtUtil;import com.chinatower.product.monitoring.mapper.ServiceEndpointMapper;import com.chinatower.product.monitoring.response.ProcessResult;@RestController@Slf4jpublic class ServiceEndpointService implements ServiceEndpointAPI{ @Autowired private ServiceEndpointMapper serviceEndpointMapper; @Override public ProcessResult saveEndpoint(ServiceEndpointBean bean, HttpServletRequest request) { // TODO Auto-generated method stub serviceEndpointMapper.saveEndpoint(bean); return new ProcessResult(ProcessResult.SUCCESS,"",null); } @Override public ProcessResult updateEndpoint(ServiceEndpointBean bean, HttpServletRequest request) { // TODO Auto-generated method stub serviceEndpointMapper.updateEndpoint(bean); return new ProcessResult(ProcessResult.SUCCESS,"",null); } @Override public ProcessResult deleteEndpoint(long id, HttpServletRequest request) { // TODO Auto-generated method stub serviceEndpointMapper.deleteEndpoint(id); return new ProcessResult(ProcessResult.SUCCESS,"",null); } @Override public ProcessResult findEndpoint(@RequestBody Map<String, Object> reqMap, HttpServletRequest request) { String token=request.getHeader("accessToken"); Jws<Claims> claims = JwtUtil.parseJWT(token); String empId = claims.getBody().getId(); empId=empId.equals("6")?"":empId; reqMap.put("empId", empId); List<ServiceEndpointBean> list=serviceEndpointMapper.findEndpoint(reqMap); return new ProcessResult(ProcessResult.SUCCESS,"操作成功",list); }}
package com.chinatower.product.monitoring.service;import io.micrometer.core.instrument.Gauge;import io.micrometer.core.instrument.MeterRegistry;import java.io.BufferedInputStream;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.HttpURLConnection;import java.net.URL;import java.net.URLEncoder;import java.util.ArrayList;import java.util.List;import java.util.Optional;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import net.sf.json.util.JSONTokener;import net.sf.json.xml.XMLSerializer;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.web.bind.annotation.RestController;import com.alibaba.fastjson.JSONArray;import com.alibaba.fastjson.JSONObject;import com.chinatower.product.monitoring.api.ServiceInstanceInventoryAPI;import com.chinatower.product.monitoring.entity.EurekaInstanceBean;import com.chinatower.product.monitoring.entity.ServiceEndpointBean;import com.chinatower.product.monitoring.entity.SysProjectServiceBean;import com.chinatower.product.monitoring.mapper.EurekaInstanceMapper;import com.chinatower.product.monitoring.mapper.SysProjectInfoMapper;import com.chinatower.product.monitoring.response.ProcessResult;/** * 实例信息 * @author FUPING * */@RestControllerpublic class ServiceInstanceInventoryService implements ServiceInstanceInventoryAPI{ private static final Logger logger = LoggerFactory.getLogger("TransLog"); @Autowired private MeterRegistry registry; @Autowired private EurekaInstanceMapper eurekaInstanceMapper; @Autowired private SysProjectInfoMapper sysProjectInfoMapper; @Value("${monitor.getEurekaInstanceStatusUrl}") private String getEurekaInstanceStatusUrl; @Override public ProcessResult getServiceInstanceStatusFromEureka() { List<EurekaInstanceBean> listInstance=new ArrayList<EurekaInstanceBean>(); if(getEurekaInstanceStatusUrl.indexOf(",")!=-1){ String[] strarray=getEurekaInstanceStatusUrl.split(","); for(int i=0;i<strarray.length;i++){ List<EurekaInstanceBean> list= sysInstanceStatus(strarray[i]); if(null!=list&&list.size()>0){ listInstance.addAll(list); } } }else{ listInstance=sysInstanceStatus(getEurekaInstanceStatusUrl); } if(null!=listInstance&&listInstance.size()>0){ for(EurekaInstanceBean instance:listInstance){ List<EurekaInstanceBean> dbData= eurekaInstanceMapper.getByIpAndPort(instance); Gauge gauge1 = Gauge.builder("monitoring_eureka_instance_guage", instance, s -> (double) instance.getLastDirtyTimestamp()) .tag("eureka_instance_Name", Optional.ofNullable(instance.getServiceId()).isPresent() ? Optional.ofNullable(instance.getServiceId()).get() : "") .tag("eureka_instance_ActionType", Optional.ofNullable(instance.getActionType()).isPresent() ? Optional.ofNullable(instance.getActionType()).get() : "") .tag("eureka_instance_App", Optional.ofNullable(instance.getApp()).isPresent() ? Optional.ofNullable(instance.getApp()).get() : "") .tag("eureka_instance_CountryId", Optional.ofNullable(instance.getCountryId()).isPresent() ? Optional.ofNullable(instance.getCountryId()).get() : "") .tag("eureka_instance_DruidUrl", Optional.ofNullable(instance.getDruidUrl()).isPresent() ? Optional.ofNullable(instance.getDruidUrl()).get() : "") .tag("eureka_instance_HealthCheckUrl", Optional.ofNullable(instance.getHealthCheckUrl()).isPresent() ? Optional.ofNullable(instance.getHealthCheckUrl()).get() : "") .tag("eureka_instance_HomePageUrl", Optional.ofNullable(instance.getHomePageUrl()).isPresent() ? Optional.ofNullable(instance.getHomePageUrl()).get() : "") .tag("eureka_instance_HostName", Optional.ofNullable(instance.getHostName()).isPresent() ? Optional.ofNullable(instance.getHostName()).get() : "") .tag("eureka_instance_InstanceId", Optional.ofNullable(instance.getInstanceId()).isPresent() ? Optional.ofNullable(instance.getInstanceId()).get() : "") .tag("eureka_instance_IpAddr", Optional.ofNullable(instance.getIpAddr()).isPresent() ? Optional.ofNullable(instance.getIpAddr()).get() : "") .tag("eureka_instance_IsCoordinatingDiscoveryServer", instance.getIsCoordinatingDiscoveryServer()) .description("monitoring_eureka_instance_guage") .register(registry); if(dbData.size()>0){ if(dbData.size()==1){ if (null==dbData.get(0).getSysServiceId()||dbData.get(0).getSysServiceId().trim().length()==0){ instance.setSysServiceId(dbData.get(0).getProject_id()); } if (null==dbData.get(0).getSkywalkingServiceName()||dbData.get(0).getSkywalkingServiceName().trim().length()==0){ instance.setSkywalkingServiceName(dbData.get(0).getVipAddress()); }else{ instance.setSkywalkingServiceName(instance.getVipAddress()); } eurekaInstanceMapper.update(instance); } }else{ String monitoring_service_name=instance.getVipAddress(); SysProjectServiceBean bean=sysProjectInfoMapper.getbyMonitoringServiceName(monitoring_service_name); if(null !=bean){ instance.setProject_id(bean.getProject_id()); } instance.setSkywalkingServiceName(monitoring_service_name); eurekaInstanceMapper.insert(instance); } } } return new ProcessResult(ProcessResult.SUCCESS,"",null); } public List<EurekaInstanceBean> sysInstanceStatus(String urlPath){ List<EurekaInstanceBean> listInstance=new ArrayList<EurekaInstanceBean>(); HttpURLConnection connection = null; BufferedReader reader = null; String line = null; JSONObject referJson =null; try { URL url = new URL(urlPath); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); StringBuilder result = new StringBuilder(); while ((line = reader.readLine()) != null) { result.append(line).append(System.getProperty("line.separator")); } XMLSerializer cacheXmlSerializer = new XMLSerializer(); net.sf.json.JSON referJsonResult = cacheXmlSerializer.read(result.toString()); referJson = JSONObject.parseObject(referJsonResult.toString()); JSONArray arr = referJson.getJSONArray("application"); for(int i=0;i<arr.size();i++){ JSONObject jsonObject = (JSONObject) arr.get(i); Object listArray = new JSONTokener(jsonObject.getString("instance")).nextValue();// if(listArray instanceof JSONObject){ if(listArray.toString().startsWith("{")){ JSONObject obj=jsonObject.getJSONObject("instance"); EurekaInstanceBean instance=JSONObject.toJavaObject(obj, EurekaInstanceBean.class); listInstance.add(instance); System.out.println(obj.get("ipAddr").toString()+":"+obj.get("port").toString()+":"+obj.get("status").toString()); } else if(listArray.toString().startsWith("[{")){// if(listArray instanceof JSONArray){ JSONArray arrInstance = jsonObject.getJSONArray("instance"); for(int j=0;j<arrInstance.size();j++){ JSONObject obj = (JSONObject) arrInstance.get(j); EurekaInstanceBean instance=JSONObject.toJavaObject(obj, EurekaInstanceBean.class); listInstance.add(instance); System.out.println(obj.get("ipAddr").toString()+":"+obj.get("port").toString()+":"+obj.get("status").toString()); } } } } } catch (IOException e) { e.printStackTrace(); } finally { try { if( reader!=null){ reader.close(); } } catch (IOException e) { e.printStackTrace(); } if(null!=connection){ connection.disconnect(); } } return listInstance; } @Override public ProcessResult downloadInstanceDumpFile(HttpServletRequest request, HttpServletResponse response){ ProcessResult result=new ProcessResult(); String ipAddr=request.getParameter("ipAddr"); String port=request.getParameter("port"); String type=request.getParameter("type");//heapdump,threaddump if(null==ipAddr||null==port||null==type){ result.setResultStat(ProcessResult.ERROR); result.setMess("入参错误,ipAddr、port、type不能为空"); return result; } if(!type.equals("heapdump")&& !type.equals("threaddump")){ result.setResultStat(ProcessResult.ERROR); result.setMess("入参错误,type类型为heapdump或threaddump"); return result; } String remoteFileUrl = "http://"+ipAddr+":"+port+"/metrics/"+type;// "http://123.126.41.204:20401/metrics/heapdump"; if (null == remoteFileUrl || remoteFileUrl.length() == 0) { throw new RuntimeException("remoteFileUrl is invalid!"); } try{ URL url = new URL(remoteFileUrl); BufferedInputStream in = null; in = new BufferedInputStream(url.openStream()); response.reset(); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=\"" + URLEncoder.encode(type, "UTF-8") + "\""); int i; while ((i = in.read()) != -1) { response.getOutputStream().write(i); } in.close(); response.getOutputStream().close(); }catch (Exception e1) {// try {// response.setContentType("application/json; charset=utf-8");// response.setHeader("Accept-Ranges", "bytes");// PrintWriter out = response.getWriter();// out.print("下载失败,服务器网络不通或者此应用没对接Prometheus,无法下载"+type+"文件");// } catch (IOException e) {// e.printStackTrace();// } result.setResultStat(ProcessResult.ERROR); result.setMess("下载失败,服务器网络不通或者此应用没对接Prometheus,无法下载"+type+"文件"); return result; } return new ProcessResult(ProcessResult.SUCCESS,"操作成功",null); } @Override public ProcessResult getInstancesInfoDetails(String sysServiceId) { List<EurekaInstanceBean> list=eurekaInstanceMapper.getInstancesInByServiceId(sysServiceId); return new ProcessResult(ProcessResult.SUCCESS,"操作成功",list); } }
package com.chinatower.product.monitoring.service;import com.chinatower.product.monitoring.common.*;import com.chinatower.product.monitoring.common.trace.*;import com.chinatower.product.monitoring.entity.ServiceEndpointBean;import com.chinatower.product.monitoring.entity.SysProjectServiceBean;import com.chinatower.product.monitoring.mapper.ServiceEndpointMapper;import io.jsonwebtoken.Claims;import io.jsonwebtoken.Jws;import java.rmi.UnexpectedException;import java.text.SimpleDateFormat;import java.util.*;import javax.servlet.http.HttpServletRequest;import io.swagger.annotations.Api;import io.swagger.annotations.ApiOperation;import org.apache.commons.lang.StringUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import com.alibaba.fastjson.JSONObject;import com.chinatower.product.monitoring.api.SkyWalkingAPI;import com.chinatower.product.monitoring.jwt.JwtUtil;import com.chinatower.product.monitoring.mapper.SkyWalkingMapper;import com.chinatower.product.monitoring.util.DataUtils;import com.chinatower.product.monitoring.util.GraphqlScript;import com.chinatower.product.monitoring.util.HttpClientUtil;@Api("SW模块接口")@RestControllerpublic class SkyWalkingService implements SkyWalkingAPI { private static final Logger logger = LoggerFactory.getLogger("TransLog"); @Autowired private SkyWalkingMapper skyWalkingMapper; @Value("${monitor.skywalkingUrl}") private String skywalkingApiUrl; @Autowired private StatsUtils statsUtils; @Autowired private ServiceEndpointMapper serviceEndpointMapper; @Override public String getHomeData(@RequestBody Map<String, Object> reqMap,HttpServletRequest request) { String token=request.getHeader("accessToken"); Jws<Claims> claims = JwtUtil.parseJWT(token); String empId = claims.getBody().getId(); logger.info("token========"+token); logger.info("empId===="+empId); empId=empId.equals("6")?"":empId; Map<String, String> result = new HashMap<String, String>(); if(!reqMap.containsKey("start")){ result.put("status","ERROR"); result.put("message","日期开始时间不能为空"); JSONObject json = (JSONObject) JSONObject.toJSON(result); return json.toJSONString(); } if(!reqMap.containsKey("end")){ result.put("status","ERROR"); result.put("message","日期结束时间不能为空"); JSONObject json = (JSONObject) JSONObject.toJSON(result); return json.toJSONString(); } // month:"MONTH",//年月 // day:"DAY",//年月日 // hour:"HOUR",//年月日小时 // minute:"MINUTE",// 年月日小时分钟 // second:"SECOND",// ...秒 if(!reqMap.containsKey("step")){ result.put("status","ERROR"); result.put("message","日期类型不能为空"); JSONObject json = (JSONObject) JSONObject.toJSON(result); return json.toJSONString(); } String start = reqMap.get("start").toString(); String end = reqMap.get("end").toString(); String step = reqMap.get("step").toString(); logger.info(start+"--------------------------------------------"+end); List<Map<String,Object>> systemInfo = skyWalkingMapper.getAllSystemInfo(empId); List<Map<String,Object>> serviceInfo = skyWalkingMapper.getAllServiceInfo(empId); for(Map<String,Object> sysMap :systemInfo){ String project_id = (String) sysMap.get("project_id"); List<Map<String,Object>> list = new ArrayList<Map<String,Object>> (); for(Map<String,Object> serviceMap : serviceInfo){ String parent_project_id = (String) serviceMap.get("parent_project_id"); if(project_id.equals(parent_project_id)){ list.add(serviceMap); } } sysMap.put("service",list); } Map<String,Object> serviceInfo1 = DataUtils.getSystemInfo(systemInfo, skywalkingApiUrl, start, end,step); JSONObject json = (JSONObject) JSONObject.toJSON(serviceInfo1); return json.toJSONString(); } @Override public String getServiceTopInfo(@RequestBody Map<String, Object> reqMap) { Map<String, String> result = new HashMap<String, String>(); if(!reqMap.containsKey("start")){ result.put("status","ERROR"); result.put("message","日期开始时间不能为空"); JSONObject json = (JSONObject) JSONObject.toJSON(result); return json.toJSONString(); } if(!reqMap.containsKey("end")){ result.put("status","ERROR"); result.put("message","日期结束时间不能为空"); JSONObject json = (JSONObject) JSONObject.toJSON(result); return json.toJSONString(); } if(!reqMap.containsKey("step")){ result.put("status","ERROR"); result.put("message","日期类型不能为空"); JSONObject json = (JSONObject) JSONObject.toJSON(result); return json.toJSONString(); } if(!reqMap.containsKey("sysId")){ result.put("status","ERROR"); result.put("message","系统ID不能为空"); JSONObject json = (JSONObject) JSONObject.toJSON(result); return json.toJSONString(); } String sysId = reqMap.get("sysId").toString(); String start = reqMap.get("start").toString(); String end = reqMap.get("end").toString(); String step = reqMap.get("step").toString(); //SELECT * FROM sys_project_info WHERE parent_project_id = ? AND monitoring_status = 1 List<Map<String,Object>> list = skyWalkingMapper.getServiceInfoBySystemId(sysId); list.forEach(s->{ String project_id = (String)s.get("project_id"); Calendar instance = Calendar.getInstance(); instance.set(Calendar.HOUR_OF_DAY,-24); TraceQueryCondition condition=new TraceQueryCondition(); SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH mm"); Pagination pagination = new Pagination(); pagination.setPageNum(1); pagination.setPageSize(15); pagination.setNeedTotal(true); condition.setPaging(pagination); Duration duration = new Duration(); duration.setStart("2019-01-01 00 00");// duration.setStart(format.format(instance.getTime())); duration.setEnd(format.format(Calendar.getInstance().getTime())); duration.setStep(Step.MINUTE); condition.setQueryDuration(duration); condition.setQueryOrder(QueryOrder.BY_DURATION); condition.setTraceState(TraceState.ALL); HashMap<String, Object> param = new HashMap<>(); param.put("project_id",project_id); List<ServiceEndpointBean> beanList = serviceEndpointMapper.findEndpoint(param); long all= 0,err= 0,suc = 0; for (ServiceEndpointBean serviceEndpointBean : beanList) { condition.setEndpointName(serviceEndpointBean.getEndpoint_en()); Map map = null; try { map = statsUtils.readTraceStatEsUtils1(condition); } catch (UnexpectedException e) { e.printStackTrace(); } try{all+= (long) map.get("allTaltal");}catch (Exception e){all=0;} try{err+= (long) map.get("errTaltal");}catch (Exception e){err=0;} try{suc+= (long) map.get("sucTaltal");}catch (Exception e){suc=0;} } s.put("allTaltal",all); s.put("errTaltal",err); s.put("sucTaltal",suc); }); String servcieResultStr = GraphqlScript.getAllServicesGraphql(start,end,step); String resultServiceStr = HttpClientUtil.doPostJson(skywalkingApiUrl,servcieResultStr); Map<String,Object> swMap = JSONObject.parseObject(resultServiceStr); if(swMap.containsKey("errors")){ Map<String,Object> map = new HashMap<>(); map.put("status","ERROR"); map.put("message",swMap.get("errors")); JSONObject json = (JSONObject) JSONObject.toJSON(map); return json.toJSONString(); } Map<String,Object> data = (Map<String, Object>) swMap.get("data"); List<Map<String,Object>> swlist = (List<Map<String, Object>>) data.get("getAllServices"); Map<String, Object> dataMap = DataUtils.ComposeServiceInfo(list, swlist, start, end, step); JSONObject json = (JSONObject) JSONObject.toJSON(dataMap); return json.toJSONString(); } @Override public String getEndpointInfo(@RequestBody Map<String, Object> reqMap) { Map<String, String> result = new HashMap<String, String>(); if(!reqMap.containsKey("start")){ result.put("status","ERROR"); result.put("message","日期开始时间不能为空"); JSONObject json = (JSONObject) JSONObject.toJSON(result); return json.toJSONString(); } if(!reqMap.containsKey("end")){ result.put("status","ERROR"); result.put("message","日期结束时间不能为空"); JSONObject json = (JSONObject) JSONObject.toJSON(result); return json.toJSONString(); } if(!reqMap.containsKey("step")){ result.put("status","ERROR"); result.put("message","日期类型不能为空"); JSONObject json = (JSONObject) JSONObject.toJSON(result); return json.toJSONString(); } if(!reqMap.containsKey("dbServiceId")){ result.put("status","ERROR"); result.put("message","服务ID不能为空"); JSONObject json = (JSONObject) JSONObject.toJSON(result); return json.toJSONString(); } if(!reqMap.containsKey("serviceId")){ result.put("status","ERROR"); result.put("message","Skywalking ID不能为空"); JSONObject json = (JSONObject) JSONObject.toJSON(result); return json.toJSONString(); } String start = reqMap.get("start").toString(); String end = reqMap.get("end").toString(); String step = reqMap.get("step").toString(); String dbServiceId = reqMap.get("dbServiceId").toString(); String serviceId = reqMap.get("serviceId").toString(); logger.info("EndpointInfo"+start+"-------------------------"+end); // SELECT * FROM sys_service_endpoint WHERE project_id = #{serviceId} List<Map<String,Object>> endpointList = skyWalkingMapper.getEndPointByServiceId(dbServiceId); StringBuffer hql = new StringBuffer(); hql.append("query{"); hql.append(GraphqlScript.searchEndpoint(serviceId,"endpointInfo")); hql.append("}"); Map<String,String> map = new HashMap<String,String>(); map.put("query",hql.toString()); String graphql = JSONObject.toJSONString(map); String resultStr = HttpClientUtil.doPostJson(skywalkingApiUrl,graphql); JSONObject endpointJson = JSONObject.parseObject(resultStr); Map<String,Object> endpointMap = endpointJson; Map<String,Object> dataMap = (Map<String, Object>) endpointMap.get("data"); List<Map<String,Object>> swMap = (List<Map<String, Object>>) dataMap.get("endpointInfo"); Map<String,Object> resultData = DataUtils.ComposeEndpointInfo(skywalkingApiUrl,start,end,step,endpointList,swMap); JSONObject json = (JSONObject) JSONObject.toJSON(resultData); return json.toJSONString(); } @Override public String getInstancesInfos(@RequestBody Map<String, Object> reqMap) { Map<String, String> result = new HashMap<String, String>(); if(!reqMap.containsKey("start")){ result.put("status","ERROR"); result.put("message","日期开始时间不能为空"); JSONObject json = (JSONObject) JSONObject.toJSON(result); return json.toJSONString(); } if(!reqMap.containsKey("end")){ result.put("status","ERROR"); result.put("message","日期结束时间不能为空"); JSONObject json = (JSONObject) JSONObject.toJSON(result); return json.toJSONString(); } if(!reqMap.containsKey("step")){ result.put("status","ERROR"); result.put("message","日期类型不能为空"); JSONObject json = (JSONObject) JSONObject.toJSON(result); return json.toJSONString(); } if(!reqMap.containsKey("dbServiceId")){ result.put("status","ERROR"); result.put("message","服务ID不能为空"); JSONObject json = (JSONObject) JSONObject.toJSON(result); return json.toJSONString(); } if(!reqMap.containsKey("swServiceId")){ result.put("status","ERROR"); result.put("message","Skywalking ID不能为空"); JSONObject json = (JSONObject) JSONObject.toJSON(result); return json.toJSONString(); } String start = reqMap.get("start").toString(); String end = reqMap.get("end").toString(); String step = reqMap.get("step").toString(); String dbServiceId = reqMap.get("dbServiceId").toString(); String swServiceId = reqMap.get("swServiceId").toString(); List<Map<String,Object>> dbInstancesList = skyWalkingMapper.getInstancesInfo(dbServiceId); StringBuffer hql = new StringBuffer(); hql.append("query{"); hql.append(GraphqlScript.getServiceInstances(start,end,step,swServiceId,"InstancesInfo")); hql.append("}"); Map<String, String> map = new HashMap<String, String>(); map.put("query",hql.toString()); JSONObject hqlJson = (JSONObject) JSONObject.toJSON(map); String resultStr = HttpClientUtil.doPostJson(skywalkingApiUrl,hqlJson.toJSONString()); JSONObject resultJson = JSONObject.parseObject(resultStr); Map<String,Object> data = (Map<String, Object>) resultJson.get("data"); List<Map<String,Object>> swInstancesInfo = (List<Map<String, Object>>) data.get("InstancesInfo"); Map<String,Object> resultMap = DataUtils.ComposeInstancesInfo(dbInstancesList,swInstancesInfo); reqMap.put("swServiceId",swServiceId); JSONObject json = (JSONObject) JSONObject.toJSON(resultMap); return json.toJSONString(); } @Override public String getInstancesInfoDetails(@RequestBody Map<String, Object> reqMap) { Map<String, String> result = new HashMap<String, String>(); if(!reqMap.containsKey("start")){ result.put("status","ERROR"); result.put("message","日期开始时间不能为空"); JSONObject json = (JSONObject) JSONObject.toJSON(result); return json.toJSONString(); } if(!reqMap.containsKey("end")){ result.put("status","ERROR"); result.put("message","日期结束时间不能为空"); JSONObject json = (JSONObject) JSONObject.toJSON(result); return json.toJSONString(); } if(!reqMap.containsKey("step")){ result.put("status","ERROR"); result.put("message","日期类型不能为空"); JSONObject json = (JSONObject) JSONObject.toJSON(result); return json.toJSONString(); } if(!reqMap.containsKey("swInstanceId")){ result.put("status","ERROR"); result.put("message","实例ID不能为空"); JSONObject json = (JSONObject) JSONObject.toJSON(result); return json.toJSONString(); } if(!reqMap.containsKey("swServiceId")){ result.put("status","ERROR"); result.put("message","Skywalking ID不能为空"); JSONObject json = (JSONObject) JSONObject.toJSON(result); return json.toJSONString(); } String start = reqMap.get("start").toString(); String end = reqMap.get("end").toString(); String step = reqMap.get("step").toString(); String swServiceId = reqMap.get("swServiceId").toString(); String swInstanceId= reqMap.get("swInstanceId").toString(); JSONObject resultJson = DataUtils.ComposeInstanceDetails(start,end,step,swServiceId,swInstanceId,skywalkingApiUrl); return resultJson.toJSONString(); } @ApiOperation("获取trace链路span统计数据") @Override public List getTraceStats( @RequestParam(name = "projectId") String projectId,// @RequestParam(name = "startSecondTB",required = false) Long startSecondTB,// @RequestParam(name = "endSecondTB",required = false)Long endSecondTB,// @RequestParam(name = "minDuration",required = false)Long minDuration,// @RequestParam(name = "maxDuration",required = false)Long maxDuration, @RequestParam(name = "start",required = false)String start, @RequestParam(name = "end",required = false)String end,// @RequestParam(name = "endpointName",required = false)String endpointName,// @RequestParam(name = "serviceId",required = false)Integer serviceId,// @RequestParam(name = "serviceInstanceId",required = false)Integer serviceInstanceId,// @RequestParam(name = "endpointId",required = false)Integer endpointId,// @RequestParam(name = "traceId",required = false)String traceId,// @RequestParam(name = "limit",required = false)Integer limit,// @RequestParam(name = "from",required = false)Integer from, @RequestParam(name = "traceState",required = false)String traceState// @RequestParam(name = "queryOrder",required = false)String queryOrder ) { Calendar instance = Calendar.getInstance(); instance.set(Calendar.HOUR_OF_DAY,-24); TraceQueryCondition condition=new TraceQueryCondition(); SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH mm");// condition.setEndpointId();// condition.setMaxTraceDuration();// condition.setMinTraceDuration(); Pagination pagination = new Pagination(); pagination.setPageNum(1); pagination.setPageSize(15); pagination.setNeedTotal(true); condition.setPaging(pagination); Duration duration = new Duration(); if(start!=null&&!"".equals(start))// duration.setStart(format.format(start)); duration.setStart(start); else duration.setStart(format.format(instance.getTime())); if(end!=null&&!"".equals(end))// duration.setEnd(format.format(end)); duration.setEnd(end); else duration.setEnd(format.format(Calendar.getInstance().getTime())); duration.setStep(Step.MINUTE); condition.setQueryDuration(duration); condition.setQueryOrder(QueryOrder.BY_DURATION);// condition.setServiceId();// condition.setServiceInstanceId();// condition.setTraceId(); if(traceState!=null&&!"".equals(traceState)&&traceState.equals(TraceState.SUCCESS)) condition.setTraceState(TraceState.SUCCESS); else if(traceState!=null&&!"".equals(traceState)&&traceState.equals(TraceState.ERROR)) condition.setTraceState(TraceState.ERROR); else condition.setTraceState(TraceState.ALL); HashMap<String, Object> param = new HashMap<>(); param.put("project_id",projectId); List<ServiceEndpointBean> beanList = serviceEndpointMapper.findEndpoint(param); ArrayList<Object> objects = new ArrayList<>(); beanList.forEach(s->{ String endpoint_en = s.getEndpoint_en(); if(endpoint_en!=null&&!"".equals(endpoint_en)) condition.setEndpointName(endpoint_en); try { Map map = statsUtils.readTraceStatEsUtils(condition); map.put("endpointCn",s.getEndpoint_cn()); objects.add(map); } catch (UnexpectedException e) { e.printStackTrace(); } });// ResultPage<SegmentRecord> segmentRecordResultPage = statsUtils.readEs(1,20);// readEs(startSecondTB, endSecondTB, minDuration,// maxDuration, endpointName, serviceId, serviceInstanceId, endpointId, traceId,// limit, from, traceState, queryOrder);// if (segmentRecordResultPage!=null){// System.out.println(segmentRecordResultPage.getPageSize());// } return objects; }}
package com.chinatower.product.monitoring.service;import com.chinatower.product.monitoring.common.StatsUtils;import com.chinatower.product.monitoring.common.trace.*;import com.chinatower.product.monitoring.entity.*;import com.chinatower.product.monitoring.mapper.ServiceEndpointMapper;import io.jsonwebtoken.Claims;import io.jsonwebtoken.Jws;import io.micrometer.core.instrument.Counter;import io.micrometer.core.instrument.Gauge;import io.micrometer.core.instrument.MeterRegistry;import io.micrometer.core.instrument.Metrics;import java.rmi.UnexpectedException;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Arrays;import java.util.Calendar;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Set;import java.util.concurrent.atomic.AtomicInteger;import java.util.function.ToDoubleFunction;import javax.servlet.http.HttpServletRequest;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RestController;import com.chinatower.product.monitoring.api.SysprojectInfoAPI;import com.chinatower.product.monitoring.common.SWUtils;import com.chinatower.product.monitoring.jwt.JwtUtil;import com.chinatower.product.monitoring.mapper.SysProjectInfoMapper;import com.chinatower.product.monitoring.response.ProcessResult;/** * 服务信息 * @author FUPING * */@RestControllerpublic class SysProjectInfoService implements SysprojectInfoAPI{ private static final Logger logger = LoggerFactory.getLogger(SysProjectInfoService.class); @Autowired private SysProjectInfoMapper sysProjectInfoMapper; @Autowired private MeterRegistry registry; @Autowired private StatsUtils statsUtils; @Autowired private ServiceEndpointMapper serviceEndpointMapper; @Override public ProcessResult synProjectStatus() { ProcessResult result=new ProcessResult(ProcessResult.SUCCESS); List<SysProjectServiceBean> list=sysProjectInfoMapper.getProjectStatus(); for(SysProjectServiceBean bean:list){ sysProjectInfoMapper.updateServiceStatus(bean); } logger.info(result.toString()); return result; } @Override public ProcessResult synServiceStatus() { ProcessResult result=new ProcessResult(ProcessResult.SUCCESS); List<SysProjectServiceBean> listService=sysProjectInfoMapper.getServiceStatus(); for(SysProjectServiceBean bean:listService){ sysProjectInfoMapper.updateServiceStatus(bean); } List<SysProjectServiceBean> listProject=sysProjectInfoMapper.getProjectStatus(); for(SysProjectServiceBean bean:listProject){ sysProjectInfoMapper.updateServiceStatus(bean); } //删除1天以上没更新的数据 sysProjectInfoMapper.deletePastDueInstance(); logger.info(result.toString()); return result; } @Override public ProcessResult synSwServiceInstanceInventory(@RequestBody ServiceInstanceInventory serviceInstanceInventory) { Counter sw_service_instance = Metrics.counter("sw_service_instance"); sw_service_instance.increment();//加一 ProcessResult result=new ProcessResult(ProcessResult.SUCCESS); SWUtils.instanceMap.put(serviceInstanceInventory.getServiceId(), serviceInstanceInventory);// SWUtils.instanceMap.forEachKey(1,s->logger.info("当前实例Map包含:"+s.toString()));// logger.info("接收synSwServiceInstanceInventory+"+serviceInstanceInventory.getServiceId()); return result; } @Override public ProcessResult synSwMetric(@RequestBody Metric metric) {// logger.info(JSON.toJSONString(metric)); ProcessResult result=new ProcessResult(ProcessResult.SUCCESS); SWUtils.addOrUpdateMetricVlue(metric, registry); SWUtils.addOrUpdateMetricSum(metric, registry); return result; } @Override public ProcessResult synSwTrace(@RequestBody SegmentObject segmentObject) { Counter sw_span_type_counter = Metrics.counter("sw_span_type_counter", SWUtils.init("synSwTrace")); sw_span_type_counter.increment();//加一 ProcessResult result=new ProcessResult(ProcessResult.SUCCESS);// logger.info(segmentObject.toString()); SWUtils.addOrUpdateTrace(segmentObject, registry); return result; } // logger.info(metric.getClassName()+":"+metric.getValue());// Gauge test = Gauge.builder("monitoring_skywalking_metric_guage_value", metric, new ToDoubleFunction<Metric>() {// @Override// public double applyAsDouble(Metric value) {// return value.getValue();// }// })// .tag("className", metric.getClassName())// .register(registry);// Metric.Gauge // Gauge gauge2 = Gauge.builder("monitoring_skywalking_metric_guage_summation", metric, s -> metric.getSummation())//// .tag("summation", String.valueOf(metric.getSummation()))//// .tag("survivalTime", metric.getSurvivalTime())//// .tag("timeBucket", metric.getTimeBucket())// .tag("className", metric.getClassName())//// .tag("tag","summation")// .register(registry);// logger.info(result.toString()); @Deprecated public ProcessResult synSkyWalkingMetric(@RequestBody HashMap<String, String> map) {// logger.info(JSON.toJSONString(map)); ProcessResult result=new ProcessResult(ProcessResult.SUCCESS); Set<String> keySet = map.keySet(); ArrayList<MyTag> myTags = new ArrayList<MyTag>(); MyTag[] tags=new MyTag[map.size()]; int i = 0; for (String s : keySet) { myTags.add(new MyTag(s,map.get(s))); tags[i++]=new MyTag(s,map.get(s)); } AtomicInteger n = new AtomicInteger(0); Gauge gauge1 = Gauge.builder("monitoring_skywalking_metric_guage_" + map.get("className") + "_" + Calendar.getInstance().getTimeInMillis(), n, new ToDoubleFunction<AtomicInteger>() { @Override public double applyAsDouble(AtomicInteger value) { return value.get(); } }) .tags(Arrays.asList(tags)) .register(registry);// logger.info(result.toString()); return result; } @Override public ProcessResult getServiceStatus(@RequestBody Map<String, Object> reqMap) { ProcessResult result=new ProcessResult(ProcessResult.SUCCESS); if(!reqMap.containsKey("projectId")){ return new ProcessResult(ProcessResult.ERROR,"projectId不能为空",null); } String projectId=reqMap.get("projectId").toString(); SysProjectServiceBean bean= sysProjectInfoMapper.getServiceStatusByProjectId(projectId); result.setData(bean); return result; } @Override public ProcessResult getProjectList(HttpServletRequest request) { ProcessResult result=new ProcessResult(ProcessResult.SUCCESS); String token=request.getHeader("accessToken"); Jws<Claims> claims = JwtUtil.parseJWT(token); String empId = claims.getBody().getId(); logger.info("token========"+token); logger.info("empId===="+empId); empId=empId.equals("6")?"":empId; List<SysProjectServiceBean> listService=sysProjectInfoMapper.getProjectList(empId); result.setData(listService); return result; } @Override public ProcessResult getServiceList(HttpServletRequest request) { ProcessResult result=new ProcessResult(ProcessResult.SUCCESS); String token=request.getHeader("accessToken"); Jws<Claims> claims = JwtUtil.parseJWT(token); String empId = claims.getBody().getId(); logger.info("token========"+token); logger.info("empId===="+empId); empId=empId.equals("6")?"":empId; List<SysProjectServiceBean> listService=sysProjectInfoMapper.getProjectList(empId); List<SysProjectServiceBean> allService=new ArrayList<>(); for (SysProjectServiceBean sysProjectServiceBean : listService) { List<SysProjectServiceBean> serviceInfo = sysProjectInfoMapper.getServiceInfo(sysProjectServiceBean.getProject_id()); allService.addAll(serviceInfo); } result.setData(allService); return result; } @Override public ProcessResult getComponentList(HttpServletRequest request) { ProcessResult result=new ProcessResult(ProcessResult.SUCCESS); String token=request.getHeader("accessToken"); Jws<Claims> claims = JwtUtil.parseJWT(token); String empId = claims.getBody().getId(); logger.info("token========"+token); logger.info("empId===="+empId); empId=empId.equals("6")?"":empId; List<SysProjectServiceBean> listService=sysProjectInfoMapper.getComponentList(empId); result.setData(listService); return result; } @Override public ProcessResult getServiceInfo(@RequestBody Map<String, Object> reqMap,HttpServletRequest request) { ProcessResult result=new ProcessResult(ProcessResult.SUCCESS); if(!reqMap.containsKey("projectId")){ return new ProcessResult(ProcessResult.ERROR,"projectId不能为空",null); } String projectId=reqMap.get("projectId").toString();// String token=request.getHeader("accessToken");// Jws<Claims> claims = JwtUtil.parseJWT(token);// String empId = claims.getBody().getId(); List<SysProjectServiceBean> listService=sysProjectInfoMapper.getServiceInfo(projectId); result.setData(listService); return result; }// @Override// public ProcessResult findSysProjectInfo(SysProjectInfoBean bean,// @RequestParam("pageNum")Integer pageNum,@RequestParam("pageSize") Integer pageSize) {// PageHelper.startPage(pageNum, pageSize,"project_id desc");// List<SysProjectInfoBean> list=sysProjectInfoMapper.findSysProjectInfo(bean);// PageInfo<SysProjectInfoBean> pageInfo = new PageInfo<SysProjectInfoBean>(list);// logger.info(InterfaceLogUtil.rspTransLog("查询结果:"+pageInfo.toString()));// return new ProcessResult(ProcessResult.SUCCESS,"",pageInfo);// }// @Override// public ProcessResult findStatusGroupByProjectId() {// List<SysServiceStatusGroupBean> list=sysProjectInfoMapper.findStatusGroupByProjectId();// logger.info(InterfaceLogUtil.rspTransLog("查询结果:"+list.toString()));// return new ProcessResult(ProcessResult.SUCCESS,"",list);// }// @Override// public ProcessResult findAllServiceStatus() {// SysServiceStatusGroupBean bean=sysProjectInfoMapper.findAllServiceStatus();// logger.info(InterfaceLogUtil.rspTransLog("查询结果:"+bean.toString()));// return new ProcessResult(ProcessResult.SUCCESS,"",bean);// }// @Override// public ProcessResult findAllprojectServiceInstance() {// List<SysProjectServiceInstance> list=sysProjectInfoMapper.findAllprojectServiceInstance();// logger.info(InterfaceLogUtil.rspTransLog("查询结果:"+list.toString()));// return new ProcessResult(ProcessResult.SUCCESS,"",list);// }// }
package cn.chinatowercom.emp.service;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.MediaType;import org.springframework.stereotype.Service;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.bind.annotation.RestController;import cn.chinatowercom.common.response.RespResult;import cn.chinatowercom.emp.dao.SysEmpInfoMapper;import cn.chinatowercom.emp.model.SysEmpInfo;import cn.chinatowercom.framework.annotation.LoginRequired;import io.swagger.annotations.ApiImplicitParam;import io.swagger.annotations.ApiImplicitParams;import io.swagger.annotations.ApiOperation;import io.swagger.annotations.ApiResponse;import io.swagger.annotations.ApiResponses;import lombok.extern.slf4j.Slf4j;@Slf4j@RestController@RequestMapping("/emp")@Servicepublic class SysEmpInfoService { @Autowired private SysEmpInfoMapper sysEmpInfoDao; @ApiOperation(value = "查询项目下所有人", notes = "查询项目下所有人", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_VALUE, response = RespResult.class) @ApiResponses({ @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对"), @ApiResponse(code = 500, message = "应用服务内部错误") }) @ApiImplicitParams({ @ApiImplicitParam(name = "projectId", value = "项目id", required = true, paramType = "string"), }) @ResponseBody @GetMapping("/projectSysEmpInfo/{projectId}") public RespResult searchSysEmpInfoByProjectId(@PathVariable("projectId") String projectId) { List<SysEmpInfo> list = sysEmpInfoDao.selectSysEmpInfoByProjectId(projectId); return RespResult.SUCCESS(list); } @ApiOperation(value = "查询验收经理", notes = "查询验收经理", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_VALUE, response = RespResult.class) @ApiResponses({ @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对"), @ApiResponse(code = 500, message = "应用服务内部错误") }) @ApiImplicitParams({ @ApiImplicitParam(name = "projectId", value = "项目id", required = true, paramType = "string"), @ApiImplicitParam(name = "roleId", value = "角色id", required = true, paramType = "string")}) @ResponseBody @GetMapping("/acceptanceManager/{projectId}/{roleId}") public RespResult getAcceptanceManager(@PathVariable("projectId") String projectId,@PathVariable("roleId") String roleId) { String empName = sysEmpInfoDao.getAcceptanceManager(projectId, roleId); return RespResult.SUCCESS(empName); }}
package cn.chinatowercom.login.service;import java.util.List;import java.util.Map;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.util.DigestUtils;import org.springframework.util.StringUtils;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import cn.chinatowercom.common.response.RespResult;import cn.chinatowercom.common.util.EncryptUtil;import cn.chinatowercom.framework.jwt.JwtUtil;import cn.chinatowercom.framework.jwt.UserInfo;import cn.chinatowercom.framework.util.JSONResult;import cn.chinatowercom.framework.util.PortalConst;import cn.chinatowercom.login.dao.LoginMapper;import cn.chinatowercom.login.model.UpdPasswordVo;import cn.chinatowercom.login.model.UserInfoPipeline;import cn.chinatowercom.login.model.UserModel;import cn.chinatowercom.org.model.OrgModel;import cn.chinatowercom.org.service.OrgService;import cn.chinatowercom.role.dao.SysEmpRoleRelInfoMapper;import cn.chinatowercom.role.model.RoleModel;import cn.chinatowercom.role.service.RoleService;import io.jsonwebtoken.Claims;import io.jsonwebtoken.Jws;import lombok.extern.slf4j.Slf4j;/** * 用户登录 */@Slf4j@RestController@RequestMapping(value = "/login")public class LoginService { @Autowired private LoginMapper loginMapper; @Autowired private RoleService roleService; @Autowired private OrgService orgService; @Autowired private SysEmpRoleRelInfoMapper sysEmpRoleRelInfoMapper; // 登录 @PostMapping(value = "/doLogin") public JSONResult<UserInfoPipeline> doLogin(@RequestBody UserModel user) { String userName = user.getEmpAccount(); String password = user.getEmpPassword(); if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) { return JSONResult.<UserInfoPipeline> Builder().setDesc("用户名密码不能为空").setStatus(PortalConst.BusinessCode.FAIL); }// UserInfo userInfo = new UserInfo(); UserInfoPipeline userInfo=new UserInfoPipeline(); UserModel userModel = loginMapper.getUserByNamePass(userName,DigestUtils.md5DigestAsHex(password.getBytes())); if (null != userModel) { userInfo.setUserId(userModel.getEmpId()); userInfo.setUserAccount(userModel.getEmpAccount()); userInfo.setUserType(PortalConst.UserType.Admin); userInfo.setDesc("用户已经正确登录"); // 生成用户token String token = JwtUtil.buildJWT(PortalConst.UserType.Admin,String.valueOf(userModel.getEmpId()),72000); userInfo.setToken(token); userInfo.setUserName(userModel.getEmpName()); RoleModel roleModel = roleService.getUserRole(userInfo.getUserId()); if(null!=roleModel){ userInfo.setRoleCode(roleModel.getRoleCode()); } userInfo.setEncodeUesrAccount(EncryptUtil.getInstance().DESencode(userInfo.getUserAccount(),EncryptUtil.KEY)); //获取用户角色列表 List<String> roleCodeList=sysEmpRoleRelInfoMapper.getEmpRoleCodeList(userModel.getEmpId()); userInfo.setRoleCodeList(roleCodeList); // 登录信息保存Redis return JSONResult.<UserInfoPipeline> Builder().setData(userInfo).setDesc("已经成功登录"); } userInfo.setDesc("用户名或密码错误");// return JSONResult.<UserInfo> Builder().setData(userInfo).setDesc("登录失败").setStatus(PortalConst.BusinessCode.FAIL); return JSONResult.<UserInfoPipeline> Builder().setData(userInfo).setDesc("登录失败").setStatus(PortalConst.BusinessCode.FAIL); } // 获取用户信息 @SuppressWarnings("unchecked") @PostMapping(value = "/userInfo") public JSONResult<UserModel> getUserByToken(@RequestParam("token") String token) { Jws<Claims> claims = JwtUtil.parseJWT(token); String empId = claims.getBody().getId(); if (null == empId) { return JSONResult.<UserModel> Builder().setStatus(PortalConst.BusinessCode.FAIL).setDesc("用户ID错误"); } UserModel user = loginMapper.selectByPrimaryKey(empId); if (null == user) { return JSONResult.<UserModel> Builder().setStatus(PortalConst.BusinessCode.FAIL).setDesc("用户ID错误"); } RoleModel roleModel = roleService.getUserRole(user.getEmpId()); if(roleModel != null) { user.setRoleCode(roleModel.getRoleCode()); user.setRoleName(roleModel.getRoleName()); } OrgModel orgModel = new OrgModel(); orgModel.setOrgId(user.getOrgId()); RespResult orgResult = orgService.getOrgDetail(orgModel); orgModel = (OrgModel)((Map<String,Object>)orgResult.getData()).get("orgDetail"); user.setOrgType(orgModel.getOrgType()); return JSONResult.<UserModel> Builder().setData(user).setDesc("成功返回"); } // 退出登录 public JSONResult<String> doLogout() { return JSONResult.<String> Builder().setData("已经退出"); } /**更改密码*/ @PostMapping(value = "/doUpdPassword") public RespResult doUpdPassword(@RequestBody UpdPasswordVo param) { if(param==null||StringUtils.isEmpty(param.getEmpId())||StringUtils.isEmpty(param.getOldPass())||StringUtils.isEmpty(param.getNewPass())) { return RespResult.FAIL("更改密码失败:用户id、原密码、新 密码都不能为空 " ); } try{ String oldPass=DigestUtils.md5DigestAsHex(param.getOldPass().getBytes()); String newPass=DigestUtils.md5DigestAsHex(param.getNewPass().getBytes()); UserModel user = loginMapper.selectByPrimaryKey(param.getEmpId()); if(user==null) { return RespResult.FAIL("更改密码失败:用户id不存在。 " ); } if(!oldPass.equals(user.getEmpPassword())) { return RespResult.FAIL("更改密码失败:原密码错误。 " ); } loginMapper.doUpdPassword(param.getEmpId(), newPass); return RespResult.SUCCESS(null, "更改密码成功"); }catch(Exception e) { return RespResult.FAIL("更改密码失败:" + e.getMessage()); } }}
package cn.chinatowercom.menu.service;import java.util.ArrayList;import java.util.List;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import cn.chinatowercom.common.response.RespResult;import cn.chinatowercom.framework.annotation.CurrentUser;import cn.chinatowercom.framework.annotation.LoginRequired;import cn.chinatowercom.framework.jwt.UserInfo;import cn.chinatowercom.framework.util.JSONResult;import cn.chinatowercom.framework.util.PortalConst;import cn.chinatowercom.menu.dao.MenuMapper;import cn.chinatowercom.menu.model.MenuModel;@Slf4j@RestController@RequestMapping(value = "/menu")public class MenuService { @Autowired private MenuMapper menuMapper; /** * 获取首页菜单 * @param token * @return */ @LoginRequired @PostMapping(value = "/getMenu") public RespResult getMenu(@CurrentUser UserInfo user) { List<MenuModel> menuList = new ArrayList<MenuModel>(); menuList = menuMapper.getMenuAll(user.getUserId().toString()); List<MenuModel> firstMenus = new ArrayList<MenuModel>(); List<MenuModel> secondMenus = new ArrayList<MenuModel>(); if (null == menuList) { return RespResult.FAIL("没有菜单权限"); } for (MenuModel v : menuList) { if (v.getMenuLevel().equals("1")) { firstMenus.add(v); } else if (v.getMenuLevel().equals("2")) { secondMenus.add(v); } } for (MenuModel v : secondMenus) { for (MenuModel m : firstMenus) { if (v.getParentMenuId().equals(m.getMenuId())) { if (null == m.getSubMenus()) { m.setSubMenus(new ArrayList<MenuModel>()); } m.getSubMenus().add(v); break; } } } return RespResult.SUCCESS(firstMenus); }}
package cn.chinatowercom.org.service;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import cn.chinatowercom.client.interfaces.LowerPersonnelClient;import cn.chinatowercom.common.db.MapperService;import cn.chinatowercom.sysDict.model.SysDictModel;import cn.chinatowercom.sysDict.service.SysDictService;import lombok.extern.slf4j.Slf4j;import org.apache.commons.lang.StringUtils;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Lazy;import org.springframework.web.bind.annotation.*;import cn.chinatowercom.common.response.RespResult;import cn.chinatowercom.framework.annotation.CurrentUser;import cn.chinatowercom.framework.annotation.LoginRequired;import cn.chinatowercom.framework.jwt.UserInfo;import cn.chinatowercom.org.dao.OrgMapper;import cn.chinatowercom.org.model.OrgModel;import cn.chinatowercom.role.model.TreeNodeModel;import cn.chinatowercom.system.model.EmpVO;@Slf4j@RestController@RequestMapping(value = "/org")public class OrgService { @Autowired private OrgMapper orgMapper; @Autowired private MapperService mapperService; @Autowired private SysDictService sysDictService; @Lazy @Autowired private LowerPersonnelClient lowerPersonnelClient; /** * 获取组织机构树 * @param orgModel * @return */ @PostMapping("/getOrgTree") public RespResult getOrgTree(@RequestBody OrgModel orgModel) { Map<String,Object> data = new HashMap<String, Object>(); try{ List<TreeNodeModel> firstNodelist = new ArrayList<TreeNodeModel>(); List<TreeNodeModel> secondNodelist = new ArrayList<TreeNodeModel>(); List<TreeNodeModel> thirdNodelist = new ArrayList<TreeNodeModel>(); List<TreeNodeModel> fourthNodelist = new ArrayList<TreeNodeModel>(); List<TreeNodeModel> fifthNodelist = new ArrayList<TreeNodeModel>(); firstNodelist=orgMapper.getfirstNodelist(); for(int j=0;firstNodelist.size()>j;j++) { secondNodelist = orgMapper.getChildNodeList(firstNodelist.get(j).getValue()); firstNodelist.get(j).setChildren(secondNodelist); for(int k=0;secondNodelist.size()>k;k++) { thirdNodelist = orgMapper.getChildNodeList(secondNodelist.get(k).getValue()); secondNodelist.get(k).setChildren(thirdNodelist); for(int w=0;thirdNodelist.size()>w;w++) { fourthNodelist = orgMapper.getChildNodeList(thirdNodelist.get(w).getValue()); thirdNodelist.get(w).setChildren(fourthNodelist); for(int z=0;fourthNodelist.size()>z;z++) { fifthNodelist = orgMapper.getChildNodeList(fourthNodelist.get(z).getValue()); fourthNodelist.get(z).setChildren(fifthNodelist); continue; } } } } data.put("orgTree", firstNodelist); }catch(Exception e){ return RespResult.FAIL(null); } return RespResult.SUCCESS(data); } /** * 获取组织详情信息 * @param orgModel * @return */ @PostMapping("/getOrgDetail") public RespResult getOrgDetail(@RequestBody OrgModel orgModel) { Map<String,Object> data = new HashMap<String, Object>(); OrgModel orgDetail = new OrgModel(); try{ orgDetail = orgMapper.getOrgDetail(orgModel); if(orgDetail!=null&&orgDetail.getAreaIds1()!=null&&orgDetail.getAreaIds1()!=""){ orgDetail.setAreaIds(orgDetail.getAreaIds1().split(",")); } data.put("orgDetail", orgDetail); List<SysDictModel> sysDicts = new ArrayList<SysDictModel>(); sysDicts=sysDictService.getSysDictByItemType("ORG_TYPE"); data.put("sysDicts", sysDicts); }catch(Exception e){ e.printStackTrace(); return RespResult.FAIL(null); } return RespResult.SUCCESS(data); } /** * 保存组织数据 * @param user * @param orgModel * @return */ @LoginRequired @PostMapping("/doSaveOrg") public RespResult doSaveOrg(@CurrentUser UserInfo user,@RequestBody OrgModel orgModel) { Map<String,Object> data = new HashMap<String, Object>(); int res = 0; try{ orgModel.setAreaIds1(StringUtils.join(orgModel.getAreaIds(), ",")); if(!"true".equals(orgModel.getAddTag())){ orgModel.setUpdater(user.getUserId()); orgModel.setUpdaterName(user.getUserName()); res = orgMapper.doUpdateOrg(orgModel);// lowerPersonnelClient.updateOrganizationPut(orgModel.getOrgId()); }else{ orgModel.setCreater(user.getUserId()); orgModel.setCreaterName(user.getUserName()); res = orgMapper.doInsertOrg(orgModel);// lowerPersonnelClient.createOrganizationPost(orgModel.getOrgId()); } data.put("res", res); }catch(Exception e){ e.printStackTrace(); return RespResult.FAIL(null); } return RespResult.SUCCESS(data); }}
package cn.chinatowercom.project.service;import cn.chinatowercom.project.dao.GitInfoDao;import cn.chinatowercom.project.model.GitInfoModel;import cn.chinatowercom.sysDict.dao.SysDictMapper;import cn.chinatowercom.sysDict.model.SysDictModel;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.util.List;@Servicepublic class GitInfoService { @Autowired private GitInfoDao getGitInfoDao; public GitInfoModel getGitInfoDetail(GitInfoModel gitInfoModel){ return getGitInfoDao.getGitInfoDetail(gitInfoModel); } public int doUpdateGitInfo(GitInfoModel gitInfoModel){ return getGitInfoDao.doUpdateGitInfo(gitInfoModel); }; public int doInsertGitInfo(GitInfoModel gitInfoModel){ return getGitInfoDao.doInsertGitInfo(gitInfoModel); }; public int doDeleteGitInfo(GitInfoModel gitInfoModel){ return getGitInfoDao.doDeleteGitInfo(gitInfoModel); };}
package cn.chinatowercom.project.service;import cn.chinatowercom.common.response.RespResult;import cn.chinatowercom.framework.annotation.CurrentUser;import cn.chinatowercom.framework.annotation.LoginRequired;import cn.chinatowercom.framework.jwt.JwtUtil;import cn.chinatowercom.framework.jwt.UserInfo;import cn.chinatowercom.login.model.UserModel;import cn.chinatowercom.project.dao.ProjectDao;import cn.chinatowercom.project.model.GitInfoModel;import cn.chinatowercom.project.model.ProjectModel;import cn.chinatowercom.role.model.TreeNodeModel;import cn.chinatowercom.sysDict.model.SysDictModel;import cn.chinatowercom.sysDict.service.SysDictService;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import io.jsonwebtoken.Claims;import io.jsonwebtoken.Jws;import java.util.*;import javax.servlet.http.HttpServletRequest;@Slf4j@RestController@RequestMapping(value = "/project")public class ProjectService { @Autowired private ProjectDao projectDao; @Autowired private SysDictService sysDictService;// @Autowired// private GitInfoService gitInfoService; /** * 获取项目树 * @param projectModel * @return */ @PostMapping("/getProjectTree") public RespResult getProjectTree(@RequestBody ProjectModel projectModel) { Map<String,Object> data = new HashMap<String, Object>(); try{ List<TreeNodeModel> firstNodelist = new ArrayList<TreeNodeModel>(); List<TreeNodeModel> secondNodelist = new ArrayList<TreeNodeModel>(); List<TreeNodeModel> thirdNodelist = new ArrayList<TreeNodeModel>(); List<TreeNodeModel> fourthNodelist = new ArrayList<TreeNodeModel>(); List<TreeNodeModel> fifthNodelist = new ArrayList<TreeNodeModel>(); firstNodelist=projectDao.getfirstNodelist(); for(int j=0;firstNodelist.size()>j;j++) { secondNodelist = projectDao.getChildNodeList(firstNodelist.get(j).getValue()); firstNodelist.get(j).setChildren(secondNodelist); for(int k=0;secondNodelist.size()>k;k++) { thirdNodelist = projectDao.getChildNodeList(secondNodelist.get(k).getValue()); secondNodelist.get(k).setChildren(thirdNodelist); for(int w=0;thirdNodelist.size()>w;w++) { fourthNodelist = projectDao.getChildNodeList(thirdNodelist.get(w).getValue()); thirdNodelist.get(w).setChildren(fourthNodelist); for(int z=0;fourthNodelist.size()>z;z++) { fifthNodelist = projectDao.getChildNodeList(fourthNodelist.get(z).getValue()); fourthNodelist.get(z).setChildren(fifthNodelist); continue; } } } } data.put("projectTree", firstNodelist); }catch(Exception e){ e.printStackTrace(); return RespResult.FAIL(null); } return RespResult.SUCCESS(data); } /** * 获取项目详情信息 * @param projectModel * @return */ @PostMapping("/getProjectDetail") public RespResult getProjectDetail(@RequestBody ProjectModel projectModel) { Map<String,Object> data = new HashMap<String, Object>(); ProjectModel projectDetail = new ProjectModel();// GitInfoModel gitInfoModel = new GitInfoModel(); try{ projectDetail = projectDao.getProjectDetail(projectModel);// gitInfoModel.setProjectId(projectDetail.getProjectId());// gitInfoModel = gitInfoService.getGitInfoDetail(gitInfoModel); data.put("projectDetail", projectDetail);// data.put("gitInfoModel",gitInfoModel); List<SysDictModel> sysDicts = new ArrayList<SysDictModel>(); sysDicts=sysDictService.getSysDictByItemType("PROJECT_TYPE");// List<SysDictModel> gitProjectType = new ArrayList<SysDictModel>();// gitProjectType=sysDictService.getSysDictByItemType("GIT_PROJECT_TYPE"); data.put("sysDicts", sysDicts);// data.put("gitProjectTypes",gitProjectType); }catch(Exception e){ e.printStackTrace(); return RespResult.FAIL(null); } return RespResult.SUCCESS(data); } /** * 保存项目数据 * @param user * @param projectModel * @return */// @LoginRequired @PostMapping("/doSaveProject")// public RespResult doSaveProject(@CurrentUser UserInfo user, @RequestBody ProjectModel projectModel) { public RespResult doSaveProject(@RequestBody ProjectModel projectModel,HttpServletRequest request) {// String token=request.getHeader("accessToken");// if(null==token||token.trim().length()==0){// data.put("status","ERROR");// data.put("message","token不能为空");// }// Jws<Claims> claims = JwtUtil.parseJWT(token);// String empId = claims.getBody().getId();// UserModel user = loginMapper.selectByPrimaryKey(empId);// String roleCode = user.getRoleCode();// String orgId = user.getOrgId(); Map<String,Object> data = new HashMap<String, Object>(); int res = 0; try{ if(!"true".equals(projectModel.getAddTag())){// GitInfoModel gitInfoModel = projectModel.getGitInfoModel();// gitInfoModel.setGitId(projectModel.getGitId());// gitInfoModel.setProjectId(projectModel.getProjectId());// gitInfoModel.setProjectName(projectModel.getProjectName()); res = projectDao.doUpdateProject(projectModel);// gitInfoService.doUpdateGitInfo(gitInfoModel); }else{ projectModel.setGitId(UUID.randomUUID().toString().replaceAll("-", "")); res = projectDao.doInsertProject(projectModel);// GitInfoModel gitInfoModel = projectModel.getGitInfoModel();// gitInfoModel.setGitId(projectModel.getGitId());// gitInfoModel.setProjectId(projectModel.getProjectId());// gitInfoModel.setProjectName(projectModel.getProjectName());// gitInfoService.doInsertGitInfo(gitInfoModel); } data.put("res", res); }catch(Exception e){ e.printStackTrace(); return RespResult.FAIL("保存失败"); } return RespResult.SUCCESS(data); }}
package cn.chinatowercom.role.service;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.UUID;import cn.chinatowercom.sysDict.service.SysDictService;import com.github.pagehelper.PageHelper;import com.github.pagehelper.PageInfo;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Lazy;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import cn.chinatowercom.common.response.RespResult;import cn.chinatowercom.framework.annotation.CurrentUser;import cn.chinatowercom.framework.annotation.LoginRequired;import cn.chinatowercom.framework.jwt.UserInfo;import cn.chinatowercom.role.dao.RoleMapper;import cn.chinatowercom.role.dao.SysEmpRoleRelInfoMapper;import cn.chinatowercom.role.model.RoleModel;import cn.chinatowercom.role.model.SysEmpRoleRelInfo;import cn.chinatowercom.role.model.TreeNodeModel;@Slf4j@RestController@RequestMapping(value = "/role")public class RoleService { @Autowired private RoleMapper roleMapper; @Autowired private SysEmpRoleRelInfoMapper sysEmpRoleRelInfoDao; @Autowired private SysDictService sysDictService; /** * 系统管理员获取角色列表 * @return */ @LoginRequired @PostMapping(value = "/getRoleList") public RespResult getRoleList(@RequestBody RoleModel roleModel) { try{ PageHelper.startPage(roleModel.getCurrentPage(),roleModel.getPageSize()); List<RoleModel> roleList = roleMapper.getRoleList(roleModel); PageInfo pageInfo = new PageInfo(roleList); return RespResult.SUCCESS(pageInfo, "查询成功!"); }catch(Exception e){ return RespResult.FAIL(null); } } /** * 删除角色 * @param roleModel * @return */ @PostMapping("/deleteRole") public RespResult deleteRole(@RequestBody RoleModel roleModel) { Map<String,Object> data = new HashMap<String, Object>(); try{ roleMapper.deleteRole(roleModel.getRoleId()); }catch(Exception e){ return RespResult.FAIL(null); } return RespResult.SUCCESS(data); } /** * 获取角色排序列 * @param roleModel * @return */ @PostMapping("/getMaxDisOrder") public RespResult getMaxDisOrder(@RequestBody RoleModel roleModel) { Map<String,Object> data = new HashMap<String, Object>(); int orderNum = 0; try{ orderNum = roleMapper.getMaxDisOrder(); data.put("disOrder", orderNum); }catch(Exception e){ return RespResult.FAIL(null); } return RespResult.SUCCESS(data); } /** * 获取角色类型字典 * @param roleModel * @return */ @PostMapping("/getRoleCode") public RespResult getRoleCode(@RequestBody RoleModel roleModel) { Map<String,Object> data = new HashMap<String, Object>(); int orderNum = 0; try{ orderNum = roleMapper.getMaxDisOrder(); data.put("sysDicts", sysDictService.getSysDictByItemType("ROLE_TYPE")); }catch(Exception e){ e.printStackTrace(); return RespResult.FAIL(null); } return RespResult.SUCCESS(data); } /** * 保存角色数据 * @param roleModel * @return */ @LoginRequired @PostMapping("/doSaveRoleInfo") public RespResult doSaveRoleInfo(@CurrentUser UserInfo user,@RequestBody RoleModel roleModel) { Map<String,Object> data = new HashMap<String, Object>(); int res = 0; try{ if(!"".equals(roleModel.getRoleId())&&roleModel.getRoleId()!=null){ roleModel.setUpdater(user.getUserId()); roleModel.setUpdaterName(user.getUserName()); res = roleMapper.doUpdateRoleInfo(roleModel); }else{ String uuid = UUID.randomUUID().toString().replaceAll("-", ""); roleModel.setRoleId(uuid); roleModel.setCreater(user.getUserId()); roleModel.setCreaterName(user.getUserName()); res = roleMapper.doSaveRoleInfo(roleModel); } data.put("res", res); }catch(Exception e){ return RespResult.FAIL(null); } return RespResult.SUCCESS(data); } /** * 获取角色数据 * @param roleModel * @return */ @PostMapping("/getRoleDetail") public RespResult getRoleDetail(@RequestBody RoleModel roleModel) { Map<String,Object> data = new HashMap<String, Object>(); RoleModel roleModel1 = new RoleModel(); try{ roleModel1 = roleMapper.getRoleDetail(roleModel.getRoleId()); data.put("roleModel", roleModel1); }catch(Exception e){ return RespResult.FAIL(null); } return RespResult.SUCCESS(data); } /** * 获取菜单树 * @param roleModel * @return */ @PostMapping("/getMenuTree") public RespResult getMenuTree(@RequestBody RoleModel roleModel) { Map<String,Object> data = new HashMap<String, Object>(); try{ List<TreeNodeModel> firstNodelist = new ArrayList<TreeNodeModel>(); List<TreeNodeModel> secondNodelist = new ArrayList<TreeNodeModel>(); firstNodelist=roleMapper.getfirstNodelist(); for(int j=0;firstNodelist.size()>j;j++) { secondNodelist = roleMapper.getChildNodeList(firstNodelist.get(j).getValue()); firstNodelist.get(j).setChildren(secondNodelist); } data.put("menuTree", firstNodelist); //树形选中节点 List<String> chooseNode = null; chooseNode = roleMapper.getChooseNode(roleModel.getRoleId()); data.put("chooseNode", chooseNode); }catch(Exception e){ return RespResult.FAIL(null); } return RespResult.SUCCESS(data); } /** * 获取所有节点ID(全选) * @param roleModel * @return */ @PostMapping("/getAllNode") public RespResult getAllNode(@RequestBody RoleModel roleModel) { Map<String,Object> data = new HashMap<String, Object>(); try{ List<String> allNode = null; allNode = roleMapper.getAllNode(); data.put("allNode", allNode); }catch(Exception e){ return RespResult.FAIL(null); } return RespResult.SUCCESS(data); } /** * 保存角色配置信息 * @param roleModel * @return */ @PostMapping("/doSaveConf") public RespResult doSaveConf(@RequestBody RoleModel roleModel) { Map<String,Object> data = new HashMap<String, Object>(); int res = 0; try{ res = roleMapper.deleteRoleConf(roleModel); if(roleModel.getMenuChecked()!=null&&roleModel.getMenuChecked().length>0){ res = roleMapper.doSaveConf(roleModel); } data.put("res", res); }catch(Exception e){ e.printStackTrace(); return RespResult.FAIL(null); } return RespResult.SUCCESS(data); } public RoleModel getUserRole(String userId) { return roleMapper.getUserRole(userId); } /** * 获取sysEmpRoleRelInfo * @param userId * @return */ @GetMapping("/sysEmpRoleRelInfo/{userId}") public RespResult getSysEmpRoleRelInfo(@PathVariable("userId") String userId) { List<SysEmpRoleRelInfo> sysEmpRoleRelInfo = sysEmpRoleRelInfoDao.selectByEmpId(userId); return RespResult.SUCCESS(sysEmpRoleRelInfo); }}
package cn.chinatowercom.sysDict.service;import java.util.ArrayList;import java.util.List;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.bind.annotation.RestController;import cn.chinatowercom.common.response.RespResult;import cn.chinatowercom.response.ProcessResult;import cn.chinatowercom.sysDict.model.SysDictModel;@Slf4j@RestController@RequestMapping(value = "/dict")public class DictService { @Autowired private SysDictService sysDictService; @ResponseBody @GetMapping("/dict") public RespResult searchSysDictByItemType() { List<SysDictModel> sysDicts = new ArrayList<SysDictModel>(); sysDicts = sysDictService.getSysDictByItemType("STAGE_TYPE"); return RespResult.SUCCESS(sysDicts); } /** * 根据itemType 查询字典 * @param itemType * @return * localhost:8703/monitor_sys_service/dict/getSysDictByItemType?itemType=REDIS_SYS */ @PostMapping(value="/getSysDictByItemType") public ProcessResult getSysDictByItemType(@RequestParam(name = "itemType",required = true) String itemType) { ProcessResult result=new ProcessResult(ProcessResult.SUCCESS); List<SysDictModel> sysDicts = new ArrayList<SysDictModel>(); sysDicts = sysDictService.getSysDictByItemType(itemType); result.setData(sysDicts); return result; }}
package cn.chinatowercom.sysDict.service;import cn.chinatowercom.sysDict.dao.SysDictMapper;import cn.chinatowercom.sysDict.model.SysDictModel;import org.apache.ibatis.annotations.Mapper;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.util.List;@Servicepublic class SysDictService { @Autowired private SysDictMapper sysDictMapper; public List<SysDictModel> getSysDictByItemType(String itemType) { return sysDictMapper.getSysDictByItemType(itemType); }}
package cn.chinatowercom.system.service;import io.jsonwebtoken.Claims;import io.jsonwebtoken.Jws;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.UUID;import javax.servlet.http.HttpServletRequest;import lombok.extern.slf4j.Slf4j;import org.apache.commons.lang.StringUtils;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Lazy;import org.springframework.util.DigestUtils;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import cn.chinatowercom.client.interfaces.LowerPersonnelClient;import cn.chinatowercom.common.response.RespResult;import cn.chinatowercom.common.util.UserUtil;import cn.chinatowercom.framework.annotation.CurrentUser;import cn.chinatowercom.framework.jwt.JwtUtil;import cn.chinatowercom.framework.jwt.UserInfo;import cn.chinatowercom.login.dao.LoginMapper;import cn.chinatowercom.login.model.UserModel;import cn.chinatowercom.system.dao.EmpDao;import cn.chinatowercom.system.model.EmpVO;import cn.chinatowercom.system.model.SysEmpProjectRel;import cn.chinatowercom.system.model.SysEmpProjectRoleRel;import cn.chinatowercom.system.model.SysEmpRoleRelInfo;import cn.chinatowercom.system.model.TreeNodeModel;@Slf4j@RestController@RequestMapping("/emp")public class EmpService { @Autowired private EmpDao empDao; @Autowired private SysEmpProjectRelService sysEmpProjectRelService; @Autowired private LoginMapper loginMapper; @Lazy @Autowired private LowerPersonnelClient lowerPersonnelClient; //人员列表数据 @PostMapping("/getEmpLoad")// public Map<String,Object> getEmpLoad(@RequestBody EmpVO vo, @CurrentUser UserInfo userInfo) { public Map<String,Object> getEmpLoad(@RequestBody EmpVO vo,HttpServletRequest request) { Map<String,Object> data = new HashMap<String, Object>(); String token=request.getHeader("accessToken"); if(null==token||token.trim().length()==0){ data.put("status","ERROR"); data.put("message","token不能为空"); } Jws<Claims> claims = JwtUtil.parseJWT(token); String empId = claims.getBody().getId(); UserModel user = loginMapper.selectByPrimaryKey(empId); String roleCode = user.getRoleCode(); String orgId = user.getOrgId(); //6是管理员id,如果是管理员就不要限制orgid,查看全部内容 if (empId!=null&&!"6".equals(empId)){ vo.setOrg_id(orgId); } List<EmpVO> list = new ArrayList<>(); if ("0".equals(roleCode)){ list = empDao.getEmpList(vo); }else { list = empDao.getEmpListByCompany(vo); } List<EmpVO> list1 = new ArrayList<EmpVO>(); for (EmpVO vo1 :list){ vo1.setOrgIds(vo1.getOrgIds1().split(",")); List<SysEmpProjectRel> list2 =sysEmpProjectRelService.getSysEmpProjectRelByEmpId(vo1.getEmp_id()); vo1.setProjectTree(list2); list1.add(vo1); } int total = 0; if ("0".equals(roleCode)){ total = empDao.getEmpCount(vo); }else { total = empDao.getEmpListByCompanyCount(vo); } data.put("emplist",list1); data.put("emptotal",total); return data; } //人员列表数据 @PostMapping("/getEmpLoadByProjectId") public Map<String,Object> getEmpLoadByProjectId(@RequestBody EmpVO vo) { List<EmpVO> list = empDao.getEmpListByProjectId(vo); int total = empDao.getEmpCountByProjectId(vo); Map<String,Object> data = new HashMap(); data.put("emplist",list); data.put("emptotal",total); return data; } // 新增人员数据 @PostMapping("/addInfo")// public RespResult addInfo(@RequestBody EmpVO vo, @CurrentUser UserInfo userInfo) { public RespResult addInfo(@RequestBody EmpVO vo, HttpServletRequest request) { Map<String,Object> data = new HashMap<String, Object>(); String token=request.getHeader("accessToken"); if(null==token||token.trim().length()==0){ data.put("status","ERROR"); data.put("message","token不能为空"); } Jws<Claims> claims = JwtUtil.parseJWT(token); String empId = claims.getBody().getId(); UserModel user = loginMapper.selectByPrimaryKey(empId); int addRes = 0; try { vo.setEmp_id(UUID.randomUUID().toString().replaceAll("-", "")); vo.setEmp_password(DigestUtils.md5DigestAsHex(vo.getEmp_password().getBytes())); vo.setCreater(user.getEmpId()); vo.setCreater_name(user.getEmpName()); int checkCount=empDao.checkInfoAccount(vo); if(checkCount == 0){ vo.setOrgIds1(StringUtils.join(vo.getOrgIds(), ",")); addRes = empDao.addInfo(vo); } if (addRes == 1){ if(!vo.getProjectTree().isEmpty()){ List<SysEmpProjectRel> list=vo.getProjectTree(); List<SysEmpProjectRel> list1=new ArrayList<SysEmpProjectRel>(); for (SysEmpProjectRel sysEmpProjectRel:list){ sysEmpProjectRel.setEmpProjectRelId(UUID.randomUUID().toString().replaceAll("-", "")); list1.add(sysEmpProjectRel); } sysEmpProjectRelService.insertSysEmpProjectRel(vo.getEmp_id(),list1); sysEmpProjectRelService.updateSysEmpProjectRel(vo.getEmp_id()); } }// lowerPersonnelClient.createEmpPost(vo.getEmp_id()); }catch (Exception e){ log.error("新增账户失败" + e); return RespResult.FAIL("新增账户失败" + e); } return RespResult.SUCCESS(data); } //项目角色配置 @PostMapping("/editProjectRole") public RespResult editProjectRole( @RequestBody EmpVO vo) { Map<String,Object> data = new HashMap<>(); try { String empId = vo.getEmp_id(); //删除人员角色关系 empDao.delRoleRel(empId); if(!vo.getRoleChecked().isEmpty()) { List<SysEmpRoleRelInfo> list = vo.getRoleChecked(); List<SysEmpRoleRelInfo> list1=new ArrayList<SysEmpRoleRelInfo>(); for (SysEmpRoleRelInfo sysEmpRoleRelInfo:list){ sysEmpRoleRelInfo.setEmpRoleRelId(UUID.randomUUID().toString().replaceAll("-", "")); sysEmpRoleRelInfo.setEmpId(vo.getEmp_id()); list1.add(sysEmpRoleRelInfo); } empDao.insertRoleRel(vo.getEmp_id(), list1); } if (!vo.getEmpProjectRoleRels().isEmpty()){ List<SysEmpProjectRoleRel> relList = vo.getEmpProjectRoleRels(); List<SysEmpProjectRoleRel> rels = new ArrayList<>(); for (SysEmpProjectRoleRel sysEmpProjectRoleRel : relList){ //删除人员项目角色关系 empDao.delProjectRoleRel(empId,sysEmpProjectRoleRel.getProjectId()); List<SysEmpRoleRelInfo> roles = sysEmpProjectRoleRel.getRoles(); for (SysEmpRoleRelInfo sysEmpRoleRelInfo : roles){ SysEmpProjectRoleRel rel = new SysEmpProjectRoleRel(); rel.setEmpProjectRelId(UUID.randomUUID().toString().replaceAll("-", "")); rel.setEmpId(empId); rel.setProjectId(sysEmpProjectRoleRel.getProjectId()); rel.setProjectName(sysEmpProjectRoleRel.getProjectName()); rel.setSystemProjectId(sysEmpProjectRoleRel.getSystemProjectId()); rel.setSystemProjectName(sysEmpProjectRoleRel.getSystemProjectName()); rel.setBusinessProjectId(sysEmpProjectRoleRel.getBusinessProjectId()); rel.setBusinessProjectName(sysEmpProjectRoleRel.getBusinessProjectName()); rel.setRoleId(sysEmpRoleRelInfo.getRoleId()); rels.add(rel); } } empDao.insertProjectRoleRel(empId,rels); }// String isLower = empDao.selectEmpByVoId(vo.getEmp_id());// if (isLower != null) {// lowerPersonnelClient.updateUserPut(vo.getEmp_id());// } else {// lowerPersonnelClient.createEmpPost(vo.getEmp_id());// } }catch (Exception e){ return RespResult.FAIL("项目角色配置失败" + e); } return RespResult.SUCCESS(data); } //删除人员数据 @PostMapping("/deleteInfo/{emp_id}") public Map<String, Object> deleteInfo(@PathVariable("emp_id") String emp_id) { int deleteRes = 0; deleteRes = empDao.deleteInfo(emp_id);// lowerPersonnelClient.deleteUserDelete(emp_id); Map<String,Object> data = new HashMap(); data.put("deleteRes",deleteRes); return data; } //修改人员数据 @PostMapping("/updateInfo") public RespResult updateInfo(@RequestBody EmpVO vo, HttpServletRequest request) { Map<String,Object> data = new HashMap<String, Object>(); String token=request.getHeader("accessToken"); if(null==token||token.trim().length()==0){ data.put("status","ERROR"); data.put("message","token不能为空"); } Jws<Claims> claims = JwtUtil.parseJWT(token); String requestEmpId = claims.getBody().getId(); UserModel user = loginMapper.selectByPrimaryKey(requestEmpId); try { String empId = vo.getEmp_id(); int checkCount=empDao.checkInfoAccount(vo); String checkSelf=empDao.checkInfoSelf(vo); if(!checkSelf.equals(vo.getEmp_password())){ vo.setEmp_password(DigestUtils.md5DigestAsHex(vo.getEmp_password().getBytes())); } vo.setOrgIds1(StringUtils.join(vo.getOrgIds(), ",")); vo.setCreater(user.getEmpId()); vo.setCreater_name(user.getEmpName()); /* vo.setCreater(userInfo.getUserId()); vo.setCreater_name(userInfo.getUserName());*/ if(checkCount==0) { //删除人员项目关系 sysEmpProjectRelService.delSysEmpProjectRel(empId); empDao.updateInfo(vo); if(!vo.getProjectTree().isEmpty()){ List<SysEmpProjectRel> list=vo.getProjectTree(); List<SysEmpProjectRel> list1=new ArrayList<SysEmpProjectRel>(); for (SysEmpProjectRel sysEmpProjectRel:list){ sysEmpProjectRel.setEmpProjectRelId(UUID.randomUUID().toString().replaceAll("-", "")); list1.add(sysEmpProjectRel); } sysEmpProjectRelService.insertSysEmpProjectRel(vo.getEmp_id(),list1); sysEmpProjectRelService.updateSysEmpProjectRel(vo.getEmp_id()); } }// String isLower = empDao.selectEmpByVoId(vo.getEmp_id());// if (isLower != null) {// lowerPersonnelClient.updateUserPut(vo.getEmp_id());// } else {// lowerPersonnelClient.createEmpPost(vo.getEmp_id());// } }catch (Exception e){ log.error("修改账户失败" + e); return RespResult.FAIL("修改账户失败" + e); } return RespResult.SUCCESS(data); } //组织下拉 @PostMapping("/getOrg") public Map<String,Object> getOrg(@RequestBody EmpVO vo) { //标签分类下拉 List<EmpVO> orgOpts=empDao.selectOrg(vo); Map<String,Object> data = new HashMap(); data.put("orgOpts",orgOpts); return data; } //父组织下拉 @PostMapping("/selectOrgParent") public Map<String,Object> selectOrgParent(@RequestBody EmpVO vo) { //标签分类下拉 List<EmpVO> orgParentOpts=empDao.selectOrgParent(vo); Map<String,Object> data = new HashMap(); data.put("orgParentOpts",orgParentOpts); return data; } //获取人员角色关系 @PostMapping("/getRoleChecked") public Map<String, Object> getRoleChecked(@RequestBody EmpVO vo) { //标签分类下拉 List<String> rolechecked=empDao.getRoleChecked(vo); Map<String,Object> data = new HashMap(); data.put("rolechecked",rolechecked); return data; } //获取人员角色数据 @PostMapping("/getRoleList") public Map<String, Object> getRoleList(@RequestBody EmpVO vo) { //标签分类下拉 List<EmpVO> roleList=empDao.getRoleList(vo); Map<String,Object> data = new HashMap(); data.put("roleList",roleList); return data; } //获取人员角色数据 @GetMapping("/getRoles") public Map<String, Object> getRoles() { //标签分类下拉 List<EmpVO> roleList=empDao.getRoles(); Map<String,Object> data = new HashMap(); data.put("roleList",roleList); return data; } //根据登陆人员获取角色数据 @GetMapping("/getRolesByEmp") public Map<String, Object> getRolesByEmp() { //标签分类下拉 UserInfo userInfo = UserUtil.getUserInfo(); String emp_id = userInfo.getUserId(); List<EmpVO> roleList=empDao.getRolesByEmp(emp_id); Map<String,Object> data = new HashMap(); data.put("roleList",roleList); return data; } //获取所有厂商列表 @PostMapping("/getCompanyList") public Map<String, Object> getCompanyList() { //标签分类下拉 List<Map<String,String>> companyList=empDao.getCompanyList(); Map<String,Object> data = new HashMap(); data.put("companyList",companyList); return data; } /** * 获取所属项目树 * @param * @return */ @PostMapping("/getProjectTree") public RespResult getProjectTree() { Map<String,Object> data = new HashMap<String, Object>(); try{ List<TreeNodeModel> firstNodelist = new ArrayList<TreeNodeModel>(); List<TreeNodeModel> secondNodelist = new ArrayList<TreeNodeModel>(); List<TreeNodeModel> thirdNodelist = new ArrayList<TreeNodeModel>(); firstNodelist=empDao.getfirstNodelist(); for(int j=0;firstNodelist.size()>j;j++) { secondNodelist = empDao.getChildNodeList(firstNodelist.get(j).getValue()); firstNodelist.get(j).setChildren(secondNodelist); for(int k=0;secondNodelist.size()>k;k++) { thirdNodelist = empDao.getChildNodeList(secondNodelist.get(k).getValue()); secondNodelist.get(k).setChildren(thirdNodelist); } } data.put("projectTree", firstNodelist); }catch(Exception e){ e.printStackTrace(); return RespResult.FAIL(null); } return RespResult.SUCCESS(data); } //根据人员项目查询角色 @PostMapping("/getRoleByEmpProject") public RespResult getRoleByEmpProject(@RequestBody EmpVO vo) { Map<String,Object> data = new HashMap<>(); List<Map<String,String>> roleList = empDao.getRoleByEmpProject(vo.getEmp_id(),vo.getProjectId()); data.put("roleList",roleList); return RespResult.SUCCESS(data); }}
package cn.chinatowercom.system.service;import cn.chinatowercom.common.response.RespResult;import cn.chinatowercom.framework.annotation.CurrentUser;import cn.chinatowercom.framework.annotation.LoginRequired;import cn.chinatowercom.framework.jwt.UserInfo;import cn.chinatowercom.system.dao.ImageDao;import cn.chinatowercom.system.model.ImageVo;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import org.springframework.web.bind.annotation.*;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.UUID;@Slf4j@RestController@RequestMapping("/image")@Service@Transactionalpublic class ImageService { @Autowired private ImageDao imageDao; //镜像列表数据 @LoginRequired @PostMapping("/getImageNameLoad") public Map<String,Object> getImageNameLoad(@RequestBody ImageVo vo) { List<ImageVo> list = imageDao.imageNameList(vo); int total = imageDao.imageNameCount(vo); Map<String,Object> data = new HashMap(); data.put("imgNamelist",list); data.put("imgNametotal",total); return data; } //镜像列表数据 @LoginRequired @PostMapping("/getImageLoad") public Map<String,Object> getImageLoad(@RequestBody ImageVo vo) { List<ImageVo> list = imageDao.imageList(vo); int total = imageDao.imageCount(vo); Map<String,Object> data = new HashMap(); data.put("imglist",list); data.put("imgtotal",total); return data; } // 新增修改名称 @LoginRequired @RequestMapping("/doSaveName") public Map<String, Object> doSaveName(@CurrentUser UserInfo user, @RequestBody ImageVo vo) { int res = 0; if("add".equals(vo.getType())){ vo.setId(UUID.randomUUID().toString()); vo.setCreater(user.getUserId()); vo.setCreater_name(user.getUserName()); vo.setUpdater(user.getUserId()); vo.setUpdater_name(user.getUserName()); res = imageDao.addImage(vo); } else if("update".equals(vo.getType())){ vo.setUpdater(user.getUserId()); vo.setUpdater_name(user.getUserName()); res = imageDao.updateImage(vo); } Map<String,Object> data = new HashMap(); data.put("res",res); return data; } // 新增修改版本 @LoginRequired @RequestMapping("/doSaveVersion") public Map<String, Object> doSaveVersion(@CurrentUser UserInfo user, @RequestBody ImageVo vo) { int res = 0; if("add".equals(vo.getType())){ vo.setId(UUID.randomUUID().toString()); vo.setCreater(user.getUserId()); vo.setCreater_name(user.getUserName()); vo.setUpdater(user.getUserId()); vo.setUpdater_name(user.getUserName()); res = imageDao.addImageVersion(vo); } else if("update".equals(vo.getType())){ vo.setUpdater(user.getUserId()); vo.setUpdater_name(user.getUserName()); res = imageDao.updateImageVersion(vo); } Map<String,Object> data = new HashMap(); data.put("res",res); return data; } //删除 @LoginRequired @RequestMapping ("/deleteName/{id}") public Map<String, Object> deleteName(@PathVariable("id") String id) { int deleteRes = 0; deleteRes = imageDao.deleteImage(id); Map<String,Object> data = new HashMap(); data.put("deleteRes",deleteRes); return data; } //删除 @LoginRequired @RequestMapping ("/deleteVersion/{id}") public Map<String, Object> deleteVersion(@PathVariable("id") String id) { int deleteRes = 0; deleteRes = imageDao.deleteImageVersion(id); Map<String,Object> data = new HashMap(); data.put("deleteRes",deleteRes); return data; } // 校验 @LoginRequired @RequestMapping("/checkName") public Map<String, Object> checkName(@RequestBody ImageVo vo) { int checkCount=0; checkCount=imageDao.checkImageName(vo); Map<String,Object> data = new HashMap(); data.put("checkCount", checkCount); return data; } // 校验 @LoginRequired @RequestMapping("/checkVersion") public Map<String, Object> checkVersion(@RequestBody ImageVo vo) { int checkCount=0; checkCount=imageDao.checkImageVersion(vo); Map<String,Object> data = new HashMap(); data.put("checkCount", checkCount); return data; }}
package cn.chinatowercom.system.service;import cn.chinatowercom.system.dao.SysEmpProjectRelDao;import cn.chinatowercom.system.model.SysEmpProjectRel;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.util.List;@Servicepublic class SysEmpProjectRelService { @Autowired private SysEmpProjectRelDao sysEmpProjectRelDao; public List<SysEmpProjectRel> getSysEmpProjectRelByEmpId(String emp_id) { return sysEmpProjectRelDao.getSysEmpProjectRelByEmpId(emp_id); } public int insertSysEmpProjectRel(String emp_id,List<SysEmpProjectRel> projectTree){ return sysEmpProjectRelDao.insertSysEmpProjectRel(emp_id,projectTree); } public int updateSysEmpProjectRel(String emp_id){ return sysEmpProjectRelDao.updateSysEmpProjectRel(emp_id); } public int delSysEmpProjectRel (String emp_id){ return sysEmpProjectRelDao.delSysEmpProjectRel(emp_id); }}
package cn.chinatowercom.system.service;import cn.chinatowercom.common.response.RespResult;import cn.chinatowercom.framework.annotation.LoginRequired;import cn.chinatowercom.system.dao.VersionDao;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.*;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;@Slf4j@RestController@RequestMapping("/version")public class VersionService { @Autowired private VersionDao versionDao; @LoginRequired @PostMapping("/getVersionList") public RespResult getVersionList(@RequestBody Map<String,Object> json){ List<String> list = (List)json.get("ids"); Map<String,Object> data = new HashMap<>(); String[] ids = new String[0]; if(list != null && list.size() != 0) { ids = list.toArray(new String[list.size()]); } List<String> versionList = versionDao.getVersionList(ids); data.put("versionList",versionList); return RespResult.SUCCESS(data); } @LoginRequired @PostMapping("/getTagList") public RespResult getTagList(){ Map<String,Object> data = new HashMap<>(); List<String> tagList = versionDao.getTagList(); data.put("tagList",tagList); return RespResult.SUCCESS(data); }}
package cn.chinatowercom.common.config;import org.springframework.boot.web.servlet.FilterRegistrationBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.cors.CorsConfiguration;import org.springframework.web.cors.UrlBasedCorsConfigurationSource;import org.springframework.web.filter.CorsFilter;//@Configurationpublic class CorsConfig {// @Bean// public FilterRegistrationBean corsFilter() {// UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();// CorsConfiguration config = new CorsConfiguration();// config.setAllowCredentials(true);// config.addAllowedOrigin("*");// config.addAllowedHeader("*");// config.addAllowedMethod("*");// source.registerCorsConfiguration("/**", config);// FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));// bean.setOrder(0);// return bean;// }}
package cn.chinatowercom.common.config;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;@Configurationpublic class SecurityConfig extends WebMvcConfigurerAdapter {// @Autowired// private SecurityInterceptor securityInterceptor;//// @Override// public void addInterceptors(InterceptorRegistry registry) {// registry.addInterceptor(securityInterceptor).addPathPatterns("/**");// super.addInterceptors(registry);// }}
package cn.chinatowercom.common.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import springfox.documentation.builders.ApiInfoBuilder;import springfox.documentation.builders.PathSelectors;import springfox.documentation.builders.RequestHandlerSelectors;import springfox.documentation.service.ApiInfo;import springfox.documentation.spi.DocumentationType;import springfox.documentation.spring.web.plugins.Docket;import springfox.documentation.swagger2.annotations.EnableSwagger2;@Configuration@EnableSwagger2public class Swagger2 { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("cn.chinatowercom")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("devops pipeline api") .description("API") //.termsOfServiceUrl("http://127.0.0.1:25001") .version("1.0") .build(); }}
package cn.chinatowercom.common.db;import org.springframework.stereotype.Repository;import tk.mybatis.mapper.common.Mapper;@Repositorypublic interface MapperDao extends Mapper<SchemaColumns> {}
package cn.chinatowercom.common.db;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.ApplicationContext;import org.springframework.stereotype.Service;import tk.mybatis.mapper.entity.Example;import tk.mybatis.spring.annotation.MapperScan;import java.util.List;@Slf4j@SpringBootApplication@MapperScan("cn.chinatowercom")@Servicepublic class MapperService { @Autowired private MapperDao mapperDao; @Autowired private SysDictDao sysDictDao; public List<SysDict> sysDict(String itemType) { Example example =new Example(SysDict.class); Example.Criteria criteria = example.createCriteria(); criteria.andEqualTo("itemType",itemType); criteria.andEqualTo("isValid","Y"); List<SysDict> list = sysDictDao.selectByExample(example); return list; } public void generatorMapper(String tableName,String packageName) { Example example =new Example(SchemaColumns.class); Example.Criteria criteria = example.createCriteria(); criteria.andEqualTo("tableSchema","hzp"); criteria.andEqualTo("tableName",tableName); List<SchemaColumns> list = mapperDao.selectByExample(example); String columnName = null; for(SchemaColumns sc : list) { columnName = sc.getColumnName(); log.info("@Column(name = \"{}\")",columnName); log.info("private {} {};",getDataType(sc.getDataType()),transColumnName(columnName) ); } } private static final String INTEGER = "Integer"; private static final String STRING = "String"; private static final String LONG = "Long"; private static final String DOUBLE = "Double"; private String getDataType(String dataType) { String result = null; switch (dataType) { case "bigint": result = LONG; break; case "int": result = INTEGER; break; case "tinyint": result = INTEGER; break; case "mediumint": result = INTEGER; break; case "smallint": result = INTEGER; break; case "varchar": result = STRING; break; case "text": result = STRING; break; case "enum": result = STRING; break; case "char": result = STRING; break; case "decimal": result = DOUBLE; break; case "float": result = DOUBLE; break; default: log.info("未识别类型:{}",dataType); break; } return result; } private String transColumnName(String columnName) { StringBuilder sb = new StringBuilder(); String[] names = columnName.split("_"); for(int i=0;i<names.length;i++) { if(i != 0) { names[i] = names[i].substring(0,1).toUpperCase().concat(names[i].substring(1).toLowerCase()); } sb.append(names[i]); } return sb.toString(); } public static void main(String[] args) { String tableName = "emall_store"; String packageName = ""; ApplicationContext context = SpringApplication.run(MapperService.class, args); MapperService mapperService = (MapperService)context.getBean("mapperService"); mapperService.generatorMapper(tableName,packageName); System.exit(0); }}
package cn.chinatowercom.common.db;import lombok.Data;import javax.persistence.Column;import javax.persistence.Table;@Data@Table(name = "information_schema.COLUMNS")public class SchemaColumns { @Column(name = "table_schema") private String tableSchema; @Column(name = "table_name") private String tableName; @Column(name = "column_name") private String columnName; @Column(name = "data_type") private String dataType;}
package cn.chinatowercom.common.db;import lombok.Data;import javax.persistence.Column;import javax.persistence.Table;@Data@Table(name = "sys_code_details")public class SysCodeDetails { @Column(name = "id") private Long id; @Column(name = "code_category") private String codeCategory; @Column(name = "coding") private String coding; @Column(name = "code_name") private String codeName; @Column(name = "valid_status") private String validStatus; @Column(name = "sort") private String sort; @Column(name = "code_category_name") private String codeCategoryName;}
package cn.chinatowercom.common.db;import org.springframework.stereotype.Repository;import tk.mybatis.mapper.common.Mapper;@Repositorypublic interface SysCodeDetailsDao extends Mapper<SysCodeDetails> {}
package cn.chinatowercom.common.db;import lombok.Data;import javax.persistence.Column;import javax.persistence.Table;@Data@Table(name = "sys_dict")public class SysDict { @Column(name = "item_id") private Long item_id; @Column(name = "item_type") private String itemType; @Column(name = "item_type_name") private String itemTypeName; @Column(name = "item_code") private String itemCode; @Column(name = "item_value") private String item_Value; @Column(name = "item_order") private String itemOrder; @Column(name = "is_valid") private String isValid;}
package cn.chinatowercom.common.db;import org.springframework.stereotype.Repository;import tk.mybatis.mapper.common.Mapper;@Repositorypublic interface SysDictDao extends Mapper<SysDict> {}
package cn.chinatowercom.common.exception;import cn.chinatowercom.common.response.RespResult;import lombok.extern.slf4j.Slf4j;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.ResponseBody;@Slf4j@ControllerAdvicepublic class ExceptionHandle { @ExceptionHandler(value = Exception.class) @ResponseBody public RespResult handle(Exception e) { log.error("系统异常:",e); return RespResult.FAIL(e.getMessage()); }}
package cn.chinatowercom.common.response;import io.swagger.annotations.ApiModel;import io.swagger.annotations.ApiModelProperty;import lombok.Data;@Data@ApiModel("API返回消息体")public class RespResult { @ApiModelProperty(value = "API接口是否调用成功", notes = "SUCCESS调用成功 FAILED调用失败") private String status = "SUCCESS"; @ApiModelProperty(value = "API接口执行结果描述", notes = "") private String desc; @ApiModelProperty("API接口返回数据") private Object data; /** * 执行成功返回数据 * @param data 返回数据对象 * @return */ public static RespResult SUCCESS(Object data) { return RespResult.SUCCESS(data,"执行成功"); } public static RespResult SUCCESS(Object data,String desc) { RespResult response = new RespResult(); response.desc = desc; response.data = data; return response; } /** * 执行失败返回 * @param desc 失败提示信息 * @return */ public static RespResult FAIL(String desc) { return RespResult.FAIL("FAILED",desc); } /** * 执行失败返回 * @param status 失败状态码 * @param desc 失败提示信息 * @return */ public static RespResult FAIL(String status, String desc) { RespResult response = new RespResult(); response.status = status; response.desc = desc; return response; }}
package cn.chinatowercom.common.security.dao;import cn.chinatowercom.common.security.model.UserToken;import org.springframework.stereotype.Repository;import tk.mybatis.mapper.common.Mapper;@Repositorypublic interface UserTokenDao extends Mapper<UserToken> {}
package cn.chinatowercom.common.security.model;import lombok.Data;import org.hibernate.annotations.DynamicUpdate;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.Id;import javax.persistence.Table;@Data@Entity@Table(name="emall_mb_user_token")public class UserToken { @Id @Column(name = "token_id") private Integer tokenId; @Column(name = "member_id") private Integer memberId; @Column(name = "member_name") private String memberName; @Column(name = "token") private String token; @Column(name = "login_time") private String loginTime; @Column(name = "client_type") private String clientType;}
package cn.chinatowercom.common.security;import lombok.extern.slf4j.Slf4j;import org.springframework.stereotype.Component;import org.springframework.web.servlet.HandlerInterceptor;import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;@Slf4j//@Componentpublic class SecurityInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) { return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) { }}
package cn.chinatowercom.common.security.service;import lombok.extern.slf4j.Slf4j;import org.springframework.web.bind.annotation.RestController;@Slf4j@RestControllerpublic class UserTokenService {}
package cn.chinatowercom.common.util;/**静态常量定义*/public class Constant { /**角色定义CODE:质量经理*/ public static final String SYS_ROLE_CODE_QA_MANAGER="1"; /**角色定义CODE:测试组长*/ public static final String SYS_ROLE_CODE_TEST_LEADER="15"; /**角色定义CODE:研发组长*/ public static final String SYS_ROLE_CODE_DEV_LEADER="6"; /**角色定义CODE:验收测试用例设计负责人*/ public static final String SYS_ROLE_CODE_CASE_DESIGN="17"; /**角色定义CODE:验收测试用例执行负责人*/ public static final String SYS_ROLE_CODE_CASE_RUN="18"; /**角色定义CODE:单元测试用例设计负责人*/ public static final String SYS_ROLE_CODE_T_CASE_DESIGN="19"; /**角色定义CODE:单元测试用例执行负责人*/ public static final String SYS_ROLE_CODE_T_CASE_RUN="20"; /**返回状态:成功*/ public static final String RespResultStatusSUCCESS="SUCCESS"; /**流水线任务类型:研发*/ public static final String DEVELOP_TASK_TYPE_DEV="DEV"; /**流水线任务类型:BUG*/ public static final String DEVELOP_TASK_TYPE_BUG="BUG"; /**流水线任务类型:研发(分配到责任人的末端研发任务,来自研发平台)*/ public static final String DEVELOP_TASK_TYPE_DEV_codeing="coding"; /**流水线任务类型:测试*/ public static final String DEVELOP_TASK_TYPE_TEST="TEST"; /**流水线任务类型:测试(分配到责任人的末端测试任务,来自测试平台)*/ public static final String DEVELOP_TASK_TYPE_T="T"; /**流水线任务类型:验收*/ public static final String DEVELOP_TASK_TYPE_REC="REC"; /**流水线任务类型:验收测试用例编制*/ public static final String C_CASE_DESIGN="c_case_design"; /**流水线任务类型:验收测试用例执行*/ public static final String C_CASE_RUN="c_case_run"; /**流水线任务类型:单元测试用例编制*/ public static final String T_CASE_DESIGN="t_case_design"; /**流水线任务类型:单元测试用例执行*/ public static final String T_CASE_RUN="t_case_run"; /**部署环境:研发*/ public static final String DEPLOY_ENV_DEV="dev"; /**部署环境:验收*/ public static final String DEPLOY_ENV_UAT="uat"; //=============================接口固定参数 /**测试平台固定参数:项目类型--单元测试*/ public static final String INRTERFACE_TEST_PJTYPE_UNIT_TEST="4";// /**测试平台固定参数:项目类型--验收测试*/// public static final String INRTERFACE_TEST_PJTYPE_ACCEPTANCE_TEST="4"; /**测试平台固定参数:项目类型--验收测试*/ public static final String INRTERFACE_TEST_PJTYPE_ACCEPTANCE_TEST="2";//暂时固定为1 /**测试平台固定参数:版本类型--测试*/ public static final String INRTERFACE_TEST_VERSION_TYPE_TEST="T"; /**测试平台固定参数:版本类型--验收*/ public static final String INRTERFACE_TEST_VERSION_TYPE_ACCEPTANCE="C"; /**测试平台固定参数:任务类型--测试*/ public static final String INRTERFACE_TEST_TASK_TYPE_TEST="T"; /**测试平台固定参数:任务类型--验收*/ public static final String INRTERFACE_TEST_TASK_TYPE_ACCEPTANCE="C";}
package cn.chinatowercom.common.util.email;import java.util.Map;public class EmailContent { /**是否使用模板*/ private boolean useTemp=true; /**模板名称(dode?)*/ private String tempName; /**模板值*/// private Map<String,Object> tempValue; private String tempValue; public EmailContent(boolean useTemp,String tempName,Map<String,Object> tempValueMap) { this.useTemp=useTemp; this.tempName=tempName;// this.tempValue=tempValue; this.setTempValue(tempValueMap); } public EmailContent(String tempName,Map<String,Object> tempValueMap) { this.useTemp=true; this.tempName=tempName;// this.tempValue=tempValue; this.setTempValue(tempValueMap); } public EmailContent(String tempName,String tempValue) { this.useTemp=true; this.tempName=tempName; this.tempValue=tempValue; } private void setTempValue(Map<String,Object> tempValueMap) { if(tempValueMap==null||tempValueMap.isEmpty()) { return; } } public boolean isUseTemp() { return useTemp; } public void setUseTemp(boolean useTemp) { this.useTemp = useTemp; } public String getTempName() { return tempName; } public void setTempName(String tempName) { this.tempName = tempName; }// public Map<String, Object> getTempValue() {// return tempValue;// }// public void setTempValue(Map<String, Object> tempValue) {// this.tempValue = tempValue;// } public String getTempValue() { return tempValue; } public void setTempValue(String tempValue) { this.tempValue = tempValue; } }
package cn.chinatowercom.common.util.email;import java.util.Map;import org.apache.commons.lang3.StringUtils;import com.alibaba.fastjson.JSONObject;import cn.chinatowercom.common.response.RespResult;import cn.chinatowercom.common.util.http.HttpClientUtil;import lombok.extern.slf4j.Slf4j;@Slf4jpublic class EmailService { private static final String CODE_SUCCESS="000000"; // @Value("${email.serverAddress}")// private String emailServerAddress;// @Autowired// private RestTemplate restTemplate; /**发送邮件(单收件人) * @param subject 邮件标题 * @param toAddress 收件人地址 * @param templete 邮件模板code * @param tempValue 邮件模板参数值 * @return */ public static RespResult sendEmail(String emailServerAddress,String subject,String toAddress,String templete,Map<String,Object> tempValueMap) { if(StringUtils.isBlank(subject)||StringUtils.isBlank(toAddress)||StringUtils.isBlank(templete)) { return RespResult.FAIL("邮件标题、收件人地址、邮件模板code都不能为空"); } String tempValue= ((JSONObject) JSONObject.toJSON(tempValueMap)).toString(); EmailContent contentObj=new EmailContent(templete,tempValue); String content=((JSONObject) JSONObject.toJSON(contentObj)).toString(); content=content.replaceAll("\\\\", "").replaceAll("\"", "'").replaceAll("'\\{'", "\\{'").replaceAll("'\\}'", "'\\}"); EmailVo emailParams=new EmailVo(); emailParams.setContent(content); emailParams.setIsSSL(0); emailParams.setReToEmail(toAddress); emailParams.setSubject(subject); try { JSONObject jsonObject = (JSONObject) JSONObject.toJSON(emailParams); String jsonString=jsonObject.toString(); //jsonString.replaceAll("\\\\", "");// HttpHeaders headers = new HttpHeaders();// headers.setContentType(MediaType.APPLICATION_JSON_UTF8);// headers.add("Accept", MediaType.APPLICATION_JSON.toString());// HttpEntity<String> formEntity = new HttpEntity<>(jsonObject.toString(), headers);// String result= restTemplate.postForObject("http://120.52.96.35:39002/email/sendEmail", formEntity, String.class); RespResult result=HttpClientUtil.httpPostJson(emailServerAddress, jsonString, "UTF-8"); if(!"SUCCESS".equals(result.getStatus())) { return RespResult.FAIL("发送邮件失败!"+result.getDesc()); } JSONObject obj=JSONObject.parseObject((String)result.getData()); String message=obj.getString("mes"); boolean flag=CODE_SUCCESS.equals(obj.getString("code")); if(!flag) { return RespResult.FAIL("发送邮件失败:"+message); } }catch(Exception e) { e.printStackTrace(); log.error(e.getMessage()); return RespResult.FAIL("发送邮件失败!"); } return RespResult.SUCCESS("发送邮件成功!"); }}//public String demandStateBack(@RequestBody DemandStateBackModel demandStateBackModel){// JSONObject jsonObject = (JSONObject) JSONObject.toJSON(demandStateBackModel);// HttpHeaders headers = new HttpHeaders();// headers.setContentType(MediaType.APPLICATION_JSON_UTF8);// headers.add("Accept", MediaType.APPLICATION_JSON.toString());// HttpEntity<String> formEntity = new HttpEntity<>(jsonObject.toString(), headers);// return restTemplate.postForObject(stateBackUrl, formEntity, String.class);//}
package cn.chinatowercom.common.util.email;import lombok.Data;/**发送邮件参数*/@Datapublic class EmailVo { /**发件人姓名*/ private String addName; /**发件人邮箱*/ private String addEmail; /**发件人凭证*/ private String addPwd; /**发件人服务器地址*/ private String addServer; /**是否使用ssl加密*/ private int isSSL=0; /**接收人姓名*/ private String receiveName; /**收件人邮箱 多个收件人时用逗号连接*/ private String reToEmail; /**抄送人邮箱 多个抄送人时用逗号连接*/ private String reCcEmail; /**密送人邮箱*/ private String reBccEmail; /**邮件主题*/ private String subject; /**邮件内容 * { * 'useTemp':true, 'tempName':'habh_lxfq', 'tempValue':{'name':'某某','company':'中国铁塔','nowDate':'2019/7/12','team':'架构组组件化'}}" * } * */ private String content; // /**发件人姓名*/// private String addName;// /**发件人姓名*/// private String addName;// /**发件人姓名*/// private String addName;// /**发件人姓名*/// private String addName;}
package cn.chinatowercom.common.util;import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;import javax.crypto.Cipher;import javax.crypto.KeyGenerator;import javax.crypto.SecretKey;import javax.crypto.spec.SecretKeySpec;import java.security.SecureRandom;public class EncryptUtil { public static final String DES = "DES"; public static final String KEY = "9VbJ8XfMJJL+iHEKrmrKRA=="; /** 编码格式;默认使用uft-8 */ public String charset = "utf-8"; /** DES */ public int keysizeDES = 0; /** AES */ public int keysizeAES = 128; public static EncryptUtil me; private EncryptUtil() { // 单例 } // 双重锁 public static EncryptUtil getInstance() { if (me == null) { synchronized (EncryptUtil.class) { if (me == null) { me = new EncryptUtil(); } } } return me; } /** * 使用KeyGenerator双向加密,DES/AES,注意这里转化为字符串的时候是将2进制转为16进制格式的字符串,不是直接转,因为会出错 * * @param res 加密的原文 * @param algorithm 加密使用的算法名称 * @param key 加密的秘钥 * @param keysize * @param isEncode * @return */ private String keyGeneratorES(String res, String algorithm, String key, int keysize, boolean isEncode) { try { KeyGenerator kg = KeyGenerator.getInstance(algorithm); SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); byte[] keyBytes = charset == null ? key.getBytes() : key.getBytes(charset); secureRandom.setSeed(keyBytes); kg.init(secureRandom); SecretKey sk = kg.generateKey(); SecretKeySpec sks = new SecretKeySpec(sk.getEncoded(), algorithm); Cipher cipher = Cipher.getInstance(algorithm); if (isEncode) { cipher.init(Cipher.ENCRYPT_MODE, sks); byte[] resBytes = charset == null ? res.getBytes() : res.getBytes(charset); return parseByte2HexStr(cipher.doFinal(resBytes)); } else { cipher.init(Cipher.DECRYPT_MODE, sks); return new String(cipher.doFinal(parseHexStr2Byte(res))); } } catch (Exception e) { e.printStackTrace(); } return null; } private String base64(byte[] res) { return Base64.encode(res); } /** 将二进制转换成16进制 */ public static String parseByte2HexStr(byte buf[]) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < buf.length; i++) { String hex = Integer.toHexString(buf[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } sb.append(hex.toUpperCase()); } return sb.toString(); } /** 将16进制转换为二进制 */ public static byte[] parseHexStr2Byte(String hexStr) { if (hexStr.length() < 1) return null; byte[] result = new byte[hexStr.length() / 2]; for (int i = 0; i < hexStr.length() / 2; i++) { int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16); int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16); result[i] = (byte) (high * 16 + low); } return result; } /** * 使用DES加密算法进行加密(可逆) * * @param res 需要加密的原文 * @param key 秘钥 * @return */ public String DESencode(String res, String key) { return keyGeneratorES(res, DES, key, keysizeDES, true); } /** * 对使用DES加密算法的密文进行解密(可逆) * * @param res 需要解密的密文 * @param key 秘钥 * @return */ public String DESdecode(String res, String key) { return keyGeneratorES(res, DES, key, keysizeDES, false); } public static void main(String[] args) { EncryptUtil util = EncryptUtil.getInstance(); EncryptUtil util1 = EncryptUtil.getInstance(); EncryptUtil util2 = EncryptUtil.getInstance(); String encode = util.DESencode("admin", util.KEY); String encode1 = util1.DESencode("admin", util1.KEY); String encode2 = util2.DESencode("admin", util2.KEY); System.out.println(encode); System.out.println(encode1); System.out.println(encode2);// String key = "9VbJ8XfMJJL+iHEKrmrKRA==";// String encode = util.DESencode("admin",key);// String encode1 = util1.DESencode("admin",key);// String decode = util.DESdecode(encode,key);// String decode1 = util1.DESdecode("6BC665143237AFC0",key);// System.out.println(encode+":"+decode);// System.out.println(encode1+":"+decode1); }}
package cn.chinatowercom.common.util.enums;public enum DevelopTaskType { DEV("DEV", "研发任务"), //流水线任务类型:研发 DEV_CODING("coding", "研发任务"),//(分配到责任人的末端研发任务,来自研发平台) TEST("TEST", "测试任务"), //流水线任务类型:测试 T("T", "测试任务"), //(分配到责任人的末端测试任务,来自测试平台) T_CASE_DESIGN("t_case_design", "用例编制"), //(分配到责任人的末端测试任务:单元测试用例编制) T_CASE_RUN("t_case_run", "用例执行"), //(分配到责任人的末端测试任务:单元测试用例执行) REC("REC", "验收任务"), //流水线任务类型:验收 C("C", "验收任务"), //(分配到责任人的末端验收任务,来自测试平台) C_CASE_DESIGN("c_case_design", "用例编制"), //(分配到责任人的末端验收任务:验收测试用例编制) C_CASE_RUN("c_case_run", "用例执行") //(分配到责任人的末端验收任务:验收测试用例执行) ; private String code; private String name; private DevelopTaskType(String code, String name) { this.code = code; this.name = name(); } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; }}
package cn.chinatowercom.common.util.enums;import org.apache.commons.lang3.StringUtils;public enum ProjectType { JAR("1", "微服务","jar"), VUE("2", "VUE前端项目","tar"), WAR("3", "WEB项目","war"); private String code; private String name; private String targetType; /**根据项目类型code获取打包类型*/ public static String getTargetTypeByCode(String code) { if(StringUtils.isBlank(code)) { return null; } if(ProjectType.JAR.getCode().equals(code)) { return ProjectType.JAR.getTargetType(); }else if(ProjectType.WAR.getCode().equals(code)) { return ProjectType.WAR.getTargetType(); }else if(ProjectType.VUE.getCode().equals(code)) { return ProjectType.VUE.getTargetType(); } return null; } private ProjectType(String code, String name,String targetType) { this.code = code; this.name = name; this.targetType=targetType; } public String getCode() { return code; } public String getName() { return name; } public String getTargetType() { return targetType; }}
package cn.chinatowercom.common.util.enums;/**测试平台环节命名称*/public enum TestPlatformLinkName { CASE_DESIGN("1","用例"),CASE_RUN("2","执行"); private String code; private String name; private TestPlatformLinkName(String code,String name) { this.code = code; this.name = name; } public String getCode() { return code; } public String getName() { return name; } }
package cn.chinatowercom.common.util.http;import java.io.IOException;import java.util.Map;import org.apache.http.HttpEntity;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClientBuilder;import org.apache.http.util.EntityUtils;import cn.chinatowercom.common.response.RespResult;public class HttpClientUtil { private static final String ContentTypeJson="application/json"; private static final String ContentTypeHtml="text/html"; /**发送http json请求*/ public static RespResult httpPostJson(String url,String jsonString,String charset){ CloseableHttpClient httpClient = HttpClientBuilder.create().build(); // 创建Post请求 HttpPost httpPost = new HttpPost(url); StringEntity entity = new StringEntity(jsonString, charset); httpPost.setEntity(entity); httpPost.setHeader("Content-Type", ContentTypeJson);// httpPost.setHeader("charset",charset); // 响应模型 CloseableHttpResponse response = null; try { // 由客户端执行(发送)Post请求 response = httpClient.execute(httpPost); // 从响应模型中获取响应实体 HttpEntity responseEntity = response.getEntity(); if(200!=(response.getStatusLine().getStatusCode())) { String ss=EntityUtils.toString(responseEntity); System.out.println(ss); return RespResult.FAIL("远程服务请求错误"); } return RespResult.SUCCESS(responseEntity==null?null:EntityUtils.toString(responseEntity), "远程服务请求成功"); } catch (Exception e) { e.printStackTrace(); return RespResult.FAIL("远程服务请求错误:"+e.getMessage()); } finally { try { // 释放资源 if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } } /**直接发送http请求get*/ public static RespResult httpGetUrL(String url,String charset,Map<String,String> header){ CloseableHttpClient httpClient = HttpClientBuilder.create().build(); // 创建Post请求 HttpGet httpGet = new HttpGet(url);// StringEntity entity = new StringEntity(jsonString, charset);// httpGet.setEntity(entity); httpGet.setHeader("Content-Type", ContentTypeHtml); if(header!=null&&!header.isEmpty()) { for(String key:header.keySet()) { httpGet.setHeader(key, header.get(key)); } }// httpGet.setHeader("PRIVATE-TOKEN", tonken);// httpPost.setHeader("charset",charset); // 响应模型 CloseableHttpResponse response = null; try { // 由客户端执行(发送)Get请求 response = httpClient.execute(httpGet); // 从响应模型中获取响应实体 HttpEntity responseEntity = response.getEntity(); if(200!=(response.getStatusLine().getStatusCode())) { String ss=EntityUtils.toString(responseEntity); System.out.println(ss); return RespResult.FAIL("远程服务请求错误"); } return RespResult.SUCCESS(responseEntity==null?null:EntityUtils.toString(responseEntity), "远程服务请求成功"); } catch (Exception e) { e.printStackTrace(); return RespResult.FAIL("远程服务请求错误:"+e.getMessage()); } finally { try { // 释放资源 if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } }}
package cn.chinatowercom.common.util;import io.kubernetes.client.apis.*;public class KubeApi { public ApisApi ApisApi(){ return new ApisApi(); } public AppsApi AppsApi() { return new AppsApi(); } public AppsV1Api AppsV1Api() { return new AppsV1Api(); } public AppsV1beta1Api AppsV1beta1Api() { return new AppsV1beta1Api(); } public AuthenticationApi AuthenticationApi() { return new AuthenticationApi(); } public AuthenticationV1Api AuthenticationV1Api() { return new AuthenticationV1Api(); } public AuthenticationV1beta1Api AuthenticationV1beta1Api() { return new AuthenticationV1beta1Api(); } public AuthorizationApi AuthorizationApi() { return new AuthorizationApi(); } public AuthorizationV1Api AuthorizationV1Api() { return new AuthorizationV1Api(); } public AuthorizationV1beta1Api AuthorizationV1beta1Api() { return new AuthorizationV1beta1Api(); } public AutoscalingApi AutoscalingApi() { return new AutoscalingApi(); } public AutoscalingV1Api AutoscalingV1Api() { return new AutoscalingV1Api(); } public BatchApi BatchApi() { return new BatchApi(); } public BatchV1Api BatchV1Api() { return new BatchV1Api(); } public BatchV2alpha1Api BatchV2alpha1Api() { return new BatchV2alpha1Api(); } public CertificatesApi CertificatesApi() { return new CertificatesApi(); } public CertificatesV1beta1Api CertificatesV1beta1Api() { return CertificatesV1beta1Api(); } public CoreApi CoreApi() { return new CoreApi(); } public CoreV1Api CoreV1Api() { return new CoreV1Api(); } public ExtensionsApi ExtensionsApi() { return new ExtensionsApi(); } public ExtensionsV1beta1Api ExtensionsV1beta1Api() { return new ExtensionsV1beta1Api(); } public LogsApi LogsApi() { return new LogsApi(); } public PolicyApi PolicyApi() { return new PolicyApi(); } public PolicyV1beta1Api PolicyV1beta1Api() { return new PolicyV1beta1Api(); } public RbacAuthorizationApi RbacAuthorizationApi() { return new RbacAuthorizationApi(); } public RbacAuthorizationV1alpha1Api RbacAuthorizationV1alpha1Api() { return new RbacAuthorizationV1alpha1Api(); } public SettingsApi SettingsApi() { return new SettingsApi(); } public SettingsV1alpha1Api SettingsV1alpha1Api() { return new SettingsV1alpha1Api(); } public StorageApi StorageApi() { return new StorageApi(); } public StorageV1Api StorageV1Api() { return new StorageV1Api(); } public StorageV1beta1Api StorageV1beta1Api() { return new StorageV1beta1Api(); } public VersionApi VersionApi() { return new VersionApi(); }}
//package cn.chinatowercom.common.util;////import com.sun.jersey.api.client.Client;//import com.sun.jersey.api.client.WebResource;//import com.sun.jersey.api.client.config.DefaultClientConfig;//import com.sun.jersey.client.urlconnection.URLConnectionClientHandler;//import lombok.extern.slf4j.Slf4j;////import javax.ws.rs.core.MediaType;////@Slf4j//public class KubeRestClient {//// private static String apiServiceUrl;// private Client _client;//// public KubeRestClient(String apiServiceUrl) {// this.apiServiceUrl = apiServiceUrl;// DefaultClientConfig config = new DefaultClientConfig();// config.getProperties().put(URLConnectionClientHandler.PROPERTY_HTTP_URL_CONNECTION_SET_METHOD_WORKAROUND,true);// _client = Client.create(config);// }//// public String get(String url) {// WebResource resource = _client.resource(this.apiServiceUrl+url);// String response = resource.accept(MediaType.APPLICATION_JSON).get(String.class);// log.info(response);// return response;// }//// public String post(String url,String bodyString) {// WebResource resource = _client.resource(this.apiServiceUrl+url);// String response = resource.type("application/yaml").post(String.class,bodyString);// log.info(response);// return response;// }//// public String delete(String url,String bodyString) {// WebResource resource = _client.resource(this.apiServiceUrl+url);// String response = resource.type("application/yaml").delete(String.class,bodyString);// log.info(response);// return response;// }////}
package cn.chinatowercom.common.util;import cn.chinatowercom.framework.jwt.UserInfo;import cn.chinatowercom.framework.util.PortalConst;import org.springframework.web.context.request.RequestContextHolder;import org.springframework.web.context.request.ServletRequestAttributes;import javax.servlet.http.HttpServletRequest;public class UserUtil { private static ThreadLocal<Integer> local = new ThreadLocal<Integer>(); public static void setUser(Integer memberId) { local.set(memberId); } public static Integer getUser(){ return local.get(); } public static UserInfo getUserInfo() { ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes(); HttpServletRequest request = servletRequestAttributes.getRequest(); return (UserInfo)request.getAttribute(PortalConst.CURRENT_USER); } public static void remove() { local.remove(); }}
package cn.chinatowercom.framework.annotation;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target({ElementType.PARAMETER})@Retention(RetentionPolicy.RUNTIME)public @interface CurrentUser {}
package cn.chinatowercom.framework.annotation;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target({ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)public @interface LoginRequired {}
package cn.chinatowercom.framework;import lombok.extern.slf4j.Slf4j;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClientBuilder;import org.springframework.beans.factory.annotation.Value;import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;import org.springframework.cloud.client.loadbalancer.LoadBalanced;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.http.client.ClientHttpRequestFactory;import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;import org.springframework.http.client.SimpleClientHttpRequestFactory;import org.springframework.web.client.RestTemplate;import sun.net.www.http.HttpClient;@Slf4j@Configuration@ConditionalOnClass(value = {RestTemplate.class, HttpClient.class})public class HttpClientConfiguration { @Value("${httpClientConfig.connMaxTotal:0}") private Integer connMaxTotal; // 连接池默认连接数 @Value("${httpClientConfig.maxPerRoute:20}") private Integer maxPerRoute; // 单个主机的最大连接数 @Value("${httpClientConfig.connRequestTimeout:60000}") private Integer connRequestTimeout; // 连接超时默认2s @Value("${httpClientConfig.connReadTimeout:60000}") private Integer connReadTimeout; // 读取超时时间,默认3秒 private ClientHttpRequestFactory createFactory() { if (this.connMaxTotal <= 0) { SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); factory.setConnectTimeout(this.connRequestTimeout); factory.setReadTimeout(this.connReadTimeout); return factory; } CloseableHttpClient httpClient = HttpClientBuilder.create().setMaxConnTotal(this.connMaxTotal).setMaxConnPerRoute(this.maxPerRoute).build(); HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient); factory.setConnectTimeout(this.connRequestTimeout); factory.setReadTimeout(this.connReadTimeout); log.info("connReadTimeout={}",this.connReadTimeout); return factory; } @Bean @LoadBalanced @ConditionalOnMissingBean(RestTemplate.class) public RestTemplate getRestTemplate() { RestTemplate restTemplate = new RestTemplate(this.createFactory());// List<HttpMessageConverter<?>> converterList = restTemplate.getMessageConverters();//// //重新设置StringHttpMessageConverter字符集为UTF-8,解决中文乱码问题// HttpMessageConverter<?> converterTarget = null;// for (HttpMessageConverter<?> item : converterList) {// if (StringHttpMessageConverter.class == item.getClass()) {// converterTarget = item;// break;// }// }// if (null != converterTarget) {// converterList.remove(converterTarget);// }// converterList.add(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));//// //加入FastJson转换器 根据使用情况进行操作,此段注释,默认使用jackson// FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();// List<MediaType> supportedMediaTypes = new ArrayList<>();// supportedMediaTypes.add(MediaType.APPLICATION_JSON);// supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);// supportedMediaTypes.add(MediaType.APPLICATION_ATOM_XML);// supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);// supportedMediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);// supportedMediaTypes.add(MediaType.APPLICATION_PDF);// supportedMediaTypes.add(MediaType.APPLICATION_RSS_XML);// supportedMediaTypes.add(MediaType.APPLICATION_XHTML_XML);// supportedMediaTypes.add(MediaType.APPLICATION_XML);// supportedMediaTypes.add(MediaType.IMAGE_GIF);// supportedMediaTypes.add(MediaType.IMAGE_JPEG);// supportedMediaTypes.add(MediaType.IMAGE_PNG);// supportedMediaTypes.add(MediaType.TEXT_EVENT_STREAM);// supportedMediaTypes.add(MediaType.TEXT_HTML);// supportedMediaTypes.add(MediaType.TEXT_MARKDOWN);// supportedMediaTypes.add(MediaType.TEXT_PLAIN);// supportedMediaTypes.add(MediaType.TEXT_XML);// fastConverter.setSupportedMediaTypes(supportedMediaTypes);// converterList.add(fastConverter);// //converterList.add(new FastJsonHttpMessageConverter4()); return restTemplate; }}
package cn.chinatowercom.framework.intercepter;import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;public class FastJsonHttpMessageConverterEx extends FastJsonHttpMessageConverter { public FastJsonHttpMessageConverterEx() { // } @Override protected boolean supports(Class<?> clazz) { return super.supports(clazz); }}
package cn.chinatowercom.framework.intercepter;import cn.chinatowercom.common.util.UserUtil;import cn.chinatowercom.framework.jwt.UserInfo;import cn.chinatowercom.framework.util.PortalConst;import lombok.extern.slf4j.Slf4j;import org.springframework.stereotype.Component;import feign.RequestInterceptor;import feign.RequestTemplate;@Component@Slf4jpublic class FeignInterceptor implements RequestInterceptor { @Override public void apply(RequestTemplate rt) { UserInfo userInfo = UserUtil.getUserInfo(); if(userInfo != null) { rt.header(PortalConst.ACCESS_TOKEN, userInfo.getToken()); log.debug("header :{}", userInfo.toString()); } }}
package cn.chinatowercom.framework.intercepter;import cn.chinatowercom.client.sys.LoginClient;import cn.chinatowercom.client.sys.UserModel;import com.fasterxml.jackson.databind.ObjectMapper;import cn.chinatowercom.framework.annotation.LoginRequired;import cn.chinatowercom.framework.jwt.JwtUtil;import cn.chinatowercom.framework.jwt.UserInfo;import cn.chinatowercom.framework.util.JSONResult;import cn.chinatowercom.framework.util.PortalConst;import cn.chinatowercom.framework.util.PortalStringUtil;import io.jsonwebtoken.Claims;import io.jsonwebtoken.Jws;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.BeanUtils;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.*;import org.springframework.stereotype.Component;import org.springframework.util.LinkedMultiValueMap;import org.springframework.util.MultiValueMap;import org.springframework.web.client.RestTemplate;import org.springframework.web.method.HandlerMethod;import org.springframework.web.servlet.HandlerInterceptor;import org.springframework.web.servlet.ModelAndView;import sun.net.www.http.HttpClient;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.lang.reflect.Method;import java.net.URI;import java.util.HashMap;import java.util.LinkedHashMap;import java.util.Map;@Slf4j@Componentpublic class TokenIntercepter implements HandlerInterceptor { @Autowired private LoginClient loginClient; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (!(handler instanceof HandlerMethod)) { return true; } HandlerMethod handlerMethod = (HandlerMethod) handler; Method method = handlerMethod.getMethod(); LoginRequired methodAnnotation = method.getAnnotation(LoginRequired.class); if (null != methodAnnotation) { String token = request.getHeader(PortalConst.ACCESS_TOKEN); if (PortalStringUtil.isNullOrEmpty(token)) { throw new RuntimeException("Token信息不存在,请登录"); } if (!JwtUtil.checkJWT(token)) { throw new RuntimeException("Token错误,请重新登录"); } Jws<Claims> claims = JwtUtil.parseJWT(token); String userType = claims.getBody().getSubject(); String userId = claims.getBody().getId(); // 管理员登录 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); headers.add("Accept", MediaType.APPLICATION_JSON.toString()); MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>(); paramMap.add("token",token); String str = new ObjectMapper().writeValueAsString(paramMap); HttpEntity<String> formEntity = new HttpEntity<String>(str, headers); //restTemplate.postForObject(PortalConst.CUSTOMER_LOGIN_URL, formEntity, JSONResult.class); JSONResult result = loginClient.getUserByToken(token); UserModel user = (UserModel)result.getData(); UserInfo userInfo = new UserInfo(); BeanUtils.copyProperties(user,userInfo); userInfo.setUserName(user.getEmpName()); userInfo.setUserType(userType); userInfo.setUserId(userId); userInfo.setToken(token); userInfo.setDesc("成功返回"); userInfo.setUserAccount(user.getEmpAccount()); log.info("------用户信息----{}---{}",userType,userId); request.setAttribute(PortalConst.CURRENT_USER,userInfo); return true; } return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) { //Do nothing } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { //Do nothing }}
package cn.chinatowercom.framework.intercepter;import cn.chinatowercom.framework.annotation.CurrentUser;import cn.chinatowercom.framework.jwt.UserInfo;import cn.chinatowercom.framework.util.PortalConst;import org.springframework.core.MethodParameter;import org.springframework.stereotype.Component;import org.springframework.web.bind.support.WebDataBinderFactory;import org.springframework.web.context.request.NativeWebRequest;import org.springframework.web.context.request.RequestAttributes;import org.springframework.web.method.support.HandlerMethodArgumentResolver;import org.springframework.web.method.support.ModelAndViewContainer;import org.springframework.web.multipart.support.MissingServletRequestPartException;@Componentpublic class UserMethodArgumentResolver implements HandlerMethodArgumentResolver{ @Override public boolean supportsParameter(MethodParameter parameter) { return parameter.getParameterType().isAssignableFrom(UserInfo.class) && parameter.hasParameterAnnotation(CurrentUser.class); } @Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { UserInfo user = (UserInfo) webRequest.getAttribute(PortalConst.CURRENT_USER,RequestAttributes.SCOPE_REQUEST); if (null != user) { return user; } throw new MissingServletRequestPartException(PortalConst.CURRENT_USER); }}
package cn.chinatowercom.framework;import cn.chinatowercom.framework.intercepter.FastJsonHttpMessageConverterEx;import cn.chinatowercom.framework.intercepter.TokenIntercepter;import cn.chinatowercom.framework.intercepter.UserMethodArgumentResolver;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.http.converter.HttpMessageConverter;import org.springframework.web.method.support.HandlerMethodArgumentResolver;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;import javax.annotation.Resource;import java.util.List;@Configurationpublic class JNWebConfig extends WebMvcConfigurerAdapter { @Resource private TokenIntercepter tokenIntercepter; @Resource private UserMethodArgumentResolver userMethodArgumentResolver; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(tokenIntercepter).addPathPatterns("/**"); super.addInterceptors(registry); } @Override public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { argumentResolvers.add(userMethodArgumentResolver); super.addArgumentResolvers(argumentResolvers); }// @Override// public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {// converters.add(fastJsonHttpMessageConverterEx());// super.configureMessageConverters(converters);// }////// @Bean// public FastJsonHttpMessageConverterEx fastJsonHttpMessageConverterEx() {// return new FastJsonHttpMessageConverterEx();// } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { super.addResourceHandlers(registry); registry.addResourceHandler("/**").addResourceLocations("classpath:/META-INF/resources/").setCachePeriod(0); }}
package cn.chinatowercom.framework.jwt;import cn.chinatowercom.framework.util.PortalConst;import io.jsonwebtoken.Claims;import io.jsonwebtoken.Jws;import io.jsonwebtoken.Jwts;import io.jsonwebtoken.SignatureAlgorithm;import io.jsonwebtoken.impl.crypto.MacProvider;//import lombok.extern.slf4j.Slf4j;import org.apache.commons.codec.binary.Base64;import org.apache.commons.lang3.StringUtils;import org.joda.time.DateTime;import javax.crypto.SecretKey;import javax.crypto.spec.SecretKeySpec;import java.security.Key;import java.util.Date;import java.util.UUID;/** * JWT校验工具类 * <ol> * <li>iss: jwt签发者</li> * <li>sub: jwt所面向的用户</li> * <li>aud: 接收jwt的一方</li> * <li>exp: jwt的过期时间,这个过期时间必须要大于签发时间</li> * <li>nbf: 定义在什么时间之前,该jwt都是不可用的</li> * <li>iat: jwt的签发时间</li> * <li>jti: jwt的唯一身份标识,主要用来作为一次性token,从而回避重放攻击</li> * </ol> *///@Slf4jpublic class JwtUtil { /** * JWT 加解密类型 */ private static final SignatureAlgorithm JWT_ALG = SignatureAlgorithm.HS256; /** * JWT 生成密钥使用的密码 */ private static final String JWT_RULE = "JINGTAIKEJIDALIAN"; /** * JWT 添加至HTTP HEAD中的前缀 */ private static final String JWT_SEPARATOR = "JTKJ "; /** * 使用JWT默认方式,生成加解密密钥 * * @param alg 加解密类型 * @return */ public static SecretKey generateKey(SignatureAlgorithm alg) { return MacProvider.generateKey(alg); } /** * 使用指定密钥生成规则,生成JWT加解密密钥 * * @param alg 加解密类型 * @param rule 密钥生成规则 * @return */ public static SecretKey generateKey(SignatureAlgorithm alg, String rule) { // 将密钥生成键转换为字节数组 byte[] bytes = Base64.decodeBase64(rule); // 根据指定的加密方式,生成密钥 return new SecretKeySpec(bytes, alg.getJcaName()); } /** * 构建JWT * * @param alg jwt 加密算法 * @param key jwt 加密密钥 * @param sub jwt 面向的用户 * @param aud jwt 接收方 * @param jti jwt 唯一身份标识 * @param iss jwt 签发者 * @param nbf jwt 生效日期时间 * @param duration jwt 有效时间,单位:秒 * @return JWT字符串 */ public static String buildJWT(SignatureAlgorithm alg, Key key, String sub, String aud, String jti, String iss, Date nbf, Integer duration) { // jwt的签发时间 DateTime iat = DateTime.now(); // jwt的过期时间,这个过期时间必须要大于签发时间 DateTime exp = null; if (duration != null) exp = (nbf == null ? iat.plusSeconds(duration) : new DateTime(nbf).plusSeconds(duration)); // 获取JWT字符串 String compact = Jwts.builder() .signWith(alg, key) .setSubject(sub) .setAudience(aud) .setId(jti) .setIssuer(iss) .setNotBefore(nbf) .setIssuedAt(iat.toDate()) .setExpiration(exp != null ? exp.toDate() : null) .compact(); // 在JWT字符串前添加"Bearer "字符串,用于加入"Authorization"请求头 return JWT_SEPARATOR + compact; } /** * 构建JWT * * @param sub jwt 面向的用户 * @param aud jwt 接收方 * @param jti jwt 唯一身份标识 * @param iss jwt 签发者 * @param nbf jwt 生效日期时间 * @param duration jwt 有效时间,单位:秒 * @return JWT字符串 */ public static String buildJWT(String sub, String aud, String jti, String iss, Date nbf, Integer duration) { return buildJWT(JWT_ALG, generateKey(JWT_ALG, JWT_RULE), sub, aud, jti, iss, nbf, duration); } /** * 构建JWT * * @param sub jwt 面向的用户 * @param jti jwt 唯一身份标识,主要用来作为一次性token,从而回避重放攻击 * @return JWT字符串 */ public static String buildJWT(String sub, String jti, Integer duration) { return buildJWT(sub, null, jti, null, null, duration); } /** * 构建JWT * <p>使用 UUID 作为 jti 唯一身份标识</p> * <p>JWT有效时间 1800 秒,即3 0 分钟</p> * * @param sub jwt 面向的用户 * @return JWT字符串 */ public static String buildJWT(String sub) { return buildJWT(sub, null, UUID.randomUUID().toString(), null, null, 1800); } /** * 解析JWT * * @param key jwt 加密密钥 * @param claimsJws jwt 内容文本 * @return {@link Jws} * @throws Exception */ public static Jws<Claims> parseJWT(Key key, String claimsJws) { // 移除 JWT 前的"Bearer "字符串 claimsJws = StringUtils.substringAfter(claimsJws, JWT_SEPARATOR); // 解析 JWT 字符串 return Jwts.parser().setSigningKey(key).parseClaimsJws(claimsJws); } public static Jws<Claims> parseJWT(String claimsJws) { claimsJws = StringUtils.substringAfter(claimsJws, JWT_SEPARATOR); SecretKey key = generateKey(JWT_ALG, JWT_RULE); return Jwts.parser().setSigningKey(key).parseClaimsJws(claimsJws); } /** * 校验JWT * * @param claimsJws jwt 内容文本 * @return ture or false */ public static Boolean checkJWT(String claimsJws) { boolean flag = false; try { SecretKey key = generateKey(JWT_ALG, JWT_RULE); // 获取 JWT 的 payload 部分 flag = (parseJWT(key, claimsJws).getBody() != null); } catch (Exception e) {// log.warn("JWT验证出错,错误原因:{}", e.getMessage()); } return flag; } /** * 校验JWT * * @param key jwt 加密密钥 * @param claimsJws jwt 内容文本 * @param sub jwt 面向的用户 * @return ture or false */ public static Boolean checkJWT(Key key, String claimsJws, String sub) { boolean flag = false; try { // 获取 JWT 的 payload 部分 Claims claims = parseJWT(key, claimsJws).getBody(); // 比对JWT中的 sub 字段 flag = claims.getSubject().equals(sub); } catch (Exception e) {// log.warn("JWT验证出错,错误原因:{}", e.getMessage()); } return flag; } /** * 校验JWT * * @param claimsJws jwt 内容文本 * @param sub jwt 面向的用户 * @return ture or false */ public static Boolean checkJWT(String claimsJws, String sub) { return checkJWT(generateKey(JWT_ALG, JWT_RULE), claimsJws, sub); } public static void main(String[] args) { System.out.println(JwtUtil.buildJWT(PortalConst.UserType.Admin,String.valueOf(20),Integer.MAX_VALUE)); }}
package cn.chinatowercom.framework.jwt;import lombok.Data;@Datapublic class UserInfo { private String userId; private String userType; private String token; private String desc; private String userName; private String roleCode; private String roleName; private String orgId; private String orgName; private String orgType; private String areaName; private String areaId; private String orgLevel; private String userAccount; private String encodeUesrAccount;}
package cn.chinatowercom.framework.model;import cn.chinatowercom.framework.util.Op;import lombok.Data;import org.hibernate.validator.constraints.NotEmpty;import javax.validation.constraints.NotNull;@Datapublic class AdminModel { @NotNull(message = "管理员ID不能为空",groups = {Op.UPDATE.class}) private Long adminId; // 管理员ID @NotEmpty(message = "账号不能为空", groups = {Op.ADD.class}) private String adminLoginName; // 管理员登录名 @NotEmpty(message = "账号不能为空", groups = {Op.ADD.class}) private String adminLoginPass; // 管理员登录密码 @NotEmpty(message = "用户名不能为空", groups = {Op.ADD.class}) private String adminName; // 管理员姓名 private String adminLastLoginTime; // 最近一次登录时间 private String adminLastLoginIp; // 最近一次登录IP private Integer deleteAvailable; // 是否可以删除}
package cn.chinatowercom.framework.util;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.*;import org.apache.commons.lang3.StringUtils;/** * 日期工具类 */public class DateUtils { /**yyyy-MM-dd*/ public static final String DATE_FROMAT_COMMON="yyyy-MM-dd"; /**yyyyMMdd*/ public static final String DATE_FROMAT_YYYYMMDD="yyyyMMdd"; /** * 获取今天 * @return String * */ public static String getToday(){ return new SimpleDateFormat("yyyy-MM-dd").format(new Date()); } /** * 获取昨天 * @return String * */ public static String getYestoday(){ Calendar cal=Calendar.getInstance(); cal.add(Calendar.DATE,-1); Date time=cal.getTime(); return new SimpleDateFormat("yyyy-MM-dd").format(time); } /** * 获取本月开始日期 * @return String * **/ public static String getMonthStart(){ Calendar cal=Calendar.getInstance(); cal.add(Calendar.MONTH, 0); cal.set(Calendar.DAY_OF_MONTH, 1); Date time=cal.getTime(); return new SimpleDateFormat("yyyy-MM-dd").format(time)+" 00:00:00"; } /** * 获取本月最后一天 * @return String * **/ public static String getMonthEnd(){ Calendar cal=Calendar.getInstance(); cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH)); Date time=cal.getTime(); return new SimpleDateFormat("yyyy-MM-dd").format(time)+" 23:59:59"; } /** * 获取下月开始日期 * @return String * **/ public static String getNextMonthStart(){ Calendar cal=Calendar.getInstance(); cal.add(Calendar.MONTH, 1); cal.set(Calendar.DAY_OF_MONTH, 1); Date time=cal.getTime(); return new SimpleDateFormat("yyyy-MM-dd").format(time)+" 00:00:00"; } /** * 获取下月最后一天 * @return String * **/ public static String getNextMonthEnd(){ Calendar cal=Calendar.getInstance(); cal.add(Calendar.MONTH, 1); cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH)); Date time=cal.getTime(); return new SimpleDateFormat("yyyy-MM-dd").format(time)+" 23:59:59"; } /** * 获取本周的第一天 * @return String * **/ public static String getWeekStart(){ Calendar cal=Calendar.getInstance(); cal.add(Calendar.WEEK_OF_MONTH, 0); cal.set(Calendar.DAY_OF_WEEK, 2); Date time=cal.getTime(); return new SimpleDateFormat("yyyy-MM-dd").format(time)+" 00:00:00"; } /** * 获取本周的最后一天 * @return String * **/ public static String getWeekEnd(){ Calendar cal=Calendar.getInstance(); cal.set(Calendar.DAY_OF_WEEK, cal.getActualMaximum(Calendar.DAY_OF_WEEK)); cal.add(Calendar.DAY_OF_WEEK, 1); Date time=cal.getTime(); return new SimpleDateFormat("yyyy-MM-dd").format(time)+" 23:59:59"; } /** * 获取本年的第一天 * @return String * **/ public static String getYearStart(){ return new SimpleDateFormat("yyyy").format(new Date())+"-01-01"; } /** * 获取本年的最后一天 * @return String * **/ public static String getYearEnd(){ Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.MONTH,calendar.getActualMaximum(Calendar.MONTH)); calendar.set(Calendar.DAY_OF_MONTH,calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); Date currYearLast = calendar.getTime(); return new SimpleDateFormat("yyyy-MM-dd").format(currYearLast)+" 23:59:59"; } /** * 获取当前时间 * @return String * **/ public static String getNow(){ SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return df.format(new Date()); } public static Date StrToDate(String str) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = null; try { date = format.parse(str); } catch (ParseException e) { e.printStackTrace(); } return date; } /**日期转字符串 按照format转换*/ public static String dateToStr(Date date,String format) { if(date==null) { return null; } if(StringUtils.isBlank(format)) { format=DATE_FROMAT_COMMON; } SimpleDateFormat sdf=new SimpleDateFormat(format); return sdf.format(date); } /**字符串转日期 按照format转换*/ public static Date strToDate(String dateStr,String format) { if(StringUtils.isBlank(dateStr)) { return null; } if(StringUtils.isBlank(format)) { format=DATE_FROMAT_COMMON; } SimpleDateFormat sdf=new SimpleDateFormat(format); Date date=null; try { date= sdf.parse(dateStr); } catch (ParseException e) { //日期格式非法 } return date; } /**转换毫秒数为时分秒显示 HH:mm:ss*/ public static String convertMillisToHMS(long millis) { Calendar c=Calendar.getInstance(); c.setTimeInMillis(millis); c.setTimeZone(TimeZone.getTimeZone("GMT+00:00")); String minuteSecondStr=new SimpleDateFormat(":mm:ss").format(c.getTime());//先转换分+秒 int hour=c.get(Calendar.HOUR_OF_DAY); //清除时分秒信息, c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.MILLISECOND, 0); c.set(Calendar.SECOND, 0); int days=Long.valueOf(c.getTimeInMillis()/86400000).intValue();//计算有多少个整数天 hour+=(days*24); return (hour<10?"0"+hour:String.valueOf(hour))+minuteSecondStr; } /**转换毫秒数为分秒显示 mm:ss*/ public static String convertMillisToMS(long millis) { Calendar c=Calendar.getInstance(); c.setTimeInMillis(millis); c.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));// String minuteSecondStr=new SimpleDateFormat(":mm:ss").format(c.getTime());//先转换分+秒 int hour=c.get(Calendar.HOUR_OF_DAY); int minute=c.get(Calendar.MINUTE); int second=c.get(Calendar.SECOND); //清除时分秒信息, c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.MILLISECOND, 0); c.set(Calendar.SECOND, 0); int days=Long.valueOf(c.getTimeInMillis()/86400000).intValue();//计算有多少个整数天 hour+=(days*24); minute+=(hour*60); return (minute<10?"0"+minute:String.valueOf(minute))+":"+(second<10?"0"+second:String.valueOf(second)); } /** * 时间转换 +8个小时 UTC->CST * * @param UTCStr * @param format * @return */ public static String UTCToCST(String UTCStr, String format) { Date date = null; SimpleDateFormat sdf = new SimpleDateFormat(format); try { date = sdf.parse(UTCStr); //System.out.println("UTC时间: " + date); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.HOUR, calendar.get(Calendar.HOUR) + 8); //calendar.getTime() 返回的是Date类型,也可以使用calendar.getTimeInMillis()获取时间戳 Date CSTDate = calendar.getTime(); return sdf.format(CSTDate); } catch (ParseException e) { throw new RuntimeException("时间转换错误"); } } /** * 字符串转long * * @param dateString * @param pattern * @return */ public static Long string2Date(String dateString, String pattern) { Long time = null; try { SimpleDateFormat sdf = new SimpleDateFormat(pattern); Date parse = sdf.parse(dateString); time = parse.getTime(); } catch (ParseException e) { e.printStackTrace(); } return time; } /** * 时间long转字符串 * * @param dateLong * @param pattern * @return */ public static String longDate2String(Long dateLong, String pattern) { SimpleDateFormat sdf = new SimpleDateFormat(pattern); Date date = new Date(dateLong); String format = sdf.format(dateLong); return format; } //2020-4-30.12 => 2020-04-30T00:00:00.000Z //时间转换 -8个小时 CST->UTC public static String dateFormat(String dateString, String pattern) { try { SimpleDateFormat sdf = new SimpleDateFormat(pattern); Date date = sdf.parse(dateString); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.HOUR, calendar.get(Calendar.HOUR) - 8); //calendar.getTime() 返回的是Date类型,也可以使用calendar.getTimeInMillis()获取时间戳 Date UTCDate = calendar.getTime(); SimpleDateFormat sdfUTC = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); String format = sdfUTC.format(UTCDate); return format; } catch (ParseException e) { e.printStackTrace(); return null; } } /** * 把现有的时间格式转为指定格式string->string * @param dateString * @param patternOld * @param patternNew * @return */ public static String stringFormatString(String dateString, String patternOld, String patternNew) { try { SimpleDateFormat sdf = new SimpleDateFormat(patternOld); Date date = sdf.parse(dateString); SimpleDateFormat sdfUTC = new SimpleDateFormat(patternNew); String format = sdfUTC.format(date); return format; } catch (ParseException e) { e.printStackTrace(); return null; } } /** * 获取某年某月的最后一天 * @param year * @param month * @return */ public static String getLastDayOfMonth(int year, int month) { Calendar cal = Calendar.getInstance(); //设置年份 cal.set(Calendar.YEAR, year); //设置月份 cal.set(Calendar.MONTH, month - 1); //获取某月最大天数 int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH); //设置日历中月份的最大天数 cal.set(Calendar.DAY_OF_MONTH, lastDay); //格式化日期 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String lastDayOfMonth = sdf.format(cal.getTime()); String lastDayOfMonthTime = lastDayOfMonth+" 23:59:59"; return lastDayOfMonthTime; } /** * 将long型时间(s)换算成最大时间单位的时间数据 多余的忽略 * @param mss * @return */ public static Map<Long, String> formatDateTime(long mss) { Map<Long, String> dateTimes = new HashMap<>(); long days = mss / ( 60 * 60 * 24); long hours = (mss % ( 60 * 60 * 24)) / (60 * 60); long minutes = (mss % ( 60 * 60)) /60; long seconds = mss % 60; if(days>0){ dateTimes.put(days,"d"); }else if(hours>0){ dateTimes.put(hours,"h"); }else if(minutes>0){ dateTimes.put(minutes,"m"); }else{ dateTimes.put(seconds,"s"); } return dateTimes; }}