Example usage for org.apache.commons.beanutils PropertyUtils isReadable

List of usage examples for org.apache.commons.beanutils PropertyUtils isReadable

Introduction

In this page you can find the example usage for org.apache.commons.beanutils PropertyUtils isReadable.

Prototype

public static boolean isReadable(Object bean, String name) 

Source Link

Document

Return true if the specified property name identifies a readable property on the specified bean; otherwise, return false.

For more details see PropertyUtilsBean.

Usage

From source file:de.alpharogroup.lang.object.MergeObjectExtensions.java

/**
 * Merge the given property to the given 'to' object with the given 'with' object.
 *
 * @param <TO>//  w w w .  j a  v a  2 s.com
 *            the generic type of the object to merge in
 * @param <WITH>
 *            the generic type of the object to merge with
 * @param toObject
 *            the object to merge in
 * @param withObject
 *            the object to merge with
 * @param propertyDescriptor
 *            the property descriptor
 * @throws InvocationTargetException
 *             if the property accessor method throws an exception
 * @throws IllegalAccessException
 *             if the caller does not have access to the property accessor method
 */
public static final <TO, WITH> void mergeProperty(final TO toObject, final WITH withObject,
        final PropertyDescriptor propertyDescriptor) throws IllegalAccessException, InvocationTargetException {
    if (PropertyUtils.isReadable(toObject, propertyDescriptor.getName())
            && PropertyUtils.isWriteable(toObject, propertyDescriptor.getName())) {
        final Method getter = propertyDescriptor.getReadMethod();
        final Object value = getter.invoke(withObject);
        if (!value.isDefaultValue()) {
            final Method setter = propertyDescriptor.getWriteMethod();
            setter.invoke(toObject, value);
        }
    }
}

From source file:com.afeng.common.utils.reflection.MyBeanUtils.java

/**
  * ?/*w  w w. java 2  s  . co  m*/
  * ???
  * 
  * @param databean
  * @param tobean
  * @throws NoSuchMethodException
  * copy
  */
public static void copyBeanNotNull2Bean(Object databean, Object tobean) throws Exception {
    PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(databean);
    for (int i = 0; i < origDescriptors.length; i++) {
        String name = origDescriptors[i].getName();
        //          String type = origDescriptors[i].getPropertyType().toString();
        if ("class".equals(name)) {
            continue; // No point in trying to set an object's class
        }
        if (PropertyUtils.isReadable(databean, name) && PropertyUtils.isWriteable(tobean, name)) {
            try {
                Object value = PropertyUtils.getSimpleProperty(databean, name);
                if (value != null) {
                    copyProperty(tobean, name, value);
                }
            } catch (IllegalArgumentException ie) {
                ; // Should not happen
            } catch (Exception e) {
                ; // Should not happen
            }

        }
    }
}

From source file:com.eryansky.common.utils.reflection.MyBeanUtils.java

/**
  * ?/*from   www  . j  av a2 s.c  o m*/
  * ???
  * 
  * @param databean
  * @param tobean
  * @throws NoSuchMethodException
  * copy
  */
public static void copyBeanNotNull2Bean(Object databean, Object tobean) throws Exception {
    PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(databean);
    for (int i = 0; i < origDescriptors.length; i++) {
        String name = origDescriptors[i].getName();
        //          String type = origDescriptors[i].getPropertyType().toString();
        if ("class".equals(name)) {
            continue; // No point in trying to set an object's class
        }
        if (PropertyUtils.isReadable(databean, name) && PropertyUtils.isWriteable(tobean, name)) {
            try {
                Object value = PropertyUtils.getSimpleProperty(databean, name);
                if (value != null) {
                    copyProperty(tobean, name, value);
                }
            } catch (java.lang.IllegalArgumentException ie) {
                ; // Should not happen
            } catch (Exception e) {
                ; // Should not happen
            }

        }
    }
}

From source file:jp.go.nict.langrid.p2pgridbasis.data.langrid.converter.ConvertUtil.java

