Example usage for org.springframework.util ReflectionUtils findField

List of usage examples for org.springframework.util ReflectionUtils findField

Introduction

In this page you can find the example usage for org.springframework.util ReflectionUtils findField.

Prototype

@Nullable
public static Field findField(Class<?> clazz, String name) 

Source Link

Document

Attempt to find a Field field on the supplied Class with the supplied name .

Usage

From source file:org.apache.syncope.core.persistence.jpa.dao.AbstractDAO.java

protected String toOrderByStatement(final Class<? extends Entity<KEY>> beanClass, final String prefix,
        final List<OrderByClause> orderByClauses) {

    StringBuilder statement = new StringBuilder();

    for (OrderByClause clause : orderByClauses) {
        String field = clause.getField().trim();
        if (ReflectionUtils.findField(beanClass, field) != null) {
            if (StringUtils.isNotBlank(prefix)) {
                statement.append(prefix).append('.');
            }//from  w  w  w. j  a va 2s . com
            statement.append(field).append(' ').append(clause.getDirection().name());
        }
    }

    if (statement.length() > 0) {
        statement.insert(0, "ORDER BY ");
    }
    return statement.toString();
}

From source file:org.apache.syncope.core.persistence.jpa.dao.ElasticsearchAnySearchDAO.java

private void addSort(final SearchRequestBuilder builder, final AnyTypeKind kind,
        final List<OrderByClause> orderBy) {

    AnyUtils attrUtils = anyUtilsFactory.getInstance(kind);

    orderBy.forEach(clause -> {/*w  ww  . jav a2  s. c o  m*/
        String sortName = null;

        // Manage difference among external key attribute and internal JPA @Id
        String fieldName = "key".equals(clause.getField()) ? "id" : clause.getField();

        Field anyField = ReflectionUtils.findField(attrUtils.anyClass(), fieldName);
        if (anyField == null) {
            PlainSchema schema = schemaDAO.find(fieldName);
            if (schema != null) {
                sortName = fieldName;
            }
        } else {
            sortName = fieldName;
        }

        if (sortName == null) {
            LOG.warn("Cannot build any valid clause from {}", clause);
        } else {
            builder.addSort(sortName, SortOrder.valueOf(clause.getDirection().name()));
        }
    });
}

From source file:org.apache.syncope.core.persistence.jpa.dao.JPAAccessTokenDAO.java

private String toOrderByStatement(final List<OrderByClause> orderByClauses) {
    StringBuilder statement = new StringBuilder();

    for (OrderByClause clause : orderByClauses) {
        String field = clause.getField().trim();
        if (ReflectionUtils.findField(JPAAccessToken.class, field) != null) {
            statement.append("e.").append(field).append(' ').append(clause.getDirection().name());
        }//w  ww.j  av a2s  . c  o  m
    }

    if (statement.length() == 0) {
        statement.append("ORDER BY e.expiryTime DESC");
    } else {
        statement.insert(0, "ORDER BY ");
    }
    return statement.toString();
}

From source file:org.apache.syncope.core.persistence.jpa.dao.JPAAnySearchDAO.java

private OrderBySupport parseOrderBy(final AnyTypeKind kind, final SearchSupport svs,
        final List<OrderByClause> orderByClauses) {

    AnyUtils attrUtils = anyUtilsFactory.getInstance(kind);

    OrderBySupport obs = new OrderBySupport();

    for (OrderByClause clause : orderByClauses) {
        OrderBySupport.Item item = new OrderBySupport.Item();

        // Manage difference among external key attribute and internal JPA @Id
        String fieldName = "key".equals(clause.getField()) ? "id" : clause.getField();

        if (ReflectionUtils.findField(attrUtils.anyClass(), fieldName) == null) {
            PlainSchema schema = schemaDAO.find(fieldName);
            if (schema != null) {
                // keep track of involvement of non-mandatory schemas in the order by clauses
                obs.nonMandatorySchemas = !"true".equals(schema.getMandatoryCondition());

                if (schema.isUniqueConstraint()) {
                    obs.views.add(svs.uniqueAttr());

                    item.select = new StringBuilder().append(svs.uniqueAttr().alias).append('.')
                            .append(svs.fieldName(schema.getType())).append(" AS ").append(fieldName)
                            .toString();
                    item.where = new StringBuilder().append(svs.uniqueAttr().alias).append(".schema_id='")
                            .append(fieldName).append("'").toString();
                    item.orderBy = fieldName + " " + clause.getDirection().name();
                } else {
                    obs.views.add(svs.attr());

                    item.select = new StringBuilder().append(svs.attr().alias).append('.')
                            .append(svs.fieldName(schema.getType())).append(" AS ").append(fieldName)
                            .toString();
                    item.where = new StringBuilder().append(svs.attr().alias).append(".schema_id='")
                            .append(fieldName).append("'").toString();
                    item.orderBy = fieldName + " " + clause.getDirection().name();
                }// w ww .j  a  va 2  s.co  m
            }
        } else {
            // Adjust field name to column name
            fieldName = "realm".equals(fieldName) ? "realm_id" : fieldName;

            obs.views.add(svs.field());

            item.select = svs.field().alias + "." + fieldName;
            item.where = StringUtils.EMPTY;
            item.orderBy = svs.field().alias + "." + fieldName + " " + clause.getDirection().name();
        }

        if (item.isEmpty()) {
            LOG.warn("Cannot build any valid clause from {}", clause);
        } else {
            obs.items.add(item);
        }
    }

    return obs;
}

