2 * Copyright (C) 2010, 2011 Openismus GmbH
4 * This file is part of GWT-Glom.
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.
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
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/>.
20 package org.glom.web.server;
22 import java.beans.PropertyVetoException;
23 import java.sql.Connection;
25 import java.sql.ResultSet;
26 import java.sql.SQLException;
27 import java.sql.Statement;
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;
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;
54 import com.google.gwt.user.server.rpc.RemoteServiceServlet;
55 import com.mchange.v2.c3p0.ComboPooledDataSource;
56 import com.mchange.v2.c3p0.DataSources;
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;
66 * This is called when the servlet is started or restarted.
68 public OnlineGlomServiceImpl() {
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");
75 @SuppressWarnings("unused")
76 boolean retval = document.load(error);
77 // TODO handle error condition (also below)
79 cpds = new ComboPooledDataSource();
80 // load the jdbc driver
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
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
92 cpds.setPassword("ChangeMe"); // of course it's not the password I'm using on my server
96 * This is called when the servlet is stopped or restarted.
98 * @see javax.servlet.GenericServlet#destroy()
100 public void destroy() {
101 Glom.libglom_deinit();
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
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
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.");
121 public GlomDocument getGlomDocument() {
122 GlomDocument glomDocument = new GlomDocument();
124 // get arrays of table names and titles, and find the default table index
125 StringVector tablesVec = document.get_table_names();
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
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;
142 tableTitles.add(document.get_table_title(tableName));
146 // set everything we need
147 glomDocument.setTableNames(tableNames);
148 glomDocument.setTableTitles(tableTitles);
149 glomDocument.setTitle(document.get_database_title());
154 public LayoutListTable getLayoutListTable(String tableName) {
155 LayoutListTable tableInfo = new LayoutListTable();
157 // access the layout list
158 LayoutGroupVector layoutListVec = document.get_data_layout_groups("list", tableName);
159 LayoutItemVector layoutItemsVec = layoutListVec.get(0).get_items();
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);
170 layoutFields.add(field);
173 tableInfo.setColumnTitles(columnTitles);
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
178 // TODO this code is really similar to code in getTableData, find a way to not duplicate the code
179 Connection conn = null;
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);
189 // get the number of rows in the query
190 rs.setFetchDirection(ResultSet.FETCH_FORWARD);
192 tableInfo.setNumRows(rs.getRow());
194 } catch (SQLException e) {
196 // we don't know how many rows are in the query
198 tableInfo.setNumRows(0);
200 // cleanup everything that has been used
205 } catch (Exception e) {
214 public ArrayList<GlomField[]> getTableData(String table, int start, int length) {
215 return getTableData(table, start, length, false, 0, false);
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);
223 private ArrayList<GlomField[]> getTableData(String table, int start, int length, boolean useSortClause,
224 int sortColumnIndex, boolean isAscending) {
226 // access the layout list
227 LayoutGroupVector layoutList = document.get_data_layout_groups("list", table);
228 LayoutItemVector layoutItems = layoutList.get(0).get_items();
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);
237 // use this field in the layout
238 layoutFields.add(field);
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
250 // create a sort clause for the column we've been asked to sort
252 LayoutItem item = layoutItems.get(sortColumnIndex);
253 LayoutItem_Field field = LayoutItem_Field.cast_dynamic(item);
255 sortClause.addLast(new SortFieldPair(field, isAscending));
256 // TODO: log error in the else condition
259 ArrayList<GlomField[]> rowsList = new ArrayList<GlomField[]>();
260 Connection conn = null;
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);
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);
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();
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));
292 // convert field values are to strings based on the glom type
293 Field.glom_field_type fieldType = field.get_glom_type();
296 String text = rs.getString(i + 1);
297 rowArray[i].setText(text != null ? text : "");
300 rowArray[i].setText(rs.getBoolean(i + 1) ? "TRUE" : "FALSE");
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);
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);
324 numFormatJava.setGroupingUsed(numFormatGlom.getM_use_thousands_separator());
327 // TODO: Do I need to do something with NumericFormat.get_default_precision() from libglom?
329 double number = rs.getDouble(i + 1);
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()));
336 rowArray[i].setText(numFormatJava.format(number));
339 Date date = rs.getDate(i + 1);
341 DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
342 rowArray[i].setText(dateFormat.format(rs.getDate(i + 1)));
344 rowArray[i].setText("");
348 Time time = rs.getTime(i + 1);
350 DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
351 rowArray[i].setText(timeFormat.format(time));
353 rowArray[i].setText("");
357 // TODO log warning message
361 // TODO log warning message
366 // add the row of GlomFields to the ArrayList we're going to return and update the row count
367 rowsList.add(rowArray);
370 } catch (SQLException e) {
371 // TODO: log error, notify user of problem
374 // cleanup everything that has been used
379 } catch (Exception e) {
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.
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