Java Code Examples for org.springframework.util.ReflectionUtils

The following are top voted examples for showing how to use org.springframework.util.ReflectionUtils. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: service-hive   File: RateLimitZuulFilter.java   View source code 9 votes vote down vote up
@Override
public Object run() {

    try {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletResponse response = ctx.getResponse();

        if (!rateLimiter.tryAcquire()) {
            HttpStatus httpStatus = HttpStatus.TOO_MANY_REQUESTS;

            response.setContentType(MediaType.TEXT_PLAIN_VALUE);
            response.setStatus(httpStatus.value());
            ctx.setResponseStatusCode(httpStatus.value());
            ctx.setSendZuulResponse(false);
        }
    } catch (Exception e) {
        ReflectionUtils.rethrowRuntimeException(e);
    }
    return null;
}
 
Example 2
Project: cloud-native-reference   File: ThrottlingPreFilter.java   View source code 7 votes vote down vote up
@Override
public Object run() {
  try {
    RequestContext currentContext = RequestContext.getCurrentContext();
    HttpServletResponse response = currentContext.getResponse();

    if (!rateLimiter.tryAcquire()) {

      response.setContentType(MediaType.TEXT_PLAIN_VALUE);
      response.setStatus(this.tooManyRequests.value());
      response.getWriter().append(this.tooManyRequests.getReasonPhrase());

      currentContext.setSendZuulResponse(false);

      throw new ZuulException(this.tooManyRequests.getReasonPhrase(),
          this.tooManyRequests.value(),
          this.tooManyRequests.getReasonPhrase());
    }
  } catch (Exception e) {
    ReflectionUtils.rethrowRuntimeException(e);
  }
  return null;
}
 
Example 3
Project: spring-cloud-sockets   File: DispatcherHandler.java   View source code 7 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
	String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.applicationContext, Object.class);
	for(String beanName : beanNames){
		Class<?> beanType = this.applicationContext.getType(beanName);
		if(beanType != null){
			final Class<?> userType = ClassUtils.getUserClass(beanType);
			ReflectionUtils.doWithMethods(userType, method -> {
				if(AnnotatedElementUtils.findMergedAnnotation(method, ReactiveSocket.class) != null) {
					ServiceMethodInfo info = new ServiceMethodInfo(method);
					logger.info("Registering remote endpoint at path {}, exchange {} for method {}", info.getMappingInfo().getPath(), info.getMappingInfo().getExchangeMode(), method);
					MethodHandler methodHandler = new MethodHandler(applicationContext.getBean(beanName), info);
					mappingHandlers.add(methodHandler);
				}
			});
		}
	}
	initDefaultConverters();
}
 
Example 4
Project: JuniperBotJ   File: SourceResolverServiceImpl.java   View source code 6 votes vote down vote up
private Object getAuthor(Event event) {
    if (event == null) {
        return null;
    }
    Class<? extends Event> clazz = event.getClass();
    Method method;
    if (!userAccessors.containsKey(clazz)) {
        method = ReflectionUtils.findMethod(clazz, "getUser");
        if (method == null) {
            method = ReflectionUtils.findMethod(clazz, "getAuthor");
        }
        userAccessors.put(clazz, method);
    } else {
        method = userAccessors.get(clazz);
    }
    if (method != null) {
        Object result = ReflectionUtils.invokeMethod(method, event);
        if (result instanceof User) {
            return result;
        }
    }
    return null;
}
 
Example 5
Project: lams   File: JBossModulesAdapter.java   View source code 6 votes vote down vote up
public JBossModulesAdapter(ClassLoader loader) {
	this.classLoader = loader;
	try {
		Field transformer = ReflectionUtils.findField(loader.getClass(), "transformer");
		transformer.setAccessible(true);
		this.delegatingTransformer = transformer.get(loader);
		if (!this.delegatingTransformer.getClass().getName().equals(DELEGATING_TRANSFORMER_CLASS_NAME)) {
			throw new IllegalStateException("Transformer not of the expected type DelegatingClassFileTransformer: " +
					this.delegatingTransformer.getClass().getName());
		}
		this.addTransformer = ReflectionUtils.findMethod(this.delegatingTransformer.getClass(),
				"addTransformer", ClassFileTransformer.class);
		this.addTransformer.setAccessible(true);
	}
	catch (Exception ex) {
		throw new IllegalStateException("Could not initialize JBoss 7 LoadTimeWeaver", ex);
	}
}
 
