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()

View license
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
Source File: AbstractTestBase.java
View license
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
Source File: AbstractTestBase.java
View license
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()

View license
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()

View license
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. 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);
}

7. FieldTests#testDoublePrimitiveLegalUse()

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

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. AbstractLoadBundleTest#setupStream()

View license
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;
}

10. WhiteboardHandlerTest#setUp()

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

12. MQTTTest#setUp()

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

13. ResolveContextTest#createActivator()

View license
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;
}

14. ResolveContextTest#createActivator()

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

15. FieldTests#testFloatPrimitiveLegalUse()

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

16. DatabaseTest#testDatabaseRemovesUnbalancedBlocksOnStartup()

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

17. IndexMergerTest#assertDimCompression()

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

18. 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);
}

19. ReflectUtilTest#testGetFieldConcreteType()

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

20. MessagingControllerTest#setAccountsInPreferences()

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

21. ListTag#toNMS()

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

22. TestUtils#changeValueOfMaximumAllowedReferencesPerManifest()

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

23. TestUtils#changeValueOfMaximumAllowedTransformsPerReference()

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

24. TestUtils#changeValueOfMaximumAllowedXMLStructureDepth()

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

25. 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));
}

26. ReplicationTestBase#assertCookieInterceptorPresent()

View license
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);
}

27. AbstractTestBase#changeValueOfMaximumAllowedReferencesPerManifest()

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

28. AbstractTestBase#changeValueOfMaximumAllowedTransformsPerReference()

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

29. AbstractTestBase#changeValueOfMaximumAllowedDecompressedBytes()

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

30. AbstractTestBase#changeValueOfMaximumAllowedReferencesPerManifest()

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

31. AbstractTestBase#changeValueOfMaximumAllowedTransformsPerReference()

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

32. AbstractTestBase#changeValueOfMaximumAllowedDecompressedBytes()

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

33. TestBoneCP#testJMXUnRegisterWithName()

Project: bonecp
Source File: TestBoneCP.java
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);
}

34. TestBoneCPConnectionProvider#testGetConnection()

