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