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