javax.validation.MessageInterpolator Java Examples

The following examples show how to use javax.validation.MessageInterpolator. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ValidationManager.java    From seed with Mozilla Public License 2.0 6 votes vote down vote up
public ValidatorFactory createValidatorFactory(Consumer<Configuration> customizer) {
    boolean skipAutoconfig = "false".equalsIgnoreCase(System.getProperty(SEEDSTACK_VALIDATION_AUTOCONFIG, "true"));
    boolean hasXmlConfiguration = findMostCompleteClassLoader(ValidationManager.class)
            .getResource(VALIDATION_XML_FILE) != null;
    if (validationLevel == ValidationLevel.NONE) {
        throw SeedException.createNew(CoreErrorCode.UNABLE_TO_CREATE_VALIDATOR_FACTORY);
    } else {
        try {
            Configuration<?> configuration = Validation.byDefaultProvider().configure();
            if (!hasXmlConfiguration && !skipAutoconfig) {
                Classes.optional("org.seedstack.seed.core.internal.validation.ReflectionParameterNameProvider")
                        .map(Classes::instantiateDefault)
                        .ifPresent(c -> configuration.parameterNameProvider((ParameterNameProvider) c));
                Classes.optional("org.seedstack.seed.core.internal.validation.HibernateMessageInterpolator")
                        .map(Classes::instantiateDefault)
                        .ifPresent(c -> configuration.messageInterpolator((MessageInterpolator) c));
            }
            if (customizer != null) {
                customizer.accept(configuration);
            }
            return configuration.buildValidatorFactory();
        } catch (Exception e) {
            throw SeedException.wrap(e, CoreErrorCode.UNABLE_TO_CREATE_VALIDATOR_FACTORY);
        }
    }
}
 
Example #2
Source File: OsgiMessageInterpolator.java    From packagedrone with Eclipse Public License 1.0 6 votes vote down vote up
protected String resolve ( final String key, final Context context, final Locale locale )
{
    for ( final Resolver resolver : this.tracker.getTracked ().values () )
    {
        final String result = resolver.resolve ( key, context, locale );
        if ( result != null )
        {
            return result;
        }
    }

    final MessageInterpolator fallback = this.fallback;

    if ( fallback == null )
    {
        return null;
    }
    return fallback.interpolate ( String.format ( "{%s}", key ), context, locale );
}
 
Example #3
Source File: BeanValidation.java    From open-Autoscaler with Apache License 2.0 6 votes vote down vote up
public static JsonNode parseScalingHistory(String jsonString, HttpServletRequest httpServletRequest) throws JsonParseException, JsonMappingException, IOException{
	 List<String> violation_message = new ArrayList<String>();
	 ObjectNode result = new_mapper.createObjectNode();
	 result.put("valid", false);
	 JavaType javaType = getCollectionType(ArrayList.class, ArrayList.class, HistoryData.class);
	 new_mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
	 List<HistoryData> scalinghistory = (List<HistoryData>)new_mapper.readValue(jsonString, javaType);
	 ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
	 Locale locale = LocaleUtil.getLocale(httpServletRequest);
	 MessageInterpolator interpolator = new LocaleSpecificMessageInterpolator(vf.getMessageInterpolator(), locale);
	 Validator validator = vf.usingContext().messageInterpolator(interpolator).getValidator();
	 Set<ConstraintViolation<List<HistoryData>>> set = validator.validate(scalinghistory);
	 if (set.size() > 0 ){
		 for (ConstraintViolation<List<HistoryData>> constraintViolation : set) {
			 violation_message.add(constraintViolation.getMessage());
		 }
		 result.set("violation_message", new_mapper.valueToTree(violation_message));
		 return result;
	 }

	 //additional data manipulation
    	 String new_json = transformHistory(scalinghistory);
	 result.put("valid", true);
	 result.put("new_json", new_json);
	 return result;
}
 
