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:com.ginema.api.enricher.SensitiveDataEnricher.java

/**
 * Enriches the object tree. In case of the collection falls back to each element of the
 * collection/* w w w .jav  a 2 s  .  com*/
 * 
 * @param o
 * @param holder
 * @throws IllegalAccessException
 */
@SuppressWarnings("rawtypes")
private void enrichObjectTree(Object o, SensitiveDataHolder holder) throws Exception {
    for (Field f : o.getClass().getDeclaredFields()) {
        if (!ReflectionUtils.isPrimitive(f)) {
            Object value = PropertyDescriptorHolder.getGetterMethod(o.getClass(), f.getName()).invoke(o);
            if (ClassUtils.isAssignable(f.getType(), SensitiveDataField.class)) {
                populateHolderMapByType(o, f, (SensitiveDataField<?>) value, holder);
            }
            checkAndEnrichObject(holder, value);
            if (value != null && ReflectionUtils.isACollection(value)) {
                for (Object element : (java.util.Collection) value) {
                    checkAndEnrichObject(holder, element);
                }

            }
        }
    }

}

From source file:gda.factory.corba.util.ImplFactory.java

protected void makeObjectsAvailable() throws FactoryException {
    POA poa = netService.getPOA();

    //TODO All errors should lead to throwing a FactoryException - check error then lead to system exit
    org.omg.PortableServer.Servant servant;

    Runtime.getRuntime().addShutdownHook(uk.ac.gda.util.ThreadManager.getThread(new Runnable() {
        @Override/*from   w ww . j  a  va  2 s  .co  m*/
        public void run() {
            shutdown();
        }
    }, getNamespace() + " ImplFactory shutdown"));

    List<Findable> findables = getFindablesToMakeAvailable();
    for (Findable findable : findables) {
        String name = findable.getName();
        if (findable instanceof Localizable && !((Localizable) findable).isLocal()) {

            if (excludedObjects != null && excludedObjects.contains(name)) {
                logger.info(String.format("Not exporting %s - it has been excluded", name));
                continue;
            }

            Class<?> type = findable.getClass();
            if (RbacUtils.objectIsCglibProxy(findable)) {
                // Object has been proxied. Get its original type
                type = type.getSuperclass();
            }

            String implName = CorbaUtils.getImplementationClassName(type);
            String adapterClassName = CorbaUtils.getAdapterClassName(type);

            org.omg.CORBA.Object obj = null;
            try {
                Class<?> classDef = Class.forName(implName);
                Constructor<?>[] ctors = classDef.getDeclaredConstructors();
                Constructor<?> ctor = ctors[0];

                final Object[] args = new Object[] { findable, poa };
                if (!ClassUtils.isAssignable(ClassUtils.toClass(args), ctor.getParameterTypes())) {
                    logger.warn("Class " + implName + " is unsuitable for " + name
                            + ", so it will be a local object");
                }

                else {
                    servant = (org.omg.PortableServer.Servant) ctor.newInstance(args);
                    obj = poa.servant_to_reference(servant);
                }
            } catch (ClassNotFoundException ex) {
                logger.warn("Cannot find class " + implName + ": " + name + " will be a local object");
            } catch (Exception e) {
                logger.error(
                        "Could not instantiate class " + implName + ": " + name + " will be a local object", e);
            }

            String fullName = getNamespace() + NetService.OBJECT_DELIMITER + name;
            if (obj != null) {
                // bind throws a factory exception which is not caught
                // but passed back to the caller.
                store.put(fullName, new CorbaBoundObject(fullName, adapterClassName, obj));
                netService.bind(fullName, adapterClassName, obj);
                logger.debug("ImplFactory created Corba object for " + fullName);
            } else {
                logger.warn("No CORBA object created for " + fullName);
            }
        }

        else {
            logger.debug(
                    String.format("Not exporting %s - it is local (or does not implement Localizable)", name));
        }
    }
}

From source file:com.yahoo.flowetl.core.pipe.result.BackedPipeResult.java

@Override
public <T> boolean isParamCastable(String name, Class<T> kls) {
    Class<?> pKls = getParamClass(name);
    if (pKls == null) {
        return false;
    }//from w  ww .  j  a v  a  2s .  c om
    if (ClassUtils.isAssignable(pKls, kls) == false) {
        return false;
    }
    return true;
}

From source file:com.ginema.api.enricher.SensitiveDataExtractor.java

