Example usage for java.lang Class isPrimitive

List of usage examples for java.lang Class isPrimitive

Introduction

In this page you can find the example usage for java.lang Class isPrimitive.

Prototype

@HotSpotIntrinsicCandidate
public native boolean isPrimitive();

Source Link

Document

Determines if the specified Class object represents a primitive type.

Usage

From source file:com.opensymphony.xwork2.util.DefaultLocalizedTextProvider.java

/**
 * Traverse up class hierarchy looking for message.  Looks at class, then implemented interface,
 * before going up hierarchy.//  w w  w .java  2s.  c  om
 *
 * @return the message
 */
private String findMessage(Class clazz, String key, String indexedKey, Locale locale, Object[] args,
        Set<String> checked, ValueStack valueStack) {
    if (checked == null) {
        checked = new TreeSet<String>();
    } else if (checked.contains(clazz.getName())) {
        return null;
    }

    // look in properties of this class
    String msg = getMessage(clazz.getName(), locale, key, valueStack, args);

    if (msg != null) {
        return msg;
    }

    if (indexedKey != null) {
        msg = getMessage(clazz.getName(), locale, indexedKey, valueStack, args);

        if (msg != null) {
            return msg;
        }
    }

    // look in properties of implemented interfaces
    Class[] interfaces = clazz.getInterfaces();

    for (Class anInterface : interfaces) {
        msg = getMessage(anInterface.getName(), locale, key, valueStack, args);

        if (msg != null) {
            return msg;
        }

        if (indexedKey != null) {
            msg = getMessage(anInterface.getName(), locale, indexedKey, valueStack, args);

            if (msg != null) {
                return msg;
            }
        }
    }

    // traverse up hierarchy
    if (clazz.isInterface()) {
        interfaces = clazz.getInterfaces();

        for (Class anInterface : interfaces) {
            msg = findMessage(anInterface, key, indexedKey, locale, args, checked, valueStack);

            if (msg != null) {
                return msg;
            }
        }
    } else {
        if (!clazz.equals(Object.class) && !clazz.isPrimitive()) {
            return findMessage(clazz.getSuperclass(), key, indexedKey, locale, args, checked, valueStack);
        }
    }

    return null;
}

From source file:com.scit.sling.test.MockValueMap.java

@SuppressWarnings("unchecked")
private <T> T convertType(Object o, Class<T> type) {
    if (o == null) {
        return null;
    }/*from   ww w  .  j a v  a  2  s  .  c om*/
    if (o.getClass().isArray() && type.isArray()) {
        if (type.getComponentType().isAssignableFrom(o.getClass().getComponentType())) {
            return (T) o;
        } else {
            // we need to convert the elements in the array
            Object array = Array.newInstance(type.getComponentType(), Array.getLength(o));
            for (int i = 0; i < Array.getLength(o); i++) {
                Array.set(array, i, convertType(Array.get(o, i), type.getComponentType()));
            }
            return (T) array;
        }
    }
    if (o.getClass().isAssignableFrom(type)) {
        return (T) o;
    }
    if (String.class.isAssignableFrom(type)) {
        // Format dates
        if (o instanceof Calendar) {
            return (T) formatDate((Calendar) o);
        } else if (o instanceof Date) {
            return (T) formatDate((Date) o);
        } else if (o instanceof DateTime) {
            return (T) formatDate((DateTime) o);
        }
        return (T) String.valueOf(o);
    } else if (o instanceof DateTime) {
        DateTime dt = (DateTime) o;
        if (Calendar.class.isAssignableFrom(type)) {
            return (T) dt.toCalendar(Locale.getDefault());
        } else if (Date.class.isAssignableFrom(type)) {
            return (T) dt.toDate();
        } else if (Number.class.isAssignableFrom(type)) {
            return convertType(dt.getMillis(), type);
        }
    } else if (o instanceof Number && Number.class.isAssignableFrom(type)) {
        if (Byte.class.isAssignableFrom(type)) {
            return (T) (Byte) ((Number) o).byteValue();
        } else if (Double.class.isAssignableFrom(type)) {
            return (T) (Double) ((Number) o).doubleValue();
        } else if (Float.class.isAssignableFrom(type)) {
            return (T) (Float) ((Number) o).floatValue();
        } else if (Integer.class.isAssignableFrom(type)) {
            return (T) (Integer) ((Number) o).intValue();
        } else if (Long.class.isAssignableFrom(type)) {
            return (T) (Long) ((Number) o).longValue();
        } else if (Short.class.isAssignableFrom(type)) {
            return (T) (Short) ((Number) o).shortValue();
        } else if (BigDecimal.class.isAssignableFrom(type)) {
            return (T) new BigDecimal(o.toString());
        }
    } else if (o instanceof Number && type.isPrimitive()) {
        final Number num = (Number) o;
        if (type == byte.class) {
            return (T) new Byte(num.byteValue());
        } else if (type == double.class) {
            return (T) new Double(num.doubleValue());
        } else if (type == float.class) {
            return (T) new Float(num.floatValue());
        } else if (type == int.class) {
            return (T) new Integer(num.intValue());
        } else if (type == long.class) {
            return (T) new Long(num.longValue());
        } else if (type == short.class) {
            return (T) new Short(num.shortValue());
        }
    } else if (o instanceof String && Number.class.isAssignableFrom(type)) {
        if (Byte.class.isAssignableFrom(type)) {
            return (T) new Byte((String) o);
        } else if (Double.class.isAssignableFrom(type)) {
            return (T) new Double((String) o);
        } else if (Float.class.isAssignableFrom(type)) {
            return (T) new Float((String) o);
        } else if (Integer.class.isAssignableFrom(type)) {
            return (T) new Integer((String) o);
        } else if (Long.class.isAssignableFrom(type)) {
            return (T) new Long((String) o);
        } else if (Short.class.isAssignableFrom(type)) {
            return (T) new Short((String) o);
        } else if (BigDecimal.class.isAssignableFrom(type)) {
            return (T) new BigDecimal((String) o);
        }
    }
    throw new NotImplementedException(
            "Can't handle conversion from " + o.getClass().getName() + " to " + type.getName());
}

