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

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

Introduction

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

Prototype

public static Class<?> wrapperToPrimitive(Class<?> cls) 

Source Link

Document

Converts the specified wrapper class to its corresponding primitive class.

This method is the counter part of primitiveToWrapper().

Usage

From source file:com.ginema.api.reflection.ReflectionUtils.java

public static boolean isPrimitive(Object c) {
    return c.getClass().isPrimitive() || ClassUtils.wrapperToPrimitive(c.getClass()) != null;

}

From source file:net.datenwerke.transloader.primitive.WrapperConverter.java

private static char getTypeCode(Object wrapper) {
    Class primitiveType = ClassUtils.wrapperToPrimitive(wrapper.getClass());
    ObjectStreamField typeCodeProvider = new ObjectStreamField(IRRELEVANT, primitiveType);
    return typeCodeProvider.getTypeCode();
}

From source file:com.adobe.acs.commons.util.TypeUtil.java

/**
 * Gets a custom string representation based on the parameter (0 argument) methodName.
 *
 * @param obj/*from www . jav  a2 s.c om*/
 * @param klass
 * @param methodName
 * @return
 */
public static String toString(final Object obj, final Class<?> klass, String methodName)
        throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
    if (StringUtils.isBlank(methodName)) {
        methodName = "toString";
    }

    boolean isPrimitiveOrWrapped = obj.getClass().isPrimitive()
            || ClassUtils.wrapperToPrimitive(obj.getClass()) != null;

    if (isPrimitiveOrWrapped) {
        return String.valueOf(obj);
    } else if (Date.class.equals(klass)) {
        return ((Date) obj).toString();
    } else if (Calendar.class.equals(klass)) {
        return ((Calendar) obj).getTime().toString();
    } else if (isArray(obj)) {
        return toStringFromArray(obj);
    } else {
        Method method = klass.getMethod(methodName);
        return (String) method.invoke(obj);
    }
}

From source file:com.adobe.acs.commons.util.TypeUtil.java

/**
 * Attempt to create a string representation of an object.
 *
 * @param obj the object to represent as a string
 * @return the string representation of the object
 *//*from  w ww. j  ava2 s .co  m*/
public static String toString(final Object obj)
        throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {

    if (obj == null) {
        return "null";
    }

    boolean isPrimitiveOrWrapped = obj.getClass().isPrimitive()
            || ClassUtils.wrapperToPrimitive(obj.getClass()) != null;

    if (isPrimitiveOrWrapped) {
        return String.valueOf(obj);
    } else if (obj instanceof Date) {
        return ((Date) obj).toString();
    } else if (obj instanceof Calendar) {
        return ((Calendar) obj).getTime().toString();
    } else if (isArray(obj)) {
        return toStringFromArray(obj);
    } else {
        Method method = obj.getClass().getMethod("toString");
        return (String) method.invoke(obj);
    }
}

From source file:ch.algotrader.esper.aggregation.GenericTALibFunctionFactory.java