From source file:org.apache.syncope.core.persistence.jpa.dao.JPASubjectSearchDAO.java

private OrderBySupport parseOrderBy(final SubjectType type, final SearchSupport svs,
        final List<OrderByClause> orderByClauses) {

    final AttributableUtil attrUtil = attrUtilFactory.getInstance(type.asAttributableType());

    OrderBySupport orderBySupport = new OrderBySupport();

    for (OrderByClause clause : orderByClauses) {
        OrderBySupport.Item obs = new OrderBySupport.Item();

        // Manage difference among external key attribute and internal JPA @Id
        String fieldName = "key".equals(clause.getField()) ? "id" : clause.getField();

        Field subjectField = ReflectionUtils.findField(attrUtil.attributableClass(), fieldName);
        if (subjectField == null) {
            PlainSchema schema = schemaDAO.find(fieldName, attrUtil.plainSchemaClass());
            if (schema != null) {
                if (schema.isUniqueConstraint()) {
                    orderBySupport.views.add(svs.uniqueAttr());

                    obs.select = new StringBuilder().append(svs.uniqueAttr().alias).append('.')
                            .append(svs.fieldName(schema.getType())).append(" AS ").append(fieldName)
                            .toString();
                    obs.where = new StringBuilder().append(svs.uniqueAttr().alias).append(".schema_name='")
                            .append(fieldName).append("'").toString();
                    obs.orderBy = fieldName + " " + clause.getDirection().name();
                } else {
                    orderBySupport.views.add(svs.attr());

                    obs.select = new StringBuilder().append(svs.attr().alias).append('.')
                            .append(svs.fieldName(schema.getType())).append(" AS ").append(fieldName)
                            .toString();
                    obs.where = new StringBuilder().append(svs.attr().alias).append(".schema_name='")
                            .append(fieldName).append("'").toString();
                    obs.orderBy = fieldName + " " + clause.getDirection().name();
                }//from  ww w  .  j  ava  2s .c  o  m
            }
        } else {
            orderBySupport.views.add(svs.field());

            obs.select = svs.field().alias + "." + fieldName;
            obs.where = StringUtils.EMPTY;
            obs.orderBy = svs.field().alias + "." + fieldName + " " + clause.getDirection().name();
        }

        if (obs.isEmpty()) {
            LOG.warn("Cannot build any valid clause from {}", clause);
        } else {
            orderBySupport.items.add(obs);
        }
    }

    return orderBySupport;
}

From source file:org.apache.syncope.core.persistence.jpa.dao.JPASubjectSearchDAO.java

