java.lang.reflect.Field

Here are the examples of the java api class java.lang.reflect.Field taken from open source projects.

1. KettleEnvironmentTest#resetKettleEnvironmentInitializationFlag()

Project: pentaho-kettle
File: KettleEnvironmentTest.java
private 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()

Project: wss4j
File: AbstractTestBase.java
public 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()

Project: wss4j
File: AbstractTestBase.java
public 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. EasyFingerprintTest#assumeApiLevel()

Project: EasyFingerprint
File: EasyFingerprintTest.java
private 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. ApiLevelTestSuite#assumeApiLevel()

Project: PermissionsDispatcher
File: ApiLevelTestSuite.java
private 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. ResourceResolverWithVanityBloomFilterTest#setMaxCachedVanityPathEntries()

Project: sling
File: ResourceResolverWithVanityBloomFilterTest.java
private 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);
}

7. WhiteboardHandlerTest#setUp()

Project: sling
File: WhiteboardHandlerTest.java
@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);
}

8. InternalLoggerTest#prepare()

Project: ApplicationInsights-Java
File: InternalLoggerTest.java
@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);
}

9. CleanWorkingDirectoryActionTest#setUp()

Project: continuum
File: CleanWorkingDirectoryActionTest.java
@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);
}

10. AbstractLoadBundleTest#setupStream()

Project: logging-log4j2
File: AbstractLoadBundleTest.java
private 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;
}

11. FieldTests#testDoublePrimitiveLegalUse()

Project: collide
File: FieldTests.java
/////////////////////////////////////////////////
///////////////////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);
}

12. ListTag#toNMS()

Project: NBTLibrary
File: ListTag.java
@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;
}

13. AbstractTestBase#changeValueOfMaximumAllowedDecompressedBytes()

Project: wss4j
File: AbstractTestBase.java
public 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;
}

14. AbstractTestBase#changeValueOfMaximumAllowedTransformsPerReference()

Project: wss4j
File: AbstractTestBase.java
public 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;
}

15. AbstractTestBase#changeValueOfMaximumAllowedReferencesPerManifest()

Project: wss4j
File: AbstractTestBase.java
public 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;
}

16. AbstractTestBase#changeValueOfMaximumAllowedDecompressedBytes()

Project: wss4j
File: AbstractTestBase.java
public 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;
}

17. AbstractTestBase#changeValueOfMaximumAllowedTransformsPerReference()

Project: wss4j
File: AbstractTestBase.java
public 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;
}

18. AbstractTestBase#changeValueOfMaximumAllowedReferencesPerManifest()

Project: wss4j
File: AbstractTestBase.java
public 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;
}

19. ReplicationTestBase#assertCookieInterceptorPresent()

Project: sync-android
File: ReplicationTestBase.java
protected 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);
}

20. FilterChainResolverProviderTest#testGet()

Project: shiro
File: FilterChainResolverProviderTest.java
@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));
}

21. TestUtils#changeValueOfMaximumAllowedXMLStructureDepth()

Project: santuario-java
File: TestUtils.java
public 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;
}

22. TestUtils#changeValueOfMaximumAllowedTransformsPerReference()

Project: santuario-java
File: TestUtils.java
public 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#changeValueOfMaximumAllowedReferencesPerManifest()

Project: santuario-java
File: TestUtils.java
public 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;
}

24. MQTTTest#setUp()

Project: activemq-artemis
File: MQTTTest.java
@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();
}

25. ResolveContextTest#createActivator()

Project: aries
File: ResolveContextTest.java
private 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;
}

26. ResolveContextTest#createActivator()

Project: apache-aries
File: ResolveContextTest.java
private 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;
}

27. FieldTests#testFloatPrimitiveLegalUse()

Project: collide
File: FieldTests.java
/////////////////////////////////////////////////
////////////////////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);
}

28. MessagingControllerTest#setAccountsInPreferences()

Project: k-9
File: MessagingControllerTest.java
private 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);
}

29. ReflectUtilTest#testGetFieldConcreteType()

Project: jodd
File: ReflectUtilTest.java
@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));
}

30. GitVersionTest#assertEqualVersions()

Project: intellij-community
File: GitVersionTest.java
// 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);
}

31. IndexMergerTest#assertDimCompression()

Project: druid
File: IndexMergerTest.java
private 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);
}

32. DatabaseTest#testDatabaseRemovesUnbalancedBlocksOnStartup()

Project: concourse
File: DatabaseTest.java
@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());
}

33. GhprbTestUtil#setFinal()

