Merge branch 'master' of code.gitlink.org.cn:otto/microservices into product_refact_deliver

# Conflicts:
#	microservices-common/microservices-common-core/src/main/java/com/microservices/common/core/constant/CacheConstants.java
#	microservices-modules/microservices-modules-pms/src/main/java/com/microservices/pms/pipeline/controller/PmsCiPipelinesController.java
#	microservices-modules/microservices-modules-pms/src/main/java/com/microservices/pms/pipeline/service/IPmsCiPipelinesService.java
#	microservices-modules/microservices-modules-pms/src/main/java/com/microservices/pms/pipeline/service/impl/PmsCiPipelinesServiceImpl.java
#	microservices-modules/microservices-modules-pms/src/main/java/com/microservices/pms/utils/PmsGitLinkRequestUrl.java
This commit is contained in:
OTTO 2025-03-18 17:03:23 +08:00
commit 904a1b551c
74 changed files with 5926 additions and 24 deletions

View File

@ -0,0 +1,46 @@
package com.microservices.system.api;
import com.alibaba.fastjson2.JSONObject;
import com.microservices.common.core.constant.ServiceNameConstants;
import com.microservices.system.api.factory.RemoteGatewayFallbackFactory;
import feign.Response;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.Map;
/**
* 网关
*
* @author microservices
*/
@Component
@FeignClient(contextId = "remoteGatewayService", value = ServiceNameConstants.GATEWAY_SERVICE, fallbackFactory = RemoteGatewayFallbackFactory.class)
public interface RemoteGatewayService {
/**
* 登录Sentinel
*
* @return 响应
*/
@PostMapping("/sentinel/auth/login")
Response loginSentinel(@RequestParam("username") String username, @RequestParam("password") String password);
/**
* 登录Nacos
*
* @return 响应
*/
@PostMapping(value = "/nacos/v1/auth/users/login", consumes = {"application/x-www-form-urlencoded"})
Response loginNacos(Map<String, ?> formParams);
/**
* 登录Portainer
*
* @return 响应
*/
@PostMapping("/portainer/api/auth")
Response loginPortainer(@RequestBody JSONObject loginBody);
}

View File

