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.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 Document document;
62 private ComboPooledDataSource cpds;
63 // TODO implement locale
64 private 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()
104 public void destroy() {
105 Glom.libglom_deinit();
107 DataSources.destroy(cpds);
108 } catch (SQLException e) {
109 // TODO log error, don't need to notify user because this is a clean up method
115 * FIXME I think Swig is generating long on 64-bit machines and int on 32-bit machines - need to keep this constant
116 * http://stackoverflow.com/questions/1590831/safely-casting-long-to-int-in-java
118 public static int safeLongToInt(long l) {
119 if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) {
120 throw new IllegalArgumentException(l + " cannot be cast to int without changing its value.");
125 public GlomDocument getGlomDocument() {
126 GlomDocument glomDocument = new GlomDocument();
128 // get arrays of table names and titles, and find the default table index
129 StringVector tablesVec = document.get_table_names();
131 int numTables = safeLongToInt(tablesVec.size());
132 // we don't know how many tables will be hidden so we'll use half of the number of tables for the default size
134 ArrayList<String> tableNames = new ArrayList<String>(numTables / 2);
135 ArrayList<String> tableTitles = new ArrayList<String>(numTables / 2);
136 boolean foundDefaultTable = false;
137 int visibleIndex = 0;
138 for (int i = 0; i < numTables; i++) {
139 String tableName = tablesVec.get(i);
140 if (!document.get_table_is_hidden(tableName)) {
141 tableNames.add(tableName);
142 // JNI is "expensive", the comparison will only be called if we haven't already found the default table
143 if (!foundDefaultTable && tableName.equals(document.get_default_table())) {
144 glomDocument.setDefaultTableIndex(visibleIndex);
145 foundDefaultTable = true;
147 tableTitles.add(document.get_table_title(tableName));
152 // set everything we need
153 glomDocument.setTableNames(tableNames);
154 glomDocument.setTableTitles(tableTitles);
155 glomDocument.setTitle(document.get_database_title());
160 public LayoutListTable getLayoutListTable(String tableName) {
161 LayoutListTable tableInfo = new LayoutListTable();
163 // access the layout list
164 LayoutGroupVector layoutListVec = document.get_data_layout_groups("list", tableName);
165 LayoutItemVector layoutItemsVec = layoutListVec.get(0).get_items();
167 // find the layout list fields
168 int numItems = safeLongToInt(layoutItemsVec.size());
169 ColumnInfo[] columns = new ColumnInfo[numItems];
170 LayoutFieldVector layoutFields = new LayoutFieldVector();
171 for (int i = 0; i < numItems; i++) {
172 // TODO add support for other LayoutItems (Text, Image, Button)
173 LayoutItem item = layoutItemsVec.get(i);
174 LayoutItem_Field field = LayoutItem_Field.cast_dynamic(item);
176 layoutFields.add(field);
177 FieldFormatting.HorizontalAlignment alignment = field.get_formatting_used_horizontal_alignment();
178 columns[i] = new ColumnInfo(item.get_title_or_name(), getColumnInfoHorizontalAlignment(alignment));
181 tableInfo.setColumns(columns);
183 // get the size of the returned query for the pager
184 // TODO since we're executing a query anyway, maybe we should return the rows that will be displayed on the
186 // TODO this code is really similar to code in getTableData, find a way to not duplicate the code
187 Connection conn = null;
191 // setup and execute the query
192 conn = cpds.getConnection();
193 st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
194 String query = Glom.build_sql_select_simple(tableName, layoutFields);
195 rs = st.executeQuery(query);
197 // get the number of rows in the query
198 rs.setFetchDirection(ResultSet.FETCH_FORWARD);
200 tableInfo.setNumRows(rs.getRow());
202 } catch (SQLException e) {
204 // we don't know how many rows are in the query
206 tableInfo.setNumRows(0);
208 // cleanup everything that has been used
213 } catch (Exception e) {
222 public ArrayList<GlomField[]> getTableData(String table, int start, int length) {
223 return getTableData(table, start, length, false, 0, false);
226 public ArrayList<GlomField[]> getSortedTableData(String table, int start, int length, int sortColumnIndex,
227 boolean isAscending) {
228 return getTableData(table, start, length, true, sortColumnIndex, isAscending);
231 private ArrayList<GlomField[]> getTableData(String table, int start, int length, boolean useSortClause,
232 int sortColumnIndex, boolean isAscending) {
234 // access the layout list
235 LayoutGroupVector layoutList = document.get_data_layout_groups("list", table);
236 LayoutItemVector layoutItems = layoutList.get(0).get_items();
238 LayoutFieldVector layoutFields = new LayoutFieldVector();
239 SortClause sortClause = new SortClause();
240 int numItems = safeLongToInt(layoutItems.size());
241 for (int i = 0; i < numItems; i++) {
242 LayoutItem item = layoutItems.get(i);
243 LayoutItem_Field field = LayoutItem_Field.cast_dynamic(item);
245 // use this field in the layout
246 layoutFields.add(field);
248 // create a sort clause if it's a primary key and we're not asked to sort a specific column
249 if (!useSortClause) {
250 Field details = field.get_full_field_details();
251 if (details != null && details.get_primary_key()) {
252 sortClause.addLast(new SortFieldPair(field, true)); // ascending
258 // create a sort clause for the column we've been asked to sort
260 LayoutItem item = layoutItems.get(sortColumnIndex);
261 LayoutItem_Field field = LayoutItem_Field.cast_dynamic(item);
263 sortClause.addLast(new SortFieldPair(field, isAscending));
264 // TODO: log error in the else condition
267 ArrayList<GlomField[]> rowsList = new ArrayList<GlomField[]>();
268 Connection conn = null;
272 // setup and execute the query
273 conn = cpds.getConnection();
274 st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
275 String query = Glom.build_sql_select_simple(table, layoutFields, sortClause);
276 rs = st.executeQuery(query);
278 // get data we're asked for
279 // TODO need to setup the result set in cursor mode so that not all of the results are pulled into memory
280 rs.setFetchDirection(ResultSet.FETCH_FORWARD);
283 while (rs.next() && rowCount <= length) {
284 int layoutItemsSize = safeLongToInt(layoutItems.size());
285 GlomField[] rowArray = new GlomField[layoutItemsSize];
286 for (int i = 0; i < layoutItemsSize; i++) {
287 // make a new GlomField to set the text and colours
288 rowArray[i] = new GlomField();
290 // get foreground and background colours
291 LayoutItem_Field field = layoutFields.get(i);
292 FieldFormatting formatting = field.get_formatting_used();
293 String fgcolour = formatting.get_text_format_color_foreground();
294 if (!fgcolour.isEmpty())
295 rowArray[i].setFGColour(convertGdkColorToHtmlColour(fgcolour));
296 String bgcolour = formatting.get_text_format_color_background();
297 if (!bgcolour.isEmpty())
298 rowArray[i].setBGColour(convertGdkColorToHtmlColour(bgcolour));
300 // convert field values are to strings based on the glom type
301 Field.glom_field_type fieldType = field.get_glom_type();
304 String text = rs.getString(i + 1);
305 rowArray[i].setText(text != null ? text : "");
308 rowArray[i].setText(rs.getBoolean(i + 1) ? "TRUE" : "FALSE");
311 // Take care of the numeric formatting before converting the number to a string.
312 NumericFormat numFormatGlom = formatting.getM_numeric_format();
313 // There's no isCurrency() method in the glom NumericFormat class so we're assuming that the
314 // number should be formatted as a currency if the currency code string is not empty.
315 String currencyCode = numFormatGlom.getM_currency_symbol();
316 NumberFormat numFormatJava = null;
317 boolean useGlomCurrencyCode = false;
318 if (currencyCode.length() == 3) {
319 // Try to format the currency using the Java Locales system.
321 Currency currency = Currency.getInstance(currencyCode);
322 // Ignore the glom numeric formatting when a valid ISO 4217 currency code is being used.
323 int digits = currency.getDefaultFractionDigits();
324 numFormatJava = (DecimalFormat) NumberFormat.getCurrencyInstance(locale);
325 numFormatJava.setCurrency(currency);
326 numFormatJava.setMinimumFractionDigits(digits);
327 numFormatJava.setMaximumFractionDigits(digits);
328 } catch (IllegalArgumentException e) {
330 // The currency code is not this is not an ISO 4217 currency code.
331 // We're going to manually set the currency code and use the glom numeric formatting.
332 useGlomCurrencyCode = true;
333 numFormatJava = getJavaNumberFormat(numFormatGlom);
335 } else if (currencyCode.length() > 0) {
336 // The length of the currency code is > 0 and != 3; this is not an ISO 4217 currency code.
337 // We're going to manually set the currency code and use the glom numeric formatting.
338 useGlomCurrencyCode = true;
339 numFormatJava = getJavaNumberFormat(numFormatGlom);
341 // The length of the currency code is 0; the number is not a currency.
342 numFormatJava = getJavaNumberFormat(numFormatGlom);
345 // TODO: Do I need to do something with NumericFormat.get_default_precision() from libglom?
347 double number = rs.getDouble(i + 1);
349 if (formatting.getM_numeric_format().getM_alt_foreground_color_for_negatives())
350 // overrides the set foreground colour
351 rowArray[i].setFGColour(convertGdkColorToHtmlColour(NumericFormat
352 .get_alternative_color_for_negatives()));
355 // Finally convert the number to text using the glom currency string if required.
356 if (useGlomCurrencyCode) {
357 rowArray[i].setText(currencyCode + " " + numFormatJava.format(number));
359 rowArray[i].setText(numFormatJava.format(number));
363 Date date = rs.getDate(i + 1);
365 DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
366 rowArray[i].setText(dateFormat.format(rs.getDate(i + 1)));
368 rowArray[i].setText("");
372 Time time = rs.getTime(i + 1);
374 DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
375 rowArray[i].setText(timeFormat.format(time));
377 rowArray[i].setText("");
381 // TODO implement this
382 rowArray[i].setText("Image (FIXME)");
386 // TODO log warning message
387 rowArray[i].setText("");
392 // add the row of GlomFields to the ArrayList we're going to return and update the row count
393 rowsList.add(rowArray);
396 } catch (SQLException e) {
397 // TODO: log error, notify user of problem
400 // cleanup everything that has been used
405 } catch (Exception e) {
413 private NumberFormat getJavaNumberFormat(NumericFormat numFormatGlom) {
414 NumberFormat numFormatJava = NumberFormat.getInstance(locale);
415 if (numFormatGlom.getM_decimal_places_restricted()) {
416 int digits = safeLongToInt(numFormatGlom.getM_decimal_places());
417 numFormatJava.setMinimumFractionDigits(digits);
418 numFormatJava.setMaximumFractionDigits(digits);
420 numFormatJava.setGroupingUsed(numFormatGlom.getM_use_thousands_separator());
421 return numFormatJava;
425 * Converts a Gdk::Color (16-bits per channel) to an HTML colour (8-bits per channel) by disgarding the least
426 * significant 8-bits in each channel.
428 private String convertGdkColorToHtmlColour(String gdkColor) {
429 if (gdkColor.length() == 13)
430 return gdkColor.substring(0, 2) + gdkColor.substring(5, 6) + gdkColor.substring(9, 10);
431 else if (gdkColor.length() == 7)
432 // TODO: log warning because we're expecting a 13 character string
440 * This method converts a FieldFormatting.HorizontalAlignment to the equivalent ColumnInfo.HorizontalAlignment. The
441 * need for this comes from the fact that the GWT HorizontalAlignment classes can't be used with RPC and there's no
442 * easy way to use the java-libglom FieldFormatting.HorizontalAlignment enum with RPC. An enum indentical to
443 * FieldFormatting.HorizontalAlignment is included in the ColumnInfo class.
445 private ColumnInfo.HorizontalAlignment getColumnInfoHorizontalAlignment(
446 FieldFormatting.HorizontalAlignment alignment) {
447 int value = alignment.swigValue();
448 ColumnInfo.HorizontalAlignment[] columnInfoValues = ColumnInfo.HorizontalAlignment.class.getEnumConstants();
449 if (value < columnInfoValues.length && value >= 0)
450 return columnInfoValues[value];
451 // TODO: log error: value out of range, returning HORIZONTAL_ALIGNMENT_RIGHT
452 return columnInfoValues[FieldFormatting.HorizontalAlignment.HORIZONTAL_ALIGNMENT_RIGHT.swigValue()];