Java Code Examples for org.springframework.util.ReflectionUtils#getField()

The following examples show how to use org.springframework.util.ReflectionUtils#getField() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Override
public Name getCalculatedId(Object entry) {
    Assert.notNull(entry, "Entry must not be null");
    EntityData entityData = getEntityData(entry.getClass());
    if(entityData.metaData.canCalculateDn()) {
        Set<AttributeMetaData> dnAttributes = entityData.metaData.getDnAttributes();
        LdapNameBuilder ldapNameBuilder = LdapNameBuilder.newInstance(entityData.metaData.getBase());

        for (AttributeMetaData dnAttribute : dnAttributes) {
            Object dnFieldValue = ReflectionUtils.getField(dnAttribute.getField(), entry);
            if(dnFieldValue == null) {
                throw new IllegalStateException(
                        String.format("DnAttribute for field %s on class %s is null; cannot build DN",
                                dnAttribute.getField().getName(), entry.getClass().getName()));
            }

            ldapNameBuilder.add(dnAttribute.getDnAttribute().value(), dnFieldValue.toString());
        }

        return ldapNameBuilder.build();
    }

    return null;
}
 
Example 2
/**
 * Throw an {@link IllegalStateException} if the supplied {@code testClass}
 * does not declare a {@code public static final SpringClassRule} field
 * that is annotated with {@code @ClassRule}.
 */
private static SpringClassRule validateSpringClassRuleConfiguration(Class<?> testClass) {
	Field ruleField = null;

	for (Field field : testClass.getFields()) {
		if (ReflectionUtils.isPublicStaticFinal(field) && SpringClassRule.class.isAssignableFrom(field.getType())) {
			ruleField = field;
			break;
		}
	}

	if (ruleField == null) {
		throw new IllegalStateException(String.format(
				"Failed to find 'public static final SpringClassRule' field in test class [%s]. " +
				"Consult the javadoc for SpringClassRule for details.", testClass.getName()));
	}

	if (!ruleField.isAnnotationPresent(ClassRule.class)) {
		throw new IllegalStateException(String.format(
				"SpringClassRule field [%s] must be annotated with JUnit's @ClassRule annotation. " +
				"Consult the javadoc for SpringClassRule for details.", ruleField));
	}

	return (SpringClassRule) ReflectionUtils.getField(ruleField, null);
}
 
Example 3
private MapTaskBatchDao getMapTaskBatchDao() throws Exception {
	Field taskExecutionDaoField = ReflectionUtils.findField(SimpleTaskExplorer.class,
			"taskExecutionDao");
	taskExecutionDaoField.setAccessible(true);

	MapTaskExecutionDao taskExecutionDao;

	if (AopUtils.isJdkDynamicProxy(this.taskExplorer)) {
		SimpleTaskExplorer dereferencedTaskRepository = (SimpleTaskExplorer) ((Advised) this.taskExplorer)
				.getTargetSource().getTarget();

		taskExecutionDao = (MapTaskExecutionDao) ReflectionUtils
				.getField(taskExecutionDaoField, dereferencedTaskRepository);
	}
	else {
		taskExecutionDao = (MapTaskExecutionDao) ReflectionUtils
				.getField(taskExecutionDaoField, this.taskExplorer);
	}

	return new MapTaskBatchDao(taskExecutionDao.getBatchJobAssociations());
}
 
Example 4
private ConfigurableBeanFactory getBeanFactory(Object enhancedConfigInstance) {
	Field field = ReflectionUtils.findField(enhancedConfigInstance.getClass(), BEAN_FACTORY_FIELD);
	Assert.state(field != null, "Unable to find generated bean factory field");
	Object beanFactory = ReflectionUtils.getField(field, enhancedConfigInstance);
	Assert.state(beanFactory != null, "BeanFactory has not been injected into @Configuration class");
	Assert.state(beanFactory instanceof ConfigurableBeanFactory,
			"Injected BeanFactory is not a ConfigurableBeanFactory");
	return (ConfigurableBeanFactory) beanFactory;
}
 