From source file:jp.furplag.util.commons.NumberUtilsTest.java

/**
 * {@link jp.furplag.util.commons.NumberUtils.NumberObject}
 *//*w ww .ja  va  2 s .  c om*/
@SuppressWarnings("unchecked")
@Test
public void NumberObjectTest() {
    try {
        Class<?> numberObject = ClassLoader.getSystemClassLoader()
                .loadClass(NumberUtils.class.getName() + "$NumberObject");

        Constructor<?> c = numberObject.getDeclaredConstructor(Class.class);
        c.setAccessible(true);

        Method ofType = numberObject.getMethod("of", Class.class);
        ofType.setAccessible(true);

        Method ofN = numberObject.getMethod("of", Number.class);
        ofN.setAccessible(true);

        Method parsable = numberObject.getDeclaredMethod("parsable", Number.class);
        parsable.setAccessible(true);

        Method contains = numberObject.getDeclaredMethod("contains", Number.class);
        contains.setAccessible(true);

        Method valueOf = numberObject.getDeclaredMethod("valueOf", Number.class);
        valueOf.setAccessible(true);

        for (Class<?> type : NUMBERS) {
            Object o = c.newInstance(type);
            Class<? extends Number> wrapper = (Class<? extends Number>) ClassUtils.primitiveToWrapper(type);
            Object numob = ofType.invoke(null, type);
            assertEquals("ofType: " + type.getSimpleName(), o, numob);
            Number n = null;
            if (!type.isPrimitive()) {
                if (ClassUtils.isPrimitiveWrapper(type)) {
                    n = (Number) ClassUtils.primitiveToWrapper(type).getMethod("valueOf", String.class)
                            .invoke(null, "1");
                } else {
                    n = (Number) type.getField("ONE").get(null);
                }
                if (type.equals(byte.class))
                    assertEquals("ofN: 1: " + type.getSimpleName(), o, ofN.invoke(null, n));
            }
            assertEquals("parsable: -1: " + type.getSimpleName(), true, parsable.invoke(numob, -1));
            assertEquals("parsable: 0: " + type.getSimpleName(), true, parsable.invoke(numob, 0));
            assertEquals("parsable: 1: " + type.getSimpleName(), true, parsable.invoke(numob, 1));

            assertEquals("parsable: null: " + type.getSimpleName(), !type.isPrimitive(),
                    parsable.invoke(numob, (Number) null));

            Object expected = ObjectUtils.isAny(wrapper, Float.class, Double.class, BigDecimal.class,
                    BigInteger.class);
            assertEquals("parsable: Infinity: Double: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, Double.POSITIVE_INFINITY));
            assertEquals("parsable: Infinity: Double: BigDecimal: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, INFINITY_DOUBLE));
            assertEquals("parsable: Infinity: Double: BigInteger: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, INFINITY_DOUBLE.toBigInteger()));
            assertEquals("parsable: Infinity: Float: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, Float.POSITIVE_INFINITY));
            assertEquals("parsable: Infinity: Float: BigDecimal: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, INFINITY_FLOAT));
            assertEquals("parsable: Infinity: Float: BigInteger: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, INFINITY_FLOAT.toBigInteger()));
            assertEquals("parsable: -Infinity: Double: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, Double.NEGATIVE_INFINITY));
            assertEquals("parsable: -Infinity: Double: BigDecimal: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, INFINITY_DOUBLE.negate()));
            assertEquals("parsable: -Infinity: Double: BigInteger: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, INFINITY_DOUBLE.negate().toBigInteger()));
            assertEquals("parsable: -Infinity: Float: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, Float.NEGATIVE_INFINITY));
            assertEquals("parsable: -Infinity: Float: BigDecimal: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, INFINITY_FLOAT.negate()));
            assertEquals("parsable: -Infinity: Float: BigInteger: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, INFINITY_FLOAT.negate().toBigInteger()));

            expected = ObjectUtils.isAny(wrapper, Float.class, Double.class);
            assertEquals("parsable: NaN: Float: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, Float.NaN));
            assertEquals("parsable: NaN: Double: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, Double.NaN));

            if (Byte.class.equals(wrapper)) {
                assertEquals("parsable: contains: min: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MIN_VALUE").getByte(null)));
                assertEquals("parsable: contains: max: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MAX_VALUE").getByte(null)));
                assertEquals("parsable: overflow: min: " + type.getSimpleName(), false,
                        parsable.invoke(numob, Short.MIN_VALUE));
                assertEquals("parsable: overflow: max: " + type.getSimpleName(), false,
                        parsable.invoke(numob, Short.MAX_VALUE));
                assertEquals("parsable: fraction: " + type.getSimpleName(), false,
                        parsable.invoke(numob, 123.456f));

                assertEquals("contains: min: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MIN_VALUE").getByte(null)));
                assertEquals("contains: max: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MAX_VALUE").getByte(null)));
                assertEquals("contains: overflow: min: " + type.getSimpleName(), false,
                        contains.invoke(numob, Short.MIN_VALUE));
                assertEquals("contains: overflow: max: " + type.getSimpleName(), false,
                        contains.invoke(numob, Short.MAX_VALUE));
                assertEquals("contains: fraction: " + type.getSimpleName(), true,
                        contains.invoke(numob, 123.456f));
                assertEquals("contains: overflow: fraction: " + type.getSimpleName(), false,
                        contains.invoke(numob, 1234.56f));
            }
            if (Short.class.equals(wrapper)) {
                assertEquals("parsable: contains: min: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MIN_VALUE").getShort(null)));
                assertEquals("parsable: contains: max: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MAX_VALUE").getShort(null)));
                assertEquals("parsable: overflow: min: " + type.getSimpleName(), false,
                        parsable.invoke(numob, Integer.MIN_VALUE));
                assertEquals("parsable: overflow: max: " + type.getSimpleName(), false,
                        parsable.invoke(numob, Integer.MAX_VALUE));
                assertEquals("parsable: fraction: " + type.getSimpleName(), false,
                        parsable.invoke(numob, 123.456f));

                assertEquals("contains: min: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MIN_VALUE").getShort(null)));
                assertEquals("contains: max: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MAX_VALUE").getShort(null)));
                assertEquals("contains: overflow: min: " + type.getSimpleName(), false,
                        contains.invoke(numob, Integer.MIN_VALUE));
                assertEquals("contains: overflow: max: " + type.getSimpleName(), false,
                        contains.invoke(numob, Integer.MAX_VALUE));
                assertEquals("contains: fraction: " + type.getSimpleName(), true,
                        contains.invoke(numob, 12345.6f));
                assertEquals("contains: overflow: fraction: " + type.getSimpleName(), false,
                        contains.invoke(numob, 123456.789f));
            }
            if (Integer.class.equals(wrapper)) {
                assertEquals("parsable: contains: min: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MIN_VALUE").getInt(null)));
                assertEquals("parsable: contains: max: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MAX_VALUE").getInt(null)));
                assertEquals("parsable: overflow: min: " + type.getSimpleName(), false,
                        parsable.invoke(numob, Long.MIN_VALUE));
                assertEquals("parsable: overflow: max: " + type.getSimpleName(), false,
                        parsable.invoke(numob, Long.MAX_VALUE));
                assertEquals("parsable: fraction: " + type.getSimpleName(), false,
                        parsable.invoke(numob, 123456.789f));

                assertEquals("contains: min: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MIN_VALUE").getInt(null)));
                assertEquals("contains: max: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MAX_VALUE").getInt(null)));
                assertEquals("contains: overflow: min: " + type.getSimpleName(), false,
                        contains.invoke(numob, Long.MIN_VALUE));
                assertEquals("contains: overflow: max: " + type.getSimpleName(), false,
                        contains.invoke(numob, Long.MAX_VALUE));
                assertEquals("contains: fraction: " + type.getSimpleName(), true,
                        contains.invoke(numob, 123456.789f));
                assertEquals("contains: overflow: fraction: " + type.getSimpleName(), false,
                        contains.invoke(numob, 12345678912345678912.3456d));
            }
            if (Long.class.equals(wrapper)) {
                assertEquals("parsable: contains: min: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MIN_VALUE").getLong(null)));
                assertEquals("parsable: contains: max: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MAX_VALUE").getLong(null)));
                assertEquals("parsable: overflow: min: " + type.getSimpleName(), false,
                        parsable.invoke(numob, BigInteger.valueOf(Long.MIN_VALUE).pow(2)));
                assertEquals("parsable: overflow: max: " + type.getSimpleName(), false,
                        parsable.invoke(numob, BigInteger.valueOf(Long.MAX_VALUE).pow(2)));
                assertEquals("parsable: fraction: " + type.getSimpleName(), false,
                        parsable.invoke(numob, 123.456f));

                assertEquals("contains: min: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MIN_VALUE").getLong(null)));
                assertEquals("contains: max: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MAX_VALUE").getLong(null)));
                assertEquals("contains: overflow: min: " + type.getSimpleName(), false,
                        contains.invoke(numob, BigInteger.valueOf(Long.MIN_VALUE).pow(2)));
                assertEquals("contains: overflow: max: " + type.getSimpleName(), false,
                        contains.invoke(numob, BigInteger.valueOf(Long.MAX_VALUE).pow(2)));
                assertEquals("contains: fraction: " + type.getSimpleName(), true,
                        contains.invoke(numob, 123456.789f));
                assertEquals("contains: overflow: fraction: " + type.getSimpleName(), false,
                        contains.invoke(numob, 12345678912345678912.3456f));
            }
            if (Float.class.equals(wrapper)) {
                assertEquals("parsable: contains: min: " + type.getSimpleName(), true,
                        parsable.invoke(numob, -wrapper.getField("MAX_VALUE").getFloat(null)));
                assertEquals("parsable: contains: max: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MAX_VALUE").getFloat(null)));
                assertEquals("parsable: overflow: max: " + type.getSimpleName(), false,
                        parsable.invoke(numob, -Double.MAX_VALUE));
                assertEquals("parsable: overflow: max: " + type.getSimpleName(), false,
                        parsable.invoke(numob, Double.MAX_VALUE));

                assertEquals("contains: min: " + type.getSimpleName(), true,
                        contains.invoke(numob, -wrapper.getField("MAX_VALUE").getFloat(null)));
                assertEquals("contains: max: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MAX_VALUE").getFloat(null)));
                assertEquals("contains: overflow: max: " + type.getSimpleName(), false,
                        contains.invoke(numob, -Double.MAX_VALUE));
                assertEquals("contains: overflow: max: " + type.getSimpleName(), false,
                        contains.invoke(numob, Double.MAX_VALUE));
            }
            if (Double.class.equals(wrapper)) {
                assertEquals("parsable: contains: min: " + type.getSimpleName(), true,
                        parsable.invoke(numob, -wrapper.getField("MAX_VALUE").getDouble(null)));
                assertEquals("parsable: contains: max: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MAX_VALUE").getDouble(null)));
                assertEquals("parsable: overflow: min: " + type.getSimpleName(), true,
                        parsable.invoke(numob, INFINITY_DOUBLE.multiply(BigDecimal.TEN).negate()));
                assertEquals("parsable: overflow: max: " + type.getSimpleName(), true,
                        parsable.invoke(numob, INFINITY_DOUBLE.multiply(BigDecimal.TEN)));

                assertEquals("contains: min: " + type.getSimpleName(), true,
                        contains.invoke(numob, -wrapper.getField("MAX_VALUE").getDouble(null)));
                assertEquals("contains: max: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MAX_VALUE").getDouble(null)));
                assertEquals("contains: overflow: min: " + type.getSimpleName(), false,
                        contains.invoke(numob, INFINITY_DOUBLE.multiply(BigDecimal.TEN).negate()));
                assertEquals("contains: overflow: max: " + type.getSimpleName(), false,
                        contains.invoke(numob, INFINITY_DOUBLE.multiply(BigDecimal.TEN)));
            }
            if (!ClassUtils.isPrimitiveWrapper(wrapper)) {
                assertEquals("parsable: fraction: " + type.getSimpleName(), BigDecimal.class.equals(type),
                        parsable.invoke(numob, 123.456f));
                assertEquals("contains: fraction: " + type.getSimpleName(), true,
                        contains.invoke(numob, 123.456f));
            }

            if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null, "123");
            } else {
                expected = new BigDecimal("123");
                if (BigInteger.class.equals(wrapper))
                    expected = ((BigDecimal) expected).toBigInteger();
            }
            for (Class<?> valueType : OBJECTS) {
                if (ClassUtils.isPrimitiveWrapper(valueType)) {
                    n = (Number) valueType.getMethod("valueOf", String.class).invoke(null, "123");
                } else {
                    n = new BigDecimal("123");
                    if (BigInteger.class.equals(valueType))
                        n = ((BigDecimal) n).toBigInteger();
                }
                assertEquals(
                        "valueOf: " + n + " (" + n.getClass().getSimpleName() + "): " + type.getSimpleName(),
                        expected, valueOf.invoke(numob, n));
                assertEquals(
                        "valueOf: " + n + " (" + n.getClass().getSimpleName() + "): class: "
                                + type.getSimpleName(),
                        expected.getClass(), valueOf.invoke(numob, n).getClass());
            }

            n = 123.456f;
            if (ObjectUtils.isAny(wrapper, Float.class, Double.class)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null, n.toString());
            } else if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null,
                        Integer.toString(((Float) n).intValue()));
            } else {
                expected = new BigDecimal(n.toString());
                if (BigInteger.class.equals(wrapper))
                    expected = ((BigDecimal) expected).toBigInteger();
            }
            assertEquals("valueOf: " + n + " (" + n.getClass().getSimpleName() + "): " + type.getSimpleName(),
                    expected, valueOf.invoke(numob, n));
            assertEquals(
                    "valueOf: " + n + " (" + n.getClass().getSimpleName() + "): class: " + type.getSimpleName(),
                    expected.getClass(), valueOf.invoke(numob, n).getClass());

            n = 1.23456789E-6d;
            if (ObjectUtils.isAny(wrapper, Float.class, Double.class)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null, n.toString());
            } else if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null,
                        Integer.toString(((Double) n).intValue()));
            } else {
                expected = new BigDecimal(n.toString());
                if (BigInteger.class.equals(wrapper))
                    expected = ((BigDecimal) expected).toBigInteger();
            }
            assertEquals("valueOf: " + n + " (" + n.getClass().getSimpleName() + "): " + type.getSimpleName(),
                    expected, valueOf.invoke(numob, n));
            assertEquals(
                    "valueOf: " + n + " (" + n.getClass().getSimpleName() + "): class: " + type.getSimpleName(),
                    expected.getClass(), valueOf.invoke(numob, n).getClass());

            n = INFINITY_DOUBLE.pow(2);
            if (ObjectUtils.isAny(wrapper, Float.class, Double.class)) {
                expected = wrapper.getField("POSITIVE_INFINITY").get(null);
            } else if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getField("MAX_VALUE").get(null);
            } else {
                expected = new BigDecimal(n.toString());
                if (BigInteger.class.equals(wrapper))
                    expected = ((BigDecimal) expected).toBigInteger();
            }
            assertEquals("valueOf: Huge: " + type.getSimpleName(), expected, valueOf.invoke(numob, n));
            assertEquals("valueOf: Huge: class: " + type.getSimpleName(), expected.getClass(),
                    valueOf.invoke(numob, n).getClass());

            n = INFINITY_DOUBLE.pow(2).negate();
            if (ObjectUtils.isAny(wrapper, Float.class, Double.class)) {
                expected = wrapper.getField("NEGATIVE_INFINITY").get(null);
            } else if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getField("MIN_VALUE").get(null);
            } else {
                expected = new BigDecimal(n.toString());
                if (BigInteger.class.equals(wrapper))
                    expected = ((BigDecimal) expected).toBigInteger();
            }
            assertEquals("valueOf: Huge: negative: " + type.getSimpleName(), expected,
                    valueOf.invoke(numob, n));
            assertEquals("valueOf: Huge: negative: class: " + type.getSimpleName(), expected.getClass(),
                    valueOf.invoke(numob, n).getClass());
        }
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace()));
    }
}

