Project

General

Profile

1
<%@page 
2
import="java.util.Iterator"%><%@page 
3
import="java.util.ArrayList"%><%@page 
4
import="edu.ucsb.nceas.utilities.OrderedMap"%><%@page 
5
import="java.util.List"%><%@page 
6
import="java.util.Enumeration"%><%@page 
7
import="java.sql.SQLException"%><%@page 
8
import="org.ecoinformatics.datamanager.transpose.DataTranspose"%><%@page 
9
import="au.com.bytecode.opencsv.CSVWriter"%><%@page 
10
import="java.io.OutputStreamWriter"%><%@page 
11
import="java.io.Writer"%><%@page 
12
import="java.sql.ResultSet"%><%@page 
13
import="edu.ucsb.nceas.metacat.dataquery.DataQuery"%><%@page 
14
import="java.io.IOException"%><%@page 
15
import="edu.ucsb.nceas.utilities.PropertyNotFoundException"%><%@page 
16
import="java.util.Hashtable"%><%@ page 
17
language="java" %><%
18
/**
19
 * 
20
 * '$RCSfile$'
21
 * Copyright: 2008 Regents of the University of California and the
22
 *             National Center for Ecological Analysis and Synthesis
23
 *    '$Author: leinfelder $'
24
 *      '$Date: 2008-08-22 16:48:56 -0700 (Fri, 22 Aug 2008) $'
25
 * '$Revision: 4305 $'
26
 * 
27
 * This program is free software; you can redistribute it and/or modify
28
 * it under the terms of the GNU General Public License as published by
29
 * the Free Software Foundation; either version 2 of the License, or
30
 * (at your option) any later version.
31
 * 
32
 * This program is distributed in the hope that it will be useful,
33
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
34
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
35
 * GNU General Public License for more details.
36
     
37
 * You should have received a copy of the GNU General Public License
38
 * along with this program; if not, write to the Free Software
39
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
40
 */  
41
%><%
42
Hashtable params = getParams(request);
43
handleDataquery(params,response,request.getSession().getId());
44
%><%!
45
	private Hashtable getParams(HttpServletRequest request) {
46
		Hashtable params = new Hashtable();
47
		Enumeration<String> paramlist = (Enumeration<String>)request.getParameterNames();
48
		while (paramlist.hasMoreElements()) {
49
	
50
			String name = paramlist.nextElement();
51
			String[] value = request.getParameterValues(name);
52
			params.put(name, value);
53
		}
54
	
55
		return params;
56
	}
