List of usage examples for org.springframework.util MethodInvoker setTargetObject
public void setTargetObject(@Nullable Object targetObject)
From source file:cn.bc.core.util.SpringUtils.java
/** * ?Bean??//from ww w . j a va 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: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();/* w ww.j a va 2 s . c om*/ 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: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]; /*//w ww . ja v a 2s. c om * 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: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); }// w w w .j av a 2 s .co m } } 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: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 www . ja v a 2 s . c om @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.//www . ja v a 2 s. c o m */ 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 . ja v a2 s. c o m @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();/* w w w.j ava2s . co m*/ return invoker.invoke(); }
From source file:org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter.java
/** * Invoke the specified listener method. * @param methodName the name of the listener method * @param arguments the message arguments to be passed in * @return the result returned from the listener method * @throws Exception if thrown by Rabbit API methods * @see #getListenerMethodName//from w w w . jav a 2s.co m * @see #buildListenerArguments */ protected Object invokeListenerMethod(String methodName, Object[] arguments) throws Exception { try { MethodInvoker methodInvoker = new MethodInvoker(); methodInvoker.setTargetObject(getDelegate()); methodInvoker.setTargetMethod(methodName); methodInvoker.setArguments(arguments); methodInvoker.prepare(); return methodInvoker.invoke(); } catch (InvocationTargetException ex) { Throwable targetEx = ex.getTargetException(); if (targetEx instanceof IOException) { throw new AmqpIOException((IOException) targetEx); } else { throw new ListenerExecutionFailedException("Listener method '" + methodName + "' threw exception", targetEx); } } catch (Throwable ex) { ArrayList<String> arrayClass = new ArrayList<String>(); if (arguments != null) { for (int i = 0; i < arguments.length; i++) { arrayClass.add(arguments[i].getClass().toString()); } } throw new ListenerExecutionFailedException("Failed to invoke target method '" + methodName + "' with argument type = [" + StringUtils.collectionToCommaDelimitedString(arrayClass) + "], value = [" + ObjectUtils.nullSafeToString(arguments) + "]", ex); } }
From source file:org.springframework.batch.item.data.RepositoryItemReader.java
private MethodInvoker createMethodInvoker(Object targetObject, String targetMethod) { MethodInvoker invoker = new MethodInvoker(); invoker.setTargetObject(targetObject); invoker.setTargetMethod(targetMethod); return invoker; }