Project

General

Profile

1 4872 leinfelder
<%@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 4874 leinfelder
	private List transpose(ResultSet rs, int idCol, int pivotCol, List pivotAttributes, boolean omitIdValues) throws SQLException {
59 4875 leinfelder
		//map keyed by id column - data
60 4872 leinfelder
		OrderedMap table = new OrderedMap();
61 4875 leinfelder
		//track all the data columns
62 4872 leinfelder
		OrderedMap widestRow = new OrderedMap();
63 4875 leinfelder
		//map keyed by the pivot column - metadata
64
		OrderedMap headerRows = new OrderedMap();
65
66 4872 leinfelder
		int colCount = rs.getMetaData().getColumnCount();
67
		String idColName = rs.getMetaData().getColumnName(idCol);
68
69
		while (rs.next()) {
70
			String id = rs.getString(idCol);
71
			String pivotValue = rs.getString(pivotCol);
72
73 4875 leinfelder
			//look up the data row we are working on
74 4872 leinfelder
			OrderedMap row = (OrderedMap) table.get(id);
75
			if (row == null) {
76
				row = new OrderedMap();
77
			}
78 4875 leinfelder
			//look up the metadata row we are working on
79
			OrderedMap metadataRow = (OrderedMap) table.get(pivotValue);
80
			if (metadataRow == null) {
81
				metadataRow = new OrderedMap();
82
			}
83 4872 leinfelder
84
			//get the values for this pivot
85
			for (int i = 1; i <= colCount; i++) {
86
				if (i != pivotCol) {
87
					String colName = rs.getMetaData().getColumnName(i);
88 4875 leinfelder
					String value = rs.getString(i);
89 4874 leinfelder
					//do we include this column in the pivot?
90
					if (pivotAttributes.contains(colName)) {
91
						//annotate the column name with the pivot column value if not the id column
92
						if (i != idCol) {
93
							colName = pivotValue + "_" + colName;
94
						}
95
						row.put(colName, value);
96 4872 leinfelder
					}
97 4875 leinfelder
					else {
98
						metadataRow.put(colName, value);
99
					}
100 4872 leinfelder
				}
101
			}
102 4875 leinfelder
			//track the data columns - the values are junk
103 4872 leinfelder
			widestRow.putAll(row);
104
105
			//put the row back (or maybe it's the first time)
106 4875 leinfelder
			table.put(id, row);
107
108
			//put the metadata header back
109
			headerRows.put(pivotValue, metadataRow);
110
111 4872 leinfelder
		}
112
113
		//now make it into a list
114
		List retTable = new ArrayList();
115
116 4875 leinfelder
		//map keyed by metadata labels
117
		OrderedMap metadataHeaders = new OrderedMap();
118
119
		//do the data header - drives the other columns - based on widest entry
120 4872 leinfelder
		List header = new ArrayList(widestRow.keySet());
121 4875 leinfelder
122
		//do the metadata header rows (basically rotate them around)
123
		Iterator headerIter = header.iterator();
124
		while (headerIter.hasNext()) {
125
			String column = (String) headerIter.next();
126
			//get the pivotValue part of column name
127
			String pivotValue = column;
128
			try {
129
				pivotValue = column.substring(0, column.indexOf("_"));
130
			}
131
			catch (Exception e) {}
132
			//look up the row from the metadata - keyed by pivot value
133
			OrderedMap metadataRow = (OrderedMap) headerRows.get(pivotValue);
134
			if (metadataRow != null) {
135
				//go through the values
136
				Iterator metadataIter = metadataRow.keySet().iterator();
137
				while (metadataIter.hasNext()) {
138
					String key = (String) metadataIter.next();
139
					String value = (String) metadataRow.get(key);
140
					OrderedMap newMetadataRow = (OrderedMap) metadataHeaders.get(key);
141
					if (newMetadataRow == null) {
142
						newMetadataRow = new OrderedMap();
143
					}
144
					newMetadataRow.put(column, value);
145
					metadataHeaders.put(key, newMetadataRow);
146
				}
147
			}
148
		}
149
150
		//make metadata rows as list/arrays on the reteurn table
151
		Iterator metadataLabelIter = metadataHeaders.keySet().iterator();
152
		while (metadataLabelIter.hasNext()) {
153
			String label = (String) metadataLabelIter.next();
154
			OrderedMap row = (OrderedMap) metadataHeaders.get(label);
155
			List rowValues = new ArrayList(row.values());
156
			rowValues.add(0, label);
157
			retTable.add(rowValues.toArray(new String[0]));
158
		}
159
160
		//put the data header row on the table
161 4872 leinfelder
		retTable.add(header.toArray(new String[0]));
162
163 4875 leinfelder
		//now the value rows in the table
164 4872 leinfelder
		Iterator rowIter = table.values().iterator();
165
		int rowCount = 1;
166
		while (rowIter.hasNext()) {
167
			OrderedMap rowMap = (OrderedMap) rowIter.next();
168
			List row = new ArrayList();
169
			//iterate over the widest row's columns
170
			Iterator columnIter = widestRow.keySet().iterator();
171
			while (columnIter.hasNext()) {
172
				Object key = columnIter.next();
173
				Object value = rowMap.get(key);
174
				//hide the value used for Ids - just increment row
175
				if (key.equals(idColName) && omitIdValues) {
176
					value = String.valueOf(rowCount);
177
				}
178
				row.add(value);
179
			}
180
			rowCount++;
181
			retTable.add(row.toArray(new String[0]));
182
		}
183
184
		return retTable;
185
	}
