Java 类org.springframework.validation.annotation.Validated 实例源码

项目:batch-scheduler    文件:TaskDefineController.java   
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "新增任务信息", notes = "向系统中添加新的任务,任务必须是存储过程,shell脚本,cmd脚本,可执行jar包,二进制文件中的一种")
public String add(@Validated TaskDefineEntity taskDefineEntity, BindingResult bindingResult, HttpServletResponse response, HttpServletRequest request) {
    // 校验参数信息
    if (bindingResult.hasErrors()) {
        for (ObjectError m : bindingResult.getAllErrors()) {
            response.setStatus(421);
            return Hret.error(421, m.getDefaultMessage(), null);
        }
    }

    RetMsg retMsg = taskDefineService.add(parse(request));
    if (retMsg.checkCode()) {
        return Hret.success(retMsg);
    }
    response.setStatus(retMsg.getCode());
    return Hret.error(retMsg);
}
项目:WeatherSystem    文件:UserController.java   
/**
 * 更新密码
 * @param user
 * @param validResult
 * @return
 */
@Permission(value = {Privilege.USER, Privilege.ADMIN})
@RequestMapping(value = MappingURL.USER_PASSWORD_UPDATE, method = RequestMethod.PUT)
public ReturnPureNotifyApi updatePassword(
        @Validated({UserPassword.class}) User user,
        BindingResult validResult,
        HttpServletRequest request
        ){
    if (validResult.hasErrors()){
        throw new ValidationException(validResult.getFieldErrors());
    }else if (userService.find(user.getUserId()) == null){
        throw new NotExistedException("userId", user.getUserId());
    }
    TokenUser tokenUser = JavaWebTokenUtil.unsign(request.getHeader("appSecret"), TokenUser.class);
    assert tokenUser != null;
    //是管理员,为所欲为
    if (userService.find(tokenUser.getUserId()).getPrivilege() == Privilege.ADMIN.getCode()){
        userService.updatePassword(user);
        return new ReturnPureNotifyApi(ApiStatus.SUCCESS);
    }else if((tokenUser.getUserId() != user.getUserId())) {//不是管理员但是想更改别人的抛出异常
        throw new NoPermissionException();
    }
    userService.updatePassword(user);
    return new ReturnPureNotifyApi(ApiStatus.SUCCESS);
}
项目:TITAN    文件:MonitorSetController.java   
/**
 * @desc 分页列表查询
 *
 * @author liuliang
 *
 * @param pr
 * @return ComponentResult<Pager<MonitorSetBO>>
 */
@RequestMapping(value = "/list")
@ResponseBody
public ComponentResult<Pager<MonitorSetBO>> list(@Validated PageRequestBO pr,BindingResult br) {
    ComponentResult<Pager<MonitorSetBO>> componentResult = new ComponentResult<Pager<MonitorSetBO>>();
    //参数校验
    Result validateResult = ValidatorUtil.getValidResult(br);
    if(ResultUtil.isfail(validateResult)) {
        return ResultUtil.copy(validateResult, componentResult);
    }
    //查询
    try {
        int totalCount = monitorSetService.getCount();
        List<MonitorSetBO> records = monitorSetService.getDataList(pr.getPageIndex(),pr.getPageSize());

        componentResult.setData(new Pager<MonitorSetBO>(totalCount, records));
        return ResultUtil.success(componentResult);
    } catch (Exception e) {
        logger.error("分页获取数据异常,params:{}",pr.toString(),e);
    }
    //失败返回
    return ResultUtil.fail(ErrorCode.QUERY_DB_ERROR,componentResult);
}
项目:TITAN    文件:SceneController.java   
/**
 * @desc 查询场景详情
 *
 * @author liuliang
 *
 * @param sceneId 场景ID
 * @return ComponentResult<SceneDetailBO>
 */
@RequestMapping(value = "/get")
@ResponseBody
public ComponentResult<SceneDetailBO> get(@Validated(Groups.Query.class) SceneBO sceneBO,BindingResult br) {
    ComponentResult<SceneDetailBO> componentResult = new ComponentResult<SceneDetailBO>();
    //参数校验
    Result validateResult = ValidatorUtil.getValidResult(br);
    if(ResultUtil.isfail(validateResult)) {
        return ResultUtil.copy(validateResult, componentResult);
    }
    //查询
    try {
        Scene scene = sceneService.getScene(sceneBO.getSceneId());
        if(null != scene){
            String containLinkid = scene.getContainLinkid();
            List<Link> linkList = linkService.getLinkListByIds(containLinkid);

            componentResult.setData(new SceneDetailBO(scene, linkList));
            return ResultUtil.success(componentResult);
        }
    } catch (Exception e) {
        logger.error("查询数据详情异常,params:{}",sceneBO.toString(),e);
    }
    //失败返回
    return ResultUtil.fail(ErrorCode.QUERY_DB_ERROR,componentResult);
}
项目:TITAN    文件:LinkController.java   
/**
 * @desc 分页获取链路数据
 *
 * @author liuliang
 *
 * @param request
 * @param response
 * @return ComponentResult<Pager<LinkBO>>
 */