Project: ghprb
File: GhprbTestUtil.java
static 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);
}

34. TestUtils#fixAdapterForTesting()

Project: Chateau
File: TestUtils.java
/**
     * 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;
}

35. TestBoneCPConnectionProvider#testGetConnection()

Project: bonecp
File: TestBoneCPConnectionProvider.java
/**
	 * 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);
}

36. TestBoneCP#testJMXUnRegisterWithName()

Project: bonecp
File: TestBoneCP.java
/** 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. GenericClassTest#testGenericClasses()

Project: openwebbeans
File: GenericClassTest.java
@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()));
}

38. ValueHandlerTest#testApplyAnonymousPrivateFinalInt()

Project: openjdk
File: ValueHandlerTest.java
@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);
}

39. MapEntriesTest#test_getVanityPaths_1()

Project: sling
File: MapEntriesTest.java
@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());
}

40. RemotingServiceImplTest#testInterceptorsAreAddedOnCreationOfServiceRegistry()

Project: activemq-artemis
File: RemotingServiceImplTest.java
/**
    * 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)));
}

41. RemotingServiceImplTest#testSetInterceptorsAddsBothInterceptorsFromConfigAndServiceRegistry()

Project: activemq-artemis
File: RemotingServiceImplTest.java
/**
    * 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)));
}

42. ClientThreadPoolsTest#testThreadPoolInjection()

Project: activemq-artemis
File: ClientThreadPoolsTest.java
@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);
}

43. TestConnectionPartition#testGetCreatedConnections()

Project: bonecp
File: TestConnectionPartition.java
/**
	 * @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);
}

44. HgVersionTest#assertEqualVersions()

Project: intellij-community
File: HgVersionTest.java
private 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);
}

45. BeanUtils#setFieldValue()

Project: lemon
File: BeanUtils.java
public 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);
}

46. ExtendsIT#constructorHasParentsProperties()

Project: jsonschema2pojo
File: ExtendsIT.java
@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")));
}

47. HudsonTest#invalidPrimaryView()

Project: Jenkins2
File: HudsonTest.java
/**
     * 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));
}

48. bug6495920#thirdValidate()

Project: jdk7u-jdk
File: bug6495920.java
public 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");
    }
}

49. CassandraUtils#deepType2tuple()

Project: deep-spark
File: CassandraUtils.java
/**
     * 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);
}

50. AopTargetUtils#getJdkDynamicProxyTargetObject()

Project: cyfm
File: AopTargetUtils.java
private 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;
}

51. AopTargetUtils#getCglibProxyTargetObject()

Project: cyfm
File: AopTargetUtils.java
private 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;
}

52. StatefulRunnableTest#setUp()

Project: fresco
File: StatefulRunnableTest.java
@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);
}

53. T6410653#main()

Project: error-prone-javac
File: T6410653.java
public 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);
}

54. ObjectBooleanHashMapTestCase#newMap()

Project: eclipse-collections
File: ObjectBooleanHashMapTestCase.java
@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);
}

55. ObjectBooleanHashMapTestCase#newWithInitialCapacity()

Project: eclipse-collections
File: ObjectBooleanHashMapTestCase.java
@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()

Project: eclipse-collections
File: ObjectBooleanHashMapTestCase.java
@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()

Project: drools
File: KieModuleRepoTest.java
private 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()

Project: collide
File: FieldTests.java
/////////////////////////////////////////////////
///////////////////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()

Project: collide
File: FieldTests.java
/////////////////////////////////////////////////
////////////////////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()

Project: camel
File: ReadingBuilder.java
public 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()

Project: byte-buddy
File: ClassFileLocatorAgentBasedTest.java
@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. HudsonTest#invalidPrimaryView()

Project: hudson
File: HudsonTest.java
/**
     * 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));
}

63. Arguments#getFields()

Project: h2o-2
File: Arguments.java
/**
   * 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;
}

64. ObjectBooleanHashMapTestCase#newMap()

Project: gs-collections
File: ObjectBooleanHashMapTestCase.java
@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);
}

65. ObjectBooleanHashMapTestCase#newWithInitialCapacity()

Project: gs-collections
File: ObjectBooleanHashMapTestCase.java
@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());
}

66. ObjectBooleanHashMapTestCase#defaultInitialCapacity()

Project: gs-collections
File: ObjectBooleanHashMapTestCase.java
@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());
}

67. ProvidersRegistryTest#testProtectionModel()

Project: wink
File: ProvidersRegistryTest.java
/**
     * 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);
}

68. ProvidersRegistry11Test#testProvidesAnnotationParsing()

Project: wink
File: ProvidersRegistry11Test.java
/**
     * 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());
}

69. ProvidersRegistry11Test#testConsumesAnnotationParsing()

Project: wink
File: ProvidersRegistry11Test.java
/**
     * 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()

Project: wasabi
File: EventLogServiceTest.java
@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()

Project: vaadin
File: TreeTest.java
@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()

Project: vaadin
File: MethodPropertyMemoryConsumptionTest.java
@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()

Project: Resteasy
File: ResteasyProviderFactoryTest.java
/**
	 * 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()

Project: NBTLibrary
File: ListTag.java
@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()

Project: spring-data-graph
File: CleanContextCacheTestExecutionListener.java
@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()

Project: spring-boot
File: RandomAccessDataFileTests.java
@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()

Project: ormlite-core
File: FieldTypeTest.java
@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()

Project: openwebbeans
File: GenericClassTest.java
@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()

Project: opentsdb
File: TestTreeBuilder.java
@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()

Project: opentsdb
File: TestBranch.java
@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()

Project: openjdk
File: T6410653.java
public 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()

Project: openjdk
File: DRBGS11n.java
public 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()

Project: openjdk
File: bug6495920.java
public 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. HealthCheckResourceTest#buildAdminResourcesContainer()

Project: karyon
File: HealthCheckResourceTest.java
private AdminResourcesContainer buildAdminResourcesContainer(final HealthCheckHandler healthCheckHandler) throws Exception {
    AdminResourcesContainer container = new AdminResourcesContainer();
    final Field injectorField = AdminResourcesContainer.class.getDeclaredField("appInjector");
    final Injector appInjector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            bind(HealthCheckHandler.class).toInstance(healthCheckHandler);
        }
    });
    injectorField.setAccessible(true);
    injectorField.set(container, appInjector);
    return container;
}

85. HealthCheckResourceTest#buildAdminResourcesContainer()

Project: karyon
File: HealthCheckResourceTest.java
private AdminResourcesContainer buildAdminResourcesContainer(final HealthCheckHandler healthCheckHandler) throws Exception {
    AdminResourcesContainer container = new AdminResourcesContainer();
    final Field injectorField = AdminResourcesContainer.class.getDeclaredField("appInjector");
    final Injector appInjector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            bind(HealthCheckHandler.class).toInstance(healthCheckHandler);
            bind(HealthCheckInvocationStrategy.class).to(SyncHealthCheckInvocationStrategy.class);
        }
    });
    injectorField.setAccessible(true);
    injectorField.set(container, appInjector);
    return container;
}

86. JacksonViewIT#jsonViewTest()

Project: jsonschema2pojo
File: JacksonViewIT.java
private Annotation jsonViewTest(String annotationStyle, Class<? extends Annotation> annotationType) throws ClassNotFoundException, NoSuchFieldException {
    ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/views/views.json", "com.example", config("annotationStyle", annotationStyle));
    Class<?> generatedType = resultsClassLoader.loadClass("com.example.Views");
    Field fieldInView = generatedType.getDeclaredField("inView");
    assertThat(fieldInView.getAnnotation(annotationType), notNullValue());
    Field fieldNotInView = generatedType.getDeclaredField("notInView");
    assertThat(fieldNotInView.getAnnotation(annotationType), nullValue());
    return fieldInView.getAnnotation(annotationType);
}

87. RingBundlerTestLockless2#testSendWithNULL_MSG()

Project: JGroups
File: RingBundlerTestLockless2.java
public void testSendWithNULL_MSG() throws Exception {
    RingBufferBundlerLockless2 bundler = new RingBufferBundlerLockless2(16);
    RingBundlerTest.MockTransport transport = new RingBundlerTest.MockTransport();
    bundler.init(transport);
    Message[] buf = (Message[]) Util.getField(Util.getField(RingBufferBundlerLockless2.class, "buf"), bundler);
    Field write_index_field = Util.getField(RingBufferBundlerLockless2.class, "write_index");
    write_index_field.setAccessible(true);
    buf[1] = buf[2] = RingBufferBundlerLockless2.NULL_MSG;
    buf[3] = null;
    write_index_field.set(bundler, 4);
    System.out.println("bundler = " + bundler);
    assert bundler.size() == 3;
    bundler._readMessages();
    System.out.println("bundler = " + bundler);
    assert bundler.writeIndex() == 4;
    assert bundler.readIndex() == 2;
    assert bundler.size() == 1;
    buf[3] = new Message(null);
    bundler._readMessages();
    assert bundler.readIndex() == 3;
    assert bundler.size() == 0;
}

88. LoadPredictorTest#createMockComputer()

Project: Jenkins2
File: LoadPredictorTest.java
private 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;
}

89. LabelExpressionTest#dataCompatibilityWithHostNameWithWhitespace()

Project: Jenkins2
File: LabelExpressionTest.java
@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());
}

90. DexMakerTest#testDeclareInstanceFields()

Project: dexmaker
File: DexMakerTest.java
public void testDeclareInstanceFields() throws Exception {
    /*
         * class Generated {
         *   public int a;
         *   protected Object b;
         * }
         */
    dexMaker.declare(GENERATED.getField(TypeId.INT, "a"), PUBLIC, null);
    dexMaker.declare(GENERATED.getField(TypeId.OBJECT, "b"), PROTECTED, null);
    addDefaultConstructor();
    Class<?> generatedClass = generateAndLoad();
    Object instance = generatedClass.newInstance();
    Field a = generatedClass.getField("a");
    assertEquals(int.class, a.getType());
    assertEquals(0, a.get(instance));
    Field b = generatedClass.getDeclaredField("b");
    assertEquals(Object.class, b.getType());
    b.setAccessible(true);
    assertEquals(null, b.get(instance));
}

