@org.springframework.validation.annotation.Validated

Here are the examples of the java api @org.springframework.validation.annotation.Validated taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1370 Examples 7

19 Source : TenantController.java
with Apache License 2.0
from zuihou

/**
 * <p>
 * 前端控制器
 * 企业
 * <p>
 * 创建租户流程:
 * 1. COLUMN模式: 新增租户、初始化内置租户数据
 * 2. SCHEMA模式: 新增租户、初始化库、初始化表、初始化内置租户数据
 * 3. DATASOURCE模式
 * 该模式有2种动态创建租户数据源的方式
 * LOCAL: 租户数据源跟默认数据源在同一个 物理数据库   (启动时程序连192.168.1.1:3306/lamp_defaults库,租户连192.168.1.2:3306/lamp_base_xxx库)
 * REMOTE:租户数据源跟默认数据源不在同一个 物理数据库(启动时程序连192.168.1.1:3306/lamp_defaults库,租户连192.168.1.2:3306/lamp_base_xxx库)
 * <p>
 * LOCAL模式会自动使用程序默认库的账号,进行创建租户库操作,所以设置的账号密码必须拥有超级权限,但在程序中配置数据库的超级权限账号是比较危险的事,所以需要谨慎使用。
 * REMOTE模式 考虑到上述问题,决定让新增租户的管理员,手动创建好租户库后,提供账号密码连接信息等,配置到DatasourceConfig表,创建好租户后,在初始化数据源页面,
 * 选择已经创建好的数据源进行初始化操作。
 * <p>
 * 以上2种方式各有利弊,请大家酌情使用。 有更好的意见可以跟我讨论一下。
 * <p>
 * 先调用 POST /datasourceConfig 接口保存数据源
 * 在调用 POST /tenant 接口保存租户信息
 * 然后调用 POST /tenant/connect 接口为每个服务连接自己的数据源,并初始化表和数据
 *
 * @author zuihou
 * @date 2019-10-24
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/tenant")
@Api(value = "Tenant", tags = "企业")
@SysLog(enabled = false)
public clreplaced TenantController extends SuperCacheController<TenantService, Long, Tenant, TenantPageQuery, TenantSaveDTO, TenantUpdateDTO> {

    @ApiOperation(value = "查询所有企业", notes = "查询所有企业")
    @GetMapping("/all")
    public R<List<Tenant>> list() {
        return success(baseService.list(Wraps.<Tenant>lbQ().eq(Tenant::getStatus, NORMAL)));
    }

    @Override
    public R<Tenant> handlerSave(TenantSaveDTO model) {
        Tenant tenant = baseService.save(model);
        return success(tenant);
    }

    @ApiOperation(value = "检测租户是否存在", notes = "检测租户是否存在")
    @GetMapping("/check/{code}")
    public R<Boolean> check(@PathVariable("code") String code) {
        return success(baseService.check(code));
    }

    @Override
    public R<Boolean> handlerDelete(List<Long> ids) {
        // 这个操作相当的危险,请谨慎操作!!!
        return success(baseService.delete(ids));
    }

    @ApiOperation(value = "删除租户和基础租户数据,请谨慎操作")
    @DeleteMapping("/deleteAll")
    @PreAuth("hasAnyRole('PT_ADMIN')")
    public R<Boolean> deleteAll(@RequestParam("ids[]") List<Long> ids) {
        return success(baseService.deleteAll(ids));
    }

    @ApiOperation(value = "修改租户状态", notes = "修改租户状态")
    @PostMapping("/status")
    public R<Boolean> updateStatus(@RequestParam("ids[]") List<Long> ids, @RequestParam(defaultValue = "FORBIDDEN") @NotNull(message = "状态不能为空") TenantStatusEnum status) {
        return success(baseService.updateStatus(ids, status));
    }

    /**
     * 初始化
     */
    @ApiOperation(value = "连接数据源", notes = "连接数据源")
    @PostMapping("/initConnect")
    public R<Boolean> initConnect(@RequestBody TenantConnectDTO tenantConnect) {
        return success(baseService.connect(tenantConnect));
    }
}

19 Source : OauthUserController.java
with Apache License 2.0
from zuihou

/**
 * <p>
 * 前端控制器
 * 用户
 * </p>
 *
 * @author zuihou
 * @date 2019-07-22
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/user")
@Api(value = "User", tags = "用户")
@AllArgsConstructor
public clreplaced OauthUserController {

    private final UserService userService;

    /**
     * 单体查询用户
     *
     * @param id 主键id
     * @return 查询结果
     */
    @ApiOperation(value = "查询用户详细", notes = "查询用户详细")
    @PostMapping(value = "/anno/id/{id}")
    public R<SysUser> getById(@PathVariable Long id, @RequestBody UserQuery query) {
        return R.success(userService.getSysUserById(id, query));
    }

    /**
     * 根据用户id,查询用户权限范围
     *
     * @param id 用户id
     */
    @ApiOperation(value = "查询用户权限范围", notes = "根据用户id,查询用户权限范围")
    @GetMapping(value = "/ds/{id}")
    @IgnoreResponseBodyAdvice
    public Map<String, Object> getDataScopeById(@PathVariable("id") Long id) {
        return userService.getDataScopeById(id);
    }
}

19 Source : SmsSendStatusController.java
with Apache License 2.0
from zuihou

/**
 * <p>
 * 前端控制器
 * 短信发送状态
 * </p>
 *
 * @author zuihou
 * @date 2019-08-01
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/smsSendStatus")
@Api(value = "SmsSendStatus", tags = "短信发送状态")
public clreplaced SmsSendStatusController extends SuperSimpleController<SmsSendStatusService, SmsSendStatus> implements QueryController<SmsSendStatus, Long, SmsSendStatus> {
}

19 Source : TestController.java
with Apache License 2.0
from zuihou

/**
 * 注入登录用户信息 测试类
 *
 * @author zuihou
 * @date 2019/07/10
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/test")
@Api(value = "Test", tags = "测试类")
public clreplaced TestController {

    @GetMapping("/{id}")
    public R<String> get(@PathVariable Long id, @ApiIgnore @LoginUser(isFull = true) SysUser user) {
        return R.success("Id");
    }

    @GetMapping("/get")
    public R<String> get2(@RequestParam("id") Long id, @ApiIgnore @LoginUser SysUser user) {
        return R.success("Id");
    }

    @PostMapping
    public R<OptLogDTO> save(@RequestBody OptLogDTO data) {
        return R.success(data);
    }

    @PostMapping("post2")
    public R<OptLogDTO> post2(@RequestBody OptLogDTO data, @ApiIgnore @LoginUser(isOrg = true, isStation = true) SysUser user) {
        return R.success(data);
    }

    @GetMapping("get3")
    public R<OptLogDTO> get3(OptLogDTO data, @ApiIgnore @LoginUser(isOrg = true, isStation = true) SysUser user) {
        return R.success(data);
    }

    @PostMapping("post3")
    public R<EnumDTO> post3(@RequestBody EnumDTO data) {
        return R.success(data);
    }

    @PostMapping("post4")
    public R<EnumDTO> post4(@RequestBody EnumDTO data) {
        int a = 1 / 0;
        log.info("a=", a);
        return R.success(data);
    }

    @PostMapping("post5")
    public R<EnumDTO> post5(@RequestBody EnumDTO data) throws Exception {
        new EnumDTO().testEx();
        return R.success(data);
    }

    @PostMapping("post6")
    public R<EnumDTO> post6(@RequestBody EnumDTO data) throws Exception {
        return R.success(data);
    }

    @PostMapping("post7")
    public R<User> post7(@RequestBody(required = false) User data) throws Exception {
        return R.success(data);
    }

    @PostMapping("post8")
    public R<Resource> post8(@RequestBody(required = false) Resource data) throws Exception {
        return R.success(data);
    }
}

19 Source : SeataTxController.java
with Apache License 2.0
from zuihou

/**
 * 分布式事务测试类
 *
 * @author zuihou
 * @date 2019/08/12
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/seata")
@Api(value = "SeataTxController", tags = "分布式事务测试类")
@RequiredArgsConstructor
public clreplaced SeataTxController {

    private final ProductService productService;

    @PostMapping("/save")
    public R<Product> save(@RequestBody Product data) {
        log.info("data={}", data);
        productService.save(data);
        return R.success(data);
    }

    @PostMapping("/saveEx")
    public R<Product> saveEx(@RequestBody Product data) {
        log.info("data={}", data);
        productService.saveEx(data);
        return R.success(data);
    }
}

19 Source : ParamValidateController.java
with Apache License 2.0
from zuihou

/**
 * 表单验证测试类
 * 必须在类上加 @Validated
 *
 * @author zuihou
 * @date 2019/07/03
 */
@Slf4j
@RestController
@RequestMapping("/valid2")
@Api(value = "Valid", tags = "验证2")
@Validated
public clreplaced ParamValidateController {

    /**
     * 不能
     *
     * @param code
     * @return
     */
    @GetMapping("/requestParam/get1")
    @Validated
    public String paramGet1(@NotEmpty(message = "不能为空") @RequestParam(value = "code", required = false) String code) {
        return "不能验证";
    }

    /**
     * 不能验证
     *
     * @param code
     * @return
     */
    @GetMapping("/requestParam/get2")
    public String paramGet2(@NotEmpty(message = "不能为空") @RequestParam(value = "code", required = false) String code) {
        return "不能验证";
    }

    @GetMapping("/requestParam/get3")
    public String paramGet3(@Validated @NotEmpty(message = "code 不能为空") @RequestParam(value = "code", required = false) String code, @NotEmpty(message = "name 不能空") @RequestParam(value = "name", required = false) String name) {
        return "不能验证";
    }

    /**
     * 不能
     *
     * @param code
     * @return
     */
    @GetMapping("/requestParam/get4")
    @Valid
    public String paramGet4(@NotEmpty(message = "不能为空") @RequestParam(value = "code", required = false) String code) {
        return "不能验证";
    }

    /**
     * 不能验证
     *
     * @param code
     * @return
     */
    @GetMapping("/requestParam/get5")
    public String paramGet5(@Valid @NotEmpty(message = "不能为空") @RequestParam(value = "code", required = false) String code) {
        return "不能验证";
    }

    @GetMapping("/requestParam/get6")
    public String paramGet6(@Valid @NotEmpty(message = "code 不能为空") @RequestParam(value = "code", required = false) String code, @NotEmpty(message = "name 不能空") @RequestParam(value = "name", required = false) String name) {
        return "不能验证";
    }
}

19 Source : ParamValidateController.java
with Apache License 2.0
from zuihou

/**
 * 不能
 *
 * @param code
 * @return
 */
@GetMapping("/requestParam/get1")
@Validated
public String paramGet1(@NotEmpty(message = "不能为空") @RequestParam(value = "code", required = false) String code) {
    return "不能验证";
}

19 Source : HibernateValidateController.java
with Apache License 2.0
from zuihou

/**
 * 表单验证测试类
 *
 * @author zuihou
 * @date 2019/07/03
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/valid")
@Api(value = "Valid", tags = "验证")
public clreplaced HibernateValidateController {

    /**
     * ok
     * 普通对象验证, @Validated 注解需要写在参数上
     *
     * @param data
     * @return
     */
    @GetMapping("/obj/get2")
    public String objGet2(@Validated(SuperEnreplacedy.Update.clreplaced) @Valid ApplicationUpdateDTO data) {
        return "验证Update组 成功";
    }

    /**
     * ok
     * 普通对象验证, @Validated 注解需要写在参数上
     *
     * @param data
     * @return
     */
    @GetMapping("/obj/get3")
    @SysLog("测试")
    public String objGet3(@Validated @Valid ApplicationUpdateDTO data) {
        return "验证默认组成功";
    }

    /**
     * 就算类上面有 @Validated 注解
     *
     * @param data
     * @return
     */
    @GetMapping("/obj/get4")
    @SysLog("测试")
    public String objGet4(ApplicationUpdateDTO data) {
        return "无法验证";
    }

    /**
     * 可以验证
     *
     * @param data
     * @return
     */
    @GetMapping("/obj/get5")
    public String objGet5(@Valid ApplicationUpdateDTO data) {
        return "可以验证";
    }

    /**
     * 可以验证
     *
     * @param data
     * @return
     */
    @GetMapping("/obj/get6")
    @Validated
    public String objGet6(@Valid ApplicationUpdateDTO data) {
        return "可以验证";
    }

    /**
     * 有 @RequestBody 注解的方法,  @Validated 注解需要写在方法上
     *
     * @param data
     * @return
     */
    @PostMapping("/requestBody/post")
    @Validated(SuperEnreplacedy.Update.clreplaced)
    public String bodyPost(@Valid @RequestBody ValidatorDTO data) {
        return "类上有 Validated,方法上有@Validated(Update), 参数有 Valid";
    }

    @PostMapping("/requestBody/post3")
    public String bodyPost3(@Validated @Valid @RequestBody ValidatorDTO data) {
        return "类上有 Validated,方法上有@Validated, 参数有 Valid";
    }

    @PostMapping("/requestBody/post5")
    public String bodyPost5(@Valid @RequestBody ValidatorDTO data) {
        return "类上有 Validated,参数有 Valid";
    }

    @PostMapping("/requestBody/post6")
    public String bodyPost6(@RequestBody ValidatorDTO data) {
        return "类上有 Validated,方法和参数没有";
    }

    /**
     * ok
     * 方法上的@Validated注解,一般用来指定 验证组
     *
     * @param code
     * @return
     */
    @GetMapping("/requestParam/get")
    @Validated
    public String paramGet(@Length(max = 3) @NotEmpty(message = "不能为空") @RequestParam(value = "code", required = false) String code) {
        return "方法上的@Validated注解,一般用来指定 验证组";
    }

    /**
     * ok
     * 方法上没有 @Validated 注解,就用类上的 @Validated 注解,
     *
     * @param code
     * @return
     */
    @GetMapping("/requestParam/get2")
    public String paramGet2(@NotEmpty(message = "不能为空") @RequestParam(value = "code", required = false) String code) {
        return "方法上没有 @Validated 注解,就用类上的 @Validated 注解";
    }
}

