Example usage for java.lang Class getEnumConstants

List of usage examples for java.lang Class getEnumConstants

Introduction

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

Prototype

public T[] getEnumConstants() 

Source Link

Document

Returns the elements of this enum class or null if this Class object does not represent an enum type.

Usage

From source file:com.heliosphere.athena.base.resource.bundle.ResourceBundleManager.java

/**
 * Registers a resource bundle using a resource bundle enumeration class
 * (implementing the {@link IBundle} interface).
 * <p>/*from   w  w w  .  j  a  va  2 s. c  o m*/
 * @param bundleEnumClass Resource bundle enumeration class.
 */
@Synchronized
public static final void register(final Class<? extends IBundle> bundleEnumClass) {
    IBundle value = bundleEnumClass.getEnumConstants()[0]; // BUNDLE_FILENAME must be at index 0!
    if (value.toString().equals(BUNDLE_FILENAME)) {
        String filename = value.getKey();

        final ResourceBundle bundle = ResourceBundle.getBundle(filename, locale);

        // Ensure the loaded bundle is for the required language.
        if (bundle.getLocale().getISO3Language().equals(locale.getISO3Language())) {
            register(bundleEnumClass, bundle);
        } else {
            throw new ResourceBundleException(BundleAthenaBase.ResourceBundleError, filename, locale);
        }
    }
}

From source file:com.heliosphere.demeter.base.resource.bundle.ResourceBundleManager.java

/**
 * Registers a resource bundle using a resource bundle enumeration class
 * (implementing the {@link IBundle} interface).
 * <p>//from www .  j  av  a2s .c o  m
 * @param bundleEnumClass Resource bundle enumeration class.
 */
@Synchronized
public static final void register(final Class<? extends IBundle> bundleEnumClass) {
    IBundle value = bundleEnumClass.getEnumConstants()[0]; // BUNDLE_FILENAME must be at index 0!
    if (value.toString().equals(BUNDLE_FILENAME)) {
        String filename = value.getKey();

        final ResourceBundle bundle = ResourceBundle.getBundle(filename, locale);

        // Ensure the loaded bundle is for the required language.
        if (bundle.getLocale().getISO3Language().equals(locale.getISO3Language())) {
            register(bundleEnumClass, bundle);
        } else {
            throw new ResourceBundleException(BundleDemeterBase.ResourceBundleError, filename, locale);
        }
    }
}

From source file:org.jaffa.util.BeanHelper.java

/** Iterates through the defined constants for the input Enum class.
 * Returns the constant that matches the input value.
 * @param enumClass The Enum class.//from w  w  w.j av  a 2 s  .  co m
 * @param value The value whose corresponding Enum constant is to be returned.
 * @return the Enum constant that matches the input value. A null is returned if no match is found or if the input class is not an Enum.
 */
private static Object findEnum(Class enumClass, String value) {
    if (enumClass.isEnum()) {
        Object[] enumConstants = enumClass.getEnumConstants();
        if (enumConstants != null) {
            for (Object enumConstant : enumConstants) {
                if (enumConstant.toString().equals(value))
                    return enumConstant;
            }
        }
    }
    return null;
}

From source file:com.sparkplatform.api.core.PropertyAsserter.java

/**
 * See {@link #assertBasicGetterSetterBehavior(Object,String)} method. Only difference is that here we accept an
 * explicit argument for the setter method.
 *
 * @param target   the object on which to invoke the getter and setter
 * @param property the property name, e.g. "firstName"
 * @param argument the property value, i.e. the value the setter will be invoked with
 *//* w w w .  j a  va2  s  .  co m*/