@SuppressWarnings("rawtypes")
private String getQuery(final SubjectCond cond, final boolean not, final List<Object> parameters,
        final SubjectType type, final SearchSupport svs) {

    final AttributableUtil attrUtil = attrUtilFactory.getInstance(type.asAttributableType());

    // Keeps track of difference between entity's getKey() and JPA @Id fields
    if ("key".equals(cond.getSchema())) {
        cond.setSchema("id");
    }/*from   w  w w  .j a v  a 2s . c om*/

    Field subjectField = ReflectionUtils.findField(attrUtil.attributableClass(), cond.getSchema());
    if (subjectField == null) {
        LOG.warn("Ignoring invalid schema '{}'", cond.getSchema());
        return EMPTY_ATTR_QUERY;
    }

    PlainSchema schema = attrUtil.newPlainSchema();
    schema.setKey(subjectField.getName());
    for (AttrSchemaType attrSchemaType : AttrSchemaType.values()) {
        if (subjectField.getType().isAssignableFrom(attrSchemaType.getType())) {
            schema.setType(attrSchemaType);
        }
    }

    // Deal with subject Integer fields logically mapping to boolean values
    // (JPARole.inheritPlainAttrs, for example)
    boolean foundBooleanMin = false;
    boolean foundBooleanMax = false;
    if (Integer.class.equals(subjectField.getType())) {
        for (Annotation annotation : subjectField.getAnnotations()) {
            if (Min.class.equals(annotation.annotationType())) {
                foundBooleanMin = ((Min) annotation).value() == 0;
            } else if (Max.class.equals(annotation.annotationType())) {
                foundBooleanMax = ((Max) annotation).value() == 1;
            }
        }
    }
    if (foundBooleanMin && foundBooleanMax) {
        schema.setType(AttrSchemaType.Boolean);
    }

    // Deal with subject fields representing relationships to other entities
    if (subjectField.getType().getAnnotation(Entity.class) != null) {
        Method relMethod = null;
        try {
            relMethod = ClassUtils.getPublicMethod(subjectField.getType(), "getKey", new Class[0]);
        } catch (Exception e) {
            LOG.error("Could not find {}#getKey", subjectField.getType(), e);
        }

        if (relMethod != null) {
            if (Long.class.isAssignableFrom(relMethod.getReturnType())) {
                cond.setSchema(cond.getSchema() + "_id");
                schema.setType(AttrSchemaType.Long);
            }
            if (String.class.isAssignableFrom(relMethod.getReturnType())) {
                cond.setSchema(cond.getSchema() + "_name");
                schema.setType(AttrSchemaType.String);
            }
        }
    }

    PlainAttrValue attrValue = attrUtil.newPlainAttrValue();
    if (cond.getType() != AttributeCond.Type.LIKE && cond.getType() != AttributeCond.Type.ISNULL
            && cond.getType() != AttributeCond.Type.ISNOTNULL) {

        try {
            schema.getValidator().validate(cond.getExpression(), attrValue);
        } catch (ValidationException e) {
            LOG.error("Could not validate expression '" + cond.getExpression() + "'", e);
            return EMPTY_ATTR_QUERY;
        }
    }

    final StringBuilder query = new StringBuilder("SELECT DISTINCT subject_id FROM ").append(svs.field().name)
            .append(" WHERE ");

    fillAttributeQuery(query, attrValue, schema, cond, not, parameters, svs);

    return query.toString();
}

From source file:org.apache.syncope.core.persistence.jpa.dao.JPATaskDAO.java

private String toOrderByStatement(final Class<? extends Task> beanClass,
        final List<OrderByClause> orderByClauses) {

    StringBuilder statement = new StringBuilder();

    orderByClauses.forEach(clause -> {
        String field = clause.getField().trim();
        if (ReflectionUtils.findField(beanClass, field) != null) {
            statement.append("t.").append(field).append(' ').append(clause.getDirection().name());
        }/*from ww w . j a  v a2  s.  com*/
    });

    if (statement.length() == 0) {
        statement.append("ORDER BY t.id DESC");
    } else {
        statement.insert(0, "ORDER BY ");
    }
    return statement.toString();
}

From source file:org.broadleafcommerce.common.util.dao.DynamicDaoHelperImpl.java

@Override
public Field getIdField(Class<?> clazz, EntityManager em) {
    clazz = getNonProxyImplementationClassIfNecessary(clazz);
    ClassMetadata metadata = em.unwrap(Session.class).getSessionFactory().getClassMetadata(clazz);
    Field idField = ReflectionUtils.findField(clazz, metadata.getIdentifierPropertyName());
    idField.setAccessible(true);/*from www  .ja va  2s  .  c  o m*/
    return idField;
}

From source file:org.broadleafcommerce.common.util.dao.DynamicDaoHelperImpl.java

@Override
public Field getIdField(Class<?> clazz, Session session) {
    clazz = getNonProxyImplementationClassIfNecessary(clazz);
    ClassMetadata metadata = session.getSessionFactory().getClassMetadata(clazz);
    Field idField = ReflectionUtils.findField(clazz, metadata.getIdentifierPropertyName());
    idField.setAccessible(true);//from w  w  w . j a  va 2s.c om
    return idField;
}

From source file:org.codehaus.groovy.grails.orm.hibernate.support.ClosureEventListener.java

private EventTriggerCaller buildCaller(Class<?> domainClazz, String event) {
    Method method = ReflectionUtils.findMethod(domainClazz, event);
    if (method != null) {
        ReflectionUtils.makeAccessible(method);
        return new MethodCaller(method);
    }//  ww w .java  2 s .com

    Field field = ReflectionUtils.findField(domainClazz, event);
    if (field != null) {
        ReflectionUtils.makeAccessible(field);
        return new FieldClosureCaller(field);
    }

    MetaMethod metaMethod = domainMetaClass.getMetaMethod(event, EMPTY_OBJECT_ARRAY);
    if (metaMethod != null) {
        return new MetaMethodCaller(metaMethod);
    }

    MetaProperty metaProperty = domainMetaClass.getMetaProperty(event);
    if (metaProperty != null) {
        return new MetaPropertyClosureCaller(metaProperty);
    }

    return null;
}