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