@Override
public void validate(AggregationValidationContext validationContext) {

    this.core = new CoreAnnotated();

    Class<?>[] paramTypes = validationContext.getParameterTypes();

    // get the functionname
    String talibFunctionName = (String) getConstant(validationContext, 0, String.class);

    // get the method by iterating over all core-methods
    // we have to do it this way, since we don't have the exact parameters
    for (Method method : this.core.getClass().getDeclaredMethods()) {
        if (method.getName().equals(talibFunctionName)) {
            this.function = method;
            break;
        }/* ww  w .  ja  va 2s  .com*/
    }

    // check that we have a function now
    if (this.function == null) {
        throw new IllegalArgumentException("function " + talibFunctionName + " was not found");
    }

    // get the parameters
    int paramCounter = 1;
    Map<String, Class<?>> outputParamTypes = new HashMap<>();
    for (Annotation[] annotations : this.function.getParameterAnnotations()) {
        for (Annotation annotation : annotations) {

            // got through all inputParameters and count them
            if (annotation instanceof InputParameterInfo) {
                InputParameterInfo inputParameterInfo = (InputParameterInfo) annotation;
                if (inputParameterInfo.type().equals(InputParameterType.TA_Input_Real)) {
                    if (paramTypes[paramCounter].equals(double.class)
                            || paramTypes[paramCounter].equals(Double.class)) {
                        this.inputParamCount++;
                        paramCounter++;
                    } else {
                        throw new IllegalArgumentException(
                                "param number " + paramCounter + " must be of type double");
                    }
                } else if (inputParameterInfo.type().equals(InputParameterType.TA_Input_Integer)) {
                    if (paramTypes[paramCounter].equals(int.class)
                            || paramTypes[paramCounter].equals(Integer.class)) {
                        this.inputParamCount++;
                        paramCounter++;
                    } else {
                        throw new IllegalArgumentException(
                                "param number " + paramCounter + " must be of type int");
                    }
                } else if (inputParameterInfo.type().equals(InputParameterType.TA_Input_Price)) {

                    // the flags define the number of parameters in use by a bitwise or
                    int priceParamSize = numberOfSetBits(inputParameterInfo.flags());
                    for (int i = 0; i < priceParamSize; i++) {
                        if (paramTypes[paramCounter].equals(double.class)
                                || paramTypes[paramCounter].equals(Double.class)) {
                            this.inputParamCount++;
                            paramCounter++;
                        } else {
                            throw new IllegalArgumentException(
                                    "param number " + paramCounter + " must be of type double");
                        }
                    }
                }

                // got through all optInputParameters and store them for later
            } else if (annotation instanceof OptInputParameterInfo) {
                OptInputParameterInfo optInputParameterInfo = (OptInputParameterInfo) annotation;
                if (optInputParameterInfo.type().equals(OptInputParameterType.TA_OptInput_IntegerRange)) {
                    this.optInputParams.add(getConstant(validationContext, paramCounter, Integer.class));
                } else if (optInputParameterInfo.type().equals(OptInputParameterType.TA_OptInput_RealRange)) {
                    this.optInputParams.add(getConstant(validationContext, paramCounter, Double.class));
                } else if (optInputParameterInfo.type().equals(OptInputParameterType.TA_OptInput_IntegerList)) {
                    String value = (String) getConstant(validationContext, paramCounter, String.class);
                    MAType type = MAType.valueOf(value);
                    this.optInputParams.add(type);
                }
                paramCounter++;

                // to through all outputParameters and store them
            } else if (annotation instanceof OutputParameterInfo) {
                OutputParameterInfo outputParameterInfo = (OutputParameterInfo) annotation;
                String paramName = outputParameterInfo.paramName();
                if (outputParameterInfo.type().equals(OutputParameterType.TA_Output_Real)) {
                    this.outputParams.put(paramName, new double[1]);
                    outputParamTypes.put(paramName.toLowerCase().substring(3), double.class);
                } else if (outputParameterInfo.type().equals(OutputParameterType.TA_Output_Integer)) {
                    this.outputParams.put(outputParameterInfo.paramName(), new int[1]);
                    outputParamTypes.put(paramName.toLowerCase().substring(3), int.class);
                }
            }
        }
    }

    // get unstable period
    int unstablePeriod = 0;
    if (paramTypes.length == paramCounter + 1) {
        unstablePeriod = (int) getConstant(validationContext, paramCounter, Integer.class);
        paramCounter++;
    }

    if (paramTypes.length > paramCounter) {
        throw new IllegalArgumentException("too many params, expected " + paramCounter + " or "
                + (paramCounter + 1) + " found " + paramTypes.length);
    }

    try {

        // get the dynamically created output class
        if (this.outputParams.size() > 1) {
            String className = StringUtils.capitalize(talibFunctionName);
            this.outputClass = getReturnClass(className, outputParamTypes);
        }

        // get the lookback size
        Object[] args = new Object[this.optInputParams.size()];
        Class<?>[] argTypes = new Class[this.optInputParams.size()];

        // supply all optInputParams
        int argCount = 0;
        for (Object object : this.optInputParams) {
            args[argCount] = object;
            Class<?> clazz = object.getClass();
            Class<?> primitiveClass = ClassUtils.wrapperToPrimitive(clazz);
            if (primitiveClass != null) {
                argTypes[argCount] = primitiveClass;
            } else {
                argTypes[argCount] = clazz;
            }
            argCount++;
        }

        // set unstable period
        if (unstablePeriod > 0) {
            for (FuncUnstId value : FuncUnstId.values()) {
                this.core.SetUnstablePeriod(value, 50);
            }
        }

        // get and invoke the lookback method
        Method lookback = this.core.getClass().getMethod(talibFunctionName + "Lookback", argTypes);
        this.lookbackPeriod = (Integer) lookback.invoke(this.core, args) + 1;

        // create the fixed size Buffers
        for (int i = 0; i < this.inputParamCount; i++) {
            this.inputParams.add(new CircularFifoBuffer<>(this.lookbackPeriod));
        }

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.hadoop.hbase.coprocessor.GroupByStatsValues.java

@Override
public void write(DataOutput out) throws IOException {
    out.writeLong(count);//from   w  w w .jav  a2  s. c  o m
    out.writeLong(missing);

    if (min == null) {
        min = ci.getMaxValue();
    }
    if (max == null) {
        max = ci.getMinValue();
    }
    if (sum == null) {
        sum = ci.castToReturnType(ci.zero());
    }
    if (sumOfSquares == null) {
        sumOfSquares = ci.castToReturnType(ci.zero());
    }
    new ObjectWritable(ClassUtils.wrapperToPrimitive(min.getClass()), min).write(out);
    new ObjectWritable(ClassUtils.wrapperToPrimitive(max.getClass()), max).write(out);
    new ObjectWritable(ClassUtils.wrapperToPrimitive(sum.getClass()), sum).write(out);
    new ObjectWritable(ClassUtils.wrapperToPrimitive(sumOfSquares.getClass()), sumOfSquares).write(out);

    WritableUtils.writeString(out, ci.getClass().getName());
}

From source file:org.apache.hadoop.hive.metastore.VerifyingObjectStore.java

private static void dumpObject(StringBuilder errorStr, String name, Object p, Class<?> c, int level)
        throws IllegalAccessException {
    String offsetStr = repeat("  ", level);
    if (p == null || c == String.class || c.isPrimitive() || ClassUtils.wrapperToPrimitive(c) != null) {
        errorStr.append(offsetStr).append(name + ": [" + p + "]\n");
    } else if (ClassUtils.isAssignable(c, Iterable.class)) {
        errorStr.append(offsetStr).append(name + " is an iterable\n");
        Iterator<?> i1 = ((Iterable<?>) p).iterator();
        int i = 0;
        while (i1.hasNext()) {
            Object o1 = i1.next();
            Class<?> t = o1 == null ? Object.class : o1.getClass(); // ...
            dumpObject(errorStr, name + "[" + (i++) + "]", o1, t, level + 1);
        }/*from w w w  . java 2s  .  c  o  m*/
    } else if (c.isArray()) {
        int len = Array.getLength(p);
        Class<?> t = c.getComponentType();
        errorStr.append(offsetStr).append(name + " is an array\n");
        for (int i = 0; i < len; ++i) {
            dumpObject(errorStr, name + "[" + i + "]", Array.get(p, i), t, level + 1);
        }
    } else if (ClassUtils.isAssignable(c, Map.class)) {
        Map<?, ?> c1 = (Map<?, ?>) p;
        errorStr.append(offsetStr).append(name + " is a map\n");
        dumpObject(errorStr, name + ".keys", c1.keySet(), Set.class, level + 1);
        dumpObject(errorStr, name + ".vals", c1.values(), Collection.class, level + 1);
    } else {
        errorStr.append(offsetStr).append(name + " is of type " + c.getCanonicalName() + "\n");
        // TODO: this doesn't include superclass.
        Field[] fields = c.getDeclaredFields();
        AccessibleObject.setAccessible(fields, true);
        for (int i = 0; i < fields.length; i++) {
            Field f = fields[i];
            if (f.getName().indexOf('$') != -1 || Modifier.isStatic(f.getModifiers()))
                continue;
            dumpObject(errorStr, name + "." + f.getName(), f.get(p), f.getType(), level + 1);
        }
    }
}

From source file:org.apache.hadoop.hive.serde2.avro.AvroLazyObjectInspector.java

/**
 * Determines if the given object is a primitive or a wrapper to a primitive. Note, even though a
 * <code>String</code> may not be a primitive in the traditional sense, but it is considered one
 * here as it is <i>not</i> a struct.
 *
 * @param clazz input class/*from w  w  w .j  av a2 s.c  o  m*/
 * @return true, if the object is a primitive or a wrapper to a primitive, false otherwise.
 * */
private boolean isPrimitive(Class<?> clazz) {
    return clazz.isPrimitive() || ClassUtils.wrapperToPrimitive(clazz) != null
            || clazz.getSimpleName().equals("String");
}

From source file:org.apache.sling.models.impl.injectors.ValueMapInjector.java

public Object getValue(@Nonnull Object adaptable, String name, @Nonnull Type type,
        @Nonnull AnnotatedElement element, @Nonnull DisposalCallbackRegistry callbackRegistry) {
    ValueMap map = getValueMap(adaptable);
    if (map == null) {
        return null;
    } else if (type instanceof Class<?>) {
        Class<?> clazz = (Class<?>) type;
        try {//from ww  w. j a  v  a  2s  .c  o  m
            return map.get(name, clazz);
        } catch (ClassCastException e) {
            // handle case of primitive/wrapper arrays
            if (clazz.isArray()) {
                Class<?> componentType = clazz.getComponentType();
                if (componentType.isPrimitive()) {
                    Class<?> wrapper = ClassUtils.primitiveToWrapper(componentType);
                    if (wrapper != componentType) {
                        Object wrapperArray = map.get(name, Array.newInstance(wrapper, 0).getClass());
                        if (wrapperArray != null) {
                            return unwrapArray(wrapperArray, componentType);
                        }
                    }
                } else {
                    Class<?> primitiveType = ClassUtils.wrapperToPrimitive(componentType);
                    if (primitiveType != componentType) {
                        Object primitiveArray = map.get(name, Array.newInstance(primitiveType, 0).getClass());
                        if (primitiveArray != null) {
                            return wrapArray(primitiveArray, componentType);
                        }
                    }
                }
            }
            return null;
        }
    } else if (type instanceof ParameterizedType) {
        // list support
        ParameterizedType pType = (ParameterizedType) type;
        if (pType.getActualTypeArguments().length != 1) {
            return null;
        }
        Class<?> collectionType = (Class<?>) pType.getRawType();
        if (!(collectionType.equals(Collection.class) || collectionType.equals(List.class))) {
            return null;
        }

        Class<?> itemType = (Class<?>) pType.getActualTypeArguments()[0];
        Object array = map.get(name, Array.newInstance(itemType, 0).getClass());
        if (array == null) {
            return null;

        }

        return Arrays.asList((Object[]) array);
    } else {
        log.debug("ValueMapInjector doesn't support non-class types {}", type);
        return null;
    }
}

From source file:org.apache.sling.models.impl.ReflectionUtil.java

public static Type mapWrapperClasses(Type type) {
    if (type instanceof Class<?>) {
        return ClassUtils.wrapperToPrimitive((Class<?>) type);
    } else {/*from  ww w  .ja v a 2s . c  o  m*/
        return type;
    }
}