186
%><%!
187
	private void handleDataquery(
188
			Hashtable<String, String[]> params,
189
	        HttpServletResponse response,
190
	        String sessionId) throws PropertyNotFoundException, IOException {
191
192
		DataQuery dq = null;
193
		if (sessionId != null) {
194
			dq = new DataQuery(sessionId);
195
		}
196
		else {
197
			dq = new DataQuery();
198
		}
199
200
		String dataqueryXML = (params.get("dataquery"))[0];
201
202
		ResultSet rs = null;
203
		try {
204
			rs = dq.executeQuery(dataqueryXML);
205
		} catch (Exception e) {
206
			//probably need to do something here
207
			e.printStackTrace();
208
			return;
209
		}
210
211
		//process the result set
212
		String qformat = "csv";
213
		String[] temp = params.get("qformat");
214
		if (temp != null && temp.length > 0) {
215
			qformat = temp[0];
216
		}
217
		String fileName = "query-results." + qformat;
218
219
		boolean transpose = false;
220
		temp = params.get("transpose");
221
		if (temp != null && temp.length > 0) {
222
			transpose = Boolean.parseBoolean(temp[0]);
223
		}
224
		int observation = 0;
225
		temp = params.get("observation");
226
		if (temp != null && temp.length > 0) {
227
			observation = Integer.parseInt(temp[0]);
228
		}
229
		int pivot = 0;
230
		temp = params.get("pivot");
231
		if (temp != null && temp.length > 0) {
232
			pivot = Integer.parseInt(temp[0]);
233
		}
234
235
		//get the results as csv file
236
		if (qformat != null && qformat.equalsIgnoreCase("csv")) {
237
			response.setContentType("text/csv");
238
			//response.setContentType("application/csv");
239
	        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
240
241
			Writer writer = new OutputStreamWriter(response.getOutputStream());
242
			CSVWriter csv = new CSVWriter(writer, CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER);
243
			try {
244
				if (transpose) {
245 4874 leinfelder
					List pivotCols = new ArrayList();
246
					pivotCols.add("studentid");
247
					pivotCols.add("score");
248
					pivotCols.add("response");
249
					List transposedTable = transpose(rs, observation, pivot, pivotCols, true);
250 4872 leinfelder
					csv.writeAll(transposedTable);
251
				} else {
252
					csv.writeAll(rs, true);
253
				}
254
255
				csv.flush();
256
				response.flushBuffer();
257
258
				rs.close();
259
260
			} catch (SQLException e) {
261
				e.printStackTrace();
262
			}
263
264
			return;
265
		}
266
267
	}
268
%>