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


Java ObjectError類代碼示例

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


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

示例1: add

import org.springframework.validation.ObjectError; //導入依賴的package包/類
@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);
}
 
開發者ID:hzwy23,項目名稱:batch-scheduler,代碼行數:20,代碼來源:TaskDefineController.java

示例2: handleMethodArgumentNotValidException

import org.springframework.validation.ObjectError; //導入依賴的package包/類
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ResponseBody
public XAPIErrorInfo handleMethodArgumentNotValidException(final HttpServletRequest request, MethodArgumentNotValidException e) {
    final List<String> errorMessages = new ArrayList<String>();
    for (ObjectError oe : e.getBindingResult().getAllErrors()) {
        if (oe instanceof FieldError) {
            final FieldError fe = (FieldError)oe;
            final String msg = String.format(
                    "Field error in object '%s' on field '%s': rejected value [%s].", fe.getObjectName(), fe.getField(), fe.getRejectedValue());
            errorMessages.add(msg);
        } else {
            errorMessages.add(oe.toString());
        }
    }
    final XAPIErrorInfo result = new XAPIErrorInfo(HttpStatus.BAD_REQUEST, request, errorMessages);
    this.logException(e);
    this.logError(result);
    return result;
}
 
開發者ID:Apereo-Learning-Analytics-Initiative,項目名稱:OpenLRW,代碼行數:21,代碼來源:XAPIExceptionHandlerAdvice.java

示例3: escapeObjectError

import org.springframework.validation.ObjectError; //導入依賴的package包/類
@SuppressWarnings("unchecked")
private <T extends ObjectError> T escapeObjectError(T source) {
	if (source == null) {
		return null;
	}
	if (source instanceof FieldError) {
		FieldError fieldError = (FieldError) source;
		Object value = fieldError.getRejectedValue();
		if (value instanceof String) {
			value = HtmlUtils.htmlEscape((String) value);
		}
		return (T) new FieldError(
				fieldError.getObjectName(), fieldError.getField(), value,
				fieldError.isBindingFailure(), fieldError.getCodes(),
				fieldError.getArguments(), HtmlUtils.htmlEscape(fieldError.getDefaultMessage()));
	}
	else {
		return (T) new ObjectError(
				source.getObjectName(), source.getCodes(), source.getArguments(),
				HtmlUtils.htmlEscape(source.getDefaultMessage()));
	}
}
 
開發者ID:langtianya,項目名稱:spring4-understanding,代碼行數:23,代碼來源:EscapedErrors.java

示例4: getMatcher

import org.springframework.validation.ObjectError; //導入依賴的package包/類
private BaseMatcher<BindException> getMatcher(String message, String field) {
	return new BaseMatcher<BindException>() {

		@Override
		public void describeTo(Description description) {

		}

		@Override
		public boolean matches(Object item) {
			BindException ex = (BindException) ((Exception) item).getCause();
			ObjectError error = ex.getAllErrors().get(0);
			boolean messageMatches = message.equals(error.getDefaultMessage());
			if (field == null) {
				return messageMatches;
			}
			String fieldErrors = ((FieldError) error).getField();
			return messageMatches && fieldErrors.equals(field);
		}

	};
}
 
開發者ID:spring-projects,項目名稱:spring-security-oauth2-boot,代碼行數:23,代碼來源:ResourceServerPropertiesTests.java

示例5: main

import org.springframework.validation.ObjectError; //導入依賴的package包/類
public static void main(String[] args) throws Exception {
  // below is output *before* logging is configured so will appear on console
  logVersionInfo();

  try {
    SpringApplication.exit(new SpringApplicationBuilder(ComparisonTool.class)
        .properties("spring.config.location:${config:null}")
        .properties("spring.profiles.active:" + Modules.REPLICATION)
        .properties("instance.home:${user.home}")
        .properties("instance.name:${source-catalog.name}_${replica-catalog.name}")
        .bannerMode(Mode.OFF)
        .registerShutdownHook(true)
        .build()
        .run(args));
  } catch (BeanCreationException e) {
    if (e.getMostSpecificCause() instanceof BindException) {
      printComparisonToolHelp(((BindException) e.getMostSpecificCause()).getAllErrors());
      throw e;
    }
    if (e.getMostSpecificCause() instanceof IllegalArgumentException) {
      LOG.error(e.getMessage(), e);
      printComparisonToolHelp(Collections.<ObjectError> emptyList());
    }
  }
}
 
開發者ID:HotelsDotCom,項目名稱:circus-train,代碼行數:26,代碼來源:ComparisonTool.java

示例6: add

import org.springframework.validation.ObjectError; //導入依賴的package包/類
/**
 * 新增域
 */
@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);
}
 
開發者ID:hzwy23,項目名稱:batch-scheduler,代碼行數:28,代碼來源:DomainController.java

示例7: update

import org.springframework.validation.ObjectError; //導入依賴的package包/類
@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);
}
 
開發者ID:hzwy23,項目名稱:batch-scheduler,代碼行數:18,代碼來源:TaskDefineController.java

