Example usage for org.springframework.util MethodInvoker MethodInvoker

List of usage examples for org.springframework.util MethodInvoker MethodInvoker

Introduction

In this page you can find the example usage for org.springframework.util MethodInvoker MethodInvoker.

Prototype

MethodInvoker

Source Link

Usage

From source file:am.ik.categolj2.infra.codelist.MethodInvokingCodeListTest.java

@Test
public void test() {
    MethodInvokingCodeList codeList = new MethodInvokingCodeList();
    codeList.setLabelField("name");
    codeList.setValueField("priority");
    PriorityService service = new PriorityService();
    MethodInvoker methodInvoker = new MethodInvoker();
    methodInvoker.setTargetMethod("findAll");
    methodInvoker.setTargetObject(service);
    codeList.setMethodInvoker(methodInvoker);

    codeList.afterPropertiesSet();/*from w ww . j a  v a 2  s .co m*/
    Map<String, String> expected = Maps.newLinkedHashMap();
    expected.put("1", "high");
    expected.put("2", "middle");
    expected.put("3", "low");
    assertThat(codeList.asMap(), is(expected));
}

From source file:cn.bc.core.util.SpringUtils.java

/**
 * ?Bean??/*from   www  .j  a v  a 2 s .  c o m*/
 * 
 * @param object
 *            object
 * @param methodName
 *            ??
 * @param arguments
 *            ?
 * @return ?bean??
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException
 * @throws ClassNotFoundException
 */
public static Object invokeBeanMethod(String beanName, String methodName, Object[] arguments) {
    try {
        // ?
        MethodInvoker methodInvoker = new MethodInvoker();
        methodInvoker.setTargetObject(SpringUtils.getBean(beanName));
        methodInvoker.setTargetMethod(methodName);

        // ?
        if (arguments != null && arguments.length > 0) {
            methodInvoker.setArguments(arguments);
        }

        // 
        methodInvoker.prepare();

        // 
        return methodInvoker.invoke();
    } catch (ClassNotFoundException e) {
        throw new CoreException(e);
    } catch (NoSuchMethodException e) {
        throw new CoreException(e);
    } catch (InvocationTargetException e) {
        throw new CoreException(e);
    } catch (IllegalAccessException e) {
        throw new CoreException(e);
    }
}

From source file:com.glaf.jbpm.action.InvokerAction.java

public void execute(ExecutionContext ctx) {
    logger.debug("-------------------------------------------------------");
    logger.debug("--------------------InvokerAction----------------------");
    logger.debug("-------------------------------------------------------");

    if (StringUtils.isNotEmpty(className) && StringUtils.isNotEmpty(method)) {
        MethodInvoker methodInvoker = new MethodInvoker();
        Object target = ClassUtils.instantiateObject(className);

        Map<String, Object> params = new java.util.HashMap<String, Object>();

        ContextInstance contextInstance = ctx.getContextInstance();
        Map<String, Object> variables = contextInstance.getVariables();
        if (variables != null && variables.size() > 0) {
            Set<Entry<String, Object>> entrySet = variables.entrySet();
            for (Entry<String, Object> entry : entrySet) {
                String name = entry.getKey();
                Object value = entry.getValue();
                if (name != null && value != null && params.get(name) == null) {
                    params.put(name, value);
                }/*from w ww  . ja  v a2 s  .com*/
            }
        }

        if (elements != null) {
            if (LogUtils.isDebug()) {
                logger.debug("elements:" + elements.asXML());
            }
            Object object = CustomFieldInstantiator.getValue(Map.class, elements);
            if (object instanceof Map) {
                Map<String, Object> paramMap = (Map<String, Object>) object;
                Set<Entry<String, Object>> entrySet = paramMap.entrySet();
                for (Entry<String, Object> entry : entrySet) {
                    String key = entry.getKey();
                    Object value = entry.getValue();
                    if (key != null && value != null) {
                        params.put(key, value);
                    }
                }
            }
        }

        Map<String, Object> varMap = contextInstance.getVariables();
        if (varMap != null && varMap.size() > 0) {
            Set<Entry<String, Object>> entrySet = varMap.entrySet();
            for (Entry<String, Object> entry : entrySet) {
                String variableName = entry.getKey();
                if (params.get(variableName) == null) {
                    Object value = contextInstance.getVariable(variableName);
                    params.put(variableName, value);
                }
            }
        }

        Object rowId = contextInstance.getVariable(Constant.PROCESS_ROWID);
        params.put("rowId", rowId);

        ProcessInstance processInstance = ctx.getProcessInstance();
        ProcessDefinition processDefinition = processInstance.getProcessDefinition();
        Long processInstanceId = processInstance.getId();
        params.put("processInstanceId", processInstanceId);
        params.put("processName", processDefinition.getName());
        params.put("processDefinitionId", processDefinition.getId());
        params.put("processDefinition", processDefinition);
        params.put("processInstance", processInstance);

        Object[] arguments = { params, ctx.getJbpmContext().getConnection() };
        methodInvoker.setArguments(arguments);
        methodInvoker.setTargetObject(target);
        methodInvoker.setTargetMethod(method);
        try {
            methodInvoker.prepare();
            methodInvoker.invoke();
        } catch (Exception ex) {
            if (LogUtils.isDebug()) {
                ex.printStackTrace();
                logger.debug(ex);
            }
            throw new JbpmException(ex);
        }
    }

}

