Project

General

Profile

1 4080 daigle
/**
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$'
9
 *     '$Date$'
10
 * '$Revision$'
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 4951 daigle
import java.io.FileInputStream;
30
import java.io.FileNotFoundException;
31 4080 daigle
import java.io.IOException;
32 4951 daigle
import java.io.InputStream;
33
import java.io.OutputStream;
34 4959 daigle
import java.io.PrintWriter;
35
import java.util.Hashtable;
36 4080 daigle
37
import javax.servlet.http.HttpServletRequest;
38
import javax.servlet.http.HttpServletResponse;
39
40
import org.apache.log4j.Logger;
41
42 5015 daigle
import edu.ucsb.nceas.metacat.shared.BaseException;
43
import edu.ucsb.nceas.metacat.shared.MetacatUtilException;
44 4951 daigle
import edu.ucsb.nceas.utilities.FileUtil;
45
46 4080 daigle
public class ResponseUtil {
47
48 4959 daigle
	// 101XXX - general errors
49
	public static Long GENERAL_UTILITY_ERROR = new Long(101001);
50
	public static Long METACAT_UTILITY_ERROR = new Long(101002);
51
	// 104XXX - property errors
52
	public static Long PROPERTY_NOT_FOUND = new Long(104001);
53
	// 105XXX - permission errors
54
	public static Long NO_READ_PERMISSION = new Long(105001);
55
	// 130XXX - scheduler errors
56
	public static Long SCHEDULE_WORKFLOW_ERROR = new Long(130001);
57 4967 daigle
	public static Long UNSCHEDULE_WORKFLOW_ERROR = new Long(130002);
58
	public static Long RESCHEDULE_WORKFLOW_ERROR = new Long(130003);
59
	public static Long GET_SCHEDULED_WORKFLOW_ERROR = new Long(130004);
60 5013 daigle
	public static Long DELETE_SCHEDULED_WORKFLOW_ERROR = new Long(130005);
61 4959 daigle
62 4967 daigle
63 4959 daigle
	// errorCodes is a lookup table for generic messages for each code.  It
64
	// is better to use the sendError() versions that accept an explicit
65
	// error message;
66
	static Hashtable<Long, String> errorCodes = new Hashtable<Long, String>();
67
	static {
68
		errorCodes.put(GENERAL_UTILITY_ERROR, "General utility error");
69
		errorCodes.put(METACAT_UTILITY_ERROR, "Metacat utility error");
70
		errorCodes.put(PROPERTY_NOT_FOUND, "Property not found");
71
		errorCodes.put(NO_READ_PERMISSION, "Read permission denied for user");
72
		errorCodes.put(SCHEDULE_WORKFLOW_ERROR, "Schedule workflow error");
73 4967 daigle
		errorCodes.put(UNSCHEDULE_WORKFLOW_ERROR, "Unschedule workflow error");
74
		errorCodes.put(RESCHEDULE_WORKFLOW_ERROR, "Reschedule workflow error");
75
		errorCodes.put(GET_SCHEDULED_WORKFLOW_ERROR, "Get scheduled workflow error");
76 5013 daigle
		errorCodes.put(DELETE_SCHEDULED_WORKFLOW_ERROR, "Delete scheduled workflow error");
77 4959 daigle
	}
78
79 4080 daigle
	private static Logger logMetacat = Logger.getLogger(ResponseUtil.class);
80
81 4951 daigle
	private static int DEFAULT_BUFFER_SIZE = 4 * 1024; // 4K buffer
82
83 4080 daigle
	/**
84
	 * private constructor - all methods are static so there is no
85
     * no need to instantiate.
86
	 */
87
	private ResponseUtil() {}
88
89
	/**
90
	 * Redirect a response.
91
	 *
92
	 * @param response
93
	 *            that is to be redirected
94
	 * @param destination
95
	 *            the context-relative URL to which the request is forwarded
96
	 */
97
	public static void redirectResponse(HttpServletRequest request,
98 4951 daigle
			HttpServletResponse response, String destination) throws MetacatUtilException {
99
		try {
100
			logMetacat.debug("Redirecting response to " + request.getContextPath() + destination);
101
			response.sendRedirect(request.getContextPath() + destination);
102
		} catch (IOException ioe) {
103
			throw new MetacatUtilException("I/O error when redirecting response to: " + destination);
104
		}
105 4080 daigle
	}
106 4951 daigle
107
	public static void writeFileToOutput(HttpServletResponse response, String fileDir, String fileName)
108
		throws MetacatUtilException {
109
110
		writeFileToOutput(response, fileDir, fileName, DEFAULT_BUFFER_SIZE);
111
	}
112
113
	public static void writeFileToOutput(HttpServletResponse response, String fileDir, String fileName, int bufferSize)
