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.uimafit.component.initialize.ConfigurationParameterInitializer.java

/**
 * Initialize a component from an {@link UimaContext} This code can be a little confusing
 * because the configuration parameter annotations are used in two contexts: in describing the
 * component and to initialize member variables from a {@link UimaContext}. Here we are
 * performing the latter task. It is important to remember that the {@link UimaContext} passed
 * in to this method may or may not have been derived using reflection of the annotations (i.e.
 * using {@link ConfigurationParameterFactory} via e.g. a call to a AnalysisEngineFactory.create
 * method). It is just as possible for the description of the component to come directly from an
 * XML descriptor file. So, for example, just because a configuration parameter specifies a
 * default value, this does not mean that the passed in context will have a value for that
 * configuration parameter. It should be possible for a descriptor file to specify its own value
 * or to not provide one at all. If the context does not have a configuration parameter, then
 * the default value provided by the developer as specified by the defaultValue element of the
 * {@link ConfigurationParameter} will be used. See comments in the code for additional details.
 *
 * @param component the component to initialize.
 * @param context a UIMA context with configuration parameters.
 *//*from w ww .  j a va2s.co m*/
public static void initialize(final Object component, final UimaContext context)
        throws ResourceInitializationException {
    MutablePropertyValues values = new MutablePropertyValues();
    List<String> mandatoryValues = new ArrayList<String>();

    for (Field field : ReflectionUtil.getFields(component)) { // component.getClass().getDeclaredFields())
        if (ConfigurationParameterFactory.isConfigurationParameterField(field)) {
            org.uimafit.descriptor.ConfigurationParameter annotation = field
                    .getAnnotation(org.uimafit.descriptor.ConfigurationParameter.class);

            Object parameterValue;
            String parameterName = ConfigurationParameterFactory.getConfigurationParameterName(field);

            // Obtain either from the context - or - if the context does not provide the
            // parameter, check if there is a default value. Note there are three possibilities:
            // 1) Parameter present and set
            // 2) Parameter present and set to null (null value)
            // 3) Parameter not present (also provided as null value by UIMA)
            // Unfortunately we cannot make a difference between case 2 and 3 since UIMA does 
            // not allow us to actually get a list of the parameters set in the context. We can
            // only get a list of the declared parameters. Thus we have to rely on the null
            // value.
            parameterValue = context.getConfigParameterValue(parameterName);
            if (parameterValue == null) {
                parameterValue = ConfigurationParameterFactory.getDefaultValue(field);
            }

            if (parameterValue != null) {
                values.addPropertyValue(field.getName(), parameterValue);
            }

            // TODO does this check really belong here? It seems that
            // this check is already performed by UIMA
            if (annotation.mandatory()) {
                mandatoryValues.add(field.getName());

                //               if (parameterValue == null) {
                //                  final String key = ResourceInitializationException.CONFIG_SETTING_ABSENT;
                //                  throw new ResourceInitializationException(key,
                //                        new Object[] { configurationParameterName });
                //               }
            }
            //            else {
            //               if (parameterValue == null) {
            //                  continue;
            //               }
            //            }
            //            final Object fieldValue = convertValue(field, parameterValue);
            //            try {
            //               setParameterValue(component, field, fieldValue);
            //            }
            //            catch (Exception e) {
            //               throw new ResourceInitializationException(e);
            //            }
        }
    }

    DataBinder binder = new DataBinder(component) {
        @Override
        protected void checkRequiredFields(MutablePropertyValues mpvs) {
            String[] requiredFields = getRequiredFields();
            if (!ObjectUtils.isEmpty(requiredFields)) {
                Map<String, PropertyValue> propertyValues = new HashMap<String, PropertyValue>();
                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);
                    // For our purposes, empty Strings or empty String arrays do not count as
                    // empty. Empty is only "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);
                        }
                    }
                }
            }
        }
    };
    binder.initDirectFieldAccess();
    PropertyEditorUtil.registerUimaFITEditors(binder);
    binder.setRequiredFields(mandatoryValues.toArray(new String[mandatoryValues.size()]));
    binder.bind(values);
    if (binder.getBindingResult().hasErrors()) {
        StringBuilder sb = new StringBuilder();
        sb.append("Errors initializing [" + component.getClass() + "]");
        for (ObjectError error : binder.getBindingResult().getAllErrors()) {
            if (sb.length() > 0) {
                sb.append("\n");
            }
            sb.append(error.getDefaultMessage());
        }
        throw new IllegalArgumentException(sb.toString());
    }
}

