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