當前位置: 首頁>>代碼示例>>Java>>正文


Java Valid類代碼示例

本文整理匯總了Java中javax.validation.Valid的典型用法代碼示例。如果您正苦於以下問題:Java Valid類的具體用法?Java Valid怎麽用?Java Valid使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Valid類屬於javax.validation包,在下文中一共展示了Valid類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: authorize

import javax.validation.Valid; //導入依賴的package包/類
@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);
    }
}
 
開發者ID:oktadeveloper,項目名稱:jhipster-microservices-example,代碼行數:21,代碼來源:UserJWTController.java

示例2: address

import javax.validation.Valid; //導入依賴的package包/類
@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);
}
 
開發者ID:modum-io,項目名稱:tokenapp-backend,代碼行數:23,代碼來源:AddressController.java

示例3: saveOrUpdateAlbum

import javax.validation.Valid; //導入依賴的package包/類
@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();
}
 
開發者ID:fontinixxl,項目名稱:our-album-collection,代碼行數:21,代碼來源:AlbumController.java

示例4: saveUserAccount

import javax.validation.Valid; //導入依賴的package包/類
@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";
}
 
開發者ID:TomirKlos,項目名稱:Webstore,代碼行數:19,代碼來源:UserController.java

示例5: updateOrganization

import javax.validation.Valid; //導入依賴的package包/類
@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;
}
 
開發者ID:Code4SocialGood,項目名稱:C4SG-Obsolete,代碼行數:18,代碼來源:OrganizationController.java

示例6: save

import javax.validation.Valid; //導入依賴的package包/類
@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);
}
 
開發者ID:ldlood,項目名稱:SpringBoot_Wechat_Sell,代碼行數:27,代碼來源:SellerCategoryController.java

示例7: login

import javax.validation.Valid; //導入依賴的package包/類
@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);

}
 
開發者ID:melonlee,項目名稱:LazyREST,代碼行數:20,代碼來源:UserController.java

示例8: createEvent

import javax.validation.Valid; //導入依賴的package包/類
@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";
}
 
開發者ID:PacktPublishing,項目名稱:Spring-Security-Third-Edition,代碼行數:25,代碼來源:EventsController.java

示例9: createTag

import javax.validation.Valid; //導入依賴的package包/類
/**
 * 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);
}
 
開發者ID:ugouku,項目名稱:shoucang,代碼行數:19,代碼來源:TagResource.java

示例10: modifyPwd

import javax.validation.Valid; //導入依賴的package包/類
/**
 * 修改密碼
 * @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();
}
 
開發者ID:nyh137,項目名稱:SSMFrameBase,代碼行數:13,代碼來源:UserController.java

示例11: changepass

import javax.validation.Valid; //導入依賴的package包/類
@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;
}
 
開發者ID:codenergic,項目名稱:theskeleton,代碼行數:16,代碼來源:ChangePasswordController.java

示例12: heartbeat

import javax.validation.Valid; //導入依賴的package包/類
/**
 * 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));
}
 
開發者ID:CloudWise-OpenSource,項目名稱:SAPNetworkMonitor,代碼行數:33,代碼來源:MonitorResource.java

示例13: getDataToSign

import javax.validation.Valid; //導入依賴的package包/類
@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;
}
 
開發者ID:esig,項目名稱:dss-demonstrations,代碼行數:20,代碼來源:SignatureMultipleDocumentsController.java

示例14: updateOtherTitleContribution

import javax.validation.Valid; //導入依賴的package包/類
@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());
}
 
開發者ID:JonkiPro,項目名稱:REST-Web-Services,代碼行數:21,代碼來源:MovieContributionRestController.java

示例15: find

import javax.validation.Valid; //導入依賴的package包/類
@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();
}
 
開發者ID:Fatlonder,項目名稱:E-Clinic,代碼行數:20,代碼來源:ClinicManagerRestEndPoint.java


注:本文中的javax.validation.Valid類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。