Example usage for java.lang Class isEnum

List of usage examples for java.lang Class isEnum

Introduction

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

Prototype

public boolean isEnum() 

Source Link

Document

Returns true if and only if this class was declared as an enum in the source code.

Usage

From source file:org.apache.axis2.jaxws.message.databinding.JAXBUtils.java

/**
 * @param list/*from   w ww.  j  a va 2  s. c om*/
 * @param pkg
 */
private static void checkClasses(List<Class> list, String pkg) {
    // The installed classfinder or directory search may inadvertently add too many 
    // classes.  This rountine is a 'double check' to make sure that the classes
    // are acceptable.
    for (int i = 0; i < list.size();) {
        Class cls = list.get(i);
        if (!cls.isInterface()
                && (cls.isEnum() || getAnnotation(cls, XmlType.class) != null
                        || ClassUtils.getDefaultPublicConstructor(cls) != null)
                && !ClassUtils.isJAXWSClass(cls) && !isSkipClass(cls)
                && cls.getPackage().getName().equals(pkg)) {
            i++; // Acceptable class
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Removing class " + cls + " from consideration because it is not in package " + pkg
                        + " or is an interface or does not have a public constructor or is" + " a jaxws class");
            }
            list.remove(i);
        }
    }
}

From source file:org.apache.sqoop.model.ConfigUtils.java

@SuppressWarnings("unchecked")
private static MConfig toConfig(String configName, Class klass, Object object) {
    ConfigClass global = (ConfigClass) klass.getAnnotation(ConfigClass.class);

    // Each configuration object must have this class annotation
    if (global == null) {
        throw new SqoopException(ModelError.MODEL_003,
                "Missing annotation ConfigClass on class " + klass.getName());
    }/*from  w  w w  .  j a v a2 s.c om*/

    // Intermediate list of inputs
    List<MInput<?>> inputs = new LinkedList<MInput<?>>();

    // Iterate over all declared fields
    for (Field field : klass.getDeclaredFields()) {
        field.setAccessible(true);

        String fieldName = field.getName();
        String inputName = configName + "." + fieldName;

        // Each field that should be part of user input should have Input
        // annotation.
        Input inputAnnotation = field.getAnnotation(Input.class);

        if (inputAnnotation != null) {
            boolean sensitive = inputAnnotation.sensitive();
            short maxLen = inputAnnotation.size();
            Class<?> type = field.getType();

            MInput input;

            // We need to support NULL, so we do not support primitive types
            if (type.isPrimitive()) {
                throw new SqoopException(ModelError.MODEL_007,
                        "Detected primitive type " + type + " for field " + fieldName);
            }

            // Instantiate corresponding MInput<?> structure
            if (type == String.class) {
                input = new MStringInput(inputName, sensitive, maxLen);
            } else if (type.isAssignableFrom(Map.class)) {
                input = new MMapInput(inputName, sensitive);
            } else if (type == Integer.class) {
                input = new MIntegerInput(inputName, sensitive);
            } else if (type == Boolean.class) {
                input = new MBooleanInput(inputName, sensitive);
            } else if (type.isEnum()) {
                input = new MEnumInput(inputName, sensitive, ClassUtils.getEnumStrings(type));
            } else {
                throw new SqoopException(ModelError.MODEL_004,
                        "Unsupported type " + type.getName() + " for input " + fieldName);
            }

            // Move value if it's present in original configuration object
            if (object != null) {
                Object value;
                try {
                    value = field.get(object);
                } catch (IllegalAccessException e) {
                    throw new SqoopException(ModelError.MODEL_005,
                            "Can't retrieve value from " + field.getName(), e);
                }
                if (value == null) {
                    input.setEmpty();
                } else {
                    input.setValue(value);
                }
            }

            inputs.add(input);
        }
    }

    return new MConfig(configName, inputs);
}

From source file:ro.pippo.csv.CsvEngine.java