Example 6
Project: lams   File: AnnotationBeanUtils.java   View source code 6 votes vote down vote up
/**
 * Copy the properties of the supplied {@link Annotation} to the supplied target bean.
 * Any properties defined in {@code excludedProperties} will not be copied.
 * <p>A specified value resolver may resolve placeholders in property values, for example.
 * @param ann the annotation to copy from
 * @param bean the bean instance to copy to
 * @param valueResolver a resolve to post-process String property values (may be {@code null})
 * @param excludedProperties the names of excluded properties, if any
 * @see org.springframework.beans.BeanWrapper
 */
public static void copyPropertiesToBean(Annotation ann, Object bean, StringValueResolver valueResolver, String... excludedProperties) {
	Set<String> excluded =  new HashSet<String>(Arrays.asList(excludedProperties));
	Method[] annotationProperties = ann.annotationType().getDeclaredMethods();
	BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(bean);
	for (Method annotationProperty : annotationProperties) {
		String propertyName = annotationProperty.getName();
		if ((!excluded.contains(propertyName)) && bw.isWritableProperty(propertyName)) {
			Object value = ReflectionUtils.invokeMethod(annotationProperty, ann);
			if (valueResolver != null && value instanceof String) {
				value = valueResolver.resolveStringValue((String) value);
			}
			bw.setPropertyValue(propertyName, value);
		}
	}
}
 
Example 7
Project: incubator-servicecomb-java-chassis   File: SPIServiceUtils.java   View source code 6 votes vote down vote up
public static <T> List<T> getSortedService(Class<T> serviceType) {
  List<Entry<Integer, T>> serviceEntries = new ArrayList<>();
  ServiceLoader<T> serviceLoader = ServiceLoader.load(serviceType);
  serviceLoader.forEach(service -> {
    int serviceOrder = 0;
    Method getOrder = ReflectionUtils.findMethod(service.getClass(), "getOrder");
    if (getOrder != null) {
      serviceOrder = (int) ReflectionUtils.invokeMethod(getOrder, service);
    }

    Entry<Integer, T> entry = new SimpleEntry<>(serviceOrder, service);
    serviceEntries.add(entry);
  });

  return serviceEntries.stream()
      .sorted(Comparator.comparingInt(Entry::getKey))
      .map(Entry::getValue)
      .collect(Collectors.toList());
}
 
Example 8
Project: lams   File: ReflectiveMethodExecutor.java   View source code 6 votes vote down vote up
@Override
public TypedValue execute(EvaluationContext context, Object target, Object... arguments) throws AccessException {
	try {
		if (arguments != null) {
			ReflectionHelper.convertArguments(context.getTypeConverter(), arguments, this.method, this.varargsPosition);
		}
		if (this.method.isVarArgs()) {
			arguments = ReflectionHelper.setupArgumentsForVarargsInvocation(this.method.getParameterTypes(), arguments);
		}
		ReflectionUtils.makeAccessible(this.method);
		Object value = this.method.invoke(target, arguments);
		return new TypedValue(value, new TypeDescriptor(new MethodParameter(this.method, -1)).narrow(value));
	}
	catch (Exception ex) {
		throw new AccessException("Problem invoking method: " + this.method, ex);
	}
}
 
Example 9
Project: camunda-task-dispatcher   File: ExternalTaskManagerImpl.java   View source code 6 votes vote down vote up
@Override
public Object toCommand(LockedExternalTaskDto task) {
    ExternalTask<?> externalTask = getExternalTask(task.getTopicName());

    Object command = JavaUtils.callWithoutCheckedException(() -> externalTask.getClazz().newInstance());

    externalTask.getFields().forEach((varName, field) -> {
        if (task.getVariables() != null) {
            task.getVariables().computeIfPresent(varName, (name, value) -> {
                JavaUtils.setFieldWithoutCheckedException(field, command, value.getValue());
                return value;
            });
        }

        Field taskField = ReflectionUtils.findField(task.getClass(), varName);
        if (taskField != null) {
            ReflectionUtils.makeAccessible(taskField);
            JavaUtils.setFieldWithoutCheckedException(field, command, () -> taskField.get(task));
        }
    });

    return command;
}
 
