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