Example usage for java.lang.reflect Field getGenericType

List of usage examples for java.lang.reflect Field getGenericType

Introduction

In this page you can find the example usage for java.lang.reflect Field getGenericType.

Prototype

public Type getGenericType() 

Source Link

Document

Returns a Type object that represents the declared type for the field represented by this Field object.

Usage

From source file:cn.afterturn.easypoi.excel.export.base.ExportCommonService.java

/**
 * ??/*w  w w  .  j av  a2s  .  c o  m*/
 *
 * @param targetId ID
 */
public void getAllExcelField(String[] exclusions, String targetId, Field[] fields,
        List<ExcelExportEntity> excelParams, Class<?> pojoClass, List<Method> getMethods,
        ExcelEntity excelGroup) throws Exception {
    List<String> exclusionsList = exclusions != null ? Arrays.asList(exclusions) : null;
    ExcelExportEntity excelEntity;
    // ??filed
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];
        // ?collection,?java,?
        if (PoiPublicUtil.isNotUserExcelUserThis(exclusionsList, field, targetId)) {
            continue;
        }
        // Excel ???
        if (field.getAnnotation(Excel.class) != null) {
            Excel excel = field.getAnnotation(Excel.class);
            String name = PoiPublicUtil.getValueByTargetId(excel.name(), targetId, null);
            if (StringUtils.isNotBlank(name)) {
                excelParams.add(createExcelExportEntity(field, targetId, pojoClass, getMethods, excelGroup));
            }
        } else if (PoiPublicUtil.isCollection(field.getType())) {
            ExcelCollection excel = field.getAnnotation(ExcelCollection.class);
            ParameterizedType pt = (ParameterizedType) field.getGenericType();
            Class<?> clz = (Class<?>) pt.getActualTypeArguments()[0];
            List<ExcelExportEntity> list = new ArrayList<ExcelExportEntity>();
            getAllExcelField(exclusions, StringUtils.isNotEmpty(excel.id()) ? excel.id() : targetId,
                    PoiPublicUtil.getClassFields(clz), list, clz, null, null);
            excelEntity = new ExcelExportEntity();
            excelEntity.setName(PoiPublicUtil.getValueByTargetId(excel.name(), targetId, null));
            if (i18nHandler != null) {
                excelEntity.setName(i18nHandler.getLocaleName(excelEntity.getName()));
            }
            excelEntity.setOrderNum(
                    Integer.valueOf(PoiPublicUtil.getValueByTargetId(excel.orderNum(), targetId, "0")));
            excelEntity.setMethod(PoiReflectorUtil.fromCache(pojoClass).getGetMethod(field.getName()));
            excelEntity.setList(list);
            excelParams.add(excelEntity);
        } else {
            List<Method> newMethods = new ArrayList<Method>();
            if (getMethods != null) {
                newMethods.addAll(getMethods);
            }
            newMethods.add(PoiReflectorUtil.fromCache(pojoClass).getGetMethod(field.getName()));
            ExcelEntity excel = field.getAnnotation(ExcelEntity.class);
            if (excel.show() && StringUtils.isEmpty(excel.name())) {
                throw new ExcelExportException("if use ExcelEntity ,name mus has value ,data: "
                        + ReflectionToStringBuilder.toString(excel), ExcelExportEnum.PARAMETER_ERROR);
            }
            getAllExcelField(exclusions, StringUtils.isNotEmpty(excel.id()) ? excel.id() : targetId,
                    PoiPublicUtil.getClassFields(field.getType()), excelParams, field.getType(), newMethods,
                    excel.show() ? excel : null);
        }
    }
}

From source file:org.LexGrid.LexBIG.caCore.web.util.LexEVSHTTPUtils.java

private String getParamatarizedListType(Field field) {
    String fieldTypeName = null;/* w ww. java  2s. co  m*/
    Type type = field.getGenericType();

    //if its a Parameterized List, see if we can dig out the type
    if (type != null && type instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType) type;
        if (pt.getActualTypeArguments().length > 0) {
            Type collectionType = pt.getActualTypeArguments()[0];
            if (collectionType instanceof Class) {
                fieldTypeName = ((Class) collectionType).getName();
            }
        }
    }
    return fieldTypeName;
}

