Java Code Examples for org.springframework.util.ReflectionUtils

The following examples show how to use org.springframework.util.ReflectionUtils. These examples are extracted from open source projects.
Example 1
Project: spring-data-cosmosdb   File: CosmosEntityInformation.java    License: MIT License 6 votes vote down vote up
private Field getIdField(Class<?> domainType) {
    final Field idField;
    final List<Field> fields = FieldUtils.getFieldsListWithAnnotation(domainType, Id.class);

    if (fields.isEmpty()) {
        idField = ReflectionUtils.findField(getJavaType(), Constants.ID_PROPERTY_NAME);
    } else if (fields.size() == 1) {
        idField = fields.get(0);
    } else {
        throw new IllegalArgumentException("only one field with @Id annotation!");
    }

    if (idField == null) {
        throw new IllegalArgumentException("domain should contain @Id field or field named id");
    } else if (idField.getType() != String.class
            && idField.getType() != Integer.class && idField.getType() != int.class) {
        throw new IllegalArgumentException("type of id field must be String or Integer");
    }

    return idField;
}
 
Example 2
Project: spring-analysis-note   File: TestContextManager.java    License: MIT License 6 votes vote down vote up
/**
 * Hook for pre-processing a test class <em>before</em> execution of any
 * tests within the class. Should be called prior to any framework-specific
 * <em>before class methods</em> (e.g., methods annotated with JUnit 4's
 * {@link org.junit.BeforeClass @BeforeClass}).
 * <p>An attempt will be made to give each registered
 * {@link TestExecutionListener} a chance to pre-process the test class
 * execution. If a listener throws an exception, however, the remaining
 * registered listeners will <strong>not</strong> be called.
 * @throws Exception if a registered TestExecutionListener throws an
 * exception
 * @since 3.0
 * @see #getTestExecutionListeners()
 */
public void beforeTestClass() throws Exception {
	Class<?> testClass = getTestContext().getTestClass();
	if (logger.isTraceEnabled()) {
		logger.trace("beforeTestClass(): class [" + testClass.getName() + "]");
	}
	getTestContext().updateState(null, null, null);

	for (TestExecutionListener testExecutionListener : getTestExecutionListeners()) {
		try {
			testExecutionListener.beforeTestClass(getTestContext());
		}
		catch (Throwable ex) {
			logException(ex, "beforeTestClass", testExecutionListener, testClass);
			ReflectionUtils.rethrowException(ex);
		}
	}
}
 
Example 3
Project: java-technology-stack   File: CustomCollectionEditor.java    License: MIT License 6 votes vote down vote up
/**
 * Create a Collection of the given type, with the given
 * initial capacity (if supported by the Collection type).
 * @param collectionType a sub-interface of Collection
 * @param initialCapacity the initial capacity
 * @return the new Collection instance
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
protected Collection<Object> createCollection(Class<? extends Collection> collectionType, int initialCapacity) {
	if (!collectionType.isInterface()) {
		try {
			return ReflectionUtils.accessibleConstructor(collectionType).newInstance();
		}
		catch (Throwable ex) {
			throw new IllegalArgumentException(
					"Could not instantiate collection class: " + collectionType.getName(), ex);
		}
	}
	else if (List.class == collectionType) {
		return new ArrayList<>(initialCapacity);
	}
	else if (SortedSet.class == collectionType) {
		return new TreeSet<>();
	}
	else {
		return new LinkedHashSet<>(initialCapacity);
	}
}
 
Example 4
Project: mPaaS   File: ModuleMappingLoader.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 构建单个maping信息到map中
 *
 * @param resultMap
 * @param key
 * @param value
 */
default void buildMapingInfo(Map<String, ModuleMappingInfo> resultMap, String key, String value) {
    if (!StringUtils.isEmpty(key) && key.startsWith(SVR_PREFIX) && !StringUtils.isEmpty(value)) {
        String method = "set" + StringHelper.toFirstUpperCase(key.substring(key.lastIndexOf(NamingConstant.DOT) + 1));
        key = key.substring(SVR_PREFIX.length(), key.lastIndexOf(NamingConstant.DOT));
        ModuleMappingInfo info = resultMap.get(key);
        if (info == null) {
            info = new ModuleMappingInfo();
            resultMap.put(key, info);
        }
        Method methodObj = ReflectionUtils.findMethod(info.getClass(), method, String.class);
        if (methodObj != null) {
            ReflectionUtils.invokeMethod(methodObj, info, value);
        }
    }
}
 
