Example usage for org.springframework.util ReflectionUtils doWithFields

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

Introduction

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

Prototype

public static void doWithFields(Class<?> clazz, FieldCallback fc, @Nullable FieldFilter ff) 

Source Link

Document

Invoke the given callback on all fields in the target class, going up the class hierarchy to get all declared fields.

Usage

From source file:com.sxj.mybatis.orm.builder.GenericStatementBuilder.java

public GenericStatementBuilder(Configuration configuration, final Class<?> entityClass) {
    super(configuration);
    this.entityClass = entityClass;
    sharded = ConfigurationProperties.isSharded(configuration);
    String resource = entityClass.getName().replace('.', '/') + ".java (best guess)";
    assistant = new MapperBuilderAssistant(configuration, resource);
    entity = entityClass.getAnnotation(Entity.class);
    mapperType = entity.mapper();//from   ww  w . ja  va 2 s.co m

    if (!mapperType.isAssignableFrom(Void.class)) {
        namespace = mapperType.getName();
    } else {
        namespace = entityClass.getName();
    }
    assistant.setCurrentNamespace(namespace);
    Collection<String> cacheNames = configuration.getCacheNames();
    for (String name : cacheNames)
        if (namespace.equals(name)) {
            assistant.useCacheRef(name);
            break;
        }

    databaseId = super.getConfiguration().getDatabaseId();
    lang = super.getConfiguration().getDefaultScriptingLanuageInstance();

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Table table = entityClass.getAnnotation(Table.class);
    if (table == null) {
        tableName = CaseFormatUtils.camelToUnderScore(entityClass.getSimpleName());
    } else {
        tableName = table.name();
    }

    ///~~~~~~~~~~~~~~~~~~~~~~
    idField = AnnotationUtils.findDeclaredFieldWithAnnoation(Id.class, entityClass);
    if (!sharded && (this.idField.isAnnotationPresent(GeneratedValue.class))
            && (((GeneratedValue) this.idField.getAnnotation(GeneratedValue.class))
                    .strategy() == GenerationType.UUID))
        columnFields.add(idField);
    else
        columnFields.add(idField);
    versionField = AnnotationUtils.findDeclaredFieldWithAnnoation(Version.class, entityClass);

    ReflectionUtils.doWithFields(entityClass, new FieldCallback() {

        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            if (field.isAnnotationPresent(Column.class))
                columnFields.add(field);
            if (field.isAnnotationPresent(Sn.class))
                containSn = true;

        }
    }, new FieldFilter() {

        public boolean matches(Field field) {
            if (Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers())) {
                return false;
            }

            for (Annotation annotation : field.getAnnotations()) {
                if (Transient.class.isAssignableFrom(annotation.getClass())
                        || Id.class.isAssignableFrom(annotation.getClass())) {
                    return false;
                }
            }

            return true;
        }
    });
}

From source file:hello.MetricsActivator.java

