Convert most code to camelCase.
[online-glom:gwt-glom.git] / src / main / java / org / glom / web / server / ConfiguredDocument.java
1 /*
2  * Copyright (C) 2011 Openismus GmbH
3  *
4  * This file is part of GWT-Glom.
5  *
6  * GWT-Glom is free software: you can redistribute it and/or modify it
7  * under the terms of the GNU Lesser General Public License as published by the
8  * Free Software Foundation, either version 3 of the License, or (at your
9  * option) any later version.
10  *
11  * GWT-Glom is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
14  * for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public License
17  * along with GWT-Glom.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 package org.glom.web.server;
21
22 import java.beans.PropertyVetoException;
23 import java.sql.Connection;
24 import java.sql.SQLException;
25 import java.util.ArrayList;
26 import java.util.List;
27 import java.util.Locale;
28
29 import org.apache.commons.lang3.StringUtils;
30 import org.glom.web.server.database.DetailsDBAccess;
31 import org.glom.web.server.database.ListViewDBAccess;
32 import org.glom.web.server.database.RelatedListDBAccess;
33 import org.glom.web.server.database.RelatedListNavigation;
34 import org.glom.web.shared.DataItem;
35 import org.glom.web.shared.DocumentInfo;
36 import org.glom.web.shared.NavigationRecord;
37 import org.glom.web.shared.Reports;
38 import org.glom.web.shared.TypedDataItem;
39 import org.glom.web.shared.libglom.Document;
40 import org.glom.web.shared.libglom.Field;
41 import org.glom.web.shared.libglom.Relationship;
42 import org.glom.web.shared.libglom.Report;
43 import org.glom.web.shared.libglom.layout.LayoutGroup;
44 import org.glom.web.shared.libglom.layout.LayoutItem;
45 import org.glom.web.shared.libglom.layout.LayoutItemCalendarPortal;
46 import org.glom.web.shared.libglom.layout.LayoutItemField;
47 import org.glom.web.shared.libglom.layout.LayoutItemPortal;
48
49 import com.mchange.v2.c3p0.ComboPooledDataSource;
50
51 /**
52  * A class to hold configuration information for a given Glom document. This class retrieves layout information from
53  * libglom and data from the underlying PostgreSQL database.
54  */
55 final class ConfiguredDocument {
56
57         private Document document;
58         private ComboPooledDataSource cpds;
59         private boolean authenticated = false;
60         private String documentID = "";
61         private String defaultLocaleID = "";
62
63         @SuppressWarnings("unused")
64         private ConfiguredDocument() {
65                 // disable default constructor
66         }
67
68         ConfiguredDocument(final Document document) throws PropertyVetoException {
69
70                 // load the jdbc driver
71                 cpds = new ComboPooledDataSource();
72
73                 // We don't support sqlite or self-hosting yet.
74                 if (document.getHostingMode() != Document.HostingMode.HOSTING_MODE_POSTGRES_CENTRAL) {
75                         Log.fatal("Error configuring the database connection." + " Only central PostgreSQL hosting is supported.");
76                         // FIXME: Throw exception?
77                 }
78
79                 try {
80                         cpds.setDriverClass("org.postgresql.Driver");
81                 } catch (final PropertyVetoException e) {
82                         Log.fatal("Error loading the PostgreSQL JDBC driver."
83                                         + " Is the PostgreSQL JDBC jar available to the servlet?", e);
84                         throw e;
85                 }
86
87                 // setup the JDBC driver for the current glom document
88                 cpds.setJdbcUrl("jdbc:postgresql://" + document.getConnectionServer() + ":" + document.getConnectionPort()
89                                 + "/" + document.getConnectionDatabase());
90
91                 this.document = document;
92         }
93
94         /**
95          * Sets the username and password for the database associated with the Glom document.
96          * 
97          * @return true if the username and password works, false otherwise
98          */
99         boolean setUsernameAndPassword(final String username, final String password) throws SQLException {
100                 cpds.setUser(username);
101                 cpds.setPassword(password);
102
103                 final int acquireRetryAttempts = cpds.getAcquireRetryAttempts();
104                 cpds.setAcquireRetryAttempts(1);
105                 Connection conn = null;
106                 try {
107                         // FIXME find a better way to check authentication
108                         // it's possible that the connection could be failing for another reason
109                         conn = cpds.getConnection();
110                         authenticated = true;
111                 } catch (final SQLException e) {
112                         Log.info(Utils.getFileName(document.getFileURI()), e.getMessage());
113                         Log.info(Utils.getFileName(document.getFileURI()),
114                                         "Connection Failed. Maybe the username or password is not correct.");
115                         authenticated = false;
116                 } finally {
117                         if (conn != null)
118                                 conn.close();
119                         cpds.setAcquireRetryAttempts(acquireRetryAttempts);
120                 }
121                 return authenticated;
122         }
123
124         Document getDocument() {
125                 return document;
126         }
127
128         ComboPooledDataSource getCpds() {
129                 return cpds;
130         }
131
132         boolean isAuthenticated() {
133                 return authenticated;
134         }
135
136         String getDocumentID() {
137                 return documentID;
138         }
139
140         void setDocumentID(final String documentID) {
141                 this.documentID = documentID;
142         }
143
144         String getDefaultLocaleID() {
145                 return defaultLocaleID;
146         }
147
148         void setDefaultLocaleID(final String localeID) {
149                 this.defaultLocaleID = localeID;
150         }
151
152         /**
153          * @return
154          */
155         DocumentInfo getDocumentInfo(final String localeID) {
156                 final DocumentInfo documentInfo = new DocumentInfo();
157
158                 // get arrays of table names and titles, and find the default table index
159                 final List<String> tablesVec = document.getTableNames();
160
161                 final 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                 final ArrayList<String> tableNames = new ArrayList<String>(numTables / 2);
165                 final 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                         final String tableName = tablesVec.get(i);
170                         if (!document.getTableIsHidden(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.getDefaultTable())) {
174                                         documentInfo.setDefaultTableIndex(visibleIndex);
175                                         foundDefaultTable = true;
176                                 }
177                                 tableTitles.add(document.getTableTitle(tableName, localeID));
178                                 visibleIndex++;
179                         }
180                 }
181
182                 // set everything we need
183                 documentInfo.setTableNames(tableNames);
184                 documentInfo.setTableTitles(tableTitles);
185                 documentInfo.setTitle(document.getDatabaseTitle(localeID));
186
187                 // Fetch arrays of locale IDs and titles:
188                 final List<String> localesVec = document.getTranslationAvailableLocales();
189                 final int numLocales = Utils.safeLongToInt(localesVec.size());
190                 final ArrayList<String> localeIDs = new ArrayList<String>(numLocales);
191                 final ArrayList<String> localeTitles = new ArrayList<String>(numLocales);
192                 for (int i = 0; i < numLocales; i++) {
193                         final String this_localeID = localesVec.get(i);
194                         localeIDs.add(this_localeID);
195
196                         // Use java.util.Locale to get a title for the locale:
197                         final String[] locale_parts = this_localeID.split("_");
198                         String locale_lang = this_localeID;
199                         if (locale_parts.length > 0)
200                                 locale_lang = locale_parts[0];
201                         String locale_country = "";
202                         if (locale_parts.length > 1)
203                                 locale_country = locale_parts[1];
204
205                         final Locale locale = new Locale(locale_lang, locale_country);
206                         final String title = locale.getDisplayName(locale);
207                         localeTitles.add(title);
208                 }
209                 documentInfo.setLocaleIDs(localeIDs);
210                 documentInfo.setLocaleTitles(localeTitles);
211
212                 return documentInfo;
213         }
214
215         /*
216          * Gets the layout group for the list view using the defined layout list in the document or the table fields if
217          * there's no defined layout group for the list view.
218          */
219         private LayoutGroup getValidListViewLayoutGroup(final String tableName, final String localeID) {
220
221                 final List<LayoutGroup> layoutGroupVec = document.getDataLayoutGroups("list", tableName);
222
223                 final int listViewLayoutGroupSize = Utils.safeLongToInt(layoutGroupVec.size());
224                 LayoutGroup libglomLayoutGroup = null;
225                 if (listViewLayoutGroupSize > 0) {
226                         // A list layout group is defined.
227                         // We use the first group as the list.
228                         if (listViewLayoutGroupSize > 1)
229                                 Log.warn(documentID, tableName, "The size of the list layout group is greater than 1. "
230                                                 + "Attempting to use the first item for the layout list view.");
231
232                         libglomLayoutGroup = layoutGroupVec.get(0);
233                 } else {
234                         // A list layout group is *not* defined; we are going make a LayoutGroup from the list of fields.
235                         // This is unusual.
236                         Log.info(documentID, tableName,
237                                         "A list layout is not defined for this table. Displaying a list layout based on the field list.");
238
239                         final List<Field> fieldsVec = document.getTableFields(tableName);
240                         libglomLayoutGroup = new LayoutGroup();
241                         for (int i = 0; i < fieldsVec.size(); i++) {
242                                 final Field field = fieldsVec.get(i);
243                                 final LayoutItemField layoutItemField = new LayoutItemField();
244                                 layoutItemField.setFullFieldDetails(field);
245                                 libglomLayoutGroup.addItem(layoutItemField);
246                         }
247                 }
248
249                 // Clone the group and change the clone, to discard unwanted informatin (such as translations),
250                 // and to store some information that we do not want to calculate on the client side:
251                 final LayoutGroup cloned = (LayoutGroup) libglomLayoutGroup.clone();
252                 updateLayoutGroup(cloned, tableName, localeID);
253
254                 return libglomLayoutGroup;
255         }
256
257         /**
258          * @param libglomLayoutGroup
259          */
260         private void updateLayoutGroup(final LayoutGroup layoutGroup, final String tableName, final String localeID) {
261                 final List<LayoutItem> layoutItemsVec = layoutGroup.getItems();
262
263                 int primaryKeyIndex = -1;
264
265                 final int numItems = Utils.safeLongToInt(layoutItemsVec.size());
266                 for (int i = 0; i < numItems; i++) {
267                         final LayoutItem layoutItem = layoutItemsVec.get(i);
268
269                         if (layoutItem instanceof LayoutItemField) {
270                                 LayoutItemField layoutItemField = (LayoutItemField) layoutItem;
271                                 final Field field = layoutItemField.getFullFieldDetails();
272                                 if (field.getPrimaryKey())
273                                         primaryKeyIndex = i;
274
275                         } else if (layoutItem instanceof LayoutGroup) {
276                                 LayoutGroup childGroup = (LayoutGroup) layoutItem;
277                                 updateLayoutGroup(childGroup, tableName, localeID);
278                         }
279                 }
280
281                 final ListViewDBAccess listViewDBAccess = new ListViewDBAccess(document, documentID, cpds, tableName,
282                                 layoutGroup);
283                 layoutGroup.setExpectedResultSize(listViewDBAccess.getExpectedResultSize());
284
285                 // Set the primary key index for the table
286                 if (primaryKeyIndex < 0) {
287                         // Add a LayoutItemField for the primary key to the end of the item list in the LayoutGroup because it
288                         // doesn't already contain a primary key.
289                         Field primaryKey = null;
290                         final List<Field> fieldsVec = document.getTableFields(tableName);
291                         for (int i = 0; i < Utils.safeLongToInt(fieldsVec.size()); i++) {
292                                 final Field field = fieldsVec.get(i);
293                                 if (field.getPrimaryKey()) {
294                                         primaryKey = field;
295                                         break;
296                                 }
297                         }
298
299                         if (primaryKey != null) {
300                                 final LayoutItemField layoutItemField = new LayoutItemField();
301                                 layoutItemField.setFullFieldDetails(primaryKey);
302                                 layoutGroup.addItem(layoutItemField); // TODO: Update the field to show just one locale?
303                                 layoutGroup.setPrimaryKeyIndex(layoutGroup.getItems().size() - 1);
304                                 layoutGroup.setHiddenPrimaryKey(true);
305                         } else {
306                                 Log.error(document.getDatabaseTitleOriginal(), tableName,
307                                                 "A primary key was not found in the FieldVector for this table. Navigation buttons will not work.");
308                         }
309                 } else {
310                         layoutGroup.setPrimaryKeyIndex(primaryKeyIndex);
311                 }
312
313                 if (layoutGroup instanceof LayoutItemPortal) {
314                         LayoutItemPortal portal = (LayoutItemPortal) layoutGroup;
315                         updateLayoutItemPortalDTO(tableName, portal, localeID);
316                 }
317         }
318
319         ArrayList<DataItem[]> getListViewData(String tableName, final String quickFind, final int start, final int length,
320                         final boolean useSortClause, final int sortColumnIndex, final boolean isAscending) {
321                 // Validate the table name.
322                 tableName = getTableNameToUse(tableName);
323
324                 // Get the LayoutGroup that represents the list view.
325                 // TODO: Performance: Avoid calling this again:
326                 final LayoutGroup libglomLayoutGroup = getValidListViewLayoutGroup(tableName, "" /* irrelevant locale */);
327
328                 // Create a database access object for the list view.
329                 final ListViewDBAccess listViewDBAccess = new ListViewDBAccess(document, documentID, cpds, tableName,
330                                 libglomLayoutGroup);
331
332                 // Return the data.
333                 return listViewDBAccess.getData(quickFind, start, length, useSortClause, sortColumnIndex, isAscending);
334         }
335
336         DataItem[] getDetailsData(String tableName, final TypedDataItem primaryKeyValue) {
337                 // Validate the table name.
338                 tableName = getTableNameToUse(tableName);
339
340                 final DetailsDBAccess detailsDBAccess = new DetailsDBAccess(document, documentID, cpds, tableName);
341
342                 return detailsDBAccess.getData(primaryKeyValue);
343         }
344
345         ArrayList<DataItem[]> getRelatedListData(String tableName, final String relationshipName,
346                         final TypedDataItem foreignKeyValue, final int start, final int length, final boolean useSortClause,
347                         final int sortColumnIndex, final boolean isAscending) {
348                 // Validate the table name.
349                 tableName = getTableNameToUse(tableName);
350
351                 // Create a database access object for the related list
352                 final RelatedListDBAccess relatedListDBAccess = new RelatedListDBAccess(document, documentID, cpds, tableName,
353                                 relationshipName);
354
355                 // Return the data
356                 return relatedListDBAccess.getData(start, length, foreignKeyValue, useSortClause, sortColumnIndex, isAscending);
357         }
358
359         List<LayoutGroup> getDetailsLayoutGroup(String tableName, final String localeID) {
360                 // Validate the table name.
361                 tableName = getTableNameToUse(tableName);
362                 return document.getDataLayoutGroups("details", tableName);
363         }
364
365         /*
366          * Gets the expected row count for a related list.
367          */
368         int getRelatedListRowCount(String tableName, final String relationshipName, final TypedDataItem foreignKeyValue) {
369                 // Validate the table name.
370                 tableName = getTableNameToUse(tableName);
371
372                 // Create a database access object for the related list
373                 final RelatedListDBAccess relatedListDBAccess = new RelatedListDBAccess(document, documentID, cpds, tableName,
374                                 relationshipName);
375
376                 // Return the row count
377                 return relatedListDBAccess.getExpectedResultSize(foreignKeyValue);
378         }
379
380         NavigationRecord getSuitableRecordToViewDetails(String tableName, final String relationshipName,
381                         final TypedDataItem primaryKeyValue) {
382                 // Validate the table name.
383                 tableName = getTableNameToUse(tableName);
384
385                 final RelatedListNavigation relatedListNavigation = new RelatedListNavigation(document, documentID, cpds,
386                                 tableName, relationshipName);
387
388                 return relatedListNavigation.getNavigationRecord(primaryKeyValue);
389         }
390
391         LayoutGroup getListViewLayoutGroup(String tableName, final String localeID) {
392                 // Validate the table name.
393                 tableName = getTableNameToUse(tableName);
394                 return getValidListViewLayoutGroup(tableName, localeID);
395         }
396
397         /**
398          * Store some cache values in the LayoutItemPortal.
399          * 
400          * @param tableName
401          * @param layoutItemPortal
402          * @param localeID
403          * @return
404          */
405         private void updateLayoutItemPortalDTO(final String tableName, final LayoutItemPortal layoutItemPortal,
406                         final String localeID) {
407
408                 // Ignore LayoutItem_CalendarPortals for now:
409                 // https://bugzilla.gnome.org/show_bug.cgi?id=664273
410                 if (layoutItemPortal instanceof LayoutItemCalendarPortal) {
411                         return;
412                 }
413
414                 final Relationship relationship = layoutItemPortal.getRelationship();
415                 if (relationship != null) {
416                         // layoutItemPortal.set_name(libglomLayoutItemPortal.get_relationship_name_used());
417                         // layoutItemPortal.setTableName(relationship.get_from_table());
418                         // layoutItemPortal.setFromField(relationship.get_from_field());
419
420                         // Set whether or not the related list will need to show the navigation buttons.
421                         // This was ported from Glom: Box_Data_Portal::get_has_suitable_record_to_view_details()
422                         final LayoutItemPortal.TableToViewDetails viewDetails = layoutItemPortal
423                                         .getSuitableTableToViewDetails(document);
424                         boolean addNavigation = false;
425                         if (viewDetails != null) {
426                                 addNavigation = !StringUtils.isEmpty(viewDetails.tableName);
427                         }
428                         layoutItemPortal.setAddNavigation(addNavigation);
429                 }
430         }
431
432         /*
433          * Converts a Gdk::Color (16-bits per channel) to an HTML colour (8-bits per channel) by discarding the least
434          * significant 8-bits in each channel.
435          */
436         private String convertGdkColorToHtmlColour(final String gdkColor) {
437                 if (gdkColor.length() == 13)
438                         return gdkColor.substring(0, 3) + gdkColor.substring(5, 7) + gdkColor.substring(9, 11);
439                 else if (gdkColor.length() == 7) {
440                         // This shouldn't happen but let's deal with it if it does.
441                         Log.warn(documentID,
442                                         "Expected a 13 character string but received a 7 character string. Returning received string.");
443                         return gdkColor;
444                 } else {
445                         Log.error("Did not receive a 13 or 7 character string. Returning black HTML colour code.");
446                         return "#000000";
447                 }
448         }
449
450         /**
451          * Gets the table name to use when accessing the database and the document. This method guards against SQL injection
452          * attacks by returning the default table if the requested table is not in the database or if the table name has not
453          * been set.
454          * 
455          * @param tableName
456          *            The table name to validate.
457          * @return The table name to use.
458          */
459         private String getTableNameToUse(final String tableName) {
460                 if (StringUtils.isEmpty(tableName) || !document.getTableIsKnown(tableName)) {
461                         return document.getDefaultTable();
462                 }
463                 return tableName;
464         }
465
466         /**
467          * @param tableName
468          * @param localeID
469          * @return
470          */
471         public Reports getReports(final String tableName, final String localeID) {
472                 final Reports result = new Reports();
473
474                 final List<String> names = document.getReportNames(tableName);
475
476                 final int count = Utils.safeLongToInt(names.size());
477                 for (int i = 0; i < count; i++) {
478                         final String name = names.get(i);
479                         final Report report = document.getReport(tableName, name);
480                         if (report == null)
481                                 continue;
482
483                         final String title = report.getTitle(localeID);
484                         result.addReport(name, title);
485                 }
486
487                 return result;
488         }
489 }