List of usage examples for org.springframework.util ReflectionUtils findField
@Nullable public static Field findField(Class<?> clazz, String name)
From source file:org.springframework.core.type.classreading.AbstractRecursiveAnnotationVisitor.java
public void visitEnum(String attributeName, String asmTypeDescriptor, String attributeValue) { Object valueToUse = attributeValue; try {//from w ww.j av a 2s. c o m Class<?> enumType = this.classLoader.loadClass(Type.getType(asmTypeDescriptor).getClassName()); Field enumConstant = ReflectionUtils.findField(enumType, attributeValue); if (enumConstant != null) { valueToUse = enumConstant.get(null); } } catch (ClassNotFoundException ex) { this.logger.debug("Failed to classload enum type while reading annotation metadata", ex); } catch (IllegalAccessException ex) { this.logger.warn("Could not access enum value while reading annotation metadata", ex); } this.attributes.put(attributeName, valueToUse); }
From source file:org.springframework.data.hadoop.mapreduce.ExecutionUtils.java
/** * Clean the LocalDirAllocator#contexts/*from ww w. j a va2s.co m*/ */ private static void cleanHadoopLocalDirAllocator() { Field field = ReflectionUtils.findField(LocalDirAllocator.class, "contexts"); ReflectionUtils.makeAccessible(field); Map contexts = (Map) ReflectionUtils.getField(field, null); if (contexts != null) { contexts.clear(); } }
From source file:org.springframework.data.hadoop.util.PermissionUtils.java
public static void hackHadoopStagingOnWin() { // do the assignment only on Windows systems if (System.getProperty("os.name").toLowerCase().startsWith("win")) { // 0655 = -rwxr-xr-x JobSubmissionFiles.JOB_DIR_PERMISSION.fromShort((short) 0650); JobSubmissionFiles.JOB_FILE_PERMISSION.fromShort((short) 0650); if (trackerDistributedCacheManagerClass != null) { // handle jar permissions as well Field field = ReflectionUtils.findField(trackerDistributedCacheManagerClass, "PUBLIC_CACHE_OBJECT_PERM"); ReflectionUtils.makeAccessible(field); FsPermission perm = (FsPermission) ReflectionUtils.getField(field, null); perm.fromShort((short) 0650); }/*www.j av a2 s .c o m*/ } }
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/*ww w . j a v a2s . c o 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.data.solr.server.support.SolrServerUtils.java
@SuppressWarnings("unchecked") private static <T> T readField(SolrServer solrServer, String fieldName) { Field field = ReflectionUtils.findField(solrServer.getClass(), fieldName); if (field == null) { return null; }/* w ww . j a v a2 s. c om*/ ReflectionUtils.makeAccessible(field); return (T) ReflectionUtils.getField(field, solrServer); }
From source file:org.springframework.data.solr.server.support.SolrServerUtils.java
/** * Solr property names do not match the getters/setters used for them. Check on any write method, try to find the * according property and set the value for it. Will ignore all other, and nested properties * /*from w w w. j a v a 2s .c o m*/ * @param source * @param target */ private static void copyProperties(SolrServer source, SolrServer target) { BeanWrapperImpl wrapperImpl = new BeanWrapperImpl(source); for (PropertyDescriptor pd : wrapperImpl.getPropertyDescriptors()) { Method writer = pd.getWriteMethod(); if (writer != null) { try { Field property = ReflectionUtils.findField(source.getClass(), pd.getName()); if (property != null) { ReflectionUtils.makeAccessible(property); Object o = ReflectionUtils.getField(property, source); if (o != null) { writer.invoke(target, o); } } } catch (Exception e) { logger.warn("Could not copy property value for: " + pd.getName(), e); } } } }
From source file:org.springframework.integration.amqp.config.AmqpOutboundChannelAdapterParserTests.java
@Test public void withHeaderMapperCustomHeaders() { Object eventDrivenConsumer = context.getBean("withHeaderMapperCustomHeaders"); AmqpOutboundEndpoint endpoint = TestUtils.getPropertyValue(eventDrivenConsumer, "handler", AmqpOutboundEndpoint.class); assertNotNull(TestUtils.getPropertyValue(endpoint, "defaultDeliveryMode")); assertFalse(TestUtils.getPropertyValue(endpoint, "lazyConnect", Boolean.class)); assertEquals("42", TestUtils .getPropertyValue(endpoint, "delayExpression", org.springframework.expression.Expression.class) .getExpressionString());/*from ww w . java 2 s . c o m*/ Field amqpTemplateField = ReflectionUtils.findField(AmqpOutboundEndpoint.class, "amqpTemplate"); amqpTemplateField.setAccessible(true); RabbitTemplate amqpTemplate = TestUtils.getPropertyValue(endpoint, "amqpTemplate", RabbitTemplate.class); amqpTemplate = Mockito.spy(amqpTemplate); final AtomicBoolean shouldBePersistent = new AtomicBoolean(); Mockito.doAnswer(invocation -> { Object[] args = invocation.getArguments(); org.springframework.amqp.core.Message amqpMessage = (org.springframework.amqp.core.Message) args[2]; MessageProperties properties = amqpMessage.getMessageProperties(); assertEquals("foo", properties.getHeaders().get("foo")); assertEquals("foobar", properties.getHeaders().get("foobar")); assertNull(properties.getHeaders().get("bar")); assertEquals( shouldBePersistent.get() ? MessageDeliveryMode.PERSISTENT : MessageDeliveryMode.NON_PERSISTENT, properties.getDeliveryMode()); return null; }).when(amqpTemplate).send(Mockito.any(String.class), Mockito.any(String.class), Mockito.any(org.springframework.amqp.core.Message.class), Mockito.any(CorrelationData.class)); ReflectionUtils.setField(amqpTemplateField, endpoint, amqpTemplate); MessageChannel requestChannel = context.getBean("requestChannel", MessageChannel.class); Message<?> message = MessageBuilder.withPayload("hello").setHeader("foo", "foo").setHeader("bar", "bar") .setHeader("foobar", "foobar").build(); requestChannel.send(message); Mockito.verify(amqpTemplate, Mockito.times(1)).send(anyString(), isNull(), Mockito.any(org.springframework.amqp.core.Message.class), isNull()); shouldBePersistent.set(true); message = MessageBuilder.withPayload("hello").setHeader("foo", "foo").setHeader("bar", "bar") .setHeader("foobar", "foobar").setHeader(AmqpHeaders.DELIVERY_MODE, MessageDeliveryMode.PERSISTENT) .build(); requestChannel.send(message); }
From source file:org.springframework.integration.amqp.config.AmqpOutboundChannelAdapterParserTests.java
@SuppressWarnings("rawtypes") @Test/*from w w w . j av a 2 s .co m*/ public void amqpOutboundChannelAdapterWithinChain() { Object eventDrivenConsumer = context.getBean("chainWithRabbitOutbound"); List chainHandlers = TestUtils.getPropertyValue(eventDrivenConsumer, "handler.handlers", List.class); AmqpOutboundEndpoint endpoint = (AmqpOutboundEndpoint) chainHandlers.get(0); assertNull(TestUtils.getPropertyValue(endpoint, "defaultDeliveryMode")); Field amqpTemplateField = ReflectionUtils.findField(AmqpOutboundEndpoint.class, "amqpTemplate"); amqpTemplateField.setAccessible(true); RabbitTemplate amqpTemplate = TestUtils.getPropertyValue(endpoint, "amqpTemplate", RabbitTemplate.class); amqpTemplate = Mockito.spy(amqpTemplate); Mockito.doAnswer(invocation -> { Object[] args = invocation.getArguments(); org.springframework.amqp.core.Message amqpMessage = (org.springframework.amqp.core.Message) args[2]; MessageProperties properties = amqpMessage.getMessageProperties(); assertEquals("hello", new String(amqpMessage.getBody())); assertEquals(MessageDeliveryMode.PERSISTENT, properties.getDeliveryMode()); return null; }).when(amqpTemplate).send(Mockito.any(String.class), Mockito.any(String.class), Mockito.any(org.springframework.amqp.core.Message.class), Mockito.any(CorrelationData.class)); ReflectionUtils.setField(amqpTemplateField, endpoint, amqpTemplate); MessageChannel requestChannel = context.getBean("amqpOutboundChannelAdapterWithinChain", MessageChannel.class); Message<?> message = MessageBuilder.withPayload("hello").build(); requestChannel.send(message); Mockito.verify(amqpTemplate, Mockito.times(1)).send(Mockito.any(String.class), isNull(), Mockito.any(org.springframework.amqp.core.Message.class), isNull()); }
From source file:org.springframework.integration.config.IdGeneratorConfigurer.java
private boolean setIdGenerator(ApplicationContext context) { try {// w w w. ja v a 2 s.c o m IdGenerator idGeneratorBean = context.getBean(IdGenerator.class); if (logger.isDebugEnabled()) { logger.debug("using custom MessageHeaders.IdGenerator [" + idGeneratorBean.getClass() + "]"); } Field idGeneratorField = ReflectionUtils.findField(MessageHeaders.class, "idGenerator"); ReflectionUtils.makeAccessible(idGeneratorField); IdGenerator currentIdGenerator = (IdGenerator) ReflectionUtils.getField(idGeneratorField, null); if (currentIdGenerator != null) { if (currentIdGenerator.equals(idGeneratorBean)) { // same instance is already set, nothing needs to be done return false; } else { if (IdGeneratorConfigurer.theIdGenerator.getClass() == idGeneratorBean.getClass()) { if (logger.isWarnEnabled()) { logger.warn("Another instance of " + idGeneratorBean.getClass() + " has already been established; ignoring"); } return true; } else { // different instance has been set, not legal throw new BeanDefinitionStoreException( "'MessageHeaders.idGenerator' has already been set and can not be set again"); } } } if (logger.isInfoEnabled()) { logger.info("Message IDs will be generated using custom IdGenerator [" + idGeneratorBean.getClass() + "]"); } ReflectionUtils.setField(idGeneratorField, null, idGeneratorBean); IdGeneratorConfigurer.theIdGenerator = idGeneratorBean; } catch (NoSuchBeanDefinitionException e) { // No custom IdGenerator. We will use the default. int idBeans = context.getBeansOfType(IdGenerator.class).size(); if (idBeans > 1 && logger.isWarnEnabled()) { logger.warn("Found too many 'IdGenerator' beans (" + idBeans + ") " + "Will use the existing UUID strategy."); } else if (logger.isDebugEnabled()) { logger.debug("Unable to locate MessageHeaders.IdGenerator. Will use the existing UUID strategy."); } return false; } catch (IllegalStateException e) { // thrown from ReflectionUtils if (logger.isWarnEnabled()) { logger.warn("Unexpected exception occurred while accessing idGenerator of MessageHeaders." + " Will use the existing UUID strategy.", e); } return false; } return true; }
From source file:org.springframework.integration.config.IdGeneratorConfigurer.java
private void unsetIdGenerator() { try {/*w w w . ja v a 2s.c om*/ Field idGeneratorField = ReflectionUtils.findField(MessageHeaders.class, "idGenerator"); ReflectionUtils.makeAccessible(idGeneratorField); idGeneratorField.set(null, null); IdGeneratorConfigurer.theIdGenerator = null; } catch (Exception e) { if (logger.isWarnEnabled()) { logger.warn("Unexpected exception occurred while accessing idGenerator of MessageHeaders.", e); } } }