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.NumberFormat;
31 import java.util.ArrayList;
32 import java.util.Currency;
33 import java.util.Locale;
35 import org.glom.libglom.Document;
36 import org.glom.libglom.Field;
37 import org.glom.libglom.FieldFormatting;
38 import org.glom.libglom.FieldVector;
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.ColumnInfo;
51 import org.glom.web.shared.GlomDocument;
52 import org.glom.web.shared.GlomField;
53 import org.glom.web.shared.LayoutListTable;
55 import com.google.gwt.user.server.rpc.RemoteServiceServlet;
56 import com.mchange.v2.c3p0.ComboPooledDataSource;
57 import com.mchange.v2.c3p0.DataSources;
59 @SuppressWarnings("serial")
60 public class OnlineGlomServiceImpl extends RemoteServiceServlet implements OnlineGlomService {
61 private final Document document;
62 private final ComboPooledDataSource cpds;
63 // TODO implement locale
64 private final Locale locale = Locale.ROOT;
67 * This is called when the servlet is started or restarted.
69 public OnlineGlomServiceImpl() {
71 document = new Document();
72 // TODO hard-coded for now, need to figure out something for this
73 // document.set_file_uri("file:///home/ben/small-business-example.glom");
74 // document.set_file_uri("file:///home/ben/music-collection.glom");
75 // document.set_file_uri("file:///home/ben/project-manager-example.glom");
76 // document.set_file_uri("file:///home/ben/openismus-film-manager.glom");
77 document.set_file_uri("file:///home/ben/lesson-planner.glom");
79 @SuppressWarnings("unused")
80 boolean retval = document.load(error);
81 // TODO handle error condition (also below)
83 cpds = new ComboPooledDataSource();
84 // load the jdbc driver
86 cpds.setDriverClass("org.postgresql.Driver");
87 } catch (PropertyVetoException e) {
88 // TODO log error, fatal error can't continue, user can be notified when db access doesn't work
92 cpds.setJdbcUrl("jdbc:postgresql://" + document.get_connection_server() + "/"
93 + document.get_connection_database());
94 // TODO figure out something for db user name and password
96 cpds.setPassword("ChangeMe"); // of course it's not the password I'm using on my server
100 * This is called when the servlet is stopped or restarted.
102 * @see javax.servlet.GenericServlet#destroy()
105 public void destroy() {
106 Glom.libglom_deinit();
108 DataSources.destroy(cpds);
109 } catch (SQLException e) {
110 // TODO log error, don't need to notify user because this is a clean up method
116 * FIXME I think Swig is generating long on 64-bit machines and int on 32-bit machines - need to keep this constant
117 * http://stackoverflow.com/questions/1590831/safely-casting-long-to-int-in-java
119 public static int safeLongToInt(long l) {
120 if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) {
121 throw new IllegalArgumentException(l + " cannot be cast to int without changing its value.");
126 public GlomDocument getGlomDocument() {
127 GlomDocument glomDocument = new GlomDocument();
129 // get arrays of table names and titles, and find the default table index
130 StringVector tablesVec = document.get_table_names();
132 int numTables = safeLongToInt(tablesVec.size());
133 // we don't know how many tables will be hidden so we'll use half of the number of tables for the default size
135 ArrayList<String> tableNames = new ArrayList<String>(numTables / 2);
136 ArrayList<String> tableTitles = new ArrayList<String>(numTables / 2);
137 boolean foundDefaultTable = false;
138 int visibleIndex = 0;
139 for (int i = 0; i < numTables; i++) {
140 String tableName = tablesVec.get(i);
141 if (!document.get_table_is_hidden(tableName)) {
142 tableNames.add(tableName);
143 // JNI is "expensive", the comparison will only be called if we haven't already found the default table
144 if (!foundDefaultTable && tableName.equals(document.get_default_table())) {
145 glomDocument.setDefaultTableIndex(visibleIndex);
146 foundDefaultTable = true;
148 tableTitles.add(document.get_table_title(tableName));
153 // set everything we need
154 glomDocument.setTableNames(tableNames);
155 glomDocument.setTableTitles(tableTitles);
156 glomDocument.setTitle(document.get_database_title());
161 public LayoutListTable getLayoutListTable(String tableName) {
162 LayoutListTable tableInfo = new LayoutListTable();
164 // access the layout list
165 LayoutGroupVector layoutListVec = document.get_data_layout_groups("list", tableName);
166 ColumnInfo[] columns = null;
167 LayoutFieldVector layoutFields = new LayoutFieldVector();
168 if (layoutListVec.size() > 0) {
169 // a layout list is defined, we can use it to for the LayoutListTable
170 // TODO log warning when the layoutListVec.size() > 1 but still use the first list
171 LayoutItemVector layoutItemsVec = layoutListVec.get(0).get_items();
173 // find the defined layout list fields
174 int numItems = safeLongToInt(layoutItemsVec.size());
175 columns = new ColumnInfo[numItems];
176 for (int i = 0; i < numItems; i++) {
177 // TODO add support for other LayoutItems (Text, Image, Button)
178 LayoutItem item = layoutItemsVec.get(i);
179 LayoutItem_Field layoutItemField = LayoutItem_Field.cast_dynamic(item);
180 if (layoutItemField != null) {
181 layoutFields.add(layoutItemField);
182 FieldFormatting.HorizontalAlignment alignment = layoutItemField
183 .get_formatting_used_horizontal_alignment();
184 columns[i] = new ColumnInfo(layoutItemField.get_title_or_name(),
185 getColumnInfoHorizontalAlignment(alignment));
189 // no layout list is defined, use the table fields as the layout list
190 FieldVector fieldsVec = document.get_table_fields(tableName);
192 // find the fields to display in the layout list
193 int numItems = safeLongToInt(fieldsVec.size());
194 columns = new ColumnInfo[numItems];
195 for (int i = 0; i < numItems; i++) {
196 Field field = fieldsVec.get(i);
197 LayoutItem_Field layoutItemField = new LayoutItem_Field();
198 layoutItemField.set_full_field_details(field);
199 layoutFields.add(layoutItemField);
200 FieldFormatting.HorizontalAlignment alignment = layoutItemField
201 .get_formatting_used_horizontal_alignment();
202 columns[i] = new ColumnInfo(layoutItemField.get_title_or_name(),
203 getColumnInfoHorizontalAlignment(alignment));
207 tableInfo.setColumns(columns);
209 // get the size of the returned query for the pager
210 // TODO since we're executing a query anyway, maybe we should return the rows that will be displayed on the
212 // TODO this code is really similar to code in getTableData, find a way to not duplicate the code
213 Connection conn = null;
217 // setup and execute the query
218 conn = cpds.getConnection();
219 st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
220 String query = Glom.build_sql_select_simple(tableName, layoutFields);
221 rs = st.executeQuery(query);
223 // get the number of rows in the query
224 rs.setFetchDirection(ResultSet.FETCH_FORWARD);
226 tableInfo.setNumRows(rs.getRow());
228 } catch (SQLException e) {
230 // we don't know how many rows are in the query
232 tableInfo.setNumRows(0);
234 // cleanup everything that has been used
239 } catch (Exception e) {
248 public ArrayList<GlomField[]> getTableData(String table, int start, int length) {
249 return getTableData(table, start, length, false, 0, false);
252 public ArrayList<GlomField[]> getSortedTableData(String table, int start, int length, int sortColumnIndex,
253 boolean isAscending) {
254 return getTableData(table, start, length, true, sortColumnIndex, isAscending);
257 private ArrayList<GlomField[]> getTableData(String table, int start, int length, boolean useSortClause,
258 int sortColumnIndex, boolean isAscending) {
260 // access the layout list using the defined layout list or the table fields if there's no layout list
261 LayoutGroupVector layoutListVec = document.get_data_layout_groups("list", table);
262 LayoutFieldVector layoutFields = new LayoutFieldVector();
263 SortClause sortClause = new SortClause();
264 if (layoutListVec.size() > 0) {
265 // a layout list is defined, we can use it to for the LayoutListTable
266 // TODO log warning when the layoutListVec.size() > 1 but still use the first list
267 LayoutItemVector layoutItemsVec = layoutListVec.get(0).get_items();
269 // find the defined layout list fields
270 int numItems = safeLongToInt(layoutItemsVec.size());
271 for (int i = 0; i < numItems; i++) {
272 // TODO add support for other LayoutItems (Text, Image, Button)
273 LayoutItem item = layoutItemsVec.get(i);
274 LayoutItem_Field layoutItemfield = LayoutItem_Field.cast_dynamic(item);
275 if (layoutItemfield != null) {
276 // use this field in the layout
277 layoutFields.add(layoutItemfield);
279 // create a sort clause if it's a primary key and we're not asked to sort a specific column
280 if (!useSortClause) {
281 Field details = layoutItemfield.get_full_field_details();
282 if (details != null && details.get_primary_key()) {
283 sortClause.addLast(new SortFieldPair(layoutItemfield, true)); // ascending
289 // no layout list is defined, use the table fields as the layout list
290 FieldVector fieldsVec = document.get_table_fields(table);
292 // find the fields to display in the layout list
293 int numItems = safeLongToInt(fieldsVec.size());
294 for (int i = 0; i < numItems; i++) {
295 Field field = fieldsVec.get(i);
296 LayoutItem_Field layoutItemField = new LayoutItem_Field();
297 layoutItemField.set_full_field_details(field);
298 layoutFields.add(layoutItemField);
300 // create a sort clause if it's a primary key and we're not asked to sort a specific column
301 if (!useSortClause) {
302 if (field.get_primary_key()) {
303 sortClause.addLast(new SortFieldPair(layoutItemField, true)); // ascending
309 // create a sort clause for the column we've been asked to sort
311 LayoutItem item = layoutFields.get(sortColumnIndex);
312 LayoutItem_Field field = LayoutItem_Field.cast_dynamic(item);
314 sortClause.addLast(new SortFieldPair(field, isAscending));
315 // TODO: log error in the else condition
318 ArrayList<GlomField[]> rowsList = new ArrayList<GlomField[]>();
319 Connection conn = null;
323 // setup and execute the query
324 conn = cpds.getConnection();
325 st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
326 String query = Glom.build_sql_select_simple(table, layoutFields, sortClause);
327 rs = st.executeQuery(query);
329 // get data we're asked for
330 // TODO need to setup the result set in cursor mode so that not all of the results are pulled into memory
331 rs.setFetchDirection(ResultSet.FETCH_FORWARD);
334 while (rs.next() && rowCount <= length) {
335 int layoutFieldsSize = safeLongToInt(layoutFields.size());
336 GlomField[] rowArray = new GlomField[layoutFieldsSize];
337 for (int i = 0; i < layoutFieldsSize; i++) {
338 // make a new GlomField to set the text and colours
339 rowArray[i] = new GlomField();
341 // get foreground and background colours
342 LayoutItem_Field field = layoutFields.get(i);
343 FieldFormatting formatting = field.get_formatting_used();
344 String fgcolour = formatting.get_text_format_color_foreground();
345 if (!fgcolour.isEmpty())
346 rowArray[i].setFGColour(convertGdkColorToHtmlColour(fgcolour));
347 String bgcolour = formatting.get_text_format_color_background();
348 if (!bgcolour.isEmpty())
349 rowArray[i].setBGColour(convertGdkColorToHtmlColour(bgcolour));
351 // convert field values are to strings based on the glom type
352 switch (field.get_glom_type()) {
354 String text = rs.getString(i + 1);
355 rowArray[i].setText(text != null ? text : "");
358 rowArray[i].setText(rs.getBoolean(i + 1) ? "TRUE" : "FALSE");
361 // Take care of the numeric formatting before converting the number to a string.
362 NumericFormat numFormatGlom = formatting.getM_numeric_format();
363 // There's no isCurrency() method in the glom NumericFormat class so we're assuming that the
364 // number should be formatted as a currency if the currency code string is not empty.
365 String currencyCode = numFormatGlom.getM_currency_symbol();
366 NumberFormat numFormatJava = null;
367 boolean useGlomCurrencyCode = false;
368 if (currencyCode.length() == 3) {
369 // Try to format the currency using the Java Locales system.
371 Currency currency = Currency.getInstance(currencyCode);
372 // Ignore the glom numeric formatting when a valid ISO 4217 currency code is being used.
373 int digits = currency.getDefaultFractionDigits();
374 numFormatJava = NumberFormat.getCurrencyInstance(locale);
375 numFormatJava.setCurrency(currency);
376 numFormatJava.setMinimumFractionDigits(digits);
377 numFormatJava.setMaximumFractionDigits(digits);
378 } catch (IllegalArgumentException e) {
380 // The currency code is not this is not an ISO 4217 currency code.
381 // We're going to manually set the currency code and use the glom numeric formatting.
382 useGlomCurrencyCode = true;
383 numFormatJava = getJavaNumberFormat(numFormatGlom);
385 } else if (currencyCode.length() > 0) {
386 // The length of the currency code is > 0 and != 3; this is not an ISO 4217 currency code.
387 // We're going to manually set the currency code and use the glom numeric formatting.
388 useGlomCurrencyCode = true;
389 numFormatJava = getJavaNumberFormat(numFormatGlom);
391 // The length of the currency code is 0; the number is not a currency.
392 numFormatJava = getJavaNumberFormat(numFormatGlom);
395 // TODO: Do I need to do something with NumericFormat.get_default_precision() from libglom?
397 double number = rs.getDouble(i + 1);
399 if (formatting.getM_numeric_format().getM_alt_foreground_color_for_negatives())
400 // overrides the set foreground colour
401 rowArray[i].setFGColour(convertGdkColorToHtmlColour(NumericFormat
402 .get_alternative_color_for_negatives()));
405 // Finally convert the number to text using the glom currency string if required.
406 if (useGlomCurrencyCode) {
407 rowArray[i].setText(currencyCode + " " + numFormatJava.format(number));
409 rowArray[i].setText(numFormatJava.format(number));
413 Date date = rs.getDate(i + 1);
415 DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
416 rowArray[i].setText(dateFormat.format(rs.getDate(i + 1)));
418 rowArray[i].setText("");
422 Time time = rs.getTime(i + 1);
424 DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
425 rowArray[i].setText(timeFormat.format(time));
427 rowArray[i].setText("");
431 byte[] image = rs.getBytes(i + 1);
433 // TODO implement field TYPE_IMAGE
434 rowArray[i].setText("Image (FIXME)");
436 rowArray[i].setText("");
441 // TODO log warning message
442 rowArray[i].setText("");
447 // add the row of GlomFields to the ArrayList we're going to return and update the row count
448 rowsList.add(rowArray);
451 } catch (SQLException e) {
452 // TODO: log error, notify user of problem
455 // cleanup everything that has been used
460 } catch (Exception e) {
468 private NumberFormat getJavaNumberFormat(NumericFormat numFormatGlom) {
469 NumberFormat numFormatJava = NumberFormat.getInstance(locale);
470 if (numFormatGlom.getM_decimal_places_restricted()) {
471 int digits = safeLongToInt(numFormatGlom.getM_decimal_places());
472 numFormatJava.setMinimumFractionDigits(digits);
473 numFormatJava.setMaximumFractionDigits(digits);
475 numFormatJava.setGroupingUsed(numFormatGlom.getM_use_thousands_separator());
476 return numFormatJava;
480 * Converts a Gdk::Color (16-bits per channel) to an HTML colour (8-bits per channel) by disgarding the least
481 * significant 8-bits in each channel.
483 private String convertGdkColorToHtmlColour(String gdkColor) {
484 if (gdkColor.length() == 13)
485 return gdkColor.substring(0, 2) + gdkColor.substring(5, 6) + gdkColor.substring(9, 10);
486 else if (gdkColor.length() == 7)
487 // TODO: log warning because we're expecting a 13 character string
495 * This method converts a FieldFormatting.HorizontalAlignment to the equivalent ColumnInfo.HorizontalAlignment. The
496 * need for this comes from the fact that the GWT HorizontalAlignment classes can't be used with RPC and there's no
497 * easy way to use the java-libglom FieldFormatting.HorizontalAlignment enum with RPC. An enum indentical to
498 * FieldFormatting.HorizontalAlignment is included in the ColumnInfo class.
500 private ColumnInfo.HorizontalAlignment getColumnInfoHorizontalAlignment(
501 FieldFormatting.HorizontalAlignment alignment) {
502 int value = alignment.swigValue();
503 ColumnInfo.HorizontalAlignment[] columnInfoValues = ColumnInfo.HorizontalAlignment.class.getEnumConstants();
504 if (value < columnInfoValues.length && value >= 0)
505 return columnInfoValues[value];
506 // TODO: log error: value out of range, returning HORIZONTAL_ALIGNMENT_RIGHT
507 return columnInfoValues[FieldFormatting.HorizontalAlignment.HORIZONTAL_ALIGNMENT_RIGHT.swigValue()];