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.sql.Connection;
24 import java.sql.SQLException;
25 import java.util.ArrayList;
26 import java.util.List;
27 import java.util.Locale;
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;
49 import com.mchange.v2.c3p0.ComboPooledDataSource;
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.
55 final class ConfiguredDocument {
57 private Document document;
58 private ComboPooledDataSource cpds;
59 private boolean authenticated = false;
60 private String documentID = "";
61 private String defaultLocaleID = "";
63 @SuppressWarnings("unused")
64 private ConfiguredDocument() {
65 // disable default constructor
68 ConfiguredDocument(final Document document) throws PropertyVetoException {
70 // load the jdbc driver
71 cpds = new ComboPooledDataSource();
73 // We don't support sqlite or self-hosting yet.
74 if (document.get_hosting_mode() != Document.HostingMode.HOSTING_MODE_POSTGRES_CENTRAL) {
75 Log.fatal("Error configuring the database connection." + " Only central PostgreSQL hosting is supported.");
76 // FIXME: Throw exception?
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);
87 // setup the JDBC driver for the current glom document
88 cpds.setJdbcUrl("jdbc:postgresql://" + document.get_connection_server() + ":" + document.get_connection_port()
89 + "/" + document.get_connection_database());
91 this.document = document;
95 * Sets the username and password for the database associated with the Glom document.
97 * @return true if the username and password works, false otherwise
99 boolean setUsernameAndPassword(final String username, final String password) throws SQLException {
100 cpds.setUser(username);
101 cpds.setPassword(password);
103 final int acquireRetryAttempts = cpds.getAcquireRetryAttempts();
104 cpds.setAcquireRetryAttempts(1);
105 Connection conn = null;
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.get_file_uri()), e.getMessage());
113 Log.info(Utils.getFileName(document.get_file_uri()),
114 "Connection Failed. Maybe the username or password is not correct.");
115 authenticated = false;
119 cpds.setAcquireRetryAttempts(acquireRetryAttempts);
121 return authenticated;
124 Document getDocument() {
128 ComboPooledDataSource getCpds() {
132 boolean isAuthenticated() {
133 return authenticated;
136 String getDocumentID() {
140 void setDocumentID(final String documentID) {
141 this.documentID = documentID;
144 String getDefaultLocaleID() {
145 return defaultLocaleID;
148 void setDefaultLocaleID(final String localeID) {
149 this.defaultLocaleID = localeID;
155 DocumentInfo getDocumentInfo(final String localeID) {
156 final DocumentInfo documentInfo = new DocumentInfo();
158 // get arrays of table names and titles, and find the default table index
159 final List<String> tablesVec = document.get_table_names();
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
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.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;
177 tableTitles.add(document.get_table_title(tableName, localeID));
182 // set everything we need
183 documentInfo.setTableNames(tableNames);
184 documentInfo.setTableTitles(tableTitles);
185 documentInfo.setTitle(document.get_database_title(localeID));
187 // Fetch arrays of locale IDs and titles:
188 final List<String> localesVec = document.get_translation_available_locales();
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);
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];
205 final Locale locale = new Locale(locale_lang, locale_country);
206 final String title = locale.getDisplayName(locale);
207 localeTitles.add(title);
209 documentInfo.setLocaleIDs(localeIDs);
210 documentInfo.setLocaleTitles(localeTitles);
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.
219 private LayoutGroup getValidListViewLayoutGroup(final String tableName, final String localeID) {
221 final List<LayoutGroup> layoutGroupVec = document.get_data_layout_groups("list", tableName);
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.");
232 libglomLayoutGroup = layoutGroupVec.get(0);
234 // A list layout group is *not* defined; we are going make a LayoutGroup from the list of fields.
236 Log.info(documentID, tableName,
237 "A list layout is not defined for this table. Displaying a list layout based on the field list.");
239 final List<Field> fieldsVec = document.get_table_fields(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.set_full_field_details(field);
245 libglomLayoutGroup.add_item(layoutItemField);
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);
254 return libglomLayoutGroup;
258 * @param libglomLayoutGroup
260 private void updateLayoutGroup(final LayoutGroup layoutGroup, final String tableName, final String localeID) {
261 final List<LayoutItem> layoutItemsVec = layoutGroup.get_items();
263 int primaryKeyIndex = -1;
265 final int numItems = Utils.safeLongToInt(layoutItemsVec.size());
266 for (int i = 0; i < numItems; i++) {
267 final LayoutItem layoutItem = layoutItemsVec.get(i);
269 if(layoutItem instanceof LayoutItemField) {
270 LayoutItemField layoutItemField = (LayoutItemField)layoutItem;
271 final Field field = layoutItemField.get_full_field_details();
272 if (field.get_primary_key())
275 } else if(layoutItem instanceof LayoutGroup) {
276 LayoutGroup childGroup = (LayoutGroup)layoutItem;
277 updateLayoutGroup(childGroup, tableName, localeID);
281 final ListViewDBAccess listViewDBAccess = new ListViewDBAccess(document, documentID, cpds, tableName, layoutGroup);
282 layoutGroup.setExpectedResultSize(listViewDBAccess.getExpectedResultSize());
284 // Set the primary key index for the table
285 if (primaryKeyIndex < 0) {
286 // Add a LayoutItemField for the primary key to the end of the item list in the LayoutGroup because it
287 // doesn't already contain a primary key.
288 Field primaryKey = null;
289 final List<Field> fieldsVec = document.get_table_fields(tableName);
290 for (int i = 0; i < Utils.safeLongToInt(fieldsVec.size()); i++) {
291 final Field field = fieldsVec.get(i);
292 if (field.get_primary_key()) {
298 if (primaryKey != null) {
299 final LayoutItemField layoutItemField = new LayoutItemField();
300 layoutItemField.set_full_field_details(primaryKey);
301 layoutGroup.add_item(layoutItemField); //TODO: Update the field to show just one locale?
302 layoutGroup.setPrimaryKeyIndex(layoutGroup.get_items().size() - 1);
303 layoutGroup.setHiddenPrimaryKey(true);
305 Log.error(document.get_database_title_original(), tableName,
306 "A primary key was not found in the FieldVector for this table. Navigation buttons will not work.");
309 layoutGroup.setPrimaryKeyIndex(primaryKeyIndex);
314 if(layoutGroup instanceof LayoutItemPortal) {
315 LayoutItemPortal portal = (LayoutItemPortal)layoutGroup;
316 updateLayoutItemPortalDTO(tableName, portal, localeID);
320 ArrayList<DataItem[]> getListViewData(String tableName, final String quickFind, final int start, final int length,
321 final boolean useSortClause, final int sortColumnIndex, final boolean isAscending) {
322 // Validate the table name.
323 tableName = getTableNameToUse(tableName);
325 // Get the LayoutGroup that represents the list view.
326 // TODO: Performance: Avoid calling this again:
327 final LayoutGroup libglomLayoutGroup = getValidListViewLayoutGroup(tableName, "" /* irrelevant locale */);
329 // Create a database access object for the list view.
330 final ListViewDBAccess listViewDBAccess = new ListViewDBAccess(document, documentID, cpds, tableName,
334 return listViewDBAccess.getData(quickFind, start, length, useSortClause, sortColumnIndex, isAscending);
337 DataItem[] getDetailsData(String tableName, final TypedDataItem primaryKeyValue) {
338 // Validate the table name.
339 tableName = getTableNameToUse(tableName);
341 final DetailsDBAccess detailsDBAccess = new DetailsDBAccess(document, documentID, cpds, tableName);
343 return detailsDBAccess.getData(primaryKeyValue);
346 ArrayList<DataItem[]> getRelatedListData(String tableName, final String relationshipName,
347 final TypedDataItem foreignKeyValue, final int start, final int length, final boolean useSortClause,
348 final int sortColumnIndex, final boolean isAscending) {
349 // Validate the table name.
350 tableName = getTableNameToUse(tableName);
352 // Create a database access object for the related list
353 final RelatedListDBAccess relatedListDBAccess = new RelatedListDBAccess(document, documentID, cpds, tableName,
357 return relatedListDBAccess.getData(start, length, foreignKeyValue, useSortClause, sortColumnIndex, isAscending);
360 List<LayoutGroup> getDetailsLayoutGroup(String tableName, final String localeID) {
361 // Validate the table name.
362 tableName = getTableNameToUse(tableName);
363 return document.get_data_layout_groups("details", tableName);
367 * Gets the expected row count for a related list.
369 int getRelatedListRowCount(String tableName, final String relationshipName, final TypedDataItem foreignKeyValue) {
370 // Validate the table name.
371 tableName = getTableNameToUse(tableName);
373 // Create a database access object for the related list
374 final RelatedListDBAccess relatedListDBAccess = new RelatedListDBAccess(document, documentID, cpds, tableName,
377 // Return the row count
378 return relatedListDBAccess.getExpectedResultSize(foreignKeyValue);
381 NavigationRecord getSuitableRecordToViewDetails(String tableName, final String relationshipName,
382 final TypedDataItem primaryKeyValue) {
383 // Validate the table name.
384 tableName = getTableNameToUse(tableName);
386 final RelatedListNavigation relatedListNavigation = new RelatedListNavigation(document, documentID, cpds,
387 tableName, relationshipName);
389 return relatedListNavigation.getNavigationRecord(primaryKeyValue);
392 LayoutGroup getListViewLayoutGroup(String tableName, final String localeID) {
393 // Validate the table name.
394 tableName = getTableNameToUse(tableName);
395 return getValidListViewLayoutGroup(tableName, localeID);
398 /** Store some cache values in the LayoutItemPortal.
401 * @param layoutItemPortal
405 private void updateLayoutItemPortalDTO(final String tableName,
406 final LayoutItemPortal layoutItemPortal, final String localeID) {
408 // Ignore LayoutItem_CalendarPortals for now:
409 // https://bugzilla.gnome.org/show_bug.cgi?id=664273
410 if(layoutItemPortal instanceof LayoutItemCalendarPortal) {
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());
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.get_suitable_table_to_view_details(document);
423 boolean addNavigation = false;
424 if(viewDetails != null) {
425 addNavigation = !StringUtils.isEmpty(viewDetails.tableName);
427 layoutItemPortal.setAddNavigation(addNavigation);
432 * Converts a Gdk::Color (16-bits per channel) to an HTML colour (8-bits per channel) by discarding the least
433 * significant 8-bits in each channel.
435 private String convertGdkColorToHtmlColour(final String gdkColor) {
436 if (gdkColor.length() == 13)
437 return gdkColor.substring(0, 3) + gdkColor.substring(5, 7) + gdkColor.substring(9, 11);
438 else if (gdkColor.length() == 7) {
439 // This shouldn't happen but let's deal with it if it does.
441 "Expected a 13 character string but received a 7 character string. Returning received string.");
444 Log.error("Did not receive a 13 or 7 character string. Returning black HTML colour code.");
450 * Gets the table name to use when accessing the database and the document. This method guards against SQL injection
451 * attacks by returning the default table if the requested table is not in the database or if the table name has not
455 * The table name to validate.
456 * @return The table name to use.
458 private String getTableNameToUse(final String tableName) {
459 if (StringUtils.isEmpty(tableName) || !document.get_table_is_known(tableName)) {
460 return document.get_default_table();
470 public Reports getReports(final String tableName, final String localeID) {
471 final Reports result = new Reports();
473 final List<String> names = document.get_report_names(tableName);
475 final int count = Utils.safeLongToInt(names.size());
476 for (int i = 0; i < count; i++) {
477 final String name = names.get(i);
478 final Report report = document.get_report(tableName, name);
482 final String title = report.get_title(localeID);
483 result.addReport(name, title);