Example 10
Project: spring-session-data-mongodb   File: ReactiveMongoWebSessionConfigurationTest.java   View source code 6 votes vote down vote up
@Test
public void overridingIntervalAndCollectionNameThroughAnnotationShouldWork() throws IllegalAccessException {

	this.context = new AnnotationConfigApplicationContext();
	this.context.register(OverrideMongoParametersConfig.class);
	this.context.refresh();

	ReactiveMongoOperationsSessionRepository repository = this.context.getBean(ReactiveMongoOperationsSessionRepository.class);

	Field inactiveField = ReflectionUtils.findField(ReactiveMongoOperationsSessionRepository.class, "maxInactiveIntervalInSeconds");
	ReflectionUtils.makeAccessible(inactiveField);
	Integer inactiveSeconds = (Integer) inactiveField.get(repository);

	Field collectionNameField = ReflectionUtils.findField(ReactiveMongoOperationsSessionRepository.class, "collectionName");
	ReflectionUtils.makeAccessible(collectionNameField);
	String collectionName = (String) collectionNameField.get(repository);

	assertThat(inactiveSeconds).isEqualTo(123);
	assertThat(collectionName).isEqualTo("test-case");
}
 
Example 11
Project: camunda-task-dispatcher   File: JmsExternalCommandListenerTest.java   View source code 6 votes vote down vote up
@Before
public void init() {
    listener = new JmsExternalCommandListener();

    JavaUtils.setFieldWithoutCheckedException(
            ReflectionUtils.findField(JmsExternalCommandListener.class, "taskService")
            , listener
            , taskService
    );
    JavaUtils.setFieldWithoutCheckedException(
            ReflectionUtils.findField(JmsExternalCommandListener.class, "taskManager")
            , listener
            , taskManager
    );
    JavaUtils.setFieldWithoutCheckedException(
            ReflectionUtils.findField(JmsExternalCommandListener.class, "taskMapper")
            , listener
            , taskMapper
    );
    JavaUtils.setFieldWithoutCheckedException(
            ReflectionUtils.findField(JmsExternalCommandListener.class, "jmsTemplate")
            , listener
            , jmsTemplate
    );
}
 
Example 12
Project: lams   File: RmiClientInterceptorUtils.java   View source code 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: springboot-shiro-cas-mybatis   File: CookieRetrievingCookieGenerator.java   View source code 6 votes vote down vote up
/**
 * Adds the cookie, taking into account {@link RememberMeCredential#REQUEST_PARAMETER_REMEMBER_ME}
 * in the request.
 *
 * @param request the request
 * @param response the response
 * @param cookieValue the cookie value
 */
public void addCookie(final HttpServletRequest request, final HttpServletResponse response, final String cookieValue) {
    final String theCookieValue = this.casCookieValueManager.buildCookieValue(cookieValue, request);

    if (!StringUtils.hasText(request.getParameter(RememberMeCredential.REQUEST_PARAMETER_REMEMBER_ME))) {
        super.addCookie(response, theCookieValue);
    } else {
        final Cookie cookie = createCookie(theCookieValue);
        cookie.setMaxAge(this.rememberMeMaxAge);
        if (isCookieSecure()) {
            cookie.setSecure(true);
        }
        if (isCookieHttpOnly()) {
            final Method setHttpOnlyMethod = ReflectionUtils.findMethod(Cookie.class, "setHttpOnly", boolean.class);
            if(setHttpOnlyMethod != null) {
                cookie.setHttpOnly(true);
            } else {
                logger.debug("Cookie cannot be marked as HttpOnly; container is not using servlet 3.0.");
            }
        }
        response.addCookie(cookie);
    }
}
 
Example 14
Project: otter-G   File: TestUtils.java   View source code 6 votes vote down vote up
/**
 * 调用方法,可以是一些私有方法
 * 
 * @param target
 * @param methodName
 * @param args
 * @return
 * @throws Exception
 */
