Example usage for org.springframework.util ObjectUtils isEmpty

List of usage examples for org.springframework.util ObjectUtils isEmpty

Introduction

In this page you can find the example usage for org.springframework.util ObjectUtils isEmpty.

Prototype

@SuppressWarnings("rawtypes")
public static boolean isEmpty(@Nullable Object obj) 

Source Link

Document

Determine whether the given object is empty.

Usage

From source file:org.springframework.validation.DataBinder.java

/**
 * Return if the given field is allowed for binding.
 * Invoked for each passed-in property value.
 * <p>The default implementation checks for "xxx*", "*xxx" and "*xxx*" matches,
 * as well as direct equality, in the specified lists of allowed fields and
 * disallowed fields. A field matching a disallowed pattern will not be accepted
 * even if it also happens to match a pattern in the allowed list.
 * <p>Can be overridden in subclasses.
 * @param field the field to check//from  w w  w  . j a  v a2 s  .c  o  m
 * @return if the field is allowed
 * @see #setAllowedFields
 * @see #setDisallowedFields
 * @see org.springframework.util.PatternMatchUtils#simpleMatch(String, String)
 */
protected boolean isAllowed(String field) {
    String[] allowed = getAllowedFields();
    String[] disallowed = getDisallowedFields();
    return ((ObjectUtils.isEmpty(allowed) || PatternMatchUtils.simpleMatch(allowed, field))
            && (ObjectUtils.isEmpty(disallowed) || !PatternMatchUtils.simpleMatch(disallowed, field)));
}

From source file:org.springframework.validation.DataBinder.java

/**
 * Check the given property values against the required fields,
 * generating missing field errors where appropriate.
 * @param mpvs the property values to be bound (can be modified)
 * @see #getRequiredFields/*  w  w  w.j a  va  2  s . c o m*/
 * @see #getBindingErrorProcessor
 * @see BindingErrorProcessor#processMissingFieldError
 */
protected void checkRequiredFields(MutablePropertyValues mpvs) {
    String[] requiredFields = getRequiredFields();
    if (!ObjectUtils.isEmpty(requiredFields)) {
        Map<String, PropertyValue> propertyValues = new HashMap<>();
        PropertyValue[] pvs = mpvs.getPropertyValues();
        for (PropertyValue pv : pvs) {
            String canonicalName = PropertyAccessorUtils.canonicalPropertyName(pv.getName());
            propertyValues.put(canonicalName, pv);
        }
        for (String field : requiredFields) {
            PropertyValue pv = propertyValues.get(field);
            boolean empty = (pv == null || pv.getValue() == null);
            if (!empty) {
                if (pv.getValue() instanceof String) {
                    empty = !StringUtils.hasText((String) pv.getValue());
                } else if (pv.getValue() instanceof String[]) {
                    String[] values = (String[]) pv.getValue();
                    empty = (values.length == 0 || !StringUtils.hasText(values[0]));
                }
            }
            if (empty) {
                // Use bind error processor to create FieldError.
                getBindingErrorProcessor().processMissingFieldError(field, getInternalBindingResult());
                // Remove property from property values to bind:
                // It has already caused a field error with a rejected value.
                if (pv != null) {
                    mpvs.removePropertyValue(pv);
                    propertyValues.remove(field);
                }
            }
        }
    }
}

From source file:org.springframework.validation.DataBinder.java

/**
 * Invoke the specified Validators, if any, with the given validation hints.
 * <p>Note: Validation hints may get ignored by the actual target Validator.
 * @param validationHints one or more hint objects to be passed to a {@link SmartValidator}
 * @see #setValidator(Validator)//from ww w .j  a  v  a  2  s .c o m
 * @see SmartValidator#validate(Object, Errors, Object...)
 */
public void validate(Object... validationHints) {
    for (Validator validator : getValidators()) {
        if (!ObjectUtils.isEmpty(validationHints) && validator instanceof SmartValidator) {
            ((SmartValidator) validator).validate(getTarget(), getBindingResult(), validationHints);
        } else if (validator != null) {
            validator.validate(getTarget(), getBindingResult());
        }
    }
}

From source file:org.springframework.validation.ValidationUtils.java

