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