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