javax.validation.metadata.ConstraintDescriptor Java Examples

The following examples show how to use javax.validation.metadata.ConstraintDescriptor. 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: ReferenceConstraintViolation.java    From cm_ext with Apache License 2.0 6 votes vote down vote up
public ReferenceConstraintViolation(String messageTemplate,
                                    String interpolatedMessage,
                                    Class<T> rootBeanClass,
                                    T rootBean,
                                    Object leafBeanInstance,
                                    Object value,
                                    DescriptorPath propertyPath,
                                    ConstraintDescriptor<?> constraintDescriptor,
                                    ElementType elementType,
                                    Object[] executableParameters,
                                    Object executableReturnValue) {
  this.messageTemplate = messageTemplate;
  this.interpolatedMessage = interpolatedMessage;
  this.rootBean = rootBean;
  this.value = value;
  this.propertyPath = propertyPath;
  this.leafBeanInstance = leafBeanInstance;
  this.constraintDescriptor = constraintDescriptor;
  this.rootBeanClass = rootBeanClass;
  this.elementType = elementType;
  this.executableParameters = executableParameters;
  this.executableReturnValue = executableReturnValue;
}
 
Example #2
Source File: SpringValidatorAdapter.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Return FieldError arguments for a validation error on the given field.
 * Invoked for each violated constraint.
 * <p>The default implementation returns a first argument indicating the field name
 * (of type DefaultMessageSourceResolvable, with "objectName.field" and "field" as codes).
 * Afterwards, it adds all actual constraint annotation attributes (i.e. excluding
 * "message", "groups" and "payload") in alphabetical order of their attribute names.
 * <p>Can be overridden to e.g. add further attributes from the constraint descriptor.
 * @param objectName the name of the target object
 * @param field the field that caused the binding error
 * @param descriptor the JSR-303 constraint descriptor
 * @return the Object array that represents the FieldError arguments
 * @see org.springframework.validation.FieldError#getArguments
 * @see org.springframework.context.support.DefaultMessageSourceResolvable
 * @see org.springframework.validation.DefaultBindingErrorProcessor#getArgumentsForBindError
 */
protected Object[] getArgumentsForConstraint(String objectName, String field, ConstraintDescriptor<?> descriptor) {
	List<Object> arguments = new LinkedList<Object>();
	String[] codes = new String[] {objectName + Errors.NESTED_PATH_SEPARATOR + field, field};
	arguments.add(new DefaultMessageSourceResolvable(codes, field));
	// Using a TreeMap for alphabetical ordering of attribute names
	Map<String, Object> attributesToExpose = new TreeMap<String, Object>();
	for (Map.Entry<String, Object> entry : descriptor.getAttributes().entrySet()) {
		String attributeName = entry.getKey();
		Object attributeValue = entry.getValue();
		if (!internalAnnotationAttributes.contains(attributeName)) {
			attributesToExpose.put(attributeName, attributeValue);
		}
	}
	arguments.addAll(attributesToExpose.values());
	return arguments.toArray(new Object[arguments.size()]);
}
 
Example #3
Source File: TypeSafeActivator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private static void applyLength(Property property, ConstraintDescriptor<?> descriptor, PropertyDescriptor propertyDescriptor) {
	if ( "org.hibernate.validator.constraints.Length".equals(
			descriptor.getAnnotation().annotationType().getName()
	)
			&& String.class.equals( propertyDescriptor.getElementClass() ) ) {
		@SuppressWarnings("unchecked")
		int max = (Integer) descriptor.getAttributes().get( "max" );

		@SuppressWarnings("unchecked")
		final Iterator<Selectable> itor = property.getColumnIterator();
		if ( itor.hasNext() ) {
			final Selectable selectable = itor.next();
			if ( Column.class.isInstance( selectable ) ) {
				Column col = (Column) selectable;
				if ( max < Integer.MAX_VALUE ) {
					col.setLength( max );
				}
			}
		}
	}
}
 
