下面列出了org.apache.commons.lang3.reflect.MethodUtils#invokeMethod ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public Object[] assembleRequest(BeforeEvent event) {
Object invocation;
if (ON_RESPONSE.equals(event.javaMethodName)) {
// for record parameter assemble
// onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {}
invocation = event.argumentArray[2];
} else {
// for repeater parameter assemble
// invoke(Invoker<?> invoker, Invocation invocation)
invocation = event.argumentArray[1];
}
try {
return (Object[]) MethodUtils.invokeMethod(invocation, "getArguments");
} catch (Exception e) {
// ignore
LogUtil.error("error occurred when assemble dubbo request", e);
}
return null;
}
/**
*
* 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);
}
}
private List<Class<?>> scanJaxrsClass(String name) throws Exception {
// String pack = "com." + name.replaceAll("_", ".");
String pack = "";
if (StringUtils.startsWith(name, "o2_")) {
pack = name.replaceAll("_", ".");
} else {
pack = "com." + name.replaceAll("_", ".");
}
try (ScanResult scanResult = new ClassGraph().whitelistPackages(pack).enableAllInfo().scan()) {
SetUniqueList<Class<?>> classes = SetUniqueList.setUniqueList(new ArrayList<Class<?>>());
for (ClassInfo info : scanResult.getClassesWithAnnotation(ApplicationPath.class.getName())) {
Class<?> applicationPathClass = ClassUtils.getClass(info.getName());
for (Class<?> o : (Set<Class<?>>) MethodUtils.invokeMethod(applicationPathClass.newInstance(),
"getClasses")) {
Path path = o.getAnnotation(Path.class);
JaxrsDescribe jaxrsDescribe = o.getAnnotation(JaxrsDescribe.class);
if (null != path && null != jaxrsDescribe) {
classes.add(o);
}
}
}
return classes;
}
}
private List<Class<?>> scanJaxrsClass() throws Exception {
try (ScanResult scanResult = new ClassGraph().disableJarScanning().enableAnnotationInfo().scan()) {
SetUniqueList<Class<?>> classes = SetUniqueList.setUniqueList(new ArrayList<Class<?>>());
for (ClassInfo info : scanResult.getClassesWithAnnotation(ApplicationPath.class.getName())) {
Class<?> applicationPathClass = ClassUtils.getClass(info.getName());
for (Class<?> o : (Set<Class<?>>) MethodUtils.invokeMethod(applicationPathClass.newInstance(),
"getClasses")) {
Path path = o.getAnnotation(Path.class);
JaxrsDescribe jaxrsDescribe = o.getAnnotation(JaxrsDescribe.class);
if (null != path && null != jaxrsDescribe) {
classes.add(o);
}
}
}
return classes;
}
}
public static void lang() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
String[] strs = new String[]{"1", "4", "2"};
ArrayUtils.addAll(strs, "3");
RandomUtils.nextInt(0, 10);
RandomStringUtils.random(3);
StopWatch stopWatch = new StopWatch();
stopWatch.start();
stopWatch.split();
stopWatch.getSplitTime();
stopWatch.suspend();
stopWatch.resume();
stopWatch.stop();
stopWatch.getTime();
long max = NumberUtils.max(new long[]{1, 5, 10}); //计算数组最大值
MethodUtils.invokeStaticMethod(StringUtils.class, "isNotBlank", "test"); //调用静态方法
MethodUtils.invokeMethod(StringUtils.class, "isNotBlank", "test"); //调用静态方法
DateUtils.truncate(new Date(), Calendar.HOUR);
DateFormatUtils.format(new Date(), "yyyyMMdd");
}
@Test
public void mustNotCrashOnMarker() throws Exception {
// Augment signature
methodNode.desc = Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { });
// Initialize variable table
VariableTable varTable = new VariableTable(classNode, methodNode);
methodNode.instructions
= merge(
// test marker of each type
debugMarker(MarkerType.NONE, "marker1"),
debugMarker(MarkerType.CONSTANT, "marker2"),
debugMarker(MarkerType.STDOUT, "marker3"),
returnVoid()
);
// Write to JAR file + load up in classloader -- then execute tests
try (URLClassLoader cl = createJarAndLoad(classNode)) {
Object obj = cl.loadClass(STUB_CLASSNAME).newInstance();
MethodUtils.invokeMethod(obj, STUB_METHOD_NAME);
}
}
@Override
protected Invocation initInvocation(BeforeEvent event) {
DubboInvocation dubboInvocation = new DubboInvocation();
// onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {}
Object invoker = event.argumentArray[1];
Object invocation = event.argumentArray[2];
try {
Object url = MethodUtils.invokeMethod(invoker, "getUrl");
@SuppressWarnings("unchecked")
Map<String, String> parameters = (Map<String, String>) MethodUtils.invokeMethod(url, "getParameters");
String protocol = (String)MethodUtils.invokeMethod(url, "getProtocol");
// methodName
String methodName = (String) MethodUtils.invokeMethod(invocation, "getMethodName");
Class<?>[] parameterTypes = (Class<?>[]) MethodUtils.invokeMethod(invocation, "getParameterTypes");
// interfaceName
String interfaceName = ((Class) MethodUtils.invokeMethod(invoker, "getInterface")).getCanonicalName();
dubboInvocation.setProtocol(protocol);
dubboInvocation.setInterfaceName(interfaceName);
dubboInvocation.setMethodName(methodName);
dubboInvocation.setParameters(parameters);
dubboInvocation.setVersion(parameters.get("version"));
dubboInvocation.setParameterTypes(transformClass(parameterTypes));
// todo find a right way to get address and group
} catch (Exception e) {
LogUtil.error("error occurred when init dubbo invocation", e);
}
return dubboInvocation;
}
@Override
public Identity assembleIdentity(BeforeEvent event) {
Object invoker;
Object invocation;
if (ON_RESPONSE.equals(event.javaMethodName)) {
// for record identity assemble
// onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {}
invoker = event.argumentArray[1];
invocation = event.argumentArray[2];
} else {
// for repeater identity assemble
// invoke(Invoker<?> invoker, Invocation invocation)
invoker = event.argumentArray[0];
invocation = event.argumentArray[1];
}
try {
// methodName
String methodName = (String) MethodUtils.invokeMethod(invocation, "getMethodName");
Class<?>[] parameterTypes = (Class<?>[]) MethodUtils.invokeMethod(invocation, "getParameterTypes");
// interfaceName
String interfaceName = ((Class)MethodUtils.invokeMethod(invoker, "getInterface")).getCanonicalName();
return new Identity(InvokeType.DUBBO.name(), interfaceName, getMethodDesc(methodName, parameterTypes), getExtra());
} catch (Exception e) {
// ignore
LogUtil.error("error occurred when assemble dubbo request", e);
}
return new Identity(InvokeType.DUBBO.name(), "unknown", "unknown", null);
}
@Override
public Object assembleResponse(Event event) {
// 在onResponse的before事件中组装response
if (event.type == Event.Type.BEFORE) {
Object appResponse = ((BeforeEvent) event).argumentArray[0];
try {
return MethodUtils.invokeMethod(appResponse, "getValue");
} catch (Exception e) {
// ignore
LogUtil.error("error occurred when assemble dubbo response", e);
}
}
return null;
}
public static Object invokeMethod(Object target, String obfName, String deobfName, Object... args) {
/* i just gave up here */
Object o = null;
try { o = MethodUtils.invokeMethod(target, true, obfName, args); } catch (Exception e) {
try { o = MethodUtils.invokeMethod(target, true, deobfName, args); } catch (Exception e1) {}}
return o;
}
public static Object invokeMethod(Object target, String obfName, String deobfName, Object... args) {
/* i just gave up here */
Object o = null;
try { o = MethodUtils.invokeMethod(target, true, obfName, args); } catch (Exception e) {
try { o = MethodUtils.invokeMethod(target, true, deobfName, args); } catch (Exception e1) {}}
return o;
}
public static Object invokeMethod(Object target, String obfName, String deobfName, Object... args) {
/* i just gave up here */
Object o = null;
try { o = MethodUtils.invokeMethod(target, true, obfName, args); } catch (Exception e) {
try { o = MethodUtils.invokeMethod(target, true, deobfName, args); } catch (Exception e1) {}}
return o;
}
@SuppressWarnings("unchecked")
private void executeLocalTransaction(final MythInvocation mythInvocation) throws Exception {
if (Objects.nonNull(mythInvocation)) {
final Class clazz = mythInvocation.getTargetClass();
final String method = mythInvocation.getMethodName();
final Object[] args = mythInvocation.getArgs();
final Class[] parameterTypes = mythInvocation.getParameterTypes();
final Object bean = SpringBeanUtils.getInstance().getBean(clazz);
MethodUtils.invokeMethod(bean, method, args, parameterTypes);
LogUtil.debug(LOGGER, "Myth执行本地协调事务:{}", () -> mythInvocation.getTargetClass() + ":" + mythInvocation.getMethodName());
}
}
@SuppressWarnings("unchecked")
private static Object execute(final HmilyInvocation hmilyInvocation) throws Exception {
if (Objects.isNull(hmilyInvocation)) {
return null;
}
final Class clazz = hmilyInvocation.getTargetClass();
final String method = hmilyInvocation.getMethodName();
final Object[] args = hmilyInvocation.getArgs();
final Class[] parameterTypes = hmilyInvocation.getParameterTypes();
final Object bean = SpringBeanUtils.getInstance().getBean(clazz);
return MethodUtils.invokeMethod(bean, method, args, parameterTypes);
}
/**
* Handles a method invocation on the proxy object.
*
* @param proxy the proxy instance
* @param method the method to be invoked
* @param parameters the parameters for the method invocation
* @return the result of the method call
* @throws Throwable if an error occurs
*/
@Override
public Object invoke(final Object proxy, final Method method, final Object[] parameters) throws Throwable {
if (eventTypes.isEmpty() || eventTypes.contains(method.getName())) {
if (hasMatchingParametersMethod(method)) {
return MethodUtils.invokeMethod(target, methodName, parameters);
} else {
return MethodUtils.invokeMethod(target, methodName);
}
}
return null;
}
@Test
public void testPostDataWithStoredResponses() throws Exception {
//given
PrebidMobile.setStoredAuctionResponse("111122223333");
PrebidMobile.addStoredBidResponse("appnexus", "221144");
PrebidMobile.addStoredBidResponse("rubicon", "221155");
//when
PrebidMobile.setApplicationContext(activity.getApplicationContext());
server.enqueue(new MockResponse().setResponseCode(200).setBody(MockPrebidServerResponses.noBid()));
DemandAdapter.DemandAdapterListener mockListener = mock(DemandAdapter.DemandAdapterListener.class);
PrebidServerAdapter adapter = new PrebidServerAdapter();
HashSet<AdSize> sizes = new HashSet<>();
sizes.add(new AdSize(500, 700));
RequestParams requestParams = new RequestParams("67890", AdType.INTERSTITIAL, sizes);
String uuid = UUID.randomUUID().toString();
adapter.requestDemand(requestParams, mockListener, uuid);
@SuppressWarnings("unchecked")
ArrayList<PrebidServerAdapter.ServerConnector> connectors = (ArrayList<PrebidServerAdapter.ServerConnector>) FieldUtils.readDeclaredField(adapter, "serverConnectors", true);
PrebidServerAdapter.ServerConnector connector = connectors.get(0);
JSONObject postData = (JSONObject) MethodUtils.invokeMethod(connector, true, "getPostData");
JSONObject prebid = postData.getJSONArray("imp").getJSONObject(0).getJSONObject("ext").getJSONObject("prebid");
JSONObject storedauctionresponse = prebid.getJSONObject("storedauctionresponse");
JSONArray storedbidresponse = prebid.getJSONArray("storedbidresponse");
JSONObject storedbidresponse1 = storedbidresponse.getJSONObject(0);
JSONObject storedbidresponse2 = storedbidresponse.getJSONObject(1);
//then
assertEquals("111122223333", storedauctionresponse.getString("id"));
Assert.assertEquals(2, storedbidresponse.length());
assertEquals("appnexus", storedbidresponse1.getString("bidder"));
assertEquals("221144", storedbidresponse1.getString("id"));
assertEquals("rubicon", storedbidresponse2.getString("bidder"));
assertEquals("221155", storedbidresponse2.getString("id"));
}
@Test
public void testVideoInterstitialAdUnit() throws Exception {
//given
PrebidMobile.setPrebidServerAccountId("12345");
//when
PrebidMobile.setApplicationContext(activity.getApplicationContext());
server.enqueue(new MockResponse().setResponseCode(200).setBody(MockPrebidServerResponses.noBid()));
DemandAdapter.DemandAdapterListener mockListener = mock(DemandAdapter.DemandAdapterListener.class);
PrebidServerAdapter adapter = new PrebidServerAdapter();
HashSet<AdSize> sizes = new HashSet<>();
sizes.add(new AdSize(500, 700));
RequestParams requestParams = new RequestParams("67890", AdType.VIDEO_INTERSTITIAL, sizes);
String uuid = UUID.randomUUID().toString();
adapter.requestDemand(requestParams, mockListener, uuid);
@SuppressWarnings("unchecked")
ArrayList<PrebidServerAdapter.ServerConnector> connectors = (ArrayList<PrebidServerAdapter.ServerConnector>) FieldUtils.readDeclaredField(adapter, "serverConnectors", true);
PrebidServerAdapter.ServerConnector connector = connectors.get(0);
JSONObject postData = (JSONObject) MethodUtils.invokeMethod(connector, true, "getPostData");
JSONObject video = postData.getJSONArray("imp").getJSONObject(0).getJSONObject("video");
JSONObject cache = postData.getJSONObject("ext").getJSONObject("prebid").getJSONObject("cache");
JSONObject vastxml = cache.getJSONObject("vastxml");
int instl = postData.getJSONArray("imp").getJSONObject(0).getInt("instl");
//then
assertEquals(5, video.getInt("placement"));
assertEquals(1, video.getInt("linearity"));
assertEquals(1, instl);
assertNotNull(vastxml);
}
@Test
public void testRewardedVideoAdUnit() throws Exception {
//given
PrebidMobile.setPrebidServerAccountId("12345");
//when
PrebidMobile.setApplicationContext(activity.getApplicationContext());
server.enqueue(new MockResponse().setResponseCode(200).setBody(MockPrebidServerResponses.noBid()));
DemandAdapter.DemandAdapterListener mockListener = mock(DemandAdapter.DemandAdapterListener.class);
PrebidServerAdapter adapter = new PrebidServerAdapter();
HashSet<AdSize> sizes = new HashSet<>();
sizes.add(new AdSize(500, 700));
RequestParams requestParams = new RequestParams("67890", AdType.REWARDED_VIDEO, sizes);
String uuid = UUID.randomUUID().toString();
adapter.requestDemand(requestParams, mockListener, uuid);
@SuppressWarnings("unchecked")
ArrayList<PrebidServerAdapter.ServerConnector> connectors = (ArrayList<PrebidServerAdapter.ServerConnector>) FieldUtils.readDeclaredField(adapter, "serverConnectors", true);
PrebidServerAdapter.ServerConnector connector = connectors.get(0);
JSONObject postData = (JSONObject) MethodUtils.invokeMethod(connector, true, "getPostData");
JSONObject video = postData.getJSONArray("imp").getJSONObject(0).getJSONObject("video");
JSONObject cache = postData.getJSONObject("ext").getJSONObject("prebid").getJSONObject("cache");
JSONObject vastxml = cache.getJSONObject("vastxml");
int instl = postData.getJSONArray("imp").getJSONObject(0).getInt("instl");
int isRewarded = postData.getJSONArray("imp").getJSONObject(0).getJSONObject("ext").getJSONObject("prebid").getInt("is_rewarded_inventory");
//then
assertEquals(5, video.getInt("placement"));
assertEquals(1, video.getInt("linearity"));
assertEquals(1, instl);
assertEquals(1, isRewarded);
assertNotNull(vastxml);
}
@Test
public void testCustomGetCommonSuperClassImplementation() throws Exception {
// augment method to take in a single int argument
methodNode.desc = Type.getMethodDescriptor(Type.VOID_TYPE, Type.INT_TYPE);
// augment method instructions
VariableTable varTable = new VariableTable(classNode, methodNode);
Class<?> iterableClass = Iterable.class;
Constructor arrayListConstructor = ConstructorUtils.getAccessibleConstructor(ArrayList.class);
Constructor linkedListConstructor = ConstructorUtils.getAccessibleConstructor(LinkedList.class);
Constructor hashSetConstructor = ConstructorUtils.getAccessibleConstructor(HashSet.class);
Method iteratorMethod = MethodUtils.getAccessibleMethod(iterableClass, "iterator");
Type iterableType = Type.getType(iterableClass);
Variable testArg = varTable.getArgument(1);
Variable listVar = varTable.acquireExtra(iterableType);
/**
* Collection it;
* switch(arg1) {
* case 0:
* it = new ArrayList()
* break;
* case 1:
* it = new LinkedList()
* break;
* case 2:
* it = new HashSet()
* break;
* default: throw new RuntimeException("must be 0 or 1");
* }
* list.iterator();
*/
LabelNode invokePoint = new LabelNode();
InsnList methodInsnList
= merge(tableSwitch(loadVar(testArg),
throwRuntimeException("must be 0 or 1"),
0,
merge(
construct(arrayListConstructor),
saveVar(listVar),
jumpTo(invokePoint)
),
merge(
construct(linkedListConstructor),
saveVar(listVar),
jumpTo(invokePoint)
),
merge(
construct(hashSetConstructor),
saveVar(listVar),
jumpTo(invokePoint)
)
),
addLabel(invokePoint),
call(iteratorMethod, GenericGenerators.loadVar(listVar)),
pop(), // discard results of call
returnVoid()
);
methodNode.instructions = methodInsnList;
// attemp to write out class -- since we're branching like this it should call getCommonSuperClass() with the types specified in
// each of the switch cases. getCommonsuperClass() is the logic we explictly override and are testing. createJarAndLoad uses
// simpleclasswriter
try (URLClassLoader cl = createJarAndLoad(classNode)) {
Object obj = cl.loadClass("SimpleStub").newInstance();
// there should not be any verifer errors here
MethodUtils.invokeMethod(obj, "fillMeIn", 0);
MethodUtils.invokeMethod(obj, "fillMeIn", 1);
MethodUtils.invokeMethod(obj, "fillMeIn", 2);
}
}
@Test
public void testVideoBaseAdUnit() throws Exception {
PrebidMobile.setPrebidServerAccountId("12345");
//given
VideoAdUnit.Parameters parameters = new VideoAdUnit.Parameters();
parameters.setApi(Arrays.asList(Signals.Api.VPAID_1, Signals.Api.VPAID_2));
parameters.setMaxBitrate(1500);
parameters.setMinBitrate(300);
parameters.setMaxDuration(30);
parameters.setMinDuration(5);
parameters.setMimes(Arrays.asList("video/x-flv", "video/mp4"));
parameters.setPlaybackMethod(Arrays.asList(Signals.PlaybackMethod.AutoPlaySoundOn, Signals.PlaybackMethod.ClickToPlay));
parameters.setProtocols(Arrays.asList(Signals.Protocols.VAST_2_0, Signals.Protocols.VAST_3_0));
parameters.setStartDelay(Signals.StartDelay.PreRoll);
//when
PrebidMobile.setApplicationContext(activity.getApplicationContext());
server.enqueue(new MockResponse().setResponseCode(200).setBody(MockPrebidServerResponses.noBid()));
DemandAdapter.DemandAdapterListener mockListener = mock(DemandAdapter.DemandAdapterListener.class);
PrebidServerAdapter adapter = new PrebidServerAdapter();
HashSet<AdSize> sizes = new HashSet<>();
sizes.add(new AdSize(500, 700));
RequestParams requestParams = new RequestParams("67890", AdType.VIDEO, sizes, null, null, null, parameters);
String uuid = UUID.randomUUID().toString();
adapter.requestDemand(requestParams, mockListener, uuid);
@SuppressWarnings("unchecked")
ArrayList<PrebidServerAdapter.ServerConnector> connectors = (ArrayList<PrebidServerAdapter.ServerConnector>) FieldUtils.readDeclaredField(adapter, "serverConnectors", true);
PrebidServerAdapter.ServerConnector connector = connectors.get(0);
JSONObject postData = (JSONObject) MethodUtils.invokeMethod(connector, true, "getPostData");
JSONObject video = postData.getJSONArray("imp").getJSONObject(0).getJSONObject("video");
//then
List<Integer> apiList = Util.convertJSONArray(video.getJSONArray("api"));
assertEquals(2, apiList.size());
assertTrue(apiList.contains(1) && apiList.contains(2));
int maxBitrate = video.getInt("maxbitrate");
assertEquals(1500, maxBitrate);
int minBitrate = video.getInt("minbitrate");
assertEquals(300, minBitrate);
int maxDuration = video.getInt("maxduration");
assertEquals(30, maxDuration);
int minDuration = video.getInt("minduration");
assertEquals(5, minDuration);
List<String> mimeList = Util.convertJSONArray(video.getJSONArray("mimes"));
assertEquals(2, mimeList.size());
assertTrue(mimeList.contains("video/x-flv") && mimeList.contains("video/mp4"));
List<Integer> playbackList = Util.convertJSONArray(video.getJSONArray("playbackmethod"));
assertEquals(2, playbackList.size());
assertTrue(playbackList.contains(1) && playbackList.contains(3));
List<Integer> protocolList = Util.convertJSONArray(video.getJSONArray("protocols"));
assertEquals(2, protocolList.size());
assertTrue(protocolList.contains(2) && protocolList.contains(3));
int startDelay = video.getInt("startdelay");
assertEquals(0, startDelay);
}