@ -4,7 +4,7 @@ import com.microservices.common.core.constant.SecurityConstants;
import com.microservices.common.core.constant.ServiceNameConstants;
import com.microservices.common.core.domain.R;
import com.microservices.system.api.domain.SysDept;
import com.microservices.system.api.factory.RemoteCmsFallbackFactory;
import com.microservices.system.api.factory.RemoteZoneFallbackFactory;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;
@ -15,7 +15,7 @@ import java.util.List;
*
* @author microservices
*/
@FeignClient(contextId = "remoteZoneService", value = ServiceNameConstants.ZONE_SERVICE, fallbackFactory = RemoteCmsFallbackFactory.class)
@FeignClient(contextId = "remoteZoneService", value = ServiceNameConstants.ZONE_SERVICE, fallbackFactory = RemoteZoneFallbackFactory.class)
public interface RemoteZoneService {
/**
* 新增组织时自动创建特色专区

View File

@ -0,0 +1,44 @@
package com.microservices.system.api.factory;
import com.alibaba.fastjson2.JSONObject;
import com.microservices.system.api.RemoteGatewayService;
import feign.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* 用户服务降级处理
*
* @author microservices
*/
@Component
public class RemoteGatewayFallbackFactory implements FallbackFactory<RemoteGatewayService> {
private static final Logger log = LoggerFactory.getLogger(RemoteGatewayFallbackFactory.class);
@Override
public RemoteGatewayService create(Throwable throwable) {
log.error("网关服务调用失败:{}", throwable.getMessage());
return new RemoteGatewayService() {
@Override
public Response loginSentinel(String password, String username) {
return null;
}
@Override
public Response loginNacos(Map<String, ?> formParams) {
return null;
}
@Override
public Response loginPortainer(JSONObject loginBody) {
System.out.println(throwable.getMessage());
return null;
}
};
}
}

View File

@ -5,3 +5,4 @@ com.microservices.system.api.factory.RemoteFileFallbackFactory
com.microservices.system.api.factory.RemoteCmsFallbackFactory
com.microservices.system.api.factory.RemoteZoneFallbackFactory
com.microservices.system.api.factory.RemotePmsFallbackFactory
com.microservices.system.api.factory.RemoteGatewayFallbackFactory

View File

@ -208,6 +208,22 @@ public class CacheConstants {
return GITLINK_ORG_ID_OPEN_ENTERPRISE_KEY + gitlinkOrgId;
}
/**
* Sentinel Token缓存Key
*/
public final static String SENTINEL_TOKEN = "sentinel_token";
/**
* Nacos Token缓存Key
*/
public static final String NACOS_TOKEN = "nacos_token";
/**
* Portainer Token缓存Key
*/
public static final String PORTAINER_TOKEN = "portainer_token";
/**
* 专区项目Gitlink信息 Key前缀
*/
@ -237,4 +253,11 @@ public class CacheConstants {
public static String getPackageFileIsFinish(String fileIdentifier) {
return PACKAGE_FILE_IS_FINISH + fileIdentifier;
}
// 全局资源数据缓存最近一年统计数据
public final static String GLOBAL_RESOURCES_DATA_KEY = "GLOBAL_RESOURCES_DATA:";
public static String getGlobalResourcesDataKey(String startDate, String endDate) {
return GLOBAL_RESOURCES_DATA_KEY + startDate + "_TO_" + endDate;
}
}

View File

@ -0,0 +1,17 @@
package com.microservices.common.core.constant;
/**
* 异常信息常量
*
* @author otto
*/
public class ExceptionMsgConstants {
/**
* 平台通用异常
*/
public static final String SYSTEM_EXEC_ERROR = "请求处理异常,请联系管理员处理";
/**
* 重试异常
*/
public static final String RETRY_ERROR = "请求发生异常,请重新请求";
}

View File

@ -32,4 +32,8 @@ public class ServiceNameConstants {
* 项目管理模块的serviceid
*/
public static final String PMS_SERVICE = "microservices-pms";
/**
* 网关模块的serviceid
*/
public static final String GATEWAY_SERVICE = "microservices-gateway";
}

View File

@ -18,6 +18,15 @@ public class TokenConstants {
* GitLink令牌标识
*/
public static final String GitLink_Token_Key = "autologin_trustie=";
/**
* Sentinel令牌标识
*/
public static final String Sentinel_Token_Key = "sentinel_dashboard_cookie";
public static final String Portainer_Token_Key = "portainer_api_key";
/**
* Sentinel令牌标识
*/
public static final String Nacos_Token_Key = "Accesstoken";
/**
* Cookie中令牌标识
*/

View File

@ -0,0 +1,40 @@
package com.microservices.common.core.utils;
import java.util.HashMap;
public class CookieUtil {
public static HashMap<String, String> getCookieMap(String cookie) {
HashMap<String, String> map = new HashMap<>();
if (cookie != null) {
String[] cookies = cookie.split(";");
for (String cookieStr : cookies) {
String[] cookieArr = cookieStr.split("=");
String key = cookieArr[0].trim();
String value = cookieArr[1].trim();
map.put(key, value);
}
}
return map;
}
public static String getCookieValue(String cookie, String key) {
HashMap<String, String> map = getCookieMap(cookie);
return map.get(key);
}
public static String removeCookieKey(String cookie, String key) {
HashMap<String, String> map = getCookieMap(cookie);
map.remove(key);
return genCookieStr(map);
}
private static String genCookieStr(HashMap<String, String> cookieMap) {
StringBuilder stringBuilder = new StringBuilder();
for (String key : cookieMap.keySet()) {
stringBuilder.append(key).append("=").append(cookieMap.get(key)).append(";");
}
return stringBuilder.toString();
}
}

View File

@ -1,9 +1,16 @@
package com.microservices.common.security.feign;
import feign.RequestInterceptor;
import feign.codec.Encoder;
import feign.form.FormEncoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Feign 配置注册
*
@ -12,9 +19,20 @@ import org.springframework.context.annotation.Configuration;
@Configuration
public class FeignAutoConfiguration
{
// 这里会由容器自动注入HttpMessageConverters的对象工厂
@Autowired
private ObjectFactory<HttpMessageConverters> messageConverters;
@Bean
public RequestInterceptor requestInterceptor()
{
return new FeignRequestInterceptor();
}
// new一个form编码器实现支持form表单提交
// 注意这里方法名称也就是bean的名称是什么不重要
// 重要的是返回类型要是 Encoder 并且实现类必须是 FormEncoder 或者其子类
@Bean
public Encoder feignFormEncoder() {
return new FormEncoder(new SpringEncoder(messageConverters));
}
}

View File

@ -2,13 +2,18 @@ package com.microservices.gateway.config;
import feign.codec.Decoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.ResponseEntityDecoder;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import java.util.stream.Collectors;
/**
* @author otto
*/
@ -25,4 +30,10 @@ public class FeignConfig {
(new MappingJackson2HttpMessageConverter());
return () -> httpMessageConverters;
}
@Bean
@ConditionalOnMissingBean
public HttpMessageConverters messageConverters(ObjectProvider<HttpMessageConverter<?>> converters) {
return new HttpMessageConverters(converters.orderedStream().collect(Collectors.toList()));
}
}

View File

@ -11,6 +11,8 @@ import com.microservices.common.core.utils.ServletUtils;
import com.microservices.common.core.utils.StringUtils;
import com.microservices.common.redis.service.RedisService;
import com.microservices.gateway.config.properties.IgnoreWhiteProperties;
import com.microservices.gateway.service.ThirdPartyToolService;
import com.microservices.gateway.utils.CustomExecutorFactory;
import com.microservices.system.api.RemoteUserService;
import com.microservices.system.api.domain.SysUserDeptRole;
import com.microservices.system.api.utils.FeignUtils;
@ -28,9 +30,8 @@ import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
/**
* 网关鉴权
@ -51,7 +52,12 @@ public class AuthFilter implements GlobalFilter, Ordered {
@Autowired
private RemoteUserService remoteUserService;
ExecutorService executorService = Executors.newFixedThreadPool(1);
@Lazy
@Autowired
private ThirdPartyToolService thirdPartyToolService;
ThreadPoolExecutor threadPoolExecutor = CustomExecutorFactory.threadPoolExecutor;
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
@ -75,12 +81,16 @@ public class AuthFilter implements GlobalFilter, Ordered {
}
if (StringUtils.isEmpty(token)) {
if (StringUtils.isNotEmpty(gitLinkCookie)) {
return unauthorizedResponse(exchange, "令牌已过期或验证不正确!");
}
return unauthorizedResponse(exchange, "令牌不能为空");
}
Claims claims;
try {
claims = JwtUtils.parseToken(token);
} catch (Exception e) {
log.error("令牌解析失败:{}", e.getMessage());
return unauthorizedResponse(exchange, "令牌格式不正确!");
}
if (claims == null) {
@ -105,6 +115,11 @@ public class AuthFilter implements GlobalFilter, Ordered {
ServletUtils.addHeader(mutate, SecurityConstants.DETAILS_USERNAME, username);
// 内部请求来源参数清除
ServletUtils.removeHeader(mutate, SecurityConstants.FROM_SOURCE);
Mono<Void> thirdPartyRes = thirdPartyToolService.handleRequestForThirdPartyTools(exchange, request, mutate);
if (thirdPartyRes != null) {
return thirdPartyRes;
}
return chain.filter(exchange.mutate().request(mutate.build()).build());
}
@ -116,7 +131,7 @@ public class AuthFilter implements GlobalFilter, Ordered {
boolean hasUserIdentifyList = redisService.hasKey(redisKey);
if (!hasUserIdentifyList) {
// 网关采用异步架构所以此处需要通过异步请求获取本系统Token
Future<R<List<SysUserDeptRole>>> future = executorService.submit(
Future<R<List<SysUserDeptRole>>> future = threadPoolExecutor.submit(
() -> remoteUserService.getSysUserDeptRoleListByUserName(username, SecurityConstants.INNER));
try {
List<SysUserDeptRole> feignResult = FeignUtils.getReturnData(
@ -130,7 +145,7 @@ public class AuthFilter implements GlobalFilter, Ordered {
}
private String genCookieByToken(String token) {
return String.format("%s%s;",TokenConstants.GitLink_Token_Key, token);
return String.format("%s%s;", TokenConstants.GitLink_Token_Key, token);
}
private String getGitLinkRequestCookie(ServerHttpRequest request) {
@ -141,7 +156,7 @@ public class AuthFilter implements GlobalFilter, Ordered {
String token = request.getHeaders().getFirst(TokenConstants.AUTHENTICATION);
if (token != null) {
// 网关采用异步架构所以此处需要通过异步请求获取本系统Token
Future<R<Boolean>> future = executorService.submit(
Future<R<Boolean>> future = threadPoolExecutor.submit(
() -> remoteUserService.checkGitLinkUserLogin(token, SecurityConstants.INNER));
try {
Boolean feignResult = FeignUtils.getReturnData(
@ -194,7 +209,7 @@ public class AuthFilter implements GlobalFilter, Ordered {
private String getGitLinkToken(String cookie) {
if (StringUtils.isNotEmpty(cookie)) {
// 网关采用异步架构所以此处需要通过异步请求获取本系统Token
Future<R<String>> future = executorService.submit(() -> remoteUserService
Future<R<String>> future = threadPoolExecutor.submit(() -> remoteUserService
.getSysUserTokenByGitLinkCookie(cookie, SecurityConstants.INNER));
R<String> feignResult;
try {

View File

@ -0,0 +1,218 @@
package com.microservices.gateway.filter;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.microservices.common.core.constant.CacheConstants;
import com.microservices.common.core.constant.ExceptionMsgConstants;
import com.microservices.common.core.utils.StringUtils;
import com.microservices.common.core.web.domain.AjaxResult;
import com.microservices.common.redis.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.reactivestreams.Publisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.NettyWriteResponseFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets;
@Slf4j
@Component
public class GlobalResponseFilter implements GlobalFilter, Ordered {
@Autowired
private RedisService redisService;
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
String lowerUrl = request.getURI().getPath().toLowerCase();
ServerHttpResponse originalResponse = exchange.getResponse();
DataBufferFactory bufferFactory = originalResponse.bufferFactory();
// 当请求为Nacos时Nacos返回的所有非JSON响应都会被自动转换为结构化的错误信息同时将HTTP状态码设置为200适合用于规范化微服务架构的响应格式
if (lowerUrl.startsWith("/nacos")) {
ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
@Override
public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
HttpStatus status = getStatusCode() != null ? getStatusCode() : HttpStatus.INTERNAL_SERVER_ERROR;
if (!status.isError()) {
return super.writeWith(body);
}
if (status == HttpStatus.FORBIDDEN) {
log.error("nacos鉴权异常已清理redis中nacos token");
// 设置新的状态码为 200
setStatusCode(HttpStatus.OK);
// 设置响应内容类型为 JSON
getHeaders().setContentType(MediaType.APPLICATION_JSON);
// 清理Sentinel失效token
redisService.deleteObject(CacheConstants.NACOS_TOKEN);
// 创建自定义的 JSON 响应内容
String jsonBody = JSON.toJSONString(AjaxResult.error(ExceptionMsgConstants.RETRY_ERROR));
byte[] bytes = jsonBody.getBytes(StandardCharsets.UTF_8);
getHeaders().setContentLength(bytes.length);
DataBuffer dataBuffer = bufferFactory.wrap(bytes);
// 返回新的响应内容
return super.writeWith(Mono.just(dataBuffer));
}
return Flux.from(body).<String>handle((dataBuffer, synchronousSink) -> {
if (status.isError()) {
byte[] bytes = new byte[dataBuffer.readableByteCount()];
dataBuffer.read(bytes);
//释放掉内存
DataBufferUtils.release(dataBuffer);
String result = new String(bytes, StandardCharsets.UTF_8);
synchronousSink.next(result);
return;
}
synchronousSink.complete();
}).flatMap(resStr -> {
// 保留原始状态码
originalResponse.setStatusCode(HttpStatus.OK);
String errMsg;
if (!JSON.isValid(resStr)) {
errMsg = resStr;
} else {
JSONObject resJson = JSONObject.parseObject(resStr);
if (resJson.containsKey("message")) {
errMsg = resJson.getString("message");
} else {
errMsg = ExceptionMsgConstants.SYSTEM_EXEC_ERROR;
}
}
byte[] bytes = JSON.toJSONBytes(AjaxResult.error(errMsg));
getHeaders().setContentLength(bytes.length);
DataBuffer buffer = bufferFactory.wrap(bytes);
return super.writeWith(Mono.just(buffer));
}).then();
}
};
return chain.filter(exchange.mutate().response(decoratedResponse).build());
}
if (lowerUrl.startsWith("/portainer")) {
ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
@Override
public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
HttpStatus status = getStatusCode() != null ? getStatusCode() : HttpStatus.INTERNAL_SERVER_ERROR;
if (!status.isError()) {
return super.writeWith(body);
}
return Flux.from(body).<String>handle((dataBuffer, synchronousSink) -> {
if (status.isError()) {
byte[] bytes = new byte[dataBuffer.readableByteCount()];
dataBuffer.read(bytes);
//释放掉内存
DataBufferUtils.release(dataBuffer);
String result = new String(bytes, StandardCharsets.UTF_8);
synchronousSink.next(result);
}
synchronousSink.complete();
}).flatMap(resStr -> {
log.error("Portainer响应处理异常异常信息{}", resStr);
originalResponse.setStatusCode(HttpStatus.OK);
byte[] bytes;
if (JSON.isValid(resStr)) {
JSONObject resJson = JSONObject.parseObject(resStr);
if (resJson.containsKey("message")) {
String message = resJson.getString("message");
if (StringUtils.isNotBlank(message) && message.contains("A valid authorisation token is missing")) {
log.error("Portainer鉴权异常已清理redis中Portainer token");
//token失效清除redis缓存
redisService.deleteObject(CacheConstants.PORTAINER_TOKEN);
bytes = JSON.toJSONBytes(AjaxResult.error(ExceptionMsgConstants.RETRY_ERROR));
} else {
bytes = JSON.toJSONBytes(AjaxResult.error(message));
}
} else {
bytes = JSON.toJSONBytes(AjaxResult.error(ExceptionMsgConstants.SYSTEM_EXEC_ERROR));
}
} else {
bytes = JSON.toJSONBytes(AjaxResult.error(ExceptionMsgConstants.SYSTEM_EXEC_ERROR));
}
getHeaders().setContentLength(bytes.length);
DataBuffer buffer = bufferFactory.wrap(bytes);
return super.writeWith(Mono.just(buffer));
}).then();
}
};
return chain.filter(exchange.mutate().response(decoratedResponse).build());
}
if (lowerUrl.startsWith("/sentinel")) {
ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
@Override
public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
HttpStatus status = getStatusCode() != null ? getStatusCode() : HttpStatus.INTERNAL_SERVER_ERROR;
if (!status.isError()) {
return super.writeWith(body);
}
if (status == HttpStatus.UNAUTHORIZED) {
log.error("sentinel鉴权异常已清理redis中sentinel token");
// 设置新的状态码为 200
setStatusCode(HttpStatus.OK);
// 设置响应内容类型为 JSON
getHeaders().setContentType(MediaType.APPLICATION_JSON);
// 清理Sentinel失效token
redisService.deleteObject(CacheConstants.SENTINEL_TOKEN);
// 创建自定义的 JSON 响应内容
String jsonBody = JSON.toJSONString(AjaxResult.error(ExceptionMsgConstants.RETRY_ERROR));
byte[] bytes = jsonBody.getBytes(StandardCharsets.UTF_8);
getHeaders().setContentLength(bytes.length);
DataBuffer dataBuffer = bufferFactory.wrap(bytes);
// 返回新的响应内容
return super.writeWith(Mono.just(dataBuffer));
}
return Flux.from(body).<String>handle((dataBuffer, synchronousSink) -> {
if (status.isError()) {
byte[] bytes = new byte[dataBuffer.readableByteCount()];
dataBuffer.read(bytes);
//释放掉内存
DataBufferUtils.release(dataBuffer);
String result = new String(bytes, StandardCharsets.UTF_8);
synchronousSink.next(result);
}
synchronousSink.complete();
}).flatMap(resStr -> {
log.error("Sentinel响应处理异常异常信息{}", resStr);
byte[] bytes;
bytes = JSON.toJSONBytes(AjaxResult.error(ExceptionMsgConstants.SYSTEM_EXEC_ERROR));
setStatusCode(HttpStatus.OK);
getHeaders().setContentLength(bytes.length);
DataBuffer buffer = bufferFactory.wrap(bytes);
return super.writeWith(Mono.just(buffer));
}).then();
}
};
return chain.filter(exchange.mutate().response(decoratedResponse).build());
}
return chain.filter(exchange);
}
@Override
public int getOrder() {
//WRITE_RESPONSE_FILTER 之前执行
return NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER - 1;
}
}

View File

@ -1,5 +1,6 @@
package com.microservices.gateway.handler;
import com.microservices.common.core.exception.ServiceException;
import com.microservices.common.core.utils.ServletUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -19,33 +20,27 @@ import reactor.core.publisher.Mono;
*/
@Order(-1)
@Configuration
public class GatewayExceptionHandler implements ErrorWebExceptionHandler
{
public class GatewayExceptionHandler implements ErrorWebExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GatewayExceptionHandler.class);
@Override
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex)
{
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
ServerHttpResponse response = exchange.getResponse();
if (exchange.getResponse().isCommitted())
{
if (exchange.getResponse().isCommitted()) {
return Mono.error(ex);
}
String msg;
if (ex instanceof NotFoundException)
{
if (ex instanceof NotFoundException) {
msg = "服务未找到";
}
else if (ex instanceof ResponseStatusException)
{
} else if (ex instanceof ServiceException) {
msg = ex.getMessage();
} else if (ex instanceof ResponseStatusException) {
ResponseStatusException responseStatusException = (ResponseStatusException) ex;
msg = responseStatusException.getMessage();
}
else
{
} else {
msg = "内部服务器错误";
}

View File

@ -0,0 +1,22 @@
package com.microservices.gateway.service;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
/**
* 第三方工具服务类
*
* @author OTTO
*/
public interface ThirdPartyToolService {
/**
* 处理第三方工具请求
*
* @param exchange
* @param request 请求
* @param mutate 请求头获取器
*/
Mono<Void> handleRequestForThirdPartyTools(ServerWebExchange exchange, ServerHttpRequest request, ServerHttpRequest.Builder mutate);
}

View File

@ -0,0 +1,232 @@
package com.microservices.gateway.service.impl;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.microservices.common.core.constant.CacheConstants;
import com.microservices.common.core.constant.ExceptionMsgConstants;
import com.microservices.common.core.constant.TokenConstants;
import com.microservices.common.core.exception.ServiceException;
import com.microservices.common.core.utils.CookieUtil;
import com.microservices.common.core.utils.ServletUtils;
import com.microservices.common.core.utils.StringUtils;
import com.microservices.common.redis.service.RedisService;
import com.microservices.gateway.service.ThirdPartyToolService;
import com.microservices.gateway.utils.CustomExecutorFactory;
import com.microservices.system.api.RemoteGatewayService;
import feign.Response;
import org.apache.commons.io.IOUtils;
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.context.annotation.Lazy;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.io.IOException;
import java.io.StringWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author OTTO
*/
@Service
public class ThirdPartyToolServiceImpl implements ThirdPartyToolService {
private static final Logger log = LoggerFactory.getLogger(ThirdPartyToolServiceImpl.class);
@Value("${thirdPartyTools.nacos.auth.username:}")
public String nacosUsername;
@Value("${thirdPartyTools.nacos.auth.password:}")
public String nacosPassword;
@Value("${thirdPartyTools.sentinel.auth.username:}")
public String sentinelUsername;
@Value("${thirdPartyTools.sentinel.auth.password:}")
public String sentinelPassword;
@Value("${thirdPartyTools.portainer.auth.username:}")
public String portainerUsername;
@Value("${thirdPartyTools.portainer.auth.password:}")
public String portainerPassword;
@Value("${thirdPartyTools.portainer.endpoints:}")
public Integer portainerEndpoints;
ThreadPoolExecutor threadPoolExecutor = CustomExecutorFactory.threadPoolExecutor;
@Lazy
@Autowired
private RemoteGatewayService remoteGatewayService;
@Autowired
private RedisService redisService;
/**
* 处理第三方工具请求
*/
@Override
public Mono<Void> handleRequestForThirdPartyTools(ServerWebExchange exchange, ServerHttpRequest request, ServerHttpRequest.Builder mutate) {
String url = request.getURI().getPath();
String lowerUrl = url.toLowerCase();
if (StringUtils.isEmpty(lowerUrl)) {
return null;
}
// 处理Sentinel请求
if (lowerUrl.startsWith("/sentinel")) {
// 检查Cookie中是否携带sentinel cookie
String cookie = request.getHeaders().getFirst(TokenConstants.Cookie);
if (StringUtils.isNotEmpty(CookieUtil.getCookieValue(cookie, TokenConstants.Sentinel_Token_Key))) {
cookie = CookieUtil.removeCookieKey(cookie, TokenConstants.Sentinel_Token_Key);
}
String sentinelCookie = null;
if (redisService.hasKey(CacheConstants.SENTINEL_TOKEN)) {
sentinelCookie = redisService.getCacheObject(CacheConstants.SENTINEL_TOKEN);
} else {
// 网关采用异步架构所以此处需要通过异步请求获取Sentinel Token
Future<Response> future = threadPoolExecutor.submit(() -> remoteGatewayService.loginSentinel(sentinelUsername, sentinelPassword));
try {
Response response = future.get(1, TimeUnit.SECONDS);
Map<String, Collection<String>> header = response.headers();
if (header != null && header.containsKey("set-cookie")) {
sentinelCookie = header.get("set-cookie").iterator().next();
//Sentinel登录状态默认30分钟失效将Sentinel Token缓存过期时间调整为28分钟
redisService.setCacheObject(CacheConstants.SENTINEL_TOKEN, sentinelCookie, 28L, TimeUnit.MINUTES);
}
} catch (TimeoutException e) {
log.error("获取Sentinel Token超时");
} catch (InterruptedException | ExecutionException e) {
log.error("获取Sentinel Token失败{}", e.getMessage());
}
}
if (StringUtils.isNotEmpty(sentinelCookie)) {
ServletUtils.removeHeader(mutate, TokenConstants.Cookie);
mutate.header(TokenConstants.Cookie, String.format("%s;%s;", cookie, sentinelCookie));
} else {
throw new ServiceException("Sentinel服务获取Token失败");
}
}
// 处理Nacos请求
if (lowerUrl.startsWith("/nacos")) {
String nacosToken = null;
if (redisService.hasKey(CacheConstants.NACOS_TOKEN)) {
nacosToken = redisService.getCacheObject(CacheConstants.NACOS_TOKEN);
} else {
Map<String, String> nacosMap = new HashMap<>();
nacosMap.put("username", nacosUsername);
nacosMap.put("password", nacosPassword);
// 网关采用异步架构所以此处需要通过异步请求获取Nacos Token
Future<Response> future = threadPoolExecutor.submit(() -> remoteGatewayService.loginNacos(nacosMap));
try {
Response res = future.get(1, TimeUnit.SECONDS);
StringWriter writer = new StringWriter();
IOUtils.copy(res.body().asInputStream(), writer, StandardCharsets.UTF_8.name());
String str = writer.toString();
if (!JSON.isValid(str)) {
return exceptionResponse(exchange, str, res.status());
}
JSONObject resJsonObject = JSONObject.parseObject(str);
if (resJsonObject == null) {
return exceptionResponse(exchange, str, res.status());
}
nacosToken = resJsonObject.getString("accessToken");
Long tokenTtl = resJsonObject.getLong("tokenTtl");
if (nacosToken != null && tokenTtl != null) {
redisService.setCacheObject(CacheConstants.NACOS_TOKEN, nacosToken, tokenTtl - 10, TimeUnit.SECONDS);
}
} catch (TimeoutException e) {
log.error("获取Nacos Token超时");
} catch (InterruptedException | ExecutionException | IOException | NullPointerException e) {
log.error("获取Nacos Token失败{}", e.getMessage());
}
}
if (StringUtils.isNotEmpty(nacosToken)) {
mutate.header(TokenConstants.Nacos_Token_Key, nacosToken);
} else {
throw new ServiceException("Nacos服务获取Token失败");
}
}
// 处理portainer请求
if (lowerUrl.startsWith("/portainer")) {
// 处理portainer指定endpoints的问题
if (lowerUrl.startsWith("/portainer/api/endpoints/")) {
String regex = "^/portainer/api/endpoints/\\d+(/?.*)";
if (Pattern.matches(regex, lowerUrl)) {
// 替换掉endpoints
regex = "(^/portainer/api/endpoints/)(\\d+)(/?.*)";
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(url);
if (matcher.find()) {
// 替换数字部分
url = matcher.replaceAll(matcher.group(1) + portainerEndpoints + matcher.group(3));
try {
mutate.uri(new URI(url));
} catch (URISyntaxException e) {
log.error("替换Portainer请求中Endpoints时发生异常{}", e.getMessage());
}
}
}
}
String portainerToken = null;
String cookie = request.getHeaders().getFirst(TokenConstants.Cookie);
if (StringUtils.isNotEmpty(CookieUtil.getCookieValue(cookie, TokenConstants.Portainer_Token_Key))) {
cookie = CookieUtil.removeCookieKey(cookie, TokenConstants.Portainer_Token_Key);
}
if (redisService.hasKey(CacheConstants.PORTAINER_TOKEN)) {
portainerToken = redisService.getCacheObject(CacheConstants.PORTAINER_TOKEN);
} else {
// 网关采用异步架构所以此处需要通过异步请求获取Portainer Token
JSONObject loginPortainerBody = new JSONObject();
loginPortainerBody.put("username", portainerUsername);
loginPortainerBody.put("password", portainerPassword);
Future<Response> future = threadPoolExecutor.submit(() -> remoteGatewayService.loginPortainer(loginPortainerBody));
try {
Response res = future.get(1, TimeUnit.SECONDS);
StringWriter writer = new StringWriter();
IOUtils.copy(res.body().asInputStream(), writer, StandardCharsets.UTF_8.name());
String str = writer.toString();
if (!JSON.isValid(str)) {
return exceptionResponse(exchange, str, res.status());
}
JSONObject resJsonObject = JSONObject.parseObject(str);
portainerToken = resJsonObject.getString("jwt");
if (portainerToken == null) {
return exceptionResponse(exchange, str, res.status());
}
String[] tokenSplit = portainerToken.split("\\.");
String tokenBodyStr = new String(Base64.getDecoder().decode(tokenSplit[1]), StandardCharsets.UTF_8);
JSONObject tokenBody = JSONObject.parseObject(tokenBodyStr);
Long expiration = tokenBody.getLong("exp");
Long now = new Date().getTime() / 1000;
long portainerTokenTtl = expiration - now;
if (portainerTokenTtl > 20) {
redisService.setCacheObject(CacheConstants.PORTAINER_TOKEN, portainerToken, portainerTokenTtl - 10, TimeUnit.SECONDS);
}
} catch (TimeoutException e) {
log.error("获取Portainer Token超时");
} catch (InterruptedException | ExecutionException | IOException | NullPointerException e) {
log.error("获取Portainer Token失败{}", e.getMessage());
}
}
if (StringUtils.isNotEmpty(portainerToken)) {
ServletUtils.removeHeader(mutate, TokenConstants.Cookie);
ServletUtils.removeHeader(mutate, TokenConstants.AUTHENTICATION);
mutate.header(TokenConstants.AUTHENTICATION, TokenConstants.PREFIX + portainerToken);
mutate.header(TokenConstants.Cookie, String.format("%s;%s;", cookie, portainerToken));
} else {
throw new ServiceException("Portainer服务获取Token失败");
}
}
return null;
}
private Mono<Void> exceptionResponse(ServerWebExchange exchange, String msg, int code) {
log.error("[第三方工具请求处理异常]请求路径:{},异常信息:{}", exchange.getRequest().getPath(), msg);
return ServletUtils.webFluxResponseWriter(exchange.getResponse(), ExceptionMsgConstants.SYSTEM_EXEC_ERROR, code);
}
}

View File

@ -0,0 +1,35 @@
package com.microservices.gateway.utils;
import com.microservices.common.core.exception.ServiceException;
import com.microservices.common.core.threadPool.ThreadPoolExecutorWrap;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @author OTTO
*/
public class CustomExecutorFactory {
/**
* 创建线程池
* 存在并发处理的情况设置核心线程为2设置有界队列长度为100最大线程数为10
* 当超出队列已满且达到最大线程数时抛出异常
* Ncpu=CPU数量
* Ucpu=目标CPU的使用率0<=Ucpu<=1
* W/C=任务等待时间与任务计算时间的比率
* Nthreads =Ncpu*Ucpu*(1+W/C)
*/
public static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutorWrap(
4
, 10
, 10
, TimeUnit.SECONDS
, new ArrayBlockingQueue<>(100)
, Executors.defaultThreadFactory()
, (r, executor) -> {
throw new ServiceException("目前处理的人太多了,请稍后再试");
}
);
}

View File

@ -0,0 +1,137 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.microservices</groupId>
<artifactId>microservices-modules</artifactId>
<version>3.6.2</version>
</parent>
<artifactId>microservices-modules-dss</artifactId>
<description>
microservices-modules-dss数据统计模块data statistics module
</description>
<dependencies>
<!-- SpringCloud Alibaba Nacos -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- SpringCloud Alibaba Nacos Config -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<!-- SpringCloud Alibaba Sentinel -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!-- SpringBoot Actuator -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- Swagger UI -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.fox.version}</version>
</dependency>
<!-- Mysql Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- Microservices Common Async -->
<dependency>
<groupId>com.microservices</groupId>
<artifactId>microservices-common-async</artifactId>
</dependency>
<!-- Microservices Common DataSource -->
<dependency>
<groupId>com.microservices</groupId>
<artifactId>microservices-common-datasource</artifactId>
</dependency>
<!-- Microservices Common DataScope -->
<dependency>
<groupId>com.microservices</groupId>
<artifactId>microservices-common-datascope</artifactId>
</dependency>
<!-- Microservices Common Log -->
<dependency>
<groupId>com.microservices</groupId>
<artifactId>microservices-common-log</artifactId>
</dependency>
<!-- Microservices Common Swagger -->
<dependency>
<groupId>com.microservices</groupId>
<artifactId>microservices-common-swagger</artifactId>
</dependency>
<dependency>
<groupId>com.microservices</groupId>
<artifactId>microservices-common-security</artifactId>
</dependency>
<dependency>
<groupId>com.microservices</groupId>
<artifactId>microservices-common-swagger</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
</dependency>
<dependency>
<groupId>com.microservices</groupId>
<artifactId>microservices-common-core</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- 处理访问Gitlink相关接口 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.14</version>
</dependency>
<dependency>
<groupId>com.microservices</groupId>
<artifactId>microservices-common-httpClient</artifactId>
<version>3.6.2</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,46 @@
package com.microservices.dss.Interceptor;
import com.microservices.common.core.utils.SpringUtils;
import com.microservices.dss.annotation.GitlinkAdminAccessRequired;
import com.microservices.dss.projects.mapper.UserMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import static com.microservices.common.security.auth.AuthUtil.getGitLinkRequestToken;
@Component
public class GitlinkAdminAccessInterceptor implements HandlerInterceptor {
public UserMapper userMapper = SpringUtils.getBean(UserMapper.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
if (method.isAnnotationPresent(GitlinkAdminAccessRequired.class)) {
String token = getGitLinkRequestToken(request);
Long userId = userMapper.getUserIdByToken(token); // 根据token获取用户ID
if (userId == null) {
response.setStatus(HttpServletResponse.SC_FORBIDDEN); // 403 Forbidden
return false;
}
Boolean isAdmin = userMapper.getAdminStatus(userId); // 根据用户ID获取admin字段值
if (isAdmin == null || !isAdmin) {
response.setStatus(HttpServletResponse.SC_FORBIDDEN); // 403 Forbidden
return false;
}
}
}
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// 可以在这里添加一些完成后的处理逻辑
}
}

View File

@ -0,0 +1,25 @@
package com.microservices.dss;
import com.microservices.common.security.annotation.EnableCustomConfig;
import com.microservices.common.security.annotation.EnableRyFeignClients;
import com.microservices.common.swagger.annotation.EnableCustomSwagger2;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* 数据统计模块
*
* @author wanjia
*/
@EnableCustomConfig
@EnableCustomSwagger2
@EnableRyFeignClients
@SpringBootApplication
@EnableScheduling
public class MicroservicesDssApplication {
public static void main(String[] args) {
SpringApplication.run(MicroservicesDssApplication.class, args);
System.out.println("(♥◠‿◠)ノ゙ 数据统计模块启动成功 ლ(´ڡ`ლ)゙ \n");
}
}

View File

@ -0,0 +1,10 @@
package com.microservices.dss.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 GitlinkAdminAccessRequired {
}

View File

@ -0,0 +1,21 @@
package com.microservices.dss.config;
import com.microservices.dss.Interceptor.GitlinkAdminAccessInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(gitlinkAdminAccessInterceptor())
.addPathPatterns("/**");
}
public GitlinkAdminAccessInterceptor gitlinkAdminAccessInterceptor() {
return new GitlinkAdminAccessInterceptor();
}
}

View File

@ -0,0 +1,30 @@
package com.microservices.dss.enums;
public enum DssTaskStatus {
DRAFT(0, "草稿"),
AUDIT(1, "待审核"),
REJECTED(2, "已拒绝"),
PAPER_COLLECT(3, "成果征集中"),
PAPER_SELECT(4, "成果评选中"),
PUBLICITY(5, "公示中"),
CONTRACT(6, "协议签订中"),
PAYMENT(7, "支付中"),
COMPLETE(8, "已完成"),
REVISE(9, "待修缮");
private final int key;
private final String name;
DssTaskStatus(int key, String name) {
this.key = key;
this.name = name;
}
public int getKey() {
return key;
}
public String getName() {
return name;
}
}

View File