@RequestMapping(value = "/list")
@ResponseBody
public ComponentResult<Pager<LinkBO>> list(@Validated PageRequestBO pr,BindingResult br) {
    ComponentResult<Pager<LinkBO>> componentResult = new ComponentResult<Pager<LinkBO>>();
    //参数校验
    Result validateResult = ValidatorUtil.getValidResult(br);
    if(ResultUtil.isfail(validateResult)) {
        return ResultUtil.copy(validateResult, componentResult);
    }
    //查询
    try {
        int totalCount = linkService.getLinkCount(pr.getFilterCondition());
        List<LinkBO> records = linkService.getLinkList(pr.getFilterCondition(),pr.getPageIndex(),pr.getPageSize());

        componentResult.setData(new Pager<LinkBO>(totalCount, records));
        return ResultUtil.success(componentResult);
    } catch (Exception e) {
        logger.error("分页获取数据异常,params:{}",pr.toString(),e);
    }
    //失败返回
    return ResultUtil.fail(ErrorCode.QUERY_DB_ERROR,componentResult);
}
项目:TITAN    文件:LinkController.java   
/**
 * @desc 新增链路
 *
 * @author liuliang
 *
 * @param linkBO 链路BO
 * @return Result
 */
@RequestMapping(value = "/add")
@ResponseBody
public Result add(@Validated(Groups.Add.class) LinkBO linkBO,BindingResult br){
    Result result = new Result();
    //参数校验
    Result validateResult = ValidatorUtil.getValidResult(br);
    if(ResultUtil.isfail(validateResult)) {
        return ResultUtil.copy(validateResult, result);
    }
    //新增
    try {
        int addResult = linkService.addLink(linkBO);
        if(0 < addResult) {
            return ResultUtil.success(result);
        }
    } catch(DuplicateKeyException de){
        logger.error("新增数据异常,链路名重复,params:{}",linkBO.toString(),de);
        return ResultUtil.fail(ErrorCode.UPDATE_DB_ERROR,"链路名已存在",result);
    } catch (Exception e) {
        logger.error("新增数据异常,params:{}",linkBO.toString(),e);
    }
    //返回失败结果
    return ResultUtil.fail(ErrorCode.UPDATE_DB_ERROR,result);
}
项目:TITAN    文件:LinkController.java   
/**
 * @desc 查询链路详情
 *
 * @author liuliang
 *
 * @param id 链路ID
 * @return ComponentResult<Link>
 */
@RequestMapping(value = "/get")
@ResponseBody
public ComponentResult<Link> get(@Validated(Groups.Query.class) LinkBO linkBO,BindingResult br) {
    ComponentResult<Link> componentResult = new ComponentResult<Link>();
    //参数校验
    Result validateResult = ValidatorUtil.getValidResult(br);
    if(ResultUtil.isfail(validateResult)) {
        return ResultUtil.copy(validateResult, componentResult);
    }
    //查询
    try {
        Link link = linkService.getLink(linkBO.getLinkId());
        if(null != link) {
            componentResult.setData(link);
            return ResultUtil.success(componentResult);
        }
    } catch (Exception e) {
        logger.error("查询数据详情异常,params:{}",linkBO.toString(),e);
    }
    //失败返回
    return ResultUtil.fail(ErrorCode.QUERY_DB_ERROR,componentResult);
}
项目:TITAN    文件:AutomaticTaskController.java   
/**
 * @desc 分页列表
 *
 * @author liuliang
 *
 * @param pr
 * @param br
 * @return
 */
@RequestMapping(value = "/list")
@ResponseBody
public ComponentResult<Pager<AutomaticTaskBO>> list(@Validated PageRequestBO pr,BindingResult br) {
    ComponentResult<Pager<AutomaticTaskBO>> componentResult = new ComponentResult<Pager<AutomaticTaskBO>>();
    //参数校验
    Result validateResult = ValidatorUtil.getValidResult(br);
    if(ResultUtil.isfail(validateResult)) {
        return ResultUtil.copy(validateResult, componentResult);
    }
    //查询
    try {
        int totalCount = automaticTaskService.getCount();
        List<AutomaticTaskBO> records = automaticTaskService.getDataList(pr.getPageIndex(),pr.getPageSize());

        componentResult.setData(new Pager<AutomaticTaskBO>(totalCount, records));
        return ResultUtil.success(componentResult);
    } catch (Exception e) {
        logger.error("分页获取数据异常,params:{}",pr.toString(),e);
    }
    //失败返回
    return ResultUtil.fail(ErrorCode.QUERY_DB_ERROR,componentResult);
}
项目:TITAN    文件:AutomaticTaskController.java   
/**
 * @desc 更新
 *
 * @author liuliang
 *
 * @param automaticTaskBO
 * @param br
 * @return
 */
@RequestMapping(value = "/update")
@ResponseBody
public Result update(@Validated(Groups.Update.class) AutomaticTaskBO automaticTaskBO,BindingResult br) {
    Result result = new Result();
    //参数校验
    Result validateResult = ValidatorUtil.getValidResult(br);
    if(ResultUtil.isfail(validateResult)) {
        return ResultUtil.copy(validateResult, result);
    }
    //更新
    try {
        int updateResult = automaticTaskService.update(automaticTaskBO);
        if (0 < updateResult) {
            // 同步定时任务
            this.syncAutomaticTask(automaticTaskBO, TaskSyncTypeEnum.UPDATE.value);
            return ResultUtil.success(result);
        }
    } catch (Exception e) {
        logger.error("更新数据异常,params:{}",automaticTaskBO.toString(),e);
    }
    //失败返回
    return ResultUtil.fail(ErrorCode.UPDATE_DB_ERROR,result);
}
项目:TITAN    文件:AutomaticTaskController.java   
/**
 * @desc 查
 *
 * @author liuliang
 *
 * @param automaticTaskBO
 * @param br
 * @return
 */