示例8: atualizar

import org.springframework.validation.ObjectError; //導入依賴的package包/類
/**
 * Atualiza os dados de um funcionário.
 * 
 * @param id
 * @param funcionarioDto
 * @param result
 * @return ResponseEntity<Response<FuncionarioDto>>
 * @throws NoSuchAlgorithmException
 */
@PutMapping(value = "/{id}")
public ResponseEntity<Response<FuncionarioDto>> atualizar(@PathVariable("id") Long id,
		@Valid @RequestBody FuncionarioDto funcionarioDto, BindingResult result) throws NoSuchAlgorithmException {
	log.info("Atualizando funcionário: {}", funcionarioDto.toString());
	Response<FuncionarioDto> response = new Response<FuncionarioDto>();

	Optional<Funcionario> funcionario = this.funcionarioService.buscarPorId(id);
	if (!funcionario.isPresent()) {
		result.addError(new ObjectError("funcionario", "Funcionário não encontrado."));
	}

	this.atualizarDadosFuncionario(funcionario.get(), funcionarioDto, result);

	if (result.hasErrors()) {
		log.error("Erro validando funcionário: {}", result.getAllErrors());
		result.getAllErrors().forEach(error -> response.getErrors().add(error.getDefaultMessage()));
		return ResponseEntity.badRequest().body(response);
	}

	this.funcionarioService.persistir(funcionario.get());
	response.setData(this.converterFuncionarioDto(funcionario.get()));

	return ResponseEntity.ok(response);
}
 
開發者ID:m4rciosouza,項目名稱:ponto-inteligente-api,代碼行數:34,代碼來源:FuncionarioController.java

示例9: atualizarDadosFuncionario

import org.springframework.validation.ObjectError; //導入依賴的package包/類
/**
 * Atualiza os dados do funcionário com base nos dados encontrados no DTO.
 * 
 * @param funcionario
 * @param funcionarioDto
 * @param result
 * @throws NoSuchAlgorithmException
 */
private void atualizarDadosFuncionario(Funcionario funcionario, FuncionarioDto funcionarioDto, BindingResult result)
		throws NoSuchAlgorithmException {
	funcionario.setNome(funcionarioDto.getNome());

	if (!funcionario.getEmail().equals(funcionarioDto.getEmail())) {
		this.funcionarioService.buscarPorEmail(funcionarioDto.getEmail())
				.ifPresent(func -> result.addError(new ObjectError("email", "Email já existente.")));
		funcionario.setEmail(funcionarioDto.getEmail());
	}

	funcionario.setQtdHorasAlmoco(null);
	funcionarioDto.getQtdHorasAlmoco()
			.ifPresent(qtdHorasAlmoco -> funcionario.setQtdHorasAlmoco(Float.valueOf(qtdHorasAlmoco)));

	funcionario.setQtdHorasTrabalhoDia(null);
	funcionarioDto.getQtdHorasTrabalhoDia()
			.ifPresent(qtdHorasTrabDia -> funcionario.setQtdHorasTrabalhoDia(Float.valueOf(qtdHorasTrabDia)));

	funcionario.setValorHora(null);
	funcionarioDto.getValorHora().ifPresent(valorHora -> funcionario.setValorHora(new BigDecimal(valorHora)));

	if (funcionarioDto.getSenha().isPresent()) {
		funcionario.setSenha(PasswordUtils.gerarBCrypt(funcionarioDto.getSenha().get()));
	}
}
 
開發者ID:m4rciosouza,項目名稱:ponto-inteligente-api,代碼行數:34,代碼來源:FuncionarioController.java

示例10: createCategory

import org.springframework.validation.ObjectError; //導入依賴的package包/類
@RequestMapping(value = "/category/create", method = RequestMethod.POST)
public String createCategory(@Valid @ModelAttribute CategoryDTO categoryDTO, BindingResult br, RedirectAttributes attr){
    if(br.hasErrors()){
        StringBuilder errorMsg = new StringBuilder();
        for(ObjectError i : br.getAllErrors()){
            errorMsg.append(i.getDefaultMessage());
        }
        attr.addFlashAttribute("error", errorMsg.toString());
        return "redirect:/error";
    }

    Category category = new Category();
    category.setCategoryName(categoryDTO.getCategoryNew());
    try{
        categoryService.saveCategory(category);
        categoryService.uploadCategoryStarterFiles(categoryDTO.getCategoryNew());
    }catch (Exception e){
        attr.addFlashAttribute("error", "Could not create category. Please contact our support team.");
        return "redirect:/error";
    }

    attr.addFlashAttribute("categoryDTO", categoryDTO);
    return "redirect:/admin";

}
 
開發者ID:Exercon,項目名稱:AntiSocial-Platform,代碼行數:26,代碼來源:AdminController.java

示例11: createCategory