From source file:net.ceos.project.poi.annotated.core.Engine.java

/**
 * Initialization of the cell by the field.
 * /* w  w  w. java2 s  . c o m*/
 * @param configCriteria
 *            the {@link XConfigCriteria}
 * @param xlsAnnotation
 *            the {@link XlsFreeElement}
 * @param o
 *            the object
 * @param field
 *            the field
 * @param idxC
 *            the position of the cell
 * @param cL
 *            the cascade level
 * @throws WorkbookException
 *             given when the object is complex.
 */
private void initializeCellByField(final XConfigCriteria configCriteria, final XlsFreeElement xlsAnnotation,
        final Object o, final Field field, final int idxC, final int cL) throws WorkbookException {

    /* make the field accessible to recover the value */
    field.setAccessible(true);

    Class<?> fT = field.getType();

    if (configCriteria.getSheet().getRow(xlsAnnotation.row()) != null) {
        configCriteria.setRow(configCriteria.getSheet().getRow(xlsAnnotation.row()));
    } else {
        configCriteria.setRow(configCriteria.getSheet().createRow(xlsAnnotation.row()));
    }
    configCriteria.setField(field);

    // initialize Element
    configCriteria.setElement(XlsElementFactory.build(xlsAnnotation));

    boolean isAppliedObject = toExcel(configCriteria, o, fT, idxC);

    if (!isAppliedObject && !fT.isPrimitive()) {
        throw new ElementException(ExceptionMessage.ELEMENT_COMPLEX_OBJECT.getMessage());
    }

}

