Add support of Date and Time number types.
[online-glom:gwt-glom.git] / src / main / java / org / glom / web / server / OnlineGlomServiceImpl.java
1 /*
2  * Copyright (C) 2010, 2011 Openismus GmbH
3  *
4  * This file is part of GWT-Glom.
5  *
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.
10  *
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
14  * for more details.
15  *
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/>.
18  */
19
20 package org.glom.web.server;
21
22 import java.beans.PropertyVetoException;
23 import java.sql.Connection;
24 import java.sql.Date;
25 import java.sql.ResultSet;
26 import java.sql.SQLException;
27 import java.sql.Statement;
28 import java.sql.Time;
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;
35
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;
52
53 import com.google.gwt.user.server.rpc.RemoteServiceServlet;
54 import com.mchange.v2.c3p0.ComboPooledDataSource;
55 import com.mchange.v2.c3p0.DataSources;
56
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;
63
64         // Called only when the servlet is stopped (the servlet container is stopped or restarted)
65         public OnlineGlomServiceImpl() {
66                 Glom.libglom_init();
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");
70                 int error = 0;
71                 @SuppressWarnings("unused")
72                 boolean retval = document.load(error);
73                 // TODO handle error condition (also below)
74
75                 cpds = new ComboPooledDataSource();
76                 // load the jdbc driver
77                 try {
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
81                         e.printStackTrace();
82                 }
83
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
87                 cpds.setUser("ben");
88                 cpds.setPassword("ChangeMe"); // of course it's not the password I'm using on my server
89         }
90
91         /*
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
94          */
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.");
98                 }
99                 return (int) l;
100         }
101
102         public GlomDocument getGlomDocument() {
103                 GlomDocument glomDocument = new GlomDocument();
104
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;
118                         }
119                         tableTitles[i] = document.get_table_title(tableName);
120                 }
121
122                 // set everything we need
123                 glomDocument.setTableNames(tableNames);
124                 glomDocument.setTableTitles(tableTitles);
125                 glomDocument.setTitle(document.get_database_title());
126
127                 return glomDocument;
128         }
129
130         public LayoutListTable getLayoutListTable(String tableName) {
131                 LayoutListTable tableInfo = new LayoutListTable();
132
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);
142                         if (field != null) {
143                                 layoutFields.add(field);
144                         }
145                 }
146
147                 tableInfo.setColumnTitles(columnTitles);
148
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
151                 // first page
152                 // TODO this code is really similar to code in getTableData, find a way to not duplicate the code
153                 Connection conn = null;
154                 Statement st = null;
155                 ResultSet rs = null;
156                 try {
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);
162
163                         // get the number of rows in the query
164                         rs.setFetchDirection(ResultSet.FETCH_FORWARD);
165                         rs.last();
166                         tableInfo.setNumRows(rs.getRow());
167
168                 } catch (SQLException e) {
169                         // TODO log error
170                         // we don't know how many rows are in the query
171                         e.printStackTrace();
172                         tableInfo.setNumRows(0);
173                 } finally {
174                         // this is a little awkward but we want to ensure that we're cleaning everything up that has been used
175                         try {
176                                 rs.close();
177                                 st.close();
178                                 conn.close();
179                         } catch (Exception e) {
180                                 // TODO log error
181                                 e.printStackTrace();
182                         }
183                 }
184
185                 return tableInfo;
186         }
187
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();
191
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);
198                         if (field != null) {
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
203                                 }
204                         }
205                 }
206
207                 ArrayList<String[]> rowsList = new ArrayList<String[]>();
208                 Connection conn = null;
209                 Statement st = null;
210                 ResultSet rs = null;
211                 try {
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);
217
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);
221                         rs.absolute(start);
222                         int rowCount = 0;
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();
229
230                                         // field values are converted to strings differently for every glom type
231                                         Field.glom_field_type fieldType = field.get_glom_type();
232                                         switch (fieldType) {
233                                         case TYPE_TEXT:
234                                                 rowArray[i] = rs.getString(i + 1);
235                                                 break;
236                                         case TYPE_BOOLEAN:
237                                                 rowArray[i] = rs.getBoolean(i + 1) ? "TRUE" : "FALSE";
238                                                 break;
239                                         case TYPE_NUMERIC:
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);
253                                                 } else {
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);
259                                                         }
260                                                         numFormatJava.setGroupingUsed(numFormatGlom.getM_use_thousands_separator());
261                                                 }
262
263                                                 // TODO: Do I need to do something with this from libglom?
264                                                 // NumericFormat.get_default_precision();
265
266                                                 rowArray[i] = numFormatJava.format(rs.getDouble(i + 1));
267                                                 break;
268                                         case TYPE_DATE:
269                                                 Date date = rs.getDate(i + 1);
270                                                 if (date != null) {
271                                                         DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
272                                                         rowArray[i] = dateFormat.format(rs.getDate(i + 1));
273                                                 } else {
274                                                         rowArray[i] = "";
275                                                 }
276                                                 break;
277                                         case TYPE_TIME:
278                                                 Time time = rs.getTime(i + 1);
279                                                 if (time != null) {
280                                                         DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
281                                                         rowArray[i] = timeFormat.format(time);
282                                                 } else {
283                                                         rowArray[i] = "";
284                                                 }
285                                                 break;
286                                         case TYPE_IMAGE:
287                                                 // TODO log warning message
288                                                 break;
289                                         case TYPE_INVALID:
290                                         default:
291                                                 // TODO log warning message
292                                                 break;
293                                         }
294                                 }
295                                 rowsList.add(rowArray);
296                                 rowCount++;
297                         }
298                 } catch (SQLException e) {
299                         // TODO: log error, notify user of problem
300                         e.printStackTrace();
301                 } finally {
302                         // this is a little awkward but we want to ensure that we're cleaning everything up that has been used
303                         try {
304                                 rs.close();
305                                 st.close();
306                                 conn.close();
307                         } catch (Exception e) {
308                                 // TODO log error
309                                 e.printStackTrace();
310                         }
311                 }
312                 return rowsList;
313         }
314
315         // Called only when the servlet is stopped (the servlet container is stopped or restarted)
316         public void destroy() {
317                 Glom.libglom_deinit();
318                 try {
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
322                         e.printStackTrace();
323                 }
324         }
325
326 }