57
%><%!
58
	private List transpose(ResultSet rs, int idCol, int pivotCol, List pivotAttributes, boolean omitIdValues) throws SQLException {
59
		//map keyed by id column - data
60
		OrderedMap table = new OrderedMap();
61
		//track all the data columns
62
		OrderedMap widestRow = new OrderedMap();
63
		//map keyed by the pivot column - metadata
64
		OrderedMap headerRows = new OrderedMap();
65
		
66
		//vocab columns
67
		String vocabNameCol = "qmetadatavocabulary";
68
		String vocabValueCol = "qmetadatavalue";
69
		//maps for the vocab lists
70
		OrderedMap vocabNames = new OrderedMap();
71
		OrderedMap vocabValues = new OrderedMap();
72
		//all vocab names/values
73
		List allVocabNames = new ArrayList();
74
		List allVocabValues = new ArrayList();
75
		
76
		int colCount = rs.getMetaData().getColumnCount();
77
		String idColName = rs.getMetaData().getColumnName(idCol);
78
		
79
		while (rs.next()) {
80
			String id = rs.getString(idCol);
81
			String pivotValue = rs.getString(pivotCol);
82
			
83
			//look up the data row we are working on
84
			OrderedMap row = (OrderedMap) table.get(id);
85
			if (row == null) {
86
				row = new OrderedMap();
87
			}
88
			//look up the metadata row we are working on
89
			OrderedMap metadataRow = (OrderedMap) table.get(pivotValue);
90
			if (metadataRow == null) {
91
				metadataRow = new OrderedMap();
92
			}
93
			
94
			//get the values for this pivot
95
			for (int i = 1; i <= colCount; i++) {
96
				if (i != pivotCol) {
97
					String colName = rs.getMetaData().getColumnName(i);
98
					String value = rs.getString(i);
99
					//clean up the value
100
					if (value != null) {
101
						value = value.replaceAll("\n", " ");
102
						value = value.replaceAll("\\s+", " ");
103
						value = value.replaceAll("<html>", " ");
104
						value = value.replaceAll("</html>", " ");
105
						value = value.replaceAll("<head>", " ");
106
						value = value.replaceAll("</head>", " ");
107
						value = value.replaceAll("<body>", " ");
108
						value = value.replaceAll("</body>", " ");
109
					}
110
					//do we include this column in the pivot?
111
					if (pivotAttributes.contains(colName)) {
112
						//annotate the column name with the pivot column value if not the id column
113
						if (i != idCol) {
114
							colName = pivotValue + "_" + colName;
115
						}
116
						row.put(colName, value);
117
					}
118
					else {
119
						metadataRow.put(colName, value);
120
					}
121
					//names
122
					if (colName.startsWith(vocabNameCol)) {
123
						List list = (List) vocabNames.get(pivotValue);
124
						if (list == null) {
125
							list = new ArrayList();
126
						}
127
						list.add(value);
128
						vocabNames.put(pivotValue, list);
129
						allVocabNames.add(value);
130
					}
131
					//values
132
					if (colName.startsWith(vocabValueCol)) {
133
						List list = (List) vocabValues.get(pivotValue);
134
						if (list == null) {
135
							list = new ArrayList();
136
						}
137
						list.add(value);
138
						vocabValues.put(pivotValue, list);
139
						allVocabValues.add(value);
140
					}
141
				}
142
			}
143
			//track the data columns - the values are junk
144
			widestRow.putAll(row);
145
			
146
			//put the row back (or maybe it's the first time)
147
			table.put(id, row);
148
			
149
			//put the metadata header back
150
			headerRows.put(pivotValue, metadataRow);
151
			
152
		}
153
		
154
		/** Construct the table structure for returning **/
155
		
156
		//now make it into a list
157
		List retTable = new ArrayList();
158
		
159
		//map keyed by metadata labels
160
		OrderedMap metadataHeaders = new OrderedMap();
161
		
162
		//do the data header - drives the other columns - based on widest entry
163
		List header = new ArrayList(widestRow.keySet());
164
		
165
		//do the metadata header rows (basically rotate them around)
166
		Iterator headerIter = header.iterator();
167
		while (headerIter.hasNext()) {
168
			String column = (String) headerIter.next();
169
			//get the pivotValue part of column name
170
			String pivotValue = column;
171
			try {
172
				pivotValue = column.substring(0, column.indexOf("_"));
173
			}
174
			catch (Exception e) {}
175
			//look up the row from the metadata - keyed by pivot value
176
			OrderedMap metadataRow = (OrderedMap) headerRows.get(pivotValue);
177
			if (metadataRow != null) {
178
				//go through the values
179
				Iterator metadataIter = metadataRow.keySet().iterator();
180
				while (metadataIter.hasNext()) {
181
					String key = (String) metadataIter.next();
182
					String value = (String) metadataRow.get(key);
183
					OrderedMap newMetadataRow = (OrderedMap) metadataHeaders.get(key);
184
					if (newMetadataRow == null) {
185
						newMetadataRow = new OrderedMap();
186
					}
187
					newMetadataRow.put(column, value);
188
					metadataHeaders.put(key, newMetadataRow);
189
				}
190
			}
191
		}
192
		
193
		//make metadata rows as list/arrays on the reteurn table
194
		Iterator metadataLabelIter = metadataHeaders.keySet().iterator();
195
		while (metadataLabelIter.hasNext()) {
196
			String label = (String) metadataLabelIter.next();
197
			OrderedMap row = (OrderedMap) metadataHeaders.get(label);
198
			List rowValues = new ArrayList(row.values());
199
			rowValues.add(0, label);
200
			retTable.add(rowValues.toArray(new String[0]));
201
		}
202
		
203
		//create the special vocab matrix rows
204
		List vocabTable = new ArrayList();
205
		List uniqueVocabs = new ArrayList();
206
		for (int i = 0; i < allVocabNames.size(); i++) {
207
			List vocabRow = new ArrayList();
208
			String vocabName = (String) allVocabNames.get(i);
209
			String vocabValue = (String) allVocabValues.get(i);
210
			String key = vocabName + "/" + vocabValue;
211
			//check if we've processed this already, skip if so
212
			if (uniqueVocabs.contains(key)) {
213
				continue;
214
			}
215
			uniqueVocabs.add(key);
216
			//TODO: expand the column count by one for _everything_
217
			vocabRow.add(key);
218
			//vocabRow.add(vocabName);
219
			//vocabRow.add(vocabValue);
220
			//go through the questions now, again
221
			headerIter = header.iterator();
222
			while (headerIter.hasNext()) {
223
				String column = (String) headerIter.next();
224
				//get the pivotValue part of column name if it exists
225
				String pivotValue = null;
226
				try {
227
					pivotValue = column.substring(0, column.indexOf("_"));
228
				}
229
				catch (Exception e) {}
230
				if (pivotValue == null) {
231
					continue;
232
				}
233
				//check to see if this question has that keyword
234
				List names = (List) vocabNames.get(pivotValue);
235
				List values = (List) vocabValues.get(pivotValue);
236
				if (names != null && names.indexOf(vocabName) > -1 && names.indexOf(vocabName) == values.indexOf(vocabValue) ) {
237
					vocabRow.add("true");
238
				}
239
				else {
240
					vocabRow.add("false");
241
				}
242
			}
243
			//put the row on
244
			vocabTable.add(vocabRow.toArray(new String[0]));
245
		}
246
		
247
		//put the vocab matrix on the table
248
		retTable.addAll(vocabTable);
249
		
250
		//put the data header row on the table
251
		retTable.add(header.toArray(new String[0]));
252
		
253
		//now the value rows in the table
254
		Iterator rowIter = table.values().iterator();
255
		int rowCount = 1;
256
		while (rowIter.hasNext()) {
257
			OrderedMap rowMap = (OrderedMap) rowIter.next();
258
			List row = new ArrayList();
259
			//iterate over the widest row's columns
260
			Iterator columnIter = widestRow.keySet().iterator();
261
			while (columnIter.hasNext()) {
262
				Object key = columnIter.next();
263
				Object value = rowMap.get(key);
264
				//hide the value used for Ids - just increment row
265
				if (key.equals(idColName) && omitIdValues) {
266
					value = String.valueOf(rowCount);
267
				}
268
				row.add(value);
269
			}
270
			rowCount++;
271
			retTable.add(row.toArray(new String[0]));
272
		}
273
		
274
		return retTable;
275
	}
