Add support for column sorting.
[online-glom:gwt-glom.git] / src / main / java / org / glom / web / server / OnlineGlomServiceImpl.java
1 /*
2  * Copyright (C) 2010, 2011 Openismus GmbH
3  *
4  * This file is part of GWT-Glom.
5  *
6  * GWT-Glom is free software: you can redistribute it and/or modify it
7  * under the terms of the GNU Lesser General Public License as published by the
8  * Free Software Foundation, either version 3 of the License, or (at your
9  * option) any later version.
10  *
11  * GWT-Glom is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
14  * for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public License
17  * along with GWT-Glom.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 package org.glom.web.server;
21
22 import java.beans.PropertyVetoException;
23 import java.sql.Connection;
24 import java.sql.Date;
25 import java.sql.ResultSet;
26 import java.sql.SQLException;
27 import java.sql.Statement;
28 import java.sql.Time;
29 import java.text.DateFormat;
30 import java.text.DecimalFormat;
31 import java.text.NumberFormat;
32 import java.util.ArrayList;
33 import java.util.Currency;
34 import java.util.Locale;
35
36 import org.glom.libglom.Document;
37 import org.glom.libglom.Field;
38 import org.glom.libglom.FieldFormatting;
39 import org.glom.libglom.Glom;
40 import org.glom.libglom.LayoutFieldVector;
41 import org.glom.libglom.LayoutGroupVector;
42 import org.glom.libglom.LayoutItem;
43 import org.glom.libglom.LayoutItemVector;
44 import org.glom.libglom.LayoutItem_Field;
45 import org.glom.libglom.NumericFormat;
46 import org.glom.libglom.SortClause;
47 import org.glom.libglom.SortFieldPair;
48 import org.glom.libglom.StringVector;
49 import org.glom.web.client.OnlineGlomService;
50 import org.glom.web.shared.GlomDocument;
51 import org.glom.web.shared.GlomField;
52 import org.glom.web.shared.LayoutListTable;
53
54 import com.google.gwt.user.server.rpc.RemoteServiceServlet;
55 import com.mchange.v2.c3p0.ComboPooledDataSource;
56 import com.mchange.v2.c3p0.DataSources;
57
58 @SuppressWarnings("serial")
59 public class OnlineGlomServiceImpl extends RemoteServiceServlet implements OnlineGlomService {
60         private Document document;
61         private ComboPooledDataSource cpds;
62         // TODO implement locale
63         private Locale locale = Locale.ENGLISH;
64
65         /*
66          * This is called when the servlet is started or restarted.
67          */
68         public OnlineGlomServiceImpl() {
69                 Glom.libglom_init();
70                 document = new Document();
71                 // TODO hardcoded for now, need to figure out something for this
72                 // document.set_file_uri("file:///home/ben/small-business-example.glom");
73                 document.set_file_uri("file:///home/ben/music-collection.glom");
74                 int error = 0;
75                 @SuppressWarnings("unused")
76                 boolean retval = document.load(error);
77                 // TODO handle error condition (also below)
78
79                 cpds = new ComboPooledDataSource();
80                 // load the jdbc driver
81                 try {
82                         cpds.setDriverClass("org.postgresql.Driver");
83                 } catch (PropertyVetoException e) {
84                         // TODO log error, fatal error can't continue, user can be nofified when db access doesn't work
85                         e.printStackTrace();
86                 }
87
88                 cpds.setJdbcUrl("jdbc:postgresql://" + document.get_connection_server() + "/"
89                                 + document.get_connection_database());
90                 // TODO figure out something for db user name and password
91                 cpds.setUser("ben");
92                 cpds.setPassword("ChangeMe"); // of course it's not the password I'm using on my server
93         }
94
95         /*
96          * This is called when the servlet is stopped or restarted.
97          * 
98          * @see javax.servlet.GenericServlet#destroy()
99          */
100         public void destroy() {
101                 Glom.libglom_deinit();
102                 try {
103                         DataSources.destroy(cpds);
104                 } catch (SQLException e) {
105                         // TODO log error, don't need to notify user because this is a clean up method
106                         e.printStackTrace();
107                 }
108         }
109
110         /*
111          * FIXME I think Swig is generating long on 64-bit machines and int on 32-bit machines - need to keep this constant
112          * http://stackoverflow.com/questions/1590831/safely-casting-long-to-int-in-java
113          */
114         public static int safeLongToInt(long l) {
115                 if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) {
116                         throw new IllegalArgumentException(l + " cannot be cast to int without changing its value.");
117                 }
118                 return (int) l;
119         }
120
121         public GlomDocument getGlomDocument() {
122                 GlomDocument glomDocument = new GlomDocument();
123
124                 // get arrays of table names and titles, and find the default table index
125                 StringVector tablesVec = document.get_table_names();
126
127                 int numTables = safeLongToInt(tablesVec.size());
128                 // we don't know how many tables will be hidden so we'll use half of the number of tables for the default size
129                 // of the ArrayList
130                 ArrayList<String> tableNames = new ArrayList<String>(numTables / 2);
131                 ArrayList<String> tableTitles = new ArrayList<String>(numTables / 2);
132                 boolean foundDefaultTable = false;
133                 for (int i = 0; i < numTables; i++) {
134                         String tableName = tablesVec.get(i);
135                         if (!document.get_table_is_hidden(tableName)) {
136                                 tableNames.add(tableName);
137                                 // JNI is "expensive", the comparison will only be called if we haven't already found the default table
138                                 if (!foundDefaultTable && tableName.equals(document.get_default_table())) {
139                                         glomDocument.setDefaultTableIndex(i);
140                                         foundDefaultTable = true;
141                                 }
142                                 tableTitles.add(document.get_table_title(tableName));
143                         }
144                 }
145
146                 // set everything we need
147                 glomDocument.setTableNames(tableNames);
148                 glomDocument.setTableTitles(tableTitles);
149                 glomDocument.setTitle(document.get_database_title());
150
151                 return glomDocument;
152         }
153
154         public LayoutListTable getLayoutListTable(String tableName) {
155                 LayoutListTable tableInfo = new LayoutListTable();
156
157                 // access the layout list
158                 LayoutGroupVector layoutListVec = document.get_data_layout_groups("list", tableName);
159                 LayoutItemVector layoutItemsVec = layoutListVec.get(0).get_items();
160
161                 // find the layout list fields
162                 int numItems = safeLongToInt(layoutItemsVec.size());
163                 String[] columnTitles = new String[numItems];
164                 LayoutFieldVector layoutFields = new LayoutFieldVector();
165                 for (int i = 0; i < numItems; i++) {
166                         LayoutItem item = layoutItemsVec.get(i);
167                         columnTitles[i] = item.get_title_or_name();
168                         LayoutItem_Field field = LayoutItem_Field.cast_dynamic(item);
169                         if (field != null) {
170                                 layoutFields.add(field);
171                         }
172                 }
173                 tableInfo.setColumnTitles(columnTitles);
174
175                 // get the size of the returned query for the pager
176                 // TODO since we're executing a query anyway, maybe we should return the rows that will be displayed on the
177                 // first page
178                 // TODO this code is really similar to code in getTableData, find a way to not duplicate the code
179                 Connection conn = null;
180                 Statement st = null;
181                 ResultSet rs = null;
182                 try {
183                         // setup and execute the query
184                         conn = cpds.getConnection();
185                         st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
186                         String query = Glom.build_sql_select_simple(tableName, layoutFields);
187                         rs = st.executeQuery(query);
188
189                         // get the number of rows in the query
190                         rs.setFetchDirection(ResultSet.FETCH_FORWARD);
191                         rs.last();
192                         tableInfo.setNumRows(rs.getRow());
193
194                 } catch (SQLException e) {
195                         // TODO log error
196                         // we don't know how many rows are in the query
197                         e.printStackTrace();
198                         tableInfo.setNumRows(0);
199                 } finally {
200                         // cleanup everything that has been used
201                         try {
202                                 rs.close();
203                                 st.close();
204                                 conn.close();
205                         } catch (Exception e) {
206                                 // TODO log error
207                                 e.printStackTrace();
208                         }
209                 }
210
211                 return tableInfo;
212         }
213
214         public ArrayList<GlomField[]> getTableData(String table, int start, int length) {
215                 return getTableData(table, start, length, false, 0, false);
216         }
217
218         public ArrayList<GlomField[]> getSortedTableData(String table, int start, int length, int sortColumnIndex,
219                         boolean isAscending) {
220                 return getTableData(table, start, length, true, sortColumnIndex, isAscending);
221         }
222
223         private ArrayList<GlomField[]> getTableData(String table, int start, int length, boolean useSortClause,
224                         int sortColumnIndex, boolean isAscending) {
225
226                 // access the layout list
227                 LayoutGroupVector layoutList = document.get_data_layout_groups("list", table);
228                 LayoutItemVector layoutItems = layoutList.get(0).get_items();
229
230                 LayoutFieldVector layoutFields = new LayoutFieldVector();
231                 SortClause sortClause = new SortClause();
232                 int numItems = safeLongToInt(layoutItems.size());
233                 for (int i = 0; i < numItems; i++) {
234                         LayoutItem item = layoutItems.get(i);
235                         LayoutItem_Field field = LayoutItem_Field.cast_dynamic(item);
236                         if (field != null) {
237                                 // use this field in the layout
238                                 layoutFields.add(field);
239
240                                 // create a sort clause if it's a primary key and we're not asked to sort a specific column
241                                 if (!useSortClause) {
242                                         Field details = field.get_full_field_details();
243                                         if (details != null && details.get_primary_key()) {
244                                                 sortClause.addLast(new SortFieldPair(field, true)); // ascending
245                                         }
246                                 }
247                         }
248                 }
249
250                 // create a sort clause for the column we've been asked to sort
251                 if (useSortClause) {
252                         LayoutItem item = layoutItems.get(sortColumnIndex);
253                         LayoutItem_Field field = LayoutItem_Field.cast_dynamic(item);
254                         if (field != null)
255                                 sortClause.addLast(new SortFieldPair(field, isAscending));
256                         // TODO: log error in the else condition
257                 }
258
259                 ArrayList<GlomField[]> rowsList = new ArrayList<GlomField[]>();
260                 Connection conn = null;
261                 Statement st = null;
262                 ResultSet rs = null;
263                 try {
264                         // setup and execute the query
265                         conn = cpds.getConnection();
266                         st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
267                         String query = Glom.build_sql_select_simple(table, layoutFields, sortClause);
268                         rs = st.executeQuery(query);
269
270                         // get data we're asked for
271                         // TODO need to setup the result set in cursor mode so that not all of the results are pulled into memory
272                         rs.setFetchDirection(ResultSet.FETCH_FORWARD);
273                         rs.absolute(start);
274                         int rowCount = 0;
275                         while (rs.next() && rowCount <= length) {
276                                 int layoutItemsSize = safeLongToInt(layoutItems.size());
277                                 GlomField[] rowArray = new GlomField[layoutItemsSize];
278                                 for (int i = 0; i < layoutItemsSize; i++) {
279                                         // make a new GlomField to set the text and colours
280                                         rowArray[i] = new GlomField();
281
282                                         // get foreground and background colours
283                                         LayoutItem_Field field = layoutFields.get(i);
284                                         FieldFormatting formatting = field.get_formatting_used();
285                                         String fgcolour = formatting.get_text_format_color_foreground();
286                                         if (!fgcolour.isEmpty())
287                                                 rowArray[i].setFGColour(convertGdkColorToHtmlColour(fgcolour));
288                                         String bgcolour = formatting.get_text_format_color_background();
289                                         if (!bgcolour.isEmpty())
290                                                 rowArray[i].setBGColour(convertGdkColorToHtmlColour(bgcolour));
291
292                                         // convert field values are to strings based on the glom type
293                                         Field.glom_field_type fieldType = field.get_glom_type();
294                                         switch (fieldType) {
295                                         case TYPE_TEXT:
296                                                 String text = rs.getString(i + 1);
297                                                 rowArray[i].setText(text != null ? text : "");
298                                                 break;
299                                         case TYPE_BOOLEAN:
300                                                 rowArray[i].setText(rs.getBoolean(i + 1) ? "TRUE" : "FALSE");
301                                                 break;
302                                         case TYPE_NUMERIC:
303                                                 // take care of the numeric formatting before converting the number to a string
304                                                 NumericFormat numFormatGlom = formatting.getM_numeric_format();
305                                                 // there's no isCurrency() method in the glom NumericFormat class so we're assuming that the
306                                                 // number should be formatted as a currency if the currency symbol is set
307                                                 String currencySymbol = numFormatGlom.getM_currency_symbol();
308                                                 NumberFormat numFormatJava;
309                                                 if (currencySymbol.length() == 3) {
310                                                         Currency currency = Currency.getInstance(currencySymbol);
311                                                         // we're not using the glom value for digits and grouping when it's a currency
312                                                         int digits = currency.getDefaultFractionDigits();
313                                                         numFormatJava = (DecimalFormat) NumberFormat.getCurrencyInstance(locale);
314                                                         numFormatJava.setCurrency(currency);
315                                                         numFormatJava.setMinimumFractionDigits(digits);
316                                                         numFormatJava.setMaximumFractionDigits(digits);
317                                                 } else {
318                                                         numFormatJava = NumberFormat.getInstance(locale);
319                                                         if (numFormatGlom.getM_decimal_places_restricted()) {
320                                                                 int digits = safeLongToInt(numFormatGlom.getM_decimal_places());
321                                                                 numFormatJava.setMinimumFractionDigits(digits);
322                                                                 numFormatJava.setMaximumFractionDigits(digits);
323                                                         }
324                                                         numFormatJava.setGroupingUsed(numFormatGlom.getM_use_thousands_separator());
325                                                 }
326
327                                                 // TODO: Do I need to do something with NumericFormat.get_default_precision() from libglom?
328
329                                                 double number = rs.getDouble(i + 1);
330                                                 if (number < 0) {
331                                                         if (formatting.getM_numeric_format().getM_alt_foreground_color_for_negatives())
332                                                                 // overrides the set foreground colour
333                                                                 rowArray[i].setFGColour(convertGdkColorToHtmlColour(NumericFormat
334                                                                                 .get_alternative_color_for_negatives()));
335                                                 }
336                                                 rowArray[i].setText(numFormatJava.format(number));
337                                                 break;
338                                         case TYPE_DATE:
339                                                 Date date = rs.getDate(i + 1);
340                                                 if (date != null) {
341                                                         DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
342                                                         rowArray[i].setText(dateFormat.format(rs.getDate(i + 1)));
343                                                 } else {
344                                                         rowArray[i].setText("");
345                                                 }
346                                                 break;
347                                         case TYPE_TIME:
348                                                 Time time = rs.getTime(i + 1);
349                                                 if (time != null) {
350                                                         DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
351                                                         rowArray[i].setText(timeFormat.format(time));
352                                                 } else {
353                                                         rowArray[i].setText("");
354                                                 }
355                                                 break;
356                                         case TYPE_IMAGE:
357                                                 // TODO log warning message
358                                                 break;
359                                         case TYPE_INVALID:
360                                         default:
361                                                 // TODO log warning message
362                                                 break;
363                                         }
364                                 }
365
366                                 // add the row of GlomFields to the ArrayList we're going to return and update the row count
367                                 rowsList.add(rowArray);
368                                 rowCount++;
369                         }
370                 } catch (SQLException e) {
371                         // TODO: log error, notify user of problem
372                         e.printStackTrace();
373                 } finally {
374                         // cleanup everything that has been used
375                         try {
376                                 rs.close();
377                                 st.close();
378                                 conn.close();
379                         } catch (Exception e) {
380                                 // TODO log error
381                                 e.printStackTrace();
382                         }
383                 }
384                 return rowsList;
385         }
386
387         /*
388          * Converts a Gdk::Color (16-bits per channel) to an HTML colour (8-bits per channel) by disgarding the least
389          * significant 8-bits in each channel.
390          */
391         private String convertGdkColorToHtmlColour(String gdkColor) {
392                 if (gdkColor.length() == 13)
393                         return gdkColor.substring(0, 2) + gdkColor.substring(5, 6) + gdkColor.substring(9, 10);
394                 else if (gdkColor.length() == 7)
395                         // TODO: log warning because we're expecting a 13 character string
396                         return gdkColor;
397                 else
398                         // TODO: log error
399                         return "";
400         }
401
402 }