Here are the examples of the java api class java.lang.reflect.Field taken from open source projects.
1. KettleEnvironmentTest#resetKettleEnvironmentInitializationFlag()
View licenseprivate void resetKettleEnvironmentInitializationFlag() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, InstantiationException { Field f = KettleEnvironment.class.getDeclaredField("initialized"); f.setAccessible(true); f.set(null, new AtomicReference<SettableFuture<Boolean>>(null)); Constructor<KettleVFS> constructor; constructor = KettleVFS.class.getDeclaredConstructor(); constructor.setAccessible(true); KettleVFS KVFS = constructor.newInstance(); f = KVFS.getClass().getDeclaredField("kettleVFS"); f.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(f, f.getModifiers() & ~Modifier.FINAL | Modifier.VOLATILE); f.set(null, KVFS); f = KVFS.getClass().getDeclaredField("defaultVariableSpace"); f.setAccessible(true); modifiersField.setInt(f, f.getModifiers() & ~Modifier.FINAL); Variables var = new Variables(); var.initializeVariablesFrom(null); f.set(null, var); }
2. AbstractTestBase#changeValueOfMaximumAllowedXMLStructureDepth()
View licensepublic static int changeValueOfMaximumAllowedXMLStructureDepth(Integer value) throws NoSuchFieldException, IllegalAccessException { Field xmlEventReaderInputProcessorField = XMLEventReaderInputProcessor.class.getDeclaredField("maximumAllowedXMLStructureDepth"); xmlEventReaderInputProcessorField.setAccessible(true); Field abstractDecryptInputProcessorField = AbstractDecryptInputProcessor.class.getDeclaredField("maximumAllowedXMLStructureDepth"); abstractDecryptInputProcessorField.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(xmlEventReaderInputProcessorField, xmlEventReaderInputProcessorField.getModifiers() & ~Modifier.FINAL); modifiersField.setInt(abstractDecryptInputProcessorField, abstractDecryptInputProcessorField.getModifiers() & ~Modifier.FINAL); Integer oldval = (Integer) xmlEventReaderInputProcessorField.get(null); xmlEventReaderInputProcessorField.set(null, value); abstractDecryptInputProcessorField.set(null, value); return oldval; }
3. AbstractTestBase#changeValueOfMaximumAllowedXMLStructureDepth()
View licensepublic static int changeValueOfMaximumAllowedXMLStructureDepth(Integer value) throws NoSuchFieldException, IllegalAccessException { Field xmlEventReaderInputProcessorField = XMLEventReaderInputProcessor.class.getDeclaredField("maximumAllowedXMLStructureDepth"); xmlEventReaderInputProcessorField.setAccessible(true); Field abstractDecryptInputProcessorField = AbstractDecryptInputProcessor.class.getDeclaredField("maximumAllowedXMLStructureDepth"); abstractDecryptInputProcessorField.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(xmlEventReaderInputProcessorField, xmlEventReaderInputProcessorField.getModifiers() & ~Modifier.FINAL); modifiersField.setInt(abstractDecryptInputProcessorField, abstractDecryptInputProcessorField.getModifiers() & ~Modifier.FINAL); Integer oldval = (Integer) xmlEventReaderInputProcessorField.get(null); xmlEventReaderInputProcessorField.set(null, value); abstractDecryptInputProcessorField.set(null, value); return oldval; }
4. ApiLevelTestSuite#assumeApiLevel()
View licenseprivate void assumeApiLevel(int apiLevel) throws Exception { // Adjust the value of Build.VERSION.SDK_INT statically using reflection Field sdkIntField = Build.VERSION.class.getDeclaredField("SDK_INT"); sdkIntField.setAccessible(true); // Temporarily remove the SDK_INT's "final" modifier Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(sdkIntField, sdkIntField.getModifiers() & ~Modifier.FINAL); // Update the SDK_INT value, re-finalize the field, and lock it again sdkIntField.set(null, apiLevel); modifiersField.setInt(sdkIntField, sdkIntField.getModifiers() | Modifier.FINAL); sdkIntField.setAccessible(false); }
5. EasyFingerprintTest#assumeApiLevel()
View licenseprivate void assumeApiLevel(int apiLevel) throws Exception { // Adjust the value of Build.VERSION.SDK_INT statically using reflection Field sdkIntField = Build.VERSION.class.getDeclaredField("SDK_INT"); sdkIntField.setAccessible(true); // Temporarily remove the SDK_INT's "final" modifier Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(sdkIntField, sdkIntField.getModifiers() & ~Modifier.FINAL); // Update the SDK_INT value, re-finalize the field, and lock it again sdkIntField.set(null, apiLevel); modifiersField.setInt(sdkIntField, sdkIntField.getModifiers() | Modifier.FINAL); sdkIntField.setAccessible(false); }
6. FieldTests#testDoublePrimitiveLegalUse()
View license///////////////////////////////////////////////// ///////////////////Doubles/////////////////////// ///////////////////////////////////////////////// @Test public void testDoublePrimitiveLegalUse() throws Exception { assertNotNull(primitives); Field f = PRIMITIVE_CLASS.getField("d"); assertEquals(0., f.getDouble(primitives)); assertEquals(0., ((Double) f.get(primitives)).doubleValue()); f.set(primitives, (double) 1); assertEquals(1., f.getDouble(primitives)); assertEquals(1., ((Double) f.get(primitives)).doubleValue()); f.set(primitives, 'a'); f.set(primitives, (byte) 1); f.set(primitives, (int) 1); f.set(primitives, (long) 1); f.set(primitives, (float) 1); }
7. AbstractLoadBundleTest#setupStream()
View licenseprivate PrintStream setupStream(final Bundle api, final PrintStream newStream) throws ReflectiveOperationException { // use reflection to access the classes internals and in the context of the api bundle final Class<?> statusLoggerClass = api.loadClass("org.apache.logging.log4j.status.StatusLogger"); final Field statusLoggerField = statusLoggerClass.getDeclaredField("STATUS_LOGGER"); statusLoggerField.setAccessible(true); final Object statusLoggerFieldValue = statusLoggerField.get(null); final Field loggerField = statusLoggerClass.getDeclaredField("logger"); loggerField.setAccessible(true); final Object loggerFieldValue = loggerField.get(statusLoggerFieldValue); final Class<?> simpleLoggerClass = api.loadClass("org.apache.logging.log4j.simple.SimpleLogger"); final Field streamField = simpleLoggerClass.getDeclaredField("stream"); streamField.setAccessible(true); final PrintStream oldStream = (PrintStream) streamField.get(loggerFieldValue); streamField.set(loggerFieldValue, newStream); return oldStream; }
8. CleanWorkingDirectoryActionTest#setUp()
View license@Before public void setUp() throws NoSuchFieldException, IllegalAccessException { // Create mocks mockWorkingDirectoryService = mock(WorkingDirectoryService.class); mockProjectDao = mock(ProjectDao.class); fsManager = new DefaultFileSystemManager(); action = new CleanWorkingDirectoryAction(); // Get the private fields and make them accessible Field wdsField = action.getClass().getDeclaredField("workingDirectoryService"); Field pdField = action.getClass().getDeclaredField("projectDao"); Field fsMgrField = action.getClass().getDeclaredField("fsManager"); for (Field f : new Field[] { wdsField, pdField }) { f.setAccessible(true); } // Inject the mocks as dependencies wdsField.set(action, mockWorkingDirectoryService); pdField.set(action, mockProjectDao); fsMgrField.set(action, fsManager); }
9. InternalLoggerTest#prepare()
View license@Before public void prepare() throws NoSuchFieldException, IllegalAccessException { Field field = InternalLogger.class.getDeclaredField("initialized"); field.setAccessible(true); field.set(InternalLogger.INSTANCE, false); field = InternalLogger.class.getDeclaredField("loggingLevel"); field.setAccessible(true); field.set(InternalLogger.INSTANCE, InternalLogger.LoggingLevel.OFF); field = InternalLogger.class.getDeclaredField("loggerOutput"); field.setAccessible(true); field.set(InternalLogger.INSTANCE, null); }
10. WhiteboardHandlerTest#setUp()
View license@Before public void setUp() throws Exception { context = MockOsgi.newBundleContext(); handler = new WhiteboardHandler(); //Getting private field through injection Field schedulerField = WhiteboardHandler.class.getDeclaredField("scheduler"); schedulerField.setAccessible(true); //Creating quartzscheduler for private field and activating it quartzScheduler = ActivatedQuartzSchedulerFactory.create(context, "testName"); //Injecting quartzScheduler to WhiteboardHandler schedulerField.set(handler, quartzScheduler); handler.activate(context); Field trackerField = WhiteboardHandler.class.getDeclaredField("serviceTracker"); trackerField.setAccessible(true); ServiceTracker serviceTracker = (ServiceTracker) trackerField.get(handler); Field customizerField = ServiceTracker.class.getDeclaredField("customizer"); customizerField.setAccessible(true); customizer = (ServiceTrackerCustomizer) customizerField.get(serviceTracker); }
11. ResourceResolverWithVanityBloomFilterTest#setMaxCachedVanityPathEntries()
View licenseprivate void setMaxCachedVanityPathEntries(long maxCachedVanityPathEntries) throws Exception { //FIXME: enabling bloom filter usage using reflection for now // we need to have a new mechanism to test different then default OSGi configurations Field commonFactory = resourceResolverFactory.getClass().getDeclaredField("commonFactory"); commonFactory.setAccessible(true); Object commonResourceResolverFactoryImpl = commonFactory.get(resourceResolverFactory); Field mapEntries = commonResourceResolverFactoryImpl.getClass().getDeclaredField("mapEntries"); mapEntries.setAccessible(true); Object mapEntriesObject = mapEntries.get(commonResourceResolverFactoryImpl); Field maxCachedVanityPathEntriesField = mapEntriesObject.getClass().getDeclaredField("maxCachedVanityPathEntries"); maxCachedVanityPathEntriesField.setAccessible(true); maxCachedVanityPathEntriesField.setLong(mapEntriesObject, maxCachedVanityPathEntries); }
12. DatabaseTest#testDatabaseRemovesUnbalancedBlocksOnStartup()
View license@Test public void testDatabaseRemovesUnbalancedBlocksOnStartup() throws Exception { Database db = (Database) store; db.accept(Write.add(TestData.getString(), TestData.getTObject(), TestData.getLong())); db.triggerSync(); db.stop(); FileSystem.deleteDirectory(current + File.separator + "csb"); FileSystem.mkdirs(current + File.separator + "csb"); // simulate server restart db = new Database(db.getBackingStore()); db.start(); Field cpb = db.getClass().getDeclaredField("cpb"); Field csb = db.getClass().getDeclaredField("csb"); Field ctb = db.getClass().getDeclaredField("ctb"); cpb.setAccessible(true); csb.setAccessible(true); ctb.setAccessible(true); Assert.assertEquals(1, ((List<?>) ctb.get(db)).size()); Assert.assertEquals(1, ((List<?>) csb.get(db)).size()); Assert.assertEquals(1, ((List<?>) cpb.get(db)).size()); }
13. IndexMergerTest#assertDimCompression()
View licenseprivate void assertDimCompression(QueryableIndex index, CompressedObjectStrategy.CompressionStrategy expectedStrategy) throws Exception { // Java voodoo if (expectedStrategy == null || expectedStrategy == CompressedObjectStrategy.CompressionStrategy.UNCOMPRESSED) { return; } Object encodedColumn = index.getColumn("dim2").getDictionaryEncoding(); Field field = SimpleDictionaryEncodedColumn.class.getDeclaredField("column"); field.setAccessible(true); Object obj = field.get(encodedColumn); Field compressedSupplierField = obj.getClass().getDeclaredField("this$0"); compressedSupplierField.setAccessible(true); Object supplier = compressedSupplierField.get(obj); Field compressionField = supplier.getClass().getDeclaredField("compression"); compressionField.setAccessible(true); Object strategy = compressionField.get(supplier); Assert.assertEquals(expectedStrategy, strategy); }
14. GitVersionTest#assertEqualVersions()
View license// Compares the parsed output and what we've expected. // Uses reflection to get private fields of GitVersion: we don't need them in code, so no need to trash the class with unused accessors. private static void assertEqualVersions(GitVersion actual, TestGitVersion expected, Type expectedType) throws Exception { Field field = GitVersion.class.getDeclaredField("myMajor"); field.setAccessible(true); final int major = field.getInt(actual); field = GitVersion.class.getDeclaredField("myMinor"); field.setAccessible(true); final int minor = field.getInt(actual); field = GitVersion.class.getDeclaredField("myRevision"); field.setAccessible(true); final int rev = field.getInt(actual); field = GitVersion.class.getDeclaredField("myPatchLevel"); field.setAccessible(true); final int patch = field.getInt(actual); field = GitVersion.class.getDeclaredField("myType"); field.setAccessible(true); final Type type = (Type) field.get(actual); assertEquals(major, expected.major); assertEquals(minor, expected.minor); assertEquals(rev, expected.rev); assertEquals(patch, expected.patch); assertEquals(type, expectedType); }
15. ReflectUtilTest#testGetFieldConcreteType()
View license@Test public void testGetFieldConcreteType() throws NoSuchFieldException { Field f1 = BaseClass.class.getField("f1"); Field f2 = BaseClass.class.getField("f2"); Field f3 = BaseClass.class.getField("f3"); Field f4 = ConcreteClass.class.getField("f4"); Field f5 = ConcreteClass.class.getField("f5"); Field array1 = BaseClass.class.getField("array1"); Class[] genericSupertypes = ReflectUtil.getGenericSupertypes(ConcreteClass.class); assertEquals(String.class, genericSupertypes[0]); assertEquals(Integer.class, genericSupertypes[1]); assertEquals(String.class, ReflectUtil.getRawType(f1.getGenericType(), ConcreteClass.class)); assertEquals(Integer.class, ReflectUtil.getRawType(f2.getGenericType(), ConcreteClass.class)); assertEquals(String.class, ReflectUtil.getRawType(f3.getGenericType(), ConcreteClass.class)); assertEquals(Long.class, ReflectUtil.getRawType(f4.getGenericType(), ConcreteClass.class)); assertEquals(List.class, ReflectUtil.getRawType(f5.getGenericType(), ConcreteClass.class)); assertEquals(String[].class, ReflectUtil.getRawType(array1.getGenericType(), ConcreteClass.class)); assertEquals(Object.class, ReflectUtil.getRawType(f1.getGenericType())); assertNull(ReflectUtil.getComponentType(f1.getGenericType(), -1)); assertEquals(Long.class, ReflectUtil.getComponentType(f5.getGenericType(), 0)); }
16. MessagingControllerTest#setAccountsInPreferences()
View licenseprivate void setAccountsInPreferences(Map<String, Account> newAccounts) throws Exception { Field accounts = Preferences.class.getDeclaredField("accounts"); accounts.setAccessible(true); accounts.set(Preferences.getPreferences(appContext), newAccounts); Field accountsInOrder = Preferences.class.getDeclaredField("accountsInOrder"); accountsInOrder.setAccessible(true); ArrayList<Account> newAccountsInOrder = new ArrayList<>(); newAccountsInOrder.addAll(newAccounts.values()); accountsInOrder.set(Preferences.getPreferences(appContext), newAccountsInOrder); }
17. FieldTests#testFloatPrimitiveLegalUse()
View license///////////////////////////////////////////////// ////////////////////Floats/////////////////////// ///////////////////////////////////////////////// @Test public void testFloatPrimitiveLegalUse() throws Exception { assertNotNull(primitives); Field f = PRIMITIVE_CLASS.getField("f"); assertEquals(0f, f.getFloat(primitives)); assertEquals(0f, ((Float) f.get(primitives)).floatValue()); f.set(primitives, (float) 1); assertEquals(1f, f.getFloat(primitives)); assertEquals(1f, ((Float) f.get(primitives)).floatValue()); f.set(primitives, 'a'); f.set(primitives, (byte) 1); f.set(primitives, (int) 1); f.set(primitives, (float) 1); }
18. ResolveContextTest#createActivator()
View licenseprivate Activator createActivator() throws Exception { BundleContext bc = EasyMock.createNiceMock(BundleContext.class); EasyMock.replay(bc); Activator a = new Activator(); Field f = Activator.class.getDeclaredField("subsystems"); f.setAccessible(true); f.set(a, new Subsystems()); Field f2 = Activator.class.getDeclaredField("systemRepositoryManager"); f2.setAccessible(true); f2.set(a, new SystemRepositoryManager(bc)); return a; }
19. ResolveContextTest#createActivator()
View licenseprivate Activator createActivator() throws Exception { BundleContext bc = EasyMock.createNiceMock(BundleContext.class); EasyMock.replay(bc); Activator a = new Activator(); Field f = Activator.class.getDeclaredField("subsystems"); f.setAccessible(true); f.set(a, new Subsystems()); Field f2 = Activator.class.getDeclaredField("systemRepositoryManager"); f2.setAccessible(true); f2.set(a, new SystemRepositoryManager(bc)); return a; }
20. MQTTTest#setUp()
View license@Override @Before public void setUp() throws Exception { Field sessions = MQTTSession.class.getDeclaredField("SESSIONS"); sessions.setAccessible(true); sessions.set(null, new ConcurrentHashMap<>()); Field connectedClients = MQTTConnectionManager.class.getDeclaredField("CONNECTED_CLIENTS"); connectedClients.setAccessible(true); connectedClients.set(null, new ConcurrentHashSet<>()); super.setUp(); }
21. TestUtils#changeValueOfMaximumAllowedReferencesPerManifest()
View licensepublic static int changeValueOfMaximumAllowedReferencesPerManifest(Integer value) throws NoSuchFieldException, IllegalAccessException { Field field = AbstractSignatureReferenceVerifyInputProcessor.class.getDeclaredField("maximumAllowedReferencesPerManifest"); field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); Integer oldval = (Integer) field.get(null); field.set(null, value); return oldval; }
22. TestUtils#changeValueOfMaximumAllowedTransformsPerReference()
View licensepublic static int changeValueOfMaximumAllowedTransformsPerReference(Integer value) throws NoSuchFieldException, IllegalAccessException { Field field = AbstractSignatureReferenceVerifyInputProcessor.class.getDeclaredField("maximumAllowedTransformsPerReference"); field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); Integer oldval = (Integer) field.get(null); field.set(null, value); return oldval; }
23. TestUtils#changeValueOfMaximumAllowedXMLStructureDepth()
View licensepublic static int changeValueOfMaximumAllowedXMLStructureDepth(Integer value) throws NoSuchFieldException, IllegalAccessException { Field field = XMLEventReaderInputProcessor.class.getDeclaredField("maximumAllowedXMLStructureDepth"); field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); Integer oldval = (Integer) field.get(null); field.set(null, value); return oldval; }
24. FilterChainResolverProviderTest#testGet()
View license@Test public void testGet() throws Exception { Injector injector = createMock(Injector.class); PatternMatcher patternMatcher = createMock(PatternMatcher.class); underTest.injector = injector; underTest.setPatternMatcher(patternMatcher); FilterChainResolver resolver = underTest.get(); Field chainsField = SimpleFilterChainResolver.class.getDeclaredField("chains"); chainsField.setAccessible(true); Field injectorField = SimpleFilterChainResolver.class.getDeclaredField("injector"); injectorField.setAccessible(true); Field patternMatcherField = SimpleFilterChainResolver.class.getDeclaredField("patternMatcher"); patternMatcherField.setAccessible(true); assertSame(chains, chainsField.get(resolver)); assertSame(injector, injectorField.get(resolver)); assertSame(patternMatcher, patternMatcherField.get(resolver)); }
25. ReplicationTestBase#assertCookieInterceptorPresent()
View licenseprotected void assertCookieInterceptorPresent(ReplicatorBuilder p, String expectedRequestBody) throws NoSuchFieldException, IllegalAccessException { // peek inside these private fields to see that interceptors have been set Field reqI = ReplicatorBuilder.class.getDeclaredField("requestInterceptors"); Field respI = ReplicatorBuilder.class.getDeclaredField("responseInterceptors"); reqI.setAccessible(true); respI.setAccessible(true); List<HttpConnectionRequestInterceptor> reqIList = (List) reqI.get(p); List<HttpConnectionRequestInterceptor> respIList = (List) respI.get(p); Assert.assertEquals(1, reqIList.size()); Assert.assertEquals(CookieInterceptor.class, reqIList.get(0).getClass()); Assert.assertEquals(1, respIList.size()); Assert.assertEquals(CookieInterceptor.class, respIList.get(0).getClass()); CookieInterceptor ci = (CookieInterceptor) reqIList.get(0); Field srbField = CookieInterceptor.class.getDeclaredField("sessionRequestBody"); srbField.setAccessible(true); byte[] srb = (byte[]) srbField.get(ci); String srbString = new String(srb); Assert.assertEquals(expectedRequestBody, srbString); }
26. AbstractTestBase#changeValueOfMaximumAllowedReferencesPerManifest()
View licensepublic static int changeValueOfMaximumAllowedReferencesPerManifest(Integer value) throws NoSuchFieldException, IllegalAccessException { Field field = AbstractSignatureReferenceVerifyInputProcessor.class.getDeclaredField("maximumAllowedReferencesPerManifest"); field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); Integer oldval = (Integer) field.get(null); field.set(null, value); return oldval; }
27. AbstractTestBase#changeValueOfMaximumAllowedTransformsPerReference()
View licensepublic static int changeValueOfMaximumAllowedTransformsPerReference(Integer value) throws NoSuchFieldException, IllegalAccessException { Field field = AbstractSignatureReferenceVerifyInputProcessor.class.getDeclaredField("maximumAllowedTransformsPerReference"); field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); Integer oldval = (Integer) field.get(null); field.set(null, value); return oldval; }
28. AbstractTestBase#changeValueOfMaximumAllowedDecompressedBytes()
View licensepublic static long changeValueOfMaximumAllowedDecompressedBytes(Long value) throws NoSuchFieldException, IllegalAccessException { Field field = DecryptInputProcessor.class.getDeclaredField("maximumAllowedDecompressedBytes"); field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); Long oldval = (Long) field.get(null); field.set(null, value); return oldval; }
29. AbstractTestBase#changeValueOfMaximumAllowedReferencesPerManifest()
View licensepublic static int changeValueOfMaximumAllowedReferencesPerManifest(Integer value) throws NoSuchFieldException, IllegalAccessException { Field field = AbstractSignatureReferenceVerifyInputProcessor.class.getDeclaredField("maximumAllowedReferencesPerManifest"); field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); Integer oldval = (Integer) field.get(null); field.set(null, value); return oldval; }
30. AbstractTestBase#changeValueOfMaximumAllowedTransformsPerReference()
View licensepublic static int changeValueOfMaximumAllowedTransformsPerReference(Integer value) throws NoSuchFieldException, IllegalAccessException { Field field = AbstractSignatureReferenceVerifyInputProcessor.class.getDeclaredField("maximumAllowedTransformsPerReference"); field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); Integer oldval = (Integer) field.get(null); field.set(null, value); return oldval; }
31. AbstractTestBase#changeValueOfMaximumAllowedDecompressedBytes()
View licensepublic static long changeValueOfMaximumAllowedDecompressedBytes(Long value) throws NoSuchFieldException, IllegalAccessException { Field field = DecryptInputProcessor.class.getDeclaredField("MAX_ALLOWED_DECOMPRESSED_BYTES"); field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); Long oldval = (Long) field.get(null); field.set(null, value); return oldval; }
32. ListTag#toNMS()
View license@Override public Object toNMS() throws ReflectiveOperationException { Class<?> clazz = NMS_CLASS_RESOLVER.resolve(getNMSClass()); Field field = clazz.getDeclaredField("list"); field.setAccessible(true); Object nms = clazz.newInstance(); Field typeField = clazz.getDeclaredField("type"); typeField.setAccessible(true); typeField.setByte(nms, (byte) getTagType()); List list = (List) field.get(nms); for (NBTTag tag : this) { list.add(tag.toNMS()); } field.set(nms, list); return nms; }
33. MapEntriesTest#test_getVanityPaths_1()
View license@Test public //SLING-4891 void test_getVanityPaths_1() throws Exception { Field field1 = MapEntries.class.getDeclaredField("maxCachedVanityPathEntries"); field1.setAccessible(true); field1.set(mapEntries, 0); Method method = MapEntries.class.getDeclaredMethod("getVanityPaths", String.class); method.setAccessible(true); method.invoke(mapEntries, "/notExisting"); Field vanityCounter = MapEntries.class.getDeclaredField("vanityCounter"); vanityCounter.setAccessible(true); AtomicLong counter = (AtomicLong) vanityCounter.get(mapEntries); assertEquals(0, counter.longValue()); }
34. ValueHandlerTest#testApplyAnonymousPrivateFinalInt()
View license@Test public void testApplyAnonymousPrivateFinalInt() throws Exception { Properties p = new Properties(); p.put("int", "010"); Object o = new Object() { @Value(name = "int") private final int i1 = -1; }; Field f = o.getClass().getDeclaredField("i1"); f.setAccessible(true); int value = f.getInt(o); Assert.assertEquals(value, -1); f.setAccessible(false); ValueHandler.apply(o, p, null); f.setAccessible(true); value = f.getInt(o); Assert.assertEquals(value, 8); f.setAccessible(false); }
35. GenericClassTest#testGenericClasses()
View license@Test public void testGenericClasses() throws Exception { Field t = Dao.class.getField("t"); Field raw = Dao.class.getField("raw"); Field check22 = Dao.class.getField("check22"); Field check22Bound = Dao.class.getField("check22WithBound"); Field check4 = WithTypeVariable.class.getField("check4"); Assert.assertFalse(GenericsUtil.satisfiesDependency(false, false, raw.getGenericType(), t.getGenericType())); Assert.assertTrue(GenericsUtil.satisfiesDependency(false, false, check4.getGenericType(), t.getGenericType())); Assert.assertTrue(GenericsUtil.satisfiesDependency(false, false, check22.getGenericType(), t.getGenericType())); Assert.assertTrue(GenericsUtil.satisfiesDependency(false, false, check22Bound.getGenericType(), t.getGenericType())); }
36. TestBoneCP#testJMXUnRegisterWithName()
View license/** Test for different pool names. * @throws SecurityException * @throws NoSuchFieldException * @throws IllegalArgumentException * @throws IllegalAccessException * @throws InstanceAlreadyExistsException * @throws MBeanRegistrationException * @throws NotCompliantMBeanException * @throws InstanceNotFoundException */ @Test public void testJMXUnRegisterWithName() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException, InstanceNotFoundException { MBeanServer mockMbs = EasyMock.createNiceMock(MBeanServer.class); Field field = testClass.getClass().getDeclaredField("mbs"); field.setAccessible(true); field.set(testClass, mockMbs); field = testClass.getClass().getDeclaredField("config"); field.setAccessible(true); field.set(testClass, mockConfig); expect(mockConfig.getPoolName()).andReturn("poolName").anyTimes(); ObjectInstance mockInstance = EasyMock.createNiceMock(ObjectInstance.class); expect(mockMbs.isRegistered((ObjectName) anyObject())).andReturn(true).anyTimes(); mockMbs.unregisterMBean((ObjectName) anyObject()); expectLastCall().times(2).andThrow(new InstanceNotFoundException()).once(); replay(mockMbs, mockInstance, mockConfig); testClass.registerUnregisterJMX(false); // should trigger an exception testClass.registerUnregisterJMX(false); verify(mockMbs); }
37. TestBoneCPConnectionProvider#testGetConnection()
View license/** * Test method for {@link com.jolbox.bonecp.provider.BoneCPConnectionProvider#getConnection()}. * @throws SQLException * @throws NoSuchFieldException * @throws SecurityException * @throws IllegalAccessException * @throws IllegalArgumentException */ @Test public void testGetConnection() throws SQLException, SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { Field field = testClass.getClass().getDeclaredField("autocommit"); field.setAccessible(true); field.set(testClass, true); field = testClass.getClass().getDeclaredField("isolation"); field.setAccessible(true); field.set(testClass, 8); expect(mockPool.getConnection()).andReturn(mockConnection).once(); expect(mockConnection.getAutoCommit()).andReturn(false).once(); expect(mockConnection.getTransactionIsolation()).andReturn(0).once(); mockConnection.setTransactionIsolation(8); expectLastCall().once(); replay(mockPool, mockConnection); testClass.getConnection(); verify(mockPool, mockConnection); }
38. TestUtils#fixAdapterForTesting()
View license/** * Fixes internal dependencies to android.database.Observable so that a RecyclerView.Adapter can be tested using regular unit tests while * observing changes to the data setIsTypingRepository. */ public static RecyclerView.AdapterDataObserver fixAdapterForTesting(RecyclerView.Adapter adapter) throws NoSuchFieldException, IllegalAccessException { // Observables are not mocked by default so we need to hook the adapter up to an observer so we can track changes Field observableField = RecyclerView.Adapter.class.getDeclaredField("mObservable"); observableField.setAccessible(true); Object observable = observableField.get(adapter); Field observersField = Observable.class.getDeclaredField("mObservers"); observersField.setAccessible(true); final ArrayList<Object> observers = new ArrayList<>(); RecyclerView.AdapterDataObserver dataObserver = mock(RecyclerView.AdapterDataObserver.class); observers.add(dataObserver); observersField.set(observable, observers); return dataObserver; }
39. GhprbTestUtil#setFinal()
View licensestatic void setFinal(Object o, Field field, Object newValue) throws Exception { field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); int prevModifiers = field.getModifiers(); modifiersField.setInt(field, prevModifiers & ~Modifier.FINAL); field.set(o, newValue); modifiersField.setInt(field, prevModifiers); modifiersField.setAccessible(false); field.setAccessible(false); }
40. ObjectBooleanHashMapTestCase#newMap()
View license@Test public void newMap() throws Exception { Field keys = this.targetClass.getDeclaredField("keys"); keys.setAccessible(true); Field values = this.targetClass.getDeclaredField("values"); values.setAccessible(true); MutableObjectBooleanMap<String> hashMap = this.getEmptyMap(); Assert.assertEquals(16L, ((Object[]) keys.get(hashMap)).length); Assert.assertEquals(64L, ((BitSet) values.get(hashMap)).size()); Assert.assertEquals(this.getEmptyMap(), hashMap); }
41. RemotingServiceImplTest#testInterceptorsAreAddedOnCreationOfServiceRegistry()
View license/** * Tests ensures that both interceptors from the service registry and also interceptors defined in the configuration * are added to the RemotingServiceImpl on creation */ @Test public void testInterceptorsAreAddedOnCreationOfServiceRegistry() throws Exception { Field incomingInterceptors = RemotingServiceImpl.class.getDeclaredField("incomingInterceptors"); Field outgoingInterceptors = RemotingServiceImpl.class.getDeclaredField("outgoingInterceptors"); incomingInterceptors.setAccessible(true); outgoingInterceptors.setAccessible(true); serviceRegistry.addIncomingInterceptor(new FakeInterceptor()); serviceRegistry.addOutgoingInterceptor(new FakeInterceptor()); List<String> interceptorClassNames = new ArrayList<>(); interceptorClassNames.add(FakeInterceptor.class.getCanonicalName()); configuration.setIncomingInterceptorClassNames(interceptorClassNames); configuration.setOutgoingInterceptorClassNames(interceptorClassNames); remotingService = new RemotingServiceImpl(null, configuration, null, null, null, null, null, serviceRegistry); assertTrue(((List) incomingInterceptors.get(remotingService)).size() == 2); assertTrue(((List) outgoingInterceptors.get(remotingService)).size() == 2); assertTrue(((List) incomingInterceptors.get(remotingService)).contains(serviceRegistry.getIncomingInterceptors(null).get(0))); assertTrue(((List) outgoingInterceptors.get(remotingService)).contains(serviceRegistry.getOutgoingInterceptors(null).get(0))); }
42. RemotingServiceImplTest#testSetInterceptorsAddsBothInterceptorsFromConfigAndServiceRegistry()
View license/** * Tests ensures that setInterceptors methods adds both interceptors from the service registry and also interceptors * defined in the configuration. */ @Test public void testSetInterceptorsAddsBothInterceptorsFromConfigAndServiceRegistry() throws Exception { Method method = RemotingServiceImpl.class.getDeclaredMethod("setInterceptors", Configuration.class); Field incomingInterceptors = RemotingServiceImpl.class.getDeclaredField("incomingInterceptors"); Field outgoingInterceptors = RemotingServiceImpl.class.getDeclaredField("outgoingInterceptors"); method.setAccessible(true); incomingInterceptors.setAccessible(true); outgoingInterceptors.setAccessible(true); serviceRegistry.addIncomingInterceptor(new FakeInterceptor()); serviceRegistry.addOutgoingInterceptor(new FakeInterceptor()); List<String> interceptorClassNames = new ArrayList<>(); interceptorClassNames.add(FakeInterceptor.class.getCanonicalName()); configuration.setIncomingInterceptorClassNames(interceptorClassNames); configuration.setOutgoingInterceptorClassNames(interceptorClassNames); method.invoke(remotingService, configuration); assertTrue(((List) incomingInterceptors.get(remotingService)).size() == 2); assertTrue(((List) outgoingInterceptors.get(remotingService)).size() == 2); assertTrue(((List) incomingInterceptors.get(remotingService)).contains(serviceRegistry.getIncomingInterceptors(null).get(0))); assertTrue(((List) outgoingInterceptors.get(remotingService)).contains(serviceRegistry.getOutgoingInterceptors(null).get(0))); }
43. ClientThreadPoolsTest#testThreadPoolInjection()
View license@Test public void testThreadPoolInjection() throws Exception { ServerLocator serverLocator = new ServerLocatorImpl(false); ThreadPoolExecutor threadPool = new ThreadPoolExecutor(1, 1, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); ScheduledThreadPoolExecutor scheduledThreadPool = new ScheduledThreadPoolExecutor(1); serverLocator.setThreadPools(threadPool, scheduledThreadPool); Field threadPoolField = ServerLocatorImpl.class.getDeclaredField("threadPool"); Field scheduledThreadPoolField = ServerLocatorImpl.class.getDeclaredField("scheduledThreadPool"); Method initialise = ServerLocatorImpl.class.getDeclaredMethod("initialise"); initialise.setAccessible(true); initialise.invoke(serverLocator); threadPoolField.setAccessible(true); scheduledThreadPoolField.setAccessible(true); ThreadPoolExecutor tpe = (ThreadPoolExecutor) threadPoolField.get(serverLocator); ScheduledThreadPoolExecutor stpe = (ScheduledThreadPoolExecutor) scheduledThreadPoolField.get(serverLocator); assertEquals(threadPool, tpe); assertEquals(scheduledThreadPool, stpe); }
44. TestConnectionPartition#testGetCreatedConnections()
View license/** * @throws SecurityException * @throws NoSuchFieldException * @throws IllegalArgumentException * @throws IllegalAccessException */ @Test public void testGetCreatedConnections() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { ReentrantReadWriteLock mockLock = createNiceMock(ReentrantReadWriteLock.class); ReadLock mockReadLock = createNiceMock(ReadLock.class); Field field = testClass.getClass().getDeclaredField("statsLock"); field.setAccessible(true); ReentrantReadWriteLock oldLock = (ReentrantReadWriteLock) field.get(testClass); field.set(testClass, mockLock); expect(mockLock.readLock()).andThrow(new RuntimeException()).once().andReturn(mockReadLock).once(); mockReadLock.lock(); expectLastCall().once(); replay(mockLock, mockReadLock); try { testClass.getCreatedConnections(); fail("Should have thrown an exception"); } catch (Throwable t) { } verify(mockLock); field.set(testClass, oldLock); }
45. HgVersionTest#assertEqualVersions()
View licenseprivate static void assertEqualVersions(HgVersion actual, TestHgVersion expected) throws Exception { Field field = HgVersion.class.getDeclaredField("myMajor"); field.setAccessible(true); final int major = field.getInt(actual); field = HgVersion.class.getDeclaredField("myMiddle"); field.setAccessible(true); final int middle = field.getInt(actual); field = HgVersion.class.getDeclaredField("myMinor"); field.setAccessible(true); final int minor = field.getInt(actual); assertEquals(major, expected.major); assertEquals(middle, expected.middle); assertEquals(minor, expected.minor); HgVersion versionFromTest = new HgVersion(expected.major, expected.middle, expected.minor); //test equals method assertEquals(versionFromTest, actual); }
46. BeanUtils#setFieldValue()
View licensepublic static void setFieldValue(Object object, String propertyName, Object newValue, boolean targetAccessible) throws NoSuchFieldException, IllegalAccessException { Assert.notNull(object); Assert.hasText(propertyName); Field field = getDeclaredField(object, propertyName); boolean accessible = field.isAccessible(); field.setAccessible(targetAccessible); field.set(object, newValue); field.setAccessible(accessible); }
47. ExtendsIT#constructorHasParentsProperties()
View license@Test @SuppressWarnings("rawtypes") public void constructorHasParentsProperties() throws Exception { ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/extends/subtypeOfB.json", "com.example", config("includeConstructors", true)); Class type = resultsClassLoader.loadClass("com.example.SubtypeOfB"); Class supertype = resultsClassLoader.loadClass("com.example.SubtypeOfBParent"); assertThat(type.getSuperclass(), is(equalTo(supertype))); assertNotNull("Parent constructor is missing", supertype.getConstructor(String.class)); assertNotNull("Constructor is missing", type.getConstructor(String.class, String.class)); Object typeInstance = type.getConstructor(String.class, String.class).newInstance("String1", "String2"); Field chieldField = type.getDeclaredField("childProperty"); chieldField.setAccessible(true); String childProp = (String) chieldField.get(typeInstance); Field parentField = supertype.getDeclaredField("parentProperty"); parentField.setAccessible(true); String parentProp = (String) parentField.get(typeInstance); assertThat(childProp, is(equalTo("String1"))); assertThat(parentProp, is(equalTo("String2"))); }
48. HudsonTest#invalidPrimaryView()
View license/** * Verify null/invalid primaryView setting doesn't result in infinite loop. */ @Test @Issue("JENKINS-6938") public void invalidPrimaryView() throws Exception { Field pv = Jenkins.class.getDeclaredField("primaryView"); pv.setAccessible(true); String value = null; pv.set(j.jenkins, value); assertNull("null primaryView", j.jenkins.getView(value)); value = "some bogus name"; pv.set(j.jenkins, value); assertNull("invalid primaryView", j.jenkins.getView(value)); }
49. bug6495920#thirdValidate()
View licensepublic void thirdValidate() throws Exception { Field key = BasicPopupMenuUI.class.getDeclaredField("MOUSE_GRABBER_KEY"); key.setAccessible(true); Object grabber = AppContext.getAppContext().get(key.get(null)); if (grabber == null) { throw new Exception("cannot find a mouse grabber in app's context"); } Field field = grabber.getClass().getDeclaredField("grabbedWindow"); field.setAccessible(true); Object window = field.get(grabber); if (window != null) { throw new Exception("interaction with GNOME is crippled"); } }
50. CassandraUtils#deepType2tuple()
View license/** * Convers an instance of type <T> to a tuple of ( Map<String, ByteBuffer>, List<ByteBuffer> ). The first map * contains the key column names and the corresponding values. The ByteBuffer list contains the value of the columns * that will be bounded to CQL query parameters. * * @param e the entity object to process. * @param <T> the entity object generic type. * @return a pair whose first element is a Cells object containing key Cell(s) and whose second element contains all * of the other Cell(s). */ public static <T extends IDeepType> Tuple2<Cells, Cells> deepType2tuple(T e) { Pair<Field[], Field[]> fields = AnnotationUtils.filterKeyFields(e.getClass()); Field[] keyFields = fields.left; Field[] otherFields = fields.right; Cells keys = new Cells(e.getClass().getName()); Cells values = new Cells(e.getClass().getName()); for (Field keyField : keyFields) { keys.add(createFromEntity(e, keyField)); } for (Field valueField : otherFields) { values.add(createFromEntity(e, valueField)); } return new Tuple2<>(keys, values); }
51. AopTargetUtils#getJdkDynamicProxyTargetObject()
View licenseprivate static Object getJdkDynamicProxyTargetObject(Object proxy) throws Exception { Field h = proxy.getClass().getSuperclass().getDeclaredField("h"); h.setAccessible(true); AopProxy aopProxy = (AopProxy) h.get(proxy); Field advised = aopProxy.getClass().getDeclaredField("advised"); advised.setAccessible(true); Object target = ((AdvisedSupport) advised.get(aopProxy)).getTargetSource().getTarget(); return target; }
52. AopTargetUtils#getCglibProxyTargetObject()
View licenseprivate static Object getCglibProxyTargetObject(Object proxy) throws Exception { Field h = proxy.getClass().getDeclaredField("CGLIB$CALLBACK_0"); h.setAccessible(true); Object dynamicAdvisedInterceptor = h.get(proxy); Field advised = dynamicAdvisedInterceptor.getClass().getDeclaredField("advised"); advised.setAccessible(true); Object target = ((AdvisedSupport) advised.get(dynamicAdvisedInterceptor)).getTargetSource().getTarget(); return target; }
53. StatefulRunnableTest#setUp()
View license@Before public void setUp() throws Exception { mResult = new Object(); mException = new ConcurrentModificationException(); mStatefulRunnable = mock(StatefulRunnable.class, CALLS_REAL_METHODS); // setup state - no constructor has been run Field mStateField = StatefulRunnable.class.getDeclaredField("mState"); mStateField.setAccessible(true); mStateField.set(mStatefulRunnable, new AtomicInteger(StatefulRunnable.STATE_CREATED)); mStateField.setAccessible(false); }
54. T6410653#main()
View licensepublic static void main(String... args) throws Exception { File testSrc = new File(System.getProperty("test.src")); String source = new File(testSrc, "T6410653.java").getPath(); ClassLoader cl = ToolProvider.getSystemToolClassLoader(); Tool compiler = ToolProvider.getSystemJavaCompiler(); Class<?> log = Class.forName("com.sun.tools.javac.util.Log", true, cl); Field useRawMessages = log.getDeclaredField("useRawMessages"); useRawMessages.setAccessible(true); useRawMessages.setBoolean(null, true); ByteArrayOutputStream out = new ByteArrayOutputStream(); compiler.run(null, null, out, "-d", source, source); System.err.println(">>>" + out + "<<<"); useRawMessages.setBoolean(null, false); if (!out.toString().equals(String.format("%s%n%s%n", "javac: javac.err.file.not.directory", "javac.msg.usage"))) { throw new AssertionError(out); } System.out.println("Test PASSED. Running javac again to see localized output:"); compiler.run(null, null, System.out, "-d", source, source); }
55. ObjectBooleanHashMapTestCase#newWithInitialCapacity()
View license@Test public void newWithInitialCapacity() throws Exception { Field keys = this.targetClass.getDeclaredField("keys"); keys.setAccessible(true); Field values = this.targetClass.getDeclaredField("values"); values.setAccessible(true); MutableObjectBooleanMap<String> hashMap = this.newMapWithInitialCapacity(3); Assert.assertEquals(8L, ((Object[]) keys.get(hashMap)).length); Assert.assertEquals(64L, ((BitSet) values.get(hashMap)).size()); MutableObjectBooleanMap<String> hashMap2 = this.newMapWithInitialCapacity(15); Assert.assertEquals(32L, ((Object[]) keys.get(hashMap2)).length); Assert.assertEquals(64L, ((BitSet) values.get(hashMap)).size()); }
56. ObjectBooleanHashMapTestCase#defaultInitialCapacity()
View license@Test public void defaultInitialCapacity() throws Exception { Field keys = this.targetClass.getDeclaredField("keys"); keys.setAccessible(true); Field values = this.targetClass.getDeclaredField("values"); values.setAccessible(true); MutableObjectBooleanMap<String> hashMap = this.getEmptyMap(); Assert.assertEquals(16L, ((Object[]) keys.get(hashMap)).length); Assert.assertEquals(64L, ((BitSet) values.get(hashMap)).size()); }
57. KieModuleRepoTest#createMockKieContainer()
View licenseprivate static KieContainerImpl createMockKieContainer(ReleaseId projectReleaseId, KieModuleRepo kieModuleRepo) throws Exception { // kie module InternalKieModule mockKieProjectKieModule = mock(InternalKieModule.class); ResourceProvider mockKieProjectKieModuleResourceProvider = mock(ResourceProvider.class); when(mockKieProjectKieModule.createResourceProvider()).thenReturn(mockKieProjectKieModuleResourceProvider); // kie project KieModuleKieProject kieProject = new KieModuleKieProject(mockKieProjectKieModule); KieModuleKieProject mockKieProject = spy(kieProject); doNothing().when(mockKieProject).init(); doReturn(projectReleaseId).when(mockKieProject).getGAV(); doNothing().when(mockKieProject).updateToModule(any(InternalKieModule.class)); // kie repository KieRepository kieRepository = new KieRepositoryImpl(); Field kieModuleRepoField = KieRepositoryImpl.class.getDeclaredField("kieModuleRepo"); kieModuleRepoField.setAccessible(true); kieModuleRepoField.set(kieRepository, kieModuleRepo); kieModuleRepoField.setAccessible(false); // kie container KieContainerImpl kieContainerImpl = new KieContainerImpl(mockKieProject, kieRepository); return kieContainerImpl; }
58. FieldTests#testLongPrimitiveLegalUse()
View license///////////////////////////////////////////////// ///////////////////Longs///////////////////////// ///////////////////////////////////////////////// @Test public void testLongPrimitiveLegalUse() throws Exception { assertNotNull(primitives); Field f = PRIMITIVE_CLASS.getField("j"); assertEquals(0, f.getLong(primitives)); assertEquals(0, ((Long) f.get(primitives)).longValue()); f.set(primitives, (long) 1); assertEquals(1, f.getLong(primitives)); assertEquals(1, ((Long) f.get(primitives)).longValue()); f.set(primitives, 'a'); f.set(primitives, (byte) 1); }
59. FieldTests#testIntPrimitiveLegalUse()
View license///////////////////////////////////////////////// ////////////////////Ints///////////////////////// ///////////////////////////////////////////////// @Test public void testIntPrimitiveLegalUse() throws Exception { assertNotNull(primitives); Field f = PRIMITIVE_CLASS.getField("i"); assertEquals(0, f.getInt(primitives)); assertEquals(0, ((Integer) f.get(primitives)).intValue()); f.set(primitives, (int) 1); assertEquals(1, f.getInt(primitives)); assertEquals(1, ((Integer) f.get(primitives)).intValue()); f.set(primitives, 'a'); f.set(primitives, (byte) 1); }
60. ReadingBuilder#copy()
View licensepublic static Reading copy(Reading reading, boolean skipSinceUtil) throws NoSuchFieldException, IllegalAccessException { // use private field access to make a copy Field field = Reading.class.getDeclaredField("parameterMap"); field.setAccessible(true); final LinkedHashMap<String, String> source = (LinkedHashMap<String, String>) field.get(reading); // create another reading, and add all fields from source Reading copy = new Reading(); final LinkedHashMap<String, String> copyMap = new LinkedHashMap<String, String>(); copyMap.putAll(source); if (skipSinceUtil) { copyMap.remove("since"); copyMap.remove("until"); } field.set(copy, copyMap); field.setAccessible(false); return copy; }
61. ClassFileLocatorAgentBasedTest#testExtractionOfInflatedMethodAccessor()
View license@Test @AgentAttachmentRule.Enforce(retransformsClasses = true) public void testExtractionOfInflatedMethodAccessor() throws Exception { assertThat(ByteBuddyAgent.install(), instanceOf(Instrumentation.class)); Method bar = Foo.class.getDeclaredMethod("bar"); for (int i = 0; i < 20; i++) { bar.invoke(new Foo()); } Field field = Method.class.getDeclaredField("methodAccessor"); field.setAccessible(true); Object methodAccessor = field.get(bar); Field delegate = methodAccessor.getClass().getDeclaredField("delegate"); delegate.setAccessible(true); Class<?> delegateClass = delegate.get(methodAccessor).getClass(); ClassFileLocator classFileLocator = ClassFileLocator.AgentBased.fromInstalledAgent(delegateClass.getClassLoader()); ClassFileLocator.Resolution resolution = classFileLocator.locate(delegateClass.getName()); assertThat(resolution.isResolved(), is(true)); assertThat(resolution.resolve(), notNullValue(byte[].class)); }
62. Arguments#getFields()
View license/** * Keep only the fields which are either primitive or strings. */ private static Field[] getFields(Arg arg) { Class target_ = arg.getClass(); Field[] fields = new Field[0]; while (target_ != null) { int flen = fields.length; Field[] f2 = target_.getDeclaredFields(); fields = Arrays.copyOf(fields, flen + f2.length); System.arraycopy(f2, 0, fields, flen, f2.length); target_ = target_.getSuperclass(); } Field[] keep = new Field[fields.length]; int num = 0; for (Field field : fields) { field.setAccessible(true); if (Modifier.isStatic(field.getModifiers())) continue; if (field.getType().isPrimitive() || field.getType() == String.class) keep[num++] = field; } Field[] res = new Field[num]; for (int i = 0; i < num; i++) res[i] = keep[i]; return res; }
63. ObjectBooleanHashMapTestCase#newMap()
View license@Test public void newMap() throws Exception { Field keys = this.targetClass.getDeclaredField("keys"); keys.setAccessible(true); Field values = this.targetClass.getDeclaredField("values"); values.setAccessible(true); MutableObjectBooleanMap<String> hashMap = this.getEmptyMap(); Assert.assertEquals(16L, ((Object[]) keys.get(hashMap)).length); Assert.assertEquals(64L, ((BitSet) values.get(hashMap)).size()); Assert.assertEquals(this.getEmptyMap(), hashMap); }
64. ObjectBooleanHashMapTestCase#newWithInitialCapacity()
View license@Test public void newWithInitialCapacity() throws Exception { Field keys = this.targetClass.getDeclaredField("keys"); keys.setAccessible(true); Field values = this.targetClass.getDeclaredField("values"); values.setAccessible(true); MutableObjectBooleanMap<String> hashMap = this.newMapWithInitialCapacity(3); Assert.assertEquals(8L, ((Object[]) keys.get(hashMap)).length); Assert.assertEquals(64L, ((BitSet) values.get(hashMap)).size()); MutableObjectBooleanMap<String> hashMap2 = this.newMapWithInitialCapacity(15); Assert.assertEquals(32L, ((Object[]) keys.get(hashMap2)).length); Assert.assertEquals(64L, ((BitSet) values.get(hashMap)).size()); }
65. ObjectBooleanHashMapTestCase#defaultInitialCapacity()
View license@Test public void defaultInitialCapacity() throws Exception { Field keys = this.targetClass.getDeclaredField("keys"); keys.setAccessible(true); Field values = this.targetClass.getDeclaredField("values"); values.setAccessible(true); MutableObjectBooleanMap<String> hashMap = this.getEmptyMap(); Assert.assertEquals(16L, ((Object[]) keys.get(hashMap)).length); Assert.assertEquals(64L, ((BitSet) values.get(hashMap)).size()); }
66. ProvidersRegistryTest#testProtectionModel()
View license/** * Tests that the providersCache object is and remains instanceof ConcurrentHashMap. * * ProvidersRegistry.MediaTypeMap uses type ConcurrentHashMap on the providersCache object to provide some lock protection on * the map when providers are dynamically added. However, lock protection is already built into the ProvidersRegistry methods: * getContextResolver(), getMessageBodyReader(), and getMessageBodyWriter(). * * However, the second protection (in the ProvidersRegistry methods) is for the cache itself which could be written to by two * different threads even if they both were getting a single MessageBodyReader (i.e. a cache value may be dropped and then two * threads come back later and try to write a new cache value). Due to some weird HashMap properties, this can blow up in * weird ways. * * Thus, we need to ensure the providersCache continues to be instantiated with ConcurrentHashMap. */ public void testProtectionModel() throws Exception { // I need the instantiated object providersCache in the abstract private nested class MediaTypeMap, so here we go! ProvidersRegistry providersRegistry = new ProvidersRegistry(new LifecycleManagersRegistry(), new ApplicationValidator()); Field field = providersRegistry.getClass().getDeclaredField("messageBodyReaders"); field.setAccessible(true); Object messageBodyReaders = field.get(providersRegistry); Field field2 = messageBodyReaders.getClass().getSuperclass().getDeclaredField("providersCache"); field2.setAccessible(true); Object providersCache = field2.get(messageBodyReaders); assertTrue(providersCache instanceof SoftConcurrentMap); }
67. ProvidersRegistry11Test#testProvidesAnnotationParsing()
View license/** * JAX-RS 1.1 allows syntax such as: * * @Produces( { "abcd/efg, hijk/lmn", "opqr/stu" }) * @throws Exception */ public void testProvidesAnnotationParsing() throws Exception { ProvidersRegistry providersRegistry = new ProvidersRegistry(new LifecycleManagersRegistry(), new ApplicationValidator()); providersRegistry.addProvider(MyProvider.class); Field field = providersRegistry.getClass().getDeclaredField("messageBodyWriters"); field.setAccessible(true); Object messageBodyWriters = field.get(providersRegistry); Field field2 = messageBodyWriters.getClass().getSuperclass().getDeclaredField("data"); field2.setAccessible(true); HashMap data = (HashMap) field2.get(messageBodyWriters); assertEquals(3, data.size()); }
68. HudsonTest#invalidPrimaryView()
View license/** * Verify null/invalid primaryView setting doesn't result in infinite loop. */ @Test @Issue("JENKINS-6938") public void invalidPrimaryView() throws Exception { Field pv = Jenkins.class.getDeclaredField("primaryView"); pv.setAccessible(true); String value = null; pv.set(j.jenkins, value); assertNull("null primaryView", j.jenkins.getView(value)); value = "some bogus name"; pv.set(j.jenkins, value); assertNull("invalid primaryView", j.jenkins.getView(value)); }
69. ProvidersRegistry11Test#testConsumesAnnotationParsing()
View license/** * JAX-RS 1.1 allows syntax such as: * * @Consumes( { "abcd/efg, hijk/lmn", "opqr/stu" }) * @throws Exception */ public void testConsumesAnnotationParsing() throws Exception { ProvidersRegistry providersRegistry = new ProvidersRegistry(new LifecycleManagersRegistry(), new ApplicationValidator()); providersRegistry.addProvider(MyProvider.class); Field field = providersRegistry.getClass().getDeclaredField("messageBodyReaders"); field.setAccessible(true); Object messageBodyReaders = field.get(providersRegistry); Field field2 = messageBodyReaders.getClass().getSuperclass().getDeclaredField("data"); field2.setAccessible(true); HashMap data = (HashMap) field2.get(messageBodyReaders); assertEquals(3, data.size()); }
70. EventLogServiceTest#testStartup()
View license@Test public void testStartup() throws Exception { EventLogService eventLogService = new EventLogService(eventLog); eventLogService.startUp(); Field eventLogSystemField = eventLogService.getClass().getDeclaredField("eventLogSystem"); eventLogSystemField.setAccessible(true); EventLogSystem eventLogSystem = (EventLogSystem) eventLogSystemField.get(eventLogService); assertNotNull(eventLogSystem); Field eventLogThreadField = eventLogSystem.getClass().getDeclaredField("eventLogThread"); eventLogThreadField.setAccessible(true); Thread eventThread = (Thread) eventLogThreadField.get(eventLogSystem); assertNotNull(eventThread); assertEquals("EventLogThread", eventThread.getName()); eventLogService.startUp(); }
71. TreeTest#testRemoveExpandedItemsOnContainerChange()
View license@Test public void testRemoveExpandedItemsOnContainerChange() throws Exception { tree.expandItem("parent"); tree.expandItem("child"); tree.setContainerDataSource(new HierarchicalContainer()); Field expandedField = tree.getClass().getDeclaredField("expanded"); Field expandedItemIdField = tree.getClass().getDeclaredField("expandedItemId"); expandedField.setAccessible(true); expandedItemIdField.setAccessible(true); HashSet<Object> expanded = (HashSet<Object>) expandedField.get(tree); assertEquals(0, expanded.size()); Object expandedItemId = expandedItemIdField.get(tree); assertNull(expandedItemId); }
72. MethodPropertyMemoryConsumptionTest#testSetArguments()
View license@Test public void testSetArguments() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { TestBean bean = new TestBean(); TestMethodProperty<String> property = new TestMethodProperty<String>(bean, "name"); Object[] getArgs = property.getGetArgs(); Object[] setArgs = property.getSetArgs(); Field getArgsField = TestMethodProperty.class.getDeclaredField("getArgs"); getArgsField.setAccessible(true); Field setArgsField = TestMethodProperty.class.getDeclaredField("setArgs"); setArgsField.setAccessible(true); Assert.assertSame("setArguments method sets non-default instance" + " of empty Object array for getArgs", getArgsField.get(property), getArgs); Assert.assertSame("setArguments method sets non-default instance" + " of empty Object array for setArgs", setArgsField.get(property), setArgs); }
73. ResteasyProviderFactoryTest#testRegisterProviderInstancePriority()
View license/** * Generic helper method for RESTEASY-1311 cases, because the test logic is the same. * Unfortunately, there seems to be no public accessors for the properties we need, * so we have to resort to using reflection to check the right priority setting. */ private void testRegisterProviderInstancePriority(Object filter, Object registry) throws Exception { int priorityOverride = Priorities.USER + 1; factory.registerProviderInstance(filter, null, priorityOverride, false); Field interceptorsField = registry.getClass().getSuperclass().getDeclaredField("interceptors"); interceptorsField.setAccessible(true); @SuppressWarnings("unchecked") List<InterceptorFactory> interceptors = (List<InterceptorFactory>) interceptorsField.get(registry); Field orderField = interceptors.get(0).getClass().getSuperclass().getDeclaredField("order"); orderField.setAccessible(true); int order = (Integer) orderField.get(interceptors.get(0)); Assert.assertEquals(priorityOverride, order); }
74. ListTag#fromNMS()
View license@Override public ListTag fromNMS(Object nms) throws ReflectiveOperationException { Class<?> clazz = NMS_CLASS_RESOLVER.resolve(getNMSClass()); Field typeField = clazz.getDeclaredField("type"); typeField.setAccessible(true); byte typeId = typeField.getByte(nms); setTagType(typeId); Field field = clazz.getDeclaredField("list"); field.setAccessible(true); List<Object> nmsList = (List<Object>) field.get(nms); for (Object o : nmsList) { NBTTag nbtTag = NBTTag.forType(typeId).newInstance(); if (nbtTag.getTypeId() == TagID.TAG_END) { continue; } add(nbtTag.fromNMS(o)); } return this; }
75. CleanContextCacheTestExecutionListener#afterTestClass()
View license@Override public void afterTestClass(TestContext testContext) throws Exception { Field cacheField = TestContext.class.getDeclaredField("contextCache"); cacheField.setAccessible(true); ContextCache cache = (ContextCache) cacheField.get(testContext); Field cacheMapField = ContextCache.class.getDeclaredField("contextKeyToContextMap"); cacheMapField.setAccessible(true); Map<String, AppletContext> cacheMap = (Map<String, AppletContext>) cacheMapField.get(cache); String[] keys = new String[cacheMap.size()]; cacheMap.keySet().toArray(keys); for (String key : keys) { cache.setDirty(key); } }
76. RandomAccessDataFileTests#close()
View license@Test public void close() throws Exception { this.file.getInputStream(ResourceAccess.PER_READ).read(); this.file.close(); Field filePoolField = RandomAccessDataFile.class.getDeclaredField("filePool"); filePoolField.setAccessible(true); Object filePool = filePoolField.get(this.file); Field filesField = filePool.getClass().getDeclaredField("files"); filesField.setAccessible(true); Queue<?> queue = (Queue<?>) filesField.get(filePool); assertThat(queue.size()).isEqualTo(0); }
77. FieldTypeTest#testFieldForeign()
View license@Test public void testFieldForeign() throws Exception { Field[] fields = ForeignParent.class.getDeclaredFields(); assertTrue(fields.length >= 3); @SuppressWarnings("unused") Field idField = fields[0]; Field nameField = fields[1]; Field bazField = fields[2]; FieldType fieldType = FieldType.createFieldType(connectionSource, ForeignParent.class.getSimpleName(), nameField, ForeignParent.class); assertEquals(nameField.getName(), fieldType.getColumnName()); assertEquals(DataType.STRING.getDataPersister(), fieldType.getDataPersister()); assertFalse(fieldType.isForeign()); assertEquals(0, fieldType.getWidth()); fieldType = FieldType.createFieldType(connectionSource, ForeignParent.class.getSimpleName(), bazField, ForeignParent.class); fieldType.configDaoInformation(connectionSource, ForeignParent.class); assertEquals(bazField.getName() + FieldType.FOREIGN_ID_FIELD_SUFFIX, fieldType.getColumnName()); // this is the type of the foreign object's id assertEquals(DataType.INTEGER.getDataPersister(), fieldType.getDataPersister()); assertTrue(fieldType.isForeign()); }
78. GenericClassTest#testGenericClasses2()
View license@Test public void testGenericClasses2() throws Exception { Field f1 = UserDao.class.getField("field1"); Field f2 = UserDao.class.getField("field2"); Field f3 = UserDao.class.getField("field3"); Field f4 = UserDao.class.getField("field4"); Assert.assertTrue(GenericsUtil.satisfiesDependency(false, false, f3.getGenericType(), f1.getGenericType())); Assert.assertTrue(GenericsUtil.satisfiesDependency(false, false, f4.getGenericType(), f1.getGenericType())); }
79. TestTreeBuilder#processTimeseriesMetaNullMetaOddNumTags()
View license@Test public void processTimeseriesMetaNullMetaOddNumTags() throws Exception { ArrayList<UIDMeta> tags = new ArrayList<UIDMeta>(4); tags.add(tagk1); //tags.add(tagv1); <-- whoops. This will process through but missing host tags.add(tagk2); tags.add(tagv2); Field tags_field = TSMeta.class.getDeclaredField("tags"); tags_field.setAccessible(true); tags_field.set(meta, tags); tags_field.setAccessible(false); treebuilder.processTimeseriesMeta(meta, false).joinUninterruptibly(); assertEquals(5, storage.numRows(TREE_TABLE)); assertEquals(2, storage.numColumns(TREE_TABLE, Branch.stringToId("00010036EBCB0001BECD000181A800000030"))); }
80. TestBranch#addChildNoLocalBranches()
View license@Test public void addChildNoLocalBranches() throws Exception { final Branch branch = buildTestBranch(tree); ; final Branch child = new Branch(tree.getTreeId()); Field branches = Branch.class.getDeclaredField("branches"); branches.setAccessible(true); branches.set(branch, null); branches.setAccessible(false); assertTrue(branch.addChild(child)); assertEquals(1, branch.getBranches().size()); assertEquals(2, branch.getLeaves().size()); }
81. T6410653#main()
View licensepublic static void main(String... args) throws Exception { File testSrc = new File(System.getProperty("test.src")); String source = new File(testSrc, "T6410653.java").getPath(); ClassLoader cl = ToolProvider.getSystemToolClassLoader(); Tool compiler = ToolProvider.getSystemJavaCompiler(); Class<?> log = Class.forName("com.sun.tools.javac.util.Log", true, cl); Field useRawMessages = log.getDeclaredField("useRawMessages"); useRawMessages.setAccessible(true); useRawMessages.setBoolean(null, true); ByteArrayOutputStream out = new ByteArrayOutputStream(); compiler.run(null, null, out, "-d", source, source); System.err.println(">>>" + out + "<<<"); useRawMessages.setBoolean(null, false); if (!out.toString().equals(String.format("%s%n%s%n", "javac: javac.err.file.not.directory", "javac.msg.usage"))) { throw new AssertionError(out); } System.out.println("Test PASSED. Running javac again to see localized output:"); compiler.run(null, null, System.out, "-d", source, source); }
82. DRBGS11n#main()
View licensepublic static void main(String[] args) throws Exception { DRBG d = new DRBG(null); Field f = DRBG.class.getDeclaredField("mdp"); f.setAccessible(true); MoreDrbgParameters mdp = (MoreDrbgParameters) f.get(d); // Corrupt the mech or capability fields inside DRBG#mdp. f = MoreDrbgParameters.class.getDeclaredField(args[0]); f.setAccessible(true); f.set(mdp, null); try { revive(d); } catch (IllegalArgumentException iae) { return; } throw new Exception("revive should fail"); }
83. bug6495920#thirdValidate()
View licensepublic void thirdValidate() throws Exception { Field key = BasicPopupMenuUI.class.getDeclaredField("MOUSE_GRABBER_KEY"); key.setAccessible(true); Object grabber = AppContext.getAppContext().get(key.get(null)); if (grabber == null) { throw new Exception("cannot find a mouse grabber in app's context"); } Field field = grabber.getClass().getDeclaredField("grabbedWindow"); field.setAccessible(true); Object window = field.get(grabber); if (window != null) { throw new Exception("interaction with GNOME is crippled"); } }
84. ForwardingTest#testStaticFieldForwarding()
View license@Test public void testStaticFieldForwarding() throws Exception { DynamicType.Loaded<Foo> loaded = implement(Foo.class, Forwarding.toStaticField(FOO, Foo.class)); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(1)); Foo instance = loaded.getLoaded().newInstance(); Field field = loaded.getLoaded().getDeclaredField(FOO); field.setAccessible(true); field.set(null, new Bar()); assertThat(instance.foo(), is(BAR)); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(Foo.class))); assertThat(instance, instanceOf(Foo.class)); }
85. JcrSystemUserValidatorTest#testIsValidWithEnforcementOfSystemUsersDisabled()
View license@Test public void testIsValidWithEnforcementOfSystemUsersDisabled() throws Exception { Field allowOnlySystemUsersField = jcrSystemUserValidator.getClass().getDeclaredField("allowOnlySystemUsers"); allowOnlySystemUsersField.setAccessible(true); allowOnlySystemUsersField.set(jcrSystemUserValidator, false); //testing null user assertFalse(jcrSystemUserValidator.isValid(null, null, null)); //testing not existing user (is considered valid here) assertTrue(jcrSystemUserValidator.isValid("notExisting", null, null)); // administrators group is not a user at all (but considered valid) assertTrue(jcrSystemUserValidator.isValid(GROUP_ADMINISTRATORS, null, null)); }
86. ForwardingTest#testInstanceFieldForwarding()
View license@Test public void testInstanceFieldForwarding() throws Exception { DynamicType.Loaded<Foo> loaded = implement(Foo.class, Forwarding.toInstanceField(FOO, Foo.class)); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(1)); Foo instance = loaded.getLoaded().newInstance(); Field field = loaded.getLoaded().getDeclaredField(FOO); field.setAccessible(true); field.set(instance, new Bar()); assertThat(instance.foo(), is(BAR)); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(Foo.class))); assertThat(instance, instanceOf(Foo.class)); }
87. IgniteSourceConnectorTest#afterTest()
View license/** {@inheritDoc} */ @Override protected void afterTest() throws Exception { herder.stop(); worker.stop(); kafkaBroker.shutdown(); grid.cache(CACHE_NAME).clear(); // reset cache name to overwrite task configurations. Field field = IgniteSourceTask.class.getDeclaredField("cacheName"); field.setAccessible(true); field.set(IgniteSourceTask.class, null); }
88. IgniteHadoopFileSystemClientSelfTest#switchHandlerErrorFlag()
View license/** * Set IGFS REST handler error flag to the given state. * * @param flag Flag state. * @throws Exception If failed. */ @SuppressWarnings("ConstantConditions") private void switchHandlerErrorFlag(boolean flag) throws Exception { IgfsProcessorAdapter igfsProc = ((IgniteKernal) grid(0)).context().igfs(); Map<String, IgfsContext> igfsMap = getField(igfsProc, "igfsCache"); IgfsServerManager srvMgr = F.first(igfsMap.values()).server(); Collection<IgfsServer> srvrs = getField(srvMgr, "srvrs"); IgfsServerHandler igfsHnd = getField(F.first(srvrs), "hnd"); Field field = igfsHnd.getClass().getDeclaredField("errWrite"); field.setAccessible(true); field.set(null, flag); }
89. LoadPredictorTest#createMockComputer()
View licenseprivate Computer createMockComputer(int nExecutors) throws Exception { Node n = mock(Node.class); Computer c = mock(Computer.class); when(c.getNode()).thenReturn(n); List executors = new CopyOnWriteArrayList(); for (int i = 0; i < nExecutors; i++) { Executor e = mock(Executor.class); when(e.isIdle()).thenReturn(true); when(e.getOwner()).thenReturn(c); executors.add(e); } Field f = Computer.class.getDeclaredField("executors"); f.setAccessible(true); f.set(c, executors); when(c.getExecutors()).thenReturn(executors); return c; }
90. LabelExpressionTest#dataCompatibilityWithHostNameWithWhitespace()
View license@Test public void dataCompatibilityWithHostNameWithWhitespace() throws Exception { DumbSlave slave = new DumbSlave("abc def (xyz) : test", "dummy", j.createTmpDir().getPath(), "1", Mode.NORMAL, "", j.createComputerLauncher(null), RetentionStrategy.NOOP, Collections.EMPTY_LIST); j.jenkins.addNode(slave); FreeStyleProject p = j.createFreeStyleProject(); p.setAssignedLabel(j.jenkins.getLabel("abc def")); assertEquals("abc def", p.getAssignedLabel().getName()); assertEquals("\"abc def\"", p.getAssignedLabel().getExpression()); // expression should be persisted, not the name Field f = AbstractProject.class.getDeclaredField("assignedNode"); f.setAccessible(true); assertEquals("\"abc def\"", f.get(p)); // but if the name is set, we'd still like to parse it f.set(p, "a:b c"); assertEquals("a:b c", p.getAssignedLabel().getName()); }
91. BeanDeploymentArchiveAgent#defineManagedBean()
View license@SuppressWarnings({ "rawtypes", "unchecked" }) private void defineManagedBean(BeanManagerImpl beanManager, EnhancedAnnotatedType eat) throws Exception { BeanAttributes attributes = BeanAttributesFactory.forBean(eat, beanManager); ManagedBean<?> bean = ManagedBean.of(attributes, eat, beanManager); Field field = beanManager.getClass().getDeclaredField("beanSet"); field.setAccessible(true); field.set(beanManager, Collections.synchronizedSet(new HashSet<Bean<?>>())); // TODO: beanManager.addBean(bean); beanManager.getBeanResolver().clear(); bean.initializeAfterBeanDiscovery(); }
92. TestRecoverableZooKeeper#testSetDataVersionMismatchInLoop()
View license@Test public void testSetDataVersionMismatchInLoop() throws Exception { String znode = "/hbase/unassigned/9af7cfc9b15910a0b3d714bf40a3248f"; Configuration conf = TEST_UTIL.getConfiguration(); Properties properties = ZKConfig.makeZKProps(conf); ZooKeeperWatcher zkw = new ZooKeeperWatcher(conf, "testSetDataVersionMismatchInLoop", abortable, true); String ensemble = ZKConfig.getZKQuorumServersString(properties); RecoverableZooKeeper rzk = ZKUtil.connect(conf, ensemble, zkw); rzk.create(znode, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); rzk.setData(znode, "OPENING".getBytes(), 0); Field zkField = RecoverableZooKeeper.class.getDeclaredField("zk"); zkField.setAccessible(true); int timeout = conf.getInt(HConstants.ZK_SESSION_TIMEOUT, HConstants.DEFAULT_ZK_SESSION_TIMEOUT); ZookeeperStub zkStub = new ZookeeperStub(ensemble, timeout, zkw); zkStub.setThrowExceptionInNumOperations(1); zkField.set(rzk, zkStub); byte[] opened = "OPENED".getBytes(); rzk.setData(znode, opened, 1); byte[] data = rzk.getData(znode, false, new Stat()); assertTrue(Bytes.equals(opened, data)); }
93. ReflectionHelper#setStaticFinalField()
View licensepublic static void setStaticFinalField(Field field, Object value) throws NoSuchFieldException, IllegalAccessException { // ?? public ?? field.setAccessible(true); // ?modifiers????final,???????? Field modifiersField = Field.class.getDeclaredField(MODIFIERS_FIELD); modifiersField.setAccessible(true); int modifiers = modifiersField.getInt(field); // ?? final ??? modifiers &= ~Modifier.FINAL; modifiersField.setInt(field, modifiers); FieldAccessor fa = reflection.newFieldAccessor(field, false); fa.set(null, value); }
94. OauthRepositoryTest#assertHasIdAndMatches()
View licensestatic void assertHasIdAndMatches(Object loaded, Object unpersistentExpected) throws NoSuchFieldException, IllegalAccessException { assertThat(loaded, is(Matchers.<Object>instanceOf(unpersistentExpected.getClass()))); Field id = loaded.getClass().getDeclaredField("id"); id.setAccessible(true); assertThat((Long) id.get(loaded), is(greaterThan(0l))); for (Field field : loaded.getClass().getDeclaredFields()) { if (field.getName().equals("id")) { continue; } field.setAccessible(true); assertThat(field.get(loaded), is(field.get(unpersistentExpected))); } }
95. RecordingSimpleLogger#logLevel()
View license/** * Resets {@link org.slf4j.impl.SimpleLogger} to the new log level. */ RecordingSimpleLogger logLevel(String logLevel) throws Exception { System.setProperty(SHOW_THREAD_NAME_KEY, "false"); System.setProperty(DEFAULT_LOG_LEVEL_KEY, logLevel); Field field = SimpleLogger.class.getDeclaredField("INITIALIZED"); field.setAccessible(true); field.set(null, false); Method method = SimpleLoggerFactory.class.getDeclaredMethod("reset"); method.setAccessible(true); method.invoke(LoggerFactory.getILoggerFactory()); return this; }
96. TestBean#getByteBuffer()
View licenseprivate static ByteBuffer getByteBuffer(Object deser) throws IllegalAccessException { Field[] fields = deser.getClass().getDeclaredFields(); Field th0 = null; for (int i = 0; i < fields.length; i++) { Field field = fields[i]; if (field.getName().indexOf("this$0") >= 0) th0 = field; } th0.setAccessible(true); TestBean this0 = (TestBean) th0.get(deser); return ((AnImpl) this0.factory.a).p; }
97. JpaConverterTest#setup()
View license@Before public void setup() throws NoSuchFieldException, IllegalAccessException { ModelConverter personConverter = createMock(ModelConverter.class); expect(personConverter.getSourceType()).andReturn(Person.class).anyTimes(); expect(personConverter.convert(isA(PersonImpl.class))).andReturn(new JpaPerson()); replay(personConverter); ModelConverter addressConverter = createMock(ModelConverter.class); expect(addressConverter.getSourceType()).andReturn(Address.class).anyTimes(); expect(addressConverter.convert(isA(AddressImpl.class))).andReturn(new JpaAddress()); replay(addressConverter); ModelConverter pageLayoutConverter = createMock(ModelConverter.class); expect(pageLayoutConverter.getSourceType()).andReturn(Address.class).anyTimes(); expect(pageLayoutConverter.convert(isA(PageLayout.class))).andReturn(new JpaPageLayout()); replay(pageLayoutConverter); List<ModelConverter> converters = new ArrayList<ModelConverter>(); converters.add(personConverter); converters.add(addressConverter); this.converters = converters; Field instance = JpaConverter.class.getDeclaredField("instance"); instance.setAccessible(true); instance.set(null, null); }
98. ExtendedStackTraceHotSpot#guessBacktraceFieldOffset()
View licenseprivate static long guessBacktraceFieldOffset() { Field[] fs = Throwable.class.getDeclaredFields(); Field second = null; for (Field f : fs) { if (getSlot(f) == 2) { second = f; break; } } if (second == null) throw new IllegalStateException(); long secondOffest = UNSAFE.objectFieldOffset(second); if (secondOffest == 16) // compressed oops return 12; if (secondOffest == 24) // no compressed oops return 16; else // unfamiliar throw new IllegalStateException("secondOffset: " + secondOffest); }
99. ReflectionUtil#getValueFromField()
View license/** * Gets the value from field. * * @param field the field * @param target the target * @return the value from field * @throws NoSuchFieldException the no such field exception * @throws SecurityException the security exception * @throws IllegalAccessException the illegal access exception */ private static Object getValueFromField(final String field, final Object target) throws NoSuchFieldException, SecurityException, IllegalAccessException { if (target == null) { return null; } Field f = null; try { f = target.getClass().getDeclaredField(field); } catch (NoSuchFieldException n) { if (target.getClass().getSuperclass() != null) { f = target.getClass().getSuperclass().getDeclaredField(field); } } f.setAccessible(true); return f.get(target); }
100. GenericTypeTest#testGenericType()
View license@Test public void testGenericType() throws Exception { GenericType<List<String>> stringListType = new GenericType<List<String>>() { }; System.out.println("type: " + stringListType.getType()); System.out.println("raw type: " + stringListType.getRawType()); PKCS7SignatureInput<List<String>> input = new PKCS7SignatureInput<List<String>>(); input.setType(stringListType); Field field = PKCS7SignatureInput.class.getDeclaredField("entity"); field.setAccessible(true); List<String> list = new ArrayList<String>(); list.add("abc"); field.set(input, list); List<String> list2 = input.getEntity(stringListType, null); System.out.println("list2: " + list2); Assert.assertEquals(list, list2); }