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;
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.server.database.RelatedListDBAccess;
40 import org.glom.web.shared.DataItem;
41 import org.glom.web.shared.DocumentInfo;
42 import org.glom.web.shared.layout.Formatting;
43 import org.glom.web.shared.layout.LayoutGroup;
44 import org.glom.web.shared.layout.LayoutItemField;
45 import org.glom.web.shared.layout.LayoutItemPortal;
47 import com.mchange.v2.c3p0.ComboPooledDataSource;
50 * A class to hold configuration information for a given Glom document. This class is used to retrieve layout
51 * information from libglom and data from the underlying PostgreSQL database.
53 * @author Ben Konrath <ben@bagu.org>
56 final class ConfiguredDocument {
58 private Document document;
59 private ComboPooledDataSource cpds;
60 private boolean authenticated = false;
61 private String documentID;
63 @SuppressWarnings("unused")
64 private ConfiguredDocument() {
65 // disable default constructor
68 ConfiguredDocument(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 (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(String username, String password) throws SQLException {
100 cpds.setUser(username);
101 cpds.setPassword(password);
103 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 (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(String documentID) {
141 this.documentID = documentID;
147 DocumentInfo getDocumentInfo() {
148 DocumentInfo documentInfo = new DocumentInfo();
150 // get arrays of table names and titles, and find the default table index
151 StringVector tablesVec = document.get_table_names();
153 int numTables = Utils.safeLongToInt(tablesVec.size());
154 // we don't know how many tables will be hidden so we'll use half of the number of tables for the default size
156 ArrayList<String> tableNames = new ArrayList<String>(numTables / 2);
157 ArrayList<String> tableTitles = new ArrayList<String>(numTables / 2);
158 boolean foundDefaultTable = false;
159 int visibleIndex = 0;
160 for (int i = 0; i < numTables; i++) {
161 String tableName = tablesVec.get(i);
162 if (!document.get_table_is_hidden(tableName)) {
163 tableNames.add(tableName);
164 // JNI is "expensive", the comparison will only be called if we haven't already found the default table
165 if (!foundDefaultTable && tableName.equals(document.get_default_table())) {
166 documentInfo.setDefaultTableIndex(visibleIndex);
167 foundDefaultTable = true;
169 tableTitles.add(document.get_table_title(tableName));
174 // set everything we need
175 documentInfo.setTableNames(tableNames);
176 documentInfo.setTableTitles(tableTitles);
177 documentInfo.setTitle(document.get_database_title());
183 * Gets the layout group for the list view using the defined layout list in the document or the table fields if
184 * there's no defined layout group for the list view.
186 private org.glom.libglom.LayoutGroup getValidListViewLayoutGroup(String tableName) {
188 LayoutGroupVector layoutGroupVec = document.get_data_layout_groups("list", tableName);
190 int listViewLayoutGroupSize = Utils.safeLongToInt(layoutGroupVec.size());
191 org.glom.libglom.LayoutGroup libglomLayoutGroup = null;
192 if (listViewLayoutGroupSize > 0) {
193 // a list layout group is defined; we can use the first group as the list
194 if (listViewLayoutGroupSize > 1)
195 Log.warn(documentID, tableName, "The size of the list layout group is greater than 1. "
196 + "Attempting to use the first item for the layout list view.");
198 libglomLayoutGroup = layoutGroupVec.get(0);
200 // a list layout group is *not* defined; we are going make a libglom layout group from the list of fields
201 Log.info(documentID, tableName,
202 "A list layout is not defined for this table. Displaying a list layout based on the field list.");
204 FieldVector fieldsVec = document.get_table_fields(tableName);
205 libglomLayoutGroup = new org.glom.libglom.LayoutGroup();
206 for (int i = 0; i < fieldsVec.size(); i++) {
207 Field field = fieldsVec.get(i);
208 LayoutItem_Field layoutItemField = new LayoutItem_Field();
209 layoutItemField.set_full_field_details(field);
210 libglomLayoutGroup.add_item(layoutItemField);
214 return libglomLayoutGroup;
217 ArrayList<DataItem[]> getListViewData(String tableName, int start, int length, boolean useSortClause,
218 int sortColumnIndex, boolean isAscending) {
219 // Validate the table name.
220 tableName = getTableNameToUse(tableName);
222 // Get the libglom LayoutGroup that represents the list view.
223 org.glom.libglom.LayoutGroup libglomLayoutGroup = getValidListViewLayoutGroup(tableName);
225 // Create a database access object for the list view.
226 ListViewDBAccess listViewDBAccess = new ListViewDBAccess(document, documentID, cpds, tableName,
230 return listViewDBAccess.getData(start, length, useSortClause, sortColumnIndex, isAscending);
233 DataItem[] getDetailsData(String tableName, String primaryKeyValue) {
234 // Validate the table name.
235 tableName = getTableNameToUse(tableName);
237 DetailsDBAccess detailsDBAccess = new DetailsDBAccess(document, documentID, cpds, tableName);
239 return detailsDBAccess.getData(primaryKeyValue);
242 ArrayList<DataItem[]> getRelatedListData(String tableName, String relationshipName, String foreignKeyValue,
243 int start, int length, boolean useSortClause, int sortColumnIndex, boolean isAscending) {
244 // Validate the table name.
245 tableName = getTableNameToUse(tableName);
247 // Create a database access object for the related list
248 RelatedListDBAccess relatedListDBAccess = new RelatedListDBAccess(document, documentID, cpds, tableName,
252 return relatedListDBAccess.getData(start, length, foreignKeyValue, useSortClause, sortColumnIndex, isAscending);
255 ArrayList<LayoutGroup> getDetailsLayoutGroup(String tableName) {
256 // Validate the table name.
257 tableName = getTableNameToUse(tableName);
259 // Get the details layout group information for each LayoutGroup in the LayoutGroupVector
260 LayoutGroupVector layoutGroupVec = document.get_data_layout_groups("details", tableName);
261 ArrayList<LayoutGroup> layoutGroups = new ArrayList<LayoutGroup>();
262 for (int i = 0; i < layoutGroupVec.size(); i++) {
263 org.glom.libglom.LayoutGroup libglomLayoutGroup = layoutGroupVec.get(i);
265 // satisfy the precondition of getDetailsLayoutGroup(String, org.glom.libglom.LayoutGroup)
266 if (libglomLayoutGroup == null)
269 layoutGroups.add(getDetailsLayoutGroup(tableName, libglomLayoutGroup));
275 LayoutGroup getListViewLayoutGroup(String tableName) {
276 // Validate the table name.
277 tableName = getTableNameToUse(tableName);
279 org.glom.libglom.LayoutGroup libglomLayoutGroup = getValidListViewLayoutGroup(tableName);
281 return getListLayoutGroup(tableName, libglomLayoutGroup);
285 * Gets the expected row count for a related list.
287 int getRelatedListRowCount(String tableName, String relationshipName, String foreignKeyValue) {
288 // Validate the table name.
289 tableName = getTableNameToUse(tableName);
291 // Create a database access object for the related list
292 RelatedListDBAccess relatedListDBAccess = new RelatedListDBAccess(document, documentID, cpds, tableName,
295 // Return the row count
296 return relatedListDBAccess.getExpectedResultSize(foreignKeyValue);
300 * Gets a LayoutGroup DTO for the given table name and libglom LayoutGroup. This method can be used for the main
301 * list view table and for the related list table.
303 private LayoutGroup getListLayoutGroup(String tableName, org.glom.libglom.LayoutGroup libglomLayoutGroup) {
304 LayoutGroup layoutGroup = new LayoutGroup();
305 int primaryKeyIndex = -1;
307 // look at each child item
308 LayoutItemVector layoutItemsVec = libglomLayoutGroup.get_items();
309 int numItems = Utils.safeLongToInt(layoutItemsVec.size());
310 for (int i = 0; i < numItems; i++) {
311 org.glom.libglom.LayoutItem libglomLayoutItem = layoutItemsVec.get(i);
313 // TODO add support for other LayoutItems (Text, Image, Button etc.)
314 LayoutItem_Field libglomLayoutItemField = LayoutItem_Field.cast_dynamic(libglomLayoutItem);
315 if (libglomLayoutItemField != null) {
316 layoutGroup.addItem(convertToGWTGlomLayoutItemField(libglomLayoutItemField));
317 Field field = libglomLayoutItemField.get_full_field_details();
318 if (field.get_primary_key())
321 Log.info(documentID, tableName,
322 "Ignoring unknown list LayoutItem of type " + libglomLayoutItem.get_part_type_name() + ".");
327 // set the expected result size for list view tables
328 LayoutItem_Portal libglomLayoutItemPortal = LayoutItem_Portal.cast_dynamic(libglomLayoutGroup);
329 if (libglomLayoutItemPortal == null) {
330 // libglomLayoutGroup is a list view
331 ListViewDBAccess listViewDBAccess = new ListViewDBAccess(document, documentID, cpds, tableName,
333 layoutGroup.setExpectedResultSize(listViewDBAccess.getExpectedResultSize());
336 // Set the primary key index for the table
337 if (primaryKeyIndex < 0) {
338 // Add a LayoutItemField for the primary key to the end of the item list in the LayoutGroup because it
339 // doesn't already contain a primary key.
340 Field primaryKey = null;
341 FieldVector fieldsVec = document.get_table_fields(tableName);
342 for (int i = 0; i < Utils.safeLongToInt(fieldsVec.size()); i++) {
343 Field field = fieldsVec.get(i);
344 if (field.get_primary_key()) {
349 if (primaryKey != null) {
350 LayoutItem_Field libglomLayoutItemField = new LayoutItem_Field();
351 libglomLayoutItemField.set_full_field_details(primaryKey);
352 layoutGroup.addItem(convertToGWTGlomLayoutItemField(libglomLayoutItemField));
353 layoutGroup.setPrimaryKeyIndex(layoutGroup.getItems().size() - 1);
354 layoutGroup.setHiddenPrimaryKey(true);
356 Log.error(document.get_database_title(), tableName,
357 "A primary key was not found in the FieldVector for this table. Navigation buttons will not work.");
360 layoutGroup.setPrimaryKeyIndex(primaryKeyIndex);
363 layoutGroup.setTableName(tableName);
369 * Gets a recursively defined Details LayoutGroup DTO for the specified libglom LayoutGroup object. This is used for
370 * getting layout information for the details view.
372 * @param documentID Glom document identifier
374 * @param tableName table name in the specified Glom document
376 * @param libglomLayoutGroup libglom LayoutGroup to convert
378 * @precondition libglomLayoutGroup must not be null
380 * @return {@link LayoutGroup} object that represents the layout for the specified {@link
381 * org.glom.libglom.LayoutGroup}
383 private LayoutGroup getDetailsLayoutGroup(String tableName, org.glom.libglom.LayoutGroup libglomLayoutGroup) {
384 LayoutGroup layoutGroup = new LayoutGroup();
385 layoutGroup.setColumnCount(Utils.safeLongToInt(libglomLayoutGroup.get_columns_count()));
386 layoutGroup.setTitle(libglomLayoutGroup.get_title());
388 // look at each child item
389 LayoutItemVector layoutItemsVec = libglomLayoutGroup.get_items();
390 for (int i = 0; i < layoutItemsVec.size(); i++) {
391 org.glom.libglom.LayoutItem libglomLayoutItem = layoutItemsVec.get(i);
393 // just a safety check
394 if (libglomLayoutItem == null)
397 org.glom.web.shared.layout.LayoutItem layoutItem = null;
398 org.glom.libglom.LayoutGroup group = org.glom.libglom.LayoutGroup.cast_dynamic(libglomLayoutItem);
400 // libglomLayoutItem is a LayoutGroup
401 LayoutItem_Portal libglomLayoutItemPortal = LayoutItem_Portal.cast_dynamic(group);
402 if (libglomLayoutItemPortal != null) {
403 // group is a LayoutItemPortal
404 LayoutItemPortal layoutItemPortal = new LayoutItemPortal();
405 Relationship relationship = libglomLayoutItemPortal.get_relationship();
406 if (relationship != null) {
407 layoutItemPortal.setNavigationType(convertToGWTGlomNavigationType(libglomLayoutItemPortal
408 .get_navigation_type()));
410 layoutItemPortal.setTitle(libglomLayoutItemPortal.get_title_used("")); // parent title not
412 LayoutGroup tempLayoutGroup = getListLayoutGroup(tableName, libglomLayoutItemPortal);
413 for (org.glom.web.shared.layout.LayoutItem item : tempLayoutGroup.getItems()) {
414 // TODO EDITING If the relationship does not allow editing, then mark all these fields as
415 // non-editable. Check relationship.get_allow_edit() to see if it's editable.
416 layoutItemPortal.addItem(item);
418 layoutItemPortal.setPrimaryKeyIndex(tempLayoutGroup.getPrimaryKeyIndex());
419 layoutItemPortal.setHiddenPrimaryKey(tempLayoutGroup.hasHiddenPrimaryKey());
420 layoutItemPortal.setName(libglomLayoutItemPortal.get_relationship_name_used());
421 layoutItemPortal.setTableName(relationship.get_from_table());
422 layoutItemPortal.setFromField(relationship.get_from_field());
425 // Note: empty layoutItemPortal used if relationship is null
426 layoutItem = layoutItemPortal;
429 // group is *not* a LayoutItemPortal//
430 // recurse into child groups
431 layoutItem = getDetailsLayoutGroup(tableName, group);
434 // libglomLayoutItem is *not* a LayoutGroup
435 // create LayoutItem DTOs based on the the libglom type
436 // TODO add support for other LayoutItems (Text, Image, Button etc.)
437 LayoutItem_Field libglomLayoutField = LayoutItem_Field.cast_dynamic(libglomLayoutItem);
438 if (libglomLayoutField != null) {
439 layoutItem = convertToGWTGlomLayoutItemField(libglomLayoutField);
441 Log.info(documentID, tableName,
442 "Ignoring unknown details LayoutItem of type " + libglomLayoutItem.get_part_type_name()
448 layoutGroup.addItem(layoutItem);
454 private LayoutItemField convertToGWTGlomLayoutItemField(LayoutItem_Field libglomLayoutItemField) {
455 LayoutItemField layoutItemField = new LayoutItemField();
458 layoutItemField.setType(convertToGWTGlomFieldType(libglomLayoutItemField.get_glom_type()));
461 Formatting formatting = new Formatting();
462 formatting.setHorizontalAlignment(convertToGWTGlomHorizonalAlignment(libglomLayoutItemField
463 .get_formatting_used_horizontal_alignment()));
464 FieldFormatting libglomFormatting = libglomLayoutItemField.get_formatting_used();
465 if (libglomFormatting.get_text_format_multiline()) {
466 formatting.setTextFormatMultilineHeightLines(Utils.safeLongToInt(libglomFormatting
467 .get_text_format_multiline_height_lines()));
469 layoutItemField.setFormatting(formatting);
471 // set title and name
472 layoutItemField.setTitle(libglomLayoutItemField.get_title_or_name());
473 layoutItemField.setName(libglomLayoutItemField.get_name());
475 return layoutItemField;
479 * This method converts a Field.glom_field_type to the equivalent ColumnInfo.FieldType. The need for this comes from
480 * the fact that the GWT FieldType classes can't be used with RPC and there's no easy way to use the java-libglom
481 * Field.glom_field_type enum with RPC. An enum identical to FieldFormatting.glom_field_type is included in the
484 private LayoutItemField.GlomFieldType convertToGWTGlomFieldType(Field.glom_field_type type) {
487 return LayoutItemField.GlomFieldType.TYPE_BOOLEAN;
489 return LayoutItemField.GlomFieldType.TYPE_DATE;
491 return LayoutItemField.GlomFieldType.TYPE_IMAGE;
493 return LayoutItemField.GlomFieldType.TYPE_NUMERIC;
495 return LayoutItemField.GlomFieldType.TYPE_TEXT;
497 return LayoutItemField.GlomFieldType.TYPE_TIME;
499 Log.info("Returning TYPE_INVALID.");
500 return LayoutItemField.GlomFieldType.TYPE_INVALID;
502 Log.error("Recieved a type that I don't know about: " + Field.glom_field_type.class.getName() + "."
503 + type.toString() + ". Returning " + LayoutItemField.GlomFieldType.TYPE_INVALID.toString() + ".");
504 return LayoutItemField.GlomFieldType.TYPE_INVALID;
509 * This method converts a FieldFormatting.HorizontalAlignment to the equivalent Formatting.HorizontalAlignment. The
510 * need for this comes from the fact that the GWT HorizontalAlignment classes can't be used with RPC and there's no
511 * easy way to use the java-libglom FieldFormatting.HorizontalAlignment enum with RPC. An enum identical to
512 * FieldFormatting.HorizontalAlignment is included in the Formatting class.
514 private Formatting.HorizontalAlignment convertToGWTGlomHorizonalAlignment(
515 FieldFormatting.HorizontalAlignment alignment) {
517 case HORIZONTAL_ALIGNMENT_AUTO:
518 return Formatting.HorizontalAlignment.HORIZONTAL_ALIGNMENT_AUTO;
519 case HORIZONTAL_ALIGNMENT_LEFT:
520 return Formatting.HorizontalAlignment.HORIZONTAL_ALIGNMENT_LEFT;
521 case HORIZONTAL_ALIGNMENT_RIGHT:
522 return Formatting.HorizontalAlignment.HORIZONTAL_ALIGNMENT_RIGHT;
524 Log.error("Recieved an alignment that I don't know about: "
525 + FieldFormatting.HorizontalAlignment.class.getName() + "." + alignment.toString() + ". Returning "
526 + Formatting.HorizontalAlignment.HORIZONTAL_ALIGNMENT_RIGHT.toString() + ".");
527 return Formatting.HorizontalAlignment.HORIZONTAL_ALIGNMENT_RIGHT;
532 * This method converts a LayoutItem_Portal.navigation_type from java-libglom to the equivalent
533 * LayoutItemPortal.NavigationType from Online Glom. This conversion is required because the LayoutItem_Portal class
534 * from java-libglom can't be used with GWT-RPC. An enum identical to LayoutItem_Portal.navigation_type from
535 * java-libglom is included in the LayoutItemPortal data transfer object.
537 private LayoutItemPortal.NavigationType convertToGWTGlomNavigationType(
538 LayoutItem_Portal.navigation_type navigationType) {
539 switch (navigationType) {
540 case NAVIGATION_NONE:
541 return LayoutItemPortal.NavigationType.NAVIGATION_NONE;
542 case NAVIGATION_AUTOMATIC:
543 return LayoutItemPortal.NavigationType.NAVIGATION_AUTOMATIC;
544 case NAVIGATION_SPECIFIC:
545 return LayoutItemPortal.NavigationType.NAVIGATION_SPECIFIC;
547 Log.error("Recieved an unknown NavigationType: " + LayoutItem_Portal.navigation_type.class.getName() + "."
548 + navigationType.toString() + ". Returning " + LayoutItemPortal.NavigationType.NAVIGATION_AUTOMATIC
550 return LayoutItemPortal.NavigationType.NAVIGATION_AUTOMATIC;
555 * Gets the table name to use when accessing the database and the document. This method guards against SQL injection
556 * attacks by returning the default table if the requested table is not in the database or if the table name has not
560 * The table name to validate.
561 * @return The table name to use.
563 private String getTableNameToUse(String tableName) {
564 if (tableName == null || tableName.isEmpty() || !document.get_table_is_known(tableName)) {
565 return document.get_default_table();