private static void populateHolderMapByType(SensitiveDataHolder holder, SensitiveDataField<?> value) {
    if (value == null || value.getValue() == null)
        return;//  w  w  w  .  j  a v a 2s.c o m
    @SuppressWarnings("rawtypes")
    Class clazz = value.getValue().getClass();
    String id = value.getIdentifier().getId();
    String name = value.getName();
    if (ClassUtils.isAssignable(clazz, Date.class)) {

        populate(holder, holder.getDates(), SensitiveDataHolder::setDates, id,
                new DateEntry(name, ((Date) value.getValue()).getTime()));
    }
    if (ClassUtils.isAssignable(clazz, String.class)) {
        populate(holder, holder.getStrings(), SensitiveDataHolder::setStrings, id,
                new StringEntry(name, (String) value.getValue()));
        return;
    }
    if (ClassUtils.isAssignable(clazz, Long.class)) {
        populate(holder, holder.getLongs(), SensitiveDataHolder::setLongs, id,
                new LongEntry(name, (Long) value.getValue()));
        return;
    }
    if (ClassUtils.isAssignable(clazz, Double.class)) {
        populate(holder, holder.getDoubles(), SensitiveDataHolder::setDoubles, id,
                new DoubleEntry(name, (Double) value.getValue()));
        return;
    }
    if (ClassUtils.isAssignable(clazz, Boolean.class)) {
        populate(holder, holder.getBooleans(), SensitiveDataHolder::setBooleans, id,
                new BooleanEntry(name, (Boolean) value.getValue()));
        return;
    }
    if (ClassUtils.isAssignable(clazz, byte[].class)) {
        BytesEntry bytesEntry = new BytesEntry(name, ByteBuffer.wrap((byte[]) value.getValue()));
        populate(holder, holder.getBytes(), SensitiveDataHolder::setBytes, id, bytesEntry);
        return;

    }

}

From source file:com.google.code.simplestuff.bean.SimpleBean.java

/**
 * Compare two bean basing the comparison only on the {@link BusinessField}
 * annotated fields.//  ww w  .  j a  v  a 2s. co  m
 * 
 * @param firstBean First bean to compare.
 * @param secondBean Second bean to compare.
 * @return The equals result.
 * @throws IllegalArgumentException If one of the beans compared is not an
 *         instance of a {@link BusinessObject} annotated class.
 */
