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:org.openmrs.web.taglib.FieldGenTag.java

@SuppressWarnings("unchecked")
public int doStartTag() throws JspException {

    if (type == null) {
        type = "";
    }//from  ww  w  .ja v a 2  s.c o m
    if (formFieldName == null) {
        formFieldName = "";
    }

    if (formFieldName.length() > 0) {
        FieldGenHandler handler = getHandlerByClassName(type);
        if (handler != null) {
            handler.setFieldGenTag(this);
            handler.run();
        } else {
            StringBuilder output = new StringBuilder(
                    "Cannot handle type [" + type + "]. Please add a module to handle this type.");

            if (type.equals("char") || type.indexOf("java.lang.Character") >= 0) {
                String startVal = "";
                if (val != null) {
                    startVal = val.toString();
                }
                if (startVal.length() > 1) {
                    startVal = startVal.substring(0, 1);
                }
                String fieldLength = this.parameterMap != null ? (String) this.parameterMap.get("fieldLength")
                        : null;
                fieldLength = (fieldLength == null) ? DEFAULT_INPUT_CHAR_LENGTH : fieldLength;
                output.setLength(0);
                output.append("<input type=\"text\" name=\"").append(formFieldName).append("\" id=\"")
                        .append(formFieldName).append("\" value=\"");
                output.append(startVal).append("\" size=\"").append(fieldLength)
                        .append("\" maxlength=\"1\" />");
            } else if (type.equals("int") || type.indexOf("java.lang.Integer") >= 0 || type.equals("long")
                    || type.indexOf("java.lang.Long") >= 0) {
                String startVal = "";
                if (val != null) {
                    startVal = val.toString();
                }
                String fieldLength = this.parameterMap != null ? (String) this.parameterMap.get("fieldLength")
                        : null;
                fieldLength = (fieldLength == null) ? DEFAULT_INPUT_INT_LENGTH : fieldLength;
                output.setLength(0);
                output.append("<input type=\"text\" name=\"").append(formFieldName).append("\" id=\"")
                        .append(formFieldName).append("\" value=\"");
                output.append(startVal).append("\" size=\"").append(fieldLength).append("\" />");
            } else if (type.equals("float") || type.indexOf("java.lang.Float") >= 0 || type.equals("double")
                    || type.indexOf("java.lang.Double") >= 0 || type.indexOf("java.lang.Number") >= 0) {
                String startVal = "";
                if (val != null) {
                    startVal = val.toString();
                }

                String fieldLength = this.parameterMap != null ? (String) this.parameterMap.get("fieldLength")
                        : null;
                fieldLength = (fieldLength == null) ? DEFAULT_INPUT_FLOAT_LENGTH : fieldLength;
                output.setLength(0);
                output.append("<input type=\"text\" name=\"").append(formFieldName).append("\" id=\"")
                        .append(formFieldName).append("\" value=\"");
                output.append(startVal).append("\" size=\"").append(fieldLength).append("\" />");
            } else if (type.equals("boolean") || type.indexOf("java.lang.Boolean") >= 0) {
                String startVal = "";
                if (val != null) {
                    startVal = val.toString();
                }
                startVal = (startVal == null) ? "" : startVal.toLowerCase();
                if ("false".equals(startVal) || "0".equals(startVal)) {
                    startVal = "false";
                }
                if ("true".equals(startVal) || "1".equals(startVal)) {
                    startVal = "true";
                }
                if ("unknown".equals(startVal) || "?".equals(startVal)) {
                    startVal = "unknown";
                }

                String forceInputType = this.parameterMap != null
                        ? (String) this.parameterMap.get("forceInputType")
                        : null;
                String isNullable = this.parameterMap != null ? (String) this.parameterMap.get("isNullable")
                        : null;
                String trueLabel = this.parameterMap != null ? (String) this.parameterMap.get("trueLabel")
                        : null;
                String falseLabel = this.parameterMap != null ? (String) this.parameterMap.get("falseLabel")
                        : null;
                String unknownLabel = this.parameterMap != null ? (String) this.parameterMap.get("unknownLabel")
                        : null;

                if (forceInputType == null) {
                    forceInputType = "";
                }

                if ("checkbox".equals(forceInputType)) {
                    output.setLength(0);
                    output.append("<input type=\"checkbox\" name=\"").append(formFieldName).append("\" id=\"")
                            .append(formFieldName);
                    output.append("\" value=\"true\"").append(("true".equals(startVal) ? " checked" : ""))
                            .append("/> ");
                } else {
                    if (isNullable == null) {
                        isNullable = "";
                    }
                    if (trueLabel == null) {
                        trueLabel = Context.getMessageSourceService().getMessage("general.yes");
                    }
                    if (falseLabel == null) {
                        falseLabel = Context.getMessageSourceService().getMessage("general.no");
                    }
                    if (unknownLabel == null) {
                        unknownLabel = Context.getMessageSourceService().getMessage("general.unknown");
                    }

                    if ("false".equalsIgnoreCase(isNullable) || "f".equalsIgnoreCase(isNullable)
                            || "0".equals(isNullable)) {
                        output.setLength(0);
                        output.append("<input type=\"radio\" name=\"").append(formFieldName).append("\" id=\"")
                                .append(formFieldName);
                        output.append("_f\" value=\"false\"")
                                .append(("false".equals(startVal) ? " checked" : "")).append("/> ");
                        output.append(falseLabel);
                        output.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
                        output.append("<input type=\"radio\" name=\"").append(formFieldName).append("\" id=\"")
                                .append(formFieldName);
                        output.append("_t\" value=\"true\"").append(("true".equals(startVal) ? " checked" : ""))
                                .append("/> ");
                        output.append(trueLabel);
                    } else {
                        output.setLength(0);
                        output.append("<input type=\"radio\" name=\"").append(formFieldName).append("\" id=\"")
                                .append(formFieldName);
                        output.append("_f\" value=\"false\"")
                                .append(("false".equals(startVal) ? " checked" : "")).append("/> ");
                        output.append(falseLabel);
                        output.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
                        output.append("<input type=\"radio\" name=\"").append(formFieldName).append("\" id=\"")
                                .append(formFieldName);
                        output.append("_t\" value=\"true\"").append(("true".equals(startVal) ? " checked" : ""))
                                .append("/> ");
                        output.append(trueLabel);
                        output.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
                        output.append("<input type=\"radio\" name=\"").append(formFieldName).append("\" id=\"")
                                .append(formFieldName);
                        output.append("_u\" value=\"unknown\"")
                                .append(("unknown".equals(startVal) ? " checked" : "")).append("/> ");
                        output.append(unknownLabel);
                    }
                }
            } else if (type.indexOf("$") >= 0) {
                // this could be an enum - if so, let's display it
                String className = type;

                Class cls = null;
                try {
                    cls = Class.forName(className);
                } catch (Exception e) {
                    cls = null;
                    log.error("Could not instantiate class for this enum of class name [" + className
                            + "] in FieldGenTag");
                }

                if (cls != null && cls.isEnum()) {
                    Object[] enumConstants = cls.getEnumConstants();

                    if (enumConstants != null && enumConstants.length > 0) {
                        String startVal = "";
                        if (val != null) {
                            startVal = val.toString();
                        }
                        log.debug("val is " + val);
                        log.debug("val.toString is " + startVal);
                        if (startVal == null) {
                            startVal = "";
                        }
                        output.setLength(0);
                        output.append("<select name=\"").append(formFieldName).append("\" id=\"")
                                .append(formFieldName).append("\">");
                        StringBuilder options = new StringBuilder();
                        for (int i = 0; i < enumConstants.length; i++) {
                            options.append("<option value=\"").append(enumConstants[i].toString()).append("\"")
                                    .append(startVal.equals(enumConstants[i].toString()) ? " selected" : "")
                                    .append(">").append(enumConstants[i].toString()).append("</option>");
                        }
                        output.append(options.toString());
                        output.append("</select> ");
                    }
                }
            } else if (type.equals("dropDownList")) {

                String startVal = "";
                if (val != null) {
                    startVal = StringEscapeUtils.escapeHtml(val.toString());
                }

                String items = this.parameterMap != null ? (String) this.parameterMap.get("items") : null;

                output.setLength(0);
                output.append("<select name=\"").append(formFieldName).append("\" id=\"").append(formFieldName)
                        .append("\">");

                if (items != null && !items.isEmpty()) {
                    StringBuilder options = new StringBuilder();
                    for (String item : items.split(",")) {
                        String escapedItem = StringEscapeUtils.escapeHtml(item);
                        escapedItem = StringEscapeUtils.escapeJavaScript(escapedItem);
                        options.append("<option value=\"").append(escapedItem).append("\"")
                                .append(startVal.equals(escapedItem) ? " selected" : "").append(">")
                                .append(escapedItem).append("</option>");
                    }
                    output.append(options.toString());
                }

                output.append("</select> ");
            } // end checking different built-in types

            try {
                pageContext.getOut().write(output.toString());
            } catch (IOException e) {
                log.error(e);
            }
        }
    }

    if (url == null) {
        url = "default.field";
    }

    // all fieldGens are contained in the /WEB-INF/view/fieldGen/ folder and end with .field
    if (!url.endsWith("field")) {
        url += ".field";
    }
    url = "/fieldGen/" + url;

    // add attrs to request so that the controller (and field jsp) can see/use them
    pageContext.getRequest().setAttribute("org.openmrs.fieldGen.type", type);
    pageContext.getRequest().setAttribute("org.openmrs.fieldGen.formFieldName", formFieldName);
    pageContext.getRequest().setAttribute("org.openmrs.fieldGen.parameters",
            OpenmrsUtil.parseParameterList(parameters));
    Map<String, Object> hmParamMap = (Map<String, Object>) pageContext.getRequest()
            .getAttribute("org.openmrs.fieldGen.parameterMap");
    if (hmParamMap == null) {
        hmParamMap = new HashMap<String, Object>();
    }
    if (this.parameterMap != null) {
        hmParamMap.putAll(this.parameterMap);
    }
    pageContext.getRequest().setAttribute("org.openmrs.fieldGen.parameterMap", hmParamMap);

    pageContext.getRequest().setAttribute("org.openmrs.fieldGen.object", val);
    pageContext.getRequest().setAttribute("org.openmrs.fieldGen.request", pageContext.getRequest());

    try {
        pageContext.include(this.url);
    } catch (ServletException e) {
        log.error("ServletException while trying to include a file in FieldGenTag", e);
    } catch (IOException e) {
        log.error("IOException while trying to include a file in FieldGenTag", e);
    }

    /*
    log.debug("FieldGenTag has reqest of " + pageContext.getRequest().toString());
    pageContext.getRequest().setAttribute("javax.servlet.include.servlet_path.fieldGen", url);
    FieldGenController fgc = new FieldGenController();
    try {
       fgc.handleRequest((HttpServletRequest)pageContext.getRequest(), (HttpServletResponse)pageContext.getResponse());
    } catch (ServletException e) {
       log.error("ServletException while attempting to pass control to FieldGenController in FieldGenTag");
    } catch (IOException e) {
       log.error("IOException while attempting to pass control to FieldGenController in FieldGenTag");
    }
    */

    resetValues();

    return SKIP_BODY;
}