Example 5
Project: java-technology-stack   File: Property.java    License: MIT License 6 votes vote down vote up
@Nullable
private Field getField() {
	String name = getName();
	if (!StringUtils.hasLength(name)) {
		return null;
	}
	Field field = null;
	Class<?> declaringClass = declaringClass();
	if (declaringClass != null) {
		field = ReflectionUtils.findField(declaringClass, name);
		if (field == null) {
			// Same lenient fallback checking as in CachedIntrospectionResults...
			field = ReflectionUtils.findField(declaringClass, StringUtils.uncapitalize(name));
			if (field == null) {
				field = ReflectionUtils.findField(declaringClass, StringUtils.capitalize(name));
			}
		}
	}
	return field;
}
 
Example 6
Project: java-technology-stack   File: HibernateTemplate.java    License: MIT License 6 votes vote down vote up
@Deprecated
@Override
@SuppressWarnings({"rawtypes", "deprecation"})
public Iterator<?> iterate(final String queryString, @Nullable final Object... values) throws DataAccessException {
	return nonNull(executeWithNativeSession((HibernateCallback<Iterator<?>>) session -> {
		org.hibernate.Query queryObject = queryObject(
				ReflectionUtils.invokeMethod(createQueryMethod, session, queryString));
		prepareQuery(queryObject);
		if (values != null) {
			for (int i = 0; i < values.length; i++) {
				queryObject.setParameter(i, values[i]);
			}
		}
		return queryObject.iterate();
	}));
}
 
Example 7
Project: spring4-understanding   File: MvcUriComponentsBuilder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) {
	if (getControllerMethod.equals(method)) {
		return this.controllerMethod;
	}
	else if (getArgumentValues.equals(method)) {
		return this.argumentValues;
	}
	else if (getControllerType.equals(method)) {
		return this.controllerType;
	}
	else if (ReflectionUtils.isObjectMethod(method)) {
		return ReflectionUtils.invokeMethod(method, obj, args);
	}
	else {
		this.controllerMethod = method;
		this.argumentValues = args;
		Class<?> returnType = method.getReturnType();
		return (void.class == returnType ? null : returnType.cast(initProxy(returnType, this)));
	}
}
 
Example 8
Project: spring-analysis-note   File: SimpleInstantiationStrategy.java    License: MIT License 6 votes vote down vote up
@Override
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,
		final Constructor<?> ctor, Object... args) {

	if (!bd.hasMethodOverrides()) {
		if (System.getSecurityManager() != null) {
			// use own privileged to change accessibility (when security is on)
			AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
				ReflectionUtils.makeAccessible(ctor);
				return null;
			});
		}
		return BeanUtils.instantiateClass(ctor, args);
	}
	else {
		return instantiateWithMethodInjection(bd, beanName, owner, ctor, args);
	}
}
 
Example 9
Project: Taroco-Scheduler   File: TaskManager.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 封装ScheduledMethodRunnable对象
 */
private ScheduledMethodRunnable buildScheduledRunnable(Object bean, String targetMethod, String params, String extKeySuffix, String scheduleKey) {
    Method method;
    Class<?> clazz;
    if (AopUtils.isAopProxy(bean)) {
        clazz = AopProxyUtils.ultimateTargetClass(bean);
    } else {
        clazz = bean.getClass();
    }
    if (params != null) {
        method = ReflectionUtils.findMethod(clazz, targetMethod, String.class);
    } else {
        method = ReflectionUtils.findMethod(clazz, targetMethod);
    }
    if (ObjectUtils.isEmpty(method)) {
        zkClient.getTaskGenerator().getScheduleTask().saveRunningInfo(scheduleKey, ScheduleServer.getInstance().getUuid(), "method not found");
        log.error("启动动态任务失败: {}, 失败原因: {}", scheduleKey, "method not found");
        return null;
    }
    return new ScheduledMethodRunnable(bean, method, params, extKeySuffix);
}
 