19 Source : HibernateValidateController.java
with Apache License 2.0
from zuihou

/**
 * ok
 * 方法上的@Validated注解,一般用来指定 验证组
 *
 * @param code
 * @return
 */
@GetMapping("/requestParam/get")
@Validated
public String paramGet(@Length(max = 3) @NotEmpty(message = "不能为空") @RequestParam(value = "code", required = false) String code) {
    return "方法上的@Validated注解,一般用来指定 验证组";
}

19 Source : ProductController.java
with Apache License 2.0
from zuihou

/**
 * <p>
 * 前端控制器
 * 订单
 * </p>
 *
 * @author zuihou
 * @date 2019-08-13
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/product")
@Api(value = "ProductController", tags = "商品")
@PreAuth(replace = "demo:product:", enabled = false)
@RequiredArgsConstructor
public clreplaced ProductController extends SuperController<ProductService, Long, Product, ProductPageQuery, ProductSaveDTO, ProductUpdateDTO> {

    private final InjectionCore injectionCore;

    @Override
    public void handlerResult(IPage<Product> page) {
        injectionCore.injection(page);
    }
}

19 Source : LoginLogController.java
with Apache License 2.0
from zuihou

/**
 * <p>
 * 前端控制器
 * 登录日志
 * </p>
 *
 * @author zuihou
 * @date 2019-10-20
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/loginLog")
@Api(value = "LoginLog", tags = "登录日志")
@PreAuth(replace = "authority:loginLog:")
public clreplaced LoginLogController extends SuperController<LoginLogService, Long, LoginLog, LoginLog, LoginLog, LoginLogUpdateDTO> {

    /**
     * 分页查询登录日志
     *
     * @param model  对象
     * @param params 分页查询参数
     * @return 查询结果
     */
    @Override
    public QueryWrap<LoginLog> handlerWrapper(LoginLog model, PageParams<LoginLog> params) {
        QueryWrap<LoginLog> wrapper = super.handlerWrapper(model, params);
        wrapper.lambda().ignore(LoginLog::setAccount).ignore(LoginLog::setRequestIp).likeRight(LoginLog::getAccount, model.getAccount()).likeRight(LoginLog::getRequestIp, model.getRequestIp());
        return wrapper;
    }

    @ApiOperation("清空日志")
    @DeleteMapping("clear")
    @SysLog("清空日志")
    public R<Boolean> clear(@RequestParam(required = false, defaultValue = "1") Integer type) {
        LocalDateTime clearBeforeTime = null;
        Integer clearBeforeNum = null;
        if (type == 1) {
            clearBeforeTime = LocalDateTime.now().plusMonths(-1);
        } else if (type == 2) {
            clearBeforeTime = LocalDateTime.now().plusMonths(-3);
        } else if (type == 3) {
            clearBeforeTime = LocalDateTime.now().plusMonths(-6);
        } else if (type == 4) {
            clearBeforeTime = LocalDateTime.now().plusMonths(-12);
        } else if (type == 5) {
            // 清理一千条以前日志数据
            clearBeforeNum = 1000;
        } else if (type == 6) {
            // 清理一万条以前日志数据
            clearBeforeNum = 10000;
        } else if (type == 7) {
            // 清理三万条以前日志数据
            clearBeforeNum = 30000;
        } else if (type == 8) {
            // 清理十万条以前日志数据
            clearBeforeNum = 100000;
        }
        return success(baseService.clearLog(clearBeforeTime, clearBeforeNum));
    }
}

19 Source : DashboardController.java
with Apache License 2.0
from zuihou

/**
 * <p>
 * 前端控制器
 * 首页
 * </p>
 *
 * @author zuihou
 * @date 2019-10-20
 */
@Slf4j
@Validated
@RestController
@Api(value = "dashboard", tags = "首页")
@RequiredArgsConstructor
public clreplaced DashboardController {

    private final LoginLogService loginLogService;

    private final UserService userService;

    private final UidGenerator uidGenerator;

    @GetMapping("/dashboard/visit")
    public R<Map<String, Object>> index(@ApiIgnore @LoginUser SysUser user) {
        Map<String, Object> data = new HashMap<>(11);
        // 获取系统访问记录
        data.put("totalVisitCount", loginLogService.getTotalVisitCount());
        data.put("todayVisitCount", loginLogService.getTodayVisitCount());
        data.put("todayIp", loginLogService.getTodayIp());
        data.put("userCount", userService.count());
        data.put("lastTenVisitCount", loginLogService.findLastTenDaysVisitCount(null));
        data.put("lastTenUserVisitCount", loginLogService.findLastTenDaysVisitCount(user.getAccount()));
        data.put("browserCount", loginLogService.findByBrowser());
        data.put("operatingSystemCount", loginLogService.findByOperatingSystem());
        return R.success(data);
    }

    @GetMapping("/common/generateId")
    public R<Object> generate() {
        long uid = uidGenerator.getUid();
        return R.success(uid + "length" + String.valueOf(uid).length());
    }
}

19 Source : RoleAuthorityController.java
with Apache License 2.0
from zuihou

/**
 * <p>
 * 前端控制器
 * 角色的资源
 * </p>
 *
 * @author zuihou
 * @date 2019-07-22
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/roleAuthority")
@Api(value = "RoleAuthority", tags = "角色的资源")
@RequiredArgsConstructor
public clreplaced RoleAuthorityController {

    private final RoleAuthorityService roleAuthorityService;

    /**
     * 查询指定角色关联的菜单和资源
     *
     * @param roleId 角色id
     * @return 查询结果
     */
    @ApiOperation(value = "查询指定角色关联的菜单和资源", notes = "查询指定角色关联的菜单和资源")
    @GetMapping("/{roleId}")
    @SysLog(value = "'查询指定角色关联的菜单和资源", response = false)
    public R<List<RoleAuthority>> queryByRoleId(@PathVariable Long roleId) {
        return R.success(roleAuthorityService.list(Wraps.<RoleAuthority>lbQ().eq(RoleAuthority::getRoleId, roleId)));
    }
}

19 Source : GlobalUserController.java
with Apache License 2.0
from zuihou

/**
 * <p>
 * 前端控制器
 * 全局账号
 * </p>
 *
 * @author zuihou
 * @date 2019-10-25
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/globalUser")
@Api(value = "GlobalUser", tags = "全局账号")
@SysLog(enabled = false)
@RequiredArgsConstructor
public clreplaced GlobalUserController extends SuperController<UserService, Long, User, GlobalUserPageDTO, GlobalUserSaveDTO, GlobalUserUpdateDTO> {

    @Override
    public R<User> handlerSave(GlobalUserSaveDTO model) {
        ContextUtil.setTenant(model.getTenantCode());
        User user = BeanPlusUtil.toBean(model, User.clreplaced);
        user.setName(StrHelper.getOrDef(model.getName(), model.getAccount()));
        if (StrUtil.isEmpty(user.getPreplacedword())) {
            user.setPreplacedword(BizConstant.DEF_PreplacedWORD);
        }
        user.setState(true);
        baseService.initUser(user);
        return success(user);
    }

    @Override
    public R<User> handlerUpdate(GlobalUserUpdateDTO model) {
        ContextUtil.setTenant(model.getTenantCode());
        User user = BeanPlusUtil.toBean(model, User.clreplaced);
        baseService.updateUser(user);
        return success(user);
    }

    @ApiImplicitParams({ @ApiImplicitParam(name = "tenantCode", value = "企业编码", dataType = DATA_TYPE_STRING, paramType = PARAM_TYPE_QUERY), @ApiImplicitParam(name = "account", value = "账号", dataType = DATA_TYPE_STRING, paramType = PARAM_TYPE_QUERY) })
    @ApiOperation(value = "检测账号是否可用", notes = "检测账号是否可用")
    @GetMapping("/check")
    public R<Boolean> check(@RequestParam String tenantCode, @RequestParam String account) {
        ContextUtil.setTenant(tenantCode);
        return success(baseService.check(account));
    }

    @Override
    public void query(PageParams<GlobalUserPageDTO> params, IPage<User> page, Long defSize) {
        GlobalUserPageDTO model = params.getModel();
        ContextUtil.setTenant(model.getTenantCode());
        // LbqWrapper<User> wrapper = Wraps.lbq(null, params.getExtra(), User.clreplaced);
        // wrapper.like(User::getAccount, model.getAccount())
        // .like(User::getName, model.getName());
        baseService.pageByRole(page, params);
    }

    @ApiOperation(value = "删除用户")
    @DeleteMapping("/delete")
    @ApiImplicitParams({ @ApiImplicitParam(name = "tenantCode", value = "企业编码", dataType = DATA_TYPE_STRING, paramType = PARAM_TYPE_QUERY), @ApiImplicitParam(name = "ids[]", value = "主键id", dataType = DATA_TYPE_STRING, allowMultiple = true, paramType = PARAM_TYPE_QUERY) })
    public R<Boolean> delete(@RequestParam String tenantCode, @RequestParam("ids[]") List<Long> ids) {
        ContextUtil.setTenant(tenantCode);
        return success(baseService.remove(ids));
    }

    /**
     * 修改密码
     *
     * @param model 修改实体
     */
    @ApiOperation(value = "修改密码", notes = "修改密码")
    @PutMapping("/reset")
    public R<Boolean> updatePreplacedword(@RequestBody @Validated(SuperEnreplacedy.Update.clreplaced) UserUpdatePreplacedwordDTO model) {
        ContextUtil.setTenant(model.getTenantCode());
        return success(baseService.reset(model));
    }
}

19 Source : ApplicationController.java
with Apache License 2.0
from zuihou

/**
 * <p>
 * 前端控制器
 * 应用
 * </p>
 *
 * @author zuihou
 * @date 2019-12-15
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/application")
@Api(value = "Application", tags = "应用")
@ApiSupport(author = "zuihou")
@PreAuth(replace = "authority:application:")
public clreplaced ApplicationController extends SuperCacheController<ApplicationService, Long, Application, ApplicationPageQuery, ApplicationSaveDTO, ApplicationUpdateDTO> {

    @Override
    public R<Application> handlerSave(ApplicationSaveDTO applicationSaveDTO) {
        applicationSaveDTO.setClientId(RandomUtil.randomString(24));
        applicationSaveDTO.setClientSecret(RandomUtil.randomString(32));
        return super.handlerSave(applicationSaveDTO);
    }
}

19 Source : TenantController.java
with Apache License 2.0
from zuihou

/**
 * <p>
 * 前端控制器
 * 企业
 * <p>
 * 创建租户流程:
 * 1. COLUMN模式: 新增租户、初始化内置租户数据
 * 2. SCHEMA模式: 新增租户、初始化库、初始化表、初始化内置租户数据
 * 3. DATASOURCE模式
 * 该模式有2种动态创建租户数据源的方式
 * LOCAL: 租户数据源跟默认数据源在同一个 物理数据库   (启动时程序连192.168.1.1:3306/lamp_defaults库,租户连192.168.1.2:3306/lamp_base_xxx库)
 * REMOTE:租户数据源跟默认数据源不在同一个 物理数据库(启动时程序连192.168.1.1:3306/lamp_defaults库,租户连192.168.1.2:3306/lamp_base_xxx库)
 * <p>
 * LOCAL模式会自动使用程序默认库的账号,进行创建租户库操作,所以设置的账号密码必须拥有超级权限,但在程序中配置数据库的超级权限账号是比较危险的事,所以需要谨慎使用。
 * REMOTE模式 考虑到上述问题,决定让新增租户的管理员,手动创建好租户库后,提供账号密码连接信息等,配置到DatasourceConfig表,创建好租户后,在初始化数据源页面,
 * 选择已经创建好的数据源进行初始化操作。
 * <p>
 * 以上2种方式各有利弊,请大家酌情使用。 有更好的意见可以跟我讨论一下。
 * <p>
 * 先调用 POST /datasourceConfig 接口保存数据源
 * 在调用 POST /tenant 接口保存租户信息
 * 然后调用 POST /tenant/connect 接口为每个服务连接自己的数据源,并初始化表和数据
 *
 * @author zuihou
 * @date 2019-10-24
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/tenant")
@Api(value = "Tenant", tags = "企业")
@SysLog(enabled = false)
public clreplaced TenantController extends SuperCacheController<TenantService, Long, Tenant, TenantPageQuery, TenantSaveDTO, TenantUpdateDTO> {

    @ApiOperation(value = "查询所有企业", notes = "查询所有企业")
    @GetMapping("/all")
    public R<List<Tenant>> list() {
        return success(baseService.list(Wraps.<Tenant>lbQ().eq(Tenant::getStatus, NORMAL)));
    }

    @Override
    public R<Tenant> handlerSave(TenantSaveDTO model) {
        Tenant tenant = baseService.save(model);
        return success(tenant);
    }

    @ApiOperation(value = "检测租户是否存在", notes = "检测租户是否存在")
    @GetMapping("/check/{code}")
    public R<Boolean> check(@PathVariable("code") String code) {
        return success(baseService.check(code));
    }

    @Override
    public R<Boolean> handlerDelete(List<Long> ids) {
        // 这个操作相当的危险,请谨慎操作!!!
        return success(baseService.delete(ids));
    }

    @ApiOperation(value = "删除租户和基础租户数据,请谨慎操作")
    @DeleteMapping("/deleteAll")
    @PreAuth("hasAnyRole('SUPER_ADMIN')")
    public R<Boolean> deleteAll(@RequestParam("ids[]") List<Long> ids) {
        return success(baseService.deleteAll(ids));
    }

    /**
     * 初始化
     */
    @ApiOperation(value = "连接数据源", notes = "连接数据源")
    @PostMapping("/initConnect")
    public R<Boolean> initConnect(@RequestBody TenantConnectDTO tenantConnect) {
        return success(baseService.connect(tenantConnect));
    }
}

