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