From source file:org.opendaylight.controller.sal.restconf.impl.RestconfImpl.java

private <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
    final T[] enumConstants = classDescriptor.getEnumConstants();
    if (enumConstants != null) {
        for (final T enm : classDescriptor.getEnumConstants()) {
            if (((Enum<?>) enm).name().equals(value)) {
                return enm;
            }/*from w  w w .  j  a v a  2s.  c  o m*/
        }
    }
    return null;
}

From source file:com.medigy.persist.model.data.EntitySeedDataPopulator.java

public void populateEntityCacheData() throws HibernateException {

    Iterator itr = null;/*from w  w  w  .  j a  v a  2 s. co m*/
    if (!useEjb)
        itr = configuration.getClassMappings();
    else
        itr = ejb3Configuration.getClassMappings();

    while (itr.hasNext()) {
        Class entityClass = ((PersistentClass) itr.next()).getMappedClass(); //(Class) classMappings.next();
        log.warn(entityClass.getName());
        if (!Entity.class.isAssignableFrom(entityClass))
            continue;

        Class[] innerClasses = entityClass.getDeclaredClasses();
        for (Class innerClass : innerClasses) {
            // TODO: assume that this is the inner CACHE class !???!!! maybe make Cache extend an interface to indicate this??
            if (innerClass.isEnum() && !entityClass.equals(Party.class)) {
                try {
                    final BeanInfo beanInfo = Introspector.getBeanInfo(entityClass);
                    final PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
                    final Hashtable pdsByName = new Hashtable();
                    for (int i = 0; i < descriptors.length; i++) {
                        final PropertyDescriptor descriptor = descriptors[i];
                        if (descriptor.getWriteMethod() != null)
                            pdsByName.put(descriptor.getReadMethod().getName(), descriptor.getWriteMethod());
                    }

                    Object[] enumObjects = innerClass.getEnumConstants();
                    // now match the enum methods with the enclosing class' methods
                    for (Object enumObj : enumObjects) {
                        Object entityObj = entityClass.newInstance();
                        final Method[] enumMethods = enumObj.getClass().getMethods();
                        for (Method enumMethod : enumMethods) {
                            final Method writeMethod = (Method) pdsByName.get(enumMethod.getName());
                            if (writeMethod != null) {
                                writeMethod.invoke(entityObj, enumMethod.invoke(enumObj));
                            }
                        }
                        HibernateUtil.getSession().save(entityObj);
                    }
                } catch (IntrospectionException e) {
                    log.error(e);
                } catch (IllegalAccessException e) {
                    log.error(e);
                } catch (InstantiationException e) {
                    log.error(e);
                } catch (InvocationTargetException e) {
                    log.error(e);
                } catch (HibernateException e) {
                    log.error(e);
                }
            }
        }
    }
}

