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.FileInputStream;
25 import java.io.IOException;
26 import java.sql.Connection;
28 import java.sql.ResultSet;
29 import java.sql.SQLException;
30 import java.sql.Statement;
32 import java.text.DateFormat;
33 import java.text.NumberFormat;
34 import java.util.ArrayList;
35 import java.util.Currency;
36 import java.util.Locale;
37 import java.util.Properties;
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.google.gwt.user.server.rpc.RemoteServiceServlet;
60 import com.mchange.v2.c3p0.ComboPooledDataSource;
61 import com.mchange.v2.c3p0.DataSources;
63 @SuppressWarnings("serial")
64 public class OnlineGlomServiceImpl extends RemoteServiceServlet implements OnlineGlomService {
65 private final Document document;
66 private final ComboPooledDataSource cpds;
67 // TODO implement locale
68 private final Locale locale = Locale.ROOT;
71 * This is called when the servlet is started or restarted.
73 public OnlineGlomServiceImpl() {
75 document = new Document();
77 Properties dbconfig = new Properties();
79 dbconfig.load(new FileInputStream("OnlineGlom.properties"));
80 } catch (IOException e1) {
81 // TODO log fatal error
85 File file = new File(dbconfig.getProperty("glomfile"));
86 document.set_file_uri("file://" + file.getAbsolutePath());
88 @SuppressWarnings("unused")
89 boolean retval = document.load(error);
90 // TODO handle error condition
92 // load the jdbc driver
93 cpds = new ComboPooledDataSource();
95 cpds.setDriverClass("org.postgresql.Driver");
96 } catch (PropertyVetoException e) {
97 // TODO log error, fatal error can't continue, user can be notified when db access doesn't work
101 cpds.setJdbcUrl("jdbc:postgresql://" + document.get_connection_server() + "/"
102 + document.get_connection_database());
103 cpds.setUser(dbconfig.getProperty("dbusername"));
104 cpds.setPassword(dbconfig.getProperty("dbpassword"));
108 * This is called when the servlet is stopped or restarted.
110 * @see javax.servlet.GenericServlet#destroy()
113 public void destroy() {
114 Glom.libglom_deinit();
116 DataSources.destroy(cpds);
117 } catch (SQLException e) {
118 // TODO log error, don't need to notify user because this is a clean up method
124 * FIXME I think Swig is generating long on 64-bit machines and int on 32-bit machines - need to keep this constant
125 * http://stackoverflow.com/questions/1590831/safely-casting-long-to-int-in-java
127 public static int safeLongToInt(long l) {
128 if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) {
129 throw new IllegalArgumentException(l + " cannot be cast to int without changing its value.");
134 public GlomDocument getGlomDocument() {
135 GlomDocument glomDocument = new GlomDocument();
137 // get arrays of table names and titles, and find the default table index
138 StringVector tablesVec = document.get_table_names();
140 int numTables = safeLongToInt(tablesVec.size());
141 // we don't know how many tables will be hidden so we'll use half of the number of tables for the default size
143 ArrayList<String> tableNames = new ArrayList<String>(numTables / 2);
144 ArrayList<String> tableTitles = new ArrayList<String>(numTables / 2);
145 boolean foundDefaultTable = false;
146 int visibleIndex = 0;
147 for (int i = 0; i < numTables; i++) {
148 String tableName = tablesVec.get(i);
149 if (!document.get_table_is_hidden(tableName)) {
150 tableNames.add(tableName);
151 // JNI is "expensive", the comparison will only be called if we haven't already found the default table
152 if (!foundDefaultTable && tableName.equals(document.get_default_table())) {
153 glomDocument.setDefaultTableIndex(visibleIndex);
154 foundDefaultTable = true;
156 tableTitles.add(document.get_table_title(tableName));
161 // set everything we need
162 glomDocument.setTableNames(tableNames);
163 glomDocument.setTableTitles(tableTitles);
164 glomDocument.setTitle(document.get_database_title());
169 public LayoutListTable getLayoutListTable(String tableName) {
170 LayoutListTable tableInfo = new LayoutListTable();
172 // access the layout list
173 LayoutGroupVector layoutListVec = document.get_data_layout_groups("list", tableName);
174 ColumnInfo[] columns = null;
175 LayoutFieldVector layoutFields = new LayoutFieldVector();
176 if (layoutListVec.size() > 0) {
177 // a layout list is defined, we can use it to for the LayoutListTable
178 // TODO log warning when the layoutListVec.size() > 1 but still use the first list
179 LayoutItemVector layoutItemsVec = layoutListVec.get(0).get_items();
181 // find the defined layout list fields
182 int numItems = safeLongToInt(layoutItemsVec.size());
183 columns = new ColumnInfo[numItems];
184 for (int i = 0; i < numItems; i++) {
185 // TODO add support for other LayoutItems (Text, Image, Button)
186 LayoutItem item = layoutItemsVec.get(i);
187 LayoutItem_Field layoutItemField = LayoutItem_Field.cast_dynamic(item);
188 if (layoutItemField != null) {
189 layoutFields.add(layoutItemField);
190 FieldFormatting.HorizontalAlignment alignment = layoutItemField
191 .get_formatting_used_horizontal_alignment();
192 columns[i] = new ColumnInfo(layoutItemField.get_title_or_name(),
193 getColumnInfoHorizontalAlignment(alignment));
197 // no layout list is defined, use the table fields as the layout list
198 FieldVector fieldsVec = document.get_table_fields(tableName);
200 // find the fields to display in the layout list
201 int numItems = safeLongToInt(fieldsVec.size());
202 columns = new ColumnInfo[numItems];
203 for (int i = 0; i < numItems; i++) {
204 Field field = fieldsVec.get(i);
205 LayoutItem_Field layoutItemField = new LayoutItem_Field();
206 layoutItemField.set_full_field_details(field);
207 layoutFields.add(layoutItemField);
208 FieldFormatting.HorizontalAlignment alignment = layoutItemField
209 .get_formatting_used_horizontal_alignment();
210 columns[i] = new ColumnInfo(layoutItemField.get_title_or_name(),
211 getColumnInfoHorizontalAlignment(alignment));
215 tableInfo.setColumns(columns);
217 // get the size of the returned query for the pager
218 // TODO since we're executing a query anyway, maybe we should return the rows that will be displayed on the
220 // TODO this code is really similar to code in getTableData, find a way to not duplicate the code
221 Connection conn = null;
225 // setup and execute the query
226 conn = cpds.getConnection();
227 st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
228 String query = Glom.build_sql_select_simple(tableName, layoutFields);
229 rs = st.executeQuery(query);
231 // get the number of rows in the query
232 rs.setFetchDirection(ResultSet.FETCH_FORWARD);
234 tableInfo.setNumRows(rs.getRow());
236 } catch (SQLException e) {
238 // we don't know how many rows are in the query
240 tableInfo.setNumRows(0);
242 // cleanup everything that has been used
247 } catch (Exception e) {
256 public ArrayList<GlomField[]> getTableData(String table, int start, int length) {
257 return getTableData(table, start, length, false, 0, false);
260 public ArrayList<GlomField[]> getSortedTableData(String table, int start, int length, int sortColumnIndex,
261 boolean isAscending) {
262 return getTableData(table, start, length, true, sortColumnIndex, isAscending);
265 private ArrayList<GlomField[]> getTableData(String table, int start, int length, boolean useSortClause,
266 int sortColumnIndex, boolean isAscending) {
268 // access the layout list using the defined layout list or the table fields if there's no layout list
269 LayoutGroupVector layoutListVec = document.get_data_layout_groups("list", table);
270 LayoutFieldVector layoutFields = new LayoutFieldVector();
271 SortClause sortClause = new SortClause();
272 if (layoutListVec.size() > 0) {
273 // a layout list is defined, we can use it to for the LayoutListTable
274 // TODO log warning when the layoutListVec.size() > 1 but still use the first list
275 LayoutItemVector layoutItemsVec = layoutListVec.get(0).get_items();
277 // find the defined layout list fields
278 int numItems = safeLongToInt(layoutItemsVec.size());
279 for (int i = 0; i < numItems; i++) {
280 // TODO add support for other LayoutItems (Text, Image, Button)
281 LayoutItem item = layoutItemsVec.get(i);
282 LayoutItem_Field layoutItemfield = LayoutItem_Field.cast_dynamic(item);
283 if (layoutItemfield != null) {
284 // use this field in the layout
285 layoutFields.add(layoutItemfield);
287 // create a sort clause if it's a primary key and we're not asked to sort a specific column
288 if (!useSortClause) {
289 Field details = layoutItemfield.get_full_field_details();
290 if (details != null && details.get_primary_key()) {
291 sortClause.addLast(new SortFieldPair(layoutItemfield, true)); // ascending
297 // no layout list is defined, use the table fields as the layout list
298 FieldVector fieldsVec = document.get_table_fields(table);
300 // find the fields to display in the layout list
301 int numItems = safeLongToInt(fieldsVec.size());
302 for (int i = 0; i < numItems; i++) {
303 Field field = fieldsVec.get(i);
304 LayoutItem_Field layoutItemField = new LayoutItem_Field();
305 layoutItemField.set_full_field_details(field);
306 layoutFields.add(layoutItemField);
308 // create a sort clause if it's a primary key and we're not asked to sort a specific column
309 if (!useSortClause) {
310 if (field.get_primary_key()) {
311 sortClause.addLast(new SortFieldPair(layoutItemField, true)); // ascending
317 // create a sort clause for the column we've been asked to sort
319 LayoutItem item = layoutFields.get(sortColumnIndex);
320 LayoutItem_Field field = LayoutItem_Field.cast_dynamic(item);
322 sortClause.addLast(new SortFieldPair(field, isAscending));
323 // TODO: log error in the else condition
326 ArrayList<GlomField[]> rowsList = new ArrayList<GlomField[]>();
327 Connection conn = null;
331 // setup and execute the query
332 conn = cpds.getConnection();
333 st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
334 String query = Glom.build_sql_select_simple(table, layoutFields, sortClause);
335 rs = st.executeQuery(query);
337 // get data we're asked for
338 // TODO need to setup the result set in cursor mode so that not all of the results are pulled into memory
339 rs.setFetchDirection(ResultSet.FETCH_FORWARD);
342 while (rs.next() && rowCount <= length) {
343 int layoutFieldsSize = safeLongToInt(layoutFields.size());
344 GlomField[] rowArray = new GlomField[layoutFieldsSize];
345 for (int i = 0; i < layoutFieldsSize; i++) {
346 // make a new GlomField to set the text and colours
347 rowArray[i] = new GlomField();
349 // get foreground and background colours
350 LayoutItem_Field field = layoutFields.get(i);
351 FieldFormatting formatting = field.get_formatting_used();
352 String fgcolour = formatting.get_text_format_color_foreground();
353 if (!fgcolour.isEmpty())
354 rowArray[i].setFGColour(convertGdkColorToHtmlColour(fgcolour));
355 String bgcolour = formatting.get_text_format_color_background();
356 if (!bgcolour.isEmpty())
357 rowArray[i].setBGColour(convertGdkColorToHtmlColour(bgcolour));
359 // convert field values are to strings based on the glom type
360 switch (field.get_glom_type()) {
362 String text = rs.getString(i + 1);
363 rowArray[i].setText(text != null ? text : "");
366 rowArray[i].setText(rs.getBoolean(i + 1) ? "TRUE" : "FALSE");
369 // Take care of the numeric formatting before converting the number to a string.
370 NumericFormat numFormatGlom = formatting.getM_numeric_format();
371 // There's no isCurrency() method in the glom NumericFormat class so we're assuming that the
372 // number should be formatted as a currency if the currency code string is not empty.
373 String currencyCode = numFormatGlom.getM_currency_symbol();
374 NumberFormat numFormatJava = null;
375 boolean useGlomCurrencyCode = false;
376 if (currencyCode.length() == 3) {
377 // Try to format the currency using the Java Locales system.
379 Currency currency = Currency.getInstance(currencyCode);
380 // Ignore the glom numeric formatting when a valid ISO 4217 currency code is being used.
381 int digits = currency.getDefaultFractionDigits();
382 numFormatJava = NumberFormat.getCurrencyInstance(locale);
383 numFormatJava.setCurrency(currency);
384 numFormatJava.setMinimumFractionDigits(digits);
385 numFormatJava.setMaximumFractionDigits(digits);
386 } catch (IllegalArgumentException e) {
388 // The currency code is not this is not an ISO 4217 currency code.
389 // We're going to manually set the currency code and use the glom numeric formatting.
390 useGlomCurrencyCode = true;
391 numFormatJava = getJavaNumberFormat(numFormatGlom);
393 } else if (currencyCode.length() > 0) {
394 // The length of the currency code is > 0 and != 3; this is not an ISO 4217 currency code.
395 // We're going to manually set the currency code and use the glom numeric formatting.
396 useGlomCurrencyCode = true;
397 numFormatJava = getJavaNumberFormat(numFormatGlom);
399 // The length of the currency code is 0; the number is not a currency.
400 numFormatJava = getJavaNumberFormat(numFormatGlom);
403 // TODO: Do I need to do something with NumericFormat.get_default_precision() from libglom?
405 double number = rs.getDouble(i + 1);
407 if (formatting.getM_numeric_format().getM_alt_foreground_color_for_negatives())
408 // overrides the set foreground colour
409 rowArray[i].setFGColour(convertGdkColorToHtmlColour(NumericFormat
410 .get_alternative_color_for_negatives()));
413 // Finally convert the number to text using the glom currency string if required.
414 if (useGlomCurrencyCode) {
415 rowArray[i].setText(currencyCode + " " + numFormatJava.format(number));
417 rowArray[i].setText(numFormatJava.format(number));
421 Date date = rs.getDate(i + 1);
423 DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
424 rowArray[i].setText(dateFormat.format(rs.getDate(i + 1)));
426 rowArray[i].setText("");
430 Time time = rs.getTime(i + 1);
432 DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
433 rowArray[i].setText(timeFormat.format(time));
435 rowArray[i].setText("");
439 byte[] image = rs.getBytes(i + 1);
441 // TODO implement field TYPE_IMAGE
442 rowArray[i].setText("Image (FIXME)");
444 rowArray[i].setText("");
449 // TODO log warning message
450 rowArray[i].setText("");
455 // add the row of GlomFields to the ArrayList we're going to return and update the row count
456 rowsList.add(rowArray);
459 } catch (SQLException e) {
460 // TODO: log error, notify user of problem
463 // cleanup everything that has been used
468 } catch (Exception e) {
476 private NumberFormat getJavaNumberFormat(NumericFormat numFormatGlom) {
477 NumberFormat numFormatJava = NumberFormat.getInstance(locale);
478 if (numFormatGlom.getM_decimal_places_restricted()) {
479 int digits = safeLongToInt(numFormatGlom.getM_decimal_places());
480 numFormatJava.setMinimumFractionDigits(digits);
481 numFormatJava.setMaximumFractionDigits(digits);
483 numFormatJava.setGroupingUsed(numFormatGlom.getM_use_thousands_separator());
484 return numFormatJava;
488 * Converts a Gdk::Color (16-bits per channel) to an HTML colour (8-bits per channel) by disgarding the least
489 * significant 8-bits in each channel.
491 private String convertGdkColorToHtmlColour(String gdkColor) {
492 if (gdkColor.length() == 13)
493 return gdkColor.substring(0, 2) + gdkColor.substring(5, 6) + gdkColor.substring(9, 10);
494 else if (gdkColor.length() == 7)
495 // TODO: log warning because we're expecting a 13 character string
503 * This method converts a FieldFormatting.HorizontalAlignment to the equivalent ColumnInfo.HorizontalAlignment. The
504 * need for this comes from the fact that the GWT HorizontalAlignment classes can't be used with RPC and there's no
505 * easy way to use the java-libglom FieldFormatting.HorizontalAlignment enum with RPC. An enum indentical to
506 * FieldFormatting.HorizontalAlignment is included in the ColumnInfo class.
508 private ColumnInfo.HorizontalAlignment getColumnInfoHorizontalAlignment(
509 FieldFormatting.HorizontalAlignment alignment) {
510 int value = alignment.swigValue();
511 ColumnInfo.HorizontalAlignment[] columnInfoValues = ColumnInfo.HorizontalAlignment.class.getEnumConstants();
512 if (value < columnInfoValues.length && value >= 0)
513 return columnInfoValues[value];
514 // TODO: log error: value out of range, returning HORIZONTAL_ALIGNMENT_RIGHT
515 return columnInfoValues[FieldFormatting.HorizontalAlignment.HORIZONTAL_ALIGNMENT_RIGHT.swigValue()];