Example usage for org.apache.commons.lang3 ClassUtils isPrimitiveOrWrapper

List of usage examples for org.apache.commons.lang3 ClassUtils isPrimitiveOrWrapper

Introduction

In this page you can find the example usage for org.apache.commons.lang3 ClassUtils isPrimitiveOrWrapper.

Prototype

public static boolean isPrimitiveOrWrapper(final Class<?> type) 

Source Link

Document

Returns whether the given type is a primitive or primitive wrapper ( Boolean , Byte , Character , Short , Integer , Long , Double , Float ).

Usage

From source file:com.intuit.karate.ScriptValue.java

public ScriptValue(Object value) {
    this.value = value;
    if (value == null) {
        logger.trace("script value constructed as null");
        type = Type.NULL;//from  ww  w  .j  av a  2  s  .c o m
    } else if (value instanceof DocumentContext) {
        type = Type.JSON;
    } else if (value instanceof Node) {
        type = Type.XML;
    } else if (value instanceof List) {
        type = Type.LIST;
    } else if (value.getClass().getName().equals(BsonDocument.class.getName())) {
        type = Type.BSON_DOCUMENT;
    } else if (value instanceof Map) {
        if (value instanceof ScriptObjectMirror) {
            ScriptObjectMirror som = (ScriptObjectMirror) value;
            if (som.isArray()) {
                type = Type.JS_ARRAY;
            } else if (som.isFunction()) {
                type = Type.JS_FUNCTION;
            } else {
                type = Type.JS_OBJECT;
            }
        } else {
            type = Type.MAP;
        }
    } else if (value instanceof String) {
        type = Type.STRING;
    } else if (value instanceof InputStream) {
        type = Type.INPUT_STREAM;
    } else if (ClassUtils.isPrimitiveOrWrapper(value.getClass())) {
        type = Type.PRIMITIVE;
    } else if (value instanceof FeatureWrapper) {
        type = Type.FEATURE_WRAPPER;
    } else {
        type = Type.UNKNOWN;
        logger.trace("value init unknown type: {} - {}", value.getClass(), value);
    }
}

From source file:com.github.yuxiaobin.mybatis.gm.GeneralSqlSessionFactoryBean.java

private boolean checkValidateClassTypes(Class<?> entityClazz) {
    return !ClassUtils.isPrimitiveOrWrapper(entityClazz) && !entityClazz.isArray() && !entityClazz.isInterface()
            && !Object.class.equals(entityClazz) && checkBeanType(entityClazz);
}

From source file:com.liferay.portal.template.soy.internal.SoyTemplate.java

