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 processResultsSet(ResultSet rs, int omitColumn, String omitColumnLabel) throws SQLException {
59
		List retTable = new ArrayList();
60
		int colCount = rs.getMetaData().getColumnCount();
61
		List columnHeaders = new ArrayList();
62
		int recordCount = 1;
63
		OrderedMap uniqueIds = new OrderedMap();
64
		
65
		while (rs.next()) {
66
			List row = new ArrayList();
67
			//get the values for this row
68
			for (int i = 1; i <= colCount; i++) {
69

    
70
				String colName = rs.getMetaData().getColumnName(i);
71
				String value = rs.getString(i);
72
					
73
				//clean up the value
74
				value = cleanUp(value);
75
				
76
				//hide the ids
77
				if (i == omitColumn) {
78
					String lookupValue = (String) uniqueIds.get(value);
79
					if (lookupValue == null) {
80
						lookupValue = recordCount + "";
81
					}
82
					uniqueIds.put(value, lookupValue);
83
					value = lookupValue;
84
					colName = omitColumnLabel;
85
				}
86
				if (recordCount == 1) {
87
					columnHeaders.add(colName);
88
				}
89
				
90
				row.add(value);
91
			}
92
			retTable.add(row.toArray(new String[0]));
93
			recordCount++;
94
		}
95
		retTable.add(0, columnHeaders.toArray(new String[0]));
96
		return retTable;
97
	}