Example 10
Project: spring-cloud-aws   File: NotificationSubjectHandlerMethodArgumentResolverTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void resolveArgument_wrongMessageType_reportsErrors() throws Exception {
	// Arrange
	NotificationSubjectHandlerMethodArgumentResolver resolver = new NotificationSubjectHandlerMethodArgumentResolver();

	byte[] subscriptionRequestJsonContent = FileCopyUtils.copyToByteArray(
			new ClassPathResource("subscriptionConfirmation.json", getClass())
					.getInputStream());
	MockHttpServletRequest servletRequest = new MockHttpServletRequest();
	servletRequest.setContent(subscriptionRequestJsonContent);

	MethodParameter methodParameter = new MethodParameter(
			ReflectionUtils.findMethod(NotificationMethods.class,
					"subscriptionMethod", NotificationStatus.class),
			0);

	// Assert
	assertThatThrownBy(() -> resolver.resolveArgument(methodParameter, null,
			new ServletWebRequest(servletRequest), null))
					.isInstanceOf(IllegalArgumentException.class)
					.hasMessageContaining(
							"@NotificationMessage annotated parameters are only allowed");
}
 
Example 11
Project: spring-analysis-note   File: AnnotationTypeMapping.java    License: MIT License 6 votes vote down vote up
private void processAliases(int attributeIndex, List<Method> aliases) {
	int rootAttributeIndex = getFirstRootAttributeIndex(aliases);
	AnnotationTypeMapping mapping = this;
	while (mapping != null) {
		if (rootAttributeIndex != -1 && mapping != this.root) {
			for (int i = 0; i < mapping.attributes.size(); i++) {
				if (aliases.contains(mapping.attributes.get(i))) {
					mapping.aliasMappings[i] = rootAttributeIndex;
				}
			}
		}
		mapping.mirrorSets.updateFrom(aliases);
		mapping.claimedAliases.addAll(aliases);
		if (mapping.annotation != null) {
			int[] resolvedMirrors = mapping.mirrorSets.resolve(null,
					mapping.annotation, ReflectionUtils::invokeMethod);
			for (int i = 0; i < mapping.attributes.size(); i++) {
				if (aliases.contains(mapping.attributes.get(i))) {
					this.annotationValueMappings[attributeIndex] = resolvedMirrors[i];
					this.annotationValueSource[attributeIndex] = mapping;
				}
			}
		}
		mapping = mapping.parent;
	}
}
 
Example 12
Project: spring-analysis-note   File: RmiClientInterceptorUtils.java    License: MIT License 6 votes vote down vote up
/**
 * Convert the given RemoteException that happened during remote access
 * to Spring's RemoteAccessException if the method signature does not
 * support RemoteException. Else, return the original RemoteException.
 * @param method the invoked method
 * @param ex the RemoteException that happened
 * @param isConnectFailure whether the given exception should be considered
 * a connect failure
 * @param serviceName the name of the service (for debugging purposes)
 * @return the exception to be thrown to the caller
 */
public static Exception convertRmiAccessException(
		Method method, RemoteException ex, boolean isConnectFailure, String serviceName) {

	if (logger.isDebugEnabled()) {
		logger.debug("Remote service [" + serviceName + "] threw exception", ex);
	}
	if (ReflectionUtils.declaresException(method, ex.getClass())) {
		return ex;
	}
	else {
		if (isConnectFailure) {
			return new RemoteConnectFailureException("Could not connect to remote service [" + serviceName + "]", ex);
		}
		else {
			return new RemoteAccessException("Could not access remote service [" + serviceName + "]", ex);
		}
	}
}
 
Example 13
Project: spring-analysis-note   File: TestContextManager.java    License: MIT License 6 votes vote down vote up
/**
 * Hook for preparing a test instance prior to execution of any individual
 * test methods, for example for injecting dependencies, etc. Should be
 * called immediately after instantiation of the test instance.
 * <p>The managed {@link TestContext} will be updated with the supplied
 * {@code testInstance}.
 * <p>An attempt will be made to give each registered
 * {@link TestExecutionListener} a chance to prepare the test instance. If a
 * listener throws an exception, however, the remaining registered listeners
 * will <strong>not</strong> be called.
 * @param testInstance the test instance to prepare (never {@code null})
 * @throws Exception if a registered TestExecutionListener throws an exception
 * @see #getTestExecutionListeners()
 */
