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.BakeryDocument.LoadFailureCodes;
39 import org.glom.libglom.Document;
40 import org.glom.libglom.Field;
41 import org.glom.libglom.FieldFormatting;
42 import org.glom.libglom.FieldVector;
43 import org.glom.libglom.Glom;
44 import org.glom.libglom.LayoutFieldVector;
45 import org.glom.libglom.LayoutGroupVector;
46 import org.glom.libglom.LayoutItem;
47 import org.glom.libglom.LayoutItemVector;
48 import org.glom.libglom.LayoutItem_Field;
49 import org.glom.libglom.NumericFormat;
50 import org.glom.libglom.SortClause;
51 import org.glom.libglom.SortFieldPair;
52 import org.glom.libglom.StringVector;
53 import org.glom.web.client.OnlineGlomService;
54 import org.glom.web.shared.ColumnInfo;
55 import org.glom.web.shared.GlomDocument;
56 import org.glom.web.shared.GlomField;
57 import org.glom.web.shared.LayoutListTable;
59 import com.allen_sauer.gwt.log.client.Log;
60 import com.google.gwt.user.server.rpc.RemoteServiceServlet;
61 import com.mchange.v2.c3p0.ComboPooledDataSource;
62 import com.mchange.v2.c3p0.DataSources;
64 @SuppressWarnings("serial")
65 public class OnlineGlomServiceImpl extends RemoteServiceServlet implements OnlineGlomService {
66 private Document document = null;
67 private ComboPooledDataSource cpds = null;
68 // TODO implement locale
69 private final Locale locale = Locale.ROOT;
70 private boolean configured = false;
73 * This is called when the servlet is started or restarted.
75 public OnlineGlomServiceImpl() {
80 * The properties file can't be loaded in the constructor because the servlet is not yet initialised and
81 * getServletContext() will return null. The work-around for this problem is to initialise the database and glom
82 * document object when makes its first request.
84 private void configureServlet() {
85 document = new Document();
87 Properties props = new Properties();
88 String propFileName = "/WEB-INF/OnlineGlom.properties";
90 props.load(getServletContext().getResourceAsStream(propFileName));
91 } catch (IOException e) {
92 Log.fatal("Error loading " + propFileName, e);
93 // TODO can't continue, notify user of problem
96 File file = new File(props.getProperty("glomfile"));
97 document.set_file_uri("file://" + file.getAbsolutePath());
99 boolean retval = document.load(error);
100 if (retval == false) {
102 if (LoadFailureCodes.LOAD_FAILURE_CODE_NOT_FOUND == LoadFailureCodes.swigToEnum(error)) {
103 message = "Could not find " + file.getAbsolutePath();
105 message = "An unknown error occurred when trying to load " + file.getAbsolutePath();
108 // TODO can't continue, notify user of problem
111 // load the jdbc driver
112 cpds = new ComboPooledDataSource();
114 cpds.setDriverClass("org.postgresql.Driver");
115 } catch (PropertyVetoException e) {
116 Log.fatal("Error loading the PostgreSQL JDBC driver. Is the PostgreSQL JDBC jar available to the servlet?",
118 // TODO can't continue, notify user of problem
121 cpds.setJdbcUrl("jdbc:postgresql://" + document.get_connection_server() + "/"
122 + document.get_connection_database());
123 cpds.setUser(props.getProperty("dbusername"));
124 cpds.setPassword(props.getProperty("dbpassword"));
125 // TODO notify user if dbusername or dbpassword are wrong
130 * This is called when the servlet is stopped or restarted.
132 * @see javax.servlet.GenericServlet#destroy()
135 public void destroy() {
136 Glom.libglom_deinit();
139 DataSources.destroy(cpds);
140 } catch (SQLException e) {
141 Log.error("Error cleaning up the ComboPooledDataSource", e);
146 * FIXME I think Swig is generating long on 64-bit machines and int on 32-bit machines - need to keep this constant
147 * http://stackoverflow.com/questions/1590831/safely-casting-long-to-int-in-java
149 private static int safeLongToInt(long l) {
150 if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) {
151 throw new IllegalArgumentException(l + " cannot be cast to int without changing its value.");
156 public GlomDocument getGlomDocument() {
160 GlomDocument glomDocument = new GlomDocument();
162 // get arrays of table names and titles, and find the default table index
163 StringVector tablesVec = document.get_table_names();
165 int numTables = safeLongToInt(tablesVec.size());
166 // we don't know how many tables will be hidden so we'll use half of the number of tables for the default size
168 ArrayList<String> tableNames = new ArrayList<String>(numTables / 2);
169 ArrayList<String> tableTitles = new ArrayList<String>(numTables / 2);
170 boolean foundDefaultTable = false;
171 int visibleIndex = 0;
172 for (int i = 0; i < numTables; i++) {
173 String tableName = tablesVec.get(i);
174 if (!document.get_table_is_hidden(tableName)) {
175 tableNames.add(tableName);
176 // JNI is "expensive", the comparison will only be called if we haven't already found the default table
177 if (!foundDefaultTable && tableName.equals(document.get_default_table())) {
178 glomDocument.setDefaultTableIndex(visibleIndex);
179 foundDefaultTable = true;
181 tableTitles.add(document.get_table_title(tableName));
186 // set everything we need
187 glomDocument.setTableNames(tableNames);
188 glomDocument.setTableTitles(tableTitles);
189 glomDocument.setTitle(document.get_database_title());
194 public LayoutListTable getLayoutListTable(String table) {
198 LayoutListTable tableInfo = new LayoutListTable();
200 // access the layout list
201 LayoutGroupVector layoutListVec = document.get_data_layout_groups("list", table);
202 ColumnInfo[] columns = null;
203 LayoutFieldVector layoutFields = new LayoutFieldVector();
204 int listViewLayoutGroupSize = safeLongToInt(layoutListVec.size());
205 if (listViewLayoutGroupSize > 0) {
206 // a layout list is defined, we can use it to for the LayoutListTable
207 if (listViewLayoutGroupSize > 1)
208 Log.warn("The size of the list view layout group for table " + table
209 + " is greater than 1. Attempting to use the first item for the layout list view.");
210 LayoutItemVector layoutItemsVec = layoutListVec.get(0).get_items();
212 // find the defined layout list fields
213 int numItems = safeLongToInt(layoutItemsVec.size());
214 columns = new ColumnInfo[numItems];
215 for (int i = 0; i < numItems; i++) {
216 // TODO add support for other LayoutItems (Text, Image, Button)
217 LayoutItem item = layoutItemsVec.get(i);
218 LayoutItem_Field layoutItemField = LayoutItem_Field.cast_dynamic(item);
219 if (layoutItemField != null) {
220 layoutFields.add(layoutItemField);
221 columns[i] = new ColumnInfo(
222 layoutItemField.get_title_or_name(),
223 getColumnInfoHorizontalAlignment(layoutItemField.get_formatting_used_horizontal_alignment()),
224 getColumnInfoGlomFieldType(layoutItemField.get_glom_type()));
228 // no layout list is defined, use the table fields as the layout list
229 FieldVector fieldsVec = document.get_table_fields(table);
231 // find the fields to display in the layout list
232 int numItems = safeLongToInt(fieldsVec.size());
233 columns = new ColumnInfo[numItems];
234 for (int i = 0; i < numItems; i++) {
235 Field field = fieldsVec.get(i);
236 LayoutItem_Field layoutItemField = new LayoutItem_Field();
237 layoutItemField.set_full_field_details(field);
238 layoutFields.add(layoutItemField);
239 columns[i] = new ColumnInfo(layoutItemField.get_title_or_name(),
240 getColumnInfoHorizontalAlignment(layoutItemField.get_formatting_used_horizontal_alignment()),
241 getColumnInfoGlomFieldType(layoutItemField.get_glom_type()));
245 tableInfo.setColumns(columns);
247 // Get the number of rows a query with the table name and layout fields would return. This is needed for the
249 Connection conn = null;
253 // Setup and execute the count query. Special care needs to be take to ensure that the results will be based
254 // on a cursor so that large amounts of memory are not consumed when the query retrieve a large amount of
255 // data. Here's the relevant PostgreSQL documentation:
256 // http://jdbc.postgresql.org/documentation/83/query.html#query-with-cursor
257 conn = cpds.getConnection();
258 conn.setAutoCommit(false);
259 st = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
260 String query = Glom.build_sql_select_count_simple(table, layoutFields);
261 // TODO Test execution time of this query with when the number of rows in the table is large (say >
262 // 1,000,000). Test memory usage at the same time (see the todo item in getTableData()).
263 rs = st.executeQuery(query);
265 // get the number of rows in the query
267 tableInfo.setNumRows(rs.getInt(1));
269 } catch (SQLException e) {
270 Log.error("Error calculating number of rows in the query. Setting number of rows to 0.", e);
271 tableInfo.setNumRows(0);
273 // cleanup everything that has been used
278 } catch (Exception e) {
279 Log.error("Error closing database resources. Subsequent database queries may not work.", e);
286 public ArrayList<GlomField[]> getTableData(String table, int start, int length) {
287 return getTableData(table, start, length, false, 0, false);
290 public ArrayList<GlomField[]> getSortedTableData(String table, int start, int length, int sortColumnIndex,
291 boolean isAscending) {
292 return getTableData(table, start, length, true, sortColumnIndex, isAscending);
295 private ArrayList<GlomField[]> getTableData(String table, int start, int length, boolean useSortClause,
296 int sortColumnIndex, boolean isAscending) {
300 // access the layout list using the defined layout list or the table fields if there's no layout list
301 LayoutGroupVector layoutListVec = document.get_data_layout_groups("list", table);
302 LayoutFieldVector layoutFields = new LayoutFieldVector();
303 SortClause sortClause = new SortClause();
304 int listViewLayoutGroupSize = safeLongToInt(layoutListVec.size());
305 if (layoutListVec.size() > 0) {
306 // a layout list is defined, we can use it to for the LayoutListTable
307 if (listViewLayoutGroupSize > 1)
308 Log.warn("The size of the list view layout group for table " + table
309 + " is greater than 1. Attempting to use the first item for the layout list view.");
310 LayoutItemVector layoutItemsVec = layoutListVec.get(0).get_items();
312 // find the defined layout list fields
313 int numItems = safeLongToInt(layoutItemsVec.size());
314 for (int i = 0; i < numItems; i++) {
315 // TODO add support for other LayoutItems (Text, Image, Button)
316 LayoutItem item = layoutItemsVec.get(i);
317 LayoutItem_Field layoutItemfield = LayoutItem_Field.cast_dynamic(item);
318 if (layoutItemfield != null) {
319 // use this field in the layout
320 layoutFields.add(layoutItemfield);
322 // create a sort clause if it's a primary key and we're not asked to sort a specific column
323 if (!useSortClause) {
324 Field details = layoutItemfield.get_full_field_details();
325 if (details != null && details.get_primary_key()) {
326 sortClause.addLast(new SortFieldPair(layoutItemfield, true)); // ascending
332 // no layout list is defined, use the table fields as the layout list
333 FieldVector fieldsVec = document.get_table_fields(table);
335 // find the fields to display in the layout list
336 int numItems = safeLongToInt(fieldsVec.size());
337 for (int i = 0; i < numItems; i++) {
338 Field field = fieldsVec.get(i);
339 LayoutItem_Field layoutItemField = new LayoutItem_Field();
340 layoutItemField.set_full_field_details(field);
341 layoutFields.add(layoutItemField);
343 // create a sort clause if it's a primary key and we're not asked to sort a specific column
344 if (!useSortClause) {
345 if (field.get_primary_key()) {
346 sortClause.addLast(new SortFieldPair(layoutItemField, true)); // ascending
352 // create a sort clause for the column we've been asked to sort
354 LayoutItem item = layoutFields.get(sortColumnIndex);
355 LayoutItem_Field field = LayoutItem_Field.cast_dynamic(item);
357 sortClause.addLast(new SortFieldPair(field, isAscending));
359 Log.error("Error getting LayoutItem_Field for column index " + sortColumnIndex
360 + ". Cannot create a sort clause for this column.");
365 ArrayList<GlomField[]> rowsList = new ArrayList<GlomField[]>();
366 Connection conn = null;
370 // Setup and execute the query. Special care needs to be take to ensure that the results will be based on a
371 // cursor so that large amounts of memory are not consumed when the query retrieve a large amount of data.
372 // Here's the relevant PostgreSQL documentation:
373 // http://jdbc.postgresql.org/documentation/83/query.html#query-with-cursor
374 conn = cpds.getConnection();
375 conn.setAutoCommit(false);
376 st = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
377 st.setFetchSize(length);
378 String query = Glom.build_sql_select_simple(table, layoutFields, sortClause) + " OFFSET " + start;
379 // TODO Test memory usage before and after we execute the query that would result in a large ResultSet.
380 // We need to ensure that the JDBC driver is in fact returning a cursor based result set that has a low
381 // memory footprint. Check the difference between this value before and after the query:
382 // Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()
383 // Test the execution time at the same time (see the todo item in getLayoutListTable()).
384 rs = st.executeQuery(query);
386 // get the data we've been asked for
388 while (rs.next() && rowCount <= length) {
389 int layoutFieldsSize = safeLongToInt(layoutFields.size());
390 GlomField[] rowArray = new GlomField[layoutFieldsSize];
391 for (int i = 0; i < layoutFieldsSize; i++) {
392 // make a new GlomField to set the text and colours
393 rowArray[i] = new GlomField();
395 // get foreground and background colours
396 LayoutItem_Field field = layoutFields.get(i);
397 FieldFormatting formatting = field.get_formatting_used();
398 String fgcolour = formatting.get_text_format_color_foreground();
399 if (!fgcolour.isEmpty())
400 rowArray[i].setFGColour(convertGdkColorToHtmlColour(fgcolour));
401 String bgcolour = formatting.get_text_format_color_background();
402 if (!bgcolour.isEmpty())
403 rowArray[i].setBGColour(convertGdkColorToHtmlColour(bgcolour));
405 // Convert the field value to a string based on the glom type. We're doing the formatting on the
406 // server side for now but it might be useful to move this to the client side.
407 switch (field.get_glom_type()) {
409 String text = rs.getString(i + 1);
410 rowArray[i].setText(text != null ? text : "");
413 rowArray[i].setBoolean(rs.getBoolean(i + 1));
416 // Take care of the numeric formatting before converting the number to a string.
417 NumericFormat numFormatGlom = formatting.getM_numeric_format();
418 // There's no isCurrency() method in the glom NumericFormat class so we're assuming that the
419 // number should be formatted as a currency if the currency code string is not empty.
420 String currencyCode = numFormatGlom.getM_currency_symbol();
421 NumberFormat numFormatJava = null;
422 boolean useGlomCurrencyCode = false;
423 if (currencyCode.length() == 3) {
424 // Try to format the currency using the Java Locales system.
426 Currency currency = Currency.getInstance(currencyCode);
427 Log.info("A valid ISO 4217 currency code is being used. Overriding the numeric formatting with information from the locale.");
428 int digits = currency.getDefaultFractionDigits();
429 numFormatJava = NumberFormat.getCurrencyInstance(locale);
430 numFormatJava.setCurrency(currency);
431 numFormatJava.setMinimumFractionDigits(digits);
432 numFormatJava.setMaximumFractionDigits(digits);
433 } catch (IllegalArgumentException e) {
434 Log.warn(currencyCode
435 + " is not a valid ISO 4217 code. Manually setting currency code with this value.");
436 // The currency code is not this is not an ISO 4217 currency code.
437 // We're going to manually set the currency code and use the glom numeric formatting.
438 useGlomCurrencyCode = true;
439 numFormatJava = getJavaNumberFormat(numFormatGlom);
441 } else if (currencyCode.length() > 0) {
442 Log.warn(currencyCode
443 + " is not a valid ISO 4217 code. Manually setting currency code with this value.");
444 // The length of the currency code is > 0 and != 3; this is not an ISO 4217 currency code.
445 // We're going to manually set the currency code and use the glom numeric formatting.
446 useGlomCurrencyCode = true;
447 numFormatJava = getJavaNumberFormat(numFormatGlom);
449 // The length of the currency code is 0; the number is not a currency.
450 numFormatJava = getJavaNumberFormat(numFormatGlom);
453 // TODO: Do I need to do something with NumericFormat.get_default_precision() from libglom?
455 double number = rs.getDouble(i + 1);
457 if (formatting.getM_numeric_format().getM_alt_foreground_color_for_negatives())
458 // overrides the set foreground colour
459 rowArray[i].setFGColour(convertGdkColorToHtmlColour(NumericFormat
460 .get_alternative_color_for_negatives()));
463 // Finally convert the number to text using the glom currency string if required.
464 if (useGlomCurrencyCode) {
465 rowArray[i].setText(currencyCode + " " + numFormatJava.format(number));
467 rowArray[i].setText(numFormatJava.format(number));
471 Date date = rs.getDate(i + 1);
473 DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
474 rowArray[i].setText(dateFormat.format(date));
476 rowArray[i].setText("");
480 Time time = rs.getTime(i + 1);
482 DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
483 rowArray[i].setText(timeFormat.format(time));
485 rowArray[i].setText("");
489 byte[] image = rs.getBytes(i + 1);
491 // TODO implement field TYPE_IMAGE
492 rowArray[i].setText("Image (FIXME)");
494 rowArray[i].setText("");
499 Log.warn("Invalid LayoutItem Field type. Using empty string for value.");
500 rowArray[i].setText("");
505 // add the row of GlomFields to the ArrayList we're going to return and update the row count
506 rowsList.add(rowArray);
509 } catch (SQLException e) {
510 Log.error("Error executing database query.", e);
511 // TODO: somehow notify user of problem
513 // cleanup everything that has been used
518 } catch (Exception e) {
519 Log.error("Error closing database resources. Subsequent database queries may not work.", e);
525 private NumberFormat getJavaNumberFormat(NumericFormat numFormatGlom) {
526 NumberFormat numFormatJava = NumberFormat.getInstance(locale);
527 if (numFormatGlom.getM_decimal_places_restricted()) {
528 int digits = safeLongToInt(numFormatGlom.getM_decimal_places());
529 numFormatJava.setMinimumFractionDigits(digits);
530 numFormatJava.setMaximumFractionDigits(digits);
532 numFormatJava.setGroupingUsed(numFormatGlom.getM_use_thousands_separator());
533 return numFormatJava;
537 * Converts a Gdk::Color (16-bits per channel) to an HTML colour (8-bits per channel) by discarding the least
538 * significant 8-bits in each channel.
540 private String convertGdkColorToHtmlColour(String gdkColor) {
541 if (gdkColor.length() == 13)
542 return gdkColor.substring(0, 2) + gdkColor.substring(5, 6) + gdkColor.substring(9, 10);
543 else if (gdkColor.length() == 7) {
544 // FIXME will this happen in on 32-bit?
545 Log.warn("convertGdkColorToHtmlColour(): Expected a 13 character string but received a 7 character string. Returning received string.");
548 Log.error("convertGdkColorToHtmlColour(): Did not receive a 13 or 7 character string. Returning black HTML colour code.");
554 * This method converts a FieldFormatting.HorizontalAlignment to the equivalent ColumnInfo.HorizontalAlignment. The
555 * need for this comes from the fact that the GWT HorizontalAlignment classes can't be used with RPC and there's no
556 * easy way to use the java-libglom FieldFormatting.HorizontalAlignment enum with RPC. An enum identical to
557 * FieldFormatting.HorizontalAlignment is included in the ColumnInfo class.
559 private ColumnInfo.HorizontalAlignment getColumnInfoHorizontalAlignment(
560 FieldFormatting.HorizontalAlignment alignment) {
561 int value = alignment.swigValue();
562 ColumnInfo.HorizontalAlignment[] columnInfoValues = ColumnInfo.HorizontalAlignment.class.getEnumConstants();
563 if (value < columnInfoValues.length && value >= 0)
564 return columnInfoValues[value];
565 Log.error("getColumnInfoHorizontalAlignment(): Mismatch between "
566 + FieldFormatting.HorizontalAlignment.class.getName() + " and "
567 + ColumnInfo.HorizontalAlignment.class.getName() + ". Returning HORIZONTAL_ALIGNMENT_RIGHT.");
568 return columnInfoValues[FieldFormatting.HorizontalAlignment.HORIZONTAL_ALIGNMENT_RIGHT.swigValue()];
573 * This method converts a Field.glom_field_type to the equivalent ColumnInfo.FieldType. The need for this comes from
574 * the fact that the GWT FieldType classes can't be used with RPC and there's no easy way to use the java-libglom
575 * Field.glom_field_type enum with RPC. An enum identical to FieldFormatting.glom_field_type is included in the
578 private ColumnInfo.GlomFieldType getColumnInfoGlomFieldType(Field.glom_field_type type) {
581 return ColumnInfo.GlomFieldType.TYPE_BOOLEAN;
583 return ColumnInfo.GlomFieldType.TYPE_DATE;
585 return ColumnInfo.GlomFieldType.TYPE_IMAGE;
587 return ColumnInfo.GlomFieldType.TYPE_NUMERIC;
589 return ColumnInfo.GlomFieldType.TYPE_TEXT;
591 return ColumnInfo.GlomFieldType.TYPE_TIME;
593 Log.info("getColumnInfoGlomFieldType(): Returning TYPE_INVALID.");
594 return ColumnInfo.GlomFieldType.TYPE_INVALID;
596 Log.error("getColumnInfoGlomFieldType(): Recieved a type that I don't know about: "
597 + Field.glom_field_type.class.getName() + "." + type.toString() + ". Returning "
598 + ColumnInfo.GlomFieldType.TYPE_INVALID.toString() + ".");
599 return ColumnInfo.GlomFieldType.TYPE_INVALID;