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-06-18 10:24:13 -0700 (Thu, 18 Jun 2009) $'
10
 * '$Revision: 4959 $'
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.FileInputStream;
30
import java.io.FileNotFoundException;
31
import java.io.IOException;
32
import java.io.InputStream;
33
import java.io.OutputStream;
34
import java.io.PrintWriter;
35
import java.util.Hashtable;
36

    
37
import javax.servlet.http.HttpServletRequest;
38
import javax.servlet.http.HttpServletResponse;
39

    
40
import org.apache.log4j.Logger;
41

    
42
import edu.ucsb.nceas.shared.BaseException;
43
import edu.ucsb.nceas.utilities.FileUtil;
44

    
45
public class ResponseUtil {
46
	
47
	// 101XXX - general errors
48
	public static Long GENERAL_UTILITY_ERROR = new Long(101001);	
49
	public static Long METACAT_UTILITY_ERROR = new Long(101002);
50
	// 104XXX - property errors
51
	public static Long PROPERTY_NOT_FOUND = new Long(104001);	
52
	// 105XXX - permission errors
53
	public static Long NO_READ_PERMISSION = new Long(105001);
54
	// 130XXX - scheduler errors
55
	public static Long SCHEDULE_WORKFLOW_ERROR = new Long(130001);
56
	
57
	// errorCodes is a lookup table for generic messages for each code.  It
58
	// is better to use the sendError() versions that accept an explicit 
59
	// error message;
60
	static Hashtable<Long, String> errorCodes = new Hashtable<Long, String>();
61
	static {
62
		errorCodes.put(GENERAL_UTILITY_ERROR, "General utility error");
63
		errorCodes.put(METACAT_UTILITY_ERROR, "Metacat utility error");
64
		errorCodes.put(PROPERTY_NOT_FOUND, "Property not found");
65
		errorCodes.put(NO_READ_PERMISSION, "Read permission denied for user");
66
		errorCodes.put(SCHEDULE_WORKFLOW_ERROR, "Schedule workflow error");
67
	}
68
	
69
	private static Logger logMetacat = Logger.getLogger(ResponseUtil.class);
70
	
71
	private static int DEFAULT_BUFFER_SIZE = 4 * 1024; // 4K buffer
72
	
73
	/**
74
	 * private constructor - all methods are static so there is no
75
     * no need to instantiate.
76
	 */
77
	private ResponseUtil() {}
78
	
79
	/**
80
	 * Redirect a response.
81
	 * 
82
	 * @param response
83
	 *            that is to be redirected
84
	 * @param destination
85
	 *            the context-relative URL to which the request is forwarded
86
	 */
87
	public static void redirectResponse(HttpServletRequest request,
88
			HttpServletResponse response, String destination) throws MetacatUtilException {
89
		try {
90
			logMetacat.debug("Redirecting response to " + request.getContextPath() + destination);
91
			response.sendRedirect(request.getContextPath() + destination);
92
		} catch (IOException ioe) {
93
			throw new MetacatUtilException("I/O error when redirecting response to: " + destination);
94
		}
95
	}
96
	
97
	public static void writeFileToOutput(HttpServletResponse response, String fileDir, String fileName)
98
		throws MetacatUtilException {
99
		
100
		writeFileToOutput(response, fileDir, fileName, DEFAULT_BUFFER_SIZE);
101
	}
102
	
103
	public static void writeFileToOutput(HttpServletResponse response, String fileDir, String fileName, int bufferSize)
104
			throws MetacatUtilException {
105
		String filePath = "";
106
		try {
107
			filePath = fileDir + FileUtil.getFS() + fileName;
108
			
109
			int lastFileSep = fileName.lastIndexOf(FileUtil.getFS());
110
			String shortFileName = fileName.substring(lastFileSep + 1, fileName.length());
111
			response.setHeader("Content-Disposition", "attachment; filename=\"" + shortFileName + "\"");
112
			
113
			InputStream inputStream = new FileInputStream(filePath);
114
			OutputStream outputStream = response.getOutputStream();
115
			
116
			byte[] byteBuffer = new byte[bufferSize]; 
117

    
118
			int b = 0;
119
			while ((b = inputStream.read(byteBuffer)) != -1) {
120
				outputStream.write(byteBuffer, 0, b);
121
			}	
122
			
123
		} catch (FileNotFoundException fnfe) {
124
			throw new MetacatUtilException("Error finding file: " + filePath 
125
					+ " when writing to output");
126
		} catch (IOException ioe) {
127
			throw new MetacatUtilException("I/O Error when writing: " + filePath 
128
					+ "  to output");
129
		}
130
	}
131
	
132
	public static void sendErrorXML(HttpServletResponse response, Long errorCode,
133
			BaseException be) throws ErrorSendingErrorException {
134

    
135
		logMetacat.error(errorCodes.get(errorCode) + " : " + be.getMessage());
136

    
137
		PrintWriter out = null;
138
		try {
139
			out = response.getWriter();
140
			response.setContentType("text/xml");
141

    
142
			out.println("<?xml version=\"1.0\"?>");
143
			out.println("<error>");
144
			out.println("<code>" + errorCode + "</code>");
145
			out.println("<defaultMessage>" + errorCodes.get(errorCode) + "</defaultMessage>");
146
			out.println("<coreMessage>" + be.getCoreMessage() + "</coreMessage>");
147
			out.println("<chainedMessage>" + be.getMessage() + "</chainedMessage>");
148
			out.println("</error>");
149

    
150
		} catch (IOException ioe) {
151
			throw new ErrorSendingErrorException("I/O error when returning error: "
152
					+ errorCode + " : " + ioe.getMessage());
153
		} finally {
154
			if (out != null) {
155
				out.close();
156
			}
157
		}
158
	}
159
	
160
	public static void sendErrorXML(HttpServletResponse response, Long errorCode,
161
			String message) throws ErrorSendingErrorException {
162

    
163
		logMetacat.error(errorCodes.get(errorCode) + " : " + message);
164

    
165
		PrintWriter out = null;
166
		try {
167
			out = response.getWriter();
168
			response.setContentType("text/xml");
169

    
170
			out.println("<?xml version=\"1.0\"?>");
171
			out.println("<error>");
172
			out.println("<code>" + errorCode + "</code>");
173
			out.println("<defaultMessage>" + errorCodes.get(errorCode) + "</defaultMessage>");
174
			out.println("<coreMessage>" + message + "</coreMessage>");
175
			out.println("<chainedMessage></chainedMessage>");
176
			out.println("</error>");
177

    
178
		} catch (IOException ioe) {
179
			throw new ErrorSendingErrorException("I/O error when returning error: "
180
					+ errorCode + " : " + ioe.getMessage());
181
		} finally {
182
			if (out != null) {
183
				out.close();
184
			}
185
		}
186
	}
187
	
188
	public static void sendSuccessXML(HttpServletResponse response, String message) 
189
		throws ErrorSendingErrorException {
190

    
191
		PrintWriter out = null;
192
		try {
193
			out = response.getWriter();
194
			response.setContentType("text/xml");
195

    
196
			out.println("<?xml version=\"1.0\"?>");
197
			out.println("<success>" + message + "</success>");
198
		} catch (IOException ioe) {
199
			throw new ErrorSendingErrorException("I/O error when returning success XML: "
200
					+ message + " : " + ioe.getMessage());
201
		} finally {
202
			if (out != null) {
203
				out.close();
204
			}
205
		}
206
	}
207
}
(10-10/13)