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