static public DataAttributes encode(Object data) throws DataConvertException {
    setLangridConverter();//w  w w .ja va 2  s  .c  o m
    logger.debug("##### encode #####");
    try {
        DataAttributes attr = new DataAttributes();
        for (PropertyDescriptor descriptor : PropertyUtils.getPropertyDescriptors(data)) {
            if (PropertyUtils.isReadable(data, descriptor.getName())) {
                if (descriptor.getName().equalsIgnoreCase("supportedLanguages")) {
                    //supportedLanguages
                    attr.setAttribute(descriptor.getName(),
                            (String) converter.lookup(descriptor.getPropertyType()).convert(String.class,
                                    PropertyUtils.getProperty(data, descriptor.getName())));
                    continue;
                } else if (descriptor.getName().equalsIgnoreCase("instance")) {
                    // 
                    // 
                    continue;
                } else if (descriptor.getName().equalsIgnoreCase("wsdl")) {
                    // 
                    // 
                    continue;
                } else if (descriptor.getName().equalsIgnoreCase("interfaceDefinitions")) {
                    // 
                    // 
                    ServiceType type = (ServiceType) data;
                    Map<String, ServiceInterfaceDefinition> map = new HashMap<String, ServiceInterfaceDefinition>();
                    map = type.getInterfaceDefinitions();
                    String str = "";

                    try {
                        for (ServiceInterfaceDefinition s : map.values()) {
                            str = str + "ProtocolId=" + s.getProtocolId() + "\n";
                            str = str + "Definition="
                                    + Base64.encode(StreamUtil.readAsBytes(s.getDefinition().getBinaryStream()))
                                    + "\n";
                            str = str + "###ServiceInterfaceDefinition###\n";
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }

                    attr.setAttribute("interfaceDefinition_list", str);
                    continue;
                } else if (descriptor.getName().equalsIgnoreCase("allowedAppProvision")) {
                    Service s = (Service) data;
                    String value = "";
                    for (String str : s.getAllowedAppProvision()) {
                        value = value + str + "\n";
                    }
                    attr.setAttribute("allowedAppProvision", value);
                    continue;
                } else if (descriptor.getName().equalsIgnoreCase("allowedUse")) {
                    Service s = (Service) data;
                    String value = "";
                    for (String str : s.getAllowedUse()) {
                        value = value + str + "\n";
                    }
                    attr.setAttribute("allowedUse", value);
                    continue;
                } else if (descriptor.getName().equalsIgnoreCase("supportedDomains")) {
                    Grid g = (Grid) data;
                    List<Domain> list = g.getSupportedDomains();
                    String value = "";
                    for (Domain d : list) {
                        value = value + d.getDomainId() + "\n";
                    }
                    attr.setAttribute("supportedDomain_list", value);
                    continue;
                } else if (descriptor.getName().equalsIgnoreCase("partnerServiceNamespaceURIs")) {
                    //partnerServiceNamespaceURIs
                    BPELService s = (BPELService) data;
                    List<String> list = s.getPartnerServiceNamespaceURIs();
                    String value = "";
                    for (String str : list) {
                        value = value + str + "\n";
                    }
                    attr.setAttribute("partnerServiceNamespaceURI_list", value);
                    continue;
                } else if (descriptor.getName().equalsIgnoreCase("serviceDeployments")) {
                    //ServiceDeployment
                    Service s = (Service) data;
                    String str = "";
                    for (ServiceDeployment sd : s.getServiceDeployments()) {
                        str = str + "GridId=" + sd.getGridId() + "\n";
                        str = str + "ServiceId=" + sd.getServiceId() + "\n";
                        str = str + "NodeId=" + sd.getNodeId() + "\n";
                        str = str + "ServicePath=" + sd.getServicePath() + "\n";
                        str = str + "Enabled=" + String.valueOf(sd.isEnabled()) + "\n";
                        str = str + "CreateTime=" + String.valueOf(sd.getCreatedDateTime().getTimeInMillis())
                                + "\n";
                        str = str + "UpdateTime=" + String.valueOf(sd.getUpdatedDateTime().getTimeInMillis())
                                + "\n";
                        if (sd.getDisabledByErrorDate() != null) {
                            str = str + "ErrorDate="
                                    + String.valueOf(sd.getDisabledByErrorDate().getTimeInMillis()) + "\n";
                        }
                        if (sd.getDeployedDateTime() != null) {
                            str = str + "DeployedTime="
                                    + String.valueOf(sd.getDeployedDateTime().getTimeInMillis()) + "\n";
                        }
                        str = str + "###ServiceDeployment###\n";
                    }
                    attr.setAttribute("deployment_list", str);
                    continue;
                } else if (descriptor.getName().equalsIgnoreCase("serviceEndpoints")) {
                    //ServiceEndpoint
                    StringBuilder str = new StringBuilder();
                    Service s = (Service) data;
                    for (ServiceEndpoint se : s.getServiceEndpoints()) {
                        str.append("GridId=" + se.getGridId() + "\n");
                        str.append("ProtocolId=" + se.getProtocolId() + "\n");
                        str.append("ServiceId=" + se.getServiceId() + "\n");
                        str.append("Enabled=" + String.valueOf(se.isEnabled()) + "\n");
                        str.append("Url=" + se.getUrl().toString() + "\n");
                        str.append("AuthUserName=" + se.getAuthUserName() + "\n");
                        str.append("AuthPassword=" + se.getAuthPassword() + "\n");
                        str.append("DisableReason=" + se.getDisableReason() + "\n");
                        str.append("CreateTime=" + String.valueOf(se.getCreatedDateTime().getTimeInMillis())
                                + "\n");
                        str.append("UpdateTime=" + String.valueOf(se.getUpdatedDateTime().getTimeInMillis())
                                + "\n");
                        if (se.getDisabledByErrorDate() != null) {
                            str.append("ErrorDate="
                                    + String.valueOf(se.getDisabledByErrorDate().getTimeInMillis()) + "\n");
                        }
                        str.append("###ServiceEndpoint###\n");
                    }
                    attr.setAttribute("endpoint_list", str.toString());
                    continue;
                } else if (descriptor.getName().equalsIgnoreCase("invocations")) {
                    //Invocation
                    String str = "";
                    Service s = (Service) data;
                    for (Invocation in : s.getInvocations()) {
                        str = str + "InvocationName=" + in.getInvocationName() + "\n";
                        str = str + "OwnerServiceGridId=" + in.getOwnerServiceGridId() + "\n";
                        str = str + "OwnerServiceId=" + in.getOwnerServiceId() + "\n";
                        str = str + "ServiceGridId=" + in.getServiceGridId() + "\n";
                        str = str + "ServiceId=" + in.getServiceId() + "\n";
                        str = str + "ServiceName=" + in.getServiceName() + "\n";
                        str = str + "CreateTime=" + String.valueOf(in.getCreatedDateTime().getTimeInMillis())
                                + "\n";
                        str = str + "UpdateTime=" + String.valueOf(in.getUpdatedDateTime().getTimeInMillis())
                                + "\n";
                        str = str + "###Invocation###\n";
                    }
                    attr.setAttribute("invocations_list", str);
                    continue;
                } else if (descriptor.getName().equalsIgnoreCase("metaAttributes")) {
                    //metaAttributes
                    String str = "";
                    if (data.getClass().getName().endsWith("ResourceType")) {
                        ResourceType r = (ResourceType) data;
                        for (ResourceMetaAttribute a : r.getMetaAttributes().values()) {
                            str = str + "DomainId=" + a.getDomainId() + "\n";
                            str = str + "AttributeId=" + a.getAttributeId() + "\n";
                            str = str + "###MetaAttribute###\n";
                        }
                    } else if (data.getClass().getName().endsWith("ServiceType")) {
                        ServiceType s = (ServiceType) data;
                        for (ServiceMetaAttribute a : s.getMetaAttributes().values()) {
                            str = str + "DomainId=" + a.getDomainId() + "\n";
                            str = str + "AttributeId=" + a.getAttributeId() + "\n";
                            str = str + "###MetaAttribute###\n";
                        }
                    } else {
                        logger.info("metaAttributes : " + data.getClass().getName());
                    }
                    attr.setAttribute("metaAttribute_list", str);
                    continue;
                } else if (descriptor.getName().equalsIgnoreCase("attributes")) {
                    //attribute
                    String str = "";
                    if (data.getClass().getName().endsWith("User")) {
                        User u = (User) data;
                        for (UserAttribute a : u.getAttributes()) {
                            str = str + "attribute_GridId=" + a.getGridId() + "\n";
                            str = str + "attribute_Id=" + a.getUserId() + "\n";
                            str = str + "attribute_Name=" + a.getName() + "\n";
                            str = str + "attribute_Value=" + a.getValue() + "\n";
                            str = str + "attribute_CreateTime="
                                    + String.valueOf(a.getCreatedDateTime().getTimeInMillis()) + "\n";
                            str = str + "attribute_UpdateTime="
                                    + String.valueOf(a.getUpdatedDateTime().getTimeInMillis()) + "\n";
                            str = str + "###Attribute###\n";
                        }
                    } else if (data.getClass().getName().endsWith("Service")) {
                        Service s = (Service) data;
                        for (ServiceAttribute a : s.getAttributes()) {
                            str = str + "attribute_GridId=" + a.getGridId() + "\n";
                            str = str + "attribute_Id=" + a.getServiceId() + "\n";
                            str = str + "attribute_Name=" + a.getName() + "\n";
                            str = str + "attribute_Value=" + a.getValue() + "\n";
                            str = str + "attribute_CreateTime="
                                    + String.valueOf(a.getCreatedDateTime().getTimeInMillis()) + "\n";
                            str = str + "attribute_UpdateTime="
                                    + String.valueOf(a.getUpdatedDateTime().getTimeInMillis()) + "\n";
                            str = str + "###Attribute###\n";
                        }
                    } else if (data.getClass().getName().endsWith("Node")) {
                        Node s = (Node) data;
                        for (NodeAttribute a : s.getAttributes()) {
                            str = str + "attribute_GridId=" + a.getGridId() + "\n";
                            str = str + "attribute_Id=" + a.getNodeId() + "\n";
                            str = str + "attribute_Name=" + a.getName() + "\n";
                            str = str + "attribute_Value=" + a.getValue() + "\n";
                            str = str + "attribute_CreateTime="
                                    + String.valueOf(a.getCreatedDateTime().getTimeInMillis()) + "\n";
                            str = str + "attribute_UpdateTime="
                                    + String.valueOf(a.getUpdatedDateTime().getTimeInMillis()) + "\n";
                            str = str + "###Attribute###\n";
                        }
                    } else if (data.getClass().getName().endsWith("Grid")) {
                        Grid s = (Grid) data;
                        for (GridAttribute a : s.getAttributes()) {
                            str = str + "attribute_GridId=" + a.getGridId() + "\n";
                            str = str + "attribute_Name=" + a.getName() + "\n";
                            str = str + "attribute_Value=" + a.getValue() + "\n";
                            str = str + "attribute_CreateTime="
                                    + String.valueOf(a.getCreatedDateTime().getTimeInMillis()) + "\n";
                            str = str + "attribute_UpdateTime="
                                    + String.valueOf(a.getUpdatedDateTime().getTimeInMillis()) + "\n";
                            str = str + "###Attribute###\n";
                        }
                    } else if (data.getClass().getName().endsWith("Resource")) {
                        Resource s = (Resource) data;
                        for (ResourceAttribute a : s.getAttributes()) {
                            str = str + "attribute_GridId=" + a.getGridId() + "\n";
                            str = str + "attribute_Id=" + a.getResourceId() + "\n";
                            str = str + "attribute_Name=" + a.getName() + "\n";
                            str = str + "attribute_Value=" + a.getValue() + "\n";
                            str = str + "attribute_CreateTime="
                                    + String.valueOf(a.getCreatedDateTime().getTimeInMillis()) + "\n";
                            str = str + "attribute_UpdateTime="
                                    + String.valueOf(a.getUpdatedDateTime().getTimeInMillis()) + "\n";
                            str = str + "###Attribute###\n";
                        }
                    }
                    attr.setAttribute("attribute_list", str);
                    continue;
                } else if (data instanceof Service && (descriptor.getName().equals("alternateServiceId")
                        || descriptor.getName().equals("useAlternateServices"))) {
                    // 
                    // 
                    continue;
                }

                //Read OK
                if (data instanceof BPELService && descriptor.getName().equals("transferExecution")) {
                    // ignore
                } else {
                    attr.setAttribute(descriptor.getName(), BeanUtils.getProperty(data, descriptor.getName()));
                }
            } else if (descriptor.getPropertyType().isArray()) {
                logger.debug("name : " + descriptor.getName() + " isArray");
                // 
                // 
                attr.setAttribute(descriptor.getName(), (String) converter.lookup(descriptor.getPropertyType())
                        .convert(String.class, PropertyUtils.getProperty(data, descriptor.getName())));
            } else {
                logger.debug("Name : " + descriptor.getName());
                for (Method m : data.getClass().getMethods()) {
                    if (m.getName().equalsIgnoreCase("get" + descriptor.getName())
                            || m.getName().equalsIgnoreCase("is" + descriptor.getName())) {
                        if (m.getParameterTypes().length != 0) {
                            // 
                            // 
                            logger.debug("class : " + data.getClass().getName());
                            logger.debug("?:Skip");
                            break;
                        } else {
                            // 
                            // 
                            logger.debug("value : " + m.invoke(data));
                        }
                        attr.setAttribute(descriptor.getName(), m.invoke(data).toString());
                        break;
                    }
                }
            }
        }
        return attr;
    } catch (InvocationTargetException e) {
        throw new DataConvertException(e);
    } catch (IllegalArgumentException e) {
        throw new DataConvertException(e);
    } catch (IllegalAccessException e) {
        throw new DataConvertException(e);
    } catch (NoSuchMethodException e) {
        throw new DataConvertException(e);
    }
}

From source file:com.prashsoft.javakiva.LenderUtil.java

public List getLendersDetails(String lenderIds) {

    JSONObject jsonObject;/*from   w w w  . j  ava  2 s.c om*/

    List lenders = new ArrayList();

    String urlSuffix = "lenders";
    String urlMethod = lenderIds;

    Object bean = KivaUtil.getBeanResponse(urlSuffix, urlMethod, null);

    if (!(PropertyUtils.isReadable(bean, "lenders")))
        return null;

    List jsonLenders = (List) KivaUtil.getBeanProperty(bean, "lenders");

    if (jsonLenders == null || jsonLenders.size() == 0)
        return null;

    Iterator lenderIter = jsonLenders.iterator();

    while (lenderIter.hasNext()) {

        jsonObject = JSONObject.fromObject(lenderIter.next());
        bean = JSONObject.toBean(jsonObject);

        Lender lender = getLender(bean);
        lenders.add(lender);

    }
    return lenders;
}

From source file:ca.sqlpower.testutil.TestUtils.java

/**
 * Gets all the settable properties on the given target object
 * which are not in the given ignore set, and stuffs them into a Map.
 * //from w  w  w.  j av  a  2 s . c  o  m
 * @param target The object to change the properties of
 * @param propertiesToIgnore The properties of target not to modify or read
 * @return The aforementioned stuffed map
 */
public static Map<String, Object> getAllInterestingProperties(Object target, Set<String> propertiesToIgnore)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    Map<String, Object> newDescription = new HashMap<String, Object>();
    PropertyDescriptor[] props = PropertyUtils.getPropertyDescriptors(target);
    for (int i = 0; i < props.length; i++) {
        if (PropertyUtils.isReadable(target, props[i].getName()) && props[i].getReadMethod() != null
                && !propertiesToIgnore.contains(props[i].getName())) {
            newDescription.put(props[i].getName(), PropertyUtils.getProperty(target, props[i].getName()));
        }
    }
    return newDescription;
}