From source file:de.tudarmstadt.ukp.dkpro.bigdata.io.hadoop.HdfsResourceLoader.java

@SuppressWarnings("deprecation")
private void doRetrieveMatchingResources(Path rootDir, String subPattern, Set<Resource> results)
        throws IOException {
    if (!this.fs.isFile(rootDir)) {
        FileStatus[] statuses = null;//from   ww  w  . j a v  a  2s  . com
        try {
            statuses = this.fs.listStatus(rootDir);
        } catch (final IOException ex) {
            // ignore (likely security exception)
        }

        if (!ObjectUtils.isEmpty(statuses)) {
            final String root = rootDir.toUri().getPath();
            for (final FileStatus fileStatus : statuses) {
                final Path p = fileStatus.getPath();
                String location = p.toUri().getPath();
                if (location.startsWith(root)) {
                    location = location.substring(root.length());
                }
                if (fileStatus.isDir() && this.pathMatcher.matchStart(subPattern, location)) {
                    doRetrieveMatchingResources(p, subPattern, results);
                }

                else if (this.pathMatcher.match(subPattern.substring(1), location)) {
                    results.add(new HdfsResource(p, this.fs));
                }
            }
        }
    }

    // Remove "if" to allow folders to be added as well
    else if (this.pathMatcher.match(subPattern, stripPrefix(rootDir.toUri().getPath()))) {
        results.add(new HdfsResource(rootDir, this.fs));
    }
}

From source file:ch.rasc.wampspring.method.PayloadArgumentResolver.java

protected void validate(Message<?> message, MethodParameter parameter, Object target) {
    if (this.validator == null) {
        return;/*  w w  w. j  av a 2  s .  c  o  m*/
    }
    for (Annotation ann : parameter.getParameterAnnotations()) {
        Validated validatedAnn = AnnotationUtils.getAnnotation(ann, Validated.class);
        if (validatedAnn != null || ann.annotationType().getSimpleName().startsWith("Valid")) {
            Object hints = validatedAnn != null ? validatedAnn.value() : AnnotationUtils.getValue(ann);
            Object[] validationHints = hints instanceof Object[] ? (Object[]) hints : new Object[] { hints };
            BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(target,
                    getParameterName(parameter));
            if (!ObjectUtils.isEmpty(validationHints) && this.validator instanceof SmartValidator) {
                ((SmartValidator) this.validator).validate(target, bindingResult, validationHints);
            } else {
                this.validator.validate(target, bindingResult);
            }
            if (bindingResult.hasErrors()) {
                throw new MethodArgumentNotValidException(message, parameter, bindingResult);
            }
            break;
        }
    }
}

From source file:spring.osgi.io.OsgiBundleResourcePatternResolver.java

public Resource[] getResources(final String locationPattern) throws IOException {

    Resource[] resources = findResources(locationPattern);

    // check whether we found something or we should fall-back to a
    // non-existing resource
    if (ObjectUtils.isEmpty(resources) && (!getPathMatcher().isPattern(locationPattern))) {
        return new Resource[] { getResourceLoader().getResource(locationPattern) };
    }/*w  w w  . j  a  v a  2  s . c  o  m*/
    // return the original array
    return resources;

}

From source file:org.springmodules.cache.provider.ehcache.EhCacheFacade.java

/**
 * Removes all the entries in the caches specified in the given flushing
 * model. The flushing model should be an instance of
 * <code>{@link EhCacheFlushingModel}</code>.
 *
 * @param model the flushing model.//from w  w w  .  java  2 s.  c om
 * @throws CacheNotFoundException if the cache specified in the given model cannot be found.
 * @throws CacheAccessException   wrapping any unexpected exception thrown by the cache.
 * @see AbstractCacheProviderFacade#onFlushCache(FlushingModel)
 */
protected void onFlushCache(FlushingModel model) throws CacheException {
    EhCacheFlushingModel flushingModel = (EhCacheFlushingModel) model;
    String[] cacheNames = flushingModel.getCacheNames();

    if (!ObjectUtils.isEmpty(cacheNames)) {
        CacheException cacheException = null;
        int nameCount = cacheNames.length;

        try {
            for (int i = 0; i < nameCount; i++) {
                Cache cache = getCache(cacheNames[i]);
                cache.removeAll();
            }
        } catch (CacheException exception) {
            cacheException = exception;
        } catch (Exception exception) {
            cacheException = new CacheAccessException(exception);
        }

        if (cacheException != null) {
            throw cacheException;
        }
    }
}

