Change to using a neutral locale for currency, date and time formatting.
[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.ColumnInfo;
51 import org.glom.web.shared.GlomDocument;
52 import org.glom.web.shared.GlomField;
53 import org.glom.web.shared.LayoutListTable;
54
55 import com.google.gwt.user.server.rpc.RemoteServiceServlet;
56 import com.mchange.v2.c3p0.ComboPooledDataSource;
57 import com.mchange.v2.c3p0.DataSources;
58
59 @SuppressWarnings("serial")
60 public class OnlineGlomServiceImpl extends RemoteServiceServlet implements OnlineGlomService {
61         private Document document;
62         private ComboPooledDataSource cpds;
63         // TODO implement locale
64         private Locale locale = Locale.ROOT;
65
66         /*
67          * This is called when the servlet is started or restarted.
68          */
69         public OnlineGlomServiceImpl() {
70                 Glom.libglom_init();
71                 document = new Document();
72                 // TODO hard-coded for now, need to figure out something for this
73                 document.set_file_uri("file:///home/ben/small-business-example.glom");
74                 // document.set_file_uri("file:///home/ben/music-collection.glom");
75                 int error = 0;
76                 @SuppressWarnings("unused")
77                 boolean retval = document.load(error);
78                 // TODO handle error condition (also below)
79
80                 cpds = new ComboPooledDataSource();
81                 // load the jdbc driver
82                 try {
83                         cpds.setDriverClass("org.postgresql.Driver");
84                 } catch (PropertyVetoException e) {
85                         // TODO log error, fatal error can't continue, user can be notified when db access doesn't work
86                         e.printStackTrace();
87                 }
88
89                 cpds.setJdbcUrl("jdbc:postgresql://" + document.get_connection_server() + "/"
90                                 + document.get_connection_database());
91                 // TODO figure out something for db user name and password
92                 cpds.setUser("ben");
93                 cpds.setPassword("ChangeMe"); // of course it's not the password I'm using on my server
94         }
95
96         /*
97          * This is called when the servlet is stopped or restarted.
98          * 
99          * @see javax.servlet.GenericServlet#destroy()
100          */
101         public void destroy() {
102                 Glom.libglom_deinit();
103                 try {
104                         DataSources.destroy(cpds);
105                 } catch (SQLException e) {
106                         // TODO log error, don't need to notify user because this is a clean up method
107                         e.printStackTrace();
108                 }
109         }
110
111         /*
112          * FIXME I think Swig is generating long on 64-bit machines and int on 32-bit machines - need to keep this constant
113          * http://stackoverflow.com/questions/1590831/safely-casting-long-to-int-in-java
114          */
115         public static int safeLongToInt(long l) {
116                 if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) {
117                         throw new IllegalArgumentException(l + " cannot be cast to int without changing its value.");
118                 }
119                 return (int) l;
120         }
121
122         public GlomDocument getGlomDocument() {
123                 GlomDocument glomDocument = new GlomDocument();
124
125                 // get arrays of table names and titles, and find the default table index
126                 StringVector tablesVec = document.get_table_names();
127
128                 int numTables = safeLongToInt(tablesVec.size());
129                 // we don't know how many tables will be hidden so we'll use half of the number of tables for the default size
130                 // of the ArrayList
131                 ArrayList<String> tableNames = new ArrayList<String>(numTables / 2);
132                 ArrayList<String> tableTitles = new ArrayList<String>(numTables / 2);
133                 boolean foundDefaultTable = false;
134                 for (int i = 0; i < numTables; i++) {
135                         String tableName = tablesVec.get(i);
136                         if (!document.get_table_is_hidden(tableName)) {
137                                 tableNames.add(tableName);
138                                 // JNI is "expensive", the comparison will only be called if we haven't already found the default table
139                                 if (!foundDefaultTable && tableName.equals(document.get_default_table())) {
140                                         glomDocument.setDefaultTableIndex(i);
141                                         foundDefaultTable = true;
142                                 }
143                                 tableTitles.add(document.get_table_title(tableName));
144                         }
145                 }
146
147                 // set everything we need
148                 glomDocument.setTableNames(tableNames);
149                 glomDocument.setTableTitles(tableTitles);
150                 glomDocument.setTitle(document.get_database_title());
151
152                 return glomDocument;
153         }
154
155         public LayoutListTable getLayoutListTable(String tableName) {
156                 LayoutListTable tableInfo = new LayoutListTable();
157
158                 // access the layout list
159                 LayoutGroupVector layoutListVec = document.get_data_layout_groups("list", tableName);
160                 LayoutItemVector layoutItemsVec = layoutListVec.get(0).get_items();
161
162                 // find the layout list fields
163                 int numItems = safeLongToInt(layoutItemsVec.size());
164                 ColumnInfo[] columns = new ColumnInfo[numItems];
165                 LayoutFieldVector layoutFields = new LayoutFieldVector();
166                 for (int i = 0; i < numItems; i++) {
167                         // TODO add support for other LayoutItems (Text, Image, Button)
168                         LayoutItem item = layoutItemsVec.get(i);
169                         LayoutItem_Field field = LayoutItem_Field.cast_dynamic(item);
170                         if (field != null) {
171                                 layoutFields.add(field);
172                                 FieldFormatting.HorizontalAlignment alignment = field.get_formatting_used_horizontal_alignment();
173                                 columns[i] = new ColumnInfo(item.get_title_or_name(), getColumnInfoHorizontalAlignment(alignment));
174                         }
175                 }
176                 tableInfo.setColumns(columns);
177
178                 // get the size of the returned query for the pager
179                 // TODO since we're executing a query anyway, maybe we should return the rows that will be displayed on the
180                 // first page
181                 // TODO this code is really similar to code in getTableData, find a way to not duplicate the code
182                 Connection conn = null;
183                 Statement st = null;
184                 ResultSet rs = null;
185                 try {
186                         // setup and execute the query
187                         conn = cpds.getConnection();
188                         st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
189                         String query = Glom.build_sql_select_simple(tableName, layoutFields);
190                         rs = st.executeQuery(query);
191
192                         // get the number of rows in the query
193                         rs.setFetchDirection(ResultSet.FETCH_FORWARD);
194                         rs.last();
195                         tableInfo.setNumRows(rs.getRow());
196
197                 } catch (SQLException e) {
198                         // TODO log error
199                         // we don't know how many rows are in the query
200                         e.printStackTrace();
201                         tableInfo.setNumRows(0);
202                 } finally {
203                         // cleanup everything that has been used
204                         try {
205                                 rs.close();
206                                 st.close();
207                                 conn.close();
208                         } catch (Exception e) {
209                                 // TODO log error
210                                 e.printStackTrace();
211                         }
212                 }
213
214                 return tableInfo;
215         }
216
217         public ArrayList<GlomField[]> getTableData(String table, int start, int length) {
218                 return getTableData(table, start, length, false, 0, false);
219         }
220
221         public ArrayList<GlomField[]> getSortedTableData(String table, int start, int length, int sortColumnIndex,
222                         boolean isAscending) {
223                 return getTableData(table, start, length, true, sortColumnIndex, isAscending);
224         }
225
226         private ArrayList<GlomField[]> getTableData(String table, int start, int length, boolean useSortClause,
227                         int sortColumnIndex, boolean isAscending) {
228
229                 // access the layout list
230                 LayoutGroupVector layoutList = document.get_data_layout_groups("list", table);
231                 LayoutItemVector layoutItems = layoutList.get(0).get_items();
232
233                 LayoutFieldVector layoutFields = new LayoutFieldVector();
234                 SortClause sortClause = new SortClause();
235                 int numItems = safeLongToInt(layoutItems.size());
236                 for (int i = 0; i < numItems; i++) {
237                         LayoutItem item = layoutItems.get(i);
238                         LayoutItem_Field field = LayoutItem_Field.cast_dynamic(item);
239                         if (field != null) {
240                                 // use this field in the layout
241                                 layoutFields.add(field);
242
243                                 // create a sort clause if it's a primary key and we're not asked to sort a specific column
244                                 if (!useSortClause) {
245                                         Field details = field.get_full_field_details();
246                                         if (details != null && details.get_primary_key()) {
247                                                 sortClause.addLast(new SortFieldPair(field, true)); // ascending
248                                         }
249                                 }
250                         }
251                 }
252
253                 // create a sort clause for the column we've been asked to sort
254                 if (useSortClause) {
255                         LayoutItem item = layoutItems.get(sortColumnIndex);
256                         LayoutItem_Field field = LayoutItem_Field.cast_dynamic(item);
257                         if (field != null)
258                                 sortClause.addLast(new SortFieldPair(field, isAscending));
259                         // TODO: log error in the else condition
260                 }
261
262                 ArrayList<GlomField[]> rowsList = new ArrayList<GlomField[]>();
263                 Connection conn = null;
264                 Statement st = null;
265                 ResultSet rs = null;
266                 try {
267                         // setup and execute the query
268                         conn = cpds.getConnection();
269                         st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
270                         String query = Glom.build_sql_select_simple(table, layoutFields, sortClause);
271                         rs = st.executeQuery(query);
272
273                         // get data we're asked for
274                         // TODO need to setup the result set in cursor mode so that not all of the results are pulled into memory
275                         rs.setFetchDirection(ResultSet.FETCH_FORWARD);
276                         rs.absolute(start);
277                         int rowCount = 0;
278                         while (rs.next() && rowCount <= length) {
279                                 int layoutItemsSize = safeLongToInt(layoutItems.size());
280                                 GlomField[] rowArray = new GlomField[layoutItemsSize];
281                                 for (int i = 0; i < layoutItemsSize; i++) {
282                                         // make a new GlomField to set the text and colours
283                                         rowArray[i] = new GlomField();
284
285                                         // get foreground and background colours
286                                         LayoutItem_Field field = layoutFields.get(i);
287                                         FieldFormatting formatting = field.get_formatting_used();
288                                         String fgcolour = formatting.get_text_format_color_foreground();
289                                         if (!fgcolour.isEmpty())
290                                                 rowArray[i].setFGColour(convertGdkColorToHtmlColour(fgcolour));
291                                         String bgcolour = formatting.get_text_format_color_background();
292                                         if (!bgcolour.isEmpty())
293                                                 rowArray[i].setBGColour(convertGdkColorToHtmlColour(bgcolour));
294
295                                         // convert field values are to strings based on the glom type
296                                         Field.glom_field_type fieldType = field.get_glom_type();
297                                         switch (fieldType) {
298                                         case TYPE_TEXT:
299                                                 String text = rs.getString(i + 1);
300                                                 rowArray[i].setText(text != null ? text : "");
301                                                 break;
302                                         case TYPE_BOOLEAN:
303                                                 rowArray[i].setText(rs.getBoolean(i + 1) ? "TRUE" : "FALSE");
304                                                 break;
305                                         case TYPE_NUMERIC:
306                                                 // Take care of the numeric formatting before converting the number to a string.
307                                                 NumericFormat numFormatGlom = formatting.getM_numeric_format();
308                                                 // There's no isCurrency() method in the glom NumericFormat class so we're assuming that the
309                                                 // number should be formatted as a currency if the currency code string is not empty.
310                                                 String currencyCode = numFormatGlom.getM_currency_symbol();
311                                                 NumberFormat numFormatJava = null;
312                                                 boolean useGlomCurrencyCode = false;
313                                                 if (currencyCode.length() == 3) {
314                                                         // Try to format the currency using the Java Locales system.
315                                                         try {
316                                                                 Currency currency = Currency.getInstance(currencyCode);
317                                                                 // Ignore the glom numeric formatting when a valid ISO 4217 currency code is being used.
318                                                                 int digits = currency.getDefaultFractionDigits();
319                                                                 numFormatJava = (DecimalFormat) NumberFormat.getCurrencyInstance(locale);
320                                                                 numFormatJava.setCurrency(currency);
321                                                                 numFormatJava.setMinimumFractionDigits(digits);
322                                                                 numFormatJava.setMaximumFractionDigits(digits);
323                                                         } catch (IllegalArgumentException e) {
324                                                                 // TODO: log warning
325                                                                 // The currency code is not this is not an ISO 4217 currency code.
326                                                                 // We're going to manually set the currency code and use the glom numeric formatting.
327                                                                 useGlomCurrencyCode = true;
328                                                                 numFormatJava = getJavaNumberFormat(numFormatGlom);
329                                                         }
330                                                 } else if (currencyCode.length() > 0) {
331                                                         // The length of the currency code is > 0 and != 3; this is not an ISO 4217 currency code.
332                                                         // We're going to manually set the currency code and use the glom numeric formatting.
333                                                         useGlomCurrencyCode = true;
334                                                         numFormatJava = getJavaNumberFormat(numFormatGlom);
335                                                 } else {
336                                                         // The length of the currency code is 0; the number is not a currency.
337                                                         numFormatJava = getJavaNumberFormat(numFormatGlom);
338                                                 }
339
340                                                 // TODO: Do I need to do something with NumericFormat.get_default_precision() from libglom?
341
342                                                 double number = rs.getDouble(i + 1);
343                                                 if (number < 0) {
344                                                         if (formatting.getM_numeric_format().getM_alt_foreground_color_for_negatives())
345                                                                 // overrides the set foreground colour
346                                                                 rowArray[i].setFGColour(convertGdkColorToHtmlColour(NumericFormat
347                                                                                 .get_alternative_color_for_negatives()));
348                                                 }
349
350                                                 // Finally convert the number to text using the glom currency string if required.
351                                                 if (useGlomCurrencyCode) {
352                                                         rowArray[i].setText(currencyCode + " " + numFormatJava.format(number));
353                                                 } else {
354                                                         rowArray[i].setText(numFormatJava.format(number));
355                                                 }
356                                                 break;
357                                         case TYPE_DATE:
358                                                 Date date = rs.getDate(i + 1);
359                                                 if (date != null) {
360                                                         DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
361                                                         rowArray[i].setText(dateFormat.format(rs.getDate(i + 1)));
362                                                 } else {
363                                                         rowArray[i].setText("");
364                                                 }
365                                                 break;
366                                         case TYPE_TIME:
367                                                 Time time = rs.getTime(i + 1);
368                                                 if (time != null) {
369                                                         DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
370                                                         rowArray[i].setText(timeFormat.format(time));
371                                                 } else {
372                                                         rowArray[i].setText("");
373                                                 }
374                                                 break;
375                                         case TYPE_IMAGE:
376                                                 // TODO log warning message
377                                                 break;
378                                         case TYPE_INVALID:
379                                         default:
380                                                 // TODO log warning message
381                                                 break;
382                                         }
383                                 }
384
385                                 // add the row of GlomFields to the ArrayList we're going to return and update the row count
386                                 rowsList.add(rowArray);
387                                 rowCount++;
388                         }
389                 } catch (SQLException e) {
390                         // TODO: log error, notify user of problem
391                         e.printStackTrace();
392                 } finally {
393                         // cleanup everything that has been used
394                         try {
395                                 rs.close();
396                                 st.close();
397                                 conn.close();
398                         } catch (Exception e) {
399                                 // TODO log error
400                                 e.printStackTrace();
401                         }
402                 }
403                 return rowsList;
404         }
405
406         private NumberFormat getJavaNumberFormat(NumericFormat numFormatGlom) {
407                 NumberFormat numFormatJava = NumberFormat.getInstance(locale);
408                 if (numFormatGlom.getM_decimal_places_restricted()) {
409                         int digits = safeLongToInt(numFormatGlom.getM_decimal_places());
410                         numFormatJava.setMinimumFractionDigits(digits);
411                         numFormatJava.setMaximumFractionDigits(digits);
412                 }
413                 numFormatJava.setGroupingUsed(numFormatGlom.getM_use_thousands_separator());
414                 return numFormatJava;
415         }
416
417         /*
418          * Converts a Gdk::Color (16-bits per channel) to an HTML colour (8-bits per channel) by disgarding the least
419          * significant 8-bits in each channel.
420          */
421         private String convertGdkColorToHtmlColour(String gdkColor) {
422                 if (gdkColor.length() == 13)
423                         return gdkColor.substring(0, 2) + gdkColor.substring(5, 6) + gdkColor.substring(9, 10);
424                 else if (gdkColor.length() == 7)
425                         // TODO: log warning because we're expecting a 13 character string
426                         return gdkColor;
427                 else
428                         // TODO: log error
429                         return "";
430         }
431
432         /*
433          * This method converts a FieldFormatting.HorizontalAlignment to the equivalent ColumnInfo.HorizontalAlignment. The
434          * need for this comes from the fact that the GWT HorizontalAlignment classes can't be used with RPC and there's no
435          * easy way to use the java-libglom FieldFormatting.HorizontalAlignment enum with RPC. An enum indentical to
436          * FieldFormatting.HorizontalAlignment is included in the ColumnInfo class.
437          */
438         private ColumnInfo.HorizontalAlignment getColumnInfoHorizontalAlignment(
439                         FieldFormatting.HorizontalAlignment alignment) {
440                 int value = alignment.swigValue();
441                 ColumnInfo.HorizontalAlignment[] columnInfoValues = ColumnInfo.HorizontalAlignment.class.getEnumConstants();
442                 if (value < columnInfoValues.length && value >= 0)
443                         return columnInfoValues[value];
444                 // TODO: log error: value out of range, returning HORIZONTAL_ALIGNMENT_RIGHT
445                 return columnInfoValues[FieldFormatting.HorizontalAlignment.HORIZONTAL_ALIGNMENT_RIGHT.swigValue()];
446         }
447
448 }