Example usage for org.apache.commons.lang3.reflect MethodUtils invokeMethod

List of usage examples for org.apache.commons.lang3.reflect MethodUtils invokeMethod

Introduction

In this page you can find the example usage for org.apache.commons.lang3.reflect MethodUtils invokeMethod.

Prototype

public static Object invokeMethod(final Object object, final String methodName, Object... args)
        throws NoSuchMethodException, IllegalAccessException, InvocationTargetException 

Source Link

Document

Invokes a named method whose parameter type matches the object type.

This method delegates the method search to #getMatchingAccessibleMethod(Class,String,Class[]) .

This method supports calls to methods taking primitive parameters via passing in wrapping classes.

Usage

From source file:com.examples.with.different.packagename.ClassPublicInterface.java

public static <L> void addEventListener(final Object eventSource, final Class<L> listenerType,
        final L listener) {
    try {//w  ww. j av a  2 s . c om
        MethodUtils.invokeMethod(eventSource, "add" + listenerType.getSimpleName(), listener);
    } catch (final NoSuchMethodException e) {
        throw new IllegalArgumentException("Class " + eventSource.getClass().getName()
                + " does not have a public add" + listenerType.getSimpleName()
                + " method which takes a parameter of type " + listenerType.getName() + ".");
    } catch (final IllegalAccessException e) {
        throw new IllegalArgumentException("Class " + eventSource.getClass().getName()
                + " does not have an accessible add" + listenerType.getSimpleName()
                + " method which takes a parameter of type " + listenerType.getName() + ".");
    } catch (final InvocationTargetException e) {
        throw new RuntimeException("Unable to add listener.", e.getCause());
    }
}

From source file:com.mycompany.selenium.factory.Page.java

public void takeAction(String action, Object... param) throws Throwable {
    action = action.replaceAll(" ", "_");
    try {/* w  w w . j a  va2  s.  c o m*/
        MethodUtils.invokeMethod(this, action, param);
    } catch (NoSuchMethodException e) {
        StringBuilder sb = new StringBuilder();

        sb.append("There is no \"").append(action).append("\" action ").append("in ").append(this.getTitle())
                .append(" page object").append("\n");
        sb.append("Possible actions are:").append("\n");
        Class tClass = this.getClass();
        Method[] methods = tClass.getDeclaredMethods();
        for (int i = 0; i < methods.length; i++) {
            sb.append("\t\"").append(this.getTitle()).append("\"->\"").append(methods[i].getName())
                    .append("\" with ").append(methods[i].getGenericParameterTypes().length)
                    .append(" input parameters").append("\n");
        }
        throw new NoSuchMethodException(sb.toString());
    } catch (InvocationTargetException ex) {
        throw ex.getCause();
    }
}

From source file:com.google.caliper.maven.CaliperBenchmark.java

public void run(String[] args) throws Exception {
    MethodUtils.invokeMethod(benchmark, "run", new Object[] { args });
}

From source file:com.pandich.dropwizard.curator.refresh.MethodRefresher.java

@Override
protected void doWrite(final Method element, final Object value) throws ReflectiveOperationException {
    MethodUtils.invokeMethod(this.configuration, element.getName(), value);
}

From source file:com.newlandframework.rpc.netty.MessageRecvInitializeTask.java

private Object reflect(MessageRequest request) throws Throwable {
    String className = request.getClassName();
    Object serviceBean = handlerMap.get(className);
    String methodName = request.getMethodName();
    Object[] parameters = request.getParameters();
    return MethodUtils.invokeMethod(serviceBean, methodName, parameters);
}

From source file:hoot.services.writers.review.ReviewPrepareDbWriter2.java

