Java Code Examples for org.apache.commons.lang.ClassUtils#isAssignable()

The following examples show how to use org.apache.commons.lang.ClassUtils#isAssignable() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MCRCommand.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
public MCRCommand(Method cmd) {
    className = cmd.getDeclaringClass().getName();
    methodName = cmd.getName();
    parameterTypes = cmd.getParameterTypes();
    org.mycore.frontend.cli.annotation.MCRCommand cmdAnnotation = cmd
        .getAnnotation(org.mycore.frontend.cli.annotation.MCRCommand.class);
    help = cmdAnnotation.help();
    messageFormat = new MessageFormat(cmdAnnotation.syntax(), Locale.ROOT);
    setMethod(cmd);

    for (int i = 0; i < parameterTypes.length; i++) {
        Class<?> paramtype = parameterTypes[i];
        if (ClassUtils.isAssignable(paramtype, Integer.class, true)
            || ClassUtils.isAssignable(paramtype, Long.class, true)) {
            messageFormat.setFormat(i, NumberFormat.getIntegerInstance(Locale.ROOT));
        } else if (!String.class.isAssignableFrom(paramtype)) {
            unsupportedArgException(className + "." + methodName, paramtype.getName());
        }
    }

    int pos = cmdAnnotation.syntax().indexOf("{");
    suffix = pos == -1 ? cmdAnnotation.syntax() : cmdAnnotation.syntax().substring(0, pos);
}
 
Example 2
Source File: RichTable.java    From rice with Educational Community License v2.0 6 votes vote down vote up
private String getSortType(Class<?> dataTypeClass) {
    String sortType = UifConstants.TableToolsValues.STRING;
    if (ClassUtils.isAssignable(dataTypeClass, KualiPercent.class)) {
        sortType = UifConstants.TableToolsValues.PERCENT;
    } else if (ClassUtils.isAssignable(dataTypeClass, KualiInteger.class) || ClassUtils.isAssignable(dataTypeClass,
            KualiDecimal.class)) {
        sortType = UifConstants.TableToolsValues.CURRENCY;
    } else if (ClassUtils.isAssignable(dataTypeClass, Timestamp.class)) {
        sortType = "date";
    } else if (ClassUtils.isAssignable(dataTypeClass, java.sql.Date.class) || ClassUtils.isAssignable(dataTypeClass,
            java.util.Date.class)) {
        sortType = UifConstants.TableToolsValues.DATE;
    } else if (ClassUtils.isAssignable(dataTypeClass, Number.class)) {
        sortType = UifConstants.TableToolsValues.NUMERIC;
    }
    return sortType;
}
 
Example 3
Source File: DateTimePanel.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void convertInput()
{
  final Date date = datePanel.getConvertedInput();
  if (date != null) {
    isNull = false;
    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);
  }
}
 
Example 4
Source File: MaxLengthTextField.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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.
 * @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;
}
 
Example 5
Source File: AbstractBaseDO.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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.
 * @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);
}
 
Example 6
Source File: WicketPageTestBase.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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.
 * @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());
  }
}
 
Example 7
Source File: StateHelper.java    From rebuild with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 加载状态枚举类
 *
 * @param stateClass
 * @return
 * @throws IllegalArgumentException
 */
public static Class<?> getSatetClass(String stateClass) throws IllegalArgumentException {
    Assert.notNull(stateClass, "[stateClass] not be null");

    Class<?> stateEnum;
    try {
        stateEnum = ClassUtils.getClass(stateClass);
        if (stateEnum.isEnum() && ClassUtils.isAssignable(stateEnum, StateSpec.class)) {
            return stateEnum;
        }
    } catch (ClassNotFoundException ignored) {
        throw new IllegalArgumentException("No class of state found: " + stateClass);
    }
    throw new IllegalArgumentException("Bad class of state found: " + stateEnum);
}
 
Example 8
Source File: MemberUtils.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Gets the number of steps required needed to turn the source class into
 * the destination class. This represents the number of steps in the object
 * hierarchy graph.
 * @param srcClass The source class
 * @param destClass The destination class
 * @return The cost of transforming an object
 */
