Replace deprecated DOM.setElementAttribute().
[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.util.ArrayList;
24 import java.util.Hashtable;
25 import java.util.List;
26 import java.util.Locale;
27
28 import org.apache.commons.lang3.StringUtils;
29 import org.glom.web.server.database.DetailsDBAccess;
30 import org.glom.web.server.database.ListViewDBAccess;
31 import org.glom.web.server.database.RelatedListDBAccess;
32 import org.glom.web.server.database.RelatedListNavigation;
33 import org.glom.web.server.libglom.Document;
34 import org.glom.web.shared.DataItem;
35 import org.glom.web.shared.DocumentInfo;
36 import org.glom.web.shared.NavigationRecord;
37 import org.glom.web.shared.Reports;
38 import org.glom.web.shared.TypedDataItem;
39 import org.glom.web.shared.libglom.CustomTitle;
40 import org.glom.web.shared.libglom.Field;
41 import org.glom.web.shared.libglom.Relationship;
42 import org.glom.web.shared.libglom.Report;
43 import org.glom.web.shared.libglom.Translatable;
44 import org.glom.web.shared.libglom.layout.LayoutGroup;
45 import org.glom.web.shared.libglom.layout.LayoutItem;
46 import org.glom.web.shared.libglom.layout.LayoutItemField;
47 import org.glom.web.shared.libglom.layout.LayoutItemImage;
48 import org.glom.web.shared.libglom.layout.LayoutItemPortal;
49 import org.glom.web.shared.libglom.layout.UsesRelationship;
50
51 import com.mchange.v2.c3p0.ComboPooledDataSource;
52
53 /**
54  * A class to hold configuration information for a given Glom document. This class retrieves layout information from
55  * libglom and data from the underlying PostgreSQL database.
56  */
57 final class ConfiguredDocument {
58
59         private Document document;
60         private String documentID = "";
61         private String defaultLocaleID = "";
62         
63         /** Credentials for the document as specified in the config file,
64          * so the user does not need to specify them.
65          * 
66          * @param docCredentials
67          */
68         private Credentials credentials;
69
70         private static class LayoutLocaleMap extends Hashtable<String, List<LayoutGroup>> {
71                 private static final long serialVersionUID = 6542501521673767267L;
72         };
73
74         private static class TableLayouts {
75                 public LayoutLocaleMap listLayouts;
76                 public LayoutLocaleMap detailsLayouts;
77         }
78
79         private static class TableLayoutsForLocale extends Hashtable<String, TableLayouts> {
80                 private static final long serialVersionUID = -1947929931925049013L;
81
82                 public LayoutGroup getListLayout(final String tableName, final String locale) {
83                         final List<LayoutGroup> groups = getLayout(tableName, locale, false);
84                         if (groups == null) {
85                                 return null;
86                         }
87
88                         if (groups.isEmpty()) {
89                                 return null;
90                         }
91
92                         return groups.get(0);
93                 }
94
95                 public List<LayoutGroup> getDetailsLayout(final String tableName, final String locale) {
96                         return getLayout(tableName, locale, true);
97                 }
98
99                 public void setListLayout(final String tableName, final String locale, final LayoutGroup layout) {
100                         final List<LayoutGroup> list = new ArrayList<LayoutGroup>();
101                         list.add(layout);
102                         setLayout(tableName, locale, list, false);
103                 }
104
105                 public void setDetailsLayout(final String tableName, final String locale, final List<LayoutGroup> layout) {
106                         setLayout(tableName, locale, layout, true);
107                 }
108
109                 private List<LayoutGroup> getLayout(final String tableName, final String locale, final boolean details) {
110                         final LayoutLocaleMap map = getMap(tableName, details);
111
112                         if (map == null) {
113                                 return null;
114                         }
115
116                         return map.get(locale);
117                 }
118
119                 private LayoutLocaleMap getMap(final String tableName, final boolean details) {
120                         final TableLayouts tableLayouts = get(tableName);
121                         if (tableLayouts == null) {
122                                 return null;
123                         }
124
125                         LayoutLocaleMap map = null;
126                         if (details) {
127                                 map = tableLayouts.detailsLayouts;
128                         } else {
129                                 map = tableLayouts.listLayouts;
130                         }
131
132                         return map;
133                 }
134
135                 private LayoutLocaleMap getMapWithAdd(final String tableName, final boolean details) {
136                         TableLayouts tableLayouts = get(tableName);
137                         if (tableLayouts == null) {
138                                 tableLayouts = new TableLayouts();
139                                 put(tableName, tableLayouts);
140                         }
141
142                         LayoutLocaleMap map = null;
143                         if (details) {
144                                 if (tableLayouts.detailsLayouts == null) {
145                                         tableLayouts.detailsLayouts = new LayoutLocaleMap();
146                                 }
147
148                                 map = tableLayouts.detailsLayouts;
149                         } else {
150                                 if (tableLayouts.listLayouts == null) {
151                                         tableLayouts.listLayouts = new LayoutLocaleMap();
152                                 }
153
154                                 map = tableLayouts.listLayouts;
155                         }
156
157                         return map;
158                 }
159
160                 private void setLayout(final String tableName, final String locale, final List<LayoutGroup> layout,
161                                 final boolean details) {
162                         final LayoutLocaleMap map = getMapWithAdd(tableName, details);
163                         if (map != null) {
164                                 map.put(locale, layout);
165                         }
166                 }
167         }
168
169         private final TableLayoutsForLocale mapTableLayouts = new TableLayoutsForLocale();
170
171         @SuppressWarnings("unused")
172         private ConfiguredDocument() {
173                 // disable default constructor
174         }
175
176         ConfiguredDocument(final Document document) throws PropertyVetoException {
177                 this.document = document;
178         }
179
180         Document getDocument() {
181                 return document;
182         }
183
184         String getDocumentID() {
185                 return documentID;
186         }
187
188         void setDocumentID(final String documentID) {
189                 this.documentID = documentID;
190         }
191
192         String getDefaultLocaleID() {
193                 return defaultLocaleID;
194         }
195
196         void setDefaultLocaleID(final String localeID) {
197                 this.defaultLocaleID = localeID;
198         }
199
200         /**
201          * @return
202          */
203         DocumentInfo getDocumentInfo(final String localeID) {
204                 final DocumentInfo documentInfo = new DocumentInfo();
205
206                 // get arrays of table names and titles, and find the default table index
207                 final List<String> tablesVec = document.getTableNames();
208
209                 final int numTables = Utils.safeLongToInt(tablesVec.size());
210                 // we don't know how many tables will be hidden so we'll use half of the number of tables for the default size
211                 // of the ArrayList
212                 final ArrayList<String> tableNames = new ArrayList<String>(numTables / 2);
213                 final ArrayList<String> tableTitles = new ArrayList<String>(numTables / 2);
214                 boolean foundDefaultTable = false;
215                 int visibleIndex = 0;
216                 for (int i = 0; i < numTables; i++) {
217                         final String tableName = tablesVec.get(i);
218                         if (!document.getTableIsHidden(tableName)) {
219                                 tableNames.add(tableName);
220
221                                 //The comparison will only be called if we haven't already found the default table
222                                 if (!foundDefaultTable && tableName.equals(document.getDefaultTable())) {
223                                         documentInfo.setDefaultTableIndex(visibleIndex);
224                                         foundDefaultTable = true;
225                                 }
226                                 tableTitles.add(document.getTableTitle(tableName, localeID));
227                                 visibleIndex++;
228                         }
229                 }
230
231                 // set everything we need
232                 documentInfo.setTableNames(tableNames);
233                 documentInfo.setTableTitles(tableTitles);
234                 documentInfo.setTitle(document.getDatabaseTitle(localeID));
235
236                 // Fetch arrays of locale IDs and titles:
237                 final List<String> localesVec = document.getTranslationAvailableLocales();
238                 final int numLocales = Utils.safeLongToInt(localesVec.size());
239                 final ArrayList<String> localeIDs = new ArrayList<String>(numLocales);
240                 final ArrayList<String> localeTitles = new ArrayList<String>(numLocales);
241                 for (int i = 0; i < numLocales; i++) {
242                         final String this_localeID = localesVec.get(i);
243                         localeIDs.add(this_localeID);
244
245                         // Use java.util.Locale to get a title for the locale:
246                         final String[] locale_parts = this_localeID.split("_");
247                         String locale_lang = this_localeID;
248                         if (locale_parts.length > 0) {
249                                 locale_lang = locale_parts[0];
250                         }
251                         String locale_country = "";
252                         if (locale_parts.length > 1) {
253                                 locale_country = locale_parts[1];
254                         }
255
256                         final Locale locale = new Locale(locale_lang, locale_country);
257                         final String title = locale.getDisplayName(locale);
258                         localeTitles.add(title);
259                 }
260                 documentInfo.setLocaleIDs(localeIDs);
261                 documentInfo.setLocaleTitles(localeTitles);
262
263                 return documentInfo;
264         }
265
266         /*
267          * Gets the layout group for the list view using the defined layout list in the document or the table fields if
268          * there's no defined layout group for the list view.
269          */
270         private LayoutGroup getValidListViewLayoutGroup(final String tableName, final String localeID) {
271
272                 // Try to return a cached version:
273                 final LayoutGroup result = mapTableLayouts.getListLayout(tableName, localeID);
274                 if (result != null) {
275                         updateLayoutGroupExpectedResultSize(result, tableName);
276                         return result;
277                 }
278
279                 final List<LayoutGroup> layoutGroupVec = document.getDataLayoutGroups(Document.LAYOUT_NAME_LIST, tableName);
280
281                 final int listViewLayoutGroupSize = Utils.safeLongToInt(layoutGroupVec.size());
282                 LayoutGroup libglomLayoutGroup = null;
283                 if (listViewLayoutGroupSize > 0) {
284                         // A list layout group is defined.
285                         // We use the first group as the list.
286                         if (listViewLayoutGroupSize > 1) {
287                                 Log.warn(documentID, tableName, "The size of the list layout group is greater than 1. "
288                                                 + "Attempting to use the first item for the layout list view.");
289                         }
290
291                         libglomLayoutGroup = layoutGroupVec.get(0);
292                 } else {
293                         // A list layout group is *not* defined; we are going make a LayoutGroup from the list of fields.
294                         // This is unusual.
295                         Log.info(documentID, tableName,
296                                         "A list layout is not defined for this table. Displaying a list layout based on the field list.");
297
298                         final List<Field> fieldsVec = document.getTableFields(tableName);
299                         libglomLayoutGroup = new LayoutGroup();
300                         for (int i = 0; i < fieldsVec.size(); i++) {
301                                 final Field field = fieldsVec.get(i);
302                                 final LayoutItemField layoutItemField = new LayoutItemField();
303                                 layoutItemField.setFullFieldDetails(field);
304                                 libglomLayoutGroup.addItem(layoutItemField);
305                         }
306                 }
307
308                 // Clone the group and change the clone, to discard unwanted information
309                 // (such as translations or binary image data) and to
310                 // store some information that we do not want to calculate on the client side.
311
312                 // Note that we don't use clone() here, because that would need clone() implementations
313                 // in classes which are also used in the client code (though the clone() methods would
314                 // not be used) and that makes the GWT java->javascript compilation fail.
315                 final LayoutGroup cloned = (LayoutGroup) Utils.deepCopy(libglomLayoutGroup);
316                 if (cloned != null) {
317                         updateTopLevelListLayoutGroup(cloned, tableName, localeID);
318
319                         // Discard unwanted translations so that getTitle(void) returns what we want.
320                         updateTitlesForLocale(cloned, localeID);
321                         
322                         // Discard binary image data:
323                         updateLayoutItemImages(cloned);
324                 }
325
326                 // Store it in the cache for next time.
327                 mapTableLayouts.setListLayout(tableName, localeID, cloned);
328
329                 return cloned;
330         }
331
332         /**
333          * @param libglomLayoutGroup
334          */
335         private void updateTopLevelListLayoutGroup(final LayoutGroup layoutGroup, final String tableName,
336                         final String localeID) {
337                 final List<LayoutItem> layoutItemsVec = layoutGroup.getItems();
338
339                 int primaryKeyIndex = -1;
340
341                 final int numItems = Utils.safeLongToInt(layoutItemsVec.size());
342                 for (int i = 0; i < numItems; i++) {
343                         final LayoutItem layoutItem = layoutItemsVec.get(i);
344
345                         if (layoutItem instanceof LayoutItemField) {
346                                 final LayoutItemField layoutItemField = (LayoutItemField) layoutItem;
347                                 final Field field = layoutItemField.getFullFieldDetails();
348                                 if ((field != null) && field.getPrimaryKey()) {
349                                         primaryKeyIndex = i;
350                                 }
351                         }
352                 }
353
354                 // Set the primary key index for the table
355                 if (primaryKeyIndex < 0) {
356                         // Add a LayoutItemField for the primary key to the end of the item list in the LayoutGroup because it
357                         // doesn't already contain a primary key.
358                         Field primaryKey = null;
359                         final List<Field> fieldsVec = document.getTableFields(tableName);
360                         for (int i = 0; i < Utils.safeLongToInt(fieldsVec.size()); i++) {
361                                 final Field field = fieldsVec.get(i);
362                                 if (field.getPrimaryKey()) {
363                                         primaryKey = field;
364                                         break;
365                                 }
366                         }
367
368                         if (primaryKey != null) {
369                                 final LayoutItemField layoutItemField = new LayoutItemField();
370                                 layoutItemField.setName(primaryKey.getName());
371                                 layoutItemField.setFullFieldDetails(primaryKey);
372                                 layoutGroup.addItem(layoutItemField);
373                                 layoutGroup.setPrimaryKeyIndex(layoutGroup.getItems().size() - 1);
374                                 layoutGroup.setHiddenPrimaryKey(true);
375                         } else {
376                                 Log.error(document.getDatabaseTitleOriginal(), tableName,
377                                                 "A primary key was not found in the FieldVector for this table. Navigation buttons will not work.");
378                         }
379                 } else {
380                         layoutGroup.setPrimaryKeyIndex(primaryKeyIndex);
381                 }
382         }
383
384         private void updateLayoutGroupExpectedResultSize(final LayoutGroup layoutGroup, final String tableName) {
385                 //TODO: Remove this?
386                 /*
387                 final ListViewDBAccess listViewDBAccess = new ListViewDBAccess(document, documentID, cpds, tableName,
388                                 layoutGroup);
389                 layoutGroup.setExpectedResultSize(listViewDBAccess.getExpectedResultSize());
390                 */
391         }
392
393         /**
394          * 
395          * @param tableName
396          * @param quickFind
397          * @param start
398          * @param length
399          * @param useSortClause
400          * @param sortColumnIndex
401          *            The index of the column to sort by, or -1 for none.
402          * @param isAscending
403          * @return
404          */
405         public ArrayList<DataItem[]> getListViewData(ComboPooledDataSource cpds, String tableName, final String quickFind, final int start, final int length,
406                         final boolean useSortClause, final int sortColumnIndex, final boolean isAscending) {
407                 // Validate the table name.
408                 tableName = getTableNameToUse(tableName);
409
410                 // Get the LayoutGroup that represents the list view.
411                 // TODO: Performance: Avoid calling this again:
412                 final LayoutGroup libglomLayoutGroup = getValidListViewLayoutGroup(tableName, "" /* irrelevant locale */);
413
414                 // Create a database access object for the list view.
415                 final ListViewDBAccess listViewDBAccess = new ListViewDBAccess(document, documentID, cpds, tableName,
416                                 libglomLayoutGroup);
417
418                 // Return the data.
419                 return listViewDBAccess.getData(quickFind, start, length, sortColumnIndex, isAscending);
420         }
421
422         DataItem[] getDetailsData(ComboPooledDataSource cpds, String tableName, final TypedDataItem primaryKeyValue) {
423                 // Validate the table name.
424                 tableName = getTableNameToUse(tableName);
425                 
426                 setDataItemType(tableName, primaryKeyValue);
427                 
428                 final DetailsDBAccess detailsDBAccess = new DetailsDBAccess(document, documentID, cpds, tableName);
429
430                 return detailsDBAccess.getData(primaryKeyValue);
431         }
432
433         /** 
434          * This make sure that the primary key value knows its actual type,
435          * in case it was received via a URL parameter as a string representation:
436          * 
437          * @param tableName The name of the table for which this is the primary key value
438          * @param primaryKeyValue The TypedDataItem to be changes.
439          */
440         private void setDataItemType(final String tableName, final TypedDataItem primaryKeyValue) {
441
442                 if(primaryKeyValue.isUnknownType()) {
443                         final Field primaryKeyField = document.getTablePrimaryKeyField(tableName);
444                         if(primaryKeyField == null) {
445                                 Log.error(document.getDatabaseTitleOriginal(), tableName,
446                                                 "Could not find the primary key.");
447                         }
448
449                         Utils.transformUnknownToActualType(primaryKeyValue, primaryKeyField.getGlomType());
450                 }
451         }
452
453         /**
454          * 
455          * @param tableName
456          * @param portal
457          * @param foreignKeyValue
458          * @param start
459          * @param length
460          * @param sortColumnIndex
461          *            The index of the column to sort by, or -1 for none.
462          * @param isAscending
463          * @return
464          */
465         ArrayList<DataItem[]> getRelatedListData(ComboPooledDataSource cpds, String tableName, final LayoutItemPortal portal,
466                         final TypedDataItem foreignKeyValue, final int start, final int length, final int sortColumnIndex,
467                         final boolean isAscending) {
468                 if (portal == null) {
469                         Log.error("getRelatedListData(): portal is null");
470                         return null;
471                 }
472
473                 // Validate the table name.
474                 tableName = getTableNameToUse(tableName);
475
476                 // Create a database access object for the related list
477                 final RelatedListDBAccess relatedListDBAccess = new RelatedListDBAccess(document, documentID, cpds, tableName,
478                                 portal);
479
480                 // Return the data
481                 return relatedListDBAccess.getData(start, length, foreignKeyValue, sortColumnIndex, isAscending);
482         }
483
484         List<LayoutGroup> getDetailsLayoutGroup(String tableName, final String localeID) {
485                 // Validate the table name.
486                 tableName = getTableNameToUse(tableName);
487
488                 // Try to return a cached version:
489                 final List<LayoutGroup> result = mapTableLayouts.getDetailsLayout(tableName, localeID);
490                 if (result != null) {
491                         updatePortalsExtras(result, tableName); // Update expected results sizes.
492                         return result;
493                 }
494
495                 final List<LayoutGroup> listGroups = document.getDataLayoutGroups(Document.LAYOUT_NAME_DETAILS, tableName);
496
497                 // Clone the group and change the clone, to discard unwanted information
498                 // (such as translations or binary image data)
499                 // and to store some information that we do not want to calculate on the client side.
500
501                 // Note that we don't use clone() here, because that would need clone() implementations
502                 // in classes which are also used in the client code (though the clone() methods would
503                 // not be used) and that makes the GWT java->javascript compilation fail.
504                 final List<LayoutGroup> listCloned = new ArrayList<LayoutGroup>();
505                 for (final LayoutGroup group : listGroups) {
506                         final LayoutGroup cloned = (LayoutGroup) Utils.deepCopy(group);
507                         if (cloned != null) {
508                                 listCloned.add(cloned);
509                         }
510                 }
511
512                 updatePortalsExtras(listCloned, tableName);
513                 updateFieldsExtras(listCloned, tableName);
514
515                 // Discard unwanted translations so that getTitle(void) returns what we want.
516                 updateTitlesForLocale(listCloned, localeID);
517                 
518                 // Discard binary image data:
519                 updateLayoutItemImages(listCloned);
520
521                 // Store it in the cache for next time.
522                 mapTableLayouts.setDetailsLayout(tableName, localeID, listCloned);
523
524                 return listCloned;
525         }
526
527         /** Discard binary image data.
528          * @param listCloned
529          */
530         private void updateLayoutItemImages(final List<LayoutGroup> listGroups) {
531                 for (final LayoutGroup group : listGroups) {
532                         updateLayoutItemImages(group);
533                 }
534                 
535         }
536
537         /** Discard binary image data.
538          * @param group
539          */
540         private void updateLayoutItemImages(final LayoutGroup group) {
541                 final List<LayoutItem> childItems = group.getItems();
542                 for (final LayoutItem item : childItems) {
543                         if (item instanceof LayoutGroup) {
544                                 // Recurse:
545                                 final LayoutGroup childGroup = (LayoutGroup) item;
546                                 updateLayoutItemImages(childGroup);
547                         } else if (item instanceof LayoutItemImage) {
548                                 final LayoutItemImage imageItem = (LayoutItemImage) item;
549                                 final DataItem image = imageItem.getImage();
550                                 image.setImageData(null);
551                                 //The client can now request the full data via the path in DataItem.getImageDataUrl().
552                         }
553                 }
554                 
555         }
556
557         /**
558          * @param result
559          * @param tableName
560          */
561         private void updatePortalsExtras(final List<LayoutGroup> listGroups, final String tableName) {
562                 for (final LayoutGroup group : listGroups) {
563                         updatePortalsExtras(group, tableName);
564                 }
565
566         }
567
568         /**
569          * @param result
570          * @param tableName
571          */
572         private void updateFieldsExtras(final List<LayoutGroup> listGroups, final String tableName) {
573                 for (final LayoutGroup group : listGroups) {
574                         updateFieldsExtras(group, tableName);
575                 }
576         }
577
578         /**
579          * @param result
580          * @param tableName
581          */
582         private void updateTitlesForLocale(final List<LayoutGroup> listGroups, final String localeID) {
583                 for (final LayoutGroup group : listGroups) {
584                         updateTitlesForLocale(group, localeID);
585                 }
586         }
587
588         private void updatePortalsExtras(final LayoutGroup group, final String tableName) {
589                 if (group instanceof LayoutItemPortal) {
590                         final LayoutItemPortal portal = (LayoutItemPortal) group;
591                         final String tableNameUsed = portal.getTableUsed(tableName);
592                         updateLayoutGroupExpectedResultSize(portal, tableNameUsed);
593
594                         //Do not add a primary key field if there is already one:
595                         if(portal.getPrimaryKeyIndex() != -1 )
596                                 return;
597
598                         final Relationship relationship = portal.getRelationship();
599                         if (relationship != null) {
600
601                                 // Cache the navigation information:
602                                 // layoutItemPortal.set_name(libglomLayoutItemPortal.get_relationship_name_used());
603                                 // layoutItemPortal.setTableName(relationship.get_from_table());
604                                 // layoutItemPortal.setFromField(relationship.get_from_field());
605
606                                 // get the primary key for the related list table
607                                 final String toTableName = relationship.getToTable();
608                                 if (!StringUtils.isEmpty(toTableName)) {
609
610                                         // get the LayoutItemField with details from its Field in the document
611                                         final List<Field> fields = document.getTableFields(toTableName); // TODO_Performance: Cache this.
612                                         for (final Field field : fields) {
613                                                 // check the names to see if they're the same
614                                                 if (field.getPrimaryKey()) {
615                                                         final LayoutItemField layoutItemField = new LayoutItemField();
616                                                         layoutItemField.setName(field.getName());
617                                                         layoutItemField.setFullFieldDetails(field);
618                                                         portal.addItem(layoutItemField);
619                                                         portal.setPrimaryKeyIndex(portal.getItems().size() - 1);
620                                                         portal.setHiddenPrimaryKey(true); // always hidden in portals
621                                                         break;
622                                                 }
623                                         }
624                                 }
625                         }
626
627                 }
628
629                 final List<LayoutItem> childItems = group.getItems();
630                 for (final LayoutItem item : childItems) {
631                         if (item instanceof LayoutGroup) {
632                                 final LayoutGroup childGroup = (LayoutGroup) item;
633                                 updatePortalsExtras(childGroup, tableName);
634                         }
635                 }
636
637         }
638
639         private void updateFieldsExtras(final LayoutGroup group, final String tableName) {
640
641                 final List<LayoutItem> childItems = group.getItems();
642                 for (final LayoutItem item : childItems) {
643                         if (item instanceof LayoutGroup) {
644                                 // Recurse:
645                                 final LayoutGroup childGroup = (LayoutGroup) item;
646                                 updateFieldsExtras(childGroup, tableName);
647                         } else if (item instanceof LayoutItemField) {
648                                 final LayoutItemField field = (LayoutItemField) item;
649
650                                 // Set whether the field should have a navigation button,
651                                 // because it identifies a related record.
652                                 final String navigationTableName = document.getLayoutItemFieldShouldHaveNavigation(tableName, field);
653                                 if (navigationTableName != null) {
654                                         field.setNavigationTableName(navigationTableName);
655                                 }
656                         }
657                 }
658         }
659
660         private void updateTitlesForLocale(final LayoutGroup group, final String localeID) {
661
662                 updateItemTitlesForLocale(group, localeID);
663
664                 final List<LayoutItem> childItems = group.getItems();
665                 for (final LayoutItem item : childItems) {
666
667                         // Call makeTitleOriginal on all Translatable items and all special
668                         // Translatable items that they use:
669                         if (item instanceof LayoutItemField) {
670                                 final LayoutItemField layoutItemField = (LayoutItemField) item;
671
672                                 final Field field = layoutItemField.getFullFieldDetails();
673                                 if (field != null) {
674                                         field.makeTitleOriginal(localeID);
675                                 }
676
677                                 final CustomTitle customTitle = layoutItemField.getCustomTitle();
678                                 if (customTitle != null) {
679                                         customTitle.makeTitleOriginal(localeID);
680                                 }
681                         }
682
683                         updateItemTitlesForLocale(item, localeID);
684
685                         if (item instanceof LayoutGroup) {
686                                 // Recurse:
687                                 final LayoutGroup childGroup = (LayoutGroup) item;
688                                 updateTitlesForLocale(childGroup, localeID);
689                         }
690                 }
691         }
692
693         private void updateItemTitlesForLocale(final LayoutItem item, final String localeID) {
694                 if (item instanceof UsesRelationship) {
695                         final UsesRelationship usesRelationship = (UsesRelationship) item;
696                         final Relationship rel = usesRelationship.getRelationship();
697
698                         if (rel != null) {
699                                 rel.makeTitleOriginal(localeID);
700                         }
701
702                         final Relationship relatedRel = usesRelationship.getRelatedRelationship();
703                         if (relatedRel != null) {
704                                 relatedRel.makeTitleOriginal(localeID);
705                         }
706                 }
707
708                 if (item instanceof Translatable) {
709                         final Translatable translatable = item;
710                         translatable.makeTitleOriginal(localeID);
711                 }
712         }
713
714         /*
715          * Gets the expected row count for a related list.
716          */
717         int getRelatedListRowCount(ComboPooledDataSource cpds, String tableName, final LayoutItemPortal portal, final TypedDataItem foreignKeyValue) {
718                 if (portal == null) {
719                         Log.error("getRelatedListData(): portal is null");
720                         return 0;
721                 }
722
723                 // Validate the table name.
724                 tableName = getTableNameToUse(tableName);
725
726                 // Create a database access object for the related list
727                 final RelatedListDBAccess relatedListDBAccess = new RelatedListDBAccess(document, documentID, cpds, tableName,
728                                 portal);
729
730                 // Return the row count
731                 return relatedListDBAccess.getExpectedResultSize(foreignKeyValue);
732         }
733
734         NavigationRecord getSuitableRecordToViewDetails(ComboPooledDataSource cpds, String tableName, final LayoutItemPortal portal,
735                         final TypedDataItem primaryKeyValue) {
736                 // Validate the table name.
737                 tableName = getTableNameToUse(tableName);
738                 
739                 setDataItemType(tableName, primaryKeyValue);
740
741                 final RelatedListNavigation relatedListNavigation = new RelatedListNavigation(document, documentID, cpds,
742                                 tableName, portal);
743
744                 return relatedListNavigation.getNavigationRecord(primaryKeyValue);
745         }
746
747         LayoutGroup getListViewLayoutGroup(String tableName, final String localeID) {
748                 // Validate the table name.
749                 tableName = getTableNameToUse(tableName);
750                 return getValidListViewLayoutGroup(tableName, localeID);
751         }
752
753         /**
754          * Gets the table name to use when accessing the database and the document. This method guards against SQL injection
755          * attacks by returning the default table if the requested table is not in the database or if the table name has not
756          * been set.
757          * 
758          * @param tableName
759          *            The table name to validate.
760          * @return The table name to use.
761          */
762         private String getTableNameToUse(final String tableName) {
763                 if (StringUtils.isEmpty(tableName) || !document.getTableIsKnown(tableName)) {
764                         return document.getDefaultTable();
765                 }
766                 return tableName;
767         }
768
769         /**
770          * @param tableName
771          * @param localeID
772          * @return
773          */
774         public Reports getReports(final String tableName, final String localeID) {
775                 final Reports result = new Reports();
776
777                 final List<String> names = document.getReportNames(tableName);
778
779                 final int count = Utils.safeLongToInt(names.size());
780                 for (int i = 0; i < count; i++) {
781                         final String name = names.get(i);
782                         final Report report = document.getReport(tableName, name);
783                         if (report == null) {
784                                 continue;
785                         }
786
787                         final String title = report.getTitle(localeID);
788                         result.addReport(name, title);
789                 }
790
791                 return result;
792         }
793
794         /**
795          * Set the credentials for the document as specified in the config file
796          * so the user does not need to specify them.
797          * These might be the global credentials, if the document-specific 
798          * credentials failed.
799          * 
800          * @param docCredentials
801          */
802         public void setCredentials(final Credentials docCredentials) {
803                 this.credentials = docCredentials;
804         }
805         
806         /**
807          * Get the credentials for the document as specified in the config file
808          * so the user does not need to specify them.
809          * These might be the global credentials, if the document-specific 
810          * credentials failed.
811          *
812          */
813         Credentials getCredentials() {
814                 return this.credentials;
815         }
816 }