public void prepareTestInstance(Object testInstance) throws Exception {
	if (logger.isTraceEnabled()) {
		logger.trace("prepareTestInstance(): instance [" + testInstance + "]");
	}
	getTestContext().updateState(testInstance, null, null);

	for (TestExecutionListener testExecutionListener : getTestExecutionListeners()) {
		try {
			testExecutionListener.prepareTestInstance(getTestContext());
		}
		catch (Throwable ex) {
			if (logger.isErrorEnabled()) {
				logger.error("Caught exception while allowing TestExecutionListener [" + testExecutionListener +
						"] to prepare test instance [" + testInstance + "]", ex);
			}
			ReflectionUtils.rethrowException(ex);
		}
	}
}
 
Example 14
Project: spring-cloud-sleuth   File: LazyTraceThreadPoolTaskScheduler.java    License: Apache License 2.0 6 votes vote down vote up
LazyTraceThreadPoolTaskScheduler(BeanFactory beanFactory,
		ThreadPoolTaskScheduler delegate) {
	this.beanFactory = beanFactory;
	this.delegate = delegate;
	this.initializeExecutor = ReflectionUtils
			.findMethod(ThreadPoolTaskScheduler.class, "initializeExecutor", null);
	makeAccessibleIfNotNull(this.initializeExecutor);
	this.createExecutor = ReflectionUtils.findMethod(ThreadPoolTaskScheduler.class,
			"createExecutor", null);
	makeAccessibleIfNotNull(this.createExecutor);
	this.cancelRemainingTask = ReflectionUtils
			.findMethod(ThreadPoolTaskScheduler.class, "cancelRemainingTask", null);
	makeAccessibleIfNotNull(this.cancelRemainingTask);
	this.nextThreadName = ReflectionUtils.findMethod(ThreadPoolTaskScheduler.class,
			"nextThreadName", null);
	makeAccessibleIfNotNull(this.nextThreadName);
	this.getDefaultThreadNamePrefix = ReflectionUtils.findMethod(
			CustomizableThreadCreator.class, "getDefaultThreadNamePrefix", null);
	makeAccessibleIfNotNull(this.getDefaultThreadNamePrefix);
}
 
Example 15
Project: elasticactors   File: LazyTraceThreadPoolTaskScheduler.java    License: Apache License 2.0 6 votes vote down vote up
LazyTraceThreadPoolTaskScheduler(ThreadPoolTaskScheduler delegate) {
    this.delegate = delegate;
    this.initializeExecutor = ReflectionUtils
            .findMethod(ThreadPoolTaskScheduler.class, "initializeExecutor", null);
    makeAccessibleIfNotNull(this.initializeExecutor);
    this.createExecutor = ReflectionUtils.findMethod(ThreadPoolTaskScheduler.class,
            "createExecutor", null);
    makeAccessibleIfNotNull(this.createExecutor);
    this.cancelRemainingTask = ReflectionUtils
            .findMethod(ThreadPoolTaskScheduler.class, "cancelRemainingTask", null);
    makeAccessibleIfNotNull(this.cancelRemainingTask);
    this.nextThreadName = ReflectionUtils.findMethod(ThreadPoolTaskScheduler.class,
            "nextThreadName", null);
    makeAccessibleIfNotNull(this.nextThreadName);
    this.getDefaultThreadNamePrefix = ReflectionUtils.findMethod(
            CustomizableThreadCreator.class, "getDefaultThreadNamePrefix", null);
    makeAccessibleIfNotNull(this.getDefaultThreadNamePrefix);
}
 