Example #4
Source File: BeanValidation.java    From open-Autoscaler with Apache License 2.0 6 votes vote down vote up
public static JsonNode parsePolicyEnable(String jsonString, HttpServletRequest httpServletRequest) throws JsonParseException, JsonMappingException, IOException{
	 List<String> violation_message = new ArrayList<String>();
	 ObjectNode result = new_mapper.createObjectNode();
	 result.put("valid", false);
	 PolicyEnbale policyEnable = new_mapper.readValue(jsonString, PolicyEnbale.class);
	 ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
	 Locale locale = LocaleUtil.getLocale(httpServletRequest);
	 MessageInterpolator interpolator = new LocaleSpecificMessageInterpolator(vf.getMessageInterpolator(), locale);
	 Validator validator = vf.usingContext().messageInterpolator(interpolator).getValidator();
	 Set<ConstraintViolation<PolicyEnbale>> set = validator.validate(policyEnable);
	 if (set.size() > 0 ){
		 for (ConstraintViolation<PolicyEnbale> constraintViolation : set) {
			 violation_message.add(constraintViolation.getMessage());
		 }
		 result.set("violation_message", new_mapper.valueToTree(violation_message));
		 return result;
	 }

	 //additional data manipulation
	 String new_json = policyEnable.transformInput();
	 result.put("valid", true);
	 result.put("new_json", new_json);
	 return result;
}
 
Example #5
Source File: CustomValidatorBean.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public void afterPropertiesSet() {
	if (this.validatorFactory == null) {
		this.validatorFactory = Validation.buildDefaultValidatorFactory();
	}

	ValidatorContext validatorContext = this.validatorFactory.usingContext();
	MessageInterpolator targetInterpolator = this.messageInterpolator;
	if (targetInterpolator == null) {
		targetInterpolator = this.validatorFactory.getMessageInterpolator();
	}
	validatorContext.messageInterpolator(new LocaleContextMessageInterpolator(targetInterpolator));
	if (this.traversableResolver != null) {
		validatorContext.traversableResolver(this.traversableResolver);
	}

	setTargetValidator(validatorContext.getValidator());
}
 
Example #6
Source File: CustomValidatorBean.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void afterPropertiesSet() {
	if (this.validatorFactory == null) {
		this.validatorFactory = Validation.buildDefaultValidatorFactory();
	}

	ValidatorContext validatorContext = this.validatorFactory.usingContext();
	MessageInterpolator targetInterpolator = this.messageInterpolator;
	if (targetInterpolator == null) {
		targetInterpolator = this.validatorFactory.getMessageInterpolator();
	}
	validatorContext.messageInterpolator(new LocaleContextMessageInterpolator(targetInterpolator));
	if (this.traversableResolver != null) {
		validatorContext.traversableResolver(this.traversableResolver);
	}

	setTargetValidator(validatorContext.getValidator());
}
 
Example #7
Source File: CustomValidatorBean.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public void afterPropertiesSet() {
	if (this.validatorFactory == null) {
		this.validatorFactory = Validation.buildDefaultValidatorFactory();
	}

	ValidatorContext validatorContext = this.validatorFactory.usingContext();
	MessageInterpolator targetInterpolator = this.messageInterpolator;
	if (targetInterpolator == null) {
		targetInterpolator = this.validatorFactory.getMessageInterpolator();
	}
	validatorContext.messageInterpolator(new LocaleContextMessageInterpolator(targetInterpolator));
	if (this.traversableResolver != null) {
		validatorContext.traversableResolver(this.traversableResolver);
	}

	setTargetValidator(validatorContext.getValidator());
}
 
Example #8
Source File: CsvBeanValidator.java    From super-csv-annotation with Apache License 2.0 6 votes vote down vote up
/**
 * ValidatorからMessageInterpolartorを取得する。
 * @param validator
 * @return {@link ValidatorImpl}出ない場合は、nullを返す。
 * @throws IllegalStateException 取得に失敗した場合。
 */