From source file:com.redhat.rcm.maven.plugin.buildmetadata.maven.MavenPropertyHelper.java

/**
 * Returns a property from the project instance.
 *//*  w  w w. j  a va 2 s .c  o m*/
private String getProjectProperty(final String name) {
    final String projectName = name.substring(PROJECT_PROPERTY_NAME_PREFIX_LENGTH);
    if (PropertyUtils.isReadable(project, projectName)) {
        try {
            return getProjectProperty(project, projectName);
        } catch (final Exception e) {
            throw new IllegalStateException("Cannot access project property '" + name + "'.");
        }
    }

    return null;
}

From source file:com.prashsoft.javakiva.LenderUtil.java

public List<Lender> getLendersFromBean(Object bean) {

    if (!(PropertyUtils.isReadable(bean, "lenders")))
        return null;

    List jsonLenders = (List) KivaUtil.getBeanProperty(bean, "lenders");

    if (jsonLenders == null || jsonLenders.size() == 0)
        return null;

    List<Lender> lenders = new ArrayList<Lender>();
    JSONObject jsonObject;//from   w  ww . j  av  a  2  s . c om
    Lender lender;
    // Iterator lenderIter = jsonLenders.iterator();

    // while (lenderIter.hasNext()) {
    for (Object jsonLender : jsonLenders) {

        jsonObject = JSONObject.fromObject(jsonLender);
        bean = JSONObject.toBean(jsonObject);

        // lender = getLenderDetails((String) KivaUtil.getBeanProperty(bean, "lender_id"));
        // lenders.add(lender);
        String lender_id = (String) KivaUtil.getBeanProperty(bean, "lender_id");
        if (StringUtils.isNotBlank(lender_id)) {
            lender = getLenderDetails(lender_id);
            lenders.add(lender);
        }
    }
    return lenders;
}

