@Test public void canGetValue() throws Exception { TestObject testObject = new TestObject("text", 123); assertThat(reflectionUtils.getValue(integerField, testObject), equalTo((Object) 123)); assertThat(reflectionUtils.getValue(stringField, testObject), equalTo((Object) "text")); }
private void call(String operation, Map<String, String> args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { final String requestClassName = packageName + ".model." + operation + "Request"; final String operationMethodName = operation.substring(0, 1).toLowerCase() + operation.substring(1); Class<Object> requestClass = ReflectionUtils.loadClass(this.getClass(), requestClassName); Object requestObject = ReflectionUtils.newInstance(requestClass); if (args != null && !args.isEmpty()) { for (Map.Entry<String, String> entry : args.entrySet()) { String key = entry.getKey().substring(0, 1).toUpperCase() + entry.getKey().substring(1); Object value = convertTo( ReflectionUtils.getParameterTypes(requestObject, Arrays.asList(key)), entry.getValue()); ReflectionUtils.setByPath(requestObject, value, Arrays.asList(key)); } } Method method = ReflectionUtils.findMethod(client, operationMethodName, requestClass); result = method.invoke(client, requestObject); }
@SmallTest public void testIdTokenParam_password() throws IllegalArgumentException, ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchFieldException { Object obj = setIdTokenFields("objectid", "upnid", "email", "subj"); Calendar calendar = new GregorianCalendar(); int seconds = 1000; ReflectionUtils.setFieldValue(obj, "mPasswordExpiration", seconds); ReflectionUtils.setFieldValue( obj, "mPasswordChangeUrl", "https://github.com/MSOpenTech/azure-activedirectory-library"); UserInfo info = (UserInfo) ReflectionUtils.getInstance(ReflectionUtils.TEST_PACKAGE_NAME + ".UserInfo", obj); calendar.add(Calendar.SECOND, seconds); Date passwordExpiresOn = calendar.getTime(); assertEquals("same userid", "objectid", info.getUserId()); assertEquals("same name", "givenName", info.getGivenName()); assertEquals("same family name", "familyName", info.getFamilyName()); assertEquals("same idenity name", "provider", info.getIdentityProvider()); assertEquals("check displayable", "upnid", info.getDisplayableId()); assertEquals( "check expireson", passwordExpiresOn.getTime() / 1000, info.getPasswordExpiresOn().getTime() / 1000); assertEquals( "check uri", "https://github.com/MSOpenTech/azure-activedirectory-library", info.getPasswordChangeUrl().toString()); }
private static Object newInstance( final JBossServiceConfig serviceConfig, final List<ClassReflectionIndex> mBeanClassHierarchy, final ClassLoader deploymentClassLoader) throws DeploymentUnitProcessingException { // set TCCL so that the MBean instantiation happens in the deployment's classloader final ClassLoader oldTCCL = WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(deploymentClassLoader); try { final JBossServiceConstructorConfig constructorConfig = serviceConfig.getConstructorConfig(); final int paramCount = constructorConfig != null ? constructorConfig.getArguments().length : 0; final Class<?>[] types = new Class<?>[paramCount]; final Object[] params = new Object[paramCount]; if (constructorConfig != null) { final Argument[] arguments = constructorConfig.getArguments(); for (int i = 0; i < paramCount; i++) { final Argument argument = arguments[i]; types[i] = ReflectionUtils.getClass(argument.getType(), deploymentClassLoader); params[i] = newValue( ReflectionUtils.getClass(argument.getType(), deploymentClassLoader), argument.getValue()); } } final Constructor<?> constructor = mBeanClassHierarchy.get(0).getConstructor(types); final Object mBeanInstance = ReflectionUtils.newInstance(constructor, params); return mBeanInstance; } finally { // switch back the TCCL WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTCCL); } }
static AdvertisingInfo getAdvertisingInfo() { label96: for (; ; ) { try { Object localObject1 = Localytics.appContext; Object localObject2 = ReflectionUtils.tryInvokeStatic( "com.google.android.gms.ads.identifier.AdvertisingIdClient", "getAdvertisingIdInfo", new Class[] {Context.class}, new Object[] {localObject1}); if (localObject2 != null) { localObject1 = (String) ReflectionUtils.tryInvokeInstance(localObject2, "getId", null, null); boolean bool = ((Boolean) ReflectionUtils.tryInvokeInstance( localObject2, "isLimitAdTrackingEnabled", null, null)) .booleanValue(); if (!TextUtils.isEmpty((CharSequence) localObject1)) { break label96; } localObject1 = null; localObject1 = new AdvertisingInfo((String) localObject1, bool); return localObject1; } } catch (Exception localException) { Localytics.Log.w("Device doesn't have Google Play Services installed"); } return null; } }
StandardProcessorTestRunner(final Processor processor) { this.processor = processor; this.idGenerator = new AtomicLong(0L); this.sharedState = new SharedSessionState(processor, idGenerator); this.flowFileQueue = sharedState.getFlowFileQueue(); this.sessionFactory = new MockSessionFactory(sharedState, processor); this.processorStateManager = new MockStateManager(processor); this.context = new MockProcessContext(processor, processorStateManager); detectDeprecatedAnnotations(processor); final MockProcessorInitializationContext mockInitContext = new MockProcessorInitializationContext(processor, context); processor.initialize(mockInitContext); logger = mockInitContext.getLogger(); try { ReflectionUtils.invokeMethodsWithAnnotation(OnAdded.class, processor); } catch (final Exception e) { Assert.fail("Could not invoke methods annotated with @OnAdded annotation due to: " + e); } triggerSerially = null != processor.getClass().getAnnotation(TriggerSerially.class); ReflectionUtils.quietlyInvokeMethodsWithAnnotation(OnConfigurationRestored.class, processor); }
@SuppressWarnings("unchecked") private static <A extends Annotation> void findRepeatableAnnotations( Annotation[] candidates, Class<A> annotationType, Class<? extends Annotation> containerType, boolean inherited, Set<A> found, Set<Annotation> visited) { for (Annotation candidate : candidates) { if (!isInJavaLangAnnotationPackage(candidate) && visited.add(candidate)) { // Exact match? if (candidate.annotationType().equals(annotationType)) { found.add(annotationType.cast(candidate)); } // Container? else if (candidate.annotationType().equals(containerType)) { // Note: it's not a legitimate container annotation if it doesn't declare // a 'value' attribute that returns an array of the contained annotation type. // Thus we proceed without verifying this assumption. Method method = ReflectionUtils.getMethod(containerType, "value").get(); Annotation[] containedAnnotations = (Annotation[]) ReflectionUtils.invokeMethod(method, candidate); found.addAll((Collection<? extends A>) asList(containedAnnotations)); } // Otherwise search recursively through the meta-annotation hierarchy... else { findRepeatableAnnotations( candidate.annotationType(), annotationType, containerType, inherited, found, visited); } } } }
/** Load spigot and NMS classes */ private static void loadClasses() { if (packetTitle == null) { packetTitle = ReflectionUtils.getCraftClass("PacketPlayOutTitle"); packetActions = ReflectionUtils.getCraftClass("PacketPlayOutTitle$EnumTitleAction"); chatBaseComponent = ReflectionUtils.getCraftClass("IChatBaseComponent"); nmsChatSerializer = ReflectionUtils.getCraftClass("IChatBaseComponent$ChatSerializer"); } }
@Test public void hasEqualsMethod() throws Exception { // String does have "equals". assertThat(reflectionUtils.fieldTypeHasEqualsMethod(integerField.getType()), is(false)); // int itself doesn't have "equals". assertThat(reflectionUtils.fieldTypeHasEqualsMethod(stringField.getType()), is(true)); }
@SmallTest public void testIdTokenParam_upn() throws IllegalArgumentException, ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchFieldException { Object obj = setIdTokenFields("objectid", "upnid", "email", "subj"); UserInfo info = (UserInfo) ReflectionUtils.getInstance(ReflectionUtils.TEST_PACKAGE_NAME + ".UserInfo", obj); assertEquals("same userid", "objectid", info.getUserId()); assertEquals("same name", "givenName", info.getGivenName()); assertEquals("same family name", "familyName", info.getFamilyName()); assertEquals("same idenity name", "provider", info.getIdentityProvider()); assertEquals("check displayable", "upnid", info.getDisplayableId()); obj = setIdTokenFields("", "upnid", "email", "subj"); info = (UserInfo) ReflectionUtils.getInstance(ReflectionUtils.TEST_PACKAGE_NAME + ".UserInfo", obj); assertEquals("same userid", "subj", info.getUserId()); assertEquals("same name", "givenName", info.getGivenName()); assertEquals("same family name", "familyName", info.getFamilyName()); assertEquals("same idenity name", "provider", info.getIdentityProvider()); assertEquals("check displayable", "upnid", info.getDisplayableId()); obj = setIdTokenFields("", "upnid", "email", ""); info = (UserInfo) ReflectionUtils.getInstance(ReflectionUtils.TEST_PACKAGE_NAME + ".UserInfo", obj); assertNull("null userid", info.getUserId()); assertEquals("same name", "givenName", info.getGivenName()); assertEquals("same family name", "familyName", info.getFamilyName()); assertEquals("same idenity name", "provider", info.getIdentityProvider()); assertEquals("check displayable", "upnid", info.getDisplayableId()); obj = setIdTokenFields("", "", "email", ""); info = (UserInfo) ReflectionUtils.getInstance(ReflectionUtils.TEST_PACKAGE_NAME + ".UserInfo", obj); assertNull("null userid", info.getUserId()); assertEquals("same name", "givenName", info.getGivenName()); assertEquals("same family name", "familyName", info.getFamilyName()); assertEquals("same idenity name", "provider", info.getIdentityProvider()); assertEquals("check displayable", "email", info.getDisplayableId()); obj = setIdTokenFields("", "", "", ""); info = (UserInfo) ReflectionUtils.getInstance(ReflectionUtils.TEST_PACKAGE_NAME + ".UserInfo", obj); assertNull("null userid", info.getUserId()); assertNull("check displayable", info.getDisplayableId()); assertEquals("same name", "givenName", info.getGivenName()); assertEquals("same family name", "familyName", info.getFamilyName()); assertEquals("same idenity name", "provider", info.getIdentityProvider()); }
/** * Null out fields in this schema and its children as specified by parameters __exclude_fields and * __include_fields. <b>NOTE: modifies the scheme tree in place.</b> */ public static void filterFields(Object o, String includes, String excludes) { if (null == excludes || "".equals(excludes)) return; if (null != includes) // not yet implemented throw new H2OIllegalArgumentException("_include_fields", "filterFields", includes); String[] exclude_paths = excludes.split(","); for (String path : exclude_paths) { // for each path. . . int slash = path.indexOf("/"); if (-1 == slash || slash == path.length()) { // NOTE: handles trailing slash // we've hit the end: null the field, if it exists Field f = ReflectionUtils.findNamedField(o, path); if (null == f) throw new H2OIllegalArgumentException("_exclude_fields", "filterFields", path); try { f.set(o, null); } catch (IllegalAccessException e) { throw new H2OIllegalArgumentException("_exclude_fields", "filterFields", path); } } // hit the end of the path else { String first = path.substring(0, slash); String rest = path.substring(slash + 1); Field f = ReflectionUtils.findNamedField(o, first); if (null == f) throw new H2OIllegalArgumentException("_exclude_fields", "filterFields", path); if (f.getType().isArray() && Object.class.isAssignableFrom(f.getType().getComponentType())) { // recurse into the children with the "rest" of the path try { Object[] field_value = (Object[]) f.get(o); for (Object child : field_value) { filterFields(child, null, rest); } } catch (IllegalAccessException e) { throw new H2OIllegalArgumentException("_exclude_fields", "filterFields", path); } } else if (Object.class.isAssignableFrom(f.getType())) { // recurse into the child with the "rest" of the path try { Object field_value = f.get(o); filterFields(field_value, null, rest); } catch (IllegalAccessException e) { throw new H2OIllegalArgumentException("_exclude_fields", "filterFields", path); } } else { throw new H2OIllegalArgumentException("_exclude_fields", "filterFields", path); } } // need to recurse } // foreach exclude_paths }
@SuppressWarnings("unchecked") private void doTestCache() { for (int i = 0; i < toConstruct.length; i++) { Class cl = toConstruct[i]; Object x = ReflectionUtils.newInstance(cl, null); Object y = ReflectionUtils.newInstance(cl, null); assertEquals(cl, x.getClass()); assertEquals(cl, y.getClass()); } }
@Test public void testDeepDeclaredFieldMap() throws Exception { Calendar c = Calendar.getInstance(); Map<String, Field> fields = ReflectionUtils.getDeepDeclaredFieldMap(c.getClass()); assertTrue(fields.size() > 0); assertTrue(fields.containsKey("firstDayOfWeek")); assertFalse(fields.containsKey("blart")); Map<String, Field> test2 = ReflectionUtils.getDeepDeclaredFieldMap(Child.class); assertEquals(2, test2.size()); assertTrue(test2.containsKey("com.cedarsoftware.util.TestReflectionUtils$Parent.foo")); assertFalse(test2.containsKey("com.cedarsoftware.util.TestReflectionUtils$Child.foo")); }
@Test public void isCglibRenamedMethod() throws SecurityException, NoSuchMethodException { @SuppressWarnings("unused") class C { public void CGLIB$m1$123() {} public void CGLIB$m1$0() {} public void CGLIB$$0() {} public void CGLIB$m1$() {} public void CGLIB$m1() {} public void m1() {} public void m1$() {} public void m1$1() {} } assertTrue(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("CGLIB$m1$123"))); assertTrue(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("CGLIB$m1$0"))); assertFalse(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("CGLIB$$0"))); assertFalse(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("CGLIB$m1$"))); assertFalse(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("CGLIB$m1"))); assertFalse(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("m1"))); assertFalse(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("m1$"))); assertFalse(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("m1$1"))); }
@Test public void setField() { TestObjectSubclassWithNewField testBean = new TestObjectSubclassWithNewField(); Field field = ReflectionUtils.findField(TestObjectSubclassWithNewField.class, "name", String.class); ReflectionUtils.makeAccessible(field); ReflectionUtils.setField(field, testBean, "FooBar"); assertNotNull(testBean.getName()); assertEquals("FooBar", testBean.getName()); ReflectionUtils.setField(field, testBean, null); assertNull(testBean.getName()); }
@Override public void enableControllerService(final ControllerService service) { final ControllerServiceConfiguration configuration = context.getConfiguration(service.getIdentifier()); if (configuration == null) { throw new IllegalArgumentException("Controller Service " + service + " is not known"); } if (configuration.isEnabled()) { throw new IllegalStateException( "Cannot enable Controller Service " + service + " because it is not disabled"); } try { final ConfigurationContext configContext = new MockConfigurationContext(service, configuration.getProperties(), context); ReflectionUtils.invokeMethodsWithAnnotation(OnEnabled.class, service, configContext); } catch (final InvocationTargetException ite) { ite.getCause().printStackTrace(); Assert.fail("Failed to enable Controller Service " + service + " due to " + ite.getCause()); } catch (final Exception e) { e.printStackTrace(); Assert.fail("Failed to enable Controller Service " + service + " due to " + e); } configuration.setEnabled(true); }
private void createDeclaredViews( final Map<String, DesignDocument.View> views, final Class<?> klass) { eachAnnotation( klass, Views.class, new Predicate<Views>() { public boolean apply(Views input) { for (View v : input.value()) { addView(views, v, klass); } return true; } }); ReflectionUtils.eachAnnotation( klass, View.class, new Predicate<View>() { public boolean apply(View input) { addView(views, input, klass); return true; } }); }
public static Object convertStringToObject(String value, Class<?> toType) { try { return org.apache.commons.beanutils.ConvertUtils.convert(value, toType); } catch (Exception e) { throw ReflectionUtils.convertReflectionExceptionToUnchecked(e); } }
@Test public void testClassAnnotation() { Annotation a = ReflectionUtils.getClassAnnotation(Bar.class, ControllerClass.class); assertNotNull(a); assertTrue(a instanceof ControllerClass); a = ReflectionUtils.getClassAnnotation(Alpha.class, ControllerClass.class); assertNotNull(a); assertTrue(a instanceof ControllerClass); a = ReflectionUtils.getClassAnnotation(Bogus.class, ControllerClass.class); assertNull(a); a = ReflectionUtils.getClassAnnotation(CCC.class, ControllerClass.class); assertNull(a); }
@Test public void getUniqueDeclaredMethods_withCovariantReturnType() throws Exception { class Parent { @SuppressWarnings("unused") public Number m1() { return new Integer(42); } } class Leaf extends Parent { @Override public Integer m1() { return new Integer(42); } } int m1MethodCount = 0; Method[] methods = ReflectionUtils.getUniqueDeclaredMethods(Leaf.class); for (Method method : methods) { if (method.getName().equals("m1")) { m1MethodCount++; } } assertThat(m1MethodCount, is(1)); assertTrue(ObjectUtils.containsElement(methods, Leaf.class.getMethod("m1"))); assertFalse(ObjectUtils.containsElement(methods, Parent.class.getMethod("m1"))); }
@Override public void addView(View child, int left, int top) { if (child.getParent() instanceof ViewGroup) { ViewGroup parent = (ViewGroup) child.getParent(); LayoutTransition layoutTransition = null; if (parent.getLayoutTransition() != null) { layoutTransition = parent.getLayoutTransition(); parent.setLayoutTransition(null); } parent.removeView(child); if (layoutTransition != null) { parent.setLayoutTransition(layoutTransition); } if (child.getParent() != null) { // LayoutTransition will cause the child to delay removal - cancel it ViewGroupUtils.cancelLayoutTransition(parent); // fail-safe if view is still attached for any reason if (child.getParent() != null && FIELD_VIEW_PARENT != null) { ReflectionUtils.setFieldValue(child, FIELD_VIEW_PARENT, null); } } if (child.getParent() != null) { return; } } child.setTag(R.id.overlay_layout_params_backup, child.getLayoutParams()); addView(child, initParams(child, left, top)); invalidate(); }
protected static Object invokeVfsMethod(Method method, Object target, Object... args) throws IOException { try { return method.invoke(target, args); } catch (InvocationTargetException ex) { Throwable targetEx = ex.getTargetException(); if (targetEx instanceof IOException) { throw (IOException) targetEx; } ReflectionUtils.handleInvocationTargetException(ex); } catch (Exception ex) { ReflectionUtils.handleReflectionException(ex); } throw new IllegalStateException("Invalid code path reached"); }
@Test public void testCache() throws Exception { assertEquals(0, cacheSize()); doTestCache(); assertEquals(toConstruct.length, cacheSize()); ReflectionUtils.clearCache(); assertEquals(0, cacheSize()); }
@Test public void invokeMethod() throws Exception { String rob = "Rob Harrop"; TestObject bean = new TestObject(); bean.setName(rob); Method getName = TestObject.class.getMethod("getName", (Class[]) null); Method setName = TestObject.class.getMethod("setName", String.class); Object name = ReflectionUtils.invokeMethod(getName, bean); assertEquals("Incorrect name returned", rob, name); String juergen = "Juergen Hoeller"; ReflectionUtils.invokeMethod(setName, bean, juergen); assertEquals("Incorrect name set", juergen, bean.getName()); }
/** * Reset the title settings * * @param player Player */ public static void resetTitle(Player player) { try { // Send timings first Object handle = ReflectionUtils.getHandle(player); Object connection = ReflectionUtils.getField(handle.getClass(), "playerConnection").get(handle); Object[] actions = packetActions.getEnumConstants(); Method sendPacket = ReflectionUtils.getMethod(connection.getClass(), "sendPacket"); Object packet = packetTitle .getConstructor(packetActions, chatBaseComponent) .newInstance(actions[4], null); sendPacket.invoke(connection, packet); } catch (Exception e) { e.printStackTrace(); } }
@Then("^the response should contain a \"([^\"]*)\"$") public void the_response_should_contain_a(String memberName) throws Throwable { String[] path = memberName.split("[.]"); Object member = ReflectionUtils.getByPath(result, Arrays.asList(path)); assertNotNull(member); }
private void expandSupertypes(Multimap<String, String> mmap, String key, Class<?> type) { for (Class<?> supertype : ReflectionUtils.getSuperTypes(type)) { if (mmap.put(supertype.getName(), key)) { if (log != null) log.debug("expanded subtype {} -> {}", supertype.getName(), key); expandSupertypes(mmap, supertype.getName(), supertype); } } }
@Override public void shutdown() { try { ReflectionUtils.invokeMethodsWithAnnotation(OnShutdown.class, processor); } catch (final Exception e) { Assert.fail("Could not invoke methods annotated with @OnShutdown annotation due to: " + e); } }
private Object setIdTokenFields(String objId, String upn, String email, String subject) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchFieldException { Object obj = ReflectionUtils.getInstance(ReflectionUtils.TEST_PACKAGE_NAME + ".IdToken"); ReflectionUtils.setFieldValue(obj, "mObjectId", objId); ReflectionUtils.setFieldValue(obj, "mSubject", subject); ReflectionUtils.setFieldValue(obj, "mTenantId", "tenantid"); ReflectionUtils.setFieldValue(obj, "mUpn", upn); ReflectionUtils.setFieldValue(obj, "mGivenName", "givenName"); ReflectionUtils.setFieldValue(obj, "mFamilyName", "familyName"); ReflectionUtils.setFieldValue(obj, "mEmail", email); ReflectionUtils.setFieldValue(obj, "mIdentityProvider", "provider"); return obj; }
/** * @param mBeanName * @param mBeanInstance * @param mBeanClassHierarchy * @param target * @param componentInstantiator * @param duServiceName the deployment unit's service name */ MBeanServices( final String mBeanName, final Object mBeanInstance, final List<ClassReflectionIndex<?>> mBeanClassHierarchy, final ServiceTarget target, ServiceComponentInstantiator componentInstantiator, final ServiceName duServiceName) { if (mBeanClassHierarchy == null) { throw SarMessages.MESSAGES.nullVar("mBeanName"); } if (mBeanInstance == null) { throw SarMessages.MESSAGES.nullVar("mBeanInstance"); } if (target == null) { throw SarMessages.MESSAGES.nullVar("target"); } final Method createMethod = ReflectionUtils.getMethod(mBeanClassHierarchy, CREATE_METHOD_NAME, NO_ARGS, false); final Method destroyMethod = ReflectionUtils.getMethod(mBeanClassHierarchy, DESTROY_METHOD_NAME, NO_ARGS, false); createDestroyService = new CreateDestroyService( mBeanInstance, createMethod, destroyMethod, componentInstantiator, duServiceName); createDestroyServiceName = ServiceNameFactory.newCreateDestroy(mBeanName); createDestroyServiceBuilder = target.addService(createDestroyServiceName, createDestroyService); if (componentInstantiator != null) { // the service that starts the EE component needs to start first createDestroyServiceBuilder.addDependency( componentInstantiator.getComponentStartServiceName()); } final Method startMethod = ReflectionUtils.getMethod(mBeanClassHierarchy, START_METHOD_NAME, NO_ARGS, false); final Method stopMethod = ReflectionUtils.getMethod(mBeanClassHierarchy, STOP_METHOD_NAME, NO_ARGS, false); startStopService = new StartStopService(mBeanInstance, startMethod, stopMethod, duServiceName); startStopServiceName = ServiceNameFactory.newStartStop(mBeanName); startStopServiceBuilder = target.addService(startStopServiceName, startStopService); startStopServiceBuilder.addDependency(createDestroyServiceName); this.mBeanName = mBeanName; this.target = target; this.duServiceName = duServiceName; }