Add support for formatting glom types as specified in the glom file.
[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.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;
32
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;
49
50 import com.google.gwt.user.server.rpc.RemoteServiceServlet;
51 import com.mchange.v2.c3p0.ComboPooledDataSource;
52 import com.mchange.v2.c3p0.DataSources;
53
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;
60
61         // Called only when the servlet is stopped (the servlet container is stopped or restarted)
62         public OnlineGlomServiceImpl() {
63                 Glom.libglom_init();
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");
67                 int error = 0;
68                 @SuppressWarnings("unused")
69                 boolean retval = document.load(error);
70                 // TODO handle error condition (also below)
71
72                 cpds = new ComboPooledDataSource();
73                 // load the jdbc driver
74                 try {
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
78                         e.printStackTrace();
79                 }
80
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
84                 cpds.setUser("ben");
85                 cpds.setPassword("ChangeMe"); // of course it's not the password I'm using on my server
86         }
87
88         /*
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
91          */
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.");
95                 }
96                 return (int) l;
97         }
98
99         public GlomDocument getGlomDocument() {
100                 GlomDocument glomDocument = new GlomDocument();
101
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;
115                         }
116                         tableTitles[i] = document.get_table_title(tableName);
117                 }
118
119                 // set everything we need
120                 glomDocument.setTableNames(tableNames);
121                 glomDocument.setTableTitles(tableTitles);
122                 glomDocument.setTitle(document.get_database_title());
123
124                 return glomDocument;
125         }
126
127         public LayoutListTable getLayoutListTable(String tableName) {
128                 LayoutListTable tableInfo = new LayoutListTable();
129
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);
139                         if (field != null) {
140                                 layoutFields.add(field);
141                         }
142                 }
143
144                 tableInfo.setColumnTitles(columnTitles);
145
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
148                 // first page
149                 // TODO this code is really similar to code in getTableData, find a way to not duplicate the code
150                 Connection conn = null;
151                 Statement st = null;
152                 ResultSet rs = null;
153                 try {
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);
159
160                         // get the number of rows in the query
161                         rs.setFetchDirection(ResultSet.FETCH_FORWARD);
162                         rs.last();
163                         tableInfo.setNumRows(rs.getRow());
164
165                 } catch (SQLException e) {
166                         // TODO log error
167                         // we don't know how many rows are in the query
168                         e.printStackTrace();
169                         tableInfo.setNumRows(0);
170                 } finally {
171                         // this is a little awkward but we want to ensure that we're cleaning everything up that has been used
172                         try {
173                                 rs.close();
174                                 st.close();
175                                 conn.close();
176                         } catch (Exception e) {
177                                 // TODO log error
178                                 e.printStackTrace();
179                         }
180                 }
181
182                 return tableInfo;
183         }
184
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();
188
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);
195                         if (field != null) {
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
200                                 }
201                         }
202                 }
203
204                 ArrayList<String[]> rowsList = new ArrayList<String[]>();
205                 Connection conn = null;
206                 Statement st = null;
207                 ResultSet rs = null;
208                 try {
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);
214
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);
218                         rs.absolute(start);
219                         int rowCount = 0;
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();
226
227                                         // field values are converted to strings differently for every glom type
228                                         Field.glom_field_type fieldType = field.get_glom_type();
229                                         switch (fieldType) {
230                                         case TYPE_TEXT:
231                                                 rowArray[i] = rs.getString(i + 1);
232                                                 break;
233                                         case TYPE_BOOLEAN:
234                                                 rowArray[i] = rs.getBoolean(i + 1) ? "TRUE" : "FALSE";
235                                                 break;
236                                         case TYPE_NUMERIC:
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);
250                                                 } else {
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);
256                                                         }
257                                                         numFormatJava.setGroupingUsed(numFormatGlom.getM_use_thousands_separator());
258                                                 }
259
260                                                 // TODO: Do I need to do something with this from libglom?
261                                                 // NumericFormat.get_default_precision();
262
263                                                 rowArray[i] = numFormatJava.format(rs.getDouble(i + 1));
264                                                 break;
265                                         case TYPE_DATE:
266                                                 // TODO implement converting from Date to string
267                                                 break;
268                                         case TYPE_TIME:
269                                                 // TODO implement coverting from Time to string
270                                                 break;
271                                         case TYPE_IMAGE:
272                                                 // TODO log warning message
273                                                 break;
274                                         case TYPE_INVALID:
275                                         default:
276                                                 // TODO log warning message
277                                                 break;
278                                         }
279                                 }
280                                 rowsList.add(rowArray);
281                                 rowCount++;
282                         }
283                 } catch (SQLException e) {
284                         // TODO: log error, notify user of problem
285                         e.printStackTrace();
286                 } finally {
287                         // this is a little awkward but we want to ensure that we're cleaning everything up that has been used
288                         try {
289                                 rs.close();
290                                 st.close();
291                                 conn.close();
292                         } catch (Exception e) {
293                                 // TODO log error
294                                 e.printStackTrace();
295                         }
296                 }
297                 return rowsList;
298         }
299
300         // Called only when the servlet is stopped (the servlet container is stopped or restarted)
301         public void destroy() {
302                 Glom.libglom_deinit();
303                 try {
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
307                         e.printStackTrace();
308                 }
309         }
310
311 }