public static boolean equals(Object firstBean, Object secondBean) {

    // null + !null = false
    // null + null = true
    if ((firstBean == null) || (secondBean == null)) {
        if ((firstBean == null) && (secondBean == null)) {
            return true;
        } else {
            return false;
        }
    }

    final BusinessObjectDescriptor firstBusinessObjectInfo = BusinessObjectContext
            .getBusinessObjectDescriptor(firstBean.getClass());
    final BusinessObjectDescriptor secondBusinessObjectInfo = BusinessObjectContext
            .getBusinessObjectDescriptor(secondBean.getClass());

    // We don't need here a not null check since by contract the
    // getBusinessObjectDescriptor method always returns an abject.

    // All this conditions are to support the case in which
    // SimpleBean.equals is used in not Business Object. Than the rules are:
    // !BO.equals(!BO) = The objects are equals if one of them is assignable
    // to the other (the or is used for the respect the symmetric rule)
    // !BO.eqauls(BO) = The equals of the !BO is used.
    // BO.equals(!BO) = The equals of the !BO is used.
    if (firstBusinessObjectInfo.getNearestBusinessObjectClass() == null) {
        if (secondBusinessObjectInfo.getNearestBusinessObjectClass() == null) {
            return firstBean.getClass().isAssignableFrom(secondBean.getClass())
                    || secondBean.getClass().isAssignableFrom(firstBean.getClass());
        } else {
            return firstBean.equals(secondBean);
        }
    } else if (secondBusinessObjectInfo.getNearestBusinessObjectClass() == null) {
        return secondBean.equals(firstBean);
    }

    // TODO: Revise this code in order to make it more readable...
    // If one of the two bean has the class with Business relevance then
    // we need to compare the lowest hierarchical annotated classes of
    // the two beans.
    if ((firstBusinessObjectInfo.isClassToBeConsideredInComparison()
            || secondBusinessObjectInfo.isClassToBeConsideredInComparison())
            && (!firstBusinessObjectInfo.getNearestBusinessObjectClass()
                    .equals(secondBusinessObjectInfo.getNearestBusinessObjectClass()))) {
        // If the comparison fails than we can already return false.
        return false;
    }

    // Then we continue with the annotated fields, first checking
    // if the two objects contain the same annotated fields. A paranoid
    // comparison (both sides) is done only if the two objects are not on
    // the same class in order to handle tricky cases.
    final boolean performParanoidComparison = false;
    if (!compareAnnotatedFieldsByName(firstBusinessObjectInfo.getAnnotatedFields(),
            secondBusinessObjectInfo.getAnnotatedFields(), performParanoidComparison)) {
        // If the comparison fails than we can already return false.
        return false;
    }

    // Then we continue with the values of the annotated fields.
    Collection<Field> firstBeanAnnotatedFields = firstBusinessObjectInfo.getAnnotatedFields();

    for (Field field : firstBeanAnnotatedFields) {

        final BusinessField fieldAnnotation = field.getAnnotation(BusinessField.class);
        // Since the cycle is on the annotated Field we are sure that
        // fieldAnnotation will always be not null.
        if (fieldAnnotation.includeInEquals()) {

            Object firstBeanFieldValue = null;
            Object secondBeanFieldValue = null;

            try {
                firstBeanFieldValue = PropertyUtils.getProperty(firstBean, field.getName());
                // Also in this case, since before of the cycle we
                // compare the annotated fields, we can be sure that the
                // field exists.
                secondBeanFieldValue = PropertyUtils.getProperty(secondBean, field.getName());

                // If there were problems (like when we compare
                // different Business Object with different Business
                // Fields), then we return false.
            } catch (IllegalAccessException e) {
                if (log.isDebugEnabled()) {
                    log.debug("IllegalAccessException exception when comparing class "
                            + firstBean.getClass().toString() + " with class"
                            + secondBean.getClass().toString(), e);
                }
                return false;
            } catch (InvocationTargetException e) {
                if (log.isDebugEnabled()) {
                    log.debug("InvocationTargetException exceptionwhen comparing class "
                            + firstBean.getClass().toString() + " with class"
                            + secondBean.getClass().toString(), e);
                }
                return false;
            } catch (NoSuchMethodException e) {
                if (log.isDebugEnabled()) {
                    log.debug("NoSuchMethodException exception when comparing class "
                            + firstBean.getClass().toString() + " with class"
                            + secondBean.getClass().toString(), e);
                }
                return false;
            }

            // Some date implementations give not exact
            // comparison...
            if ((ClassUtils.isAssignable(field.getType(), Date.class))
                    || (ClassUtils.isAssignable(field.getType(), Calendar.class))) {

                if (firstBeanFieldValue != null) {
                    firstBeanFieldValue = DateUtils.round(firstBeanFieldValue, Calendar.MILLISECOND);
                }

                if (secondBeanFieldValue != null) {
                    secondBeanFieldValue = DateUtils.round(secondBeanFieldValue, Calendar.MILLISECOND);
                }

            }

            // We use always EqualsBuilder since we can get also
            // primitive arrays and they need ot be internally
            // compared.
            EqualsBuilder equalsBuilder = new EqualsBuilder();
            equalsBuilder.append(firstBeanFieldValue, secondBeanFieldValue);
            if (!equalsBuilder.isEquals()) {
                return false;
            } else {

                // If we are here the bean are both not null and
                // equals or both null (then equals)... the cycle
                // can
                // continue...
                continue;
            }

        }
    }

    // If we finally arrive here, then all the comparison were
    // successful and the two beans are equals.
    return true;

}

From source file:at.ac.tuwien.infosys.jcloudscale.utility.ReflectionUtil.java

/**
 * Returns a {@link Method} with a certain name and parameter types declared in the given class or any subclass
 * (except {@link Object}).//from   w w  w.jav  a2s .  c o m
 * <p/>
 * If no parameter types are specified i.e., {@code paramTypes} is {@code null} the parameter types are ignored
 * for signature comparison.<br/>
 * If a parameter type is not known i.e., it is {@code null}, all declared methods are checked whether their
 * parameter types conform to the known parameter types i.e., if every known type is assignable to the parameter
 * type of the method and if exactly one was found, it is returned.<br/>
 * Otherwise a {@link NoSuchMethodException} is thrown indicating that no or several methods were found.
 * 
 * @param type the class
 * @param methodName the name of the method to find
 * @param clazzes the full-qualified class names of the parameters
 * @return the accessible method resolved
 * @throws ClassNotFoundException if a class cannot be located by the specified class loader
 */