View license
/**
	 * Test method for [email protected] [email protected]()}.
	 * @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);
}

35. TestUtils#fixAdapterForTesting()

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

36. GhprbTestUtil#setFinal()

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

37. ValueHandlerTest#testApplyAnonymousPrivateFinalInt()

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

38. GenericClassTest#testGenericClasses()

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

39. MapEntriesTest#test_getVanityPaths_1()

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

40. 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);
}

41. 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)));
}

42. 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)));
}

43. TestConnectionPartition#testGetCreatedConnections()

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

44. 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));
}

45. ReadingBuilder#copy()

Project: camel
Source File: ReadingBuilder.java
View license
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;
}

46. FieldTests#testIntPrimitiveLegalUse()

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

47. FieldTests#testLongPrimitiveLegalUse()

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

48. AopTargetUtils#getCglibProxyTargetObject()

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

49. AopTargetUtils#getJdkDynamicProxyTargetObject()

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

50. CassandraUtils#deepType2tuple()

Project: deep-spark
Source File: CassandraUtils.java
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. KieModuleRepoTest#createMockKieContainer()

Project: drools
Source File: KieModuleRepoTest.java
View license
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;
}

52. 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());
}

53. 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());
}

54. 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);
}

55. T6410653#main()

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

56. StatefulRunnableTest#setUp()

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

57. 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());
}

58. 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());
}

59. 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);
}

60. Arguments#getFields()

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

61. HudsonTest#invalidPrimaryView()

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

62. HgVersionTest#assertEqualVersions()

View license
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);
}

63. bug6495920#thirdValidate()

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

64. HudsonTest#invalidPrimaryView()

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

65. ExtendsIT#constructorHasParentsProperties()

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

66. BeanUtils#setFieldValue()

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

67. ListTag#fromNMS()

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

68. bug6495920#thirdValidate()

Project: openjdk
Source File: bug6495920.java
View license
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");
    }
}

69. DRBGS11n#main()

Project: openjdk
Source File: DRBGS11n.java
View license
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");
}

70. T6410653#main()

Project: openjdk
Source File: T6410653.java
View license
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);
}

71. TestBranch#addChildNoLocalBranches()

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

72. TestTreeBuilder#processTimeseriesMetaNullMetaOddNumTags()

Project: opentsdb
Source File: TestTreeBuilder.java
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")));
}

73. GenericClassTest#testGenericClasses2()

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

74. FieldTypeTest#testFieldForeign()

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

75. 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);
}

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. 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);
    }
}

78. 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);
}

79. TreeTest#testRemoveExpandedItemsOnContainerChange()

Project: vaadin
Source File: TreeTest.java
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);
}

80. EventLogServiceTest#testStartup()

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

81. ProvidersRegistry11Test#testConsumesAnnotationParsing()

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

82. ProvidersRegistry11Test#testProvidesAnnotationParsing()

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

83. ProvidersRegistryTest#testProtectionModel()

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

84. AriesApplicationManagerImplTest#createApplication()

View license
private AriesApplication createApplication(String fileName) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, ManagementException, ResolverException {
    // This next block is a very long winded way of constructing a BundleInfoImpl
    // against the existing (BundleManifest bm, String location) constructor. If we 
    // find we need a String-based BundleInfoImpl constructor for other reasons, 
    // we could change to using it here. 
    Set<BundleInfo> nextResolverResult = new HashSet<BundleInfo>();
    String persistenceLibraryLocation = "../src/test/resources/bundles/repository/a.handy.persistence.library.jar";
    File persistenceLibrary = new File(persistenceLibraryLocation);
    BundleManifest mf = BundleManifest.fromBundle(persistenceLibrary);
    BundleInfo resolvedPersistenceLibrary = new SimpleBundleInfo(mf, persistenceLibraryLocation);
    Field v = SimpleBundleInfo.class.getDeclaredField("_version");
    v.setAccessible(true);
    v.set(resolvedPersistenceLibrary, new Version("1.1.0"));
    nextResolverResult.add(resolvedPersistenceLibrary);
    _resolver.setNextResult(nextResolverResult);
    IDirectory testEba = FileSystem.getFSRoot(new File(fileName));
    AriesApplication app = _appMgr.createApplication(testEba);
    app = _appMgr.resolve(app);
    return app;
}

85. ClientWeavingHookGenericCapabilityTest#mockSpiFlyBundle()

View license
private Bundle mockSpiFlyBundle(String bsn, Version version, Bundle... bundles) throws Exception {
    Bundle spiFlyBundle = EasyMock.createMock(Bundle.class);
    BundleContext spiFlyBundleContext = EasyMock.createMock(BundleContext.class);
    EasyMock.expect(spiFlyBundleContext.getBundle()).andReturn(spiFlyBundle).anyTimes();
    List<Bundle> allBundles = new ArrayList<Bundle>(Arrays.asList(bundles));
    allBundles.add(spiFlyBundle);
    EasyMock.expect(spiFlyBundleContext.getBundles()).andReturn(allBundles.toArray(new Bundle[] {})).anyTimes();
    EasyMock.replay(spiFlyBundleContext);
    EasyMock.expect(spiFlyBundle.getSymbolicName()).andReturn(bsn).anyTimes();
    EasyMock.expect(spiFlyBundle.getVersion()).andReturn(version).anyTimes();
    EasyMock.expect(spiFlyBundle.getBundleId()).andReturn(Long.MAX_VALUE).anyTimes();
    EasyMock.expect(spiFlyBundle.getBundleContext()).andReturn(spiFlyBundleContext).anyTimes();
    EasyMock.replay(spiFlyBundle);
    // Set the bundle context for testing purposes
    Field bcField = BaseActivator.class.getDeclaredField("bundleContext");
    bcField.setAccessible(true);
    bcField.set(activator, spiFlyBundle.getBundleContext());
    return spiFlyBundle;
}

86. ClientWeavingHookOSGi43Test#mockSpiFlyBundle()

View license
private Bundle mockSpiFlyBundle(String bsn, Version version, Bundle... bundles) throws Exception {
    Bundle spiFlyBundle = EasyMock.createMock(Bundle.class);
    BundleContext spiFlyBundleContext = EasyMock.createMock(BundleContext.class);
    EasyMock.expect(spiFlyBundleContext.getBundle()).andReturn(spiFlyBundle).anyTimes();
    List<Bundle> allBundles = new ArrayList<Bundle>(Arrays.asList(bundles));
    allBundles.add(spiFlyBundle);
    EasyMock.expect(spiFlyBundleContext.getBundles()).andReturn(allBundles.toArray(new Bundle[] {})).anyTimes();
    EasyMock.replay(spiFlyBundleContext);
    EasyMock.expect(spiFlyBundle.getSymbolicName()).andReturn(bsn).anyTimes();
    EasyMock.expect(spiFlyBundle.getVersion()).andReturn(version).anyTimes();
    EasyMock.expect(spiFlyBundle.getBundleId()).andReturn(Long.MAX_VALUE).anyTimes();
    EasyMock.expect(spiFlyBundle.getBundleContext()).andReturn(spiFlyBundleContext).anyTimes();
    EasyMock.replay(spiFlyBundle);
    // Set the bundle context for testing purposes
    Field bcField = BaseActivator.class.getDeclaredField("bundleContext");
    bcField.setAccessible(true);
    bcField.set(activator, spiFlyBundle.getBundleContext());
    return spiFlyBundle;
}

87. ClientWeavingHookTest#mockSpiFlyBundle()

View license
private Bundle mockSpiFlyBundle(String bsn, Version version, Bundle... bundles) throws Exception {
    Bundle spiFlyBundle = EasyMock.createMock(Bundle.class);
    BundleContext spiFlyBundleContext = EasyMock.createMock(BundleContext.class);
    EasyMock.expect(spiFlyBundleContext.getBundle()).andReturn(spiFlyBundle).anyTimes();
    List<Bundle> allBundles = new ArrayList<Bundle>(Arrays.asList(bundles));
    allBundles.add(spiFlyBundle);
    EasyMock.expect(spiFlyBundleContext.getBundles()).andReturn(allBundles.toArray(new Bundle[] {})).anyTimes();
    EasyMock.replay(spiFlyBundleContext);
    EasyMock.expect(spiFlyBundle.getSymbolicName()).andReturn(bsn).anyTimes();
    EasyMock.expect(spiFlyBundle.getVersion()).andReturn(version).anyTimes();
    EasyMock.expect(spiFlyBundle.getBundleId()).andReturn(Long.MAX_VALUE).anyTimes();
    EasyMock.expect(spiFlyBundle.getBundleContext()).andReturn(spiFlyBundleContext).anyTimes();
    EasyMock.replay(spiFlyBundle);
    // Set the bundle context for testing purposes
    Field bcField = BaseActivator.class.getDeclaredField("bundleContext");
    bcField.setAccessible(true);
    bcField.set(activator, spiFlyBundle.getBundleContext());
    return spiFlyBundle;
}

88. ApacheSenderFactoryTest#createApacheSender()

View license
private static ApacheSender createApacheSender(boolean isNewVersion) throws NoSuchFieldException, IllegalAccessException {
    Field field = ClassDataUtils.class.getDeclaredField("verifier");
    field.setAccessible(true);
    ClassDataVerifier mockVerifier = Mockito.mock(ClassDataVerifier.class);
    Mockito.doReturn(isNewVersion).when(mockVerifier).verifyClassExists(anyString());
    field.set(ClassDataUtils.INSTANCE, mockVerifier);
    ApacheSender sender = new ApacheSenderFactory().create();
    assertNotNull(sender);
    return sender;
}

89. WebRequestTrackingFilterTests#createInitializedFilterWithMockTelemetryClient()

View license
private FilterAndTelemetryClientMock createInitializedFilterWithMockTelemetryClient(boolean withTelemetryClient, boolean clientThrows) throws ServletException, NoSuchFieldException, IllegalAccessException {
    Filter filter = createInitializedFilter();
    Field field = WebRequestTrackingFilter.class.getDeclaredField("telemetryClient");
    field.setAccessible(true);
    StubTelemetryClient mockTelemetryClient = null;
    if (withTelemetryClient) {
        mockTelemetryClient = new StubTelemetryClient();
        if (clientThrows) {
            mockTelemetryClient.shouldThrow = true;
        }
    }
    field.set(filter, mockTelemetryClient);
    return new FilterAndTelemetryClientMock(filter, mockTelemetryClient);
}

90. AriesApplicationManagerImplTest#createApplication()

View license
private AriesApplication createApplication(String fileName) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, ManagementException, ResolverException {
    // This next block is a very long winded way of constructing a BundleInfoImpl
    // against the existing (BundleManifest bm, String location) constructor. If we 
    // find we need a String-based BundleInfoImpl constructor for other reasons, 
    // we could change to using it here. 
    Set<BundleInfo> nextResolverResult = new HashSet<BundleInfo>();
    String persistenceLibraryLocation = "../src/test/resources/bundles/repository/a.handy.persistence.library.jar";
    File persistenceLibrary = new File(persistenceLibraryLocation);
    BundleManifest mf = BundleManifest.fromBundle(persistenceLibrary);
    BundleInfo resolvedPersistenceLibrary = new SimpleBundleInfo(mf, persistenceLibraryLocation);
    Field v = SimpleBundleInfo.class.getDeclaredField("_version");
    v.setAccessible(true);
    v.set(resolvedPersistenceLibrary, new Version("1.1.0"));
    nextResolverResult.add(resolvedPersistenceLibrary);
    _resolver.setNextResult(nextResolverResult);
    IDirectory testEba = FileSystem.getFSRoot(new File(fileName));
    AriesApplication app = _appMgr.createApplication(testEba);
    app = _appMgr.resolve(app);
    return app;
}

91. ClientWeavingHookGenericCapabilityTest#mockSpiFlyBundle()

View license
private Bundle mockSpiFlyBundle(String bsn, Version version, Bundle... bundles) throws Exception {
    Bundle spiFlyBundle = EasyMock.createMock(Bundle.class);
    BundleContext spiFlyBundleContext = EasyMock.createMock(BundleContext.class);
    EasyMock.expect(spiFlyBundleContext.getBundle()).andReturn(spiFlyBundle).anyTimes();
    List<Bundle> allBundles = new ArrayList<Bundle>(Arrays.asList(bundles));
    allBundles.add(spiFlyBundle);
    EasyMock.expect(spiFlyBundleContext.getBundles()).andReturn(allBundles.toArray(new Bundle[] {})).anyTimes();
    EasyMock.replay(spiFlyBundleContext);
    EasyMock.expect(spiFlyBundle.getSymbolicName()).andReturn(bsn).anyTimes();
    EasyMock.expect(spiFlyBundle.getVersion()).andReturn(version).anyTimes();
    EasyMock.expect(spiFlyBundle.getBundleId()).andReturn(Long.MAX_VALUE).anyTimes();
    EasyMock.expect(spiFlyBundle.getBundleContext()).andReturn(spiFlyBundleContext).anyTimes();
    EasyMock.replay(spiFlyBundle);
    // Set the bundle context for testing purposes
    Field bcField = BaseActivator.class.getDeclaredField("bundleContext");
    bcField.setAccessible(true);
    bcField.set(activator, spiFlyBundle.getBundleContext());
    return spiFlyBundle;
}

92. ClientWeavingHookOSGi43Test#mockSpiFlyBundle()

View license
private Bundle mockSpiFlyBundle(String bsn, Version version, Bundle... bundles) throws Exception {
    Bundle spiFlyBundle = EasyMock.createMock(Bundle.class);
    BundleContext spiFlyBundleContext = EasyMock.createMock(BundleContext.class);
    EasyMock.expect(spiFlyBundleContext.getBundle()).andReturn(spiFlyBundle).anyTimes();
    List<Bundle> allBundles = new ArrayList<Bundle>(Arrays.asList(bundles));
    allBundles.add(spiFlyBundle);
    EasyMock.expect(spiFlyBundleContext.getBundles()).andReturn(allBundles.toArray(new Bundle[] {})).anyTimes();
    EasyMock.replay(spiFlyBundleContext);
    EasyMock.expect(spiFlyBundle.getSymbolicName()).andReturn(bsn).anyTimes();
    EasyMock.expect(spiFlyBundle.getVersion()).andReturn(version).anyTimes();
    EasyMock.expect(spiFlyBundle.getBundleId()).andReturn(Long.MAX_VALUE).anyTimes();
    EasyMock.expect(spiFlyBundle.getBundleContext()).andReturn(spiFlyBundleContext).anyTimes();
    EasyMock.replay(spiFlyBundle);
    // Set the bundle context for testing purposes
    Field bcField = BaseActivator.class.getDeclaredField("bundleContext");
    bcField.setAccessible(true);
    bcField.set(activator, spiFlyBundle.getBundleContext());
    return spiFlyBundle;
}

93. ClientWeavingHookTest#mockSpiFlyBundle()

Project: aries
Source File: ClientWeavingHookTest.java
View license
private Bundle mockSpiFlyBundle(String bsn, Version version, Bundle... bundles) throws Exception {
    Bundle spiFlyBundle = EasyMock.createMock(Bundle.class);
    BundleContext spiFlyBundleContext = EasyMock.createMock(BundleContext.class);
    EasyMock.expect(spiFlyBundleContext.getBundle()).andReturn(spiFlyBundle).anyTimes();
    List<Bundle> allBundles = new ArrayList<Bundle>(Arrays.asList(bundles));
    allBundles.add(spiFlyBundle);
    EasyMock.expect(spiFlyBundleContext.getBundles()).andReturn(allBundles.toArray(new Bundle[] {})).anyTimes();
    EasyMock.replay(spiFlyBundleContext);
    EasyMock.expect(spiFlyBundle.getSymbolicName()).andReturn(bsn).anyTimes();
    EasyMock.expect(spiFlyBundle.getVersion()).andReturn(version).anyTimes();
    EasyMock.expect(spiFlyBundle.getBundleId()).andReturn(Long.MAX_VALUE).anyTimes();
    EasyMock.expect(spiFlyBundle.getBundleContext()).andReturn(spiFlyBundleContext).anyTimes();
    EasyMock.replay(spiFlyBundle);
    // Set the bundle context for testing purposes
    Field bcField = BaseActivator.class.getDeclaredField("bundleContext");
    bcField.setAccessible(true);
    bcField.set(activator, spiFlyBundle.getBundleContext());
    return spiFlyBundle;
}

94. DeviceProxyTest#setUpClass()

View license
@BeforeClass
public static void setUpClass() throws Exception {
    // mock the ClientRequestMonitor singleton
    mockMonitor = mock(ClientRequestMonitor.class);
    Mockito.doNothing().when(mockMonitor).restartTimerForDevice(DEVICE_ID);
    // set proxy's ClientRequestMonitor field with the mocked monitor
    deviceProxyMonitorField = DeviceProxy.class.getDeclaredField("timeoutMonitor");
    deviceProxyMonitorField.setAccessible(true);
    device = new Device(new DeviceInformation(), DEVICE_ID, proxyPasskey);
    devicePoolDao = mock(DevicePoolDao.class);
    when(devicePoolDao.getDevice(eq(DEVICE_ID))).thenReturn(device);
    Field poolDao = DataSourceProvider.class.getDeclaredField("devicePoolDao");
    poolDao.setAccessible(true);
    poolDao.set(null, devicePoolDao);
}

95. BreakpointLifecycleTest#setUp()

View license
@Before
public void setUp() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
    m_debugger = new MockDebugger(new ModuleTargetSettings(CommonTestObjects.MODULE));
    m_debugger.setAddressTranslator(CommonTestObjects.MODULE, mockFileBase, mockImageBase.getAddress());
    m_breakpointManager = m_debugger.getBreakpointManager();
    m_synchronizer = new DebuggerSynchronizer(m_debugger);
    m_synchronizer.addListener(m_listener);
    // assign the synchronizer to the internally used one by the debugger so we can test the
    // synchronizer itself
    // as well as the combination of synchronizer and debugger
    final Field synchronizerField = AbstractDebugger.class.getDeclaredField("synchronizer");
    synchronizerField.setAccessible(true);
    synchronizerField.set(m_debugger, m_synchronizer);
}

96. CBreakpointSynchronizerTest#setUp()

View license
@Before
public void setUp() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
    m_debugger = new MockDebugger(new ModuleTargetSettings(mockModule));
    m_debugger.setAddressTranslator(mockModule, mockFileBase, mockImageBase.getAddress());
    m_breakpointManager = m_debugger.getBreakpointManager();
    m_synchronizer = new DebuggerSynchronizer(m_debugger);
    m_synchronizer.addListener(m_listener);
    // assign the synchronizer to the internally used one by the debugger so we can test the
    // synchronizer itself
    // as well as the combination of synchronizer and debugger
    final Field synchronizerField = AbstractDebugger.class.getDeclaredField("synchronizer");
    synchronizerField.setAccessible(true);
    synchronizerField.set(m_debugger, m_synchronizer);
}

97. CDebuggerSynchronizerTest#setUp()

View license
@Before
public void setUp() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
    mockDebugger = new MockDebugger(new ModuleTargetSettings(CommonTestObjects.MODULE));
    mockDebugger.setAddressTranslator(CommonTestObjects.MODULE, new CAddress(0), new CAddress(0x1000));
    breakpointManager = mockDebugger.getBreakpointManager();
    debuggerSynchronizer = new DebuggerSynchronizer(mockDebugger);
    debuggerSynchronizer.addListener(listener);
    // assign the synchronizer to the internally used one by the debugger so we can test the
    // synchronizer itself
    // as well as the combination of synchronizer and debugger
    final Field synchronizerField = AbstractDebugger.class.getDeclaredField("synchronizer");
    synchronizerField.setAccessible(true);
    synchronizerField.set(mockDebugger, debuggerSynchronizer);
}

98. CHistoryStringBuilderTest#setUp()

View license
@Before
public void setUp() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
    m_debugger = new MockDebugger(new ModuleTargetSettings(mockModule));
    m_debugger.setAddressTranslator(mockModule, mockFileBase, mockImageBase.getAddress());
    m_breakpointManager = m_debugger.getBreakpointManager();
    m_synchronizer = new DebuggerSynchronizer(m_debugger);
    m_synchronizer.addListener(m_listener);
    // assign the synchronizer to the internally used one by the debugger so we can test the
    // synchronizer itself
    // as well as the combination of synchronizer and debugger
    final Field synchronizerField = AbstractDebugger.class.getDeclaredField("synchronizer");
    synchronizerField.setAccessible(true);
    synchronizerField.set(m_debugger, m_synchronizer);
}

99. MMCIFFileTools#getFields()

Project: biojava
Source File: MMCIFFileTools.java
View license
/**
	 * Gets all fields for a particular class, filtering fields annotated
	 * with [email protected] IgnoreField @IgnoreField}.
	 * 
	 * As a side effect, calls [email protected] Field#setAccessible(boolean) setAccessible(true)}
	 * on all fields.
	 * @param c
	 * @return
	 */
