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.ENGLISH;
67 * This is called when the servlet is started or restarted.
69 public OnlineGlomServiceImpl() {
71 document = new Document();
72 // TODO hardcoded 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");
76 @SuppressWarnings("unused")
77 boolean retval = document.load(error);
78 // TODO handle error condition (also below)
80 cpds = new ComboPooledDataSource();
81 // load the jdbc driver
83 cpds.setDriverClass("org.postgresql.Driver");
84 } catch (PropertyVetoException e) {
85 // TODO log error, fatal error can't continue, user can be nofified when db access doesn't work
89 cpds.setJdbcUrl("jdbc:postgresql://" + document.get_connection_server() + "/"
90 + document.get_connection_database());
91 // TODO figure out something for db user name and password
93 cpds.setPassword("ChangeMe"); // of course it's not the password I'm using on my server
97 * This is called when the servlet is stopped or restarted.
99 * @see javax.servlet.GenericServlet#destroy()
101 public void destroy() {
102 Glom.libglom_deinit();
104 DataSources.destroy(cpds);
105 } catch (SQLException e) {
106 // TODO log error, don't need to notify user because this is a clean up method
112 * FIXME I think Swig is generating long on 64-bit machines and int on 32-bit machines - need to keep this constant
113 * http://stackoverflow.com/questions/1590831/safely-casting-long-to-int-in-java
115 public static int safeLongToInt(long l) {
116 if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) {
117 throw new IllegalArgumentException(l + " cannot be cast to int without changing its value.");
122 public GlomDocument getGlomDocument() {
123 GlomDocument glomDocument = new GlomDocument();
125 // get arrays of table names and titles, and find the default table index
126 StringVector tablesVec = document.get_table_names();
128 int numTables = safeLongToInt(tablesVec.size());
129 // we don't know how many tables will be hidden so we'll use half of the number of tables for the default size
131 ArrayList<String> tableNames = new ArrayList<String>(numTables / 2);
132 ArrayList<String> tableTitles = new ArrayList<String>(numTables / 2);
133 boolean foundDefaultTable = false;
134 for (int i = 0; i < numTables; i++) {
135 String tableName = tablesVec.get(i);
136 if (!document.get_table_is_hidden(tableName)) {
137 tableNames.add(tableName);
138 // JNI is "expensive", the comparison will only be called if we haven't already found the default table
139 if (!foundDefaultTable && tableName.equals(document.get_default_table())) {
140 glomDocument.setDefaultTableIndex(i);
141 foundDefaultTable = true;
143 tableTitles.add(document.get_table_title(tableName));
147 // set everything we need
148 glomDocument.setTableNames(tableNames);
149 glomDocument.setTableTitles(tableTitles);
150 glomDocument.setTitle(document.get_database_title());
155 public LayoutListTable getLayoutListTable(String tableName) {
156 LayoutListTable tableInfo = new LayoutListTable();
158 // access the layout list
159 LayoutGroupVector layoutListVec = document.get_data_layout_groups("list", tableName);
160 LayoutItemVector layoutItemsVec = layoutListVec.get(0).get_items();
162 // find the layout list fields
163 int numItems = safeLongToInt(layoutItemsVec.size());
164 ColumnInfo[] columns = new ColumnInfo[numItems];
165 LayoutFieldVector layoutFields = new LayoutFieldVector();
166 for (int i = 0; i < numItems; i++) {
167 // TODO add support for other LayoutItems (Text, Image, Button)
168 LayoutItem item = layoutItemsVec.get(i);
169 LayoutItem_Field field = LayoutItem_Field.cast_dynamic(item);
171 layoutFields.add(field);
172 FieldFormatting.HorizontalAlignment alignment = field.get_formatting_used_horizontal_alignment();
173 columns[i] = new ColumnInfo(item.get_title_or_name(), getColumnInfoHorizontalAlignment(alignment));
176 tableInfo.setColumns(columns);
178 // get the size of the returned query for the pager
179 // TODO since we're executing a query anyway, maybe we should return the rows that will be displayed on the
181 // TODO this code is really similar to code in getTableData, find a way to not duplicate the code
182 Connection conn = null;
186 // setup and execute the query
187 conn = cpds.getConnection();
188 st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
189 String query = Glom.build_sql_select_simple(tableName, layoutFields);
190 rs = st.executeQuery(query);
192 // get the number of rows in the query
193 rs.setFetchDirection(ResultSet.FETCH_FORWARD);
195 tableInfo.setNumRows(rs.getRow());
197 } catch (SQLException e) {
199 // we don't know how many rows are in the query
201 tableInfo.setNumRows(0);
203 // cleanup everything that has been used
208 } catch (Exception e) {
217 public ArrayList<GlomField[]> getTableData(String table, int start, int length) {
218 return getTableData(table, start, length, false, 0, false);
221 public ArrayList<GlomField[]> getSortedTableData(String table, int start, int length, int sortColumnIndex,
222 boolean isAscending) {
223 return getTableData(table, start, length, true, sortColumnIndex, isAscending);
226 private ArrayList<GlomField[]> getTableData(String table, int start, int length, boolean useSortClause,
227 int sortColumnIndex, boolean isAscending) {
229 // access the layout list
230 LayoutGroupVector layoutList = document.get_data_layout_groups("list", table);
231 LayoutItemVector layoutItems = layoutList.get(0).get_items();
233 LayoutFieldVector layoutFields = new LayoutFieldVector();
234 SortClause sortClause = new SortClause();
235 int numItems = safeLongToInt(layoutItems.size());
236 for (int i = 0; i < numItems; i++) {
237 LayoutItem item = layoutItems.get(i);
238 LayoutItem_Field field = LayoutItem_Field.cast_dynamic(item);
240 // use this field in the layout
241 layoutFields.add(field);
243 // create a sort clause if it's a primary key and we're not asked to sort a specific column
244 if (!useSortClause) {
245 Field details = field.get_full_field_details();
246 if (details != null && details.get_primary_key()) {
247 sortClause.addLast(new SortFieldPair(field, true)); // ascending
253 // create a sort clause for the column we've been asked to sort
255 LayoutItem item = layoutItems.get(sortColumnIndex);
256 LayoutItem_Field field = LayoutItem_Field.cast_dynamic(item);
258 sortClause.addLast(new SortFieldPair(field, isAscending));
259 // TODO: log error in the else condition
262 ArrayList<GlomField[]> rowsList = new ArrayList<GlomField[]>();
263 Connection conn = null;
267 // setup and execute the query
268 conn = cpds.getConnection();
269 st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
270 String query = Glom.build_sql_select_simple(table, layoutFields, sortClause);
271 rs = st.executeQuery(query);
273 // get data we're asked for
274 // TODO need to setup the result set in cursor mode so that not all of the results are pulled into memory
275 rs.setFetchDirection(ResultSet.FETCH_FORWARD);
278 while (rs.next() && rowCount <= length) {
279 int layoutItemsSize = safeLongToInt(layoutItems.size());
280 GlomField[] rowArray = new GlomField[layoutItemsSize];
281 for (int i = 0; i < layoutItemsSize; i++) {
282 // make a new GlomField to set the text and colours
283 rowArray[i] = new GlomField();
285 // get foreground and background colours
286 LayoutItem_Field field = layoutFields.get(i);
287 FieldFormatting formatting = field.get_formatting_used();
288 String fgcolour = formatting.get_text_format_color_foreground();
289 if (!fgcolour.isEmpty())
290 rowArray[i].setFGColour(convertGdkColorToHtmlColour(fgcolour));
291 String bgcolour = formatting.get_text_format_color_background();
292 if (!bgcolour.isEmpty())
293 rowArray[i].setBGColour(convertGdkColorToHtmlColour(bgcolour));
295 // convert field values are to strings based on the glom type
296 Field.glom_field_type fieldType = field.get_glom_type();
299 String text = rs.getString(i + 1);
300 rowArray[i].setText(text != null ? text : "");
303 rowArray[i].setText(rs.getBoolean(i + 1) ? "TRUE" : "FALSE");
306 // take care of the numeric formatting before converting the number to a string
307 NumericFormat numFormatGlom = formatting.getM_numeric_format();
308 // there's no isCurrency() method in the glom NumericFormat class so we're assuming that the
309 // number should be formatted as a currency if the currency symbol is set
310 String currencySymbol = numFormatGlom.getM_currency_symbol();
311 NumberFormat numFormatJava;
312 if (currencySymbol.length() == 3) {
313 Currency currency = Currency.getInstance(currencySymbol);
314 // we're not using the glom value for digits and grouping when it's a currency
315 int digits = currency.getDefaultFractionDigits();
316 numFormatJava = (DecimalFormat) NumberFormat.getCurrencyInstance(locale);
317 numFormatJava.setCurrency(currency);
318 numFormatJava.setMinimumFractionDigits(digits);
319 numFormatJava.setMaximumFractionDigits(digits);
321 numFormatJava = NumberFormat.getInstance(locale);
322 if (numFormatGlom.getM_decimal_places_restricted()) {
323 int digits = safeLongToInt(numFormatGlom.getM_decimal_places());
324 numFormatJava.setMinimumFractionDigits(digits);
325 numFormatJava.setMaximumFractionDigits(digits);
327 numFormatJava.setGroupingUsed(numFormatGlom.getM_use_thousands_separator());
330 // TODO: Do I need to do something with NumericFormat.get_default_precision() from libglom?
332 double number = rs.getDouble(i + 1);
334 if (formatting.getM_numeric_format().getM_alt_foreground_color_for_negatives())
335 // overrides the set foreground colour
336 rowArray[i].setFGColour(convertGdkColorToHtmlColour(NumericFormat
337 .get_alternative_color_for_negatives()));
339 rowArray[i].setText(numFormatJava.format(number));
342 Date date = rs.getDate(i + 1);
344 DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
345 rowArray[i].setText(dateFormat.format(rs.getDate(i + 1)));
347 rowArray[i].setText("");
351 Time time = rs.getTime(i + 1);
353 DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
354 rowArray[i].setText(timeFormat.format(time));
356 rowArray[i].setText("");
360 // TODO log warning message
364 // TODO log warning message
369 // add the row of GlomFields to the ArrayList we're going to return and update the row count
370 rowsList.add(rowArray);
373 } catch (SQLException e) {
374 // TODO: log error, notify user of problem
377 // cleanup everything that has been used
382 } catch (Exception e) {
391 * Converts a Gdk::Color (16-bits per channel) to an HTML colour (8-bits per channel) by disgarding the least
392 * significant 8-bits in each channel.
394 private String convertGdkColorToHtmlColour(String gdkColor) {
395 if (gdkColor.length() == 13)
396 return gdkColor.substring(0, 2) + gdkColor.substring(5, 6) + gdkColor.substring(9, 10);
397 else if (gdkColor.length() == 7)
398 // TODO: log warning because we're expecting a 13 character string
406 * This method converts a FieldFormatting.HorizontalAlignment to the equivalent ColumnInfo.HorizontalAlignment. The
407 * need for this comes from the fact that the GWT HorizontalAlignment classes can't be used with RPC and there's no
408 * easy way to use the java-libglom FieldFormatting.HorizontalAlignment enum with RPC. An enum indentical to
409 * FieldFormatting.HorizontalAlignment is included in the ColumnInfo class.
411 private ColumnInfo.HorizontalAlignment getColumnInfoHorizontalAlignment(
412 FieldFormatting.HorizontalAlignment alignment) {
413 int value = alignment.swigValue();
414 ColumnInfo.HorizontalAlignment[] columnInfoValues = ColumnInfo.HorizontalAlignment.class.getEnumConstants();
415 if (value < columnInfoValues.length && value >= 0)
416 return columnInfoValues[value];
417 // TODO: log error: value out of range, returning HORIZONTAL_ALIGNMENT_RIGHT
418 return columnInfoValues[FieldFormatting.HorizontalAlignment.HORIZONTAL_ALIGNMENT_RIGHT.swigValue()];