protected Object getSoyMapValue(Object value) {
    if (value == null) {
        return null;
    }/*from w  w w. j  a v a2s .c  om*/

    Class<?> clazz = value.getClass();

    if (ClassUtils.isPrimitiveOrWrapper(clazz) || value instanceof String) {
        return value;
    }

    if (clazz.isArray()) {
        List<Object> newList = new ArrayList<>();

        for (int i = 0; i < Array.getLength(value); i++) {
            Object object = Array.get(value, i);

            newList.add(getSoyMapValue(object));
        }

        return newList;
    }

    if (value instanceof Iterable) {
        @SuppressWarnings("unchecked")
        Iterable<Object> iterable = (Iterable<Object>) value;

        List<Object> newList = new ArrayList<>();

        for (Object object : iterable) {
            newList.add(getSoyMapValue(object));
        }

        return newList;
    }

    if (value instanceof JSONArray) {
        JSONArray jsonArray = (JSONArray) value;

        List<Object> newList = new ArrayList<>();

        for (int i = 0; i < jsonArray.length(); i++) {
            Object object = jsonArray.opt(i);

            newList.add(getSoyMapValue(object));
        }

        return newList;
    }

    if (value instanceof Map) {
        Map<Object, Object> map = (Map<Object, Object>) value;

        Map<Object, Object> newMap = new TreeMap<>();

        for (Map.Entry<Object, Object> entry : map.entrySet()) {
            Object newKey = getSoyMapValue(entry.getKey());

            if (newKey == null) {
                continue;
            }

            Object newValue = getSoyMapValue(entry.getValue());

            newMap.put(newKey, newValue);
        }

        return newMap;
    }

    if (value instanceof JSONObject) {
        JSONObject jsonObject = (JSONObject) value;

        Map<String, Object> newMap = new TreeMap<>();

        Iterator<String> iterator = jsonObject.keys();

        while (iterator.hasNext()) {
            String key = iterator.next();

            Object object = jsonObject.get(key);

            Object newValue = getSoyMapValue(object);

            newMap.put(key, newValue);
        }

        return newMap;
    }

    if (value instanceof org.json.JSONObject) {
        org.json.JSONObject jsonObject = (org.json.JSONObject) value;

        Map<Object, Object> newMap = new TreeMap<>();

        Iterator<String> iterator = jsonObject.keys();

        while (iterator.hasNext()) {
            String key = iterator.next();

            Object object = jsonObject.opt(key);

            Object newValue = getSoyMapValue(object);

            newMap.put(key, newValue);
        }

        return newMap;
    }

    if (value instanceof SoyRawData) {
        SoyRawData soyRawData = (SoyRawData) value;

        return soyRawData.getValue();
    }

    Map<String, Object> newMap = new TreeMap<>();

    BeanPropertiesUtil.copyProperties(value, newMap);

    if (newMap.isEmpty()) {
        return null;
    }

    return getSoyMapValue(newMap);
}

From source file:com.conversantmedia.mapreduce.tool.DistributedResourceManager.java

private static Object getResourceValue(Field field, String valueString, String originalTypeClassname,
        Path[] distFiles) throws IOException, ClassNotFoundException {

    // First, determine our approach:
    Object value = null;/*from   w w  w . j a va2  s. c o  m*/
    if (field.getType().isAssignableFrom(String.class)) {
        value = valueString;
    } else if (ClassUtils.isPrimitiveOrWrapper(field.getType())) {
        value = ConvertUtils.convert(valueString, field.getType());
    } else {
        Path path = distributedFilePath(valueString, distFiles);

        // This is something on the distributed cache (or illegal)
        if (field.getType() == Path.class) {
            value = path;
        } else if (field.getType() == File.class) {
            value = new File(path.toUri());
        }
        // Deserialize .ser file
        else if (field.getType().isAssignableFrom(Class.forName(originalTypeClassname))) {
            ObjectInputStream in = null;
            try {
                File beanSerFile = new File(path.toUri().getPath());
                FileInputStream fileIn = new FileInputStream(beanSerFile);
                in = new ObjectInputStream(fileIn);
                value = in.readObject();
            } finally {
                IOUtils.closeQuietly(in);
            }
        } else {
            throw new IllegalArgumentException("Cannot locate resource for field [" + field.getName() + "]");
        }
    }

    return value;
}

From source file:com.robertsmieja.test.utils.junit.GenericObjectFactory.java

protected <T> boolean doesClassExistInCache(Class<T> aClass) {
    if (ClassUtils.isPrimitiveOrWrapper(aClass) || String.class.equals(aClass)) {
        return true;
    }//from  w  ww.jav a2  s.  co m
    return additionalClassToValuesMap.containsKey(aClass)
            && additionalClassToDifferentValuesMap.containsKey(aClass);
}

From source file:com.artistech.protobuf.TuioProtoConverter.java

