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;
24 import java.io.IOException;
25 import java.sql.Connection;
27 import java.sql.ResultSet;
28 import java.sql.SQLException;
29 import java.sql.Statement;
31 import java.text.DateFormat;
32 import java.text.NumberFormat;
33 import java.util.ArrayList;
34 import java.util.Currency;
35 import java.util.Locale;
36 import java.util.Properties;
38 import org.glom.libglom.Document;
39 import org.glom.libglom.Field;
40 import org.glom.libglom.FieldFormatting;
41 import org.glom.libglom.FieldVector;
42 import org.glom.libglom.Glom;
43 import org.glom.libglom.LayoutFieldVector;
44 import org.glom.libglom.LayoutGroupVector;
45 import org.glom.libglom.LayoutItem;
46 import org.glom.libglom.LayoutItemVector;
47 import org.glom.libglom.LayoutItem_Field;
48 import org.glom.libglom.NumericFormat;
49 import org.glom.libglom.SortClause;
50 import org.glom.libglom.SortFieldPair;
51 import org.glom.libglom.StringVector;
52 import org.glom.web.client.OnlineGlomService;
53 import org.glom.web.shared.ColumnInfo;
54 import org.glom.web.shared.GlomDocument;
55 import org.glom.web.shared.GlomField;
56 import org.glom.web.shared.LayoutListTable;
58 import com.google.gwt.user.server.rpc.RemoteServiceServlet;
59 import com.mchange.v2.c3p0.ComboPooledDataSource;
60 import com.mchange.v2.c3p0.DataSources;
62 @SuppressWarnings("serial")
63 public class OnlineGlomServiceImpl extends RemoteServiceServlet implements OnlineGlomService {
64 private Document document = null;
65 private ComboPooledDataSource cpds = null;
66 // TODO implement locale
67 private final Locale locale = Locale.ROOT;
68 private boolean configured = false;
71 * This is called when the servlet is started or restarted.
73 public OnlineGlomServiceImpl() {
78 * The properties file can't be loaded in the constructor because the servlet is not yet initialised and
79 * getServletContext() will return null. The work-around for this problem is to initialise the database and glom
80 * document object when makes its first request.
82 private void configureServlet() {
83 document = new Document();
85 Properties props = new Properties();
86 String propFileName = "/WEB-INF/OnlineGlom.properties";
88 props.load(getServletContext().getResourceAsStream(propFileName));
89 } catch (IOException e) {
90 // TODO log fatal error, notify user of problem
94 File file = new File(props.getProperty("glomfile"));
95 document.set_file_uri("file://" + file.getAbsolutePath());
97 @SuppressWarnings("unused")
98 boolean retval = document.load(error);
99 // TODO handle error condition
101 // load the jdbc driver
102 cpds = new ComboPooledDataSource();
104 cpds.setDriverClass("org.postgresql.Driver");
105 } catch (PropertyVetoException e) {
106 // TODO log error, fatal error can't continue, user can be notified when db access doesn't work
110 cpds.setJdbcUrl("jdbc:postgresql://" + document.get_connection_server() + "/"
111 + document.get_connection_database());
112 cpds.setUser(props.getProperty("dbusername"));
113 cpds.setPassword(props.getProperty("dbpassword"));
118 * This is called when the servlet is stopped or restarted.
120 * @see javax.servlet.GenericServlet#destroy()
123 public void destroy() {
124 Glom.libglom_deinit();
127 DataSources.destroy(cpds);
128 } catch (SQLException e) {
129 // TODO log error, don't need to notify user because this is a clean up method
135 * FIXME I think Swig is generating long on 64-bit machines and int on 32-bit machines - need to keep this constant
136 * http://stackoverflow.com/questions/1590831/safely-casting-long-to-int-in-java
138 private static int safeLongToInt(long l) {
139 if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) {
140 throw new IllegalArgumentException(l + " cannot be cast to int without changing its value.");
145 public GlomDocument getGlomDocument() {
149 GlomDocument glomDocument = new GlomDocument();
151 // get arrays of table names and titles, and find the default table index
152 StringVector tablesVec = document.get_table_names();
154 int numTables = safeLongToInt(tablesVec.size());
155 // we don't know how many tables will be hidden so we'll use half of the number of tables for the default size
157 ArrayList<String> tableNames = new ArrayList<String>(numTables / 2);
158 ArrayList<String> tableTitles = new ArrayList<String>(numTables / 2);
159 boolean foundDefaultTable = false;
160 int visibleIndex = 0;
161 for (int i = 0; i < numTables; i++) {
162 String tableName = tablesVec.get(i);
163 if (!document.get_table_is_hidden(tableName)) {
164 tableNames.add(tableName);
165 // JNI is "expensive", the comparison will only be called if we haven't already found the default table
166 if (!foundDefaultTable && tableName.equals(document.get_default_table())) {
167 glomDocument.setDefaultTableIndex(visibleIndex);
168 foundDefaultTable = true;
170 tableTitles.add(document.get_table_title(tableName));
175 // set everything we need
176 glomDocument.setTableNames(tableNames);
177 glomDocument.setTableTitles(tableTitles);
178 glomDocument.setTitle(document.get_database_title());
183 public LayoutListTable getLayoutListTable(String tableName) {
187 LayoutListTable tableInfo = new LayoutListTable();
189 // access the layout list
190 LayoutGroupVector layoutListVec = document.get_data_layout_groups("list", tableName);
191 ColumnInfo[] columns = null;
192 LayoutFieldVector layoutFields = new LayoutFieldVector();
193 if (layoutListVec.size() > 0) {
194 // a layout list is defined, we can use it to for the LayoutListTable
195 // TODO log warning when the layoutListVec.size() > 1 but still use the first list
196 LayoutItemVector layoutItemsVec = layoutListVec.get(0).get_items();
198 // find the defined layout list fields
199 int numItems = safeLongToInt(layoutItemsVec.size());
200 columns = new ColumnInfo[numItems];
201 for (int i = 0; i < numItems; i++) {
202 // TODO add support for other LayoutItems (Text, Image, Button)
203 LayoutItem item = layoutItemsVec.get(i);
204 LayoutItem_Field layoutItemField = LayoutItem_Field.cast_dynamic(item);
205 if (layoutItemField != null) {
206 layoutFields.add(layoutItemField);
207 FieldFormatting.HorizontalAlignment alignment = layoutItemField
208 .get_formatting_used_horizontal_alignment();
209 columns[i] = new ColumnInfo(layoutItemField.get_title_or_name(),
210 getColumnInfoHorizontalAlignment(alignment));
214 // no layout list is defined, use the table fields as the layout list
215 FieldVector fieldsVec = document.get_table_fields(tableName);
217 // find the fields to display in the layout list
218 int numItems = safeLongToInt(fieldsVec.size());
219 columns = new ColumnInfo[numItems];
220 for (int i = 0; i < numItems; i++) {
221 Field field = fieldsVec.get(i);
222 LayoutItem_Field layoutItemField = new LayoutItem_Field();
223 layoutItemField.set_full_field_details(field);
224 layoutFields.add(layoutItemField);
225 FieldFormatting.HorizontalAlignment alignment = layoutItemField
226 .get_formatting_used_horizontal_alignment();
227 columns[i] = new ColumnInfo(layoutItemField.get_title_or_name(),
228 getColumnInfoHorizontalAlignment(alignment));
232 tableInfo.setColumns(columns);
234 // Get the number of rows a query with the table name and layout fields would return. This is needed for the
236 Connection conn = null;
240 // Setup and execute the count query. Special care needs to be take to ensure that the results will be based
241 // on a cursor so that large amounts of memory are not consumed when the query retrieve a large amount of
242 // data. Here's the relevant PostgreSQL documentation:
243 // http://jdbc.postgresql.org/documentation/83/query.html#query-with-cursor
244 conn = cpds.getConnection();
245 conn.setAutoCommit(false);
246 st = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
247 String query = Glom.build_sql_select_count_simple(tableName, layoutFields);
248 // TODO Test execution time of this query with when the number of rows in the table is large (say >
249 // 1,000,000). Test memory usage at the same time (see the todo item in getTableData()).
250 rs = st.executeQuery(query);
252 // get the number of rows in the query
254 tableInfo.setNumRows(rs.getInt(1));
256 } catch (SQLException e) {
258 // we don't know how many rows are in the query
260 tableInfo.setNumRows(0);
262 // cleanup everything that has been used
267 } catch (Exception e) {
276 public ArrayList<GlomField[]> getTableData(String table, int start, int length) {
277 return getTableData(table, start, length, false, 0, false);
280 public ArrayList<GlomField[]> getSortedTableData(String table, int start, int length, int sortColumnIndex,
281 boolean isAscending) {
282 return getTableData(table, start, length, true, sortColumnIndex, isAscending);
285 private ArrayList<GlomField[]> getTableData(String table, int start, int length, boolean useSortClause,
286 int sortColumnIndex, boolean isAscending) {
290 // access the layout list using the defined layout list or the table fields if there's no layout list
291 LayoutGroupVector layoutListVec = document.get_data_layout_groups("list", table);
292 LayoutFieldVector layoutFields = new LayoutFieldVector();
293 SortClause sortClause = new SortClause();
294 if (layoutListVec.size() > 0) {
295 // a layout list is defined, we can use it to for the LayoutListTable
296 // TODO log warning when the layoutListVec.size() > 1 but still use the first list
297 LayoutItemVector layoutItemsVec = layoutListVec.get(0).get_items();
299 // find the defined layout list fields
300 int numItems = safeLongToInt(layoutItemsVec.size());
301 for (int i = 0; i < numItems; i++) {
302 // TODO add support for other LayoutItems (Text, Image, Button)
303 LayoutItem item = layoutItemsVec.get(i);
304 LayoutItem_Field layoutItemfield = LayoutItem_Field.cast_dynamic(item);
305 if (layoutItemfield != null) {
306 // use this field in the layout
307 layoutFields.add(layoutItemfield);
309 // create a sort clause if it's a primary key and we're not asked to sort a specific column
310 if (!useSortClause) {
311 Field details = layoutItemfield.get_full_field_details();
312 if (details != null && details.get_primary_key()) {
313 sortClause.addLast(new SortFieldPair(layoutItemfield, true)); // ascending
319 // no layout list is defined, use the table fields as the layout list
320 FieldVector fieldsVec = document.get_table_fields(table);
322 // find the fields to display in the layout list
323 int numItems = safeLongToInt(fieldsVec.size());
324 for (int i = 0; i < numItems; i++) {
325 Field field = fieldsVec.get(i);
326 LayoutItem_Field layoutItemField = new LayoutItem_Field();
327 layoutItemField.set_full_field_details(field);
328 layoutFields.add(layoutItemField);
330 // create a sort clause if it's a primary key and we're not asked to sort a specific column
331 if (!useSortClause) {
332 if (field.get_primary_key()) {
333 sortClause.addLast(new SortFieldPair(layoutItemField, true)); // ascending
339 // create a sort clause for the column we've been asked to sort
341 LayoutItem item = layoutFields.get(sortColumnIndex);
342 LayoutItem_Field field = LayoutItem_Field.cast_dynamic(item);
344 sortClause.addLast(new SortFieldPair(field, isAscending));
345 // TODO: log error in the else condition
348 ArrayList<GlomField[]> rowsList = new ArrayList<GlomField[]>();
349 Connection conn = null;
353 // Setup and execute the query. Special care needs to be take to ensure that the results will be based on a
354 // cursor so that large amounts of memory are not consumed when the query retrieve a large amount of data.
355 // Here's the relevant PostgreSQL documentation:
356 // http://jdbc.postgresql.org/documentation/83/query.html#query-with-cursor
357 conn = cpds.getConnection();
358 conn.setAutoCommit(false);
359 st = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
360 st.setFetchSize(length);
361 String query = Glom.build_sql_select_simple(table, layoutFields, sortClause) + " OFFSET " + start;
362 // TODO Test memory usage before and after we execute the query that would result in a large ResultSet.
363 // We need to ensure that the JDBC driver is in fact returning a cursor based result set that has a low
364 // memory footprint. Check the difference between this value before and after the query:
365 // Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()
366 // Test the execution time at the same time (see the todo item in getLayoutListTable()).
367 rs = st.executeQuery(query);
369 // get the data we've been asked for
371 while (rs.next() && rowCount <= length) {
372 int layoutFieldsSize = safeLongToInt(layoutFields.size());
373 GlomField[] rowArray = new GlomField[layoutFieldsSize];
374 for (int i = 0; i < layoutFieldsSize; i++) {
375 // make a new GlomField to set the text and colours
376 rowArray[i] = new GlomField();
378 // get foreground and background colours
379 LayoutItem_Field field = layoutFields.get(i);
380 FieldFormatting formatting = field.get_formatting_used();
381 String fgcolour = formatting.get_text_format_color_foreground();
382 if (!fgcolour.isEmpty())
383 rowArray[i].setFGColour(convertGdkColorToHtmlColour(fgcolour));
384 String bgcolour = formatting.get_text_format_color_background();
385 if (!bgcolour.isEmpty())
386 rowArray[i].setBGColour(convertGdkColorToHtmlColour(bgcolour));
388 // convert field values are to strings based on the glom type
389 switch (field.get_glom_type()) {
391 String text = rs.getString(i + 1);
392 rowArray[i].setText(text != null ? text : "");
395 rowArray[i].setText(rs.getBoolean(i + 1) ? "TRUE" : "FALSE");
398 // Take care of the numeric formatting before converting the number to a string.
399 NumericFormat numFormatGlom = formatting.getM_numeric_format();
400 // There's no isCurrency() method in the glom NumericFormat class so we're assuming that the
401 // number should be formatted as a currency if the currency code string is not empty.
402 String currencyCode = numFormatGlom.getM_currency_symbol();
403 NumberFormat numFormatJava = null;
404 boolean useGlomCurrencyCode = false;
405 if (currencyCode.length() == 3) {
406 // Try to format the currency using the Java Locales system.
408 Currency currency = Currency.getInstance(currencyCode);
409 // Ignore the glom numeric formatting when a valid ISO 4217 currency code is being used.
410 int digits = currency.getDefaultFractionDigits();
411 numFormatJava = NumberFormat.getCurrencyInstance(locale);
412 numFormatJava.setCurrency(currency);
413 numFormatJava.setMinimumFractionDigits(digits);
414 numFormatJava.setMaximumFractionDigits(digits);
415 } catch (IllegalArgumentException e) {
417 // The currency code is not this is not an ISO 4217 currency code.
418 // We're going to manually set the currency code and use the glom numeric formatting.
419 useGlomCurrencyCode = true;
420 numFormatJava = getJavaNumberFormat(numFormatGlom);
422 } else if (currencyCode.length() > 0) {
423 // The length of the currency code is > 0 and != 3; this is not an ISO 4217 currency code.
424 // We're going to manually set the currency code and use the glom numeric formatting.
425 useGlomCurrencyCode = true;
426 numFormatJava = getJavaNumberFormat(numFormatGlom);
428 // The length of the currency code is 0; the number is not a currency.
429 numFormatJava = getJavaNumberFormat(numFormatGlom);
432 // TODO: Do I need to do something with NumericFormat.get_default_precision() from libglom?
434 double number = rs.getDouble(i + 1);
436 if (formatting.getM_numeric_format().getM_alt_foreground_color_for_negatives())
437 // overrides the set foreground colour
438 rowArray[i].setFGColour(convertGdkColorToHtmlColour(NumericFormat
439 .get_alternative_color_for_negatives()));
442 // Finally convert the number to text using the glom currency string if required.
443 if (useGlomCurrencyCode) {
444 rowArray[i].setText(currencyCode + " " + numFormatJava.format(number));
446 rowArray[i].setText(numFormatJava.format(number));
450 Date date = rs.getDate(i + 1);
452 DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
453 rowArray[i].setText(dateFormat.format(rs.getDate(i + 1)));
455 rowArray[i].setText("");
459 Time time = rs.getTime(i + 1);
461 DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
462 rowArray[i].setText(timeFormat.format(time));
464 rowArray[i].setText("");
468 byte[] image = rs.getBytes(i + 1);
470 // TODO implement field TYPE_IMAGE
471 rowArray[i].setText("Image (FIXME)");
473 rowArray[i].setText("");
478 // TODO log warning message
479 rowArray[i].setText("");
484 // add the row of GlomFields to the ArrayList we're going to return and update the row count
485 rowsList.add(rowArray);
488 } catch (SQLException e) {
489 // TODO: log error, notify user of problem
492 // cleanup everything that has been used
497 } catch (Exception e) {
505 private NumberFormat getJavaNumberFormat(NumericFormat numFormatGlom) {
506 NumberFormat numFormatJava = NumberFormat.getInstance(locale);
507 if (numFormatGlom.getM_decimal_places_restricted()) {
508 int digits = safeLongToInt(numFormatGlom.getM_decimal_places());
509 numFormatJava.setMinimumFractionDigits(digits);
510 numFormatJava.setMaximumFractionDigits(digits);
512 numFormatJava.setGroupingUsed(numFormatGlom.getM_use_thousands_separator());
513 return numFormatJava;
517 * Converts a Gdk::Color (16-bits per channel) to an HTML colour (8-bits per channel) by disgarding the least
518 * significant 8-bits in each channel.
520 private String convertGdkColorToHtmlColour(String gdkColor) {
521 if (gdkColor.length() == 13)
522 return gdkColor.substring(0, 2) + gdkColor.substring(5, 6) + gdkColor.substring(9, 10);
523 else if (gdkColor.length() == 7)
524 // TODO: log warning because we're expecting a 13 character string
532 * This method converts a FieldFormatting.HorizontalAlignment to the equivalent ColumnInfo.HorizontalAlignment. The
533 * need for this comes from the fact that the GWT HorizontalAlignment classes can't be used with RPC and there's no
534 * easy way to use the java-libglom FieldFormatting.HorizontalAlignment enum with RPC. An enum indentical to
535 * FieldFormatting.HorizontalAlignment is included in the ColumnInfo class.
537 private ColumnInfo.HorizontalAlignment getColumnInfoHorizontalAlignment(
538 FieldFormatting.HorizontalAlignment alignment) {
539 int value = alignment.swigValue();
540 ColumnInfo.HorizontalAlignment[] columnInfoValues = ColumnInfo.HorizontalAlignment.class.getEnumConstants();
541 if (value < columnInfoValues.length && value >= 0)
542 return columnInfoValues[value];
543 // TODO: log error: value out of range, returning HORIZONTAL_ALIGNMENT_RIGHT
544 return columnInfoValues[FieldFormatting.HorizontalAlignment.HORIZONTAL_ALIGNMENT_RIGHT.swigValue()];