public static Object invokeMethod(Object target, String methodName, Object... args) throws Exception {
    Method method = null;
    // 查找对应的方法
    if (args == null || args.length == 0) {
        method = ReflectionUtils.findMethod(target.getClass(), methodName);
    } else {
        Class[] argsClass = new Class[args.length];
        for (int i = 0; i < args.length; i++) {
            argsClass[i] = args[i].getClass();
        }
        method = ReflectionUtils.findMethod(target.getClass(), methodName, argsClass);
    }
    ReflectionUtils.makeAccessible(method);

    if (args == null || args.length == 0) {
        return ReflectionUtils.invokeMethod(method, target);
    } else {
        return ReflectionUtils.invokeMethod(method, target, args);
    }
}
 
Example 15
Project: JuniperBotJ   File: SourceResolverServiceImpl.java   View source code 6 votes vote down vote up
@Override
public Guild getGuild(Event event) {
    if (event == null) {
        return null;
    }
    Class<? extends Event> 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) {
        Object result = ReflectionUtils.invokeMethod(method, event);
        if (result instanceof Guild) {
            return (Guild) result;
        }
    }
    return null;
}
 
Example 16
Project: os   File: CheckingEntityListener.java   View source code 6 votes vote down vote up
@PostLoad
public void checking(Object target) {
	AnnotationCheckingMetadata metadata = AnnotationCheckingMetadata.getMetadata(target.getClass());
	if (metadata.isCheckable()) {
		StringBuilder sb = new StringBuilder();
		for (Field field : metadata.getCheckedFields()) {
			ReflectionUtils.makeAccessible(field);
			Object value = ReflectionUtils.getField(field, target);
			if (value instanceof Date) {
				throw new RuntimeException("不支持时间类型字段解密!");
			}
			sb.append(value).append(" - ");
		}
		sb.append(MD5_KEY);
		LOGGER.debug("验证数据:" + sb);
		String hex = MD5Utils.encode(sb.toString());
		Field checksumField = metadata.getCheckableField();
		ReflectionUtils.makeAccessible(checksumField);
		String checksum = (String) ReflectionUtils.getField(checksumField, target);
		if (!checksum.equals(hex)) {
			//throw new RuntimeException("数据验证失败!");
		}
	}
}
 
Example 17
Project: lams   File: ConstructorResolver.java   View source code 6 votes vote down vote up
/**
 * Retrieve all candidate methods for the given class, considering
 * the {@link RootBeanDefinition#isNonPublicAccessAllowed()} flag.
 * Called as the starting point for factory method determination.
 */
private Method[] getCandidateMethods(final Class<?> factoryClass, final RootBeanDefinition mbd) {
	if (System.getSecurityManager() != null) {
		return AccessController.doPrivileged(new PrivilegedAction<Method[]>() {
			@Override
			public Method[] run() {
				return (mbd.isNonPublicAccessAllowed() ?
						ReflectionUtils.getAllDeclaredMethods(factoryClass) : factoryClass.getMethods());
			}
		});
	}
	else {
		return (mbd.isNonPublicAccessAllowed() ?
				ReflectionUtils.getAllDeclaredMethods(factoryClass) : factoryClass.getMethods());
	}
}
 
Example 18
Project: spring-data-documentdb   File: DocumentDbEntityInformation.java   View source code 6 votes vote down vote up
public DocumentDbEntityInformation(Class<T> domainClass) {
    super(domainClass);

    this.id = getIdField(domainClass);
    if (this.id != null) {
        ReflectionUtils.makeAccessible(this.id);
    }

    this.collectionName = getCollectionName(domainClass);
    this.partitionKeyField = getPartitionKeyField(domainClass);
    if (this.partitionKeyField != null) {
        ReflectionUtils.makeAccessible(this.partitionKeyField);
    }

    this.requestUnit = getRequestUnit(domainClass);
}
 
Example 19
Project: otter-G   File: TestUtils.java   View source code 6 votes vote down vote up
/**
 * 调用方法,可以是一些私有方法
 * 
 * @param target
 * @param methodName
 * @param args
 * @return
 * @throws Exception
 */
