1 /*
2 * $Id$
3 *
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
11 *
12 * http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
19 * under the License.
20 */
21 package org.apache.struts.dispatcher;
22
23 import java.lang.reflect.Method;
24
25 import org.apache.struts.action.Action;
26 import org.apache.struts.chain.contexts.ActionContext;
27
28 /**
29 * This abstract class is the stock template for resolving methods for a
30 * {@link Dispatcher}. The implementation handles methods that accept no
31 * arguments or only an {@link ActionContext} instance:
32 * <ul>
33 * <li><code><i>return_type</i> execute()</code></li>
34 * <li><code><i>return_type</i> execute(ActionContext context)</code></li>
35 * </ul>
36 *
37 * @version $Rev$
38 * @since Struts 1.4
39 */
40 public abstract class AbstractMethodResolver implements MethodResolver {
41 private static final long serialVersionUID = -9045373032747695495L;
42
43 /**
44 * The argument listing for a method without arguments.
45 *
46 * @see #EMPTY_ARGUMENT_TYPES
47 */
48 protected static final Object[] EMPTY_ARGUMENTS = {};
49
50 /**
51 * The type listing used for a method without arguments.
52 *
53 * @see #EMPTY_ARGUMENTS
54 */
55 protected static final Class<?>[] EMPTY_ARGUMENT_TYPES = {};
56
57 /**
58 * The argument listing for a method accepting the {@link ActionContext}.
59 */
60 private static final Class<?>[] ACTION_CONTEXT_ARGUMENT_TYPES = { ActionContext.class };
61
62 public Object[] buildArguments(ActionContext context, Method method) {
63 Class<?>[] parameterTypes = method.getParameterTypes();
64 switch (parameterTypes.length) {
65 case 0:
66 return EMPTY_ARGUMENTS;
67
68 case 1:
69 if (parameterTypes[0].isInstance(context)) {
70 return new Object[] { context };
71 }
72 return null;
73
74 default:
75 return null;
76 }
77 }
78
79 public Method resolveMethod(ActionContext context, String methodName) throws NoSuchMethodException {
80 Class<? extends Action> actionClass = context.getAction().getClass();
81
82 // Does the method accept nothing?
83 try {
84 return actionClass.getMethod(methodName, EMPTY_ARGUMENT_TYPES);
85 } catch (NoSuchMethodException e) {
86 // continue
87 }
88
89 // Does the method accept the action context?
90 return actionClass.getMethod(methodName, ACTION_CONTEXT_ARGUMENT_TYPES);
91 }
92
93 }