19 Source : AccountController.java
with Apache License 2.0
from Zoctan

/**
 * @author Zoctan
 * @date 2018/06/09
 */
@RestController
@RequestMapping("/account")
@Validated
public clreplaced AccountController {

    @Resource
    private AccountService accountService;

    @Resource
    private AccountDetailsServiceImpl userDetailsService;

    @Resource
    private JwtUtil jwtUtil;

    @PostMapping
    public Result register(@RequestBody @Valid final AccountDto account, final BindingResult bindingResult) {
        // {"name":"123456", "preplacedword":"123456", "email": "[email protected]"}
        if (bindingResult.hasErrors()) {
            // noinspection ConstantConditions
            final String msg = bindingResult.getFieldError().getDefaultMessage();
            return ResultGenerator.genFailedResult(msg);
        } else {
            this.accountService.save(account);
            return this.getToken(account.getName());
        }
    }

    @PreAuthorize("hasAuthority('account:delete')")
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable final Long id, final Principal principal) {
        final Account dbAccount = this.accountService.getById(id);
        if (dbAccount == null) {
            return ResultGenerator.genFailedResult("用户不存在");
        }
        this.accountService.deleteById(id);
        return ResultGenerator.genOkResult();
    }

    @PostMapping("/preplacedword")
    public Result validatePreplacedword(@RequestBody final Account account) {
        final Account dbAccount = this.accountService.getById(account.getId());
        final boolean isValidate = this.accountService.verifyPreplacedword(account.getPreplacedword(), dbAccount.getPreplacedword());
        return ResultGenerator.genOkResult(isValidate);
    }

    /**
     * 更新其他账户的资料
     */
    @PreAuthorize("hasAuthority('account:update')")
    @PutMapping("/{id}")
    public Result updateOthers(@PathVariable final Long id, @RequestBody final Account account, final Principal principal) {
        final Account dbAccount = this.accountService.getById(id);
        if (dbAccount == null) {
            return ResultGenerator.genFailedResult("用户不存在");
        }
        this.accountService.update(account);
        return ResultGenerator.genOkResult();
    }

    /**
     * 更新自己的资料
     */
    @PutMapping("/detail")
    public Result updateMe(@RequestBody final Account account) {
        this.accountService.update(account);
        final Account dbAccount = this.accountService.getById(account.getId());
        return this.getToken(dbAccount.getName());
    }

    /**
     * 其他账户的资料
     */
    @PreAuthorize("hasAuthority('account:detail')")
    @GetMapping("/{id}")
    public Result detail(@PathVariable final Long id) {
        final Account dbAccount = this.accountService.getById(id);
        return ResultGenerator.genOkResult(dbAccount);
    }

    /**
     * 自己的资料
     */
    @GetMapping("/detail")
    public Result detail(final Principal principal) {
        final Account dbAccount = this.accountService.findDetailByName(principal.getName());
        return ResultGenerator.genOkResult(dbAccount);
    }

    @PreAuthorize("hasAuthority('account:list')")
    @GetMapping
    public Result list(@RequestParam(defaultValue = "0") final Integer page, @RequestParam(defaultValue = "0") final Integer size) {
        PageHelper.startPage(page, size);
        final List<AccountWithRole> list = this.accountService.listAllWithRole();
        final PageInfo<AccountWithRole> pageInfo = new PageInfo<>(list);
        return ResultGenerator.genOkResult(pageInfo);
    }

    @PreAuthorize("hasAuthority('account:search')")
    @PostMapping("/search")
    public Result search(@RequestBody final Map<String, Object> param) {
        PageHelper.startPage((Integer) param.get("page"), (Integer) param.get("size"));
        final List<AccountWithRole> list = this.accountService.findWithRoleBy(param);
        final PageInfo<AccountWithRole> pageInfo = new PageInfo<>(list);
        return ResultGenerator.genOkResult(pageInfo);
    }

    @PostMapping("/token")
    public Result login(@RequestBody final Account account) {
        // {"name":"admin", "preplacedword":"admin123"}
        // {"email":"[email protected]", "preplacedword":"admin123"}
        if (account.getName() == null && account.getEmail() == null) {
            return ResultGenerator.genFailedResult("用户名或邮箱为空");
        }
        if (account.getPreplacedword() == null) {
            return ResultGenerator.genFailedResult("密码为空");
        }
        // 用户名登录
        Account dbAccount = null;
        if (account.getName() != null) {
            dbAccount = this.accountService.getBy("name", account.getName());
            if (dbAccount == null) {
                return ResultGenerator.genFailedResult("用户名错误");
            }
        }
        // 邮箱登录
        if (account.getEmail() != null) {
            dbAccount = this.accountService.getBy("email", account.getEmail());
            if (dbAccount == null) {
                return ResultGenerator.genFailedResult("邮箱错误");
            }
            account.setName(dbAccount.getName());
        }
        // 验证密码
        // noinspection ConstantConditions
        if (!this.accountService.verifyPreplacedword(account.getPreplacedword(), dbAccount.getPreplacedword())) {
            return ResultGenerator.genFailedResult("密码错误");
        }
        // 更新登录时间
        this.accountService.updateLoginTimeByName(account.getName());
        return this.getToken(account.getName());
    }

    @DeleteMapping("/token")
    public Result logout(final Principal principal) {
        this.jwtUtil.invalidRedisToken(principal.getName());
        return ResultGenerator.genOkResult();
    }

    /**
     * 获得 token
     */
    private Result getToken(final String name) {
        final UserDetails accountDetails = this.userDetailsService.loadUserByUsername(name);
        final String token = this.jwtUtil.sign(name, accountDetails.getAuthorities(), true);
        return ResultGenerator.genOkResult(token);
    }
}

19 Source : RoleController.java
with MIT License
from yuuki80code

/**
 * (Role)表控制层
 *
 * @author yuuki
 * @since 2019-11-13 16:25:03
 */
