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