From source file:net.ceos.project.poi.annotated.core.Engine.java

/**
 * Initialize an cell according the type of field and the PropagationType is
 * PROPAGATION_HORIZONTAL.//  www  .  j  a  va  2 s. c o  m
 * 
 * @param configCriteria
 *            the {@link XConfigCriteria}
 * @param o
 *            the object
 * @param idxR
 *            the position of the row
 * @param idxC
 *            the position of the cell
 * @param cL
 *            the cascade level
 * @return in case of the object return the number of cells created,
 *         otherwise 0
 * @throws WorkbookException
 *             given when no such element.
 */
private int initializeCellByFieldHorizontal(final XConfigCriteria configCriteria, final Object o,
        final int idxR, final int idxC, final int cL) throws WorkbookException {

    int counter = 0;

    /* make the field accessible to recover the value */
    configCriteria.getField().setAccessible(true);

    Class<?> fT = configCriteria.getField().getType();

    if (Collection.class.isAssignableFrom(fT)) {
        try {
            // E uma lista entao ha que crear uma sheet nova
            marshallCollectionEngineT(configCriteria, (Collection<?>) configCriteria.getField().get(o), idxC,
                    fT, cL + 1);
        } catch (IllegalAccessException e) {
            throw new CustomizedRulesException(ExceptionMessage.ELEMENT_NO_SUCH_METHOD.getMessage(), e);
        }
    } else {

        boolean isAppliedObject = toExcel(configCriteria, o, fT, idxC);

        /* backup of the cell index */
        configCriteria.setLastCellIndex(idxC);

        if (!isAppliedObject && !fT.isPrimitive()) {
            try {
                Object nO = configCriteria.getField().get(o);
                /* manage null objects */
                if (nO == null) {
                    nO = fT.newInstance();
                }
                Class<?> oC = nO.getClass();

                counter = marshalAsPropagationHorizontal(configCriteria, nO, oC, idxR, idxC - 1, cL + 1);
            } catch (InstantiationException | IllegalAccessException e) {
                throw new CustomizedRulesException(ExceptionMessage.ELEMENT_NO_SUCH_METHOD.getMessage(), e);
            }
        }
    }

    return counter;
}