public static Object invokeMethod(Object target, String methodName, Object... args) throws Exception {
    Method method = null;
    // 查找对应的方法
    if (args == null || args.length == 0) {
        method = ReflectionUtils.findMethod(target.getClass(), methodName);
    } else {
        Class[] argsClass = new Class[args.length];
        for (int i = 0; i < args.length; i++) {
            argsClass[i] = args[i].getClass();
        }
        method = ReflectionUtils.findMethod(target.getClass(), methodName, argsClass);
    }
    ReflectionUtils.makeAccessible(method);

    if (args == null || args.length == 0) {
        return ReflectionUtils.invokeMethod(method, target);
    } else {
        return ReflectionUtils.invokeMethod(method, target, args);
    }
}
 
Example 20
Project: bootstrap   File: CsvForJpa.java   View source code 6 votes vote down vote up
/**
 * Return JPA managed properties.
 * 
 * @param <T>
 *            Bean type.
 * @param beanType
 *            the bean type.
 * @return the headers built from given type.
 */
public <T> String[] getJpaHeaders(final Class<T> beanType) {
	// Build descriptor list respecting the declaration order
	final OrderedFieldCallback fieldCallBack = new OrderedFieldCallback();
	ReflectionUtils.doWithFields(beanType, fieldCallBack);
	final List<String> orderedDescriptors = fieldCallBack.descriptorsOrdered;

	// Now filter the properties
	final List<String> descriptorsFiltered = new ArrayList<>();
	final ManagedType<T> managedType = transactionManager.getEntityManagerFactory().getMetamodel().managedType(beanType);
	for (final String propertyDescriptor : orderedDescriptors) {
		for (final Attribute<?, ?> attribute : managedType.getAttributes()) {
			// Match only basic attributes
			if (attribute instanceof SingularAttribute<?, ?> && propertyDescriptor.equals(attribute.getName())) {
				descriptorsFiltered.add(attribute.getName());
				break;
			}
		}
	}

	// Initialize the CSV reader
	return descriptorsFiltered.toArray(new String[descriptorsFiltered.size()]);
}
 
Example 21
Project: tasfe-framework   File: EnumFieldReflectUtil.java   View source code 6 votes vote down vote up
/**
 * 设置枚举类型的字段值
 *
 * @param target  the target object from which to get the field
 * @param field   the field to set
 * @param ordinal enum.ordinal
 * @throws Exception IllegalArgumentException, IllegalAccess
 */
@SuppressWarnings("rawtypes")
public static void setFieldEnumValueByOrdinal(Object target, Field field, int ordinal) throws Exception {
    if (field.getType().isEnum()) {
        if (!field.isAccessible()) {
            ReflectionUtils.makeAccessible(field);
        }
        Enum[] enumObjs = (Enum[]) (field.getType()).getEnumConstants();
        for (Enum enumObj : enumObjs) {
            if (enumObj.ordinal() == ordinal) {
                field.set(target, enumObj);
            }
        }
    } else {
        throw new ReflectionException(target.getClass().getName() + "." + field.getName()
                + ":field type is not Enum, can not convertToEnum");
    }
}
 
Example 22
Project: Cloud-Foundry-For-Developers   File: HomeController.java   View source code 6 votes vote down vote up
private String toString(DataSource dataSource) {
    if (dataSource == null) {
        return "<none>";
    } else {
        try {
            Field urlField = ReflectionUtils.findField(dataSource.getClass(), "url");
            ReflectionUtils.makeAccessible(urlField);
            return stripCredentials((String) urlField.get(dataSource));
        } catch (Exception fe) {
            try {
                Method urlMethod = ReflectionUtils.findMethod(dataSource.getClass(), "getUrl");
                ReflectionUtils.makeAccessible(urlMethod);
                return stripCredentials((String) urlMethod.invoke(dataSource, (Object[])null));
            } catch (Exception me){
                return "<unknown> " + dataSource.getClass();
            }
        }
    }
}
 
Example 23
Project: Cloud-Foundry-For-Developers   File: HomeController.java   View source code 6 votes vote down vote up
private String toString(DataSource dataSource) {
    if (dataSource == null) {
        return "<none>";
    } else {
        try {
            Field urlField = ReflectionUtils.findField(dataSource.getClass(), "url");
            ReflectionUtils.makeAccessible(urlField);
            return stripCredentials((String) urlField.get(dataSource));
        } catch (Exception fe) {
            try {
                Method urlMethod = ReflectionUtils.findMethod(dataSource.getClass(), "getUrl");
                ReflectionUtils.makeAccessible(urlMethod);
                return stripCredentials((String) urlMethod.invoke(dataSource, (Object[])null));
            } catch (Exception me){
                return "<unknown> " + dataSource.getClass();
            }
        }
    }
}
 
