summaryrefslogtreecommitdiff
path: root/projects/net.wotonomy.web/src/main/java/net/wotonomy/web/WODirectAction.java
blob: 0ad418174a8c67e511c5ff505a5aa7c55d55f55a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
/*
Wotonomy: OpenStep design patterns for pure Java applications.
Copyright (C) 2000 Blacksmith, Inc.

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, see http://www.gnu.org
*/

package net.wotonomy.web;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import jakarta.servlet.http.HttpSession;
import net.wotonomy.foundation.NSArray;
import net.wotonomy.foundation.NSSelector;
import net.wotonomy.foundation.internal.Introspector;
import net.wotonomy.foundation.internal.ValueConverter;

/**
 * A pure java implementation of WODirectAction. This class provides a number of
 * services to subclasses, including access to the query parameters, the
 * request, the session, and logging and debugging facilities. A new instance of
 * the class is created and then destroyed for every request-response cycle.<br>
 * <br>
 *
 * Subclass this to implement direct actions for your application. Subclasses
 * would typically override the constructor to initialize state based on the
 * request, and then provide additional methods that would be invoked based on
 * the value at the end of the URI. <br>
 * <br>
 *
 * Example: "http://www/MyApp.woa/MyActions/search" would call the method named
 * "searchAction" on the DirectAction subclass named "MyActions". If the
 * subclass name is omitted, a subclass named "DirectAction" is assumed to exist
 * within the application.
 *
 * @author michael@mpowers.net
 * @author $Author: cgruber $
 * @version $Revision: 905 $
 */
public class WODirectAction {
	private WORequest request;
	WOContext context;

	/**
	 * Default constructor. This is called implicitly by subclasses in all cases.
	 * Package access only.
	 */
	WODirectAction() {

	}

	/**
	 * Request constructor. This is the constructor used to create an action in
	 * response to a user request. Override to perform any necessary initialization
	 * in your subclass.
	 */
	public WODirectAction(WORequest aRequest) {
		this();
		request = aRequest;
	}

	/**
	 * Returns the response from the component named "Main".
	 */
	public WOActionResults defaultAction() {
		return pageWithName("Main").generateResponse();
	}

	/**
	 * Returns the WORequest object for the current request.
	 */
	public WORequest request() {
		return request;
	}

	/**
	 * Returns the existing session, or null if no session exists.
	 */
	public WOSession existingSession() {
		// FIXME: this is incorrect
		HttpSession session = request.servletRequest().getSession();
		if (session == null)
			return null;
		WOSession wosession = new WOSession();
		wosession.setServletSession(session);
		return wosession;
	}

	/**
	 * Returns the existing session if it exists. If no session exists, returns a
	 * newly created session. Note that if the user client does not support session
	 * ids/cookies, this will create a new session with each request.
	 */
	public WOSession session() {
		// FIXME: this is incorrect
		WOSession wosession = new WOSession();
		wosession.setServletSession(request.servletRequest().getSession(true));
		return wosession;
	}

	/**
	 * Returns the named WOComponent.
	 */
	public WOComponent pageWithName(String aString) {
		return request.application().pageWithName(aString, context);
	}

	/**
	 * Appends "Action" to the specified string and tries to invoke method with that
	 * name and no arguments. Returns null if the method does not exist. If anAction
	 * is null, "defaultAction" will be assumed.
	 */
	public WOActionResults performActionNamed(String anAction) {
		if (anAction == null)
			anAction = "default";
		try {
			NSSelector sel = new NSSelector(anAction + "Action");
			return (WOActionResults) sel.invoke(this);
		} catch (NoSuchMethodException exc) {
			// returns below
		} catch (InvocationTargetException exc) {
			Throwable e = exc.getTargetException();
			exc.printStackTrace();
			throw new RuntimeException(e.toString());
		} catch (Exception exc) {
			exc.printStackTrace();
			throw new RuntimeException(exc.toString());
		}
		WOResponse error = new WOResponse();
		error.setStatus(404); // not found
		error.appendContentString("Could not find method named \"" + anAction + "Action\".");
		return error;
	}