private static float getObjectTransformationCost(Class srcClass, Class destClass) {
    if (destClass.isPrimitive()) {
        return getPrimitivePromotionCost(srcClass, destClass);
    }
    float cost = 0.0f;
    while (srcClass != null && !destClass.equals(srcClass)) {
        if (destClass.isInterface() && ClassUtils.isAssignable(srcClass, destClass)) {
            // slight penalty for interface match.
            // we still want an exact match to override an interface match,
            // but
            // an interface match should override anything where we have to
            // get a superclass.
            cost += 0.25f;
            break;
        }
        cost++;
        srcClass = srcClass.getSuperclass();
    }
    /*
     * If the destination class is null, we've travelled all the way up to
     * an Object match. We'll penalize this by adding 1.5 to the cost.
     */
    if (srcClass == null) {
        cost += 1.5f;
    }
    return cost;
}
 
Example 9
Source File: MethodUtils.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>Find an accessible method that matches the given name and has compatible parameters.
 * Compatible parameters mean that every method parameter is assignable from 
 * the given parameters.
 * In other words, it finds a method with the given name 
 * that will take the parameters given.<p>
 *
 * <p>This method is used by 
 * {@link 
 * #invokeMethod(Object object, String methodName, Object[] args, Class[] parameterTypes)}.
 *
 * <p>This method can match primitive parameter by passing in wrapper classes.
 * For example, a <code>Boolean</code> will match a primitive <code>boolean</code>
 * parameter.
 *
 * @param cls find method in this class
 * @param methodName find method with this name
 * @param parameterTypes find method with most compatible parameters 
 * @return The accessible method
 */
public static Method getMatchingAccessibleMethod(Class cls,
        String methodName, Class[] parameterTypes) {
    try {
        Method method = cls.getMethod(methodName, parameterTypes);
        MemberUtils.setAccessibleWorkaround(method);
        return method;
    } catch (NoSuchMethodException e) { /* SWALLOW */
    }
    // search through all methods
    Method bestMatch = null;
    Method[] methods = cls.getMethods();
    for (int i = 0, size = methods.length; i < size; i++) {
        if (methods[i].getName().equals(methodName)) {
            // compare parameters
            if (ClassUtils.isAssignable(parameterTypes, methods[i]
                    .getParameterTypes(), true)) {
                // get accessible version of method
                Method accessibleMethod = getAccessibleMethod(methods[i]);
                if (accessibleMethod != null) {
                    if (bestMatch == null
                            || MemberUtils.compareParameterTypes(
                                    accessibleMethod.getParameterTypes(),
                                    bestMatch.getParameterTypes(),
                                    parameterTypes) < 0) {
                        bestMatch = accessibleMethod;
                    }
                }
            }
        }
    }
    if (bestMatch != null) {
        MemberUtils.setAccessibleWorkaround(bestMatch);
    }
    return bestMatch;
}
 
Example 10
Source File: ValueNormalizationUtil.java    From moneta with Apache License 2.0 5 votes vote down vote up
/**
 * Will convert a String into the specified property type.  Integer, Long, Boolean, and String supported.
 * @param targetType
 * @param value
 * @return convertedValue
 */
public static Object convertString(Class targetType, String value) {
	Validate.notNull(targetType, "Null targetType not allowed.");
	if (value == null) {
		return value;
	}
	if (ClassUtils.isAssignable(targetType, String.class)) {
		return value;
	}
	if (ClassUtils.isAssignable(targetType, Integer.class)) {
		return Integer.valueOf(value);
	}
	if (ClassUtils.isAssignable(targetType, int.class)) {
		return Integer.valueOf(value);
	}
	if (ClassUtils.isAssignable(targetType, Long.class)) {
		return Long.valueOf(value);
	}
	if (ClassUtils.isAssignable(targetType, long.class)) {
		return Long.valueOf(value);
	}
	Boolean bValue = BooleanUtils.toBooleanObject(value);
	if (bValue != null) {
		return bValue;
	}
	
	throw new MonetaException("Property type not supported")
		.addContextValue("targetType", targetType.getName());
}
 
Example 11
Source File: MinMaxNumberField.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param id
 * @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()));
  }
}
 
Example 12
Source File: MyAbstractDateConverter.java    From projectforge-webapp with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 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.
 */
@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).
  }
}
 
Example 13
Source File: MyBeanComparator.java    From projectforge-webapp with GNU General Public License v3.0 4 votes vote down vote up
@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;
  }
  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) {
      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;
  }
}