public static ValidatorFactory buildFactory( final ValidationInfo config, final ClassLoader classLoader) { ValidatorFactory factory = null; final Thread thread = Thread.currentThread(); final ClassLoader oldContextLoader = thread.getContextClassLoader(); try { thread.setContextClassLoader(classLoader); if (config == null) { factory = Validation.buildDefaultValidatorFactory(); } else { final Configuration<?> configuration = getConfig(config); try { factory = configuration.buildValidatorFactory(); } catch (final ValidationException ve) { thread.setContextClassLoader(ValidatorBuilder.class.getClassLoader()); factory = Validation.buildDefaultValidatorFactory(); thread.setContextClassLoader(classLoader); logger.warning( "Unable create validator factory with config " + config + " (" + ve.getMessage() + ")." + " Default factory will be used."); } } } finally { thread.setContextClassLoader(oldContextLoader); } return factory; }
@Override public String save( HttpServletRequest request, @ModelAttribute("modelObject") ShiftCalendar entity, BindingResult bindingResult, ModelMap model) { if (entity.getCompany() == null) { bindingResult.rejectValue("company", "error.select.option", null, null); } if (entity.getEffectivestartdate() != null && entity.getEffectiveenddate() != null) { if (entity.getEffectiveenddate().before(entity.getEffectivestartdate())) { bindingResult.rejectValue("effectivestartdate", "error.textbox.StartEndDate", null, null); } } if (entity.getStarttimehours() != null && entity.getStarttimeminutes() != null) { String s1 = entity.getStarttimehours(); String s2 = entity.getStarttimeminutes(); String s3 = s1 + ":" + s2; entity.setStarttime(s3); } if (entity.getEndtimehours() != null && entity.getEndtimeminutes() != null) { String s1 = entity.getEndtimehours(); String s2 = entity.getEndtimeminutes(); String s3 = s1 + ":" + s2; entity.setEndtime(s3); } try { getValidator().validate(entity, bindingResult); } catch (ValidationException e) { e.printStackTrace(); log.warn("Error in validation :" + e); } // return to form if we had errors if (bindingResult.hasErrors()) { setupCreate(model, request); bindingResult.getFieldError(); // System.out.println("\nsave--bindingResult.hasErrors()=="+bindingResult.getFieldError()+"\n"); return urlContext + "/form"; } beforeSave(request, entity, model); // merge into datasource // System.out.println("\nsave\n"); genericDAO.saveOrUpdate(entity); cleanUp(request); // return to list return "redirect:/" + urlContext + "/list.do"; // // return super.save(request, entity, bindingResult, model); }
@Test public void handlingValidationExceptionCausedByInvalidParameter() { try { hello.say("Nurse"); fail(); } catch (ValidationException cause) { assertEquals(IllegalArgumentException.class, cause.getCause().getClass()); } }
@Test public void handlingValidationExceptionCausedByNullParameter() { try { hello.say(null); fail(); } catch (ValidationException cause) { assertEquals(NullPointerException.class, cause.getCause().getClass()); } }
static Validator getBeanValidator() { if (beanValidator == null) { try { ValidatorFactory f = Validation.buildDefaultValidatorFactory(); return f.getValidator(); } catch (ValidationException e) { LOG.info("No JSR-303 bean validation configuration found: " + e.getMessage()); return null; } } return beanValidator; }
@Override public String save( HttpServletRequest request, @ModelAttribute("modelObject") Invoice entity, BindingResult bindingResult, ModelMap model) { // TODO Auto-generated method stub if (entity.getTransferStation() == null) { bindingResult.rejectValue("transferStation", "error.select.option", null, null); } if (entity.getLandfill() == null) { bindingResult.rejectValue("landfill", "error.select.option", null, null); } // validate entity try { getValidator().validate(entity, bindingResult); } catch (ValidationException e) { e.printStackTrace(); log.warn("Error in validation :" + e); } // return to form if we had errors if (bindingResult.hasErrors()) { setupCreate(model, request); return urlContext + "/form"; } String path = Configuration.getProperty("storage.folder.repository") + "/" + "invoice"; CommonsMultipartFile file = entity.getInvoiceFile(); String invoicefileName = file.getOriginalFilename(); File folderpath = new File(path); try { if (!folderpath.exists()) { folderpath.mkdirs(); } String fullpath = path + "/" + invoicefileName; System.out.println(fullpath); File invoicefile = new File(fullpath); if (!invoicefile.exists()) { invoicefile.createNewFile(); } file.transferTo(invoicefile); entity.setFilePath(fullpath); beforeSave(request, entity, model); // merge into datasource genericDAO.saveOrUpdate(entity); cleanUp(request); } catch (IOException e) { e.printStackTrace(); } return "redirect:list.do"; }
public String confirmar() { try { getService().save(idioma); MessagesUtil.addInfoMessage("msg.salvar.sucesso", true); setOperacao(Operacao.PESQUISAR); return pesquisar(); } catch (ValidationException e) { MessagesUtil.addErrorMessage(e.getMessage(), true); } catch (Exception e) { MessagesUtil.addErrorMessage("msg.salvar.erro", e.getMessage(), true); } return getRetorno(); }
@SuppressWarnings("unchecked") private static Configuration<?> getConfig(final ValidationInfo info) { Configuration<?> target = null; final Thread thread = Thread.currentThread(); final ClassLoader classLoader = thread.getContextClassLoader(); String providerClassName = info.providerClassName; if (providerClassName == null) { providerClassName = SystemInstance.get().getOptions().get(VALIDATION_PROVIDER_KEY, (String) null); } if (providerClassName != null) { try { @SuppressWarnings({"unchecked", "rawtypes"}) final Class clazz = classLoader.loadClass(providerClassName); target = Validation.byProvider(clazz).configure(); logger.info("Using " + providerClassName + " as validation provider."); } catch (final ClassNotFoundException e) { logger.warning("Unable to load provider class " + providerClassName, e); } catch (final ValidationException ve) { logger.warning( "Unable create validator factory with provider " + providerClassName + " (" + ve.getMessage() + ")." + " Default one will be used."); } } if (target == null) { // force to use container provider to ignore any conflicting configuration thread.setContextClassLoader(ValidatorBuilder.class.getClassLoader()); target = Validation.byDefaultProvider().configure(); thread.setContextClassLoader(classLoader); } final Set<ExecutableType> types = new HashSet<>(); for (final String type : info.validatedTypes) { types.add(ExecutableType.valueOf(type)); } final Map<String, String> props = new HashMap<>(); for (final Map.Entry<Object, Object> entry : info.propertyTypes.entrySet()) { final PropertyType property = new PropertyType(); property.setName((String) entry.getKey()); property.setValue((String) entry.getValue()); props.put(property.getName(), property.getValue()); if (logger.isDebugEnabled()) { logger.debug( "Found property '" + property.getName() + "' with value '" + property.getValue()); } target.addProperty(property.getName(), property.getValue()); } final OpenEjbBootstrapConfig bootstrapConfig = new OpenEjbBootstrapConfig( providerClassName, info.constraintFactoryClass, info.messageInterpolatorClass, info.traversableResolverClass, info.parameterNameProviderClass, new HashSet<>(info.constraintMappings), info.executableValidationEnabled, types, props); final OpenEjbConfig config = new OpenEjbConfig(bootstrapConfig, target); target.ignoreXmlConfiguration(); final String messageInterpolatorClass = info.messageInterpolatorClass; if (messageInterpolatorClass != null) { try { @SuppressWarnings("unchecked") final Class<MessageInterpolator> clazz = (Class<MessageInterpolator>) classLoader.loadClass(messageInterpolatorClass); target.messageInterpolator(newInstance(config, clazz)); } catch (final Exception e) { logger.warning( "Unable to set " + messageInterpolatorClass + " as message interpolator.", e); } logger.info("Using " + messageInterpolatorClass + " as message interpolator."); } final String traversableResolverClass = info.traversableResolverClass; if (traversableResolverClass != null) { try { @SuppressWarnings("unchecked") final Class<TraversableResolver> clazz = (Class<TraversableResolver>) classLoader.loadClass(traversableResolverClass); target.traversableResolver(newInstance(config, clazz)); } catch (final Exception e) { logger.warning( "Unable to set " + traversableResolverClass + " as traversable resolver.", e); } logger.info("Using " + traversableResolverClass + " as traversable resolver."); } final String constraintFactoryClass = info.constraintFactoryClass; if (constraintFactoryClass != null) { try { @SuppressWarnings("unchecked") final Class<ConstraintValidatorFactory> clazz = (Class<ConstraintValidatorFactory>) classLoader.loadClass(constraintFactoryClass); target.constraintValidatorFactory(newInstance(config, clazz)); } catch (final Exception e) { logger.warning("Unable to set " + constraintFactoryClass + " as constraint factory.", e); } logger.info("Using " + constraintFactoryClass + " as constraint factory."); } for (final String mappingFileName : info.constraintMappings) { if (logger.isDebugEnabled()) { logger.debug("Opening input stream for " + mappingFileName); } final InputStream in = classLoader.getResourceAsStream(mappingFileName); if (in == null) { logger.warning( "Unable to open input stream for mapping file " + mappingFileName + ". It will be ignored"); } else { target.addMapping(in); } } if (info.parameterNameProviderClass != null) { try { final Class<ParameterNameProvider> clazz = (Class<ParameterNameProvider>) classLoader.loadClass(info.parameterNameProviderClass); target.parameterNameProvider(newInstance(config, clazz)); } catch (final Exception e) { logger.warning( "Unable to set " + info.parameterNameProviderClass + " as parameter name provider.", e); } logger.info("Using " + info.parameterNameProviderClass + " as parameter name provider."); } return config; }
@Override public String save( HttpServletRequest request, @ModelAttribute("modelObject") DriverFuelCard entity, BindingResult bindingResult, ModelMap model) { if (entity.getDriver() == null) { bindingResult.rejectValue("driver", "error.select.option", null, null); } if (entity.getFuelvendor() == null) { bindingResult.rejectValue("fuelvendor", "error.select.option", null, null); } if (entity.getFuelcard() == null) { bindingResult.rejectValue("fuelcard", "error.select.option", null, null); } /*else{ if (entity.getFuelvendor() == null) { } else { Map criterias = new HashMap(); criterias.clear(); criterias.put("fuelvendor.id",entity.getFuelvendor().getId()); criterias.put("id",entity.getFuelcard().getId()); List<FuelCard> fuelcards=genericDAO.findByCriteria(FuelCard.class, criterias, "fuelvendor", false); if(fuelcards.isEmpty() || fuelcards.size()==0){ bindingResult.rejectValue("fuelcard", "error.select.mismatch", null, null); } } }*/ try { getValidator().validate(entity, bindingResult); } catch (ValidationException e) { e.printStackTrace(); log.warn("Error in validation :" + e); } // return to form if we had errors if (bindingResult.hasErrors()) { setupCreate(model, request); if (entity.getFuelcard() == null) { if (entity.getFuelvendor() != null) { Map criteria = new HashMap(); criteria.put("fuelvendor.id", Long.parseLong(request.getParameter("fuelvendor"))); model.addAttribute( "fuelcard", genericDAO.findByCriteria(FuelCard.class, criteria, "fuelcardNum", false)); } } return urlContext + "/form"; } Map prop = new HashMap(); prop.put("fuelvendor", entity.getFuelvendor().getId()); prop.put("driver", entity.getDriver().getId()); prop.put("fuelcard", entity.getFuelcard().getId()); boolean rst = genericDAO.isUnique(DriverFuelCard.class, entity, prop); if (!rst) { setupCreate(model, request); Map criteria = new HashMap(); criteria.put("fuelvendor.id", Long.parseLong(request.getParameter("fuelvendor"))); model.addAttribute( "fuelcard", genericDAO.findByCriteria(FuelCard.class, criteria, "fuelcardNum", false)); request .getSession() .setAttribute( "error", "Duplicate Entry! Same Card is already been assigned to this Driver."); return urlContext + "/form"; } beforeSave(request, entity, model); // merge into datasource genericDAO.saveOrUpdate(entity); cleanUp(request); // return to list return "redirect:/" + urlContext + "/list.do"; // return super.save(request, entity, bindingResult, model); }