Example 5
public void testCustomPartitionedProducerMultipleInstances() {
	ApplicationContext context = SpringApplication.run(
			CustomPartitionedProducerTest.TestSourceMultipleStrategies.class,
			"--spring.jmx.enabled=false", "--spring.main.web-application-type=none",
			"--spring.cloud.stream.bindings.output.producer.partitionKeyExtractorName=customPartitionKeyExtractorOne",
			"--spring.cloud.stream.bindings.output.producer.partitionSelectorName=customPartitionSelectorTwo",
			"--spring.cloud.stream.default-binder=mock");
	Source testSource = context.getBean(Source.class);
	DirectChannel messageChannel = (DirectChannel) testSource.output();
	for (ChannelInterceptor channelInterceptor : messageChannel
			.getInterceptors()) {
		if (channelInterceptor instanceof MessageConverterConfigurer.PartitioningInterceptor) {
			Field partitionHandlerField = ReflectionUtils.findField(
					MessageConverterConfigurer.PartitioningInterceptor.class,
					"partitionHandler");
			ReflectionUtils.makeAccessible(partitionHandlerField);
			PartitionHandler partitionHandler = (PartitionHandler) ReflectionUtils
					.getField(partitionHandlerField, channelInterceptor);
			Field partitonKeyExtractorField = ReflectionUtils.findField(
					PartitionHandler.class, "partitionKeyExtractorStrategy");
			ReflectionUtils.makeAccessible(partitonKeyExtractorField);
			Field partitonSelectorField = ReflectionUtils
					.findField(PartitionHandler.class, "partitionSelectorStrategy");
			ReflectionUtils.makeAccessible(partitonSelectorField);
			assertThat(((PartitionKeyExtractorStrategy) ReflectionUtils
					.getField(partitonKeyExtractorField, partitionHandler)).getClass()
							.equals(CustomPartitionKeyExtractorClass.class)).isTrue();
			assertThat(((PartitionSelectorStrategy) ReflectionUtils
					.getField(partitonSelectorField, partitionHandler)).getClass()
							.equals(CustomPartitionSelectorClass.class)).isTrue();
		}
	}
}
 
Example 6
@Override
public void unregisterChannelModel(ChannelModel channelModel, String tenantId, EventRepositoryService eventRepositoryService) {
    String endpointId = getEndpointId(channelModel,tenantId);
    // currently it is not possible to unregister a listener container
    // In order not to do a lot of the logic that Spring does we are manually accessing the containers to remove them
    // see https://github.com/spring-projects/spring-framework/issues/24228
    MessageListenerContainer listenerContainer = endpointRegistry.getListenerContainer(endpointId);
    if (listenerContainer != null) {
        listenerContainer.stop();
    }

    if (listenerContainer instanceof DisposableBean) {
        try {
            ((DisposableBean) listenerContainer).destroy();
        } catch (Exception e) {
            throw new RuntimeException("Failed to destroy listener container", e);
        }
    }

    Field listenerContainersField = ReflectionUtils.findField(endpointRegistry.getClass(), "listenerContainers");
    if (listenerContainersField != null) {
        listenerContainersField.setAccessible(true);
        @SuppressWarnings("unchecked")
        Map<String, MessageListenerContainer> listenerContainers = (Map<String, MessageListenerContainer>) ReflectionUtils.getField(listenerContainersField, endpointRegistry);
        if (listenerContainers != null) {
            listenerContainers.remove(endpointId);
        }
    } else {
        throw new IllegalStateException("Endpoint registry " + endpointRegistry + " does not have listenerContainers field");
    }
}
 
Example 7
@Test
public void testCustomPartitionedProducerAsSingletons() {
	ApplicationContext context = SpringApplication.run(
			CustomPartitionedProducerTest.TestSource.class,
			"--spring.jmx.enabled=false", "--spring.main.web-application-type=none",
			"--spring.cloud.stream.default-binder=mock");
	Source testSource = context.getBean(Source.class);
	DirectChannel messageChannel = (DirectChannel) testSource.output();
	for (ChannelInterceptor channelInterceptor : messageChannel
			.getInterceptors()) {
		if (channelInterceptor instanceof MessageConverterConfigurer.PartitioningInterceptor) {
			Field partitionHandlerField = ReflectionUtils.findField(
					MessageConverterConfigurer.PartitioningInterceptor.class,
					"partitionHandler");
			ReflectionUtils.makeAccessible(partitionHandlerField);
			PartitionHandler partitionHandler = (PartitionHandler) ReflectionUtils
					.getField(partitionHandlerField, channelInterceptor);
			Field partitonKeyExtractorField = ReflectionUtils.findField(
					PartitionHandler.class, "partitionKeyExtractorStrategy");
			ReflectionUtils.makeAccessible(partitonKeyExtractorField);
			Field partitonSelectorField = ReflectionUtils
					.findField(PartitionHandler.class, "partitionSelectorStrategy");
			ReflectionUtils.makeAccessible(partitonSelectorField);
			assertThat(((PartitionKeyExtractorStrategy) ReflectionUtils
					.getField(partitonKeyExtractorField, partitionHandler)).getClass()
							.equals(CustomPartitionKeyExtractorClass.class)).isTrue();
			assertThat(((PartitionSelectorStrategy) ReflectionUtils
					.getField(partitonSelectorField, partitionHandler)).getClass()
							.equals(CustomPartitionSelectorClass.class)).isTrue();
		}
	}
}
 