@RequestMapping(value = "/get")
@ResponseBody
public ComponentResult<AutomaticTask> get(@Validated(Groups.Query.class) AutomaticTaskBO automaticTaskBO,BindingResult br) {
    ComponentResult<AutomaticTask> componentResult = new ComponentResult<AutomaticTask>();
    //参数校验
    Result validateResult = ValidatorUtil.getValidResult(br);
    if(ResultUtil.isfail(validateResult)) {
        return ResultUtil.copy(validateResult, componentResult);
    }
    //查询
    try {
        AutomaticTask automaticTask = automaticTaskService.getDataDetail(automaticTaskBO.getAutomaticTaskId());
        if(null != automaticTask) {
            componentResult.setData(automaticTask);
            return ResultUtil.success(componentResult);
        }
    } catch (Exception e) {
        logger.error("查询数据详情异常,params:{}",automaticTaskBO.toString(),e);
    }       
    //失败返回
    return ResultUtil.fail(ErrorCode.QUERY_DB_ERROR,componentResult);
}
项目:webDemo    文件:DemoController.java   
@GetMapping("/userListByPage.json")
    @ResponseBody
    @ApiOperation(value = "分页查询用户列表", notes = "不传分页默认1页15条")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码"),
            @ApiImplicitParam(name = "pageSize", value = "条数")
    })
    public JsonResponse getUserList(@Validated({Search.class}) UserQuery user,
                                    BindingResult bindingResult,
                                    PageKey pageKey)
            throws ValidateException {

        BindingResultUtil.validateResult(bindingResult);
        Page<Object> objects = PageHelper.startPage(pageKey.getPage(), pageKey.getPageSize(), true);
        UserExample example = new UserExample();
        example.createCriteria().andUserNameLike(StringUtil.turn2LikeStr(user.getName()));
        JsonResponse json = new JsonResponse();
        List<User> users = userMapper.selectByExample(example);
        json.putData("list", users);
        System.out.println("**********共有" + objects.getTotal() + "条数据*********");

//        redisTemplate.opsForList().rightPushAll("userList", users);
        return json;
    }
项目:airsonic    文件:UserSettingsController.java   
@RequestMapping(method = RequestMethod.POST)
protected String doSubmitAction(@ModelAttribute("command") @Validated UserSettingsCommand command, BindingResult bindingResult, RedirectAttributes redirectAttributes) throws Exception {

    if(!bindingResult.hasErrors()) {
        if (command.isDeleteUser()) {
            deleteUser(command);
        } else if (command.isNewUser()) {
            createUser(command);
        } else {
            updateUser(command);
        }
        redirectAttributes.addFlashAttribute("settings_reload", true);
        redirectAttributes.addFlashAttribute("settings_toast", true);
    } else {
        redirectAttributes.addFlashAttribute("command", command);
        redirectAttributes.addFlashAttribute("org.springframework.validation.BindingResult.command", bindingResult);
        redirectAttributes.addFlashAttribute("userIndex", getUserIndex(command));
    }

    return "redirect:userSettings.view";
}
项目:spring_mvc_demo    文件:InputController.java   
@RequestMapping(value = "/addStudent",method = RequestMethod.POST)
    public String addStudent(@ModelAttribute("student") @Validated Student student, BindingResult bindingResult,ModelMap model){
//        if(bindingResult.hasErrors()){
//            return "addStudent";
//        }
        System.out.println("id = "+student.getId());
        model.addAttribute("id",student.getId());
        model.addAttribute("name",student.getName());
        model.addAttribute("age",student.getAge());
        model.addAttribute("receivePaper",student.isReceivePaper());
        model.addAttribute("gender",student.getGender());
        model.addAttribute("color",student.getColor());
        model.addAttribute("city",student.getCity());
        model.addAttribute("tec",student.getTec());
        return "result";
    }
项目:batch-scheduler    文件:DomainController.java   
/**
 * 新增域
 */
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "新增域信息", notes = "添加新的域信息,新增的域默认授权给创建人")
@ApiImplicitParam(name = "domain_id", value = "域编码", required = true, dataType = "String")
public String add(@Validated DomainEntity domainEntity, BindingResult bindingResult, HttpServletResponse response, HttpServletRequest request) {
    if (bindingResult.hasErrors()) {
        for (ObjectError m : bindingResult.getAllErrors()) {
            response.setStatus(421);
            return Hret.error(421, m.getDefaultMessage(), null);
        }
    }

    String userId = JwtService.getConnUser(request).getUserId();
    domainEntity.setDomainModifyUser(userId);
    domainEntity.setCreateUserId(userId);
    RetMsg retMsg = domainService.add(domainEntity);

    if (retMsg.checkCode()) {
        return Hret.success(retMsg);
    }

    response.setStatus(retMsg.getCode());
    return Hret.error(retMsg);
}
项目:batch-scheduler    文件:TaskDefineController.java   
@RequestMapping(method = RequestMethod.PUT)
@ResponseBody
public String update(@Validated TaskDefineEntity taskDefineEntity, BindingResult bindingResult, HttpServletResponse response, HttpServletRequest request) {
    if (bindingResult.hasErrors()) {
        for (ObjectError m : bindingResult.getAllErrors()) {
            response.setStatus(421);
            return Hret.error(421, m.getDefaultMessage(), null);
        }
    }

    RetMsg retMsg = taskDefineService.update(parse(request));
    if (!retMsg.checkCode()) {
        response.setStatus(retMsg.getCode());
        return Hret.error(retMsg);
    }
    return Hret.success(retMsg);
}
项目:spring-boot-start-current    文件:AuthenticationController.java   
/**
 * 认证
 *
 * @param user   : 表单
 * @param device : 终端
 * @return token
 * @throws AuthenticationException 认证失败则会抛异常
 */