import org.springframework.validation.ObjectError; //導入依賴的package包/類
@RequestMapping(value = "/category/create", method = RequestMethod.POST)
public String createCategory(@Valid @ModelAttribute CategoryDTO categoryDTO, BindingResult br, RedirectAttributes attr){
    if(br.hasErrors()){
        StringBuilder errorMsg = new StringBuilder();
        for(ObjectError i : br.getAllErrors()){
            errorMsg.append(i.getDefaultMessage());
        }
        attr.addFlashAttribute("error", errorMsg.toString());
        return "redirect:/oups";
    }

    Category category = new Category();
    category.setCategoryName(categoryDTO.getCategoryNew());
    try{
        categoryService.saveCategory(category);
        categoryService.uploadCategoryStarterFiles(categoryDTO.getCategoryNew());
    }catch (Exception e){
        attr.addFlashAttribute("error", "Could not create category. Please contact our support team.");
        return "redirect:/oups";
    }

    attr.addFlashAttribute("categoryDTO", categoryDTO);
    return "redirect:/admin";

}
 
開發者ID:Exercon,項目名稱:AntiSocial-Platform,代碼行數:26,代碼來源:AdminController.java

示例12: resolveError

import org.springframework.validation.ObjectError; //導入依賴的package包/類
private void resolveError(BasicResponse response, ObjectError error) {
    Locale currentLocale = LocaleContextHolder.getLocale();

    String defaultMessage = error.getDefaultMessage();
    if (StringUtils.isNotBlank(defaultMessage) && defaultMessage.startsWith("{DEMO-")) {
        String errorCode = defaultMessage.substring(1, defaultMessage.length() - 1);
        response.setErrorCode(errorCode);
        response.setErrorMessage(getLocalizedErrorMessage(errorCode, error.getArguments()));
    } else {
        String[] errorCodes = error.getCodes();
        for (String code : errorCodes) {
            String message = getLocalizedErrorMessage(currentLocale, code, error.getArguments());
            if (!code.equals(message)) {
                response.setErrorCode(code);
                response.setErrorMessage(message);
                return;
            }
        }

        response.setErrorCode(error.getCode());
        response.setErrorMessage(getLocalizedErrorMessage(error.getCode(), error.getArguments()));
    }
}
 
開發者ID:barrykalok,項目名稱:spring-boot-drools-example,代碼行數:24,代碼來源:ApiControllerAdvice.java

示例13: testSpringValidationWithClassLevel

import org.springframework.validation.ObjectError; //導入依賴的package包/類
@Test
public void testSpringValidationWithClassLevel() throws Exception {
	LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
	validator.afterPropertiesSet();
	ValidPerson person = new ValidPerson();
	person.setName("Juergen");
	person.getAddress().setStreet("Juergen's Street");
	BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person");
	validator.validate(person, result);
	assertEquals(1, result.getErrorCount());
	ObjectError globalError = result.getGlobalError();
	List<String> errorCodes = Arrays.asList(globalError.getCodes());
	assertEquals(2, errorCodes.size());
	assertTrue(errorCodes.contains("NameAddressValid.person"));
	assertTrue(errorCodes.contains("NameAddressValid"));
}
 
開發者ID:langtianya,項目名稱:spring4-understanding,代碼行數:17,代碼來源:ValidatorFactoryTests.java

示例14: testSpringValidationWithClassLevel

import org.springframework.validation.ObjectError; //導入依賴的package包/類
@Test
public void testSpringValidationWithClassLevel() throws Exception {
	LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
	validator.afterPropertiesSet();

	ValidPerson person = new ValidPerson();
	person.setName("Juergen");
	person.getAddress().setStreet("Juergen's Street");
	BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person");
	validator.validate(person, result);
	assertEquals(1, result.getErrorCount());
	ObjectError globalError = result.getGlobalError();
	List<String> errorCodes = Arrays.asList(globalError.getCodes());
	assertEquals(2, errorCodes.size());
	assertTrue(errorCodes.contains("NameAddressValid.person"));
	assertTrue(errorCodes.contains("NameAddressValid"));
}
 
開發者ID:langtianya,項目名稱:spring4-understanding,代碼行數:18,代碼來源:ValidatorFactoryTests.java

示例15: testSpringValidationWithAutowiredValidator

import org.springframework.validation.ObjectError; //導入依賴的package包/類
@Test
public void testSpringValidationWithAutowiredValidator() throws Exception {
	ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(
			LocalValidatorFactoryBean.class);
	LocalValidatorFactoryBean validator = ctx.getBean(LocalValidatorFactoryBean.class);

	ValidPerson person = new ValidPerson();
	person.expectsAutowiredValidator = true;
	person.setName("Juergen");
	person.getAddress().setStreet("Juergen's Street");
	BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person");
	validator.validate(person, result);
	assertEquals(1, result.getErrorCount());
	ObjectError globalError = result.getGlobalError();
	List<String> errorCodes = Arrays.asList(globalError.getCodes());
	assertEquals(2, errorCodes.size());
	assertTrue(errorCodes.contains("NameAddressValid.person"));
	assertTrue(errorCodes.contains("NameAddressValid"));
	ctx.close();
}
 
開發者ID:langtianya,項目名稱:spring4-understanding,代碼行數:21,代碼來源:ValidatorFactoryTests.java


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