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.Hashtable;
27 import java.util.List;
28 import java.util.Locale;
30 import org.apache.commons.lang3.StringUtils;
31 import org.glom.web.server.database.DetailsDBAccess;
32 import org.glom.web.server.database.ListViewDBAccess;
33 import org.glom.web.server.database.RelatedListDBAccess;
34 import org.glom.web.server.database.RelatedListNavigation;
35 import org.glom.web.server.libglom.Document;
36 import org.glom.web.shared.DataItem;
37 import org.glom.web.shared.DocumentInfo;
38 import org.glom.web.shared.NavigationRecord;
39 import org.glom.web.shared.Reports;
40 import org.glom.web.shared.TypedDataItem;
41 import org.glom.web.shared.libglom.CustomTitle;
42 import org.glom.web.shared.libglom.Field;
43 import org.glom.web.shared.libglom.Relationship;
44 import org.glom.web.shared.libglom.Report;
45 import org.glom.web.shared.libglom.Translatable;
46 import org.glom.web.shared.libglom.layout.LayoutGroup;
47 import org.glom.web.shared.libglom.layout.LayoutItem;
48 import org.glom.web.shared.libglom.layout.LayoutItemField;
49 import org.glom.web.shared.libglom.layout.LayoutItemPortal;
50 import org.glom.web.shared.libglom.layout.TableToViewDetails;
51 import org.glom.web.shared.libglom.layout.UsesRelationship;
53 import com.mchange.v2.c3p0.ComboPooledDataSource;
56 * A class to hold configuration information for a given Glom document. This class retrieves layout information from
57 * libglom and data from the underlying PostgreSQL database.
59 final class ConfiguredDocument {
61 private Document document;
62 private ComboPooledDataSource cpds;
63 private boolean authenticated = false;
64 private String documentID = "";
65 private String defaultLocaleID = "";
67 private static class LayoutLocaleMap extends Hashtable<String, List<LayoutGroup>> {
68 private static final long serialVersionUID = 6542501521673767267L;
71 private static class TableLayouts {
72 public LayoutLocaleMap listLayouts;
73 public LayoutLocaleMap detailsLayouts;
76 private static class TableLayoutsForLocale extends Hashtable<String, TableLayouts> {
77 private static final long serialVersionUID = -1947929931925049013L;
79 public LayoutGroup getListLayout(final String tableName, final String locale) {
80 final List<LayoutGroup> groups = getLayout(tableName, locale, false);
85 if (groups.isEmpty()) {
92 public List<LayoutGroup> getDetailsLayout(final String tableName, final String locale) {
93 return getLayout(tableName, locale, true);
96 public void setListLayout(final String tableName, final String locale, LayoutGroup layout) {
97 List<LayoutGroup> list = new ArrayList<LayoutGroup>();
99 setLayout(tableName, locale, list, false);
102 public void setDetailsLayout(final String tableName, final String locale, final List<LayoutGroup> layout) {
103 setLayout(tableName, locale, layout, true);
106 private List<LayoutGroup> getLayout(final String tableName, final String locale, boolean details) {
107 LayoutLocaleMap map = getMap(tableName, details);
113 return map.get(locale);
116 private LayoutLocaleMap getMap(final String tableName, boolean details) {
117 final TableLayouts tableLayouts = get(tableName);
118 if (tableLayouts == null) {
122 LayoutLocaleMap map = null;
124 map = tableLayouts.detailsLayouts;
126 map = tableLayouts.listLayouts;
132 private LayoutLocaleMap getMapWithAdd(final String tableName, boolean details) {
133 TableLayouts tableLayouts = get(tableName);
134 if (tableLayouts == null) {
135 tableLayouts = new TableLayouts();
136 put(tableName, tableLayouts);
139 LayoutLocaleMap map = null;
141 if (tableLayouts.detailsLayouts == null) {
142 tableLayouts.detailsLayouts = new LayoutLocaleMap();
145 map = tableLayouts.detailsLayouts;
147 if (tableLayouts.listLayouts == null) {
148 tableLayouts.listLayouts = new LayoutLocaleMap();
151 map = tableLayouts.listLayouts;
157 private void setLayout(final String tableName, final String locale, final List<LayoutGroup> layout,
159 LayoutLocaleMap map = getMapWithAdd(tableName, details);
161 map.put(locale, layout);
166 private TableLayoutsForLocale mapTableLayouts = new TableLayoutsForLocale();
168 @SuppressWarnings("unused")
169 private ConfiguredDocument() {
170 // disable default constructor
173 ConfiguredDocument(final Document document) throws PropertyVetoException {
175 // load the jdbc driver
176 cpds = new ComboPooledDataSource();
178 // We don't support sqlite or self-hosting yet.
179 if (document.getHostingMode() != Document.HostingMode.HOSTING_MODE_POSTGRES_CENTRAL) {
180 Log.fatal("Error configuring the database connection." + " Only central PostgreSQL hosting is supported.");
181 // FIXME: Throw exception?
185 cpds.setDriverClass("org.postgresql.Driver");
186 } catch (final PropertyVetoException e) {
187 Log.fatal("Error loading the PostgreSQL JDBC driver."
188 + " Is the PostgreSQL JDBC jar available to the servlet?", e);
192 // setup the JDBC driver for the current glom document
193 cpds.setJdbcUrl("jdbc:postgresql://" + document.getConnectionServer() + ":" + document.getConnectionPort()
194 + "/" + document.getConnectionDatabase());
196 this.document = document;
200 * Sets the username and password for the database associated with the Glom document.
202 * @return true if the username and password works, false otherwise
204 boolean setUsernameAndPassword(final String username, final String password) throws SQLException {
205 cpds.setUser(username);
206 cpds.setPassword(password);
208 final int acquireRetryAttempts = cpds.getAcquireRetryAttempts();
209 cpds.setAcquireRetryAttempts(1);
210 Connection conn = null;
212 // FIXME find a better way to check authentication
213 // it's possible that the connection could be failing for another reason
214 conn = cpds.getConnection();
215 authenticated = true;
216 } catch (final SQLException e) {
217 Log.info(Utils.getFileName(document.getFileURI()), e.getMessage());
218 Log.info(Utils.getFileName(document.getFileURI()),
219 "Connection Failed. Maybe the username or password is not correct.");
220 authenticated = false;
224 cpds.setAcquireRetryAttempts(acquireRetryAttempts);
226 return authenticated;
229 Document getDocument() {
233 ComboPooledDataSource getCpds() {
237 boolean isAuthenticated() {
238 return authenticated;
241 String getDocumentID() {
245 void setDocumentID(final String documentID) {
246 this.documentID = documentID;
249 String getDefaultLocaleID() {
250 return defaultLocaleID;
253 void setDefaultLocaleID(final String localeID) {
254 this.defaultLocaleID = localeID;
260 DocumentInfo getDocumentInfo(final String localeID) {
261 final DocumentInfo documentInfo = new DocumentInfo();
263 // get arrays of table names and titles, and find the default table index
264 final List<String> tablesVec = document.getTableNames();
266 final int numTables = Utils.safeLongToInt(tablesVec.size());
267 // we don't know how many tables will be hidden so we'll use half of the number of tables for the default size
269 final ArrayList<String> tableNames = new ArrayList<String>(numTables / 2);
270 final ArrayList<String> tableTitles = new ArrayList<String>(numTables / 2);
271 boolean foundDefaultTable = false;
272 int visibleIndex = 0;
273 for (int i = 0; i < numTables; i++) {
274 final String tableName = tablesVec.get(i);
275 if (!document.getTableIsHidden(tableName)) {
276 tableNames.add(tableName);
277 // JNI is "expensive", the comparison will only be called if we haven't already found the default table
278 if (!foundDefaultTable && tableName.equals(document.getDefaultTable())) {
279 documentInfo.setDefaultTableIndex(visibleIndex);
280 foundDefaultTable = true;
282 tableTitles.add(document.getTableTitle(tableName, localeID));
287 // set everything we need
288 documentInfo.setTableNames(tableNames);
289 documentInfo.setTableTitles(tableTitles);
290 documentInfo.setTitle(document.getDatabaseTitle(localeID));
292 // Fetch arrays of locale IDs and titles:
293 final List<String> localesVec = document.getTranslationAvailableLocales();
294 final int numLocales = Utils.safeLongToInt(localesVec.size());
295 final ArrayList<String> localeIDs = new ArrayList<String>(numLocales);
296 final ArrayList<String> localeTitles = new ArrayList<String>(numLocales);
297 for (int i = 0; i < numLocales; i++) {
298 final String this_localeID = localesVec.get(i);
299 localeIDs.add(this_localeID);
301 // Use java.util.Locale to get a title for the locale:
302 final String[] locale_parts = this_localeID.split("_");
303 String locale_lang = this_localeID;
304 if (locale_parts.length > 0)
305 locale_lang = locale_parts[0];
306 String locale_country = "";
307 if (locale_parts.length > 1)
308 locale_country = locale_parts[1];
310 final Locale locale = new Locale(locale_lang, locale_country);
311 final String title = locale.getDisplayName(locale);
312 localeTitles.add(title);
314 documentInfo.setLocaleIDs(localeIDs);
315 documentInfo.setLocaleTitles(localeTitles);
321 * Gets the layout group for the list view using the defined layout list in the document or the table fields if
322 * there's no defined layout group for the list view.
324 private LayoutGroup getValidListViewLayoutGroup(final String tableName, final String localeID) {
326 // Try to return a cached version:
327 final LayoutGroup result = mapTableLayouts.getListLayout(tableName, localeID);
328 if (result != null) {
329 updateLayoutGroupExpectedResultSize(result, tableName);
333 final List<LayoutGroup> layoutGroupVec = document.getDataLayoutGroups("list", tableName);
335 final int listViewLayoutGroupSize = Utils.safeLongToInt(layoutGroupVec.size());
336 LayoutGroup libglomLayoutGroup = null;
337 if (listViewLayoutGroupSize > 0) {
338 // A list layout group is defined.
339 // We use the first group as the list.
340 if (listViewLayoutGroupSize > 1)
341 Log.warn(documentID, tableName, "The size of the list layout group is greater than 1. "
342 + "Attempting to use the first item for the layout list view.");
344 libglomLayoutGroup = layoutGroupVec.get(0);
346 // A list layout group is *not* defined; we are going make a LayoutGroup from the list of fields.
348 Log.info(documentID, tableName,
349 "A list layout is not defined for this table. Displaying a list layout based on the field list.");
351 final List<Field> fieldsVec = document.getTableFields(tableName);
352 libglomLayoutGroup = new LayoutGroup();
353 for (int i = 0; i < fieldsVec.size(); i++) {
354 final Field field = fieldsVec.get(i);
355 final LayoutItemField layoutItemField = new LayoutItemField();
356 layoutItemField.setFullFieldDetails(field);
357 libglomLayoutGroup.addItem(layoutItemField);
361 // TODO: Clone the group and change the clone, to discard unwanted information (such as translations)
362 // store some information that we do not want to calculate on the client side.
364 // Note that we don't use clone() here, because that would need clone() implementations
365 // in classes which are also used in the client code (though the clone() methods would
366 // not be used) and that makes the GWT java->javascript compilation fail.
367 final LayoutGroup cloned = (LayoutGroup) Utils.deepCopy(libglomLayoutGroup);
368 if (cloned != null) {
369 updateTopLevelListLayoutGroup(cloned, tableName, localeID);
371 // Discard unwanted translations so that getTitle(void) returns what we want.
372 updateTitlesForLocale(cloned, localeID);
375 // Store it in the cache for next time.
376 mapTableLayouts.setListLayout(tableName, localeID, cloned);
382 * @param libglomLayoutGroup
384 private void updateTopLevelListLayoutGroup(final LayoutGroup layoutGroup, final String tableName,
385 final String localeID) {
386 final List<LayoutItem> layoutItemsVec = layoutGroup.getItems();
388 int primaryKeyIndex = -1;
390 final int numItems = Utils.safeLongToInt(layoutItemsVec.size());
391 for (int i = 0; i < numItems; i++) {
392 final LayoutItem layoutItem = layoutItemsVec.get(i);
394 if (layoutItem instanceof LayoutItemField) {
395 LayoutItemField layoutItemField = (LayoutItemField) layoutItem;
396 final Field field = layoutItemField.getFullFieldDetails();
397 if ((field != null) && field.getPrimaryKey())
402 // Set the primary key index for the table
403 if (primaryKeyIndex < 0) {
404 // Add a LayoutItemField for the primary key to the end of the item list in the LayoutGroup because it
405 // doesn't already contain a primary key.
406 Field primaryKey = null;
407 final List<Field> fieldsVec = document.getTableFields(tableName);
408 for (int i = 0; i < Utils.safeLongToInt(fieldsVec.size()); i++) {
409 final Field field = fieldsVec.get(i);
410 if (field.getPrimaryKey()) {
416 if (primaryKey != null) {
417 final LayoutItemField layoutItemField = new LayoutItemField();
418 layoutItemField.setName(primaryKey.getName());
419 layoutItemField.setFullFieldDetails(primaryKey);
420 layoutGroup.addItem(layoutItemField);
421 layoutGroup.setPrimaryKeyIndex(layoutGroup.getItems().size() - 1);
422 layoutGroup.setHiddenPrimaryKey(true);
424 Log.error(document.getDatabaseTitleOriginal(), tableName,
425 "A primary key was not found in the FieldVector for this table. Navigation buttons will not work.");
428 layoutGroup.setPrimaryKeyIndex(primaryKeyIndex);
432 private void updateLayoutGroupExpectedResultSize(final LayoutGroup layoutGroup, final String tableName) {
433 final ListViewDBAccess listViewDBAccess = new ListViewDBAccess(document, documentID, cpds, tableName,
435 layoutGroup.setExpectedResultSize(listViewDBAccess.getExpectedResultSize());
438 ArrayList<DataItem[]> getListViewData(String tableName, final String quickFind, final int start, final int length,
439 final boolean useSortClause, final int sortColumnIndex, final boolean isAscending) {
440 // Validate the table name.
441 tableName = getTableNameToUse(tableName);
443 // Get the LayoutGroup that represents the list view.
444 // TODO: Performance: Avoid calling this again:
445 final LayoutGroup libglomLayoutGroup = getValidListViewLayoutGroup(tableName, "" /* irrelevant locale */);
447 // Create a database access object for the list view.
448 final ListViewDBAccess listViewDBAccess = new ListViewDBAccess(document, documentID, cpds, tableName,
452 return listViewDBAccess.getData(quickFind, start, length, useSortClause, sortColumnIndex, isAscending);
455 DataItem[] getDetailsData(String tableName, final TypedDataItem primaryKeyValue) {
456 // Validate the table name.
457 tableName = getTableNameToUse(tableName);
459 final DetailsDBAccess detailsDBAccess = new DetailsDBAccess(document, documentID, cpds, tableName);
461 return detailsDBAccess.getData(primaryKeyValue);
464 ArrayList<DataItem[]> getRelatedListData(String tableName, final LayoutItemPortal portal,
465 final TypedDataItem foreignKeyValue, final int start, final int length, final boolean useSortClause,
466 final int sortColumnIndex, final boolean isAscending) {
467 if (portal == null) {
468 Log.error("getRelatedListData(): portal is null");
472 // Validate the table name.
473 tableName = getTableNameToUse(tableName);
475 // Create a database access object for the related list
476 final RelatedListDBAccess relatedListDBAccess = new RelatedListDBAccess(document, documentID, cpds, tableName,
480 return relatedListDBAccess.getData(start, length, foreignKeyValue, useSortClause, sortColumnIndex, isAscending);
483 List<LayoutGroup> getDetailsLayoutGroup(String tableName, final String localeID) {
484 // Validate the table name.
485 tableName = getTableNameToUse(tableName);
487 // Try to return a cached version:
488 final List<LayoutGroup> result = mapTableLayouts.getDetailsLayout(tableName, localeID);
489 if (result != null) {
490 updatePortalsExtras(result, tableName); // Update expected results sizes.
494 final List<LayoutGroup> listGroups = document.getDataLayoutGroups("details", tableName);
496 // Clone the group and change the clone, to discard unwanted information (such as translations)
497 // and to store some information that we do not want to calculate on the client side.
499 // Note that we don't use clone() here, because that would need clone() implementations
500 // in classes which are also used in the client code (though the clone() methods would
501 // not be used) and that makes the GWT java->javascript compilation fail.
502 final List<LayoutGroup> listCloned = new ArrayList<LayoutGroup>();
503 for (LayoutGroup group : listGroups) {
504 final LayoutGroup cloned = (LayoutGroup) Utils.deepCopy(group);
505 if (cloned != null) {
506 listCloned.add(cloned);
510 updatePortalsExtras(listCloned, tableName);
511 updateFieldsExtras(listCloned, tableName);
513 // Discard unwanted translations so that getTitle(void) returns what we want.
514 updateTitlesForLocale(listCloned, localeID);
516 // Store it in the cache for next time.
517 mapTableLayouts.setDetailsLayout(tableName, localeID, listCloned);
526 private void updatePortalsExtras(List<LayoutGroup> listGroups, String tableName) {
527 for (LayoutGroup group : listGroups) {
528 updatePortalsExtras(group, tableName);
537 private void updateFieldsExtras(final List<LayoutGroup> listGroups, String tableName) {
538 for (LayoutGroup group : listGroups) {
539 updateFieldsExtras(group, tableName);
547 private void updateTitlesForLocale(final List<LayoutGroup> listGroups, String localeID) {
548 for (LayoutGroup group : listGroups) {
549 updateTitlesForLocale(group, localeID);
553 private void updatePortalsExtras(LayoutGroup group, String tableName) {
554 if (group instanceof LayoutItemPortal) {
555 final LayoutItemPortal portal = (LayoutItemPortal) group;
556 final String tableNameUsed = portal.getTableUsed(tableName);
557 updateLayoutGroupExpectedResultSize(portal, tableNameUsed);
559 final Relationship relationship = portal.getRelationship();
560 if (relationship != null) {
562 // Cache the navigation information:
563 // layoutItemPortal.set_name(libglomLayoutItemPortal.get_relationship_name_used());
564 // layoutItemPortal.setTableName(relationship.get_from_table());
565 // layoutItemPortal.setFromField(relationship.get_from_field());
567 // Set whether the related list will need to show the navigation buttons,
568 // (null table name string if not) and what table to navigation to.
569 // This was ported from Glom: Box_Data_Portal::get_has_suitable_record_to_view_details()
570 final TableToViewDetails viewDetails = document.getPortalSuitableTableToViewDetails(portal);
571 if (viewDetails != null) {
572 portal.setNavigationTable(viewDetails);
575 // get the primary key for the related list table
576 final String toTableName = relationship.getToTable();
577 if (!StringUtils.isEmpty(toTableName)) {
579 // get the LayoutItemField with details from its Field in the document
580 final List<Field> fields = document.getTableFields(toTableName); // TODO_Performance: Cache this.
581 for (Field field : fields) {
582 // check the names to see if they're the same
583 if (field.getPrimaryKey()) {
584 final LayoutItemField layoutItemField = new LayoutItemField();
585 layoutItemField.setName(field.getName());
586 layoutItemField.setFullFieldDetails(field);
587 portal.addItem(layoutItemField);
588 portal.setPrimaryKeyIndex(portal.getItems().size() - 1);
589 portal.setHiddenPrimaryKey(true); // always hidden in portals
598 List<LayoutItem> childItems = group.getItems();
599 for (LayoutItem item : childItems) {
600 if (item instanceof LayoutGroup) {
601 final LayoutGroup childGroup = (LayoutGroup) item;
602 updatePortalsExtras(childGroup, tableName);
608 private void updateFieldsExtras(final LayoutGroup group, final String tableName) {
610 List<LayoutItem> childItems = group.getItems();
611 for (LayoutItem item : childItems) {
612 if (item instanceof LayoutGroup) {
614 final LayoutGroup childGroup = (LayoutGroup) item;
615 updateFieldsExtras(childGroup, tableName);
616 } else if (item instanceof LayoutItemField) {
617 final LayoutItemField field = (LayoutItemField) item;
619 // Set whether the field should have a navigation button,
620 // because it identifies a related record.
621 final String navigationTableName = document.getLayoutItemFieldShouldHaveNavigation(tableName, field);
622 if (navigationTableName != null) {
623 field.setNavigationTableName(navigationTableName);
629 private void updateTitlesForLocale(final LayoutGroup group, final String localeID) {
631 updateItemTitlesForLocale(group, localeID);
633 List<LayoutItem> childItems = group.getItems();
634 for (LayoutItem item : childItems) {
636 // Call makeTitleOriginal on all Translatable items and all special
637 // Translatable items that they use:
638 if (item instanceof LayoutItemField) {
639 final LayoutItemField layoutItemField = (LayoutItemField) item;
641 final Field field = layoutItemField.getFullFieldDetails();
643 field.makeTitleOriginal(localeID);
646 final CustomTitle customTitle = layoutItemField.getCustomTitle();
647 if (customTitle != null) {
648 customTitle.makeTitleOriginal(localeID);
652 updateItemTitlesForLocale(item, localeID);
654 if (item instanceof LayoutGroup) {
656 final LayoutGroup childGroup = (LayoutGroup) item;
657 updateTitlesForLocale(childGroup, localeID);
662 private void updateItemTitlesForLocale(LayoutItem item, final String localeID) {
663 if (item instanceof UsesRelationship) {
664 final UsesRelationship usesRelationship = (UsesRelationship) item;
665 final Relationship rel = usesRelationship.getRelationship();
668 rel.makeTitleOriginal(localeID);
671 final Relationship relatedRel = usesRelationship.getRelatedRelationship();
672 if (relatedRel != null) {
673 relatedRel.makeTitleOriginal(localeID);
677 if (item instanceof Translatable) {
678 final Translatable translatable = item;
679 translatable.makeTitleOriginal(localeID);
684 * Gets the expected row count for a related list.
686 int getRelatedListRowCount(String tableName, final LayoutItemPortal portal, final TypedDataItem foreignKeyValue) {
687 if (portal == null) {
688 Log.error("getRelatedListData(): portal is null");
692 // Validate the table name.
693 tableName = getTableNameToUse(tableName);
695 // Create a database access object for the related list
696 final RelatedListDBAccess relatedListDBAccess = new RelatedListDBAccess(document, documentID, cpds, tableName,
699 // Return the row count
700 return relatedListDBAccess.getExpectedResultSize(foreignKeyValue);
703 NavigationRecord getSuitableRecordToViewDetails(String tableName, final LayoutItemPortal portal,
704 final TypedDataItem primaryKeyValue) {
705 // Validate the table name.
706 tableName = getTableNameToUse(tableName);
708 final RelatedListNavigation relatedListNavigation = new RelatedListNavigation(document, documentID, cpds,
711 return relatedListNavigation.getNavigationRecord(primaryKeyValue);
714 LayoutGroup getListViewLayoutGroup(String tableName, final String localeID) {
715 // Validate the table name.
716 tableName = getTableNameToUse(tableName);
717 return getValidListViewLayoutGroup(tableName, localeID);
721 * Gets the table name to use when accessing the database and the document. This method guards against SQL injection
722 * attacks by returning the default table if the requested table is not in the database or if the table name has not
726 * The table name to validate.
727 * @return The table name to use.
729 private String getTableNameToUse(final String tableName) {
730 if (StringUtils.isEmpty(tableName) || !document.getTableIsKnown(tableName)) {
731 return document.getDefaultTable();
741 public Reports getReports(final String tableName, final String localeID) {
742 final Reports result = new Reports();
744 final List<String> names = document.getReportNames(tableName);
746 final int count = Utils.safeLongToInt(names.size());
747 for (int i = 0; i < count; i++) {
748 final String name = names.get(i);
749 final Report report = document.getReport(tableName, name);
753 final String title = report.getTitle(localeID);
754 result.addReport(name, title);