javax.validation.constraints.Digits#javax.validation.metadata.ConstraintDescriptor源码实例Demo

下面列出了javax.validation.constraints.Digits#javax.validation.metadata.ConstraintDescriptor 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

/**
 * 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();
}
 
/**
 * 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();
}
 
源代码3 项目: lams   文件: SpringValidatorAdapter.java
/**
 * 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()]);
}
 
源代码4 项目: lams   文件: TypeSafeActivator.java
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 );
			}
		}
	}
}
 
源代码5 项目: lams   文件: TypeSafeActivator.java
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 );
			}
		}
	}
}
 
源代码6 项目: lams   文件: TypeSafeActivator.java
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 );
			}
		}

	}
}
 
源代码7 项目: lams   文件: TypeSafeActivator.java
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 );
			}
		}
	}
}
 
源代码8 项目: lams   文件: TypeSafeActivator.java
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 );
				}
			}
		}
	}
}
 
/**
 * 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()]);
}
 
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;
}
 
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;
}
 
源代码12 项目: lastaflute   文件: ActionValidator.java
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));
}
 
源代码13 项目: cm_ext   文件: MonitoringConstraintViolation.java
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;
}
 
源代码14 项目: cm_ext   文件: ReferenceConstraintViolation.java
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;
}
 
源代码15 项目: xlsmapper   文件: SheetBeanValidator.java
/**
 * 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;
    
}
 
源代码16 项目: xlsmapper   文件: MessageInterpolatorAdapter.java
/**
 * メッセージ中で利用可能な変数を作成する
 * @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;
}
 
源代码17 项目: super-csv-annotation   文件: CsvBeanValidator.java
/**
 * 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;
    
}
 
源代码18 项目: syndesis   文件: Violation.java
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();
}
 
源代码19 项目: lams   文件: TypeSafeActivator.java
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;
}
 
源代码20 项目: lams   文件: TypeSafeActivator.java
@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;
}
 
源代码21 项目: viritin   文件: MBeanFieldGroup.java
/**
 * 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;
}
 
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;
}
 
源代码23 项目: sinavi-jfw   文件: JseLocalValidatorFactoryBean.java
/**
 * {@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;
}
 
源代码24 项目: cm_ext   文件: TemplateMessageInterpolatorTest.java
@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));
}
 
源代码25 项目: openregistry   文件: AddSoRPersonFlowTests.java
@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");
}
 
/**
 * メッセージ中で利用可能な変数を作成する
 * @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;
    
}
 
源代码27 项目: super-csv-annotation   文件: CsvBeanValidator.java
/**
 * エラーコードの決定する
 * @param descriptor フィールド情報
 * @return エラーコード
 */
protected String[] determineErrorCode(ConstraintDescriptor<?> descriptor) {
    return new String[] {
            descriptor.getAnnotation().annotationType().getSimpleName()/*,
            descriptor.getAnnotation().annotationType().getCanonicalName(),
            descriptor.getAnnotation().annotationType().getCanonicalName() + ".message"
            */
    };
}
 
源代码28 项目: jkube   文件: ResourceValidator.java
@Override
public ConstraintDescriptor<?> getConstraintDescriptor() {
    return null;
}
 
源代码29 项目: krazo   文件: ConstraintViolationTranslator.java
@Override
public ConstraintDescriptor<?> getConstraintDescriptor() {
    return violation.getConstraintDescriptor();
}
 
源代码30 项目: jweb-cms   文件: ResourceClient.java
@Override
public ConstraintDescriptor<?> getConstraintDescriptor() {
    return null;
}