91. DexMakerTest#testDeclareStaticFields()

Project: dexmaker
File: DexMakerTest.java
public void testDeclareStaticFields() throws Exception {
    /*
         * class Generated {
         *   public static int a;
         *   protected static Object b;
         * }
         */
    dexMaker.declare(GENERATED.getField(TypeId.INT, "a"), PUBLIC | STATIC, 3);
    dexMaker.declare(GENERATED.getField(TypeId.OBJECT, "b"), PROTECTED | STATIC, null);
    Class<?> generatedClass = generateAndLoad();
    Field a = generatedClass.getField("a");
    assertEquals(int.class, a.getType());
    assertEquals(3, a.get(null));
    Field b = generatedClass.getDeclaredField("b");
    assertEquals(Object.class, b.getType());
    b.setAccessible(true);
    assertEquals(null, b.get(null));
}

92. TestGoldenGateEventProducer#run_with_mock_timer()

Project: databus
File: TestGoldenGateEventProducer.java
private void run_with_mock_timer(GoldenGateEventProducer gg) throws NoSuchFieldException, IllegalAccessException {
    RateControl rc = gg.getRateControl();
    MockRateMonitor mrm = new MockRateMonitor("mock");
    mrm.setNanoTime(0L);
    mrm.start();
    Field field = rc.getClass().getDeclaredField("_ra");
    field.setAccessible(true);
    field.set(rc, mrm);
}

