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:edu.utah.further.ds.impl.executor.db.hibernate.criteria.HibernateDistinctIdExecutor.java

/**
 * @param request/*w  w w . j  a  v  a 2 s.  c o  m*/
 * @return
 * @see edu.utah.further.core.chain.AbstractRequestHandler#process(edu.utah.further.core.api.chain.ChainRequest)
 * @see http://opensource.atlassian.com/projects/hibernate/browse/HHH-817
 */
@Override
public boolean process(final ChainRequest request) {
    final HibernateExecReq executionReq = new HibernateExecReq(request);

    // Validate required input
    final GenericCriteria hibernateCriteria = executionReq.getResult();
    notNull(hibernateCriteria, "Expected Hibernate criteria");

    final Class<? extends PersistentEntity<?>> domainClass = executionReq.getRootEntity();
    final Class<? extends PersistentEntity<?>> entityClass = dao.getEntityClass(domainClass);

    notNull(entityClass, "Expected root entity class");

    final SessionFactory sessionFactory = executionReq.getSessionFactory();
    notNull(sessionFactory, "Expected SessionFactory");

    final ClassMetadata classMetadata = sessionFactory.getClassMetadata(entityClass);
    final String identifierName = classMetadata.getIdentifierPropertyName();
    final Type identifierType = classMetadata.getIdentifierType();

    // A hack to obtain projections out of the critieria by casting to the Hibernate
    // implementation. TODO: improve adapter to do that via interface access
    final ProjectionList projectionList = Projections.projectionList();
    final Projection existingProjection = ((CriteriaImpl) hibernateCriteria.getHibernateCriteria())
            .getProjection();

    if (existingProjection != null && !overrideExistingProjection) {
        return false;
    }

    if (identifierType.isComponentType()) {
        final ComponentType componentType = (ComponentType) identifierType;
        final String[] idPropertyNames = componentType.getPropertyNames();

        // Add distinct to the first property
        projectionList.add(
                Projections
                        .distinct(Property.forName(identifierName + PROPERTY_SCOPE_CHAR + idPropertyNames[0])),
                idPropertyNames[0]);

        // Add the remaining properties to the projection list
        for (int i = 1; i < idPropertyNames.length; i++) {
            projectionList.add(Property.forName(identifierName + PROPERTY_SCOPE_CHAR + idPropertyNames[i]),
                    idPropertyNames[i]);
        }

        hibernateCriteria.setProjection(projectionList);
        hibernateCriteria.setResultTransformer(new AliasToBeanResultTransformer(
                ReflectionUtils.findField(entityClass, identifierName).getType()));
    } else {
        // 'this' required to avoid HHH-817
        projectionList.add(Projections.distinct(Property.forName(THIS_CONTEXT + identifierName)));
        hibernateCriteria.setProjection(projectionList);
    }

    executionReq.setResult(hibernateCriteria);

    return false;
}

From source file:gr.abiss.calipso.tiers.util.ModelContext.java

public ModelContext(ModelRelatedResource resource, Class<?> domainClass) {
    String packageName = domainClass.getPackage().getName();
    this.beansBasePackage = packageName.endsWith(".model")
            ? packageName.substring(0, packageName.indexOf(".model"))
            : packageName;//ww w.j a va2s.  c  o  m

    this.name = getPath(domainClass);
    this.apiAnnotationMembers = getApiAnnotationMembers(domainClass);

    String parentProperty = resource.parentProperty();
    this.parentClass = (Class<?>) ReflectionUtils.findField(domainClass, parentProperty).getType();

    String parentName = getPath(parentClass);
    this.path = "/" + parentName + "/{peId}/" + this.name;

    this.modelType = (Class<?>) domainClass;
    this.modelIdType = EntityUtil.getIdType(domainClass);
    this.generatedClassNamePrefix = domainClass.getSimpleName().replace("Model", "").replace("Entity", "");

    this.parentProperty = resource.parentProperty();
}

From source file:gr.abiss.calipso.tiers.util.ModelContext.java

public boolean isNestedCollection() {
    if (!isNested()) {
        return false;
    }//from  ww  w .  ja va 2 s  . c  o m

    ModelRelatedResource anr = modelType.getAnnotation(ModelRelatedResource.class);
    Assert.notNull(anr, "Not a nested resource");

    String parentProperty = anr.parentProperty();
    Field field = ReflectionUtils.findField(modelType, parentProperty);
    if (hasAnnotation(field, OneToOne.class, org.hibernate.mapping.OneToOne.class)) {
        return false;
    } else if (hasAnnotation(field, ManyToOne.class, org.hibernate.mapping.ManyToOne.class, ManyToMany.class,
            ManyToAny.class)) { // TODO handle more mappings here?
        return true;
    }

    throw new IllegalStateException("No known mapping found");

}

