Example usage for org.apache.commons.lang ClassUtils isAssignable

List of usage examples for org.apache.commons.lang ClassUtils isAssignable

Introduction

In this page you can find the example usage for org.apache.commons.lang ClassUtils isAssignable.

Prototype


public static boolean isAssignable(Class<?> cls, Class<?> toClass) 

Source Link

Document

Checks if one Class can be assigned to a variable of another Class.

Unlike the Class#isAssignableFrom(java.lang.Class) method, this method takes into account widenings of primitive classes and nulls.

Primitive widenings allow an int to be assigned to a long, float or double.

Usage

From source file:org.openmrs.module.clinicalsummary.web.controller.WebUtils.java

/**
 * @param object/*from  ww w .  j  av  a2s . co  m*/
 * @return
 */
public static String getIdValue(final Object object) {
    String value = StringUtils.EMPTY;
    if (object != null && ClassUtils.isAssignable(object.getClass(), OpenmrsObject.class)) {
        Integer id = ((OpenmrsObject) object).getId();
        if (id != null)
            value = String.valueOf(id);
    }
    return value;
}

From source file:org.openmrs.module.odkconnector.serialization.serializer.ListSerializer.java

/**
 * Write the data to the output stream./*from  w  ww. jav  a  2 s . com*/
 *
 * @param stream the output stream
 * @param data   the data that need to be written to the output stream
 * @throws java.io.IOException thrown when the writing process encounter is failing
 */
@Override
public void write(final OutputStream stream, final Object data) throws IOException {

    DataOutputStream outputStream = new DataOutputStream(stream);

    List list = null;
    if (ClassUtils.isAssignable(data.getClass(), List.class))
        list = (List) data;

    if (list == null || CollectionUtils.isEmpty(list))
        outputStream.writeInt(Serializer.ZERO);
    else {
        outputStream.writeInt(list.size());
        for (Object object : list) {
            Serializer serializer = HandlerUtil.getPreferredHandler(Serializer.class, object.getClass());
            serializer.write(outputStream, object);
        }
        outputStream.flush();
    }
}

From source file:org.projectforge.common.MyBeanComparator.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public int compare(final T o1, final T o2) {
    try {/*w  w  w.  ja  v a2s .com*/
        final Object value1 = BeanHelper.getNestedProperty(o1, property);
        final Object value2 = BeanHelper.getNestedProperty(o2, property);
        if (value1 == null) {
            if (value2 == null)
                return 0;
            else
                return (asc == true) ? -1 : 1;
        }
        if (value2 == null) {
            return (asc == true) ? 1 : -1;
        }
        if (ClassUtils.isAssignable(value2.getClass(), value1.getClass()) == true) {
            if (asc == true) {
                return ((Comparable) value1).compareTo(value2);
            } else {
                return -((Comparable) value1).compareTo(value2);
            }
        } else {
            final String sval1 = String.valueOf(value1);
            final String sval2 = String.valueOf(value2);
            if (asc == true) {
                return sval1.compareTo(sval2);
            } else {
                return -sval1.compareTo(sval2);
            }
        }
    } catch (final Exception ex) {
        log.error("Exception while comparing values of property '" + property + "': " + ex.getMessage());
        return 0;
    }
}

From source file:org.projectforge.core.AbstractBaseDO.java

/**
 * Copies all values from the given src object excluding the values created and lastUpdate. Do not overwrite created and lastUpdate from
 * the original database object.//  w  w  w .j av  a2 s.c  o m
 * @param src
 * @param dest
 * @param ignoreFields Does not copy these properties (by field name).
 * @return true, if any modifications are detected, otherwise false;
 */
@SuppressWarnings("unchecked")
public static ModificationStatus copyValues(final BaseDO src, final BaseDO dest, final String... ignoreFields) {
    if (ClassUtils.isAssignable(src.getClass(), dest.getClass()) == false) {
        throw new RuntimeException("Try to copyValues from different BaseDO classes: this from type "
                + dest.getClass().getName() + " and src from type" + src.getClass().getName() + "!");
    }
    if (src.getId() != null && (ignoreFields == null || ArrayUtils.contains(ignoreFields, "id") == false)) {
        dest.setId(src.getId());
    }
    return copyDeclaredFields(src.getClass(), src, dest, ignoreFields);
}

