View Javadoc

1   /*--------------------------------------------------------------------------
2    *  Copyright 2008 utgenome.org
3    *
4    *  Licensed under the Apache License, Version 2.0 (the "License");
5    *  you may not use this file except in compliance with the License.
6    *  You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   *  Unless required by applicable law or agreed to in writing, software
11   *  distributed under the License is distributed on an "AS IS" BASIS,
12   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *  See the License for the specific language governing permissions and
14   *  limitations under the License.
15   *--------------------------------------------------------------------------*/
16  //--------------------------------------
17  // utgb-core Project
18  //
19  // WebTrackBase.java
20  // Since: Jan 22, 2008
21  //
22  // $URL$ 
23  // $Author$
24  //--------------------------------------
25  package org.utgenome.gwt.utgb.server;
26  
27  import java.io.BufferedReader;
28  import java.io.IOException;
29  import java.io.Reader;
30  import java.util.ArrayList;
31  import java.util.Enumeration;
32  import java.util.List;
33  
34  import javax.servlet.ServletException;
35  import javax.servlet.http.HttpServletRequest;
36  import javax.servlet.http.HttpServletResponse;
37  
38  import org.utgenome.UTGBErrorCode;
39  import org.utgenome.UTGBException;
40  import org.xerial.core.XerialException;
41  import org.xerial.db.DBException;
42  import org.xerial.db.sql.DatabaseAccess;
43  import org.xerial.db.sql.SQLExpression;
44  import org.xerial.lens.JSONLens;
45  import org.xerial.util.FileResource;
46  import org.xerial.util.ObjectHandler;
47  import org.xerial.util.ObjectHandlerBase;
48  import org.xerial.util.StringUtil;
49  import org.xerial.util.log.Logger;
50  
51  /**
52   * @author leo
53   * 
54   */
55  public abstract class WebTrackBase extends RequestHandlerBase {
56  
57  	private static final long serialVersionUID = 1L;
58  	private static Logger _logger = Logger.getLogger(WebTrackBase.class);
59  
60  	public static String createSQLStatement(String sqlTemplate, Object... args) throws UTGBException {
61  		try {
62  			return SQLExpression.fillTemplate(sqlTemplate, args);
63  		}
64  		catch (DBException e) {
65  			throw new UTGBException(UTGBErrorCode.MaliciousSQLSyntax, e);
66  		}
67  	}
68  
69  	/**
70  	 * Retrieves the database access
71  	 * 
72  	 * @param name
73  	 * @return
74  	 * @throws UTGBException
75  	 */
76  	public DatabaseAccess getDatabaseAccess(String databaseID) throws UTGBException {
77  		return UTGBMaster.getDatabaseAccess(databaseID);
78  	}
79  
80  	/**
81  	 * Get the property written in the track-config.xml file
82  	 * 
83  	 * @param key
84  	 * @return
85  	 */
86  	public String getTrackConfigProperty(String key, String defaultValue) {
87  		return UTGBMaster.getUTGBConfig().getProperty(key, defaultValue);
88  	}
89  
90  	/**
91  	 * 
92  	 * @param <T>
93  	 * @param databaseID
94  	 * @param sql
95  	 * @param classType
96  	 * @throws UTGBException
97  	 * @throws IOException
98  	 */
99  	public <T> void toJSON(String databaseID, String sql, Class<T> resultClass, HttpServletResponse response) throws UTGBException, IOException {
100 		DatabaseAccess db;
101 		try {
102 			db = getDatabaseAccess(databaseID);
103 			db.toJSON(sql, resultClass, response.getWriter());
104 		}
105 		catch (DBException e) {
106 			throw new UTGBException(UTGBErrorCode.DatabaseError, e);
107 		}
108 	}
109 
110 	/**
111 	 * Load JSON data from the stream and convert the JSON data into Object of the given resultClass. Each object is
112 	 * passed to the result handler.
113 	 * 
114 	 * @param <T>
115 	 * @param jsonStream
116 	 * @param resultClass
117 	 * @param resultHandler
118 	 * @throws UTGBException
119 	 * @throws IOException
120 	 */
121 	public <T> void loadJSON(Reader jsonStream, Class<T> resultClass, ObjectHandler<T> resultHandler) throws UTGBException, IOException {
122 		try {
123 			JSONLens.loadJSON(resultClass, jsonStream, resultHandler);
124 		}
125 		catch (XerialException e) {
126 			throw new UTGBException(UTGBErrorCode.JSONToObjectMapping, e);
127 		}
128 	}
129 
130 	private static class JSONAccumulator<T> extends ObjectHandlerBase<T> {
131 		private ArrayList<T> result = new ArrayList<T>();
132 
133 		public void handle(T bean) throws Exception {
134 			result.add(bean);
135 		}
136 
137 		public ArrayList<T> getResult() {
138 			return result;
139 		}
140 
141 	}
142 
143 	/**
144 	 * load the json data, and converts them into a list of result class instances
145 	 * 
146 	 * @param <T>
147 	 * @param jsonStream
148 	 * @param resultClass
149 	 * @return
150 	 * @throws UTGBException
151 	 * @throws IOException
152 	 */
153 	public <T> List<T> loadJSON(Reader jsonStream, Class<T> resultClass) throws UTGBException, IOException {
154 		try {
155 			JSONAccumulator<T> ja = new JSONAccumulator<T>();
156 			JSONLens.loadJSON(resultClass, jsonStream, ja);
157 			return ja.getResult();
158 		}
159 		catch (XerialException e) {
160 			throw new UTGBException(UTGBErrorCode.JSONToObjectMapping, e);
161 		}
162 
163 	}
164 
165 	/**
166 	 * Opens a BufferedReader that reads data from another action
167 	 * 
168 	 * @param request
169 	 * @param path
170 	 *            path to the another action. e.g. "hello"
171 	 * @return
172 	 * @throws ServletException
173 	 * @throws IOException
174 	 */
175 	public BufferedReader openAction(HttpServletRequest request, String path) throws ServletException, IOException {
176 		return openAction(request, path, false);
177 	}
178 
179 	/**
180 	 * @param request
181 	 * @param path
182 	 * @param bypassRequestParameter
183 	 * @return
184 	 * @throws ServletException
185 	 * @throws IOException
186 	 */
187 	public BufferedReader openAction(HttpServletRequest request, String path, boolean bypassRequestParameter) throws ServletException, IOException {
188 		if (bypassRequestParameter) {
189 			path = path + "?" + getHTTPRequestQueryString(request);
190 		}
191 
192 		return UTGBMaster.openServletReader(request, path);
193 	}
194 
195 	@SuppressWarnings("unchecked")
196 	public static String getHTTPRequestQueryString(HttpServletRequest request) {
197 		ArrayList<String> argList = new ArrayList<String>();
198 
199 		for (Enumeration<String> e = request.getParameterNames(); e.hasMoreElements();) {
200 			String param = e.nextElement();
201 			argList.add(param + "=" + request.getParameter(param));
202 		}
203 		return StringUtil.join(argList, "&");
204 	}
205 
206 	/**
207 	 * Create an SQL from a given file (relative to the caller class) and variable assignments.
208 	 * 
209 	 * @param sqlFileName
210 	 *            an SQL (text) file name, which contains a single sql expression. This SQL file can contain variables
211 	 *            $1, $2, ..., where each of them corresponds to the args of this method
212 	 * @param args
213 	 *            values each of them are assigned to the corresponding variable in the SQL
214 	 * @return the generated SQL
215 	 * @throws IOException
216 	 *             when failed to read the file
217 	 * @throws UTGBException
218 	 *             {@link UTGBErrorCode#InvalidSQLSyntax}
219 	 */
220 	public String createSQLFromFile(String sqlFileName, Object... args) throws IOException, UTGBException {
221 		BufferedReader reader = FileResource.open(this.getClass(), sqlFileName);
222 		if (reader == null) {
223 			throw new UTGBException(UTGBErrorCode.FileNotFound, sqlFileName);
224 		}
225 		StringBuilder sql = new StringBuilder();
226 		for (String line; (line = reader.readLine()) != null;) {
227 			sql.append(line);
228 			sql.append("\n");
229 		}
230 
231 		try {
232 			return SQLExpression.fillTemplate(sql.toString(), args);
233 		}
234 		catch (DBException e) {
235 			throw new UTGBException(UTGBErrorCode.InvalidSQLSyntax, sql.toString());
236 		}
237 	}
238 
239 	/**
240 	 * Create an SQL from a given template and variable assignments.
241 	 * 
242 	 * @param sqlTemplate
243 	 *            an SQL template, which can contain variables $1, $2, ..., each of them corresponds to the args of this
244 	 *            method
245 	 * @param args
246 	 *            variable assignments
247 	 * @return the generated SQL
248 	 * @throws UTGBException
249 	 *             {@link UTGBErrorCode#InvalidSQLSyntax}
250 	 */
251 	public String createSQL(String sqlTemplate, Object... args) throws UTGBException {
252 		try {
253 			return SQLExpression.fillTemplate(sqlTemplate, args);
254 		}
255 		catch (DBException e) {
256 			throw new UTGBException(UTGBErrorCode.InvalidSQLSyntax, sqlTemplate);
257 		}
258 	}
259 
260 	/**
261 	 * Returns the path to the project root folder
262 	 * 
263 	 * @return
264 	 */
265 	public static String getProjectRootPath() {
266 		Object value = UTGBMaster.getVariable("projectRoot");
267 		return (value != null) ? value.toString() : "";
268 	}
269 
270 	/**
271 	 * Return the action suffix attached to the request
272 	 * 
273 	 * @param request
274 	 * @return the action suffix. if no suffix is specified in the action, return "".
275 	 */
276 	public String getActionSuffix(HttpServletRequest request) {
277 		String suffix = (String) request.getAttribute("actionSuffix");
278 		return suffix == null ? "" : suffix;
279 	}
280 
281 	/**
282 	 * Return the action prefix of the request
283 	 * 
284 	 * @param request
285 	 * @return
286 	 */
287 	public String getActionPrefix(HttpServletRequest request) {
288 		String prefix = (String) request.getAttribute("actionPrefix");
289 		return prefix == null ? "" : prefix;
290 	}
291 
292 }