From source file:grails.util.GrailsClassUtils.java

/**
 * <p>Get a static field value.</p>
 *
 * @param clazz The class to check for static property
 * @param name The field name/*from w ww .  j a v  a2  s .co  m*/
 * @return The value if there is one, or null if unset OR there is no such field
 */
public static Object getStaticFieldValue(Class<?> clazz, String name) {
    Field field = ReflectionUtils.findField(clazz, name);
    if (field != null) {
        ReflectionUtils.makeAccessible(field);
        try {
            return field.get(clazz);
        } catch (IllegalAccessException ignored) {
        }
    }
    return null;
}

From source file:hello.MetricsActivator.java

private static Object getField(Object target, String name) {
    Assert.notNull(target, "Target object must not be null");
    Field field = ReflectionUtils.findField(target.getClass(), name);
    if (field == null) {
        throw new IllegalArgumentException("Could not find field [" + name + "] on target [" + target + "]");
    }//ww w  . jav  a  2  s  .  c om

    if (logger.isDebugEnabled()) {
        logger.debug("Getting field [" + name + "] from target [" + target + "]");
    }
    ReflectionUtils.makeAccessible(field);
    return ReflectionUtils.getField(field, target);
}

From source file:io.servicecomb.springboot.starter.configuration.CseAutoConfiguration.java

private static void setStatic(Class<?> type, String name, Object value) {
    // Hack a private static field
    Field field = ReflectionUtils.findField(type, name);
    ReflectionUtils.makeAccessible(field);
    ReflectionUtils.setField(field, null, value);
}

From source file:org.alfresco.util.test.junitrules.TemporaryMockOverride.java

@Override
protected void after() {
    // For all objects that have been tampered with, we'll revert them to their original state.
    for (int i = pristineFieldValues.size() - 1; i >= 0; i--) {
        FieldValueOverride override = pristineFieldValues.get(i);

        if (log.isDebugEnabled()) {
            log.debug("Reverting mocked field '" + override.fieldName + "' on object "
                    + override.objectContainingField + " to original value '" + override.fieldPristineValue
                    + "'");
        }/*from  w  w w.ja  va  2  s  . c o m*/

        // Hack into the Java field object
        Field f = ReflectionUtils.findField(override.objectContainingField.getClass(), override.fieldName);
        ReflectionUtils.makeAccessible(f);
        // and revert its value.
        ReflectionUtils.setField(f, override.objectContainingField, override.fieldPristineValue);
    }
}

From source file:org.alfresco.util.test.junitrules.TemporaryMockOverride.java

public void setTemporaryField(Object objectContainingField, String fieldName, Object fieldValue) {
    if (log.isDebugEnabled()) {
        log.debug("Overriding field '" + fieldName + "' on object " + objectContainingField + " to new value '"
                + fieldValue + "'");
    }/*from  w w  w  .ja v  a2 s.  c o  m*/

    // Extract the pristine value of the field we're going to mock.
    Field f = ReflectionUtils.findField(objectContainingField.getClass(), fieldName);

    if (f == null) {
        final String msg = "Object of type '" + objectContainingField.getClass().getSimpleName()
                + "' has no field named '" + fieldName + "'";
        if (log.isDebugEnabled()) {
            log.debug(msg);
        }
        throw new IllegalArgumentException(msg);
    }

    ReflectionUtils.makeAccessible(f);
    Object pristineValue = ReflectionUtils.getField(f, objectContainingField);

    // and add it to the list.
    pristineFieldValues.add(new FieldValueOverride(objectContainingField, fieldName, pristineValue));

    // and set it on the object
    ReflectionUtils.setField(f, objectContainingField, fieldValue);
}

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