From source file:com.xdtech.core.orm.utils.AssertUtils.java

/**
 * Assert that an array has elements; that is, it must not be
 * <code>null</code> and must have at least one element.
 * <pre class="code">Assert.notEmpty(array, "The array must have elements");</pre>
 * @param array the array to check//  w  ww . j a  v a 2s .co m
 * @param message the exception message to use if the assertion fails
 * @throws IllegalArgumentException if the object array is <code>null</code> or has no elements
 */
public static void notEmpty(Object[] array, String message) {
    if (ObjectUtils.isEmpty(array)) {
        throw new IllegalArgumentException(message);
    }
}

From source file:com.xdtech.core.orm.utils.AssertUtils.java

public static void notEmpty(Object[] array, RuntimeException throwIfAssertFail) {
    if (ObjectUtils.isEmpty(array)) {
        throw throwIfAssertFail;
    }/*from w w  w  .  j av  a 2s .  co  m*/
}

From source file:com.glaf.core.db.mybatis2.SqlMapClientFactoryBean.java

/**
 * Build a SqlMapClient instance based on the given standard configuration.
 * <p>/*from ww w  .ja v  a 2  s .co  m*/
 * The default implementation uses the standard iBATIS
 * {@link SqlMapClientBuilder} API to build a SqlMapClient instance based on
 * an InputStream (if possible, on iBATIS 2.3 and higher) or on a Reader (on
 * iBATIS up to version 2.2).
 * 
 * @param configLocations
 *            the config files to load from
 * @param properties
 *            the SqlMapClient properties (if any)
 * @return the SqlMapClient instance (never {@code null})
 * @throws IOException
 *             if loading the config file failed
 * @see com.ibatis.sqlmap.client.SqlMapClientBuilder#buildSqlMapClient
 */
protected SqlMapClient buildSqlMapClient(Resource[] configLocations, Resource[] mappingLocations,
        Properties properties) throws IOException {

    if (ObjectUtils.isEmpty(configLocations)) {
        throw new IllegalArgumentException("At least 1 'configLocation' entry is required");
    }

    SqlMapClient client = null;
    SqlMapConfigParser configParser = new SqlMapConfigParser();
    for (Resource configLocation : configLocations) {
        InputStream is = configLocation.getInputStream();
        try {
            client = configParser.parse(is, properties);
        } catch (RuntimeException ex) {
            throw new NestedIOException("Failed to parse config resource: " + configLocation, ex.getCause());
        }
    }

    if (mappingLocations != null) {
        SqlMapParser mapParser = SqlMapParserFactory.createSqlMapParser(configParser);
        for (Resource mappingLocation : mappingLocations) {
            try {
                mapParser.parse(mappingLocation.getInputStream());
            } catch (NodeletException ex) {
                throw new NestedIOException("Failed to parse mapping resource: " + mappingLocation, ex);
            }
        }
    }

    return client;
}

From source file:spring.osgi.io.OsgiBundleResource.java

/**
 * Resolves a resource from *the bundle space* only. Only the bundle and its
 * attached fragments are searched for the given resource. Note that this
 * method returns only the first URL found, discarding the rest. To retrieve
 * the entire set, consider using {@link spring.osgi.io.OsgiBundleResourcePatternResolver}.
 *
 * @param bundlePath the path to resolve
 * @return a URL to the returned resource or null if none is found
 * @throws java.io.IOException/*from w ww  . ja v a  2s  .c o  m*/
 */
ContextResource getResourceFromBundleSpace(String bundlePath) throws IOException {
    ContextResource[] res = getAllUrlsFromBundleSpace(bundlePath);
    return (ObjectUtils.isEmpty(res) ? null : res[0]);
}

From source file:com.gst.accounting.rule.serialization.AccountingRuleCommandFromApiJsonDeserializer.java

public void validateCreditOrDebitTagArray(final String[] creditOrDebitTagArray,
        final DataValidatorBuilder baseDataValidator, final String parameter) {
    if (creditOrDebitTagArray != null && !ObjectUtils.isEmpty(creditOrDebitTagArray)) {
        for (final String tag : creditOrDebitTagArray) {
            baseDataValidator.reset().parameter(parameter).value(tag).ignoreIfNull().notBlank()
                    .longGreaterThanZero();
        }// w  w w.  j  a  va2  s .  c  o m
    }
}