Example 16
Project: JuniperBot   File: SourceResolverServiceImpl.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public Guild getGuild(GenericEvent event) {
    if (event == null) {
        return null;
    }
    Class<? extends GenericEvent> clazz = event.getClass();
    Method method;
    if (!guildAccessors.containsKey(clazz)) {
        method = ReflectionUtils.findMethod(clazz, "getGuild");
        guildAccessors.put(clazz, method);
    } else {
        method = guildAccessors.get(clazz);
    }
    if (method != null) {
        try {
            Object result = ReflectionUtils.invokeMethod(method, event);
            if (result instanceof Guild) {
                return (Guild) result;
            }
        } catch (Exception e) {
            // we don't care
        }
    }
    return null;
}
 
Example 17
Project: soul   File: ApacheDubboServiceBeanPostProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private void handler(final ServiceBean serviceBean) {
    Class<?> clazz = serviceBean.getRef().getClass();
    if (ClassUtils.isCglibProxyClass(clazz)) {
        String superClassName = clazz.getGenericSuperclass().getTypeName();
        try {
            clazz = Class.forName(superClassName);
        } catch (ClassNotFoundException e) {
            log.error(String.format("class not found: %s", superClassName));
            return;
        }
    }
    final Method[] methods = ReflectionUtils.getUniqueDeclaredMethods(clazz);
    for (Method method : methods) {
        SoulDubboClient soulDubboClient = method.getAnnotation(SoulDubboClient.class);
        if (Objects.nonNull(soulDubboClient)) {
            post(buildJsonParams(serviceBean, soulDubboClient, method));
        }
    }
}
 
Example 18
Project: java-technology-stack   File: Jaxb2CollectionHttpMessageConverter.java    License: MIT License 6 votes vote down vote up
/**
 * Create a Collection of the given type, with the given initial capacity
 * (if supported by the Collection type).
 * @param collectionClass the type of Collection to instantiate
 * @return the created Collection instance
 */
@SuppressWarnings("unchecked")
protected T createCollection(Class<?> collectionClass) {
	if (!collectionClass.isInterface()) {
		try {
			return (T) ReflectionUtils.accessibleConstructor(collectionClass).newInstance();
		}
		catch (Throwable ex) {
			throw new IllegalArgumentException(
					"Could not instantiate collection class: " + collectionClass.getName(), ex);
		}
	}
	else if (List.class == collectionClass) {
		return (T) new ArrayList();
	}
	else if (SortedSet.class == collectionClass) {
		return (T) new TreeSet();
	}
	else {
		return (T) new LinkedHashSet();
	}
}
 
Example 19
Project: java-technology-stack   File: ConfigurationClassEnhancer.java    License: MIT License 5 votes vote down vote up
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 20
Project: spring-analysis-note   File: JCacheInterceptorTests.java    License: MIT License 5 votes vote down vote up
@Test
public void noCacheCouldBeResolved() {
	JCacheInterceptor interceptor = createInterceptor(createOperationSource(
			cacheManager, new NamedCacheResolver(cacheManager), // Returns empty list
			defaultExceptionCacheResolver, defaultKeyGenerator));

	AnnotatedJCacheableService service = new AnnotatedJCacheableService(cacheManager.getCache("default"));
	Method m = ReflectionUtils.findMethod(AnnotatedJCacheableService.class, "cache", String.class);
	assertThatIllegalStateException().isThrownBy(() ->
			interceptor.execute(dummyInvoker, service, m, new Object[] {"myId"}))
		.withMessageContaining("Cache could not have been resolved for");
}
 
Example 21
Project: quickperf   File: QuickPerfProxyBeanPostProcessor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object invoke(final MethodInvocation invocation) throws Throwable {
    Method proxyMethod = ReflectionUtils.findMethod( this.datasourceProxy.getClass()
                                                   , invocation.getMethod().getName());
    if (proxyMethod != null) {
        return proxyMethod.invoke(this.datasourceProxy, invocation.getArguments());
    }
    return invocation.proceed();
}
 
Example 22
Project: DotCi   File: DbBackedBuild.java    License: MIT License 5 votes vote down vote up
public String getState() {
    String stateName = null;
    try {
        final Field field = Run.class.getDeclaredField("state");
        field.setAccessible(true);
        stateName = ReflectionUtils.getField(field, this).toString();
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }

    return stateName;
}
 