Example 24
Project: gemini.blueprint   File: AbstractOsgiTests.java   View source code 6 votes vote down vote up
/**
 * Determines through reflection the methods used for invoking the TestRunnerService.
 *
 * @throws Exception
 */
private void initializeServiceRunnerInvocationMethods() throws Exception {
    // get JUnit test service reference
    // this is a loose reference - update it if the JUnitTestActivator class is changed.

    BundleContext ctx = getRuntimeBundleContext();

    ServiceReference reference = ctx.getServiceReference(ACTIVATOR_REFERENCE);
    Assert.notNull(reference, "no OSGi service reference found at " + ACTIVATOR_REFERENCE);

    service = ctx.getService(reference);
    Assert.notNull(service, "no service found for reference: " + reference);

    serviceTrigger = service.getClass().getDeclaredMethod("executeTest", new Class[0]);
    ReflectionUtils.makeAccessible(serviceTrigger);
    Assert.notNull(serviceTrigger, "no executeTest() method found on: " + service.getClass());
}
 
Example 25
Project: gemini.blueprint   File: ServiceReferenceInjectionBeanPostProcessor.java   View source code 6 votes vote down vote up
private void injectServicesViaAnnotatedSetterMethods(final Object bean, final String beanName) {
	ReflectionUtils.doWithMethods(bean.getClass(), new ReflectionUtils.MethodCallback() {

		public void doWith(Method method) {
			ServiceReference s = AnnotationUtils.getAnnotation(method, ServiceReference.class);
			if (s != null && method.getParameterTypes().length == 1) {
				try {
					if (logger.isDebugEnabled())
						logger.debug("Processing annotation [" + s + "] for [" + bean.getClass().getName() + "."
								+ method.getName() + "()] on bean [" + beanName + "]");
					method.invoke(bean, getServiceImporter(s, method, beanName).getObject());
				}
				catch (Exception e) {
					throw new IllegalArgumentException("Error processing service annotation", e);
				}
			}
		}
	});
}
 
Example 26
Project: spring-cloud-skipper   File: StateMachineTests.java   View source code 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 27
Project: FastBootWeixin   File: WxMenuAnnotationProcessor.java   View source code 5 votes vote down vote up
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    Class<?> targetClass = AopUtils.getTargetClass(bean);
    ReflectionUtils.doWithMethods(targetClass, method -> {
        WxButton wxButton = AnnotationUtils.getAnnotation(method, WxButton.class);
        if (wxButton != null) {
            wxMenuManager.add(wxButton);
        }
    });
    return bean;
}
 
Example 28
Project: incubator-servicecomb-java-chassis   File: Utils.java   View source code 5 votes vote down vote up
public static Object getFieldValue(Object instance, String fieldName) {
  try {
    return ReflectionUtils.findField(instance.getClass(), fieldName).get(instance);
  } catch (Exception e) {
    throw new Error(e);
  }
}
 
Example 29
Project: incubator-servicecomb-java-chassis   File: MockUtil.java   View source code 5 votes vote down vote up
public void mockReflectionUtils() {

    new MockUp<ReflectionUtils>() {
      @Mock
      Object getField(Field field, Object target) {
        Response response = Response.ok(200);
        return new CseClientHttpResponse(response);
      }
    };
  }
 
Example 30
Project: lams   File: AdaptableJobFactory.java   View source code 5 votes vote down vote up
/**
 * Create an instance of the specified job class.
 * <p>Can be overridden to post-process the job instance.
 * @param bundle the TriggerFiredBundle from which the JobDetail
 * and other info relating to the trigger firing can be obtained
 * @return the job instance
 * @throws Exception if job instantiation failed
 */
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
	// Reflectively adapting to differences between Quartz 1.x and Quartz 2.0...
	Method getJobDetail = bundle.getClass().getMethod("getJobDetail");
	Object jobDetail = ReflectionUtils.invokeMethod(getJobDetail, bundle);
	Method getJobClass = jobDetail.getClass().getMethod("getJobClass");
	Class<?> jobClass = (Class<?>) ReflectionUtils.invokeMethod(getJobClass, jobDetail);
	return jobClass.newInstance();
}
 