@Override
protected boolean parseElementUniqueIdTags(final long mapId) throws Exception {
    final String logMsgStart = "Parsing element unique ID tags for map with ID: " + mapId + ".  Step 2 of 4.";
    log.info(logMsgStart);/*from ww  w.  j a  v  a  2s .  c om*/

    uniqueIdsParsed = 0;
    idMappingRecordWritten = false;
    List<ElementIdMappings> elementIdMappingRecordsToInsert = new ArrayList<ElementIdMappings>();
    //create this outside of the batch read loop, since we need to maintain a list of unique
    //ID's parsed over the entire map's set of reviewable records
    Set<String> elementIds = new HashSet<String>();

    for (ElementType elementType : ElementType.values()) {
        if (!elementType.equals(ElementType.Changeset)) {
            //final Element prototype = ElementFactory.getInstance().create(elementType, conn);

            int numElementsReturned = Integer.MAX_VALUE;
            int elementIndex = 0;
            while (numElementsReturned > 0) {
                //get all reviewable elements
                final Map<Long, Object> reviewableElementRecords = getParseableElementRecords(mapId,
                        elementType, maxRecordSelectSize, elementIndex);
                numElementsReturned = reviewableElementRecords.size();
                elementIndex += numElementsReturned;
                for (Map.Entry<Long, Object> reviewableElementRecordEntry : reviewableElementRecords
                        .entrySet()) {
                    final long osmElementId = reviewableElementRecordEntry.getKey();
                    final Object reviewableElementRecord = reviewableElementRecordEntry.getValue();
                    final Map<String, String> tags = PostgresUtils.postgresObjToHStore((PGobject) MethodUtils
                            .invokeMethod(reviewableElementRecord, "getTags", new Object[] {}));
                    final String uniqueElementIdStr = StringUtils.trimToNull(tags.get("uuid"));
                    if (uniqueElementIdStr == null) {
                        log.warn("Invalid UUID: " + uniqueElementIdStr + " for map with ID: " + mapId
                                + ".  Skipping adding unique ID record...");
                    } else {
                        //In the case of the fuzzy match conflict example, this ID may be made up of multiple
                        //parts.  Treat each ID part separately.  TODO: add test for this case
                        String[] uniqueElementIds = null;
                        if (uniqueElementIdStr.contains(";")) {
                            log.debug("Multiple part UUID...");
                            uniqueElementIds = uniqueElementIdStr.split(";");
                        } else {
                            uniqueElementIds = new String[1];
                            uniqueElementIds[0] = uniqueElementIdStr;
                        }

                        for (String uniqueElementId : uniqueElementIds) {
                            //TODO: make this a batch query somehow
                            if (new SQLQuery(conn, DbUtils.getConfiguration(mapId)).from(elementIdMappings)
                                    .where(elementIdMappings.mapId.eq(mapId)
                                            .and(elementIdMappings.elementId.eq(uniqueElementId)))
                                    .count() > 0) {
                                log.warn("UUID: " + uniqueElementId + " for map with ID: " + mapId
                                        + " already exists.  " + "Skipping adding unique ID record...");
                            } else {
                                if (elementIds.add(uniqueElementId)) //don't add duplicates
                                {
                                    log.debug("Adding UUID: " + uniqueElementId);
                                    elementIdMappingRecordsToInsert.add(createElementIdMappingRecord(
                                            uniqueElementId, osmElementId, elementType, mapId));
                                    flushIdMappingRecords(elementIdMappingRecordsToInsert, maxRecordBatchSize,
                                            logMsgStart);
                                } else {
                                    log.warn("Duplicate element ID: " + uniqueElementId.toString()
                                            + " for map with ID: " + mapId
                                            + ".  Skipping adding unique ID record...");
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    //final flush
    flushIdMappingRecords(elementIdMappingRecordsToInsert, 0, logMsgStart);

    log.debug("Wrote " + elementIds.size() + " ID mappings.");

    return idMappingRecordWritten;
}

From source file:com.opensymphony.xwork2.interceptor.annotations.AnnotationWorkflowInterceptor.java

/**
 * Discovers annotated methods on the action and calls them according to the workflow
 *
 * @see com.opensymphony.xwork2.interceptor.Interceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
 *///  ww  w  . ja  va2  s .  c  om
public String intercept(ActionInvocation invocation) throws Exception {
    final Object action = invocation.getAction();
    invocation.addPreResultListener(this);
    List<Method> methods = new ArrayList<>(
            MethodUtils.getMethodsListWithAnnotation(action.getClass(), Before.class, true, true));
    if (methods.size() > 0) {
        // methods are only sorted by priority
        Collections.sort(methods, new Comparator<Method>() {
            public int compare(Method method1, Method method2) {
                return comparePriorities(
                        MethodUtils.getAnnotation(method1, Before.class, true, true).priority(),
                        MethodUtils.getAnnotation(method2, Before.class, true, true).priority());
            }
        });
        for (Method m : methods) {
            final String resultCode = (String) MethodUtils.invokeMethod(action, true, m.getName());
            if (resultCode != null) {
                // shortcircuit execution
                return resultCode;
            }
        }
    }

    String invocationResult = invocation.invoke();

    // invoke any @After methods
    methods = new ArrayList<Method>(
            MethodUtils.getMethodsListWithAnnotation(action.getClass(), After.class, true, true));

    if (methods.size() > 0) {
        // methods are only sorted by priority
        Collections.sort(methods, new Comparator<Method>() {
            public int compare(Method method1, Method method2) {
                return comparePriorities(MethodUtils.getAnnotation(method1, After.class, true, true).priority(),
                        MethodUtils.getAnnotation(method2, After.class, true, true).priority());
            }
        });
        for (Method m : methods) {
            MethodUtils.invokeMethod(action, true, m.getName());
        }
    }

    return invocationResult;
}

From source file:com.offbynull.coroutines.instrumenter.asm.SimpleClassWriterTest.java

@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);

    /**//from w  w w . ja v a 2 s  . co  m
     * 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), throwException("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, InstructionUtils.loadVar(listVar)), pop(), // discard results of call
            returnDummy(Type.VOID_TYPE));

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

From source file:com.opensymphony.xwork2.interceptor.annotations.AnnotationWorkflowInterceptor.java

/**
 * Invokes any &#64;BeforeResult annotated methods
 *
 * @see com.opensymphony.xwork2.interceptor.PreResultListener#beforeResult(com.opensymphony.xwork2.ActionInvocation,String)
 *//*from  ww w  . java 2  s  .  c o  m*/
public void beforeResult(ActionInvocation invocation, String resultCode) {
    Object action = invocation.getAction();
    List<Method> methods = new ArrayList<Method>(
            MethodUtils.getMethodsListWithAnnotation(action.getClass(), BeforeResult.class, true, true));

    if (methods.size() > 0) {
        // methods are only sorted by priority
        Collections.sort(methods, new Comparator<Method>() {
            public int compare(Method method1, Method method2) {
                return comparePriorities(
                        MethodUtils.getAnnotation(method1, BeforeResult.class, true, true).priority(),
                        MethodUtils.getAnnotation(method2, BeforeResult.class, true, true).priority());
            }
        });
        for (Method m : methods) {
            try {
                MethodUtils.invokeMethod(action, true, m.getName());
            } catch (Exception e) {
                throw new XWorkException(e);
            }
        }
    }
}

From source file:hoot.services.models.osm.Element.java

/**
 * Returns the ID of the element associated services database record
 *//*  w w  w  .  ja  v a2 s.  co m*/
public long getId() throws Exception {
    //this is a little risky, but I'm assuming the field probably won't ever change in name
    //in the OSM tables
    return (Long) MethodUtils.invokeMethod(record, "getId", new Object[] {});
}