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.nonninz.robomodel.RoboModel.java

private void loadField(Field field, Cursor query) throws DatabaseNotUpToDateException {
    final Class<?> type = field.getType();
    final boolean wasAccessible = field.isAccessible();
    final int columnIndex = query.getColumnIndex(field.getName());
    field.setAccessible(true);//  w  w  w.  j  av a2 s .c  om

    /*
     * TODO: There is the potential of a problem here:
     * What happens if the developer changes the type of a field between releases?
     *
     * If he saves first, then the column type will be changed (In the future).
     * If he loads first, we don't know if an Exception will be thrown if the
     * types are incompatible, because it's undocumented in the Cursor documentation.
     */

    try {
        if (type == String.class) {
            field.set(this, query.getString(columnIndex));
        } else if (type == Boolean.TYPE) {
            final boolean value = query.getInt(columnIndex) == 1 ? true : false;
            field.setBoolean(this, value);
        } else if (type == Byte.TYPE) {
            field.setByte(this, (byte) query.getShort(columnIndex));
        } else if (type == Double.TYPE) {
            field.setDouble(this, query.getDouble(columnIndex));
        } else if (type == Float.TYPE) {
            field.setFloat(this, query.getFloat(columnIndex));
        } else if (type == Integer.TYPE) {
            field.setInt(this, query.getInt(columnIndex));
        } else if (type == Long.TYPE) {
            field.setLong(this, query.getLong(columnIndex));
        } else if (type == Short.TYPE) {
            field.setShort(this, query.getShort(columnIndex));
        } else if (type.isEnum()) {
            final String string = query.getString(columnIndex);
            if (string != null && string.length() > 0) {
                final Object[] constants = type.getEnumConstants();
                final Method method = type.getMethod("valueOf", Class.class, String.class);
                final Object value = method.invoke(constants[0], type, string);
                field.set(this, value);
            }
        } else {
            // Try to de-json it (db column must be of type text)
            try {
                final Object value = mMapper.readValue(query.getString(columnIndex), field.getType());
                field.set(this, value);
            } catch (final Exception e) {
                final String msg = String.format("Type %s is not supported for field %s", type,
                        field.getName());
                Ln.w(e, msg);
                throw new IllegalArgumentException(msg);
            }
        }
    } catch (final IllegalAccessException e) {
        final String msg = String.format("Field %s is not accessible", type, field.getName());
        throw new IllegalArgumentException(msg);
    } catch (final NoSuchMethodException e) {
        // Should not happen
        throw new RuntimeException(e);
    } catch (final InvocationTargetException e) {
        // Should not happen
        throw new RuntimeException(e);
    } catch (IllegalStateException e) {
        // This is when there is no column in db, but there is in the model
        throw new DatabaseNotUpToDateException(e);
    } finally {
        field.setAccessible(wasAccessible);
    }
}

From source file:it.delli.mwebc.utils.DefaultCastHelper.java

