2 * Copyright (C) 2010, 2011 Openismus GmbH
4 * This file is part of GWT-Glom.
6 * GWT-Glom is free software: you can redistribute it and/or modify it
7 * under the terms of the GNU Lesser General Public License as published by the
8 * Free Software Foundation, either version 3 of the License, or (at your
9 * option) any later version.
11 * GWT-Glom is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with GWT-Glom. If not, see <http://www.gnu.org/licenses/>.
20 package org.glom.web.server;
22 import java.beans.PropertyVetoException;
23 import java.sql.Connection;
25 import java.sql.ResultSet;
26 import java.sql.SQLException;
27 import java.sql.Statement;
29 import java.text.DateFormat;
30 import java.text.DecimalFormat;
31 import java.text.NumberFormat;
32 import java.util.ArrayList;
33 import java.util.Currency;
34 import java.util.Locale;
36 import org.glom.libglom.Document;
37 import org.glom.libglom.Field;
38 import org.glom.libglom.FieldFormatting;
39 import org.glom.libglom.Glom;
40 import org.glom.libglom.LayoutFieldVector;
41 import org.glom.libglom.LayoutGroupVector;
42 import org.glom.libglom.LayoutItem;
43 import org.glom.libglom.LayoutItemVector;
44 import org.glom.libglom.LayoutItem_Field;
45 import org.glom.libglom.NumericFormat;
46 import org.glom.libglom.SortClause;
47 import org.glom.libglom.SortFieldPair;
48 import org.glom.libglom.StringVector;
49 import org.glom.web.client.OnlineGlomService;
50 import org.glom.web.shared.GlomDocument;
51 import org.glom.web.shared.LayoutListTable;
53 import com.google.gwt.user.server.rpc.RemoteServiceServlet;
54 import com.mchange.v2.c3p0.ComboPooledDataSource;
55 import com.mchange.v2.c3p0.DataSources;
57 @SuppressWarnings("serial")
58 public class OnlineGlomServiceImpl extends RemoteServiceServlet implements OnlineGlomService {
59 private Document document;
60 private ComboPooledDataSource cpds;
61 // TODO implement locale
62 private Locale locale = Locale.ENGLISH;
64 // Called only when the servlet is stopped (the servlet container is stopped or restarted)
65 public OnlineGlomServiceImpl() {
67 document = new Document();
68 // TODO hardcoded for now, need to figure out something for this
69 document.set_file_uri("file:///home/ben/small-business-example.glom");
71 @SuppressWarnings("unused")
72 boolean retval = document.load(error);
73 // TODO handle error condition (also below)
75 cpds = new ComboPooledDataSource();
76 // load the jdbc driver
78 cpds.setDriverClass("org.postgresql.Driver");
79 } catch (PropertyVetoException e) {
80 // TODO log error, fatal error can't continue, user can be nofified when db access doesn't work
84 cpds.setJdbcUrl("jdbc:postgresql://" + document.get_connection_server() + "/"
85 + document.get_connection_database());
86 // TODO figure out something for db user name and password
88 cpds.setPassword("ChangeMe"); // of course it's not the password I'm using on my server
92 * FIXME I think Swig is generating long on 64-bit machines and int on 32-bit machines - need to keep this constant
93 * http://stackoverflow.com/questions/1590831/safely-casting-long-to-int-in-java
95 public static int safeLongToInt(long l) {
96 if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) {
97 throw new IllegalArgumentException(l + " cannot be cast to int without changing its value.");
102 public GlomDocument getGlomDocument() {
103 GlomDocument glomDocument = new GlomDocument();
105 // get arrays of table names and titles, and find the default table index
106 StringVector tablesVec = document.get_table_names();
108 int numTables = safeLongToInt(tablesVec.size());
109 // we don't know how many tables will be hidden so we'll use half of the number of tables for the default size
111 ArrayList<String> tableNames = new ArrayList<String>(numTables / 2);
112 ArrayList<String> tableTitles = new ArrayList<String>(numTables / 2);
113 boolean foundDefaultTable = false;
114 for (int i = 0; i < numTables; i++) {
115 String tableName = tablesVec.get(i);
116 if (!document.get_table_is_hidden(tableName)) {
117 tableNames.add(tableName);
118 // JNI is "expensive", the comparison will only be called if we haven't already found the default table
119 if (!foundDefaultTable && tableName.equals(document.get_default_table())) {
120 glomDocument.setDefaultTableIndex(i);
121 foundDefaultTable = true;
123 tableTitles.add(document.get_table_title(tableName));
127 // set everything we need
128 glomDocument.setTableNames(tableNames);
129 glomDocument.setTableTitles(tableTitles);
130 glomDocument.setTitle(document.get_database_title());
135 public LayoutListTable getLayoutListTable(String tableName) {
136 LayoutListTable tableInfo = new LayoutListTable();
138 LayoutGroupVector layoutListVec = document.get_data_layout_groups("list", tableName);
139 LayoutItemVector layoutItemsVec = layoutListVec.get(0).get_items();
141 int numItems = safeLongToInt(layoutItemsVec.size());
142 String[] columnTitles = new String[numItems];
143 LayoutFieldVector layoutFields = new LayoutFieldVector();
144 for (int i = 0; i < numItems; i++) {
145 LayoutItem item = layoutItemsVec.get(i);
146 columnTitles[i] = item.get_title_or_name();
147 LayoutItem_Field field = LayoutItem_Field.cast_dynamic(item);
149 layoutFields.add(field);
153 tableInfo.setColumnTitles(columnTitles);
155 // get the size of the returned query for the pager
156 // TODO since we're executing a query anyway, maybe we should return the rows that will be displayed on the
158 // TODO this code is really similar to code in getTableData, find a way to not duplicate the code
159 Connection conn = null;
163 // setup and execute the query
164 conn = cpds.getConnection();
165 st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
166 String query = Glom.build_sql_select_simple(tableName, layoutFields);
167 rs = st.executeQuery(query);
169 // get the number of rows in the query
170 rs.setFetchDirection(ResultSet.FETCH_FORWARD);
172 tableInfo.setNumRows(rs.getRow());
174 } catch (SQLException e) {
176 // we don't know how many rows are in the query
178 tableInfo.setNumRows(0);
180 // this is a little awkward but we want to ensure that we're cleaning everything up that has been used
185 } catch (Exception e) {
194 public ArrayList<String[]> getTableData(int start, int length, String table) {
195 LayoutGroupVector layoutList = document.get_data_layout_groups("list", table);
196 LayoutItemVector layoutItems = layoutList.get(0).get_items();
198 LayoutFieldVector layoutFields = new LayoutFieldVector();
199 SortClause sortClause = new SortClause();
200 int numItems = safeLongToInt(layoutItems.size());
201 for (int i = 0; i < numItems; i++) {
202 LayoutItem item = layoutItems.get(i);
203 LayoutItem_Field field = LayoutItem_Field.cast_dynamic(item);
205 layoutFields.add(field);
206 Field details = field.get_full_field_details();
207 if (details != null && details.get_primary_key()) {
208 sortClause.addLast(new SortFieldPair(field, true)); // ascending
213 ArrayList<String[]> rowsList = new ArrayList<String[]>();
214 Connection conn = null;
218 // setup and execute the query
219 conn = cpds.getConnection();
220 st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
221 String query = Glom.build_sql_select_simple(table, layoutFields, sortClause);
222 rs = st.executeQuery(query);
224 // get data we're asked for
225 // TODO need to setup the result set in cursor mode so that not all of the results are pulled into memory
226 rs.setFetchDirection(ResultSet.FETCH_FORWARD);
229 while (rs.next() && rowCount <= length) {
230 int layoutItemsSize = safeLongToInt(layoutItems.size());
231 String[] rowArray = new String[layoutItemsSize];
232 for (int i = 0; i < layoutItemsSize; i++) {
233 LayoutItem_Field field = layoutFields.get(i);
234 FieldFormatting formatting = field.get_formatting_used();
236 // field values are converted to strings differently for every glom type
237 Field.glom_field_type fieldType = field.get_glom_type();
240 rowArray[i] = rs.getString(i + 1);
243 rowArray[i] = rs.getBoolean(i + 1) ? "TRUE" : "FALSE";
246 NumericFormat numFormatGlom = formatting.getM_numeric_format();
247 // there's no isCurrency() method in the glom NumericFormat class so we're assuming that the
248 // number should be formatted as a currency if the currency symbol is set
249 String currencySymbol = numFormatGlom.getM_currency_symbol();
250 NumberFormat numFormatJava;
251 if (currencySymbol.length() == 3) {
252 Currency currency = Currency.getInstance(currencySymbol);
253 // we're not using the glom value for digits and grouping when it's a currency
254 int digits = currency.getDefaultFractionDigits();
255 numFormatJava = (DecimalFormat) NumberFormat.getCurrencyInstance(locale);
256 numFormatJava.setCurrency(currency);
257 numFormatJava.setMinimumFractionDigits(digits);
258 numFormatJava.setMaximumFractionDigits(digits);
260 numFormatJava = NumberFormat.getInstance(locale);
261 if (numFormatGlom.getM_decimal_places_restricted()) {
262 int digits = safeLongToInt(numFormatGlom.getM_decimal_places());
263 numFormatJava.setMinimumFractionDigits(digits);
264 numFormatJava.setMaximumFractionDigits(digits);
266 numFormatJava.setGroupingUsed(numFormatGlom.getM_use_thousands_separator());
269 // TODO: Do I need to do something with this from libglom?
270 // NumericFormat.get_default_precision();
272 rowArray[i] = numFormatJava.format(rs.getDouble(i + 1));
275 Date date = rs.getDate(i + 1);
277 DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
278 rowArray[i] = dateFormat.format(rs.getDate(i + 1));
284 Time time = rs.getTime(i + 1);
286 DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
287 rowArray[i] = timeFormat.format(time);
293 // TODO log warning message
297 // TODO log warning message
301 rowsList.add(rowArray);
304 } catch (SQLException e) {
305 // TODO: log error, notify user of problem
308 // this is a little awkward but we want to ensure that we're cleaning everything up that has been used
313 } catch (Exception e) {
321 // Called only when the servlet is stopped (the servlet container is stopped or restarted)
322 public void destroy() {
323 Glom.libglom_deinit();
325 DataSources.destroy(cpds);
326 } catch (SQLException e) {
327 // TODO log error, don't need to notify user because this is a clean up method