public Object objectFromString(String value, Class<?> objectClass) throws ParseException {
    if (value == null) {
        return null;
    } else if (objectClass.isAssignableFrom(value.getClass())) {
        return value;
    }/* w w  w.  j  a v  a 2 s.  c  o  m*/

    // re-use the infinitely useful ParameterValue class
    ParameterValue pv = new ParameterValue(value);
    if (objectClass.isEnum()) {
        return pv.toEnum((Class) objectClass);
    } else if (java.sql.Date.class.isAssignableFrom(objectClass)) {
        return pv.toSqlDate();
    } else if (java.sql.Time.class.isAssignableFrom(objectClass)) {
        return pv.toSqlTime();
    } else if (java.sql.Timestamp.class.isAssignableFrom(objectClass)) {
        return pv.toSqlTimestamp();
    } else if (Date.class.isAssignableFrom(objectClass)) {
        return pv.toDate(datePattern);
    }

    return pv.to(objectClass);
}

From source file:com.britesnow.snow.util.ObjectUtil.java

public static final <T> T getValue(String valueStr, Class<T> cls, T defaultValue) {
    if (valueStr == null) {
        return defaultValue;
    } else {/*from  ww  w .ja v  a2 s.co m*/
        try {
            if (cls == String.class) {
                return (T) valueStr;
            } else if (valueStr.length() > 0) {

                if (cls.isArray()) {
                    return getValue(new String[] { valueStr }, cls, defaultValue);
                } else if (cls == Integer.class) {
                    Integer value = numberFormat.parse(valueStr).intValue();
                    return (T) value;
                } else if (cls == Long.class) {
                    Long value = numberFormat.parse(valueStr).longValue();
                    return (T) value;
                } else if (cls == Float.class) {
                    Float value = numberFormat.parse(valueStr).floatValue();
                    return (T) value;
                } else if (cls == Double.class) {
                    Double value = numberFormat.parse(valueStr).doubleValue();
                    return (T) value;
                } else if (cls == Boolean.class) {
                    if ("true".equals(valueStr)) {
                        return (T) new Boolean(true);
                    } else {
                        return (T) new Boolean(false);
                    }
                } else if (cls.isEnum()) {
                    try {
                        return (T) Enum.valueOf((Class<Enum>) cls, valueStr);
                    } catch (IllegalArgumentException e) {
                        return defaultValue;
                    }
                } else if (cls == Date.class) {
                    SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_DATE_PATTERN);
                    return (T) new java.util.Date(sdf.parse(valueStr).getTime());
                }
            } else {
                return defaultValue;
            }
        } catch (Exception e) {
            return defaultValue;
        }
    }
    return defaultValue;
}

From source file:org.polymap.model2.store.geotools.FeatureTypeBuilder.java

