Don't use Strings to hold primary key values.
[online-glom:gwt-glom.git] / src / main / java / org / glom / web / server / ConfiguredDocument.java
1 /*
2  * Copyright (C) 2011 Openismus GmbH
3  *
4  * This file is part of GWT-Glom.
5  *
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.
10  *
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
14  * for more details.
15  *
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/>.
18  */
19
20 package org.glom.web.server;
21
22 import java.beans.PropertyVetoException;
23 import java.sql.Connection;
24 import java.sql.SQLException;
25 import java.util.ArrayList;
26
27 import org.glom.libglom.Document;
28 import org.glom.libglom.Field;
29 import org.glom.libglom.FieldFormatting;
30 import org.glom.libglom.FieldVector;
31 import org.glom.libglom.Glom;
32 import org.glom.libglom.LayoutGroupVector;
33 import org.glom.libglom.LayoutItemVector;
34 import org.glom.libglom.LayoutItem_Field;
35 import org.glom.libglom.LayoutItem_Notebook;
36 import org.glom.libglom.LayoutItem_Portal;
37 import org.glom.libglom.NumericFormat;
38 import org.glom.libglom.Relationship;
39 import org.glom.libglom.StringVector;
40 import org.glom.web.server.database.DetailsDBAccess;
41 import org.glom.web.server.database.ListViewDBAccess;
42 import org.glom.web.server.database.RelatedListDBAccess;
43 import org.glom.web.server.database.RelatedListNavigation;
44 import org.glom.web.shared.DataItem;
45 import org.glom.web.shared.DocumentInfo;
46 import org.glom.web.shared.GlomNumericFormat;
47 import org.glom.web.shared.NavigationRecord;
48 import org.glom.web.shared.PrimaryKeyItem;
49 import org.glom.web.shared.layout.Formatting;
50 import org.glom.web.shared.layout.LayoutGroup;
51 import org.glom.web.shared.layout.LayoutItem;
52 import org.glom.web.shared.layout.LayoutItemField;
53 import org.glom.web.shared.layout.LayoutItemNotebook;
54 import org.glom.web.shared.layout.LayoutItemPortal;
55
56 import com.mchange.v2.c3p0.ComboPooledDataSource;
57
58 /**
59  * A class to hold configuration information for a given Glom document. This class is used to retrieve layout
60  * information from libglom and data from the underlying PostgreSQL database.
61  * 
62  * @author Ben Konrath <ben@bagu.org>
63  * 
64  */
65 final class ConfiguredDocument {
66
67         private Document document;
68         private ComboPooledDataSource cpds;
69         private boolean authenticated = false;
70         private String documentID;
71
72         @SuppressWarnings("unused")
73         private ConfiguredDocument() {
74                 // disable default constructor
75         }
76
77         ConfiguredDocument(Document document) throws PropertyVetoException {
78
79                 // load the jdbc driver
80                 cpds = new ComboPooledDataSource();
81
82                 // We don't support sqlite or self-hosting yet.
83                 if (document.get_hosting_mode() != Document.HostingMode.HOSTING_MODE_POSTGRES_CENTRAL) {
84                         Log.fatal("Error configuring the database connection." + " Only central PostgreSQL hosting is supported.");
85                         // FIXME: Throw exception?
86                 }
87
88                 try {
89                         cpds.setDriverClass("org.postgresql.Driver");
90                 } catch (PropertyVetoException e) {
91                         Log.fatal("Error loading the PostgreSQL JDBC driver."
92                                         + " Is the PostgreSQL JDBC jar available to the servlet?", e);
93                         throw e;
94                 }
95
96                 // setup the JDBC driver for the current glom document
97                 cpds.setJdbcUrl("jdbc:postgresql://" + document.get_connection_server() + ":" + document.get_connection_port()
98                                 + "/" + document.get_connection_database());
99
100                 this.document = document;
101         }
102
103         /**
104          * Sets the username and password for the database associated with the Glom document.
105          * 
106          * @return true if the username and password works, false otherwise
107          */
108         boolean setUsernameAndPassword(String username, String password) throws SQLException {
109                 cpds.setUser(username);
110                 cpds.setPassword(password);
111
112                 int acquireRetryAttempts = cpds.getAcquireRetryAttempts();
113                 cpds.setAcquireRetryAttempts(1);
114                 Connection conn = null;
115                 try {
116                         // FIXME find a better way to check authentication
117                         // it's possible that the connection could be failing for another reason
118                         conn = cpds.getConnection();
119                         authenticated = true;
120                 } catch (SQLException e) {
121                         Log.info(Utils.getFileName(document.get_file_uri()), e.getMessage());
122                         Log.info(Utils.getFileName(document.get_file_uri()),
123                                         "Connection Failed. Maybe the username or password is not correct.");
124                         authenticated = false;
125                 } finally {
126                         if (conn != null)
127                                 conn.close();
128                         cpds.setAcquireRetryAttempts(acquireRetryAttempts);
129                 }
130                 return authenticated;
131         }
132
133         Document getDocument() {
134                 return document;
135         }
136
137         ComboPooledDataSource getCpds() {
138                 return cpds;
139         }
140
141         boolean isAuthenticated() {
142                 return authenticated;
143         }
144
145         String getDocumentID() {
146                 return documentID;
147         }
148
149         void setDocumentID(String documentID) {
150                 this.documentID = documentID;
151         }
152
153         /**
154          * @return
155          */
156         DocumentInfo getDocumentInfo() {
157                 DocumentInfo documentInfo = new DocumentInfo();
158
159                 // get arrays of table names and titles, and find the default table index
160                 StringVector tablesVec = document.get_table_names();
161
162                 int numTables = Utils.safeLongToInt(tablesVec.size());
163                 // we don't know how many tables will be hidden so we'll use half of the number of tables for the default size
164                 // of the ArrayList
165                 ArrayList<String> tableNames = new ArrayList<String>(numTables / 2);
166                 ArrayList<String> tableTitles = new ArrayList<String>(numTables / 2);
167                 boolean foundDefaultTable = false;
168                 int visibleIndex = 0;
169                 for (int i = 0; i < numTables; i++) {
170                         String tableName = tablesVec.get(i);
171                         if (!document.get_table_is_hidden(tableName)) {
172                                 tableNames.add(tableName);
173                                 // JNI is "expensive", the comparison will only be called if we haven't already found the default table
174                                 if (!foundDefaultTable && tableName.equals(document.get_default_table())) {
175                                         documentInfo.setDefaultTableIndex(visibleIndex);
176                                         foundDefaultTable = true;
177                                 }
178                                 tableTitles.add(document.get_table_title(tableName));
179                                 visibleIndex++;
180                         }
181                 }
182
183                 // set everything we need
184                 documentInfo.setTableNames(tableNames);
185                 documentInfo.setTableTitles(tableTitles);
186                 documentInfo.setTitle(document.get_database_title());
187
188                 return documentInfo;
189         }
190
191         /*
192          * Gets the layout group for the list view using the defined layout list in the document or the table fields if
193          * there's no defined layout group for the list view.
194          */
195         private org.glom.libglom.LayoutGroup getValidListViewLayoutGroup(String tableName) {
196
197                 LayoutGroupVector layoutGroupVec = document.get_data_layout_groups("list", tableName);
198
199                 int listViewLayoutGroupSize = Utils.safeLongToInt(layoutGroupVec.size());
200                 org.glom.libglom.LayoutGroup libglomLayoutGroup = null;
201                 if (listViewLayoutGroupSize > 0) {
202                         // a list layout group is defined; we can use the first group as the list
203                         if (listViewLayoutGroupSize > 1)
204                                 Log.warn(documentID, tableName, "The size of the list layout group is greater than 1. "
205                                                 + "Attempting to use the first item for the layout list view.");
206
207                         libglomLayoutGroup = layoutGroupVec.get(0);
208                 } else {
209                         // a list layout group is *not* defined; we are going make a libglom layout group from the list of fields
210                         Log.info(documentID, tableName,
211                                         "A list layout is not defined for this table. Displaying a list layout based on the field list.");
212
213                         FieldVector fieldsVec = document.get_table_fields(tableName);
214                         libglomLayoutGroup = new org.glom.libglom.LayoutGroup();
215                         for (int i = 0; i < fieldsVec.size(); i++) {
216                                 Field field = fieldsVec.get(i);
217                                 LayoutItem_Field layoutItemField = new LayoutItem_Field();
218                                 layoutItemField.set_full_field_details(field);
219                                 libglomLayoutGroup.add_item(layoutItemField);
220                         }
221                 }
222
223                 return libglomLayoutGroup;
224         }
225
226         ArrayList<DataItem[]> getListViewData(String tableName, int start, int length, boolean useSortClause,
227                         int sortColumnIndex, boolean isAscending) {
228                 // Validate the table name.
229                 tableName = getTableNameToUse(tableName);
230
231                 // Get the libglom LayoutGroup that represents the list view.
232                 org.glom.libglom.LayoutGroup libglomLayoutGroup = getValidListViewLayoutGroup(tableName);
233
234                 // Create a database access object for the list view.
235                 ListViewDBAccess listViewDBAccess = new ListViewDBAccess(document, documentID, cpds, tableName,
236                                 libglomLayoutGroup);
237
238                 // Return the data.
239                 return listViewDBAccess.getData(start, length, useSortClause, sortColumnIndex, isAscending);
240         }
241
242         DataItem[] getDetailsData(String tableName, PrimaryKeyItem primaryKeyValue) {
243                 // Validate the table name.
244                 tableName = getTableNameToUse(tableName);
245
246                 DetailsDBAccess detailsDBAccess = new DetailsDBAccess(document, documentID, cpds, tableName);
247
248                 return detailsDBAccess.getData(primaryKeyValue);
249         }
250
251         ArrayList<DataItem[]> getRelatedListData(String tableName, String relationshipName, PrimaryKeyItem foreignKeyValue,
252                         int start, int length, boolean useSortClause, int sortColumnIndex, boolean isAscending) {
253                 // Validate the table name.
254                 tableName = getTableNameToUse(tableName);
255
256                 // Create a database access object for the related list
257                 RelatedListDBAccess relatedListDBAccess = new RelatedListDBAccess(document, documentID, cpds, tableName,
258                                 relationshipName);
259
260                 // Return the data
261                 return relatedListDBAccess.getData(start, length, foreignKeyValue, useSortClause, sortColumnIndex, isAscending);
262         }
263
264         ArrayList<LayoutGroup> getDetailsLayoutGroup(String tableName) {
265                 // Validate the table name.
266                 tableName = getTableNameToUse(tableName);
267
268                 // Get the details layout group information for each LayoutGroup in the LayoutGroupVector
269                 LayoutGroupVector layoutGroupVec = document.get_data_layout_groups("details", tableName);
270                 ArrayList<LayoutGroup> layoutGroups = new ArrayList<LayoutGroup>();
271                 for (int i = 0; i < layoutGroupVec.size(); i++) {
272                         org.glom.libglom.LayoutGroup libglomLayoutGroup = layoutGroupVec.get(i);
273
274                         // satisfy the precondition of getDetailsLayoutGroup(String, org.glom.libglom.LayoutGroup)
275                         if (libglomLayoutGroup == null)
276                                 continue;
277
278                         layoutGroups.add(getDetailsLayoutGroup(tableName, libglomLayoutGroup));
279                 }
280
281                 return layoutGroups;
282         }
283
284         LayoutGroup getListViewLayoutGroup(String tableName) {
285                 // Validate the table name.
286                 tableName = getTableNameToUse(tableName);
287
288                 org.glom.libglom.LayoutGroup libglomLayoutGroup = getValidListViewLayoutGroup(tableName);
289
290                 return getListLayoutGroup(tableName, libglomLayoutGroup);
291         }
292
293         /*
294          * Gets the expected row count for a related list.
295          */
296         int getRelatedListRowCount(String tableName, String relationshipName, PrimaryKeyItem foreignKeyValue) {
297                 // Validate the table name.
298                 tableName = getTableNameToUse(tableName);
299
300                 // Create a database access object for the related list
301                 RelatedListDBAccess relatedListDBAccess = new RelatedListDBAccess(document, documentID, cpds, tableName,
302                                 relationshipName);
303
304                 // Return the row count
305                 return relatedListDBAccess.getExpectedResultSize(foreignKeyValue);
306         }
307
308         NavigationRecord getSuitableRecordToViewDetails(String tableName, String relationshipName,
309                         PrimaryKeyItem primaryKeyValue) {
310                 // Validate the table name.
311                 tableName = getTableNameToUse(tableName);
312
313                 RelatedListNavigation relatedListNavigation = new RelatedListNavigation(document, documentID, cpds, tableName,
314                                 relationshipName);
315
316                 return relatedListNavigation.getNavigationRecord(primaryKeyValue);
317         }
318
319         /*
320          * Gets a LayoutGroup DTO for the given table name and libglom LayoutGroup. This method can be used for the main
321          * list view table and for the related list table.
322          */
323         private LayoutGroup getListLayoutGroup(String tableName, org.glom.libglom.LayoutGroup libglomLayoutGroup) {
324                 LayoutGroup layoutGroup = new LayoutGroup();
325                 int primaryKeyIndex = -1;
326
327                 // look at each child item
328                 LayoutItemVector layoutItemsVec = libglomLayoutGroup.get_items();
329                 int numItems = Utils.safeLongToInt(layoutItemsVec.size());
330                 for (int i = 0; i < numItems; i++) {
331                         org.glom.libglom.LayoutItem libglomLayoutItem = layoutItemsVec.get(i);
332
333                         // TODO add support for other LayoutItems (Text, Image, Button etc.)
334                         LayoutItem_Field libglomLayoutItemField = LayoutItem_Field.cast_dynamic(libglomLayoutItem);
335                         if (libglomLayoutItemField != null) {
336                                 layoutGroup.addItem(convertToGWTGlomLayoutItemField(libglomLayoutItemField, true));
337                                 Field field = libglomLayoutItemField.get_full_field_details();
338                                 if (field.get_primary_key())
339                                         primaryKeyIndex = i;
340                         } else {
341                                 Log.info(documentID, tableName,
342                                                 "Ignoring unknown list LayoutItem of type " + libglomLayoutItem.get_part_type_name() + ".");
343                                 continue;
344                         }
345                 }
346
347                 // set the expected result size for list view tables
348                 LayoutItem_Portal libglomLayoutItemPortal = LayoutItem_Portal.cast_dynamic(libglomLayoutGroup);
349                 if (libglomLayoutItemPortal == null) {
350                         // libglomLayoutGroup is a list view
351                         ListViewDBAccess listViewDBAccess = new ListViewDBAccess(document, documentID, cpds, tableName,
352                                         libglomLayoutGroup);
353                         layoutGroup.setExpectedResultSize(listViewDBAccess.getExpectedResultSize());
354                 }
355
356                 // Set the primary key index for the table
357                 if (primaryKeyIndex < 0) {
358                         // Add a LayoutItemField for the primary key to the end of the item list in the LayoutGroup because it
359                         // doesn't already contain a primary key.
360                         Field primaryKey = null;
361                         FieldVector fieldsVec = document.get_table_fields(tableName);
362                         for (int i = 0; i < Utils.safeLongToInt(fieldsVec.size()); i++) {
363                                 Field field = fieldsVec.get(i);
364                                 if (field.get_primary_key()) {
365                                         primaryKey = field;
366                                         break;
367                                 }
368                         }
369                         if (primaryKey != null) {
370                                 LayoutItem_Field libglomLayoutItemField = new LayoutItem_Field();
371                                 libglomLayoutItemField.set_full_field_details(primaryKey);
372                                 layoutGroup.addItem(convertToGWTGlomLayoutItemField(libglomLayoutItemField, false));
373                                 layoutGroup.setPrimaryKeyIndex(layoutGroup.getItems().size() - 1);
374                                 layoutGroup.setHiddenPrimaryKey(true);
375                         } else {
376                                 Log.error(document.get_database_title(), tableName,
377                                                 "A primary key was not found in the FieldVector for this table. Navigation buttons will not work.");
378                         }
379
380                 } else {
381                         layoutGroup.setPrimaryKeyIndex(primaryKeyIndex);
382                 }
383
384                 layoutGroup.setTableName(tableName);
385
386                 return layoutGroup;
387         }
388
389         /*
390          * Gets a recursively defined Details LayoutGroup DTO for the specified libglom LayoutGroup object. This is used for
391          * getting layout information for the details view.
392          * 
393          * @param documentID Glom document identifier
394          * 
395          * @param tableName table name in the specified Glom document
396          * 
397          * @param libglomLayoutGroup libglom LayoutGroup to convert
398          * 
399          * @precondition libglomLayoutGroup must not be null
400          * 
401          * @return {@link LayoutGroup} object that represents the layout for the specified {@link
402          * org.glom.libglom.LayoutGroup}
403          */
404         private LayoutGroup getDetailsLayoutGroup(String tableName, org.glom.libglom.LayoutGroup libglomLayoutGroup) {
405                 LayoutGroup layoutGroup = new LayoutGroup();
406                 layoutGroup.setColumnCount(Utils.safeLongToInt(libglomLayoutGroup.get_columns_count()));
407                 String layoutGroupTitle = libglomLayoutGroup.get_title();
408                 if (layoutGroupTitle.isEmpty())
409                         layoutGroup.setName(libglomLayoutGroup.get_name());
410                 else
411                         layoutGroup.setTitle(layoutGroupTitle);
412
413                 // look at each child item
414                 LayoutItemVector layoutItemsVec = libglomLayoutGroup.get_items();
415                 for (int i = 0; i < layoutItemsVec.size(); i++) {
416                         org.glom.libglom.LayoutItem libglomLayoutItem = layoutItemsVec.get(i);
417
418                         // just a safety check
419                         if (libglomLayoutItem == null)
420                                 continue;
421
422                         org.glom.web.shared.layout.LayoutItem layoutItem = null;
423                         org.glom.libglom.LayoutGroup group = org.glom.libglom.LayoutGroup.cast_dynamic(libglomLayoutItem);
424                         if (group != null) {
425                                 // libglomLayoutItem is a LayoutGroup
426                                 LayoutItem_Portal libglomLayoutItemPortal = LayoutItem_Portal.cast_dynamic(group);
427                                 if (libglomLayoutItemPortal != null) {
428                                         // group is a LayoutItem_Portal
429                                         LayoutItemPortal layoutItemPortal = new LayoutItemPortal();
430                                         Relationship relationship = libglomLayoutItemPortal.get_relationship();
431                                         if (relationship != null) {
432                                                 layoutItemPortal.setNavigationType(convertToGWTGlomNavigationType(libglomLayoutItemPortal
433                                                                 .get_navigation_type()));
434
435                                                 layoutItemPortal.setTitle(libglomLayoutItemPortal.get_title_used("")); // parent title not
436                                                                                                                                                                                                 // relevant
437                                                 LayoutGroup tempLayoutGroup = getListLayoutGroup(tableName, libglomLayoutItemPortal);
438                                                 for (org.glom.web.shared.layout.LayoutItem item : tempLayoutGroup.getItems()) {
439                                                         // TODO EDITING If the relationship does not allow editing, then mark all these fields as
440                                                         // non-editable. Check relationship.get_allow_edit() to see if it's editable.
441                                                         layoutItemPortal.addItem(item);
442                                                 }
443                                                 layoutItemPortal.setPrimaryKeyIndex(tempLayoutGroup.getPrimaryKeyIndex());
444                                                 layoutItemPortal.setHiddenPrimaryKey(tempLayoutGroup.hasHiddenPrimaryKey());
445                                                 layoutItemPortal.setName(libglomLayoutItemPortal.get_relationship_name_used());
446                                                 layoutItemPortal.setTableName(relationship.get_from_table());
447                                                 layoutItemPortal.setFromField(relationship.get_from_field());
448
449                                                 // Set whether or not the related list will need to show the navigation buttons.
450                                                 // This was ported from Glom: Box_Data_Portal::get_has_suitable_record_to_view_details()
451                                                 StringBuffer navigationTableName = new StringBuffer();
452                                                 LayoutItem_Field navigationRelationship = new LayoutItem_Field(); // Ignored.
453                                                 libglomLayoutItemPortal.get_suitable_table_to_view_details(navigationTableName,
454                                                                 navigationRelationship, document);
455                                                 layoutItemPortal.setAddNavigation(!(navigationTableName.toString().isEmpty()));
456                                         }
457
458                                         // Note: empty layoutItemPortal used if relationship is null
459                                         layoutItem = layoutItemPortal;
460
461                                 } else {
462                                         // libglomLayoutItem is a LayoutGroup
463                                         LayoutItem_Notebook libglomLayoutItemNotebook = LayoutItem_Notebook.cast_dynamic(group);
464                                         if (libglomLayoutItemNotebook != null) {
465                                                 // group is a LayoutItem_Notebook
466                                                 LayoutGroup tempLayoutGroup = getDetailsLayoutGroup(tableName, libglomLayoutItemNotebook);
467                                                 LayoutItemNotebook layoutItemNotebook = new LayoutItemNotebook();
468                                                 for (LayoutItem item : tempLayoutGroup.getItems()) {
469                                                         layoutItemNotebook.addItem(item);
470                                                 }
471                                                 layoutItemNotebook.setName(tableName);
472                                                 layoutItem = layoutItemNotebook;
473                                         } else {
474                                                 // group is *not* a LayoutItem_Portal or a LayoutItem_Notebook
475                                                 // recurse into child groups
476                                                 layoutItem = getDetailsLayoutGroup(tableName, group);
477                                         }
478                                 }
479                         } else {
480                                 // libglomLayoutItem is *not* a LayoutGroup
481                                 // create LayoutItem DTOs based on the the libglom type
482                                 // TODO add support for other LayoutItems (Text, Image, Button etc.)
483                                 LayoutItem_Field libglomLayoutItemField = LayoutItem_Field.cast_dynamic(libglomLayoutItem);
484                                 if (libglomLayoutItemField != null) {
485
486                                         LayoutItemField layoutItemField = convertToGWTGlomLayoutItemField(libglomLayoutItemField, true);
487
488                                         // Set the full field details with updated field details from the document.
489                                         libglomLayoutItemField.set_full_field_details(document.get_field(
490                                                         libglomLayoutItemField.get_table_used(tableName), libglomLayoutItemField.get_name()));
491
492                                         // Determine if the field should have a navigation button and set this in the DTO.
493                                         Relationship fieldUsedInRelationshipToOne = new Relationship();
494                                         boolean addNavigation = Glom.layout_field_should_have_navigation(tableName, libglomLayoutItemField,
495                                                         document, fieldUsedInRelationshipToOne);
496                                         layoutItemField.setAddNavigation(addNavigation);
497
498                                         // Set the the name of the table to navigate to if navigation should be enabled.
499                                         if (addNavigation) {
500                                                 // It's not possible to directly check if fieldUsedInRelationshipToOne is
501                                                 // null because of the way that the glom_sharedptr macro works. This workaround accomplishes the
502                                                 // same task.
503                                                 String tableNameUsed;
504                                                 try {
505                                                         Relationship temp = new Relationship();
506                                                         temp.equals(fieldUsedInRelationshipToOne); // this will throw an NPE if
507                                                                                                                                                 // fieldUsedInRelationshipToOne is null
508                                                         // fieldUsedInRelationshipToOne is *not* null
509                                                         tableNameUsed = fieldUsedInRelationshipToOne.get_to_table();
510
511                                                 } catch (NullPointerException e) {
512                                                         // fieldUsedInRelationshipToOne is null
513                                                         tableNameUsed = libglomLayoutItemField.get_table_used(tableName);
514                                                 }
515
516                                                 // Set the navigation table name only if it's not different than the current table name.
517                                                 if (!tableName.equals(tableNameUsed)) {
518                                                         layoutItemField.setNavigationTableName(tableNameUsed);
519                                                 }
520                                         }
521
522                                         layoutItem = layoutItemField;
523
524                                 } else {
525                                         Log.info(documentID, tableName,
526                                                         "Ignoring unknown details LayoutItem of type " + libglomLayoutItem.get_part_type_name()
527                                                                         + ".");
528                                         continue;
529                                 }
530                         }
531
532                         layoutGroup.addItem(layoutItem);
533                 }
534
535                 return layoutGroup;
536         }
537
538         private GlomNumericFormat convertNumbericFormat(NumericFormat libglomNumericFormat) {
539                 GlomNumericFormat gnf = new GlomNumericFormat();
540                 gnf.setUseAltForegroundColourForNegatives(libglomNumericFormat.getM_alt_foreground_color_for_negatives());
541                 gnf.setCurrencyCode(libglomNumericFormat.getM_currency_symbol());
542                 gnf.setDecimalPlaces(Utils.safeLongToInt(libglomNumericFormat.getM_decimal_places()));
543                 gnf.setDecimalPlacesRestricted(libglomNumericFormat.getM_decimal_places_restricted());
544                 gnf.setUseThousandsSeparator(libglomNumericFormat.getM_use_thousands_separator());
545                 return gnf;
546         }
547
548         private Formatting convertFormatting(FieldFormatting libglomFormatting) {
549                 Formatting formatting = new Formatting();
550
551                 // horizontal alignment
552                 Formatting.HorizontalAlignment horizontalAlignment;
553                 switch (libglomFormatting.get_horizontal_alignment()) {
554                 case HORIZONTAL_ALIGNMENT_LEFT:
555                         horizontalAlignment = Formatting.HorizontalAlignment.HORIZONTAL_ALIGNMENT_LEFT;
556                 case HORIZONTAL_ALIGNMENT_RIGHT:
557                         horizontalAlignment = Formatting.HorizontalAlignment.HORIZONTAL_ALIGNMENT_RIGHT;
558                 case HORIZONTAL_ALIGNMENT_AUTO:
559                 default:
560                         horizontalAlignment = Formatting.HorizontalAlignment.HORIZONTAL_ALIGNMENT_AUTO;
561                 }
562                 formatting.setHorizontalAlignment(horizontalAlignment);
563
564                 // text colour
565                 String foregroundColour = libglomFormatting.get_text_format_color_foreground();
566                 if (foregroundColour != null && !foregroundColour.isEmpty())
567                         formatting.setTextFormatColourForeground(convertGdkColorToHtmlColour(foregroundColour));
568                 String backgroundColour = libglomFormatting.get_text_format_color_background();
569                 if (backgroundColour != null && !backgroundColour.isEmpty())
570                         formatting.setTextFormatColourBackground(convertGdkColorToHtmlColour(backgroundColour));
571
572                 // multiline
573                 if (libglomFormatting.get_text_format_multiline()) {
574                         formatting.setTextFormatMultilineHeightLines(Utils.safeLongToInt(libglomFormatting
575                                         .get_text_format_multiline_height_lines()));
576                 }
577
578                 return formatting;
579         }
580
581         private LayoutItemField convertToGWTGlomLayoutItemField(LayoutItem_Field libglomLayoutItemField,
582                         boolean includeFormatting) {
583                 LayoutItemField layoutItemField = new LayoutItemField();
584
585                 // set type
586                 layoutItemField.setType(convertToGWTGlomFieldType(libglomLayoutItemField.get_glom_type()));
587
588                 // set title and name
589                 layoutItemField.setTitle(libglomLayoutItemField.get_title_or_name());
590                 layoutItemField.setName(libglomLayoutItemField.get_name());
591
592                 if (includeFormatting) {
593                         FieldFormatting glomFormatting = libglomLayoutItemField.get_formatting_used();
594                         Formatting formatting = convertFormatting(glomFormatting);
595
596                         // create a GlomNumericFormat DTO for numeric values
597                         if (libglomLayoutItemField.get_glom_type() == org.glom.libglom.Field.glom_field_type.TYPE_NUMERIC) {
598                                 formatting.setGlomNumericFormat(convertNumbericFormat(glomFormatting.getM_numeric_format()));
599                         }
600                         layoutItemField.setFormatting(formatting);
601                 }
602
603                 return layoutItemField;
604         }
605
606         /*
607          * This method converts a Field.glom_field_type to the equivalent ColumnInfo.FieldType. The need for this comes from
608          * the fact that the GWT FieldType classes can't be used with RPC and there's no easy way to use the java-libglom
609          * Field.glom_field_type enum with RPC. An enum identical to FieldFormatting.glom_field_type is included in the
610          * ColumnInfo class.
611          */
612         private LayoutItemField.GlomFieldType convertToGWTGlomFieldType(Field.glom_field_type type) {
613                 switch (type) {
614                 case TYPE_BOOLEAN:
615                         return LayoutItemField.GlomFieldType.TYPE_BOOLEAN;
616                 case TYPE_DATE:
617                         return LayoutItemField.GlomFieldType.TYPE_DATE;
618                 case TYPE_IMAGE:
619                         return LayoutItemField.GlomFieldType.TYPE_IMAGE;
620                 case TYPE_NUMERIC:
621                         return LayoutItemField.GlomFieldType.TYPE_NUMERIC;
622                 case TYPE_TEXT:
623                         return LayoutItemField.GlomFieldType.TYPE_TEXT;
624                 case TYPE_TIME:
625                         return LayoutItemField.GlomFieldType.TYPE_TIME;
626                 case TYPE_INVALID:
627                         Log.info("Returning TYPE_INVALID.");
628                         return LayoutItemField.GlomFieldType.TYPE_INVALID;
629                 default:
630                         Log.error("Recieved a type that I don't know about: " + Field.glom_field_type.class.getName() + "."
631                                         + type.toString() + ". Returning " + LayoutItemField.GlomFieldType.TYPE_INVALID.toString() + ".");
632                         return LayoutItemField.GlomFieldType.TYPE_INVALID;
633                 }
634         }
635
636         /*
637          * Converts a Gdk::Color (16-bits per channel) to an HTML colour (8-bits per channel) by discarding the least
638          * significant 8-bits in each channel.
639          */
640         private String convertGdkColorToHtmlColour(String gdkColor) {
641                 if (gdkColor.length() == 13)
642                         return gdkColor.substring(0, 3) + gdkColor.substring(5, 7) + gdkColor.substring(9, 11);
643                 else if (gdkColor.length() == 7) {
644                         // This shouldn't happen but let's deal with it if it does.
645                         Log.warn(documentID,
646                                         "Expected a 13 character string but received a 7 character string. Returning received string.");
647                         return gdkColor;
648                 } else {
649                         Log.error("Did not receive a 13 or 7 character string. Returning black HTML colour code.");
650                         return "#000000";
651                 }
652         }
653
654         /*
655          * This method converts a LayoutItem_Portal.navigation_type from java-libglom to the equivalent
656          * LayoutItemPortal.NavigationType from Online Glom. This conversion is required because the LayoutItem_Portal class
657          * from java-libglom can't be used with GWT-RPC. An enum identical to LayoutItem_Portal.navigation_type from
658          * java-libglom is included in the LayoutItemPortal data transfer object.
659          */
660         private LayoutItemPortal.NavigationType convertToGWTGlomNavigationType(
661                         LayoutItem_Portal.navigation_type navigationType) {
662                 switch (navigationType) {
663                 case NAVIGATION_NONE:
664                         return LayoutItemPortal.NavigationType.NAVIGATION_NONE;
665                 case NAVIGATION_AUTOMATIC:
666                         return LayoutItemPortal.NavigationType.NAVIGATION_AUTOMATIC;
667                 case NAVIGATION_SPECIFIC:
668                         return LayoutItemPortal.NavigationType.NAVIGATION_SPECIFIC;
669                 default:
670                         Log.error("Recieved an unknown NavigationType: " + LayoutItem_Portal.navigation_type.class.getName() + "."
671                                         + navigationType.toString() + ". Returning " + LayoutItemPortal.NavigationType.NAVIGATION_AUTOMATIC
672                                         + ".");
673                         return LayoutItemPortal.NavigationType.NAVIGATION_AUTOMATIC;
674                 }
675         }
676
677         /**
678          * Gets the table name to use when accessing the database and the document. This method guards against SQL injection
679          * attacks by returning the default table if the requested table is not in the database or if the table name has not
680          * been set.
681          * 
682          * @param tableName
683          *            The table name to validate.
684          * @return The table name to use.
685          */
686         private String getTableNameToUse(String tableName) {
687                 if (tableName == null || tableName.isEmpty() || !document.get_table_is_known(tableName)) {
688                         return document.get_default_table();
689                 }
690                 return tableName;
691         }
692
693 }