From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

@Override
public String checkExists(String className, String attribute, String value, Locale locale)
        throws PersistenceException {
    EntityManager em = null;/*from www .j a v  a2s . c  o m*/
    try {
        em = getEntityManager();
        boolean isString;
        if (value != null) {
            PropertyDescriptor[] pds = (PropertyDescriptor[]) propertyDescriptorsByClassName.get(className);
            boolean isNumber = false;
            isString = false;
            for (PropertyDescriptor pd : pds) {
                if (pd.getName().equals(attribute)) {
                    Class propertyType = pd.getPropertyType();
                    if ((propertyType.isPrimitive()) || (Number.class.isAssignableFrom(propertyType))) {
                        isNumber = true;
                        break;
                    }
                    if (!(String.class.isAssignableFrom(propertyType)))
                        break;
                    isString = true;
                    break;
                }
            }

            StringBuilder q = getCheckExistsQuery(className, attribute, value, isNumber, isString);

            Query q1 = em.createQuery(q.toString());
            if (isString)
                q1.setParameter(1, value.toLowerCase());
            List l = q1.getResultList();
            ResourceBundle ressource;
            if ((l != null) && (l.size() > 0)) {
                return getUniqueErrorMsg(attribute, value, locale);
            }

            return null;
        }

        List l = em.createQuery("select 1 from " + className + " o where o." + attribute + " is null")
                .getResultList();
        ResourceBundle ressource;
        if ((l != null) && (l.size() > 0)) {
            return getUniqueErrorMsg(attribute, value, locale);
        }

        return null;
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Exception in checkExists " + e.getMessage(), e);
        throw new PersistenceException("Exception in checkExists " + e.getMessage(), e);
    } finally {
        closeEntityManager(em);
    }
}

