Improve browser configuration error messages.
[online-glom:gwt-glom.git] / src / main / java / org / glom / web / server / OnlineGlomServiceImpl.java
1 /*
2  * Copyright (C) 2010, 2011 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.FilenameFilter;
24 import java.io.InputStream;
25 import java.sql.SQLException;
26 import java.util.ArrayList;
27 import java.util.Hashtable;
28 import java.util.Properties;
29
30 import javax.servlet.ServletException;
31
32 import org.glom.libglom.BakeryDocument.LoadFailureCodes;
33 import org.glom.libglom.Document;
34 import org.glom.libglom.Glom;
35 import org.glom.web.client.OnlineGlomService;
36 import org.glom.web.shared.DataItem;
37 import org.glom.web.shared.DetailsLayoutAndData;
38 import org.glom.web.shared.DocumentInfo;
39 import org.glom.web.shared.Documents;
40 import org.glom.web.shared.NavigationRecord;
41 import org.glom.web.shared.PrimaryKeyItem;
42 import org.glom.web.shared.layout.LayoutGroup;
43
44 import com.google.gwt.user.server.rpc.RemoteServiceServlet;
45 import com.mchange.v2.c3p0.DataSources;
46
47 /**
48  * The servlet class for setting up the server side of Online Glom. The public methods in this class are the methods
49  * that can be called by the client side code.
50  * 
51  * @author Ben Konrath <ben@bagu.org>
52  */
53 @SuppressWarnings("serial")
54 public class OnlineGlomServiceImpl extends RemoteServiceServlet implements OnlineGlomService {
55
56         private static final String GLOM_FILE_EXTENSION = ".glom";
57
58         // convenience class to for dealing with the Online Glom configuration file
59         private class OnlineGlomProperties extends Properties {
60                 public String getKey(String value) {
61                         for (String key : stringPropertyNames()) {
62                                 if (getProperty(key).trim().equals(value))
63                                         return key;
64                         }
65                         return null;
66                 }
67         }
68
69         private final Hashtable<String, ConfiguredDocument> documentMapping = new Hashtable<String, ConfiguredDocument>();
70         private Exception configurtionException = null;
71
72         /*
73          * This is called when the servlet is started or restarted.
74          * 
75          * (non-Javadoc)
76          * 
77          * @see javax.servlet.GenericServlet#init()
78          */
79         @Override
80         public void init() throws ServletException {
81
82                 // All of the initialisation code is surrounded by a try/catch block so that the servlet can be in an
83                 // initialised state and the error message can be retrived by the client code.
84                 try {
85                         // Find the configuration file. See this thread for background info:
86                         // http://stackoverflow.com/questions/2161054/where-to-place-properties-files-in-a-jsp-servlet-web-application
87                         // FIXME move onlineglom.properties to the WEB-INF folder (option number 2 from the stackoverflow question)
88                         OnlineGlomProperties config = new OnlineGlomProperties();
89                         InputStream is = Thread.currentThread().getContextClassLoader()
90                                         .getResourceAsStream("onlineglom.properties");
91                         if (is == null) {
92                                 String errorMessage = "onlineglom.properties not found.";
93                                 Log.fatal(errorMessage);
94                                 throw new Exception(errorMessage);
95                         }
96                         config.load(is); // can throw an IOException
97
98                         // check if we can read the configured glom file directory
99                         String documentDirName = config.getProperty("glom.document.directory");
100                         File documentDir = new File(documentDirName);
101                         if (!documentDir.isDirectory()) {
102                                 String errorMessage = documentDirName + " is not a directory.";
103                                 Log.fatal(errorMessage);
104                                 throw new Exception(errorMessage);
105                         }
106                         if (!documentDir.canRead()) {
107                                 String errorMessage = "Can't read the files in directory " + documentDirName + " .";
108                                 Log.fatal(errorMessage);
109                                 throw new Exception(errorMessage);
110                         }
111
112                         // get and check the glom files in the specified directory
113                         File[] glomFiles = documentDir.listFiles(new FilenameFilter() {
114                                 @Override
115                                 public boolean accept(File dir, String name) {
116                                         return name.endsWith(GLOM_FILE_EXTENSION);
117                                 }
118                         });
119
120                         // don't continue if there aren't any Glom files to configure
121                         if (glomFiles.length <= 0) {
122                                 String errorMessage = "Unable to find any Glom documents in the configured directory "
123                                                 + documentDirName
124                                                 + " . Check the onlineglom.properties file to ensure that 'glom.document.directory' is set to the correct directory.";
125                                 Log.error(errorMessage);
126                                 throw new Exception(errorMessage);
127                         }
128
129                         // intitize libglom
130                         Glom.libglom_init(); // can throw an UnsatisfiedLinkError exception
131
132                         // Allow a fake connection, so sqlbuilder_get_full_query() can work:
133                         Glom.set_fake_connection();
134
135                         for (File glomFile : glomFiles) {
136                                 Document document = new Document();
137                                 document.set_file_uri("file://" + glomFile.getAbsolutePath());
138                                 int error = 0;
139                                 boolean retval = document.load(error);
140                                 if (retval == false) {
141                                         String message;
142                                         if (LoadFailureCodes.LOAD_FAILURE_CODE_NOT_FOUND == LoadFailureCodes.swigToEnum(error)) {
143                                                 message = "Could not find file: " + glomFile.getAbsolutePath();
144                                         } else {
145                                                 message = "An unknown error occurred when trying to load file: " + glomFile.getAbsolutePath();
146                                         }
147                                         Log.error(message);
148                                         // continue with for loop because there may be other documents in the directory
149                                         continue;
150                                 }
151
152                                 ConfiguredDocument configuredDocument = new ConfiguredDocument(document); // can throw a
153                                                                                                                                                                                         // PropertyVetoException
154
155                                 // check if a username and password have been set and work for the current document
156                                 String filename = glomFile.getName();
157                                 String key = config.getKey(filename);
158                                 if (key != null) {
159                                         String[] keyArray = key.split("\\.");
160                                         if (keyArray.length == 3 && "filename".equals(keyArray[2])) {
161                                                 // username/password could be set, let's check to see if it works
162                                                 String usernameKey = key.replaceAll(keyArray[2], "username");
163                                                 String passwordKey = key.replaceAll(keyArray[2], "password");
164                                                 configuredDocument.setUsernameAndPassword(config.getProperty(usernameKey).trim(),
165                                                                 config.getProperty(passwordKey)); // can throw an SQLException
166                                         }
167                                 }
168
169                                 // check the if the global username and password have been set and work with this document
170                                 if (!configuredDocument.isAuthenticated()) {
171                                         configuredDocument.setUsernameAndPassword(config.getProperty("glom.document.username").trim(),
172                                                         config.getProperty("glom.document.password")); // can throw an SQLException
173                                 }
174
175                                 // The key for the hash table is the file name without the .glom extension and with spaces ( ) replaced
176                                 // with pluses (+). The space/plus replacement makes the key more friendly for URLs.
177                                 String documentID = filename.substring(0, glomFile.getName().length() - GLOM_FILE_EXTENSION.length())
178                                                 .replace(' ', '+');
179                                 configuredDocument.setDocumentID(documentID);
180                                 documentMapping.put(documentID, configuredDocument);
181                         }
182
183                 } catch (Exception e) {
184                         // Don't throw the Exception so that servlet will be initialised and the error message can be retrieved.
185                         configurtionException = e;
186                 }
187
188         }
189
190         /*
191          * This is called when the servlet is stopped or restarted.
192          * 
193          * @see javax.servlet.GenericServlet#destroy()
194          */
195         @Override
196         public void destroy() {
197                 Glom.libglom_deinit();
198
199                 for (String documenTitle : documentMapping.keySet()) {
200                         ConfiguredDocument configuredDoc = documentMapping.get(documenTitle);
201                         try {
202                                 DataSources.destroy(configuredDoc.getCpds());
203                         } catch (SQLException e) {
204                                 Log.error(documenTitle, "Error cleaning up the ComboPooledDataSource.", e);
205                         }
206                 }
207         }
208
209         /*
210          * (non-Javadoc)
211          * 
212          * @see org.glom.web.client.OnlineGlomService#getConfigurationErrorMessage()
213          */
214         @Override
215         public String getConfigurationErrorMessage() {
216                 if (configurtionException == null)
217                         return "No configuration errors to report.";
218                 else
219                         return configurtionException.getMessage();
220         }
221
222         /*
223          * (non-Javadoc)
224          * 
225          * @see org.glom.web.client.OnlineGlomService#getDocumentInfo(java.lang.String)
226          */
227         @Override
228         public DocumentInfo getDocumentInfo(String documentID) {
229
230                 ConfiguredDocument configuredDoc = documentMapping.get(documentID);
231
232                 // FIXME check for authentication
233
234                 return configuredDoc.getDocumentInfo();
235
236         }
237
238         /*
239          * (non-Javadoc)
240          * 
241          * @see org.glom.web.client.OnlineGlomService#getListViewLayout(java.lang.String, java.lang.String)
242          */
243         @Override
244         public LayoutGroup getListViewLayout(String documentID, String tableName) {
245                 ConfiguredDocument configuredDoc = documentMapping.get(documentID);
246
247                 // FIXME check for authentication
248
249                 return configuredDoc.getListViewLayoutGroup(tableName);
250         }
251
252         /*
253          * (non-Javadoc)
254          * 
255          * @see org.glom.web.client.OnlineGlomService#getListViewData(java.lang.String, java.lang.String, int, int)
256          */
257         @Override
258         public ArrayList<DataItem[]> getListViewData(String documentID, String tableName, int start, int length) {
259                 ConfiguredDocument configuredDoc = documentMapping.get(documentID);
260                 if (!configuredDoc.isAuthenticated()) {
261                         return new ArrayList<DataItem[]>();
262                 }
263                 return configuredDoc.getListViewData(tableName, start, length, false, 0, false);
264         }
265
266         /*
267          * (non-Javadoc)
268          * 
269          * @see org.glom.web.client.OnlineGlomService#getSortedListViewData(java.lang.String, java.lang.String, int, int,
270          * int, boolean)
271          */
272         @Override
273         public ArrayList<DataItem[]> getSortedListViewData(String documentID, String tableName, int start, int length,
274                         int sortColumnIndex, boolean isAscending) {
275                 ConfiguredDocument configuredDoc = documentMapping.get(documentID);
276                 if (!configuredDoc.isAuthenticated()) {
277                         return new ArrayList<DataItem[]>();
278                 }
279                 return configuredDoc.getListViewData(tableName, start, length, true, sortColumnIndex, isAscending);
280         }
281
282         /*
283          * (non-Javadoc)
284          * 
285          * @see org.glom.web.client.OnlineGlomService#getDocuments()
286          */
287         @Override
288         public Documents getDocuments() {
289                 Documents documents = new Documents();
290                 for (String documentID : documentMapping.keySet()) {
291                         ConfiguredDocument configuredDoc = documentMapping.get(documentID);
292                         documents.addDocument(documentID, configuredDoc.getDocument().get_database_title());
293                 }
294                 return documents;
295         }
296
297         /*
298          * (non-Javadoc)
299          * 
300          * @see org.glom.web.client.OnlineGlomService#isAuthenticated(java.lang.String)
301          */
302         public boolean isAuthenticated(String documentID) {
303                 return documentMapping.get(documentID).isAuthenticated();
304         }
305
306         /*
307          * (non-Javadoc)
308          * 
309          * @see org.glom.web.client.OnlineGlomService#checkAuthentication(java.lang.String, java.lang.String,
310          * java.lang.String)
311          */
312         @Override
313         public boolean checkAuthentication(String documentID, String username, String password) {
314                 ConfiguredDocument configuredDoc = documentMapping.get(documentID);
315                 try {
316                         return configuredDoc.setUsernameAndPassword(username, password);
317                 } catch (SQLException e) {
318                         Log.error(documentID, "Unknown SQL Error checking the database authentication.", e);
319                         return false;
320                 }
321         }
322
323         /*
324          * (non-Javadoc)
325          * 
326          * @see org.glom.web.client.OnlineGlomService#getDetailsData(java.lang.String, java.lang.String, java.lang.String)
327          */
328         @Override
329         public DataItem[] getDetailsData(String documentID, String tableName, PrimaryKeyItem primaryKeyValue) {
330                 ConfiguredDocument configuredDoc = documentMapping.get(documentID);
331
332                 // FIXME check for authentication
333
334                 return configuredDoc.getDetailsData(tableName, primaryKeyValue);
335         }
336
337         /*
338          * (non-Javadoc)
339          * 
340          * @see org.glom.web.client.OnlineGlomService#getDetailsLayoutAndData(java.lang.String, java.lang.String,
341          * java.lang.String)
342          */
343         @Override
344         public DetailsLayoutAndData getDetailsLayoutAndData(String documentID, String tableName,
345                         PrimaryKeyItem primaryKeyValue) {
346                 ConfiguredDocument configuredDoc = documentMapping.get(documentID);
347                 if (configuredDoc == null)
348                         return null;
349
350                 // FIXME check for authentication
351
352                 DetailsLayoutAndData initalDetailsView = new DetailsLayoutAndData();
353                 initalDetailsView.setLayout(configuredDoc.getDetailsLayoutGroup(tableName));
354                 initalDetailsView.setData(configuredDoc.getDetailsData(tableName, primaryKeyValue));
355
356                 return initalDetailsView;
357         }
358
359         /*
360          * (non-Javadoc)
361          * 
362          * @see org.glom.web.client.OnlineGlomService#getRelatedListData(java.lang.String, java.lang.String, int, int)
363          */
364         @Override
365         public ArrayList<DataItem[]> getRelatedListData(String documentID, String tableName, String relationshipName,
366                         PrimaryKeyItem foreignKeyValue, int start, int length) {
367                 ConfiguredDocument configuredDoc = documentMapping.get(documentID);
368
369                 // FIXME check for authentication
370
371                 return configuredDoc.getRelatedListData(tableName, relationshipName, foreignKeyValue, start, length, false, 0,
372                                 false);
373         }
374
375         /*
376          * (non-Javadoc)
377          * 
378          * @see org.glom.web.client.OnlineGlomService#getSortedRelatedListData(java.lang.String, java.lang.String, int, int,
379          * int, boolean)
380          */
381         @Override
382         public ArrayList<DataItem[]> getSortedRelatedListData(String documentID, String tableName, String relationshipName,
383                         PrimaryKeyItem foreignKeyValue, int start, int length, int sortColumnIndex, boolean ascending) {
384                 ConfiguredDocument configuredDoc = documentMapping.get(documentID);
385
386                 // FIXME check for authentication
387
388                 return configuredDoc.getRelatedListData(tableName, relationshipName, foreignKeyValue, start, length, true,
389                                 sortColumnIndex, ascending);
390         }
391
392         public int getRelatedListRowCount(String documentID, String tableName, String relationshipName,
393                         PrimaryKeyItem foreignKeyValue) {
394                 ConfiguredDocument configuredDoc = documentMapping.get(documentID);
395
396                 // FIXME check for authentication
397
398                 return configuredDoc.getRelatedListRowCount(tableName, relationshipName, foreignKeyValue);
399         }
400
401         /*
402          * (non-Javadoc)
403          * 
404          * @see org.glom.web.client.OnlineGlomService#getSuitableRecordToViewDetails(java.lang.String, java.lang.String,
405          * java.lang.String, java.lang.String)
406          */
407         @Override
408         public NavigationRecord getSuitableRecordToViewDetails(String documentID, String tableName,
409                         String relationshipName, PrimaryKeyItem primaryKeyValue) {
410                 ConfiguredDocument configuredDoc = documentMapping.get(documentID);
411
412                 // FIXME check for authentication
413
414                 return configuredDoc.getSuitableRecordToViewDetails(tableName, relationshipName, primaryKeyValue);
415         }
416
417 }