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) 

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:org.sherlok.utils.BundleCreatorUtil.java

private static void createBundle(Set<BundleDef> bundleDefs) throws Exception {

    // create fake POM from bundles and copy it
    String fakePom = MavenPom.writePom(bundleDefs, "BundleCreator", System.currentTimeMillis() + "");// must be unique
    Artifact rootArtifact = new DefaultArtifact(fakePom);
    LOG.trace("* rootArtifact: '{}'", rootArtifact);

    // add remote repository urls
    RepositorySystem system = AetherResolver.newRepositorySystem();
    RepositorySystemSession session = AetherResolver.newRepositorySystemSession(system,
            AetherResolver.LOCAL_REPO_PATH);
    Map<String, String> repositoriesDefs = map();
    for (BundleDef b : bundleDefs) {
        b.validate(b.getId());/*from  w ww .j a v  a2s  .c o m*/
        for (Entry<String, String> id_url : b.getRepositories().entrySet()) {
            repositoriesDefs.put(id_url.getKey(), id_url.getValue());
        }
    }
    List<RemoteRepository> repos = AetherResolver.newRepositories(system, session, repositoriesDefs);

    // solve dependencies
    CollectRequest collectRequest = new CollectRequest();
    collectRequest.setRoot(new Dependency(rootArtifact, ""));
    collectRequest
            .setRepositories(AetherResolver.newRepositories(system, session, new HashMap<String, String>()));
    CollectResult collectResult = system.collectDependencies(session, collectRequest);
    collectResult.getRoot().accept(new AetherResolver.ConsoleDependencyGraphDumper());
    PreorderNodeListGenerator p = new PreorderNodeListGenerator();
    collectResult.getRoot().accept(p);

    // now do the real fetching, and add jars to classpath
    List<Artifact> resolvedArtifacts = list();
    for (Dependency dependency : p.getDependencies(true)) {
        Artifact resolvedArtifact = system
                .resolveArtifact(session, new ArtifactRequest(dependency.getArtifact(), repos, ""))
                .getArtifact();
        resolvedArtifacts.add(resolvedArtifact);
        File jar = resolvedArtifact.getFile();

        // add this jar to the classpath
        ClassPathHack.addFile(jar);
        LOG.trace("* resolved artifact '{}', added to classpath: '{}'", resolvedArtifact,
                jar.getAbsolutePath());
    }

    BundleDef createdBundle = new BundleDef();
    createdBundle.setVersion("TODO!");
    createdBundle.setName("TODO!");
    for (BundleDef bundleDef : bundleDefs) {
        for (BundleDependency dep : bundleDef.getDependencies()) {
            createdBundle.addDependency(dep);
        }
    }

    for (Artifact a : resolvedArtifacts) {

        // only consider artifacts that were included in the initial bundle
        boolean found = false;
        for (BundleDef bundleDef : bundleDefs) {
            for (BundleDependency dep : bundleDef.getDependencies()) {
                if (a.getArtifactId().equals(dep.getArtifactId())) {
                    found = true;
                    break;
                }
            }
        }

        if (found) {

            JarInputStream is = new JarInputStream(new FileInputStream(a.getFile()));
            JarEntry entry;
            while ((entry = is.getNextJarEntry()) != null) {
                if (entry.getName().endsWith(".class")) {

                    try {
                        Class<?> clazz = Class.forName(entry.getName().replace('/', '.').replace(".class", ""));

                        // scan for all uimafit AnnotationEngines
                        if (JCasAnnotator_ImplBase.class.isAssignableFrom(clazz)) {
                            LOG.debug("AnnotationEngine: {}", clazz.getSimpleName());

                            final EngineDef engine = new EngineDef().setClassz(clazz.getName())
                                    .setName(clazz.getSimpleName()).setBundle(createdBundle);
                            createdBundle.addEngine(engine);
                            LOG.debug("{}", engine);

                            ReflectionUtils.doWithFields(clazz, new FieldCallback() {
                                public void doWith(final Field f)
                                        throws IllegalArgumentException, IllegalAccessException {

                                    ConfigurationParameter c = f.getAnnotation(ConfigurationParameter.class);
                                    if (c != null) {
                                        LOG.debug("* param: {} {} {} {}", new Object[] { c.name(),
                                                c.defaultValue(), c.mandatory(), f.getType() });

                                        String deflt = c.mandatory() ? "TODO" : "IS OPTIONAL";

                                        String value = c.defaultValue()[0]
                                                .equals(ConfigurationParameter.NO_DEFAULT_VALUE) ? deflt
                                                        : c.defaultValue()[0].toString();
                                        engine.addParameter(c.name(), list(value));
                                    }
                                }
                            });
                        }
                    } catch (Throwable e) {
                        System.err.println("something wrong with class " + entry.getName() + " " + e);
                    }
                }
            }
            is.close();
        }
    }

    // delete fake pom
    deleteDirectory(new File(LOCAL_REPO_PATH + "/org/sherlok/BundleCreator"));

    System.out.println(FileBased.writeAsString(createdBundle));
}