	/**
	 * Assigns the arrays of form values for the specified keys to properties on
	 * this object with matching names whose type is NSArray or is convertable from
	 * a Collection.
	 */
	public void takeFormValueArraysForKeyArray(NSArray anArray) {
		if (anArray == null)
			return;

		Method m;
		Object key;
		Object value;
		java.util.Enumeration e = anArray.objectEnumerator();
		while (e.hasMoreElements()) {
			key = e.nextElement();
			value = request.formValuesForKey(key.toString());
			try {
				// obtain setter method for this class
				m = Introspector.getPropertyWriteMethod(this.getClass(), key.toString(),
						new Class[] { Introspector.WILD });
				if (m != null) {
					// if value isn't null, try to convert it to type
					if (value != null) {
						Class[] paramTypes = m.getParameterTypes();
						if (!paramTypes[0].isAssignableFrom(value.getClass())) {
							// TODO: find a constructor whose parameter
							// is assignable from value.getClass()
							// and instantiate it in the place of value.
						}
					}
					// set property to value
					m.invoke(this, new Object[] { value });
				}
			} catch (Exception exc) {
				// show error and continue
				debugString("WODirectAction.takeFormValuesForKeyArray: " + exc);
			}
		}

	}

	/**
	 * Assigns the form values for the specified keys to properties on this object
	 * with matching names.
	 */
	public void takeFormValuesForKeyArray(NSArray anArray) {
		if (anArray == null)
			return;

		Method m;
		Object key;
		Object value;
		java.util.Enumeration e = anArray.objectEnumerator();
		while (e.hasMoreElements()) {
			key = e.nextElement();
			value = request.formValueForKey(key.toString());
			try {
				// obtain setter method for this class
				m = Introspector.getPropertyWriteMethod(this.getClass(), key.toString(),
						new Class[] { Introspector.WILD });
				if (m != null) {
					// if value isn't null, try to convert it to type
					if (value != null) {
						Class[] paramTypes = m.getParameterTypes();
						Object convertedValue = ValueConverter.convertObjectToClass(value, paramTypes[0]);
						if (convertedValue != null) {
							value = convertedValue;
						}
					}
					// set property to value
					m.invoke(this, new Object[] { value });
				}
			} catch (Exception exc) {
				// show error and continue
				debugString("WODirectAction.takeFormValuesForKeyArray: " + exc);
			}
		}

	}

	/**
	 * Writes a message to the standard error stream.
	 */
	public static void logString(String aString) {
		System.err.println(aString);
	}

	/**
	 * Writes a message to the standard error stream if debugging is activated.
	 */
	public static void debugString(String aString) {
		// TODO: Check to see if debugging is enabled.
		System.err.println(aString);
	}
}

/*
 * $Log$ Revision 1.2 2006/02/19 01:44:02 cgruber Add xmlrpc files Remove jclark
 * and replace with dom4j and javax.xml.sax stuff Re-work dependencies and
 * imports so it all compiles.
 *
 * Revision 1.1 2006/02/16 13:22:22 cgruber Check in all sources in
 * eclipse-friendly maven-enabled packages.
 *
 * Revision 1.5 2003/01/13 22:24:51 mpowers Request-response cycle is working
 * with session and page persistence.
 *
 * Revision 1.4 2003/01/09 21:16:48 mpowers Bringing request-response cycle more
 * into conformance.
 *
 * Revision 1.3 2003/01/07 15:58:11 mpowers Implementing the request-response
 * cycle. WOSession refactored to support distribution.
 *
 * Revision 1.2 2002/12/17 14:57:43 mpowers Minor corrections to WORequests's
 * parsing, and updated javadocs.
 *
 * Revision 1.1.1.1 2000/12/21 15:53:18 mpowers Contributing wotonomy.
 *
 * Revision 1.2 2000/12/20 16:25:50 michael Added log to all files.
 *
 *
 */