private static MessageInterpolator getMessageInterpolatorFromValidator(Validator validator) {
    
    if(!(validator instanceof ValidatorImpl)) {
        return null;
    }
    
    try {
        Field field = ValidatorImpl.class.getDeclaredField("messageInterpolator");
        field.setAccessible(true);
        
        MessageInterpolator interpolator = (MessageInterpolator)field.get(validator);
        return interpolator;
        
    } catch (IllegalAccessException | NoSuchFieldException | SecurityException e) {
        throw new IllegalStateException("fail reflect MessageInterpolrator from ValidatorImpl.", e);
    }
    
}
 
Example #9
Source File: CustomValidatorBean.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public void afterPropertiesSet() {
	if (this.validatorFactory == null) {
		this.validatorFactory = Validation.buildDefaultValidatorFactory();
	}

	ValidatorContext validatorContext = this.validatorFactory.usingContext();
	MessageInterpolator targetInterpolator = this.messageInterpolator;
	if (targetInterpolator == null) {
		targetInterpolator = this.validatorFactory.getMessageInterpolator();
	}
	validatorContext.messageInterpolator(new LocaleContextMessageInterpolator(targetInterpolator));
	if (this.traversableResolver != null) {
		validatorContext.traversableResolver(this.traversableResolver);
	}

	setTargetValidator(validatorContext.getValidator());
}
 
Example #10
Source File: DefaultValidatorTest.java    From vraptor4 with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
	ResourceBundle bundle = new SafeResourceBundle(ResourceBundle.getBundle("messages"));

	ValidatorFactory validatorFactory = javax.validation.Validation.buildDefaultValidatorFactory();
	javax.validation.Validator bvalidator = validatorFactory.getValidator();
	MessageInterpolator interpolator = validatorFactory.getMessageInterpolator();

	Proxifier proxifier = new JavassistProxifier();
	Messages messages = new Messages();

	validator = new DefaultValidator(result, new DefaultValidationViewsFactory(result, proxifier, new DefaultReflectionProvider()), 
			outjector, proxifier, bundle, bvalidator, interpolator, Locale.ENGLISH, messages);
	when(result.use(LogicResult.class)).thenReturn(logicResult);
	when(result.use(PageResult.class)).thenReturn(pageResult);
	when(logicResult.forwardTo(MyComponent.class)).thenReturn(instance);
	when(pageResult.of(MyComponent.class)).thenReturn(instance);
}
 
Example #11
Source File: DefaultValidator.java    From vraptor4 with Apache License 2.0 5 votes vote down vote up
@Inject
public DefaultValidator(Result result, ValidationViewsFactory factory, Outjector outjector, Proxifier proxifier, 
		ResourceBundle bundle, javax.validation.Validator bvalidator, MessageInterpolator interpolator, Locale locale,
		Messages messages) {
	this.result = result;
	this.viewsFactory = factory;
	this.outjector = outjector;
	this.proxifier = proxifier;
	this.bundle = bundle;
	this.bvalidator = bvalidator;
	this.interpolator = interpolator;
	this.locale = locale;
	this.messages = messages;
}
 
Example #12
Source File: DefaultValidatorConfiguration.java    From cm_ext with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the validator factory bean that Spring uses to
 * construct a Validator.
 *
 * @return a Validator Factory Bean
 */
@Bean
public LocalValidatorFactoryBean validatorFactoryBean() {
  BeanConstraintValidatorFactory validatorFactory = ctx.getBean(BeanConstraintValidatorFactory.class);
  MessageInterpolator messageInterpolator = ctx.getBean(MessageInterpolator.class);
  LocalValidatorFactoryBean factoryBean = new LocalValidatorFactoryBean();
  factoryBean.setMessageInterpolator(messageInterpolator);
  factoryBean.setConstraintValidatorFactory(validatorFactory);
  return factoryBean;
}
 