From source file:org.springframework.batch.core.jsr.configuration.support.BatchPropertyBeanPostProcessor.java

private void injectBatchProperties(final Object bean, final Properties artifactProperties) {
    ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() {
        @Override/*from   w  w  w .ja  v  a  2s .c  om*/
        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            if (isValidFieldModifier(field) && isAnnotated(field)) {
                boolean isAccessible = field.isAccessible();
                field.setAccessible(true);

                String batchProperty = getBatchPropertyFieldValue(field, artifactProperties);

                if (batchProperty != null) {
                    field.set(bean, batchProperty);
                }

                field.setAccessible(isAccessible);
            }
        }
    });
}

From source file:org.springframework.batch.core.jsr.launch.support.BatchPropertyBeanPostProcessor.java

private void injectBatchProperties(final Object artifact, final Properties artifactProperties) {
    ReflectionUtils.doWithFields(artifact.getClass(), new ReflectionUtils.FieldCallback() {
        @Override/*from   w  ww . j  a  va  2s.c  om*/
        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            if (isValidFieldModifier(field) && isAnnotated(field)) {
                boolean isAccessible = field.isAccessible();
                field.setAccessible(true);

                String batchProperty = getBatchPropertyFieldValue(field, artifactProperties);

                if (StringUtils.hasText(batchProperty)) {
                    field.set(artifact, batchProperty);
                }

                field.setAccessible(isAccessible);
            }
        }
    });
}

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

private void initFields() {
    ReflectionUtils.doWithFields(this.clazz, new FieldCallback() {

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

            if (field.isAnnotationPresent(Transient.class) || field.isSynthetic()
                    || field.getModifiers() == Modifier.FINAL || field.getModifiers() == Modifier.TRANSIENT) {
                return;
            }

            // Field can only have one of these, if more than one throw an
            // error
            List<Annotation> annots = org.springframework.data.keyvalue.riak.util.AnnotationUtils
                    .getFoundAnnotation(Id.class, Column.class, Embedded.class, Version.class, ManyToOne.class,
                            OneToMany.class, Basic.class);

            // Probably allow auto generation at some point, but for now
            // have to add one of the annotations
            if (annots.size() > 1)
                throw new IllegalArgumentException(String.format(
                        "The field %s must have only one of the following annotations: "
                                + "@Id, @Basic, @Column, @Embedded, @Version, @ManyToOne, @OneToMany",
                        field.getName()));

            Annotation annot = annots.get(0);

            if (annot.annotationType().equals(Id.class))
                RiakMappedClass.this.id = field;

            // Create a new mapped field here and then add to a list of
            // property MappedFields
            propertyFields.add(new RiakMappedField(field, annot));
        }
    });
    Map<Class<? extends Annotation>, Annotation> fieldAnnotMap = new HashMap<Class<? extends Annotation>, Annotation>();
    for (Class<? extends Annotation> a : entityAnnotations) {
        Target target = a.getAnnotation(Target.class);
        if (target != null && (ArrayUtils.contains(target.value(), ElementType.FIELD)
                || ArrayUtils.contains(target.value(), ElementType.METHOD))) {
            Annotation fieldAnnot;
            if ((fieldAnnot = this.clazz.getAnnotation(a)) != null) {
                fieldAnnotMap.put(a, fieldAnnot);
            }
        }
    }
}

From source file:org.springframework.integration.channel.P2pChannelTests.java

/**
 * @param channel//w ww. ja  v  a 2s  . co m
 */
private void verifySubscriptions(final AbstractSubscribableChannel channel) {
    final Log logger = mock(Log.class);
    when(logger.isInfoEnabled()).thenReturn(true);
    final List<String> logs = new ArrayList<String>();
    doAnswer(new Answer<Object>() {
        public Object answer(InvocationOnMock invocation) throws Throwable {
            logs.add((String) invocation.getArguments()[0]);
            return null;
        }
    }).when(logger).info(Mockito.anyString());
    ReflectionUtils.doWithFields(AbstractMessageChannel.class, new FieldCallback() {
        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            if ("logger".equals(field.getName())) {
                field.setAccessible(true);
                field.set(channel, logger);
            }
        }
    });
    String log = "Channel '" + channel.getComponentName() + "' has " + "%d subscriber(s).";

    MessageHandler handler1 = mock(MessageHandler.class);
    channel.subscribe(handler1);
    assertEquals(String.format(log, 1), logs.remove(0));
    MessageHandler handler2 = mock(MessageHandler.class);
    channel.subscribe(handler2);
    assertEquals(String.format(log, 2), logs.remove(0));
    channel.unsubscribe(handler1);
    assertEquals(String.format(log, 1), logs.remove(0));
    channel.unsubscribe(handler1);
    assertEquals(0, logs.size());
    channel.unsubscribe(handler2);
    assertEquals(String.format(log, 0), logs.remove(0));
    verify(logger, times(4)).info(Mockito.anyString());
}