public static void assertBasicGetterSetterBehavior(Object target, String property, Object argument) {
    try {
        PropertyDescriptor descriptor = new PropertyDescriptor(property, target.getClass());
        Object arg = argument;
        Class type = descriptor.getPropertyType();
        if (arg == null) {
            if (type.isArray()) {
                arg = Array.newInstance(type.getComponentType(), new int[] { TEST_ARRAY_SIZE });
            } else if (type.isEnum()) {
                arg = type.getEnumConstants()[0];
            } else if (TYPE_ARGUMENTS.containsKey(type)) {
                arg = TYPE_ARGUMENTS.get(type);
            } else {
                arg = invokeDefaultConstructorEvenIfPrivate(type);
            }
        }

        Method writeMethod = descriptor.getWriteMethod();
        Method readMethod = descriptor.getReadMethod();

        writeMethod.invoke(target, arg);
        Object propertyValue = readMethod.invoke(target);
        if (type.isPrimitive()) {
            assertEquals(property + " getter/setter failed test", arg, propertyValue);
        } else {
            assertSame(property + " getter/setter failed test", arg, propertyValue);
        }
    } catch (IntrospectionException e) {
        String msg = "Error creating PropertyDescriptor for property [" + property
                + "]. Do you have a getter and a setter?";
        log.error(msg, e);
        fail(msg);
    } catch (IllegalAccessException e) {
        String msg = "Error accessing property. Are the getter and setter both accessible?";
        log.error(msg, e);
        fail(msg);
    } catch (InvocationTargetException e) {
        String msg = "Error invoking method on target";
        log.error(msg, e);
        fail(msg);
    }
}

From source file:edu.usu.sdl.openstorefront.doc.EntityProcessor.java