Example #13
Source File: CejugValidator.java    From hurraa with GNU General Public License v2.0 5 votes vote down vote up
@Inject
public CejugValidator(Result result, ValidationViewsFactory factory, Outjector outjector, Proxifier proxifier,
		ResourceBundle bundle, Validator validator, MessageInterpolator interpolator, Locale locale) {
	super(result, factory, outjector, proxifier, bundle,  validator, interpolator, locale);
	this.result = result;
	this.viewsFactory = factory;
	this.outjector = outjector;
	this.proxifier = proxifier;
}
 
Example #14
Source File: BeanValidation.java    From open-Autoscaler with Apache License 2.0 5 votes vote down vote up
public static JsonNode parsePolicy(String jsonString, Map<String, String> service_info, HttpServletRequest httpServletRequest) throws JsonParseException, JsonMappingException, IOException{
	 List<String> violation_message = new ArrayList<String>();
	 ObjectNode result = new_mapper.createObjectNode();
	 result.put("valid", false);
	 logger.info("received policy : " + jsonString); //debug
	 new_mapper.readValue(jsonString, Policy.class); //for syntax error check
	 String transfered_json = TransferedPolicy.packServiceInfo(jsonString, service_info);
	 logger.info("transfered policy after update with service_information : " + transfered_json); //debug
	 TransferedPolicy policy = new_mapper.readValue(transfered_json, TransferedPolicy.class);
	 logger.info("we get policy as " + (Obj2Map(policy)).toString());//debug
	 //additional data manipulation and check again
	 policy = policy.setMaxInstCount();
	 HibernateValidatorConfiguration config = BeanValidation.getPolicyRange();
	 ValidatorFactory vf = config.buildValidatorFactory();
	 Locale locale = LocaleUtil.getLocale(httpServletRequest);
	 MessageInterpolator interpolator = new LocaleSpecificMessageInterpolator(vf.getMessageInterpolator(), locale);
	 Validator validator = vf.usingContext().messageInterpolator(interpolator).getValidator();
	 Set<ConstraintViolation<TransferedPolicy>> set = validator.validate(policy);
	 if (set.size() > 0 ){
		 for (ConstraintViolation<TransferedPolicy> constraintViolation : set) {
			 violation_message.add(constraintViolation.getMessage());
		 }
		 result.set("violation_message", new_mapper.valueToTree(violation_message));
		 return result;
	 }

	 String new_json = policy.transformInput();
	 logger.info("policy before trigger back : " + new_json); //debug
	 new_json = TransferedPolicy.unpackServiceInfo(new_json, service_info);
	 result.put("valid", true);
	 logger.info("send out policy: " + new_json); //debug
	 result.put("new_json", new_json);
	 return result;
}
 
Example #15
Source File: BeanValidation.java    From open-Autoscaler with Apache License 2.0 5 votes vote down vote up
public static JsonNode parsePolicyOutput(String jsonString, Map<String, String> supplyment, Map<String, String> service_info, HttpServletRequest httpServletRequest) throws JsonParseException, JsonMappingException, IOException{
	 List<String> violation_message = new ArrayList<String>();
	 ObjectNode result = new_mapper.createObjectNode();
	 result.put("valid", false);
	 logger.info("received json: " + jsonString); 
	 String transfered_json = TransferedPolicy.packServiceInfo(jsonString, service_info);
	 logger.info("transfered policy after update with service_information : " + transfered_json); //debug
	 TransferedPolicy policy = new_mapper.readValue(transfered_json, TransferedPolicy.class);
	 logger.info("we get policy as " + (Obj2Map(policy)).toString());//debug
	 ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
	 Locale locale = LocaleUtil.getLocale(httpServletRequest);
	 MessageInterpolator interpolator = new LocaleSpecificMessageInterpolator(vf.getMessageInterpolator(), locale);
	 Validator validator = vf.usingContext().messageInterpolator(interpolator).getValidator();
	 Set<ConstraintViolation<TransferedPolicy>> set = validator.validate(policy);
	 if (set.size() > 0 ){
		 for (ConstraintViolation<TransferedPolicy> constraintViolation : set) {
			 violation_message.add(constraintViolation.getMessage());
		 }
		 result.set("violation_message", new_mapper.valueToTree(violation_message));
		 return result;
	 }

	 //additional data manipulation
	 policy = policy.transformSchedules();
	 String new_json = policy.transformOutput(supplyment, service_info);
	 result.put("valid", true);
	 result.put("new_json", new_json);
	 return result;
}
 