From source file:architecture.ee.web.view.freemarker.ExtendedTemplateLoader.java

@Override
public Object findTemplateSource(String name) throws IOException {

    log.debug("searching... " + name + ", customized : " + isCustomizedEnabled());

    if (isCustomizedEnabled()) {
        try {/* w  ww  .j  av a2 s. c  o m*/
            MethodInvoker invoker = new MethodInvoker();
            invoker.setStaticMethod("architecture.ee.web.struts2.util.ActionUtils.getAction");
            invoker.prepare();
            Object action = invoker.invoke();
            if (action instanceof WebSiteAware) {
                WebSite site = ((WebSiteAware) action).getWebSite();
                String nameToUse = SEP_IS_SLASH ? name : name.replace('/', File.separatorChar);
                if (nameToUse.charAt(0) == File.separatorChar) {
                    nameToUse = File.separatorChar + "sites" + File.separatorChar + site.getName().toLowerCase()
                            + nameToUse;
                } else {
                    nameToUse = File.separatorChar + "sites" + File.separatorChar + site.getName().toLowerCase()
                            + File.separatorChar + nameToUse;
                }
                log.debug((new StringBuilder()).append("website:").append(site.getName().toLowerCase())
                        .append(", template: ").append(nameToUse).toString());
                File source = new File(baseDir, SEP_IS_SLASH ? name : name.replace('/', File.separatorChar));
                return super.findTemplateSource(nameToUse);
            }
        } catch (Exception e) {
            log.warn(e);
        }
    }
    return null;
    /*      if( usingDatabase() ){
             try {            
    MethodInvoker invoker = new MethodInvoker();      
    invoker.setStaticMethod("architecture.ee.web.struts2.util.ActionUtils.getAction");
    invoker.prepare();
    Object action = invoker.invoke();
            
    if( action instanceof TemplateAware ){
       Template template = ((TemplateAware)action).getTargetTemplate();
       if( log.isDebugEnabled() )
          log.debug( name + " < compare > template from action:" + template.getTitle() + ", type=" + template.getTemplateType() + ", locaion=" + template.getLocation());               
       if(  "ftl".equals(template.getTemplateType()) && name.contains(template.getLocation() ))
          return template;
    }
            
             } catch (Exception e) {
    log.warn(e);            
             }
             List<Template> contents = getCurrentCompanyTemplates();
             for( Template template : contents){
    if( log.isDebugEnabled() )
       log.debug( name + "< compare > template from database :" + template.getTitle() + ", type:" + template.getTemplateType() + ", match:" + template.getLocation() .contains(name) );
    if(  template.getLocation() .contains(name)){
       return template;
    }
             }         
          }   */
}

From source file:se.ivankrizsan.messagecowboy.services.scheduling.MethodInvokingJob.java