Example 23
Project: spring-cloud-sleuth   File: SleuthAdvisorConfig.java    License: Apache License 2.0 5 votes vote down vote up
boolean hasAnnotatedMethods(Class<?> clazz) {
	final AtomicBoolean found = new AtomicBoolean(false);
	ReflectionUtils.doWithMethods(clazz, (method -> {
		if (found.get()) {
			return;
		}
		Annotation annotation = AnnotationUtils.findAnnotation(method,
				AnnotationMethodsResolver.this.annotationType);
		if (annotation != null) {
			found.set(true);
		}
	}));
	return found.get();
}
 
Example 24
Project: apollo   File: ApolloJsonValueProcessor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void processMethod(Object bean, String beanName, Method method) {
  ApolloJsonValue apolloJsonValue = AnnotationUtils.getAnnotation(method, ApolloJsonValue.class);
  if (apolloJsonValue == null) {
    return;
  }
  String placeHolder = apolloJsonValue.value();

  Object propertyValue = placeholderHelper
      .resolvePropertyValue(beanFactory, beanName, placeHolder);

  // propertyValue will never be null, as @ApolloJsonValue will not allow that
  if (!(propertyValue instanceof String)) {
    return;
  }

  Type[] types = method.getGenericParameterTypes();
  Preconditions.checkArgument(types.length == 1,
      "Ignore @Value setter {}.{}, expecting 1 parameter, actual {} parameters",
      bean.getClass().getName(), method.getName(), method.getParameterTypes().length);

  boolean accessible = method.isAccessible();
  method.setAccessible(true);
  ReflectionUtils.invokeMethod(method, bean, parseJsonValue((String)propertyValue, types[0]));
  method.setAccessible(accessible);

  if (configUtil.isAutoUpdateInjectedSpringPropertiesEnabled()) {
    Set<String> keys = placeholderHelper.extractPlaceholderKeys(placeHolder);
    for (String key : keys) {
      SpringValue springValue = new SpringValue(key, apolloJsonValue.value(), bean, beanName,
          method, true);
      springValueRegistry.register(beanFactory, key, springValue);
      logger.debug("Monitoring {}", springValue);
    }
  }
}
 
Example 25
Project: spring-analysis-note   File: ApplicationListenerMethodAdapterTests.java    License: MIT License 5 votes vote down vote up
@Test
public void invokeListenerWithGenericPayload() {
	Method method = ReflectionUtils.findMethod(
			SampleEvents.class, "handleGenericStringPayload", EntityWrapper.class);
	EntityWrapper<String> payload = new EntityWrapper<>("test");
	invokeListener(method, new PayloadApplicationEvent<>(this, payload));
	verify(this.sampleEvents, times(1)).handleGenericStringPayload(payload);
}
 
Example 26
Project: servicecomb-java-chassis   File: RpcReferenceProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private void handleReferenceField(Object obj, Field field,
    RpcReference reference) {
  String microserviceName = reference.microserviceName();
  microserviceName = resolver.resolveStringValue(microserviceName);

  PojoReferenceMeta pojoReference = new PojoReferenceMeta();
  pojoReference.setMicroserviceName(microserviceName);
  pojoReference.setSchemaId(reference.schemaId());
  pojoReference.setConsumerIntf(field.getType());

  pojoReference.afterPropertiesSet();

  ReflectionUtils.makeAccessible(field);
  ReflectionUtils.setField(field, obj, pojoReference.getProxy());
}
 
Example 27
Project: java-technology-stack   File: ApplicationListenerMethodTransactionalAdapterTests.java    License: MIT License 5 votes vote down vote up
@Test
public void phaseAndClassesSet() {
	Method m = ReflectionUtils.findMethod(SampleEvents.class, "phaseAndClassesSet");
	assertPhase(m, TransactionPhase.AFTER_COMPLETION);
	supportsEventType(true, m, createGenericEventType(String.class));
	supportsEventType(true, m, createGenericEventType(Integer.class));
	supportsEventType(false, m, createGenericEventType(Double.class));
}
 