From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

@Override
public String checkExists(String className, com.hiperf.common.ui.shared.util.Id id, String attribute,
        String value, Locale locale) throws PersistenceException {
    EntityManager em = null;/* w  w  w  .j ava 2s  . com*/
    try {
        Set<PropertyDescriptor> ids = idsByClassName.get(className);
        PropertyDescriptor[] idsArr = (PropertyDescriptor[]) ids.toArray(new PropertyDescriptor[0]);
        em = getEntityManager();
        int i;
        if (value != null) {
            boolean isNumber = false;
            boolean isString = false;
            PropertyDescriptor[] pds = (PropertyDescriptor[]) propertyDescriptorsByClassName.get(className);
            Class<?> propertyType;
            for (PropertyDescriptor pd : pds) {
                if (pd.getName().equals(attribute)) {
                    propertyType = pd.getPropertyType();
                    if ((propertyType.isPrimitive()) || (Number.class.isAssignableFrom(propertyType))) {
                        isNumber = true;
                        break;
                    }
                    if (!(String.class.isAssignableFrom(propertyType)))
                        break;
                    isString = true;
                    break;
                }
            }

            StringBuilder q = getCheckExistsQuery(className, attribute, value, isNumber, isString);

            q.append(" and o.");
            i = 0;
            for (String att : id.getFieldNames()) {
                q.append(att);
                q.append(" != ");
                if (StorageService.isNumber(att, idsArr)) {
                    q.append(id.getFieldValues().get(i));
                } else {
                    q.append(" '").append(StringUtils.replace(id.getFieldValues().get(i).toString(), "'", "''"))
                            .append("'");
                }
                ++i;
                if (i < id.getFieldNames().size())
                    q.append(" and o.");
            }
            Query q1 = em.createQuery(q.toString());
            if (isString)
                q1.setParameter(1, value.toLowerCase());
            List l = q1.getResultList();
            if ((l != null) && (l.size() > 0)) {
                return getUniqueErrorMsg(attribute, value, locale);
            }

            return null;
        }

        StringBuilder q = new StringBuilder(
                "select 1 from " + className + " o where o." + attribute + " is null and o.");
        i = 0;
        for (String att : id.getFieldNames()) {
            q.append(att);
            q.append(" != ");
            if (StorageService.isNumber(att, idsArr)) {
                q.append(id.getFieldValues().get(i));
            } else {
                q.append(" '");
                q.append(StringUtils.replace(id.getFieldValues().get(i).toString(), "'", "''"));
                q.append("'");
            }
            ++i;
            if (i < id.getFieldNames().size())
                q.append(" and o.");
        }
        List l = em.createQuery(q.toString()).getResultList();
        if ((l != null) && (l.size() > 0)) {
            return getUniqueErrorMsg(attribute, value, locale);
        }

        return null;
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Exception in checkExists " + e.getMessage(), e);
        throw new PersistenceException("Exception in checkExists " + e.getMessage(), e);
    } finally {
        closeEntityManager(em);
    }
}

