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 4872 leinfelder
		OrderedMap table = new OrderedMap();
60
		OrderedMap widestRow = new OrderedMap();
61
		int colCount = rs.getMetaData().getColumnCount();
62
		String idColName = rs.getMetaData().getColumnName(idCol);
63
64
		while (rs.next()) {
65
			String id = rs.getString(idCol);
66
			String pivotValue = rs.getString(pivotCol);
67
68
			//look up the row we are working on
69
			OrderedMap row = (OrderedMap) table.get(id);
70
			if (row == null) {
71
				row = new OrderedMap();
72
			}
73
74
			//get the values for this pivot
75
			for (int i = 1; i <= colCount; i++) {
76
				if (i != pivotCol) {
77
					String colName = rs.getMetaData().getColumnName(i);
78 4874 leinfelder
					//do we include this column in the pivot?
79
					if (pivotAttributes.contains(colName)) {
80
						//annotate the column name with the pivot column value if not the id column
81
						if (i != idCol) {
82
							colName = pivotValue + "_" + colName;
83
						}
84
						String value = rs.getString(i);
85
						row.put(colName, value);
86 4872 leinfelder
					}
87
				}
88
			}
89
			//track the headers - the values are junk
90
			widestRow.putAll(row);
91
92
			//put the row back (or maybe it's the first time)
93
			table.put(id, row);
94
		}
95
96
		//now make it into a list
97
		List retTable = new ArrayList();
98
99
		//do the header, based on widest entry
100
		List header = new ArrayList(widestRow.keySet());
101
		retTable.add(header.toArray(new String[0]));
102
103
		//now the value rows
104
		Iterator rowIter = table.values().iterator();
105
		int rowCount = 1;
106
		while (rowIter.hasNext()) {
107
			OrderedMap rowMap = (OrderedMap) rowIter.next();
108
			List row = new ArrayList();
109
			//iterate over the widest row's columns
110
			Iterator columnIter = widestRow.keySet().iterator();
111
			while (columnIter.hasNext()) {
112
				Object key = columnIter.next();
113
				Object value = rowMap.get(key);
114
				//hide the value used for Ids - just increment row
115
				if (key.equals(idColName) && omitIdValues) {
116
					value = String.valueOf(rowCount);
117
				}
118
				row.add(value);
119
			}
120
			rowCount++;
121
			retTable.add(row.toArray(new String[0]));
122
		}
123
124
		return retTable;
125
	}
126
%><%!
127
	private void handleDataquery(
128
			Hashtable<String, String[]> params,
129
	        HttpServletResponse response,
130
	        String sessionId) throws PropertyNotFoundException, IOException {
131
132
		DataQuery dq = null;
133
		if (sessionId != null) {
134
			dq = new DataQuery(sessionId);
135
		}
136
		else {
137
			dq = new DataQuery();
138
		}
139
140
		String dataqueryXML = (params.get("dataquery"))[0];
141
142
		ResultSet rs = null;
143
		try {
144
			rs = dq.executeQuery(dataqueryXML);
145
		} catch (Exception e) {
146
			//probably need to do something here
147
			e.printStackTrace();
148
			return;
149
		}
150
151
		//process the result set
152
		String qformat = "csv";
153
		String[] temp = params.get("qformat");
154
		if (temp != null && temp.length > 0) {
155
			qformat = temp[0];
156
		}
157
		String fileName = "query-results." + qformat;
158
159
		boolean transpose = false;
160
		temp = params.get("transpose");
161
		if (temp != null && temp.length > 0) {
162
			transpose = Boolean.parseBoolean(temp[0]);
163
		}
164
		int observation = 0;
165
		temp = params.get("observation");
166
		if (temp != null && temp.length > 0) {
167
			observation = Integer.parseInt(temp[0]);
168
		}
169
		int pivot = 0;
170
		temp = params.get("pivot");
171
		if (temp != null && temp.length > 0) {
172
			pivot = Integer.parseInt(temp[0]);
173
		}
174
175
		//get the results as csv file
176
		if (qformat != null && qformat.equalsIgnoreCase("csv")) {
177
			response.setContentType("text/csv");
178
			//response.setContentType("application/csv");
179
	        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
180
181
			Writer writer = new OutputStreamWriter(response.getOutputStream());
182
			CSVWriter csv = new CSVWriter(writer, CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER);
183
			try {
184
				if (transpose) {
185 4874 leinfelder
					List pivotCols = new ArrayList();
186
					pivotCols.add("studentid");
187
					pivotCols.add("score");
188
					pivotCols.add("response");
189
					List transposedTable = transpose(rs, observation, pivot, pivotCols, true);
190 4872 leinfelder
					csv.writeAll(transposedTable);
191
				} else {
192
					csv.writeAll(rs, true);
193
				}
194
195
				csv.flush();
196
				response.flushBuffer();
197
198
				rs.close();
199
200
			} catch (SQLException e) {
201
				e.printStackTrace();
202
			}
203
204
			return;
205
		}
206
207
	}
208
%>