From source file:at.alladin.rmbt.shared.hstoreparser.HstoreParser.java

/**
 * /*from ww  w  . jav  a  2 s  .  co  m*/
 * @param hstore
 * @return
 * @throws HstoreParseException 
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public T fromJson(JSONObject json) throws HstoreParseException {
    T object;
    try {
        object = constructor.newInstance();
    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException e) {
        throw new HstoreParseException(HstoreParseException.HSTORE_PARSE_EXCEPTION + e.getLocalizedMessage(),
                e);
    }

    if (object == null) {
        throw new HstoreParseException(
                HstoreParseException.HSTORE_COULD_NOT_INSTANTIATE + clazz.getCanonicalName());
    }

    //iterate through all json entries:
    Iterator<String> jsonKeys = json.keys();
    while (jsonKeys.hasNext()) {
        String key = jsonKeys.next();

        //if fieldsWithKeys contain a key (=it was annotated with @HstoreKey) then try to set the value of the field in T object
        if (fieldsWithKeys.containsKey(key)) {
            final Field field = fieldsWithKeys.get(key);
            try {
                Object value = getFromJsonByField(json, key, field);
                field.setAccessible(true);
                //cast / new instance needed?
                if (field.isAnnotationPresent(HstoreCollection.class)) {
                    Class<?> fieldClazz = field.getType();
                    //System.out.println("FieldClazz: " + fieldClazz + " -> " + fieldClazz.isAssignableFrom(Collection.class));
                    if (Collection.class.isAssignableFrom(fieldClazz)) {
                        //get collection and instantiate if necessary
                        Collection collection = (Collection) field.get(object);
                        if (collection == null) {
                            collection = (Collection) fieldClazz.newInstance();
                        }

                        ParameterizedType fieldType = (ParameterizedType) field.getGenericType();
                        Class<?> genericClazz = (Class<?>) fieldType.getActualTypeArguments()[0];
                        //System.out.println("genericClazz: " + genericClazz);

                        //Object jsonObject = hstore.toJson((String) value, genericClazz);
                        Object jsonObject = null;
                        //System.out.println(value);
                        if (!value.equals(JSONObject.NULL)) {
                            if (value instanceof JSONArray || value instanceof JSONObject) {
                                jsonObject = hstore.toJson(value.toString(), genericClazz);
                            } else {
                                jsonObject = hstore.toJson((String) value, genericClazz);
                            }
                        } else {
                            jsonObject = hstore.toJson(null, genericClazz);
                        }

                        if (jsonObject != null) {
                            if (jsonObject instanceof JSONArray) {
                                //System.out.println(jsonObject);
                                Object[] array = hstore.fromJSONArray((JSONArray) jsonObject, genericClazz);
                                for (int i = 0; i < array.length; i++) {
                                    //System.out.println("Created element: " + array[i]);
                                    collection.add(array[i]);
                                }
                            } else {
                                Object element = hstore.fromString((String) value, genericClazz);
                                //System.out.println("Created element: " + element);
                                collection.add(element);
                            }
                        }

                        value = collection;
                    } else {
                        throw new HstoreParseException(HstoreParseException.HSTORE_MUST_BE_A_COLLECTION + field
                                + " - " + clazz.getCanonicalName());
                    }
                }

                if (field.isAnnotationPresent(HstoreCast.class)) {
                    HstoreCast castDef = field.getAnnotation(HstoreCast.class);
                    if (castDef.simpleCast()) {
                        //simple cast
                        field.set(object, castDef.clazz().cast(value));
                    } else {
                        //new instance
                        field.set(object, castDef.clazz().getConstructor(castDef.constructorParamClazz())
                                .newInstance(value));
                    }
                } else {
                    if (JSONObject.NULL.equals(value)) {
                        field.set(object, null);
                    } else {
                        field.set(object, parseFieldValue(field, value));
                    }
                }

            } catch (IllegalAccessException | IllegalArgumentException | JSONException e) {
                throw new HstoreParseException(
                        HstoreParseException.HSTORE_COULD_NOT_INSTANTIATE + clazz.getCanonicalName(), e);
            } catch (InstantiationException e) {
                throw new HstoreParseException(
                        HstoreParseException.HSTORE_COULD_NOT_INSTANTIATE + clazz.getCanonicalName(), e);
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ClassCastException e) {
                System.out.println("field: " + field.toString() + ", key: " + key);
                e.printStackTrace();
            }
        }
    }

    return object;
}