public static Method findMethod(final Class<?> type, String methodName, Class<?>... clazzes)
        throws ClassNotFoundException {
    Method method = null;

    // If all parameter types are known, find the method that exactly matches the signature
    if (clazzes != null && !ArrayUtils.contains(clazzes, null)) {
        for (Class<?> clazz = type; clazz != Object.class; clazz = clazz.getSuperclass()) {
            try {
                method = type.getDeclaredMethod(methodName, clazzes);
                break;
            } catch (NoSuchMethodException e) {
                // Ignore
            }
        }
    }

    // If no method was found, find all possible candidates
    if (method == null) {
        List<Method> candidates = new ArrayList<>();
        for (Class<?> clazz = type; clazz != null; clazz = clazz.getSuperclass()) {
            for (Method declaredMethod : clazz.getDeclaredMethods()) {
                if (declaredMethod.getName().equals(methodName) && (clazzes == null
                        || ClassUtils.isAssignable(clazzes, declaredMethod.getParameterTypes()))) {

                    // Check if there is already a overridden method with the same signature
                    for (Method candidate : candidates) {
                        if (candidate.getName().equals(declaredMethod.getName())) {
                            /**
                             * If there is at least one parameters in the method of the super type, which is a
                             * sub type of the corresponding parameter of the sub type, remove the method declared
                             * in the sub type.
                             */
                            if (!Arrays.equals(declaredMethod.getParameterTypes(),
                                    candidate.getParameterTypes())
                                    && ClassUtils.isAssignable(declaredMethod.getParameterTypes(),
                                            candidate.getParameterTypes())) {
                                candidates.remove(candidate);
                            } else {
                                declaredMethod = null;
                            }
                            break;
                        }
                    }

                    // If the method has a different signature matching the given types, add it to the candidates
                    if (declaredMethod != null) {
                        candidates.add(declaredMethod);
                    }
                }
            }
        }

        if (candidates.size() != 1) {
            throw new JCloudScaleException(
                    String.format("Cannot find distinct method '%s.%s()' with parameter types %s", type,
                            methodName, Arrays.toString(clazzes)));
        }
        method = candidates.get(0);
    }

    //do we really need this dependency?
    //ReflectionUtils.makeAccessible(method);
    if (method != null && !method.isAccessible())
        method.setAccessible(true);

    return method;

}

From source file:de.hybris.platform.cronjob.jalo.TriggerableJobTest.java

private Job createTwoSecondJob(final String jobName) throws Exception {
    final Map<String, Object> jobParams = new HashMap<String, Object>();
    jobParams.put(Job.CODE, jobName + new Date());
    final ComposedType job_ct = prepareComposedTypeIfNeeded(jobName, jobParams);
    final Job newJobInstance = (Job) job_ct.newInstance(jobParams);
    Assert.assertTrue("Created job instance should be triggerable or service layer job at least ", //
            ClassUtils.isAssignable(UnPerformableJob.class, TriggerableJob.class) //
                    || //
                    ClassUtils.isAssignable(UnPerformableJob.class, ServicelayerJob.class)//
    );//  ww  w. j a  v  a  2s.  com
    return newJobInstance;
}

From source file:com.swordlord.gozer.datatypeformat.DataTypeHelper.java

/**
 * @param dataTypeClass/*from  w  w w  . j  a v a 2  s.co  m*/
 * @param untypedValue
 * @return
 */
public static Object toDataType(Class<?> dataTypeClass, Object untypedValue) {
    if ((dataTypeClass == null) || (untypedValue == null)
            || ClassUtils.isAssignable(untypedValue.getClass(), dataTypeClass)) {
        if (Date.class == dataTypeClass) {
            return DateUtils.truncate(untypedValue, Calendar.DATE);
        }

        return untypedValue;
    }

    Object v = null;

    String strUntypedValue = null;
    boolean isStringUntypedValue = untypedValue instanceof String;

    Number numUntypedValue = null;
    boolean isNumberUntypedValue = untypedValue instanceof Number;

    if (isStringUntypedValue) {
        strUntypedValue = (String) untypedValue;
    }

    if (isNumberUntypedValue) {
        numUntypedValue = (Number) untypedValue;
    }

    if (dataTypeClass == boolean.class || dataTypeClass == Boolean.class) {
        if (isNumberUntypedValue) {
            v = BooleanUtils.toBooleanObject(numUntypedValue.intValue());
        } else if (isStringUntypedValue) {
            v = BooleanUtils.toBooleanObject(strUntypedValue);
        }
    } else if (dataTypeClass == Integer.class) {
        if (isNumberUntypedValue) {
            v = new Integer(numUntypedValue.intValue());
        } else if (isStringUntypedValue) {
            v = NumberUtils.createInteger(strUntypedValue);
        }
    } else if (dataTypeClass == Double.class) {
        if (isNumberUntypedValue) {
            v = new Double(numUntypedValue.doubleValue());
        } else if (isStringUntypedValue) {
            v = NumberUtils.createDouble(strUntypedValue);
        }
    } else if (dataTypeClass == Date.class) {
        if (isNumberUntypedValue) {
            v = DateUtils.truncate(new Date(numUntypedValue.longValue()), Calendar.DATE);
        }
    } else {
        v = ObjectUtils.toString(untypedValue);
    }

    return v;
}