98
%><%!
99
	private List transpose(ResultSet rs, int idCol, int pivotCol, List pivotAttributes, boolean omitIdValues) throws SQLException {
100
		//map keyed by id column - data
101
		OrderedMap table = new OrderedMap();
102
		//track all the data columns
103
		OrderedMap widestRow = new OrderedMap();
104
		//map keyed by the pivot column - metadata
105
		OrderedMap headerRows = new OrderedMap();
106
		
107
		//vocab columns
108
		String vocabNameCol = "qmetadatavocabulary";
109
		String vocabValueCol = "qmetadatavalue";
110
		//maps for the vocab lists
111
		OrderedMap vocabNames = new OrderedMap();
112
		OrderedMap vocabValues = new OrderedMap();
113
		//all vocab names/values
114
		List allVocabNames = new ArrayList();
115
		List allVocabValues = new ArrayList();
116
		boolean twoColumnMetadata = true;
117
		
118
		int colCount = rs.getMetaData().getColumnCount();
119
		String idColName = rs.getMetaData().getColumnName(idCol);
120
		
121
		while (rs.next()) {
122
			String id = rs.getString(idCol);
123
			String pivotValue = rs.getString(pivotCol);
124
			
125
			//look up the data row we are working on
126
			OrderedMap row = (OrderedMap) table.get(id);
127
			if (row == null) {
128
				row = new OrderedMap();
129
			}
130
			//look up the metadata row we are working on
131
			OrderedMap metadataRow = (OrderedMap) table.get(pivotValue);
132
			if (metadataRow == null) {
133
				metadataRow = new OrderedMap();
134
			}
135
			
136
			//get the values for this pivot
137
			for (int i = 1; i <= colCount; i++) {
138
				if (i != pivotCol) {
139
					String colName = rs.getMetaData().getColumnName(i);
140
					String value = rs.getString(i);
141
					
142
					//clean up the value
143
					value = cleanUp(value);
144
					
145
					//do we include this column in the pivot?
146
					if (pivotAttributes.contains(colName)) {
147
						//annotate the column name with the pivot column value if not the id column
148
						if (i != idCol) {
149
							colName = pivotValue + "_" + colName;
150
						}
151
						row.put(colName, value);
152
					}
153
					else {
154
						if (colName.startsWith(vocabNameCol) || colName.startsWith(vocabValueCol)) {
155
							//don't add it to the normal metadata
156
						}
157
						else {
158
							metadataRow.put(colName, value);
159
						}
160
					}
161
					//names
162
					if (colName.startsWith(vocabNameCol)) {
163
						List list = (List) vocabNames.get(pivotValue);
164
						if (list == null) {
165
							list = new ArrayList();
166
						}
167
						list.add(value);
168
						vocabNames.put(pivotValue, list);
169
						allVocabNames.add(value);
170
					}
171
					//values
172
					if (colName.startsWith(vocabValueCol)) {
173
						List list = (List) vocabValues.get(pivotValue);
174
						if (list == null) {
175
							list = new ArrayList();
176
						}
177
						list.add(value);
178
						vocabValues.put(pivotValue, list);
179
						allVocabValues.add(value);
180
					}
181
				}
182
			}
183
			//track the data columns - the values are junk
184
			widestRow.putAll(row);
185
			
186
			//put the row back (or maybe it's the first time)
187
			table.put(id, row);
188
			
189
			//put the metadata header back
190
			headerRows.put(pivotValue, metadataRow);
191
			
192
		}
193
		
194
		/** Construct the table structure for returning **/
195
		
196
		//now make it into a list
197
		List retTable = new ArrayList();
198
		
199
		//map keyed by metadata labels
200
		OrderedMap metadataHeaders = new OrderedMap();
201
		
202
		//do the data header - drives the other columns - based on widest entry
203
		List header = new ArrayList(widestRow.keySet());
204
		
205
		//do the metadata header rows (basically rotate them around)
206
		Iterator headerIter = header.iterator();
207
		String lastValue = "";
208
		while (headerIter.hasNext()) {
209
			String column = (String) headerIter.next();
210
			//get the pivotValue part of column name
211
			String pivotValue = column;
212
			try {
213
				pivotValue = column.substring(0, column.indexOf("_"));
214
			}
215
			catch (Exception e) {}
216
			//look up the row from the metadata - keyed by pivot value
217
			OrderedMap metadataRow = (OrderedMap) headerRows.get(pivotValue);
218
			if (metadataRow != null) {
219
				//go through the values
220
				Iterator metadataIter = metadataRow.keySet().iterator();
221
				while (metadataIter.hasNext()) {
222
					String key = (String) metadataIter.next();
223
					String value = (String) metadataRow.get(key);
224
					OrderedMap newMetadataRow = (OrderedMap) metadataHeaders.get(key);
225
					if (newMetadataRow == null) {
226
						newMetadataRow = new OrderedMap();
227
					}
228
					//if it's the same as the last one, just use null value
229
					if (lastValue.equals(pivotValue)) {
230
						value = null;
231
					} 
232
					newMetadataRow.put(column, value);
233
					metadataHeaders.put(key, newMetadataRow);
234
				}
235
			}
236
			
237
			lastValue = pivotValue;
238

    
239
		}
240
		
241
		//make metadata rows as list/arrays on the reteurn table
242
		Iterator metadataLabelIter = metadataHeaders.keySet().iterator();
243
		while (metadataLabelIter.hasNext()) {
244
			String label = (String) metadataLabelIter.next();
245
			OrderedMap row = (OrderedMap) metadataHeaders.get(label);
246
			List rowValues = new ArrayList(row.values());
247
			rowValues.add(0, label);
248
			if (twoColumnMetadata) {
249
				//add extra column
250
				rowValues.add(1, null);
251
			}
252
			retTable.add(rowValues.toArray(new String[0]));
253
		}
254
		
255
		//create the special vocab matrix rows
256
		List vocabTable = new ArrayList();
257
		List uniqueVocabs = new ArrayList();
258
		for (int i = 0; i < allVocabNames.size(); i++) {
259
			List vocabRow = new ArrayList();
260
			String vocabName = (String) allVocabNames.get(i);
261
			String vocabValue = (String) allVocabValues.get(i);
262
			String key = vocabName + "/" + vocabValue;
263
			//check if we've processed this already, skip if so
264
			if (uniqueVocabs.contains(key)) {
265
				continue;
266
			}
267
			uniqueVocabs.add(key);			
268
			if (twoColumnMetadata) {
269
				vocabRow.add(vocabName);
270
				vocabRow.add(vocabValue);
271
			}
272
			else {
273
				vocabRow.add(key);
274
			}
275
			//go through the questions now, again
276
			headerIter = header.iterator();
277
			while (headerIter.hasNext()) {
278
				String column = (String) headerIter.next();
279
				//get the pivotValue part of column name if it exists
280
				String pivotValue = null;
281
				try {
282
					pivotValue = column.substring(0, column.indexOf("_"));
283
				}
284
				catch (Exception e) {}
285
				if (pivotValue == null) {
286
					continue;
287
				}
288
				//check to see if this question has that keyword
289
				List names = (List) vocabNames.get(pivotValue);
290
				List values = (List) vocabValues.get(pivotValue);
291
				if (names != null && names.indexOf(vocabName) > -1 && names.indexOf(vocabName) == values.indexOf(vocabValue) ) {
292
					vocabRow.add("true");
293
				}
294
				else {
295
					vocabRow.add("false");
296
				}
297
			}
298
			//put the row on
299
			vocabTable.add(vocabRow.toArray(new String[0]));
300
		}
301
		
302
		//put the vocab matrix on the table
303
		retTable.addAll(vocabTable);
304
		
305
		if (twoColumnMetadata) {
306
			//add column to data header row
307
			header.add(1, null);
308
		}
309
		
310
		//replace the "studentId" label
311
		int temp = header.indexOf("studentid");
312
		if (header.remove(temp) != null) {
313
			header.add(temp, "recordNum");
314
		}
315
		
316
		//put the data header row on the table
317
		retTable.add(header.toArray(new String[0]));
318
		
319
		//now the value rows in the table
320
		Iterator rowIter = table.values().iterator();
321
		int rowCount = 1;
322
		while (rowIter.hasNext()) {
323
			OrderedMap rowMap = (OrderedMap) rowIter.next();
324
			List row = new ArrayList();
325
			//iterate over the widest row's columns
326
			Iterator columnIter = widestRow.keySet().iterator();
327
			while (columnIter.hasNext()) {
328
				Object key = columnIter.next();
329
				Object value = rowMap.get(key);
330
				//hide the value used for Ids - just increment row
331
				if (key.equals(idColName) && omitIdValues) {
332
					value = String.valueOf(rowCount);
333
				}
334
				row.add(value);
335
			}
336
			rowCount++;
337
			if (twoColumnMetadata) {
338
				//add extra column
339
				row.add(1, null);
340
			}
341
			retTable.add(row.toArray(new String[0]));
342
		}
343
		
344
		return retTable;
345
	}
