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