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