From source file:com.google.code.simplestuff.bean.SimpleBean.java

/**
 * //w  w  w . ja v  a2 s. com
 * Returns the hashCode basing considering only the {@link BusinessField}
 * annotated fields.
 * 
 * @param bean The bean.
 * @return The hashCode result.
 * @throws IllegalArgumentException If the bean is not a Business Object.
 */
public static int hashCode(Object bean) {

    if (bean == null) {
        throw new IllegalArgumentException("The bean passed is null!!!");
    }

    BusinessObjectDescriptor businessObjectInfo = BusinessObjectContext
            .getBusinessObjectDescriptor(bean.getClass());

    // We don't need here a not null check since by contract the
    // getBusinessObjectDescriptor method always returns an abject.
    if (businessObjectInfo.getNearestBusinessObjectClass() == null) {
        return bean.hashCode();
        // throw new IllegalArgumentException(
        // "The bean passed is not annotated in the hierarchy as Business Object!!!");
    }

    Collection<Field> annotatedField = businessObjectInfo.getAnnotatedFields();

    HashCodeBuilder builder = new HashCodeBuilder();
    for (Field field : annotatedField) {
        field.setAccessible(true);
        final BusinessField fieldAnnotation = field.getAnnotation(BusinessField.class);
        if ((fieldAnnotation != null) && (fieldAnnotation.includeInHashCode())) {
            try {
                // Vincenzo Vitale(vita) May 23, 2007 2:39:26 PM: some
                // date implementations give not equals values...
                if ((ClassUtils.isAssignable(field.getType(), Date.class))
                        || (ClassUtils.isAssignable(field.getType(), Calendar.class))) {
                    Object fieldValue = PropertyUtils.getProperty(bean, field.getName());
                    if (fieldValue != null) {
                        builder.append(DateUtils.round(fieldValue, Calendar.MILLISECOND));
                    }

                } else {
                    builder.append(PropertyUtils.getProperty(bean, field.getName()));
                }
            } catch (IllegalAccessException e) {
                if (log.isDebugEnabled()) {
                    log.debug("IllegalAccessException exception when calculating the hashcode of class"
                            + bean.getClass().toString(), e);
                }
            } catch (InvocationTargetException e) {
                if (log.isDebugEnabled()) {
                    log.debug("InvocationTargetException exception when calculating the hashcode of class"
                            + bean.getClass().toString(), e);
                }
            } catch (NoSuchMethodException e) {
                if (log.isDebugEnabled()) {
                    log.debug("NoSuchMethodException exception when calculating the hashcode of class"
                            + bean.getClass().toString(), e);
                }
            }
        }
    }

    return builder.toHashCode();

}

From source file:de.hybris.platform.cronjob.jalo.CronJobTest.java

@Test
/*//from w  w w .j  a  va2 s.  c o  m
 * PLA-8368
 */
public void testTriggerCreationForTriggerableJobs() throws Exception {

    final TypeManager manager = TypeManager.getInstance();
    final ComposedType jobType = manager.createComposedType(manager.getComposedType(Job.class),
            "UnperformableJobType");
    jobType.setJaloClass(UnPerformableJob.class);

    final UnPerformableJob unperformable = (UnPerformableJob) jobType
            .newInstance(Collections.singletonMap(Job.CODE, "MyUnperformableJob"));

    if (ClassUtils.isAssignable(UnPerformableJob.class, TriggerableJob.class)
            || ClassUtils.isAssignable(UnPerformableJob.class, ServicelayerJob.class)) {
        final Map values = new HashMap();
        values.put("job", unperformable.getPK());

        // initially there should be no triggers for this triggerable job instance
        assertEquals(Collections.emptyList(), unperformable.getTriggers());
        // initially there should be no assigned cronjob for this triggerable job instance
        assertEquals(Collections.emptyList(), unperformable.getCronJobs());

        final Trigger trigger = createTriggerForJobNow(unperformable);
        trigger.activate();

        Thread.sleep(2000);

        final Collection<CronJob> cronJobs = unperformable.getCronJobs();
        assertEquals(1, cronJobs.size());
        final CronJob newlyCreateCronjob = cronJobs.iterator().next();

        final List<Trigger> cronjobTriggers = newlyCreateCronjob.getTriggers();
        assertEquals(1, cronjobTriggers.size());
    }
}