Example 31
Project: lams   File: JndiRmiClientInterceptor.java   View source code 5 votes vote down vote up
/**
 * Convert the given CORBA SystemException that happened during remote access
 * to Spring's RemoteAccessException if the method signature does not declare
 * RemoteException. Else, return the SystemException wrapped in a RemoteException.
 * @param method the invoked method
 * @param ex the RemoteException that happened
 * @return the exception to be thrown to the caller
 */
private Exception convertCorbaAccessException(SystemException ex, Method method) {
	if (ReflectionUtils.declaresException(method, RemoteException.class)) {
		// A traditional RMI service: wrap CORBA exceptions in standard RemoteExceptions.
		return new RemoteException("Failed to access CORBA service [" + getJndiName() + "]", ex);
	}
	else {
		if (isConnectFailure(ex)) {
			return new RemoteConnectFailureException("Could not connect to CORBA service [" + getJndiName() + "]", ex);
		}
		else {
			return new RemoteAccessException("Could not access CORBA service [" + getJndiName() + "]", ex);
		}
	}
}
 
Example 32
Project: lams   File: JBossNativeJdbcExtractor.java   View source code 5 votes vote down vote up
/**
 * Retrieve the Connection via JBoss' {@code getUnderlyingResultSet} method.
 */
@Override
public ResultSet getNativeResultSet(ResultSet rs) throws SQLException {
	if (this.wrappedResultSetClass.isAssignableFrom(rs.getClass())) {
		return (ResultSet) ReflectionUtils.invokeJdbcMethod(this.getUnderlyingResultSetMethod, rs);
	}
	return rs;
}
 
Example 33
Project: camunda-task-dispatcher   File: ExternalTaskManagerImplTest.java   View source code 5 votes vote down vote up
@Before
public void init() {
    manager = new ExternalTaskManagerImpl();

    JavaUtils.setFieldWithoutCheckedException(
            ReflectionUtils.findField(ExternalTaskManagerImpl.class, "packages")
            , manager
            , Arrays.asList(Command.class.getPackage().getName())
    );
}
 
Example 34
Project: camunda-task-dispatcher   File: ExternalTaskManagerImplTest.java   View source code 5 votes vote down vote up
@Test
public void testToCommand() {
    manager.init();

    LockedExternalTaskDto task = EnhancedRandom.random(LockedExternalTaskDto.class);
    JavaUtils.setFieldWithoutCheckedException(
            ReflectionUtils.findField(LockedExternalTaskDto.class, "topicName")
            , task
            , Command.TASK_NAME
    );
    String stringVar = "value";
    String otherVar = "other value";

    task.getVariables().put("stringVar", VariableValueDto.fromTypedValue(new PrimitiveTypeValueImpl.StringValueImpl(stringVar)));
    task.getVariables().put("otherVar", VariableValueDto.fromTypedValue(new PrimitiveTypeValueImpl.StringValueImpl(otherVar)));

    Object object = manager.toCommand(task);
    Assert.assertNotNull(object);
    Assert.assertTrue(object instanceof Command);

    Command command = (Command) object;
    Assert.assertEquals(stringVar, command.getStringVar());
    Assert.assertEquals(otherVar, command.getAnotherStringVar());

    ReflectionUtils.doWithFields(LockedExternalTaskDto.class, field -> {
        if (field.getName().equals("variables")) {
            return;
        }

        Field commandField = ReflectionUtils.findField(Command.class, field.getName());
        Assert.assertNotNull("No field with name: " + field.getName(), commandField);
        Assert.assertEquals(
                JavaUtils.getFieldWithoutCheckedException(field, task)
                , JavaUtils.getFieldWithoutCheckedException(commandField, command)
        );
    });
}
 