From source file:org.projectforge.framework.utils.MyBeanComparator.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private int compare(final T o1, final T o2, final String prop, final boolean asc) {
    if (prop == null) {
        // Not comparable.
        return 0;
    }//from  w w  w .  j  a v a  2s.c om
    try {
        final Object value1 = BeanHelper.getNestedProperty(o1, prop);
        final Object value2 = BeanHelper.getNestedProperty(o2, prop);
        if (value1 == null) {
            if (value2 == null)
                return 0;
            else
                return (asc == true) ? -1 : 1;
        }
        if (value2 == null) {
            return (asc == true) ? 1 : -1;
        }
        if (value1 instanceof String && value2 instanceof String) {
            if (checkAnnotation(BeanHelper.getDeclaredAnnotations(o1.getClass(), prop),
                    StringAlphanumericSort.class)
                    && checkAnnotation(BeanHelper.getDeclaredAnnotations(o2.getClass(), prop),
                            StringAlphanumericSort.class)) {
                AlphanumericComparator alphanumericComparator = new AlphanumericComparator(
                        ThreadLocalUserContext.getLocale());
                if (asc) {
                    return alphanumericComparator.compare((String) value2, (String) value1);
                } else {
                    return alphanumericComparator.compare((String) value1, (String) value2);
                }
            } else {
                return StringComparator.getInstance().compare((String) value1, (String) value2, asc);
            }
        }
        if (ClassUtils.isAssignable(value2.getClass(), value1.getClass()) == true) {
            if (asc == true) {
                return ((Comparable) value1).compareTo(value2);
            } else {
                return -((Comparable) value1).compareTo(value2);
            }
        } else {
            final String sval1 = String.valueOf(value1);
            final String sval2 = String.valueOf(value2);
            if (asc == true) {
                return sval1.compareTo(sval2);
            } else {
                return -sval1.compareTo(sval2);
            }
        }
    } catch (final Exception ex) {
        log.error("Exception while comparing values of property '" + prop + "': " + ex.getMessage());
        return 0;
    }
}

From source file:org.projectforge.web.wicket.components.DateTimePanel.java

@Override
protected void convertInput() {
    final Date date = datePanel.getConvertedInput();
    if (date != null) {
        isNull = false;//w  w  w.jav  a  2  s.  co  m
        getDateHolder().setDate(date);
        final Integer hours = hourOfDayDropDownChoice.getConvertedInput();
        final Integer minutes = minuteDropDownChoice.getConvertedInput();
        if (hours != null) {
            dateHolder.setHourOfDay(hours);
        }
        if (minutes != null) {
            dateHolder.setMinute(minutes);
        }
        if (ClassUtils.isAssignable(getType(), Timestamp.class) == true) {
            setConvertedInput(dateHolder.getTimestamp());
        } else {
            setConvertedInput(dateHolder.getDate());
        }
    } else if (settings.required == false) {
        isNull = true;
        setConvertedInput(null);
    }
}

From source file:org.projectforge.web.wicket.components.MaxLengthTextField.java

/**
 * The field length (if defined by Hibernate). The entity is the target class of the PropertyModel and the field name is the expression of
 * the given PropertyModel./*ww  w.j  av a2s.c o m*/
 * @param model If not from type PropertyModel then null is returned.
 * @return
 */
public static Integer getMaxLength(final IModel<String> model) {
    Integer length = null;
    if (ClassUtils.isAssignable(model.getClass(), PropertyModel.class)) {
        final PropertyModel<?> propertyModel = (PropertyModel<?>) model;
        final Object entity = BeanHelper.getFieldValue(propertyModel, ChainingModel.class, "target");
        if (entity == null) {
            log.warn("Oups, can't get private field 'target' of PropertyModel!.");
        } else {
            final Field field = propertyModel.getPropertyField();
            if (field != null) {
                length = HibernateUtils.getPropertyLength(entity.getClass().getName(), field.getName());
            } else {
                log.info("Can't get field '" + propertyModel.getPropertyExpression() + "'.");
            }
        }
    }
    return length;
}