protected ComplexType buildComplexType(Class<? extends Composite> compositeClass, String indent)
        throws Exception {
    // fields -> properties
    Collection<PropertyDescriptor> properties = new ArrayList();

    // super classes and mixins
    Deque<Class> stack = new ArrayDeque();
    stack.push(compositeClass);//www  . j  a  v a  2  s.c  o  m

    while (!stack.isEmpty()) {
        Class type = stack.pop();
        log.debug(indent + "Composite: " + type);

        // super class
        if (type.getSuperclass() != null && !Entity.class.equals(type.getSuperclass())
                && !Composite.class.equals(type.getSuperclass())) {
            stack.push(type.getSuperclass());
        }

        // mixins
        CompositeInfoImpl typeInfo = new CompositeInfoImpl(type);
        //log.debug( indent + "  " + "Mixins: " + typeInfo.getMixins() );
        stack.addAll(typeInfo.getMixins());

        // fields
        for (Field field : type.getDeclaredFields()) {
            // Property or CollectionProperty
            if (Property.class.isAssignableFrom(field.getType())
                    || CollectionProperty.class.isAssignableFrom(field.getType())) {

                PropertyInfoImpl propInfo = new PropertyInfoImpl(field);
                Class<?> binding = propInfo.getType();

                // attribute
                if (binding.isPrimitive() || binding.equals(String.class)
                        || Number.class.isAssignableFrom(binding) || Boolean.class.isAssignableFrom(binding)
                        || Date.class.isAssignableFrom(binding) || binding.isEnum()) {

                    if (binding.isEnum()) {
                        binding = String.class;
                    }
                    AttributeType propType = buildAttributeType(field, binding);
                    AttributeDescriptor desc = factory.createAttributeDescriptor(propType, propType.getName(),
                            0, propInfo.getMaxOccurs(), propInfo.isNullable(), propInfo.getDefaultValue());
                    properties.add(desc);
                    log.debug(indent + "  " + "Attribute: " + desc);
                }
                // geometry
                else if (Geometry.class.isAssignableFrom(binding)) {
                    AttributeType propType = buildAttributeType(field, binding);

                    GeometryType geomType = factory.createGeometryType(propType.getName(),
                            propType.getBinding(), crs, propType.isIdentified(), propType.isAbstract(),
                            propType.getRestrictions(), propType.getSuper(), propType.getDescription());

                    GeometryDescriptor desc = factory.createGeometryDescriptor(geomType, geomType.getName(), 0,
                            1, propInfo.isNullable(), propInfo.getDefaultValue());
                    properties.add(desc);
                    log.debug(indent + "  " + "Geometry: " + desc);
                }
                // complex
                else if (Composite.class.isAssignableFrom(binding)) {
                    ComplexType propType = buildComplexType((Class<? extends Composite>) binding,
                            indent + "    ");
                    AttributeDescriptor desc = factory.createAttributeDescriptor(propType, nameInStore(field),
                            0, propInfo.getMaxOccurs(), propInfo.isNullable(), propInfo.getDefaultValue());
                    properties.add(desc);
                    log.debug(indent + "  " + "Complex Property: " + desc);
                } else {
                    throw new RuntimeException("Property value type is not supported: " + binding);
                }
            }
        }
    }

    NameInStore nameInStore = compositeClass.getAnnotation(NameInStore.class);
    Name name = buildName(nameInStore != null ? nameInStore.value() : compositeClass.getSimpleName());
    boolean isIdentified = false;
    boolean isAbstract = false;
    List<Filter> restrictions = null;
    AttributeType superType = null;
    Description annotation = compositeClass.getAnnotation(Description.class);
    InternationalString description = annotation != null ? SimpleInternationalString.wrap(annotation.value())
            : null;

    return factory.createComplexType(name, properties, isIdentified, isAbstract, restrictions, superType,
            description);
}

From source file:com.grepcurl.random.ObjectGenerator.java

public <T> T generate(Class<T> klass) {
    Validate.notNull(klass);/*w  ww .  j  ava  2 s .co m*/
    if (verbose) {
        log(String.format("generating object of type: %s", klass));
    }
    try {
        Deque<Object> objectStack = new ArrayDeque<>();
        T t;
        if (klass.isEnum()) {
            int randomOrdinal = randomInt(0, klass.getEnumConstants().length - 1);
            t = klass.getEnumConstants()[randomOrdinal];
        } else {
            t = klass.getConstructor().newInstance();
        }
        objectStack.push(t);
        Method[] methods = klass.getMethods();
        for (Method method : methods) {
            _processMethod(method, null, t, objectStack);
        }
        objectStack.pop();
        return t;
    } catch (Exception e) {
        throw new FailedRandomObjectGenerationException(e);
    }
}

From source file:org.apache.sqoop.model.ConfigUtils.java

/**
 * Convert configuration object to JSON. Only filled properties are serialized,
 * properties with null value are skipped.
 *
 * @param configuration Correctly annotated configuration object
 * @return String of JSON representation
 *//* www .  ja v  a 2 s . c  o m*/
