Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that implements administrative methods 
4
 *  Copyright: 2008 Regents of the University of California and the
5
 *             National Center for Ecological Analysis and Synthesis
6
 *    Authors: Michael Daigle
7
 * 
8
 *   '$Author: daigle $'
9
 *     '$Date: 2009-08-14 14:26:08 -0700 (Fri, 14 Aug 2009) $'
10
 * '$Revision: 5027 $'
11
 *
12
 * This program is free software; you can redistribute it and/or modify
13
 * it under the terms of the GNU General Public License as published by
14
 * the Free Software Foundation; either version 2 of the License, or
15
 * (at your option) any later version.
16
 *
17
 * This program is distributed in the hope that it will be useful,
18
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
 * GNU General Public License for more details.
21
 *
22
 * You should have received a copy of the GNU General Public License
23
 * along with this program; if not, write to the Free Software
24
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
25
 */
26

    
27
package edu.ucsb.nceas.metacat.util;
28

    
29
import java.io.InputStreamReader;
30
import java.io.IOException;
31
import java.io.BufferedReader;
32
import java.io.PrintWriter;
33
import java.io.StringReader;
34
import java.net.MalformedURLException;
35
import java.net.URL;
36
import java.net.URLConnection;
37
import java.util.Enumeration;
38
import java.util.HashMap;
39
import java.util.Hashtable;
40
import java.util.Set;
41
import java.util.Vector;
42

    
43
import javax.servlet.ServletContext;
44
import javax.servlet.ServletException;
45
import javax.servlet.http.Cookie;
46
import javax.servlet.http.HttpServletRequest;
47
import javax.servlet.http.HttpServletResponse;
48
import javax.servlet.http.HttpSession;
49

    
50
import org.apache.commons.httpclient.HttpClient;
51
import org.apache.commons.httpclient.HttpException;
52
import org.apache.commons.httpclient.methods.PostMethod;
53
import org.apache.log4j.Logger;
54

    
55
import edu.ucsb.nceas.metacat.service.SessionService;
56
import edu.ucsb.nceas.metacat.shared.MetacatUtilException;
57

    
58
public class RequestUtil {
59
	
60
	private static Logger logMetacat = Logger.getLogger(RequestUtil.class);
61
	
62
	/**
63
	 * private constructor - all methods are static so there is no
64
     * no need to instantiate.
65
	 */
66
	private RequestUtil() {}
67
	
68
	/**
69
	 * Forward a request that was received by this servlet on to another JSP
70
	 * page or servlet to continue handling the request.
71
	 * 
72
	 * @param request
73
	 *            to be forwarded
74
	 * @param response
75
	 *            that can be used for writing output to the client
76
	 * @param destination
77
	 *            the context-relative URL to which the request is forwarded
78
	 */
79
	public static void forwardRequest(HttpServletRequest request,
80
			HttpServletResponse response, String destinationUrl, Hashtable<String, String[]> params)
81
			throws IOException, ServletException {
82

    
83
		destinationUrl += "?" + paramsToQuery(params);
84
		
85
		logMetacat.debug("Forwarding request to " + destinationUrl);
86
		ServletContext servletContext = request.getSession()
87
				.getServletContext();
88

    
89
		servletContext.getRequestDispatcher(destinationUrl).forward(request,
90
				response);
91
	}
92

    
93
	/**
94
	 * Post a request and return the response body
95
	 * 
96
	 * @param httpClient
97
	 *            The HttpClient to use in the post.  This is passed in because
98
     * 			  the same client may be used in several posts
99
	 * @param url
100
	 *            the url to post to
101
	 * @param paramMap
102
	 *            map of parameters to add to the post
103
	 * @returns a string holding the response body
104
	 */
105
	public static String post(HttpClient httpClient, String url,
106
			HashMap<String, String> paramMap) throws IOException, HttpException {
107

    
108
		PostMethod method = new PostMethod(url);
109

    
110
		// Configure the form parameters
111
		if (paramMap != null) {
112
			Set<String> paramNames = paramMap.keySet();
113
			for (String paramName : paramNames) {
114
				method.addParameter(paramName, paramMap.get(paramName));
115
			}
116
		}
117

    
118
		// Execute the POST method
119
		int statusCode = httpClient.executeMethod(method);
120
		if (statusCode != -1) {
121
			String contents = method.getResponseBodyAsString();
122
			method.releaseConnection();
123
			return (contents);
124
		}
125

    
126
		return null;
127
	}
128
	
129
	public static String get(String urlString, Hashtable<String, String[]> params)  throws MetacatUtilException {	
130
		try {
131
			URL url = new URL(urlString);
132
			URLConnection urlConn = url.openConnection();
133
			
134
			urlConn.setDoOutput(true);
135
			
136
			PrintWriter pw = new PrintWriter(urlConn.getOutputStream());
137
			pw.println(paramsToQuery(params));
138
			pw.close();
139
			
140
			// get the input from the request
141
			BufferedReader in = 
142
				new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
143
			
144
			StringBuffer sb = new StringBuffer();
145
			String line;
146
			while ((line = in.readLine()) != null) {
147
				sb.append(line);
148
			}
149
			in.close();
150
			
151
			return sb.toString();
152
		} catch (MalformedURLException mue) {
153
			throw new MetacatUtilException("URL error when contacting: " + urlString + " : " + mue.getMessage());
154
		} catch (IOException ioe) {
155
			throw new MetacatUtilException("I/O error when contacting: " + urlString + " : " + ioe.getMessage());
156
		} 
157
	}
158
	
159
	/**
160
	 * Get a cookie from a request by the cookie name
161
	 * 
162
	 * @param request
163
	 *            the request from which to get the cookie
164
	 * @param cookieName
165
	 *            the name of the cookie to look for
166
	 */
167
	public static Cookie getCookie(HttpServletRequest request, String cookieName)  {
168
		Cookie sessionCookies[] = request.getCookies();
169

    
170
		if (sessionCookies == null) {
171
			return null;
172
		}
173
		
174
		for (int i = 0; i < sessionCookies.length; i++) {
175
			if(sessionCookies[i].getName().equals(cookieName)) {
176
				return sessionCookies[i];
177
			}
178
		}	
179
		
180
		return null;
181
	}
182
	
183
	/**
184
	 * Get the session data from a request. The Scenarios we can run across
185
	 * here: 
186
	 * -- the session id parameter was set in the request parameters 
187
	 * -- request.getSession returns a new session. There is a chance that the
188
	 *    session id was set in a cookie. Check for a JSESSIONID cookie and use
189
	 *    that id if provided. 
190
	 * -- request.getSession returns a session that is a)
191
	 *    preexisting or b) new but without a JSESSIONID cookie. Use the session id
192
	 *    from this session
193
	 * 
194
	 * @param request
195
	 *            the request from which to get the session data
196
	 * @return the session data object representing the active session for this
197
	 *         request. If there is no active session, the public session data
198
	 *         is returned
199
	 */
200
	public static SessionData getSessionData(HttpServletRequest request) {
201
		SessionData sessionData = null;
202
		String sessionId = null;
203

    
204
		Hashtable<String, String[]> params = getParameters(request);
205

    
206
		if (params.containsKey("sessionid")) {
207
			// the session id is specified in the request parameters
208
			sessionId = ((String[]) params.get("sessionid"))[0];
209
			logMetacat.debug("session ID provided in request properties: " + sessionId);
210
		} else {
211
			HttpSession session = request.getSession(true);
212
			if (session.isNew()) {
213
				// this is a new session
214
				Cookie sessionCookie = RequestUtil.getCookie(request, "JSESSIONID");
215
				if (sessionCookie != null) {
216
					// and there is a JSESSIONID cookie
217
					sessionId = sessionCookie.getValue();
218
					logMetacat.debug("session ID provided in request cookie: "
219
							+ sessionId);
220
				}
221
			}
222
			if (sessionId == null) {
223
				// there is an existing session (session is old)
224
				sessionId = session.getId();
225
				logMetacat.debug("session ID retrieved from request: " + sessionId);
226
			}
227
		}
228

    
229
		// if the session id is registered in SessionService, get the
230
		// SessionData for it. Otherwise, use the public session.
231
		if (SessionService.isSessionRegistered(sessionId)) {
232
			logMetacat.debug("retrieving session data from session service "
233
					+ "for session id " + sessionId);
234
			sessionData = SessionService.getRegisteredSession(sessionId);
235
		} else {
236
			logMetacat.debug("using public session.  Given session id is "
237
					+ "registered: " + sessionId);
238
			sessionData = SessionService.getPublicSession();
239
		}
240
		
241
		return sessionData;
242
	}
243

    
244
	/**
245
	 * Get a cookie from a request by the cookie name
246
	 * 
247
	 * @param request
248
	 *            the request from which to get the cookie
249
	 * @param cookieName
250
	 *            the name of the cookie to look for
251
	 */
252
	public static Hashtable<String, String[]> getParameters(HttpServletRequest request)  {
253
		Hashtable<String, String[]> params = new Hashtable<String, String[]>();
254
		
255
		Enumeration<String> paramlist = (Enumeration<String>)request.getParameterNames();
256
		while (paramlist.hasMoreElements()) {
257
			String name = (String) paramlist.nextElement();
258
			String[] value = request.getParameterValues(name);
259
			params.put(name, value);
260
		}
261
		
262
		return params;
263
	}
264
	
265
	/**
266
	 * Add a list of errors to the request. The pages will pick up the errors
267
	 * and display them where appropriate.
268
	 * 
269
	 * @param request
270
	 *            the request that will get forwarded
271
	 * @param errorVector
272
	 *            a list of error strings
273
	 */
274
	public static void setRequestErrors(HttpServletRequest request,
275
			Vector<String> errorVector) {
276
		request.setAttribute("formErrors", "true");
277
		request.setAttribute("processingErrors", errorVector);
278
	}
279
	
280
	/**
281
	 * Add a list of form errors to the request. The pages will pick up the
282
	 * errors and display them where appropriate.
283
	 * 
284
	 * @param request
285
	 *            the request that will get forwarded
286
	 * @param errorVector
287
	 *            a list of form error strings
288
	 */
289
	public static void setRequestFormErrors(HttpServletRequest request,
290
			Vector<String> errorVector) {
291
		request.setAttribute("formErrors", "true");
292
		request.setAttribute("formFieldErrors", errorVector);
293
	}
294
	
295
	/**
296
	 * Add a list of success messages to the request. The pages will pick up the
297
	 * messages and display them where appropriate.
298
	 * 
299
	 * @param request
300
	 *            the request that will get forwarded
301
	 * @param errorVector
302
	 *            a list of success message strings
303
	 */
304
	public static void setRequestSuccess(HttpServletRequest request,
305
			Vector<String> successVector) {
306
		request.setAttribute("formSuccess", "true");
307
		request.setAttribute("processingSuccess", successVector);
308
	}
309
	
310
	/**
311
	 * Add a list of general messages to the request. The pages will pick up the
312
	 * messages and display them where appropriate.
313
	 * 
314
	 * @param request
315
	 *            the request that will get forwarded
316
	 * @param errorVector
317
	 *            a list of general message strings
318
	 */
319
	public static void setRequestMessage(HttpServletRequest request,
320
			Vector<String> messageVector) {
321
		request.setAttribute("formMessage", "true");
322
		request.setAttribute("processingMessage", messageVector);
323
	}
324
	
325
	/**
326
	 * Add a list of general messages to the request. The pages will pick up the
327
	 * messages and display them where appropriate.
328
	 * 
329
	 * @param request
330
	 *            the request that will get forwarded
331
	 * @param errorVector
332
	 *            a list of general message strings
333
	 */
334
	public static void clearRequestMessages(HttpServletRequest request) {
335
		request.setAttribute("formMessage", null);
336
		request.setAttribute("formSuccess", null);
337
		request.setAttribute("formErrors", null);
338
		request.setAttribute("processingMessage", null);
339
		request.setAttribute("processingSuccess", null);
340
		request.setAttribute("formFieldErrors", null);
341
		request.setAttribute("processingErrors", null);
342
	}
343
	
344
	/**
345
	 * Add the user's login id to the session on this request
346
	 * 
347
	 * @param request
348
	 *            the request that will get forwarded
349
	 * @param userId
350
	 *            the user's login id
351
	 */
352
	public static void setUserId(HttpServletRequest request, String userId) {
353
		request.getSession().setAttribute("userId", userId);
354
	}
355
	
356
	private static String paramsToQuery(Hashtable<String, String[]> params) {
357
		String query = "";
358
		if (params != null) {
359
			boolean firstParam = true;
360
			for (String paramName : params.keySet()) {
361
				if (firstParam) {
362
//					query = "?" ;
363
					firstParam = false;
364
				} else {
365
					query += "&";
366
				}
367
				query += paramName + "=" + params.get(paramName)[0];
368
			}
369
		}
370
		
371
		return query;
372
	}
373
	
374

    
375
}
(10-10/14)