114
			throws MetacatUtilException {
115
		String filePath = "";
116
		try {
117
			filePath = fileDir + FileUtil.getFS() + fileName;
118
119
			int lastFileSep = fileName.lastIndexOf(FileUtil.getFS());
120
			String shortFileName = fileName.substring(lastFileSep + 1, fileName.length());
121
			response.setHeader("Content-Disposition", "attachment; filename=\"" + shortFileName + "\"");
122
123
			InputStream inputStream = new FileInputStream(filePath);
124
			OutputStream outputStream = response.getOutputStream();
125
126
			byte[] byteBuffer = new byte[bufferSize];
127
128
			int b = 0;
129
			while ((b = inputStream.read(byteBuffer)) != -1) {
130
				outputStream.write(byteBuffer, 0, b);
131
			}
132
133
		} catch (FileNotFoundException fnfe) {
134
			throw new MetacatUtilException("Error finding file: " + filePath
135
					+ " when writing to output");
136
		} catch (IOException ioe) {
137
			throw new MetacatUtilException("I/O Error when writing: " + filePath
138
					+ "  to output");
139
		}
140
	}
141 4959 daigle
142 4967 daigle
	public static void send(HttpServletResponse response, String content) throws ErrorSendingErrorException {
143
144
		PrintWriter out = null;
145
		try {
146
			out = response.getWriter();
147
			response.setContentType("text/xml");
148
149
			out.print(content);
150
151
		} catch (IOException ioe) {
152
			throw new ErrorSendingErrorException("I/O error when sending content: "
153
					+ content + " : " + ioe.getMessage());
154
		} finally {
155
			if (out != null) {
156
				out.close();
157
			}
158
		}
159
	}
160
161 4959 daigle
	public static void sendErrorXML(HttpServletResponse response, Long errorCode,
162
			BaseException be) throws ErrorSendingErrorException {
163
164
		logMetacat.error(errorCodes.get(errorCode) + " : " + be.getMessage());
165
166
		PrintWriter out = null;
167
		try {
168
			out = response.getWriter();
169
			response.setContentType("text/xml");
170
171
			out.println("<?xml version=\"1.0\"?>");
172
			out.println("<error>");
173
			out.println("<code>" + errorCode + "</code>");
174
			out.println("<defaultMessage>" + errorCodes.get(errorCode) + "</defaultMessage>");
175
			out.println("<coreMessage>" + be.getCoreMessage() + "</coreMessage>");
176
			out.println("<chainedMessage>" + be.getMessage() + "</chainedMessage>");
177
			out.println("</error>");
178
179
		} catch (IOException ioe) {
180
			throw new ErrorSendingErrorException("I/O error when returning error: "
181
					+ errorCode + " : " + ioe.getMessage());
182
		} finally {
183
			if (out != null) {
184
				out.close();
185
			}
186
		}
187
	}
188
189
	public static void sendErrorXML(HttpServletResponse response, Long errorCode,
190
			String message) throws ErrorSendingErrorException {
191
192
		logMetacat.error(errorCodes.get(errorCode) + " : " + message);
193
194
		PrintWriter out = null;
195
		try {
196
			out = response.getWriter();
197
			response.setContentType("text/xml");
198
199
			out.println("<?xml version=\"1.0\"?>");
200
			out.println("<error>");
201
			out.println("<code>" + errorCode + "</code>");
202
			out.println("<defaultMessage>" + errorCodes.get(errorCode) + "</defaultMessage>");
203
			out.println("<coreMessage>" + message + "</coreMessage>");
204
			out.println("<chainedMessage></chainedMessage>");
205
			out.println("</error>");
206
207
		} catch (IOException ioe) {
208
			throw new ErrorSendingErrorException("I/O error when returning error: "
209
					+ errorCode + " : " + ioe.getMessage());
210
		} finally {
211
			if (out != null) {
212
				out.close();
213
			}
214
		}
215
	}
216
217
	public static void sendSuccessXML(HttpServletResponse response, String message)
218
		throws ErrorSendingErrorException {
219
220
		PrintWriter out = null;
221
		try {
222
			out = response.getWriter();
223
			response.setContentType("text/xml");
224
225
			out.println("<?xml version=\"1.0\"?>");
226
			out.println("<success>" + message + "</success>");
227
		} catch (IOException ioe) {
228
			throw new ErrorSendingErrorException("I/O error when returning success XML: "
229
					+ message + " : " + ioe.getMessage());
230
		} finally {
231
			if (out != null) {
232
				out.close();
233
			}
234
		}
235
	}
236 4967 daigle
237
	public static boolean isSuccessXML(String message) {
238
239
		return message.indexOf("<success>") != -1;
240
	}
241
242 4080 daigle
}