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