当前位置: 首页>>代码示例>>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;未经允许,请勿转载。