@ -0,0 +1,88 @@
package com.microservices.dss.makerspace.controller;
import com.microservices.common.core.web.controller.BaseController;
import com.microservices.common.core.web.domain.AjaxResult;
import com.microservices.dss.annotation.GitlinkAdminAccessRequired;
import com.microservices.dss.makerspace.service.ITasksService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/open/makerSpace")
@Api(tags = "数据统计-创客空间相关接口")
public class MakerSpaceDataController extends BaseController {
@Autowired
private ITasksService tasksService;
@ApiOperation("创客空间全局资源获取")
@GetMapping(value = "/total")
@GitlinkAdminAccessRequired
public AjaxResult getTotalData() {
return success(tasksService.getTotalStatisticalData());
}
@ApiOperation("创客任务新增趋势")
@GetMapping(value = "/task/trend")
@GitlinkAdminAccessRequired
public AjaxResult getTaskTrendData() {
return success(tasksService.getTaskAdditionTrendData());
}
@ApiOperation("创客成果新增趋势")
@GetMapping(value = "/paper/trend")
@GitlinkAdminAccessRequired
public AjaxResult getPaperTrendData() {
return success(tasksService.getPaperAdditionTrendData());
}
@ApiOperation("创客任务最新操作日志")
@GetMapping(value = "/task/operLog")
@GitlinkAdminAccessRequired
public AjaxResult getPaperTrendData(@ApiParam("获取最新操作日志的数量") @RequestParam Integer topNum) {
return success(tasksService.getTaskOperLogTopN(topNum));
}
@ApiOperation("创客任务奖金分布")
@GetMapping(value = "/task/bountyDistribution")
@GitlinkAdminAccessRequired
public AjaxResult getBountyDistribution() {
return success(tasksService.getBountyDistribution());
}
@ApiOperation("创客任务热度排行")
@GetMapping(value = "/task/heatRank")
@GitlinkAdminAccessRequired
public AjaxResult getHeatTopN(@ApiParam("获取热度排行的数量") @RequestParam Integer topNum) {
return success(tasksService.getTaskHeatTopN(topNum));
}
@ApiOperation("创客类型分布统计(统筹/自主)")
@GetMapping(value = "/task/mode")
@GitlinkAdminAccessRequired
public AjaxResult getTaskModeStatisticalData() {
return success(tasksService.getTaskModeStatisticalData());
}
@ApiOperation("创客任务-开启中状态任务数分布")
@GetMapping(value = "/task/statusDistribution/opening")
@GitlinkAdminAccessRequired
public AjaxResult getOpeningTaskStatusDistribution(@ApiParam("获取开启中状态任务分布的数量") @RequestParam Integer topNum) {
return success(tasksService.getOpeningTaskStatusDistribution(topNum));
}
@ApiOperation("创客任务-所有任务类型分布")
@GetMapping(value = "/task/categoryDistribution")
@GitlinkAdminAccessRequired
public AjaxResult getAllTaskCategoryDistribution() {
return success(tasksService.getAllTaskCategoryDistribution());
}
}

View File