@Override
public void execute(final JobExecutionContext inContext) throws JobExecutionException {
    final JobDataMap theJobDataMap = inContext.getJobDetail().getJobDataMap();
    final String theTaskName = inContext.getJobDetail().getKey().getName();
    final String theTaskGroupName = inContext.getJobDetail().getKey().getGroup();

    LOGGER.info("Started executing task {} in group {}", theTaskName, theTaskGroupName);

    final Object theTargetObject = theJobDataMap.get(TARGET_OBJECT_KEY);
    final Object theTargetMethodNameObject = theJobDataMap.get(TARGET_METHOD_KEY);
    final Object theTargetMethodParamsObject = theJobDataMap.get(TARGET_METHOD_PARAMETERS_KEY);

    if (theTargetObject != null && theTargetMethodNameObject != null) {
        /* Cast parameters to appropriate types. */
        final String theTargetMethodName = (String) theTargetMethodNameObject;
        Object[] theTargetMethodParams = new Object[0];

        /*//from  w ww  .ja  va 2s  . co  m
         * Parameter array may be null, in which a no-params method
         * invocation will be performed.
         */
        if (theTargetMethodParamsObject != null) {
            theTargetMethodParams = (Object[]) theTargetMethodParamsObject;
        }

        /*
         * Check if logging is enabled before applying conversions only
         * needed for logging purposes.
         */
        if (LOGGER.isDebugEnabled()) {
            final Object[] theDebugLogArguments = new Object[] { theTargetMethodName,
                    theTargetObject.getClass().getName(), Arrays.asList(theTargetMethodParams).toString() };
            LOGGER.debug("Invoking the method {} on object of the type {} with the parameters {}",
                    theDebugLogArguments);
        }

        /* Invoke the target method. */
        try {
            MethodInvoker theMethodInvoker = new MethodInvoker();
            theMethodInvoker.setTargetObject(theTargetObject);
            theMethodInvoker.setTargetMethod(theTargetMethodName);
            theMethodInvoker.setArguments(theTargetMethodParams);
            theMethodInvoker.prepare();

            theMethodInvoker.invoke();
        } catch (final Throwable theException) {
            /*
             * Catch all exceptions, in order to allow the program to
             * continue to run despite exceptions.
             */
            LOGGER.error("An error occurred invoking the method " + theTargetMethodName + " on object of"
                    + " the type " + theTargetObject.getClass().getName() + " with the parameters "
                    + Arrays.asList(theTargetMethodParams).toString(), theException);
        }

        LOGGER.info("Successfully completed executing task {} in group {}", theTaskName, theTaskGroupName);
    }
}

From source file:org.dkpro.lab.Util.java

public static void createSymbolicLink(File aSource, File aTarget) throws IOException {
    if (aTarget.exists()) {
        throw new FileExistsException(aTarget);
    }/*from   ww  w  . ja  v a2 s  .  c o m*/

    File parentDir = aTarget.getAbsoluteFile().getParentFile();
    if (parentDir != null && !parentDir.exists()) {
        FileUtils.forceMkdir(parentDir);
    }

    // Try Java 7 methods
    try {
        Object fromPath = MethodUtils.invokeExactMethod(aSource, "toPath", new Object[0]);
        Object toPath = MethodUtils.invokeExactMethod(aTarget, "toPath", new Object[0]);
        Object options = Array.newInstance(Class.forName("java.nio.file.attribute.FileAttribute"), 0);
        MethodInvoker inv = new MethodInvoker();
        inv.setStaticMethod("java.nio.file.Files.createSymbolicLink");
        inv.setArguments(new Object[] { toPath, fromPath, options });
        inv.prepare();
        inv.invoke();
        return;
    } catch (ClassNotFoundException e) {
        // Ignore
    } catch (NoSuchMethodException e) {
        // Ignore
    } catch (IllegalAccessException e) {
        // Ignore
    } catch (InvocationTargetException e) {
        if ("java.nio.file.FileAlreadyExistsException".equals(e.getTargetException().getClass().getName())) {
            throw new FileExistsException(aTarget);
        }
    }

    // If the Java 7 stuff is not available, fall back to Runtime.exec
    String[] cmdline = { "ln", "-s", aSource.getAbsolutePath(), aTarget.getAbsolutePath() };
    Execute exe = new Execute();
    exe.setVMLauncher(false);
    exe.setCommandline(cmdline);
    exe.execute();
    if (exe.isFailure()) {
        throw new IOException("Unable to create symlink from [" + aSource + "] to [" + aTarget + "]");
    }
}

From source file:org.kuali.rice.krad.uif.lifecycle.finalize.InvokeFinalizerTask.java

/**
 * Invokes the finalize method for the component (if configured) and sets the render output for
 * the component to the returned method string (if method is not a void type)
 *///from ww  w .j a va  2s. c  o  m