@Override
public Object convertFromProtobuf(final GeneratedMessage obj) {
    Object target;//from w ww  .  j  av a  2s.com

    if (TuioProtos.Blob.class.isAssignableFrom(obj.getClass())) {
        target = new TUIO.TuioBlob();
    } else if (TuioProtos.Time.class.isAssignableFrom(obj.getClass())) {
        target = new TUIO.TuioTime();
    } else if (TuioProtos.Cursor.class.isAssignableFrom(obj.getClass())) {
        target = new TUIO.TuioCursor();
    } else if (TuioProtos.Object.class.isAssignableFrom(obj.getClass())) {
        target = new TUIO.TuioObject();
    } else if (TuioProtos.Point.class.isAssignableFrom(obj.getClass())) {
        target = new TUIO.TuioPoint();
    } else {
        return null;
    }

    try {
        PropertyDescriptor[] targetProps = Introspector.getBeanInfo(target.getClass()).getPropertyDescriptors();

        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] messageProps = beanInfo.getPropertyDescriptors();
        Method[] methods = obj.getClass().getMethods();

        for (PropertyDescriptor targetProp : targetProps) {
            for (PropertyDescriptor messageProp : messageProps) {
                if (targetProp.getName().equals(messageProp.getName())) {
                    Method writeMethod = targetProp.getWriteMethod();
                    Method readMethod = null;
                    for (Method m : methods) {
                        if (writeMethod != null
                                && m.getName().equals(writeMethod.getName().replaceFirst("set", "get"))) {
                            readMethod = m;
                            break;
                        }
                    }
                    try {
                        if (writeMethod != null && readMethod != null && targetProp.getReadMethod() != null) {
                            boolean primitiveOrWrapper = ClassUtils
                                    .isPrimitiveOrWrapper(targetProp.getReadMethod().getReturnType());

                            if (readMethod.getParameterTypes().length > 0) {
                                if (DeepCopy) {
                                    if (!Modifier.isAbstract(targetProp.getPropertyType().getModifiers())) {
                                        //basically, ArrayList
                                        Object newInstance = targetProp.getPropertyType().newInstance();
                                        Method addMethod = newInstance.getClass().getMethod("add",
                                                Object.class);
                                        Method m = obj.getClass().getMethod(readMethod.getName() + "Count");
                                        int size = (int) m.invoke(obj);
                                        for (int ii = 0; ii < size; ii++) {
                                            Object o = readMethod.invoke(obj, ii);
                                            addMethod.invoke(newInstance, o);
                                        }
                                        writeMethod.invoke(target, newInstance);
                                    } else if (Collection.class
                                            .isAssignableFrom(targetProp.getPropertyType())) {
                                        //do something if it is a collection or iterable...
                                    }
                                }
                            } else if (primitiveOrWrapper) {
                                writeMethod.invoke(target, messageProp.getReadMethod().invoke(obj));
                            } else {
                                if (GeneratedMessage.class
                                        .isAssignableFrom(messageProp.getReadMethod().getReturnType())) {

                                    GeneratedMessage invoke = (GeneratedMessage) messageProp.getReadMethod()
                                            .invoke(obj);
                                    Object val = null;
                                    for (ProtoConverter converter : services) {
                                        if (converter.supportsConversion(invoke)) {
                                            val = convertFromProtobuf(invoke);
                                            break;
                                        }
                                    }
                                    if (val != null) {
                                        writeMethod.invoke(target, val);
                                    }
                                }
                                //                                    System.out.println("Prop1 Name!: " + targetProp.getName());
                            }
                        }
                    } catch (NullPointerException ex) {
                        //Logger.getLogger(ZeroMqMouse.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (InstantiationException | NoSuchMethodException | IllegalArgumentException
                            | SecurityException | IllegalAccessException | InvocationTargetException ex) {
                        logger.error(ex);
                    }
                    break;
                }
            }
        }
    } catch (java.beans.IntrospectionException ex) {
        logger.fatal(ex);
    }
    return target;
}

From source file:com.sunchenbin.store.feilong.core.tools.jsonlib.JsonUtil.java

/**
 * ??json format.// w  w w  .  j  av a2 s. co m
 *
 * @param <V>
 *            the value type
 * @param value
 *            the value
 * @param allowClassTypes
 *            the allow class types
 * @return true, if checks if is allow format type
 * @since 1.4.0
 */