@PostMapping
public ResponseEntity createAuthenticationToken ( @Validated( ValidatedGroups.Special.class ) @RequestBody UserForm user ,
                                                  Device device ) throws AuthenticationException {
    // 执行安全认证
    final Authentication authentication = authenticationManager.authenticate(
        new UsernamePasswordAuthenticationToken(
            user.getUsername() ,
            user.getPassword()
        )
    );
    SecurityContextHolder.getContext().setAuthentication( authentication );
    final UserDetails userDetails = ( UserDetails ) authentication.getPrincipal();
    final String      token       = jwtTokenUtil.generateToken( userDetails , device );
    // 返回
    return new ResponseEntityPro().add( "token" , token )
                                  .add( "user" , userDetails )
                                  .flushBodyByFilterFields(
                                      "*,-user.password,-user.lastPasswordResetDate,-user.createTime,-user.updateTime,-user.remark,-user.enabled"
                                  ).buildOk();
}
项目:OperatieBRP    文件:LeveringsautorisatieController.java   
/**
 * Slaat een gewijzigd item op.
 * @param item item
 * @param leveringsautorisatieId id van de leveringsautorisatie
 * @param dienstbundelId id van de dienstbundel
 * @return item
 * @throws NotFoundException wanneer het item niet gevonden kan worden om te updaten
 */