Example 35
Project: picocli-spring-boot-starter   File: PicocliAutoConfiguration.java   View source code 5 votes vote down vote up
private Object getMainCommand(Collection<Object> candidates) {
    Object mainCommand = null;
    for (Object candidate : candidates) {
        Class<?> clazz = AopUtils.getTargetClass(candidate);
        Method method = ReflectionUtils.findMethod(Command.class, "name");
        if (clazz.isAnnotationPresent(Command.class)
                && method != null
                && clazz.getAnnotation(Command.class).name().equals(method.getDefaultValue())) {
            mainCommand = candidate;
            break;
        }
    }
    if (mainCommand == null) {
        mainCommand = new PicocliCommand() {};
    }
    return mainCommand;
}
 
Example 36
Project: camunda-task-dispatcher   File: JsonTaskMapperTest.java   View source code 5 votes vote down vote up
@Before
public void init() throws IOException {
    Mockito.when(objectMapper.writeValueAsString(Mockito.any())).thenReturn(JSON);
    Mockito.when(objectMapper.readValue(Mockito.anyString(), Mockito.<Class<SimpleCommand>>any())).thenReturn(COMMAND);

    mapper = new JsonTaskMapper();

    JavaUtils.setFieldWithoutCheckedException(
            ReflectionUtils.findField(JsonTaskMapper.class, "objectMapper")
            , mapper
            , objectMapper
    );
}
 
Example 37
Project: gemini.blueprint   File: LocalBundleContextAdviceTest.java   View source code 5 votes vote down vote up
protected void setUp() throws Exception {
	Method m = ReflectionUtils.findMethod(Object.class, "hashCode");
	context = new MockBundleContext();
	interceptor = new LocalBundleContextAdvice(context);
	
	invocation = new MockMethodInvocation(m) {
		public Object proceed() throws Throwable {
			assertSame("bundle context not set", context, LocalBundleContext.getInvokerBundleContext());
			return null;
		}
	};

}
 
Example 38
Project: lams   File: WebSphereDataSourceAdapter.java   View source code 5 votes vote down vote up
/**
 * Builds a WebSphere JDBCConnectionSpec object for the current settings
 * and calls {@code WSDataSource.getConnection(JDBCConnectionSpec)}.
 * @see #createConnectionSpec
 * @see com.ibm.websphere.rsadapter.WSDataSource#getConnection(com.ibm.websphere.rsadapter.JDBCConnectionSpec)
 */
@Override
protected Connection doGetConnection(String username, String password) throws SQLException {
	// Create JDBCConnectionSpec using current isolation level value and read-only flag.
	Object connSpec = createConnectionSpec(
			getCurrentIsolationLevel(), getCurrentReadOnlyFlag(), username, password);
	if (logger.isDebugEnabled()) {
		logger.debug("Obtaining JDBC Connection from WebSphere DataSource [" +
				getTargetDataSource() + "], using ConnectionSpec [" + connSpec + "]");
	}
	// Create Connection through invoking WSDataSource.getConnection(JDBCConnectionSpec)
	return (Connection) ReflectionUtils.invokeJdbcMethod(
			this.wsDataSourceGetConnectionMethod, getTargetDataSource(), connSpec);
}
 
Example 39
Project: springboot-shiro-cas-mybatis   File: CookieRetrievingCookieGenerator.java   View source code 5 votes vote down vote up
/**
 * Instantiates a new Cookie retrieving cookie generator.
 * @param casCookieValueManager the cookie manager
 */
public CookieRetrievingCookieGenerator(final CookieValueManager casCookieValueManager) {
    super();
    final Method setHttpOnlyMethod = ReflectionUtils.findMethod(Cookie.class, "setHttpOnly", boolean.class);
    if(setHttpOnlyMethod != null) {
        super.setCookieHttpOnly(true);
    } else {
        logger.debug("Cookie cannot be marked as HttpOnly; container is not using servlet 3.0.");
    }
    this.casCookieValueManager = casCookieValueManager;
}
 
Example 40
Project: lams   File: MBeanClientInterceptor.java   View source code 5 votes vote down vote up
private Object convertDataArrayToTargetArray(Object[] array, Class<?> targetClass) throws NoSuchMethodException {
	Class<?> targetType = targetClass.getComponentType();
	Method fromMethod = targetType.getMethod("from", array.getClass().getComponentType());
	Object resultArray = Array.newInstance(targetType, array.length);
	for (int i = 0; i < array.length; i++) {
		Array.set(resultArray, i, ReflectionUtils.invokeMethod(fromMethod, null, array[i]));
	}
	return resultArray;
}