93. WorkflowSuiteContextShutdownTest#closeContext()

Project: community-edition
File: WorkflowSuiteContextShutdownTest.java
public static void closeContext() throws NoSuchFieldException, IllegalAccessException, InterruptedException {
    ApplicationContextHelper.closeApplicationContext();
    // Null out the static Workflow engine field
    Field engineField = WorkflowTaskInstance.class.getDeclaredField("jbpmEngine");
    engineField.setAccessible(true);
    engineField.set(null, null);
    Thread.yield();
    Thread.sleep(25);
    Thread.yield();
}

94. ServerConfigurationBeanTest#testDestroyWhenThreadPoolIsNull()

Project: community-edition
File: ServerConfigurationBeanTest.java
/**
     * ALF-19669: NullPointerException when stopping fileServers subsystem
     */
@Test
public void testDestroyWhenThreadPoolIsNull() throws Exception {
    // Ensure threadPool is null
    Field threadPoolField = serverConf.getClass().getDeclaredField("threadPool");
    threadPoolField.setAccessible(true);
    threadPoolField.set(serverConf, null);
    assertNull("Test precondition failure - threadPool is not null", threadPoolField.get(serverConf));
    try {
        serverConf.destroy();
    } catch (NullPointerException error) {
        fail("Unable to cleanly destroy " + serverConf.getClass().getSimpleName() + " instance.");
    }
}

95. ClassLoaderContextSelectorTest#testMultipleClassLoaders()