Example #16
Source File: BeanValidation.java    From open-Autoscaler with Apache License 2.0 5 votes vote down vote up
public static JsonNode parseMetrics(String jsonString, HttpServletRequest httpServletRequest) throws JsonParseException, JsonMappingException, IOException{
	 List<String> violation_message = new ArrayList<String>();
	 ObjectNode result = new_mapper.createObjectNode();
	 result.put("valid", false);
	 //JavaType javaType = getCollectionType(ArrayList.class, HistoryData.class);
	 //new_mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
	 logger.info("Received metrics: " + jsonString);
	 Metrics metrics = new_mapper.readValue(jsonString, Metrics.class);
	 
	 ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
	 Locale locale = LocaleUtil.getLocale(httpServletRequest);
	 MessageInterpolator interpolator = new LocaleSpecificMessageInterpolator(vf.getMessageInterpolator(), locale);
	 Validator validator = vf.usingContext().messageInterpolator(interpolator).getValidator();
	 Set<ConstraintViolation<Metrics>> set = validator.validate(metrics);
	 if (set.size() > 0 ){
		 for (ConstraintViolation<Metrics> constraintViolation : set) {
			 violation_message.add(constraintViolation.getMessage());
		 }
		 result.set("violation_message", new_mapper.valueToTree(violation_message));
		 return result;
	 }
         

	 //additional data manipulation
   	 String new_json = metrics.transformOutput();
	 result.put("valid", true);
	 result.put("new_json", new_json);
	 return result;
}
 
Example #17
Source File: ValidatorContextResolver.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
public GeneralValidator getContext(final Class<?> type) {
    final ResourceBundleLocator resourceBundleLocator = new PlatformResourceBundleLocator("messages");
    final MessageInterpolator messageInterpolator = new ResourceBundleMessageInterpolator(resourceBundleLocator);
    final Configuration<?> config = Validation.byDefaultProvider().configure()
        .messageInterpolator(messageInterpolator);
    final BootstrapConfiguration bootstrapConfiguration = config.getBootstrapConfiguration();
    final boolean isExecutableValidationEnabled = bootstrapConfiguration.isExecutableValidationEnabled();
    final Set<ExecutableType> defaultValidatedExecutableTypes = bootstrapConfiguration
        .getDefaultValidatedExecutableTypes();

    return new GeneralValidatorImpl(validatorFactory, isExecutableValidationEnabled,
        defaultValidatedExecutableTypes);
}
 
Example #18
Source File: ValidationUtil.java    From BlogManagePlatform with Apache License 2.0 5 votes vote down vote up
@PostConstruct
private void init() {
	ValidatorProperties properties = ContextUtil.bean(ValidatorProperties.class);
	HibernateValidatorConfiguration configuration = Validation.byProvider(HibernateValidator.class).configure();
	//配置hibernate-validator消息插值源
	MessageInterpolator interpolator = new ResourceBundleMessageInterpolator(new PlatformResourceBundleLocator(properties
		.getMessageConfigPath()));
	configuration.messageInterpolator(interpolator);
	//配置快速失败
	configuration.failFast(properties.getFailFast());
	failFast = properties.getFailFast();
	engine = configuration.buildValidatorFactory().getValidator();
}
 
Example #19
Source File: MBeanFieldGroup.java    From viritin with Apache License 2.0 5 votes vote down vote up
/**
 * A helper method that returns "bean level" validation errors, i.e. errors
 * that are not tied to a specific property/field.
 *
 * @return error messages from "bean level validation"
 */
