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