private static <V> boolean isAllowFormatType(V value, Class<?>... allowClassTypes) {
    if (null == value) {//null ? format
        return true;
    }
    Class<?> klassClass = value.getClass();
    return ClassUtils.isPrimitiveOrWrapper(klassClass) //
            || String.class == klassClass //
            || ObjectUtil.isArray(value)//XXX  ?? 
            || ClassUtil.isInstance(value, allowClassTypes)//
    ;
}

From source file:com.sunchenbin.store.feilong.core.bean.PropertyUtil.java

/**
 *  <code>Object obj</code>,.
 * /*from ww w  . j av  a2 s  . com*/
 * <h3>??:</h3>
 * 
 * <blockquote>
 * <ol>
 * <li>{@code if ClassUtil.isInstance(findValue, toBeFindedClassType)  findValue}</li>
 * <li>{@code isPrimitiveOrWrapper},{@code CharSequence},{@code Collection},{@code Map}</li>
 * <li> {@link PropertyUtil#describe(Object)} ?</li>
 * </ol>
 * </blockquote>
 *
 * @param <T>
 *            the generic type
 * @param obj
 *            ?
 * @param toBeFindedClassType
 *            the to be finded class type
 * @return a value of the given type found if there is a clear match,or {@code null} if none such value found
 * @see "org.springframework.util.CollectionUtils#findValueOfType(Collection, Class)"
 * @since 1.4.1
 */
@SuppressWarnings("unchecked")
public static <T> T findValueOfType(Object obj, Class<T> toBeFindedClassType) {
    if (Validator.isNullOrEmpty(obj)) {
        return null;
    }

    if (null == toBeFindedClassType) {
        throw new NullPointerException("toBeFindedClassType can't be null/empty!");
    }

    if (ClassUtil.isInstance(obj, toBeFindedClassType)) {
        return (T) obj;
    }

    //command ?  string int,list map
    //,?? findedClassType
    boolean canFindType = !ClassUtils.isPrimitiveOrWrapper(toBeFindedClassType)//
            && !ClassUtil.isInstance(obj, CharSequence.class)//
            && !ClassUtil.isInstance(obj, Collection.class) //
            && !ClassUtil.isInstance(obj, Map.class) //
    ;

    if (!canFindType) {
        return null;
    }

    //******************************************************************************
    Map<String, Object> describe = describe(obj);

    for (Map.Entry<String, Object> entry : describe.entrySet()) {
        String key = entry.getKey();
        Object value = entry.getValue();

        if (null != value && !"class".equals(key)) {
            //?
            T t = findValueOfType(value, toBeFindedClassType);
            if (null != t) {
                return t;
            }
        }
    }
    return null;
}

From source file:com.strider.datadefender.DatabaseAnonymizer.java

/**
 * Calls the anonymization function for the given Column, and returns its
 * anonymized value.// ww w.j  a  v a  2s  . c  o m
 * 
 * @param dbConn
 * @param row
 * @param column
 * @return
 * @throws NoSuchMethodException
 * @throws SecurityException
 * @throws IllegalAccessException
 * @throws IllegalArgumentException
 * @throws InvocationTargetException 
 */
private Object callAnonymizingFunctionWithParameters(final Connection dbConn, final ResultSet row,
        final Column column, final String vendor) throws SQLException, NoSuchMethodException, SecurityException,
        IllegalAccessException, IllegalArgumentException, InvocationTargetException {

    final String function = column.getFunction();
    if (function == null || function.equals("")) {
        log.warn("Function is not defined for column [" + column + "]. Moving to the next column.");
        return "";
    }

    try {
        final String className = Utils.getClassName(function);
        final String methodName = Utils.getMethodName(function);
        final Class<?> clazz = Class.forName(className);

        final CoreFunctions instance = (CoreFunctions) Class.forName(className).newInstance();
        instance.setDatabaseConnection(dbConn);
        instance.setVendor(vendor);

        final List<Parameter> parms = column.getParameters();
        final Map<String, Object> paramValues = new HashMap<>(parms.size());
        final String columnValue = row.getString(column.getName());

        for (final Parameter param : parms) {
            if (param.getValue().equals("@@value@@")) {
                paramValues.put(param.getName(), columnValue);
            } else if (param.getValue().equals("@@row@@") && param.getType().equals("java.sql.ResultSet")) {
                paramValues.put(param.getName(), row);
            } else {
                paramValues.put(param.getName(), param.getTypeValue());
            }
        }

        final List<Object> fnArguments = new ArrayList<>(parms.size());
        final Method[] methods = clazz.getMethods();
        Method selectedMethod = null;

        methodLoop: for (final Method m : methods) {
            if (m.getName().equals(methodName) && m.getReturnType() == String.class) {

                log.debug("  Found method: " + m.getName());
                log.debug("  Match w/: " + paramValues);

                final java.lang.reflect.Parameter[] mParams = m.getParameters();
                fnArguments.clear();
                for (final java.lang.reflect.Parameter par : mParams) {
                    //log.debug("    Name present? " + par.isNamePresent());
                    // Note: requires -parameter compiler flag
                    log.debug("    Real param: " + par.getName());
                    if (!paramValues.containsKey(par.getName())) {
                        continue methodLoop;
                    }

                    final Object value = paramValues.get(par.getName());
                    Class<?> fnParamType = par.getType();
                    final Class<?> confParamType = (value == null) ? fnParamType : value.getClass();

                    if (fnParamType.isPrimitive() && value == null) {
                        continue methodLoop;
                    }
                    if (ClassUtils.isPrimitiveWrapper(confParamType)) {
                        if (!ClassUtils.isPrimitiveOrWrapper(fnParamType)) {
                            continue methodLoop;
                        }
                        fnParamType = ClassUtils.primitiveToWrapper(fnParamType);
                    }
                    if (!fnParamType.equals(confParamType)) {
                        continue methodLoop;
                    }
                    fnArguments.add(value);
                }

                // actual parameters check less than xml defined parameters size, because values could be auto-assigned (like 'values' and 'row' params)
                if (fnArguments.size() != mParams.length || fnArguments.size() < paramValues.size()) {
                    continue;
                }

                selectedMethod = m;
                break;
            }
        }

        if (selectedMethod == null) {
            final StringBuilder s = new StringBuilder("Anonymization method: ");
            s.append(methodName).append(" with parameters matching (");
            String comma = "";
            for (final Parameter p : parms) {
                s.append(comma).append(p.getType()).append(' ').append(p.getName());
                comma = ", ";
            }
            s.append(") was not found in class ").append(className);
            throw new NoSuchMethodException(s.toString());
        }

        log.debug("Anonymizing function: " + methodName + " with parameters: "
                + Arrays.toString(fnArguments.toArray()));
        final Object anonymizedValue = selectedMethod.invoke(instance, fnArguments.toArray());
        if (anonymizedValue == null) {
            return null;
        }
        return anonymizedValue.toString();

    } catch (InstantiationException | ClassNotFoundException ex) {
        log.error(ex.toString());
    }

    return "";
}

From source file:com.feilong.core.bean.PropertyUtil.java

/**
 * command ?  string int,list map./*  w  w w  .ja  va2s .com*/
 * 
 * <p>
 * ,?? findedClassType
 * </p>
 * 
 * @param obj
 *            the obj
 * @return true, if checks if is can find type
 * @since 1.6.3
 */
private static boolean isDonotSupportFindType(Object obj) {
    //command ?  string int,list map
    //,?? findedClassType
    return ClassUtils.isPrimitiveOrWrapper(obj.getClass())//
            || ClassUtil.isInstanceAnyClass(obj, CharSequence.class, Collection.class, Map.class);
}