From source file:com.erudika.para.utils.ValidationUtils.java

/**
 * Validates objects./*from w  ww  .j  a  v a  2 s . c  om*/
 * @param content an object to be validated
 * @param app the current app
 * @return a list of error messages or empty if object is valid
 */
public static String[] validateObject(App app, ParaObject content) {
    if (content == null || app == null) {
        return new String[] { "Object cannot be null." };
    }
    try {
        String type = content.getType();
        boolean isCustomType = (content instanceof Sysprop) && !type.equals(Utils.type(Sysprop.class));
        // Validate custom types and user-defined properties
        if (!app.getValidationConstraints().isEmpty() && isCustomType) {
            Map<String, Map<String, Map<String, Object>>> fieldsMap = app.getValidationConstraints().get(type);
            if (fieldsMap != null && !fieldsMap.isEmpty()) {
                ArrayList<String> errors = new ArrayList<String>();
                for (Map.Entry<String, Map<String, Map<String, Object>>> e : fieldsMap.entrySet()) {
                    String field = e.getKey();
                    Object actualValue = ((Sysprop) content).getProperty(field);
                    // overriding core property validation rules is allowed
                    if (actualValue == null && PropertyUtils.isReadable(content, field)) {
                        actualValue = PropertyUtils.getProperty(content, field);
                    }
                    Map<String, Map<String, Object>> consMap = e.getValue();
                    for (Map.Entry<String, Map<String, Object>> constraint : consMap.entrySet()) {
                        String consName = constraint.getKey();
                        Map<String, Object> vals = constraint.getValue();
                        if (vals == null) {
                            vals = Collections.emptyMap();
                        }

                        Object val = vals.get("value");
                        Object min = vals.get("min");
                        Object max = vals.get("max");
                        Object in = vals.get("integer");
                        Object fr = vals.get("fraction");

                        if ("required".equals(consName) && !required().isValid(actualValue)) {
                            errors.add(Utils.formatMessage("{0} is required.", field));
                        } else if (matches(Min.class, consName) && !min(val).isValid(actualValue)) {
                            errors.add(
                                    Utils.formatMessage("{0} must be a number larger than {1}.", field, val));
                        } else if (matches(Max.class, consName) && !max(val).isValid(actualValue)) {
                            errors.add(
                                    Utils.formatMessage("{0} must be a number smaller than {1}.", field, val));
                        } else if (matches(Size.class, consName) && !size(min, max).isValid(actualValue)) {
                            errors.add(
                                    Utils.formatMessage("{0} must be between {1} and {2}.", field, min, max));
                        } else if (matches(Email.class, consName) && !email().isValid(actualValue)) {
                            errors.add(Utils.formatMessage("{0} is not a valid email.", field));
                        } else if (matches(Digits.class, consName) && !digits(in, fr).isValid(actualValue)) {
                            errors.add(
                                    Utils.formatMessage("{0} is not a valid number or within range.", field));
                        } else if (matches(Pattern.class, consName) && !pattern(val).isValid(actualValue)) {
                            errors.add(Utils.formatMessage("{0} doesn't match the pattern {1}.", field, val));
                        } else if (matches(AssertFalse.class, consName) && !falsy().isValid(actualValue)) {
                            errors.add(Utils.formatMessage("{0} must be false.", field));
                        } else if (matches(AssertTrue.class, consName) && !truthy().isValid(actualValue)) {
                            errors.add(Utils.formatMessage("{0} must be true.", field));
                        } else if (matches(Future.class, consName) && !future().isValid(actualValue)) {
                            errors.add(Utils.formatMessage("{0} must be in the future.", field));
                        } else if (matches(Past.class, consName) && !past().isValid(actualValue)) {
                            errors.add(Utils.formatMessage("{0} must be in the past.", field));
                        } else if (matches(URL.class, consName) && !url().isValid(actualValue)) {
                            errors.add(Utils.formatMessage("{0} is not a valid URL.", field));
                        }
                    }
                }
                if (!errors.isEmpty()) {
                    return errors.toArray(new String[0]);
                }
            }
        }
    } catch (Exception ex) {
        logger.error(null, ex);
    }
    return validateObject(content);
}