From source file:org.rhq.scripting.javascript.JavascriptCompletor.java

/**
 * Look through all available contexts to find bindings that both start with
 * the supplied start and match the typeFilter.
 * @param start// w  w  w  .ja  va 2s.co m
 * @param typeFilter
 * @return
 */
private Map<String, Object> getContextMatches(String start, Class<?> typeFilter) {
    Map<String, Object> found = new HashMap<String, Object>();
    if (context != null) {
        for (int scope : context.getScopes()) {
            Bindings bindings = context.getBindings(scope);
            for (String var : bindings.keySet()) {
                if (var.startsWith(start)) {

                    if ((bindings.get(var) != null && typeFilter.isAssignableFrom(bindings.get(var).getClass()))
                            || recomplete == 3) {
                        found.put(var, bindings.get(var));
                    }
                }
            }
        }

        if (typeFilter.isEnum()) {
            for (Object ec : typeFilter.getEnumConstants()) {
                Enum<?> e = (Enum<?>) ec;
                String code = typeFilter.getSimpleName() + "." + e.name();
                if (code.startsWith(start)) {
                    found.put(typeFilter.getSimpleName() + "." + e.name(), e);
                }
            }
        }
    }
    return found;
}

From source file:com.gatf.generator.core.GatfTestGeneratorMojo.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private Object getObject(Class claz, List<Type> heirarchies) throws Exception {

    if (claz.isEnum())
        return claz.getEnumConstants()[0];

    if (isMap(claz)) {
        return getMapValue(claz, claz.getTypeParameters(), heirarchies);
    } else if (isCollection(claz)) {
        return getListSetValue(claz, claz.getTypeParameters(), heirarchies);
    } else if (claz.isInterface() || Modifier.isAbstract(claz.getModifiers())) {
        return null;
    }/*from  w w w.  j a  v a 2 s  .  c  o  m*/

    if (heirarchies.contains(claz) || heirarchies.size() >= 2)
        return null;
    heirarchies.add(claz);

    Constructor cons = null;
    try {
        cons = claz.getConstructor(new Class[] {});
    } catch (Exception e) {
        getLog().error("No public no-args constructor found for class " + claz.getName());
        return null;
    }

    Object object = cons.newInstance(new Object[] {});
    List<Field> allFields = getAllFields(claz);

    for (Field field : allFields) {

        if (Modifier.isStatic(field.getModifiers()))
            continue;

        if (!field.isAccessible()) {
            field.setAccessible(true);
        }

        List<Type> fheirlst = new ArrayList<Type>(heirarchies);

        if (isDebugEnabled())
            getLog().info("Parsing Class " + getHeirarchyStr(fheirlst) + " field " + field.getName() + " type "
                    + field.getType().equals(boolean.class));

        if (isPrimitive(field.getType())) {
            field.set(object, getPrimitiveValue(field.getType()));
        } else if (isMap(field.getType())) {
            ParameterizedType type = (ParameterizedType) field.getGenericType();
            field.set(object, getMapValue(field.getType(), type.getActualTypeArguments(), fheirlst));
        } else if (isCollection(field.getType())) {
            ParameterizedType type = (ParameterizedType) field.getGenericType();
            field.set(object, getListSetValue(field.getType(), type.getActualTypeArguments(), fheirlst));
        } else if (!claz.equals(field.getType())) {
            Object fieldval = getObject(field.getType(), fheirlst);
            field.set(object, fieldval);
        } else if (claz.equals(field.getType())) {
            if (isDebugEnabled())
                getLog().info("Ignoring recursive fields...");
        }
    }
    return object;
}