Example 28
Project: cloudbreak   File: ConsulUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static ConsulClient createClient(String apiAddress, int apiPort, TlsConfiguration tlsConfiguration) throws Exception {
    HttpClient httpClient = createHttpClient(tlsConfiguration.getClientCert(), tlsConfiguration.getClientKey(), tlsConfiguration.getServerCert());
    ConsulRawClient rawClient = new ConsulRawClient("https://" + apiAddress + ':' + apiPort, httpClient);
    Field agentAddress = ReflectionUtils.findField(ConsulRawClient.class, "agentAddress");
    ReflectionUtils.makeAccessible(agentAddress);
    ReflectionUtils.setField(agentAddress, rawClient, "https://" + apiAddress + ':' + apiPort + "/consul");
    return new ConsulClient(rawClient);
}
 
Example 29
/**
 * Identify a specific GlassFish thread pool to talk to.
 * <p>The thread pool name matches the resource adapter name
 * in default RAR deployment scenarios.
 */
public void setThreadPoolName(String threadPoolName) {
	WorkManager wm = (WorkManager) ReflectionUtils.invokeMethod(this.getWorkManagerMethod, null, threadPoolName);
	if (wm == null) {
		throw new IllegalArgumentException("Specified thread pool name '" + threadPoolName +
				"' does not correspond to an actual pool definition in GlassFish. Check your configuration!");
	}
	setWorkManager(wm);
}
 
Example 30
Project: spring-cloud-task   File: TaskBatchEventListenerBeanPostProcessor.java    License: Apache License 2.0 5 votes vote down vote up
@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 31
Project: phone   File: AopProxyUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static ProxyFactory findCglibProxyFactory(final Object proxy) {
    Field field  = ReflectionUtils.findField(proxy.getClass(), "CGLIB$CALLBACK_0");
    ReflectionUtils.makeAccessible(field);
    Object CGLIB$CALLBACK_0 = ReflectionUtils.getField(field, proxy);
    return (ProxyFactory) ReflectionUtils.getField(CglibAopProxy$DynamicAdvisedInterceptor_advised_FIELD, CGLIB$CALLBACK_0);

}
 