Example 8
Source Project: canal-1.1.3   File: ZooKeeperx.java    License: Apache License 2.0 5 votes vote down vote up
public void configMutliCluster(ZooKeeper zk) {
    if (_serversList.size() == 1) {
        return;
    }
    String cluster1 = _serversList.get(0);
    try {
        if (_serversList.size() > 1) {
            // 强制的声明accessible
            ReflectionUtils.makeAccessible(clientCnxnField);
            ReflectionUtils.makeAccessible(hostProviderField);
            ReflectionUtils.makeAccessible(serverAddressesField);

            // 添加第二组集群列表
            for (int i = 1; i < _serversList.size(); i++) {
                String cluster = _serversList.get(i);
                // 强制获取zk中的地址信息
                ClientCnxn cnxn = (ClientCnxn) ReflectionUtils.getField(clientCnxnField, zk);
                HostProvider hostProvider = (HostProvider) ReflectionUtils.getField(hostProviderField, cnxn);
                List<InetSocketAddress> serverAddrs = (List<InetSocketAddress>) ReflectionUtils.getField(serverAddressesField,
                    hostProvider);
                // 添加第二组集群列表
                serverAddrs.addAll(new ConnectStringParser(cluster).getServerAddresses());
            }
        }
    } catch (Exception e) {
        try {
            if (zk != null) {
                zk.close();
            }
        } catch (InterruptedException ie) {
            // ignore interrupt
        }
        throw new ZkException("zookeeper_create_error, serveraddrs=" + cluster1, e);
    }

}
 
Example 9
@Override
public void unregisterChannelModel(ChannelModel channelModel, String tenantId, EventRepositoryService eventRepositoryService) {
    String endpointId = getEndpointId(channelModel, tenantId);
    // currently it is not possible to unregister a listener container
    // In order not to do a lot of the logic that Spring does we are manually accessing the containers to remove them
    // see https://github.com/spring-projects/spring-framework/issues/24228
    MessageListenerContainer listenerContainer = endpointRegistry.getListenerContainer(endpointId);
    if (listenerContainer != null) {
        listenerContainer.stop();
    }

    if (listenerContainer instanceof DisposableBean) {
        try {
            ((DisposableBean) listenerContainer).destroy();
        } catch (Exception e) {
            throw new RuntimeException("Failed to destroy listener container", e);
        }
    }

    Field listenerContainersField = ReflectionUtils.findField(endpointRegistry.getClass(), "listenerContainers");
    if (listenerContainersField != null) {
        listenerContainersField.setAccessible(true);
        @SuppressWarnings("unchecked")
        Map<String, MessageListenerContainer> listenerContainers = (Map<String, MessageListenerContainer>) ReflectionUtils
            .getField(listenerContainersField, endpointRegistry);
        if (listenerContainers != null) {
            listenerContainers.remove(endpointId);
        }
    } else {
        throw new IllegalStateException("Endpoint registry " + endpointRegistry + " does not have listenerContainers field");
    }
}
 
Example 10
@Test
public void testHelperLoadingOrder() {
  ConfigPropertySourcesProcessor processor = new ConfigPropertySourcesProcessor();

  Field field = ReflectionUtils.findField(ConfigPropertySourcesProcessor.class, "helper");
  ReflectionUtils.makeAccessible(field);
  Object helper = ReflectionUtils.getField(field, processor);

  assertEquals("helper is not TestProcessorHelper instance", TestProcessorHelper.class, helper.getClass());
}
 
Example 11
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
		throws BeansException {

	registerJobExecutionEventListener(bean);

	if (bean instanceof AbstractStep) {
		registerStepExecutionEventListener(bean);
		if (bean instanceof TaskletStep) {
			TaskletStep taskletStep = (TaskletStep) bean;
			Tasklet tasklet = taskletStep.getTasklet();
			registerChunkEventsListener(bean);

			if (tasklet instanceof ChunkOrientedTasklet) {
				Field chunkProviderField = ReflectionUtils
						.findField(ChunkOrientedTasklet.class, "chunkProvider");
				ReflectionUtils.makeAccessible(chunkProviderField);
				SimpleChunkProvider chunkProvider = (SimpleChunkProvider) ReflectionUtils
						.getField(chunkProviderField, tasklet);
				Field chunkProcessorField = ReflectionUtils
						.findField(ChunkOrientedTasklet.class, "chunkProcessor");
				ReflectionUtils.makeAccessible(chunkProcessorField);
				SimpleChunkProcessor chunkProcessor = (SimpleChunkProcessor) ReflectionUtils
						.getField(chunkProcessorField, tasklet);
				registerItemReadEvents(chunkProvider);
				registerSkipEvents(chunkProvider);
				registerItemProcessEvents(chunkProcessor);
				registerItemWriteEvents(chunkProcessor);
				registerSkipEvents(chunkProcessor);
			}
		}
	}

	return bean;
}
 