public Object toType(String value, Class<?> type) {
    Object obj = null;/*from  w  w w. ja  v a  2 s . c  o  m*/
    try {
        if (value != null) {
            if (type.getName().equals(String.class.getName())) {
                obj = toString(value);
            } else if (type.getName().equals(String[].class.getName())) {
                obj = toStringArray(value);
            } else if (type.getName().equals(Character.class.getName())) {
                obj = toCharacter(value);
            } else if (type.getName().equals(Character[].class.getName())) {
                obj = toCharacterArray(value);
            } else if (type.getName().equals(Integer.class.getName())) {
                obj = toInteger(value);
            } else if (type.getName().equals(Integer[].class.getName())) {
                obj = toIntegerArray(value);
            } else if (type.getName().equals(Long.class.getName())) {
                obj = toLong(value);
            } else if (type.getName().equals(Long[].class.getName())) {
                obj = toLongArray(value);
            } else if (type.getName().equals(Double.class.getName())) {
                obj = toDouble(value);
            } else if (type.getName().equals(Double[].class.getName())) {
                obj = toDoubleArray(value);
            } else if (type.getName().equals(Boolean.class.getName())) {
                obj = toBoolean(value);
            } else if (type.getName().equals(Boolean[].class.getName())) {
                obj = toBooleanArray(value);
            } else if (type.getName().equals(Date.class.getName())) {
                obj = toDate(value);
            } else if (type.getName().equals(Date[].class.getName())) {
                obj = toDateArray(value);
            } else if (type.getName().equals(Color.class.getName())) {
                obj = toColor(value);
            } else if (type.getName().equals(Color[].class.getName())) {
                obj = toColorArray(value);
            } else if (type.isEnum()) {
                for (int i = 0; i < type.getEnumConstants().length; i++) {
                    if (type.getEnumConstants()[i].toString().equals(value)) {
                        obj = type.getEnumConstants()[i];
                    }
                }
            } else if (type.isArray() && type.getComponentType().isEnum()) {
                String[] tmp = value.split(",");
                Enum[] array = new Enum[tmp.length];
                for (int j = 0; j < tmp.length; j++) {
                    String item = tmp[j].trim();
                    for (int i = 0; i < type.getComponentType().getEnumConstants().length; i++) {
                        if (type.getComponentType().getEnumConstants()[i].toString().equals(item)) {
                            array[j] = (Enum) type.getComponentType().getEnumConstants()[i];
                        }
                    }
                }
                obj = array;
            } else if (type.getName().equals(Map.class.getName())
                    || type.getName().equals(HashMap.class.getName())
                    || type.getName().equals(LinkedHashMap.class.getName())) {
                obj = toMap(value, type);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return obj;
}

From source file:org.icelib.beans.ObjectMapping.java

@SuppressWarnings({ "unchecked", "restriction", "rawtypes" })
public static <V> V value(Object value, Class<V> targetClass, Object... constructorArgs) {

    Transformer<Object, V> t = (Transformer<Object, V>) objectConverters
            .get(new ClassKey(value.getClass(), targetClass));
    if (t != null) {
        return (V) (t.transform(value));
    }//from ww  w.j a v  a2  s.co m

    if (value instanceof Number) {
        if (targetClass.equals(Long.class) || targetClass.equals(long.class)) {
            return (V) ((Long) (((Number) value).longValue()));
        } else if (targetClass.equals(Double.class) || targetClass.equals(double.class)) {
            return (V) ((Double) (((Number) value).doubleValue()));
        } else if (targetClass.equals(Integer.class) || targetClass.equals(int.class)) {
            return (V) ((Integer) (((Number) value).intValue()));
        } else if (targetClass.equals(Short.class) || targetClass.equals(short.class)) {
            return (V) ((Short) (((Number) value).shortValue()));
        } else if (targetClass.equals(Float.class) || targetClass.equals(float.class)) {
            return (V) ((Float) (((Number) value).floatValue()));
        } else if (targetClass.equals(Byte.class) || targetClass.equals(byte.class)) {
            return (V) ((Byte) (((Number) value).byteValue()));
        } else if (targetClass.equals(Boolean.class) || targetClass.equals(boolean.class)) {
            return (V) ((Boolean) (((Number) value).intValue() != 0));
        } else if (targetClass.equals(String.class)) {
            return (V) (value.toString());
        } else {
            throw new IllegalArgumentException(
                    String.format("Cannot convert number %s to %s", value, targetClass));
        }
    } else if (value instanceof Boolean) {
        return (V) (((Boolean) value));
    } else if (value instanceof String) {
        if (targetClass.equals(Long.class)) {
            return (V) ((Long) Long.parseLong((String) value));
        } else if (targetClass.equals(Double.class)) {
            return (V) ((Double) Double.parseDouble((String) value));
        } else if (targetClass.equals(Integer.class)) {
            return (V) ((Integer) Integer.parseInt((String) value));
        } else if (targetClass.equals(Short.class)) {
            return (V) ((Short) Short.parseShort((String) value));
        } else if (targetClass.equals(Float.class)) {
            return (V) ((Float) Float.parseFloat((String) value));
        } else if (targetClass.equals(Byte.class)) {
            return (V) ((Byte) Byte.parseByte((String) value));
        } else if (targetClass.equals(Boolean.class)) {
            return (V) ((Boolean) Boolean.parseBoolean((String) value));
        } else if (targetClass.equals(String.class)) {
            return (V) (value.toString());
        } else if (targetClass.isEnum()) {
            for (V ev : targetClass.getEnumConstants()) {
                if (ev.toString().toLowerCase().equalsIgnoreCase(value.toString())) {
                    return ev;
                }
            }
            throw new IllegalArgumentException(String.format("Unknown enum %s in %s", value, targetClass));
        } else {
            // Maybe the target has a constructor that takes a string
            try {
                Constructor<V> con = targetClass.getConstructor(String.class);
                return con.newInstance((String) value);
            } catch (NoSuchMethodException nsme) {
                // That's it, give up
                throw new IllegalArgumentException(
                        String.format("Cannot convert string %s to %s", value, targetClass));
            } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                    | InvocationTargetException e) {
                throw new RuntimeException(e);
            }

        }
    } else if (value instanceof Map) {
        /*
         * This covers ScriptObjectMirror from Nashorn which is a list AND a
         * map describing an object or an array. It also covers ordinary map
         * and lists
         */

        if (isScriptNativeArray(value)) {
            Collection<?> c = ((jdk.nashorn.api.scripting.ScriptObjectMirror) value).values();
            if (c instanceof List && MappedList.class.isAssignableFrom(targetClass)) {
                try {
                    V v = getTargetInstance(value, targetClass, constructorArgs);
                    for (Object o : ((List) c)) {
                        ((List) v).add(o);
                    }
                    return v;
                } catch (NoSuchMethodException e) {
                    throw new IllegalArgumentException(String.format(
                            "No zero-length constructor for class %s and no valid constructor args provided.",
                            targetClass));
                } catch (InstantiationException | SecurityException | IllegalAccessException
                        | IllegalArgumentException | InvocationTargetException e) {
                    throw new RuntimeException(String.format("Could not construct %s", targetClass), e);
                }
            } else if ((List.class.isAssignableFrom(targetClass) && c instanceof List)
                    || (Collection.class.isAssignableFrom(targetClass) && c instanceof Collection)) {
                return (V) c;
            } else if (Set.class.isAssignableFrom(targetClass)) {
                return (V) new LinkedHashSet<Object>(c);
            } else if (Collection.class.isAssignableFrom(targetClass)) {
                return (V) new ArrayList<Object>(c);
            } else if (targetClass.isArray()) {
                return (V) c.toArray((Object[]) Array.newInstance(targetClass.getComponentType(), c.size()));
            }
        } else if (value instanceof List && List.class.isAssignableFrom(targetClass)) {
            return (V) ((List<?>) value);
        } else if (!isScriptNativeObject(value) && Map.class.isAssignableFrom(targetClass)) {
            return (V) ((Map<?, ?>) value);
        } else {
            try {
                V v = getTargetInstance(value, targetClass, constructorArgs);
                ObjectMapper<?> m = new ObjectMapper<>(v);
                try {
                    m.map((Map<String, Object>) value);
                } catch (Exception e) {
                    throw new RuntimeException(String.format("Failed to map %s.", targetClass), e);
                }
                return v;
            } catch (NoSuchMethodException e) {
                throw new IllegalArgumentException(String.format(
                        "No zero-length constructor for class %s and no valid constructor args provided.",
                        targetClass));
            } catch (InstantiationException | SecurityException | IllegalAccessException
                    | IllegalArgumentException | InvocationTargetException e) {
                throw new RuntimeException(String.format("Could not construct %s", targetClass), e);
            }
        }
    } else if (targetClass.isAssignableFrom(value.getClass())) {
        return (V) value;
    } else if (value instanceof Collection && List.class.isAssignableFrom(targetClass)) {
        try {
            V v = getTargetInstance(value, targetClass, constructorArgs);
            ((List) v).addAll((Collection) value);
            return v;
        } catch (InstantiationException | SecurityException | IllegalAccessException | IllegalArgumentException
                | InvocationTargetException e) {
            throw new RuntimeException(String.format("Could not construct %s", targetClass), e);
        } catch (NoSuchMethodException nse) {
        }
    }
    throw new IllegalArgumentException(
            String.format("Cannot convert %s (%s) to %s", value, value.getClass(), targetClass));
}

From source file:org.apache.syncope.client.console.panels.BeanPanel.java

public BeanPanel(final String id, final IModel<T> bean,
        final Map<String, Pair<AbstractFiqlSearchConditionBuilder, List<SearchClause>>> sCondWrapper,
        final String... excluded) {
    super(id, bean);
    setOutputMarkupId(true);//from   w  ww  .  j  ava  2 s.c o m

    this.sCondWrapper = sCondWrapper;

    this.excluded = new ArrayList<>(Arrays.asList(excluded));
    this.excluded.add("serialVersionUID");
    this.excluded.add("class");

    final LoadableDetachableModel<List<String>> model = new LoadableDetachableModel<List<String>>() {

        private static final long serialVersionUID = 5275935387613157437L;

        @Override
        protected List<String> load() {
            final List<String> result = new ArrayList<>();

            if (BeanPanel.this.getDefaultModelObject() != null) {
                ReflectionUtils.doWithFields(BeanPanel.this.getDefaultModelObject().getClass(),
                        new FieldCallback() {

                            public void doWith(final Field field)
                                    throws IllegalArgumentException, IllegalAccessException {
                                result.add(field.getName());
                            }

                        }, new FieldFilter() {

                            public boolean matches(final Field field) {
                                return !BeanPanel.this.excluded.contains(field.getName());
                            }
                        });
            }
            return result;
        }
    };

    add(new ListView<String>("propView", model) {

        private static final long serialVersionUID = 9101744072914090143L;

        @SuppressWarnings({ "unchecked", "rawtypes" })
        @Override
        protected void populateItem(final ListItem<String> item) {
            final String fieldName = item.getModelObject();

            item.add(new Label("fieldName", new ResourceModel(fieldName, fieldName)));

            Field field = ReflectionUtils.findField(bean.getObject().getClass(), fieldName);

            if (field == null) {
                return;
            }

            final SearchCondition scondAnnot = field.getAnnotation(SearchCondition.class);
            final Schema schemaAnnot = field.getAnnotation(Schema.class);

            BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(bean.getObject());

            Panel panel;

            if (scondAnnot != null) {
                final String fiql = (String) wrapper.getPropertyValue(fieldName);

                final List<SearchClause> clauses;
                if (StringUtils.isEmpty(fiql)) {
                    clauses = new ArrayList<>();
                } else {
                    clauses = SearchUtils.getSearchClauses(fiql);
                }

                final AbstractFiqlSearchConditionBuilder builder;

                switch (scondAnnot.type()) {
                case "USER":
                    panel = new UserSearchPanel.Builder(new ListModel<>(clauses)).required(false)
                            .build("value");
                    builder = SyncopeClient.getUserSearchConditionBuilder();
                    break;
                case "GROUP":
                    panel = new GroupSearchPanel.Builder(new ListModel<>(clauses)).required(false)
                            .build("value");
                    builder = SyncopeClient.getGroupSearchConditionBuilder();
                    break;
                default:
                    panel = new AnyObjectSearchPanel.Builder(scondAnnot.type(), new ListModel<>(clauses))
                            .required(false).build("value");
                    builder = SyncopeClient.getAnyObjectSearchConditionBuilder(null);
                }

                if (BeanPanel.this.sCondWrapper != null) {
                    BeanPanel.this.sCondWrapper.put(fieldName, Pair.of(builder, clauses));
                }
            } else if (List.class.equals(field.getType())) {
                Class<?> listItemType = String.class;
                if (field.getGenericType() instanceof ParameterizedType) {
                    listItemType = (Class<?>) ((ParameterizedType) field.getGenericType())
                            .getActualTypeArguments()[0];
                }

                if (listItemType.equals(String.class) && schemaAnnot != null) {
                    SchemaRestClient schemaRestClient = new SchemaRestClient();

                    final List<AbstractSchemaTO> choices = new ArrayList<>();

                    for (SchemaType type : schemaAnnot.type()) {
                        switch (type) {
                        case PLAIN:
                            choices.addAll(
                                    schemaRestClient.getSchemas(SchemaType.PLAIN, schemaAnnot.anyTypeKind()));
                            break;

                        case DERIVED:
                            choices.addAll(
                                    schemaRestClient.getSchemas(SchemaType.DERIVED, schemaAnnot.anyTypeKind()));
                            break;

                        case VIRTUAL:
                            choices.addAll(
                                    schemaRestClient.getSchemas(SchemaType.VIRTUAL, schemaAnnot.anyTypeKind()));
                            break;

                        default:
                        }
                    }

                    panel = new AjaxPalettePanel.Builder<>().setName(fieldName)
                            .build("value", new PropertyModel<>(bean.getObject(), fieldName), new ListModel<>(
                                    choices.stream().map(EntityTO::getKey).collect(Collectors.toList())))
                            .hideLabel();
                } else if (listItemType.isEnum()) {
                    panel = new AjaxPalettePanel.Builder<>().setName(fieldName)
                            .build("value", new PropertyModel<>(bean.getObject(), fieldName),
                                    new ListModel(Arrays.asList(listItemType.getEnumConstants())))
                            .hideLabel();
                } else {
                    panel = new MultiFieldPanel.Builder<>(new PropertyModel<>(bean.getObject(), fieldName))
                            .build("value", fieldName,
                                    buildSinglePanel(bean.getObject(), field.getType(), fieldName, "panel"))
                            .hideLabel();
                }
            } else {
                panel = buildSinglePanel(bean.getObject(), field.getType(), fieldName, "value").hideLabel();
            }

            item.add(panel.setRenderBodyOnly(true));
        }

    }.setReuseItems(true).setOutputMarkupId(true));
}

From source file:mondrian.olap.fun.FunUtil.java

/**
 * Returns the ordinal of a literal argument. If the argument does not
 * belong to the supplied enumeration, returns -1.
 *//* w  w  w . j a  v a 2 s  .  c o  m*/
static <E extends Enum<E>> E getLiteralArg(ResolvedFunCall call, int i, E defaultValue,
        Class<E> allowedValues) {
    if (i >= call.getArgCount()) {
        if (defaultValue == null) {
            throw newEvalException(call.getFunDef(), "Required argument is missing");
        } else {
            return defaultValue;
        }
    }
    Exp arg = call.getArg(i);
    if (!(arg instanceof Literal) || arg.getCategory() != Category.Symbol) {
        throw newEvalException(call.getFunDef(), "Expected a symbol, found '" + arg + "'");
    }
    String s = (String) ((Literal) arg).getValue();
    for (E e : allowedValues.getEnumConstants()) {
        if (e.name().equalsIgnoreCase(s)) {
            return e;
        }
    }
    StringBuilder buf = new StringBuilder(64);
    int k = 0;
    for (E e : allowedValues.getEnumConstants()) {
        if (k++ > 0) {
            buf.append(", ");
        }
        buf.append(e.name());
    }
    throw newEvalException(call.getFunDef(), "Allowed values are: {" + buf + "}");
}

From source file:com.sun.socialsite.util.DebugBeanJsonConverter.java

@SuppressWarnings("boxing")
private <T> void callSetterWithValue(T pojo, Method method, JSONObject jsonObject, String fieldName)
        throws IllegalAccessException, InvocationTargetException, NoSuchFieldException, JSONException {

    log.debug("Calling setter [" + method.getName() + "]");

    Class<?> expectedType = method.getParameterTypes()[0];
    Object value = null;/*  w  w w .  java2  s . c  om*/

    if (!jsonObject.has(fieldName)) {
        // Skip
    } else if (expectedType.equals(List.class)) {
        ParameterizedType genericListType = (ParameterizedType) method.getGenericParameterTypes()[0];
        Type type = genericListType.getActualTypeArguments()[0];
        Class<?> rawType;
        Class<?> listElementClass;
        if (type instanceof ParameterizedType) {
            listElementClass = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0];
            rawType = (Class<?>) ((ParameterizedType) type).getRawType();
        } else {
            listElementClass = (Class<?>) type;
            rawType = listElementClass;
        }

        List<Object> list = Lists.newArrayList();
        JSONArray jsonArray = jsonObject.getJSONArray(fieldName);
        for (int i = 0; i < jsonArray.length(); i++) {
            if (org.apache.shindig.protocol.model.Enum.class.isAssignableFrom(rawType)) {
                list.add(convertEnum(listElementClass, jsonArray.getJSONObject(i)));
            } else {
                list.add(convertToObject(jsonArray.getString(i), listElementClass));
            }
        }

        value = list;

    } else if (expectedType.equals(Map.class)) {
        ParameterizedType genericListType = (ParameterizedType) method.getGenericParameterTypes()[0];
        Type[] types = genericListType.getActualTypeArguments();
        Class<?> valueClass = (Class<?>) types[1];

        // We only support keys being typed as Strings.
        // Nothing else really makes sense in json.
        Map<String, Object> map = Maps.newHashMap();
        JSONObject jsonMap = jsonObject.getJSONObject(fieldName);

        Iterator<?> keys = jsonMap.keys();
        while (keys.hasNext()) {
            String keyName = (String) keys.next();
            map.put(keyName, convertToObject(jsonMap.getString(keyName), valueClass));
        }

        value = map;

    } else if (org.apache.shindig.protocol.model.Enum.class.isAssignableFrom(expectedType)) {
        // TODO Need to stop using Enum as a class name :(
        value = convertEnum((Class<?>) ((ParameterizedType) method.getGenericParameterTypes()[0])
                .getActualTypeArguments()[0], jsonObject.getJSONObject(fieldName));
    } else if (expectedType.isEnum()) {
        if (jsonObject.has(fieldName)) {
            for (Object v : expectedType.getEnumConstants()) {
                if (v.toString().equals(jsonObject.getString(fieldName))) {
                    value = v;
                    break;
                }
            }
            if (value == null) {
                throw new IllegalArgumentException("No enum value  '" + jsonObject.getString(fieldName)
                        + "' in " + expectedType.getName());
            }
        }
    } else if (expectedType.equals(String.class)) {
        value = jsonObject.getString(fieldName);
    } else if (expectedType.equals(Date.class)) {
        // Use JODA ISO parsing for the conversion
        value = new DateTime(jsonObject.getString(fieldName)).toDate();
    } else if (expectedType.equals(Long.class) || expectedType.equals(Long.TYPE)) {
        value = jsonObject.getLong(fieldName);
    } else if (expectedType.equals(Integer.class) || expectedType.equals(Integer.TYPE)) {
        value = jsonObject.getInt(fieldName);
    } else if (expectedType.equals(Boolean.class) || expectedType.equals(Boolean.TYPE)) {
        value = jsonObject.getBoolean(fieldName);
    } else if (expectedType.equals(Float.class) || expectedType.equals(Float.TYPE)) {
        value = ((Double) jsonObject.getDouble(fieldName)).floatValue();
    } else if (expectedType.equals(Double.class) || expectedType.equals(Double.TYPE)) {
        value = jsonObject.getDouble(fieldName);
    } else {
        // Assume its an injected type
        value = convertToObject(jsonObject.getJSONObject(fieldName).toString(), expectedType);
    }

    if (value != null) {
        method.invoke(pojo, value);
    }
}

From source file:org.wrml.runtime.schema.generator.SchemaGenerator.java

public Choices generateChoices(final Class<?> nativeChoicesEnumClass) {

    if (nativeChoicesEnumClass == null || !nativeChoicesEnumClass.isEnum()) {
        return null;
    }//from www.  j a v a2 s  . co m

    final SchemaLoader schemaLoader = getSchemaLoader();
    final Choices choices = getContext().newModel(schemaLoader.getChoicesSchemaUri());

    final URI choicesUri = schemaLoader.getTypeUri(nativeChoicesEnumClass);
    choices.setUri(choicesUri);

    final UniqueName choicesUniqueName = schemaLoader.getTypeUniqueName(choicesUri);
    choices.setUniqueName(choicesUniqueName);

    final Object[] enumConstants = nativeChoicesEnumClass.getEnumConstants();
    if (enumConstants != null && enumConstants.length > 0) {
        final LinkedHashSet choiceSet = new LinkedHashSet(enumConstants.length);

        for (final Object enumConstant : enumConstants) {
            final String choice = String.valueOf(enumConstant);
            choiceSet.add(enumConstant);
        }

        choices.getList().addAll(choiceSet);
    }

    return choices;
}

From source file:org.apache.syncope.console.pages.ReportletConfModalPage.java

private ListView<String> buildPropView() {
    LoadableDetachableModel<List<String>> propViewModel = new LoadableDetachableModel<List<String>>() {

        private static final long serialVersionUID = 5275935387613157437L;

        @Override//from w  w  w .j  a  va2s .co m
        protected List<String> load() {
            List<String> result = new ArrayList<String>();
            if (ReportletConfModalPage.this.reportletConf != null) {
                for (Field field : ReportletConfModalPage.this.reportletConf.getClass().getDeclaredFields()) {
                    if (!ArrayUtils.contains(EXCLUDE_PROPERTIES, field.getName())) {
                        result.add(field.getName());
                    }
                }
            }

            return result;
        }
    };

    propView = new ListView<String>("propView", propViewModel) {

        private static final long serialVersionUID = 9101744072914090143L;

        @SuppressWarnings({ "unchecked", "rawtypes" })
        @Override
        protected void populateItem(final ListItem<String> item) {
            final String fieldName = item.getModelObject();

            Label label = new Label("key", fieldName);
            item.add(label);

            Field field = null;
            try {
                field = ReportletConfModalPage.this.reportletConf.getClass().getDeclaredField(fieldName);
            } catch (Exception e) {
                LOG.error("Could not find field {} in class {}", fieldName,
                        ReportletConfModalPage.this.reportletConf.getClass(), e);
            }
            if (field == null) {
                return;
            }

            FormAttributeField annotation = field.getAnnotation(FormAttributeField.class);

            BeanWrapper wrapper = PropertyAccessorFactory
                    .forBeanPropertyAccess(ReportletConfModalPage.this.reportletConf);

            Panel panel;

            if (String.class.equals(field.getType()) && annotation != null && annotation.userSearch()) {
                panel = new UserSearchPanel.Builder("value").fiql((String) wrapper.getPropertyValue(fieldName))
                        .required(false).build();
                // This is needed in order to manually update this.reportletConf with search panel selections
                panel.setDefaultModel(new Model<String>(fieldName));
            } else if (String.class.equals(field.getType()) && annotation != null && annotation.roleSearch()) {
                panel = new RoleSearchPanel.Builder("value").fiql((String) wrapper.getPropertyValue(fieldName))
                        .required(false).build();
                // This is needed in order to manually update this.reportletConf with search panel selections
                panel.setDefaultModel(new Model<String>(fieldName));
            } else if (List.class.equals(field.getType())) {
                Class<?> listItemType = String.class;
                if (field.getGenericType() instanceof ParameterizedType) {
                    listItemType = (Class<?>) ((ParameterizedType) field.getGenericType())
                            .getActualTypeArguments()[0];
                }

                if (listItemType.equals(String.class) && annotation != null) {
                    List<String> choices;
                    switch (annotation.schema()) {
                    case UserSchema:
                        choices = schemaRestClient.getSchemaNames(AttributableType.USER);
                        break;

                    case UserDerivedSchema:
                        choices = schemaRestClient.getDerSchemaNames(AttributableType.USER);
                        break;

                    case UserVirtualSchema:
                        choices = schemaRestClient.getVirSchemaNames(AttributableType.USER);
                        break;

                    case RoleSchema:
                        choices = schemaRestClient.getSchemaNames(AttributableType.ROLE);
                        break;

                    case RoleDerivedSchema:
                        choices = schemaRestClient.getDerSchemaNames(AttributableType.ROLE);
                        break;

                    case RoleVirtualSchema:
                        choices = schemaRestClient.getVirSchemaNames(AttributableType.ROLE);
                        break;

                    case MembershipSchema:
                        choices = schemaRestClient.getSchemaNames(AttributableType.MEMBERSHIP);
                        break;

                    case MembershipDerivedSchema:
                        choices = schemaRestClient.getDerSchemaNames(AttributableType.MEMBERSHIP);
                        break;

                    case MembershipVirtualSchema:
                        choices = schemaRestClient.getVirSchemaNames(AttributableType.MEMBERSHIP);
                        break;

                    default:
                        choices = Collections.emptyList();
                    }

                    panel = new AjaxPalettePanel("value",
                            new PropertyModel<List<String>>(ReportletConfModalPage.this.reportletConf,
                                    fieldName),
                            new ListModel<String>(choices), true);
                } else if (listItemType.isEnum()) {
                    panel = new CheckBoxMultipleChoiceFieldPanel("value",
                            new PropertyModel(ReportletConfModalPage.this.reportletConf, fieldName),
                            new ListModel(Arrays.asList(listItemType.getEnumConstants())));
                } else {
                    if (((List) wrapper.getPropertyValue(fieldName)).isEmpty()) {
                        ((List) wrapper.getPropertyValue(fieldName)).add(null);
                    }

                    panel = new MultiFieldPanel("value",
                            new PropertyModel<List>(ReportletConfModalPage.this.reportletConf, fieldName),
                            buildSinglePanel(field.getType(), fieldName, "panel"));
                }
            } else {
                panel = buildSinglePanel(field.getType(), fieldName, "value");
            }

            item.add(panel);
        }
    };

    return propView;
}

From source file:org.apache.syncope.client.console.pages.ReportletConfModalPage.java

private ListView<String> buildPropView() {
    LoadableDetachableModel<List<String>> propViewModel = new LoadableDetachableModel<List<String>>() {

        private static final long serialVersionUID = 5275935387613157437L;

        @Override/*from w ww .  ja  v  a  2  s  . c om*/
        protected List<String> load() {
            List<String> result = new ArrayList<String>();
            if (ReportletConfModalPage.this.reportletConf != null) {
                for (Field field : ReportletConfModalPage.this.reportletConf.getClass().getDeclaredFields()) {
                    if (!ArrayUtils.contains(EXCLUDE_PROPERTIES, field.getName())) {
                        result.add(field.getName());
                    }
                }
            }

            return result;
        }
    };

    propView = new ListView<String>("propView", propViewModel) {

        private static final long serialVersionUID = 9101744072914090143L;

        @SuppressWarnings({ "unchecked", "rawtypes" })
        @Override
        protected void populateItem(final ListItem<String> item) {
            final String fieldName = item.getModelObject();

            Label label = new Label("key", fieldName);
            item.add(label);

            Field field = null;
            try {
                field = ReportletConfModalPage.this.reportletConf.getClass().getDeclaredField(fieldName);
            } catch (Exception e) {
                LOG.error("Could not find field {} in class {}", fieldName,
                        ReportletConfModalPage.this.reportletConf.getClass(), e);
            }
            if (field == null) {
                return;
            }

            FormAttributeField annotation = field.getAnnotation(FormAttributeField.class);

            BeanWrapper wrapper = PropertyAccessorFactory
                    .forBeanPropertyAccess(ReportletConfModalPage.this.reportletConf);

            Panel panel;

            if (String.class.equals(field.getType()) && annotation != null && annotation.userSearch()) {
                panel = new UserSearchPanel.Builder("value").fiql((String) wrapper.getPropertyValue(fieldName))
                        .required(false).build();
                // This is needed in order to manually update this.reportletConf with search panel selections
                panel.setDefaultModel(new Model<String>(fieldName));
            } else if (String.class.equals(field.getType()) && annotation != null && annotation.groupSearch()) {
                panel = new GroupSearchPanel.Builder("value").fiql((String) wrapper.getPropertyValue(fieldName))
                        .required(false).build();
                // This is needed in order to manually update this.reportletConf with search panel selections
                panel.setDefaultModel(new Model<String>(fieldName));
            } else if (List.class.equals(field.getType())) {
                Class<?> listItemType = String.class;
                if (field.getGenericType() instanceof ParameterizedType) {
                    listItemType = (Class<?>) ((ParameterizedType) field.getGenericType())
                            .getActualTypeArguments()[0];
                }

                if (listItemType.equals(String.class) && annotation != null) {
                    List<String> choices;
                    switch (annotation.schema()) {
                    case UserPlainSchema:
                        choices = schemaRestClient.getPlainSchemaNames(AttributableType.USER);
                        break;

                    case UserDerivedSchema:
                        choices = schemaRestClient.getDerSchemaNames(AttributableType.USER);
                        break;

                    case UserVirtualSchema:
                        choices = schemaRestClient.getVirSchemaNames(AttributableType.USER);
                        break;

                    case GroupPlainSchema:
                        choices = schemaRestClient.getPlainSchemaNames(AttributableType.GROUP);
                        break;

                    case GroupDerivedSchema:
                        choices = schemaRestClient.getDerSchemaNames(AttributableType.GROUP);
                        break;

                    case GroupVirtualSchema:
                        choices = schemaRestClient.getVirSchemaNames(AttributableType.GROUP);
                        break;

                    case MembershipPlainSchema:
                        choices = schemaRestClient.getPlainSchemaNames(AttributableType.MEMBERSHIP);
                        break;

                    case MembershipDerivedSchema:
                        choices = schemaRestClient.getDerSchemaNames(AttributableType.MEMBERSHIP);
                        break;

                    case MembershipVirtualSchema:
                        choices = schemaRestClient.getVirSchemaNames(AttributableType.MEMBERSHIP);
                        break;

                    default:
                        choices = Collections.emptyList();
                    }

                    panel = new AjaxPalettePanel("value",
                            new PropertyModel<List<String>>(ReportletConfModalPage.this.reportletConf,
                                    fieldName),
                            new ListModel<String>(choices), true);
                } else if (listItemType.isEnum()) {
                    panel = new CheckBoxMultipleChoiceFieldPanel("value",
                            new PropertyModel(ReportletConfModalPage.this.reportletConf, fieldName),
                            new ListModel(Arrays.asList(listItemType.getEnumConstants())));
                } else {
                    if (((List) wrapper.getPropertyValue(fieldName)).isEmpty()) {
                        ((List) wrapper.getPropertyValue(fieldName)).add(null);
                    }

                    panel = new MultiFieldPanel("value",
                            new PropertyModel<List>(ReportletConfModalPage.this.reportletConf, fieldName),
                            buildSinglePanel(field.getType(), fieldName, "panel"));
                }
            } else {
                panel = buildSinglePanel(field.getType(), fieldName, "value");
            }

            item.add(panel);
        }
    };

    return propView;
}