Example 32
Project: spring4-understanding   File: VelocityToolboxView.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Overridden to check for the ViewContext interface which is part of the
 * view package of Velocity Tools. This requires a special Velocity context,
 * like ChainedContext as set up by {@link #createVelocityContext} in this class.
 */
@Override
protected void initTool(Object tool, Context velocityContext) throws Exception {
	// Velocity Tools 1.3: a class-level "init(Object)" method.
	Method initMethod = ClassUtils.getMethodIfAvailable(tool.getClass(), "init", Object.class);
	if (initMethod != null) {
		ReflectionUtils.invokeMethod(initMethod, tool, velocityContext);
	}
}
 
Example 33
Project: spring-analysis-note   File: ApplicationListenerMethodAdapterTests.java    License: MIT License 5 votes vote down vote up
@Test
public void invokeListenerWithWrongGenericPayload() {
	Method method = ReflectionUtils.findMethod
			(SampleEvents.class, "handleGenericStringPayload", EntityWrapper.class);
	EntityWrapper<Integer> payload = new EntityWrapper<>(123);
	invokeListener(method, new PayloadApplicationEvent<>(this, payload));
	verify(this.sampleEvents, times(0)).handleGenericStringPayload(any());
}
 
Example 34
Project: spring-analysis-note   File: CachedExpressionEvaluatorTests.java    License: MIT License 5 votes vote down vote up
@Test
public void cacheExpression() {
	Method method = ReflectionUtils.findMethod(getClass(), "toString");

	expressionEvaluator.getTestExpression("true", method, getClass());
	expressionEvaluator.getTestExpression("true", method, getClass());
	expressionEvaluator.getTestExpression("true", method, getClass());
	hasParsedExpression("true");
	assertEquals("Only one expression should be in cache", 1, expressionEvaluator.testCache.size());
}
 
Example 35
Project: spring-analysis-note   File: ApplicationListenerMethodAdapterTests.java    License: MIT License 5 votes vote down vote up
@Test
public void invokeListenerWithAnyGenericPayload() {
	Method method = ReflectionUtils.findMethod(
			SampleEvents.class, "handleGenericAnyPayload", EntityWrapper.class);
	EntityWrapper<String> payload = new EntityWrapper<>("test");
	invokeListener(method, new PayloadApplicationEvent<>(this, payload));
	verify(this.sampleEvents, times(1)).handleGenericAnyPayload(payload);
}
 
Example 36
Project: spring-analysis-note   File: ApplicationListenerMethodAdapterTests.java    License: MIT License 5 votes vote down vote up
@Test
public void invokeListenerRuntimeException() {
	Method method = ReflectionUtils.findMethod(
			SampleEvents.class, "generateRuntimeException", GenericTestEvent.class);
	GenericTestEvent<String> event = createGenericTestEvent("fail");

	assertThatIllegalStateException().isThrownBy(() ->
			invokeListener(method, event))
		.withMessageContaining("Test exception")
		.withNoCause();
}
 
Example 37
Project: spring-analysis-note   File: AbstractHandshakeHandler.java    License: MIT License 5 votes vote down vote up
private static RequestUpgradeStrategy initRequestUpgradeStrategy() {
	String className;
	if (tomcatWsPresent) {
		className = "org.springframework.web.socket.server.standard.TomcatRequestUpgradeStrategy";
	}
	else if (jettyWsPresent) {
		className = "org.springframework.web.socket.server.jetty.JettyRequestUpgradeStrategy";
	}
	else if (undertowWsPresent) {
		className = "org.springframework.web.socket.server.standard.UndertowRequestUpgradeStrategy";
	}
	else if (glassfishWsPresent) {
		className = "org.springframework.web.socket.server.standard.GlassFishRequestUpgradeStrategy";
	}
	else if (weblogicWsPresent) {
		className = "org.springframework.web.socket.server.standard.WebLogicRequestUpgradeStrategy";
	}
	else if (websphereWsPresent) {
		className = "org.springframework.web.socket.server.standard.WebSphereRequestUpgradeStrategy";
	}
	else {
		throw new IllegalStateException("No suitable default RequestUpgradeStrategy found");
	}

	try {
		Class<?> clazz = ClassUtils.forName(className, AbstractHandshakeHandler.class.getClassLoader());
		return (RequestUpgradeStrategy) ReflectionUtils.accessibleConstructor(clazz).newInstance();
	}
	catch (Throwable ex) {
		throw new IllegalStateException(
				"Failed to instantiate RequestUpgradeStrategy: " + className, ex);
	}
}
 
Example 38
Project: spring-cloud-alibaba   File: SentinelFeign.java    License: Apache License 2.0 5 votes vote down vote up
private Object getFieldValue(Object instance, String fieldName) {
	Field field = ReflectionUtils.findField(instance.getClass(), fieldName);
	field.setAccessible(true);
	try {
		return field.get(instance);
	}
	catch (IllegalAccessException e) {
		// ignore
	}
	return null;
}
 
Example 39
Project: spring-cloud-skipper   File: StateMachineTests.java    License: Apache License 2.0 5 votes vote down vote up
private static void setId(Class<?> clazz, Object instance, String fieldName, Object value) {
	try {
		Field field = ReflectionUtils.findField(clazz, fieldName);
		field.setAccessible(true);
		int modifiers = field.getModifiers();
		Field modifierField = field.getClass().getDeclaredField("modifiers");
		modifiers = modifiers & ~Modifier.FINAL;
		modifierField.setAccessible(true);
		modifierField.setInt(field, modifiers);
		ReflectionUtils.setField(field, instance, value);
	}
	catch (ReflectiveOperationException e) {
		throw new IllegalArgumentException(e);
	}
}
 
Example 40
Project: infobip-spring-data-querydsl   File: QuerydslJdbcRepositoryFactory.java    License: Apache License 2.0 5 votes vote down vote up
private RelationalPathBase<?> getRelationalPathBase(Class<?> queryClass) {
    String fieldName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, queryClass.getSimpleName().substring(1));
    Field field = ReflectionUtils.findField(queryClass, fieldName);

    if (field == null) {
        throw new IllegalArgumentException("Did not find a static field of the same type in " + queryClass);
    }

    return (RelationalPathBase<?>) ReflectionUtils.getField(field, null);
}