@Override
protected void performLifecycleTask() {
    Component component = (Component) getElementState().getElement();
    String finalizeMethodToCall = component.getFinalizeMethodToCall();
    MethodInvoker finalizeMethodInvoker = component.getFinalizeMethodInvoker();

    if (StringUtils.isBlank(finalizeMethodToCall) && (finalizeMethodInvoker == null)) {
        return;
    }

    if (finalizeMethodInvoker == null) {
        finalizeMethodInvoker = new MethodInvoker();
    }

    // if method not set on invoker, use finalizeMethodToCall, note staticMethod could be set(don't know since
    // there is not a getter), if so it will override the target method in prepare
    if (StringUtils.isBlank(finalizeMethodInvoker.getTargetMethod())) {
        finalizeMethodInvoker.setTargetMethod(finalizeMethodToCall);
    }

    // if target class or object not set, use view helper service
    if ((finalizeMethodInvoker.getTargetClass() == null) && (finalizeMethodInvoker.getTargetObject() == null)) {
        finalizeMethodInvoker.setTargetObject(ViewLifecycle.getHelper());
    }

    // setup arguments for method
    List<Object> additionalArguments = component.getFinalizeMethodAdditionalArguments();
    if (additionalArguments == null) {
        additionalArguments = new ArrayList<Object>();
    }

    Object[] arguments = new Object[2 + additionalArguments.size()];
    arguments[0] = component;
    arguments[1] = ViewLifecycle.getModel();

    int argumentIndex = 1;
    for (Object argument : additionalArguments) {
        argumentIndex++;
        arguments[argumentIndex] = argument;
    }
    finalizeMethodInvoker.setArguments(arguments);

    // invoke finalize method
    try {
        LOG.debug("Invoking finalize method: " + finalizeMethodInvoker.getTargetMethod() + " for component: "
                + component.getId());
        finalizeMethodInvoker.prepare();

        Class<?> methodReturnType = finalizeMethodInvoker.getPreparedMethod().getReturnType();
        if (StringUtils.equals("void", methodReturnType.getName())) {
            finalizeMethodInvoker.invoke();
        } else {
            String renderOutput = (String) finalizeMethodInvoker.invoke();

            component.setSelfRendered(true);
            component.setRenderedHtmlOutput(renderOutput);
        }
    } catch (Exception e) {
        LOG.error("Error invoking finalize method for component: " + component.getId(), e);
        throw new RuntimeException("Error invoking finalize method for component: " + component.getId(), e);
    }
}

From source file:org.openspaces.core.space.mode.SpaceModeContextLoader.java

/**
 * A hack to only send the application event on the child application context we are loading,
 * without propogating it to the parent application context (when using {@link
 * ApplicationContext#publishEvent(org.springframework.context.ApplicationEvent)} which will
 * create a recursive event calling.//from  www.java2s.  c om
 */
protected void publishEvent(ApplicationEvent applicationEvent) {
    if (applicationContext == null) {
        return;
    }
    ApplicationEventMulticaster eventMulticaster;
    try {
        MethodInvoker methodInvoker = new MethodInvoker();
        methodInvoker.setTargetClass(AbstractApplicationContext.class);
        methodInvoker.setTargetMethod("getApplicationEventMulticaster");
        methodInvoker.setTargetObject(applicationContext);
        methodInvoker.setArguments(null);
        methodInvoker.prepare();
        eventMulticaster = (ApplicationEventMulticaster) methodInvoker.invoke();
    } catch (Exception e) {
        logger.warn("Failed to get application event multicaster to publish event to child application context",
                e);
        return;
    }
    eventMulticaster.multicastEvent(applicationEvent);
}

From source file:org.openspaces.events.adapter.AbstractReflectionEventListenerAdapter.java

/**
 * Delegates the event listener invocation to the appropriate method of the configured {@link
 * #setDelegate(Object)}. If a single event listener delegate method is found, uses the cached
 * reflection Method. If more than one event listener delegate method is configured uses
 * reflection to dynamically find the relevant event listener method.
 *//*  ww  w  .j  av  a2  s  . c  om*/