Example #4
Source File: TypeSafeActivator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private static void applySize(Property property, ConstraintDescriptor<?> descriptor, PropertyDescriptor propertyDescriptor) {
	if ( Size.class.equals( descriptor.getAnnotation().annotationType() )
			&& String.class.equals( propertyDescriptor.getElementClass() ) ) {
		@SuppressWarnings("unchecked")
		ConstraintDescriptor<Size> sizeConstraint = (ConstraintDescriptor<Size>) descriptor;
		int max = sizeConstraint.getAnnotation().max();

		@SuppressWarnings("unchecked")
		final Iterator<Selectable> itor = property.getColumnIterator();
		if ( itor.hasNext() ) {
			final Selectable selectable = itor.next();
			Column col = (Column) selectable;
			if ( max < Integer.MAX_VALUE ) {
				col.setLength( max );
			}
		}
	}
}
 
Example #5
Source File: TypeSafeActivator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private static void applyDigits(Property property, ConstraintDescriptor<?> descriptor) {
	if ( Digits.class.equals( descriptor.getAnnotation().annotationType() ) ) {
		@SuppressWarnings("unchecked")
		ConstraintDescriptor<Digits> digitsConstraint = (ConstraintDescriptor<Digits>) descriptor;
		int integerDigits = digitsConstraint.getAnnotation().integer();
		int fractionalDigits = digitsConstraint.getAnnotation().fraction();

		@SuppressWarnings("unchecked")
		final Iterator<Selectable> itor = property.getColumnIterator();
		if ( itor.hasNext() ) {
			final Selectable selectable = itor.next();
			if ( Column.class.isInstance( selectable ) ) {
				Column col = (Column) selectable;
				col.setPrecision( integerDigits + fractionalDigits );
				col.setScale( fractionalDigits );
			}
		}

	}
}
 
Example #6
Source File: ClientDataValidationErrorHandlerListenerTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
private ConstraintViolation<Object> setupConstraintViolation(Class offendingObjectClass, String path, Class<? extends Annotation> annotationClass, String message) {
    ConstraintViolation<Object> mockConstraintViolation = mock(ConstraintViolation.class);

    Path mockPath = mock(Path.class);
    doReturn(path).when(mockPath).toString();

    Annotation mockAnnotation = mock(Annotation.class);
    doReturn(annotationClass).when(mockAnnotation).annotationType();

    ConstraintDescriptor<?> mockConstraintDescriptor = mock(ConstraintDescriptor.class);
    doReturn(mockAnnotation).when(mockConstraintDescriptor).getAnnotation();

    when(mockConstraintViolation.getPropertyPath()).thenReturn(mockPath);
    doReturn(mockConstraintDescriptor).when(mockConstraintViolation).getConstraintDescriptor();
    when(mockConstraintViolation.getMessage()).thenReturn(message);

    doReturn(offendingObjectClass).when(mockConstraintViolation).getRootBeanClass();

    return mockConstraintViolation;
}
 
Example #7
Source File: TypeSafeActivator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private static void applyMax(Property property, ConstraintDescriptor<?> descriptor, Dialect dialect) {
	if ( Max.class.equals( descriptor.getAnnotation().annotationType() ) ) {
		@SuppressWarnings("unchecked")
		ConstraintDescriptor<Max> maxConstraint = (ConstraintDescriptor<Max>) descriptor;
		long max = maxConstraint.getAnnotation().value();

		@SuppressWarnings("unchecked")
		final Iterator<Selectable> itor = property.getColumnIterator();
		if ( itor.hasNext() ) {
			final Selectable selectable = itor.next();
			if ( Column.class.isInstance( selectable ) ) {
				Column col = (Column) selectable;
				String checkConstraint = col.getQuotedName( dialect ) + "<=" + max;
				applySQLCheck( col, checkConstraint );
			}
		}
	}
}
 
Example #8
Source File: TypeSafeActivator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private static void applyMin(Property property, ConstraintDescriptor<?> descriptor, Dialect dialect) {
	if ( Min.class.equals( descriptor.getAnnotation().annotationType() ) ) {
		@SuppressWarnings("unchecked")
		ConstraintDescriptor<Min> minConstraint = (ConstraintDescriptor<Min>) descriptor;
		long min = minConstraint.getAnnotation().value();

		@SuppressWarnings("unchecked")
		final Iterator<Selectable> itor = property.getColumnIterator();
		if ( itor.hasNext() ) {
			final Selectable selectable = itor.next();
			if ( Column.class.isInstance( selectable ) ) {
				Column col = (Column) selectable;
				String checkConstraint = col.getQuotedName(dialect) + ">=" + min;
				applySQLCheck( col, checkConstraint );
			}
		}
	}
}
 