@ -0,0 +1,387 @@
package com.microservices.dss.makerspace.domain;
import java.math.BigDecimal;
import java.util.Date;
public class Tasks {
private Integer id;
private String name;
private BigDecimal bounty;
private String number;
private Boolean published;
private Integer visits;
private Date expiredAt;
private Date publishedAt;
private Integer publishMode;
private Integer collectionMode;
private Integer showUserMode;
private Integer status;
private Integer papersCount;
private Integer taskModeId;
private Date createdAt;
private Date updatedAt;
private Integer categoryId;
private Integer userId;
private String enterpriseName;
private String contactName;
private String contactPhone;
private Boolean showUserStatus;
private Integer agreementSigning;
private Boolean isDelete;
private String ip;
private Date paidAt;
private Date makePublicAt;
private Integer collectingDays;
private Integer choosingDays;
private Integer makePublicDays;
private Integer signingDays;
private Integer payingDays;
private Boolean exceptClosedBoolean;
private Boolean isProofBoolean;
private Integer cancelStatus;
private Integer isSigningUpload;
private Boolean isPayingUpload;
private Date uploadProofAt;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public BigDecimal getBounty() {
return bounty;
}
public void setBounty(BigDecimal bounty) {
this.bounty = bounty;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number == null ? null : number.trim();
}
public Boolean getPublished() {
return published;
}
public void setPublished(Boolean published) {
this.published = published;
}
public Integer getVisits() {
return visits;
}
public void setVisits(Integer visits) {
this.visits = visits;
}
public Date getExpiredAt() {
return expiredAt;
}
public void setExpiredAt(Date expiredAt) {
this.expiredAt = expiredAt;
}
public Date getPublishedAt() {
return publishedAt;
}
public void setPublishedAt(Date publishedAt) {
this.publishedAt = publishedAt;
}
public Integer getPublishMode() {
return publishMode;
}
public void setPublishMode(Integer publishMode) {
this.publishMode = publishMode;
}
public Integer getCollectionMode() {
return collectionMode;
}
public void setCollectionMode(Integer collectionMode) {
this.collectionMode = collectionMode;
}
public Integer getShowUserMode() {
return showUserMode;
}
public void setShowUserMode(Integer showUserMode) {
this.showUserMode = showUserMode;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Integer getPapersCount() {
return papersCount;
}
public void setPapersCount(Integer papersCount) {
this.papersCount = papersCount;
}
public Integer getTaskModeId() {
return taskModeId;
}
public void setTaskModeId(Integer taskModeId) {
this.taskModeId = taskModeId;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public Integer getCategoryId() {
return categoryId;
}
public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getEnterpriseName() {
return enterpriseName;
}
public void setEnterpriseName(String enterpriseName) {
this.enterpriseName = enterpriseName == null ? null : enterpriseName.trim();
}
public String getContactName() {
return contactName;
}
public void setContactName(String contactName) {
this.contactName = contactName == null ? null : contactName.trim();
}
public String getContactPhone() {
return contactPhone;
}
public void setContactPhone(String contactPhone) {
this.contactPhone = contactPhone == null ? null : contactPhone.trim();
}
public Boolean getShowUserStatus() {
return showUserStatus;
}
public void setShowUserStatus(Boolean showUserStatus) {
this.showUserStatus = showUserStatus;
}
public Integer getAgreementSigning() {
return agreementSigning;
}
public void setAgreementSigning(Integer agreementSigning) {
this.agreementSigning = agreementSigning;
}
public Boolean getIsDelete() {
return isDelete;
}
public void setIsDelete(Boolean isDelete) {
this.isDelete = isDelete;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip == null ? null : ip.trim();
}
public Date getPaidAt() {
return paidAt;
}
public void setPaidAt(Date paidAt) {
this.paidAt = paidAt;
}
public Date getMakePublicAt() {
return makePublicAt;
}
public void setMakePublicAt(Date makePublicAt) {
this.makePublicAt = makePublicAt;
}
public Integer getCollectingDays() {
return collectingDays;
}
public void setCollectingDays(Integer collectingDays) {
this.collectingDays = collectingDays;
}
public Integer getChoosingDays() {
return choosingDays;
}
public void setChoosingDays(Integer choosingDays) {
this.choosingDays = choosingDays;
}
public Integer getMakePublicDays() {
return makePublicDays;
}
public void setMakePublicDays(Integer makePublicDays) {
this.makePublicDays = makePublicDays;
}
public Integer getSigningDays() {
return signingDays;
}
public void setSigningDays(Integer signingDays) {
this.signingDays = signingDays;
}
public Integer getPayingDays() {
return payingDays;
}
public void setPayingDays(Integer payingDays) {
this.payingDays = payingDays;
}
public Boolean getExceptClosedBoolean() {
return exceptClosedBoolean;
}
public void setExceptClosedBoolean(Boolean exceptClosedBoolean) {
this.exceptClosedBoolean = exceptClosedBoolean;
}
public Boolean getIsProofBoolean() {
return isProofBoolean;
}
public void setIsProofBoolean(Boolean isProofBoolean) {
this.isProofBoolean = isProofBoolean;
}
public Integer getCancelStatus() {
return cancelStatus;
}
public void setCancelStatus(Integer cancelStatus) {
this.cancelStatus = cancelStatus;
}
public Integer getIsSigningUpload() {
return isSigningUpload;
}
public void setIsSigningUpload(Integer isSigningUpload) {
this.isSigningUpload = isSigningUpload;
}
public Boolean getIsPayingUpload() {
return isPayingUpload;
}
public void setIsPayingUpload(Boolean isPayingUpload) {
this.isPayingUpload = isPayingUpload;
}
public Date getUploadProofAt() {
return uploadProofAt;
}
public void setUploadProofAt(Date uploadProofAt) {
this.uploadProofAt = uploadProofAt;
}
}

View File

@ -0,0 +1,21 @@
package com.microservices.dss.makerspace.domain.vo;
import lombok.Data;
import java.util.List;
@Data
public class MakerSpaceTotalDataVo {
private int totalTasks;
private int totalApplicants;
private int currentTotalAwardAmount;
private List<Object> taskPublishedCountsByYear;
private List<Object> taskBountyCountsByYear;
}

View File

@ -0,0 +1,19 @@
package com.microservices.dss.makerspace.domain.vo;
import lombok.Data;
import java.util.Date;
@Data
public class TaskHeatInfoVo {
private String taskName;
private Date publishDate;
private Integer participantCount;
private String winnerNames;
private Integer taskId;
}

View File

@ -0,0 +1,43 @@
package com.microservices.dss.makerspace.mapper;
import com.microservices.dss.makerspace.domain.vo.TaskHeatInfoVo;
import com.microservices.dss.projects.domain.PieChartNameAndValue;
import org.apache.ibatis.annotations.MapKey;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
@Mapper
public interface TasksMapper{
int getTotalTaskCount();
int getTotalApplicantCount();
int getCurrentTotalAwardAmount();
List<Object> getTaskPublishedCountsByYear();
List<Object> getTaskBountyCountsByYear();
List<Object> getNewAddedTasksByMonth(@Param("startTime") String startTime, @Param("endTime") String endTime);
List<Object> getNewAddedPapersByMonth(@Param("startTime") String startTime, @Param("endTime") String endTime);
List<Map<String, String>> getTaskOperLogTopN(@Param("topNum") Integer topNum);
List<PieChartNameAndValue> getOpeningTaskNumOfTaskStatus(@Param("topNum") Integer topNum);
List<PieChartNameAndValue> getAllTaskNumOfTaskCategory();
List<Map<String, String>> getBountyDistribution();
Map<String, String> getTotalCompletedBounty();
List<TaskHeatInfoVo> getTaskInfoByVisits(@Param("topNum") Integer topNum);
List<Map<String, String>> getTaskModeStatistic();
}

View File

@ -0,0 +1,28 @@
package com.microservices.dss.makerspace.service;
import com.microservices.dss.makerspace.domain.vo.MakerSpaceTotalDataVo;
import com.microservices.dss.makerspace.domain.vo.TaskHeatInfoVo;
import com.microservices.dss.projects.domain.PieChartNameAndValue;
import java.util.List;
import java.util.Map;
public interface ITasksService {
MakerSpaceTotalDataVo getTotalStatisticalData();
int[] getTaskAdditionTrendData();
int[] getPaperAdditionTrendData();
List<Map<String, String>> getTaskOperLogTopN(Integer topNum);
List<PieChartNameAndValue> getOpeningTaskStatusDistribution(Integer topNum);
List<PieChartNameAndValue> getAllTaskCategoryDistribution();
List<Map<String, String>> getBountyDistribution();
List<TaskHeatInfoVo> getTaskHeatTopN(Integer topNum);
List<Map<String, String>> getTaskModeStatisticalData();
}

View File

@ -0,0 +1,128 @@
package com.microservices.dss.makerspace.service.impl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.microservices.common.core.exception.ServiceException;
import com.microservices.dss.enums.DssTaskStatus;
import com.microservices.dss.makerspace.domain.vo.MakerSpaceTotalDataVo;
import com.microservices.dss.makerspace.domain.vo.TaskHeatInfoVo;
import com.microservices.dss.makerspace.mapper.TasksMapper;
import com.microservices.dss.makerspace.service.ITasksService;
import com.microservices.dss.projects.domain.PieChartNameAndValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.text.ParseException;
import java.util.List;
import java.util.Map;
import static com.microservices.dss.utils.DataStructureConvertUtil.MapInitByMonth;
import static com.microservices.dss.utils.DataStructureConvertUtil.dbResult2Array;
import static com.microservices.dss.utils.DateUtil.getFormattedCurrentDateTime;
import static com.microservices.dss.utils.DateUtil.getFormattedPreviousYearSameMonth;
@Service
public class TasksServiceImpl implements ITasksService {
private static final Logger logger = LoggerFactory.getLogger(TasksServiceImpl.class);
@Resource
private TasksMapper tasksMapper;
@Override
public MakerSpaceTotalDataVo getTotalStatisticalData() {
MakerSpaceTotalDataVo makerSpaceTotalDataVo = new MakerSpaceTotalDataVo();
makerSpaceTotalDataVo.setTotalTasks(tasksMapper.getTotalTaskCount());
makerSpaceTotalDataVo.setTotalApplicants(tasksMapper.getTotalApplicantCount());
makerSpaceTotalDataVo.setCurrentTotalAwardAmount(tasksMapper.getCurrentTotalAwardAmount()/10000);
makerSpaceTotalDataVo.setTaskPublishedCountsByYear(tasksMapper.getTaskPublishedCountsByYear());
makerSpaceTotalDataVo.setTaskBountyCountsByYear(tasksMapper.getTaskBountyCountsByYear());
return makerSpaceTotalDataVo;
}
@Override
public int[] getTaskAdditionTrendData() {
String startTime = getFormattedPreviousYearSameMonth();
String endTime = getFormattedCurrentDateTime();
try {
return getNewAddedTasksByMonth(startTime, endTime);
} catch (ParseException e) {
logger.error("ParseException occurred while getting task addition trend data", e);
throw new ServiceException("获取新增任务趋势数据失败");
} catch (JsonProcessingException e) {
logger.error("JsonProcessingException occurred while getting task addition trend data", e);
throw new ServiceException("获取新增任务趋势数据失败");
}
}
@Override
public int[] getPaperAdditionTrendData() {
String startTime = getFormattedPreviousYearSameMonth();
String endTime = getFormattedCurrentDateTime();
try {
return getNewAddedPapersByMonth(startTime, endTime);
} catch (ParseException e) {
logger.error("ParseException occurred while getting paper addition trend data", e);
throw new ServiceException("获取新增成果趋势数据失败");
} catch (JsonProcessingException e) {
logger.error("JsonProcessingException occurred while getting paper addition trend data", e);
throw new ServiceException("获取新增成果趋势数据失败");
}
}
@Override
public List<Map<String, String>> getTaskOperLogTopN(Integer topNum) {
return tasksMapper.getTaskOperLogTopN(topNum);
}
@Override
public List<PieChartNameAndValue> getOpeningTaskStatusDistribution(Integer topNum) {
List<PieChartNameAndValue> distribution = tasksMapper.getOpeningTaskNumOfTaskStatus(topNum);
for (PieChartNameAndValue pieChartNameAndValue : distribution) {
DssTaskStatus status = DssTaskStatus.values()[Integer.parseInt(pieChartNameAndValue.getName())];
pieChartNameAndValue.setName(status.getName());
}
return distribution;
}
@Override
public List<PieChartNameAndValue> getAllTaskCategoryDistribution() {
return tasksMapper.getAllTaskNumOfTaskCategory();
}
@Override
public List<Map<String, String>> getBountyDistribution() {
List<Map<String, String>> bountyDistribution = tasksMapper.getBountyDistribution();
Map<String, String> totalCompletedBounty = tasksMapper.getTotalCompletedBounty();
bountyDistribution.add(totalCompletedBounty);
return bountyDistribution;
}
@Override
public List<TaskHeatInfoVo> getTaskHeatTopN(Integer topNum) {
return tasksMapper.getTaskInfoByVisits(topNum);
}
@Override
public List<Map<String, String>> getTaskModeStatisticalData() {
return tasksMapper.getTaskModeStatistic();
}
private int[] getNewAddedTasksByMonth(String startTime, String endTime) throws ParseException, JsonProcessingException {
int monthDiff = 12;
Map<Object, Object> map_init = MapInitByMonth(monthDiff,endTime);
List<Object> Db_result = tasksMapper.getNewAddedTasksByMonth(startTime, endTime);
int[] resultArray = new int[monthDiff+1];
return dbResult2Array(Db_result,"createTime","num",map_init,resultArray);
}
private int[] getNewAddedPapersByMonth(String startTime, String endTime) throws ParseException, JsonProcessingException {
int monthDiff = 12;
Map<Object, Object> map_init = MapInitByMonth(monthDiff,endTime);
List<Object> Db_result = tasksMapper.getNewAddedPapersByMonth(startTime, endTime);
int[] resultArray = new int[monthDiff+1];
return dbResult2Array(Db_result,"createTime","num",map_init,resultArray);
}
}

View File

@ -0,0 +1,58 @@
package com.microservices.dss.projects.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.microservices.common.core.web.controller.BaseController;
import com.microservices.common.core.web.domain.AjaxResult;
import com.microservices.dss.annotation.GitlinkAdminAccessRequired;
import com.microservices.dss.projects.service.IProjectGlobalResourcesService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.text.ParseException;
@RestController
@RequestMapping("/open/projects")
@Api(tags = "数据统计-开源项目相关接口")
public class ProjectDataController extends BaseController {
@Autowired
private IProjectGlobalResourcesService projectGlobalResourcesService;
@ApiOperation("开源项目全局资源获取")
@GetMapping(value = "/global-resources")
@GitlinkAdminAccessRequired
public AjaxResult getGlobalResourcesData() throws ParseException, JsonProcessingException {
return success(projectGlobalResourcesService.getProjectGlobalResourcesData());
}
@ApiOperation("开源项目最新动态获取")
@GetMapping(value = "/latestActivities")
@GitlinkAdminAccessRequired
public AjaxResult getLatestActivitiesData(@ApiParam("分页数") @RequestParam(value = "page", defaultValue = "1") int page,
@ApiParam("分页大小") @RequestParam(value = "limit", defaultValue = "6") int limit){
return success(projectGlobalResourcesService.getLatestActivitiesData(page, limit));
}
@ApiOperation("开源项目-项目排行获取")
@GetMapping(value = "/projectRank")
@GitlinkAdminAccessRequired
public AjaxResult getProjectRankData(@ApiParam("统计时间范围(天)") @RequestParam(value = "time", defaultValue = "365") int time,
@ApiParam("top数") @RequestParam(value = "limit", defaultValue = "5") int limit){
return success(projectGlobalResourcesService.getProjectRankData(time, limit));
}
@ApiOperation("开源项目-用户排行获取")
@GetMapping(value = "/userRank")
@GitlinkAdminAccessRequired
public AjaxResult getUserRankData(@ApiParam("统计时间范围(天)") @RequestParam(value = "time", defaultValue = "365") int time,
@ApiParam("top数") @RequestParam(value = "limit", defaultValue = "5") int limit){
return success(projectGlobalResourcesService.getUserRankData(time, limit));
}
}

View File

@ -0,0 +1,95 @@
package com.microservices.dss.projects.domain;
import java.util.Date;
public class Commits {
private Integer id;
private Integer repositoryId;
private String version;
private String committer;
private Date committedOn;
private Integer projectId;
private Date createdAt;
private Date updatedAt;
private String comments;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getRepositoryId() {
return repositoryId;
}
public void setRepositoryId(Integer repositoryId) {
this.repositoryId = repositoryId;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version == null ? null : version.trim();
}
public String getCommitter() {
return committer;
}
public void setCommitter(String committer) {
this.committer = committer == null ? null : committer.trim();
}
public Date getCommittedOn() {
return committedOn;
}
public void setCommittedOn(Date committedOn) {
this.committedOn = committedOn;
}
public Integer getProjectId() {
return projectId;
}
public void setProjectId(Integer projectId) {
this.projectId = projectId;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments == null ? null : comments.trim();
}
}

View File

@ -0,0 +1,77 @@
package com.microservices.dss.projects.domain;
public class DeveloperNewDetailData {
private int id;
private String userName;
private String nickName;
private int newTask;
private int completedTask;
private int newPrNum;
private int newCommitNum;
private int newCodeNum;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public int getNewTask() {
return newTask;
}
public void setNewTask(int newTask) {
this.newTask = newTask;
}
public int getCompletedTask() {
return completedTask;
}
public void setCompletedTask(int completedTask) {
this.completedTask = completedTask;
}
public int getNewPrNum() {
return newPrNum;
}
public void setNewPrNum(int newPrNum) {
this.newPrNum = newPrNum;
}
public int getNewCommitNum() {
return newCommitNum;
}
public void setNewCommitNum(int newCommitNum) {
this.newCommitNum = newCommitNum;
}
public int getNewCodeNum() {
return newCodeNum;
}
public void setNewCodeNum(int newCodeNum) {
this.newCodeNum = newCodeNum;
}
}

View File

@ -0,0 +1,59 @@
package com.microservices.dss.projects.domain;
public class DeveloperNewDetailDataByDate {
private String date;
private int newTask;
private int completedTask;
private int newPrNum;
private int newCommitNum;
private int newCodeNum;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public int getNewTask() {
return newTask;
}
public void setNewTask(int newTask) {
this.newTask = newTask;
}
public int getCompletedTask() {
return completedTask;
}
public void setCompletedTask(int completedTask) {
this.completedTask = completedTask;
}
public int getNewPrNum() {
return newPrNum;
}
public void setNewPrNum(int newPrNum) {
this.newPrNum = newPrNum;
}
public int getNewCommitNum() {
return newCommitNum;
}
public void setNewCommitNum(int newCommitNum) {
this.newCommitNum = newCommitNum;
}
public int getNewCodeNum() {
return newCodeNum;
}
public void setNewCodeNum(int newCodeNum) {
this.newCodeNum = newCodeNum;
}
}

View File

@ -0,0 +1,315 @@
package com.microservices.dss.projects.domain;
import java.util.Date;
public class Issues {
private Integer id;
private Integer trackerId;
private Integer projectId;
private String subject;
private Date dueDate;
private Integer categoryId;
private Integer statusId;
private Integer assignedToId;
private Integer priorityId;
private Integer fixedVersionId;
private Integer authorId;
private Date createdOn;
private Date updatedOn;
private Date startDate;
private Integer doneRatio;
private Float estimatedHours;
private Integer parentId;
private Integer rootId;
private Integer lft;
private Integer rgt;
private Boolean isPrivate;
private Date closedOn;
private Integer projectIssuesIndex;
private String issueType;
private Integer token;
private String issueTagsValue;
private Boolean isLock;
private String issueClassify;
private String refName;
private String branchName;
private String description;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getTrackerId() {
return trackerId;
}
public void setTrackerId(Integer trackerId) {
this.trackerId = trackerId;
}
public Integer getProjectId() {
return projectId;
}
public void setProjectId(Integer projectId) {
this.projectId = projectId;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject == null ? null : subject.trim();
}
public Date getDueDate() {
return dueDate;
}
public void setDueDate(Date dueDate) {
this.dueDate = dueDate;
}
public Integer getCategoryId() {
return categoryId;
}
public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}
public Integer getStatusId() {
return statusId;
}
public void setStatusId(Integer statusId) {
this.statusId = statusId;
}
public Integer getAssignedToId() {
return assignedToId;
}
public void setAssignedToId(Integer assignedToId) {
this.assignedToId = assignedToId;
}
public Integer getPriorityId() {
return priorityId;
}
public void setPriorityId(Integer priorityId) {
this.priorityId = priorityId;
}
public Integer getFixedVersionId() {
return fixedVersionId;
}
public void setFixedVersionId(Integer fixedVersionId) {
this.fixedVersionId = fixedVersionId;
}
public Integer getAuthorId() {
return authorId;
}
public void setAuthorId(Integer authorId) {
this.authorId = authorId;
}
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
public Date getUpdatedOn() {
return updatedOn;
}
public void setUpdatedOn(Date updatedOn) {
this.updatedOn = updatedOn;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Integer getDoneRatio() {
return doneRatio;
}
public void setDoneRatio(Integer doneRatio) {
this.doneRatio = doneRatio;
}
public Float getEstimatedHours() {
return estimatedHours;
}
public void setEstimatedHours(Float estimatedHours) {
this.estimatedHours = estimatedHours;
}
public Integer getParentId() {
return parentId;
}
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
public Integer getRootId() {
return rootId;
}
public void setRootId(Integer rootId) {
this.rootId = rootId;
}
public Integer getLft() {
return lft;
}
public void setLft(Integer lft) {
this.lft = lft;
}
public Integer getRgt() {
return rgt;
}
public void setRgt(Integer rgt) {
this.rgt = rgt;
}
public Boolean getIsPrivate() {
return isPrivate;
}
public void setIsPrivate(Boolean isPrivate) {
this.isPrivate = isPrivate;
}
public Date getClosedOn() {
return closedOn;
}
public void setClosedOn(Date closedOn) {
this.closedOn = closedOn;
}
public Integer getProjectIssuesIndex() {
return projectIssuesIndex;
}
public void setProjectIssuesIndex(Integer projectIssuesIndex) {
this.projectIssuesIndex = projectIssuesIndex;
}
public String getIssueType() {
return issueType;
}
public void setIssueType(String issueType) {
this.issueType = issueType == null ? null : issueType.trim();
}
public Integer getToken() {
return token;
}
public void setToken(Integer token) {
this.token = token;
}
public String getIssueTagsValue() {
return issueTagsValue;
}
public void setIssueTagsValue(String issueTagsValue) {
this.issueTagsValue = issueTagsValue == null ? null : issueTagsValue.trim();
}
public Boolean getIsLock() {
return isLock;
}
public void setIsLock(Boolean isLock) {
this.isLock = isLock;
}
public String getIssueClassify() {
return issueClassify;
}
public void setIssueClassify(String issueClassify) {
this.issueClassify = issueClassify == null ? null : issueClassify.trim();
}
public String getRefName() {
return refName;
}
public void setRefName(String refName) {
this.refName = refName == null ? null : refName.trim();
}
public String getBranchName() {
return branchName;
}
public void setBranchName(String branchName) {
this.branchName = branchName == null ? null : branchName.trim();
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description == null ? null : description.trim();
}
}

View File

@ -0,0 +1,205 @@
package com.microservices.dss.projects.domain;
import java.util.Date;
public class Journals {
private Integer id;
private Integer journalizedId;
private String journalizedType;
private Integer userId;
private String notes;
private Date createdOn;
private Boolean privateNotes;
private Integer parentId;
private Integer commentsCount;
private Integer replyId;
private Long reviewId;
private String commitId;
private String lineCode;
private String path;
private Integer state;
private Date resolveAt;
private Integer resolveerId;
private Boolean needRespond;
private Date updatedOn;
private String diff;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getJournalizedId() {
return journalizedId;
}
public void setJournalizedId(Integer journalizedId) {
this.journalizedId = journalizedId;
}
public String getJournalizedType() {
return journalizedType;
}
public void setJournalizedType(String journalizedType) {
this.journalizedType = journalizedType == null ? null : journalizedType.trim();
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes == null ? null : notes.trim();
}
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
public Boolean getPrivateNotes() {
return privateNotes;
}
public void setPrivateNotes(Boolean privateNotes) {
this.privateNotes = privateNotes;
}
public Integer getParentId() {
return parentId;
}
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
public Integer getCommentsCount() {
return commentsCount;
}
public void setCommentsCount(Integer commentsCount) {
this.commentsCount = commentsCount;
}
public Integer getReplyId() {
return replyId;
}
public void setReplyId(Integer replyId) {
this.replyId = replyId;
}
public Long getReviewId() {
return reviewId;
}
public void setReviewId(Long reviewId) {
this.reviewId = reviewId;
}
public String getCommitId() {
return commitId;
}
public void setCommitId(String commitId) {
this.commitId = commitId == null ? null : commitId.trim();
}
public String getLineCode() {
return lineCode;
}
public void setLineCode(String lineCode) {
this.lineCode = lineCode == null ? null : lineCode.trim();
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path == null ? null : path.trim();
}
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
public Date getResolveAt() {
return resolveAt;
}
public void setResolveAt(Date resolveAt) {
this.resolveAt = resolveAt;
}
public Integer getResolveerId() {
return resolveerId;
}
public void setResolveerId(Integer resolveerId) {
this.resolveerId = resolveerId;
}
public Boolean getNeedRespond() {
return needRespond;
}
public void setNeedRespond(Boolean needRespond) {
this.needRespond = needRespond;
}
public Date getUpdatedOn() {
return updatedOn;
}
public void setUpdatedOn(Date updatedOn) {
this.updatedOn = updatedOn;
}
public String getDiff() {
return diff;
}
public void setDiff(String diff) {
this.diff = diff == null ? null : diff.trim();
}
}

View File

@ -0,0 +1,24 @@
package com.microservices.dss.projects.domain;
public class PieChartNameAndValue {
private String name;
private Integer value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}

View File

@ -0,0 +1,485 @@
package com.microservices.dss.projects.domain;
import java.util.Date;
public class Projects {
private Integer id;
private String name;
private String homepage;
private Boolean isPublic;
private Integer parentId;
private Date createdOn;
private Date updatedOn;
private String identifier;
private Integer status;
private Integer lft;
private Integer rgt;
private Boolean inheritMembers;
private Integer projectType;
private Boolean hiddenRepo;
private Integer attachmenttype;
private Integer userId;
private Integer dtsTest;
private String enterpriseName;
private Integer organizationId;
private Integer projectNewType;
private Integer gpid;
private Integer forkedFromProjectId;
private Integer forkedCount;
private Integer publishResource;
private Integer visits;
private Integer hot;
private String inviteCode;
private String qrcode;
private Integer qrcodeExpiretime;
private Byte trainingStatus;
private String repIdentifier;
private Integer projectCategoryId;
private Integer projectLanguageId;
private Integer licenseId;
private Integer ignoreId;
private Integer praisesCount;
private Integer watchersCount;
private Integer issuesCount;
private Integer pullRequestsCount;
private String language;
private Integer versionsCount;
private Integer issueTagsCount;
private Integer closedIssuesCount;
private Boolean openDevops;
private Integer giteaWebhookId;
private Integer openDevopsCount;
private Boolean recommend;
private Integer platform;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public String getHomepage() {
return homepage;
}
public void setHomepage(String homepage) {
this.homepage = homepage == null ? null : homepage.trim();
}
public Boolean getIsPublic() {
return isPublic;
}
public void setIsPublic(Boolean isPublic) {
this.isPublic = isPublic;
}
public Integer getParentId() {
return parentId;
}
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
public Date getUpdatedOn() {
return updatedOn;
}
public void setUpdatedOn(Date updatedOn) {
this.updatedOn = updatedOn;
}
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier == null ? null : identifier.trim();
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Integer getLft() {
return lft;
}
public void setLft(Integer lft) {
this.lft = lft;
}
public Integer getRgt() {
return rgt;
}
public void setRgt(Integer rgt) {
this.rgt = rgt;
}
public Boolean getInheritMembers() {
return inheritMembers;
}
public void setInheritMembers(Boolean inheritMembers) {
this.inheritMembers = inheritMembers;
}
public Integer getProjectType() {
return projectType;
}
public void setProjectType(Integer projectType) {
this.projectType = projectType;
}
public Boolean getHiddenRepo() {
return hiddenRepo;
}
public void setHiddenRepo(Boolean hiddenRepo) {
this.hiddenRepo = hiddenRepo;
}
public Integer getAttachmenttype() {
return attachmenttype;
}
public void setAttachmenttype(Integer attachmenttype) {
this.attachmenttype = attachmenttype;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Integer getDtsTest() {
return dtsTest;
}
public void setDtsTest(Integer dtsTest) {
this.dtsTest = dtsTest;
}
public String getEnterpriseName() {
return enterpriseName;
}
public void setEnterpriseName(String enterpriseName) {
this.enterpriseName = enterpriseName == null ? null : enterpriseName.trim();
}
public Integer getOrganizationId() {
return organizationId;
}
public void setOrganizationId(Integer organizationId) {
this.organizationId = organizationId;
}
public Integer getProjectNewType() {
return projectNewType;
}
public void setProjectNewType(Integer projectNewType) {
this.projectNewType = projectNewType;
}
public Integer getGpid() {
return gpid;
}
public void setGpid(Integer gpid) {
this.gpid = gpid;
}
public Integer getForkedFromProjectId() {
return forkedFromProjectId;
}
public void setForkedFromProjectId(Integer forkedFromProjectId) {
this.forkedFromProjectId = forkedFromProjectId;
}
public Integer getForkedCount() {
return forkedCount;
}
public void setForkedCount(Integer forkedCount) {
this.forkedCount = forkedCount;
}
public Integer getPublishResource() {
return publishResource;
}
public void setPublishResource(Integer publishResource) {
this.publishResource = publishResource;
}
public Integer getVisits() {
return visits;
}
public void setVisits(Integer visits) {
this.visits = visits;
}
public Integer getHot() {
return hot;
}
public void setHot(Integer hot) {
this.hot = hot;
}
public String getInviteCode() {
return inviteCode;
}
public void setInviteCode(String inviteCode) {
this.inviteCode = inviteCode == null ? null : inviteCode.trim();
}
public String getQrcode() {
return qrcode;
}
public void setQrcode(String qrcode) {
this.qrcode = qrcode == null ? null : qrcode.trim();
}
public Integer getQrcodeExpiretime() {
return qrcodeExpiretime;
}
public void setQrcodeExpiretime(Integer qrcodeExpiretime) {
this.qrcodeExpiretime = qrcodeExpiretime;
}
public Byte getTrainingStatus() {
return trainingStatus;
}
public void setTrainingStatus(Byte trainingStatus) {
this.trainingStatus = trainingStatus;
}
public String getRepIdentifier() {
return repIdentifier;
}
public void setRepIdentifier(String repIdentifier) {
this.repIdentifier = repIdentifier == null ? null : repIdentifier.trim();
}
public Integer getProjectCategoryId() {
return projectCategoryId;
}
public void setProjectCategoryId(Integer projectCategoryId) {
this.projectCategoryId = projectCategoryId;
}
public Integer getProjectLanguageId() {
return projectLanguageId;
}
public void setProjectLanguageId(Integer projectLanguageId) {
this.projectLanguageId = projectLanguageId;
}
public Integer getLicenseId() {
return licenseId;
}
public void setLicenseId(Integer licenseId) {
this.licenseId = licenseId;
}
public Integer getIgnoreId() {
return ignoreId;
}
public void setIgnoreId(Integer ignoreId) {
this.ignoreId = ignoreId;
}
public Integer getPraisesCount() {
return praisesCount;
}
public void setPraisesCount(Integer praisesCount) {
this.praisesCount = praisesCount;
}
public Integer getWatchersCount() {
return watchersCount;
}
public void setWatchersCount(Integer watchersCount) {
this.watchersCount = watchersCount;
}
public Integer getIssuesCount() {
return issuesCount;
}
public void setIssuesCount(Integer issuesCount) {
this.issuesCount = issuesCount;
}
public Integer getPullRequestsCount() {
return pullRequestsCount;
}
public void setPullRequestsCount(Integer pullRequestsCount) {
this.pullRequestsCount = pullRequestsCount;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language == null ? null : language.trim();
}
public Integer getVersionsCount() {
return versionsCount;
}
public void setVersionsCount(Integer versionsCount) {
this.versionsCount = versionsCount;
}
public Integer getIssueTagsCount() {
return issueTagsCount;
}
public void setIssueTagsCount(Integer issueTagsCount) {
this.issueTagsCount = issueTagsCount;
}
public Integer getClosedIssuesCount() {
return closedIssuesCount;
}
public void setClosedIssuesCount(Integer closedIssuesCount) {
this.closedIssuesCount = closedIssuesCount;
}
public Boolean getOpenDevops() {
return openDevops;
}
public void setOpenDevops(Boolean openDevops) {
this.openDevops = openDevops;
}
public Integer getGiteaWebhookId() {
return giteaWebhookId;
}
public void setGiteaWebhookId(Integer giteaWebhookId) {
this.giteaWebhookId = giteaWebhookId;
}
public Integer getOpenDevopsCount() {
return openDevopsCount;
}
public void setOpenDevopsCount(Integer openDevopsCount) {
this.openDevopsCount = openDevopsCount;
}
public Boolean getRecommend() {
return recommend;
}
public void setRecommend(Boolean recommend) {
this.recommend = recommend;
}
public Integer getPlatform() {
return platform;
}
public void setPlatform(Integer platform) {
this.platform = platform;
}
}

View File

@ -0,0 +1,97 @@
package com.microservices.dss.projects.domain;
//项目活跃度相关数据
public class ProjectsActivity {
private int id;
private int projectId;
private String name;
private int activityScore;
private int visits;
private int watchersCount;
private int praisesCount;
private int issuesCount;
private int pullRequestsCount;
private int versionsCount;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getProjectId() {
return projectId;
}
public void setProjectId(int projectId) {
this.projectId = projectId;
}
public int getPullRequestsCount() {
return pullRequestsCount;
}
public void setPullRequestsCount(int pullRequestsCount) {
this.pullRequestsCount = pullRequestsCount;
}
public int getVisits() {
return visits;
}
public void setVisits(int visits) {
this.visits = visits;
}
public int getWatchersCount() {
return watchersCount;
}
public void setWatchersCount(int watchersCount) {
this.watchersCount = watchersCount;
}
public int getPraisesCount() {
return praisesCount;
}
public void setPraisesCount(int praisesCount) {
this.praisesCount = praisesCount;
}
public int getIssuesCount() {
return issuesCount;
}
public void setIssuesCount(int issuesCount) {
this.issuesCount = issuesCount;
}
public int getVersionsCount() {
return versionsCount;
}
public void setVersionsCount(int versionsCount) {
this.versionsCount = versionsCount;
}
public int getActivityScore() {
return activityScore;
}
public void setActivityScore(int activityScore) {
this.activityScore = activityScore;
}
}

View File

@ -0,0 +1,195 @@
package com.microservices.dss.projects.domain;
import java.util.Date;
public class PullRequests {
private Integer id;
private Integer pullRequestId;
private Integer gpid;
private Integer userId;
private Date createdAt;
private Date updatedAt;
private Integer status;
private Integer projectId;
private String title;
private Integer milestone;
private String head;
private String base;
private Integer issueId;
private Integer forkProjectId;
private Boolean isOriginal;
private Integer commentsCount;
private Integer commitsCount;
private Integer filesCount;
private String body;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getPullRequestId() {
return pullRequestId;
}
public void setPullRequestId(Integer pullRequestId) {
this.pullRequestId = pullRequestId;
}
public Integer getGpid() {
return gpid;
}
public void setGpid(Integer gpid) {
this.gpid = gpid;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Integer getProjectId() {
return projectId;
}
public void setProjectId(Integer projectId) {
this.projectId = projectId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title == null ? null : title.trim();
}
public Integer getMilestone() {
return milestone;
}
public void setMilestone(Integer milestone) {
this.milestone = milestone;
}
public String getHead() {
return head;
}
public void setHead(String head) {
this.head = head == null ? null : head.trim();
}
public String getBase() {
return base;
}
public void setBase(String base) {
this.base = base == null ? null : base.trim();
}
public Integer getIssueId() {
return issueId;
}
public void setIssueId(Integer issueId) {
this.issueId = issueId;
}
public Integer getForkProjectId() {
return forkProjectId;
}
public void setForkProjectId(Integer forkProjectId) {
this.forkProjectId = forkProjectId;
}
public Boolean getIsOriginal() {
return isOriginal;
}
public void setIsOriginal(Boolean isOriginal) {
this.isOriginal = isOriginal;
}
public Integer getCommentsCount() {
return commentsCount;
}
public void setCommentsCount(Integer commentsCount) {
this.commentsCount = commentsCount;
}
public Integer getCommitsCount() {
return commitsCount;
}
public void setCommitsCount(Integer commitsCount) {
this.commitsCount = commitsCount;
}
public Integer getFilesCount() {
return filesCount;
}
public void setFilesCount(Integer filesCount) {
this.filesCount = filesCount;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body == null ? null : body.trim();
}
}

View File

@ -0,0 +1,483 @@
package com.microservices.dss.projects.domain;
import java.util.Date;
public class User {
private Integer id;
private String login;
private String hashedPassword;
private String firstname;
private String lastname;
private String mail;
private Boolean admin;
private Integer status;
private Date lastLoginOn;
private String language;
private Integer authSourceId;
private Date createdOn;
private Date updatedOn;
private String type;
private String identityUrl;
private String mailNotification;
private String salt;
private Integer gid;
private Integer visits;
private Integer excellentTeacher;
private Integer excellentStudent;
private String phone;
private Boolean authentication;
private Integer grade;
private Integer experience;
private String nickname;
private Boolean showRealname;
private Boolean professionalCertification;
private String idNumber;
private Integer certification;
private Boolean homepageTeacher;
private Boolean homepageEngineer;
private Byte isTest;
private Integer ecoderUserId;
private Boolean business;
private Boolean profileCompleted;
private Long laboratoryId;
private String platform;
private String giteaToken;
private Integer giteaUid;
private Boolean isShixunMarker;
private Boolean isSyncPwd;
private Integer watchersCount;
private Boolean enterpriseCertification;
private Byte adminRole;
private Integer devopsStep;
public Boolean getShixunMarker() {
return isShixunMarker;
}
public void setShixunMarker(Boolean shixunMarker) {
isShixunMarker = shixunMarker;
}
public Boolean getSyncPwd() {
return isSyncPwd;
}
public void setSyncPwd(Boolean syncPwd) {
isSyncPwd = syncPwd;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login == null ? null : login.trim();
}
public String getHashedPassword() {
return hashedPassword;
}
public void setHashedPassword(String hashedPassword) {
this.hashedPassword = hashedPassword == null ? null : hashedPassword.trim();
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname == null ? null : firstname.trim();
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname == null ? null : lastname.trim();
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail == null ? null : mail.trim();
}
public Boolean getAdmin() {
return admin;
}
public void setAdmin(Boolean admin) {
this.admin = admin;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Date getLastLoginOn() {
return lastLoginOn;
}
public void setLastLoginOn(Date lastLoginOn) {
this.lastLoginOn = lastLoginOn;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language == null ? null : language.trim();
}
public Integer getAuthSourceId() {
return authSourceId;
}
public void setAuthSourceId(Integer authSourceId) {
this.authSourceId = authSourceId;
}
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
public Date getUpdatedOn() {
return updatedOn;
}
public void setUpdatedOn(Date updatedOn) {
this.updatedOn = updatedOn;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type == null ? null : type.trim();
}
public String getIdentityUrl() {
return identityUrl;
}
public void setIdentityUrl(String identityUrl) {
this.identityUrl = identityUrl == null ? null : identityUrl.trim();
}
public String getMailNotification() {
return mailNotification;
}
public void setMailNotification(String mailNotification) {
this.mailNotification = mailNotification == null ? null : mailNotification.trim();
}
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt == null ? null : salt.trim();
}
public Integer getGid() {
return gid;
}
public void setGid(Integer gid) {
this.gid = gid;
}
public Integer getVisits() {
return visits;
}
public void setVisits(Integer visits) {
this.visits = visits;
}
public Integer getExcellentTeacher() {
return excellentTeacher;
}
public void setExcellentTeacher(Integer excellentTeacher) {
this.excellentTeacher = excellentTeacher;
}
public Integer getExcellentStudent() {
return excellentStudent;
}
public void setExcellentStudent(Integer excellentStudent) {
this.excellentStudent = excellentStudent;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone == null ? null : phone.trim();
}
public Boolean getAuthentication() {
return authentication;
}
public void setAuthentication(Boolean authentication) {
this.authentication = authentication;
}
public Integer getGrade() {
return grade;
}
public void setGrade(Integer grade) {
this.grade = grade;
}
public Integer getExperience() {
return experience;
}
public void setExperience(Integer experience) {
this.experience = experience;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname == null ? null : nickname.trim();
}
public Boolean getShowRealname() {
return showRealname;
}
public void setShowRealname(Boolean showRealname) {
this.showRealname = showRealname;
}
public Boolean getProfessionalCertification() {
return professionalCertification;
}
public void setProfessionalCertification(Boolean professionalCertification) {
this.professionalCertification = professionalCertification;
}
public String getIdNumber() {
return idNumber;
}
public void setIdNumber(String idNumber) {
this.idNumber = idNumber == null ? null : idNumber.trim();
}
public Integer getCertification() {
return certification;
}
public void setCertification(Integer certification) {
this.certification = certification;
}
public Boolean getHomepageTeacher() {
return homepageTeacher;
}
public void setHomepageTeacher(Boolean homepageTeacher) {
this.homepageTeacher = homepageTeacher;
}
public Boolean getHomepageEngineer() {
return homepageEngineer;
}
public void setHomepageEngineer(Boolean homepageEngineer) {
this.homepageEngineer = homepageEngineer;
}
public Byte getIsTest() {
return isTest;
}
public void setIsTest(Byte isTest) {
this.isTest = isTest;
}
public Integer getEcoderUserId() {
return ecoderUserId;
}
public void setEcoderUserId(Integer ecoderUserId) {
this.ecoderUserId = ecoderUserId;
}
public Boolean getBusiness() {
return business;
}
public void setBusiness(Boolean business) {
this.business = business;
}
public Boolean getProfileCompleted() {
return profileCompleted;
}
public void setProfileCompleted(Boolean profileCompleted) {
this.profileCompleted = profileCompleted;
}
public Long getLaboratoryId() {
return laboratoryId;
}
public void setLaboratoryId(Long laboratoryId) {
this.laboratoryId = laboratoryId;
}
public String getPlatform() {
return platform;
}
public void setPlatform(String platform) {
this.platform = platform == null ? null : platform.trim();
}
public String getGiteaToken() {
return giteaToken;
}
public void setGiteaToken(String giteaToken) {
this.giteaToken = giteaToken == null ? null : giteaToken.trim();
}
public Integer getGiteaUid() {
return giteaUid;
}
public void setGiteaUid(Integer giteaUid) {
this.giteaUid = giteaUid;
}
public Boolean getIsShixunMarker() {
return isShixunMarker;
}
public void setIsShixunMarker(Boolean isShixunMarker) {
this.isShixunMarker = isShixunMarker;
}
public Boolean getIsSyncPwd() {
return isSyncPwd;
}
public void setIsSyncPwd(Boolean isSyncPwd) {
this.isSyncPwd = isSyncPwd;
}
public Integer getWatchersCount() {
return watchersCount;
}
public void setWatchersCount(Integer watchersCount) {
this.watchersCount = watchersCount;
}
public Boolean getEnterpriseCertification() {
return enterpriseCertification;
}
public void setEnterpriseCertification(Boolean enterpriseCertification) {
this.enterpriseCertification = enterpriseCertification;
}
public Byte getAdminRole() {
return adminRole;
}
public void setAdminRole(Byte adminRole) {
this.adminRole = adminRole;
}
public Integer getDevopsStep() {
return devopsStep;
}
public void setDevopsStep(Integer devopsStep) {
this.devopsStep = devopsStep;
}
}

View File

@ -0,0 +1,51 @@
package com.microservices.dss.projects.domain.vo;
//新增任务数完成任务数新增PR数新增提交数新增代码数
public class DeveloperNewTotalDataVo {
private int[] newTask;
private int[] completedTask;
private int[] newPrNum;
private int[] newCommitNum;
private int[] newCodeNum;
public int[] getNewTask() {
return newTask;
}
public void setNewTask(int[] newTask) {
this.newTask = newTask;
}
public int[] getCompletedTask() {
return completedTask;
}
public void setCompletedTask(int[] completedTask) {
this.completedTask = completedTask;
}
public int[] getNewPrNum() {
return newPrNum;
}
public void setNewPrNum(int[] newPrNum) {
this.newPrNum = newPrNum;
}
public int[] getNewCodeNum() {
return newCodeNum;
}
public void setNewCodeNum(int[] newCodeNum) {
this.newCodeNum = newCodeNum;
}
public int[] getNewCommitNum() {
return newCommitNum;
}
public void setNewCommitNum(int[] newCommitNum) {
this.newCommitNum = newCommitNum;
}
}

View File

@ -0,0 +1,149 @@
package com.microservices.dss.projects.domain.vo;
import com.microservices.dss.projects.domain.PieChartNameAndValue;
import java.util.List;
//1.总项目数总成员数
//2.新增项目数新增成员数新增代码提交次数任务完成量
public class GlobalResourcesDataVo {
private int totalProjects;
private int totalMembers;
private int totalCommits;
private int totalPullRequest;
private int[] newAddedProjects;
private int[] newAddedMembers;
private int[] newCodeSubmissionTimes;
private int[] newPullRequestTimes;
private int[] newCommentTimes;
private int[] taskCompletion;
private int[] activeProjects;
private int[] activeUsers;
private String[] weeklyDates;
private List<PieChartNameAndValue> programLanguagePieChart;
private List<PieChartNameAndValue> projectCategoryPieChart;
public int getTotalProjects() {
return totalProjects;
}
public void setTotalProjects(int totalProjects) {
this.totalProjects = totalProjects;
}
public int getTotalMembers() {
return totalMembers;
}
public void setTotalMembers(int totalMembers) {
this.totalMembers = totalMembers;
}
public int getTotalCommits() {
return totalCommits;
}
public void setTotalCommits(int totalCommits) {
this.totalCommits = totalCommits;
}
public int getTotalPullRequest() {
return totalPullRequest;
}
public void setTotalPullRequest(int totalPullRequest) {
this.totalPullRequest = totalPullRequest;
}
public int[] getNewAddedProjects() {
return newAddedProjects;
}
public void setNewAddedProjects(int[] newAddedProjects) {
this.newAddedProjects = newAddedProjects;
}
public int[] getNewAddedMembers() {
return newAddedMembers;
}
public void setNewAddedMembers(int[] newAddedMembers) {
this.newAddedMembers = newAddedMembers;
}
public int[] getNewCodeSubmissionTimes() {
return newCodeSubmissionTimes;
}
public void setNewCodeSubmissionTimes(int[] newCodeSubmissionTimes) {
this.newCodeSubmissionTimes = newCodeSubmissionTimes;
}
public int[] getNewPullRequestTimes() {
return newPullRequestTimes;
}
public void setNewPullRequestTimes(int[] newPullRequestTimes) {
this.newPullRequestTimes = newPullRequestTimes;
}
public int[] getNewCommentTimes() {
return newCommentTimes;
}
public void setNewCommentTimes(int[] newCommentTimes) {
this.newCommentTimes = newCommentTimes;
}
public int[] getTaskCompletion() {
return taskCompletion;
}
public void setTaskCompletion(int[] taskCompletion) {
this.taskCompletion = taskCompletion;
}
public int[] getActiveProjects() {
return activeProjects;
}
public void setActiveProjects(int[] activeProjects) {
this.activeProjects = activeProjects;
}
public int[] getActiveUsers() {
return activeUsers;
}
public void setActiveUsers(int[] activeUsers) {
this.activeUsers = activeUsers;
}
public String[] getWeeklyDates() {
return weeklyDates;
}
public void setWeeklyDates(String[] weeklyDates) {
this.weeklyDates = weeklyDates;
}
public List<PieChartNameAndValue> getProgramLanguagePieChart() {
return programLanguagePieChart;
}
public void setProgramLanguagePieChart(List<PieChartNameAndValue> programLanguagePieChart) {
this.programLanguagePieChart = programLanguagePieChart;
}
public List<PieChartNameAndValue> getProjectCategoryPieChart() {
return projectCategoryPieChart;
}
public void setProjectCategoryPieChart(List<PieChartNameAndValue> projectCategoryPieChart) {
this.projectCategoryPieChart = projectCategoryPieChart;
}
}

View File

@ -0,0 +1,126 @@
package com.microservices.dss.projects.domain.vo;
public class SingleProjectResourcesDataVo {
private int totalWatcher;
private int totalPraise;
private int totalForked;
private int totalVisits;
private int[] newDeveloperNum;
private int[] newCodeSubmissionTimes;
private int[] newPullRequestTimes;
private int[] newCommentTimes;
private int[] newIssueNum;
private int[] newForkNum;
private int[] newWatchNum;
private int[] newProjectTrendNum;
private String[] weeklyDates;
public int getTotalWatcher() {
return totalWatcher;
}
public void setTotalWatcher(int totalWatcher) {
this.totalWatcher = totalWatcher;
}
public int getTotalPraise() {
return totalPraise;
}
public void setTotalPraise(int totalPraise) {
this.totalPraise = totalPraise;
}
public int getTotalForked() {
return totalForked;
}
public void setTotalForked(int totalForked) {
this.totalForked = totalForked;
}
public int getTotalVisits() {
return totalVisits;
}
public void setTotalVisits(int totalVisits) {
this.totalVisits = totalVisits;
}
public int[] getNewDeveloperNum() {
return newDeveloperNum;
}
public void setNewDeveloperNum(int[] newDeveloperNum) {
this.newDeveloperNum = newDeveloperNum;
}
public int[] getNewCodeSubmissionTimes() {
return newCodeSubmissionTimes;
}
public void setNewCodeSubmissionTimes(int[] newCodeSubmissionTimes) {
this.newCodeSubmissionTimes = newCodeSubmissionTimes;
}
public int[] getNewPullRequestTimes() {
return newPullRequestTimes;
}
public void setNewPullRequestTimes(int[] newPullRequestTimes) {
this.newPullRequestTimes = newPullRequestTimes;
}
public int[] getNewCommentTimes() {
return newCommentTimes;
}
public void setNewCommentTimes(int[] newCommentTimes) {
this.newCommentTimes = newCommentTimes;
}
public int[] getNewIssueNum() {
return newIssueNum;
}
public void setNewIssueNum(int[] newIssueNum) {
this.newIssueNum = newIssueNum;
}
public int[] getNewForkNum() {
return newForkNum;
}
public void setNewForkNum(int[] newForkNum) {
this.newForkNum = newForkNum;
}
public String[] getWeeklyDates() {
return weeklyDates;
}
public void setWeeklyDates(String[] weeklyDates) {
this.weeklyDates = weeklyDates;
}
public int[] getNewWatchNum() {
return newWatchNum;
}
public void setNewWatchNum(int[] newWatchNum) {
this.newWatchNum = newWatchNum;
}
public int[] getNewProjectTrendNum() {
return newProjectTrendNum;
}
public void setNewProjectTrendNum(int[] newProjectTrendNum) {
this.newProjectTrendNum = newProjectTrendNum;
}
}

View File

@ -0,0 +1,14 @@
package com.microservices.dss.projects.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface CommitsMapper {
int selectTotalCommitCount();
List<Object> getNewCodeSubmissionTimesByMonth(@Param("startTime") String startTime, @Param("endTime") String endTime);
}

View File

@ -0,0 +1,11 @@
package com.microservices.dss.projects.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface IssuesMapper {
List<Object> getNewAddedIssuesCompletionByMonth(@Param("startTime") String startTime, @Param("endTime") String endTime);
}

View File

@ -0,0 +1,11 @@
package com.microservices.dss.projects.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface JournalsMapper {
List<Object> getNewJournalsNumByMonth(@Param("startTime") String startTime, @Param("endTime") String endTime);
}

View File

@ -0,0 +1,21 @@
package com.microservices.dss.projects.mapper;
import com.microservices.dss.projects.domain.PieChartNameAndValue;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface ProjectsMapper {
int selectProjectCount();
List<Object> getNewAddedProjectsByMonth(@Param("startTime") String startTime, @Param("endTime") String endTime);
List<Object> getActiveProjectsByMonth(@Param("startTime") String startTime, @Param("endTime") String endTime);
List<PieChartNameAndValue> getProjectNumOfDiffProgramLanguage(@Param("topNumber") Integer topNumber);
List<PieChartNameAndValue> getProjectNumOfProjectCategory(@Param("topNumber") Integer topNumber);
}

View File

@ -0,0 +1,14 @@
package com.microservices.dss.projects.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface PullRequestsMapper {
int selectTotalPullRequestCount();
List<Object> getNewPullRequestNumByMonth(@Param("startTime") String startTime, @Param("endTime") String endTime);
}

View File

@ -0,0 +1,20 @@
package com.microservices.dss.projects.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface UserMapper {
int selectUserCount();
List<Object> getNewAddedMembersByMonth(@Param("startTime") String startTime, @Param("endTime") String endTime);
List<Object> getActiveMembersByMonth(@Param("startTime") String startTime, @Param("endTime") String endTime);
Long getUserIdByToken(@Param("token") String token);
Boolean getAdminStatus(@Param("userId") Long userId);
}

View File

@ -0,0 +1,17 @@
package com.microservices.dss.projects.service;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.microservices.dss.projects.domain.vo.GlobalResourcesDataVo;
import java.text.ParseException;
public interface IProjectGlobalResourcesService {
GlobalResourcesDataVo getProjectGlobalResourcesData() throws ParseException, JsonProcessingException;
JSONObject getLatestActivitiesData(int page, int limit);
JSONObject getProjectRankData(int time, int limit);
JSONObject getUserRankData(int time, int limit);
}

View File

@ -0,0 +1,186 @@
package com.microservices.dss.projects.service.impl;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.microservices.common.core.constant.CacheConstants;
import com.microservices.common.httpClient.util.GitLinkRequestHelper;
import com.microservices.dss.projects.domain.vo.GlobalResourcesDataVo;
import com.microservices.dss.projects.mapper.*;
import com.microservices.dss.projects.service.IProjectGlobalResourcesService;
import com.microservices.dss.utils.DateUtil;
import com.microservices.dss.utils.DssGitLinkRequestUrl;
import org.springframework.beans.factory.annotation.Autowired;
import com.microservices.common.redis.service.RedisService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import static com.microservices.dss.utils.DataStructureConvertUtil.MapInitByMonth;
import static com.microservices.dss.utils.DataStructureConvertUtil.dbResult2Array;
import static com.microservices.dss.utils.DateUtil.*;
@Service
public class ProjectGlobalResourcesServiceImpl implements IProjectGlobalResourcesService {
@Autowired
private RedisService redisService;
@Resource
private ProjectsMapper projectsMapper;
@Resource
private UserMapper userMapper;
@Resource
private CommitsMapper commitsMapper;
@Resource
private PullRequestsMapper pullRequestsMapper;
@Resource
private IssuesMapper issuesMapper;
@Resource
private JournalsMapper journalsMapper;
@Autowired
private GitLinkRequestHelper gitLinkRequestHelper;
@Override
public GlobalResourcesDataVo getProjectGlobalResourcesData() throws ParseException, JsonProcessingException {
String currentYearMonth = getFormattedCurrentDate();
String previousYearMonth = DateUtil.DateAddByYear(currentYearMonth, -1);
GlobalResourcesDataVo globalResourcesDataVo = new GlobalResourcesDataVo();
String cacheKey = CacheConstants.getGlobalResourcesDataKey(previousYearMonth, currentYearMonth);
if (redisService.hasKey(cacheKey)) {
globalResourcesDataVo = redisService.getCacheObject(cacheKey);
return globalResourcesDataVo;
}
String startTime = getFormattedPreviousYearSameMonth();
String endTime = getFormattedCurrentDateTime();
globalResourcesDataVo.setTotalProjects(this.getTotalProjects());
globalResourcesDataVo.setTotalMembers(userMapper.selectUserCount());
globalResourcesDataVo.setTotalCommits(commitsMapper.selectTotalCommitCount());
globalResourcesDataVo.setTotalPullRequest(pullRequestsMapper.selectTotalPullRequestCount());
globalResourcesDataVo.setNewAddedProjects(this.getNewAddedProjectsByMonth(startTime, endTime));
globalResourcesDataVo.setNewAddedMembers(this.getNewAddedMembersByMonth(startTime, endTime));
globalResourcesDataVo.setNewPullRequestTimes(this.getNewPrNumByMonth(startTime, endTime));
globalResourcesDataVo.setNewCommentTimes(this.getNewCommentNumByMonth(startTime, endTime));
globalResourcesDataVo.setActiveUsers(this.getActiveMembersByMonth(startTime, endTime));
globalResourcesDataVo.setActiveProjects(this.getActiveProjectsByMonth(startTime, endTime));
globalResourcesDataVo.setNewCodeSubmissionTimes(this.getNewCodeSubmissionTimesByMonth(startTime, endTime));
globalResourcesDataVo.setTaskCompletion(this.getNewAddedIssuesCompletionByMonth(startTime,endTime));
globalResourcesDataVo.setProgramLanguagePieChart(projectsMapper.getProjectNumOfDiffProgramLanguage(6));
globalResourcesDataVo.setProjectCategoryPieChart(projectsMapper.getProjectNumOfProjectCategory(6));
return globalResourcesDataVo;
}
@Override
public JSONObject getLatestActivitiesData(int page, int limit) {
JSONObject result = gitLinkRequestHelper.doGet(DssGitLinkRequestUrl.GET_LATEST_ACTIVITIES(page, limit));
JSONObject latestActivities = new JSONObject();
latestActivities.put("total_count", result.get("total_count"));
latestActivities.put("project_trends", result.getJSONArray("project_trends"));
return latestActivities;
}
@Override
public JSONObject getProjectRankData(int time, int limit) {
JSONObject result = gitLinkRequestHelper.doGet(DssGitLinkRequestUrl.GET_PROJECT_RANK(time, limit));
JSONObject projectRank = new JSONObject();
projectRank.put("projects", result.getJSONArray("projects"));
return projectRank;
}
@Override
public JSONObject getUserRankData(int time, int limit) {
JSONObject result = gitLinkRequestHelper.doGet(DssGitLinkRequestUrl.GET_USER_RANK(time, limit));
JSONObject userRank = new JSONObject();
userRank.put("users", result.getJSONArray("users"));
return userRank;
}
private int getTotalProjects() {
return projectsMapper.selectProjectCount();
}
private int[] getNewAddedProjectsByMonth(String startTime, String endTime) throws ParseException, JsonProcessingException {
int monthDiff = 12;
Map<Object, Object> map_init = MapInitByMonth(monthDiff,endTime);
List<Object> Db_result = projectsMapper.getNewAddedProjectsByMonth(startTime, endTime);
int[] resultArray = new int[monthDiff+1];
int[] result = dbResult2Array(Db_result,"createTime","num",map_init,resultArray);
return result;
}
private int[] getNewAddedMembersByMonth(String startTime, String endTime) throws ParseException, JsonProcessingException {
int monthDiff = 12;
Map<Object, Object> map_init = MapInitByMonth(monthDiff,endTime);
List<Object> Db_result = userMapper.getNewAddedMembersByMonth(startTime,endTime);
int[] resultArray = new int[monthDiff+1];
int[] result = dbResult2Array(Db_result,"createTime","num",map_init,resultArray);
return result;
}
private int[] getNewPrNumByMonth(String startTime, String endTime) throws JsonProcessingException, ParseException{
int monthDiff;
monthDiff = 12;
Map<Object, Object> map_init = MapInitByMonth(monthDiff,endTime);
List<Object> Db_result = pullRequestsMapper.getNewPullRequestNumByMonth(startTime,endTime);
int[] resultArray = new int[monthDiff+1];
int[] result = dbResult2Array(Db_result,"createTime","num",map_init,resultArray);
return result;
}
private int[] getNewCommentNumByMonth(String startTime, String endTime) throws JsonProcessingException, ParseException {
int monthDiff;
monthDiff = 12;
Map<Object, Object> map_init = MapInitByMonth(monthDiff,endTime);
List<Object> Db_result = journalsMapper.getNewJournalsNumByMonth(startTime,endTime);
int[] resultArray = new int[monthDiff+1];
int[] result = dbResult2Array(Db_result,"createTime","num",map_init,resultArray);
return result;
}
private int[] getActiveMembersByMonth(String startTime, String endTime) throws ParseException, JsonProcessingException {
int monthDiff = 12;
Map<Object, Object> map_init = MapInitByMonth(monthDiff,endTime);
List<Object> Db_result = userMapper.getActiveMembersByMonth(startTime,endTime);
int[] resultArray = new int[monthDiff+1];
int[] result = dbResult2Array(Db_result,"createTime","num",map_init,resultArray);
return result;
}
private int[] getActiveProjectsByMonth(String startTime, String endTime) throws ParseException, JsonProcessingException {
int monthDiff = 12;
Map<Object, Object> map_init = MapInitByMonth(monthDiff,endTime);
List<Object> Db_result = projectsMapper.getActiveProjectsByMonth(startTime, endTime);
int[] resultArray = new int[monthDiff+1];
int[] result = dbResult2Array(Db_result,"createTime","num",map_init,resultArray);
return result;
}
private int[] getNewCodeSubmissionTimesByMonth(String startTime, String endTime) throws JsonProcessingException, ParseException {
int monthDiff;
monthDiff = 12;
Map<Object, Object> map_init = MapInitByMonth(monthDiff,endTime);
List<Object> Db_result = commitsMapper.getNewCodeSubmissionTimesByMonth(startTime,endTime);
int[] resultArray = new int[monthDiff+1];
int[] result = dbResult2Array(Db_result,"createTime","num",map_init,resultArray);
return result;
}
private int[] getNewAddedIssuesCompletionByMonth(String startTime, String endTime) throws JsonProcessingException, ParseException {
int monthDiff;
monthDiff = 12;
Map<Object, Object> map_init = MapInitByMonth(monthDiff,endTime);
List<Object> Db_result = issuesMapper.getNewAddedIssuesCompletionByMonth(startTime,endTime);
int[] resultArray = new int[monthDiff+1];
int[] result = dbResult2Array(Db_result,"createTime","num",map_init,resultArray);
return result;
}
}

View File

@ -0,0 +1,40 @@
package com.microservices.dss.task;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.microservices.common.core.constant.CacheConstants;
import com.microservices.common.redis.service.RedisService;
import com.microservices.dss.projects.domain.vo.GlobalResourcesDataVo;
import com.microservices.dss.projects.service.IProjectGlobalResourcesService;
import com.microservices.dss.utils.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.ParseException;
import java.util.concurrent.TimeUnit;
import static com.microservices.dss.utils.DateUtil.getFormattedCurrentDate;
@Component
public class ProjectsGlobalResourcesTask {
private static final Logger log = LoggerFactory.getLogger(ProjectsGlobalResourcesTask.class);
@Autowired
private IProjectGlobalResourcesService projectGlobalResourcesService;
@Autowired
private RedisService redisService;
@Scheduled(cron = "0 0 2 * * ?")
public void updateProjectsGlobalResources() throws ParseException, JsonProcessingException {
log.info("开始更新近一年全局资源数据");
String currentDate = getFormattedCurrentDate();
String startTime = DateUtil.DateAddByYear(currentDate, -1);
GlobalResourcesDataVo globalResourcesDataVo = projectGlobalResourcesService.getProjectGlobalResourcesData();
String cacheKey = CacheConstants.getGlobalResourcesDataKey(startTime, currentDate);
redisService.setCacheObject(cacheKey, globalResourcesDataVo, 24L, TimeUnit.HOURS);
}
}

View File

@ -0,0 +1,44 @@
package com.microservices.dss.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.text.ParseException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class DataStructureConvertUtil {
public static Map<Object,Object> MapInitByMonth(int monthDiff, String endTime) throws ParseException {
Map<Object, Object> map_init = new LinkedHashMap<>();
//构建一个size为monthDiff按顺序的日期作为key,value为0
for(int i=-(monthDiff);i<=0;i++){
map_init.put(DateUtil.OnlyYearMonthDateAddByMonth(endTime,i),0);
}
return map_init;
}
public static int[] dbResult2Array(List<Object> db_result, String key, String value, Map<Object, Object> map_init, int[] resultArray) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
for (Object o : db_result) {
// 使用 ObjectMapper 直接将对象转为 Map
Map<?, ?> m = mapper.convertValue(o, Map.class);
Object mapKey = m.get(key);
if (map_init.containsKey(mapKey)) {
map_init.put(mapKey, m.get(value));
}
}
int index = 0; // 维护一个索引
for (Object mapValue : map_init.values()) {
if (index < resultArray.length) { // 确保不会越界
resultArray[index++] = Integer.parseInt(mapValue.toString());
}
}
return resultArray;
}
}

View File

@ -0,0 +1,62 @@
package com.microservices.dss.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateUtil {
public static final String PATTERN_DATE_ONLY_YEAR_MONTH = "yyyy-MM";
/**
* @author wanjia
* Description 日期运算加减年份
* Date 2021/5/12 19:47
* @param date 传入日期 yyyy-mm-dd
* @param i 被加数
* @return java.lang.String
**/
public static String DateAddByYear(String date,int i) throws ParseException {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM");
Date date1 = df.parse(date);
calendar.setTime(date1);
calendar.add(Calendar.YEAR,i);
return df.format(calendar.getTime());
}
public static String OnlyYearMonthDateAddByMonth(String date,int i) throws ParseException {
Calendar calendar;
calendar = Calendar.getInstance();
SimpleDateFormat df=new SimpleDateFormat(PATTERN_DATE_ONLY_YEAR_MONTH);
Date date1 = df.parse(date);
calendar.setTime(date1);
calendar.add(Calendar.MONTH,i);
return df.format(calendar.getTime());
}
public static String currentYearMonth() {
return new SimpleDateFormat("yyyy-MM").format(Calendar.getInstance().getTime());
}
public static String getFormattedCurrentDate() {
return new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime());
}
/**
* 得到当前日期的结束时间
*/
public static String getFormattedCurrentDateTime() {
return getFormattedCurrentDate() + " 23:59:59";
}
/**
* 得到当前时间前一年同月的第一天的日期
**/
public static String getFormattedPreviousYearSameMonth() {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, -1);
return new SimpleDateFormat("yyyy-MM-01 00:00:00").format(calendar.getTime());
}
}

View File

@ -0,0 +1,45 @@
package com.microservices.dss.utils;
import com.alibaba.fastjson2.JSONObject;
import com.microservices.common.core.utils.DateUtils;
import com.microservices.common.core.utils.StringUtils;
import com.microservices.common.httpClient.domain.GitLinkRequestUrl;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author otto
*/
public class DssGitLinkRequestUrl extends GitLinkRequestUrl {
/**
* 获取项目最新动态
*/
public static GitLinkRequestUrl GET_LATEST_ACTIVITIES(int page, int limit) {
return getAdminGitLinkRequestUrl(
String.format("/api/activity/last.json?page=%d&limit=%d", page, limit)
);
}
/**
* 获取项目排行列表
*/
public static GitLinkRequestUrl GET_PROJECT_RANK(int time, int limit) {
return getAdminGitLinkRequestUrl(
String.format("/api/project_rank.json?time=%d&limit=%d", time, limit)
);
}
/**
* 获取用户排行列表
*/
public static GitLinkRequestUrl GET_USER_RANK(int time, int limit) {
return getAdminGitLinkRequestUrl(
String.format("/api/user_rank.json?time=%d&limit=%d", time, limit)
);
}
}

View File

@ -0,0 +1,34 @@
# Tomcat
server:
port: 9198
# Spring
spring:
application:
# 应用名称
name: microservices-dss
config:
activate:
# 环境配置
on-profile:
prod
cloud:
sentinel:
# 取消控制台懒加载
eager: true
nacos:
discovery:
# 服务注册地址
server-addr: ${nacos_ip}:${nacos_port}
username: ${nacos_username}
password: ${nacos_password}
config:
# 配置中心地址
server-addr: ${nacos_ip}:${nacos_port}
username: ${nacos_username}
password: ${nacos_password}
# 配置文件格式
file-extension: yml
# 共享配置
shared-configs:
- { dataId: "application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}",refresh: true }

View File

@ -0,0 +1,32 @@
# Tomcat
server:
port: 9198
# Spring
spring:
application:
# 应用名称
name: microservices-dss
profiles:
# 环境配置
active: dev
cloud:
sentinel:
# 取消控制台懒加载
eager: true
nacos:
discovery:
# 服务注册地址
server-addr: 127.0.0.1:8848
username: nacos
password: nacos
config:
# 配置中心地址
server-addr: 127.0.0.1:8848
username: nacos
password: nacos
# 配置文件格式
file-extension: yml
# 共享配置
shared-configs:
- { dataId: "application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}",refresh: true }

View File

@ -0,0 +1,101 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<!-- 日志存放路径 -->
<property name="log.path" value="logs/microservices-dss"/>
<!-- 日志输出格式 -->
<property name="log.pattern" value="%d{HH:mm:ss.SSS} [%thread] %-5level %logger{20} - [%method,%line] - %msg%n"/>
<!-- 控制台输出 -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
</appender>
<!-- 系统日志输出 -->
<appender name="file_info" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/info.log</file>
<!-- 循环政策:基于时间创建日志文件 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志文件名格式 -->
<fileNamePattern>${log.path}/info.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大的历史 60天 -->
<maxHistory>60</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<!-- 过滤的级别 -->
<level>INFO</level>
<!-- 匹配时的操作:接收(记录) -->
<onMatch>ACCEPT</onMatch>
<!-- 不匹配时的操作:拒绝(不记录) -->
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<appender name="file_error" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/error.log</file>
<!-- 循环政策:基于时间创建日志文件 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志文件名格式 -->
<fileNamePattern>${log.path}/error.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大的历史 60天 -->
<maxHistory>60</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<!-- 过滤的级别 -->
<level>ERROR</level>
<!-- 匹配时的操作:接收(记录) -->
<onMatch>ACCEPT</onMatch>
<!-- 不匹配时的操作:拒绝(不记录) -->
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 系统模块日志级别控制 -->
<logger name="com.microservices" level="info"/>
<!-- Spring日志级别控制 -->
<logger name="org.springframework" level="warn"/>
<!-- add converter for %tid -->
<conversionRule conversionWord="tid"
converterClass="org.apache.skywalking.apm.toolkit.log.logback.v1.x.LogbackPatternConverter"/>
<!-- add converter for %sw_ctx -->
<conversionRule conversionWord="sw_ctx"
converterClass="org.apache.skywalking.apm.toolkit.log.logback.v1.x.LogbackSkyWalkingContextPatternConverter"/>
<appender name="skywalking_grpc"
class="org.apache.skywalking.apm.toolkit.log.logback.v1.x.log.GRPCLogClientAppender">
<encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
<layout class="org.apache.skywalking.apm.toolkit.log.logback.v1.x.mdc.TraceIdMDCPatternLogbackLayout">
<Pattern>
{
"level": "%level",
"tid": "%tid",
"skyWalkingContext": "%sw_ctx",
"thread": "%thread",
"class": "%logger{1.}:%L",
"message": "%message",
"stackTrace": "%exception{10}"
}
</Pattern>
</layout>
</encoder>
</appender>
<root level="info">
<appender-ref ref="skywalking_grpc"/>
<appender-ref ref="console"/>
</root>
<!--系统操作日志-->
<root level="info">
<appender-ref ref="file_info"/>
<appender-ref ref="file_error"/>
</root>
</configuration>

View File

@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.microservices.dss.projects.mapper.CommitsMapper">
<resultMap id="BaseResultMap" type="com.microservices.dss.projects.domain.Commits">
<id column="id" property="id" jdbcType="INTEGER" />
<result column="repository_id" property="repositoryId" jdbcType="INTEGER" />
<result column="version" property="version" jdbcType="VARCHAR" />
<result column="committer" property="committer" jdbcType="VARCHAR" />
<result column="committed_on" property="committedOn" jdbcType="TIMESTAMP" />
<result column="project_id" property="projectId" jdbcType="INTEGER" />
<result column="created_at" property="createdAt" jdbcType="TIMESTAMP" />
<result column="updated_at" property="updatedAt" jdbcType="TIMESTAMP" />
</resultMap>
<select id="selectTotalCommitCount" resultType="java.lang.Integer">
select count(*)
from commit_logs
</select>
<select id="getNewCodeSubmissionTimesByMonth" parameterType="java.lang.String" resultType="java.util.HashMap">
SELECT
DATE_FORMAT(created_at, '%Y-%m') AS createTime,
COUNT(*) AS num
FROM
commit_logs
WHERE
created_at &gt;= #{startTime,jdbcType=VARCHAR}
AND created_at &lt;= #{endTime,jdbcType=VARCHAR}
GROUP BY DATE_FORMAT(created_at, '%Y-%m')
</select>
</mapper>

View File

@ -0,0 +1,50 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.microservices.dss.projects.mapper.IssuesMapper">
<resultMap id="BaseResultMap" type="com.microservices.dss.projects.domain.Issues">
<id column="id" property="id" jdbcType="INTEGER" />
<result column="tracker_id" property="trackerId" jdbcType="INTEGER" />
<result column="project_id" property="projectId" jdbcType="INTEGER" />
<result column="subject" property="subject" jdbcType="VARCHAR" />
<result column="due_date" property="dueDate" jdbcType="DATE" />
<result column="category_id" property="categoryId" jdbcType="INTEGER" />
<result column="status_id" property="statusId" jdbcType="INTEGER" />
<result column="assigned_to_id" property="assignedToId" jdbcType="INTEGER" />
<result column="priority_id" property="priorityId" jdbcType="INTEGER" />
<result column="fixed_version_id" property="fixedVersionId" jdbcType="INTEGER" />
<result column="author_id" property="authorId" jdbcType="INTEGER" />
<result column="created_on" property="createdOn" jdbcType="TIMESTAMP" />
<result column="updated_on" property="updatedOn" jdbcType="TIMESTAMP" />
<result column="start_date" property="startDate" jdbcType="DATE" />
<result column="done_ratio" property="doneRatio" jdbcType="INTEGER" />
<result column="estimated_hours" property="estimatedHours" jdbcType="REAL" />
<result column="parent_id" property="parentId" jdbcType="INTEGER" />
<result column="root_id" property="rootId" jdbcType="INTEGER" />
<result column="lft" property="lft" jdbcType="INTEGER" />
<result column="rgt" property="rgt" jdbcType="INTEGER" />
<result column="is_private" property="isPrivate" jdbcType="BIT" />
<result column="closed_on" property="closedOn" jdbcType="TIMESTAMP" />
<result column="project_issues_index" property="projectIssuesIndex" jdbcType="INTEGER" />
<result column="issue_type" property="issueType" jdbcType="VARCHAR" />
<result column="token" property="token" jdbcType="INTEGER" />
<result column="issue_tags_value" property="issueTagsValue" jdbcType="VARCHAR" />
<result column="is_lock" property="isLock" jdbcType="BIT" />
<result column="issue_classify" property="issueClassify" jdbcType="VARCHAR" />
<result column="ref_name" property="refName" jdbcType="VARCHAR" />
<result column="branch_name" property="branchName" jdbcType="VARCHAR" />
</resultMap>
<select id="getNewAddedIssuesCompletionByMonth" parameterType="java.lang.String" resultType="java.util.HashMap">
SELECT
DATE_FORMAT(created_on, '%Y-%m') AS createTime,
COUNT(*) AS num
FROM
issues
WHERE
created_on &gt;= #{startTime,jdbcType=VARCHAR}
AND created_on &lt;= #{endTime,jdbcType=VARCHAR}
GROUP BY DATE_FORMAT(created_on, '%Y-%m')
</select>
</mapper>

View File

@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.microservices.dss.projects.mapper.JournalsMapper">
<resultMap id="BaseResultMap" type="com.microservices.dss.projects.domain.Journals" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="journalized_id" property="journalizedId" jdbcType="INTEGER" />
<result column="journalized_type" property="journalizedType" jdbcType="VARCHAR" />
<result column="user_id" property="userId" jdbcType="INTEGER" />
<result column="notes" property="notes" jdbcType="VARCHAR" />
<result column="created_on" property="createdOn" jdbcType="TIMESTAMP" />
<result column="private_notes" property="privateNotes" jdbcType="BIT" />
<result column="parent_id" property="parentId" jdbcType="INTEGER" />
<result column="comments_count" property="commentsCount" jdbcType="INTEGER" />
<result column="reply_id" property="replyId" jdbcType="INTEGER" />
<result column="review_id" property="reviewId" jdbcType="BIGINT" />
<result column="commit_id" property="commitId" jdbcType="VARCHAR" />
<result column="line_code" property="lineCode" jdbcType="VARCHAR" />
<result column="path" property="path" jdbcType="VARCHAR" />
<result column="state" property="state" jdbcType="INTEGER" />
<result column="resolve_at" property="resolveAt" jdbcType="TIMESTAMP" />
<result column="resolveer_id" property="resolveerId" jdbcType="INTEGER" />
<result column="need_respond" property="needRespond" jdbcType="BIT" />
<result column="updated_on" property="updatedOn" jdbcType="TIMESTAMP" />
</resultMap>
<select id="getNewJournalsNumByMonth" parameterType="java.lang.String" resultType="java.util.HashMap">
SELECT
DATE_FORMAT(created_on, '%Y-%m') AS createTime,
COUNT(*) AS num
FROM
journals
WHERE
created_on &gt;= #{startTime,jdbcType=VARCHAR}
AND created_on &lt;= #{endTime,jdbcType=VARCHAR}
GROUP BY DATE_FORMAT(created_on, '%Y-%m')
</select>
</mapper>

View File

@ -0,0 +1,102 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.microservices.dss.projects.mapper.ProjectsMapper">
<resultMap id="BaseResultMap" type="com.microservices.dss.projects.domain.Projects" >
<result column="id" property="id" jdbcType="INTEGER" />
<result column="name" property="name" jdbcType="VARCHAR" />
<result column="homepage" property="homepage" jdbcType="VARCHAR" />
<result column="is_public" property="isPublic" jdbcType="BIT" />
<result column="parent_id" property="parentId" jdbcType="INTEGER" />
<result column="created_on" property="createdOn" jdbcType="TIMESTAMP" />
<result column="updated_on" property="updatedOn" jdbcType="TIMESTAMP" />
<result column="identifier" property="identifier" jdbcType="VARCHAR" />
<result column="status" property="status" jdbcType="INTEGER" />
<result column="lft" property="lft" jdbcType="INTEGER" />
<result column="rgt" property="rgt" jdbcType="INTEGER" />
<result column="inherit_members" property="inheritMembers" jdbcType="BIT" />
<result column="project_type" property="projectType" jdbcType="INTEGER" />
<result column="hidden_repo" property="hiddenRepo" jdbcType="BIT" />
<result column="attachmenttype" property="attachmenttype" jdbcType="INTEGER" />
<result column="user_id" property="userId" jdbcType="INTEGER" />
<result column="dts_test" property="dtsTest" jdbcType="INTEGER" />
<result column="enterprise_name" property="enterpriseName" jdbcType="VARCHAR" />
<result column="organization_id" property="organizationId" jdbcType="INTEGER" />
<result column="project_new_type" property="projectNewType" jdbcType="INTEGER" />
<result column="gpid" property="gpid" jdbcType="INTEGER" />
<result column="forked_from_project_id" property="forkedFromProjectId" jdbcType="INTEGER" />
<result column="forked_count" property="forkedCount" jdbcType="INTEGER" />
<result column="publish_resource" property="publishResource" jdbcType="INTEGER" />
<result column="visits" property="visits" jdbcType="INTEGER" />
<result column="hot" property="hot" jdbcType="INTEGER" />
<result column="invite_code" property="inviteCode" jdbcType="VARCHAR" />
<result column="qrcode" property="qrcode" jdbcType="VARCHAR" />
<result column="qrcode_expiretime" property="qrcodeExpiretime" jdbcType="INTEGER" />
<result column="training_status" property="trainingStatus" jdbcType="TINYINT" />
<result column="rep_identifier" property="repIdentifier" jdbcType="VARCHAR" />
<result column="project_category_id" property="projectCategoryId" jdbcType="INTEGER" />
<result column="project_language_id" property="projectLanguageId" jdbcType="INTEGER" />
<result column="license_id" property="licenseId" jdbcType="INTEGER" />
<result column="ignore_id" property="ignoreId" jdbcType="INTEGER" />
<result column="praises_count" property="praisesCount" jdbcType="INTEGER" />
<result column="watchers_count" property="watchersCount" jdbcType="INTEGER" />
<result column="issues_count" property="issuesCount" jdbcType="INTEGER" />
<result column="pull_requests_count" property="pullRequestsCount" jdbcType="INTEGER" />
<result column="language" property="language" jdbcType="VARCHAR" />
<result column="versions_count" property="versionsCount" jdbcType="INTEGER" />
<result column="issue_tags_count" property="issueTagsCount" jdbcType="INTEGER" />
<result column="closed_issues_count" property="closedIssuesCount" jdbcType="INTEGER" />
<result column="open_devops" property="openDevops" jdbcType="BIT" />
<result column="gitea_webhook_id" property="giteaWebhookId" jdbcType="INTEGER" />
<result column="open_devops_count" property="openDevopsCount" jdbcType="INTEGER" />
<result column="recommend" property="recommend" jdbcType="BIT" />
<result column="platform" property="platform" jdbcType="INTEGER" />
</resultMap>
<select id="selectProjectCount" resultType="java.lang.Integer">
select count(*)
from projects;
</select>
<select id="getNewAddedProjectsByMonth" parameterType="java.lang.String" resultType="java.util.HashMap">
SELECT
DATE_FORMAT(created_on, '%Y-%m') AS createTime,
COUNT(*) AS num
FROM
projects
WHERE
created_on between #{startTime,jdbcType=VARCHAR}
AND #{endTime,jdbcType=VARCHAR}
GROUP BY createTime
</select>
<select id="getActiveProjectsByMonth" parameterType="java.lang.String" resultType="java.util.HashMap">
SELECT
DATE_FORMAT(updated_on, '%Y-%m') AS createTime,
COUNT(DISTINCT project_id) AS num
from (
SELECT id as project_id, DATE_FORMAT(updated_on, '%Y-%m-%d' ) as updated_on FROM projects WHERE updated_on BETWEEN #{startTime,jdbcType=VARCHAR} AND #{endTime,jdbcType=VARCHAR}
UNION ALL
SELECT DISTINCT project_id, DATE_FORMAT(updated_at, '%Y-%m-%d' ) as updated_on FROM commit_logs WHERE updated_at BETWEEN #{startTime,jdbcType=VARCHAR} AND #{endTime,jdbcType=VARCHAR}
UNION ALL
SELECT DISTINCT project_id, DATE_FORMAT(updated_on, '%Y-%m-%d' ) as updated_on FROM issues WHERE updated_on BETWEEN #{startTime,jdbcType=VARCHAR} AND #{endTime,jdbcType=VARCHAR}
) as t
GROUP BY createTime
</select>
<select id="getProjectNumOfDiffProgramLanguage"
resultType="com.microservices.dss.projects.domain.PieChartNameAndValue">
select name,projects_count as `value`
from project_languages
order by projects_count desc
limit #{topNumber};
</select>
<select id="getProjectNumOfProjectCategory"
resultType="com.microservices.dss.projects.domain.PieChartNameAndValue">
select name,projects_count as `value`
from `project_categories`
order by projects_count desc
limit #{topNumber};
</select>
</mapper>

View File

@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.microservices.dss.projects.mapper.PullRequestsMapper">
<resultMap id="BaseResultMap" type="com.microservices.dss.projects.domain.PullRequests">
<id column="id" property="id" jdbcType="INTEGER" />
<result column="pull_request_id" property="pullRequestId" jdbcType="INTEGER" />
<result column="gpid" property="gpid" jdbcType="INTEGER" />
<result column="user_id" property="userId" jdbcType="INTEGER" />
<result column="created_at" property="createdAt" jdbcType="TIMESTAMP" />
<result column="updated_at" property="updatedAt" jdbcType="TIMESTAMP" />
<result column="status" property="status" jdbcType="INTEGER" />
<result column="project_id" property="projectId" jdbcType="INTEGER" />
<result column="title" property="title" jdbcType="VARCHAR" />
<result column="milestone" property="milestone" jdbcType="INTEGER" />
<result column="head" property="head" jdbcType="VARCHAR" />
<result column="base" property="base" jdbcType="VARCHAR" />
<result column="issue_id" property="issueId" jdbcType="INTEGER" />
<result column="fork_project_id" property="forkProjectId" jdbcType="INTEGER" />
<result column="is_original" property="isOriginal" jdbcType="BIT" />
<result column="comments_count" property="commentsCount" jdbcType="INTEGER" />
<result column="commits_count" property="commitsCount" jdbcType="INTEGER" />
<result column="files_count" property="filesCount" jdbcType="INTEGER" />
</resultMap>
<select id="selectTotalPullRequestCount" resultType="java.lang.Integer">
select count(*)
from pull_requests
</select>
<select id="getNewPullRequestNumByMonth" parameterType="java.lang.String" resultType="java.util.HashMap">
SELECT
DATE_FORMAT(created_at, '%Y-%m') AS createTime,
COUNT(*) AS num
FROM
pull_requests
WHERE
created_at &gt;= #{startTime,jdbcType=VARCHAR}
AND created_at &lt;= #{endTime,jdbcType=VARCHAR}
GROUP BY DATE_FORMAT(created_at, '%Y-%m')
</select>
</mapper>

View File

@ -0,0 +1,211 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.microservices.dss.makerspace.mapper.TasksMapper">
<resultMap id="BaseResultMap" type="com.microservices.dss.makerspace.domain.Tasks">
<id column="id" property="id" jdbcType="INTEGER" />
<result column="name" property="name" jdbcType="VARCHAR" />
<result column="bounty" property="bounty" jdbcType="DECIMAL" />
<result column="number" property="number" jdbcType="VARCHAR" />
<result column="published" property="published" jdbcType="BIT" />
<result column="visits" property="visits" jdbcType="INTEGER" />
<result column="expired_at" property="expiredAt" jdbcType="TIMESTAMP" />
<result column="published_at" property="publishedAt" jdbcType="TIMESTAMP" />
<result column="publish_mode" property="publishMode" jdbcType="INTEGER" />
<result column="collection_mode" property="collectionMode" jdbcType="INTEGER" />
<result column="show_user_mode" property="showUserMode" jdbcType="INTEGER" />
<result column="status" property="status" jdbcType="INTEGER" />
<result column="papers_count" property="papersCount" jdbcType="INTEGER" />
<result column="task_mode_id" property="taskModeId" jdbcType="INTEGER" />
<result column="created_at" property="createdAt" jdbcType="TIMESTAMP" />
<result column="updated_at" property="updatedAt" jdbcType="TIMESTAMP" />
<result column="category_id" property="categoryId" jdbcType="INTEGER" />
<result column="user_id" property="userId" jdbcType="INTEGER" />
<result column="enterprise_name" property="enterpriseName" jdbcType="VARCHAR" />
<result column="contact_name" property="contactName" jdbcType="VARCHAR" />
<result column="contact_phone" property="contactPhone" jdbcType="VARCHAR" />
<result column="show_user_status" property="showUserStatus" jdbcType="BIT" />
<result column="agreement_signing" property="agreementSigning" jdbcType="INTEGER" />
<result column="is_delete" property="isDelete" jdbcType="BIT" />
<result column="ip" property="ip" jdbcType="VARCHAR" />
<result column="paid_at" property="paidAt" jdbcType="TIMESTAMP" />
<result column="make_public_at" property="makePublicAt" jdbcType="TIMESTAMP" />
<result column="collecting_days" property="collectingDays" jdbcType="INTEGER" />
<result column="choosing_days" property="choosingDays" jdbcType="INTEGER" />
<result column="make_public_days" property="makePublicDays" jdbcType="INTEGER" />
<result column="signing_days" property="signingDays" jdbcType="INTEGER" />
<result column="paying_days" property="payingDays" jdbcType="INTEGER" />
<result column="except_closed_boolean" property="exceptClosedBoolean" jdbcType="BIT" />
<result column="is_proof_boolean" property="isProofBoolean" jdbcType="BIT" />
<result column="cancel_status" property="cancelStatus" jdbcType="INTEGER" />
<result column="is_signing_upload" property="isSigningUpload" jdbcType="INTEGER" />
<result column="is_paying_upload" property="isPayingUpload" jdbcType="BIT" />
<result column="upload_proof_at" property="uploadProofAt" jdbcType="TIMESTAMP" />
</resultMap>
<select id="getTotalTaskCount" resultType="java.lang.Integer">
select count(*)
from tasks
where is_delete = 0 and `status` between 3 and 8
</select>
<select id="getTotalApplicantCount" resultType="java.lang.Integer">
select count(*)
from papers
where is_delete = 0 and parent_id = 0
</select>
<select id="getCurrentTotalAwardAmount" resultType="java.lang.Integer">
select sum(bounty)
from tasks
where is_delete = 0 and `status` between 3 and 8
</select>
<select id="getTaskPublishedCountsByYear" resultType="map">
SELECT
YEAR(created_at) AS `year`,
COUNT(*) AS taskCount
FROM
tasks
WHERE
is_delete = 0
AND STATUS BETWEEN 3 AND 8
AND YEAR(created_at) IN (YEAR(CURDATE()) - 1, YEAR(CURDATE()))
GROUP BY
YEAR(created_at)
ORDER BY
YEAR;
</select>
<select id="getTaskBountyCountsByYear" resultType="map">
SELECT
YEAR(created_at) AS `year`,
FLOOR((sum(bounty) / 10000)) AS bountyCount
FROM
tasks
WHERE
is_delete = 0
AND STATUS BETWEEN 3 AND 8
AND YEAR(created_at) IN (YEAR(CURDATE()) - 1, YEAR(CURDATE()))
GROUP BY
YEAR(created_at)
ORDER BY
YEAR;
</select>
<select id="getNewAddedTasksByMonth" parameterType="java.lang.String" resultType="java.util.HashMap">
SELECT
DATE_FORMAT(created_at, '%Y-%m') AS createTime,
COUNT(*) AS num
FROM
tasks
WHERE
created_at between #{startTime,jdbcType=VARCHAR}
AND #{endTime,jdbcType=VARCHAR}
AND is_delete = 0
AND `status` BETWEEN 3 AND 8
GROUP BY createTime
</select>
<select id="getNewAddedPapersByMonth" parameterType="java.lang.String" resultType="java.util.HashMap">
SELECT
DATE_FORMAT(created_at, '%Y-%m') AS createTime,
COUNT(*) AS num
FROM
papers
WHERE
created_at between #{startTime,jdbcType=VARCHAR}
AND #{endTime,jdbcType=VARCHAR}
AND is_delete = 0
AND parent_id = 0
GROUP BY createTime
</select>
<select id="getTaskOperLogTopN" resultType="map">
SELECT
log_desc as log_desc,
CASE
WHEN TIMESTAMPDIFF(MINUTE, oper_time, NOW()) = 0 THEN CONCAT(TIMESTAMPDIFF(SECOND, oper_time, NOW()), '秒前')
WHEN TIMESTAMPDIFF(HOUR, oper_time, NOW()) = 0 THEN CONCAT(TIMESTAMPDIFF(MINUTE, oper_time, NOW()), '分钟前')
WHEN TIMESTAMPDIFF(DAY, oper_time, NOW()) = 0 THEN CONCAT(TIMESTAMPDIFF(HOUR, oper_time, NOW()), '小时前')
ELSE CONCAT(TIMESTAMPDIFF(DAY, oper_time, NOW()), '天前')
END AS time_ago,
task_id
FROM
task_oper_log
ORDER BY
id DESC
LIMIT #{topNum};
</select>
<select id="getOpeningTaskNumOfTaskStatus"
resultType="com.microservices.dss.projects.domain.PieChartNameAndValue">
select `status` as `name`,count(id) as `value`
from tasks
where is_delete = 0 and `status` between 3 and 7
GROUP BY `status`
order by `value` desc
limit #{topNum};
</select>
<select id="getAllTaskNumOfTaskCategory"
resultType="com.microservices.dss.projects.domain.PieChartNameAndValue">
select c.name as `name`,count(t.id) as `value`
from tasks as t
left join categories as c on t.category_id = c.id
where t.is_delete = 0 and t.status between 3 and 8
GROUP BY c.`name`
order by `value` desc
</select>
<select id="getBountyDistribution" resultType="map">
SELECT
CASE
WHEN bounty &lt;= 5000 THEN '5k以下'
WHEN bounty > 5000 AND bounty &lt;= 20000 THEN '5k-2w以下'
WHEN bounty > 20000 AND bounty &lt;= 50000 THEN '2w-5W以下'
WHEN bounty > 50000 AND bounty &lt;= 100000 THEN '5W-10W以下'
WHEN bounty > 100000 AND bounty &lt;= 500000 THEN '10W-50W以下'
ELSE '50W以上'
END AS bounty_range,
COUNT(*) AS task_count,
ROUND(COUNT(CASE WHEN STATUS = 8 THEN 1 END) / COUNT(*) * 100, 0) AS paied_rate
FROM
tasks
WHERE
is_delete = 0 AND STATUS BETWEEN 3 AND 8
GROUP BY
bounty_range
ORDER BY
CASE bounty_range
WHEN '5k以下' THEN 1
WHEN '5k-2w以下' THEN 2
WHEN '2w-5W以下' THEN 3
WHEN '5W-10W以下' THEN 4
WHEN '10W-50W以下' THEN 5
ELSE 6
END;
</select>
<select id="getTotalCompletedBounty" resultType="map">
SELECT SUM(bounty) as 'total_paid_bounty'
FROM tasks
WHERE is_delete = 0 AND `status` = 8;
</select>
<select id="getTaskInfoByVisits" resultType="com.microservices.dss.makerspace.domain.vo.TaskHeatInfoVo">
SELECT t.`name` AS taskName, t.published_at AS publishDate,
COUNT(p.id) AS participantCount, trp.winner_name AS winnerNames, t.id AS taskId
FROM tasks AS t
LEFT JOIN papers AS p ON p.task_id = t.id
LEFT JOIN task_result_proof AS trp ON trp.task_id = t.id
WHERE t.is_delete = 0 AND t.status BETWEEN 3 AND 8
GROUP BY t.`name`, t.published_at, t.visits, trp.winner_name, t.id
ORDER BY t.visits DESC
LIMIT #{topNum};
</select>
<select id="getTaskModeStatistic" resultType="java.util.Map">
SELECT
CASE
WHEN publish_mode = 0 THEN '自筹任务'
WHEN publish_mode = 1 THEN '统筹任务'
ELSE '其他'
END as taskMode,
COUNT(id) AS taskCount,
SUM(bounty) AS totalBounty
FROM tasks
WHERE is_delete = 0 AND `status` BETWEEN 3 AND 8
GROUP BY publish_mode
</select>
</mapper>

View File

@ -0,0 +1,95 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.microservices.dss.projects.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.microservices.dss.projects.domain.User">
<id column="id" property="id" jdbcType="INTEGER"/>
<result column="login" property="login" jdbcType="VARCHAR"/>
<result column="hashed_password" property="hashedPassword" jdbcType="VARCHAR"/>
<result column="firstname" property="firstname" jdbcType="VARCHAR"/>
<result column="lastname" property="lastname" jdbcType="VARCHAR"/>
<result column="mail" property="mail" jdbcType="VARCHAR"/>
<result column="admin" property="admin" jdbcType="BIT"/>
<result column="status" property="status" jdbcType="INTEGER"/>
<result column="last_login_on" property="lastLoginOn" jdbcType="TIMESTAMP"/>
<result column="language" property="language" jdbcType="VARCHAR"/>
<result column="auth_source_id" property="authSourceId" jdbcType="INTEGER"/>
<result column="created_on" property="createdOn" jdbcType="TIMESTAMP"/>
<result column="updated_on" property="updatedOn" jdbcType="TIMESTAMP"/>
<result column="type" property="type" jdbcType="VARCHAR"/>
<result column="identity_url" property="identityUrl" jdbcType="VARCHAR"/>
<result column="mail_notification" property="mailNotification" jdbcType="VARCHAR"/>
<result column="salt" property="salt" jdbcType="VARCHAR"/>
<result column="gid" property="gid" jdbcType="INTEGER"/>
<result column="visits" property="visits" jdbcType="INTEGER"/>
<result column="excellent_teacher" property="excellentTeacher" jdbcType="INTEGER"/>
<result column="excellent_student" property="excellentStudent" jdbcType="INTEGER"/>
<result column="phone" property="phone" jdbcType="VARCHAR"/>
<result column="authentication" property="authentication" jdbcType="BIT"/>
<result column="grade" property="grade" jdbcType="INTEGER"/>
<result column="experience" property="experience" jdbcType="INTEGER"/>
<result column="nickname" property="nickname" jdbcType="VARCHAR"/>
<result column="show_realname" property="showRealname" jdbcType="BIT"/>
<result column="professional_certification" property="professionalCertification" jdbcType="BIT"/>
<result column="ID_number" property="idNumber" jdbcType="VARCHAR"/>
<result column="certification" property="certification" jdbcType="INTEGER"/>
<result column="homepage_teacher" property="homepageTeacher" jdbcType="BIT"/>
<result column="homepage_engineer" property="homepageEngineer" jdbcType="BIT"/>
<result column="is_test" property="isTest" jdbcType="TINYINT"/>
<result column="ecoder_user_id" property="ecoderUserId" jdbcType="INTEGER"/>
<result column="business" property="business" jdbcType="BIT"/>
<result column="profile_completed" property="profileCompleted" jdbcType="BIT"/>
<result column="laboratory_id" property="laboratoryId" jdbcType="BIGINT"/>
<result column="platform" property="platform" jdbcType="VARCHAR"/>
<result column="gitea_token" property="giteaToken" jdbcType="VARCHAR"/>
<result column="gitea_uid" property="giteaUid" jdbcType="INTEGER"/>
<result column="is_shixun_marker" property="isShixunMarker" jdbcType="BIT"/>
<result column="is_sync_pwd" property="isSyncPwd" jdbcType="BIT"/>
<result column="watchers_count" property="watchersCount" jdbcType="INTEGER"/>
<result column="enterprise_certification" property="enterpriseCertification" jdbcType="BIT"/>
<result column="admin_role" property="adminRole" jdbcType="TINYINT"/>
<result column="devops_step" property="devopsStep" jdbcType="INTEGER"/>
<result column="business" property="business" jdbcType="BIT"/>
</resultMap>
<select id="selectUserCount" resultType="java.lang.Integer">
select count(*)
from users
</select>
<select id="getNewAddedMembersByMonth" parameterType="java.lang.String" resultType="java.util.HashMap">
SELECT
DATE_FORMAT(created_on, '%Y-%m') AS createTime,
COUNT(*) AS num
FROM
users
WHERE
created_on &gt;= #{startTime,jdbcType=VARCHAR}
AND created_on &lt;= #{endTime,jdbcType=VARCHAR}
GROUP BY DATE_FORMAT(created_on, '%Y-%m')
</select>
<select id="getActiveMembersByMonth" parameterType="java.lang.String" resultType="java.util.HashMap">
SELECT
DATE_FORMAT(updated_on, '%Y-%m') AS createTime,
COUNT(DISTINCT user_id) AS num
from (
SELECT id as user_id, DATE_FORMAT(last_login_on, '%Y-%m-%d' ) as updated_on FROM users WHERE last_login_on &gt;= #{startTime,jdbcType=VARCHAR} AND last_login_on &lt;= #{endTime,jdbcType=VARCHAR}
UNION ALL
SELECT DISTINCT user_id, DATE_FORMAT(updated_at, '%Y-%m-%d' ) as updated_on FROM user_actions WHERE updated_at &gt;= #{startTime,jdbcType=VARCHAR} AND updated_at &lt;= #{endTime,jdbcType=VARCHAR}
UNION ALL
SELECT DISTINCT user_id, DATE_FORMAT(updated_at, '%Y-%m-%d' ) as updated_on FROM commit_logs WHERE updated_at &gt;= #{startTime,jdbcType=VARCHAR} AND updated_at &lt;= #{endTime,jdbcType=VARCHAR}
) as t GROUP BY createTime
</select>
<select id="getUserIdByToken" resultType="java.lang.Long">
select user_id
from tokens
where `value` = #{token}
</select>
<select id="getAdminStatus" resultType="java.lang.Boolean">
select admin
from users
where id = #{userId}
</select>
</mapper>

View File

@ -203,6 +203,14 @@ public class PmsCiPipelinesController extends BaseController {
return success(pmsCiPipelinesService.savePipelineYamlByGraphicJson(id, pmsCiPipelineBuildInputVo));
}
@PostMapping(value = "/{id}/savePipelineYamlNew")
@ApiOperation("流水线图形构建声明式yaml并保存")
public AjaxResult savePipelineYamlNew(@ApiParam(name = "id", value = "流水线id")@PathVariable Long id,
@RequestBody @Validated PmsCiPipelineBuildYamlInputVo pmsCiPipelineBuildInputVo)
{
return success(pmsCiPipelinesService.savePipelineYamlByGraphicJsonNew(id, pmsCiPipelineBuildInputVo));
}
/**
* 启动流水线执行记录任务
*/
@ -270,5 +278,4 @@ public class PmsCiPipelinesController extends BaseController {
@ApiParam(name = "fileName", value = "流水线文件名") @PathVariable String fileName) {
return success(pmsCiPipelinesService.getPipelineId(repoOwner, repoIdentifier, fileName));
}
}