From source file:org.projectforge.web.wicket.components.MinMaxNumberField.java

/**
 * @param id/* ww  w . j  av  a  2 s  .  com*/
 * @param model
 * @see org.apache.wicket.Component#Component(String, IModel)
 */
public MinMaxNumberField(final String id, final IModel<Z> model, final Z minimum, final Z maximum) {
    super(id, model);
    if (minimum.compareTo(maximum) <= 0) {
        add(new RangeValidator<Z>(minimum, maximum));
    } else {
        add(new RangeValidator<Z>(maximum, minimum));

    }
    if (ClassUtils.isAssignable(minimum.getClass(), Integer.class) == true) {
        setMaxLength(Math.max(String.valueOf(minimum).length(), String.valueOf(maximum).length()));
    }
}

From source file:org.projectforge.web.wicket.converter.MyAbstractDateConverter.java

/**
 * Attempts to convert a String to a Date object. Pre-processes the input by invoking the method preProcessInput(), then uses an ordered
 * list of DateFormat objects (supplied by getDateFormats()) to try and parse the String into a Date.
 *//*ww  w  .  j  a  va2 s.c  om*/
@Override
public Date convertToObject(final String value, final Locale locale) {
    if (StringUtils.isBlank(value) == true) {
        return null;
    }
    final String[] formatStrings = getFormatStrings(locale);
    final SimpleDateFormat[] dateFormats = new SimpleDateFormat[formatStrings.length];

    for (int i = 0; i < formatStrings.length; i++) {
        dateFormats[i] = new SimpleDateFormat(formatStrings[i], locale);
        dateFormats[i].setLenient(false);
        if (ClassUtils.isAssignable(targetType, java.sql.Date.class) == false) {
            // Set time zone not for java.sql.Date, because e. g. for Europe/Berlin the date 1970-11-21 will
            // result in 1970-11-20 23:00:00 UTC and therefore 1970-11-20!
            dateFormats[i].setTimeZone(PFUserContext.getTimeZone());
        }
    }

    // Step 1: pre-process the input to make it more palatable
    final String parseable = preProcessInput(value, locale);

    // Step 2: try really hard to parse the input
    Date date = null;
    for (final DateFormat format : dateFormats) {
        try {
            date = format.parse(parseable);
            break;
        } catch (final ParseException pe) { /* Do nothing, we'll get lots of these. */
        }
    }
    // Step 3: If we successfully parsed, return a date, otherwise send back an error
    if (date != null) {
        if (ClassUtils.isAssignable(targetType, java.sql.Date.class) == true) {
            final DayHolder day = new DayHolder(date);
            return day.getSQLDate();
        }
        return date;
    } else {
        log.info("Unparseable date string: " + value);
        throw new ConversionException("validation.error.general"); // Message key will not be used (dummy).
    }
}

From source file:org.projectforge.web.wicket.WicketPageTestBase.java

/**
 * Logs the user in, if not already logged-in. If an user is already logged in then nothing is done. Therefore you must log-out an user
 * before any new login./*from  w  w w.  j  a va  2 s. co  m*/
 * @param username
 * @param password not encrypted.
 */
public void login(final String username, final String password, final boolean checkDefaultPage) {
    // start and render the test page
    tester.startPage(LoginPage.class);
    if (ClassUtils.isAssignable(tester.getLastRenderedPage().getClass(),
            WicketUtils.getDefaultPage()) == true) {
        // Already logged-in.
        return;
    }
    // assert rendered page class
    tester.assertRenderedPage(LoginPage.class);
    final FormTester form = tester.newFormTester("body:form");
    form.setValue(findComponentByLabel(form, "username"), username);
    form.setValue(findComponentByLabel(form, "password"), password);
    form.submit(KEY_LOGINPAGE_BUTTON_LOGIN);
    if (checkDefaultPage == true) {
        tester.assertRenderedPage(WicketUtils.getDefaultPage());
    }
}