From source file:org.springframework.integration.channel.P2pChannelTests.java

@Test
public void testExecutorChannelLoggingWithMoreThenOneSubscriber() {
    final ExecutorChannel channel = new ExecutorChannel(mock(Executor.class));
    channel.setBeanName("executorChannel");

    final Log logger = mock(Log.class);
    when(logger.isInfoEnabled()).thenReturn(true);
    ReflectionUtils.doWithFields(AbstractMessageChannel.class, new FieldCallback() {

        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            if ("logger".equals(field.getName())) {
                field.setAccessible(true);
                field.set(channel, logger);
            }/*from www  .j a v  a  2 s .com*/
        }
    });
    channel.subscribe(mock(MessageHandler.class));
    channel.subscribe(mock(MessageHandler.class));
    verify(logger, times(2)).info(Mockito.anyString());
}

From source file:org.springframework.integration.channel.P2pChannelTests.java

@Test
public void testPubSubChannelLoggingWithMoreThenOneSubscriber() {
    final PublishSubscribeChannel channel = new PublishSubscribeChannel();
    channel.setBeanName("pubSubChannel");

    final Log logger = mock(Log.class);
    when(logger.isInfoEnabled()).thenReturn(true);
    ReflectionUtils.doWithFields(AbstractMessageChannel.class, new FieldCallback() {

        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            if ("logger".equals(field.getName())) {
                field.setAccessible(true);
                field.set(channel, logger);
            }//from w  w  w.  j a  v  a 2 s .  com
        }
    });
    channel.subscribe(mock(MessageHandler.class));
    channel.subscribe(mock(MessageHandler.class));
    verify(logger, times(2)).info(Mockito.anyString());
}

From source file:org.springframework.integration.smpp.TestSmppSessionFactoryBean.java

@Test
public void testSmppSessionFactory() throws Throwable {

    SmppSessionFactoryBean smppSessionFactoryBean = new SmppSessionFactoryBean();
    smppSessionFactoryBean.setSystemId(this.systemId);
    smppSessionFactoryBean.setPort(this.port);
    smppSessionFactoryBean.setPassword(this.password);
    smppSessionFactoryBean.setHost(this.host);
    smppSessionFactoryBean.afterPropertiesSet();

    ExtendedSmppSession extendedSmppSession = smppSessionFactoryBean.getObject();
    Assert.assertTrue(extendedSmppSession instanceof ExtendedSmppSessionAdaptingDelegate);

    ExtendedSmppSessionAdaptingDelegate es = (ExtendedSmppSessionAdaptingDelegate) extendedSmppSession;
    Assert.assertNotNull("the factoried object should not be null", extendedSmppSession);
    es.addMessageReceiverListener(new MessageReceiverListener() {
        public void onAcceptDeliverSm(DeliverSm deliverSm) throws ProcessRequestException {
            logger.debug("in onAcceptDeliverSm");
        }/*from  www. j  ava  2s.  c o  m*/

        public void onAcceptAlertNotification(AlertNotification alertNotification) {
            logger.debug("in onAcceptAlertNotification");
        }

        public DataSmResult onAcceptDataSm(DataSm dataSm, Session source) throws ProcessRequestException {
            logger.debug("in onAcceptDataSm");
            return null;
        }
    });
    Assert.assertEquals(extendedSmppSession.getClass(), ExtendedSmppSessionAdaptingDelegate.class);
    Assert.assertNotNull(es.getTargetClientSession());
    Assert.assertTrue(es.getTargetClientSession() != null);
    final SMPPSession s = es.getTargetClientSession();

    ReflectionUtils.doWithFields(ExtendedSmppSessionAdaptingDelegate.class,
            new ReflectionUtils.FieldCallback() {
                public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
                    if (field.getName().equalsIgnoreCase("messageReceiverListener")) {
                        field.setAccessible(true);
                        MessageReceiverListener messageReceiverListener = (MessageReceiverListener) field
                                .get(s);
                        Assert.assertNotNull(messageReceiverListener);
                        Assert.assertTrue(messageReceiverListener instanceof DelegatingMessageReceiverListener);
                        final DelegatingMessageReceiverListener delegatingMessageReceiverListener = (DelegatingMessageReceiverListener) messageReceiverListener;
                        ReflectionUtils.doWithFields(DelegatingMessageReceiverListener.class,
                                new ReflectionUtils.FieldCallback() {
                                    public void doWith(Field field)
                                            throws IllegalArgumentException, IllegalAccessException {
                                        if (field.getName().equals("messageReceiverListenerSet")) {
                                            field.setAccessible(true);
                                            @SuppressWarnings("unchecked")
                                            Set<MessageReceiverListener> l = (Set<MessageReceiverListener>) field
                                                    .get(delegatingMessageReceiverListener);
                                            Assert.assertEquals(l.size(), 1);
                                        }
                                    }
                                });
                    }
                }
            });
}