@RestController
@RequestMapping("role")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Validated
public clreplaced RoleController {

    private final RoleService roleService;

    /**
     * 分页查询所有数据
     *
     * @param params 分页对象
     * @return 分页对象
     */
    @GetMapping("/bulk")
    @PreAuthorize("hasAuthority('role:view')")
    public Page selectByPage(PageInfo params, Role role) {
        return (Page) this.roleService.selectWithMenu(params, role);
    }

    /**
     *  获取所有角色列表
     */
    @GetMapping
    public List<Role> selectAll() {
        return roleService.list();
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/{id}")
    public Response selectOne(@PathVariable Serializable id) {
        return Response.success(this.roleService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param role 实体对象
     * @return 新增结果 success、 false
     */
    @PostMapping
    @PreAuthorize("hasAuthority('role:add')")
    public Response insert(@RequestBody @Valid Role role) {
        return roleService.addRole(role);
    }

    /**
     * 修改数据
     *
     * @param role 实体对象
     * @return 修改结果 success、 false
     */
    @PutMapping
    @PreAuthorize("hasAuthority('role:edit')")
    public Response update(@RequestBody @Valid Role role) {
        return this.roleService.updateRole(role);
    }

    /**
     * 删除数据
     *
     * @param ids 主键
     * @return 删除结果
     */
    @DeleteMapping("/{ids}")
    @PreAuthorize("hasAuthority('role:del')")
    public Response deleteOne(@PathVariable String ids) {
        return this.roleService.deleteRoles(ids);
    }
}

19 Source : MenuController.java
with MIT License
from yuuki80code

/**
 * (Menu)表控制层
 *
 * @author makejava
 * @since 2019-09-08 19:51:58
 */
@RestController
@RequestMapping("menu")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Validated
public clreplaced MenuController {

    private final MenuService menuService;

    /**
     * 分页查询所有数据
     *
     * @param params 分页对象
     * @return 分页对象
     */
    @GetMapping("/bulk")
    @PreAuthorize("hasAuthority('menu:view')")
    public List<Menu> selectAll(PageInfo params, Menu menu) {
        return this.menuService.list();
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/{id}")
    public Response selectOne(@PathVariable Serializable id) {
        return Response.success(this.menuService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param menu 实体对象
     * @return 新增结果 success、 false
     */
    @PostMapping
    @PreAuthorize("hasAuthority('menu:add')")
    public Response insert(@RequestBody @Valid Menu menu) {
        return Response.success(this.menuService.save(menu));
    }

    /**
     * 修改数据
     *
     * @param menu 实体对象
     * @return 修改结果 success、 false
     */
    @PutMapping
    @PreAuthorize("hasAuthority('menu:edit')")
    public Response update(@RequestBody @Valid Menu menu) {
        return Response.success(this.menuService.updateById(menu));
    }

    /**
     * 删除数据
     *
     * @param ids 主键
     * @return 删除结果
     */
    @DeleteMapping("/{ids}")
    @PreAuthorize("hasAuthority('menu:del')")
    public Response deleteOne(@PathVariable String ids) {
        return menuService.deleteMenus(ids);
    }

    @GetMapping("userPerms/{username}")
    public String findPermsByUser(@PathVariable String username) {
        return menuService.findPermsByUser(username);
    }

    @GetMapping("/userRouter/{username}")
    public Response findUserRouter(@PathVariable String username) {
        return menuService.findUserRouter(username);
    }
}

19 Source : DeptController.java
with MIT License
from yuuki80code

/**
 * (Dept)表控制层
 *
 * @author yuuki
 * @since 2019-11-13 11:13:25
 */
@RestController
@RequestMapping("dept")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Validated
public clreplaced DeptController {

    private final DeptService deptService;

    /**
     * 分页查询所有数据
     *
     * @return 分页对象
     */
    @GetMapping("/bulk")
    @PreAuthorize("hasAuthority('dept:view')")
    public List<Dept> selectAll() {
        return this.deptService.list();
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/{id}")
    public Response selectOne(@PathVariable Serializable id) {
        return Response.success(this.deptService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param dept 实体对象
     * @return 新增结果 success、 false
     */
    @PostMapping
    @PreAuthorize("hasAuthority('dept:add')")
    public Response insert(@RequestBody @Valid Dept dept) {
        return Response.success(this.deptService.save(dept));
    }

    /**
     * 修改数据
     *
     * @param dept 实体对象
     * @return 修改结果 success、 false
     */
    @PutMapping
    @PreAuthorize("hasAuthority('dept:edit')")
    public Response update(@RequestBody @Valid Dept dept) {
        return Response.success(this.deptService.updateById(dept));
    }

    /**
     * 删除数据
     *
     * @param ids 主键
     * @return 删除结果
     */
    @DeleteMapping("/{ids}")
    @PreAuthorize("hasAuthority('dept:del')")
    public Response delete(@PathVariable String ids) {
        return this.deptService.deleteDepts(ids);
    }
}

19 Source : SysPostServiceImpl.java
with MIT License
from YunaiV

/**
 * 岗位 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public clreplaced SysPostServiceImpl implements SysPostService {

    @Resource
    private SysPostMapper postMapper;

    @Override
    public Long createPost(SysPostCreateReqVO reqVO) {
        // 校验正确性
        this.checkCreateOrUpdate(null, reqVO.getName(), reqVO.getCode());
        // 插入岗位
        SysPostDO post = SysPostConvert.INSTANCE.convert(reqVO);
        postMapper.insert(post);
        return post.getId();
    }

    @Override
    public void updatePost(SysPostUpdateReqVO reqVO) {
        // 校验正确性
        this.checkCreateOrUpdate(reqVO.getId(), reqVO.getName(), reqVO.getCode());
        // 更新岗位
        SysPostDO updateObj = SysPostConvert.INSTANCE.convert(reqVO);
        postMapper.updateById(updateObj);
    }

    @Override
    public void deletePost(Long id) {
        // 校验是否存在
        this.checkPostExists(id);
        // 删除部门
        postMapper.deleteById(id);
    }

    @Override
    public List<SysPostDO> getPosts(Collection<Long> ids, Collection<Integer> statuses) {
        return postMapper.selectList(ids, statuses);
    }

    @Override
    public PageResult<SysPostDO> getPostPage(SysPostPageReqVO reqVO) {
        return postMapper.selectPage(reqVO);
    }

    @Override
    public List<SysPostDO> getPosts(SysPostExportReqVO reqVO) {
        return postMapper.selectList(reqVO);
    }

    @Override
    public SysPostDO getPost(Long id) {
        return postMapper.selectById(id);
    }

    private void checkCreateOrUpdate(Long id, String name, String code) {
        // 校验自己存在
        checkPostExists(id);
        // 校验岗位名的唯一性
        checkPostNameUnique(id, name);
        // 校验岗位编码的唯一性
        checkPostCodeUnique(id, code);
    }

    private void checkPostNameUnique(Long id, String name) {
        SysPostDO post = postMapper.selectByName(name);
        if (post == null) {
            return;
        }
        // 如果 id 为空,说明不用比较是否为相同 id 的岗位
        if (id == null) {
            throw ServiceExceptionUtil.exception(POST_NAME_DUPLICATE);
        }
        if (!post.getId().equals(id)) {
            throw ServiceExceptionUtil.exception(POST_NAME_DUPLICATE);
        }
    }

    private void checkPostCodeUnique(Long id, String code) {
        SysPostDO post = postMapper.selectByCode(code);
        if (post == null) {
            return;
        }
        // 如果 id 为空,说明不用比较是否为相同 id 的岗位
        if (id == null) {
            throw ServiceExceptionUtil.exception(POST_CODE_DUPLICATE);
        }
        if (!post.getId().equals(id)) {
            throw ServiceExceptionUtil.exception(POST_CODE_DUPLICATE);
        }
    }

    private void checkPostExists(Long id) {
        if (id == null) {
            return;
        }
        SysPostDO post = postMapper.selectById(id);
        if (post == null) {
            throw ServiceExceptionUtil.exception(POST_NOT_FOUND);
        }
    }
}

19 Source : SysDeptServiceImpl.java
with MIT License
from YunaiV

/**
 * 部门 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
@Slf4j
public clreplaced SysDeptServiceImpl implements SysDeptService {

    /**
     * 定时执行 {@link #schedulePeriodicRefresh()} 的周期
     * 因为已经通过 Redis Pub/Sub 机制,所以频率不需要高
     */
    private static final long SCHEDULER_PERIOD = 5 * 60 * 1000L;

    /**
     * 部门缓存
     * key:部门编号 {@link SysDeptDO#getId()}
     *
     * 这里声明 volatile 修饰的原因是,每次刷新时,直接修改指向
     */
    @SuppressWarnings("FieldCanBeLocal")
    private volatile Map<Long, SysDeptDO> deptCache;

    /**
     * 父部门缓存
     * key:部门编号 {@link SysDeptDO#getParentId()}
     * value: 直接子部门列表
     *
     * 这里声明 volatile 修饰的原因是,每次刷新时,直接修改指向
     */
    private volatile Multimap<Long, SysDeptDO> parentDeptCache;

    /**
     * 缓存部门的最大更新时间,用于后续的增量轮询,判断是否有更新
     */
    private volatile Date maxUpdateTime;

    @Resource
    private SysDeptMapper deptMapper;

    @Resource
    private SysDeptProducer deptProducer;

    @Override
    @PostConstruct
    public synchronized void initLocalCache() {
        // 获取部门列表,如果有更新
        List<SysDeptDO> deptList = this.loadDeptIfUpdate(maxUpdateTime);
        if (CollUtil.isEmpty(deptList)) {
            return;
        }
        // 构建缓存
        ImmutableMap.Builder<Long, SysDeptDO> builder = ImmutableMap.builder();
        ImmutableMultimap.Builder<Long, SysDeptDO> parentBuilder = ImmutableMultimap.builder();
        deptList.forEach(sysRoleDO -> {
            builder.put(sysRoleDO.getId(), sysRoleDO);
            parentBuilder.put(sysRoleDO.getParentId(), sysRoleDO);
        });
        // 设置缓存
        deptCache = builder.build();
        parentDeptCache = parentBuilder.build();
        // 断言,避免告警
        replacedert deptList.size() > 0;
        maxUpdateTime = deptList.stream().max(Comparator.comparing(BaseDO::getUpdateTime)).get().getUpdateTime();
        log.info("[initLocalCache][初始化 Dept 数量为 {}]", deptList.size());
    }

    @Scheduled(fixedDelay = SCHEDULER_PERIOD, initialDelay = SCHEDULER_PERIOD)
    public void schedulePeriodicRefresh() {
        initLocalCache();
    }

    /**
     * 如果部门发生变化,从数据库中获取最新的全量部门。
     * 如果未发生变化,则返回空
     *
     * @param maxUpdateTime 当前部门的最大更新时间
     * @return 部门列表
     */
    private List<SysDeptDO> loadDeptIfUpdate(Date maxUpdateTime) {
        // 第一步,判断是否要更新。
        if (maxUpdateTime == null) {
            // 如果更新时间为空,说明 DB 一定有新数据
            log.info("[loadMenuIfUpdate][首次加载全量部门]");
        } else {
            // 判断数据库中是否有更新的部门
            if (!deptMapper.selectExistsByUpdateTimeAfter(maxUpdateTime)) {
                return null;
            }
            log.info("[loadMenuIfUpdate][增量加载全量部门]");
        }
        // 第二步,如果有更新,则从数据库加载所有部门
        return deptMapper.selectList();
    }

    @Override
    public Long createDept(SysDeptCreateReqVO reqVO) {
        // 校验正确性
        checkCreateOrUpdate(null, reqVO.getParentId(), reqVO.getName());
        // 插入部门
        SysDeptDO dept = SysDeptConvert.INSTANCE.convert(reqVO);
        deptMapper.insert(dept);
        // 发送刷新消息
        deptProducer.sendDeptRefreshMessage();
        return dept.getId();
    }

    @Override
    public void updateDept(SysDeptUpdateReqVO reqVO) {
        // 校验正确性
        checkCreateOrUpdate(reqVO.getId(), reqVO.getParentId(), reqVO.getName());
        // 更新部门
        SysDeptDO updateObj = SysDeptConvert.INSTANCE.convert(reqVO);
        deptMapper.updateById(updateObj);
        // 发送刷新消息
        deptProducer.sendDeptRefreshMessage();
    }

    @Override
    public void deleteDept(Long id) {
        // 校验是否存在
        checkDeptExists(id);
        // 校验是否有子部门
        if (deptMapper.selectCountByParentId(id) > 0) {
            throw ServiceExceptionUtil.exception(DEPT_EXITS_CHILDREN);
        }
        // 删除部门
        deptMapper.deleteById(id);
        // TODO 需要处理下与角色的数据权限关联,等做数据权限一起处理下
        // 发送刷新消息
        deptProducer.sendDeptRefreshMessage();
    }

    @Override
    public List<SysDeptDO> getSimpleDepts(Collection<Long> ids) {
        return deptMapper.selectBatchIds(ids);
    }

    @Override
    public List<SysDeptDO> getSimpleDepts(SysDeptListReqVO reqVO) {
        return deptMapper.selectList(reqVO);
    }

    @Override
    public List<SysDeptDO> getDeptsByParentIdFromCache(Long parentId, boolean recursive) {
        List<SysDeptDO> result = new ArrayList<>();
        // 递归,简单粗暴
        this.listDeptsByParentIdFromCache(result, parentId, // 如果递归获取,则无限;否则,只递归 1 次
        recursive ? Integer.MAX_VALUE : 1, parentDeptCache);
        return result;
    }

    /**
     * 递归获取所有的子部门,添加到 result 结果
     *
     * @param result 结果
     * @param parentId 父编号
     * @param recursiveCount 递归次数
     * @param parentDeptMap 父部门 Map,使用缓存,避免变化
     */
    private void listDeptsByParentIdFromCache(List<SysDeptDO> result, Long parentId, int recursiveCount, Multimap<Long, SysDeptDO> parentDeptMap) {
        // 递归次数为 0,结束!
        if (recursiveCount == 0) {
            return;
        }
        // 获得子部门
        Collection<SysDeptDO> depts = parentDeptMap.get(parentId);
        if (CollUtil.isEmpty(depts)) {
            return;
        }
        result.addAll(depts);
        // 继续递归
        depts.forEach(dept -> listDeptsByParentIdFromCache(result, dept.getId(), recursiveCount - 1, parentDeptMap));
    }

    @Override
    public SysDeptDO getDept(Long id) {
        return deptMapper.selectById(id);
    }

    private void checkCreateOrUpdate(Long id, Long parentId, String name) {
        // 校验自己存在
        checkDeptExists(id);
        // 校验父部门的有效性
        checkParentDeptEnable(id, parentId);
        // 校验部门名的唯一性
        checkDeptNameUnique(id, parentId, name);
    }

    private void checkParentDeptEnable(Long id, Long parentId) {
        if (parentId == null || DeptIdEnum.ROOT.getId().equals(parentId)) {
            return;
        }
        // 不能设置自己为父部门
        if (parentId.equals(id)) {
            throw ServiceExceptionUtil.exception(DEPT_PARENT_ERROR);
        }
        // 父岗位不存在
        SysDeptDO dept = deptMapper.selectById(parentId);
        if (dept == null) {
            throw ServiceExceptionUtil.exception(DEPT_PARENT_NOT_EXITS);
        }
        // 父部门被禁用
        if (!CommonStatusEnum.ENABLE.getStatus().equals(dept.getStatus())) {
            throw ServiceExceptionUtil.exception(DEPT_NOT_ENABLE);
        }
        // 父部门不能是原来的子部门
        List<SysDeptDO> children = this.getDeptsByParentIdFromCache(id, true);
        if (children.stream().anyMatch(dept1 -> dept1.getId().equals(parentId))) {
            throw ServiceExceptionUtil.exception(DEPT_PARENT_IS_CHILD);
        }
    }

    private void checkDeptExists(Long id) {
        if (id == null) {
            return;
        }
        SysDeptDO dept = deptMapper.selectById(id);
        if (dept == null) {
            throw ServiceExceptionUtil.exception(DEPT_NOT_FOUND);
        }
    }

    private void checkDeptNameUnique(Long id, Long parentId, String name) {
        SysDeptDO menu = deptMapper.selectByParentIdAndName(parentId, name);
        if (menu == null) {
            return;
        }
        // 如果 id 为空,说明不用比较是否为相同 id 的岗位
        if (id == null) {
            throw ServiceExceptionUtil.exception(DEPT_NAME_DUPLICATE);
        }
        if (!menu.getId().equals(id)) {
            throw ServiceExceptionUtil.exception(DEPT_NAME_DUPLICATE);
        }
    }
    // @Override
    // @DataScope(deptAlias = "d")
    // public List<SysDept> selectDeptList(SysDept dept)
    // {
    // return deptMapper.selectDeptList(dept);
    // }
}

19 Source : SysUserController.java
with MIT License
from YunaiV

@Api(tags = "用户")
@RestController
@RequestMapping("/system/user")
@Validated
public clreplaced SysUserController {

    @Resource
    private SysUserService userService;

    @Resource
    private SysDeptService deptService;

    @PostMapping("/create")
    @ApiOperation("新增用户")
    @PreAuthorize("@ss.hasPermission('system:user:create')")
    public CommonResult<Long> createUser(@Valid @RequestBody SysUserCreateReqVO reqVO) {
        Long id = userService.createUser(reqVO);
        return success(id);
    }

    @PutMapping("update")
    @ApiOperation("修改用户")
    @PreAuthorize("@ss.hasPermission('system:user:update')")
    public CommonResult<Boolean> updateUser(@Valid @RequestBody SysUserUpdateReqVO reqVO) {
        userService.updateUser(reqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除用户")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClreplaced = Long.clreplaced)
    @PreAuthorize("@ss.hasPermission('system:user:delete')")
    public CommonResult<Boolean> deleteUser(@RequestParam("id") Long id) {
        userService.deleteUser(id);
        return success(true);
    }

    @PutMapping("/update-preplacedword")
    @ApiOperation("重置用户密码")
    @PreAuthorize("@ss.hasPermission('system:user:update-preplacedword')")
    public CommonResult<Boolean> updateUserPreplacedword(@Valid @RequestBody SysUserUpdatePreplacedwordReqVO reqVO) {
        userService.updateUserPreplacedword(reqVO.getId(), reqVO.getPreplacedword());
        return success(true);
    }

    @PutMapping("/update-status")
    @ApiOperation("修改用户状态")
    @PreAuthorize("@ss.hasPermission('system:user:update')")
    public CommonResult<Boolean> updateUserStatus(@Valid @RequestBody SysUserUpdateStatusReqVO reqVO) {
        userService.updateUserStatus(reqVO.getId(), reqVO.getStatus());
        return success(true);
    }

    @GetMapping("/page")
    @ApiOperation("获得用户分页列表")
    @PreAuthorize("@ss.hasPermission('system:user:list')")
    public CommonResult<PageResult<SysUserPageItemRespVO>> getUserPage(@Valid SysUserPageReqVO reqVO) {
        // 获得用户分页列表
        PageResult<SysUserDO> pageResult = userService.getUserPage(reqVO);
        if (CollUtil.isEmpty(pageResult.getList())) {
            // 返回空
            return success(new PageResult<>(pageResult.getTotal()));
        }
        // 获得拼接需要的数据
        Collection<Long> deptIds = CollectionUtils.convertList(pageResult.getList(), SysUserDO::getDeptId);
        Map<Long, SysDeptDO> deptMap = deptService.getDeptMap(deptIds);
        // 拼接结果返回
        List<SysUserPageItemRespVO> userList = new ArrayList<>(pageResult.getList().size());
        pageResult.getList().forEach(user -> {
            SysUserPageItemRespVO respVO = SysUserConvert.INSTANCE.convert(user);
            respVO.setDept(SysUserConvert.INSTANCE.convert(deptMap.get(user.getDeptId())));
            userList.add(respVO);
        });
        return success(new PageResult<>(userList, pageResult.getTotal()));
    }

    @GetMapping("/get")
    @ApiOperation("获得用户详情")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClreplaced = Long.clreplaced)
    @PreAuthorize("@ss.hasPermission('system:user:query')")
    public CommonResult<SysUserRespVO> getInfo(@RequestParam("id") Long id) {
        return success(SysUserConvert.INSTANCE.convert(userService.getUser(id)));
    }

    @GetMapping("/export")
    @ApiOperation("导出用户")
    @PreAuthorize("@ss.hasPermission('system:user:export')")
    @OperateLog(type = EXPORT)
    public void exportUsers(@Validated SysUserExportReqVO reqVO, HttpServletResponse response) throws IOException {
        // 获得用户列表
        List<SysUserDO> users = userService.getUsers(reqVO);
        // 获得拼接需要的数据
        Collection<Long> deptIds = CollectionUtils.convertList(users, SysUserDO::getDeptId);
        Map<Long, SysDeptDO> deptMap = deptService.getDeptMap(deptIds);
        // 拼接数据
        List<SysUserExcelVO> excelUsers = new ArrayList<>(users.size());
        users.forEach(user -> {
            SysUserExcelVO excelVO = SysUserConvert.INSTANCE.convert02(user);
            MapUtils.findAndThen(deptMap, user.getDeptId(), dept -> {
                excelVO.setDeptName(dept.getName());
                excelVO.setDeptLeader(dept.getLeader());
            });
            excelUsers.add(excelVO);
        });
        // 输出
        ExcelUtils.write(response, "用户数据.xls", "用户列表", SysUserExcelVO.clreplaced, excelUsers);
    }

    @GetMapping("/get-import-template")
    @ApiOperation("获得导入用户模板")
    public void importTemplate(HttpServletResponse response) throws IOException {
        // 手动创建导出 demo
        List<SysUserImportExcelVO> list = Arrays.asList(SysUserImportExcelVO.builder().username("yudao").deptId(1L).email("[email protected]").mobile("15601691300").nickname("芋道").status(CommonStatusEnum.ENABLE.getStatus()).sex(SysSexEnum.MALE.getSEX()).build(), SysUserImportExcelVO.builder().username("yuanma").deptId(2L).email("[email protected]").mobile("15601701300").nickname("源码").status(CommonStatusEnum.DISABLE.getStatus()).sex(SysSexEnum.FEMALE.getSEX()).build());
        // 输出
        ExcelUtils.write(response, "用户导入模板.xls", "用户列表", SysUserImportExcelVO.clreplaced, list);
    }

    @PostMapping("/import")
    @ApiOperation("导入用户")
    @ApiImplicitParams({ @ApiImplicitParam(name = "file", value = "Excel 文件", required = true, dataTypeClreplaced = MultipartFile.clreplaced), @ApiImplicitParam(name = "updateSupport", value = "是否支持更新,默认为 false", example = "true", dataTypeClreplaced = Boolean.clreplaced) })
    @PreAuthorize("@ss.hasPermission('system:user:import')")
    public CommonResult<SysUserImportRespVO> importExcel(@RequestParam("file") MultipartFile file, @RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport) throws Exception {
        List<SysUserImportExcelVO> list = ExcelUtils.raed(file, SysUserImportExcelVO.clreplaced);
        return success(userService.importUsers(list, updateSupport));
    }
}

19 Source : SysRoleController.java
with MIT License
from YunaiV

@Api(tags = "角色")
@RestController
@RequestMapping("/system/role")
@Validated
public clreplaced SysRoleController {

    @Resource
    private SysRoleService roleService;

    @PostMapping("/create")
    @ApiOperation("创建角色")
    @PreAuthorize("@ss.hasPermission('system:role:create')")
    public CommonResult<Long> createRole(@Valid @RequestBody SysRoleCreateReqVO reqVO) {
        return success(roleService.createRole(reqVO));
    }

    @PutMapping("/update")
    @ApiOperation("修改角色")
    @PreAuthorize("@ss.hasPermission('system:role:update')")
    public CommonResult<Boolean> updateRole(@Valid @RequestBody SysRoleUpdateReqVO reqVO) {
        roleService.updateRole(reqVO);
        return success(true);
    }

    @PutMapping("/update-status")
    @ApiOperation("修改角色状态")
    @PreAuthorize("@ss.hasPermission('system:role:update')")
    public CommonResult<Boolean> updateRoleStatus(@Valid @RequestBody SysRoleUpdateStatusReqVO reqVO) {
        roleService.updateRoleStatus(reqVO.getId(), reqVO.getStatus());
        return success(true);
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除角色")
    @ApiImplicitParam(name = "id", value = "角色编号", required = true, example = "1024", dataTypeClreplaced = Long.clreplaced)
    @PreAuthorize("@ss.hasPermission('system:role:delete')")
    public CommonResult<Boolean> deleteRole(@RequestParam("id") Long id) {
        roleService.deleteRole(id);
        return success(true);
    }

    @GetMapping("/get")
    @ApiOperation("获得角色信息")
    @PreAuthorize("@ss.hasPermission('system:role:query')")
    public CommonResult<SysRoleRespVO> getRole(@RequestParam("id") Long id) {
        SysRoleDO role = roleService.getRole(id);
        return success(SysRoleConvert.INSTANCE.convert(role));
    }

    @GetMapping("/page")
    @ApiOperation("获得角色分页")
    @PreAuthorize("@ss.hasPermission('system:role:query')")
    public CommonResult<PageResult<SysRoleDO>> getRolePage(SysRolePageReqVO reqVO) {
        return success(roleService.getRolePage(reqVO));
    }

    @GetMapping("/list-all-simple")
    @ApiOperation(value = "获取角色精简信息列表", notes = "只包含被开启的角色,主要用于前端的下拉选项")
    public CommonResult<List<SysRoleSimpleRespVO>> getSimpleRoles() {
        // 获得角色列表,只要开启状态的
        List<SysRoleDO> list = roleService.getRoles(Collections.singleton(CommonStatusEnum.ENABLE.getStatus()));
        // 排序后,返回个诶前端
        list.sort(Comparator.comparing(SysRoleDO::getSort));
        return success(SysRoleConvert.INSTANCE.convertList02(list));
    }

    @GetMapping("/export")
    @OperateLog(type = EXPORT)
    @PreAuthorize("@ss.hasPermission('system:role:export')")
    public void export(HttpServletResponse response, @Validated SysRoleExportReqVO reqVO) throws IOException {
        List<SysRoleDO> list = roleService.getRoles(reqVO);
        List<SysRoleExcelVO> data = SysRoleConvert.INSTANCE.convertList03(list);
        // 输出
        ExcelUtils.write(response, "角色数据.xls", "角色列表", SysRoleExcelVO.clreplaced, data);
    }
}

19 Source : SysMenuController.java
with MIT License
from YunaiV

@Api(tags = "菜单")
@RestController
@RequestMapping("/system/menu")
@Validated
public clreplaced SysMenuController {

    @Resource
    private SysMenuService menuService;

    @PostMapping("/create")
    @ApiOperation("创建菜单")
    @PreAuthorize("@ss.hasPermission('system:menu:create')")
    public CommonResult<Long> createMenu(@Valid @RequestBody SysMenuCreateReqVO reqVO) {
        Long menuId = menuService.createMenu(reqVO);
        return success(menuId);
    }

    @PutMapping("/update")
    @ApiOperation("修改菜单")
    @PreAuthorize("@ss.hasPermission('system:menu:update')")
    public CommonResult<Boolean> updateMenu(@Valid @RequestBody SysMenuUpdateReqVO reqVO) {
        menuService.updateMenu(reqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除菜单")
    @ApiImplicitParam(name = "id", value = "角色编号", required = true, example = "1024", dataTypeClreplaced = Long.clreplaced)
    @PreAuthorize("@ss.hasPermission('system:menu:delete')")
    public CommonResult<Boolean> deleteMenu(@RequestParam("id") Long id) {
        menuService.deleteMenu(id);
        return success(true);
    }

    @GetMapping("/list")
    @ApiOperation("获取菜单列表")
    @PreAuthorize("@ss.hasPermission('system:menu:query')")
    public CommonResult<List<SysMenuRespVO>> getMenus(SysMenuListReqVO reqVO) {
        List<SysMenuDO> list = menuService.getMenus(reqVO);
        list.sort(Comparator.comparing(SysMenuDO::getSort));
        return success(SysMenuConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/list-all-simple")
    @ApiOperation(value = "获取菜单精简信息列表", notes = "只包含被开启的菜单,主要用于前端的下拉选项")
    public CommonResult<List<SysMenuSimpleRespVO>> getSimpleMenus() {
        // 获得菜单列表,只要开启状态的
        SysMenuListReqVO reqVO = new SysMenuListReqVO();
        reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus());
        List<SysMenuDO> list = menuService.getMenus(reqVO);
        // 排序后,返回个诶前端
        list.sort(Comparator.comparing(SysMenuDO::getSort));
        return success(SysMenuConvert.INSTANCE.convertList02(list));
    }

    @GetMapping("/get")
    @ApiOperation("获取菜单信息")
    @PreAuthorize("@ss.hasPermission('system:menu:query')")
    public CommonResult<SysMenuRespVO> getMenu(Long id) {
        SysMenuDO menu = menuService.getMenu(id);
        return success(SysMenuConvert.INSTANCE.convert(menu));
    }
}

19 Source : SysNoticeController.java
with MIT License
from YunaiV

@Api(tags = "通知公告")
@RestController
@RequestMapping("/system/notice")
@Validated
public clreplaced SysNoticeController {

    @Resource
    private SysNoticeService noticeService;

    @PostMapping("/create")
    @ApiOperation("创建通知公告")
    @PreAuthorize("@ss.hasPermission('system:notice:create')")
    public CommonResult<Long> createNotice(@Valid @RequestBody SysNoticeCreateReqVO reqVO) {
        Long noticeId = noticeService.createNotice(reqVO);
        return success(noticeId);
    }

    @PutMapping("/update")
    @ApiOperation("修改通知公告")
    @PreAuthorize("@ss.hasPermission('system:notice:update')")
    public CommonResult<Boolean> updateNotice(@Valid @RequestBody SysNoticeUpdateReqVO reqVO) {
        noticeService.updateNotice(reqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除通知公告")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClreplaced = Long.clreplaced)
    @PreAuthorize("@ss.hasPermission('system:notice:delete')")
    public CommonResult<Boolean> deleteNotice(@RequestParam("id") Long id) {
        noticeService.deleteNotice(id);
        return success(true);
    }

    @GetMapping("/page")
    @ApiOperation("获取通知公告列表")
    @PreAuthorize("@ss.hasPermission('system:notice:quey')")
    public CommonResult<PageResult<SysNoticeRespVO>> pageNotices(@Validated SysNoticePageReqVO reqVO) {
        return success(SysNoticeConvert.INSTANCE.convertPage(noticeService.pageNotices(reqVO)));
    }

    @GetMapping("/get")
    @ApiOperation("获得通知公告")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClreplaced = Long.clreplaced)
    @PreAuthorize("@ss.hasPermission('system:notice:quey')")
    public CommonResult<SysNoticeRespVO> getNotice(@RequestParam("id") Long id) {
        return success(SysNoticeConvert.INSTANCE.convert(noticeService.getNotice(id)));
    }
}

19 Source : SysLoginLogController.java
with MIT License
from YunaiV

@Api(tags = "登陆日志")
@RestController
@RequestMapping("/system/login-log")
@Validated
public clreplaced SysLoginLogController {

    @Resource
    private SysLoginLogService loginLogService;

    @GetMapping("/page")
    @ApiOperation("获得登陆日志分页列表")
    @PreAuthorize("@ss.hasPermission('system:login-log:query')")
    public CommonResult<PageResult<SysLoginLogRespVO>> getLoginLogPage(@Valid SysLoginLogPageReqVO reqVO) {
        PageResult<SysLoginLogDO> page = loginLogService.getLoginLogPage(reqVO);
        return CommonResult.success(SysLoginLogConvert.INSTANCE.convertPage(page));
    }

    @GetMapping("/export")
    @ApiOperation("导出登陆日志 Excel")
    @PreAuthorize("@ss.hasPermission('system:login-log:export')")
    @OperateLog(type = EXPORT)
    public void exportLoginLog(HttpServletResponse response, @Valid SysLoginLogExportReqVO reqVO) throws IOException {
        List<SysLoginLogDO> list = loginLogService.getLoginLogList(reqVO);
        // 拼接数据
        List<SysLoginLogExcelVO> data = SysLoginLogConvert.INSTANCE.convertList(list);
        // 输出
        ExcelUtils.write(response, "登陆日志.xls", "数据列表", SysLoginLogExcelVO.clreplaced, data);
    }
}

19 Source : SysDictDataController.java
with MIT License
from YunaiV

@Api(tags = "字典数据")
@RestController
@RequestMapping("/system/dict-data")
@Validated
public clreplaced SysDictDataController {

    @Resource
    private SysDictDataService dictDataService;

    @PostMapping("/create")
    @ApiOperation("新增字典数据")
    @PreAuthorize("@ss.hasPermission('system:dict:create')")
    public CommonResult<Long> createDictData(@Valid @RequestBody SysDictDataCreateReqVO reqVO) {
        Long dictDataId = dictDataService.createDictData(reqVO);
        return success(dictDataId);
    }

    @PutMapping("update")
    @ApiOperation("修改字典数据")
    @PreAuthorize("@ss.hasPermission('system:dict:update')")
    public CommonResult<Boolean> updateDictData(@Valid @RequestBody SysDictDataUpdateReqVO reqVO) {
        dictDataService.updateDictData(reqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除字典数据")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClreplaced = Long.clreplaced)
    @PreAuthorize("@ss.hasPermission('system:dict:delete')")
    public CommonResult<Boolean> deleteDictData(Long id) {
        dictDataService.deleteDictData(id);
        return success(true);
    }

    @GetMapping("/list-all-simple")
    @ApiOperation(value = "获得全部字典数据列表", notes = "一般用于管理后台缓存字典数据在本地")
    public // 无需添加权限认证,因为前端全局都需要
    CommonResult<List<SysDictDataSimpleVO>> getSimpleDictDatas() {
        List<SysDictDataDO> list = dictDataService.getDictDatas();
        return success(SysDictDataConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/page")
    @ApiOperation("/获得字典类型的分页列表")
    @PreAuthorize("@ss.hasPermission('system:dict:query')")
    public CommonResult<PageResult<SysDictDataRespVO>> getDictTypePage(@Valid SysDictDataPageReqVO reqVO) {
        return success(SysDictDataConvert.INSTANCE.convertPage(dictDataService.getDictDataPage(reqVO)));
    }

    @GetMapping(value = "/get")
    @ApiOperation("/查询字典数据详细")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClreplaced = Long.clreplaced)
    @PreAuthorize("@ss.hasPermission('system:dict:query')")
    public CommonResult<SysDictDataRespVO> getDictData(@RequestParam("id") Long id) {
        return success(SysDictDataConvert.INSTANCE.convert(dictDataService.getDictData(id)));
    }

    @GetMapping("/export")
    @ApiOperation("导出字典数据")
    @PreAuthorize("@ss.hasPermission('system:dict:export')")
    @OperateLog(type = EXPORT)
    public void export(HttpServletResponse response, @Valid SysDictDataExportReqVO reqVO) throws IOException {
        List<SysDictDataDO> list = dictDataService.getDictDatas(reqVO);
        List<SysDictDataExcelVO> data = SysDictDataConvert.INSTANCE.convertList02(list);
        // 输出
        ExcelUtils.write(response, "字典数据.xls", "数据列表", SysDictDataExcelVO.clreplaced, data);
    }
}

19 Source : SysDeptController.java
with MIT License
from YunaiV

@Api(tags = "部门")
@RestController
@RequestMapping("/system/dept")
@Validated
public clreplaced SysDeptController {

    @Resource
    private SysDeptService deptService;

    @PostMapping("create")
    @ApiOperation("创建部门")
    @PreAuthorize("@ss.hasPermission('system:dept:create')")
    public CommonResult<Long> createDept(@Valid @RequestBody SysDeptCreateReqVO reqVO) {
        Long deptId = deptService.createDept(reqVO);
        return success(deptId);
    }

    @PutMapping("update")
    @ApiOperation("更新部门")
    @PreAuthorize("@ss.hasPermission('system:dept:update')")
    public CommonResult<Boolean> updateDept(@Valid @RequestBody SysDeptUpdateReqVO reqVO) {
        deptService.updateDept(reqVO);
        return success(true);
    }

    @DeleteMapping("delete")
    @ApiOperation("删除部门")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClreplaced = Long.clreplaced)
    @PreAuthorize("@ss.hasPermission('system:dept:delete')")
    public CommonResult<Boolean> deleteDept(@RequestParam("id") Long id) {
        deptService.deleteDept(id);
        return success(true);
    }

    @GetMapping("/list")
    @ApiOperation("获取部门列表")
    @PreAuthorize("@ss.hasPermission('system:dept:query')")
    public CommonResult<List<SysDeptRespVO>> listDepts(SysDeptListReqVO reqVO) {
        List<SysDeptDO> list = deptService.getSimpleDepts(reqVO);
        list.sort(Comparator.comparing(SysDeptDO::getSort));
        return success(SysDeptConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/list-all-simple")
    @ApiOperation(value = "获取部门精简信息列表", notes = "只包含被开启的部门,主要用于前端的下拉选项")
    public CommonResult<List<SysDeptSimpleRespVO>> getSimpleDepts() {
        // 获得部门列表,只要开启状态的
        SysDeptListReqVO reqVO = new SysDeptListReqVO();
        reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus());
        List<SysDeptDO> list = deptService.getSimpleDepts(reqVO);
        // 排序后,返回给前端
        list.sort(Comparator.comparing(SysDeptDO::getSort));
        return success(SysDeptConvert.INSTANCE.convertList02(list));
    }

    @GetMapping("/get")
    @ApiOperation("获得部门信息")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClreplaced = Long.clreplaced)
    @PreAuthorize("@ss.hasPermission('system:dept:query')")
    public CommonResult<SysDeptRespVO> getDept(@RequestParam("id") Long id) {
        return success(SysDeptConvert.INSTANCE.convert(deptService.getDept(id)));
    }
}

19 Source : InfApiErrorLogServiceImpl.java
with MIT License
from YunaiV

/**
 * API 错误日志 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public clreplaced InfApiErrorLogServiceImpl implements InfApiErrorLogService {

    @Resource
    private InfApiErrorLogMapper apiErrorLogMapper;

    @Override
    @Async
    public Future<Boolean> createApiErrorLogAsync(ApiErrorLogCreateDTO createDTO) {
        InfApiErrorLogDO apiErrorLog = InfApiErrorLogConvert.INSTANCE.convert(createDTO);
        apiErrorLog.setProcessStatus(InfApiErrorLogProcessStatusEnum.INIT.getStatus());
        int insert = apiErrorLogMapper.insert(apiErrorLog);
        return new AsyncResult<>(insert == 1);
    }

    @Override
    public PageResult<InfApiErrorLogDO> getApiErrorLogPage(InfApiErrorLogPageReqVO pageReqVO) {
        return apiErrorLogMapper.selectPage(pageReqVO);
    }

    @Override
    public List<InfApiErrorLogDO> getApiErrorLogList(InfApiErrorLogExportReqVO exportReqVO) {
        return apiErrorLogMapper.selectList(exportReqVO);
    }

    @Override
    public void updateApiErrorLogProcess(Long id, Integer processStatus, Long processUserId) {
        InfApiErrorLogDO errorLog = apiErrorLogMapper.selectById(id);
        if (errorLog == null) {
            throw exception(API_ERROR_LOG_NOT_FOUND);
        }
        if (!InfApiErrorLogProcessStatusEnum.INIT.getStatus().equals(errorLog.getProcessStatus())) {
            throw exception(API_ERROR_LOG_PROCESSED);
        }
        // 标记处理
        apiErrorLogMapper.updateById(InfApiErrorLogDO.builder().id(id).processStatus(processStatus).processUserId(processUserId).processTime(new Date()).build());
    }
}

19 Source : InfJobServiceImpl.java
with MIT License
from YunaiV

/**
 * 定时任务 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public clreplaced InfJobServiceImpl implements InfJobService {

    @Resource
    private InfJobMapper jobMapper;

    @Resource
    private SchedulerManager schedulerManager;

    @Override
    @Transactional(rollbackFor = Exception.clreplaced)
    public Long createJob(InfJobCreateReqVO createReqVO) throws SchedulerException {
        validateCronExpression(createReqVO.getCronExpression());
        // 校验唯一性
        if (jobMapper.selectByHandlerName(createReqVO.getHandlerName()) != null) {
            throw exception(JOB_HANDLER_EXISTS);
        }
        // 插入
        InfJobDO job = InfJobConvert.INSTANCE.convert(createReqVO);
        job.setStatus(InfJobStatusEnum.INIT.getStatus());
        fillJobMonitorTimeoutEmpty(job);
        jobMapper.insert(job);
        // 添加 Job 到 Quartz 中
        schedulerManager.addJob(job.getId(), job.getHandlerName(), job.getHandlerParam(), job.getCronExpression(), createReqVO.getRetryCount(), createReqVO.getRetryInterval());
        // 更新
        InfJobDO updateObj = InfJobDO.builder().id(job.getId()).status(InfJobStatusEnum.NORMAL.getStatus()).build();
        jobMapper.updateById(updateObj);
        // 返回
        return job.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.clreplaced)
    public void updateJob(InfJobUpdateReqVO updateReqVO) throws SchedulerException {
        validateCronExpression(updateReqVO.getCronExpression());
        // 校验存在
        InfJobDO job = this.validateJobExists(updateReqVO.getId());
        // 只有开启状态,才可以修改.原因是,如果出暂停状态,修改 Quartz Job 时,会导致任务又开始执行
        if (!job.getStatus().equals(InfJobStatusEnum.NORMAL.getStatus())) {
            throw exception(JOB_UPDATE_ONLY_NORMAL_STATUS);
        }
        // 更新
        InfJobDO updateObj = InfJobConvert.INSTANCE.convert(updateReqVO);
        fillJobMonitorTimeoutEmpty(updateObj);
        jobMapper.updateById(updateObj);
        // 更新 Job 到 Quartz 中
        schedulerManager.updateJob(job.getHandlerName(), updateReqVO.getHandlerParam(), updateReqVO.getCronExpression(), updateReqVO.getRetryCount(), updateReqVO.getRetryInterval());
    }

    @Override
    @Transactional(rollbackFor = Exception.clreplaced)
    public void updateJobStatus(Long id, Integer status) throws SchedulerException {
        // 校验 status
        if (!containsAny(status, InfJobStatusEnum.NORMAL.getStatus(), InfJobStatusEnum.STOP.getStatus())) {
            throw exception(JOB_CHANGE_STATUS_INVALID);
        }
        // 校验存在
        InfJobDO job = this.validateJobExists(id);
        // 校验是否已经为当前状态
        if (job.getStatus().equals(status)) {
            throw exception(JOB_CHANGE_STATUS_EQUALS);
        }
        // 更新 Job 状态
        InfJobDO updateObj = InfJobDO.builder().id(id).status(status).build();
        jobMapper.updateById(updateObj);
        // 更新状态 Job 到 Quartz 中
        if (InfJobStatusEnum.NORMAL.getStatus().equals(status)) {
            // 开启
            schedulerManager.resumeJob(job.getHandlerName());
        } else {
            // 暂停
            schedulerManager.pauseJob(job.getHandlerName());
        }
    }

    @Override
    public void triggerJob(Long id) throws SchedulerException {
        // 校验存在
        InfJobDO job = this.validateJobExists(id);
        // 触发 Quartz 中的 Job
        schedulerManager.triggerJob(job.getId(), job.getHandlerName(), job.getHandlerParam());
    }

    @Override
    @Transactional(rollbackFor = Exception.clreplaced)
    public void deleteJob(Long id) throws SchedulerException {
        // 校验存在
        InfJobDO job = this.validateJobExists(id);
        // 更新
        jobMapper.deleteById(id);
        // 删除 Job 到 Quartz 中
        schedulerManager.deleteJob(job.getHandlerName());
    }

    private InfJobDO validateJobExists(Long id) {
        InfJobDO job = jobMapper.selectById(id);
        if (job == null) {
            throw exception(JOB_NOT_EXISTS);
        }
        return job;
    }

    private void validateCronExpression(String cronExpression) {
        if (!CronUtils.isValid(cronExpression)) {
            throw exception(JOB_CRON_EXPRESSION_VALID);
        }
    }

    @Override
    public InfJobDO getJob(Long id) {
        return jobMapper.selectById(id);
    }

    @Override
    public List<InfJobDO> getJobList(Collection<Long> ids) {
        return jobMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<InfJobDO> getJobPage(InfJobPageReqVO pageReqVO) {
        return jobMapper.selectPage(pageReqVO);
    }

    @Override
    public List<InfJobDO> getJobList(InfJobExportReqVO exportReqVO) {
        return jobMapper.selectList(exportReqVO);
    }

    private static void fillJobMonitorTimeoutEmpty(InfJobDO job) {
        if (job.getMonitorTimeout() == null) {
            job.setMonitorTimeout(0);
        }
    }
}

19 Source : InfJobLogServiceImpl.java
with MIT License
from YunaiV

/**
 * Job 日志 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
@Slf4j
public clreplaced InfJobLogServiceImpl implements InfJobLogService {

    @Resource
    private InfJobLogMapper jobLogMapper;

    @Override
    public Long createJobLog(Long jobId, Date beginTime, String jobHandlerName, String jobHandlerParam, Integer executeIndex) {
        InfJobLogDO log = InfJobLogDO.builder().jobId(jobId).handlerName(jobHandlerName).handlerParam(jobHandlerParam).executeIndex(executeIndex).beginTime(beginTime).status(InfJobLogStatusEnum.RUNNING.getStatus()).build();
        jobLogMapper.insert(log);
        return log.getId();
    }

    @Override
    @Async
    public void updateJobLogResultAsync(Long logId, Date endTime, Integer duration, boolean success, String result) {
        try {
            InfJobLogDO updateObj = InfJobLogDO.builder().id(logId).endTime(endTime).duration(duration).status(success ? InfJobLogStatusEnum.SUCCESS.getStatus() : InfJobLogStatusEnum.FAILURE.getStatus()).result(result).build();
            jobLogMapper.updateById(updateObj);
        } catch (Exception ex) {
            log.error("[updateJobLogResultAsync][logId({}) endTime({}) duration({}) success({}) result({})]", logId, endTime, duration, success, result);
        }
    }

    @Override
    public InfJobLogDO getJobLog(Long id) {
        return jobLogMapper.selectById(id);
    }

    @Override
    public List<InfJobLogDO> getJobLogList(Collection<Long> ids) {
        return jobLogMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<InfJobLogDO> getJobLogPage(InfJobLogPageReqVO pageReqVO) {
        return jobLogMapper.selectPage(pageReqVO);
    }

    @Override
    public List<InfJobLogDO> getJobLogList(InfJobLogExportReqVO exportReqVO) {
        return jobLogMapper.selectList(exportReqVO);
    }
}

19 Source : InfJobLogController.java
with MIT License
from YunaiV

@Api(tags = "定时任务日志")
@RestController
@RequestMapping("/infra/job-log")
@Validated
public clreplaced InfJobLogController {

    @Resource
    private InfJobLogService jobLogService;

    @GetMapping("/get")
    @ApiOperation("获得定时任务日志")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClreplaced = Long.clreplaced)
    @PreAuthorize("@ss.hasPermission('infra:job:query')")
    public CommonResult<InfJobLogRespVO> getJobLog(@RequestParam("id") Long id) {
        InfJobLogDO jobLog = jobLogService.getJobLog(id);
        return success(InfJobLogConvert.INSTANCE.convert(jobLog));
    }

    @GetMapping("/list")
    @ApiOperation("获得定时任务日志列表")
    @ApiImplicitParam(name = "ids", value = "编号列表", required = true, example = "1024,2048", dataTypeClreplaced = List.clreplaced)
    @PreAuthorize("@ss.hasPermission('infra:job:query')")
    public CommonResult<List<InfJobLogRespVO>> getJobLogList(@RequestParam("ids") Collection<Long> ids) {
        List<InfJobLogDO> list = jobLogService.getJobLogList(ids);
        return success(InfJobLogConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/page")
    @ApiOperation("获得定时任务日志分页")
    @PreAuthorize("@ss.hasPermission('infra:job:query')")
    public CommonResult<PageResult<InfJobLogRespVO>> getJobLogPage(@Valid InfJobLogPageReqVO pageVO) {
        PageResult<InfJobLogDO> pageResult = jobLogService.getJobLogPage(pageVO);
        return success(InfJobLogConvert.INSTANCE.convertPage(pageResult));
    }

    @GetMapping("/export-excel")
    @ApiOperation("导出定时任务日志 Excel")
    @PreAuthorize("@ss.hasPermission('infra:job:export')")
    @OperateLog(type = EXPORT)
    public void exportJobLogExcel(@Valid InfJobLogExportReqVO exportReqVO, HttpServletResponse response) throws IOException {
        List<InfJobLogDO> list = jobLogService.getJobLogList(exportReqVO);
        // 导出 Excel
        List<InfJobLogExcelVO> datas = InfJobLogConvert.INSTANCE.convertList02(list);
        ExcelUtils.write(response, "任务日志.xls", "数据", InfJobLogExcelVO.clreplaced, datas);
    }
}

19 Source : InfJobController.java
with MIT License
from YunaiV

@Api(tags = "定时任务")
@RestController
@RequestMapping("/infra/job")
@Validated
public clreplaced InfJobController {

    @Resource
    private InfJobService jobService;

    @PostMapping("/create")
    @ApiOperation("创建定时任务")
    @PreAuthorize("@ss.hasPermission('infra:job:create')")
    public CommonResult<Long> createJob(@Valid @RequestBody InfJobCreateReqVO createReqVO) throws SchedulerException {
        return success(jobService.createJob(createReqVO));
    }

    @PutMapping("/update")
    @ApiOperation("更新定时任务")
    @PreAuthorize("@ss.hasPermission('infra:job:update')")
    public CommonResult<Boolean> updateJob(@Valid @RequestBody InfJobUpdateReqVO updateReqVO) throws SchedulerException {
        jobService.updateJob(updateReqVO);
        return success(true);
    }

    @PutMapping("/update-status")
    @ApiOperation("更新定时任务的状态")
    @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClreplaced = Long.clreplaced), @ApiImplicitParam(name = "status", value = "状态", required = true, example = "1", dataTypeClreplaced = Integer.clreplaced) })
    @PreAuthorize("@ss.hasPermission('infra:job:update')")
    public CommonResult<Boolean> updateJobStatus(@RequestParam(value = "id") Long id, @RequestParam("status") Integer status) throws SchedulerException {
        jobService.updateJobStatus(id, status);
        return success(true);
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除定时任务")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClreplaced = Long.clreplaced)
    @PreAuthorize("@ss.hasPermission('infra:job:delete')")
    public CommonResult<Boolean> deleteJob(@RequestParam("id") Long id) throws SchedulerException {
        jobService.deleteJob(id);
        return success(true);
    }

    @PutMapping("/trigger")
    @ApiOperation("触发定时任务")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClreplaced = Long.clreplaced)
    @PreAuthorize("@ss.hasPermission('infra:job:trigger')")
    public CommonResult<Boolean> triggerJob(@RequestParam("id") Long id) throws SchedulerException {
        jobService.triggerJob(id);
        return success(true);
    }

    @GetMapping("/get")
    @ApiOperation("获得定时任务")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClreplaced = Long.clreplaced)
    @PreAuthorize("@ss.hasPermission('infra:job:query')")
    public CommonResult<InfJobRespVO> getJob(@RequestParam("id") Long id) {
        InfJobDO job = jobService.getJob(id);
        return success(InfJobConvert.INSTANCE.convert(job));
    }

    @GetMapping("/list")
    @ApiOperation("获得定时任务列表")
    @ApiImplicitParam(name = "ids", value = "编号列表", required = true, dataTypeClreplaced = List.clreplaced)
    @PreAuthorize("@ss.hasPermission('infra:job:query')")
    public CommonResult<List<InfJobRespVO>> getJobList(@RequestParam("ids") Collection<Long> ids) {
        List<InfJobDO> list = jobService.getJobList(ids);
        return success(InfJobConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/page")
    @ApiOperation("获得定时任务分页")
    @PreAuthorize("@ss.hasPermission('infra:job:query')")
    public CommonResult<PageResult<InfJobRespVO>> getJobPage(@Valid InfJobPageReqVO pageVO) {
        PageResult<InfJobDO> pageResult = jobService.getJobPage(pageVO);
        return success(InfJobConvert.INSTANCE.convertPage(pageResult));
    }

    @GetMapping("/export-excel")
    @ApiOperation("导出定时任务 Excel")
    @PreAuthorize("@ss.hasPermission('infra:job:export')")
    @OperateLog(type = EXPORT)
    public void exportJobExcel(@Valid InfJobExportReqVO exportReqVO, HttpServletResponse response) throws IOException {
        List<InfJobDO> list = jobService.getJobList(exportReqVO);
        // 导出 Excel
        List<InfJobExcelVO> datas = InfJobConvert.INSTANCE.convertList02(list);
        ExcelUtils.write(response, "定时任务.xls", "数据", InfJobExcelVO.clreplaced, datas);
    }

    @GetMapping("/get_next_times")
    @ApiOperation("获得定时任务的下 n 次执行时间")
    @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClreplaced = Long.clreplaced), @ApiImplicitParam(name = "count", value = "数量", example = "5", dataTypeClreplaced = Long.clreplaced) })
    @PreAuthorize("@ss.hasPermission('infra:job:query')")
    public CommonResult<List<Date>> getJobNextTimes(@RequestParam("id") Long id, @RequestParam(value = "count", required = false, defaultValue = "5") Integer count) {
        InfJobDO job = jobService.getJob(id);
        if (job == null) {
            return success(Collections.emptyList());
        }
        return success(CronUtils.getNextTimes(job.getCronExpression(), count));
    }
}

19 Source : InfConfigController.java
with MIT License
from YunaiV

@Api(tags = "参数配置")
@RestController
@RequestMapping("/infra/config")
@Validated
public clreplaced InfConfigController {

    @Resource
    private InfConfigService configService;

    @PostMapping("/create")
    @ApiOperation("创建参数配置")
    @PreAuthorize("@ss.hasPermission('infra:config:create')")
    public CommonResult<Long> createConfig(@Valid @RequestBody InfConfigCreateReqVO reqVO) {
        return success(configService.createConfig(reqVO));
    }

    @PutMapping("/update")
    @ApiOperation("修改参数配置")
    @PreAuthorize("@ss.hasPermission('infra:config:update')")
    public CommonResult<Boolean> updateConfig(@Valid @RequestBody InfConfigUpdateReqVO reqVO) {
        configService.updateConfig(reqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除参数配置")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClreplaced = Long.clreplaced)
    @PreAuthorize("@ss.hasPermission('infra:config:delete')")
    public CommonResult<Boolean> deleteConfig(@RequestParam("id") Long id) {
        configService.deleteConfig(id);
        return success(true);
    }

    @GetMapping(value = "/get")
    @ApiOperation("获得参数配置")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClreplaced = Long.clreplaced)
    @PreAuthorize("@ss.hasPermission('infra:config:query')")
    public CommonResult<InfConfigRespVO> getConfig(@RequestParam("id") Long id) {
        return success(InfConfigConvert.INSTANCE.convert(configService.getConfig(id)));
    }

    @GetMapping(value = "/get-value-by-key")
    @ApiOperation(value = "根据参数键名查询参数值", notes = "敏感配置,不允许返回给前端")
    @ApiImplicitParam(name = "key", value = "参数键", required = true, example = "yunai.biz.username", dataTypeClreplaced = String.clreplaced)
    public CommonResult<String> getConfigKey(@RequestParam("key") String key) {
        InfConfigDO config = configService.getConfigByKey(key);
        if (config == null) {
            return null;
        }
        if (config.getSensitive()) {
            throw exception(CONFIG_GET_VALUE_ERROR_IF_SENSITIVE);
        }
        return success(config.getValue());
    }

    @GetMapping("/page")
    @ApiOperation("获取参数配置分页")
    @PreAuthorize("@ss.hasPermission('infra:config:query')")
    public CommonResult<PageResult<InfConfigRespVO>> getConfigPage(@Valid InfConfigPageReqVO reqVO) {
        PageResult<InfConfigDO> page = configService.getConfigPage(reqVO);
        return success(InfConfigConvert.INSTANCE.convertPage(page));
    }

    @GetMapping("/export")
    @ApiOperation("导出参数配置")
    @PreAuthorize("@ss.hasPermission('infra:config:export')")
    @OperateLog(type = EXPORT)
    public void exportSysConfig(@Valid InfConfigExportReqVO reqVO, HttpServletResponse response) throws IOException {
        List<InfConfigDO> list = configService.getConfigList(reqVO);
        // 拼接数据
        List<InfConfigExcelVO> datas = InfConfigConvert.INSTANCE.convertList(list);
        // 输出
        ExcelUtils.write(response, "参数配置.xls", "数据", InfConfigExcelVO.clreplaced, datas);
    }
}

19 Source : FileProperties.java
with MIT License
from YunaiV

@ConfigurationProperties(prefix = "yudao.file")
@Validated
@Data
public clreplaced FileProperties {

    /**
     * 对应 {@link InfFileController#}
     */
    @NotNull(message = "基础文件路径不能为空")
    private String basePath;
    // TODO 七牛、等等
}

19 Source : CaptchaProperties.java
with MIT License
from YunaiV

@ConfigurationProperties(prefix = "yudao.captcha")
@Validated
@Data
public clreplaced CaptchaProperties {

    /**
     * 验证码的过期时间
     */
    @NotNull(message = "验证码的过期时间不为空")
    private Duration timeout;

    /**
     * 验证码的高度
     */
    @NotNull(message = "验证码的高度不能为空")
    private Integer height;

    /**
     * 验证码的宽度
     */
    @NotNull(message = "验证码的宽度不能为空")
    private Integer width;
}

19 Source : SampleConfigurationProperties.java
with Apache License 2.0
from yuanmabiji

@Validated
@Component
@ConfigurationProperties(prefix = "sample")
public clreplaced SampleConfigurationProperties {

    @NotNull
    private String name;

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

19 Source : ExampleController3.java
with Apache License 2.0
from yuanmabiji

/**
 * Example {@link Controller} used with {@link WebMvcTest} tests.
 *
 * @author Stephane Nicoll
 */
@RestController
@Validated
public clreplaced ExampleController3 {

    @GetMapping("/three/{id}")
    public String three(@PathVariable @Size(max = 4) String id) {
        return "Hello " + id;
    }
}

19 Source : AccountController.java
with Apache License 2.0
from yizhuoyan

@RestController
@RequestMapping("/api")
@Validated
public clreplaced AccountController {

    @Autowired
    UserAccountService accountService;

    @PatchMapping(path = "/account/preplacedword/{id}")
    public JSONResponse modifyUserPreplacedword(@PathVariable String id, ModifyPreplacedwordAo ao) throws Exception {
        accountService.updatePreplacedword(id, ao);
        return JSONResponse.ok();
    }

    @PatchMapping(path = "/account/name/{id}")
    public JSONResponse setRecommendAvatar(@PathVariable String id, String name, HttpSession session) throws Exception {
        // 获取当前登录用户
        AccountContext ac = (AccountContext) session.getAttribute(AccountContext.clreplaced.getName());
        // 更新帐号
        accountService.changeName(ac.getId(), name);
        return JSONResponse.ok();
    }
}

19 Source : SessionController.java
with Apache License 2.0
from yizhuoyan

@RestController
@RequestMapping("/api")
@Validated
public clreplaced SessionController {

    @Autowired
    UserAccountService accountService;

    @PostMapping("/session")
    public JSONResponse login(String account, String preplacedword, HttpServletRequest req, HttpSession session) throws Exception {
        // 获取登录IP
        String ip = req.getRemoteHost();
        String ip2 = req.getRemoteAddr();
        // 获取登录设备
        String userAgent = req.getHeader("user-agent");
        if (userAgent.contains("android")) {
        } else if (userAgent.contains("")) {
        }
        AccountContext ac = accountService.login(account, preplacedword);
        session.setAttribute(AccountContext.clreplaced.getName(), ac);
        return JSONResponse.ok(session.getId());
    }

    @DeleteMapping("/session/{token}")
    public JSONResponse logout(@PathVariable String token, HttpSession session) throws Exception {
        session.invalidate();
        System.out.println(token);
        return JSONResponse.ok();
    }

    @GetMapping("/session")
    public ResponseEnreplacedy getSession(HttpSession session) {
        AccountContext ac = (AccountContext) session.getAttribute(AccountContext.clreplaced.getName());
        if (ac != null) {
            return ResponseEnreplacedy.ok(ac);
        }
        return ResponseEnreplacedy.status(HttpStatus.GONE).build();
    }
}

19 Source : TestController.java
with Apache License 2.0
from yihonglei

/**
 * 控制层,service,请求规范,响应规范测试
 *
 * @author yihonglei
 */
@Validated
@RestController
@RequestMapping("/test")
public clreplaced TestController {

    @Autowired
    private TestService testService;

    @GetMapping("/test")
    public ApiResponse test() {
        return ApiResponse.success("daisy启动成功了!");
    }

    @PostMapping("/queryTestById")
    public ApiResponse queryTestById(TestDTO testDTO) {
        return ApiResponse.success(testService.queryTestById(testDTO));
    }

    @PostMapping("queryTestByIdXml")
    public ApiResponse queryTestByIdXml(TestDTO testDTO) {
        return ApiResponse.success(testService.queryTestByIdXml(testDTO));
    }
}

19 Source : TestController.java
with Apache License 2.0
from yihonglei

/**
 * 控制层,service,请求规范,响应规范
 *
 * @author yihonglei
 */
@Validated
@RestController
@RequestMapping("/test")
public clreplaced TestController {

    @Autowired
    private TestService testService;

    @GetMapping("/test")
    public ApiResponse test() {
        return ApiResponse.success("daisy启动成功了!");
    }

    @PostMapping("/queryTestById")
    public ApiResponse queryTestById(TestDTO testDTO) {
        return ApiResponse.success(testService.queryTestById(testDTO));
    }

    @PostMapping("queryTestByIdXml")
    public ApiResponse queryTestByIdXml(TestDTO testDTO) {
        return ApiResponse.success(testService.queryTestByIdXml(testDTO));
    }
}

19 Source : SwaggerController.java
with Apache License 2.0
from yihonglei

/**
 * Swagger API 接口文档
 *
 * @author yihonglei
 */
@Validated
@RestController
@RequestMapping("/swagger/test")
@Api(value = "SwaggerController", tags = { "Swagger相关" })
public clreplaced SwaggerController {

    @Autowired
    private TestService testService;

    @ApiOperation(value = "查询用户信息", notes = "用户查询", response = ApiResponse.clreplaced)
    @PostMapping("/queryTestById")
    public ApiResponse queryTestById(TestDTO testDTO) {
        return ApiResponse.success(testService.queryTestById(testDTO));
    }
}

19 Source : UserController.java
with Apache License 2.0
from yeecode

@Validated
@RestController
@RequestMapping("/user")
public clreplaced UserController {

    @Autowired
    private UserBusiness userBusiness;

    @RequestMapping("/add")
    public Result add(@NotBlank String appName, @NotBlank String userKey, String userName, String appToken) {
        return userBusiness.add(appToken, new UserModel(appName, userKey, userName));
    }

    @RequestMapping("/deleteByKey")
    public Result deleteByKey(@NotBlank String appName, @NotBlank String userKey, String appToken) {
        return userBusiness.deleteByKey(appToken, new UserModel(appName, userKey, null));
    }

    @RequestMapping("/updateByKey")
    public Result updateByKey(@NotBlank String appName, @NotBlank String userKey, String userName, String appToken) {
        return userBusiness.updateByKey(appToken, new UserModel(appName, userKey, userName));
    }

    @RequestMapping("/queryByAppName")
    public Result queryByAppName(@NotBlank String appName, String appToken) {
        return userBusiness.queryByAppName(appToken, appName);
    }

    @RequestMapping("/queryByKey")
    public Result queryByKey(@NotBlank String appName, @NotBlank String userKey, String appToken) {
        return userBusiness.queryByKey(appToken, new UserModel(appName, userKey, null));
    }
}

19 Source : PermissionController.java
with Apache License 2.0
from yeecode

@Validated
@RestController
@RequestMapping("/permission")
public clreplaced PermissionController {

    @Autowired
    private PermissionBusiness permissionBusiness;

    @RequestMapping("/add")
    public Result add(@NotBlank String appName, @NotBlank String permKey, @NotBlank String name, String description, String appToken) {
        return permissionBusiness.add(appToken, new PermissionModel(appName, permKey, name, description));
    }

    @RequestMapping("/deleteByKey")
    public Result deleteByKey(@NotBlank String appName, @NotNull String permKey, String appToken) {
        return permissionBusiness.deleteByKey(appToken, new PermissionModel(appName, permKey, null, null));
    }

    @RequestMapping("/updateByKey")
    public Result updateByKey(@NotBlank String appName, @NotNull String permKey, @NotBlank String name, String description, String appToken) {
        return permissionBusiness.updateByKey(appToken, new PermissionModel(appName, permKey, name, description));
    }

    @RequestMapping("/queryByAppName")
    public Result queryByAppName(@NotBlank String appName, String appToken) {
        return permissionBusiness.queryByAppName(appToken, appName);
    }

    @RequestMapping("/queryByKey")
    public Result queryByKey(@NotBlank String appName, @NotNull String permKey, String appToken) {
        return permissionBusiness.queryByKey(appToken, new PermissionModel(appName, permKey, null, null));
    }
}

19 Source : DataSourceController.java
with Apache License 2.0
from yeecode

@Validated
@RestController
@RequestMapping("/datasource")
public clreplaced DataSourceController {

    @Autowired
    private TokenValidator tokenValidator;

    @Autowired
    private DataSourceBusiness dataSourceBusiness;

    @RequestMapping("/add")
    public Result add(@NotBlank String dataSourceName, @NotBlank String dataSourceUrl, @NotBlank String dataSourceDriver, String dataSourceUserName, String dataSourcePreplacedword, String adminToken) {
        if (tokenValidator.checkAdminToken(adminToken)) {
            return dataSourceBusiness.add(new DataSourceModel(dataSourceName, dataSourceUrl, dataSourceDriver, dataSourceUserName, dataSourcePreplacedword));
        } else {
            return ResultUtil.getFailResult(Sentence.ILLEGAL_ADMIN_TOKEN);
        }
    }

    @RequestMapping("/deleteByName")
    public Result deleteByName(@NotBlank String dataSourceName, String adminToken) {
        if (tokenValidator.checkAdminToken(adminToken)) {
            return dataSourceBusiness.deleteByName(dataSourceName);
        } else {
            return ResultUtil.getFailResult(Sentence.ILLEGAL_ADMIN_TOKEN);
        }
    }

    @RequestMapping("/update")
    public Result update(@NotBlank String dataSourceName, @NotBlank String dataSourceUrl, @NotBlank String dataSourceDriver, String dataSourceUserName, String dataSourcePreplacedword, String adminToken) {
        if (tokenValidator.checkAdminToken(adminToken)) {
            return dataSourceBusiness.updateByName(new DataSourceModel(dataSourceName, dataSourceUrl, dataSourceDriver, dataSourceUserName, dataSourcePreplacedword));
        } else {
            return ResultUtil.getFailResult(Sentence.ILLEGAL_ADMIN_TOKEN);
        }
    }

    @RequestMapping("/queryAll")
    public Result update(String adminToken) {
        if (tokenValidator.checkAdminToken(adminToken)) {
            return dataSourceBusiness.queryAll();
        } else {
            return ResultUtil.getFailResult(Sentence.ILLEGAL_ADMIN_TOKEN);
        }
    }

    @RequestMapping("/queryByName")
    public Result queryByName(@NotBlank String dataSourceName, String adminToken) {
        if (tokenValidator.checkAdminToken(adminToken)) {
            return dataSourceBusiness.queryByName(dataSourceName);
        } else {
            return ResultUtil.getFailResult(Sentence.ILLEGAL_ADMIN_TOKEN);
        }
    }
}

19 Source : CacheController.java
with Apache License 2.0
from yeecode

@Validated
@RestController
@RequestMapping("/cache")
public clreplaced CacheController {

    @Autowired
    private TokenValidator tokenValidator;

    @Autowired
    private CacheBusiness cacheBusiness;

    @RequestMapping("/add")
    public Result add(@NotBlank String cacheName, @NotBlank String cacheUrl, String cachePreplacedword, String adminToken) {
        if (tokenValidator.checkAdminToken(adminToken)) {
            return cacheBusiness.add(new CacheModel(cacheName, cacheUrl, cachePreplacedword));
        } else {
            return ResultUtil.getFailResult(Sentence.ILLEGAL_ADMIN_TOKEN);
        }
    }

    @RequestMapping("/deleteByName")
    public Result deleteByName(@NotBlank String cacheName, String adminToken) {
        if (tokenValidator.checkAdminToken(adminToken)) {
            return cacheBusiness.deleteByName(cacheName);
        } else {
            return ResultUtil.getFailResult(Sentence.ILLEGAL_ADMIN_TOKEN);
        }
    }

    @RequestMapping("/update")
    public Result update(@NotBlank String cacheName, @NotBlank String cacheUrl, String cachePreplacedword, String adminToken) {
        if (tokenValidator.checkAdminToken(adminToken)) {
            return cacheBusiness.updateByName(new CacheModel(cacheName, cacheUrl, cachePreplacedword));
        } else {
            return ResultUtil.getFailResult(Sentence.ILLEGAL_ADMIN_TOKEN);
        }
    }

    @RequestMapping("/queryAll")
    public Result update(String adminToken) {
        if (tokenValidator.checkAdminToken(adminToken)) {
            return cacheBusiness.queryAll();
        } else {
            return ResultUtil.getFailResult(Sentence.ILLEGAL_ADMIN_TOKEN);
        }
    }

    @RequestMapping("/queryByName")
    public Result queryByName(@NotBlank String cacheName, String adminToken) {
        if (tokenValidator.checkAdminToken(adminToken)) {
            return cacheBusiness.queryByName(cacheName);
        } else {
            return ResultUtil.getFailResult(Sentence.ILLEGAL_ADMIN_TOKEN);
        }
    }
}

19 Source : AuthController.java
with Apache License 2.0
from yeecode

@Validated
@RestController
@RequestMapping("/auth")
public clreplaced AuthController {

    @Autowired
    private AuthBusiness authBusiness;

    @RequestMapping("/addUserXRole")
    public Result addUserXRole(@NotBlank String appName, @NotBlank String userKey, @NotNull String roleName, String requestSource, String appToken) {
        RequestSource rs;
        if (requestSource == null) {
            rs = RequestSource.Interface;
        } else {
            rs = RequestSource.valueOf(requestSource);
        }
        return authBusiness.addUserXRole(appToken, appName, userKey, roleName, rs);
    }

    @RequestMapping("/deleteUserXRole")
    public Result deleteUserXRole(@NotBlank String appName, @NotBlank String userKey, @NotNull String roleName, String requestSource, String appToken) {
        RequestSource rs;
        if (requestSource == null) {
            rs = RequestSource.Interface;
        } else {
            rs = RequestSource.valueOf(requestSource);
        }
        return authBusiness.deleteUserXRole(appToken, appName, userKey, roleName, rs);
    }

    @RequestMapping("/addRoleXPermission")
    public Result addRoleXPermission(@NotBlank String appName, @NotNull String roleName, @NotNull String permKey, String appToken) {
        return authBusiness.addRoleXPermission(appToken, appName, roleName, permKey);
    }

    @RequestMapping("/deleteRoleXPermission")
    public Result deleteRoleXPermission(@NotBlank String appName, @NotNull String roleName, @NotNull String permKey, String appToken) {
        return authBusiness.deleteRoleXPermission(appToken, appName, roleName, permKey);
    }

    @RequestMapping("/fastQueryPermissionCodesByUserKey")
    public Result fastQueryPermissionCodesByUserKey(@NotBlank String appName, @NotBlank String userKey) {
        return authBusiness.fastQueryPermissionCodesByUserKey(appName, userKey);
    }
}

19 Source : ApplicationController.java
with Apache License 2.0
from yeecode

@Validated
@RestController
@RequestMapping("/application")
public clreplaced ApplicationController {

    @Autowired
    private TokenValidator tokenValidator;

    @Autowired
    private ApplicationBusiness applicationBusiness;

    @RequestMapping("/add")
    public Result add(@NotBlank String appName, String appToken, String dataSourceName, String cacheName, String adminToken) {
        if (tokenValidator.checkAdminToken(adminToken)) {
            return applicationBusiness.add(new ApplicationModel(appName, appToken, dataSourceName, cacheName));
        } else {
            return ResultUtil.getFailResult(Sentence.ILLEGAL_ADMIN_TOKEN);
        }
    }

    @RequestMapping("/deleteByName")
    public Result deleteByName(@NotBlank String appName, String adminToken) {
        if (tokenValidator.checkAdminToken(adminToken)) {
            return applicationBusiness.deleteByName(appName);
        } else {
            return ResultUtil.getFailResult(Sentence.ILLEGAL_ADMIN_TOKEN);
        }
    }

    @RequestMapping("/update")
    public Result update(@NotBlank String appName, String appToken, @NotBlank String dataSourceName, String cacheName, String adminToken) {
        if (tokenValidator.checkAdminToken(adminToken)) {
            return applicationBusiness.updateByName(new ApplicationModel(appName, appToken, dataSourceName, cacheName));
        } else {
            return ResultUtil.getFailResult(Sentence.ILLEGAL_ADMIN_TOKEN);
        }
    }

    @RequestMapping("/queryAll")
    public Result update(String adminToken) {
        if (tokenValidator.checkAdminToken(adminToken)) {
            return applicationBusiness.queryAll();
        } else {
            return ResultUtil.getFailResult(Sentence.ILLEGAL_ADMIN_TOKEN);
        }
    }

    @RequestMapping("/queryByName")
    public Result queryByName(@NotBlank String appName, String adminToken) {
        if (tokenValidator.checkAdminToken(adminToken)) {
            return applicationBusiness.queryByName(appName);
        } else {
            return ResultUtil.getFailResult(Sentence.ILLEGAL_ADMIN_TOKEN);
        }
    }
}

See More Examples