@SuppressWarnings("unchecked")
public static String toJson(Object configuration) {
    Class klass = configuration.getClass();
    Set<String> configNames = new HashSet<String>();
    ConfigurationClass configurationClass = (ConfigurationClass) klass.getAnnotation(ConfigurationClass.class);

    // Each configuration object must have this class annotation
    if (configurationClass == null) {
        throw new SqoopException(ModelError.MODEL_003,
                "Missing annotation ConfigurationGroup on class " + klass.getName());
    }

    JSONObject jsonOutput = new JSONObject();

    // Iterate over all declared fields
    for (Field configField : klass.getDeclaredFields()) {
        configField.setAccessible(true);

        // We're processing only config validations
        Config configAnnotation = configField.getAnnotation(Config.class);
        if (configAnnotation == null) {
            continue;
        }
        String configName = getConfigName(configField, configAnnotation, configNames);

        Object configValue;
        try {
            configValue = configField.get(configuration);
        } catch (IllegalAccessException e) {
            throw new SqoopException(ModelError.MODEL_005, "Issue with field " + configName, e);
        }

        JSONObject jsonConfig = new JSONObject();

        // Now process each input on the config
        for (Field inputField : configField.getType().getDeclaredFields()) {
            inputField.setAccessible(true);
            String inputName = inputField.getName();

            Object value;
            try {
                value = inputField.get(configValue);
            } catch (IllegalAccessException e) {
                throw new SqoopException(ModelError.MODEL_005,
                        "Issue with field " + configName + "." + inputName, e);
            }

            Input inputAnnotation = inputField.getAnnotation(Input.class);

            // Do not serialize all values
            if (inputAnnotation != null && value != null) {
                Class<?> type = inputField.getType();

                // We need to support NULL, so we do not support primitive types
                if (type.isPrimitive()) {
                    throw new SqoopException(ModelError.MODEL_007,
                            "Detected primitive type " + type + " for field " + configName + "." + inputName);
                }

                if (type == String.class) {
                    jsonConfig.put(inputName, value);
                } else if (type.isAssignableFrom(Map.class)) {
                    JSONObject map = new JSONObject();
                    for (Object key : ((Map) value).keySet()) {
                        map.put(key, ((Map) value).get(key));
                    }
                    jsonConfig.put(inputName, map);
                } else if (type == Integer.class) {
                    jsonConfig.put(inputName, value);
                } else if (type.isEnum()) {
                    jsonConfig.put(inputName, value.toString());
                } else if (type == Boolean.class) {
                    jsonConfig.put(inputName, value);
                } else {
                    throw new SqoopException(ModelError.MODEL_004, "Unsupported type " + type.getName()
                            + " for input " + configName + "." + inputName);
                }
            }
        }

        jsonOutput.put(configName, jsonConfig);
    }
    return jsonOutput.toJSONString();
}

From source file:org.hyperledger.fabric.sdk.Endpoint.java

private void addNettyBuilderProps(NettyChannelBuilder channelBuilder, Properties props)
        throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {

    if (props == null) {
        return;/*w ww .  ja v a2  s . c o  m*/
    }

    for (Map.Entry<?, ?> es : props.entrySet()) {
        Object methodprop = es.getKey();
        if (methodprop == null) {
            continue;
        }
        String methodprops = String.valueOf(methodprop);

        Matcher match = METHOD_PATTERN.matcher(methodprops);

        String methodName = null;

        if (match.matches() && match.groupCount() == 1) {
            methodName = match.group(1).trim();

        }
        if (null == methodName || "forAddress".equals(methodName) || "build".equals(methodName)) {

            continue;
        }

        Object parmsArrayO = es.getValue();
        Object[] parmsArray;
        if (!(parmsArrayO instanceof Object[])) {
            parmsArray = new Object[] { parmsArrayO };

        } else {
            parmsArray = (Object[]) parmsArrayO;
        }

        Class<?>[] classParms = new Class[parmsArray.length];
        int i = -1;
        for (Object oparm : parmsArray) {
            ++i;

            if (null == oparm) {
                classParms[i] = Object.class;
                continue;
            }

            Class<?> unwrapped = WRAPPERS_TO_PRIM.get(oparm.getClass());
            if (null != unwrapped) {
                classParms[i] = unwrapped;
            } else {

                Class<?> clz = oparm.getClass();

                Class<?> ecz = clz.getEnclosingClass();
                if (null != ecz && ecz.isEnum()) {
                    clz = ecz;
                }

                classParms[i] = clz;
            }
        }

        final Method method = channelBuilder.getClass().getMethod(methodName, classParms);

        method.invoke(channelBuilder, parmsArray);

        if (logger.isTraceEnabled()) {
            StringBuilder sb = new StringBuilder(200);
            String sep = "";
            for (Object p : parmsArray) {
                sb.append(sep).append(p + "");
                sep = ", ";

            }
            logger.trace(format("Endpoint with url: %s set managed channel builder method %s (%s) ", url,
                    method, sb.toString()));

        }

    }

}

From source file:com.github.helenusdriver.driver.impl.DataDecoder.java