public static Field[] getFields(Class<?> c) {
    Field[] allFields = c.getDeclaredFields();
    Field[] fields = new Field[allFields.length];
    int n = 0;
    for (Field f : allFields) {
        f.setAccessible(true);
        IgnoreField anno = f.getAnnotation(IgnoreField.class);
        if (anno == null) {
            fields[n] = f;
            n++;
        }
    }
    return Arrays.copyOf(fields, n);
}

100. TestBoneCP#testJMXRegister()

Project: bonecp
Source File: TestBoneCP.java
View license
/** JMX setup test
	 * @throws SecurityException
	 * @throws NoSuchFieldException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws InstanceAlreadyExistsException
	 * @throws MBeanRegistrationException
	 * @throws NotCompliantMBeanException
	 * @throws InstanceNotFoundException 
	 */
@Test
public void testJMXRegister() 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);
    expect(mockConfig.getPoolName()).andReturn(null).anyTimes();
    ObjectInstance mockInstance = EasyMock.createNiceMock(ObjectInstance.class);
    expect(mockMbs.isRegistered((ObjectName) anyObject())).andReturn(false).anyTimes();
    expect(mockMbs.registerMBean(anyObject(), (ObjectName) anyObject())).andReturn(mockInstance).once().andThrow(new InstanceAlreadyExistsException()).once();
    replay(mockMbs, mockInstance, mockConfig);
    testClass.registerUnregisterJMX(true);
    verify(mockMbs);
}