Example #9
Source File: ServersideValidationErrorHandlerListenerTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
private ConstraintViolation<Object> setupConstraintViolation(String path, Class<? extends Annotation> annotationClass, String message) {
    ConstraintViolation<Object> mockConstraintViolation = mock(ConstraintViolation.class);

    Path mockPath = mock(Path.class);
    doReturn(path).when(mockPath).toString();

    Annotation mockAnnotation = mock(Annotation.class);
    doReturn(annotationClass).when(mockAnnotation).annotationType();

    ConstraintDescriptor<?> mockConstraintDescriptor = mock(ConstraintDescriptor.class);
    doReturn(mockAnnotation).when(mockConstraintDescriptor).getAnnotation();

    when(mockConstraintViolation.getPropertyPath()).thenReturn(mockPath);
    doReturn(mockConstraintDescriptor).when(mockConstraintViolation).getConstraintDescriptor();
    when(mockConstraintViolation.getMessage()).thenReturn(message);

    return mockConstraintViolation;
}
 
Example #10
Source File: SpringValidatorAdapter.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Return FieldError arguments for a validation error on the given field.
 * Invoked for each violated constraint.
 * <p>The default implementation returns a first argument indicating the field name
 * (see {@link #getResolvableField}). Afterwards, it adds all actual constraint
 * annotation attributes (i.e. excluding "message", "groups" and "payload") in
 * alphabetical order of their attribute names.
 * <p>Can be overridden to e.g. add further attributes from the constraint descriptor.
 * @param objectName the name of the target object
 * @param field the field that caused the binding error
 * @param descriptor the JSR-303 constraint descriptor
 * @return the Object array that represents the FieldError arguments
 * @see org.springframework.validation.FieldError#getArguments
 * @see org.springframework.context.support.DefaultMessageSourceResolvable
 * @see org.springframework.validation.DefaultBindingErrorProcessor#getArgumentsForBindError
 */
protected Object[] getArgumentsForConstraint(String objectName, String field, ConstraintDescriptor<?> descriptor) {
	List<Object> arguments = new LinkedList<Object>();
	arguments.add(getResolvableField(objectName, field));
	// Using a TreeMap for alphabetical ordering of attribute names
	Map<String, Object> attributesToExpose = new TreeMap<String, Object>();
	for (Map.Entry<String, Object> entry : descriptor.getAttributes().entrySet()) {
		String attributeName = entry.getKey();
		Object attributeValue = entry.getValue();
		if (!internalAnnotationAttributes.contains(attributeName)) {
			if (attributeValue instanceof String) {
				attributeValue = new ResolvableAttribute(attributeValue.toString());
			}
			attributesToExpose.put(attributeName, attributeValue);
		}
	}
	arguments.addAll(attributesToExpose.values());
	return arguments.toArray(new Object[arguments.size()]);
}
 
Example #11
Source File: MessageInterpolatorAdapter.java    From xlsmapper with Apache License 2.0 6 votes vote down vote up
/**
 * メッセージ中で利用可能な変数を作成する
 * @param context コンテキスト
 * @return メッセージ変数のマップ
 */
protected Map<String, Object> createMessageVars(final Context context) {
    
    final Map<String, Object> vars = new HashMap<String, Object>();
    
    final ConstraintDescriptor<?> descriptor = context.getConstraintDescriptor();
    for(Map.Entry<String, Object> entry : descriptor.getAttributes().entrySet()) {
        final String attrName = entry.getKey();
        final Object attrValue = entry.getValue();
        
        vars.put(attrName, attrValue);
    }
    
    // 検証対象の値
    vars.computeIfAbsent("validatedValue", key -> context.getValidatedValue());
    
    // デフォルトのメッセージ
    final String defaultCode = String.format("%s.message", descriptor.getAnnotation().annotationType().getCanonicalName());
    final Optional<String> defaultMessage = messageResolver.getMessage(defaultCode);
    
    vars.put(defaultCode, 
            defaultMessage.orElseThrow(() -> new RuntimeException(String.format("not found message code '%s'", defaultCode))));
    
    return vars;
}
 
Example #12
Source File: MonitoringConstraintViolation.java    From cm_ext with Apache License 2.0 6 votes vote down vote up
public MonitoringConstraintViolation(
    String messageTemplate,
    String interpolatedMessage,
    Class<T> rootBeanClass,
    T rootBean,
    Object leafBeanInstance,
    Object value,
    DescriptorPath propertyPath,
    ConstraintDescriptor<?> constraintDescriptor,
    ElementType elementType,
    Object[] executableParameters,
    Object executableReturnValue) {
  this.messageTemplate = messageTemplate;
  this.interpolatedMessage = interpolatedMessage;
  this.rootBean = rootBean;
  this.value = value;
  this.propertyPath = propertyPath;
  this.leafBeanInstance = leafBeanInstance;
  this.constraintDescriptor = constraintDescriptor;
  this.rootBeanClass = rootBeanClass;
  this.elementType = elementType;
  this.executableParameters = executableParameters;
  this.executableReturnValue = executableReturnValue;
}
 
Example #13
Source File: SheetBeanValidator.java    From xlsmapper with Apache License 2.0 6 votes vote down vote up
/**
 * BeanValidationのアノテーションの値を元に、メッセージ変数を作成する。
 * @param descriptor
 * @return メッセージ変数
 */
protected Map<String, Object> createVariableForConstraint(final ConstraintDescriptor<?> descriptor) {
    
    final Map<String, Object> vars = new HashMap<String, Object>();
    
    for(Map.Entry<String, Object> entry : descriptor.getAttributes().entrySet()) {
        final String attrName = entry.getKey();
        final Object attrValue = entry.getValue();
        
        // メッセージ変数で必要ないものを除外する
        if(EXCLUDE_MESSAGE_ANNOTATION_ATTRIBUTES.contains(attrName)) {
            continue;
        }
        
        vars.put(attrName, attrValue);
    }
    
    return vars;
    
}
 
Example #14
Source File: ActionValidator.java    From lastaflute with Apache License 2.0 6 votes vote down vote up
protected void registerActionMessage(UserMessages messages, ConstraintViolation<Object> vio) {
    final String propertyPath = extractPropertyPath(vio);
    final String plainMessage = filterMessageItem(extractMessage(vio), propertyPath);
    final String delimiter = MESSAGE_HINT_DELIMITER;
    final String messageItself;
    final String messageKey;
    if (plainMessage.contains(delimiter)) { // basically here
        messageItself = Srl.substringFirstRear(plainMessage, delimiter);
        messageKey = Srl.substringFirstFront(plainMessage, delimiter);
    } else { // just in case
        messageItself = plainMessage;
        messageKey = null;
    }
    final ConstraintDescriptor<?> descriptor = vio.getConstraintDescriptor();
    final Annotation annotation = descriptor.getAnnotation();
    final Set<Class<?>> groupSet = descriptor.getGroups();
    final Class<?>[] groups = groupSet.toArray(new Class<?>[groupSet.size()]);
    messages.add(propertyPath, createDirectMessage(messageItself, annotation, groups, messageKey));
}
 
Example #15
Source File: SpringValidatorAdapter.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Return FieldError arguments for a validation error on the given field.
 * Invoked for each violated constraint.
 * <p>The default implementation returns a first argument indicating the field name
 * (see {@link #getResolvableField}). Afterwards, it adds all actual constraint
 * annotation attributes (i.e. excluding "message", "groups" and "payload") in
 * alphabetical order of their attribute names.
 * <p>Can be overridden to e.g. add further attributes from the constraint descriptor.
 * @param objectName the name of the target object
 * @param field the field that caused the binding error
 * @param descriptor the JSR-303 constraint descriptor
 * @return the Object array that represents the FieldError arguments
 * @see org.springframework.validation.FieldError#getArguments
 * @see org.springframework.context.support.DefaultMessageSourceResolvable
 * @see org.springframework.validation.DefaultBindingErrorProcessor#getArgumentsForBindError
 */
protected Object[] getArgumentsForConstraint(String objectName, String field, ConstraintDescriptor<?> descriptor) {
	List<Object> arguments = new ArrayList<>();
	arguments.add(getResolvableField(objectName, field));
	// Using a TreeMap for alphabetical ordering of attribute names
	Map<String, Object> attributesToExpose = new TreeMap<>();
	descriptor.getAttributes().forEach((attributeName, attributeValue) -> {
		if (!internalAnnotationAttributes.contains(attributeName)) {
			if (attributeValue instanceof String) {
				attributeValue = new ResolvableAttribute(attributeValue.toString());
			}
			attributesToExpose.put(attributeName, attributeValue);
		}
	});
	arguments.addAll(attributesToExpose.values());
	return arguments.toArray();
}
 
Example #16
Source File: CsvBeanValidator.java    From super-csv-annotation with Apache License 2.0 6 votes vote down vote up
/**
 * BeanValidationのアノテーションの値を元に、メッセージ変数を作成する。
 * @param descriptor
 * @return メッセージ変数
 */
private Map<String, Object> createVariableForConstraint(final ConstraintDescriptor<?> descriptor) {
    
    final Map<String, Object> vars = new HashMap<>();
    
    for(Map.Entry<String, Object> entry : descriptor.getAttributes().entrySet()) {
        final String attrName = entry.getKey();
        final Object attrValue = entry.getValue();
        
        // メッセージ変数で必要ないものを除外する
        if(EXCLUDE_MESSAGE_ANNOTATION_ATTRIBUTES.contains(attrName)) {
            continue;
        }
        
        vars.put(attrName, attrValue);
    }
    
    return vars;
    
}
 
Example #17
Source File: SpringValidatorAdapter.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Return FieldError arguments for a validation error on the given field.
 * Invoked for each violated constraint.
 * <p>The default implementation returns a first argument indicating the field name
 * (see {@link #getResolvableField}). Afterwards, it adds all actual constraint
 * annotation attributes (i.e. excluding "message", "groups" and "payload") in
 * alphabetical order of their attribute names.
 * <p>Can be overridden to e.g. add further attributes from the constraint descriptor.
 * @param objectName the name of the target object
 * @param field the field that caused the binding error
 * @param descriptor the JSR-303 constraint descriptor
 * @return the Object array that represents the FieldError arguments
 * @see org.springframework.validation.FieldError#getArguments
 * @see org.springframework.context.support.DefaultMessageSourceResolvable
 * @see org.springframework.validation.DefaultBindingErrorProcessor#getArgumentsForBindError
 */
protected Object[] getArgumentsForConstraint(String objectName, String field, ConstraintDescriptor<?> descriptor) {
	List<Object> arguments = new ArrayList<>();
	arguments.add(getResolvableField(objectName, field));
	// Using a TreeMap for alphabetical ordering of attribute names
	Map<String, Object> attributesToExpose = new TreeMap<>();
	descriptor.getAttributes().forEach((attributeName, attributeValue) -> {
		if (!internalAnnotationAttributes.contains(attributeName)) {
			if (attributeValue instanceof String) {
				attributeValue = new ResolvableAttribute(attributeValue.toString());
			}
			attributesToExpose.put(attributeName, attributeValue);
		}
	});
	arguments.addAll(attributesToExpose.values());
	return arguments.toArray();
}
 
Example #18
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 #19
Source File: TemplateMessageInterpolatorTest.java    From cm_ext with Apache License 2.0 5 votes vote down vote up
@Test
public void testDoInterpolate() {
  String str = "My ${var1} string";
  Map<String, Object> variables = ImmutableMap.<String, Object> of("var1", "value1");
  ConstraintDescriptor descriptor = mock(ConstraintDescriptor.class);
  when(context.getConstraintDescriptor()).thenReturn(descriptor);
  when(descriptor.getAttributes()).thenReturn(variables);
  assertEquals("My value1 string", interpolator.doInterpolate(str, context));
}
 
Example #20
Source File: EmailClientValidationConstraint.java    From primefaces-blueprints with The Unlicense 5 votes vote down vote up
public Map<String, Object> getMetadata(ConstraintDescriptor constraintDescriptor) {
    Map<String,Object> metadata = new HashMap<String, Object>();
    Map attrs = constraintDescriptor.getAttributes();
    Object message = attrs.get("message");    
    if(message != null) {
        metadata.put(MESSAGE_METADATA, message);
    }
    
    return metadata;
}
 
Example #21
Source File: TypeSafeActivator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static boolean applyNotNull(Property property, ConstraintDescriptor<?> descriptor) {
	boolean hasNotNull = false;
	if ( NotNull.class.equals( descriptor.getAnnotation().annotationType() ) ) {
		// single table inheritance should not be forced to null due to shared state
		if ( !( property.getPersistentClass() instanceof SingleTableSubclass ) ) {
			//composite should not add not-null on all columns
			if ( !property.isComposite() ) {
				final Iterator<Selectable> itr = property.getColumnIterator();
				while ( itr.hasNext() ) {
					final Selectable selectable = itr.next();
					if ( Column.class.isInstance( selectable ) ) {
						Column.class.cast( selectable ).setNullable( false );
					}
					else {
						LOG.debugf(
								"@NotNull was applied to attribute [%s] which is defined (at least partially) " +
										"by formula(s); formula portions will be skipped",
								property.getName()
						);
					}
				}
			}
		}
		hasNotNull = true;
	}
	return hasNotNull;
}
 
Example #22
Source File: JseLocalValidatorFactoryBean.java    From sinavi-jfw with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected Object[] getArgumentsForConstraint(final String objectName, String field, ConstraintDescriptor<?> descriptor) {
    Object[] args = super.getArgumentsForConstraint(objectName, field, descriptor);
    int index = 0;
    for (Object arg : args) {
        if (arg instanceof DefaultMessageSourceResolvable) {
            args[index] = getMessageSourceResolvable(objectName, field);
        }
        index++;
    }
    return args;
}
 
Example #23
Source File: TypeSafeActivator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private static boolean applyConstraints(
		Set<ConstraintDescriptor<?>> constraintDescriptors,
		Property property,
		PropertyDescriptor propertyDesc,
		Set<Class<?>> groups,
		boolean canApplyNotNull,
		Dialect dialect) {
	boolean hasNotNull = false;
	for ( ConstraintDescriptor<?> descriptor : constraintDescriptors ) {
		if ( groups != null && Collections.disjoint( descriptor.getGroups(), groups ) ) {
			continue;
		}

		if ( canApplyNotNull ) {
			hasNotNull = hasNotNull || applyNotNull( property, descriptor );
		}

		// apply bean validation specific constraints
		applyDigits( property, descriptor );
		applySize( property, descriptor, propertyDesc );
		applyMin( property, descriptor, dialect );
		applyMax( property, descriptor, dialect );

		// apply hibernate validator specific constraints - we cannot import any HV specific classes though!
		// no need to check explicitly for @Range. @Range is a composed constraint using @Min and @Max which
		// will be taken care later
		applyLength( property, descriptor, propertyDesc );

		// pass an empty set as composing constraints inherit the main constraint and thus are matching already
		boolean hasNotNullFromComposingConstraints = applyConstraints(
				descriptor.getComposingConstraints(),
				property, propertyDesc, null,
				canApplyNotNull,
				dialect
		);

		hasNotNull = hasNotNull || hasNotNullFromComposingConstraints;
	}
	return hasNotNull;
}
 
Example #24
Source File: AddSoRPersonFlowTests.java    From openregistry with Apache License 2.0 5 votes vote down vote up
@Test
public void testCriteriaSubmitError() throws ReconciliationException, SorPersonAlreadyExistsException {
    final ReconciliationCriteria criteria = constructReconciliationCriteria(RUDYARD, RUDYARD, "INVALID_SSN", null, PHONE_NUMBER, new Date(0), OR_WEBAPP_IDENTIFIER);
    final ServiceExecutionResult<Person> serviceExecutionResult = mock(ServiceExecutionResult.class, RETURNS_SMART_NULLS);
    final Set<ConstraintViolation> violations = mock(Set.class, RETURNS_SMART_NULLS);
    final Iterator iter = mock(Iterator.class);
    final ConstraintViolation constraintViolation = mock(ConstraintViolation.class, RETURNS_SMART_NULLS);
    final Path path = mock(Path.class);
    final ConstraintDescriptor constraintDescriptor = mock(ConstraintDescriptor.class, RETURNS_SMART_NULLS);
    final Map map = mock(Map.class, RETURNS_SMART_NULLS);

    when(constraintViolation.getMessage()).thenReturn("errorCode");
    when(constraintViolation.getConstraintDescriptor()).thenReturn(constraintDescriptor);
    when(constraintDescriptor.getAttributes()).thenReturn(map);
    when(map.values()).thenReturn(new ArrayList());
    when(constraintDescriptor.getAnnotation()).thenReturn(new TestAnnotation());

    when(iter.next()).thenReturn(constraintViolation);
    when(iter.hasNext()).thenReturn(true).thenReturn(false);
    when(violations.iterator()).thenReturn(iter);
    when(violations.isEmpty()).thenReturn(false);
    when(serviceExecutionResult.succeeded()).thenReturn(false);
    when(serviceExecutionResult.getValidationErrors()).thenReturn(violations);
    when(personService.addPerson(criteria)).thenReturn(serviceExecutionResult);


    setCurrentState("addPerson");
    getFlowScope().put("personSearch", criteria);

    MockExternalContext context = new MockExternalContext();

    //submit with invalid input
    context.setEventId("submitAddPerson");
    resumeFlow(context);
    assertCurrentStateEquals("addPerson");
}
 
Example #25
Source File: Violation.java    From syndesis with Apache License 2.0 5 votes vote down vote up
public static Violation fromConstraintViolation(final ConstraintViolation<?> constraintViolation) {
    final String property = constraintViolation.getPropertyPath().toString();
    final ConstraintDescriptor<?> constraintDescriptor = constraintViolation.getConstraintDescriptor();
    final Annotation annotation = constraintDescriptor.getAnnotation();
    final Class<? extends Annotation> annotationType = annotation.annotationType();
    final String error = annotationType.getSimpleName();
    final String message = constraintViolation.getMessage();

    return new Builder().property(property).error(error).message(message).build();
}
 
Example #26
Source File: MessageInterpolatorAdapter.java    From super-csv-annotation with Apache License 2.0 5 votes vote down vote up
/**
 * メッセージ中で利用可能な変数を作成する
 * @param context コンテキスト
 * @return メッセージ変数のマップ
 */
private Map<String, Object> createMessageVariables(final Context context) {
    
    final Map<String, Object> vars = new HashMap<>();
    
    if(context instanceof MessageInterpolatorContext) {
        MessageInterpolatorContext mic = (MessageInterpolatorContext)context;
        vars.putAll(mic.getMessageParameters());
    }
    
    final ConstraintDescriptor<?> descriptor = context.getConstraintDescriptor();
    for(Map.Entry<String, Object> entry : descriptor.getAttributes().entrySet()) {
        final String attrName = entry.getKey();
        final Object attrValue = entry.getValue();
        
        vars.put(attrName, attrValue);
    }
    
    // 検証対象の値
    vars.computeIfAbsent("validatedValue", key -> context.getValidatedValue());
    
    // デフォルトのメッセージ
    final String defaultCode = String.format("%s.message", descriptor.getAnnotation().annotationType().getCanonicalName());
    final Optional<String> defaultMessage = messageResolver.getMessage(defaultCode);
    
    vars.put(defaultCode, 
            defaultMessage.orElseThrow(() -> new RuntimeException(String.format("not found message code '%s'", defaultCode))));
    
    
    return vars;
    
}
 
Example #27
Source File: CsvBeanValidator.java    From super-csv-annotation with Apache License 2.0 5 votes vote down vote up
/**
 * エラーコードの決定する
 * @param descriptor フィールド情報
 * @return エラーコード
 */
protected String[] determineErrorCode(ConstraintDescriptor<?> descriptor) {
    return new String[] {
            descriptor.getAnnotation().annotationType().getSimpleName()/*,
            descriptor.getAnnotation().annotationType().getCanonicalName(),
            descriptor.getAnnotation().annotationType().getCanonicalName() + ".message"
            */
    };
}
 
Example #28
Source File: UpdateStackRequestValidatorTest.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
@Override
public Set<ConstraintDescriptor<?>> getComposingConstraints() {
    return Collections.emptySet();
}
 
Example #29
Source File: ReferenceConstraintViolation.java    From cm_ext with Apache License 2.0 4 votes vote down vote up
@Override
public ConstraintDescriptor<?> getConstraintDescriptor() {
  return this.constraintDescriptor;
}
 
Example #30
Source File: ParcelDescriptorValidatorImplTest.java    From cm_ext with Apache License 2.0 4 votes vote down vote up
private void assertConstraint(ConstraintViolation<?> violation, Class<?> constraint) {
  ConstraintDescriptor<?> descriptor = violation.getConstraintDescriptor();
  assertEquals(constraint, descriptor.getAnnotation().annotationType());
}