From source file:org.janusgraph.diskstorage.configuration.backend.CommonsConfiguration.java

@Override
public <O> O get(String key, Class<O> datatype) {
    if (!config.containsKey(key))
        return null;

    if (datatype.isArray()) {
        Preconditions.checkArgument(datatype.getComponentType() == String.class,
                "Only string arrays are supported: %s", datatype);
        return (O) config.getStringArray(key);
    } else if (Number.class.isAssignableFrom(datatype)) {
        // A properties file configuration returns Strings even for numeric
        // values small enough to fit inside Integer (e.g. 5000). In-memory
        // configuration impls seem to be able to store and return actual
        // numeric types rather than String
        ////from   ww  w  .  j ava2 s .  com
        // We try to handle either case here
        Object o = config.getProperty(key);
        if (datatype.isInstance(o)) {
            return (O) o;
        } else {
            return constructFromStringArgument(datatype, o.toString());
        }
    } else if (datatype == String.class) {
        return (O) config.getString(key);
    } else if (datatype == Boolean.class) {
        return (O) new Boolean(config.getBoolean(key));
    } else if (datatype.isEnum()) {
        Enum[] constants = (Enum[]) datatype.getEnumConstants();
        Preconditions.checkState(null != constants && 0 < constants.length, "Zero-length or undefined enum");

        String estr = config.getProperty(key).toString();
        for (Enum ec : constants)
            if (ec.toString().equals(estr))
                return (O) ec;
        throw new IllegalArgumentException("No match for string \"" + estr + "\" in enum " + datatype);
    } else if (datatype == Object.class) {
        return (O) config.getProperty(key);
    } else if (Duration.class.isAssignableFrom(datatype)) {
        // This is a conceptual leak; the config layer should ideally only handle standard library types
        Object o = config.getProperty(key);
        if (Duration.class.isInstance(o)) {
            return (O) o;
        } else {
            String[] comps = o.toString().split("\\s");
            TemporalUnit unit = null;
            if (comps.length == 1) {
                //By default, times are in milli seconds
                unit = ChronoUnit.MILLIS;
            } else if (comps.length == 2) {
                unit = Durations.parse(comps[1]);
            } else {
                throw new IllegalArgumentException("Cannot parse time duration from: " + o.toString());
            }
            return (O) Duration.of(Long.valueOf(comps[0]), unit);
        }
        // Lists are deliberately not supported.  List's generic parameter
        // is subject to erasure and can't be checked at runtime.  Someone
        // could create a ConfigOption<List<Number>>; we would instead return
        // a List<String> like we always do at runtime, and it wouldn't break
        // until the client tried to use the contents of the list.
        //
        // We could theoretically get around this by adding a type token to
        // every declaration of a List-typed ConfigOption, but it's just
        // not worth doing since we only actually use String[] anyway.
        //        } else if (List.class.isAssignableFrom(datatype)) {
        //            return (O) config.getProperty(key);
    } else
        throw new IllegalArgumentException("Unsupported data type: " + datatype);
}

