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
		//put the data header row on the table
310
		retTable.add(header.toArray(new String[0]));
311
		
312
		//now the value rows in the table
313
		Iterator rowIter = table.values().iterator();
314
		int rowCount = 1;
315
		while (rowIter.hasNext()) {
316
			OrderedMap rowMap = (OrderedMap) rowIter.next();
317
			List row = new ArrayList();
318
			//iterate over the widest row's columns
319
			Iterator columnIter = widestRow.keySet().iterator();
320
			while (columnIter.hasNext()) {
321
				Object key = columnIter.next();
322
				Object value = rowMap.get(key);
323
				//hide the value used for Ids - just increment row
324
				if (key.equals(idColName) && omitIdValues) {
325
					value = String.valueOf(rowCount);
326
				}
327
				row.add(value);
328
			}
329
			rowCount++;
330
			if (twoColumnMetadata) {
331
				//add extra column
332
				row.add(1, null);
333
			}
334
			retTable.add(row.toArray(new String[0]));
335
		}
336
		
337
		return retTable;
338
	}
339
%><%!
340
	private String cleanUp(String value) {
341
		if (value != null) {
342
			value = value.replaceAll("\n", " ");
343
			value = value.replaceAll("\\s+", " ");
344
			value = value.replaceAll("<html>", " ");
345
			value = value.replaceAll("</html>", " ");
346
			value = value.replaceAll("<head>", " ");
347
			value = value.replaceAll("</head>", " ");
348
			value = value.replaceAll("<body>", " ");
349
			value = value.replaceAll("</body>", " ");
350
		}
351
		return value;
352
	}
353
%><%!
354
	private void handleDataquery(
355
			Hashtable<String, String[]> params,
356
	        HttpServletResponse response,
357
	        String sessionId) throws PropertyNotFoundException, IOException {
358
		
359
		DataQuery dq = null;
360
		if (sessionId != null) {
361
			dq = new DataQuery(sessionId);
362
		}
363
		else {
364
			dq = new DataQuery();
365
		}
366
		
367
		String dataqueryXML = (params.get("dataquery"))[0];
368
	
369
		ResultSet rs = null;
370
		try {
371
			rs = dq.executeQuery(dataqueryXML);
372
		} catch (Exception e) {
373
			//probably need to do something here
374
			e.printStackTrace();
375
			return;
376
		}
377
		
378
		//process the result set
379
		String qformat = "csv";
380
		String[] temp = params.get("qformat");
381
		if (temp != null && temp.length > 0) {
382
			qformat = temp[0];
383
		}
384
		String fileName = "query-results." + qformat;
385
		
386
		boolean transpose = false;
387
		temp = params.get("transpose");
388
		if (temp != null && temp.length > 0) {
389
			transpose = Boolean.parseBoolean(temp[0]);
390
		}
391
		int observation = 0;
392
		temp = params.get("observation");
393
		if (temp != null && temp.length > 0) {
394
			observation = Integer.parseInt(temp[0]);
395
		}
396
		int pivot = 0;
397
		temp = params.get("pivot");
398
		if (temp != null && temp.length > 0) {
399
			pivot = Integer.parseInt(temp[0]);
400
		}
401
		
402
		//get the results as csv file
403
		if (qformat != null && qformat.equalsIgnoreCase("csv")) {
404
			response.setContentType("text/csv");
405
			//response.setContentType("application/csv");
406
	        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
407
	        
408
			Writer writer = new OutputStreamWriter(response.getOutputStream());
409
			//CSVWriter csv = new CSVWriter(writer, CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER);
410
			CSVWriter csv = new CSVWriter(writer, CSVWriter.DEFAULT_SEPARATOR, CSVWriter.DEFAULT_QUOTE_CHARACTER, CSVWriter.DEFAULT_ESCAPE_CHARACTER);
411
			try {
412
				if (transpose) {
413
					List pivotCols = new ArrayList();
414
					pivotCols.add("studentid");
415
					pivotCols.add("score");
416
					pivotCols.add("response");
417
					List transposedTable = transpose(rs, observation, pivot, pivotCols, true);
418
					csv.writeAll(transposedTable);
419
				} else {
420
					List processedTable = processResultsSet(rs, 3, "recordNum");
421
					csv.writeAll(processedTable);
422
				}
423
				
424
				csv.flush();
425
				response.flushBuffer();
426
				
427
				rs.close();
428
				
429
			} catch (SQLException e) {
430
				e.printStackTrace();
431
			}
432
			
433
			return;
434
		}
435
		
436
	}
437
%>
(4-4/22)