@PostMapping("/authenticate") @Timed public ResponseEntity authorize(@Valid @RequestBody LoginVM loginVM, HttpServletResponse response) { UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginVM.getUsername(), loginVM.getPassword()); try { Authentication authentication = this.authenticationManager.authenticate(authenticationToken); SecurityContextHolder.getContext().setAuthentication(authentication); boolean rememberMe = (loginVM.isRememberMe() == null) ? false : loginVM.isRememberMe(); String jwt = tokenProvider.createToken(authentication, rememberMe); response.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer " + jwt); return ResponseEntity.ok(new JWTToken(jwt)); } catch (AuthenticationException ae) { log.trace("Authentication exception trace: {}", ae); return new ResponseEntity<>(Collections.singletonMap("AuthenticationException", ae.getLocalizedMessage()), HttpStatus.UNAUTHORIZED); } }
@RequestMapping(value = "/address", method = POST, consumes = APPLICATION_JSON_UTF8_VALUE, produces = APPLICATION_JSON_UTF8_VALUE) public ResponseEntity<AddressResponse> address(@Valid @RequestBody AddressRequest addressRequest, @Valid @Size(max = Constants.UUID_CHAR_MAX_SIZE) @RequestHeader(value="Authorization") String authorizationHeader, @Context HttpServletRequest httpServletRequest) throws BaseException { // Get token String emailConfirmationToken = getEmailConfirmationToken(authorizationHeader); // Get IP address from request String ipAddress = httpServletRequest.getHeader("X-Real-IP"); if (ipAddress == null) ipAddress = httpServletRequest.getRemoteAddr(); LOG.info("/address called from {} with token {}, address {}, refundBTC {} refundETH {}", ipAddress, emailConfirmationToken, addressRequest.getAddress(), addressRequest.getRefundBTC(), addressRequest.getRefundETH()); return setWalletAddress(addressRequest, emailConfirmationToken); }
@RequestMapping(value = "/albums", method = RequestMethod.POST) public String saveOrUpdateAlbum(@ModelAttribute("album") @Valid Album album, BindingResult result, final RedirectAttributes redirectAttributes) { logger.debug("saveOrUpdateUser() : {}", album); if (result.hasErrors()) { return "albums/add"; } // Delegate business logic to albumService, which will decide // either to save or to update. // TODO: Catch any possible exception during database transaction this.albumService.saveOrUpdate(album); redirectAttributes.addFlashAttribute("css", "success"); redirectAttributes.addFlashAttribute("msg", "Album added successfully!"); // POST/REDIRECT/GET pattern return "redirect:/albums/" + album.getId(); }
@RequestMapping(value = { "/register" }, method = RequestMethod.POST) public String saveUserAccount(@Valid User user, BindingResult result, ModelMap model) { if (result.hasErrors() || result==null) { return "register"; } if(!userService.isUserSSOUnique(user.getId(), user.getSsoId())){ FieldError ssoError =new FieldError("user","ssoId",messageSource.getMessage("non.unique.ssoId", new String[]{user.getSsoId()}, Locale.getDefault())); result.addError(ssoError); return "register"; } userService.saveCustomerAccount(user); model.addAttribute("success", "Użytkownik " + user.getFirstName() + " "+ user.getLastName() + " został zarejestrowany."); model.addAttribute("loggedinuser", getPrincipal()); return "registrationsuccess"; }
@CrossOrigin @RequestMapping(value = "/update/{id}", method = RequestMethod.PUT) @ApiOperation(value = "Update an existing organization") public Map<String, Object> updateOrganization(@ApiParam(value = "Updated organization object", required = true) @PathVariable("id") int id, @RequestBody @Valid OrganizationDTO organizationDTO) { System.out.println("**************Update : id=" + organizationDTO.getId() + "**************"); Map<String, Object> responseData = null; try { OrganizationDTO updatedOrganization = organizationService.updateOrganization(id, organizationDTO); responseData = Collections.synchronizedMap(new HashMap<>()); responseData.put("organization", updatedOrganization); } catch (Exception e) { System.err.println(e); } return responseData; }
@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); }
@Log("用户登录") @RequestMapping(value = "/login", method = RequestMethod.POST) public Result login(@Valid User user, BindingResult result) { if (result.hasErrors()) { return new Result().failure("参数有误", ValidateUtil.toStringJson(result)); } User sysUser = userService.login(user); if (sysUser == null) { //注册用户 sysUser = userService.register(user); } String token = tokenManager.createToken(sysUser.getUsername()); Map<String, Object> map = new HashMap<String, Object>(); map.put("user", sysUser); map.put("token", token); return new Result().success(map); }
@PostMapping(value = "/new") public String createEvent(@Valid CreateEventForm createEventForm, BindingResult result, RedirectAttributes redirectAttributes) { if (result.hasErrors()) { return "events/create"; } CalendarUser attendee = calendarService.findUserByEmail(createEventForm.getAttendeeEmail()); if (attendee == null) { result.rejectValue("attendeeEmail", "attendeeEmail.missing", "Could not find a user for the provided Attendee Email"); } if (result.hasErrors()) { return "events/create"; } Event event = new Event(); event.setAttendee(attendee); event.setDescription(createEventForm.getDescription()); event.setOwner(userContext.getCurrentUser()); event.setSummary(createEventForm.getSummary()); event.setWhen(createEventForm.getWhen()); calendarService.createEvent(event); redirectAttributes.addFlashAttribute("message", "Successfully added the new event"); return "redirect:/events/my"; }
/** * POST /admin/tags -> Create a new tag. */ @RequestMapping(value = "/admin/tags", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public ResponseEntity<Tag> createTag(@Valid @RequestBody Tag tag) throws URISyntaxException { log.debug("REST request to save tag : {}", tag); if (tag.getId() != null) { return ResponseEntity.badRequest().header("Failure", "A new tag cannot already have an ID").body(null); } tag.setUser(userService.getUserWithAuthorities()); Tag result = tagRepository.save(tag); return ResponseEntity.created(new URI("/api/admin/tags/" + result.getId())) .headers(HeaderUtil.createEntityCreationAlert("tag", result.getId().toString())) .body(result); }
/** * 修改密码 * @param session * @return */ @RequestMapping(value = "/user/security/modifyPwd", method=RequestMethod.POST) @ResponseBody public JSON modifyPwd(@RequestBody @Valid UserModifyPwdReq req, HttpSession session) { User user = getSessionUser(session); userService.updatePwd(req, user); return JsonUtil.newJson().toJson(); }
@PostMapping public String changepass(Model model, @Valid ChangePasswordForm changePasswordForm, BindingResult bindingResult) { if (bindingResult.hasErrors()) return changepassView(changePasswordForm); UserEntity user = registrationService.findUserByEmail(changePasswordForm.getEmail()); if (user == null) { bindingResult.rejectValue("email", "error.changePasswordForm", "Can't find that email, sorry."); return changepassView(changePasswordForm); } else { tokenStoreService.sendTokenNotification(TokenStoreType.CHANGE_PASSWORD, user); } model.addAttribute(MESSAGE, CHANGEPASS); return CHANGEPASS_CONFIRMATION; }
/** * Agent和Server之间的心跳,可以1分钟或更长时间一次,传回Monitor的信息,返回MonitorJob信息 * * @param monitorId * @param monitor * @return */ @POST @Path("/monitor/{monitorId}/heartbeat") public RestfulReturnResult heartbeat(@Auth OAuthUser user, @PathParam("monitorId") String monitorId, @NotNull @Valid Monitor monitor) { if (!monitorId.equals(monitor.getMonitorId())) { log.error("monitor id in path {} and json {} and parameter not match error.", monitorId, monitor.getMonitorId()); return new RestfulReturnResult(new NiPingException(MonitoridNotMatchError), null); } monitor.setMonitorId(monitorId); monitor.setAccountId(user.getAccountId()); log.info("user {} monitorId {} send heartbeat {}", user, monitorId, monitor); monitorService.heartbeat(monitor); Optional<MonitorJob> job = Optional.empty(); try { monitorService.saveMonitor(monitor); job = taskService.getNextJob(monitorId, monitor.getRunningTaskIds()); if (log.isInfoEnabled() && job.isPresent()) { log.info("user {} monitorId {} get next job {}", user, monitorId, job.get()); } } catch (NiPingException e) { return new RestfulReturnResult(e, job.orElse(null)); } return new RestfulReturnResult(SUCCESS, job.orElse(null)); }
@RequestMapping(value = "/get-data-to-sign", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public GetDataToSignResponse getDataToSign(Model model, @RequestBody @Valid DataToSignParams params, @ModelAttribute("signatureMultipleDocumentsForm") @Valid SignatureMultipleDocumentsForm signatureMultipleDocumentsForm, BindingResult result) { signatureMultipleDocumentsForm.setBase64Certificate(params.getSigningCertificate()); signatureMultipleDocumentsForm.setBase64CertificateChain(params.getCertificateChain()); signatureMultipleDocumentsForm.setEncryptionAlgorithm(params.getEncryptionAlgorithm()); signatureMultipleDocumentsForm.setSigningDate(new Date()); model.addAttribute("signatureMultipleDocumentsForm", signatureMultipleDocumentsForm); ToBeSigned dataToSign = signingService.getDataToSign(signatureMultipleDocumentsForm); if (dataToSign == null) { return null; } GetDataToSignResponse responseJson = new GetDataToSignResponse(); responseJson.setDataToSign(DatatypeConverter.printBase64Binary(dataToSign.getBytes())); return responseJson; }
@ApiOperation(value = "Update the contribution of titles") @ApiResponses(value = { @ApiResponse(code = 400, message = "Incorrect data in the DTO"), @ApiResponse(code = 404, message = "No movie found or no user found"), @ApiResponse(code = 409, message = "An ID conflict or element exists"), }) @PreAuthorize("hasRole('ROLE_USER')") @PutMapping(value = "/contributions/{id}/othertitles", consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.NO_CONTENT) public void updateOtherTitleContribution( @ApiParam(value = "The contribution ID", required = true) @PathVariable("id") final Long id, @ApiParam(value = "The contribution", required = true) @RequestBody @Valid final ContributionUpdate<OtherTitle> contribution ) { log.info("Called with id {}, contribution {}", id, contribution); this.movieContributionPersistenceService.updateOtherTitleContribution(contribution, id, this.authorizationService.getUserId()); }
@GET @Path("find/{id}") @Produces(MediaType.APPLICATION_JSON) public Response find(@PathParam("id") @Valid String id) { JsonObject build = null; try { Clinicmanager get = clinicManagerService.get(Integer.valueOf(id)); build = Json.createObjectBuilder() .add("firstname", get.getPersonId().getFirstName()) .add("lastname", get.getPersonId().getLastName()) .add("id", get.getManagerId()) .add("genderId", get.getPersonId().getGenderId().getGenderId()) .build(); } catch (Exception ex) { return Response.ok().header("Exception", ex.getMessage()).build(); } return Response.ok().entity(build == null ? "No data found" : build).build(); }
@RequestMapping(value="/dologin.html") public ModelAndView userLogin(@Valid User loginuser, BindingResult result){ ModelAndView mv = new ModelAndView(); // BindingResult����洢���DZ?��֤�Ľ�� if(result.hasErrors() == true){ // ��֤���� mv.setViewName("login"); // ��ת���?ҳ�� return mv; } // ����Service����ʵ�ֵ�¼��֤ User user = userService.login(loginuser.getUsercode(), loginuser.getUserpassword()); //User user = null; // ���user��Ϊnull����¼�ɹ� if(user != null){ mv.setViewName("frame"); }else{ mv.addObject("error", "用户名或密码错误 "); mv.setViewName("login"); } return mv; }
/** * 保存连接信息 * @param form * @param bindingResult * @param session * @return */ @RequestMapping("connection/save.json") @ResponseBody public Map<String,Object> saveConnection(@Valid ZookeeperConnectForm form, BindingResult bindingResult, HttpSession session){ if(bindingResult.hasErrors()){ return Result.formErrorWrapper(bindingResult.getFieldError().getField(),bindingResult.getFieldError().getDefaultMessage()); } ConnectionInfo connInfo = new ConnectionInfo(); connInfo.setConnectUrl(form.getConnectString()); connInfo.setAcl(form.getAcl()); connInfo.setOwner(ShiroUtils.getCurrUser().getLoginName()); connInfo.setRemark(form.getRemark()==null?"未命名":form.getRemark()); connInfo.setSessionTimeout(form.getSessionTimeout()); try { coreService.saveConnection(connInfo); } catch (DataExistException e) { return Result.errorWrapper(e.getMessage()); } return Result.SIMPLE_SUCCESS; }
/** * POST /operinos/:id/components : add the component posted to the "id" operino. * * @param id the id of the operino to add component to * @return the ResponseEntity with status 201 (OK) and with body the operino, or with status 404 (Not Found) */ @PostMapping("/operinos/{id}/components") @Timed public ResponseEntity<OperinoComponent> addOperinoComponent(@PathVariable Long id, @Valid @RequestBody OperinoComponent operinoComponent) throws URISyntaxException { log.debug("REST request to get components for Operino : {}", id); Operino operino = operinoService.verifyOwnershipAndGet(id); if (operino != null) { if (operinoComponent.getId() != null) { return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new operinoComponent cannot already have an ID")).body(null); } operinoComponent.setOperino(operino); OperinoComponent result = operinoComponentService.save(operinoComponent); operino.addComponents(result); // also save operino operinoService.save(operino); return ResponseEntity.created(new URI("/api/operino-components/" + result.getId())) .headers(HeaderUtil.createEntityCreationAlert(COMPONENT_ENTITY_NAME, result.getId().toString())) .body(result); } else { return ResponseEntity.badRequest() .headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "Not found", String.valueOf(id))).build(); } }
/** * Cadastra uma pessoa jurídica no sistema. * * @param cadastroPJDto * @param result * @return ResponseEntity<Response<CadastroPJDto>> * @throws NoSuchAlgorithmException */ @PostMapping public ResponseEntity<Response<CadastroPJDto>> cadastrar(@Valid @RequestBody CadastroPJDto cadastroPJDto, BindingResult result) throws NoSuchAlgorithmException { log.info("Cadastrando PJ: {}", cadastroPJDto.toString()); Response<CadastroPJDto> response = new Response<CadastroPJDto>(); validarDadosExistentes(cadastroPJDto, result); Empresa empresa = this.converterDtoParaEmpresa(cadastroPJDto); Funcionario funcionario = this.converterDtoParaFuncionario(cadastroPJDto, result); if (result.hasErrors()) { log.error("Erro validando dados de cadastro PJ: {}", result.getAllErrors()); result.getAllErrors().forEach(error -> response.getErrors().add(error.getDefaultMessage())); return ResponseEntity.badRequest().body(response); } this.empresaService.persistir(empresa); funcionario.setEmpresa(empresa); this.funcionarioService.persistir(funcionario); response.setData(this.converterCadastroPJDto(funcionario)); return ResponseEntity.ok(response); }
@RequestMapping(value = "/new", method = RequestMethod.POST) public String createEvent(@Valid CreateEventForm createEventForm, BindingResult result, RedirectAttributes redirectAttributes) { if (result.hasErrors()) { return "events/create"; } CalendarUser attendee = calendarService.findUserByEmail(createEventForm.getAttendeeEmail()); if (attendee == null) { result.rejectValue("attendeeEmail", "attendeeEmail.missing", "Could not find a user for the provided Attendee Email"); } if (result.hasErrors()) { return "events/create"; } Event event = new Event(); event.setAttendee(attendee); event.setDescription(createEventForm.getDescription()); event.setOwner(userContext.getCurrentUser()); event.setSummary(createEventForm.getSummary()); event.setWhen(createEventForm.getWhen()); calendarService.createEvent(event); redirectAttributes.addFlashAttribute("message", "Successfully added the new event"); return "redirect:/events/my"; }
@PUT @Path("/uuid/{id}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @ApiOperation( value = "Update an existing ObjectType.", notes = "This operation updates an existing ObjectType.", response = ObjectType.class ) @ApiResponses({ @ApiResponse(code = 401, message = "User could not be authenticated."), @ApiResponse(code = 403, message = "User is not allowed to perform this operation."), @ApiResponse(code = 404, message = "ObjectType does not exist."), @ApiResponse(code = 412, message = "Any parameter has an invalid format.") }) public Response updateObjectType( @PathParam("id") @ApiParam(value = "UUID of ObjectType.") @NotNull @Valid UUID id, @ApiParam(value = "Request to update ObjectType.") @NotNull @Valid UpdateObjectTypeRequest request ) throws AccessDeniedException, AuthenticationFailedException, InvalidArgumentException, ObjectNotFoundException { return buildResponse(service.updateObjectType(getHeader(), request.setId(id))); }
@RequestMapping(value = "/login" , method=RequestMethod.GET) @Menu(type = "apps" , subtype = "user" , access = true) public ModelAndView login(HttpServletRequest request, HttpServletResponse response , @RequestHeader(value = "referer", required = false) String referer , @Valid String msg) { ModelAndView view = request(super.createRequestPageTempletResponse("redirect:/")); if(request.getSession(true).getAttribute(UKDataContext.USER_SESSION_NAME) ==null){ view = request(super.createRequestPageTempletResponse("/login")); if(!StringUtils.isBlank(request.getParameter("referer"))){ referer = request.getParameter("referer") ; } if(!StringUtils.isBlank(referer)){ view.addObject("referer", referer) ; } } if(!StringUtils.isBlank(msg)){ view.addObject("msg", msg) ; } return view; }
@RequestMapping(value = "/FinalizarCompraSegura") public String comprar(Model model, @Valid Pedido pedido, HttpSession session, BindingResult result) { Cliente cliente = (Cliente) session.getAttribute("clienteLogado"); Carrinho carrinho = (Carrinho) session.getAttribute("carrinho"); // Gerar numero randomico int min = 100000000;//na vdd s�o 14 campos int max = 999999999; int numb_ped = ThreadLocalRandom.current().nextInt(min, max + 1); pedido.setNumero_ped(numb_ped); if(result.hasErrors()) { return "forward:forma_de_pagamento"; } else { carrinho.removeAll(); session.setAttribute("carrinho", carrinho); Long id = dao.create(pedido, carrinho, cliente); return "redirect:boleto/"+id; } }
/** * {@inheritDoc} */ @Override public Long createPhoto( @NotNull @Valid final ImageRequest photo, @NotNull final MovieEntity movie ) { log.info("Called with photo {}, movie {}", photo, movie); final MoviePhotoEntity moviePhoto = new MoviePhotoEntity(); moviePhoto.setIdInCloud(photo.getIdInCloud()); moviePhoto.setMovie(movie); movie.getPhotos().add(moviePhoto); this.movieRepository.save(movie); return Iterables.getLast(movie.getPhotos()).getId(); }
/** * PUT /users : Updates an existing User. * * @param userDTO the user to update * @return the ResponseEntity with status 200 (OK) and with body the updated user * @throws EmailAlreadyUsedException 400 (Bad Request) if the email is already in use * @throws LoginAlreadyUsedException 400 (Bad Request) if the login is already in use */ @PutMapping("/users") @Timed @Secured(AuthoritiesConstants.ADMIN) public ResponseEntity<UserDTO> updateUser(@Valid @RequestBody UserDTO userDTO) { log.debug("REST request to update User : {}", userDTO); Optional<User> existingUser = userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()); if (existingUser.isPresent() && (!existingUser.get().getId().equals(userDTO.getId()))) { throw new EmailAlreadyUsedException(); } existingUser = userRepository.findOneByLogin(userDTO.getLogin().toLowerCase()); if (existingUser.isPresent() && (!existingUser.get().getId().equals(userDTO.getId()))) { throw new LoginAlreadyUsedException(); } Optional<UserDTO> updatedUser = userService.updateUser(userDTO); return ResponseUtil.wrapOrNotFound(updatedUser, HeaderUtil.createAlert("userManagement.updated", userDTO.getLogin())); }
@RequestMapping(value="/signup/new",method=RequestMethod.POST) public String signup(@Valid SignupForm signupForm, BindingResult result, RedirectAttributes redirectAttributes) { if(result.hasErrors()) { return "signup/form"; } String email = signupForm.getEmail(); if(calendarService.findUserByEmail(email) != null) { result.rejectValue("email", "errors.signup.email", "Email address is already in use."); return "signup/form"; } CalendarUser user = new CalendarUser(); user.setEmail(email); user.setFirstName(signupForm.getFirstName()); user.setLastName(signupForm.getLastName()); user.setPassword(signupForm.getPassword()); logger.info("CalendarUser: {}", user); int id = calendarService.createUser(user); user.setId(id); userContext.setCurrentUser(user); redirectAttributes.addFlashAttribute("message", "You have successfully signed up and logged in."); return "redirect:/"; }
@PostMapping(value="/signup/new") public String signup(@Valid SignupForm signupForm, BindingResult result, RedirectAttributes redirectAttributes) { if(result.hasErrors()) { return "signup/form"; } String email = signupForm.getEmail(); if(calendarService.findUserByEmail(email) != null) { result.rejectValue("email", "errors.signup.email", "Email address is already in use."); return "signup/form"; } CalendarUser user = new CalendarUser(); user.setEmail(email); user.setFirstName(signupForm.getFirstName()); user.setLastName(signupForm.getLastName()); user.setPassword(signupForm.getPassword()); logger.info("CalendarUser: {}", user); int id = calendarService.createUser(user); user.setId(id); userContext.setCurrentUser(user); redirectAttributes.addFlashAttribute("message", "You have successfully signed up and logged in."); return "redirect:/"; }
/** * POST /account : update the current user information. * * @param user the current user information * @return the ResponseEntity with status 200 (OK), or status 400 (Bad Request) or 500 (Internal * Server Error) if the user couldn't be updated */ @PostMapping("/account") @Timed public ResponseEntity saveAccount(@Valid @RequestBody UserDTO user) { user.getLogins().forEach(userLogin -> userLoginRepository.findOneByLoginIgnoreCaseAndUserIdNot( userLogin.getLogin(), user.getId()).ifPresent(s -> { throw new BusinessException(LOGIN_IS_USED_ERROR_TEXT); })); Optional<UserDTO> updatedUser = accountService.updateAccount(user); updatedUser.ifPresent(userDTO -> produceEvent(userDTO, Constants.UPDATE_PROFILE_EVENT_TYPE)); return ResponseUtil.wrapOrNotFound(updatedUser, HeaderUtil.createAlert("userManagement.updated", user.getUserKey())); }
/** * Get queue * @return queue **/ @ApiModelProperty(value = "") @Valid public Link getQueue() { return queue; }
@GET @Produces(SseFeature.SERVER_SENT_EVENTS) @NoCache public EventOutput getServerSentEventsFull( @NotNull @Valid @BeanParam SubscriptionRequestParams subscriptionRequestParams) { return createEventOutput(subscriptionRequestParams, true); }
/** * POST /brands : Create a new brand. * * @param brand the brand to create * @return the ResponseEntity with status 201 (Created) and with body the new brand, or with status 400 (Bad Request) if the brand has already an ID * @throws URISyntaxException if the Location URI syntax is incorrect */ @PostMapping("/brands") @Timed public ResponseEntity<Brand> createBrand(@Valid @RequestBody Brand brand) throws URISyntaxException { log.debug("REST request to save Brand : {}", brand); if (brand.getId() != null) { return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new brand cannot already have an ID")).body(null); } Brand result = brandService.save(brand); return ResponseEntity.created(new URI("/api/brands/" + result.getId())) .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString())) .body(result); }
/** * This method will be called on form submission, handling POST request for * saving user in database. It also validates the user input */ @RequestMapping(value = {"/studentregistration"}, method = RequestMethod.POST) public String saveStudentUser(@Valid StudentUser user, BindingResult result, ModelMap model) { if (result.hasErrors()) { return "studentregistration"; } /* * Preferred way to achieve uniqueness of field [sso] should be implementing custom @Unique annotation * and applying it on field [sso] of Model class [User]. * * Below mentioned peace of code [if block] is to demonstrate that you can fill custom errors outside the validation * framework as well while still using internationalized messages. * */ if (!userService.isStudentUnique(user.getStudentUserId(), user.getEmail())) { FieldError ssoError = new FieldError("studentuser", "email", messageSource.getMessage("non.unique.ssoId", new String[]{user.getEmail()}, Locale.getDefault())); result.addError(ssoError); model.addAttribute("loggedinuser", getPrincipal()); return "studentregistration"; } userService.saveUser(user); model.addAttribute("success", "User " + user.getFirstName() + " " + user.getLastName() + " registered successfully"); model.addAttribute("loggedinuser", getPrincipal()); //return "success"; return "registrationsuccess"; }
@RequestMapping(value="/validations/{id}", method=RequestMethod.PUT, produces={ MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity<Validation> updateValidation(@PathVariable(value="id") Integer validationId, @Valid @RequestBody Validation validationDetails) { Validation validation = validationRepository.findOne(validationId); if(validation == null) return ResponseEntity.notFound().build(); validation.setUserId(validationDetails.getUserId()); validation.setProjectId(validationDetails.getProjectId()); validation.setProjectStatus(validationDetails.getProjectStatus()); Validation updatedValidation = validationRepository.save(validation); return ResponseEntity.ok(updatedValidation); }
/** * PUT /blogs : Updates an existing blog. * * @param blog the blog to update * @return the ResponseEntity with status 200 (OK) and with body the updated blog, * or with status 400 (Bad Request) if the blog is not valid, * or with status 500 (Internal Server Error) if the blog couldnt be updated * @throws URISyntaxException if the Location URI syntax is incorrect */ @PutMapping("/blogs") @Timed public ResponseEntity<Blog> updateBlog(@Valid @RequestBody Blog blog) throws URISyntaxException { log.debug("REST request to update Blog : {}", blog); if (blog.getId() == null) { return createBlog(blog); } Blog result = blogRepository.save(blog); blogSearchRepository.save(result); return ResponseEntity.ok() .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, blog.getId().toString())) .body(result); }