@RequestMapping(value = "/{id}/dienstbundels/{did3}/diensten", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
public final Dienst saveDienst(
        @PathVariable(value = "id") final Integer leveringsautorisatieId,
        @PathVariable(value = "did3") final Integer dienstbundelId,
        @Validated @RequestBody final Dienst item) throws NotFoundException {
    return new SaveTransaction<Dienst>(getTransactionTemplate()).execute(() -> {
        final Leveringsautorisatie leveringsautorisatie = get(leveringsautorisatieId);
        final SoortDienstRepository soortDienstRepository = new SoortDienstRepository();
        if (!soortDienstRepository.filterEnumOpStelsel(Stelsel.GBA.equals(leveringsautorisatie.getStelsel())).contains(item.getSoortDienst())) {
            throw new IllegalArgumentException("Ongeldige soort dienst voor deze GBA autorisatie.");
        }

        item.setDienstbundel(dienstbundelRepository.findOne(dienstbundelId));

        return dienstController.save(item);
    });
}
项目:OperatieBRP    文件:VrijBerichtController.java   
@Override
public VrijBericht save(@Validated @RequestBody final VrijBericht item) throws ErrorHandler.NotFoundException {
    boolean nieuwItem = false;
    if (item.getId() == null) {
        // Bepaling nieuw item via EntityManager.contains
        nieuwItem = true;
    }
    VrijBericht vrijBericht = item;
    if (nieuwItem) {
        final List<VrijBerichtPartij> teVerwijderenPartijen = Lists.newArrayList();
        for (VrijBerichtPartij vrijBerichtPartij : vrijBericht.getVrijBerichtPartijen()) {
            final String partijCode = vrijBerichtPartij.getPartij().getCode();
            try {
                vrijBerichtClientService.verstuurVrijBericht(vrijBericht, partijCode);
            } catch (VrijBerichtClientService.VrijBerichtClientException e) {
                LOG.error("Kon vrij bericht niet versturen. Bericht voor partij met code {} is niet verstuurd: {}", partijCode, e);
                teVerwijderenPartijen.add(vrijBerichtPartij);
            }
        }
        if (!teVerwijderenPartijen.isEmpty()) {
            vrijBericht.getVrijBerichtPartijen().removeAll(teVerwijderenPartijen);
        }
    }
    vrijBericht = super.save(item);
    return vrijBericht;
}
项目:JuniperBotJ    文件:RankingController.java   
@RequestMapping(value = "/ranking/{serverId}", method = RequestMethod.POST)
public ModelAndView save(
        @PathVariable long serverId,
        @Validated @ModelAttribute("config") RankingConfigDto config,
        BindingResult result) {
    validateGuildId(serverId);
    if (result.hasErrors()) {
        return createModel("ranking.admin", serverId)
                .addObject("prefix", configService.getPrefix(serverId))
                .addObject("rolesManageable", hasPermission(serverId, Permission.MANAGE_ROLES))
                .addObject("roles", getRoles(serverId));
    }
    rankingDao.saveConfig(config, serverId);
    flash.success("flash.rating.save.success.message");
    return view(serverId, false);
}
项目:spring-jdbc-orm    文件:FreightController.java   
@ApiOperation(value = "保存")
@RequestMapping(value = "save", method = RequestMethod.POST)
public Map<String, Object> save(@Validated FreightBody body){

    Freight target = new Freight();
    BeanUtils.copyProperties(body, target);
    service.save(target);

    return successData("data", body);
}
项目:meparty    文件:BaseCrudController.java   
/**
 * {@inheritDoc}
 */
@Override
public final RestResponse create(@Validated @RequestBody final DtoT dto)
    throws DtoCrudException {
  Serializable id = doInsert(dto);
  String location = getMappingUrlOfController() + "/" + id.toString();

  return RestResponse.of(ResponseEntity
      .status(HttpStatus.CREATED)
      .header("Location", location)
      .build());
}
项目:spring-boot-oauth2-demo    文件:CityController.java   
@PostMapping("/update")
public ModelResult<City> update(@Validated @RequestBody UpdateCityRequestDto updateCityRequestDto) {
    City city = cityDtoMapper.cityDto2City(updateCityRequestDto);
    ModelResult<City> modelResult = new ModelResult<>();
    int count = cityMapper.updateByPrimaryKeySelective(city);
    if (count == 1) {
        city = cityMapper.selectByPrimaryKey(city.getId());
        modelResult.setData(city);
    } else {
        modelResult.setReturnCode("-1");
        modelResult.setReturnMsg("操作数据库失败");
    }
    return modelResult;
}
项目:Spring-5.0-Cookbook    文件:FormController.java   
@RequestMapping(method=RequestMethod.POST)
public String submitForm(Model model, @ModelAttribute("employeeForm") @Validated EmployeeForm employeeForm, BindingResult result ){
    model.addAttribute("employeeForm", employeeForm);
    validator.validate(employeeForm, result);
    if(result.hasErrors()){
        return "form_page";
    }
    return "success_page";
}
项目:Spring-5.0-Cookbook    文件:FormController.java   
@RequestMapping(method=RequestMethod.POST)
public String submitForm(Model model, @ModelAttribute("employeeForm") @Validated EmployeeForm employeeForm, BindingResult result ){
    model.addAttribute("employeeForm", employeeForm);
    validator.validate(employeeForm, result);
    if(result.hasErrors()){
        return "form_page";
    }
    return "success_page";
}
项目:WeatherSystem    文件:UserController.java   
/**
 * 用户注册接口
 * @param user
 * @return
 */
@Permission(value = {Privilege.ADMIN, Privilege.USER})
@RequestMapping(value = MappingURL.USER_REGISTER_URL, method = RequestMethod.POST)
public ReturnPureNotifyApi register(
        @Validated( { UserAdd.class }) User user,
        BindingResult validResult
){
    if (validResult.hasErrors()){
        throw new ValidationException(validResult.getFieldErrors());
    }else if (userService.isExist(user.getUsername())){
        throw new ExistedException("username", user.getUsername());
    }
    userService.add(user);
    return new ReturnPureNotifyApi(ApiStatus.SUCCESS);
}
项目:WeatherSystem    文件:UserController.java   
/**
 * 更新用户基本属性 [如果是管理员,可以更改用户权限]
 * @param user
 * @param request
 * @param validResult
 * @return
 */
@Permission(value = {Privilege.USER, Privilege.ADMIN})
@RequestMapping(value = MappingURL.USER_PROFILE_UPDATE, method = RequestMethod.PUT)
public ReturnPureNotifyApi update(
        @Validated({UserUpdate.class}) User user,
        BindingResult validResult,
        HttpServletRequest request
        ){
    if (validResult.hasErrors()){
        throw new ValidationException(validResult.getFieldErrors());
    }else if (userService.find(user.getUserId()) == null){
        throw new NotExistedException("userId", user.getUserId());
    }
    TokenUser tokenUser = JavaWebTokenUtil.unsign(request.getHeader("appSecret"), TokenUser.class);
    assert tokenUser != null;
    if (userService.find(tokenUser.getUserId()).getPrivilege() == Privilege.ADMIN.getCode()){
        //如果操作员是管理员,可以更改自己以及其他用户的信息,包括权限
        userService.superUpdate(user);
    }else {
        //如果操作员是普通用户,当用户id和要更改的用户id不一致,返回没有权限异常
        if(tokenUser.getUserId() != user.getUserId()){
            throw new NoPermissionException();
        }
        userService.update(user);
    }
    return new ReturnPureNotifyApi(ApiStatus.SUCCESS);
}
项目:spring-boot-graph-day    文件:PersonController.java   
@RequestMapping(method = RequestMethod.PUT, path = "/{id:\\d+}/parents")
public Map<String, PersonDto> setParents(
        @PathVariable("id") long personId,
        @Validated @RequestBody SetParentsDto dto) {

    repository.setParents(personId, dto.getFatherId(), dto.getMotherId());

    return getParents(personId);
}
项目:TITAN    文件:MonitorSetController.java   
/**
 * @desc 新增
 *
 * @author liuliang
 *
 * @param monitorSetBO
 * @param br
 * @return
 */
@RequestMapping(value = "/add")
@ResponseBody
public Result add(@Validated(Groups.Add.class) MonitorSetBO monitorSetBO,BindingResult br) {
    Result result = new Result();
    //参数校验
    Result validateResult = ValidatorUtil.getValidResult(br);
    if(ResultUtil.isfail(validateResult)) {
        return ResultUtil.copy(validateResult, result);
    }
    //新增
    try {
        Scene scene = sceneService.getSceneByName(monitorSetBO.getSceneName());
        if(null == scene) {
            return ResultUtil.fail(ErrorCode.REQUEST_PARA_ERROR,"场景名不存在",result);
        }
        monitorSetBO.setSceneId(scene.getSceneId());
        int addResult = monitorSetService.add(monitorSetBO);
        if(0 < addResult) {
            return ResultUtil.success(result);
        }
    } catch (DuplicateKeyException de) {
        logger.error("新增异常,唯一索引重复,params:{}", monitorSetBO.toString(), de);
        return ResultUtil.fail(ErrorCode.UPDATE_DB_ERROR,"场景名重复",result);
    } catch (Exception e) {
        logger.error("新增数据异常,params:{}",monitorSetBO.toString(),e);
    }
    //返回失败结果
    return ResultUtil.fail(ErrorCode.UPDATE_DB_ERROR,result);
}
项目:TITAN    文件:MonitorSetController.java   
/**
 * @desc 更新
 *
 * @author liuliang
 *
 * @param monitorSetBO
 * @param br
 * @return
 */
@RequestMapping(value = "/update")
@ResponseBody
public Result update(@Validated(Groups.Update.class) MonitorSetBO monitorSetBO,BindingResult br) {
    Result result = new Result();
    //参数校验
    Result validateResult = ValidatorUtil.getValidResult(br);
    if(ResultUtil.isfail(validateResult)) {
        return ResultUtil.copy(validateResult, result);
    }
    //更新
    try {
        Scene scene = sceneService.getSceneByName(monitorSetBO.getSceneName());
        if(null == scene) {
            return ResultUtil.fail(ErrorCode.REQUEST_PARA_ERROR,"场景名不存在",result);
        }
        int updateResult = monitorSetService.update(monitorSetBO);
        if(0 < updateResult) {
            return ResultUtil.success(result);
        }
    } catch (DuplicateKeyException de) {
        logger.error("更新异常,唯一索引重复,params:{}", monitorSetBO.toString(), de);
        return ResultUtil.fail(ErrorCode.UPDATE_DB_ERROR,"场景名重复",result);
    } catch (Exception e) {
        logger.error("更新数据异常,params:{}",monitorSetBO.toString(),e);
    }
    //失败返回
    return ResultUtil.fail(ErrorCode.UPDATE_DB_ERROR,result);
}
项目:TITAN    文件:MonitorSetController.java   
/**
 * @desc 压测报告详情页 图表数据
 *
 * @author liuliang
 *
 * @param reportBO
 * @return
 */
@RequestMapping(value = "/chartdetail")
@ResponseBody
public ComponentResult<Object> chartdetail(@Validated(Groups.Query.class) ReportBO reportBO,BindingResult br) {
    ComponentResult<Object> componentResult = new ComponentResult<Object>();
    try {
        Map<String,List<Monitor>> map = monitorSetService.getReportDetailMonitorData(reportBO);
        componentResult.setData(map);
        return ResultUtil.success(componentResult);
    } catch (Exception e) {
        logger.error("压测报告详情,查询监控数据DB异常",e);
    }
    return ResultUtil.fail(ErrorCode.QUERY_DB_ERROR,componentResult);
}
项目:TITAN    文件:SceneController.java   
/**
 * @desc 分页获取场景数据
 *
 * @author liuliang
 *
 * @param request
 * @param response
 * @return ComponentResult<Pager<SceneBO>>
 */
@RequestMapping(value = "/list")
@ResponseBody
public ComponentResult<Pager<SceneBO>> list(@Validated PageRequestBO pr,BindingResult br) {
    ComponentResult<Pager<SceneBO>> componentResult = new ComponentResult<Pager<SceneBO>>();
    //参数校验
    Result validateResult = ValidatorUtil.getValidResult(br);
    if(ResultUtil.isfail(validateResult)) {
        return ResultUtil.copy(validateResult, componentResult);
    }
    //查询
    try {
        int totalCount = sceneService.getSceneCount(pr.getFilterCondition());
        List<SceneBO> records = sceneService.getSceneList(pr.getFilterCondition(),pr.getPageIndex(),pr.getPageSize());
        if(null != records) {
            for(SceneBO sceneBO:records){
                AutomaticTask automaticTask = automaticTaskService.getDataDetailBySceneId(sceneBO.getSceneId());
                if(null != automaticTask){
                    sceneBO.setIsAutomatic(1);
                }
            }
        }
        componentResult.setData(new Pager<SceneBO>(totalCount, records));
        return ResultUtil.success(componentResult);
    } catch (Exception e) {
        logger.error("分页获取数据异常,pageRequestBO:{}",pr.toString(),e);
    }
    //失败返回
    return ResultUtil.fail(ErrorCode.QUERY_DB_ERROR,componentResult);
}
项目:TITAN    文件:SceneController.java   
/**
 * @desc 新增场景
 *
 * @author liuliang
 *
 * @param sceneBO 场景BO
 * @return Result
 */
@RequestMapping(value = "/add")
@ResponseBody
public Result add(@Validated(Groups.Add.class) SceneBO sceneBO,BindingResult br){
    Result result = new Result();
    //参数校验
    Result validateResult = ValidatorUtil.getValidResult(br);
    if(ResultUtil.isfail(validateResult)) {
        return ResultUtil.copy(validateResult, result);
    }
    long totalRequest = sceneBO.getTotalRequest();
    long concurrentUser = sceneBO.getConcurrentUser();
    long useAgent = sceneBO.getUseAgent();
    long concurrentStart = sceneBO.getConcurrentStart();
    if( (totalRequest < concurrentUser) || (concurrentUser < useAgent) 
            || (0 != (totalRequest % concurrentUser)) || (0 != (concurrentUser % useAgent))){
        return ResultUtil.fail(ErrorCode.REQUEST_PARA_ERROR,"总请求数、并发用户数、agent数倍数关系错误",result);
    }
    if(concurrentStart > concurrentUser){
        return ResultUtil.fail(ErrorCode.REQUEST_PARA_ERROR,"起始并发用户数不能大于并发用户数",result);
    }
    //新增
    try {
        int addResult = sceneService.addScene(sceneBO);
        if(0 < addResult) {
            return ResultUtil.success(result);
        }
    } catch(DuplicateKeyException de){
        logger.error("新增数据异常,场景名重复,params:{}",sceneBO.toString(),de);
        return ResultUtil.fail(ErrorCode.UPDATE_DB_ERROR,"场景名已存在",result);
    } catch (Exception e) {
        logger.error("新增数据异常,params:{}",sceneBO.toString(),e);
    }
    //返回失败结果
    return ResultUtil.fail(ErrorCode.UPDATE_DB_ERROR,result);
}
项目:TITAN    文件:LoginController.java   
/**
 * @desc 登录
 *
 * @author liuliang
 *
 * @param request
 * @param response
 * @return LoginResponseBO 登录结果BO
 */
@RequestMapping(value = "/login")
@ResponseBody
public ComponentResult<LoginResultBO> login(@Validated UserInfoBO userInfoBO,BindingResult br) {
    ComponentResult<LoginResultBO> componentResult = new ComponentResult<LoginResultBO>();
    //1、参数校验
    Result validateResult = ValidatorUtil.getValidResult(br);
    if(ResultUtil.isfail(validateResult)) {
        return ResultUtil.copy(validateResult, componentResult);
    }
    //2、登录
    String username = userInfoBO.getUsername();
    String password = userInfoBO.getPassword();
    String[] userArray = titanManagerUser.split("\\|");
    for(int i=0,userArraySize=userArray.length ; i<userArraySize ; i++){
        String[] tempUser = userArray[i].split("\\,");
        if(username.equals(tempUser[0]) && password.equals(tempUser[1])){
            String ticket = TicketBuilderUtil.getTicket(userInfoBO.getUsername());
            //设置ticket到缓存中
            if(-1 == ticketExpireTime){
                jedisCluster.set(TitanConstant.TICKET_PREFIX + ticket,username);
            }else{
                jedisCluster.setex(TitanConstant.TICKET_PREFIX + ticket,ticketExpireTime, username);
            }
            //3、返回登录成功
            componentResult.setData(new LoginResultBO(ticket));
            ResultUtil.success(componentResult);
            return componentResult;
        }
    }
    //4、失败返回
    return ResultUtil.fail(ErrorCode.LOGIN_ERROR,componentResult);
}
项目:TITAN    文件:LinkController.java   
/**
 * @desc 更新链路
 *
 * @author liuliang
 *
 * @param linkBO 链路BO
 * @return Result
 */
@RequestMapping(value = "/update")
@ResponseBody
public Result update(@Validated(Groups.Update.class) LinkBO linkBO,BindingResult br){
    Result result = new Result();
    //参数校验
    Result validateResult = ValidatorUtil.getValidResult(br);
    if(ResultUtil.isfail(validateResult)) {
        return ResultUtil.copy(validateResult, result);
    }
    //更新
    try {
        //查原数据
        Link link = linkService.getLink(linkBO.getLinkId());
        String oldtestFileName = link.getTestfilePath();
        //更新DB
        int updateResult = linkService.updateLink(linkBO);
        if(0 < updateResult) {
            //若存在旧的压测文件,则删除
            if(StringUtils.isNotBlank(oldtestFileName) && (!oldtestFileName.equals(linkBO.getTestfilePath()))){
                boolean delResult = ftpUtils.deleteFile(new File(oldtestFileName));
                if(!delResult){
                    logger.error("删除旧压测文件失败,linkId:{},filename:{}",linkBO.getLinkId(),oldtestFileName);
                }
            }
            return ResultUtil.success(result);
        }
    } catch(DuplicateKeyException de){
        logger.error("更新数据异常,链路名重复,linkBO:{}",linkBO.toString(),de);
        return ResultUtil.fail(ErrorCode.UPDATE_DB_ERROR,"链路名已存在",result);
    }catch (Exception e) {
        logger.error("更新数据异常,params:{}",linkBO.toString(),e);
    }
    //失败返回
    return ResultUtil.fail(ErrorCode.UPDATE_DB_ERROR,result);
}
项目:TITAN    文件:OperateController.java   
/**
 * @desc 操作Agent节点
 *
 * @author liuliang
 *
 * @param operateBO
 * @param br
 * @return
 */
@RequestMapping(value = "/agent")
@ResponseBody
public Result agent(@Validated(Groups.Update.class) OperateBO operateBO,BindingResult br){
    Result result = new Result();
    //参数校验
    Result validateResult = ValidatorUtil.getValidResult(br);
    if(ResultUtil.isfail(validateResult)) {
        return ResultUtil.copy(validateResult, result);
    }
    //执行命令
    String commandPath = null;
    switch (operateBO.getOperateType()) {
        case OperateTypeConstant.START:     
            commandPath = startAgentPath;
            break;
        case OperateTypeConstant.STOP:      
            commandPath = stopAgentPath;
            break;
        case OperateTypeConstant.RESTART:
            commandPath = restartAgentPath;
            break;  
        default:
            logger.error("操作Agent,操作类型错误,params:{}",operateBO.toString());
            break;
    }
    if(StringUtils.isNotBlank(commandPath)){
        try {
            String commandResult = agentService.executeCommand(commandPath);
            logger.info("执行agent命令结果,commandResult:{}",commandResult);
            return ResultUtil.success(result);
        } catch (Exception e) {
            logger.error("执行shell命令异常,params:{}",operateBO.toString(),e);
            return ResultUtil.fail(ErrorCode.FAIL,"执行命令异常",result);
        }
    }else{
        return ResultUtil.fail(ErrorCode.FAIL,"操作类型错误",result);
    }
}
项目:canal_mysql_elasticsearch_sync    文件:SyncController.java   
/**
 * 通过库名和表名全量同步数据
 *
 * @param request 请求参数
 */
@RequestMapping("/byTable")
@ResponseBody
public String syncTable(@Validated SyncByTableRequest request) {
    logger.debug("request_info: " + JsonUtil.toJson(request));
    String response = Response.success(syncService.syncByTable(request)).toString();
    logger.debug("response_info: " + JsonUtil.toJson(request));
    return response;
}
项目:TITAN    文件:AutomaticTaskController.java   
/**
 * @desc 新增
 *
 * @author liuliang
 *
 * @param automaticTaskBO
 * @param br
 * @return
 */
@RequestMapping(value = "/add")
@ResponseBody
public Result add(@Validated(Groups.Add.class) AutomaticTaskBO automaticTaskBO,BindingResult br) {
    Result result = new Result();
    //参数校验
    Result validateResult = ValidatorUtil.getValidResult(br);
    if(ResultUtil.isfail(validateResult)) {
        return ResultUtil.copy(validateResult, result);
    }
    //新增
    try {
        int addResult = automaticTaskService.add(automaticTaskBO);
        if(0 < addResult) {
            // 同步定时任务
            this.syncAutomaticTask(automaticTaskBO, TaskSyncTypeEnum.UPDATE.value);
            return ResultUtil.success(result);
        }
    } catch(DuplicateKeyException de){
        logger.error("新增数据异常,主键重复,params:{}",automaticTaskBO.toString(),de);
        return ResultUtil.fail(ErrorCode.UPDATE_DB_ERROR,"主键重复",result);
    } catch (Exception e) {
        logger.error("新增数据异常,params:{}",automaticTaskBO.toString(),e);
    }
    //返回失败结果
    return ResultUtil.fail(ErrorCode.UPDATE_DB_ERROR,result);
}
项目:TITAN    文件:AutomaticTaskController.java   
/**
 * @desc  删除
 *
 * @author liuliang
 *
 * @param automaticTaskBO
 * @param br
 * @return
 */
@RequestMapping(value = "/del")
@ResponseBody
public Result del(@Validated(Groups.Query.class) AutomaticTaskBO automaticTaskBO,BindingResult br) {
    Result result = new Result();
    //参数校验
    Result validateResult = ValidatorUtil.getValidResult(br);
    if(ResultUtil.isfail(validateResult)) {
        return ResultUtil.copy(validateResult, result);
    }
    //删除
    try {
        AutomaticTask automaticTask = automaticTaskService.getDataDetail(automaticTaskBO.getAutomaticTaskId());
        int delResult = automaticTaskService.del(automaticTaskBO.getAutomaticTaskId());
        if(0 < delResult) {
            // 同步定时任务
            AutomaticTaskBO obj = new AutomaticTaskBO();
            BeanUtils.copyProperties(automaticTask, obj);
            this.syncAutomaticTask(obj, TaskSyncTypeEnum.DELETE.value);

            return ResultUtil.success(result);
        }
    } catch (Exception e) {
        logger.error("删除数据异常,params:{}",automaticTaskBO.toString(),e);
    }
    //失败返回
    return ResultUtil.fail(ErrorCode.UPDATE_DB_ERROR,result);
}
项目:spring-boot-oauth2-demo    文件:CityController.java   
/**
 * 城市收录
 *
 * @param insertCityRequestDto
 * @return
 */
@PutMapping("/insert")
public ModelResult<City> insertCity(@Validated @RequestBody InsertCityRequestDto insertCityRequestDto) {
    ModelResult<City> modelResult = new ModelResult<>();
    City city = cityDtoMapper.cityDto2City(insertCityRequestDto);
    int count = cityMapper.insert(city);
    if (count == 1) {
        modelResult.setData(city);
    } else {
        modelResult.setReturnCode("-1");
        modelResult.setReturnMsg("操作数据库失败");
    }
    return modelResult;
}
项目:airsonic    文件:DatabaseSettingsController.java   
@RequestMapping(method = RequestMethod.POST)
protected String onSubmit(@ModelAttribute("command") @Validated DatabaseSettingsCommand command,
                          BindingResult bindingResult,
                          RedirectAttributes redirectAttributes) throws Exception {
    if (!bindingResult.hasErrors()) {
        settingsService.resetDatabaseToDefault();
        settingsService.setDatabaseConfigType(command.getConfigType());
        switch(command.getConfigType()) {
            case EMBED:
                settingsService.setDatabaseConfigEmbedDriver(command.getEmbedDriver());
                settingsService.setDatabaseConfigEmbedPassword(command.getEmbedPassword());
                settingsService.setDatabaseConfigEmbedUrl(command.getEmbedUrl());
                settingsService.setDatabaseConfigEmbedUsername(command.getEmbedUsername());
                break;
            case JNDI:
                settingsService.setDatabaseConfigJNDIName(command.getJNDIName());
                break;
            case LEGACY:
            default:
                break;
        }
        if(command.getConfigType() != DataSourceConfigType.LEGACY) {
            settingsService.setDatabaseMysqlVarcharMaxlength(command.getMysqlVarcharMaxlength());
            settingsService.setDatabaseUsertableQuote(command.getUsertableQuote());
        }
        redirectAttributes.addFlashAttribute("settings_toast", true);
        settingsService.save();
        return "redirect:databaseSettings.view";
    } else {
        return "databaseSettings.view";
    }
}