public Collection<String> getBeanLevelValidationErrors() {
    Collection<String> errors = new ArrayList<>();
    if (getConstraintViolations() != null) {
        for (final ConstraintViolation<T> constraintViolation : getConstraintViolations()) {
            final MessageInterpolator.Context context = new MessageInterpolator.Context() {
                @Override
                public ConstraintDescriptor<?> getConstraintDescriptor() {
                    return constraintViolation.getConstraintDescriptor();
                }

                @Override
                public Object getValidatedValue() {
                    return constraintViolation.getInvalidValue();
                }

                @Override
                public <T> T unwrap(Class<T> type) {
                    throw new ValidationException();
                }
            };

            final String msg = getJavaxBeanValidatorFactory().getMessageInterpolator().interpolate(
                constraintViolation.getMessageTemplate(),
                context, getLocale());
            errors.add(msg);
        }
    }
    if (getBasicConstraintViolations() != null) {
        for (Validator.InvalidValueException cv : getBasicConstraintViolations()) {
            errors.add(cv.getMessage());
        }
    }
    return errors;
}
 
Example #20
Source File: TemplateMessageInterpolator.java    From cm_ext with Apache License 2.0 4 votes vote down vote up
public TemplateMessageInterpolator(MessageInterpolator delegate,
                                   StringInterpolator stringInterpolator) {
  super(delegate);
  this.stringInterpolator = stringInterpolator;
}
 
Example #21
Source File: MessageSourceInterpolator.java    From cm_ext with Apache License 2.0 4 votes vote down vote up
public MessageSourceInterpolator(MessageInterpolator delegate) {
  super(delegate);
  this.source = messageSource();
}
 
Example #22
Source File: DelegatingMessageInterpolator.java    From cm_ext with Apache License 2.0 4 votes vote down vote up
public DelegatingMessageInterpolator(MessageInterpolator delegate) {
  this.delegate = delegate;
}
 
Example #23
Source File: MethodValidator.java    From vraptor4 with Apache License 2.0 4 votes vote down vote up
@Inject
public MethodValidator(Instance<Locale> locale, MessageInterpolator interpolator, javax.validation.Validator bvalidator) {
	this.locale = locale;
	this.interpolator = interpolator;
	this.bvalidator = bvalidator;
}
 
Example #24
Source File: ValidationConfiguration.java    From cxf with Apache License 2.0 4 votes vote down vote up
public void setMessageInterpolator(MessageInterpolator messageInterpolator) {
    this.messageInterpolator = messageInterpolator;
}
 
Example #25
Source File: DefaultValidatorConfiguration.java    From cm_ext with Apache License 2.0 4 votes vote down vote up
public MessageInterpolator defaultInterpolator() {
  return Validation.byDefaultProvider().configure().getDefaultMessageInterpolator();
}
 
Example #26
Source File: DefaultValidatorConfiguration.java    From cm_ext with Apache License 2.0 4 votes vote down vote up
@Bean
public MessageInterpolator messageInterpolator() {
  return new MessageSourceInterpolator(templateMessageInterpolator());
}
 
Example #27
Source File: ValidationConfiguration.java    From cxf with Apache License 2.0 4 votes vote down vote up
public MessageInterpolator getMessageInterpolator() {
    return messageInterpolator;
}
 
Example #28
Source File: LocaleSpecificMessageInterpolator.java    From open-Autoscaler with Apache License 2.0 4 votes vote down vote up
public LocaleSpecificMessageInterpolator(MessageInterpolator interpolator, Locale locale) {
	this.defaultLocale = locale;
	this.defaultInterpolator = interpolator;
}
 
Example #29
Source File: MessageInterpolatorFactory.java    From vraptor4 with Apache License 2.0 4 votes vote down vote up
@Produces
@ApplicationScoped
public MessageInterpolator getInstance() {
	logger.debug("Initializing Bean Validator MessageInterpolator");
	return factory.getMessageInterpolator();
}
 
Example #30
Source File: ValidatorBuilder.java    From tomee with Apache License 2.0 4 votes vote down vote up
@Override
public MessageInterpolator getDefaultMessageInterpolator() {
    return delegate.getDefaultMessageInterpolator();
}