Details: Show images.
[online-glom:gwt-glom.git] / src / main / java / org / glom / web / server / ConfiguredDocumentSet.java
1 /*
2  * Copyright (C) 2012 Openismus GmbH
3  *
4  * This file is part of GWT-Glom.
5  *
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.
10  *
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
14  * for more details.
15  *
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/>.
18  */
19
20 package org.glom.web.server;
21
22 import java.io.File;
23 import java.io.InputStream;
24 import java.sql.SQLException;
25 import java.util.Collection;
26 import java.util.Hashtable;
27 import java.util.List;
28
29 import javax.servlet.ServletException;
30
31 import org.apache.commons.io.FileUtils;
32 import org.apache.commons.io.FilenameUtils;
33 import org.apache.commons.lang3.StringUtils;
34 import org.glom.web.server.OnlineGlomProperties.Credentials;
35 import org.glom.web.server.libglom.Document;
36 import org.glom.web.shared.Documents;
37
38 import com.mchange.v2.c3p0.DataSources;
39
40 /**
41  * @author  Murray Cumming <murrayc@openismus.com>
42  */
43 public class ConfiguredDocumentSet {
44         private static final String GLOM_FILE_EXTENSION = "glom";
45
46         private Hashtable<String, ConfiguredDocument> documentMapping = new Hashtable<String, ConfiguredDocument>();
47         private Exception configurationException = null;
48
49         /**
50          * 
51          */
52         public ConfiguredDocumentSet() {
53         }
54         
55         public ConfiguredDocument getDocument(final String documentID) {
56                 return documentMapping.get(documentID);
57         }
58         
59         public Exception getConfigurationException() {
60                 return configurationException;
61         }
62
63         private void addDocument(final ConfiguredDocument configuredDocument, final String filename) {
64                 // The key for the hash table is the file name without the .glom extension and with spaces ( ) replaced
65                 // with pluses (+). The space/plus replacement makes the key more friendly for URLs.
66                 final String documentID = FilenameUtils.removeExtension(filename).replace(' ', '+');
67                 configuredDocument.setDocumentID(documentID);
68         
69                 documentMapping.put(documentID, configuredDocument);
70         }
71         
72         
73
74         public void readConfiguration() throws ServletException {
75         
76                 // All of the initialisation code is surrounded by a try/catch block so that the servlet can be in an
77                 // initialised state and the error message can be retrieved by the client code.
78                 try {
79                         // Find the configuration file. See this thread for background info:
80                         // http://stackoverflow.com/questions/2161054/where-to-place-properties-files-in-a-jsp-servlet-web-application
81                         final OnlineGlomProperties config = new OnlineGlomProperties();
82                         final InputStream is = Thread.currentThread().getContextClassLoader()
83                                         .getResourceAsStream("onlineglom.properties");
84                         if (is == null) {
85                                 final String errorMessage = "onlineglom.properties not found.";
86                                 Log.fatal(errorMessage);
87                                 throw new Exception(errorMessage);
88                         }
89                         config.load(is); // can throw an IOException
90         
91                         // check if we can read the configured glom file directory
92                         final String documentDirName = config.getDocumentsDirectory();
93                         final File documentDir = new File(documentDirName);
94                         if (!documentDir.isDirectory()) {
95                                 final String errorMessage = documentDirName + " is not a directory.";
96                                 Log.fatal(errorMessage);
97                                 throw new Exception(errorMessage);
98                         }
99                         if (!documentDir.canRead()) {
100                                 final String errorMessage = "Can't read the files in directory " + documentDirName + " .";
101                                 Log.fatal(errorMessage);
102                                 throw new Exception(errorMessage);
103                         }
104         
105                         // get and check the glom files in the specified directory
106                         // TODO: Test this:
107                         final String[] extensions = { GLOM_FILE_EXTENSION };
108                         final Collection<?> glomFiles = FileUtils.listFiles(documentDir, extensions, true /* recursive */);
109                         if(!(glomFiles instanceof List<?>)) {
110                                 final String errorMessage = "onlineglom.properties: listFiles() failed.";
111                                 Log.fatal(errorMessage);
112                                 throw new Exception(errorMessage);
113                         }
114         
115                         // don't continue if there aren't any Glom files to configure
116                         if (glomFiles.size() <= 0) {
117                                 final String errorMessage = "Unable to find any Glom documents in the configured directory "
118                                                 + documentDirName
119                                                 + " . Check the onlineglom.properties file to ensure that 'glom.document.directory' is set to the correct directory.";
120                                 Log.error(errorMessage);
121                                 throw new Exception(errorMessage);
122                         }
123         
124                         // Check for a specified default locale,
125                         // for table titles, field titles, etc:
126                         final String globalLocaleID = StringUtils.defaultString(config.getGlobalLocale());
127         
128                         for (final Object objGlomFile : glomFiles) {
129                                 if(!(objGlomFile instanceof File)) {
130                                         continue;
131                                 }
132                                 
133                                 final File glomFile = (File)objGlomFile;
134         
135                                 final Document document = new Document();
136                                 document.setFileURI("file://" + glomFile.getAbsolutePath());
137                                 final boolean retval = document.load();
138                                 if (retval == false) {
139                                         final String message = "An error occurred when trying to load file: " + glomFile.getAbsolutePath();
140                                         Log.error(message);
141                                         // continue with for loop because there may be other documents in the directory
142                                         continue;
143                                 }
144         
145                                 final ConfiguredDocument configuredDocument = new ConfiguredDocument(document); // can throw a
146                                 // PropertyVetoException
147         
148                                 final String globalUserName = config.getGlobalUsername();
149                                 final String globalPassword = config.getGlobalPassword();
150         
151                                 // check if a username and password have been set and work for the current document
152                                 final String filename = glomFile.getName();
153                                 
154                                 // Username/password could be set. Let's check to see if it works.
155                                 final Credentials docCredentials = config.getCredentials(filename);
156                                 if(docCredentials != null) {
157                                                 configuredDocument.setUsernameAndPassword(docCredentials.userName, docCredentials.password); // can throw an SQLException
158                                 }
159         
160                                 // check the if the global username and password have been set and work with this document
161                                 if (!configuredDocument.isAuthenticated()) {
162                                         configuredDocument.setUsernameAndPassword(globalUserName, globalPassword); // can throw an SQLException
163                                 }
164         
165                                 if (!StringUtils.isEmpty(globalLocaleID)) {
166                                         configuredDocument.setDefaultLocaleID(globalLocaleID.trim());
167                                 }
168         
169                                 addDocument(configuredDocument, filename);
170                         }
171         
172                 } catch (final Exception e) {
173                         // Don't throw the Exception so that servlet will be initialised and the error message can be retrieved.
174                         configurationException = e;
175                 }
176         
177         }
178
179         /**
180          * 
181          */
182         public void forgetDocuments() {
183                 for (final String documentID : documentMapping.keySet()) {
184                         final ConfiguredDocument configuredDoc = getDocument(documentID);
185                         if (configuredDoc == null) {
186                                 continue;
187                         }
188
189                         try {
190                                 DataSources.destroy(configuredDoc.getCpds());
191                         } catch (final SQLException e) {
192                                 Log.error(documentID, "Error cleaning up the ComboPooledDataSource.", e);
193                         }
194                 }
195                 
196         }
197
198         /**
199          * @return
200          */
201         public Documents getDocuments() {
202                 final Documents documents = new Documents();
203                 for (final String documentID : documentMapping.keySet()) {
204                         final ConfiguredDocument configuredDoc = getDocument(documentID);
205                         if (configuredDoc == null) {
206                                 continue;
207                         }
208
209                         final Document glomDocument = configuredDoc.getDocument();
210                         if (glomDocument == null) {
211                                 final String errorMessage = "getDocuments(): getDocument() failed.";
212                                 Log.fatal(errorMessage);
213                                 // TODO: throw new Exception(errorMessage);
214                                 continue;
215                         }
216
217                         final String localeID = StringUtils.defaultString(configuredDoc.getDefaultLocaleID());
218                         documents.addDocument(documentID, glomDocument.getDatabaseTitle(localeID), localeID);
219                 }
220                 return documents;
221         }
222 }