/**
 * Invoke the given {@link Validator}/{@link SmartValidator} for the supplied object and
 * {@link Errors} instance./* ww w .ja v a2  s  .com*/
 * @param validator the {@code Validator} to be invoked (must not be {@code null})
 * @param obj the object to bind the parameters to
 * @param errors the {@link Errors} instance that should store the errors (must not be {@code null})
 * @param validationHints one or more hint objects to be passed to the validation engine
 * @throws IllegalArgumentException if either of the {@code Validator} or {@code Errors} arguments is
 * {@code null}, or if the supplied {@code Validator} does not {@link Validator#supports(Class) support}
 * the validation of the supplied object's type
 */
public static void invokeValidator(Validator validator, @Nullable Object obj, Errors errors,
        @Nullable Object... validationHints) {

    Assert.notNull(validator, "Validator must not be null");
    Assert.notNull(errors, "Errors object must not be null");

    if (logger.isDebugEnabled()) {
        logger.debug("Invoking validator [" + validator + "]");
    }
    if (obj != null && !validator.supports(obj.getClass())) {
        throw new IllegalArgumentException(
                "Validator [" + validator.getClass() + "] does not support [" + obj.getClass() + "]");
    }

    if (!ObjectUtils.isEmpty(validationHints) && validator instanceof SmartValidator) {
        ((SmartValidator) validator).validate(obj, errors, validationHints);
    } else {
        validator.validate(obj, errors);
    }

    if (logger.isDebugEnabled()) {
        if (errors.hasErrors()) {
            logger.debug("Validator found " + errors.getErrorCount() + " errors");
        } else {
            logger.debug("Validator found no errors");
        }
    }
}

From source file:org.springframework.web.reactive.resource.ResourceWebHandler.java

/**
 * Look for a {@code PathResourceResolver} among the configured resource
 * resolvers and set its {@code allowedLocations} property (if empty) to
 * match the {@link #setLocations locations} configured on this class.
 *///from  w  ww. j  av a  2s. c  o  m
protected void initAllowedLocations() {
    if (CollectionUtils.isEmpty(this.locations)) {
        if (logger.isWarnEnabled()) {
            logger.warn("Locations list is empty. No resources will be served unless a "
                    + "custom ResourceResolver is configured as an alternative to PathResourceResolver.");
        }
        return;
    }
    for (int i = getResourceResolvers().size() - 1; i >= 0; i--) {
        if (getResourceResolvers().get(i) instanceof PathResourceResolver) {
            PathResourceResolver resolver = (PathResourceResolver) getResourceResolvers().get(i);
            if (ObjectUtils.isEmpty(resolver.getAllowedLocations())) {
                resolver.setAllowedLocations(getLocations().toArray(new Resource[getLocations().size()]));
            }
            break;
        }
    }
}

From source file:org.springframework.web.servlet.config.annotation.BeanTypeNotPresentCondition.java

public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
    ListableBeanFactory factory = context.getBeanFactory();
    String[] names = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(factory, this.beanType, false, false);
    if (ObjectUtils.isEmpty(names)) {
        logger.debug("No bean of type [" + this.beanType + "]. Conditional configuration applies.");
        return true;
    } else {//w w  w .j a  va  2s . c  o m
        logger.debug("Found bean of type [" + this.beanType + "]. Conditional configuration does not apply.");
        return false;
    }
}

From source file:org.springframework.web.servlet.HandlerExecutionChain.java

public void addInterceptors(HandlerInterceptor... interceptors) {
    if (!ObjectUtils.isEmpty(interceptors)) {
        CollectionUtils.mergeArrayIntoCollection(interceptors, initInterceptorList());
    }// w  w w. j  ava 2  s.  c  o  m
}

From source file:org.springframework.web.servlet.HandlerExecutionChain.java

/**
 * Apply postHandle methods of registered interceptors.
 */// ww  w .j  a v  a 2s.c o m
void applyPostHandle(HttpServletRequest request, HttpServletResponse response, @Nullable ModelAndView mv)
        throws Exception {

    HandlerInterceptor[] interceptors = getInterceptors();
    if (!ObjectUtils.isEmpty(interceptors)) {
        for (int i = interceptors.length - 1; i >= 0; i--) {
            HandlerInterceptor interceptor = interceptors[i];
            interceptor.postHandle(request, response, this.handler, mv);
        }
    }
}

From source file:org.springframework.web.servlet.HandlerExecutionChain.java

/**
 * Trigger afterCompletion callbacks on the mapped HandlerInterceptors.
 * Will just invoke afterCompletion for all interceptors whose preHandle invocation
 * has successfully completed and returned true.
 *///from w  ww . j  ava2s.  c  o  m
void triggerAfterCompletion(HttpServletRequest request, HttpServletResponse response, @Nullable Exception ex)
        throws Exception {

    HandlerInterceptor[] interceptors = getInterceptors();
    if (!ObjectUtils.isEmpty(interceptors)) {
        for (int i = this.interceptorIndex; i >= 0; i--) {
            HandlerInterceptor interceptor = interceptors[i];
            try {
                interceptor.afterCompletion(request, response, this.handler, ex);
            } catch (Throwable ex2) {
                logger.error("HandlerInterceptor.afterCompletion threw exception", ex2);
            }
        }
    }
}

From source file:org.springframework.web.servlet.HandlerExecutionChain.java

/**
 * Delegates to the handler's {@code toString()}.
 *///from w  ww.  j a  va  2 s. c  o  m
@Override
public String toString() {
    Object handler = getHandler();
    StringBuilder sb = new StringBuilder();
    sb.append("HandlerExecutionChain with handler [").append(handler).append("]");
    HandlerInterceptor[] interceptors = getInterceptors();
    if (!ObjectUtils.isEmpty(interceptors)) {
        sb.append(" and ").append(interceptors.length).append(" interceptor");
        if (interceptors.length > 1) {
            sb.append("s");
        }
    }
    return sb.toString();
}