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