private MessageHandler handlerInAnonymousWrapper(final Object bean) {
    if (bean != null && bean.getClass().isAnonymousClass()) {
        final AtomicReference<MessageHandler> wrapped = new AtomicReference<MessageHandler>();
        ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() {

            @Override//from  w  ww  .  ja va  2 s . co m
            public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
                field.setAccessible(true);
                Object handler = field.get(bean);
                if (handler instanceof MessageHandler) {
                    wrapped.set((MessageHandler) handler);
                }
            }
        }, new FieldFilter() {

            @Override
            public boolean matches(Field field) {
                return wrapped.get() == null && field.getName().startsWith("val$");
            }
        });
        return wrapped.get();
    } else {
        return null;
    }
}

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);/*  ww w .j a  va2 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:org.springframework.amqp.rabbit.core.RabbitTemplateIntegrationTests.java

@Test
public void testAtomicSendAndReceiveExternalExecutor() throws Exception {
    CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
    ThreadPoolTaskExecutor exec = new ThreadPoolTaskExecutor();
    final String execName = "make-sure-exec-passed-in";
    exec.setBeanName(execName);//  w w  w.jav  a  2 s  .  c  o  m
    exec.afterPropertiesSet();
    connectionFactory.setExecutor(exec);
    final Field[] fields = new Field[1];
    ReflectionUtils.doWithFields(RabbitTemplate.class, new FieldCallback() {
        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            field.setAccessible(true);
            fields[0] = field;
        }
    }, new FieldFilter() {
        public boolean matches(Field field) {
            return field.getName().equals("logger");
        }
    });
    Log logger = Mockito.mock(Log.class);
    when(logger.isTraceEnabled()).thenReturn(true);

    final AtomicBoolean execConfiguredOk = new AtomicBoolean();

    doAnswer(new Answer<Object>() {
        public Object answer(InvocationOnMock invocation) throws Throwable {
            String log = (String) invocation.getArguments()[0];
            if (log.startsWith("Message received") && Thread.currentThread().getName().startsWith(execName)) {
                execConfiguredOk.set(true);
            }
            return null;
        }
    }).when(logger).trace(Mockito.anyString());
    final RabbitTemplate template = new RabbitTemplate(connectionFactory);
    ReflectionUtils.setField(fields[0], template, logger);
    template.setRoutingKey(ROUTE);
    template.setQueue(ROUTE);
    ExecutorService executor = Executors.newFixedThreadPool(1);
    // Set up a consumer to respond to our producer
    Future<Message> received = executor.submit(new Callable<Message>() {

        public Message call() throws Exception {
            Message message = null;
            for (int i = 0; i < 10; i++) {
                message = template.receive();
                if (message != null) {
                    break;
                }
                Thread.sleep(100L);
            }
            assertNotNull("No message received", message);
            template.send(message.getMessageProperties().getReplyTo(), message);
            return message;
        }

    });
    Message message = new Message("test-message".getBytes(), new MessageProperties());
    Message reply = template.sendAndReceive(message);
    assertEquals(new String(message.getBody()),
            new String(received.get(1000, TimeUnit.MILLISECONDS).getBody()));
    assertNotNull("Reply is expected", reply);
    assertEquals(new String(message.getBody()), new String(reply.getBody()));
    // Message was consumed so nothing left on queue
    reply = template.receive();
    assertEquals(null, reply);

    assertTrue(execConfiguredOk.get());
}

From source file:org.springframework.data.keyvalue.riak.RiakTemplate.java

private List<RiakLink> getLinksFromObject(final Object val) {
    final List<RiakLink> listOfLinks = new ArrayList<RiakLink>();
    ReflectionUtils.doWithFields(val.getClass(), new FieldCallback() {

        @Override/*from   w ww . ja v  a  2s. co m*/
        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            if (!field.isAccessible())
                ReflectionUtils.makeAccessible(field);

            org.springframework.data.keyvalue.riak.RiakLink linkAnnot = field
                    .getAnnotation(org.springframework.data.keyvalue.riak.RiakLink.class);
            String property = linkAnnot.property();
            Object referencedObj = field.get(val);
            Field prop = ReflectionUtils.findField(referencedObj.getClass(), property);

            if (!prop.isAccessible())
                ReflectionUtils.makeAccessible(prop);

            listOfLinks.add(new RiakLink(field.getType().getName(), prop.get(referencedObj).toString(),
                    linkAnnot.value()));

        }
    }, new FieldFilter() {

        @Override
        public boolean matches(Field field) {
            return field.isAnnotationPresent(org.springframework.data.keyvalue.riak.RiakLink.class);
        }
    });

    return listOfLinks;
}

From source file:org.springframework.integration.ip.tcp.connection.TcpNioConnectionTests.java

@Test
public void testCleanup() throws Exception {
    TcpNioClientConnectionFactory factory = new TcpNioClientConnectionFactory("localhost", 0);
    factory.setApplicationEventPublisher(nullPublisher);
    factory.setNioHarvestInterval(100);//ww  w.  j  a  v a2 s . com
    Map<SocketChannel, TcpNioConnection> connections = new HashMap<SocketChannel, TcpNioConnection>();
    SocketChannel chan1 = mock(SocketChannel.class);
    SocketChannel chan2 = mock(SocketChannel.class);
    SocketChannel chan3 = mock(SocketChannel.class);
    TcpNioConnection conn1 = mock(TcpNioConnection.class);
    TcpNioConnection conn2 = mock(TcpNioConnection.class);
    TcpNioConnection conn3 = mock(TcpNioConnection.class);
    connections.put(chan1, conn1);
    connections.put(chan2, conn2);
    connections.put(chan3, conn3);
    final List<Field> fields = new ArrayList<Field>();
    ReflectionUtils.doWithFields(SocketChannel.class, field -> {
        field.setAccessible(true);
        fields.add(field);
    }, field -> field.getName().equals("open"));
    Field field = fields.get(0);
    // Can't use Mockito because isOpen() is final
    ReflectionUtils.setField(field, chan1, true);
    ReflectionUtils.setField(field, chan2, true);
    ReflectionUtils.setField(field, chan3, true);
    Selector selector = mock(Selector.class);
    HashSet<SelectionKey> keys = new HashSet<SelectionKey>();
    when(selector.selectedKeys()).thenReturn(keys);
    factory.processNioSelections(1, selector, null, connections);
    assertEquals(3, connections.size()); // all open

    ReflectionUtils.setField(field, chan1, false);
    factory.processNioSelections(1, selector, null, connections);
    assertEquals(3, connections.size()); // interval didn't pass
    Thread.sleep(110);
    factory.processNioSelections(1, selector, null, connections);
    assertEquals(2, connections.size()); // first is closed

    ReflectionUtils.setField(field, chan2, false);
    factory.processNioSelections(1, selector, null, connections);
    assertEquals(2, connections.size()); // interval didn't pass
    Thread.sleep(110);
    factory.processNioSelections(1, selector, null, connections);
    assertEquals(1, connections.size()); // second is closed

    ReflectionUtils.setField(field, chan3, false);
    factory.processNioSelections(1, selector, null, connections);
    assertEquals(1, connections.size()); // interval didn't pass
    Thread.sleep(110);
    factory.processNioSelections(1, selector, null, connections);
    assertEquals(0, connections.size()); // third is closed

    assertEquals(0, TestUtils.getPropertyValue(factory, "connections", Map.class).size());
}