private static void addFields(Class entity, EntityDocModel docModel) {
    if (entity != null) {
        Field[] fields = entity.getDeclaredFields();
        for (Field field : fields) {
            //Skip static field
            if ((Modifier.isStatic(field.getModifiers()) && Modifier.isFinal(field.getModifiers())) == false) {

                EntityFieldModel fieldModel = new EntityFieldModel();
                fieldModel.setName(field.getName());
                fieldModel.setType(field.getType().getSimpleName());
                fieldModel.setOriginClass(entity.getSimpleName());
                fieldModel.setEmbeddedType(ReflectionUtil.isComplexClass(field.getType()));
                if (ReflectionUtil.isCollectionClass(field.getType())) {
                    DataType dataType = (DataType) field.getAnnotation(DataType.class);
                    if (dataType != null) {
                        String typeClass = dataType.value().getSimpleName();
                        if (StringUtils.isNotBlank(dataType.actualClassName())) {
                            typeClass = dataType.actualClassName();
                        }//from   w  w w . j  a  v a 2s  .  co m
                        fieldModel.setGenericType(typeClass);
                    }
                }

                APIDescription description = (APIDescription) field.getAnnotation(APIDescription.class);
                if (description != null) {
                    fieldModel.setDescription(description.value());
                }

                for (Annotation annotation : field.getAnnotations()) {
                    if (annotation.annotationType().getName().equals(APIDescription.class.getName()) == false) {
                        EntityConstraintModel entityConstraintModel = new EntityConstraintModel();
                        entityConstraintModel.setName(annotation.annotationType().getSimpleName());

                        APIDescription annotationDescription = (APIDescription) annotation.annotationType()
                                .getAnnotation(APIDescription.class);
                        if (annotationDescription != null) {
                            entityConstraintModel.setDescription(annotationDescription.value());
                        }

                        //rules
                        Object annObj = field.getAnnotation(annotation.annotationType());
                        if (annObj instanceof NotNull) {
                            entityConstraintModel.setRules("Field is required");
                        } else if (annObj instanceof PK) {
                            PK pk = (PK) annObj;
                            entityConstraintModel.setRules("<b>Generated:</b> " + pk.generated());
                            fieldModel.setPrimaryKey(true);
                        } else if (annObj instanceof FK) {
                            FK fk = (FK) annObj;

                            StringBuilder sb = new StringBuilder();
                            sb.append("<b>Foreign Key:</b> ").append(fk.value().getSimpleName());
                            sb.append(" (<b>Enforce</b>: ").append(fk.enforce());
                            sb.append(" <b>Soft reference</b>: ").append(fk.softReference());
                            if (StringUtils.isNotBlank(fk.referencedField())) {
                                sb.append(" <b>Reference Field</b>: ").append(fk.referencedField());
                            }
                            sb.append(" )");
                            entityConstraintModel.setRules(sb.toString());
                        } else if (annObj instanceof ConsumeField) {
                            entityConstraintModel.setRules("");
                        } else if (annObj instanceof Size) {
                            Size size = (Size) annObj;
                            entityConstraintModel
                                    .setRules("<b>Min:</b> " + size.min() + " <b>Max:</b> " + size.max());
                        } else if (annObj instanceof Pattern) {
                            Pattern pattern = (Pattern) annObj;
                            entityConstraintModel.setRules("<b>Pattern:</b> " + pattern.regexp());
                        } else if (annObj instanceof Sanitize) {
                            Sanitize sanitize = (Sanitize) annObj;
                            entityConstraintModel
                                    .setRules("<b>Sanitize:</b> " + sanitize.value().getSimpleName());
                        } else if (annObj instanceof Unique) {
                            Unique unique = (Unique) annObj;
                            entityConstraintModel.setRules("<b>Handler:</b> " + unique.value().getSimpleName());
                        } else if (annObj instanceof ValidValueType) {
                            ValidValueType validValueType = (ValidValueType) annObj;
                            StringBuilder sb = new StringBuilder();
                            if (validValueType.value().length > 0) {
                                sb.append(" <b>Values:</b> ").append(Arrays.toString(validValueType.value()));
                            }

                            if (validValueType.lookupClass().length > 0) {
                                sb.append(" <b>Lookups:</b> ");
                                for (Class lookupClass : validValueType.lookupClass()) {
                                    sb.append(lookupClass.getSimpleName()).append("  ");
                                }
                            }

                            if (validValueType.enumClass().length > 0) {
                                sb.append(" <b>Enumerations:</b> ");
                                for (Class enumClass : validValueType.enumClass()) {
                                    sb.append(enumClass.getSimpleName()).append("  (");
                                    sb.append(Arrays.toString(enumClass.getEnumConstants())).append(")");
                                }
                            }

                            entityConstraintModel.setRules(sb.toString());
                        } else if (annObj instanceof Min) {
                            Min min = (Min) annObj;
                            entityConstraintModel.setRules("<b>Min value:</b> " + min.value());
                        } else if (annObj instanceof Max) {
                            Max max = (Max) annObj;
                            entityConstraintModel.setRules("<b>Max value:</b> " + max.value());
                        } else if (annObj instanceof Version) {
                            entityConstraintModel.setRules("Entity version; For Multi-Version control");
                        } else if (annObj instanceof DataType) {
                            DataType dataType = (DataType) annObj;
                            String typeClass = dataType.value().getSimpleName();
                            if (StringUtils.isNotBlank(dataType.actualClassName())) {
                                typeClass = dataType.actualClassName();
                            }
                            entityConstraintModel.setRules("<b>Type:</b> " + typeClass);
                        } else {
                            entityConstraintModel.setRules(annotation.toString());
                        }

                        //Annotations that have related classes
                        if (annObj instanceof DataType) {
                            DataType dataType = (DataType) annObj;
                            entityConstraintModel.getRelatedClasses().add(dataType.value().getSimpleName());
                        }
                        if (annObj instanceof FK) {
                            FK fk = (FK) annObj;
                            entityConstraintModel.getRelatedClasses().add(fk.value().getSimpleName());
                        }
                        if (annObj instanceof ValidValueType) {
                            ValidValueType validValueType = (ValidValueType) annObj;
                            for (Class lookupClass : validValueType.lookupClass()) {
                                entityConstraintModel.getRelatedClasses().add(lookupClass.getSimpleName());
                            }

                            StringBuilder sb = new StringBuilder();
                            for (Class enumClass : validValueType.enumClass()) {
                                sb.append("<br>");
                                sb.append(enumClass.getSimpleName()).append(":  (");
                                sb.append(Arrays.toString(enumClass.getEnumConstants())).append(")");
                            }
                            entityConstraintModel
                                    .setRules(entityConstraintModel.getRules() + " " + sb.toString());
                        }

                        fieldModel.getConstraints().add(entityConstraintModel);
                    }
                }

                docModel.getFieldModels().add(fieldModel);
            }
        }
        addFields(entity.getSuperclass(), docModel);
    }
}

