Add support for horizontal alignment in the LayoutList columns.
[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.ENGLISH;
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 hardcoded 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 nofified 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 symbol is set
310                                                 String currencySymbol = numFormatGlom.getM_currency_symbol();
311                                                 NumberFormat numFormatJava;
312                                                 if (currencySymbol.length() == 3) {
313                                                         Currency currency = Currency.getInstance(currencySymbol);
314                                                         // we're not using the glom value for digits and grouping when it's a currency
315                                                         int digits = currency.getDefaultFractionDigits();
316                                                         numFormatJava = (DecimalFormat) NumberFormat.getCurrencyInstance(locale);
317                                                         numFormatJava.setCurrency(currency);
318                                                         numFormatJava.setMinimumFractionDigits(digits);
319                                                         numFormatJava.setMaximumFractionDigits(digits);
320                                                 } else {
321                                                         numFormatJava = NumberFormat.getInstance(locale);
322                                                         if (numFormatGlom.getM_decimal_places_restricted()) {
323                                                                 int digits = safeLongToInt(numFormatGlom.getM_decimal_places());
324                                                                 numFormatJava.setMinimumFractionDigits(digits);
325                                                                 numFormatJava.setMaximumFractionDigits(digits);
326                                                         }
327                                                         numFormatJava.setGroupingUsed(numFormatGlom.getM_use_thousands_separator());
328                                                 }
329
330                                                 // TODO: Do I need to do something with NumericFormat.get_default_precision() from libglom?
331
332                                                 double number = rs.getDouble(i + 1);
333                                                 if (number < 0) {
334                                                         if (formatting.getM_numeric_format().getM_alt_foreground_color_for_negatives())
335                                                                 // overrides the set foreground colour
336                                                                 rowArray[i].setFGColour(convertGdkColorToHtmlColour(NumericFormat
337                                                                                 .get_alternative_color_for_negatives()));
338                                                 }
339                                                 rowArray[i].setText(numFormatJava.format(number));
340                                                 break;
341                                         case TYPE_DATE:
342                                                 Date date = rs.getDate(i + 1);
343                                                 if (date != null) {
344                                                         DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
345                                                         rowArray[i].setText(dateFormat.format(rs.getDate(i + 1)));
346                                                 } else {
347                                                         rowArray[i].setText("");
348                                                 }
349                                                 break;
350                                         case TYPE_TIME:
351                                                 Time time = rs.getTime(i + 1);
352                                                 if (time != null) {
353                                                         DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
354                                                         rowArray[i].setText(timeFormat.format(time));
355                                                 } else {
356                                                         rowArray[i].setText("");
357                                                 }
358                                                 break;
359                                         case TYPE_IMAGE:
360                                                 // TODO log warning message
361                                                 break;
362                                         case TYPE_INVALID:
363                                         default:
364                                                 // TODO log warning message
365                                                 break;
366                                         }
367                                 }
368
369                                 // add the row of GlomFields to the ArrayList we're going to return and update the row count
370                                 rowsList.add(rowArray);
371                                 rowCount++;
372                         }
373                 } catch (SQLException e) {
374                         // TODO: log error, notify user of problem
375                         e.printStackTrace();
376                 } finally {
377                         // cleanup everything that has been used
378                         try {
379                                 rs.close();
380                                 st.close();
381                                 conn.close();
382                         } catch (Exception e) {
383                                 // TODO log error
384                                 e.printStackTrace();
385                         }
386                 }
387                 return rowsList;
388         }
389
390         /*
391          * Converts a Gdk::Color (16-bits per channel) to an HTML colour (8-bits per channel) by disgarding the least
392          * significant 8-bits in each channel.
393          */
394         private String convertGdkColorToHtmlColour(String gdkColor) {
395                 if (gdkColor.length() == 13)
396                         return gdkColor.substring(0, 2) + gdkColor.substring(5, 6) + gdkColor.substring(9, 10);
397                 else if (gdkColor.length() == 7)
398                         // TODO: log warning because we're expecting a 13 character string
399                         return gdkColor;
400                 else
401                         // TODO: log error
402                         return "";
403         }
404
405         /*
406          * This method converts a FieldFormatting.HorizontalAlignment to the equivalent ColumnInfo.HorizontalAlignment. The
407          * need for this comes from the fact that the GWT HorizontalAlignment classes can't be used with RPC and there's no
408          * easy way to use the java-libglom FieldFormatting.HorizontalAlignment enum with RPC. An enum indentical to
409          * FieldFormatting.HorizontalAlignment is included in the ColumnInfo class.
410          */
411         private ColumnInfo.HorizontalAlignment getColumnInfoHorizontalAlignment(
412                         FieldFormatting.HorizontalAlignment alignment) {
413                 int value = alignment.swigValue();
414                 ColumnInfo.HorizontalAlignment[] columnInfoValues = ColumnInfo.HorizontalAlignment.class.getEnumConstants();
415                 if (value < columnInfoValues.length && value >= 0)
416                         return columnInfoValues[value];
417                 // TODO: log error: value out of range, returning HORIZONTAL_ALIGNMENT_RIGHT
418                 return columnInfoValues[FieldFormatting.HorizontalAlignment.HORIZONTAL_ALIGNMENT_RIGHT.swigValue()];
419         }
420
421 }