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