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();
107 int numTables = safeLongToInt(tablesVec.size());
108 String[] tableNames = new String[numTables];
109 String[] tableTitles = new String[numTables];
110 boolean foundDefaultTable = false;
111 for (int i = 0; i < numTables; i++) {
112 String tableName = tablesVec.get(i);
113 tableNames[i] = tableName;
114 // JNI is "expensive", the comparison will only be called if we haven't already found the default table
115 if (!foundDefaultTable && tableName.equals(document.get_default_table())) {
116 glomDocument.setDefaultTableIndex(i);
117 foundDefaultTable = true;
119 tableTitles[i] = document.get_table_title(tableName);
122 // set everything we need
123 glomDocument.setTableNames(tableNames);
124 glomDocument.setTableTitles(tableTitles);
125 glomDocument.setTitle(document.get_database_title());
130 public LayoutListTable getLayoutListTable(String tableName) {
131 LayoutListTable tableInfo = new LayoutListTable();
133 LayoutGroupVector layoutListVec = document.get_data_layout_groups("list", tableName);
134 LayoutItemVector layoutItemsVec = layoutListVec.get(0).get_items();
135 int numItems = safeLongToInt(layoutItemsVec.size());
136 String[] columnTitles = new String[numItems];
137 LayoutFieldVector layoutFields = new LayoutFieldVector();
138 for (int i = 0; i < numItems; i++) {
139 LayoutItem item = layoutItemsVec.get(i);
140 columnTitles[i] = item.get_title_or_name();
141 LayoutItem_Field field = LayoutItem_Field.cast_dynamic(item);
143 layoutFields.add(field);
147 tableInfo.setColumnTitles(columnTitles);
149 // get the size of the returned query for the pager
150 // TODO since we're executing a query anyway, maybe we should return the rows that will be displayed on the
152 // TODO this code is really similar to code in getTableData, find a way to not duplicate the code
153 Connection conn = null;
157 // setup and execute the query
158 conn = cpds.getConnection();
159 st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
160 String query = Glom.build_sql_select_simple(tableName, layoutFields);
161 rs = st.executeQuery(query);
163 // get the number of rows in the query
164 rs.setFetchDirection(ResultSet.FETCH_FORWARD);
166 tableInfo.setNumRows(rs.getRow());
168 } catch (SQLException e) {
170 // we don't know how many rows are in the query
172 tableInfo.setNumRows(0);
174 // this is a little awkward but we want to ensure that we're cleaning everything up that has been used
179 } catch (Exception e) {
188 public ArrayList<String[]> getTableData(int start, int length, String table) {
189 LayoutGroupVector layoutList = document.get_data_layout_groups("list", table);
190 LayoutItemVector layoutItems = layoutList.get(0).get_items();
192 LayoutFieldVector layoutFields = new LayoutFieldVector();
193 SortClause sortClause = new SortClause();
194 int numItems = safeLongToInt(layoutItems.size());
195 for (int i = 0; i < numItems; i++) {
196 LayoutItem item = layoutItems.get(i);
197 LayoutItem_Field field = LayoutItem_Field.cast_dynamic(item);
199 layoutFields.add(field);
200 Field details = field.get_full_field_details();
201 if (details != null && details.get_primary_key()) {
202 sortClause.addLast(new SortFieldPair(field, true)); // ascending
207 ArrayList<String[]> rowsList = new ArrayList<String[]>();
208 Connection conn = null;
212 // setup and execute the query
213 conn = cpds.getConnection();
214 st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
215 String query = Glom.build_sql_select_simple(table, layoutFields, sortClause);
216 rs = st.executeQuery(query);
218 // get data we're asked for
219 // TODO need to setup the result set in cursor mode so that not all of the results are pulled into memory
220 rs.setFetchDirection(ResultSet.FETCH_FORWARD);
223 while (rs.next() && rowCount <= length) {
224 int layoutItemsSize = safeLongToInt(layoutItems.size());
225 String[] rowArray = new String[layoutItemsSize];
226 for (int i = 0; i < layoutItemsSize; i++) {
227 LayoutItem_Field field = layoutFields.get(i);
228 FieldFormatting formatting = field.get_formatting_used();
230 // field values are converted to strings differently for every glom type
231 Field.glom_field_type fieldType = field.get_glom_type();
234 rowArray[i] = rs.getString(i + 1);
237 rowArray[i] = rs.getBoolean(i + 1) ? "TRUE" : "FALSE";
240 NumericFormat numFormatGlom = formatting.getM_numeric_format();
241 // there's no isCurrency() method in the glom NumericFormat class so we're assuming that the
242 // number should be formatted as a currency if the currency symbol is set
243 String currencySymbol = numFormatGlom.getM_currency_symbol();
244 NumberFormat numFormatJava;
245 if (currencySymbol.length() == 3) {
246 Currency currency = Currency.getInstance(currencySymbol);
247 // we're not using the glom value for digits or grouping when it's a currency
248 int digits = currency.getDefaultFractionDigits();
249 numFormatJava = (DecimalFormat) NumberFormat.getCurrencyInstance(locale);
250 numFormatJava.setCurrency(currency);
251 numFormatJava.setMinimumFractionDigits(digits);
252 numFormatJava.setMaximumFractionDigits(digits);
254 numFormatJava = NumberFormat.getInstance(locale);
255 if (numFormatGlom.getM_decimal_places_restricted()) {
256 int digits = safeLongToInt(numFormatGlom.getM_decimal_places());
257 numFormatJava.setMinimumFractionDigits(digits);
258 numFormatJava.setMaximumFractionDigits(digits);
260 numFormatJava.setGroupingUsed(numFormatGlom.getM_use_thousands_separator());
263 // TODO: Do I need to do something with this from libglom?
264 // NumericFormat.get_default_precision();
266 rowArray[i] = numFormatJava.format(rs.getDouble(i + 1));
269 Date date = rs.getDate(i + 1);
271 DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
272 rowArray[i] = dateFormat.format(rs.getDate(i + 1));
278 Time time = rs.getTime(i + 1);
280 DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
281 rowArray[i] = timeFormat.format(time);
287 // TODO log warning message
291 // TODO log warning message
295 rowsList.add(rowArray);
298 } catch (SQLException e) {
299 // TODO: log error, notify user of problem
302 // this is a little awkward but we want to ensure that we're cleaning everything up that has been used
307 } catch (Exception e) {
315 // Called only when the servlet is stopped (the servlet container is stopped or restarted)
316 public void destroy() {
317 Glom.libglom_deinit();
319 DataSources.destroy(cpds);
320 } catch (SQLException e) {
321 // TODO log error, don't need to notify user because this is a clean up method