346
%><%!
347
	private String cleanUp(String value) {
348
		if (value != null) {
349
			value = value.replaceAll("\n", " ");
350
			value = value.replaceAll("\\s+", " ");
351
			value = value.replaceAll("<html>", " ");
352
			value = value.replaceAll("</html>", " ");
353
			value = value.replaceAll("<head>", " ");
354
			value = value.replaceAll("</head>", " ");
355
			value = value.replaceAll("<body>", " ");
356
			value = value.replaceAll("</body>", " ");
357
		}
358
		return value;
359
	}
360
%><%!
361
	private void handleDataquery(
362
			Hashtable<String, String[]> params,
363
	        HttpServletResponse response,
364
	        String sessionId) throws PropertyNotFoundException, IOException {
365
		
366
		DataQuery dq = null;
367
		if (sessionId != null) {
368
			dq = new DataQuery(sessionId);
369
		}
370
		else {
371
			dq = new DataQuery();
372
		}
373
		
374
		String dataqueryXML = (params.get("dataquery"))[0];
375
	
376
		ResultSet rs = null;
377
		try {
378
			rs = dq.executeQuery(dataqueryXML);
379
		} catch (Exception e) {
380
			//probably need to do something here
381
			e.printStackTrace();
382
			return;
383
		}
384
		
385
		//process the result set
386
		String qformat = "csv";
387
		String[] temp = params.get("qformat");
388
		if (temp != null && temp.length > 0) {
389
			qformat = temp[0];
390
		}
391
		String fileName = "query-results." + qformat;
392
		
393
		boolean transpose = false;
394
		temp = params.get("transpose");
395
		if (temp != null && temp.length > 0) {
396
			transpose = Boolean.parseBoolean(temp[0]);
397
		}
398
		int observation = 0;
399
		temp = params.get("observation");
400
		if (temp != null && temp.length > 0) {
401
			observation = Integer.parseInt(temp[0]);
402
		}
403
		int pivot = 0;
404
		temp = params.get("pivot");
405
		if (temp != null && temp.length > 0) {
406
			pivot = Integer.parseInt(temp[0]);
407
		}
408
		
409
		//get the results as csv file
410
		if (qformat != null && qformat.equalsIgnoreCase("csv")) {
411
			response.setContentType("text/csv");
412
			//response.setContentType("application/csv");
413
	        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
414
	        
415
			Writer writer = new OutputStreamWriter(response.getOutputStream());
416
			//CSVWriter csv = new CSVWriter(writer, CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER);
417
			CSVWriter csv = new CSVWriter(writer, CSVWriter.DEFAULT_SEPARATOR, CSVWriter.DEFAULT_QUOTE_CHARACTER, CSVWriter.DEFAULT_ESCAPE_CHARACTER);
418
			try {
419
				if (transpose) {
420
					List pivotCols = new ArrayList();
421
					pivotCols.add("studentid");
422
					pivotCols.add("score");
423
					pivotCols.add("response");
424
					List transposedTable = transpose(rs, observation, pivot, pivotCols, true);
425
					csv.writeAll(transposedTable);
426
				} else {
427
					List processedTable = processResultsSet(rs, 3, "recordNum");
428
					csv.writeAll(processedTable);
429
				}
430
				
431
				csv.flush();
432
				response.flushBuffer();
433
				
434
				rs.close();
435
				
436
			} catch (SQLException e) {
437
				e.printStackTrace();
438
			}
439
			
440
			return;
441
		}
442
		
443
	}
444
%>
(4-4/22)