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