Unverified Commit 0959a37e authored by zhu-mingye's avatar zhu-mingye Committed by GitHub

[Feature] Added op log (#2155)

* added operate log --------- Co-authored-by: 's avatarzhu-mingye <zhu-mingye@users.noreply.github.com>
parent db725ef5
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.annotation;
import org.dinky.data.enums.BusinessType;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/** 自定义操作日志记录注解 */
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log {
/** 模块 */
public String title() default "";
/** 功能 */
public BusinessType businessType() default BusinessType.OTHER;
/** 是否保存请求的参数 */
public boolean isSaveRequestData() default true;
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.aop;
import org.dinky.annotation.Log;
import org.dinky.context.UserInfoContextHolder;
import org.dinky.data.enums.BusinessStatus;
import org.dinky.data.model.OperateLog;
import org.dinky.data.model.User;
import org.dinky.service.impl.OperateLogServiceImpl;
import org.dinky.utils.IpUtils;
import org.dinky.utils.ServletUtils;
import org.apache.commons.lang3.StringUtils;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
/** 操作日志记录处理 */
@Aspect
@Slf4j
@Component
public class LogAspect {
@Pointcut("@annotation(org.dinky.annotation.Log)")
public void logPointCut() {}
/**
* 处理完请求后执行
*
* @param joinPoint 切点
*/
@AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
handleLog(joinPoint, null, jsonResult);
}
/**
* 拦截异常操作
*
* @param joinPoint 切点
* @param e 异常
*/
@AfterThrowing(value = "logPointCut()", throwing = "e")
public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
handleLog(joinPoint, e, null);
}
protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult) {
try {
// 获得注解
Log controllerLog = getAnnotationLog(joinPoint);
if (controllerLog == null) {
return;
}
// 获取当前的用户
User user = UserInfoContextHolder.get(StpUtil.getLoginIdAsInt()).getUser();
// *========数据库日志=========*//
OperateLog operLog = new OperateLog();
operLog.setStatus(BusinessStatus.SUCCESS.ordinal());
// 请求的地址
String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
operLog.setOperateIp(ip);
// 返回参数
operLog.setJsonResult(JSONUtil.toJsonStr(jsonResult));
operLog.setOperateUrl(ServletUtils.getRequest().getRequestURI());
if (user != null) {
operLog.setOperateName(user.getUsername());
operLog.setOperateUserId(user.getId());
}
if (e != null) {
operLog.setStatus(BusinessStatus.FAIL.ordinal());
log.error("pre doAfterThrowing Exception:{}", e.getMessage());
operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
}
operLog.setStatus(BusinessStatus.SUCCESS.ordinal());
// 设置方法名称
String className = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
operLog.setMethod(className + "." + methodName + "()");
// 设置请求方式
operLog.setRequestMethod(ServletUtils.getRequest().getMethod());
// 处理设置注解上的参数
getControllerMethodDescription(joinPoint, controllerLog, operLog);
operLog.setOperateTime(LocalDateTime.now());
// 保存数据库
SpringUtil.getBean(OperateLogServiceImpl.class).saveLog(operLog);
} catch (Exception exp) {
// 记录本地异常日志
log.error("pre doAfterThrowing Exception:{}", exp.getMessage());
exp.printStackTrace();
}
}
/**
* 获取注解中对方法的描述信息 用于Controller层注解
*
* @param log 日志
* @param operLog 操作日志
* @throws Exception
*/
public void getControllerMethodDescription(JoinPoint joinPoint, Log log, OperateLog operLog)
throws Exception {
// 设置action动作
operLog.setBusinessType(log.businessType().ordinal());
// 设置标题
operLog.setModuleName(log.title());
// 是否需要保存request,参数和值
if (log.isSaveRequestData()) {
// 获取参数的信息,传入到数据库中。
setRequestValue(joinPoint, operLog);
}
}
/**
* 获取请求的参数,放到log中
*
* @param operLog 操作日志
* @throws Exception 异常
*/
private void setRequestValue(JoinPoint joinPoint, OperateLog operLog) throws Exception {
String requestMethod = operLog.getRequestMethod();
if (HttpMethod.PUT.name().equals(requestMethod)
|| HttpMethod.POST.name().equals(requestMethod)) {
String params = argsArrayToString(joinPoint.getArgs());
operLog.setOperateParam(StringUtils.substring(params, 0, 2000));
} else {
Map<?, ?> paramsMap =
(Map<?, ?>)
ServletUtils.getRequest()
.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
operLog.setOperateParam(StringUtils.substring(paramsMap.toString(), 0, 2000));
}
}
/** 是否存在注解,如果存在就获取 */
private Log getAnnotationLog(JoinPoint joinPoint) throws Exception {
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
if (method != null) {
return method.getAnnotation(Log.class);
}
return null;
}
/** 参数拼装 */
private String argsArrayToString(Object[] paramsArray) {
String params = "";
if (paramsArray != null && paramsArray.length > 0) {
for (int i = 0; i < paramsArray.length; i++) {
if (!isFilterObject(paramsArray[i])) {
String jsonObj = JSONUtil.toJsonStr(paramsArray[i]);
params += jsonObj + " ";
}
}
}
return params.trim();
}
/**
* 判断是否需要过滤的对象。
*
* @param o 对象信息。
* @return 如果是需要过滤的对象,则返回true;否则返回false。
*/
public boolean isFilterObject(final Object o) {
return o instanceof MultipartFile
|| o instanceof HttpServletRequest
|| o instanceof HttpServletResponse;
}
}
......@@ -19,12 +19,14 @@
package org.dinky.controller;
import org.dinky.annotation.Log;
import org.dinky.data.dto.APICancelDTO;
import org.dinky.data.dto.APIExecuteJarDTO;
import org.dinky.data.dto.APIExecuteSqlDTO;
import org.dinky.data.dto.APIExplainSqlDTO;
import org.dinky.data.dto.APISavePointDTO;
import org.dinky.data.dto.APISavePointTaskDTO;
import org.dinky.data.enums.BusinessType;
import org.dinky.data.enums.Status;
import org.dinky.data.model.JobInstance;
import org.dinky.data.result.APIJobResult;
......@@ -47,6 +49,7 @@ import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
......@@ -68,52 +71,72 @@ public class APIController {
private final JobInstanceService jobInstanceService;
@GetMapping("/submitTask")
@ApiOperation("Submit task")
@Log(title = "Submit task", businessType = BusinessType.SUBMIT)
public Result<JobResult> submitTask(@RequestParam Integer id) {
taskService.initTenantByTaskId(id);
return Result.succeed(taskService.submitTask(id), Status.EXECUTE_SUCCESS);
}
@PostMapping("/executeSql")
@Log(title = "Execute Sql", businessType = BusinessType.EXECUTE)
@ApiOperation("Execute sql")
public Result<APIJobResult> executeSql(@RequestBody APIExecuteSqlDTO apiExecuteSqlDTO) {
return Result.succeed(apiService.executeSql(apiExecuteSqlDTO), Status.EXECUTE_SUCCESS);
}
@PostMapping("/explainSql")
@Log(title = "Explain Sql", businessType = BusinessType.EXECUTE)
@ApiOperation("Explain sql")
public Result<ExplainResult> explainSql(@RequestBody APIExplainSqlDTO apiExecuteSqlDTO) {
return Result.succeed(apiService.explainSql(apiExecuteSqlDTO), Status.EXECUTE_SUCCESS);
}
@PostMapping("/getJobPlan")
@Log(title = "Get Job Plan", businessType = BusinessType.EXECUTE)
@ApiOperation("Get job plan")
public Result<ObjectNode> getJobPlan(@RequestBody APIExplainSqlDTO apiExecuteSqlDTO) {
return Result.succeed(apiService.getJobPlan(apiExecuteSqlDTO), Status.EXECUTE_SUCCESS);
}
@PostMapping("/getStreamGraph")
@Log(title = "Get Stream Graph", businessType = BusinessType.EXECUTE)
@ApiOperation("Get stream graph")
public Result<ObjectNode> getStreamGraph(@RequestBody APIExplainSqlDTO apiExecuteSqlDTO) {
return Result.succeed(apiService.getStreamGraph(apiExecuteSqlDTO), Status.EXECUTE_SUCCESS);
}
@GetMapping("/getJobData")
@Log(title = "Get Job Data", businessType = BusinessType.EXECUTE)
@ApiOperation("Get job data")
public Result<SelectResult> getJobData(@RequestParam String jobId) {
return Result.succeed(studioService.getJobData(jobId));
}
@PostMapping("/cancel")
@Log(title = "Cancel Flink Job", businessType = BusinessType.TRIGGER)
@ApiOperation("Cancel Flink Job")
public Result<Boolean> cancel(@RequestBody APICancelDTO apiCancelDTO) {
return Result.succeed(apiService.cancel(apiCancelDTO), Status.EXECUTE_SUCCESS);
}
@PostMapping("/savepoint")
@Log(title = "Savepoint trigger", businessType = BusinessType.TRIGGER)
@ApiOperation("Savepoint trigger")
public Result<SavePointResult> savepoint(@RequestBody APISavePointDTO apiSavePointDTO) {
return Result.succeed(apiService.savepoint(apiSavePointDTO), Status.EXECUTE_SUCCESS);
}
@PostMapping("/executeJar")
@Log(title = "Execute Jar", businessType = BusinessType.EXECUTE)
@ApiOperation("Execute jar")
public Result<APIJobResult> executeJar(@RequestBody APIExecuteJarDTO apiExecuteJarDTO) {
return Result.succeed(apiService.executeJar(apiExecuteJarDTO), Status.EXECUTE_SUCCESS);
}
@PostMapping("/savepointTask")
@Log(title = "Savepoint task", businessType = BusinessType.TRIGGER)
@ApiOperation("Savepoint task")
public Result<Boolean> savepointTask(@RequestBody APISavePointTaskDTO apiSavePointTaskDTO) {
return Result.succeed(
taskService.savepointTask(
......@@ -123,6 +146,8 @@ public class APIController {
/** 重启任务 */
@GetMapping("/restartTask")
@ApiOperation("Restart task")
@Log(title = "Restart task", businessType = BusinessType.EXECUTE)
public Result<JobResult> restartTask(@RequestParam Integer id) {
taskService.initTenantByTaskId(id);
return Result.succeed(taskService.restartTask(id, null), Status.RESTART_SUCCESS);
......@@ -130,6 +155,8 @@ public class APIController {
/** 选择保存点重启任务 */
@GetMapping("/selectSavePointRestartTask")
@ApiOperation("Select save point restart task")
@Log(title = "Select save point restart task", businessType = BusinessType.EXECUTE)
public Result<JobResult> restartTask(
@RequestParam Integer id, @RequestParam String savePointPath) {
taskService.initTenantByTaskId(id);
......@@ -138,6 +165,8 @@ public class APIController {
/** 上线任务 */
@GetMapping("/onLineTask")
@ApiOperation("On line task")
@Log(title = "On line task", businessType = BusinessType.EXECUTE)
public Result<JobResult> onLineTask(@RequestParam Integer id) {
taskService.initTenantByTaskId(id);
return taskService.onLineTask(id);
......@@ -145,6 +174,8 @@ public class APIController {
/** 下线任务 */
@GetMapping("/offLineTask")
@ApiOperation("Off line task")
@Log(title = "Off line task", businessType = BusinessType.EXECUTE)
public Result<Void> offLineTask(@RequestParam Integer id) {
taskService.initTenantByTaskId(id);
return taskService.offLineTask(id, null);
......@@ -152,6 +183,8 @@ public class APIController {
/** 重新上线任务 */
@GetMapping("/reOnLineTask")
@ApiOperation("Re on line task")
@Log(title = "Re on line task", businessType = BusinessType.EXECUTE)
public Result<JobResult> reOnLineTask(@RequestParam Integer id) {
taskService.initTenantByTaskId(id);
return taskService.reOnLineTask(id, null);
......@@ -159,6 +192,8 @@ public class APIController {
/** 选择保存点重新上线任务 */
@GetMapping("/selectSavePointReOnLineTask")
@ApiOperation("Select save point re on line task")
@Log(title = "Select save point re on line task", businessType = BusinessType.EXECUTE)
public Result<JobResult> selectSavePointReOnLineTask(
@RequestParam Integer id, @RequestParam String savePointPath) {
taskService.initTenantByTaskId(id);
......@@ -167,6 +202,8 @@ public class APIController {
/** 获取Job实例的信息 */
@GetMapping("/getJobInstance")
@Log(title = "Get Job Instance", businessType = BusinessType.QUERY)
@ApiOperation("Get job instance")
public Result<JobInstance> getJobInstance(@RequestParam Integer id) {
jobInstanceService.initTenantByJobInstanceId(id);
return Result.succeed(jobInstanceService.getById(id));
......@@ -174,6 +211,8 @@ public class APIController {
/** 通过 taskId 获取 Task 对应的 Job 实例的信息 */
@GetMapping("/getJobInstanceByTaskId")
@Log(title = "Get Job Instance By Task Id", businessType = BusinessType.QUERY)
@ApiOperation("Get job instance by task id")
public Result<JobInstance> getJobInstanceByTaskId(@RequestParam Integer id) {
taskService.initTenantByTaskId(id);
return Result.succeed(jobInstanceService.getJobInstanceByTaskId(id));
......
......@@ -37,6 +37,7 @@ import org.springframework.web.bind.annotation.RestController;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
......@@ -60,6 +61,7 @@ public class AdminController {
* @return {@link Result}{@link UserDTO} obtain the user's UserDTO
*/
@PostMapping("/login")
@ApiOperation(value = "Login", notes = "Login")
public Result<UserDTO> login(@RequestBody LoginDTO loginDTO) {
return userService.loginUser(loginDTO);
}
......@@ -70,6 +72,7 @@ public class AdminController {
* @return {@link Result}{@link Void} user loginout status information
*/
@DeleteMapping("/outLogin")
@ApiOperation(value = "LogOut", notes = "LogOut")
public Result<Void> outLogin() {
userService.outLogin();
return Result.succeed(I18nMsgUtils.getMsg(Status.SIGN_OUT_SUCCESS));
......@@ -81,6 +84,7 @@ public class AdminController {
* @return {@link Result}{@link UserDTO} obtain the current user's UserDTO
*/
@GetMapping("/current")
@ApiOperation(value = "Current User Info", notes = "Current User Info")
public Result<UserDTO> getCurrentUserInfo() {
return userService.queryCurrentUserInfo();
}
......@@ -92,6 +96,7 @@ public class AdminController {
* @return {@link Result}{@link Tenant} the specified tenant
*/
@PostMapping("/chooseTenant")
@ApiOperation(value = "Choose Tenant To Login", notes = "Choose Tenant To Login")
public Result<Tenant> switchingTenant(@RequestParam("tenantId") Integer tenantId) {
return userService.chooseTenant(tenantId);
}
......@@ -102,6 +107,7 @@ public class AdminController {
* @return {@link Result}{@link SaTokenInfo}
*/
@GetMapping("/tokenInfo")
@ApiOperation(value = "Query Current User Token Info", notes = "Query Current User Token Info")
public Result<SaTokenInfo> getTokenInfo() {
return Result.succeed(StpUtil.getTokenInfo());
}
......
......@@ -19,6 +19,8 @@
package org.dinky.controller;
import org.dinky.annotation.Log;
import org.dinky.data.enums.BusinessType;
import org.dinky.data.enums.Status;
import org.dinky.data.model.AlertGroup;
import org.dinky.data.model.AlertHistory;
......@@ -41,6 +43,7 @@ import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.JsonNode;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
......@@ -62,6 +65,8 @@ public class AlertGroupController {
* @throws Exception {@link Exception}
*/
@PutMapping
@Log(title = "INSERT OR UPDATE AlertGroup ", businessType = BusinessType.INSERT_OR_UPDATE)
@ApiOperation("INSERT OR UPDATE AlertGroup")
public Result<Void> saveOrUpdate(@RequestBody AlertGroup alertGroup) throws Exception {
if (alertGroupService.saveOrUpdate(alertGroup)) {
return Result.succeed(Status.SAVE_SUCCESS);
......@@ -77,6 +82,8 @@ public class AlertGroupController {
* @return {@link ProTableResult} with {@link AlertGroup}
*/
@PostMapping
@Log(title = "Query AlertGroup List", businessType = BusinessType.QUERY)
@ApiOperation("Query AlertGroup List")
public ProTableResult<AlertGroup> listAlertGroups(@RequestBody JsonNode para) {
return alertGroupService.selectForProTable(para);
}
......@@ -114,6 +121,8 @@ public class AlertGroupController {
* @return {@link Result} with {@link List} of {@link AlertGroup}
*/
@GetMapping("/listEnabledAll")
@ApiOperation("Query AlertGroup List Of Enable")
@Log(title = "Query AlertGroup List Of Enable", businessType = BusinessType.QUERY)
public Result<List<AlertGroup>> listEnabledAll() {
return Result.succeed(alertGroupService.listEnabledAll());
}
......@@ -124,6 +133,8 @@ public class AlertGroupController {
* @return {@link Result} with {@link List} of {@link AlertGroup}
*/
@PutMapping("/enable")
@ApiOperation("Update AlertGroup Status")
@Log(title = "Update AlertGroup Status", businessType = BusinessType.UPDATE)
public Result<List<AlertGroup>> enable(@RequestParam("id") Integer id) {
if (alertGroupService.enable(id)) {
return Result.succeed(Status.MODIFY_SUCCESS);
......@@ -139,6 +150,8 @@ public class AlertGroupController {
* @return {@link Result} of {@link Void}
*/
@DeleteMapping("/delete")
@ApiOperation("Delete AlertGroup By Id")
@Log(title = "Delete AlertGroup By Id", businessType = BusinessType.DELETE)
public Result<Void> deleteGroupById(@RequestParam("id") Integer id) {
if (alertGroupService.deleteGroupById(id)) {
return Result.succeed(Status.DELETE_SUCCESS);
......@@ -154,6 +167,8 @@ public class AlertGroupController {
* @return {@link ProTableResult} with {@link AlertHistory}
*/
@PostMapping("/history")
@Log(title = "Query AlertHistory List", businessType = BusinessType.QUERY)
@ApiOperation("Query AlertHistory List")
public ProTableResult<AlertHistory> listAlertHistory(@RequestBody JsonNode para) {
return alertHistoryService.selectForProTable(para);
}
......
......@@ -19,6 +19,8 @@
package org.dinky.controller;
import org.dinky.annotation.Log;
import org.dinky.data.enums.BusinessType;
import org.dinky.data.model.AlertHistory;
import org.dinky.data.result.ProTableResult;
import org.dinky.service.AlertHistoryService;
......@@ -30,6 +32,7 @@ import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.JsonNode;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
......@@ -48,6 +51,8 @@ public class AlertHistoryController {
/** 动态查询列表 */
@PostMapping
@ApiOperation("Query Alert History")
@Log(title = "Query Alert History", businessType = BusinessType.QUERY)
public ProTableResult<AlertHistory> listAlertHistory(@RequestBody JsonNode para) {
return alertHistoryService.selectForProTable(para);
}
......
......@@ -21,6 +21,8 @@ package org.dinky.controller;
import org.dinky.alert.AlertPool;
import org.dinky.alert.AlertResult;
import org.dinky.annotation.Log;
import org.dinky.data.enums.BusinessType;
import org.dinky.data.enums.Status;
import org.dinky.data.model.AlertInstance;
import org.dinky.data.result.ProTableResult;
......@@ -40,6 +42,7 @@ import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.JsonNode;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
......@@ -60,6 +63,8 @@ public class AlertInstanceController {
* @throws Exception {@link Exception}
*/
@PutMapping
@Log(title = "INSERT OR UPDATE AlertInstance", businessType = BusinessType.INSERT_OR_UPDATE)
@ApiOperation("INSERT OR UPDATE AlertInstance")
public Result<Void> saveOrUpdate(@RequestBody AlertInstance alertInstance) throws Exception {
if (alertInstanceService.saveOrUpdate(alertInstance)) {
AlertPool.remove(alertInstance.getName());
......@@ -76,6 +81,8 @@ public class AlertInstanceController {
* @return {@link ProTableResult} of {@link AlertInstance}
*/
@PostMapping
@Log(title = "Query AlertInstance List", businessType = BusinessType.QUERY)
@ApiOperation("Query AlertInstance List")
public ProTableResult<AlertInstance> listAlertInstances(@RequestBody JsonNode para) {
return alertInstanceService.selectForProTable(para);
}
......@@ -100,7 +107,9 @@ public class AlertInstanceController {
* @return {@link Result} of {@link Void}
*/
@DeleteMapping("/delete")
public Result<Void> deleteInstanceById(@RequestParam("id") Integer id) {
@Log(title = "Delete AlertInstance By Id", businessType = BusinessType.DELETE)
@ApiOperation("Delete AlertInstance By Id")
public Result<AlertInstance> deleteInstanceById(@RequestParam("id") Integer id) {
if (alertInstanceService.deleteAlertInstance(id)) {
return Result.succeed(Status.DELETE_SUCCESS);
} else {
......@@ -115,7 +124,9 @@ public class AlertInstanceController {
* @return {@link Result} of {@link Void}
*/
@PutMapping("/enable")
public Result<Void> enable(@RequestParam("id") Integer id) {
@Log(title = "Update AlertInstance Status", businessType = BusinessType.UPDATE)
@ApiOperation("Update AlertInstance Status")
public Result<AlertInstance> enable(@RequestParam("id") Integer id) {
if (alertInstanceService.enable(id)) {
return Result.succeed(Status.MODIFY_SUCCESS);
} else {
......@@ -129,6 +140,8 @@ public class AlertInstanceController {
* @return {@link Result} of {@link AlertInstance}
*/
@GetMapping("/listEnabledAll")
@Log(title = "Query AlertInstance List Of Enable", businessType = BusinessType.QUERY)
@ApiOperation("Query AlertInstance List Of Enable")
public Result<List<AlertInstance>> listEnabledAll() {
return Result.succeed(alertInstanceService.listEnabledAll());
}
......@@ -140,6 +153,8 @@ public class AlertInstanceController {
* @return {@link Result} of {@link Void}
*/
@PostMapping("/sendTest")
@Log(title = "Test Send To AlertInstance", businessType = BusinessType.TEST)
@ApiOperation("Test Send To AlertInstance")
public Result<Void> sendTest(@RequestBody AlertInstance alertInstance) {
AlertResult alertResult = alertInstanceService.testAlert(alertInstance);
if (alertResult.getSuccess()) {
......
......@@ -19,7 +19,9 @@
package org.dinky.controller;
import org.dinky.annotation.Log;
import org.dinky.data.dto.CatalogueTaskDTO;
import org.dinky.data.enums.BusinessType;
import org.dinky.data.enums.Status;
import org.dinky.data.model.Catalogue;
import org.dinky.data.result.Result;
......@@ -43,6 +45,7 @@ import org.springframework.web.multipart.MultipartFile;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ZipUtil;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
......@@ -60,6 +63,8 @@ public class CatalogueController {
private final CatalogueService catalogueService;
@PostMapping("/upload/{id}")
@Log(title = "Upload Catalogue", businessType = BusinessType.UPLOAD)
@ApiOperation("Upload Zip Package And Create Catalogue")
public Result<String> upload(MultipartFile file, @PathVariable Integer id) {
// 获取上传的路径
String filePath = PathConstant.WORK_DIR;
......@@ -161,6 +166,8 @@ public class CatalogueController {
/** 新增或者更新 */
@PutMapping
@Log(title = "Insert Or Update Catalogue", businessType = BusinessType.INSERT_OR_UPDATE)
@ApiOperation("Insert Or Update Catalogue")
public Result<Void> saveOrUpdate(@RequestBody Catalogue catalogue) throws Exception {
if (catalogueService.saveOrUpdate(catalogue)) {
return Result.succeed(Status.SAVE_SUCCESS);
......@@ -171,6 +178,8 @@ public class CatalogueController {
/** 获取指定ID的信息 */
@PostMapping("/getOneById")
@Log(title = "Get Catalogue Info By Id", businessType = BusinessType.QUERY)
@ApiOperation("Get Catalogue Info By Id")
public Result<Catalogue> getOneById(@RequestBody Catalogue catalogue) throws Exception {
catalogue = catalogueService.getById(catalogue.getId());
return Result.succeed(catalogue);
......@@ -178,6 +187,8 @@ public class CatalogueController {
/** 获取所有目录 */
@PostMapping("/getCatalogueTreeData")
@Log(title = "Get Catalogue Tree Data", businessType = BusinessType.QUERY)
@ApiOperation("Get Catalogue Tree Data")
public Result<List<Catalogue>> getCatalogueTreeData() {
List<Catalogue> catalogues = catalogueService.getAllData();
return Result.succeed(catalogues);
......@@ -185,6 +196,8 @@ public class CatalogueController {
/** 创建节点和作业 */
@PutMapping("/createTask")
@Log(title = "Create Catalogue And Task", businessType = BusinessType.INSERT_OR_UPDATE)
@ApiOperation("Create Catalogue And Task")
public Result<Catalogue> createTask(@RequestBody CatalogueTaskDTO catalogueTaskDTO) {
Catalogue catalogue = catalogueService.saveOrUpdateCatalogueAndTask(catalogueTaskDTO);
if (catalogue.getId() != null) {
......@@ -196,6 +209,8 @@ public class CatalogueController {
/** 重命名节点和作业 */
@PutMapping("/toRename")
@Log(title = "Rename Catalogue And Task", businessType = BusinessType.UPDATE)
@ApiOperation("Rename Catalogue And Task")
public Result<Void> toRename(@RequestBody Catalogue catalogue) {
if (catalogueService.toRename(catalogue)) {
return Result.succeed(Status.RENAME_SUCCESS);
......@@ -206,6 +221,8 @@ public class CatalogueController {
/** 重命名节点和作业 */
@PutMapping("/moveCatalogue")
@Log(title = "Move Catalogue", businessType = BusinessType.UPDATE)
@ApiOperation("Move Catalogue")
public Result<Boolean> moveCatalogue(@RequestBody Catalogue catalogue) {
if (catalogueService.moveCatalogue(catalogue.getId(), catalogue.getParentId())) {
return Result.succeed(true, Status.MOVE_SUCCESS);
......@@ -215,6 +232,8 @@ public class CatalogueController {
}
@PostMapping("/copyTask")
@Log(title = "Copy Task", businessType = BusinessType.INSERT_OR_UPDATE)
@ApiOperation("Copy Task")
public Result<Catalogue> copyTask(@RequestBody Catalogue catalogue) {
if (catalogueService.copyTask(catalogue)) {
return Result.succeed(Status.COPY_SUCCESS);
......
......@@ -19,7 +19,9 @@
package org.dinky.controller;
import org.dinky.annotation.Log;
import org.dinky.assertion.Asserts;
import org.dinky.data.enums.BusinessType;
import org.dinky.data.enums.Status;
import org.dinky.data.model.ClusterConfiguration;
import org.dinky.data.result.ProTableResult;
......@@ -41,6 +43,7 @@ import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.JsonNode;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
......@@ -59,6 +62,8 @@ public class ClusterConfigurationController {
/** 新增或者更新 */
@PutMapping
@Log(title = "Cluster Config Save Or Update", businessType = BusinessType.INSERT_OR_UPDATE)
@ApiOperation("Cluster Config Save Or Update")
public Result<Void> saveOrUpdate(@RequestBody ClusterConfiguration clusterConfiguration) {
Integer id = clusterConfiguration.getId();
TestResult testResult = clusterConfigurationService.testGateway(clusterConfiguration);
......@@ -72,6 +77,8 @@ public class ClusterConfigurationController {
/** 动态查询列表 */
@PostMapping
@Log(title = "Cluster Config List", businessType = BusinessType.QUERY)
@ApiOperation("Cluster Config List")
public ProTableResult<ClusterConfiguration> listClusterConfigs(@RequestBody JsonNode para) {
return clusterConfigurationService.selectForProTable(para);
}
......@@ -109,6 +116,8 @@ public class ClusterConfigurationController {
/** 获取可用的集群列表 */
@GetMapping("/listEnabledAll")
@Log(title = "Cluster Config List Enabled All", businessType = BusinessType.QUERY)
@ApiOperation("Cluster Config List Enabled All")
public Result<List<ClusterConfiguration>> listEnabledAll() {
List<ClusterConfiguration> clusters = clusterConfigurationService.listEnabledAll();
return Result.succeed(clusters);
......@@ -121,6 +130,8 @@ public class ClusterConfigurationController {
* @return {@link Result}<{@link Void}>
*/
@DeleteMapping("/delete")
@Log(title = "Cluster Config Delete by id", businessType = BusinessType.DELETE)
@ApiOperation("Cluster Config Delete by id")
public Result<Void> deleteById(@RequestParam("id") Integer id) {
boolean removeById = clusterConfigurationService.removeById(id);
if (removeById) {
......@@ -137,6 +148,8 @@ public class ClusterConfigurationController {
* @return {@link Result}<{@link Void}>
*/
@PutMapping("/enable")
@Log(title = "Update Cluster Config Status", businessType = BusinessType.UPDATE)
@ApiOperation("Update Cluster Config Status")
public Result<Void> enable(@RequestParam("id") Integer id) {
if (clusterConfigurationService.enable(id)) {
return Result.succeed(Status.MODIFY_SUCCESS);
......@@ -152,6 +165,8 @@ public class ClusterConfigurationController {
* @return {@link Result}<{@link Void}>
*/
@PostMapping("/testConnect")
@Log(title = "Test Connection", businessType = BusinessType.TEST)
@ApiOperation("Test Connection")
public Result<Void> testConnect(@RequestBody ClusterConfiguration clusterConfiguration) {
TestResult testResult = clusterConfigurationService.testGateway(clusterConfiguration);
if (testResult.isAvailable()) {
......
......@@ -19,6 +19,8 @@
package org.dinky.controller;
import org.dinky.annotation.Log;
import org.dinky.data.enums.BusinessType;
import org.dinky.data.enums.Status;
import org.dinky.data.model.Cluster;
import org.dinky.data.model.JobInstance;
......@@ -44,6 +46,7 @@ import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.JsonNode;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
......@@ -65,6 +68,8 @@ public class ClusterInstanceController {
* @throws Exception exception
*/
@PutMapping
@Log(title = "Save or update cluster instance", businessType = BusinessType.INSERT_OR_UPDATE)
@ApiOperation("Save or update cluster instance")
public Result<Void> saveOrUpdate(@RequestBody Cluster cluster) throws Exception {
cluster.setAutoRegisters(false);
Integer id = cluster.getId();
......@@ -79,6 +84,8 @@ public class ClusterInstanceController {
* @return {@link Result}<{@link Void}>
*/
@PutMapping("/enable")
@Log(title = "Update Cluster Instance Status", businessType = BusinessType.UPDATE)
@ApiOperation("Update Cluster Instance Status")
public Result<Void> enableCluster(@RequestParam Integer id) {
Boolean enabled = clusterInstanceService.enableClusterInstance(id);
if (enabled) {
......@@ -95,6 +102,8 @@ public class ClusterInstanceController {
* @return {@link Result}<{@link Void}>
*/
@DeleteMapping("/delete")
@Log(title = "Cluster Instance Delete by id", businessType = BusinessType.DELETE)
@ApiOperation("Cluster Instance Delete by id")
@Transactional(rollbackFor = Exception.class)
public Result<Void> deleteClusterInstanceById(@RequestParam Integer id) {
Boolean deleted = clusterInstanceService.deleteClusterInstanceById(id);
......@@ -112,6 +121,8 @@ public class ClusterInstanceController {
* @return {@link ProTableResult}<{@link Cluster}>
*/
@PostMapping
@Log(title = "Cluster Instance List", businessType = BusinessType.QUERY)
@ApiOperation("Cluster Instance List")
public ProTableResult<Cluster> listClusters(@RequestBody JsonNode para) {
return clusterInstanceService.selectForProTable(para);
}
......@@ -163,6 +174,8 @@ public class ClusterInstanceController {
* @return {@link Result}<{@link List}<{@link Cluster}>>
*/
@GetMapping("/listEnabledAll")
@Log(title = "Get all enable cluster instances", businessType = BusinessType.QUERY)
@ApiOperation("Get all enable cluster instances")
public Result<List<Cluster>> listEnabledAll() {
List<Cluster> clusters = clusterInstanceService.listEnabledAll();
return Result.succeed(clusters);
......@@ -186,6 +199,8 @@ public class ClusterInstanceController {
* @return {@link Result}<{@link Void}>
*/
@PostMapping("/heartbeats")
@Log(title = "Cluster Instance Heartbeat", businessType = BusinessType.UPDATE)
@ApiOperation("Cluster Instance Heartbeat")
public Result<Void> heartbeat() {
List<Cluster> clusters = clusterInstanceService.list();
for (Cluster cluster : clusters) {
......@@ -200,6 +215,8 @@ public class ClusterInstanceController {
* @return {@link Result}<{@link Integer}>
*/
@DeleteMapping("/recycle")
@Log(title = "Cluster Instance Recycle", businessType = BusinessType.DELETE)
@ApiOperation("Cluster Instance Recycle")
@Transactional(rollbackFor = Exception.class)
public Result<Integer> recycleCluster() {
return Result.succeed(
......@@ -213,6 +230,8 @@ public class ClusterInstanceController {
* @return {@link Result}<{@link Void}>
*/
@GetMapping("/killCluster")
@Log(title = "Cluster Instance Kill", businessType = BusinessType.UPDATE)
@ApiOperation("Cluster Instance Kill")
public Result<Void> killCluster(@RequestParam("id") Integer id) {
clusterInstanceService.killCluster(id);
return Result.succeed("Kill Cluster Succeed.");
......@@ -249,6 +268,8 @@ public class ClusterInstanceController {
}
@PutMapping("/deploySessionClusterInstance")
@Log(title = "Deploy Session Cluster Instance", businessType = BusinessType.INSERT_OR_UPDATE)
@ApiOperation("Deploy Session Cluster Instance")
public Result<Cluster> deploySessionClusterInstance(@RequestParam("id") Integer id) {
return Result.succeed(
clusterInstanceService.deploySessionCluster(id), Status.CLUSTER_INSTANCE_DEPLOY);
......
......@@ -19,8 +19,10 @@
package org.dinky.controller;
import org.dinky.annotation.Log;
import org.dinky.assertion.Asserts;
import org.dinky.data.constant.CommonConstant;
import org.dinky.data.enums.BusinessType;
import org.dinky.data.enums.Status;
import org.dinky.data.model.Column;
import org.dinky.data.model.DataBase;
......@@ -49,6 +51,7 @@ import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.JsonNode;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
......@@ -72,6 +75,8 @@ public class DataBaseController {
* @return {@link Result}< {@link Void}>
*/
@PutMapping
@Log(title = "DataBase Save Or Update", businessType = BusinessType.INSERT_OR_UPDATE)
@ApiOperation("DataBase Save Or Update")
public Result<Void> saveOrUpdate(@RequestBody DataBase database) {
if (databaseService.saveOrUpdateDataBase(database)) {
DriverPool.remove(database.getName());
......@@ -88,6 +93,8 @@ public class DataBaseController {
* @return {@link ProTableResult}< {@link DataBase}>
*/
@PostMapping
@Log(title = "DataBase Get All", businessType = BusinessType.QUERY)
@ApiOperation("DataBase Get All")
public ProTableResult<DataBase> listDataBases(@RequestBody JsonNode para) {
return databaseService.selectForProTable(para);
}
......@@ -127,6 +134,8 @@ public class DataBaseController {
* @return {@link Result}< {@link Void}>
*/
@DeleteMapping("/delete")
@Log(title = "DataBase Delete By Id", businessType = BusinessType.DELETE)
@ApiOperation("DataBase Delete By Id")
public Result<Void> deleteById(@RequestParam Integer id) {
if (databaseService.removeById(id)) {
return Result.succeed(Status.DELETE_SUCCESS);
......@@ -141,6 +150,8 @@ public class DataBaseController {
* @return {@link Result}< {@link Void}>
*/
@PutMapping("/enable")
@Log(title = "DataBase Enable Or Disable By Id", businessType = BusinessType.UPDATE)
@ApiOperation("DataBase Enable Or Disable By Id")
public Result<Void> enable(@RequestParam Integer id) {
if (databaseService.enable(id)) {
return Result.succeed(Status.MODIFY_SUCCESS);
......@@ -154,6 +165,8 @@ public class DataBaseController {
* @return {@link Result}< {@link List}< {@link DataBase}>>
*/
@GetMapping("/listEnabledAll")
@Log(title = "Get All DataBase Enabled", businessType = BusinessType.QUERY)
@ApiOperation("Get All DataBase Enabled")
public Result<List<DataBase>> listEnabledAll() {
List<DataBase> dataBases = databaseService.listEnabledAll();
return Result.succeed(dataBases);
......@@ -166,6 +179,8 @@ public class DataBaseController {
* @return {@link Result}< {@link Void}>
*/
@PostMapping("/testConnect")
@Log(title = "DataBase Test Connect", businessType = BusinessType.TEST)
@ApiOperation("DataBase Test Connect")
public Result<Void> testConnect(@RequestBody DataBase database) {
String msg = databaseService.testConnect(database);
boolean isHealthy = Asserts.isEquals(CommonConstant.HEALTHY, msg);
......@@ -228,6 +243,8 @@ public class DataBaseController {
* @return {@link Result}< {@link Void}>
*/
@PutMapping("/checkHeartBeatByDataSourceId")
@Log(title = "DataBase Check Heart Beat By Id", businessType = BusinessType.TEST)
@ApiOperation("DataBase Check Heart Beat By Id")
public Result<Void> checkHeartBeatByDataSourceId(@RequestParam Integer id) {
DataBase dataBase = databaseService.getById(id);
Asserts.checkNotNull(dataBase, Status.DATASOURCE_NOT_EXIST.getMsg());
......@@ -252,6 +269,8 @@ public class DataBaseController {
*/
@Cacheable(cacheNames = "metadata_schema", key = "#id")
@GetMapping("/getSchemasAndTables")
@Log(title = "Get All Schemas And Tables", businessType = BusinessType.QUERY)
@ApiOperation("Get All Schemas And Tables")
public Result<List<Schema>> getSchemasAndTables(@RequestParam Integer id) {
return Result.succeed(databaseService.getSchemasAndTables(id));
}
......@@ -264,6 +283,8 @@ public class DataBaseController {
*/
@CacheEvict(cacheNames = "metadata_schema", key = "#id")
@GetMapping("/unCacheSchemasAndTables")
@Log(title = "Clear Cache Of Schemas And Tables", businessType = BusinessType.DELETE)
@ApiOperation("Clear Cache Of Schemas And Tables")
public Result<String> unCacheSchemasAndTables(@RequestParam Integer id) {
return Result.succeed(Status.DATASOURCE_CLEAR_CACHE_SUCCESS);
}
......@@ -277,6 +298,8 @@ public class DataBaseController {
* @return {@link Result}< {@link List}< {@link Column}>>
*/
@GetMapping("/listColumns")
@Log(title = "Get Columns Of Table", businessType = BusinessType.QUERY)
@ApiOperation("Get Columns Of Table")
public Result<List<Column>> listColumns(
@RequestParam Integer id,
@RequestParam String schemaName,
......@@ -291,6 +314,8 @@ public class DataBaseController {
* @return {@link Result}< {@link JdbcSelectResult}>
*/
@PostMapping("/queryData")
@Log(title = "Query Data Of Table", businessType = BusinessType.QUERY)
@ApiOperation("Query Data Of Table")
public Result<JdbcSelectResult> queryData(@RequestBody QueryData queryData) {
JdbcSelectResult jdbcSelectResult = databaseService.queryData(queryData);
if (jdbcSelectResult.isSuccess()) {
......@@ -307,6 +332,8 @@ public class DataBaseController {
* @return {@link Result}< {@link JdbcSelectResult}>
*/
@PostMapping("/execSql")
@Log(title = "Exec Sql", businessType = BusinessType.EXECUTE)
@ApiOperation("Exec Sql")
public Result<JdbcSelectResult> execSql(@RequestBody QueryData queryData) {
JdbcSelectResult jdbcSelectResult = databaseService.execSql(queryData);
if (jdbcSelectResult.isSuccess()) {
......@@ -325,6 +352,8 @@ public class DataBaseController {
* @return {@link Result}< {@link SqlGeneration}>
*/
@GetMapping("/getSqlGeneration")
@Log(title = "Get Sql Generation", businessType = BusinessType.QUERY)
@ApiOperation("Get Sql Generation")
public Result<SqlGeneration> getSqlGeneration(
@RequestParam Integer id,
@RequestParam String schemaName,
......@@ -339,6 +368,8 @@ public class DataBaseController {
* @return {@link Result}< {@link Void}>
*/
@PostMapping("/copyDatabase")
@Log(title = "Copy Database", businessType = BusinessType.INSERT_OR_UPDATE)
@ApiOperation("Copy Database")
public Result<Void> copyDatabase(@RequestBody DataBase database) {
if (databaseService.copyDatabase(database)) {
return Result.succeed(Status.COPY_SUCCESS);
......
......@@ -19,6 +19,8 @@
package org.dinky.controller;
import org.dinky.annotation.Log;
import org.dinky.data.enums.BusinessType;
import org.dinky.data.enums.Status;
import org.dinky.data.model.Document;
import org.dinky.data.result.ProTableResult;
......@@ -39,6 +41,7 @@ import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.JsonNode;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
......@@ -59,6 +62,8 @@ public class DocumentController {
* @throws Exception {@link Exception}
*/
@PutMapping
@Log(title = "Document Save Or Update", businessType = BusinessType.INSERT_OR_UPDATE)
@ApiOperation("Document Save Or Update")
public Result<Void> saveOrUpdate(@RequestBody Document document) throws Exception {
if (documentService.saveOrUpdate(document)) {
return Result.succeed(Status.SAVE_SUCCESS);
......@@ -74,6 +79,8 @@ public class DocumentController {
* @return {@link ProTableResult} of {@link Document}
*/
@PostMapping
@Log(title = "Document Query List", businessType = BusinessType.QUERY)
@ApiOperation("Document Query List")
public ProTableResult<Document> listDocuments(@RequestBody JsonNode para) {
return documentService.selectForProTable(para);
}
......@@ -112,6 +119,8 @@ public class DocumentController {
* @return {@link Result} of {@link Void}
*/
@DeleteMapping("/delete")
@Log(title = "Document Delete By id", businessType = BusinessType.DELETE)
@ApiOperation("Document Delete By id")
public Result<Void> deleteById(@RequestParam Integer id) {
if (documentService.removeById(id)) {
return Result.succeed(Status.DELETE_SUCCESS);
......@@ -127,6 +136,8 @@ public class DocumentController {
* @return {@link Result} of {@link Void}
*/
@PutMapping("/enable")
@Log(title = "Update Document Status", businessType = BusinessType.UPDATE)
@ApiOperation("Update Document Status")
public Result<Void> enable(@RequestParam Integer id) {
if (documentService.enable(id)) {
return Result.succeed(Status.MODIFY_SUCCESS);
......@@ -143,6 +154,8 @@ public class DocumentController {
* @throws {@link Exception}
*/
@GetMapping("/getFillAllByVersion")
@Log(title = "Get Document By Version", businessType = BusinessType.QUERY)
@ApiOperation("Get Document By Version")
public Result<List<Document>> getFillAllByVersion(@RequestParam String version) {
return Result.succeed(documentService.getFillAllByVersion(version));
}
......
......@@ -19,7 +19,9 @@
package org.dinky.controller;
import org.dinky.annotation.Log;
import org.dinky.assertion.Asserts;
import org.dinky.data.enums.BusinessType;
import org.dinky.data.exception.BusException;
import org.dinky.data.model.FlinkUdfManifest;
import org.dinky.function.constant.PathConstant;
......@@ -44,6 +46,7 @@ import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.json.JSONUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
/** @since 0.7.0 */
......@@ -53,6 +56,8 @@ import lombok.extern.slf4j.Slf4j;
public class DownloadController {
@GetMapping("downloadDepJar/{taskId}")
@Log(title = "Download UDF Jar", businessType = BusinessType.DOWNLOAD)
@ApiOperation("Download UDF Jar")
public void downloadJavaUDF(@PathVariable Integer taskId, HttpServletResponse resp) {
if (Asserts.isNull(taskId)) {
throw new BusException("task id can not null!");
......@@ -108,6 +113,8 @@ public class DownloadController {
* @param resp resp
*/
@GetMapping("downloadAppJar/{version}")
@Log(title = "Download App Jar", businessType = BusinessType.DOWNLOAD)
@ApiOperation("Download App Jar")
public void downloadAppJar(@PathVariable String version, HttpServletResponse resp) {
List<File> files =
FileUtil.loopFiles(
......
......@@ -19,7 +19,9 @@
package org.dinky.controller;
import org.dinky.annotation.Log;
import org.dinky.data.constant.UploadFileConstant;
import org.dinky.data.enums.BusinessType;
import org.dinky.data.result.Result;
import org.dinky.service.FileUploadService;
......@@ -32,6 +34,7 @@ import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
......@@ -54,6 +57,8 @@ public class FileUploadController {
* @return {@link Result}
*/
@PostMapping
@Log(title = "upload file", businessType = BusinessType.UPLOAD)
@ApiOperation("upload file")
public Result<Void> upload(
@RequestPart("files") MultipartFile[] files,
@RequestParam(value = "dir", defaultValue = "", required = false) String dir,
......@@ -83,6 +88,8 @@ public class FileUploadController {
* @return {@link Result}
*/
@PostMapping(value = "hdfs")
@Log(title = "upload hdfs file", businessType = BusinessType.UPLOAD)
@ApiOperation("upload hdfs file")
public Result<Void> uploadHdfs(
@RequestPart("files") MultipartFile[] files,
@RequestParam(value = "dir", defaultValue = "", required = false) String dir,
......
......@@ -19,6 +19,8 @@
package org.dinky.controller;
import org.dinky.annotation.Log;
import org.dinky.data.enums.BusinessType;
import org.dinky.data.enums.Status;
import org.dinky.data.model.FragmentVariable;
import org.dinky.data.result.ProTableResult;
......@@ -38,6 +40,7 @@ import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.JsonNode;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
......@@ -57,6 +60,8 @@ public class FragmentVariableController {
* @return {@link Result} of {@link Void}
*/
@PutMapping
@Log(title = "FragmentVariable Save Or Update", businessType = BusinessType.INSERT_OR_UPDATE)
@ApiOperation("FragmentVariable Save Or Update")
public Result<Void> saveOrUpdate(@RequestBody FragmentVariable fragmentVariable)
throws Exception {
if (fragmentVariableService.saveOrUpdate(fragmentVariable)) {
......@@ -73,6 +78,8 @@ public class FragmentVariableController {
* @return {@link ProTableResult} of {@link FragmentVariable}
*/
@PostMapping
@Log(title = "FragmentVariable List", businessType = BusinessType.QUERY)
@ApiOperation("FragmentVariable List")
public ProTableResult<FragmentVariable> listFragmentVariable(@RequestBody JsonNode para) {
return fragmentVariableService.selectForProTable(para);
}
......@@ -84,6 +91,8 @@ public class FragmentVariableController {
* @return {@link Result} of {@link Void}
*/
@DeleteMapping("/delete")
@Log(title = "FragmentVariable Delete", businessType = BusinessType.DELETE)
@ApiOperation("FragmentVariable Delete")
public Result<Void> deleteById(@RequestParam Integer id) {
if (fragmentVariableService.removeById(id)) {
return Result.succeed(Status.DELETE_SUCCESS);
......@@ -99,6 +108,8 @@ public class FragmentVariableController {
* @return {@link Result} of {@link Void}
*/
@PutMapping("/enable")
@Log(title = "Update FragmentVariable Status", businessType = BusinessType.UPDATE)
@ApiOperation("Update FragmentVariable Status")
public Result<Void> enable(@RequestParam Integer id) {
if (fragmentVariableService.enable(id)) {
return Result.succeed(Status.MODIFY_SUCCESS);
......
......@@ -19,9 +19,11 @@
package org.dinky.controller;
import org.dinky.annotation.Log;
import org.dinky.data.annotation.PublicInterface;
import org.dinky.data.dto.GitProjectDTO;
import org.dinky.data.dto.TreeNodeDTO;
import org.dinky.data.enums.BusinessType;
import org.dinky.data.enums.Status;
import org.dinky.data.model.GitProject;
import org.dinky.data.params.GitProjectSortJarParams;
......@@ -55,6 +57,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Dict;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
/**
......@@ -74,6 +77,8 @@ public class GitController {
* @return {@link Result} of {@link Void}
*/
@PutMapping("/saveOrUpdate")
@Log(title = "GitProject Save Or Update", businessType = BusinessType.INSERT_OR_UPDATE)
@ApiOperation("GitProject Save Or Update")
public Result<Void> saveOrUpdate(@Validated @RequestBody GitProjectDTO gitProject) {
gitProjectService.saveOrUpdate(gitProject);
GitRepository gitRepository =
......@@ -89,6 +94,8 @@ public class GitController {
* @return {@link Result}<{@link Void}>
*/
@PostMapping("/dragendSortProject")
@Log(title = "GitProject Sort", businessType = BusinessType.UPDATE)
@ApiOperation("GitProject Sort")
public Result<Void> dragendSortProject(@RequestBody Map sortList) {
if (sortList == null) {
return Result.failed(Status.GIT_PROJECT_NOT_FOUND);
......@@ -104,6 +111,8 @@ public class GitController {
* @return {@link Result}<{@link Void}>
*/
@PostMapping("/dragendSortJar")
@Log(title = "GitProject Jar Sort", businessType = BusinessType.UPDATE)
@ApiOperation("GitProject Jar Sort")
public Result<Void> dragendSortJar(
@RequestBody GitProjectSortJarParams gitProjectSortJarParams) {
GitProject gitProjectServiceById =
......@@ -126,6 +135,8 @@ public class GitController {
* @return {@link Result} of {@link List}
*/
@PostMapping("/getBranchList")
@ApiOperation("GitProject Get Branch List")
@Log(title = "GitProject Get Branch List", businessType = BusinessType.QUERY)
public Result<List<String>> getBranchList(@RequestBody GitProjectDTO gitProjectDTO) {
GitRepository gitRepository = new GitRepository(gitProjectDTO);
return Result.succeed(gitRepository.getBranchList());
......@@ -138,6 +149,8 @@ public class GitController {
* @return {@link Result} of {@link Void}
*/
@DeleteMapping("/deleteProject")
@Log(title = "Delete GitProject by id", businessType = BusinessType.DELETE)
@ApiOperation("Delete GitProject by id")
public Result<Void> deleteProject(@RequestParam("id") Integer id) {
gitProjectService.removeProjectAndCodeCascade(id);
return Result.succeed();
......@@ -150,6 +163,8 @@ public class GitController {
* @return {@link Result} of {@link Void}
*/
@PutMapping("/updateEnable")
@Log(title = "Enable or Disable GitProject by id", businessType = BusinessType.UPDATE)
@ApiOperation("Enable or Disable GitProject by id")
public Result<Void> updateEnable(@RequestParam("id") Integer id) {
gitProjectService.updateState(id);
return Result.succeed();
......@@ -162,6 +177,8 @@ public class GitController {
* @return {@link ProTableResult} of {@link GitProject}
*/
@PostMapping("/getProjectList")
@ApiOperation("Get GitProject List")
@Log(title = "Get GitProject List", businessType = BusinessType.QUERY)
public ProTableResult<GitProject> getAllProject(@RequestBody JsonNode params) {
return gitProjectService.selectForProTable(params);
}
......@@ -173,6 +190,8 @@ public class GitController {
* @return {@link Result} of {@link GitProject}
*/
@PostMapping("/getOneDetails")
@ApiOperation("Get GitProject Details by id")
@Log(title = "Get GitProject Details by id", businessType = BusinessType.QUERY)
public Result<GitProject> getOneDetails(@RequestParam("id") Integer id) {
return Result.succeed(gitProjectService.getById(id));
}
......@@ -211,6 +230,8 @@ public class GitController {
@GetMapping(path = "/build-step-logs", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
@CrossOrigin("*")
@PublicInterface
@Log(title = "GitProject Build Step Logs", businessType = BusinessType.QUERY)
@ApiOperation("GitProject Build Step Logs")
public SseEmitter buildStepLogs(@RequestParam("id") Integer id) {
SseEmitter emitter = new SseEmitterUTF8(TimeUnit.MINUTES.toMillis(30));
GitProject gitProject = gitProjectService.getById(id);
......@@ -233,6 +254,8 @@ public class GitController {
* @return {@link Result} of {@link Void}
*/
@GetMapping("/getProjectCode")
@ApiOperation("Get GitProject Code")
@Log(title = "Get GitProject Code", businessType = BusinessType.QUERY)
public Result<List<TreeNodeDTO>> getProjectCode(@RequestParam("id") Integer id) {
List<TreeNodeDTO> projectCode = gitProjectService.getProjectCode(id);
......
......@@ -20,16 +20,23 @@
package org.dinky.controller;
import org.dinky.data.model.LoginLog;
import org.dinky.data.model.OperateLog;
import org.dinky.data.result.ProTableResult;
import org.dinky.data.result.Result;
import org.dinky.service.LoginLogService;
import org.dinky.service.OperateLogService;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
......@@ -41,8 +48,16 @@ public class LogController {
private final LoginLogService loginLogService;
private final OperateLogService operateLogService;
@GetMapping("/loginRecord/{userId}")
public Result<List<LoginLog>> loginRecord(@PathVariable Integer userId) {
return Result.succeed(loginLogService.loginRecord(userId));
}
@PostMapping("/operateLog/{userId}")
public ProTableResult<OperateLog> operateRecord(
@RequestBody JsonNode para, @PathVariable Integer userId) {
return operateLogService.operateRecord(para, userId);
}
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.data.enums;
/** oper log business status */
public enum BusinessStatus {
SUCCESS,
FAIL,
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.data.enums;
/** 业务操作类型 */
public enum BusinessType {
/** 其它 */
OTHER,
/** 新增 */
INSERT,
/** 新增或修改 */
INSERT_OR_UPDATE,
/** 修改 */
UPDATE,
/** 提交 */
SUBMIT,
/** 执行 */
EXECUTE,
/** 触发 */
TRIGGER,
/** query */
QUERY,
/** test */
TEST,
/** 删除 */
DELETE,
/** 授权 */
GRANT,
/** 导出 */
EXPORT,
/** 导入 */
IMPORT,
/** 上传 */
UPLOAD,
/** 下载 */
DOWNLOAD,
}
......@@ -21,6 +21,7 @@ package org.dinky.data.model;
import org.dinky.mybatis.annotation.Save;
import java.io.Serializable;
import java.time.LocalDateTime;
import javax.validation.constraints.NotNull;
......@@ -39,8 +40,9 @@ import lombok.Data;
@Data
@TableName("dinky_sys_login_log")
public class LoginLog {
public class LoginLog implements Serializable {
private static final long serialVersionUID = 1L;
/** 主键ID */
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
......
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.data.model;
import java.io.Serializable;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
@Data
@TableName("dinky_sys_operate_log")
public class OperateLog implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/** 操作模块 */
private String moduleName;
private Integer businessType;
/** 请求方法 */
private String method;
/** 请求方式 */
private String requestMethod;
private String operateName;
private Integer operateUserId;
/** 请求url */
private String operateUrl;
/** 操作地址 */
private String operateIp;
/** 操作地点 */
private String operateLocation;
/** 请求参数 */
private String operateParam;
/** 返回参数 */
private String jsonResult;
/** 操作状态(0正常 1异常) */
private Integer status;
/** 错误消息 */
private String errorMsg;
/** 操作时间 */
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime operateTime;
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.mapper;
import org.dinky.data.model.OperateLog;
import org.dinky.mybatis.mapper.SuperMapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface OperateLogMapper extends SuperMapper<OperateLog> {}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.service;
import org.dinky.data.model.OperateLog;
import org.dinky.data.result.ProTableResult;
import org.dinky.mybatis.service.ISuperService;
import com.fasterxml.jackson.databind.JsonNode;
public interface OperateLogService extends ISuperService<OperateLog> {
void saveLog(OperateLog operateLog);
ProTableResult<OperateLog> operateRecord(JsonNode para, Integer userId);
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.service.impl;
import org.dinky.data.model.OperateLog;
import org.dinky.data.result.ProTableResult;
import org.dinky.mapper.OperateLogMapper;
import org.dinky.mybatis.service.impl.SuperServiceImpl;
import org.dinky.service.OperateLogService;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.databind.JsonNode;
@Service
public class OperateLogServiceImpl extends SuperServiceImpl<OperateLogMapper, OperateLog>
implements OperateLogService {
/** @param operateLog */
@Override
public void saveLog(OperateLog operateLog) {
getBaseMapper().insert(operateLog);
}
@Override
public ProTableResult<OperateLog> operateRecord(JsonNode para, Integer userId) {
Map<String, Object> paraMap = new HashMap<>();
paraMap.put("userId", userId);
return this.selectForProTable(para, paraMap);
}
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.utils;
import org.apache.commons.lang3.StringUtils;
import cn.hutool.http.HTMLFilter;
public class EscapeUtil {
public static final String RE_HTML_MARK = "(<[^<]*?>)|(<[\\s]*?/[^<]*?>)|(<[^<]*?/[\\s]*?>)";
private static final char[][] TEXT = new char[64][];
static {
for (int i = 0; i < 64; i++) {
TEXT[i] = new char[] {(char) i};
}
// special HTML characters
TEXT['\''] = "&#039;".toCharArray(); // 单引号
TEXT['"'] = "&#34;".toCharArray(); // 单引号
TEXT['&'] = "&#38;".toCharArray(); // &符
TEXT['<'] = "&#60;".toCharArray(); // 小于号
TEXT['>'] = "&#62;".toCharArray(); // 大于号
}
/**
* 转义文本中的HTML字符为安全的字符
*
* @param text 被转义的文本
* @return 转义后的文本
*/
public static String escape(String text) {
return encode(text);
}
/**
* 还原被转义的HTML特殊字符
*
* @param content 包含转义符的HTML内容
* @return 转换后的字符串
*/
public static String unescape(String content) {
return decode(content);
}
/**
* 清除所有HTML标签,但是不删除标签内的内容
*
* @param content 文本
* @return 清除标签后的文本
*/
public static String clean(String content) {
return new HTMLFilter().filter(content);
}
/**
* Escape编码
*
* @param text 被编码的文本
* @return 编码后的字符
*/
private static String encode(String text) {
int len;
if ((text == null) || ((len = text.length()) == 0)) {
return StringUtils.EMPTY;
}
StringBuilder buffer = new StringBuilder(len + (len >> 2));
char c;
for (int i = 0; i < len; i++) {
c = text.charAt(i);
if (c < 64) {
buffer.append(TEXT[c]);
} else {
buffer.append(c);
}
}
return buffer.toString();
}
/**
* Escape解码
*
* @param content 被转义的内容
* @return 解码后的字符串
*/
public static String decode(String content) {
if (StringUtils.isEmpty(content)) {
return content;
}
StringBuilder tmp = new StringBuilder(content.length());
int lastPos = 0, pos = 0;
char ch;
while (lastPos < content.length()) {
pos = content.indexOf("%", lastPos);
if (pos == lastPos) {
if (content.charAt(pos + 1) == 'u') {
ch = (char) Integer.parseInt(content.substring(pos + 2, pos + 6), 16);
tmp.append(ch);
lastPos = pos + 6;
} else {
ch = (char) Integer.parseInt(content.substring(pos + 1, pos + 3), 16);
tmp.append(ch);
lastPos = pos + 3;
}
} else {
if (pos == -1) {
tmp.append(content.substring(lastPos));
lastPos = content.length();
} else {
tmp.append(content.substring(lastPos, pos));
lastPos = pos;
}
}
}
return tmp.toString();
}
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.utils;
import org.dinky.assertion.Asserts;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.servlet.http.HttpServletRequest;
/** 获取IP方法 */
public class IpUtils {
public static String getIpAddr(HttpServletRequest request) {
if (request == null) {
return "unknown";
}
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Forwarded-For");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Real-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : EscapeUtil.clean(ip);
}
public static boolean internalIp(String ip) {
byte[] addr = textToNumericFormatV4(ip);
return internalIp(addr) || "127.0.0.1".equals(ip);
}
private static boolean internalIp(byte[] addr) {
if (Asserts.isNull(addr) || addr.length < 2) {
return true;
}
final byte b0 = addr[0];
final byte b1 = addr[1];
// 10.x.x.x/8
final byte SECTION_1 = 0x0A;
// 172.16.x.x/12
final byte SECTION_2 = (byte) 0xAC;
final byte SECTION_3 = (byte) 0x10;
final byte SECTION_4 = (byte) 0x1F;
// 192.168.x.x/16
final byte SECTION_5 = (byte) 0xC0;
final byte SECTION_6 = (byte) 0xA8;
switch (b0) {
case SECTION_1:
return true;
case SECTION_2:
if (b1 >= SECTION_3 && b1 <= SECTION_4) {
return true;
}
case SECTION_5:
switch (b1) {
case SECTION_6:
return true;
}
default:
return false;
}
}
/**
* 将IPv4地址转换成字节
*
* @param text IPv4地址
* @return byte 字节
*/
public static byte[] textToNumericFormatV4(String text) {
if (text.length() == 0) {
return null;
}
byte[] bytes = new byte[4];
String[] elements = text.split("\\.", -1);
try {
long l;
int i;
switch (elements.length) {
case 1:
l = Long.parseLong(elements[0]);
if ((l < 0L) || (l > 4294967295L)) {
return null;
}
bytes[0] = (byte) (int) (l >> 24 & 0xFF);
bytes[1] = (byte) (int) ((l & 0xFFFFFF) >> 16 & 0xFF);
bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);
bytes[3] = (byte) (int) (l & 0xFF);
break;
case 2:
l = Integer.parseInt(elements[0]);
if ((l < 0L) || (l > 255L)) {
return null;
}
bytes[0] = (byte) (int) (l & 0xFF);
l = Integer.parseInt(elements[1]);
if ((l < 0L) || (l > 16777215L)) {
return null;
}
bytes[1] = (byte) (int) (l >> 16 & 0xFF);
bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);
bytes[3] = (byte) (int) (l & 0xFF);
break;
case 3:
for (i = 0; i < 2; ++i) {
l = Integer.parseInt(elements[i]);
if ((l < 0L) || (l > 255L)) {
return null;
}
bytes[i] = (byte) (int) (l & 0xFF);
}
l = Integer.parseInt(elements[2]);
if ((l < 0L) || (l > 65535L)) {
return null;
}
bytes[2] = (byte) (int) (l >> 8 & 0xFF);
bytes[3] = (byte) (int) (l & 0xFF);
break;
case 4:
for (i = 0; i < 4; ++i) {
l = Integer.parseInt(elements[i]);
if ((l < 0L) || (l > 255L)) {
return null;
}
bytes[i] = (byte) (int) (l & 0xFF);
}
break;
default:
return null;
}
} catch (NumberFormatException e) {
return null;
}
return bytes;
}
public static String getHostIp() {
try {
return InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
}
return "127.0.0.1";
}
public static String getHostName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
}
return "UnKnown";
}
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.utils;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import cn.hutool.core.convert.Convert;
/** 客户端工具类 */
public class ServletUtils {
/** 获取String参数 */
public static String getParameter(String name) {
return getRequest().getParameter(name);
}
/** 获取String参数 */
public static String getParameter(String name, String defaultValue) {
return Convert.toStr(getRequest().getParameter(name), defaultValue);
}
/** 获取Integer参数 */
public static Integer getParameterToInt(String name) {
return Convert.toInt(getRequest().getParameter(name));
}
/** 获取Integer参数 */
public static Integer getParameterToInt(String name, Integer defaultValue) {
return Convert.toInt(getRequest().getParameter(name), defaultValue);
}
/** 获取request */
public static HttpServletRequest getRequest() {
return getRequestAttributes().getRequest();
}
/** 获取response */
public static HttpServletResponse getResponse() {
return getRequestAttributes().getResponse();
}
/** 获取session */
public static HttpSession getSession() {
return getRequest().getSession();
}
public static ServletRequestAttributes getRequestAttributes() {
RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
return (ServletRequestAttributes) attributes;
}
/**
* 将字符串渲染到客户端
*
* @param response 渲染对象
* @param string 待渲染的字符串
* @return null
*/
public static String renderString(HttpServletResponse response, String string) {
try {
response.setStatus(200);
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.getWriter().print(string);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 是否是Ajax异步请求
*
* @param request
*/
public static boolean isAjaxRequest(HttpServletRequest request) {
String accept = request.getHeader("accept");
if (accept != null && accept.indexOf("application/json") != -1) {
return true;
}
String xRequestedWith = request.getHeader("X-Requested-With");
if (xRequestedWith != null && xRequestedWith.indexOf("XMLHttpRequest") != -1) {
return true;
}
String uri = request.getRequestURI();
if (uri.endsWith(".json") || uri.endsWith(".xml")) {
return true;
}
String ajax = request.getParameter("__ajax");
// if (StringUtils.inStringIgnoreCase(ajax, "json", "xml"))
if (uri.endsWith("json") || uri.endsWith("xml")) {
return true;
}
return false;
}
}
......@@ -1706,3 +1706,27 @@ CREATE TABLE `dinky_sys_login_log` (
`is_deleted` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
-- ----------------------------
-- Table structure for dinky_sys_operate_log
-- ----------------------------
DROP TABLE IF EXISTS `dinky_sys_operate_log`;
CREATE TABLE `dinky_sys_operate_log` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT 'id',
`module_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT 'module name',
`business_type` int NULL DEFAULT 0 COMMENT 'business type',
`method` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT 'method name',
`request_method` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT 'request method',
`operate_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT 'operate name',
`operate_user_id` int NOT NULL COMMENT 'operate user id',
`operate_url` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT 'operate url',
`operate_ip` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT 'ip',
`operate_location` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT 'operate location',
`operate_param` varchar(2000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT 'request param',
`json_result` text CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT null COMMENT 'return json result',
`status` int NULL DEFAULT NULL COMMENT 'operate status',
`error_msg` text CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT 'error msg',
`operate_time` datetime(0) NULL DEFAULT NULL COMMENT 'operate time',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB;
<?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="org.dinky.mapper.OperateLogMapper">
<select id="selectForProTable" resultType="org.dinky.data.model.OperateLog">
select
a.*
from
dinky_sys_operate_log a
<where>
1=1
<if test='param.userId!=null and param.userId!=""'>
and a.operate_user_id = #{param.userId}
</if>
<if test='param.moduleName!=null and param.moduleName!=""'>
and a.module_name like "%${param.name}%"
</if>
<if test='param.method!=null and param.method!=""'>
and a.method like "%${param.name}%"
</if>
<!-- <if test='param.operateTime!=null and param.operateTime!=""'>-->
<!-- and a.operate_time <![CDATA[>=]]> str_to_date( #{operateTime},'%Y-%m-%d %H:%i:%s')-->
<!-- </if>-->
<if test='ew.sqlSegment!=null and ew.sqlSegment!="" and !ew.sqlSegment.startsWith(" ORDER BY")'>
and
</if>
<if test='ew.sqlSegment!=null and ew.sqlSegment!=""'>
${ew.sqlSegment}
</if>
</where>
</select>
</mapper>
......@@ -159,6 +159,7 @@ export default {
'global.info': 'Info',
'global.error': 'Error',
'global.result': 'Result',
'global.warning': 'Warning',
'global.success': 'Success',
'global.getdata.tips': 'Get Data',
......
......@@ -163,6 +163,19 @@ export default {
'user.login.status.msg': 'Message',
'user.login.accesstime': 'Login Time',
'user.login.ip': 'Login IP',
'user.op.time': 'Operation Time',
'user.op.type': 'Type',
'user.op.name': 'User',
'user.op.module': 'Module',
'user.op.method': 'Method',
'user.request.type': 'Type',
'user.op.params': 'Params',
'user.op.result': 'Result',
'user.op.url': 'URL',
'user.op.ip': 'IP',
'user.op.status': 'Status',
'user.op.error.msg': 'Error Message',
// -- personal info
'user.info': 'Personal Info',
'user.tenant': 'Tenant',
......
......@@ -156,6 +156,7 @@ export default {
'global.no': '否',
'global.info': '信息',
'global.result': '结果',
'global.error': '错误',
'global.warning': '警告',
'global.success': '成功',
......
......@@ -157,7 +157,19 @@ export default {
'user.login.status.code': '状态值',
'user.login.status.msg': '信息',
'user.login.accesstime': '登录时间',
'user.login.ip': '登录IP',
'user.login.ip': '登录IP',
'user.op.time': '操作时间',
'user.op.type': '业务类型',
'user.op.name': '操作人',
'user.op.module': '模块',
'user.op.method': '方法',
'user.request.type': '请求类型',
'user.op.params': '请求参数',
'user.op.result': '返回结果',
'user.op.url': '地址',
'user.op.ip': 'IP',
'user.op.status': '状态',
'user.op.error.msg': '错误信息',
// -- personal info
'user.info': '个人信息',
......
......@@ -19,10 +19,11 @@
import React, {useCallback, useEffect, useState} from "react";
import {queryDataByParams} from "@/services/BusinessCrud";
import {BackTop, Button, Card, Spin, Timeline} from "antd";
import {Button, Card, Spin, Timeline} from "antd";
import {LoginLog} from "@/types/User/data";
import {l} from "@/utils/intl";
import {renderTimeLineItems} from "@/pages/Other/PersonCenter/LoginLogRecord/function";
import {API_CONSTANTS} from "@/services/constants";
type LoginLogRecordProps = {
......@@ -36,7 +37,7 @@ const LoginLogRecord: React.FC<LoginLogRecordProps> = (props) => {
const queryLoginLog = useCallback(async (id: number) => {
setRefresh(true)
await queryDataByParams(`/api/log/loginRecord/${id}`).then(res => {
await queryDataByParams(`${API_CONSTANTS.LOGIN_RECORD}/${id}`).then(res => {
setLoginRecord(res)
setRefresh(false)
})
......
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import CodeShow from "@/components/CustomEditor/CodeShow";
import React from "react";
import {Modal} from "antd";
import {l} from "@/utils/intl";
import {NORMAL_MODAL_OPTIONS} from "@/services/constants";
type ResultShowProps = {
config: {
open: boolean,
data: string,
},
onCancel: () => void
}
const ResultShow: React.FC<ResultShowProps> = (props) => {
const {config: {open, data},onCancel} = props
return <>
<Modal
title={l('global.result')}
open={open}
{...NORMAL_MODAL_OPTIONS}
onCancel={onCancel}
okButtonProps={{hidden: true}}
cancelText={l('button.close')}
>
<CodeShow language={'json'} height={'60vh'} code={data} />
</Modal>
</>
}
export default ResultShow;
\ No newline at end of file
......@@ -17,8 +17,147 @@
*
*/
const OperationLogRecord = () => {
return <div>OperationLogRecord</div>;
import {ProTable} from "@ant-design/pro-components";
import {API_CONSTANTS, PROTABLE_OPTIONS_PUBLIC, STATUS_ENUM} from "@/services/constants";
import {queryList} from "@/services/api";
import React, {useState} from "react";
import {OperateLog} from "@/types/User/data";
import {ProColumns} from "@ant-design/pro-table";
import {ShowLogIcon} from "@/components/Icons/CustomIcons";
import { Button } from "antd";
import ResultShow from "@/pages/Other/PersonCenter/OperationLogRecord/ResultShow";
import {l} from "@/utils/intl";
type OperationLogRecordProps = {
userId: number
}
const OperationLogRecord: React.FC<OperationLogRecordProps> = (props) => {
const {userId} = props
const [showResult, setShowResult] = useState({
open: false,
data: ''
})
const columns: ProColumns<OperateLog>[] = [
{
title: l('user.op.time'),
dataIndex: 'operateTime',
valueType: 'dateTime',
hideInSearch: true,
},
{
title: l('user.op.name'),
dataIndex: 'operateName',
hideInSearch: true,
},
{
title: l('user.op.module'),
dataIndex: 'moduleName',
ellipsis: true,
},
{
title: l('user.op.type'),
dataIndex: 'businessType',
},
{
title: l('user.op.method'),
dataIndex: 'method',
ellipsis: true,
},
{
title: l('user.request.type'),
dataIndex: 'requestMethod',
hideInSearch: true,
},
{
title: l('user.op.params'),
render: (text, record) => {
return <Button icon={<ShowLogIcon/>} type={'link'} onClick={() => setShowResult({
open: true,
data: record.operateParam
}) }/>
},
hideInSearch: true,
},
{
title: l('user.op.result'),
dataIndex: 'jsonResult',
hideInSearch: true,
render: (text, record) => {
return <Button icon={<ShowLogIcon/>} type={'link'} onClick={() => setShowResult({
open: true,
data: record.jsonResult
}) }/>
},
},
{
title: l('user.op.url'),
dataIndex: 'operateUrl',
hideInSearch: true,
},
{
title: l('user.op.ip'),
dataIndex: 'operateIp',
hideInSearch: true,
},
{
title: l('user.op.status'),
dataIndex: 'status',
valueEnum: {
0: {text: l('global.error'), status: 'error'},
1: {text: l('global.success'), status: 'Success'},
},
hideInSearch: true,
},
{
title: l('user.op.error.msg'),
dataIndex: 'errorMsg',
render: (text, record) => {
return <>
{record.errorMsg ? <Button icon={<ShowLogIcon/>} type={'link'} onClick={() => setShowResult({
open: true,
data: record.errorMsg
}) }/>: <>-</>}
</>
},
}
];
const handleCloseResult = () => {
setShowResult(prevState => ({
...prevState,
open: false, data: ''
}))
}
return <>
<ProTable<OperateLog>
headerTitle={undefined}
ghost
options={false}
size={'small'}
{...PROTABLE_OPTIONS_PUBLIC}
pagination={{
position: ['bottomCenter'],
pageSize: 18,
hideOnSinglePage: true,
showQuickJumper: true,
}}
request={ async (params, sorter, filter: any) => await queryList(`${API_CONSTANTS.OPERATE_LOG}/${userId}`, {
...params,
sorter,
filter
})}
columns={columns}
/>
<ResultShow onCancel={handleCloseResult} config ={showResult} />
</>
}
export default OperationLogRecord
\ No newline at end of file
......@@ -121,7 +121,7 @@ const PersonCenter = () => {
{
key: 'operation',
label: <><LogSvg/>{l('user.op')}</>,
children: <><OperationLogRecord/></>,
children: <><OperationLogRecord userId={user?.id}/></>,
},
{
key: 'changePassword',
......@@ -137,13 +137,13 @@ const PersonCenter = () => {
return <Pop>
<PageContainer title={false}>
<ProCard ghost gutter={[16, 16]} hoverable loading={!loading && currentUser}>
<ProCard style={{height: '91vh', textAlign:'center', overflowY: 'auto',}} colSpan="30%" hoverable bordered>
<ProCard style={{height: '91vh', textAlign:'center', overflowY: 'auto',}} colSpan="22%" hoverable bordered>
<BaseInfo user={user} tenant={currentTenant} />
<Divider orientation={'left'} plain >{l('user.tenant')}</Divider>
<Descriptions size={'small'} column={4}>{renderTenantTagList(tenantList || [])}</Descriptions>
<Descriptions size={'small'} column={3}>{renderTenantTagList(tenantList || [])}</Descriptions>
<Divider plain ></Divider>
<Divider orientation={'left'} plain >{l('user.role')}</Divider>
<Descriptions size={'small'} column={4}>{renderRoleTagList(roleList || [])}</Descriptions>
<Descriptions size={'small'} column={3}>{renderRoleTagList(roleList || [])}</Descriptions>
</ProCard>
<ProCard
......
......@@ -27,6 +27,8 @@ export const API_CONSTANTS = {
// login path
LOGIN_PATH: "/user/login",
TOKEN_INFO: "/api/tokenInfo",
LOGIN_RECORD: "/api/log/loginRecord",
OPERATE_LOG: "/api/log/operateLog",
// user login
LOGIN: "/api/login",
// current user info
......
......@@ -91,4 +91,22 @@ export type LoginLog = {
accessTime: Date;
createTime: Date;
updateTime: Date;
}
\ No newline at end of file
};
export type OperateLog = {
id: number;
moduleName: string;
businessType: number;
method: string;
requestMethod: string;
operateName: string;
operateUserId: number;
operateUrl: string;
operateIp: string;
operateLocation: string;
operateParam: string;
jsonResult: string;
status: number;
errorMsg: string;
operateTime: Date;
};
\ No newline at end of file
......@@ -1150,6 +1150,29 @@ CREATE TABLE `dinky_sys_login_log` (
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='system login log record'
-- ----------------------------
-- Table structure for dinky_sys_operate_log
-- ----------------------------
DROP TABLE IF EXISTS `dinky_sys_operate_log`;
CREATE TABLE `dinky_sys_operate_log` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT 'id',
`module_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT 'module name',
`business_type` int NULL DEFAULT 0 COMMENT 'business type',
`method` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT 'method name',
`request_method` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT 'request method',
`operate_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT 'operate name',
`operate_user_id` int NOT NULL COMMENT 'operate user id',
`operate_url` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT 'operate url',
`operate_ip` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT 'ip',
`operate_location` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT 'operate location',
`operate_param` varchar(2000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT 'request param',
`json_result` text CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT null COMMENT 'return json result',
`status` int DEFAULT NULL COMMENT 'operate status',
`error_msg` text CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT 'error msg',
`operate_time` datetime(0) NULL DEFAULT NULL COMMENT 'operate time',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = 'operate log record' ROW_FORMAT = Dynamic;
......
......@@ -2127,28 +2127,6 @@ ALTER TABLE "public"."dinky_resources" ADD CONSTRAINT "dinky_resources_pkey" PRI
create table if not exists public.dinky_sys_login_log
(
id integer,
user_id integer,
username varchar(60),
login_type integer,
ip varchar(40),
status integer,
msg text,
create_time timestamp,
access_time timestamp,
update_time timestamp,
is_deleted smallint
);
comment on table public.dinky_sys_login_log is 'dinky_sys_login_log';
alter table public.dinky_sys_login_log
owner to dinky;
-- ----------------------------
-- Table structure for dinky_sys_login_log
-- ----------------------------
......@@ -2178,3 +2156,27 @@ COMMENT ON COLUMN "public"."dinky_sys_login_log"."create_time" IS 'create time';
COMMENT ON COLUMN "public"."dinky_sys_login_log"."access_time" IS 'access time';
COMMENT ON COLUMN "public"."dinky_sys_login_log"."update_time" IS 'update time';
COMMENT ON COLUMN "public"."dinky_sys_login_log"."is_deleted" IS 'is deleted';
DROP TABLE IF EXISTS "public"."dinky_sys_operate_log";
create table "public"."dinky_sys_operate_log" (
id int4,
module_name character varying(50),
business_type int4,
method character varying(100),
request_method character varying(10),
operate_name character varying(50),
operate_user_id int4,
operate_url character varying(255),
operate_ip character varying(50),
operate_location character varying(255),
operate_param character varying(2000),
json_result text,
status int4,
error_msg text,
operate_time timestamp without time zone
);
comment on table public.dinky_sys_operate_log is 'dinky_sys_operate_log';
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment