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.server.libglom.Document;
35 import org.glom.web.shared.DataItem;
36 import org.glom.web.shared.DocumentInfo;
37 import org.glom.web.shared.NavigationRecord;
38 import org.glom.web.shared.Reports;
39 import org.glom.web.shared.TypedDataItem;
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.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?
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.getConnectionServer() + ":" + document.getConnectionPort()
89 + "/" + document.getConnectionDatabase());
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.getFileURI()), e.getMessage());
113 Log.info(Utils.getFileName(document.getFileURI()),
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.getTableNames();
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.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;
177 tableTitles.add(document.getTableTitle(tableName, localeID));
182 // set everything we need
183 documentInfo.setTableNames(tableNames);
184 documentInfo.setTableTitles(tableTitles);
185 documentInfo.setTitle(document.getDatabaseTitle(localeID));
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);
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.getDataLayoutGroups("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.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);
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.getItems();
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.getFullFieldDetails();
272 if (field.getPrimaryKey())
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,
283 layoutGroup.setExpectedResultSize(listViewDBAccess.getExpectedResultSize());
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()) {
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);
306 Log.error(document.getDatabaseTitleOriginal(), tableName,
307 "A primary key was not found in the FieldVector for this table. Navigation buttons will not work.");
310 layoutGroup.setPrimaryKeyIndex(primaryKeyIndex);
313 if (layoutGroup instanceof LayoutItemPortal) {
314 LayoutItemPortal portal = (LayoutItemPortal) layoutGroup;
315 updateLayoutItemPortalDTO(tableName, portal, localeID);
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);
324 // Get the LayoutGroup that represents the list view.
325 // TODO: Performance: Avoid calling this again:
326 final LayoutGroup libglomLayoutGroup = getValidListViewLayoutGroup(tableName, "" /* irrelevant locale */);
328 // Create a database access object for the list view.
329 final ListViewDBAccess listViewDBAccess = new ListViewDBAccess(document, documentID, cpds, tableName,
333 return listViewDBAccess.getData(quickFind, start, length, useSortClause, sortColumnIndex, isAscending);
336 DataItem[] getDetailsData(String tableName, final TypedDataItem primaryKeyValue) {
337 // Validate the table name.
338 tableName = getTableNameToUse(tableName);
340 final DetailsDBAccess detailsDBAccess = new DetailsDBAccess(document, documentID, cpds, tableName);
342 return detailsDBAccess.getData(primaryKeyValue);
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);
351 // Create a database access object for the related list
352 final RelatedListDBAccess relatedListDBAccess = new RelatedListDBAccess(document, documentID, cpds, tableName,
356 return relatedListDBAccess.getData(start, length, foreignKeyValue, useSortClause, sortColumnIndex, isAscending);
359 List<LayoutGroup> getDetailsLayoutGroup(String tableName, final String localeID) {
360 // Validate the table name.
361 tableName = getTableNameToUse(tableName);
362 return document.getDataLayoutGroups("details", tableName);
366 * Gets the expected row count for a related list.
368 int getRelatedListRowCount(String tableName, final String relationshipName, final TypedDataItem foreignKeyValue) {
369 // Validate the table name.
370 tableName = getTableNameToUse(tableName);
372 // Create a database access object for the related list
373 final RelatedListDBAccess relatedListDBAccess = new RelatedListDBAccess(document, documentID, cpds, tableName,
376 // Return the row count
377 return relatedListDBAccess.getExpectedResultSize(foreignKeyValue);
380 NavigationRecord getSuitableRecordToViewDetails(String tableName, final String relationshipName,
381 final TypedDataItem primaryKeyValue) {
382 // Validate the table name.
383 tableName = getTableNameToUse(tableName);
385 final RelatedListNavigation relatedListNavigation = new RelatedListNavigation(document, documentID, cpds,
386 tableName, relationshipName);
388 return relatedListNavigation.getNavigationRecord(primaryKeyValue);
391 LayoutGroup getListViewLayoutGroup(String tableName, final String localeID) {
392 // Validate the table name.
393 tableName = getTableNameToUse(tableName);
394 return getValidListViewLayoutGroup(tableName, localeID);
398 * Store some cache values in the LayoutItemPortal.
401 * @param layoutItemPortal
405 private void updateLayoutItemPortalDTO(final String tableName, final LayoutItemPortal layoutItemPortal,
406 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 Document.TableToViewDetails viewDetails = document
423 .getPortalSuitableTableToViewDetails(layoutItemPortal);
424 boolean addNavigation = false;
425 if (viewDetails != null) {
426 addNavigation = !StringUtils.isEmpty(viewDetails.tableName);
428 layoutItemPortal.setAddNavigation(addNavigation);
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.
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.
442 "Expected a 13 character string but received a 7 character string. Returning received string.");
445 Log.error("Did not receive a 13 or 7 character string. Returning black HTML colour code.");
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
456 * The table name to validate.
457 * @return The table name to use.
459 private String getTableNameToUse(final String tableName) {
460 if (StringUtils.isEmpty(tableName) || !document.getTableIsKnown(tableName)) {
461 return document.getDefaultTable();
471 public Reports getReports(final String tableName, final String localeID) {
472 final Reports result = new Reports();
474 final List<String> names = document.getReportNames(tableName);
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);
483 final String title = report.getTitle(localeID);
484 result.addReport(name, title);