private <T extends AbstractSchemaModalPage> List<IColumn> getColumns(final WebMarkupContainer webContainer,
        final ModalWindow modalWindow, final AttributableType attributableType, final SchemaType schemaType,
        final Collection<String> fields) {

    List<IColumn> columns = new ArrayList<IColumn>();

    for (final String field : fields) {
        final Field clazzField = ReflectionUtils.findField(schemaType.getToClass(), field);

        if (clazzField != null) {
            if (clazzField.getType().equals(Boolean.class) || clazzField.getType().equals(boolean.class)) {
                columns.add(new AbstractColumn<AbstractSchemaTO, String>(new ResourceModel(field)) {

                    private static final long serialVersionUID = 8263694778917279290L;

                    @Override//from ww  w. j ava2s .com
                    public void populateItem(final Item<ICellPopulator<AbstractSchemaTO>> item,
                            final String componentId, final IModel<AbstractSchemaTO> model) {

                        BeanWrapper bwi = new BeanWrapperImpl(model.getObject());
                        Object obj = bwi.getPropertyValue(field);

                        item.add(new Label(componentId, ""));
                        item.add(new AttributeModifier("class", new Model<String>(obj.toString())));
                    }

                    @Override
                    public String getCssClass() {
                        return "small_fixedsize";
                    }
                });
            } else {
                IColumn column = new PropertyColumn(new ResourceModel(field), field, field) {

                    private static final long serialVersionUID = 3282547854226892169L;

                    @Override
                    public String getCssClass() {
                        String css = super.getCssClass();
                        if ("key".equals(field)) {
                            css = StringUtils.isBlank(css) ? "medium_fixedsize" : css + " medium_fixedsize";
                        }
                        return css;
                    }
                };
                columns.add(column);
            }
        }
    }

    columns.add(new AbstractColumn<AbstractSchemaTO, String>(new ResourceModel("actions", "")) {

        private static final long serialVersionUID = 2054811145491901166L;

        @Override
        public String getCssClass() {
            return "action";
        }

        @Override
        public void populateItem(final Item<ICellPopulator<AbstractSchemaTO>> item, final String componentId,
                final IModel<AbstractSchemaTO> model) {

            final AbstractSchemaTO schemaTO = model.getObject();

            final ActionLinksPanel panel = new ActionLinksPanel(componentId, model, getPageReference());

            panel.addWithRoles(new ActionLink() {

                private static final long serialVersionUID = -3722207913631435501L;

                @Override
                public void onClick(final AjaxRequestTarget target) {
                    modalWindow.setPageCreator(new ModalWindow.PageCreator() {

                        private static final long serialVersionUID = -7834632442532690940L;

                        @Override
                        public Page createPage() {
                            AbstractSchemaModalPage page = SchemaModalPageFactory
                                    .getSchemaModalPage(attributableType, schemaType);

                            page.setSchemaModalPage(Schema.this.getPageReference(), modalWindow, schemaTO,
                                    false);

                            return page;
                        }
                    });

                    modalWindow.show(target);
                }
            }, ActionType.EDIT, allowedReadRoles);

            panel.addWithRoles(new ActionLink() {

                private static final long serialVersionUID = -3722207913631435501L;

                @Override
                public void onClick(final AjaxRequestTarget target) {

                    switch (schemaType) {
                    case DERIVED:
                        restClient.deleteDerSchema(attributableType, schemaTO.getKey());
                        break;

                    case VIRTUAL:
                        restClient.deleteVirSchema(attributableType, schemaTO.getKey());
                        break;

                    default:
                        restClient.deletePlainSchema(attributableType, schemaTO.getKey());
                        break;
                    }

                    info(getString(Constants.OPERATION_SUCCEEDED));
                    feedbackPanel.refresh(target);

                    target.add(webContainer);
                }
            }, ActionType.DELETE, allowedDeleteRoles);

            item.add(panel);
        }
    });

    return columns;
}

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

@Override
protected List<IColumn<A, String>> getColumns() {
    final List<IColumn<A, String>> columns = new ArrayList<>();
    final List<IColumn<A, String>> prefcolumns = new ArrayList<>();

    columns.add(new KeyPropertyColumn<>(new ResourceModel(Constants.KEY_FIELD_NAME, Constants.KEY_FIELD_NAME),
            Constants.KEY_FIELD_NAME));/*from   ww  w. java2  s  .co m*/

    prefMan.getList(getRequest(), DisplayAttributesModalPanel.getPrefDetailView(type)).stream()
            .filter(name -> !Constants.KEY_FIELD_NAME.equalsIgnoreCase(name)).forEachOrdered(name -> {
                addPropertyColumn(name,
                        ReflectionUtils.findField(DisplayAttributesModalPanel.getTOClass(type), name),
                        prefcolumns);
            });

    prefMan.getList(getRequest(), DisplayAttributesModalPanel.getPrefPlainAttributeView(type)).stream()
            .filter(name -> pSchemaNames.contains(name)).forEachOrdered(name -> {
                prefcolumns.add(new AttrColumn<>(name, SchemaType.PLAIN));
            });

    prefMan.getList(getRequest(), DisplayAttributesModalPanel.getPrefDerivedAttributeView(type)).stream()
            .filter(name -> (dSchemaNames.contains(name))).forEachOrdered(name -> {
                prefcolumns.add(new AttrColumn<>(name, SchemaType.DERIVED));
            });

    // Add defaults in case of no selection
    if (prefcolumns.isEmpty()) {
        for (String name : getDefaultAttributeSelection()) {
            addPropertyColumn(name,
                    ReflectionUtils.findField(DisplayAttributesModalPanel.getTOClass(type), name), prefcolumns);
        }

        prefMan.setList(getRequest(), getResponse(), DisplayAttributesModalPanel.getPrefDetailView(type),
                Arrays.asList(getDefaultAttributeSelection()));
    }

    columns.addAll(prefcolumns);
    return columns;
}