Breakup the OnlineGlomServiceImpl class to make it more manageable.
[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.LayoutGroupVector;
32 import org.glom.libglom.LayoutItemVector;
33 import org.glom.libglom.LayoutItem_Field;
34 import org.glom.libglom.LayoutItem_Portal;
35 import org.glom.libglom.Relationship;
36 import org.glom.libglom.StringVector;
37 import org.glom.web.server.database.DetailsDBAccess;
38 import org.glom.web.server.database.ListViewDBAccess;
39 import org.glom.web.shared.GlomDocument;
40 import org.glom.web.shared.GlomField;
41 import org.glom.web.shared.layout.Formatting;
42 import org.glom.web.shared.layout.LayoutGroup;
43 import org.glom.web.shared.layout.LayoutItemField;
44 import org.glom.web.shared.layout.LayoutItemPortal;
45
46 import com.mchange.v2.c3p0.ComboPooledDataSource;
47
48 /**
49  * A class to hold configuration information for a given Glom document. This class is used to retrieve layout
50  * information from libglom and data from the underlying PostgreSQL database.
51  * 
52  * @author Ben Konrath <ben@bagu.org>
53  * 
54  */
55 final class ConfiguredDocument {
56
57         private Document document;
58         private ComboPooledDataSource cpds;
59         private boolean authenticated = false;
60         private String documentID;
61
62         @SuppressWarnings("unused")
63         private ConfiguredDocument() {
64                 // disable default constructor
65         }
66
67         ConfiguredDocument(Document document) throws PropertyVetoException {
68
69                 // load the jdbc driver
70                 cpds = new ComboPooledDataSource();
71
72                 // We don't support sqlite or self-hosting yet.
73                 if (document.get_hosting_mode() != Document.HostingMode.HOSTING_MODE_POSTGRES_CENTRAL) {
74                         Log.fatal("Error configuring the database connection." + " Only central PostgreSQL hosting is supported.");
75                         // FIXME: Throw exception?
76                 }
77
78                 try {
79                         cpds.setDriverClass("org.postgresql.Driver");
80                 } catch (PropertyVetoException e) {
81                         Log.fatal("Error loading the PostgreSQL JDBC driver."
82                                         + " Is the PostgreSQL JDBC jar available to the servlet?", e);
83                         throw e;
84                 }
85
86                 // setup the JDBC driver for the current glom document
87                 cpds.setJdbcUrl("jdbc:postgresql://" + document.get_connection_server() + ":" + document.get_connection_port()
88                                 + "/" + document.get_connection_database());
89
90                 this.document = document;
91         }
92
93         /**
94          * Sets the username and password for the database associated with the Glom document.
95          * 
96          * @return true if the username and password works, false otherwise
97          */
98         boolean setUsernameAndPassword(String username, String password) throws SQLException {
99                 cpds.setUser(username);
100                 cpds.setPassword(password);
101
102                 int acquireRetryAttempts = cpds.getAcquireRetryAttempts();
103                 cpds.setAcquireRetryAttempts(1);
104                 Connection conn = null;
105                 try {
106                         // FIXME find a better way to check authentication
107                         // it's possible that the connection could be failing for another reason
108                         conn = cpds.getConnection();
109                         authenticated = true;
110                 } catch (SQLException e) {
111                         Log.info(Utils.getFileName(document.get_file_uri()), e.getMessage());
112                         Log.info(Utils.getFileName(document.get_file_uri()),
113                                         "Connection Failed. Maybe the username or password is not correct.");
114                         authenticated = false;
115                 } finally {
116                         if (conn != null)
117                                 conn.close();
118                         cpds.setAcquireRetryAttempts(acquireRetryAttempts);
119                 }
120                 return authenticated;
121         }
122
123         Document getDocument() {
124                 return document;
125         }
126
127         ComboPooledDataSource getCpds() {
128                 return cpds;
129         }
130
131         boolean isAuthenticated() {
132                 return authenticated;
133         }
134
135         String getDocumentID() {
136                 return documentID;
137         }
138
139         void setDocumentID(String documentID) {
140                 this.documentID = documentID;
141         }
142
143         /**
144          * @return
145          */
146         GlomDocument getGlomDocument() {
147                 GlomDocument glomDocument = new GlomDocument();
148
149                 // get arrays of table names and titles, and find the default table index
150                 StringVector tablesVec = document.get_table_names();
151
152                 int numTables = Utils.safeLongToInt(tablesVec.size());
153                 // we don't know how many tables will be hidden so we'll use half of the number of tables for the default size
154                 // of the ArrayList
155                 ArrayList<String> tableNames = new ArrayList<String>(numTables / 2);
156                 ArrayList<String> tableTitles = new ArrayList<String>(numTables / 2);
157                 boolean foundDefaultTable = false;
158                 int visibleIndex = 0;
159                 for (int i = 0; i < numTables; i++) {
160                         String tableName = tablesVec.get(i);
161                         if (!document.get_table_is_hidden(tableName)) {
162                                 tableNames.add(tableName);
163                                 // JNI is "expensive", the comparison will only be called if we haven't already found the default table
164                                 if (!foundDefaultTable && tableName.equals(document.get_default_table())) {
165                                         glomDocument.setDefaultTableIndex(visibleIndex);
166                                         foundDefaultTable = true;
167                                 }
168                                 tableTitles.add(document.get_table_title(tableName));
169                                 visibleIndex++;
170                         }
171                 }
172
173                 // set everything we need
174                 glomDocument.setTableNames(tableNames);
175                 glomDocument.setTableTitles(tableTitles);
176                 glomDocument.setTitle(document.get_database_title());
177
178                 return glomDocument;
179         }
180
181         /*
182          * Gets the layout group for the list view using the defined layout list in the document or the table fields if
183          * there's no defined layout group for the list view.
184          */
185         private org.glom.libglom.LayoutGroup getValidListViewLayoutGroup(String tableName) {
186
187                 LayoutGroupVector layoutGroupVec = document.get_data_layout_groups("list", tableName);
188
189                 int listViewLayoutGroupSize = Utils.safeLongToInt(layoutGroupVec.size());
190                 org.glom.libglom.LayoutGroup libglomLayoutGroup = null;
191                 if (listViewLayoutGroupSize > 0) {
192                         // a list layout group is defined; we can use the first group as the list
193                         if (listViewLayoutGroupSize > 1)
194                                 Log.warn(documentID, tableName, "The size of the list layout group is greater than 1. "
195                                                 + "Attempting to use the first item for the layout list view.");
196
197                         libglomLayoutGroup = layoutGroupVec.get(0);
198                 } else {
199                         // a list layout group is *not* defined; we are going make a libglom layout group from the list of fields
200                         Log.info(documentID, tableName,
201                                         "A list layout is not defined for this table. Displaying a list layout based on the field list.");
202
203                         FieldVector fieldsVec = document.get_table_fields(tableName);
204                         libglomLayoutGroup = new org.glom.libglom.LayoutGroup();
205                         for (int i = 0; i < fieldsVec.size(); i++) {
206                                 Field field = fieldsVec.get(i);
207                                 LayoutItem_Field layoutItemField = new LayoutItem_Field();
208                                 layoutItemField.set_full_field_details(field);
209                                 libglomLayoutGroup.add_item(layoutItemField);
210                         }
211                 }
212
213                 return libglomLayoutGroup;
214         }
215
216         ArrayList<GlomField[]> getListViewData(String tableName, int start, int length, boolean useSortClause,
217                         int sortColumnIndex, boolean isAscending) {
218                 // Validate the table name.
219                 tableName = getTableNameToUse(tableName);
220
221                 // Get the libglom LayoutGroup that represents the list view.
222                 org.glom.libglom.LayoutGroup libglomLayoutGroup = getValidListViewLayoutGroup(tableName);
223
224                 // Create a database access object for the list view.
225                 ListViewDBAccess listViewDBAccess = new ListViewDBAccess(document, documentID, cpds, tableName,
226                                 libglomLayoutGroup);
227
228                 // Return the data.
229                 return listViewDBAccess.getData(start, length, useSortClause, sortColumnIndex, isAscending);
230         }
231
232         GlomField[] getDetailsData(String tableName, String primaryKeyValue) {
233                 // Validate the table name.
234                 tableName = getTableNameToUse(tableName);
235
236                 DetailsDBAccess detailsDBAccess = new DetailsDBAccess(document, documentID, cpds, tableName);
237
238                 return detailsDBAccess.getData(primaryKeyValue);
239         }
240
241         ArrayList<LayoutGroup> getDetailsLayoutGroup(String tableName) {
242                 // Validate the table name.
243                 tableName = getTableNameToUse(tableName);
244
245                 // Get the details layout group information for each LayoutGroup in the LayoutGroupVector
246                 LayoutGroupVector layoutGroupVec = document.get_data_layout_groups("details", tableName);
247                 ArrayList<LayoutGroup> layoutGroups = new ArrayList<LayoutGroup>();
248                 for (int i = 0; i < layoutGroupVec.size(); i++) {
249                         org.glom.libglom.LayoutGroup libglomLayoutGroup = layoutGroupVec.get(i);
250
251                         // satisfy the precondition of getDetailsLayoutGroup(String, org.glom.libglom.LayoutGroup)
252                         if (libglomLayoutGroup == null)
253                                 continue;
254
255                         layoutGroups.add(getDetailsLayoutGroup(tableName, libglomLayoutGroup));
256                 }
257
258                 return layoutGroups;
259         }
260
261         LayoutGroup getListViewLayoutGroup(String tableName) {
262                 // Validate the table name.
263                 tableName = getTableNameToUse(tableName);
264
265                 org.glom.libglom.LayoutGroup libglomLayoutGroup = getValidListViewLayoutGroup(tableName);
266
267                 return getListLayoutGroup(tableName, libglomLayoutGroup);
268         }
269
270         /*
271          * Gets a LayoutGroup DTO for the given table name and libglom LayoutGroup.
272          */
273         private LayoutGroup getListLayoutGroup(String tableName, org.glom.libglom.LayoutGroup libglomLayoutGroup) {
274                 LayoutGroup layoutGroup = new LayoutGroup();
275
276                 // look at each child item
277                 LayoutItemVector layoutItemsVec = libglomLayoutGroup.get_items();
278                 int numItems = Utils.safeLongToInt(layoutItemsVec.size());
279                 for (int i = 0; i < numItems; i++) {
280                         org.glom.libglom.LayoutItem libglomLayoutItem = layoutItemsVec.get(i);
281
282                         // TODO add support for other LayoutItems (Text, Image, Button etc.)
283                         LayoutItem_Field libglomLayoutField = LayoutItem_Field.cast_dynamic(libglomLayoutItem);
284                         if (libglomLayoutField != null) {
285                                 layoutGroup.addItem(convertToGWTGlomLayoutItemField(libglomLayoutField));
286                         } else {
287                                 Log.info(documentID, tableName,
288                                                 "Ignoring unknown LayoutItem of type " + libglomLayoutItem.get_part_type_name() + ".");
289                                 continue;
290                         }
291                 }
292
293                 ListViewDBAccess listViewDBAccess = new ListViewDBAccess(document, documentID, cpds, tableName,
294                                 libglomLayoutGroup);
295                 layoutGroup.setExpectedResultSize(listViewDBAccess.getExpectedResultSize());
296
297                 // Set the primary key index for the table
298                 int primaryKeyIndex = listViewDBAccess.getPrimaryKeyIndex();
299                 if (primaryKeyIndex < 0) {
300                         // Add a LayoutItemField for the primary key to the end of the item list in the LayoutGroup because it
301                         // doesn't already contain a primary key.
302                         LayoutItem_Field libglomLayoutItemField = listViewDBAccess.getPrimaryKeyLayoutItemField();
303                         layoutGroup.addItem(convertToGWTGlomLayoutItemField(libglomLayoutItemField));
304                         layoutGroup.setPrimaryKeyIndex(layoutGroup.getItems().size() - 1);
305                         layoutGroup.setHiddenPrimaryKey(true);
306
307                 } else {
308                         layoutGroup.setPrimaryKeyIndex(primaryKeyIndex);
309                 }
310
311                 layoutGroup.setTableName(tableName);
312
313                 return layoutGroup;
314         }
315
316         /*
317          * Gets a recursively defined Details LayoutGroup DTO for the specified libglom LayoutGroup object. This is used for
318          * getting layout information for the details view.
319          * 
320          * @param documentID Glom document identifier
321          * 
322          * @param tableName table name in the specified Glom document
323          * 
324          * @param libglomLayoutGroup libglom LayoutGroup to convert
325          * 
326          * @precondition libglomLayoutGroup must not be null
327          * 
328          * @return {@link LayoutGroup} object that represents the layout for the specified {@link
329          * org.glom.libglom.LayoutGroup}
330          */
331         private LayoutGroup getDetailsLayoutGroup(String tableName, org.glom.libglom.LayoutGroup libglomLayoutGroup) {
332                 LayoutGroup layoutGroup = new LayoutGroup();
333                 layoutGroup.setColumnCount(Utils.safeLongToInt(libglomLayoutGroup.get_columns_count()));
334                 layoutGroup.setTitle(libglomLayoutGroup.get_title());
335
336                 // look at each child item
337                 LayoutItemVector layoutItemsVec = libglomLayoutGroup.get_items();
338                 for (int i = 0; i < layoutItemsVec.size(); i++) {
339                         org.glom.libglom.LayoutItem libglomLayoutItem = layoutItemsVec.get(i);
340
341                         // just a safety check
342                         if (libglomLayoutItem == null)
343                                 continue;
344
345                         org.glom.web.shared.layout.LayoutItem layoutItem = null;
346                         org.glom.libglom.LayoutGroup group = org.glom.libglom.LayoutGroup.cast_dynamic(libglomLayoutItem);
347                         if (group != null) {
348                                 // libglomLayoutItem is a LayoutGroup
349                                 LayoutItem_Portal libglomLayoutItemPortal = LayoutItem_Portal.cast_dynamic(group);
350                                 if (libglomLayoutItemPortal != null) {
351                                         // group is a LayoutItemPortal
352                                         LayoutItemPortal layoutItemPortal = new LayoutItemPortal();
353                                         Relationship relationship = libglomLayoutItemPortal.get_relationship();
354                                         if (relationship != null) {
355                                                 layoutItemPortal.setNavigationType(convertToGWTGlomNavigationType(libglomLayoutItemPortal
356                                                                 .get_navigation_type()));
357
358                                                 layoutItemPortal.setTitle(libglomLayoutItemPortal.get_title_used("")); // parent title not
359                                                                                                                                                                                                 // relevant
360                                                 LayoutGroup tempLayoutGroup = getListLayoutGroup(tableName, libglomLayoutItemPortal);
361                                                 for (org.glom.web.shared.layout.LayoutItem item : tempLayoutGroup.getItems()) {
362                                                         // TODO EDITING If the relationship does not allow editing, then mark all these fields as
363                                                         // non-editable. Check relationship.get_allow_edit() to see if it's editable.
364                                                         layoutItemPortal.addItem(item);
365                                                 }
366                                                 layoutItemPortal.setPrimaryKeyIndex(tempLayoutGroup.getPrimaryKeyIndex());
367                                                 layoutItemPortal.setHiddenPrimaryKey(tempLayoutGroup.hasHiddenPrimaryKey());
368                                                 layoutItemPortal.setTableName(libglomLayoutItemPortal.get_from_table());
369                                                 layoutItemPortal.setName(libglomLayoutItemPortal.get_relationship_name_used());
370                                         }
371
372                                         // Note: empty layoutItemPortal used if relationship is null
373                                         layoutItem = layoutItemPortal;
374
375                                 } else {
376                                         // group is *not* a LayoutItemPortal//
377                                         // recurse into child groups
378                                         layoutItem = getDetailsLayoutGroup(tableName, group);
379                                 }
380                         } else {
381                                 // libglomLayoutItem is *not* a LayoutGroup
382                                 // create LayoutItem DTOs based on the the libglom type
383                                 // TODO add support for other LayoutItems (Text, Image, Button etc.)
384                                 LayoutItem_Field libglomLayoutField = LayoutItem_Field.cast_dynamic(libglomLayoutItem);
385                                 if (libglomLayoutField != null) {
386                                         layoutItem = convertToGWTGlomLayoutItemField(libglomLayoutField);
387                                 } else {
388                                         Log.info(documentID, tableName,
389                                                         "Ignoring unknown LayoutItem of type " + libglomLayoutItem.get_part_type_name() + ".");
390                                         continue;
391                                 }
392                         }
393
394                         layoutGroup.addItem(layoutItem);
395                 }
396
397                 return layoutGroup;
398         }
399
400         private LayoutItemField convertToGWTGlomLayoutItemField(LayoutItem_Field libglomLayoutItemField) {
401                 LayoutItemField layoutItemField = new LayoutItemField();
402
403                 // set type
404                 layoutItemField.setType(convertToGWTGlomFieldType(libglomLayoutItemField.get_glom_type()));
405
406                 // set formatting
407                 Formatting formatting = new Formatting();
408                 formatting.setHorizontalAlignment(convertToGWTGlomHorizonalAlignment(libglomLayoutItemField
409                                 .get_formatting_used_horizontal_alignment()));
410                 FieldFormatting libglomFormatting = libglomLayoutItemField.get_formatting_used();
411                 if (libglomFormatting.get_text_format_multiline()) {
412                         formatting.setTextFormatMultilineHeightLines(Utils.safeLongToInt(libglomFormatting
413                                         .get_text_format_multiline_height_lines()));
414                 }
415                 layoutItemField.setFormatting(formatting);
416
417                 // set title
418                 layoutItemField.setTitle(libglomLayoutItemField.get_title_or_name());
419
420                 return layoutItemField;
421         }
422
423         /*
424          * This method converts a Field.glom_field_type to the equivalent ColumnInfo.FieldType. The need for this comes from
425          * the fact that the GWT FieldType classes can't be used with RPC and there's no easy way to use the java-libglom
426          * Field.glom_field_type enum with RPC. An enum identical to FieldFormatting.glom_field_type is included in the
427          * ColumnInfo class.
428          */
429         private LayoutItemField.GlomFieldType convertToGWTGlomFieldType(Field.glom_field_type type) {
430                 switch (type) {
431                 case TYPE_BOOLEAN:
432                         return LayoutItemField.GlomFieldType.TYPE_BOOLEAN;
433                 case TYPE_DATE:
434                         return LayoutItemField.GlomFieldType.TYPE_DATE;
435                 case TYPE_IMAGE:
436                         return LayoutItemField.GlomFieldType.TYPE_IMAGE;
437                 case TYPE_NUMERIC:
438                         return LayoutItemField.GlomFieldType.TYPE_NUMERIC;
439                 case TYPE_TEXT:
440                         return LayoutItemField.GlomFieldType.TYPE_TEXT;
441                 case TYPE_TIME:
442                         return LayoutItemField.GlomFieldType.TYPE_TIME;
443                 case TYPE_INVALID:
444                         Log.info("Returning TYPE_INVALID.");
445                         return LayoutItemField.GlomFieldType.TYPE_INVALID;
446                 default:
447                         Log.error("Recieved a type that I don't know about: " + Field.glom_field_type.class.getName() + "."
448                                         + type.toString() + ". Returning " + LayoutItemField.GlomFieldType.TYPE_INVALID.toString() + ".");
449                         return LayoutItemField.GlomFieldType.TYPE_INVALID;
450                 }
451         }
452
453         /*
454          * This method converts a FieldFormatting.HorizontalAlignment to the equivalent Formatting.HorizontalAlignment. The
455          * need for this comes from the fact that the GWT HorizontalAlignment classes can't be used with RPC and there's no
456          * easy way to use the java-libglom FieldFormatting.HorizontalAlignment enum with RPC. An enum identical to
457          * FieldFormatting.HorizontalAlignment is included in the Formatting class.
458          */
459         private Formatting.HorizontalAlignment convertToGWTGlomHorizonalAlignment(
460                         FieldFormatting.HorizontalAlignment alignment) {
461                 switch (alignment) {
462                 case HORIZONTAL_ALIGNMENT_AUTO:
463                         return Formatting.HorizontalAlignment.HORIZONTAL_ALIGNMENT_AUTO;
464                 case HORIZONTAL_ALIGNMENT_LEFT:
465                         return Formatting.HorizontalAlignment.HORIZONTAL_ALIGNMENT_LEFT;
466                 case HORIZONTAL_ALIGNMENT_RIGHT:
467                         return Formatting.HorizontalAlignment.HORIZONTAL_ALIGNMENT_RIGHT;
468                 default:
469                         Log.error("Recieved an alignment that I don't know about: "
470                                         + FieldFormatting.HorizontalAlignment.class.getName() + "." + alignment.toString() + ". Returning "
471                                         + Formatting.HorizontalAlignment.HORIZONTAL_ALIGNMENT_RIGHT.toString() + ".");
472                         return Formatting.HorizontalAlignment.HORIZONTAL_ALIGNMENT_RIGHT;
473                 }
474         }
475
476         /*
477          * This method converts a LayoutItem_Portal.navigation_type from java-libglom to the equivalent
478          * LayoutItemPortal.NavigationType from Online Glom. This conversion is required because the LayoutItem_Portal class
479          * from java-libglom can't be used with GWT-RPC. An enum identical to LayoutItem_Portal.navigation_type from
480          * java-libglom is included in the LayoutItemPortal data transfer object.
481          */
482         private LayoutItemPortal.NavigationType convertToGWTGlomNavigationType(
483                         LayoutItem_Portal.navigation_type navigationType) {
484                 switch (navigationType) {
485                 case NAVIGATION_NONE:
486                         return LayoutItemPortal.NavigationType.NAVIGATION_NONE;
487                 case NAVIGATION_AUTOMATIC:
488                         return LayoutItemPortal.NavigationType.NAVIGATION_AUTOMATIC;
489                 case NAVIGATION_SPECIFIC:
490                         return LayoutItemPortal.NavigationType.NAVIGATION_SPECIFIC;
491                 default:
492                         Log.error("Recieved an unknown NavigationType: " + LayoutItem_Portal.navigation_type.class.getName() + "."
493                                         + navigationType.toString() + ". Returning " + LayoutItemPortal.NavigationType.NAVIGATION_AUTOMATIC
494                                         + ".");
495                         return LayoutItemPortal.NavigationType.NAVIGATION_AUTOMATIC;
496                 }
497         }
498
499         /**
500          * Gets the table name to use when accessing the database and the document. This method guards against SQL injection
501          * attacks by returning the default table if the requested table is not in the database or if the table name has not
502          * been set.
503          * 
504          * @param tableName
505          *            The table name to validate.
506          * @return The table name to use.
507          */
508         private String getTableNameToUse(String tableName) {
509                 if (tableName == null || tableName.isEmpty() || !document.get_table_is_known(tableName)) {
510                         return document.get_default_table();
511                 }
512                 return tableName;
513         }
514
515 }