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.FilenameFilter;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.sql.Connection;
29 import java.sql.ResultSet;
30 import java.sql.SQLException;
31 import java.sql.Statement;
33 import java.text.DateFormat;
34 import java.text.NumberFormat;
35 import java.util.ArrayList;
36 import java.util.Currency;
37 import java.util.Hashtable;
38 import java.util.Locale;
39 import java.util.Properties;
41 import org.glom.libglom.BakeryDocument.LoadFailureCodes;
42 import org.glom.libglom.Document;
43 import org.glom.libglom.Field;
44 import org.glom.libglom.FieldFormatting;
45 import org.glom.libglom.FieldVector;
46 import org.glom.libglom.Glom;
47 import org.glom.libglom.LayoutFieldVector;
48 import org.glom.libglom.LayoutGroupVector;
49 import org.glom.libglom.LayoutItem;
50 import org.glom.libglom.LayoutItemVector;
51 import org.glom.libglom.LayoutItem_Field;
52 import org.glom.libglom.LayoutItem_Portal;
53 import org.glom.libglom.NumericFormat;
54 import org.glom.libglom.SortClause;
55 import org.glom.libglom.SortFieldPair;
56 import org.glom.libglom.StringVector;
57 import org.glom.web.client.OnlineGlomService;
58 import org.glom.web.shared.GlomDocument;
59 import org.glom.web.shared.GlomField;
60 import org.glom.web.shared.layout.Formatting;
61 import org.glom.web.shared.layout.LayoutGroup;
62 import org.glom.web.shared.layout.LayoutItemField;
64 import com.google.gwt.user.server.rpc.RemoteServiceServlet;
65 import com.mchange.v2.c3p0.ComboPooledDataSource;
66 import com.mchange.v2.c3p0.DataSources;
68 @SuppressWarnings("serial")
69 public class OnlineGlomServiceImpl extends RemoteServiceServlet implements OnlineGlomService {
71 // class to hold configuration information for related to the glom document and db access
72 private class ConfiguredDocument {
73 private Document document;
74 private ComboPooledDataSource cpds;
75 private boolean authenticated = false;
78 public Document getDocument() { return document; }
79 public void setDocument(Document document) { this.document = document; }
80 public ComboPooledDataSource getCpds() { return cpds; }
81 public void setCpds(ComboPooledDataSource cpds) { this.cpds = cpds; }
82 public boolean isAuthenticated() { return authenticated; }
83 public void setAuthenticated(boolean authenticated) { this.authenticated = authenticated; }
87 // convenience class to for dealing with the Online Glom configuration file
88 private class OnlineGlomProperties extends Properties {
89 public String getKey(String value) {
90 for (String key : stringPropertyNames()) {
91 if (getProperty(key).trim().equals(value))
98 private final Hashtable<String, ConfiguredDocument> documents = new Hashtable<String, ConfiguredDocument>();
99 // TODO implement locale
100 private final Locale locale = Locale.ROOT;
103 * This is called when the servlet is started or restarted.
105 public OnlineGlomServiceImpl() throws Exception {
107 // Find the configuration file. See this thread for background info:
108 // http://stackoverflow.com/questions/2161054/where-to-place-properties-files-in-a-jsp-servlet-web-application
109 OnlineGlomProperties config = new OnlineGlomProperties();
110 InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("onlineglom.properties");
112 Log.fatal("onlineglom.properties not found.");
113 throw new IOException();
117 // check the configured glom file directory
118 String documentDirName = config.getProperty("glom.document.directory");
119 File documentDir = new File(documentDirName);
120 if (!documentDir.isDirectory()) {
121 Log.fatal(documentDirName + " is not a directory.");
122 throw new IOException();
124 if (!documentDir.canRead()) {
125 Log.fatal("Can't read the files in : " + documentDirName);
126 throw new IOException();
129 // get and check the glom files in the specified directory
130 File[] glomFiles = documentDir.listFiles(new FilenameFilter() {
132 public boolean accept(File dir, String name) {
133 return name.endsWith(".glom");
137 for (File glomFile : glomFiles) {
138 Document document = new Document();
139 document.set_file_uri("file://" + glomFile.getAbsolutePath());
141 boolean retval = document.load(error);
142 if (retval == false) {
144 if (LoadFailureCodes.LOAD_FAILURE_CODE_NOT_FOUND == LoadFailureCodes.swigToEnum(error)) {
145 message = "Could not find file: " + glomFile.getAbsolutePath();
147 message = "An unknown error occurred when trying to load file: " + glomFile.getAbsolutePath();
150 // continue with for loop because there may be other documents in the directory
154 // load the jdbc driver for the current glom document
155 ComboPooledDataSource cpds = new ComboPooledDataSource();
158 cpds.setDriverClass("org.postgresql.Driver");
159 } catch (PropertyVetoException e) {
160 Log.fatal("Error loading the PostgreSQL JDBC driver."
161 + " Is the PostgreSQL JDBC jar available to the servlet?", e);
165 // setup the JDBC driver for the current glom document
166 cpds.setJdbcUrl("jdbc:postgresql://" + document.get_connection_server() + "/"
167 + document.get_connection_database());
169 // check if a username and password have been set and work for the current document
170 String documentTitle = document.get_database_title().trim();
171 ConfiguredDocument configuredDocument = new ConfiguredDocument();
172 String key = config.getKey(documentTitle);
174 String[] keyArray = key.split("\\.");
175 if (keyArray.length == 3 && "title".equals(keyArray[2])) {
176 // username/password could be set, let's check to see if it works
177 String usernameKey = key.replaceAll(keyArray[2], "username");
178 String passwordKey = key.replaceAll(keyArray[2], "password");
179 configuredDocument.setAuthenticated(checkAuthentication(documentTitle, cpds,
180 config.getProperty(usernameKey), config.getProperty(passwordKey)));
184 // check the if the global username and password have been set and work with this document
185 if (!configuredDocument.isAuthenticated()) {
186 configuredDocument.setAuthenticated(checkAuthentication(documentTitle, cpds,
187 config.getProperty("glom.document.username"), config.getProperty("glom.document.password")));
190 // add information to the hash table
191 configuredDocument.setDocument(document);
192 configuredDocument.setCpds(cpds);
193 documents.put(documentTitle, configuredDocument);
198 * Checks if the username and password works with the database configured with the specified ComboPooledDataSource.
200 * @return true if authentication works, false otherwise
202 private boolean checkAuthentication(String documentTitle, ComboPooledDataSource cpds, String username,
203 String password) throws SQLException {
204 cpds.setUser(username);
205 cpds.setPassword(password);
207 int acquireRetryAttempts = cpds.getAcquireRetryAttempts();
208 cpds.setAcquireRetryAttempts(1);
209 Connection conn = null;
211 // FIXME find a better way to check authentication
212 // it's possible that the connection could be failing for another reason
213 conn = cpds.getConnection();
215 } catch (SQLException e) {
216 Log.info(documentTitle, "Username and password not correct.");
220 cpds.setAcquireRetryAttempts(acquireRetryAttempts);
226 * This is called when the servlet is stopped or restarted.
228 * @see javax.servlet.GenericServlet#destroy()
231 public void destroy() {
232 Glom.libglom_deinit();
234 for (String documenTitle : documents.keySet()) {
235 ConfiguredDocument configuredDoc = documents.get(documenTitle);
237 DataSources.destroy(configuredDoc.getCpds());
238 } catch (SQLException e) {
239 Log.error(documenTitle, "Error cleaning up the ComboPooledDataSource.", e);
245 public GlomDocument getGlomDocument(String documentTitle) {
247 Document document = documents.get(documentTitle).getDocument();
248 GlomDocument glomDocument = new GlomDocument();
250 // get arrays of table names and titles, and find the default table index
251 StringVector tablesVec = document.get_table_names();
253 int numTables = safeLongToInt(tablesVec.size());
254 // we don't know how many tables will be hidden so we'll use half of the number of tables for the default size
256 ArrayList<String> tableNames = new ArrayList<String>(numTables / 2);
257 ArrayList<String> tableTitles = new ArrayList<String>(numTables / 2);
258 boolean foundDefaultTable = false;
259 int visibleIndex = 0;
260 for (int i = 0; i < numTables; i++) {
261 String tableName = tablesVec.get(i);
262 if (!document.get_table_is_hidden(tableName)) {
263 tableNames.add(tableName);
264 // JNI is "expensive", the comparison will only be called if we haven't already found the default table
265 if (!foundDefaultTable && tableName.equals(document.get_default_table())) {
266 glomDocument.setDefaultTableIndex(visibleIndex);
267 foundDefaultTable = true;
269 tableTitles.add(document.get_table_title(tableName));
274 // set everything we need
275 glomDocument.setTableNames(tableNames);
276 glomDocument.setTableTitles(tableTitles);
284 * @see org.glom.web.client.OnlineGlomService#getDefaultLayoutListTable(java.lang.String)
287 public LayoutGroup getDefaultListLayout(String documentTitle) {
288 GlomDocument glomDocument = getGlomDocument(documentTitle);
289 String tableName = glomDocument.getTableNames().get(glomDocument.getDefaultTableIndex());
290 LayoutGroup layoutGroup = getListLayout(documentTitle, tableName);
291 layoutGroup.setDefaultTableName(tableName);
295 public LayoutGroup getListLayout(String documentTitle, String tableName) {
296 ConfiguredDocument configuredDoc = documents.get(documentTitle);
297 Document document = configuredDoc.getDocument();
299 // access the layout list
300 LayoutGroupVector layoutGroupVec = document.get_data_layout_groups("list", tableName);
301 int listViewLayoutGroupSize = safeLongToInt(layoutGroupVec.size());
302 org.glom.libglom.LayoutGroup libglomLayoutGroup = null;
303 if (listViewLayoutGroupSize > 0) {
304 // a list layout group is defined; we can use the first group as the list
305 if (listViewLayoutGroupSize > 1)
306 Log.warn(documentTitle, tableName,
307 "The size of the list layout group is greater than 1. Attempting to use the first item for the layout list view.");
309 libglomLayoutGroup = layoutGroupVec.get(0);
311 // a list layout group is *not* defined; we are going make a libglom layout group from the list of fields
312 Log.info(documentTitle, tableName,
313 "A list layout is not defined for this table. Displaying a list layout based on the field list.");
315 FieldVector fieldsVec = document.get_table_fields(tableName);
316 libglomLayoutGroup = new org.glom.libglom.LayoutGroup();
317 for (int i = 0; i < fieldsVec.size(); i++) {
318 Field field = fieldsVec.get(i);
319 LayoutItem_Field layoutItemField = new LayoutItem_Field();
320 layoutItemField.set_full_field_details(field);
321 libglomLayoutGroup.add_item(layoutItemField);
325 // confirm the libglom LayoutGroup is not null as per the method's precondition
326 if (libglomLayoutGroup == null) {
327 Log.error(documentTitle, tableName, "A LayoutGroup was not found. Returning null.");
331 LayoutGroup layoutGroup = getLayoutGroup(documentTitle, tableName, libglomLayoutGroup);
333 // use the same fields list as will be used for the query
334 LayoutFieldVector fieldsToGet = getFieldsToShowForSQLQuery(document, tableName, "list");
335 layoutGroup.setExpectedResultSize(getResultSizeOfSQLQuery(documentTitle, tableName, fieldsToGet));
340 * Get the number of rows a query with the table name and layout fields would return. This is needed for the /* list
343 private int getResultSizeOfSQLQuery(String documentTitle, String tableName, LayoutFieldVector fieldsToGet) {
344 ConfiguredDocument configuredDoc = documents.get(documentTitle);
345 if (!configuredDoc.isAuthenticated())
347 Connection conn = null;
351 // Setup and execute the count query. Special care needs to be take to ensure that the results will be based
352 // on a cursor so that large amounts of memory are not consumed when the query retrieve a large amount of
353 // data. Here's the relevant PostgreSQL documentation:
354 // http://jdbc.postgresql.org/documentation/83/query.html#query-with-cursor
355 ComboPooledDataSource cpds = configuredDoc.getCpds();
356 conn = cpds.getConnection();
357 conn.setAutoCommit(false);
358 st = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
359 String query = Glom.build_sql_select_count_simple(tableName, fieldsToGet);
360 // TODO Test execution time of this query with when the number of rows in the table is large (say >
361 // 1,000,000). Test memory usage at the same time (see the todo item in getTableData()).
362 rs = st.executeQuery(query);
364 // get the number of rows in the query
368 } catch (SQLException e) {
369 Log.error(documentTitle, tableName,
370 "Error calculating number of rows in the query. Setting number of rows to 0.", e);
373 // cleanup everything that has been used
381 } catch (Exception e) {
382 Log.error(documentTitle, tableName,
383 "Error closing database resources. Subsequent database queries may not work.", e);
388 // FIXME Rename to getListData(), getSortedListDat() for consistency in method naming.
389 // FIXME Check if we can use getFieldsToShowForSQLQuery() in these methods
390 public ArrayList<GlomField[]> getTableData(String documentTitle, String tableName, int start, int length) {
391 return getTableData(documentTitle, tableName, start, length, false, 0, false);
394 public ArrayList<GlomField[]> getSortedTableData(String documentTitle, String tableName, int start, int length,
395 int sortColumnIndex, boolean isAscending) {
396 return getTableData(documentTitle, tableName, start, length, true, sortColumnIndex, isAscending);
399 private ArrayList<GlomField[]> getTableData(String documentTitle, String tableName, int start, int length,
400 boolean useSortClause, int sortColumnIndex, boolean isAscending) {
402 ConfiguredDocument configuredDoc = documents.get(documentTitle);
403 if (!configuredDoc.isAuthenticated())
404 return new ArrayList<GlomField[]>();
405 Document document = configuredDoc.getDocument();
407 // access the layout list using the defined layout list or the table fields if there's no layout list
408 LayoutGroupVector layoutListVec = document.get_data_layout_groups("list", tableName);
409 LayoutFieldVector layoutFields = new LayoutFieldVector();
410 SortClause sortClause = new SortClause();
411 int listViewLayoutGroupSize = safeLongToInt(layoutListVec.size());
412 if (layoutListVec.size() > 0) {
413 // a layout list is defined, we can use it to for the LayoutListTable
414 if (listViewLayoutGroupSize > 1)
415 Log.warn(documentTitle, tableName,
416 "The size of the list view layout group for table is greater than 1. "
417 + "Attempting to use the first item for the layout list view.");
418 LayoutItemVector layoutItemsVec = layoutListVec.get(0).get_items();
420 // find the defined layout list fields
421 int numItems = safeLongToInt(layoutItemsVec.size());
422 for (int i = 0; i < numItems; i++) {
423 // TODO add support for other LayoutItems (Text, Image, Button)
424 LayoutItem item = layoutItemsVec.get(i);
425 LayoutItem_Field layoutItemfield = LayoutItem_Field.cast_dynamic(item);
426 if (layoutItemfield != null) {
427 // use this field in the layout
428 layoutFields.add(layoutItemfield);
430 // create a sort clause if it's a primary key and we're not asked to sort a specific column
431 if (!useSortClause) {
432 Field details = layoutItemfield.get_full_field_details();
433 if (details != null && details.get_primary_key()) {
434 sortClause.addLast(new SortFieldPair(layoutItemfield, true)); // ascending
440 // no layout list is defined, use the table fields as the layout list
441 FieldVector fieldsVec = document.get_table_fields(tableName);
443 // find the fields to display in the layout list
444 int numItems = safeLongToInt(fieldsVec.size());
445 for (int i = 0; i < numItems; i++) {
446 Field field = fieldsVec.get(i);
447 LayoutItem_Field layoutItemField = new LayoutItem_Field();
448 layoutItemField.set_full_field_details(field);
449 layoutFields.add(layoutItemField);
451 // create a sort clause if it's a primary key and we're not asked to sort a specific column
452 if (!useSortClause) {
453 if (field.get_primary_key()) {
454 sortClause.addLast(new SortFieldPair(layoutItemField, true)); // ascending
460 // create a sort clause for the column we've been asked to sort
462 LayoutItem item = layoutFields.get(sortColumnIndex);
463 LayoutItem_Field field = LayoutItem_Field.cast_dynamic(item);
465 sortClause.addLast(new SortFieldPair(field, isAscending));
467 Log.error(documentTitle, tableName, "Error getting LayoutItem_Field for column index "
468 + sortColumnIndex + ". Cannot create a sort clause for this column.");
473 ArrayList<GlomField[]> rowsList = new ArrayList<GlomField[]>();
474 Connection conn = null;
478 // Setup the JDBC driver and get the query. Special care needs to be take to ensure that the results will be
479 // based on a cursor so that large amounts of memory are not consumed when the query retrieve a large amount
480 // of data. Here's the relevant PostgreSQL documentation:
481 // http://jdbc.postgresql.org/documentation/83/query.html#query-with-cursor
482 ComboPooledDataSource cpds = configuredDoc.getCpds();
483 conn = cpds.getConnection();
484 conn.setAutoCommit(false);
485 st = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
486 st.setFetchSize(length);
487 String query = Glom.build_sql_select_simple(tableName, layoutFields, sortClause) + " OFFSET " + start;
488 // TODO Test memory usage before and after we execute the query that would result in a large ResultSet.
489 // We need to ensure that the JDBC driver is in fact returning a cursor based result set that has a low
490 // memory footprint. Check the difference between this value before and after the query:
491 // Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()
492 // Test the execution time at the same time (see the todo item in getLayoutListTable()).
493 rs = st.executeQuery(query);
495 // get the results from the ResultSet
496 rowsList = getData(documentTitle, tableName, length, layoutFields, rs);
497 } catch (SQLException e) {
498 Log.error(documentTitle, tableName, "Error executing database query.", e);
499 // TODO: somehow notify user of problem
501 // cleanup everything that has been used
509 } catch (Exception e) {
510 Log.error(documentTitle, tableName,
511 "Error closing database resources. Subsequent database queries may not work.", e);
517 private ArrayList<GlomField[]> getData(String documentTitle, String tableName, int length,
518 LayoutFieldVector layoutFields, ResultSet rs) throws SQLException {
520 // get the data we've been asked for
522 ArrayList<GlomField[]> rowsList = new ArrayList<GlomField[]>();
523 while (rs.next() && rowCount <= length) {
524 int layoutFieldsSize = safeLongToInt(layoutFields.size());
525 GlomField[] rowArray = new GlomField[layoutFieldsSize];
526 for (int i = 0; i < layoutFieldsSize; i++) {
527 // make a new GlomField to set the text and colours
528 rowArray[i] = new GlomField();
530 // get foreground and background colours
531 LayoutItem_Field field = layoutFields.get(i);
532 FieldFormatting formatting = field.get_formatting_used();
533 String fgcolour = formatting.get_text_format_color_foreground();
534 if (!fgcolour.isEmpty())
535 rowArray[i].setFGColour(convertGdkColorToHtmlColour(fgcolour));
536 String bgcolour = formatting.get_text_format_color_background();
537 if (!bgcolour.isEmpty())
538 rowArray[i].setBGColour(convertGdkColorToHtmlColour(bgcolour));
540 // Convert the field value to a string based on the glom type. We're doing the formatting on the
541 // server side for now but it might be useful to move this to the client side.
542 switch (field.get_glom_type()) {
544 String text = rs.getString(i + 1);
545 rowArray[i].setText(text != null ? text : "");
548 rowArray[i].setBoolean(rs.getBoolean(i + 1));
551 // Take care of the numeric formatting before converting the number to a string.
552 NumericFormat numFormatGlom = formatting.getM_numeric_format();
553 // There's no isCurrency() method in the glom NumericFormat class so we're assuming that the
554 // number should be formatted as a currency if the currency code string is not empty.
555 String currencyCode = numFormatGlom.getM_currency_symbol();
556 NumberFormat numFormatJava = null;
557 boolean useGlomCurrencyCode = false;
558 if (currencyCode.length() == 3) {
559 // Try to format the currency using the Java Locales system.
561 Currency currency = Currency.getInstance(currencyCode);
562 Log.info(documentTitle, tableName, "A valid ISO 4217 currency code is being used."
563 + " Overriding the numeric formatting with information from the locale.");
564 int digits = currency.getDefaultFractionDigits();
565 numFormatJava = NumberFormat.getCurrencyInstance(locale);
566 numFormatJava.setCurrency(currency);
567 numFormatJava.setMinimumFractionDigits(digits);
568 numFormatJava.setMaximumFractionDigits(digits);
569 } catch (IllegalArgumentException e) {
570 Log.warn(documentTitle, tableName, currencyCode + " is not a valid ISO 4217 code."
571 + " Manually setting currency code with this value.");
572 // The currency code is not this is not an ISO 4217 currency code.
573 // We're going to manually set the currency code and use the glom numeric formatting.
574 useGlomCurrencyCode = true;
575 numFormatJava = getJavaNumberFormat(numFormatGlom);
577 } else if (currencyCode.length() > 0) {
578 Log.warn(documentTitle, tableName, currencyCode + " is not a valid ISO 4217 code."
579 + " Manually setting currency code with this value.");
580 // The length of the currency code is > 0 and != 3; this is not an ISO 4217 currency code.
581 // We're going to manually set the currency code and use the glom numeric formatting.
582 useGlomCurrencyCode = true;
583 numFormatJava = getJavaNumberFormat(numFormatGlom);
585 // The length of the currency code is 0; the number is not a currency.
586 numFormatJava = getJavaNumberFormat(numFormatGlom);
589 // TODO: Do I need to do something with NumericFormat.get_default_precision() from libglom?
591 double number = rs.getDouble(i + 1);
593 if (formatting.getM_numeric_format().getM_alt_foreground_color_for_negatives())
594 // overrides the set foreground colour
595 rowArray[i].setFGColour(convertGdkColorToHtmlColour(NumericFormat
596 .get_alternative_color_for_negatives()));
599 // Finally convert the number to text using the glom currency string if required.
600 if (useGlomCurrencyCode) {
601 rowArray[i].setText(currencyCode + " " + numFormatJava.format(number));
603 rowArray[i].setText(numFormatJava.format(number));
607 Date date = rs.getDate(i + 1);
609 DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
610 rowArray[i].setText(dateFormat.format(date));
612 rowArray[i].setText("");
616 Time time = rs.getTime(i + 1);
618 DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
619 rowArray[i].setText(timeFormat.format(time));
621 rowArray[i].setText("");
625 byte[] image = rs.getBytes(i + 1);
627 // TODO implement field TYPE_IMAGE
628 rowArray[i].setText("Image (FIXME)");
630 rowArray[i].setText("");
635 Log.warn(documentTitle, tableName, "Invalid LayoutItem Field type. Using empty string for value.");
636 rowArray[i].setText("");
641 // add the row of GlomFields to the ArrayList we're going to return and update the row count
642 rowsList.add(rowArray);
649 public ArrayList<String> getDocumentTitles() {
650 ArrayList<String> documentTitles = new ArrayList<String>();
651 for (String title : documents.keySet()) {
652 documentTitles.add(title);
654 return documentTitles;
658 * This method safely converts longs from libglom into ints. This method was taken from stackoverflow:
660 * http://stackoverflow.com/questions/1590831/safely-casting-long-to-int-in-java
662 private int safeLongToInt(long value) {
663 if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) {
664 throw new IllegalArgumentException(value + " cannot be cast to int without changing its value.");
669 private NumberFormat getJavaNumberFormat(NumericFormat numFormatGlom) {
670 NumberFormat numFormatJava = NumberFormat.getInstance(locale);
671 if (numFormatGlom.getM_decimal_places_restricted()) {
672 int digits = safeLongToInt(numFormatGlom.getM_decimal_places());
673 numFormatJava.setMinimumFractionDigits(digits);
674 numFormatJava.setMaximumFractionDigits(digits);
676 numFormatJava.setGroupingUsed(numFormatGlom.getM_use_thousands_separator());
677 return numFormatJava;
681 * Converts a Gdk::Color (16-bits per channel) to an HTML colour (8-bits per channel) by discarding the least
682 * significant 8-bits in each channel.
684 private String convertGdkColorToHtmlColour(String gdkColor) {
685 if (gdkColor.length() == 13)
686 return gdkColor.substring(0, 3) + gdkColor.substring(5, 7) + gdkColor.substring(9, 11);
687 else if (gdkColor.length() == 7) {
688 // This shouldn't happen but let's deal with it if it does.
689 Log.warn("Expected a 13 character string but received a 7 character string. Returning received string.");
692 Log.error("Did not receive a 13 or 7 character string. Returning black HTML colour code.");
698 * This method converts a FieldFormatting.HorizontalAlignment to the equivalent ColumnInfo.HorizontalAlignment. The
699 * need for this comes from the fact that the GWT HorizontalAlignment classes can't be used with RPC and there's no
700 * easy way to use the java-libglom FieldFormatting.HorizontalAlignment enum with RPC. An enum identical to
701 * FieldFormatting.HorizontalAlignment is included in the ColumnInfo class.
703 private Formatting.HorizontalAlignment convertToGWTGlomHorizonalAlignment(
704 FieldFormatting.HorizontalAlignment alignment) {
706 case HORIZONTAL_ALIGNMENT_AUTO:
707 return Formatting.HorizontalAlignment.HORIZONTAL_ALIGNMENT_AUTO;
708 case HORIZONTAL_ALIGNMENT_LEFT:
709 return Formatting.HorizontalAlignment.HORIZONTAL_ALIGNMENT_LEFT;
710 case HORIZONTAL_ALIGNMENT_RIGHT:
711 return Formatting.HorizontalAlignment.HORIZONTAL_ALIGNMENT_RIGHT;
713 Log.error("Recieved an alignment that I don't know about: "
714 + FieldFormatting.HorizontalAlignment.class.getName() + "." + alignment.toString() + ". Returning "
715 + Formatting.HorizontalAlignment.HORIZONTAL_ALIGNMENT_RIGHT.toString() + ".");
716 return Formatting.HorizontalAlignment.HORIZONTAL_ALIGNMENT_RIGHT;
721 * This method converts a Field.glom_field_type to the equivalent ColumnInfo.FieldType. The need for this comes from
722 * the fact that the GWT FieldType classes can't be used with RPC and there's no easy way to use the java-libglom
723 * Field.glom_field_type enum with RPC. An enum identical to FieldFormatting.glom_field_type is included in the
726 private LayoutItemField.GlomFieldType convertToGWTGlomFieldType(Field.glom_field_type type) {
729 return LayoutItemField.GlomFieldType.TYPE_BOOLEAN;
731 return LayoutItemField.GlomFieldType.TYPE_DATE;
733 return LayoutItemField.GlomFieldType.TYPE_IMAGE;
735 return LayoutItemField.GlomFieldType.TYPE_NUMERIC;
737 return LayoutItemField.GlomFieldType.TYPE_TEXT;
739 return LayoutItemField.GlomFieldType.TYPE_TIME;
741 Log.info("Returning TYPE_INVALID.");
742 return LayoutItemField.GlomFieldType.TYPE_INVALID;
744 Log.error("Recieved a type that I don't know about: " + Field.glom_field_type.class.getName() + "."
745 + type.toString() + ". Returning " + LayoutItemField.GlomFieldType.TYPE_INVALID.toString() + ".");
746 return LayoutItemField.GlomFieldType.TYPE_INVALID;
753 * @see org.glom.web.client.OnlineGlomService#isAuthenticated(java.lang.String)
755 public boolean isAuthenticated(String documentTitle) {
756 return documents.get(documentTitle).isAuthenticated();
762 * @see org.glom.web.client.OnlineGlomService#checkAuthentication(java.lang.String, java.lang.String,
765 public boolean checkAuthentication(String documentTitle, String username, String password) {
766 ConfiguredDocument configuredDoc = documents.get(documentTitle);
767 boolean authenticated;
769 authenticated = checkAuthentication(documentTitle, configuredDoc.getCpds(), username, password);
770 } catch (SQLException e) {
771 Log.error(documentTitle, "Unknown SQL Error checking the database authentication.", e);
774 configuredDoc.setAuthenticated(authenticated);
775 return authenticated;
781 * @see org.glom.web.client.OnlineGlomService#getDefaultDetailsLayoutGroup(java.lang.String)
784 public ArrayList<LayoutGroup> getDefaultDetailsLayout(String documentTitle) {
785 GlomDocument glomDocument = getGlomDocument(documentTitle);
786 String tableName = glomDocument.getTableNames().get(glomDocument.getDefaultTableIndex());
787 return getDetailsLayout(documentTitle, tableName);
793 * @see org.glom.web.client.OnlineGlomService#getDetailsLayoutGroup(java.lang.String, java.lang.String)
795 public ArrayList<LayoutGroup> getDetailsLayout(String documentTitle, String tableName) {
796 ConfiguredDocument configuredDoc = documents.get(documentTitle);
797 Document document = configuredDoc.getDocument();
798 LayoutGroupVector layoutGroupVec = document.get_data_layout_groups("details", tableName);
800 ArrayList<LayoutGroup> layoutGroups = new ArrayList<LayoutGroup>();
801 for (int i = 0; i < layoutGroupVec.size(); i++) {
802 org.glom.libglom.LayoutGroup libglomLayoutGroup = layoutGroupVec.get(i);
804 if (libglomLayoutGroup == null)
807 layoutGroups.add(getLayoutGroup(documentTitle, tableName, libglomLayoutGroup));
813 * Gets a GWT-Glom LayoutGroup object for the specified libglom LayoutGroup object.
815 * @param libglomLayoutGroup
816 * <dt><b>Precondition:</b>
818 * libglomLayoutGroup must not be null
821 private LayoutGroup getLayoutGroup(String documentTitle, String tableName,
822 org.glom.libglom.LayoutGroup libglomLayoutGroup) {
823 LayoutGroup layoutGroup = new LayoutGroup();
824 layoutGroup.setColumnCount(safeLongToInt(libglomLayoutGroup.get_columns_count()));
826 // look at each child item
827 LayoutItemVector layoutItemsVec = libglomLayoutGroup.get_items();
828 for (int i = 0; i < layoutItemsVec.size(); i++) {
829 org.glom.libglom.LayoutItem libglomLayoutItem = layoutItemsVec.get(i);
831 // just a safety check
832 if (libglomLayoutItem == null)
835 org.glom.web.shared.layout.LayoutItem layoutItem = null;
836 org.glom.libglom.LayoutGroup group = org.glom.libglom.LayoutGroup.cast_dynamic(libglomLayoutItem);
838 // recurse into child groups
839 layoutItem = getLayoutGroup(documentTitle, tableName, group);
841 // create GWT-Glom LayoutItem types based on the the libglom type
842 // TODO add support for other LayoutItems (Text, Image, Button etc.)
843 LayoutItem_Field libglomLayoutField = LayoutItem_Field.cast_dynamic(libglomLayoutItem);
844 if (libglomLayoutField != null) {
845 LayoutItemField layoutItemField = new LayoutItemField();
846 layoutItemField.setType(convertToGWTGlomFieldType(libglomLayoutField.get_glom_type()));
847 Formatting formatting = new Formatting();
848 formatting.setHorizontalAlignment(convertToGWTGlomHorizonalAlignment(libglomLayoutField
849 .get_formatting_used_horizontal_alignment()));
850 layoutItemField.setFormatting(formatting);
851 layoutItem = layoutItemField;
853 Log.info(documentTitle, tableName,
854 "Ignoring unknown LayoutItem of type " + libglomLayoutItem.get_part_type_name() + ".");
860 layoutItem.setTitle(libglomLayoutItem.get_title_or_name());
861 layoutGroup.addItem(layoutItem);
867 public GlomField[] getDetailsData(String documentTitle, String tableName, String primaryKeyValue) {
869 ConfiguredDocument configuredDoc = documents.get(documentTitle);
870 Document document = configuredDoc.getDocument();
872 LayoutFieldVector fieldsToGet = getFieldsToShowForSQLQuery(document, tableName, "details");
874 if (fieldsToGet == null || fieldsToGet.size() <= 0) {
875 Log.warn(documentTitle, tableName, "Didn't find any fields to show. Returning null.");
879 // get primary key for the table to use in the SQL query
880 Field primaryKey = null;
881 FieldVector fieldsVec = document.get_table_fields(tableName);
882 for (int i = 0; i < safeLongToInt(fieldsVec.size()); i++) {
883 Field field = fieldsVec.get(i);
884 if (field.get_primary_key()) {
890 // send back an empty GlomField array if can't find a primaryKey Field
891 if (primaryKey == null) {
892 Log.error(documentTitle, tableName, "Couldn't find primary key in table. Returning null.");
896 ArrayList<GlomField[]> rowsList = new ArrayList<GlomField[]>();
897 Connection conn = null;
901 // Setup the JDBC driver and get the query.
902 ComboPooledDataSource cpds = configuredDoc.getCpds();
903 conn = cpds.getConnection();
904 st = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
905 String query = Glom.build_sql_select_with_key(tableName, fieldsToGet, primaryKey, primaryKeyValue);
906 rs = st.executeQuery(query);
908 // get the results from the ResultSet
909 // using 2 as a length parameter so we can log a warning if the result set is greater than one
910 rowsList = getData(documentTitle, tableName, 2, fieldsToGet, rs);
911 } catch (SQLException e) {
912 Log.error(documentTitle, tableName, "Error executing database query.", e);
913 // TODO: somehow notify user of problem
916 // cleanup everything that has been used
924 } catch (Exception e) {
925 Log.error(documentTitle, tableName,
926 "Error closing database resources. Subsequent database queries may not work.", e);
930 if (rowsList.size() == 0) {
931 Log.error(documentTitle, tableName, "The query returned an empty ResultSet. Returning null.");
933 } else if (rowsList.size() > 1) {
934 Log.warn(documentTitle, tableName,
935 "The query did not return a unique result. Returning the first result in the set.");
938 return rowsList.get(0);
943 * Gets a LayoutFieldVector to use when generating an SQL query.
945 private LayoutFieldVector getFieldsToShowForSQLQuery(Document document, String tableName, String layoutName) {
946 LayoutGroupVector layoutGroupVec = document.get_data_layout_groups(layoutName, tableName);
947 LayoutFieldVector layoutFieldVector = new LayoutFieldVector();
949 // special case for list layouts that don't have a defined layout group
950 if ("list".equals(layoutName) && layoutGroupVec.size() == 0) {
951 FieldVector fieldsVec = document.get_table_fields(tableName);
952 for (int i = 0; i < fieldsVec.size(); i++) {
953 Field field = fieldsVec.get(i);
954 LayoutItem_Field layoutItemField = new LayoutItem_Field();
955 layoutItemField.set_full_field_details(field);
956 layoutFieldVector.add(layoutItemField);
958 return layoutFieldVector;
961 // We will show the fields that the document says we should:
962 for (int i = 0; i < layoutGroupVec.size(); i++) {
963 org.glom.libglom.LayoutGroup layoutGroup = layoutGroupVec.get(i);
966 ArrayList<LayoutItem_Field> layoutItemsFields = getFieldsToShowForSQLQueryAddGroup(document, tableName,
968 for (LayoutItem_Field layoutItem_Field : layoutItemsFields) {
969 layoutFieldVector.add(layoutItem_Field);
972 return layoutFieldVector;
975 private ArrayList<LayoutItem_Field> getFieldsToShowForSQLQueryAddGroup(Document document, String tableName,
976 org.glom.libglom.LayoutGroup layoutGroup) {
978 ArrayList<LayoutItem_Field> layoutItemFields = new ArrayList<LayoutItem_Field>();
979 LayoutItemVector items = layoutGroup.get_items();
980 for (int i = 0; i < items.size(); i++) {
981 LayoutItem layoutItem = items.get(i);
983 LayoutItem_Field layoutItemField = LayoutItem_Field.cast_dynamic(layoutItem);
984 if (layoutItemField != null) {
985 // the layoutItem is a LayoutItem_Field
987 if (layoutItemField.get_has_relationship_name()) {
988 // layoutItemField is a field in a related table
989 fields = document.get_table_fields(layoutItemField.get_table_used(tableName));
991 // layoutItemField is a field in this table
992 fields = document.get_table_fields(tableName);
995 // set the layoutItemFeild with details from its Field in the document and
996 // add it to the list to be returned
997 for (int j = 0; j < fields.size(); j++) {
998 // check the names to see if they're the same
999 // this works because we're using the field list from the related table if necessary
1000 if (layoutItemField.get_name().equals(fields.get(j).get_name())) {
1001 Field field = fields.get(j);
1002 if (field != null) {
1003 layoutItemField.set_full_field_details(field);
1004 layoutItemFields.add(layoutItemField);
1006 Log.warn(document.get_database_title(), tableName,
1007 "LayoutItem_Field " + layoutItemField.get_layout_display_name()
1008 + " not found in document field list.");
1015 // the layoutItem is not a LayoutItem_Field
1016 org.glom.libglom.LayoutGroup subLayoutGroup = org.glom.libglom.LayoutGroup.cast_dynamic(layoutItem);
1017 if (subLayoutGroup != null) {
1018 // the layoutItem is a LayoutGroup
1019 LayoutItem_Portal layoutItemPortal = LayoutItem_Portal.cast_dynamic(layoutItem);
1020 if (layoutItemPortal == null) {
1021 // The subGroup is not a LayoutItem_Portal.
1022 // We're ignoring portals because they are filled by means of a separate SQL query.
1024 .addAll(getFieldsToShowForSQLQueryAddGroup(document, tableName, subLayoutGroup));
1029 return layoutItemFields;