/**
 * Gets a "set" to {@link Set} decoder based on the given element class.
 *
 * @author paouelle//from  w  ww  .  java 2  s  .co  m
 *
 * @param  eclazz the non-<code>null</code> class of elements
 * @param  mandatory if the field associated with the decoder is mandatory or
 *         represents a primary key
 * @return the non-<code>null</code> decoder for sets of the specified element
 *         class
 */
@SuppressWarnings("rawtypes")
public final static DataDecoder<Set> set(final Class<?> eclazz, final boolean mandatory) {
    return new DataDecoder<Set>(Set.class) {
        @SuppressWarnings("unchecked")
        private Set decodeImpl(Class<?> etype, Set<Object> set) {
            if (set == null) {
                // safe to return as is unless mandatory, that is because Cassandra
                // returns null for empty sets and the schema definition requires
                // that mandatory and primary keys be non null
                if (mandatory) {
                    if (eclazz.isEnum()) {
                        // for enum values we create an enum set. Now we won't preserve the order
                        // the entries were added but that should be fine anyways in this case
                        return EnumSet.noneOf((Class<? extends Enum>) eclazz);
                    }
                    return new LinkedHashSet(16); // to keep order
                }
                return set;
            }
            final Set nset;

            if (eclazz.isEnum()) {
                // for enum values we create an enum set. Now we won't preserve the order
                // the entries were added but that should be fine anyways in this case
                nset = EnumSet.noneOf((Class<? extends Enum>) eclazz);
            } else {
                nset = new LinkedHashSet(set.size()); // to keep order
            }
            if (eclazz.isAssignableFrom(etype)) {
                // we only need to store elements to make sure list is modifiable
                nset.addAll(set);
            } else {
                // will need to do some conversion of each element
                final ElementConverter converter = ElementConverter.getConverter(eclazz, etype);

                for (final Object o : set) {
                    nset.add((o != null) ? converter.convert(o) : null);
                }
            }
            return nset;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected Set decodeImpl(Row row, String name, Class clazz) {
            return decodeImpl(
                    // get the element type from the row's metadata
                    row.getColumnDefinitions().getType(name).getTypeArguments().get(0).getName().asJavaClass(),
                    row.isNull(name) ? null : row.getSet(name, Object.class) // keeps things generic so we can handle our own errors
            );
        }

        @SuppressWarnings("unchecked")
        @Override
        protected Set decodeImpl(UDTValue uval, String name, Class clazz) {
            return decodeImpl(
                    // get the element type from the row's metadata
                    uval.getType().getFieldType(name).getTypeArguments().get(0).getName().asJavaClass(),
                    uval.isNull(name) ? null : uval.getSet(name, Object.class) // keeps things generic so we can handle our own errors
            );
        }
    };
}

From source file:ca.oson.json.util.ObjectUtil.java

public static boolean isSameDataType(Class ftype, Class mtype) {
    if (ftype == null || mtype == null) {
        return false;
    }/*from  w ww  . j av  a 2  s  .c  o m*/

    if (mtype == java.lang.Integer.class) {
        if (ftype == int.class || ftype == byte.class || ftype == short.class || ftype == long.class
                || ftype == float.class || ftype == double.class || ftype == Integer.class
                || ftype == BigInteger.class || ftype == BigDecimal.class || ftype == Short.class
                || ftype == Byte.class || ftype == Long.class || ftype == Float.class || ftype == Double.class
                || ftype == AtomicInteger.class || ftype == AtomicLong.class || ftype.isEnum()
                || Date.class.isAssignableFrom(ftype)) {
            return true;
        }

    } else if (mtype == String.class) {
        if (ftype == String.class || ftype == char.class || ftype == Character.class || ftype == Date.class
                || ftype.isEnum()) {
            return true;
        }

    } else if (mtype == Boolean.class) {
        if (ftype == Boolean.class || ftype == boolean.class) {
            return true;
        }

    } else if (mtype == Double.class) {
        if (ftype == double.class || ftype == float.class || ftype == Float.class || ftype == Double.class) {
            return true;
        }

    } else if (mtype.isAssignableFrom(ftype) || ftype.isAssignableFrom(mtype)) {
        return true;
    }

    return false;
}