View File

@ -0,0 +1,148 @@
package com.microservices.pms.pipeline.domain.vo;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import java.util.*;
import java.util.stream.Collectors;
@Getter
@Setter
@NoArgsConstructor
public class NodeActionVo {
private String name;
private final Map<String, Object> on = new LinkedHashMap<>();
private final Map<String, Object> jobs = new LinkedHashMap<>();
@JsonIgnore
private Map<String, Object> params = new LinkedHashMap<>();
public void buildName(String name) {
this.name = name;
}
public void parse(List<Map<String, Object>> steps, PipelineVo.PipelineJson.Nodes node){
String nodeName = Optional.ofNullable(node.getName()).orElse("");
if (nodeName.startsWith("on-")) {
buildOn(node);
}else if (nodeName.startsWith("setup-")) {
buildSetupStep(steps, node);
}else if (Objects.equals(nodeName,"shell")) {
buildShellStep(steps, node);
}else if (StringUtils.isNotEmpty(nodeName)) {
buildOtherStep(steps, node);
}
}
public void buildOn(PipelineVo.PipelineJson.Nodes node) {
String nodeName = node.getName();
Map<String, Object> step = new LinkedHashMap<>();
List<PipelineVo.PipelineJson.Nodes.Inputs> inputs = getInputs(node);
if (Objects.equals(nodeName, "on-schedule")) {
inputs.forEach(e -> {
step.put(e.getName(), e.getValue());
});
this.on.put(nodeName.split("-")[1], step);
return;
}
inputs.forEach(e -> {
step.put(e.getName(), e.getValue().replace("\'","").split(","));
});
this.on.put(nodeName.split("-")[1], step);
}
public void buildJobs(String jobKey, String jobName, List<Map<String, Object>> steps) {
if (steps.isEmpty()) return;
Map<String, Object> job = new LinkedHashMap<>();
job.put("runs-on", "ubuntu-latest");
job.put("name", jobName);
job.put("steps", steps);
this.jobs.put(jobKey+(this.jobs.size()), job);
}
public void buildSetupStep(List<Map<String, Object>> steps, PipelineVo.PipelineJson.Nodes node) {
String nodeName = node.getName();
Map<String, Object> step = new LinkedHashMap<>();
List<PipelineVo.PipelineJson.Nodes.Inputs> inputs = getInputs(node);
if (nodeName.startsWith("setup-java")) {
Map<String, String> name2Value = inputs.stream()
.collect(Collectors.toMap(e -> e.getName(), e -> e.getValue(), (o, n) -> n));
Map<String, Object> with = new LinkedHashMap<>();
if (name2Value.containsKey("download_url") && StringUtils.isNotBlank(name2Value.get("download_url"))) {
steps.add(Collections.singletonMap("run", "download_url=" + name2Value.get("download_url") + " && " + "wget -O $RUNNER_TEMP/java_package.tar.gz $download_url"));
with.put("distribution", "jdkfile");
with.put("jdkFile", "${{ runner.temp }}/java_package.tar.gz");
}
step.put("name", node.getLabel());
step.put("uses", node.getFull_name().trim());
if (!inputs.isEmpty()) {
inputs.forEach(i -> {
with.put(i.getName(), Optional.ofNullable(i.getValue()).orElse(""));
});
step.put("with", with);
}
steps.add(step);
return;
}
step.put("name", node.getLabel());
step.put("uses", node.getFull_name().trim());
if (!inputs.isEmpty()) {
Map<String, Object> with = new LinkedHashMap<>();
inputs.forEach(i -> {
with.put(i.getName(), Optional.ofNullable(i.getValue()).orElse(""));
});
step.put("with", with);
}
steps.add(step);
}
public void buildShellStep(List<Map<String, Object>> steps, PipelineVo.PipelineJson.Nodes node) {
Map<String, Object> step = new LinkedHashMap<>();
step.put("name", node.getLabel());
List<PipelineVo.PipelineJson.Nodes.Inputs> inputs = Optional.ofNullable(node.getInputs()).orElse(new ArrayList<>());
inputs.forEach(i -> {
step.put(i.getName(), Optional.ofNullable(i.getValue()).orElse(""));
});
steps.add(step);
}
public void buildOtherStep(List<Map<String, Object>> steps, PipelineVo.PipelineJson.Nodes node) {
Map<String, Object> step = new LinkedHashMap<>();
List<PipelineVo.PipelineJson.Nodes.Inputs> inputs = getInputs(node);
step.put("name", node.getLabel());
step.put("uses", node.getFull_name().trim());
if (!inputs.isEmpty()) {
Map<String, Object> with = new LinkedHashMap<>();
inputs.forEach(i -> {
with.put(i.getName(), Optional.ofNullable(i.getValue()).orElse(""));
});
step.put("with", with);
}
steps.add(step);
}
private List<PipelineVo.PipelineJson.Nodes.Inputs> getInputs(PipelineVo.PipelineJson.Nodes node) {
return Optional.ofNullable(node.getInputs()).orElse(new ArrayList<>())
.stream()
.filter(e -> StringUtils.isNotBlank(e.getValue())).collect(Collectors.toList());
}
}

