@PostMapping("/comments") public Mono<String> addComment(Mono<Comment> newComment) { if (commentSink != null) { return newComment .map(comment -> { commentSink.next(MessageBuilder .withPayload(comment) .setHeader(MessageHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .build()); return comment; }) .flatMap(comment -> { meterRegistry .counter("comments.produced", "imageId", comment.getImageId()) .increment(); return Mono.just("redirect:/"); }); } else { return Mono.just("redirect:/"); } }
@PostMapping(value = "/upload/qualification", headers = "Accept=application/json") @Secured({"ROLE_ADMIN", "ROLE_USER"}) @ResponseStatus(value = HttpStatus.ACCEPTED) public String uploadQualifications(@ModelAttribute final com.unilog.app.representation.Qualification qualification, final HttpSession session, final Map<String, Object> model) throws UnsupportedEncodingException { checkSession(session); qualification.setIssuer((String) session.getAttribute("currentUser")); String result = userService.uploadQualification(qualification); if (result.equals("success")) { LOGGER.info("Adding qualifications"); model.put("success", true); com.unilog.app.representation.Qualification emptyQualification = new com.unilog.app.representation.Qualification(); emptyQualification.getTranscripts().add(new Transcript()); emptyQualification.getTranscripts().add(new Transcript()); model.put("qualification", emptyQualification); } else if (result.equals("qualificationError")) { model.put("qualificationError", true); } else { model.put("emailError", true); } return "qualification"; }
/** * 新增用户 * @param person * @param session * @return */ @PostMapping("/add") public ServerResponse add(Person person,MultipartFile avatarFile,HttpSession session,HttpServletRequest request){ if(person.getName().isEmpty()||person.getPwd().isEmpty()){ return ServerResponse.createErrorResponse(400,"Name or Pwd is null."); } if(!checkLogin(session)){ return ServerResponse.createErrorResponse(401,"Login Please."); } if(!avatarFile.isEmpty()){ ServerResponse serverResponse=upload(avatarFile); if(serverResponse.getStatus()!=200){ return serverResponse; }else{ person.setAvatar((String) serverResponse.getData()); } } return personService.addPerson(person); }
@PostMapping("/create") public String createUser(@Valid CreateUserForm form, BindingResult bindingResult, RedirectAttributes redirectAttributes) { if (bindingResult.hasErrors()) { redirectAttributes.addFlashAttribute("flashMessage", "admin.users.create.error." + bindingResult.getFieldError().getField()); return "redirect:/admin/users"; } boolean error = false; try{ userCreationService.create(form.toUisUser()); }catch(ValidationException e){ error = true; redirectAttributes.addFlashAttribute("flashMessage", "admin.users.create.error.email"); } if(!error){ redirectAttributes.addFlashAttribute("flashMessage", "admin.users.create.success"); } return "redirect:/admin/users"; }
@PostMapping("/{id}/delete") public void deleteAjax(@PathVariable String id, HttpServletRequest req, HttpServletResponse res) { if (utils.isAuthenticated(req)) { Comment comment = pc.read(id); Profile authUser = utils.getAuthUser(req); boolean isMod = utils.isMod(authUser); if (comment != null && (comment.getCreatorid().equals(authUser.getId()) || isMod)) { // check parent and correct (for multi-parent-object pages) comment.delete(); if (!isMod) { utils.addBadgeAndUpdate(authUser, DISCIPLINED, true); } } } res.setStatus(200); }
@ApiOperation(value = "修改用户角色") @PostMapping(value = "/user/update/role") @RequiresPermissions("sys.permisson.userRole.update") public Object userRole(ModelMap modelMap, @RequestBody List<SysUserRole> list) { Long userId = null; Long currentUserId = getCurrUser(); for (SysUserRole sysUserRole : list) { if (sysUserRole.getUserId() != null) { if (userId != null && sysUserRole.getUserId() != null && userId.longValue() != sysUserRole.getUserId()) { throw new IllegalParameterException("参数错误."); } userId = sysUserRole.getUserId(); } sysUserRole.setCreateBy(currentUserId); sysUserRole.setUpdateBy(currentUserId); sysUserRole.setCreateTime(new Date()); sysUserRole.setUpdateTime(new Date()); } Parameter parameter = new Parameter(getService(), "updateUserRole").setList(list); logger.info("{} execute updateUserRole start...", parameter.getNo()); provider.execute(parameter); logger.info("{} execute updateUserRole end.", parameter.getNo()); return setSuccessModelMap(modelMap); }
/** * @param method method * @return String */ private String getMappingUrl(String requestMethod, Method method) { String[] mappingValue; switch (requestMethod) { case "POST": PostMapping postMapping = method.getAnnotation(PostMapping.class); mappingValue = postMapping.value().length != 0 ? postMapping.value() : postMapping.path(); break; case "PUT": PutMapping putMapping = method.getAnnotation(PutMapping.class); mappingValue = putMapping.value().length != 0 ? putMapping.value() : putMapping.path(); break; case "DELETE": DeleteMapping deleteMapping = method.getAnnotation(DeleteMapping.class); mappingValue = deleteMapping.value().length != 0 ? deleteMapping.value() : deleteMapping.path(); break; default: GetMapping getMapping = method.getAnnotation(GetMapping.class); mappingValue = getMapping.value().length != 0 ? getMapping.value() : getMapping.path(); break; } return mappingValue[0]; }
@ApiOperation(value = "用户添加界面") @PostMapping("/edit") @ResponseBody public BaseResult edit(SysUser user){ BaseResult result=new BaseResult(BaseResultCode.SUCCESS,"成功"); SysUser curentUser= UserUtils.getUser(); if(StringUtils.isEmpty(user.getId())){ user.setCreateBy(curentUser.getId()); user.setUpdateBy(curentUser.getId()); String ecPwd= MD5Util.shiroPwd(user.getPassword(),user.getLoginName()); user.setPassword(ecPwd); userService.insert(user); }else { user.setUpdateBy(curentUser.getId()); userService.updateByPrimaryKeySelective(user); } return result; }
/** * Gera e retorna um novo token JWT. * * @param authenticationDto * @param result * @return ResponseEntity<Response<TokenDto>> * @throws AuthenticationException */ @PostMapping public ResponseEntity<Response<TokenDto>> gerarTokenJwt( @Valid @RequestBody JwtAuthenticationDto authenticationDto, BindingResult result) throws AuthenticationException { Response<TokenDto> response = new Response<TokenDto>(); if (result.hasErrors()) { log.error("Erro validando lançamento: {}", result.getAllErrors()); result.getAllErrors().forEach(error -> response.getErrors().add(error.getDefaultMessage())); return ResponseEntity.badRequest().body(response); } log.info("Gerando token para o email {}.", authenticationDto.getEmail()); Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken( authenticationDto.getEmail(), authenticationDto.getSenha())); SecurityContextHolder.getContext().setAuthentication(authentication); UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationDto.getEmail()); String token = jwtTokenUtil.obterToken(userDetails); response.setData(new TokenDto(token)); return ResponseEntity.ok(response); }
/** * 上传接口 * @param file * @return */ @PostMapping("/upload") @ResponseBody public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) { File returnFile = null; try { File f = new File(file.getOriginalFilename(), file.getContentType(), file.getSize(),file.getBytes()); f.setMd5( MD5Util.getMD5(file.getInputStream()) ); returnFile = fileService.saveFile(f); String path = "//"+ serverAddress + ":" + serverPort + "/view/"+returnFile.getId(); return ResponseEntity.status(HttpStatus.OK).body(path); } catch (IOException | NoSuchAlgorithmException ex) { ex.printStackTrace(); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ex.getMessage()); } }
@ApiOperation(value = "修改角色操作权限") @PostMapping(value = "/role/update/permission") @RequiresPermissions("sys.permisson.role.update") public Object updateRolePermission(ModelMap modelMap, @RequestBody List<SysRoleMenu> list) { Long roleId = null; Long userId = getCurrUser(); for (SysRoleMenu sysRoleMenu : list) { if (sysRoleMenu.getRoleId() != null) { if (roleId != null && sysRoleMenu.getRoleId() != null && roleId.longValue() != sysRoleMenu.getRoleId()) { throw new IllegalParameterException("参数错误."); } roleId = sysRoleMenu.getRoleId(); } sysRoleMenu.setCreateBy(userId); sysRoleMenu.setUpdateBy(userId); sysRoleMenu.setCreateTime(new Date()); sysRoleMenu.setUpdateTime(new Date()); } Parameter parameter = new Parameter(getService(), "updateRolePermission").setList(list); logger.info("{} execute updateRolePermission start...", parameter.getNo()); provider.execute(parameter); logger.info("{} execute updateRolePermission end.", parameter.getNo()); return setSuccessModelMap(modelMap); }
@ApiOperation(value = "修改角色菜单") @PostMapping(value = "/role/update/menu") @RequiresPermissions("sys.permisson.roleMenu.update") public Object roleMenu(ModelMap modelMap, @RequestBody List<SysRoleMenu> list) { Long roleId = null; Long userId = getCurrUser(); for (SysRoleMenu sysRoleMenu : list) { if (sysRoleMenu.getRoleId() != null) { if (roleId != null && sysRoleMenu.getRoleId() != null && roleId.longValue() != sysRoleMenu.getRoleId()) { throw new IllegalParameterException("参数错误."); } roleId = sysRoleMenu.getRoleId(); } sysRoleMenu.setCreateBy(userId); sysRoleMenu.setUpdateBy(userId); sysRoleMenu.setCreateTime(new Date()); sysRoleMenu.setUpdateTime(new Date()); } Parameter parameter = new Parameter(getService(), "updateRoleMenu"); parameter.setList(list); logger.info("{} execute updateRoleMenu start...", parameter.getNo()); provider.execute(parameter); logger.info("{} execute updateRoleMenu end.", parameter.getNo()); return setSuccessModelMap(modelMap); }
@ApiOperation(value = "菜单管理-编辑接口") @PostMapping("/edit") @ResponseBody public BaseResult edit(SysMenu model){ BaseResult result=new BaseResult(BaseResultCode.SUCCESS,"成功"); SysUser curentUser= UserUtils.getUser(); if(StringUtils.isEmpty(model.getId())){ model.setCreateBy(curentUser.getId()); model.setUpdateBy(curentUser.getId()); service.insert(model); }else { model.setUpdateBy(curentUser.getId()); service.updateByPrimaryKeySelective(model); } return result; }
@PostMapping ( "/container/create" ) public ObjectNode containerCreate ( boolean start, String usingImage, String name, String command, String entry, String workingDirectory, String networkMode, String restartPolicy, String runUser, String ports, String volumes, String environmentVariables, String limits ) throws Exception { issueAudit( "creating container: " + name + " from image: " + usingImage, null ); return dockerHelper.containerCreate( null, start, usingImage, name, command, entry, workingDirectory, networkMode, restartPolicy, runUser, ports, volumes, environmentVariables, limits ); }
@PostMapping("/login") public JsonResult login(@RequestParam String phone, @RequestParam String password) { ErrorsMap errors = validator.existsValid(phone); if (errors.hasError()) return new JsonResult(404, "登陆失败", errors); User user = service.login(phone, password); if (user == null) { errors.put("password", "密码错误"); return new JsonResult(400, "登陆失败", errors); } else{ return new JsonResult(0, "登陆成功", new HashMap() {{ put("token", jwtUtils.createJWT(user.getId(), user.getUserType())); }}); } }
@ApiOperation("发布回复接口") @ApiImplicitParams({ @ApiImplicitParam(name = "content", value = "回复内容", dataType = "String"), @ApiImplicitParam(name = "token", value = "用户令牌", dataType = "String"), @ApiImplicitParam(name = "postsId", value = "帖子ID", dataType = "Integer") }) @PostMapping public QuarkResult CreateReply(Reply reply,Integer postsId,String token){ QuarkResult result = restProcessor(() -> { if (token == null) return QuarkResult.warn("请先登录!"); User userbytoken = userService.getUserByToken(token); if (userbytoken == null) return QuarkResult.warn("用户不存在,请先登录!"); User user = userService.findOne(userbytoken.getId()); if (user.getEnable() != 1) return QuarkResult.warn("用户处于封禁状态!"); replyService.saveReply(reply, postsId, user); return QuarkResult.ok(); }); return result; }
@PostMapping("/save") public ModelAndView save(@Valid CategoryForm form, BindingResult bindingResult, Map<String, Object> map) { if (bindingResult.hasErrors()) { map.put("msg", bindingResult.getFieldError().getDefaultMessage()); map.put("url", "/sell/seller/category/index"); return new ModelAndView("common/error", map); } ProductCategory productCategory = new ProductCategory(); try { if (form.getCategoryId() != null) { productCategory = categoryService.findOne(form.getCategoryId()); } BeanUtils.copyProperties(form, productCategory); categoryService.save(productCategory); } catch (SellException e) { map.put("msg", e.getMessage()); map.put("url", "/seller/category/index"); return new ModelAndView("common/error", map); } map.put("url", "/seller/category/list"); return new ModelAndView("common/success", map); }
@ResponseBody @PostMapping(URL) public VerifyCheckResult check(@RequestBody Code code){ String requestId = verifyAction.getRequestId(); if(requestId == null){ log.info("No requestId found."); return fail("Your code has expired, reload the page"); } log.info("Verifing request ID {} code {}", requestId, code); Optional<CheckResult> checkResult = verifyService.check(requestId, code.getCode()); if(checkResult.isPresent()){ if(checkResult.get().getStatus() == CheckResult.STATUS_OK){ log.info("Verification of Request ID was sucessfull", requestId); userUtils.getLoggedUserDetails().get().markTwoFaAsCompleted(); return ok(verifyAction.getSuccessRedirectUrl()); } return fail(checkResult.get().getErrorText()); } return fail("Verification has failed"); }
@PostMapping(value = "/admin/portal", params = "action=Complete All") @ResponseStatus(value = HttpStatus.ACCEPTED) @Secured("ROLE_ADMIN") public String adminPortalPublishAllUsers(final Map<String, Object> model) { try { String result = adminService.completeAllAccounts(); if (result.equals("allSuccess")) { model.put(result, true); } else if (result.equals("partialSuccess")) { model.put(result, true); } else { //zeroSuccess model.put(result, true); } } catch (Exception e) { e.printStackTrace(); model.put("publishError", true); } model.put("adminWindow", adminService.generateAdminWindow()); return "adminPortal"; }
@PostMapping @ApiOperation(value = "新增任务") @RequiresPermissions("sys.task.scheduled.update") public Object updateTask(@RequestBody TaskScheduled scheduled, ModelMap modelMap) { Assert.notNull(scheduled.getTaskGroup(), "TASKGROUP"); Assert.notNull(scheduled.getTaskName(), "TASKNAME"); Assert.notNull(scheduled.getJobType(), "JOBTYPE"); Assert.notNull(scheduled.getTaskType(), "TASKTYPE"); Assert.notNull(scheduled.getTargetObject(), "TARGETOBJECT"); Assert.notNull(scheduled.getTargetMethod(), "TARGETMETHOD"); Assert.notNull(scheduled.getTaskCron(), "TASKCRON"); Assert.notNull(scheduled.getTaskDesc(), "TASKDESC"); if (TaskType.dubbo.equals(scheduled.getTaskType())) { Assert.notNull(scheduled.getTargetSystem(), "TARGETSYSTEM"); } Parameter parameter = new Parameter(getService(), "updateTask").setModel(scheduled); provider.execute(parameter); return setSuccessModelMap(modelMap); }
/** * POST /users : Creates a new user. * * <p>Creates a new user if the login and email are not already used, and sends an mail with an * activation link. The user needs to be activated on creation. * @param user the user to create * @return the ResponseEntity with status 201 (Created) and with body the new user, or with * status 400 (Bad Request) if the login or email is already in use * @throws URISyntaxException if the Location URI syntax is incorrect */ @PostMapping("/users") @Timed @Secured(AuthoritiesConstants.ADMIN) public ResponseEntity createUser(@Valid @RequestBody UserDTO user) throws URISyntaxException { if (user.getId() != null) { return ResponseEntity.badRequest() .headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new user cannot already have an ID")) .body(null); } user.getLogins().forEach(userLogin -> userLoginRepository.findOneByLoginIgnoreCase(userLogin.getLogin()) .ifPresent(s -> { throw new BusinessException(Constants.LOGIN_IS_USED_ERROR_TEXT); }) ); User newUser = userService.createUser(user); produceEvent(new UserDTO(newUser), Constants.CREATE_PROFILE_EVENT_TYPE); mailService.sendCreationEmail(newUser, TenantUtil.getApplicationUrl(), TenantContext.getCurrent().getTenant(), MDCUtil.getRid()); return ResponseEntity.created(new URI("/api/users/" + newUser.getUserKey())) .headers(HeaderUtil.createAlert("userManagement.created", newUser.getUserKey())) .body(new UserDTO(newUser)); }
@PostMapping("/result_music") public String mediaMusicSubmit(@ModelAttribute Media media, Model model, HttpServletRequest request ) { LinkedList<MusicInfo> a = null; String maxResult= media.getMaxResult(); if (maxResult.equals("")) maxResult="10"; if(media.getTitle().equals("") && media.getAuthor().equals("")) return "media_music"; try { if (media.getService().equals("itunes")) a = APIOperations.musicGetInfoItunes(media.getTitle(), maxResult,media.getOrderBy(),media.getAuthor(),media.getYear()); else { a = APIOperations.musicGetInfoDiscogs(media.getTitle(), maxResult,"FILE,MP3,Single",media.getOrderBy(),media.getAuthor(),media.getYear()); } } catch (Exception e) { e.printStackTrace(); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).toString(); } RabbitSend.sendMediaRequest(media.getTitle(),"Music",request); if (a.size()==0) return "no_result"; model.addAttribute("mediaList", a); if (media.getService().equals("itunes")) return "result_music_itunes"; else return "result_music"; }
@PostMapping("/putArticle") @ResponseBody public String putArticle(@RequestParam("artical") String artical, HttpServletRequest request) throws ValidationException { String safeArtical = ESAPI.validator().getValidSafeHTML("htmlInput", artical, 1000, true); return "{status:ok}"; }
@PostMapping ( "/container/stop" ) public ObjectNode containerStop ( String id, String name, boolean kill, int stopSeconds ) throws Exception { issueAudit( "starting container: " + name, null ); return dockerHelper.containerStop( id, name, kill, stopSeconds ); }
@PostMapping public RegistrationForm register(@RequestBody @Valid RegistrationForm registrationForm) { UserEntity user = registrationService.registerUser(registrationForm); if (user != null && user.getId() != null) tokenStoreService.sendTokenNotification(TokenStoreType.USER_ACTIVATION, user); return registrationForm; }
@PostMapping(value = "/deleteLog") public OperationResult deleteLog(Long id){ Check.GreaterThan(id,0L,"id"); logService.softDelete(id); return OperationResult.Success("删除成功",null); }
@PostMapping("/searchAds") public ServerResponse searchAds(HttpSession session,String userId,String startDate,String endDate){ Map<String,Object> map=new HashMap<>(); if(userId!=null){ map.put("userId",userId); } if(startDate!=null&&endDate!=null){ map.put("startDate", StringUtils.trimAllWhitespace(startDate)); map.put("endDate",StringUtils.trimAllWhitespace(endDate)); } String userSessionId= (String) session.getAttribute("userSessionId"); return ServerResponse.createSuccessResponse(advertiseService.findConditions(map,userSessionId)); }
@PostMapping("/login") public JsonMap login(HttpServletRequest request, @RequestBody Account account){ Account actAccount = accountService.checkUsernameAndPassword(account.getUsername(), account.getPassword()); String status = "success"; if (accountService.isNeedChangePassword(actAccount)){ status = "needChangePassword"; } RequestContext.storeAccountInSession(request, actAccount); return success(); }
@PostMapping("/client/deposit") public ResponseEntity<Void> deposit(@RequestBody final DepositCommand command, final HttpMethod method, final WebRequest request ){ _print(method, request); final Client client = _findClient(request); final Account destinationAccount = client.findAccount(command.accountId).get(); final Amount amount = new Amount(command.amount); client.deposit(destinationAccount, amount); return new ResponseEntity<>(HttpStatus.NO_CONTENT); }
@PostMapping("/aliPayFail") @ApiOperation("当alipay支付异常的时候,pay表的数据不会新增 alipay表不会新增 wechat表不会新增") public String aliPayFail() { try { payService.payWithAliPayFail(); } catch (Exception e) { e.printStackTrace(); return "aili pay fail and pay not commit"; } return "success"; }
@ApiOperation(value = "修改个人信息") @PostMapping(value = "/update/person") public Object updatePerson(ModelMap modelMap, @RequestBody SysUser param) { param.setId(getCurrUser()); param.setPassword(null); Assert.isNotBlank(param.getAccount(), "ACCOUNT"); Assert.length(param.getAccount(), 3, 15, "ACCOUNT"); return super.update(modelMap, param); }
@PostMapping(value = "/admin/portal", params = "action=Register") @ResponseStatus(value = HttpStatus.ACCEPTED) @Secured("ROLE_ADMIN") public String adminPortalRegisterUser(@ModelAttribute final AdminWindow request, final Map<String, Object> model) { if (!adminService.registerAccount(request)) { model.put("registrationError", true); } else { model.put("registrationSuccess", true); } model.put("adminWindow", adminService.generateAdminWindow()); return "adminPortal"; }
@PostMapping(path = "/some/{someId}/other/{otherId}") public ResponseEntity<Resource<TestDateHolder>> doSomething(@PathVariable String someId, @PathVariable Integer otherId, @RequestBody TestDateHolder testDateHolder) { testDateHolder.setId(UUID.randomUUID().toString()); Resource<TestDateHolder> resource = new Resource<>(testDateHolder); resource.add(linkTo(methodOn(TestController.class).doSomething(someId, otherId, null)).withSelfRel()); return ResponseEntity.ok(resource); }
@PostMapping("/comentario/articulo/{id}") public String comentar (Model model, Comentario comentario, @PathVariable long id, HttpSession sesion){ //Guardo el comentario escrito creado Articulo articulo = articulo_repository.findOne(id); comentario.setArticulo(articulo); Usuario usuario = usuario_repository.findByEmail((String) sesion.getAttribute("email")); comentario.setAutor(usuario); articulo.getComentarios().add(comentario); comentario_repository.save(comentario); return "comentario_guardado"; }
@PostMapping(value="/signup") public ExecutionStatus processSignup(ModelMap model, @RequestBody User reqUser) { User user = null; try { user = userService.doesUserExist(reqUser.getEmail()); } catch (UserNotFoundException e) { } if(user != null) { return new ExecutionStatus("USER_ACCOUNT_EXISTS", "User account with same email address exists. Please try again!"); } user = new User(); user.setEmail(reqUser.getEmail()); user.setPassword(reqUser.getPassword()); user.setFirstName(reqUser.getFirstname()); user.setLastname(reqUser.getLastname()); user.setContactNumber(reqUser.getContactNumber()); user.setAlternateContactNumber(reqUser.getAlternateContactNumber()); user.setCityCode(reqUser.getCityCode()); user.setStateCode(reqUser.getStateCode()); user.setCountryCode(reqUser.getCountryCode()); user.setAge(reqUser.getAge()); user.setGender(reqUser.getGender()); user.setRole(reqUser.getRole()); User persistedUser = userService.save(user); // // Add entry in doctor table if user is a doctor // docService.addDoctor(user); return new ExecutionStatus("USER_ACCOUNT_CREATED", "User account successfully created"); }
@ApiOperation(value = "用户登录") @PostMapping("/login") public Object login(@RequestBody SysUser sysUser, ModelMap modelMap, HttpServletRequest request) { Assert.notNull(sysUser.getAccount(), "ACCOUNT"); Assert.notNull(sysUser.getPassword(), "PASSWORD"); if (LoginHelper.login(sysUser.getAccount(), SecurityUtil.encryptPassword(sysUser.getPassword()))) { request.setAttribute("msg", "[" + sysUser.getAccount() + "]登录成功."); return setSuccessModelMap(modelMap); } request.setAttribute("msg", "[" + sysUser.getAccount() + "]登录失败."); throw new LoginException(Resources.getMessage("LOGIN_FAIL")); }
@PostMapping public ModelAndView save(Profile profile) { GoogleUser user = (GoogleUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); profile.setUser(user); Profile newProfile = profileRepository.save(profile); ModelAndView mv = new ModelAndView("redirect:/profile"); mv.addObject("profile", newProfile); return mv; }
@PostMapping("/test-contracts") public TestContractView createContract( @RequestParam("returnArkAddress") String returnArkAddress, @RequestParam("donationArkAmount") String donationArkAmount ) { BigDecimal donationArkAmountValue = new BigDecimal(donationArkAmount); BigDecimal requiredArkAmount = donationArkAmountValue.add(arkTransactionFee); TestContractEntity testContractEntity = new TestContractEntity(); testContractEntity.setToken(UUID.randomUUID().toString()); testContractEntity.setCreatedAt(ZonedDateTime.from(Instant.now().atOffset(ZoneOffset.UTC))); testContractEntity.setStatus(TestContractEntity.STATUS_PENDING); testContractEntity.setServiceArkAddress(serviceArkAddress); testContractEntity.setDonationArkAmount(donationArkAmountValue.setScale(8, BigDecimal.ROUND_UP)); testContractEntity.setReturnArkAddress(returnArkAddress); testContractEntity.setRequiredArkAmount(requiredArkAmount); testContractRepository.save(testContractEntity); // Register contract message with listener so we get a callback when a matching ark transaction is found CreateMessageRequest createMessageRequest = new CreateMessageRequest(); createMessageRequest.setCallbackUrl("http://localhost:8080/test-contracts/ark-transaction-matches"); createMessageRequest.setToken(testContractEntity.getToken()); listenerRestTemplate.postForObject("/messages", createMessageRequest, Void.class); return testContractViewMapper.map(testContractEntity); }
@PostMapping(value = "/update") @Permission public AjaxResponse update(@RequestBody CompensationDTO compensationDTO) { if (recoverRetryMax < compensationDTO.getRetry()) { return AjaxResponse.error("重试次数超过最大设置,请您重新设置!"); } final Boolean success = compensationService.updateRetry(compensationDTO.getId(), compensationDTO.getRetry(), compensationDTO.getApplicationName()); return AjaxResponse.success(success); }