276
%><%!
277
	private void handleDataquery(
278
			Hashtable<String, String[]> params,
279
	        HttpServletResponse response,
280
	        String sessionId) throws PropertyNotFoundException, IOException {
281
		
282
		DataQuery dq = null;
283
		if (sessionId != null) {
284
			dq = new DataQuery(sessionId);
285
		}
286
		else {
287
			dq = new DataQuery();
288
		}
289
		
290
		String dataqueryXML = (params.get("dataquery"))[0];
291
	
292
		ResultSet rs = null;
293
		try {
294
			rs = dq.executeQuery(dataqueryXML);
295
		} catch (Exception e) {
296
			//probably need to do something here
297
			e.printStackTrace();
298
			return;
299
		}
300
		
301
		//process the result set
302
		String qformat = "csv";
303
		String[] temp = params.get("qformat");
304
		if (temp != null && temp.length > 0) {
305
			qformat = temp[0];
306
		}
307
		String fileName = "query-results." + qformat;
308
		
309
		boolean transpose = false;
310
		temp = params.get("transpose");
311
		if (temp != null && temp.length > 0) {
312
			transpose = Boolean.parseBoolean(temp[0]);
313
		}
314
		int observation = 0;
315
		temp = params.get("observation");
316
		if (temp != null && temp.length > 0) {
317
			observation = Integer.parseInt(temp[0]);
318
		}
319
		int pivot = 0;
320
		temp = params.get("pivot");
321
		if (temp != null && temp.length > 0) {
322
			pivot = Integer.parseInt(temp[0]);
323
		}
324
		
325
		//get the results as csv file
326
		if (qformat != null && qformat.equalsIgnoreCase("csv")) {
327
			response.setContentType("text/csv");
328
			//response.setContentType("application/csv");
329
	        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
330
	        
331
			Writer writer = new OutputStreamWriter(response.getOutputStream());
332
			//CSVWriter csv = new CSVWriter(writer, CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER);
333
			CSVWriter csv = new CSVWriter(writer, CSVWriter.DEFAULT_SEPARATOR, CSVWriter.DEFAULT_QUOTE_CHARACTER, CSVWriter.DEFAULT_ESCAPE_CHARACTER);
334
			try {
335
				if (transpose) {
336
					List pivotCols = new ArrayList();
337
					pivotCols.add("studentid");
338
					pivotCols.add("score");
339
					pivotCols.add("response");
340
					List transposedTable = transpose(rs, observation, pivot, pivotCols, true);
341
					csv.writeAll(transposedTable);
342
				} else {
343
					csv.writeAll(rs, true);
344
				}
345
				
346
				csv.flush();
347
				response.flushBuffer();
348
				
349
				rs.close();
350
				
351
			} catch (SQLException e) {
352
				e.printStackTrace();
353
			}
354
			
355
			return;
356
		}
357
		
358
	}
359
%>
(4-4/22)