View File

@ -0,0 +1,284 @@
package com.microservices.pms.pipeline.domain.vo;
import java.io.Serializable;
import java.util.List;
public class PipelineVo implements Serializable {
private String pipelineName;
private PipelineJson pipelineJson;
public String getPipelineName() {
return this.pipelineName;
}
public void setPipelineName(String pipelineName) {
this.pipelineName = pipelineName;
}
public PipelineJson getPipelineJson() {
return this.pipelineJson;
}
public void setPipelineJson(PipelineJson pipelineJson) {
this.pipelineJson = pipelineJson;
}
public static class PipelineJson implements Serializable {
private List<Nodes> nodes;
private List<Edges> edges;
public List<Nodes> getNodes() {
return this.nodes;
}
public void setNodes(List<Nodes> nodes) {
this.nodes = nodes;
}
public List<Edges> getEdges() {
return this.edges;
}
public void setEdges(List<Edges> edges) {
this.edges = edges;
}
public static class Nodes implements Serializable {
private Integer action_node_types_id;
private String img;
private List<Inputs> inputs;
private String icon;
private String description;
private String label;
private String type;
private Integer sort_no;
private Integer use_count;
private String full_name;
private String name;
private Integer x;
private Double y;
private String id;
private Boolean isCluster;
private String yaml;
public Integer getAction_node_types_id() {
return this.action_node_types_id;
}
public void setAction_node_types_id(Integer action_node_types_id) {
this.action_node_types_id = action_node_types_id;
}
public String getImg() {
return this.img;
}
public void setImg(String img) {
this.img = img;
}
public List<Inputs> getInputs() {
return this.inputs;
}
public void setInputs(List<Inputs> inputs) {
this.inputs = inputs;
}
public String getIcon() {
return this.icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public String getLabel() {
return this.label;
}
public void setLabel(String label) {
this.label = label;
}
public String getType() {
return this.type;
}
public void setType(String type) {
this.type = type;
}
public Integer getSort_no() {
return this.sort_no;
}
public void setSort_no(Integer sort_no) {
this.sort_no = sort_no;
}
public Integer getUse_count() {
return this.use_count;
}
public void setUse_count(Integer use_count) {
this.use_count = use_count;
}
public String getFull_name() {
return this.full_name;
}
public void setFull_name(String full_name) {
this.full_name = full_name;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Integer getX() {
return this.x;
}
public void setX(Integer x) {
this.x = x;
}
public Double getY() {
return this.y;
}
public void setY(Double y) {
this.y = y;
}
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public Boolean getIsCluster() {
return this.isCluster;
}
public void setIsCluster(Boolean isCluster) {
this.isCluster = isCluster;
}
public String getYaml() {
return this.yaml;
}
public void setYaml(String yaml) {
this.yaml = yaml;
}
public static class Inputs implements Serializable {
private Boolean is_required;
private String name;
private String value;
private String input_type;
private Integer id;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Boolean getIs_required() {
return this.is_required;
}
public void setIs_required(Boolean is_required) {
this.is_required = is_required;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getInput_type() {
return this.input_type;
}
public void setInput_type(String input_type) {
this.input_type = input_type;
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
}
}
public static class Edges implements Serializable {
private String source;
private String target;
public String getSource() {
return this.source;
}
public void setSource(String source) {
this.source = source;
}
public String getTarget() {
return this.target;
}
public void setTarget(String target) {
this.target = target;
}
}
}
}

View File

@ -92,6 +92,8 @@ public interface IPmsCiPipelinesService
JSONObject savePipelineYamlByGraphicJson(Long id, PmsCiPipelineBuildYamlInputVo pmsCiPipelineBuildInputVo);
JSONObject savePipelineYamlByGraphicJsonNew(Long id, PmsCiPipelineBuildYamlInputVo pmsCiPipelineBuildInputVo);
JSONObject reRunPipelineRunsJob(Long id, String run, String job);
JSONObject reRunAllJobsInPipelineRun(Long id, String run);
@ -102,6 +104,8 @@ public interface IPmsCiPipelinesService
JSONObject getPipelineRunResults(Long id, String run);
JSONObject getPipelineRunResults(Long id, String run);
JSONObject getPipelineRubyIdByJavaId(Long javaId);
JSONObject getPipelineId(String repoOwner, String repoIdentifier, String fileName);

View File

@ -1,8 +1,17 @@
package com.microservices.pms.pipeline.service.impl;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.microservices.common.core.exception.ServiceException;
import com.microservices.common.core.utils.DateUtils;
import com.microservices.common.core.utils.StringUtils;
@ -23,6 +32,7 @@ import com.microservices.pms.pipeline.mapper.PmsCiPipelinesMapper;
import com.microservices.pms.pipeline.service.IPmsCiPipelineGraphicsService;
import com.microservices.pms.pipeline.service.IPmsCiPipelinesService;
import com.microservices.pms.utils.PmsGitLinkRequestUrl;
import com.microservices.pms.utils.YamlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
@ -405,6 +415,34 @@ public class PmsCiPipelinesServiceImpl implements IPmsCiPipelinesService {
return result;
}
@Override
public JSONObject savePipelineYamlByGraphicJsonNew(Long id, PmsCiPipelineBuildYamlInputVo pmsCiPipelineBuildInputVo) {
PmsCiPipelines pmsCiPipelines = pmsCiPipelinesMapper.selectPmsCiPipelinesById(id);
if (pmsCiPipelines == null) {
throw new ServiceException("该项目流水线不存在(流水线ID[%s])", id);
}
try {
PipelineVo vo = JSON.parseObject(JSON.toJSONString(pmsCiPipelineBuildInputVo), PipelineVo.class);
List<PipelineVo.PipelineJson.Nodes> nodes = vo.getPipelineJson().getNodes();
String pipelineName = vo.getPipelineName();
NodeActionVo actionVo = new NodeActionVo();
actionVo.buildName(pipelineName);
nodes.forEach(s -> {
List<Map<String, Object>> steps = new ArrayList<>();
actionVo.parse(steps, s);
actionVo.buildJobs("job", s.getLabel()+String.format("[%s]",s.getId().trim()), steps);
});
String yaml = YamlUtil.toYaml(actionVo);
JSONObject result = new JSONObject();
result.put("pipeline_yaml", yaml);
return result;
} catch (Exception e) {
logger.error("流水线图形Json解析失败)", e);
return null;
}
}
@Override
public JSONObject reRunPipelineRunsJob(Long id, String run, String job) {
PmsCiPipelines pmsCiPipelines = pmsCiPipelinesMapper.selectPmsCiPipelinesById(id);

View File

@ -440,4 +440,8 @@ public class PmsGitLinkRequestUrl extends GitLinkRequestUrl {
return getGitLinkRequestUrl(String.format("/api/pm/action_runs?owner_id=%s&workflows=%s", owner, workflows), "data");
}
public static GitLinkRequestUrl GET_PIPELINE_RUN_RESULTS(String owner, String repoIdentifier, String run){
return getGitLinkRequestUrl(String.format("/api/v1/%s/%s/pipelines/run_results.json?run_id=%s", owner, repoIdentifier, run));
}
}

View File

@ -0,0 +1,58 @@
package com.microservices.pms.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
import com.microservices.common.core.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.io.StringWriter;
@Slf4j
public class YamlUtil {
/**
* 将yaml字符串转成类对象
*
* @param yamlStr 字符串
* @param clazz 目标类
* @param <T> 泛型
* @return 目标类
*/
public static <T> T toObject(String yamlStr, Class<T> clazz) {
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
mapper.findAndRegisterModules();
try {
return mapper.readValue(yamlStr, clazz);
} catch (JsonProcessingException e) {
log.error("yaml文本解析成java对象错误", e);
throw new ServiceException("yaml文本解析成java对象错误");
}
}
/**
* 将类对象转yaml字符串
*
* @param object 对象
* @return yaml字符串
*/
public static String toYaml(Object object) {
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
mapper.findAndRegisterModules();
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
mapper = new ObjectMapper(new YAMLFactory().disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER));
StringWriter stringWriter = new StringWriter();
try {
mapper.writeValue(stringWriter, object);
return stringWriter.toString();
} catch (IOException e) {
log.error("Java对象解析成Yaml文本错误", e);
}
return null;
}
}

View File

@ -17,6 +17,7 @@
<module>microservices-modules-zone</module>
<module>microservices-modules-pms</module>
<module>microservices-modules-wiki</module>
<module>microservices-modules-dss</module>
</modules>
<artifactId>microservices-modules</artifactId>