Example usage for java.lang Class getFields

List of usage examples for java.lang Class getFields

Introduction

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

Prototype

@CallerSensitive
public Field[] getFields() throws SecurityException 

Source Link

Document

Returns an array containing Field objects reflecting all the accessible public fields of the class or interface represented by this Class object.

Usage

From source file:es.logongas.ix3.web.controllers.SearchHelper.java

public Map<String, Object> getParametersSearchFromWebParameters(Map<String, String[]> parametersMap,
        CRUDBusinessProcess crudBusinessProcess, String methodName, DataSession dataSession)
        throws BusinessException {
    Map<String, Object> parameters = new HashMap<String, Object>();
    Class businessProcessArgumentsClass = getBusinessProcessMethodArguments(crudBusinessProcess, methodName);
    Map<String, String[]> webParameters = removeDollarParameters(parametersMap);

    for (Field field : businessProcessArgumentsClass.getFields()) {
        String parameterName = field.getName();
        Class parameterType = field.getType();
        String stringParameterValue;
        Object parameterValue;/*from   w  w  w  .  java2 s .co m*/

        if (webParameters.get(parameterName) == null) {
            stringParameterValue = "";
        } else {

            if (webParameters.get(parameterName).length != 1) {
                throw new RuntimeException("El parametro de la peticin http '" + parameterName
                        + "' solo puede teenr un nico valor pero tiene:"
                        + webParameters.get(parameterName).length);
            }

            stringParameterValue = webParameters.get(parameterName)[0];
        }

        MetaData metaDataParameter = metaDataFactory.getMetaData(parameterType);
        if (metaDataParameter != null) {
            //El parmetro es una Entidad de negocio pero solo nos han pasado la clave primaria.

            //Vamos a obtener el tipo de la clave primaria
            Class primaryKeyType = metaDataParameter.getPropertiesMetaData()
                    .get(metaDataParameter.getPrimaryKeyPropertyName()).getType();

            //Ahora vamos a obtener el valor de la clave primaria
            Serializable primaryKey;
            try {
                primaryKey = (Serializable) conversion.convertFromString(stringParameterValue, primaryKeyType);
            } catch (Exception ex) {
                throw new BusinessException("El parmetro " + field.getName()
                        + " no tiene el formato adecuado para ser una PK:" + stringParameterValue);
            }

            if (primaryKey == null) {
                parameterValue = null;
            } else {
                //Y finalmente Leemos la entidad en funcin de la clave primaria
                CRUDService crudServiceParameter = crudServiceFactory.getService(parameterType);
                parameterValue = crudServiceParameter.read(dataSession, primaryKey);
                if (parameterValue == null) {
                    throw new BusinessException("El parmetro " + field.getName() + " con valor '"
                            + stringParameterValue + "' no es de ninguna entidad.");
                }
            }
        } else {
            try {
                parameterValue = conversion.convertFromString(stringParameterValue, parameterType);
            } catch (Exception ex) {
                throw new BusinessException("El parmetro " + field.getName()
                        + " no tiene el formato adecuado:" + stringParameterValue);
            }
        }

        parameters.put(parameterName, parameterValue);

    }

    return parameters;
}

From source file:de.innovationgate.webgate.api.WGFactory.java

/**
 * retrieves all metainfos of the given class
 * @param c/*from w w  w.  j  a  v a  2  s .com*/
 * @return Map of meta infos
 */
private Map<String, MetaInfo> gatherMetaInfos(Class<? extends MetaInfoProvider> c) {
    Map<String, MetaInfo> map = new HashMap<String, MetaInfo>();
    Field[] fields = c.getFields();
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];
        if (field.getName().startsWith("META_")) {
            try {
                String metaName = (String) field.get(null);
                String metaInfoFieldName = "METAINFO_" + field.getName().substring(5, field.getName().length());
                Field metaInfoField = c.getField(metaInfoFieldName);
                MetaInfo metaInfo = (MetaInfo) metaInfoField.get(null);
                // check info
                if (!metaName.equals(metaInfo.getName())) {
                    throw new RuntimeException(
                            "Unable to initialize metadata-framework. MetaInfo for metafield '"
                                    + field.getName() + "' of class ' " + c.getName()
                                    + "' is invalid. Name mismatch!.");
                }
                metaInfo.setDefiningClass(c);
                map.put(metaName, metaInfo);

            } catch (IllegalAccessException e) {
                throw new RuntimeException("Unable to initialize metadata-framework.", e);
            } catch (SecurityException e) {
                throw new RuntimeException("Unable to initialize metadata-framework.", e);
            } catch (NoSuchFieldException e) {
                throw new RuntimeException("Unable to initialize metadata-framework. MetaInfo for metafield '"
                        + field.getName() + "' of class '" + c.getName() + "' not found.", e);
            }
        }
    }
    return map;
}