@Override
protected Object onEventWithResult(Object data, GigaSpace gigaSpace, TransactionStatus txStatus,
        Object source) {
    Method listenerMethod = listenerMethods[0];

    /*
    Object newValue = null, oldValue = null;
    boolean doubleParameter = false;
    if (notifyPreviousValueOnUpdate && source instanceof EntryArrivedRemoteEvent) {
    EntryArrivedRemoteEvent event = (EntryArrivedRemoteEvent) source;
    try {
        newValue = event.getNewObject();
        oldValue = event.getOldObject();
        doubleParameter = true;
    } catch (Exception e) {
        newValue = null;
        oldValue = null;
    }
    }
            
    // set up the arguments passed to the method
    Object[] listenerArguments = null;
    if (numberOfParameters == 1) {
    listenerArguments = new Object[] { data };
    } else if (numberOfParameters == 2) {
    if (doubleParameter) {
        listenerArguments = new Object[] { oldValue, newValue };
    } else {
        listenerArguments = new Object[]{ data, gigaSpace};
    }
    } else if (numberOfParameters == 3) {
    if (doubleParameter) {
        listenerArguments = new Object[] { oldValue, newValue, gigaSpace };
    } else {
        listenerArguments = new Object[]{ data, gigaSpace, txStatus};
    }
    } else if (numberOfParameters == 4) {
    if (doubleParameter) {
        listenerArguments = new Object[] { oldValue, newValue, gigaSpace, txStatus };
    } else {
        listenerArguments = new Object[]{ data, gigaSpace, txStatus, source};
    }
    } else if (numberOfParameters == 5 && doubleParameter) {
    listenerArguments = new Object[] { oldValue, newValue, gigaSpace, txStatus, source};
    }
    */
    // set up the arguments passed to the method
    Object[] listenerArguments = null;
    if (numberOfParameters == 1) {
        listenerArguments = new Object[] { data };
    } else if (numberOfParameters == 2) {
        listenerArguments = new Object[] { data, gigaSpace };
    } else if (numberOfParameters == 3) {
        listenerArguments = new Object[] { data, gigaSpace, txStatus };
    } else if (numberOfParameters == 4) {
        listenerArguments = new Object[] { data, gigaSpace, txStatus, source };
    }

    Object result = null;
    if (listenerMethods.length == 1) {
        // single method, use the already obtained Method to invoke the listener
        try {
            result = fastMethod.invoke(delegate, listenerArguments);
        } catch (IllegalAccessException ex) {
            throw new PermissionDeniedDataAccessException(
                    "Failed to invoke event method [" + listenerMethod.getName() + "]", ex);
        } catch (InvocationTargetException ex) {
            throw new ListenerExecutionFailedException(
                    "Listener event method [" + listenerMethod.getName() + "] of class ["
                            + listenerMethod.getDeclaringClass().getName() + "] threw exception",
                    ex.getTargetException());
        } catch (Throwable ex) {
            throw new ListenerExecutionFailedException("Listener event method [" + listenerMethod.getName()
                    + "] of class [" + listenerMethod.getDeclaringClass().getName() + "] threw exception", ex);
        }
    } else {
        // more than one method, we need to use reflection to find the matched method
        MethodInvoker methodInvoker = new MethodInvoker();
        methodInvoker.setTargetObject(getDelegate());
        methodInvoker.setTargetMethod(listenerMethod.getName());
        methodInvoker.setArguments(listenerArguments);
        try {
            methodInvoker.prepare();
            result = methodInvoker.invoke();
        } catch (InvocationTargetException ex) {
            throw new ListenerExecutionFailedException(
                    "Listener method '" + listenerMethod.getName() + "' threw exception",
                    ex.getTargetException());
        } catch (Throwable ex) {
            throw new ListenerExecutionFailedException(
                    "Failed to invoke target method '" + listenerMethod.getName() + "' with arguments "
                            + ObjectUtils.nullSafeToString(listenerArguments),
                    ex);
        }

    }
    return result;
}

From source file:org.pssframework.jmx.MBeanServerConnectionInterceptor.java

private Object processed(MethodInvocation invocation) throws Throwable {
    MethodInvoker invoker = new MethodInvoker();
    invoker.setArguments(invocation.getArguments());
    invoker.setTargetObject(connection);
    invoker.setTargetClass(this.connection.getClass());
    invoker.setTargetMethod(invocation.getMethod().getName());
    invoker.prepare();/*from w ww  . j  a v a 2  s .c o m*/
    return invoker.invoke();
}