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;
24 import java.sql.ResultSet;
25 import java.sql.SQLException;
26 import java.sql.Statement;
27 import java.text.DecimalFormat;
28 import java.text.NumberFormat;
29 import java.util.ArrayList;
30 import java.util.Currency;
31 import java.util.Locale;
33 import org.glom.libglom.Document;
34 import org.glom.libglom.Field;
35 import org.glom.libglom.FieldFormatting;
36 import org.glom.libglom.Glom;
37 import org.glom.libglom.LayoutFieldVector;
38 import org.glom.libglom.LayoutGroupVector;
39 import org.glom.libglom.LayoutItem;
40 import org.glom.libglom.LayoutItemVector;
41 import org.glom.libglom.LayoutItem_Field;
42 import org.glom.libglom.NumericFormat;
43 import org.glom.libglom.SortClause;
44 import org.glom.libglom.SortFieldPair;
45 import org.glom.libglom.StringVector;
46 import org.glom.web.client.OnlineGlomService;
47 import org.glom.web.shared.GlomDocument;
48 import org.glom.web.shared.LayoutListTable;
50 import com.google.gwt.user.server.rpc.RemoteServiceServlet;
51 import com.mchange.v2.c3p0.ComboPooledDataSource;
52 import com.mchange.v2.c3p0.DataSources;
54 @SuppressWarnings("serial")
55 public class OnlineGlomServiceImpl extends RemoteServiceServlet implements OnlineGlomService {
56 private Document document;
57 private ComboPooledDataSource cpds;
58 // TODO implement locale
59 private Locale locale = Locale.ENGLISH;
61 // Called only when the servlet is stopped (the servlet container is stopped or restarted)
62 public OnlineGlomServiceImpl() {
64 document = new Document();
65 // TODO hardcoded for now, need to figure out something for this
66 document.set_file_uri("file:///home/ben/music-collection.glom");
68 @SuppressWarnings("unused")
69 boolean retval = document.load(error);
70 // TODO handle error condition (also below)
72 cpds = new ComboPooledDataSource();
73 // load the jdbc driver
75 cpds.setDriverClass("org.postgresql.Driver");
76 } catch (PropertyVetoException e) {
77 // TODO log error, fatal error can't continue, user can be nofified when db access doesn't work
81 cpds.setJdbcUrl("jdbc:postgresql://" + document.get_connection_server() + "/"
82 + document.get_connection_database());
83 // TODO figure out something for db user name and password
85 cpds.setPassword("ChangeMe"); // of course it's not the password I'm using on my server
89 * FIXME I think Swig is generating long on 64-bit machines and int on 32-bit machines - need to keep this constant
90 * http://stackoverflow.com/questions/1590831/safely-casting-long-to-int-in-java
92 public static int safeLongToInt(long l) {
93 if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) {
94 throw new IllegalArgumentException(l + " cannot be cast to int without changing its value.");
99 public GlomDocument getGlomDocument() {
100 GlomDocument glomDocument = new GlomDocument();
102 // get arrays of table names and titles, and find the default table index
103 StringVector tablesVec = document.get_table_names();
104 int numTables = safeLongToInt(tablesVec.size());
105 String[] tableNames = new String[numTables];
106 String[] tableTitles = new String[numTables];
107 boolean foundDefaultTable = false;
108 for (int i = 0; i < numTables; i++) {
109 String tableName = tablesVec.get(i);
110 tableNames[i] = tableName;
111 // JNI is "expensive", the comparison will only be called if we haven't already found the default table
112 if (!foundDefaultTable && tableName.equals(document.get_default_table())) {
113 glomDocument.setDefaultTableIndex(i);
114 foundDefaultTable = true;
116 tableTitles[i] = document.get_table_title(tableName);
119 // set everything we need
120 glomDocument.setTableNames(tableNames);
121 glomDocument.setTableTitles(tableTitles);
122 glomDocument.setTitle(document.get_database_title());
127 public LayoutListTable getLayoutListTable(String tableName) {
128 LayoutListTable tableInfo = new LayoutListTable();
130 LayoutGroupVector layoutListVec = document.get_data_layout_groups("list", tableName);
131 LayoutItemVector layoutItemsVec = layoutListVec.get(0).get_items();
132 int numItems = safeLongToInt(layoutItemsVec.size());
133 String[] columnTitles = new String[numItems];
134 LayoutFieldVector layoutFields = new LayoutFieldVector();
135 for (int i = 0; i < numItems; i++) {
136 LayoutItem item = layoutItemsVec.get(i);
137 columnTitles[i] = item.get_title_or_name();
138 LayoutItem_Field field = LayoutItem_Field.cast_dynamic(item);
140 layoutFields.add(field);
144 tableInfo.setColumnTitles(columnTitles);
146 // get the size of the returned query for the pager
147 // TODO since we're executing a query anyway, maybe we should return the rows that will be displayed on the
149 // TODO this code is really similar to code in getTableData, find a way to not duplicate the code
150 Connection conn = null;
154 // setup and execute the query
155 conn = cpds.getConnection();
156 st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
157 String query = Glom.build_sql_select_simple(tableName, layoutFields);
158 rs = st.executeQuery(query);
160 // get the number of rows in the query
161 rs.setFetchDirection(ResultSet.FETCH_FORWARD);
163 tableInfo.setNumRows(rs.getRow());
165 } catch (SQLException e) {
167 // we don't know how many rows are in the query
169 tableInfo.setNumRows(0);
171 // this is a little awkward but we want to ensure that we're cleaning everything up that has been used
176 } catch (Exception e) {
185 public ArrayList<String[]> getTableData(int start, int length, String table) {
186 LayoutGroupVector layoutList = document.get_data_layout_groups("list", table);
187 LayoutItemVector layoutItems = layoutList.get(0).get_items();
189 LayoutFieldVector layoutFields = new LayoutFieldVector();
190 SortClause sortClause = new SortClause();
191 int numItems = safeLongToInt(layoutItems.size());
192 for (int i = 0; i < numItems; i++) {
193 LayoutItem item = layoutItems.get(i);
194 LayoutItem_Field field = LayoutItem_Field.cast_dynamic(item);
196 layoutFields.add(field);
197 Field details = field.get_full_field_details();
198 if (details != null && details.get_primary_key()) {
199 sortClause.addLast(new SortFieldPair(field, true)); // ascending
204 ArrayList<String[]> rowsList = new ArrayList<String[]>();
205 Connection conn = null;
209 // setup and execute the query
210 conn = cpds.getConnection();
211 st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
212 String query = Glom.build_sql_select_simple(table, layoutFields, sortClause);
213 rs = st.executeQuery(query);
215 // get data we're asked for
216 // TODO need to setup the result set in cursor mode so that not all of the results are pulled into memory
217 rs.setFetchDirection(ResultSet.FETCH_FORWARD);
220 while (rs.next() && rowCount <= length) {
221 int layoutItemsSize = safeLongToInt(layoutItems.size());
222 String[] rowArray = new String[layoutItemsSize];
223 for (int i = 0; i < layoutItemsSize; i++) {
224 LayoutItem_Field field = layoutFields.get(i);
225 FieldFormatting formatting = field.get_formatting_used();
227 // field values are converted to strings differently for every glom type
228 Field.glom_field_type fieldType = field.get_glom_type();
231 rowArray[i] = rs.getString(i + 1);
234 rowArray[i] = rs.getBoolean(i + 1) ? "TRUE" : "FALSE";
237 NumericFormat numFormatGlom = formatting.getM_numeric_format();
238 // there's no isCurrency() method in the glom NumericFormat class so we're assuming that the
239 // number should be formatted as a currency if the currency symbol is set
240 String currencySymbol = numFormatGlom.getM_currency_symbol();
241 NumberFormat numFormatJava;
242 if (currencySymbol.length() == 3) {
243 Currency currency = Currency.getInstance(currencySymbol);
244 // we're not using the glom value for digits or grouping when it's a currency
245 int digits = currency.getDefaultFractionDigits();
246 numFormatJava = (DecimalFormat) NumberFormat.getCurrencyInstance(locale);
247 numFormatJava.setCurrency(currency);
248 numFormatJava.setMinimumFractionDigits(digits);
249 numFormatJava.setMaximumFractionDigits(digits);
251 numFormatJava = NumberFormat.getInstance(locale);
252 if (numFormatGlom.getM_decimal_places_restricted()) {
253 int digits = safeLongToInt(numFormatGlom.getM_decimal_places());
254 numFormatJava.setMinimumFractionDigits(digits);
255 numFormatJava.setMaximumFractionDigits(digits);
257 numFormatJava.setGroupingUsed(numFormatGlom.getM_use_thousands_separator());
260 // TODO: Do I need to do something with this from libglom?
261 // NumericFormat.get_default_precision();
263 rowArray[i] = numFormatJava.format(rs.getDouble(i + 1));
266 // TODO implement converting from Date to string
269 // TODO implement coverting from Time to string
272 // TODO log warning message
276 // TODO log warning message
280 rowsList.add(rowArray);
283 } catch (SQLException e) {
284 // TODO: log error, notify user of problem
287 // this is a little awkward but we want to ensure that we're cleaning everything up that has been used
292 } catch (Exception e) {
300 // Called only when the servlet is stopped (the servlet container is stopped or restarted)
301 public void destroy() {
302 Glom.libglom_deinit();
304 DataSources.destroy(cpds);
305 } catch (SQLException e) {
306 // TODO log error, don't need to notify user because this is a clean up method