Example 12
Source Project: bdf3   File: UUIDPolicy.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Object getValue(Object entity, Field field) {
	Object value = ReflectionUtils.getField(field, entity);
	if (value == null) {
		return UUID.randomUUID().toString();
	}
	return value;
}
 
Example 13
private int countShutdownHooks() {
	Class<?> type = ClassUtils.resolveClassName("java.lang.ApplicationShutdownHooks",
			null);
	Field field = ReflectionUtils.findField(type, "hooks");
	ReflectionUtils.makeAccessible(field);
	@SuppressWarnings("rawtypes")
	Map map = (Map) ReflectionUtils.getField(field, null);
	return map.size();
}
 
Example 14
public String getPid() {
	String pid = null;
	try {
		if (started != null) {
			Field field = ReflectionUtils.findField(started.getClass(), "pid");
			ReflectionUtils.makeAccessible(field);
			pid = "" + ReflectionUtils.getField(field, started);
		}
	}
	catch (Exception e) {
	}
	return pid;
}
 
Example 15
private void createProxyHandler(RedisTemplate redisTemplate, Class clazz, String name) {
    try {
        Field field = ReflectionUtils.findField(RedisTemplate.class, name, clazz);
        ReflectionUtils.makeAccessible(field);
        Object object = ReflectionUtils.getField(field, redisTemplate);
        DataRedisProxyHandler handler = new DataRedisProxyHandler(object);
        Object proxy = Proxy.newProxyInstance(handler.getClass().getClassLoader(), new Class[] {clazz}, handler);
        field.set(redisTemplate, proxy);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 16
/**
 * @param customConverters a list of {@link AbstractMessageConverter}
 * @param objectMapper object mapper for for serialization / deserialization
 */
public CompositeMessageConverterFactory(
		List<? extends MessageConverter> customConverters,
		ObjectMapper objectMapper) {
	this.objectMapper = objectMapper;
	if (!CollectionUtils.isEmpty(customConverters)) {
		this.converters = new ArrayList<>(customConverters);
	}
	else {
		this.converters = new ArrayList<>();
	}
	initDefaultConverters();

	Field headersField = ReflectionUtils.findField(MessageHeaders.class, "headers");
	headersField.setAccessible(true);
	DefaultContentTypeResolver resolver = new DefaultContentTypeResolver() {
		@Override
		@SuppressWarnings("unchecked")
		public MimeType resolve(@Nullable MessageHeaders headers) {
			Object contentType = headers.get(MessageHeaders.CONTENT_TYPE);
			if (contentType instanceof byte[]) {
				contentType = new String((byte[]) contentType, StandardCharsets.UTF_8);
				contentType = ((String) contentType).replace("\"", "");
				Map<String, Object> headersMap = (Map<String, Object>) ReflectionUtils.getField(headersField, headers);
				headersMap.put(MessageHeaders.CONTENT_TYPE, contentType);
			}
			return super.resolve(headers);
		}
	};
	resolver.setDefaultMimeType(BindingProperties.DEFAULT_CONTENT_TYPE);
	this.converters.stream().filter(mc -> mc instanceof AbstractMessageConverter)
			.forEach(mc -> ((AbstractMessageConverter) mc)
					.setContentTypeResolver(resolver));
}
 
Example 17
private HttpClient getActualHttpClient(HttpConnection actualConnection) {
	Field clientField = ReflectionUtils.findField(actualConnection.getClass(),
			"client");
	ReflectionUtils.makeAccessible(clientField);
	return (HttpClient) ReflectionUtils.getField(clientField, actualConnection);
}
 
Example 18
Source Project: gocd   File: RouteInformationProvider.java    License: Apache License 2.0 4 votes vote down vote up
private static <T> T getField(Object o, String fieldName) {
    Field field = ReflectionUtils.findField(o.getClass(), fieldName);
    ReflectionUtils.makeAccessible(field);
    return (T) ReflectionUtils.getField(field, o);
}
 
Example 19
Source Project: phone   File: AopProxyUtils.java    License: Apache License 2.0 4 votes vote down vote up
private static ProxyFactory findJdkDynamicProxyFactory(final Object proxy) {
    Object jdkDynamicAopProxy = ReflectionUtils.getField(JdkDynamicProxy_h_FIELD, proxy);
    return (ProxyFactory) ReflectionUtils.getField(JdkDynamicAopProxy_advised_FIELD, jdkDynamicAopProxy);
}
 
Example 20
public String getPartitionKeyFieldValue(T entity) {
    return partitionKeyField == null ? null : (String) ReflectionUtils.getField(partitionKeyField, entity);
}