From source file:windows.webservices.JsonDeserializer.Deserializer.java

@Override
public E deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException {
    try {/*w  w w .ja v  a  2 s .  c  o m*/

        JsonNode json = jp.getCodec().readTree(jp);

        if (StringUtils.isEmpty(json.toString()) || json.toString().length() < 4) {
            return getNullValue(dc);
        }
        E instance = classChild.newInstance();
        ObjectMapper mapper = new ObjectMapper();
        SimpleModule modul = new SimpleModule("parroquia")
                .addDeserializer(Parroquia.class, new ParroquiaDeserializer())
                .addDeserializer(Semana.class, new SemanaDeserializer())
                .addDeserializer(Animal.class, new AnimalDeserializer())
                .addDeserializer(Semana.class, new SemanaDeserializer())
                .addDeserializer(Especie.class, new EspecieDeserializer())
                .addDeserializer(Persona.class, new PersonaDeserializer())
                .addDeserializer(Permiso.class, new PermisoDeserializer())
                .addDeserializer(Usuario.class, new UsuarioDeserializer())
                .addDeserializer(Cliente.class, new ClienteDeserializer())
                .addDeserializer(Municipio.class, new MunicipioDeserializer())
                .addDeserializer(Animal_has_Caso.class, new Animal_has_CasoDeserializer())
                .addDeserializer(Caso.class, new CasoDeserializer())
                .addDeserializer(Novedades.class, new NovedadesDeserializer())
                .addDeserializer(RegistroVacunacion.class, new RegistroVacunacionDeserializer())
                .addDeserializer(RegistroVacunacion_has_Animal.class,
                        new RegistroVacunacion_has_AnimalDeserializer())
                .addDeserializer(Vacunacion.class, new VacunacionDeserializer());
        mapper.registerModule(modul);

        for (Field field : ReflectionUtils.getAllFields(classChild)) {
            Object value = null;
            Iterator<String> it = json.fieldNames();
            String column = null;
            String fieldName = field.getName();
            JsonProperty property = field.getAnnotation(JsonProperty.class);
            if (property != null) {
                fieldName = property.value();
            }
            while (it.hasNext()) {
                String name = it.next();
                if (Objects.equals(name.trim(), fieldName)) {
                    column = name;
                    break;
                }
            }
            if (column == null) {
                System.out.println("No se reconoce la siguente columna : " + fieldName + " de : "
                        + classChild.getSimpleName());
                continue;
            }
            if (field.getType().equals(String.class)) {
                value = json.get(column).asText();
            } else if (Collection.class.isAssignableFrom(field.getType())) {
                if (StringUtils.isNotEmpty(json.get(column).toString())) {
                    ParameterizedType stringListType = (ParameterizedType) field.getGenericType();
                    Class<?> stringListClass = (Class<?>) stringListType.getActualTypeArguments()[0];
                    value = mapper.readValue(json.get(column).toString(),
                            mapper.getTypeFactory().constructCollectionType(List.class, stringListClass));
                } else {
                    value = null;
                }
            } else if (!field.getType().equals(Date.class)) {
                try {
                    value = mapper.convertValue(json.get(column), field.getType());
                } catch (IllegalArgumentException ex) {
                    value = null;
                }
            } else {
                String date = json.get(column).textValue();
                try {
                    if (date != null) {
                        value = d.parse(date.replace("-", "/"));
                    }
                } catch (ParseException ex) {
                    Logger.getLogger(Deserializer.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            ReflectionUtils.runSetter(field, instance, value);
        }
        return instance;
    } catch (InstantiationException | IllegalAccessException ex) {
        Logger.getLogger(Deserializer.class.getName()).log(Level.SEVERE, null, ex);
    }
    return getNullValue(dc);
}

From source file:org.kuali.rice.krad.data.provider.annotation.impl.AnnotationMetadataProviderImpl.java

/**
 * Adds a collection relationship for a field to the metadata object.
 *
 * @param metadata the metadata for the class.
 * @param f the field to process./*w w  w . j  a  v  a 2 s .co  m*/
 * @param a the collection relationship to add.
 */
protected void addDataObjectCollection(DataObjectMetadataImpl metadata, Field f, CollectionRelationship a) {
    List<DataObjectCollection> collections = new ArrayList<DataObjectCollection>(metadata.getCollections());
    DataObjectCollectionImpl collection = new DataObjectCollectionImpl();
    collection.setName(f.getName());

    if (!Collection.class.isAssignableFrom(f.getType())) {
        throw new IllegalArgumentException(
                "@CollectionRelationship annotations can only be on attributes of Collection type.  Field: "
                        + f.getDeclaringClass().getName() + "." + f.getName() + " (" + f.getType() + ")");
    }

    if (a.collectionElementClass().equals(Object.class)) { // Object is the default (and meaningless anyway)
        Type[] genericArgs = ((ParameterizedType) f.getGenericType()).getActualTypeArguments();
        if (genericArgs.length == 0) {
            throw new IllegalArgumentException(
                    "You can only leave off the collectionElementClass annotation on a @CollectionRelationship when the Collection type has been <typed>.  Field: "
                            + f.getDeclaringClass().getName() + "." + f.getName() + " (" + f.getType() + ")");
        }
        collection.setRelatedType((Class<?>) genericArgs[0]);
    } else {
        collection.setRelatedType(a.collectionElementClass());
    }

    List<DataObjectAttributeRelationship> attributeRelationships = new ArrayList<DataObjectAttributeRelationship>(
            a.attributeRelationships().length);
    for (AttributeRelationship rel : a.attributeRelationships()) {
        attributeRelationships.add(
                new DataObjectAttributeRelationshipImpl(rel.parentAttributeName(), rel.childAttributeName()));
    }
    collection.setAttributeRelationships(attributeRelationships);

    collection.setReadOnly(false);
    collection.setSavedWithParent(false);
    collection.setDeletedWithParent(false);
    collection.setLoadedAtParentLoadTime(true);
    collection.setLoadedDynamicallyUponUse(false);
    List<DataObjectCollectionSortAttribute> sortAttributes = new ArrayList<DataObjectCollectionSortAttribute>(
            a.sortAttributes().length);
    for (CollectionSortAttribute csa : a.sortAttributes()) {
        sortAttributes.add(new DataObjectCollectionSortAttributeImpl(csa.value(), csa.sortDirection()));
    }
    collection.setDefaultCollectionOrderingAttributeNames(sortAttributes);

    collection.setIndirectCollection(a.indirectCollection());
    collection.setMinItemsInCollection(a.minItemsInCollection());
    collection.setMaxItemsInCollection(a.maxItemsInCollection());
    if (StringUtils.isNotBlank(a.label())) {
        collection.setLabel(a.label());
    }
    if (StringUtils.isNotBlank(a.elementLabel())) {
        collection.setLabel(a.elementLabel());
    }

    collections.add(collection);
    metadata.setCollections(collections);
}

From source file:org.castor.jaxb.reflection.ClassInfoBuilder.java

/**
 * Build the FieldInfo for a Field./*  ww w.  j ava  2s. c  o m*/
 * 
 * @param classInfo
 *            the ClassInfo to check if this field already exists
 * @param field
 *            the Field to describe
 * @return the ClassInfo containing the FieldInfo build
 */
private void buildFieldInfo(final ClassInfo classInfo, final Field field) {
    if (classInfo == null) {
        String message = "Argument classInfo must not be null.";
        LOG.warn(message);
        throw new IllegalArgumentException(message);
    }
    if (field == null) {
        String message = "Argument field must not be null.";
        LOG.warn(message);
        throw new IllegalArgumentException(message);
    }
    String fieldName = javaNaming.extractFieldNameFromField(field);
    FieldInfo fieldInfo = classInfo.getFieldInfo(fieldName);
    if (fieldInfo == null) {
        fieldInfo = createFieldInfo(fieldName);
        classInfo.addFieldInfo(fieldInfo);
        fieldInfo.setParentClassInfo(classInfo);
    }
    JaxbFieldNature jaxbFieldNature = new JaxbFieldNature(fieldInfo);
    jaxbFieldNature.setField(field);
    Class<?> fieldType = field.getDeclaringClass();
    if (fieldType.isArray() || fieldType.isAssignableFrom(Collection.class)) {
        jaxbFieldNature.setMultivalued(true);
    }
    jaxbFieldNature.setGenericType(field.getGenericType());
    fieldAnnotationProcessingService.processAnnotations(jaxbFieldNature, field.getAnnotations());
}

From source file:dinistiq.Dinistiq.java

/**
 * Injects all available dependencies into a given bean and records all dependencies.
 *
 * @param key key / name/ id of the bean
 * @param bean bean instance/*from w  w w  .  ja  v  a  2 s  .c  om*/
 * @param dependencies dependencies map where the dependecies of the bean are recorded with the given key
 * @throws Exception
 */
private void injectDependencies(Map<String, Set<Object>> dependencies, String key, Object bean)
        throws Exception {
    // Prepare values from properties files
    Properties beanProperties = getProperties(key);
    LOG.debug("injectDependencies({}) bean properties {}", key, beanProperties.keySet());

    // fill injected fields
    Class<? extends Object> beanClass = bean.getClass();
    String beanClassName = beanClass.getName();
    while (beanClass != Object.class) {
        if (bean instanceof Map) {
            fillMap(bean, getProperties(key));
            LOG.info("injectDependencies() filled map '{}' {}", key, bean);
            return; // If it's a map we don't need to inject anything beyond some map properties files.
        } // if
        for (Field field : beanClass.getDeclaredFields()) {
            LOG.debug("injectDependencies({}) field {}", key, field.getName());
            if (field.getAnnotation(Inject.class) != null) {
                Named named = field.getAnnotation(Named.class);
                String name = (named == null) ? null
                        : (StringUtils.isBlank(named.value()) ? field.getName() : named.value());
                LOG.info("injectDependencies({}) {} :{} needs injection with name {}", key, field.getName(),
                        field.getGenericType(), name);
                Object b = getValue(beanProperties, dependencies, key, field.getType(), field.getGenericType(),
                        name);
                final boolean accessible = field.isAccessible();
                try {
                    field.setAccessible(true);
                    field.set(bean, b);
                } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
                    LOG.error("injectDependencies() error setting field " + field.getName() + " :"
                            + field.getType().getName() + " at '" + key + "' :" + beanClassName, e);
                } finally {
                    field.setAccessible(accessible);
                } // try/catch
            } // if
        } // for
        beanClass = beanClass.getSuperclass();
    } // while

    // call methods with annotated injections
    for (Method m : bean.getClass().getMethods()) {
        if (m.getAnnotation(Inject.class) != null) {
            LOG.debug("injectDependencies({}) inject parameters on method {}", key, m.getName());
            Class<? extends Object>[] parameterTypes = m.getParameterTypes();
            Type[] genericParameterTypes = m.getGenericParameterTypes();
            Annotation[][] parameterAnnotations = m.getParameterAnnotations();
            Object[] parameters = getParameters(beanProperties, dependencies, key, parameterTypes,
                    genericParameterTypes, parameterAnnotations);
            try {
                m.invoke(bean, parameters);
            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
                LOG.error("injectDependencies() error injecting for method " + m.getName() + " at '" + key
                        + "' :" + beanClassName, ex);
            } // try/catch
        } // if
    } // for

    // Fill in manually set values from properties file
    for (String property : beanProperties.stringPropertyNames()) {
        String methodName = "set" + property.substring(0, 1).toUpperCase() + property.substring(1);
        LOG.debug("injectDependencies({}) {} -> {}", key, property, methodName);
        Method m = null;
        // Have to find it just by name
        for (Method me : bean.getClass().getMethods()) {
            if (me.getName().equals(methodName) && (me.getParameterTypes().length > 0)) {
                m = me;
            } // if
        } // for
        if (m == null) {
            LOG.warn("injectDependencies({}) no setter method found for property {}", key, property);
        } else {
            String propertyName = Introspector.decapitalize(m.getName().substring(3));
            Class<?> parameterType = m.getParameterTypes()[0];
            Type genericType = m.getGenericParameterTypes()[0];
            LOG.debug("injectDependencies({}) writable property found {} :{} {}", key, propertyName,
                    parameterType, genericType);
            String propertyValue = beanProperties.getProperty(propertyName); // Must definetely be there without additional check
            boolean isBoolean = (parameterType == Boolean.class) || (m.getParameterTypes()[0] == Boolean.TYPE);
            boolean isCollection = Collection.class.isAssignableFrom(parameterType);
            Object[] parameters = new Object[1];
            LOG.debug("injectDependencies({}) trying to set value {} (bool {}) (collection {}) '{}'", key,
                    propertyName, isBoolean, isCollection, propertyValue);
            try {
                parameters[0] = getReferenceValue(propertyValue);
                if (isBoolean && (parameters[0] instanceof String)) {
                    parameters[0] = Boolean.valueOf(propertyValue);
                } // if
                if ("long".equals(parameterType.getName())) {
                    parameters[0] = new Long(propertyValue);
                } // if
                if ("int".equals(parameterType.getName())) {
                    parameters[0] = new Integer(propertyValue);
                } // if
                if ("float".equals(parameterType.getName())) {
                    parameters[0] = new Float(propertyValue);
                } // if
                if ("double".equals(parameterType.getName())) {
                    parameters[0] = new Double(propertyValue);
                } // if
                if (isCollection) {
                    if (!Collection.class.isAssignableFrom(parameters[0].getClass())) {
                        Collection<Object> values = List.class.isAssignableFrom(parameterType)
                                ? new ArrayList<>()
                                : new HashSet<>();
                        for (String value : propertyValue.split(",")) {
                            values.add(getReferenceValue(value));
                        } // for
                        parameters[0] = values;
                    } // if
                    if (dependencies != null) {
                        for (Object d : (Collection<?>) parameters[0]) {
                            if (beans.containsValue(d)) {
                                dependencies.get(key).add(d);
                            } // if
                        } // if
                    } // if
                } else {
                    if ((dependencies != null) && (beans.containsValue(parameters[0]))) {
                        dependencies.get(key).add(parameters[0]);
                    } // if
                } // if
                LOG.debug("injectDependencies({}) setting value {} '{}' :{}", key, propertyName, parameters[0],
                        parameters[0].getClass());
                m.invoke(bean, parameters);
            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
                LOG.error("injectDependencies() error setting property " + propertyName + " to '"
                        + propertyValue + "' at " + key + " :" + beanClassName, ex);
            } // try/catch
        } // if
    } // for
}

From source file:com.eucalyptus.objectstorage.pipeline.binding.ObjectStorageRESTBinding.java

protected List<String> populateObjectList(final GroovyObject obj,
        final Map.Entry<String, String> paramFieldPair, final Map<String, String> params, final int paramSize) {
    List<String> failedMappings = new ArrayList<String>();
    try {//from  w  ww.  j  a v  a 2 s.c o  m
        Field declaredField = obj.getClass().getDeclaredField(paramFieldPair.getValue());
        ArrayList theList = (ArrayList) obj.getProperty(paramFieldPair.getValue());
        Class genericType = (Class) ((ParameterizedType) declaredField.getGenericType())
                .getActualTypeArguments()[0];
        // :: simple case: FieldName.# :://
        if (String.class.equals(genericType)) {
            if (params.containsKey(paramFieldPair.getKey())) {
                theList.add(params.remove(paramFieldPair.getKey()));
            } else {
                List<String> keys = Lists.newArrayList(params.keySet());
                for (String k : keys) {
                    if (k.matches(paramFieldPair.getKey() + "\\.\\d*")) {
                        theList.add(params.remove(k));
                    }
                }
            }
        } else if (declaredField.isAnnotationPresent(HttpEmbedded.class)) {
            HttpEmbedded annoteEmbedded = (HttpEmbedded) declaredField.getAnnotation(HttpEmbedded.class);
            // :: build the parameter map and call populate object recursively :://
            if (annoteEmbedded.multiple()) {
                String prefix = paramFieldPair.getKey();
                List<String> embeddedListFieldNames = new ArrayList<String>();
                for (String actualParameterName : params.keySet())
                    if (actualParameterName.matches(prefix + ".1.*"))
                        embeddedListFieldNames.add(actualParameterName.replaceAll(prefix + ".1.", ""));
                for (int i = 0; i < paramSize + 1; i++) {
                    boolean foundAll = true;
                    Map<String, String> embeddedParams = new HashMap<String, String>();
                    for (String fieldName : embeddedListFieldNames) {
                        String paramName = prefix + "." + i + "." + fieldName;
                        if (!params.containsKey(paramName)) {
                            failedMappings.add("Mismatched embedded field: " + paramName);
                            foundAll = false;
                        } else
                            embeddedParams.put(fieldName, params.get(paramName));
                    }
                    if (foundAll)
                        failedMappings.addAll(populateEmbedded(genericType, embeddedParams, theList));
                    else
                        break;
                }
            } else
                failedMappings.addAll(populateEmbedded(genericType, params, theList));
        }
    } catch (Exception e1) {
        failedMappings.add(paramFieldPair.getKey());
    }
    return failedMappings;
}

From source file:com.eucalyptus.objectstorage.pipeline.WalrusRESTBinding.java

private List<String> populateObjectList(final GroovyObject obj, final Map.Entry<String, String> paramFieldPair,
        final Map<String, String> params, final int paramSize) {
    List<String> failedMappings = new ArrayList<String>();
    try {//from w w  w .  j  a va 2  s  . c om
        Field declaredField = obj.getClass().getDeclaredField(paramFieldPair.getValue());
        ArrayList theList = (ArrayList) obj.getProperty(paramFieldPair.getValue());
        Class genericType = (Class) ((ParameterizedType) declaredField.getGenericType())
                .getActualTypeArguments()[0];
        // :: simple case: FieldName.# :://
        if (String.class.equals(genericType)) {
            if (params.containsKey(paramFieldPair.getKey())) {
                theList.add(params.remove(paramFieldPair.getKey()));
            } else {
                List<String> keys = Lists.newArrayList(params.keySet());
                for (String k : keys) {
                    if (k.matches(paramFieldPair.getKey() + "\\.\\d*")) {
                        theList.add(params.remove(k));
                    }
                }
            }
        } else if (declaredField.isAnnotationPresent(HttpEmbedded.class)) {
            HttpEmbedded annoteEmbedded = (HttpEmbedded) declaredField.getAnnotation(HttpEmbedded.class);
            // :: build the parameter map and call populate object recursively :://
            if (annoteEmbedded.multiple()) {
                String prefix = paramFieldPair.getKey();
                List<String> embeddedListFieldNames = new ArrayList<String>();
                for (String actualParameterName : params.keySet())
                    if (actualParameterName.matches(prefix + ".1.*"))
                        embeddedListFieldNames.add(actualParameterName.replaceAll(prefix + ".1.", ""));
                for (int i = 0; i < paramSize + 1; i++) {
                    boolean foundAll = true;
                    Map<String, String> embeddedParams = new HashMap<String, String>();
                    for (String fieldName : embeddedListFieldNames) {
                        String paramName = prefix + "." + i + "." + fieldName;
                        if (!params.containsKey(paramName)) {
                            failedMappings.add("Mismatched embedded field: " + paramName);
                            foundAll = false;
                        } else
                            embeddedParams.put(fieldName, params.get(paramName));
                    }
                    if (foundAll)
                        failedMappings.addAll(populateEmbedded(genericType, embeddedParams, theList));
                    else
                        break;
                }
            } else
                failedMappings.addAll(populateEmbedded(genericType, params, theList));
        }
    } catch (Exception e1) {
        failedMappings.add(paramFieldPair.getKey());
    }
    return failedMappings;
}