From source file:com.evolveum.openicf.lotus.DominoConnector.java

private Set<AttributeInfo> createAttributes(Class<? extends DominoAttribute> type) {
    Set<AttributeInfo> infos = new HashSet<AttributeInfo>();
    for (DominoAttribute attr : type.getEnumConstants()) {
        if (attr.getAttribute() != null) {
            infos.add(attr.getAttribute());
        } else {/*from w  w w  .  ja  va2  s.  c  o m*/
            infos.add(AttributeInfoBuilder.build(attr.getName(), attr.getType(), attr.getFlags()));
        }
    }

    return infos;
}

From source file:net.firejack.platform.model.service.reverse.ReverseEngineeringService.java

private FieldModel createField(String name, Class type, boolean required, EntityModel entityModel) {
    FieldModel fieldModel = new FieldModel();
    fieldModel.setName(StringUtils.uncapitalize(name));
    fieldModel.setPath(entityModel.getLookup());
    fieldModel.setLookup(DiffUtils.lookup(entityModel.getLookup(), name));
    fieldModel.setDisplayName(StringUtils.capitalize(name));
    fieldModel.setRequired(required);/*from   w w  w . ja v a 2  s .  c  om*/
    fieldModel.setParent(entityModel);

    if (type.isEnum()) {
        Enum[] enumConstants = (Enum[]) type.getEnumConstants();
        fieldModel.setFieldType(LONG_TEXT);
        AllowedFieldValueList valueList = new AllowedFieldValueList();
        for (Enum enumConstant : enumConstants)
            valueList.add(enumConstant.name());
        fieldModel.setAllowedFieldValueList(valueList);
    } else {
        fieldModel.setFieldType(convert(type));
    }

    return fieldModel;
}