From source file:com.erudika.para.validation.ValidationUtils.java

/**
 * Validates objects./*w ww  .  j  a  va 2 s  . c o  m*/
 * @param content an object to be validated
 * @param app the current app
 * @return a list of error messages or empty if object is valid
 */
public static String[] validateObject(App app, ParaObject content) {
    if (content == null || app == null) {
        return new String[] { "Object cannot be null." };
    }
    try {
        String type = content.getType();
        boolean isCustomType = (content instanceof Sysprop) && !type.equals(Utils.type(Sysprop.class));
        // Validate custom types and user-defined properties
        if (!app.getValidationConstraints().isEmpty() && isCustomType) {
            Map<String, Map<String, Map<String, ?>>> fieldsMap = app.getValidationConstraints().get(type);
            if (fieldsMap != null && !fieldsMap.isEmpty()) {
                LinkedList<String> errors = new LinkedList<String>();
                for (Map.Entry<String, Map<String, Map<String, ?>>> e : fieldsMap.entrySet()) {
                    String field = e.getKey();
                    Object actualValue = ((Sysprop) content).getProperty(field);
                    // overriding core property validation rules is allowed
                    if (actualValue == null && PropertyUtils.isReadable(content, field)) {
                        actualValue = PropertyUtils.getProperty(content, field);
                    }
                    Map<String, Map<String, ?>> consMap = e.getValue();
                    for (Map.Entry<String, Map<String, ?>> constraint : consMap.entrySet()) {
                        String consName = constraint.getKey();
                        Map<String, ?> vals = constraint.getValue();
                        if (vals == null) {
                            vals = Collections.emptyMap();
                        }

                        Object val = vals.get("value");
                        Object min = vals.get("min");
                        Object max = vals.get("max");
                        Object in = vals.get("integer");
                        Object fr = vals.get("fraction");

                        if ("required".equals(consName) && !required().isValid(actualValue)) {
                            errors.add(Utils.formatMessage("{0} is required.", field));
                        } else if (matches(Min.class, consName) && !min(val).isValid(actualValue)) {
                            errors.add(
                                    Utils.formatMessage("{0} must be a number larger than {1}.", field, val));
                        } else if (matches(Max.class, consName) && !max(val).isValid(actualValue)) {
                            errors.add(
                                    Utils.formatMessage("{0} must be a number smaller than {1}.", field, val));
                        } else if (matches(Size.class, consName) && !size(min, max).isValid(actualValue)) {
                            errors.add(
                                    Utils.formatMessage("{0} must be between {1} and {2}.", field, min, max));
                        } else if (matches(Email.class, consName) && !email().isValid(actualValue)) {
                            errors.add(Utils.formatMessage("{0} is not a valid email.", field));
                        } else if (matches(Digits.class, consName) && !digits(in, fr).isValid(actualValue)) {
                            errors.add(
                                    Utils.formatMessage("{0} is not a valid number or within range.", field));
                        } else if (matches(Pattern.class, consName) && !pattern(val).isValid(actualValue)) {
                            errors.add(Utils.formatMessage("{0} doesn't match the pattern {1}.", field, val));
                        } else if (matches(AssertFalse.class, consName) && !falsy().isValid(actualValue)) {
                            errors.add(Utils.formatMessage("{0} must be false.", field));
                        } else if (matches(AssertTrue.class, consName) && !truthy().isValid(actualValue)) {
                            errors.add(Utils.formatMessage("{0} must be true.", field));
                        } else if (matches(Future.class, consName) && !future().isValid(actualValue)) {
                            errors.add(Utils.formatMessage("{0} must be in the future.", field));
                        } else if (matches(Past.class, consName) && !past().isValid(actualValue)) {
                            errors.add(Utils.formatMessage("{0} must be in the past.", field));
                        } else if (matches(URL.class, consName) && !url().isValid(actualValue)) {
                            errors.add(Utils.formatMessage("{0} is not a valid URL.", field));
                        }
                    }
                }
                if (!errors.isEmpty()) {
                    return errors.toArray(new String[0]);
                }
            }
        }
    } catch (Exception ex) {
        logger.error(null, ex);
    }
    return validateObject(content);
}