From source file:es.logongas.ix3.web.controllers.SearchHelper.java

public Object executeNamedSearchParameters(Principal principal, DataSession dataSession,
        CRUDBusinessProcess crudBusinessProcess, String namedSearch, Map<String, Object> filter,
        PageRequest pageRequest, List<Order> orders, SearchResponse searchResponse) throws BusinessException {
    try {//from ww  w  . j av a2 s . c o m
        if (getNamedSearchType(crudBusinessProcess, namedSearch) != NameSearchType.PARAMETERS) {
            throw new RuntimeException("El mtodo '" + namedSearch + "' de '" + crudBusinessProcess.getClass()
                    + "' debe ser de tipo Parameters");
        }

        if (filter == null) {
            filter = new HashMap<String, Object>();
        }
        if (orders == null) {
            orders = new ArrayList<Order>();
        }

        Class businessProcessArgumentsClass = getBusinessProcessMethodArguments(crudBusinessProcess,
                namedSearch);

        Object businessProcessArgument = businessProcessArgumentsClass.newInstance();

        for (Field field : businessProcessArgumentsClass.getFields()) {
            Class parameterClass = field.getType();
            if (parameterClass.isAssignableFrom(PageRequest.class) == true) {
                field.set(businessProcessArgument, pageRequest);
            } else if (parameterClass.isAssignableFrom(orders.getClass()) == true) {
                field.set(businessProcessArgument, orders);
            } else if (parameterClass.isAssignableFrom(SearchResponse.class) == true) {
                field.set(businessProcessArgument, searchResponse);
            } else if (parameterClass.isAssignableFrom(Principal.class) == true) {
                field.set(businessProcessArgument, principal);
            } else if (parameterClass.isAssignableFrom(DataSession.class) == true) {
                field.set(businessProcessArgument, dataSession);
            } else {
                Object parameterValue = filter.get(field.getName());
                field.set(businessProcessArgument, parameterValue);
            }

        }

        Method method = ReflectionUtil.getDeclaredMethod(crudBusinessProcess.getClass(), namedSearch);
        Object result = method.invoke(crudBusinessProcess, businessProcessArgument);

        return result;

    } catch (InvocationTargetException ex) {
        BusinessException businessException = ExceptionUtil.getBusinessExceptionFromThrowable(ex);
        if (businessException != null) {
            throw businessException;
        } else {
            throw new RuntimeException(ex);
        }
    } catch (RuntimeException ex) {
        throw ex;
    } catch (BusinessException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:es.logongas.ix3.web.controllers.SearchHelper.java

public Object executeNamedSearchFilters(Principal principal, DataSession dataSession,
        CRUDBusinessProcess crudBusinessProcess, String namedSearch, Filters filters, PageRequest pageRequest,
        List<Order> orders, SearchResponse searchResponse) throws BusinessException {
    try {//w  w w.j  av a  2  s .  co  m
        if (getNamedSearchType(crudBusinessProcess, namedSearch) != NameSearchType.FILTER) {
            throw new RuntimeException("El mtodo '" + namedSearch + "' de '" + crudBusinessProcess.getClass()
                    + "' debe ser de tipo Filter");
        }

        if (filters == null) {
            filters = new Filters();
        }

        if (orders == null) {
            orders = new ArrayList<Order>();
        }

        Class businessProcessArgumentsClass = getBusinessProcessMethodArguments(crudBusinessProcess,
                namedSearch);

        Object businessProcessArgument = businessProcessArgumentsClass.newInstance();

        for (Field field : businessProcessArgumentsClass.getFields()) {
            Class parameterClass = field.getType();
            if (parameterClass.isAssignableFrom(filters.getClass()) == true) {
                field.set(businessProcessArgument, filters);
            } else if (parameterClass.isAssignableFrom(PageRequest.class) == true) {
                field.set(businessProcessArgument, pageRequest);
            } else if (parameterClass.isAssignableFrom(orders.getClass()) == true) {
                field.set(businessProcessArgument, orders);
            } else if (parameterClass.isAssignableFrom(SearchResponse.class) == true) {
                field.set(businessProcessArgument, searchResponse);
            } else if (parameterClass.isAssignableFrom(Principal.class) == true) {
                field.set(businessProcessArgument, principal);
            } else if (parameterClass.isAssignableFrom(DataSession.class) == true) {
                field.set(businessProcessArgument, dataSession);
            } else {
                throw new RuntimeException("El tipo del argumento no es vlido");
            }
        }

        Method method = ReflectionUtil.getMethod(crudBusinessProcess.getClass(), namedSearch);
        Object result = method.invoke(crudBusinessProcess, businessProcessArgument);

        return result;

    } catch (InvocationTargetException ex) {
        BusinessException businessException = ExceptionUtil.getBusinessExceptionFromThrowable(ex);
        if (businessException != null) {
            throw businessException;
        } else {
            throw new RuntimeException(ex);
        }
    } catch (RuntimeException ex) {
        throw ex;
    } catch (BusinessException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.cloudera.livy.client.common.TestHttpMessages.java

/**
 * Tests that all defined messages can be serialized and deserialized using Jackson.
 */// ww w  . j a va  2 s . c om
@Test
public void testMessageSerialization() throws Exception {
    ObjectMapper mapper = new ObjectMapper();

    for (Class<?> msg : HttpMessages.class.getClasses()) {
        if (msg.isInterface()) {
            continue;
        }

        String name = msg.getSimpleName();

        Constructor c = msg.getConstructors()[0];
        Object[] params = new Object[c.getParameterTypes().length];
        Type[] genericTypes = c.getGenericParameterTypes();
        for (int i = 0; i < params.length; i++) {
            params[i] = dummyValue(c.getParameterTypes()[i], genericTypes[i]);
        }

        Object o1 = c.newInstance(params);
        byte[] serialized = mapper.writeValueAsBytes(o1);
        Object o2 = mapper.readValue(serialized, msg);

        assertNotNull("could not deserialize " + name, o2);
        for (Field f : msg.getFields()) {
            checkEquals(name, f, o1, o2);
        }
    }

}

From source file:com.streamsets.datacollector.definition.ConfigDefinitionExtractor.java

private List<ErrorMessage> validate(String configPrefix, Class klass, List<String> stageGroups,
        boolean validateDependencies, boolean isBean, boolean isComplexField, Object contextMsg) {
    List<ErrorMessage> errors = new ArrayList<>();
    boolean noConfigs = true;
    for (Field field : klass.getFields()) {
        if (field.getAnnotation(ConfigDef.class) != null && field.getAnnotation(ConfigDefBean.class) != null) {
            errors.add(new ErrorMessage(DefinitionError.DEF_152, contextMsg, field.getName()));
        } else {/*  w w w  .  j  av  a2s.  co  m*/
            if (field.getAnnotation(ConfigDef.class) != null
                    || field.getAnnotation(ConfigDefBean.class) != null) {
                if (Modifier.isStatic(field.getModifiers())) {
                    errors.add(new ErrorMessage(DefinitionError.DEF_151, contextMsg, klass.getSimpleName(),
                            field.getName()));
                }
                if (Modifier.isFinal(field.getModifiers())) {
                    errors.add(new ErrorMessage(DefinitionError.DEF_154, contextMsg, klass.getSimpleName(),
                            field.getName()));
                }
            }
            if (field.getAnnotation(ConfigDef.class) != null) {
                noConfigs = false;
                List<ErrorMessage> subErrors = validateConfigDef(configPrefix, stageGroups, field,
                        isComplexField, Utils.formatL("{} Field='{}'", contextMsg, field.getName()));
                errors.addAll(subErrors);
            } else if (field.getAnnotation(ConfigDefBean.class) != null) {
                noConfigs = false;
                List<ErrorMessage> subErrors = validateConfigDefBean(configPrefix + field.getName() + ".",
                        field, stageGroups, isComplexField,
                        Utils.formatL("{} BeanField='{}'", contextMsg, field.getName()));
                errors.addAll(subErrors);
            }
        }
    }
    if (isBean && noConfigs) {
        errors.add(new ErrorMessage(DefinitionError.DEF_160, contextMsg));
    }
    if (errors.isEmpty() & validateDependencies) {
        errors.addAll(validateDependencies(getConfigDefinitions(configPrefix, klass, stageGroups, contextMsg),
                contextMsg));
    }
    return errors;
}

From source file:ch.unil.genescore.main.PascalSettings.java

/** Dump all settings to a file (ugly format without comments) */
public void dumpSettingsToFile() {

    FileExport writer = new FileExport(Pascal.log, new File(outputDirectory_, "settingsDump.txt"));
    try {//from  w w w . j  av a2 s  . c  o m
        Class<?> cls = Class.forName("ch.unil.genescore.main.Settings");
        System.out.println("Class found = " + cls.getName());
        System.out.println("Package = " + cls.getPackage());
        Field f[] = cls.getFields();
        for (int i = 0; i < f.length; i++) {
            String result = String.format("%s\t%s", f[i].getName(), f[i].get(null));
            writer.println(result);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        writer.close();
    }
}

From source file:org.apache.openjpa.lib.util.Options.java

/**
 * Matches a key to an object/setter pair.
 *
 * @param key the key given at the command line; may be of the form
 * 'foo.bar' to signify the 'bar' property of the 'foo' owned object
 * @param match an array of length 2, where the first index is set
 * to the object to retrieve the setter for
 * @return true if a match was made, false otherwise; additionally,
 * the first index of the match array will be set to
 * the matching object and the second index will be
 * set to the setter method or public field for the
 * property named by the key/*w  ww .j  ava  2  s . c o m*/
 */
private static boolean matchOptionToMember(String key, Object[] match) throws Exception {
    if (StringUtils.isEmpty(key))
        return false;

    // unfortunately we can't use bean properties for setters; any
    // setter with more than 1 argument is ignored; calculate setter and getter
    // name to look for
    String[] find = Strings.split(key, ".", 2);
    String base = StringUtils.capitalize(find[0]);
    String set = "set" + base;
    String get = "get" + base;

    // look for a setter/getter matching the key; look for methods first
    Class<? extends Object> type = match[0].getClass();
    Method[] meths = type.getMethods();
    Method setMeth = null;
    Method getMeth = null;
    Class[] params;
    for (int i = 0; i < meths.length; i++) {
        if (meths[i].getName().equals(set)) {
            params = meths[i].getParameterTypes();
            if (params.length == 0)
                continue;
            if (params[0].isArray())
                continue;

            // use this method if we haven't found any other setter, if
            // it has less parameters than any other setter, or if it uses
            // string parameters
            if (setMeth == null)
                setMeth = meths[i];
            else if (params.length < setMeth.getParameterTypes().length)
                setMeth = meths[i];
            else if (params.length == setMeth.getParameterTypes().length && params[0] == String.class)
                setMeth = meths[i];
        } else if (meths[i].getName().equals(get))
            getMeth = meths[i];
    }

    // if no methods found, check for public field
    Member setter = setMeth;
    Member getter = getMeth;
    if (setter == null) {
        Field[] fields = type.getFields();
        String uncapBase = StringUtils.uncapitalize(find[0]);
        for (int i = 0; i < fields.length; i++) {
            if (fields[i].getName().equals(base) || fields[i].getName().equals(uncapBase)) {
                setter = fields[i];
                getter = fields[i];
                break;
            }
        }
    }

    // if no way to access property, give up
    if (setter == null && getter == null)
        return false;

    // recurse on inner object with remainder of key?
    if (find.length > 1) {
        Object inner = null;
        if (getter != null)
            inner = invoke(match[0], getter, null);

        // if no getter or current inner is null, try to create a new
        // inner instance and set it in object
        if (inner == null && setter != null) {
            Class<?> innerType = getType(setter)[0];
            try {
                inner = AccessController.doPrivileged(J2DoPrivHelper.newInstanceAction(innerType));
            } catch (PrivilegedActionException pae) {
                throw pae.getException();
            }
            invoke(match[0], setter, new Object[] { inner });
        }
        match[0] = inner;
        return matchOptionToMember(find[1], match);
    }

    // got match; find setter for property
    match[1] = setter;
    return match[1] != null;
}

From source file:org.eclipse.wb.internal.rcp.databinding.emf.model.bindables.PropertiesSupport.java

private Map<String, ClassInfo> loadEmfClassInfos(IType literalsType, Set<String> allClasses) throws Exception {
    Class<?> literalsClass = m_classLoader.loadClass(literalsType.getFullyQualifiedName());
    String packageName = literalsClass.getPackage().getName();
    Map<String, ClassInfo> packageClasses = Maps.newHashMap();
    String literalsReference = literalsType.getFullyQualifiedName('.') + ".";
    List<Field> eClasses = Lists.newArrayList();
    List<Field> eProperties = Lists.newArrayList();
    // collect literals
    for (Field field : literalsClass.getFields()) {
        Class<?> fieldType = field.getType();
        if (m_EClass.isAssignableFrom(fieldType)) {
            eClasses.add(field);//from w ww.  j  ava  2 s . c om
        } else if (m_EAttribute.isAssignableFrom(fieldType) || m_EReference.isAssignableFrom(fieldType)
                || m_EStructuralFeature.isAssignableFrom(fieldType)) {
            eProperties.add(field);
        }
    }
    // process EClass & its properties
    for (Field eClassField : eClasses) {
        String fieldName = eClassField.getName();
        ClassInfo classInfo = new ClassInfo(fieldName);
        packageClasses.put(fieldName, classInfo);
        //
        String unformatClassName = packageName + "." + EmfCodeGenUtil.unformat(classInfo.className);
        //
        try {
            classInfo.thisClass = m_classLoader.loadClass(unformatClassName);
        } catch (Throwable e) {
            for (String className : allClasses) {
                if (unformatClassName.equalsIgnoreCase(className)) {
                    try {
                        classInfo.thisClass = m_classLoader.loadClass(className);
                    } catch (Throwable t) {
                    }
                }
            }
        }
        //
        String propertyPrefix = fieldName + "__";
        for (Field ePropertyField : eProperties) {
            String propertyName = ePropertyField.getName();
            if (propertyName.startsWith(propertyPrefix)) {
                classInfo.properties.add(new PropertyInfo(classInfo, literalsReference + propertyName,
                        propertyName.substring(propertyPrefix.length())));
            }
        }
    }
    //
    for (ClassInfo classInfo : packageClasses.values()) {
        linkClassProperties(classInfo);
    }
    //
    return packageClasses;
}

From source file:ca.uhn.fhir.context.ModelScanner.java

private void scanResourceForSearchParams(Class<? extends IBaseResource> theClass,
        RuntimeResourceDefinition theResourceDef) {

    Map<String, RuntimeSearchParam> nameToParam = new HashMap<String, RuntimeSearchParam>();
    Map<Field, SearchParamDefinition> compositeFields = new LinkedHashMap<Field, SearchParamDefinition>();

    for (Field nextField : theClass.getFields()) {
        SearchParamDefinition searchParam = pullAnnotation(nextField, SearchParamDefinition.class);
        if (searchParam != null) {
            RestSearchParameterTypeEnum paramType = RestSearchParameterTypeEnum
                    .forCode(searchParam.type().toLowerCase());
            if (paramType == null) {
                throw new ConfigurationException(
                        "Search param " + searchParam.name() + " has an invalid type: " + searchParam.type());
            }// ww  w.  ja v a  2s .com
            Set<String> providesMembershipInCompartments = null;
            providesMembershipInCompartments = new HashSet<String>();
            for (Compartment next : searchParam.providesMembershipIn()) {
                if (paramType != RestSearchParameterTypeEnum.REFERENCE) {
                    StringBuilder b = new StringBuilder();
                    b.append("Search param ");
                    b.append(searchParam.name());
                    b.append(" on resource type ");
                    b.append(theClass.getName());
                    b.append(" provides compartment membership but is not of type 'reference'");
                    ourLog.warn(b.toString());
                    continue;
                    //                  throw new ConfigurationException(b.toString());
                }
                providesMembershipInCompartments.add(next.name());
            }

            if (paramType == RestSearchParameterTypeEnum.COMPOSITE) {
                compositeFields.put(nextField, searchParam);
                continue;
            }

            RuntimeSearchParam param = new RuntimeSearchParam(searchParam.name(), searchParam.description(),
                    searchParam.path(), paramType, providesMembershipInCompartments,
                    toTargetList(searchParam.target()));
            theResourceDef.addSearchParam(param);
            nameToParam.put(param.getName(), param);
        }
    }

    for (Entry<Field, SearchParamDefinition> nextEntry : compositeFields.entrySet()) {
        SearchParamDefinition searchParam = nextEntry.getValue();

        List<RuntimeSearchParam> compositeOf = new ArrayList<RuntimeSearchParam>();
        for (String nextName : searchParam.compositeOf()) {
            RuntimeSearchParam param = nameToParam.get(nextName);
            if (param == null) {
                ourLog.warn(
                        "Search parameter {}.{} declares that it is a composite with compositeOf value '{}' but that is not a valid parametr name itself. Valid values are: {}",
                        new Object[] { theResourceDef.getName(), searchParam.name(), nextName,
                                nameToParam.keySet() });
                continue;
            }
            compositeOf.add(param);
        }

        RuntimeSearchParam param = new RuntimeSearchParam(searchParam.name(), searchParam.description(),
                searchParam.path(), RestSearchParameterTypeEnum.COMPOSITE, compositeOf, null,
                toTargetList(searchParam.target()));
        theResourceDef.addSearchParam(param);
    }
}