From source file:com.vmware.photon.controller.deployer.helpers.TestHelper.java

public static Object[][] getInvalidStageTransitions(@Nullable Class<? extends Enum> subStages) {

    if (subStages == null) {

        ////from  w  ww . j a v  a  2s. c  om
        // N.B. Tasks without sub-stages must reject these default stage transitions.
        //

        return new Object[][] { { TaskState.TaskStage.CREATED, TaskState.TaskStage.CREATED },
                { TaskState.TaskStage.STARTED, TaskState.TaskStage.CREATED },
                { TaskState.TaskStage.FINISHED, TaskState.TaskStage.CREATED },
                { TaskState.TaskStage.FINISHED, TaskState.TaskStage.STARTED },
                { TaskState.TaskStage.FINISHED, TaskState.TaskStage.FINISHED },
                { TaskState.TaskStage.FINISHED, TaskState.TaskStage.FAILED },
                { TaskState.TaskStage.FINISHED, TaskState.TaskStage.CANCELLED },
                { TaskState.TaskStage.FAILED, TaskState.TaskStage.CREATED },
                { TaskState.TaskStage.FAILED, TaskState.TaskStage.STARTED },
                { TaskState.TaskStage.FAILED, TaskState.TaskStage.FINISHED },
                { TaskState.TaskStage.FAILED, TaskState.TaskStage.FAILED },
                { TaskState.TaskStage.FAILED, TaskState.TaskStage.CANCELLED },
                { TaskState.TaskStage.CANCELLED, TaskState.TaskStage.CREATED },
                { TaskState.TaskStage.CANCELLED, TaskState.TaskStage.STARTED },
                { TaskState.TaskStage.CANCELLED, TaskState.TaskStage.FINISHED },
                { TaskState.TaskStage.CANCELLED, TaskState.TaskStage.FAILED },
                { TaskState.TaskStage.CANCELLED, TaskState.TaskStage.CANCELLED }, };
    }

    if (!subStages.isEnum() || subStages.getEnumConstants().length == 0) {
        throw new IllegalStateException("Class " + subStages.getName() + " is not a valid enum");
    }

    List<Object[]> invalidStageTransitions = new ArrayList<>();
    invalidStageTransitions
            .add(new Object[] { TaskState.TaskStage.CREATED, null, TaskState.TaskStage.CREATED, null });

    Enum[] enumConstants = subStages.getEnumConstants();
    for (int i = 0; i < enumConstants.length; i++) {
        invalidStageTransitions.add(new Object[] { TaskState.TaskStage.STARTED, enumConstants[i],
                TaskState.TaskStage.CREATED, null });
        for (int j = 0; j < i; j++) {
            invalidStageTransitions.add(new Object[] { TaskState.TaskStage.STARTED, enumConstants[i],
                    TaskState.TaskStage.STARTED, enumConstants[j] });
        }
    }

    invalidStageTransitions
            .add(new Object[] { TaskState.TaskStage.FINISHED, null, TaskState.TaskStage.CREATED, null });
    for (int i = 0; i < enumConstants.length; i++) {
        invalidStageTransitions.add(new Object[] { TaskState.TaskStage.FINISHED, null,
                TaskState.TaskStage.STARTED, enumConstants[i] });
    }
    invalidStageTransitions
            .add(new Object[] { TaskState.TaskStage.FINISHED, null, TaskState.TaskStage.FINISHED, null });
    invalidStageTransitions
            .add(new Object[] { TaskState.TaskStage.FINISHED, null, TaskState.TaskStage.FAILED, null });
    invalidStageTransitions
            .add(new Object[] { TaskState.TaskStage.FINISHED, null, TaskState.TaskStage.CANCELLED, null });

    invalidStageTransitions
            .add(new Object[] { TaskState.TaskStage.FAILED, null, TaskState.TaskStage.CREATED, null });
    for (int i = 0; i < enumConstants.length; i++) {
        invalidStageTransitions.add(new Object[] { TaskState.TaskStage.FAILED, null,
                TaskState.TaskStage.STARTED, enumConstants[i] });
    }
    invalidStageTransitions
            .add(new Object[] { TaskState.TaskStage.FAILED, null, TaskState.TaskStage.FINISHED, null });
    invalidStageTransitions
            .add(new Object[] { TaskState.TaskStage.FAILED, null, TaskState.TaskStage.FAILED, null });
    invalidStageTransitions
            .add(new Object[] { TaskState.TaskStage.FAILED, null, TaskState.TaskStage.CANCELLED, null });

    invalidStageTransitions
            .add(new Object[] { TaskState.TaskStage.CANCELLED, null, TaskState.TaskStage.CREATED, null });
    for (int i = 0; i < enumConstants.length; i++) {
        invalidStageTransitions.add(new Object[] { TaskState.TaskStage.CANCELLED, null,
                TaskState.TaskStage.STARTED, enumConstants[i] });
    }
    invalidStageTransitions
            .add(new Object[] { TaskState.TaskStage.CANCELLED, null, TaskState.TaskStage.FINISHED, null });
    invalidStageTransitions
            .add(new Object[] { TaskState.TaskStage.CANCELLED, null, TaskState.TaskStage.FAILED, null });
    invalidStageTransitions
            .add(new Object[] { TaskState.TaskStage.CANCELLED, null, TaskState.TaskStage.CANCELLED, null });

    Object[][] returnValue = new Object[invalidStageTransitions.size()][4];
    for (int i = 0; i < invalidStageTransitions.size(); i++) {
        returnValue[i][0] = invalidStageTransitions.get(i)[0];
        returnValue[i][1] = invalidStageTransitions.get(i)[1];
        returnValue[i][2] = invalidStageTransitions.get(i)[2];
        returnValue[i][3] = invalidStageTransitions.get(i)[3];
    }

    return returnValue;
}

From source file:com.gdevelop.gwt.syncrpc.SyncClientSerializationStreamReader.java

private Object instantiate(Class<?> customSerializer, Class<?> instanceClass)
        throws InstantiationException, IllegalAccessException, IllegalArgumentException,
        InvocationTargetException, NoSuchMethodException, SerializationException {
    if (customSerializer != null) {
        for (Method method : customSerializer.getMethods()) {
            if ("instantiate".equals(method.getName())) {
                return method.invoke(null, this);
            }//w  w w  .j a va2 s . c o  m
        }
        // Ok to not have one.
    }

    if (instanceClass.isArray()) {
        int length = readInt();
        // We don't pre-allocate the array; this prevents an allocation attack
        return new BoundedList<Object>(instanceClass.getComponentType(), length);
    } else if (instanceClass.isEnum()) {
        Enum<?>[] enumConstants = (Enum[]) instanceClass.getEnumConstants();
        int ordinal = readInt();
        assert (ordinal >= 0 && ordinal < enumConstants.length);
        return enumConstants[ordinal];
    } else {
        Constructor<?> constructor = instanceClass.getDeclaredConstructor();
        constructor.setAccessible(true);
        return constructor.newInstance();
    }
}