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