Project: logging-log4j2
File: ClassLoaderContextSelectorTest.java
@Test
public void testMultipleClassLoaders() throws Exception {
    final Class<?> logging1 = loader1.loadClass(PKG + ".a.Logging1");
    final Field field1 = logging1.getDeclaredField("logger");
    final Logger logger1 = (Logger) ReflectionUtil.getStaticFieldValue(field1);
    assertNotNull(logger1);
    final Class<?> logging2 = loader2.loadClass(PKG + ".b.Logging2");
    final Field field2 = logging2.getDeclaredField("logger");
    final Logger logger2 = (Logger) ReflectionUtil.getStaticFieldValue(field2);
    assertNotNull(logger2);
    final Class<?> logging3 = loader3.loadClass(PKG + ".c.Logging3");
    final Field field3 = logging3.getDeclaredField("logger");
    final Logger logger3 = (Logger) ReflectionUtil.getStaticFieldValue(field3);
    assertNotNull(logger3);
    assertNotSame(logger1.getContext(), logger2.getContext());
    assertNotSame(logger1.getContext(), logger3.getContext());
    assertNotSame(logger2.getContext(), logger3.getContext());
}

96. BeanUtils#getFieldValue()

Project: lemon
File: BeanUtils.java
public static Object getFieldValue(Object object, String fieldName, boolean targetAccessible) throws NoSuchFieldException, IllegalAccessException {
    Assert.notNull(object);
    Assert.hasText(fieldName);
    Field field = getDeclaredField(object, fieldName);
    boolean accessible = field.isAccessible();
    field.setAccessible(targetAccessible);
    Object result = field.get(object);
    field.setAccessible(accessible);
    return result;
}

97. ResultIterator#getPartitionKeyField()

Project: Kundera
File: ResultIterator.java
/**
     * Will return partition key part of composite id.
     *
     * @return the partition key field
     */
private Field getPartitionKeyField() {
    Field[] embeddedFields = entityMetadata.getIdAttribute().getBindableJavaType().getDeclaredFields();
    Field field = null;
    for (Field embeddedField : embeddedFields) {
        if (!ReflectUtils.isTransientOrStatic(embeddedField)) {
            field = embeddedField;
            break;
        }
    }
    return field;
}

98. MetaModelBuilderTest#combinedTest()

Project: Kundera
File: MetaModelBuilderTest.java
/**
     * Combined test.
     * 
     * @param <X>
     *            the generic type
     * @param <T>
     *            the generic type
     */
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public <X extends Class, T extends Object> void combinedTest() {
    X clazz = (X) SingularEntity.class;
    // MetaModelBuilder builder = new MetaModelBuilder<X, T>();
    builder.process(clazz);
    Field[] field = SingularEntity.class.getDeclaredFields();
    for (Field f : field) {
        builder.construct(SingularEntity.class, f);
    }
    clazz = (X) SingularEntityEmbeddable.class;
    builder.process(clazz);
    field = SingularEntityEmbeddable.class.getDeclaredFields();
    for (Field f : field) {
        builder.construct(SingularEntityEmbeddable.class, f);
    }
    Map<Class<?>, AbstractManagedType<?>> managedTypes = getManagedTypes();
    Assert.assertEquals(2, managedTypes.size());
}

99. FieldTests#testShortPrimitiveLegalUse()

Project: collide
File: FieldTests.java
/////////////////////////////////////////////////
/////////////////Shorts//////////////////////////
/////////////////////////////////////////////////
@Test
public void testShortPrimitiveLegalUse() throws Exception {
    assertNotNull(primitives);
    Field f = PRIMITIVE_CLASS.getField("s");
    assertEquals(0, f.getShort(primitives));
    assertEquals(0, ((Short) f.get(primitives)).shortValue());
    f.set(primitives, (short) 1);
    assertEquals(1, f.getShort(primitives));
    assertEquals(1, ((Short) f.get(primitives)).shortValue());
    f.set(primitives, new Byte((byte) 1));
}

100. AutomaticBeanTest#testSetupInvalidChildFromBaseClass()

Project: checkstyle
File: AutomaticBeanTest.java
@Test
public void testSetupInvalidChildFromBaseClass() throws Exception {
    final TestBean testBean = new TestBean();
    final DefaultConfiguration parentConf = new DefaultConfiguration("parentConf");
    final DefaultConfiguration childConf = new DefaultConfiguration("childConf");
    final Field field = AutomaticBean.class.getDeclaredField("configuration");
    field.setAccessible(true);
    field.set(testBean, parentConf);
    try {
        testBean.setupChild(childConf);
        fail("expecting checkstyle exception");
    } catch (CheckstyleException ex) {
        assertEquals("expected exception", "childConf is not allowed as a child in parentConf", ex.getMessage());
    }
}