From source file:com.evolveum.midpoint.repo.sql.util.RUtil.java

public static <T extends SchemaEnum> T getRepoEnumValue(Object object, Class<T> type) {
    if (object == null) {
        return null;
    }//from ww  w . j  a  v a 2s  .c  om
    Object[] values = type.getEnumConstants();
    for (Object value : values) {
        T schemaEnum = (T) value;
        if (schemaEnum.getSchemaValue().equals(object)) {
            return schemaEnum;
        }
    }

    throw new IllegalArgumentException("Unknown value '" + object + "' of type '" + object.getClass()
            + "', can't translate to '" + type + "'.");
}

From source file:com.bjond.utilities.MiscUtils.java

public static <T extends Enum<T>> T parseEnumCaseInsensitive(Class<T> enumType, String s) {
    if (s == null)
        return null;

    for (val v : enumType.getEnumConstants()) {
        if (v.name().compareToIgnoreCase(s) == 0)
            return v;
    }//from   w ww  . j  av a  2  s .c  o  m
    return null;
}

From source file:io.apiman.manager.api.es.EsMarshallingTest.java

/**
 * Populate the given set with one or two items of the given type.
 * @param collection/*from ww w  .j a v  a  2  s.  com*/
 * @param typeClass
 */
private static void populateSet(Set collection, Class<?> typeClass)
        throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException,
        SecurityException, ClassNotFoundException {
    if (typeClass.isEnum()) {
        collection.add(typeClass.getEnumConstants()[0]);
        collection.add(typeClass.getEnumConstants()[1]);
    } else if (typeClass == String.class) {
        collection.add("VALUE_1");
        collection.add("VALUE_2");
    } else if (typeClass.getPackage().getName().startsWith("io.apiman.manager.api.beans")) {
        Object bean1 = createBean(typeClass);
        Object bean2 = createBean(typeClass);
        collection.add(bean1);
        collection.add(bean2);
    } else {
        throw new IllegalAccessException("Failed to populate Set of type: " + typeClass.getSimpleName());
    }
}

From source file:org.openhab.io.neeo.internal.NeeoUtil.java

/**
 * Gets the {@link Command} for the specified enum name - ignoring case
 *
 * @param cmd      the non-null {@link Command}
 * @param enumName the non-empty enum name to search for
 * @return the {@link Command} or null if not found (or null if cmd's class is not an enum)
 *///  w  w w .  j av  a2 s .  c om
@Nullable
static Command getEnum(Class<? extends Command> cmd, String enumName) {
    Objects.requireNonNull(cmd, "cmd cannot be null");
    requireNotEmpty(enumName, "enumName cannot be null");

    if (cmd.isEnum()) {
        for (Command cmdEnum : cmd.getEnumConstants()) {
            if (StringUtils.equalsIgnoreCase(((Enum<?>) cmdEnum).name(), enumName)) {
                return cmdEnum;
            }
        }
    }
    return null;
}

From source file:och.util.Util.java

public static <T extends Enum<T>> T tryGetEnumByCode(Integer code, Class<T> enumType, T defaultVal) {
    if (code == null)
        return defaultVal;
    try {/*  www. ja va 2s .  co m*/
        for (T c : enumType.getEnumConstants()) {
            int curCode = ((och.util.model.HasIntCode) c).getCode();
            if (curCode == code)
                return c;
        }
        return defaultVal;
    } catch (Exception e) {
        return defaultVal;
    }
}