View Javadoc
1   /*
2    *  Licensed to the Apache Software Foundation (ASF) under one
3    *  or more contributor license agreements.  See the NOTICE file
4    *  distributed with this work for additional information
5    *  regarding copyright ownership.  The ASF licenses this file
6    *  to you under the Apache License, Version 2.0 (the
7    *  "License"); you may not use this file except in compliance
8    *  with the License.  You may obtain a copy of the License at
9    *
10   *    http://www.apache.org/licenses/LICENSE-2.0
11   *
12   *  Unless required by applicable law or agreed to in writing,
13   *  software distributed under the License is distributed on an
14   *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   *  KIND, either express or implied.  See the License for the
16   *  specific language governing permissions and limitations
17   *  under the License.
18   *
19   */
20  package org.apache.mina.statemachine.transition;
21  
22  import java.lang.reflect.InvocationTargetException;
23  import java.lang.reflect.Method;
24  import java.util.Arrays;
25  
26  import org.apache.mina.statemachine.State;
27  import org.apache.mina.statemachine.StateMachine;
28  import org.apache.mina.statemachine.context.StateContext;
29  import org.slf4j.Logger;
30  import org.slf4j.LoggerFactory;
31  
32  /**
33   * {@link SelfTransition} which invokes a {@link Method}. The {@link Method} can
34   * have zero or any number of StateContext and State regarding order
35   * <p>
36   * Normally you wouldn't create instances of this class directly but rather use
37   * the {@link SelfTransition} annotation to define the methods which should be
38   * used as transitions in your state machine and then let
39   * {@link org.apache.mina.statemachine#StateMachineFactory} create a
40   * {@link StateMachine} for you.
41   * </p>
42   * 
43   * @author <a href="http://mina.apache.org">Apache MINA Project</a>
44   */
45  public class MethodSelfTransition extends AbstractSelfTransition {
46      private static final Logger LOGGER = LoggerFactory.getLogger(MethodTransition.class);
47  
48      private Method method;
49  
50      private final Object target;
51  
52      private static final Object[] EMPTY_ARGUMENTS = new Object[0];
53  
54      public MethodSelfTransition(Method method, Object target) {
55          super();
56          this.method = method;
57          this.target = target;
58      }
59  
60      /**
61       * Creates a new instance
62       * 
63       * @param methodName
64       *            the target method.
65       * @param target
66       *            the target object.
67       */
68      public MethodSelfTransition(String methodName, Object target) {
69  
70          this.target = target;
71  
72          Method[] candidates = target.getClass().getMethods();
73          Method result = null;
74  
75          for (int i = 0; i < candidates.length; i++) {
76              if (candidates[i].getName().equals(methodName)) {
77                  if (result != null) {
78                      throw new AmbiguousMethodException(methodName);
79                  }
80                  result = candidates[i];
81              }
82          }
83  
84          if (result == null) {
85              throw new NoSuchMethodException(methodName);
86          }
87  
88          this.method = result;
89  
90      }
91  
92      /**
93       * Returns the target {@link Method}.
94       * 
95       * @return the method.
96       */
97      public Method getMethod() {
98          return method;
99      }
100 
101     public boolean doExecute(StateContext stateContext, State state) {
102         Class<?>[] types = method.getParameterTypes();
103 
104         if (types.length == 0) {
105             invokeMethod(EMPTY_ARGUMENTS);
106             return true;
107         }
108 
109         if (types.length > 2) {
110             return false;
111         }
112 
113         Object[] args = new Object[types.length];
114 
115         int i = 0;
116 
117         if (types[i].isAssignableFrom(StateContext.class)) {
118             args[i++] = stateContext;
119         }
120         if ((i < types.length) && types[i].isAssignableFrom(State.class)) {
121             args[i++] = state;
122         }
123 
124         invokeMethod(args);
125 
126         return true;
127     }
128 
129     private void invokeMethod(Object[] arguments) {
130         try {
131             if (LOGGER.isDebugEnabled()) {
132                 LOGGER.debug("Executing method " + method + " with arguments " + Arrays.asList(arguments));
133             }
134             method.invoke(target, arguments);
135         } catch (InvocationTargetException ite) {
136             if (ite.getCause() instanceof RuntimeException) {
137                 throw (RuntimeException) ite.getCause();
138             }
139             throw new MethodInvocationException(method, ite);
140         } catch (IllegalAccessException iae) {
141             throw new MethodInvocationException(method, iae);
142         }
143     }
144 
145 }