From source file:com.xiovr.unibot.bot.impl.BotGameConfigImpl.java

@Override
// public void loadSettings(Settings instance, Class<?> clazz, String fn)
public void loadSettings(Settings instance, String fn) {

    Class<?> clazz = instance.getClass().getInterfaces()[0];
    //      File file = new File("/" + DIR_PATH + "/" + fn);
    File file = new File(fn);
    Properties props = null;/*from  w  w  w  .j  a  v  a2  s .co  m*/
    try {
        props = BotUtils.loadProperties(file);

        // botEnvironment.setClientIp((props.getProperty("client.ip",
        // "127.0.0.1"));
    } catch (IOException e) {
        // e.printStackTrace();
        //         logger.warn("Can't load settings /" + DIR_PATH + "/" + fn
        //               + ". Create new settings file.");
        logger.warn("Can't load settings " + fn + ". Create new settings file.");
        props = createSettings(clazz, fn, "Bot v" + VERSION);

    }
    Method[] methods = clazz.getMethods();
    for (Method method : methods) {
        // Find setters
        if (method.getName().startsWith("set")) {

            if (method.isAnnotationPresent(Param.class)) {

                Annotation annotation = method.getAnnotation(Param.class);
                Param param = (Param) annotation;
                if (param.name().equals("") || param.values().length == 0) {
                    throw new RuntimeException("Wrong param in class " + clazz.getCanonicalName()
                            + " with method " + method.getName());
                }
                Class<?>[] paramClazzes = method.getParameterTypes();
                if (paramClazzes.length != 1) {
                    throw new RuntimeException("Error contract design in class " + clazz.getCanonicalName()
                            + " with method " + method.getName());
                }
                // Check param belongs to List
                Class<?> paramClazz = paramClazzes[0];

                try {
                    if (List.class.isAssignableFrom(paramClazz)) {
                        // Oh, its array...
                        // May be its InetSocketAddress?

                        Type[] gpt = method.getGenericParameterTypes();
                        if (gpt[0] instanceof ParameterizedType) {
                            ParameterizedType type = (ParameterizedType) gpt[0];
                            Type[] typeArguments = type.getActualTypeArguments();

                            for (Type typeArgument : typeArguments) {
                                Class<?> classType = ((Class<?>) typeArgument);
                                if (InetSocketAddress.class.isAssignableFrom(classType)) {
                                    List<InetSocketAddress> isaArr = new ArrayList<>();
                                    int cnt = Integer.parseInt(props.getProperty(param.name() + ".count", "2"));
                                    for (int i = 0; i < cnt; ++i) {
                                        String defaultHostname = "";
                                        String defaultPort = "";
                                        if (param.values().length > i * 2) {
                                            defaultHostname = param.values()[i * 2];
                                            defaultPort = param.values()[i * 2 + 1];
                                        } else {
                                            defaultHostname = DEFAULT_HOSTNAME;
                                            defaultPort = String.valueOf(DEFAULT_PORT);
                                        }
                                        InetSocketAddress isa = new InetSocketAddress(
                                                props.getProperty(
                                                        param.name() + "." + String.valueOf(i) + ".ip",
                                                        defaultHostname),
                                                Integer.parseInt(props.getProperty(
                                                        param.name() + "." + String.valueOf(i) + ".port",
                                                        defaultPort)));
                                        // invocableClazz.getMethod(method.getName(),
                                        // InetSocketAddress.class).invoke(
                                        // instance, isa);
                                        isaArr.add(isa);

                                    }

                                    method.invoke(instance, isaArr);

                                } else {
                                    throw new RuntimeException("Settings param in class "
                                            + clazz.getCanonicalName() + " with method " + method.getName()
                                            + " not implemented yet");
                                }
                            }

                        }
                    } else if (paramClazz.isPrimitive()) {
                        if (int.class.isAssignableFrom(paramClazz)) {
                            method.invoke(instance,
                                    Integer.parseInt(props.getProperty(param.name(), param.values()[0])));
                        } else if (long.class.isAssignableFrom(paramClazz)) {
                            method.invoke(instance,
                                    Long.parseLong(props.getProperty(param.name(), param.values()[0])));
                        } else if (boolean.class.isAssignableFrom(paramClazz)) {
                            method.invoke(instance,
                                    Boolean.parseBoolean(props.getProperty(param.name(), param.values()[0])));
                        } else if (double.class.isAssignableFrom(paramClazz)) {
                            method.invoke(instance,
                                    Double.parseDouble(props.getProperty(param.name(), param.values()[0])));
                        }

                    } else if (String.class.isAssignableFrom(paramClazz)) {
                        method.invoke(instance, props.getProperty(param.name(), param.values()[0]));
                    } else {
                        throw new RuntimeException("Settings param in class " + clazz.getCanonicalName()
                                + " with method " + method.getName() + " not implemented yet");
                    }
                } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}

From source file:net.ceos.project.poi.annotated.core.Engine.java

/**
 * Initialize an cell according the type of field and the PropagationType is
 * PROPAGATION_VERTICAL./*from  w w  w .j a va2s. co m*/
 * 
 * @param configCriteria
 *            the {@link XConfigCriteria}
 * @param o
 *            the object
 * @param r
 *            the content row
 * @param idxR
 *            the position of the row
 * @param idxC
 *            the position of the cell
 * @param cL
 *            the cascade level
 * @return in case of the object return the number of cells created,
 *         otherwise 0
 * @throws WorkbookException
 *             given when the object is complex.
 */
private int initializeCellByFieldVertical(final XConfigCriteria configCriteria, final Object o, final Row r,
        final int idxR, final int idxC, int cL) throws WorkbookException {

    int counter = 0;

    /* make the field accessible to recover the value */
    configCriteria.getField().setAccessible(true);

    Class<?> fT = configCriteria.getField().getType();

    configCriteria.setRow(r);

    if (Collection.class.isAssignableFrom(fT)) {
        Collection<?> collection = null;
        try {
            collection = (Collection<?>) configCriteria.getField().get(o);
        } catch (IllegalArgumentException | IllegalAccessException e1) {
            throw new ElementException(ExceptionMessage.ELEMENT_NULL_OBJECT.getMessage());
        }
        if (collection != null) {
            Object objectRT;
            try {
                objectRT = collection.stream().findFirst().get();
            } catch (Exception e) {
                throw new ElementException(ExceptionMessage.ELEMENT_NULL_OBJECT.getMessage());
            }

            /* initialize the runtime class of the object */
            Class<?> oC = initializeRuntimeClass(objectRT);

            // E uma lista entao ha que crear uma sheet nova
            marshallCollectionEngineT(configCriteria, collection, idxC, oC, cL + 1);
        }

    } else {
        boolean isAppliedObject = toExcel(configCriteria, o, fT, idxC);

        /* backup of the cell index */
        configCriteria.setLastCellIndex(idxC);

        if (!isAppliedObject && !fT.isPrimitive()) {
            try {
                Object nO = configCriteria.getField().get(o);
                /* manage null objects */
                if (nO == null) {
                    nO = fT.newInstance();
                }
                Class<?> oC = nO.getClass();

                counter = marshalAsPropagationVertical(configCriteria, nO, oC, idxR - 1, idxC - 1, cL + 1);
            } catch (InstantiationException | IllegalAccessException e) {
                throw new CustomizedRulesException(ExceptionMessage.ELEMENT_NO_SUCH_METHOD.getMessage(), e);
            }
        }
    }
    return counter;
}

From source file:jef.tools.XMLUtils.java

private static Element appendBean(Node parent, Object bean, Class<?> type, Boolean asAttrib, String tagName) {
    if (type == null) {
        if (bean == null) {
            return null;
        }/*from  www. j a v a2  s.  c o  m*/
        type = bean.getClass();
    }
    if (tagName == null || tagName.length() == 0) {
        tagName = type.getSimpleName();
    }
    if (type.isArray()) {
        if (bean == null)
            return null;
        Element collection = addElement(parent, tagName);
        for (int i = 0; i < Array.getLength(bean); i++) {
            appendBean(collection, Array.get(bean, i), null, asAttrib, null);
        }
        return collection;
    } else if (Collection.class.isAssignableFrom(type)) {
        if (bean == null)
            return null;
        Element collection = addElement(parent, tagName);
        for (Object obj : (Collection<?>) bean) {
            appendBean(collection, obj, null, asAttrib, null);
        }
        return collection;
    } else if (Map.class.isAssignableFrom(type)) {
        Element map = addElement(parent, tagName);
        for (Entry<?, ?> e : ((Map<?, ?>) bean).entrySet()) {
            Element entry = XMLUtils.addElement(map, "entry");
            Element key = XMLUtils.addElement(entry, "key");
            appendBean(key, e.getKey(), null, asAttrib, null);
            Element value = XMLUtils.addElement(entry, "value");
            appendBean(value, e.getValue(), null, asAttrib, null);
        }
        return map;
    } else if (CharSequence.class.isAssignableFrom(type)) {
        if (Boolean.TRUE.equals(asAttrib)) {
            ((Element) parent).setAttribute(tagName, StringUtils.toString(bean));
        } else {
            addElement(parent, tagName, StringUtils.toString(bean));
        }
    } else if (Date.class.isAssignableFrom(type)) {
        if (Boolean.FALSE.equals(asAttrib)) {
            addElement(parent, tagName, DateUtils.formatDateTime((Date) bean));
        } else {
            ((Element) parent).setAttribute(tagName, DateUtils.formatDateTime((Date) bean));
        }
    } else if (Number.class.isAssignableFrom(type) || type.isPrimitive() || type == Boolean.class) {
        if (Boolean.FALSE.equals(asAttrib)) {
            addElement(parent, tagName, StringUtils.toString(bean));
        } else {
            ((Element) parent).setAttribute(tagName, StringUtils.toString(bean));
        }
    } else {
        if (bean == null)
            return null;
        Element root = addElement(parent, type.getSimpleName());
        BeanWrapper bw = BeanWrapper.wrap(bean);
        for (Property p : bw.getProperties()) {
            appendBean(root, p.get(bean), p.getType(), asAttrib, p.getName());
        }
        return root;
    }
    return null;
}