Rename PrimaryKeyItem to TypedDataItem.
[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.TypedDataItem;
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                         // Check to see if the native library of java libglom is visible to the JVM
130                         if (!isNativeLibraryVisibleToJVM())
131                                 throw new Exception("The java-libglom shared library is not visible to the JVM."
132                                                 + " Ensure that 'java.library.path' is set with the path to the java-libglom shared library.");
133
134                         // intitize libglom
135                         Glom.libglom_init(); // can throw an UnsatisfiedLinkError exception
136
137                         // Allow a fake connection, so sqlbuilder_get_full_query() can work:
138                         Glom.set_fake_connection();
139
140                         for (File glomFile : glomFiles) {
141                                 Document document = new Document();
142                                 document.set_file_uri("file://" + glomFile.getAbsolutePath());
143                                 int error = 0;
144                                 boolean retval = document.load(error);
145                                 if (retval == false) {
146                                         String message;
147                                         if (LoadFailureCodes.LOAD_FAILURE_CODE_NOT_FOUND == LoadFailureCodes.swigToEnum(error)) {
148                                                 message = "Could not find file: " + glomFile.getAbsolutePath();
149                                         } else {
150                                                 message = "An unknown error occurred when trying to load file: " + glomFile.getAbsolutePath();
151                                         }
152                                         Log.error(message);
153                                         // continue with for loop because there may be other documents in the directory
154                                         continue;
155                                 }
156
157                                 ConfiguredDocument configuredDocument = new ConfiguredDocument(document); // can throw a
158                                                                                                                                                                                         // PropertyVetoException
159
160                                 // check if a username and password have been set and work for the current document
161                                 String filename = glomFile.getName();
162                                 String key = config.getKey(filename);
163                                 if (key != null) {
164                                         String[] keyArray = key.split("\\.");
165                                         if (keyArray.length == 3 && "filename".equals(keyArray[2])) {
166                                                 // username/password could be set, let's check to see if it works
167                                                 String usernameKey = key.replaceAll(keyArray[2], "username");
168                                                 String passwordKey = key.replaceAll(keyArray[2], "password");
169                                                 configuredDocument.setUsernameAndPassword(config.getProperty(usernameKey).trim(),
170                                                                 config.getProperty(passwordKey)); // can throw an SQLException
171                                         }
172                                 }
173
174                                 // check the if the global username and password have been set and work with this document
175                                 if (!configuredDocument.isAuthenticated()) {
176                                         configuredDocument.setUsernameAndPassword(config.getProperty("glom.document.username").trim(),
177                                                         config.getProperty("glom.document.password")); // can throw an SQLException
178                                 }
179
180                                 // The key for the hash table is the file name without the .glom extension and with spaces ( ) replaced
181                                 // with pluses (+). The space/plus replacement makes the key more friendly for URLs.
182                                 String documentID = filename.substring(0, glomFile.getName().length() - GLOM_FILE_EXTENSION.length())
183                                                 .replace(' ', '+');
184                                 configuredDocument.setDocumentID(documentID);
185                                 documentMapping.put(documentID, configuredDocument);
186                         }
187
188                 } catch (Exception e) {
189                         // Don't throw the Exception so that servlet will be initialised and the error message can be retrieved.
190                         configurtionException = e;
191                 }
192
193         }
194
195         /**
196          * Checks if the java-libglom native library is visible to the JVM.
197          * 
198          * @return true if the java-libglom native library is visible to the JVM, false if it's not
199          */
200         private boolean isNativeLibraryVisibleToJVM() {
201                 String javaLibraryPath = System.getProperty("java.library.path");
202
203                 // Go through all the library paths and check for the java_libglom .so.
204                 for (String libDirName : javaLibraryPath.split(":")) {
205                         File libDir = new File(libDirName);
206
207                         if (!libDir.isDirectory())
208                                 continue;
209                         if (!libDir.canRead())
210                                 continue;
211
212                         File[] libs = libDir.listFiles(new FilenameFilter() {
213                                 @Override
214                                 public boolean accept(File dir, String name) {
215                                         return name.matches("libjava_libglom-[0-9]\\.[0-9].+\\.so");
216                                 }
217                         });
218
219                         // if at least one directory had the .so, we're done
220                         if (libs.length > 0)
221                                 return true;
222                 }
223
224                 return false;
225         }
226
227         /*
228          * This is called when the servlet is stopped or restarted.
229          * 
230          * @see javax.servlet.GenericServlet#destroy()
231          */
232         @Override
233         public void destroy() {
234                 Glom.libglom_deinit();
235
236                 for (String documenTitle : documentMapping.keySet()) {
237                         ConfiguredDocument configuredDoc = documentMapping.get(documenTitle);
238                         try {
239                                 DataSources.destroy(configuredDoc.getCpds());
240                         } catch (SQLException e) {
241                                 Log.error(documenTitle, "Error cleaning up the ComboPooledDataSource.", e);
242                         }
243                 }
244         }
245
246         /*
247          * (non-Javadoc)
248          * 
249          * @see org.glom.web.client.OnlineGlomService#getConfigurationErrorMessage()
250          */
251         @Override
252         public String getConfigurationErrorMessage() {
253                 if (configurtionException == null)
254                         return "No configuration errors to report.";
255                 else
256                         return configurtionException.getMessage();
257         }
258
259         /*
260          * (non-Javadoc)
261          * 
262          * @see org.glom.web.client.OnlineGlomService#getDocumentInfo(java.lang.String)
263          */
264         @Override
265         public DocumentInfo getDocumentInfo(String documentID) {
266
267                 ConfiguredDocument configuredDoc = documentMapping.get(documentID);
268
269                 // FIXME check for authentication
270
271                 return configuredDoc.getDocumentInfo();
272
273         }
274
275         /*
276          * (non-Javadoc)
277          * 
278          * @see org.glom.web.client.OnlineGlomService#getListViewLayout(java.lang.String, java.lang.String)
279          */
280         @Override
281         public LayoutGroup getListViewLayout(String documentID, String tableName) {
282                 ConfiguredDocument configuredDoc = documentMapping.get(documentID);
283
284                 // FIXME check for authentication
285
286                 return configuredDoc.getListViewLayoutGroup(tableName);
287         }
288
289         /*
290          * (non-Javadoc)
291          * 
292          * @see org.glom.web.client.OnlineGlomService#getListViewData(java.lang.String, java.lang.String, int, int)
293          */
294         @Override
295         public ArrayList<DataItem[]> getListViewData(String documentID, String tableName, int start, int length) {
296                 ConfiguredDocument configuredDoc = documentMapping.get(documentID);
297                 if (!configuredDoc.isAuthenticated()) {
298                         return new ArrayList<DataItem[]>();
299                 }
300                 return configuredDoc.getListViewData(tableName, start, length, false, 0, false);
301         }
302
303         /*
304          * (non-Javadoc)
305          * 
306          * @see org.glom.web.client.OnlineGlomService#getSortedListViewData(java.lang.String, java.lang.String, int, int,
307          * int, boolean)
308          */
309         @Override
310         public ArrayList<DataItem[]> getSortedListViewData(String documentID, String tableName, int start, int length,
311                         int sortColumnIndex, boolean isAscending) {
312                 ConfiguredDocument configuredDoc = documentMapping.get(documentID);
313                 if (!configuredDoc.isAuthenticated()) {
314                         return new ArrayList<DataItem[]>();
315                 }
316                 return configuredDoc.getListViewData(tableName, start, length, true, sortColumnIndex, isAscending);
317         }
318
319         /*
320          * (non-Javadoc)
321          * 
322          * @see org.glom.web.client.OnlineGlomService#getDocuments()
323          */
324         @Override
325         public Documents getDocuments() {
326                 Documents documents = new Documents();
327                 for (String documentID : documentMapping.keySet()) {
328                         ConfiguredDocument configuredDoc = documentMapping.get(documentID);
329                         documents.addDocument(documentID, configuredDoc.getDocument().get_database_title());
330                 }
331                 return documents;
332         }
333
334         /*
335          * (non-Javadoc)
336          * 
337          * @see org.glom.web.client.OnlineGlomService#isAuthenticated(java.lang.String)
338          */
339         public boolean isAuthenticated(String documentID) {
340                 return documentMapping.get(documentID).isAuthenticated();
341         }
342
343         /*
344          * (non-Javadoc)
345          * 
346          * @see org.glom.web.client.OnlineGlomService#checkAuthentication(java.lang.String, java.lang.String,
347          * java.lang.String)
348          */
349         @Override
350         public boolean checkAuthentication(String documentID, String username, String password) {
351                 ConfiguredDocument configuredDoc = documentMapping.get(documentID);
352                 try {
353                         return configuredDoc.setUsernameAndPassword(username, password);
354                 } catch (SQLException e) {
355                         Log.error(documentID, "Unknown SQL Error checking the database authentication.", e);
356                         return false;
357                 }
358         }
359
360         /*
361          * (non-Javadoc)
362          * 
363          * @see org.glom.web.client.OnlineGlomService#getDetailsData(java.lang.String, java.lang.String, java.lang.String)
364          */
365         @Override
366         public DataItem[] getDetailsData(String documentID, String tableName, TypedDataItem primaryKeyValue) {
367                 ConfiguredDocument configuredDoc = documentMapping.get(documentID);
368
369                 // FIXME check for authentication
370
371                 return configuredDoc.getDetailsData(tableName, primaryKeyValue);
372         }
373
374         /*
375          * (non-Javadoc)
376          * 
377          * @see org.glom.web.client.OnlineGlomService#getDetailsLayoutAndData(java.lang.String, java.lang.String,
378          * java.lang.String)
379          */
380         @Override
381         public DetailsLayoutAndData getDetailsLayoutAndData(String documentID, String tableName,
382                         TypedDataItem primaryKeyValue) {
383                 ConfiguredDocument configuredDoc = documentMapping.get(documentID);
384                 if (configuredDoc == null)
385                         return null;
386
387                 // FIXME check for authentication
388
389                 DetailsLayoutAndData initalDetailsView = new DetailsLayoutAndData();
390                 initalDetailsView.setLayout(configuredDoc.getDetailsLayoutGroup(tableName));
391                 initalDetailsView.setData(configuredDoc.getDetailsData(tableName, primaryKeyValue));
392
393                 return initalDetailsView;
394         }
395
396         /*
397          * (non-Javadoc)
398          * 
399          * @see org.glom.web.client.OnlineGlomService#getRelatedListData(java.lang.String, java.lang.String, int, int)
400          */
401         @Override
402         public ArrayList<DataItem[]> getRelatedListData(String documentID, String tableName, String relationshipName,
403                         TypedDataItem foreignKeyValue, int start, int length) {
404                 ConfiguredDocument configuredDoc = documentMapping.get(documentID);
405
406                 // FIXME check for authentication
407
408                 return configuredDoc.getRelatedListData(tableName, relationshipName, foreignKeyValue, start, length, false, 0,
409                                 false);
410         }
411
412         /*
413          * (non-Javadoc)
414          * 
415          * @see org.glom.web.client.OnlineGlomService#getSortedRelatedListData(java.lang.String, java.lang.String, int, int,
416          * int, boolean)
417          */
418         @Override
419         public ArrayList<DataItem[]> getSortedRelatedListData(String documentID, String tableName, String relationshipName,
420                         TypedDataItem foreignKeyValue, int start, int length, int sortColumnIndex, boolean ascending) {
421                 ConfiguredDocument configuredDoc = documentMapping.get(documentID);
422
423                 // FIXME check for authentication
424
425                 return configuredDoc.getRelatedListData(tableName, relationshipName, foreignKeyValue, start, length, true,
426                                 sortColumnIndex, ascending);
427         }
428
429         public int getRelatedListRowCount(String documentID, String tableName, String relationshipName,
430                         TypedDataItem foreignKeyValue) {
431                 ConfiguredDocument configuredDoc = documentMapping.get(documentID);
432
433                 // FIXME check for authentication
434
435                 return configuredDoc.getRelatedListRowCount(tableName, relationshipName, foreignKeyValue);
436         }
437
438         /*
439          * (non-Javadoc)
440          * 
441          * @see org.glom.web.client.OnlineGlomService#getSuitableRecordToViewDetails(java.lang.String, java.lang.String,
442          * java.lang.String, java.lang.String)
443          */
444         @Override
445         public NavigationRecord getSuitableRecordToViewDetails(String documentID, String tableName,
446                         String relationshipName, TypedDataItem primaryKeyValue) {
447                 ConfiguredDocument configuredDoc = documentMapping.get(documentID);
448
449                 // FIXME check for authentication
450
451                 return configuredDoc.getSuitableRecordToViewDetails(tableName, relationshipName, primaryKeyValue);
452         }
453
454 }