2 * Copyright (C) 2011 Openismus GmbH
4 * This file is part of GWT-Glom.
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.
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
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/>.
20 package org.glom.web.server;
22 import java.beans.PropertyVetoException;
23 import java.io.ByteArrayInputStream;
24 import java.io.ByteArrayOutputStream;
25 import java.io.IOException;
26 import java.io.ObjectInputStream;
27 import java.io.ObjectOutputStream;
28 import java.sql.Connection;
29 import java.sql.SQLException;
30 import java.util.ArrayList;
31 import java.util.List;
32 import java.util.Locale;
34 import org.apache.commons.lang3.StringUtils;
35 import org.glom.web.server.database.DetailsDBAccess;
36 import org.glom.web.server.database.ListViewDBAccess;
37 import org.glom.web.server.database.RelatedListDBAccess;
38 import org.glom.web.server.database.RelatedListNavigation;
39 import org.glom.web.server.libglom.Document;
40 import org.glom.web.shared.DataItem;
41 import org.glom.web.shared.DocumentInfo;
42 import org.glom.web.shared.NavigationRecord;
43 import org.glom.web.shared.Reports;
44 import org.glom.web.shared.TypedDataItem;
45 import org.glom.web.shared.libglom.Field;
46 import org.glom.web.shared.libglom.Relationship;
47 import org.glom.web.shared.libglom.Report;
48 import org.glom.web.shared.libglom.layout.LayoutGroup;
49 import org.glom.web.shared.libglom.layout.LayoutItem;
50 import org.glom.web.shared.libglom.layout.LayoutItemCalendarPortal;
51 import org.glom.web.shared.libglom.layout.LayoutItemField;
52 import org.glom.web.shared.libglom.layout.LayoutItemPortal;
54 import com.mchange.v2.c3p0.ComboPooledDataSource;
57 * A class to hold configuration information for a given Glom document. This class retrieves layout information from
58 * libglom and data from the underlying PostgreSQL database.
60 final class ConfiguredDocument {
62 private Document document;
63 private ComboPooledDataSource cpds;
64 private boolean authenticated = false;
65 private String documentID = "";
66 private String defaultLocaleID = "";
68 @SuppressWarnings("unused")
69 private ConfiguredDocument() {
70 // disable default constructor
73 ConfiguredDocument(final Document document) throws PropertyVetoException {
75 // load the jdbc driver
76 cpds = new ComboPooledDataSource();
78 // We don't support sqlite or self-hosting yet.
79 if (document.getHostingMode() != Document.HostingMode.HOSTING_MODE_POSTGRES_CENTRAL) {
80 Log.fatal("Error configuring the database connection." + " Only central PostgreSQL hosting is supported.");
81 // FIXME: Throw exception?
85 cpds.setDriverClass("org.postgresql.Driver");
86 } catch (final PropertyVetoException e) {
87 Log.fatal("Error loading the PostgreSQL JDBC driver."
88 + " Is the PostgreSQL JDBC jar available to the servlet?", e);
92 // setup the JDBC driver for the current glom document
93 cpds.setJdbcUrl("jdbc:postgresql://" + document.getConnectionServer() + ":" + document.getConnectionPort()
94 + "/" + document.getConnectionDatabase());
96 this.document = document;
100 * Sets the username and password for the database associated with the Glom document.
102 * @return true if the username and password works, false otherwise
104 boolean setUsernameAndPassword(final String username, final String password) throws SQLException {
105 cpds.setUser(username);
106 cpds.setPassword(password);
108 final int acquireRetryAttempts = cpds.getAcquireRetryAttempts();
109 cpds.setAcquireRetryAttempts(1);
110 Connection conn = null;
112 // FIXME find a better way to check authentication
113 // it's possible that the connection could be failing for another reason
114 conn = cpds.getConnection();
115 authenticated = true;
116 } catch (final SQLException e) {
117 Log.info(Utils.getFileName(document.getFileURI()), e.getMessage());
118 Log.info(Utils.getFileName(document.getFileURI()),
119 "Connection Failed. Maybe the username or password is not correct.");
120 authenticated = false;
124 cpds.setAcquireRetryAttempts(acquireRetryAttempts);
126 return authenticated;
129 Document getDocument() {
133 ComboPooledDataSource getCpds() {
137 boolean isAuthenticated() {
138 return authenticated;
141 String getDocumentID() {
145 void setDocumentID(final String documentID) {
146 this.documentID = documentID;
149 String getDefaultLocaleID() {
150 return defaultLocaleID;
153 void setDefaultLocaleID(final String localeID) {
154 this.defaultLocaleID = localeID;
160 DocumentInfo getDocumentInfo(final String localeID) {
161 final DocumentInfo documentInfo = new DocumentInfo();
163 // get arrays of table names and titles, and find the default table index
164 final List<String> tablesVec = document.getTableNames();
166 final int numTables = Utils.safeLongToInt(tablesVec.size());
167 // we don't know how many tables will be hidden so we'll use half of the number of tables for the default size
169 final ArrayList<String> tableNames = new ArrayList<String>(numTables / 2);
170 final ArrayList<String> tableTitles = new ArrayList<String>(numTables / 2);
171 boolean foundDefaultTable = false;
172 int visibleIndex = 0;
173 for (int i = 0; i < numTables; i++) {
174 final String tableName = tablesVec.get(i);
175 if (!document.getTableIsHidden(tableName)) {
176 tableNames.add(tableName);
177 // JNI is "expensive", the comparison will only be called if we haven't already found the default table
178 if (!foundDefaultTable && tableName.equals(document.getDefaultTable())) {
179 documentInfo.setDefaultTableIndex(visibleIndex);
180 foundDefaultTable = true;
182 tableTitles.add(document.getTableTitle(tableName, localeID));
187 // set everything we need
188 documentInfo.setTableNames(tableNames);
189 documentInfo.setTableTitles(tableTitles);
190 documentInfo.setTitle(document.getDatabaseTitle(localeID));
192 // Fetch arrays of locale IDs and titles:
193 final List<String> localesVec = document.getTranslationAvailableLocales();
194 final int numLocales = Utils.safeLongToInt(localesVec.size());
195 final ArrayList<String> localeIDs = new ArrayList<String>(numLocales);
196 final ArrayList<String> localeTitles = new ArrayList<String>(numLocales);
197 for (int i = 0; i < numLocales; i++) {
198 final String this_localeID = localesVec.get(i);
199 localeIDs.add(this_localeID);
201 // Use java.util.Locale to get a title for the locale:
202 final String[] locale_parts = this_localeID.split("_");
203 String locale_lang = this_localeID;
204 if (locale_parts.length > 0)
205 locale_lang = locale_parts[0];
206 String locale_country = "";
207 if (locale_parts.length > 1)
208 locale_country = locale_parts[1];
210 final Locale locale = new Locale(locale_lang, locale_country);
211 final String title = locale.getDisplayName(locale);
212 localeTitles.add(title);
214 documentInfo.setLocaleIDs(localeIDs);
215 documentInfo.setLocaleTitles(localeTitles);
221 * Gets the layout group for the list view using the defined layout list in the document or the table fields if
222 * there's no defined layout group for the list view.
224 private LayoutGroup getValidListViewLayoutGroup(final String tableName, final String localeID) {
226 final List<LayoutGroup> layoutGroupVec = document.getDataLayoutGroups("list", tableName);
228 final int listViewLayoutGroupSize = Utils.safeLongToInt(layoutGroupVec.size());
229 LayoutGroup libglomLayoutGroup = null;
230 if (listViewLayoutGroupSize > 0) {
231 // A list layout group is defined.
232 // We use the first group as the list.
233 if (listViewLayoutGroupSize > 1)
234 Log.warn(documentID, tableName, "The size of the list layout group is greater than 1. "
235 + "Attempting to use the first item for the layout list view.");
237 libglomLayoutGroup = layoutGroupVec.get(0);
239 // A list layout group is *not* defined; we are going make a LayoutGroup from the list of fields.
241 Log.info(documentID, tableName,
242 "A list layout is not defined for this table. Displaying a list layout based on the field list.");
244 final List<Field> fieldsVec = document.getTableFields(tableName);
245 libglomLayoutGroup = new LayoutGroup();
246 for (int i = 0; i < fieldsVec.size(); i++) {
247 final Field field = fieldsVec.get(i);
248 final LayoutItemField layoutItemField = new LayoutItemField();
249 layoutItemField.setFullFieldDetails(field);
250 libglomLayoutGroup.addItem(layoutItemField);
254 // TODO: Clone the group and change the clone, to discard unwanted informatin (such as translations)
255 //store some information that we do not want to calculate on the client side.
257 //Note that we don't use clone() here, because that would need clone() implementations
258 //in classes which are also used in the client code (though the clone() methods would
259 //not be used) and that makes the GWT java->javascript compilation fail.
260 final LayoutGroup cloned = (LayoutGroup) deepCopy(libglomLayoutGroup);
262 updateLayoutGroup(cloned, tableName, localeID);
265 return libglomLayoutGroup;
268 static public Object deepCopy(Object oldObj)
270 ObjectOutputStream oos = null;
271 ObjectInputStream ois = null;
274 ByteArrayOutputStream bos =
275 new ByteArrayOutputStream();
276 oos = new ObjectOutputStream(bos);
277 // serialize and pass the object
278 oos.writeObject(oldObj); // C
280 ByteArrayInputStream bin =
281 new ByteArrayInputStream(bos.toByteArray());
282 ois = new ObjectInputStream(bin);
283 // return the new object
284 return ois.readObject();
285 } catch(Exception e) {
286 System.out.println("Exception in deepCopy:" + e);
292 } catch(IOException e) {
293 System.out.println("Exception in deepCopy during finally: " + e);
300 * @param libglomLayoutGroup
302 private void updateLayoutGroup(final LayoutGroup layoutGroup, final String tableName, final String localeID) {
303 final List<LayoutItem> layoutItemsVec = layoutGroup.getItems();
305 int primaryKeyIndex = -1;
307 final int numItems = Utils.safeLongToInt(layoutItemsVec.size());
308 for (int i = 0; i < numItems; i++) {
309 final LayoutItem layoutItem = layoutItemsVec.get(i);
311 if (layoutItem instanceof LayoutItemField) {
312 LayoutItemField layoutItemField = (LayoutItemField) layoutItem;
313 final Field field = layoutItemField.getFullFieldDetails();
314 if (field.getPrimaryKey())
317 } else if (layoutItem instanceof LayoutGroup) {
318 LayoutGroup childGroup = (LayoutGroup) layoutItem;
319 updateLayoutGroup(childGroup, tableName, localeID);
323 final ListViewDBAccess listViewDBAccess = new ListViewDBAccess(document, documentID, cpds, tableName,
325 layoutGroup.setExpectedResultSize(listViewDBAccess.getExpectedResultSize());
327 // Set the primary key index for the table
328 if (primaryKeyIndex < 0) {
329 // Add a LayoutItemField for the primary key to the end of the item list in the LayoutGroup because it
330 // doesn't already contain a primary key.
331 Field primaryKey = null;
332 final List<Field> fieldsVec = document.getTableFields(tableName);
333 for (int i = 0; i < Utils.safeLongToInt(fieldsVec.size()); i++) {
334 final Field field = fieldsVec.get(i);
335 if (field.getPrimaryKey()) {
341 if (primaryKey != null) {
342 final LayoutItemField layoutItemField = new LayoutItemField();
343 layoutItemField.setFullFieldDetails(primaryKey);
344 layoutGroup.addItem(layoutItemField); // TODO: Update the field to show just one locale?
345 layoutGroup.setPrimaryKeyIndex(layoutGroup.getItems().size() - 1);
346 layoutGroup.setHiddenPrimaryKey(true);
348 Log.error(document.getDatabaseTitleOriginal(), tableName,
349 "A primary key was not found in the FieldVector for this table. Navigation buttons will not work.");
352 layoutGroup.setPrimaryKeyIndex(primaryKeyIndex);
355 if (layoutGroup instanceof LayoutItemPortal) {
356 LayoutItemPortal portal = (LayoutItemPortal) layoutGroup;
357 updateLayoutItemPortalDTO(tableName, portal, localeID);
361 ArrayList<DataItem[]> getListViewData(String tableName, final String quickFind, final int start, final int length,
362 final boolean useSortClause, final int sortColumnIndex, final boolean isAscending) {
363 // Validate the table name.
364 tableName = getTableNameToUse(tableName);
366 // Get the LayoutGroup that represents the list view.
367 // TODO: Performance: Avoid calling this again:
368 final LayoutGroup libglomLayoutGroup = getValidListViewLayoutGroup(tableName, "" /* irrelevant locale */);
370 // Create a database access object for the list view.
371 final ListViewDBAccess listViewDBAccess = new ListViewDBAccess(document, documentID, cpds, tableName,
375 return listViewDBAccess.getData(quickFind, start, length, useSortClause, sortColumnIndex, isAscending);
378 DataItem[] getDetailsData(String tableName, final TypedDataItem primaryKeyValue) {
379 // Validate the table name.
380 tableName = getTableNameToUse(tableName);
382 final DetailsDBAccess detailsDBAccess = new DetailsDBAccess(document, documentID, cpds, tableName);
384 return detailsDBAccess.getData(primaryKeyValue);
387 ArrayList<DataItem[]> getRelatedListData(String tableName, final String relationshipName,
388 final TypedDataItem foreignKeyValue, final int start, final int length, final boolean useSortClause,
389 final int sortColumnIndex, final boolean isAscending) {
390 // Validate the table name.
391 tableName = getTableNameToUse(tableName);
393 // Create a database access object for the related list
394 final RelatedListDBAccess relatedListDBAccess = new RelatedListDBAccess(document, documentID, cpds, tableName,
398 return relatedListDBAccess.getData(start, length, foreignKeyValue, useSortClause, sortColumnIndex, isAscending);
401 List<LayoutGroup> getDetailsLayoutGroup(String tableName, final String localeID) {
402 // Validate the table name.
403 tableName = getTableNameToUse(tableName);
404 return document.getDataLayoutGroups("details", tableName);
408 * Gets the expected row count for a related list.
410 int getRelatedListRowCount(String tableName, final String relationshipName, final TypedDataItem foreignKeyValue) {
411 // Validate the table name.
412 tableName = getTableNameToUse(tableName);
414 // Create a database access object for the related list
415 final RelatedListDBAccess relatedListDBAccess = new RelatedListDBAccess(document, documentID, cpds, tableName,
418 // Return the row count
419 return relatedListDBAccess.getExpectedResultSize(foreignKeyValue);
422 NavigationRecord getSuitableRecordToViewDetails(String tableName, final String relationshipName,
423 final TypedDataItem primaryKeyValue) {
424 // Validate the table name.
425 tableName = getTableNameToUse(tableName);
427 final RelatedListNavigation relatedListNavigation = new RelatedListNavigation(document, documentID, cpds,
428 tableName, relationshipName);
430 return relatedListNavigation.getNavigationRecord(primaryKeyValue);
433 LayoutGroup getListViewLayoutGroup(String tableName, final String localeID) {
434 // Validate the table name.
435 tableName = getTableNameToUse(tableName);
436 return getValidListViewLayoutGroup(tableName, localeID);
440 * Store some cache values in the LayoutItemPortal.
443 * @param layoutItemPortal
447 private void updateLayoutItemPortalDTO(final String tableName, final LayoutItemPortal layoutItemPortal,
448 final String localeID) {
450 // Ignore LayoutItem_CalendarPortals for now:
451 // https://bugzilla.gnome.org/show_bug.cgi?id=664273
452 if (layoutItemPortal instanceof LayoutItemCalendarPortal) {
456 final Relationship relationship = layoutItemPortal.getRelationship();
457 if (relationship != null) {
458 // layoutItemPortal.set_name(libglomLayoutItemPortal.get_relationship_name_used());
459 // layoutItemPortal.setTableName(relationship.get_from_table());
460 // layoutItemPortal.setFromField(relationship.get_from_field());
462 // Set whether or not the related list will need to show the navigation buttons.
463 // This was ported from Glom: Box_Data_Portal::get_has_suitable_record_to_view_details()
464 final Document.TableToViewDetails viewDetails = document
465 .getPortalSuitableTableToViewDetails(layoutItemPortal);
466 boolean addNavigation = false;
467 if (viewDetails != null) {
468 addNavigation = !StringUtils.isEmpty(viewDetails.tableName);
470 layoutItemPortal.setAddNavigation(addNavigation);
475 * Converts a Gdk::Color (16-bits per channel) to an HTML colour (8-bits per channel) by discarding the least
476 * significant 8-bits in each channel.
478 private String convertGdkColorToHtmlColour(final String gdkColor) {
479 if (gdkColor.length() == 13)
480 return gdkColor.substring(0, 3) + gdkColor.substring(5, 7) + gdkColor.substring(9, 11);
481 else if (gdkColor.length() == 7) {
482 // This shouldn't happen but let's deal with it if it does.
484 "Expected a 13 character string but received a 7 character string. Returning received string.");
487 Log.error("Did not receive a 13 or 7 character string. Returning black HTML colour code.");
493 * Gets the table name to use when accessing the database and the document. This method guards against SQL injection
494 * attacks by returning the default table if the requested table is not in the database or if the table name has not
498 * The table name to validate.
499 * @return The table name to use.
501 private String getTableNameToUse(final String tableName) {
502 if (StringUtils.isEmpty(tableName) || !document.getTableIsKnown(tableName)) {
503 return document.getDefaultTable();
513 public Reports getReports(final String tableName, final String localeID) {
514 final Reports result = new Reports();
516 final List<String> names = document.getReportNames(tableName);
518 final int count = Utils.safeLongToInt(names.size());
519 for (int i = 0; i < count; i++) {
520 final String name = names.get(i);
521 final Report report = document.getReport(tableName, name);
525 final String title = report.getTitle(localeID);
526 result.addReport(name, title);