KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > webapps > addressbook > AddressBookServlet


1 package org.jahia.webapps.addressbook;
2
3 import java.io.*;
4 import java.text.*;
5 import java.util.*;
6 import java.sql.*;
7 import javax.servlet.*;
8 import javax.servlet.http.*;
9
10 // import the OJB stuff
11
import org.apache.ojb.broker.PBFactoryException;
12 import org.apache.ojb.broker.PersistenceBroker;
13 import org.apache.ojb.broker.PersistenceBrokerFactory;
14 import org.apache.ojb.broker.util.ui.AsciiSplash;
15 import org.odmg.*;
16 import org.apache.ojb.odmg.*;
17
18
19
20
21 import org.jahia.tools.*;
22 import org.jahia.tools.db.*;
23 import org.jahia.tools.files.*;
24 import org.jahia.webapps.util.*;
25
26 /**
27  * Class AddressBookServlet : the actual controller of the web application
28  *
29  * @author Jerome Tamiotti <a HREF="mailto:jtamiotti@mycomponents.com">jtamiotti@mycomponents.com</a>
30  */

31 public class AddressBookServlet extends HttpServlet {
32
33     /** the external properties file ServletConfig key **/
34     private final static String JavaDoc SC_KEY_PROPERTIES = "properties";
35
36     private final static String JavaDoc SC_KEY_METHODS = "methods";
37     private final static String JavaDoc SC_KEY_CLASSNAME = "classname";
38     private final static String JavaDoc SC_KEY_USEMODE = "usemode";
39     private final static String JavaDoc SC_KEY_COUNTRY = "countries";
40     private final static String JavaDoc SC_KEY_PATH = "tmpDirPath";
41
42     //== database =========
43
/** the database driver attribute name in the properties file **/
44    // private final static String PROP_DB_DRIVER = "database.driver";
45
/** the database url attribute name in the properties file **/
46    // private final static String PROP_DB_URL = "database.url";
47
/** the database username attribute name in the properties file **/
48    // private final static String PROP_DB_USERNAME = "database.username";
49
/** the database password attribute name in the properties file **/
50    // private final static String PROP_DB_PASSWORD = "database.password";
51
/** the database initial connections number attribute name in the properties file **/
52     //private final static String PROP_DB_INITIALCONNECTIONS = "database.initialConnections";
53
/** the database max connections attribute name in the properties file **/
54     //private final static String PROP_DB_MAXCONNECTIONS = "database.maxConnections";
55

56     private static String JavaDoc CONTEXT_ROOT_REAL_PATH = "$contextRootRealPath";
57
58     private static String JavaDoc LIST_SIZE;
59
60     //== JDBC members =====
61
/** the database driver **/
62     private String JavaDoc m_DB_DRIVER;
63     /** the database url **/
64     private String JavaDoc m_DB_URL;
65     /** the database username **/
66     private String JavaDoc m_DB_USERNAME;
67     /** the database password **/
68     private String JavaDoc m_DB_PASSWORD;
69     /** the database max connections **/
70     private int m_DB_MAXCONNECTIONS;
71     /** the database initial connections **/
72     private int m_DB_INITIALCONNECTIONS;
73     /** The OBJ broker, will be instanciated by this class */
74     private PersistenceBroker broker = null;
75
76
77     private String JavaDoc dirPath;
78     private String JavaDoc useModePath;
79     private String JavaDoc countriesPath;
80     private ActionHandler actionHandler;
81
82
83     /**
84      * Method init
85      * This init method will load the default resources from a
86      * properties file and instanciate database pooling
87      *
88      * @param config typical Servlet initialization parameter.
89      * @exception ServletException a servlet exception.
90      */

91     public void init(ServletConfig config) throws ServletException {
92
93       Tools.toConsole("AddressBookServlet: init", "begin");
94       super.init(config);
95       String JavaDoc propsPath = config.getInitParameter(SC_KEY_PROPERTIES);
96       if ( propsPath == null ) {
97         throw new ServletException("Property file not specified in the servlet config - please specify init-param \""+SC_KEY_PROPERTIES+"\"");
98       }
99       String JavaDoc realPath = getServletContext().getRealPath(propsPath);
100       if ( realPath != null ) {
101         if (loadProperties(realPath)) {
102           try {
103             // init DBServices
104
//AdbApplicationDB.initDBServices( m_DB_DRIVER, m_DB_URL, m_DB_USERNAME, m_DB_PASSWORD, m_DB_INITIALCONNECTIONS, m_DB_MAXCONNECTIONS );
105

106             Tools.toConsole("AddressBookServlet::init", "stage 1");
107             if (broker != null) broker.close();
108             broker = PersistenceBrokerFactory.defaultPersistenceBroker();
109             AdbApplicationDB.init(broker);
110             Tools.toConsole("AddressBookServlet::init", "stage 2");
111
112
113           } catch (Throwable JavaDoc t) {
114             Tools.toConsole("TimeReportingServlet::init", "error initializing PersistenceBroker");
115             t.printStackTrace();
116             throw new ServletException("error initializing database via OJB", t);
117           }
118         } else {
119           System.out.println("Error Loading Properties");
120         }
121       }
122
123       // Load methods names
124
String JavaDoc methods_path = getServletContext().getRealPath(config.getInitParameter(SC_KEY_METHODS));
125       if ( methods_path == null ) {
126         throw new ServletException("Methods file not specified in the servlet config - please specify init-param \""+SC_KEY_METHODS+"\"");
127       }
128       actionHandler = new ActionHandler(methods_path,config.getInitParameter(SC_KEY_CLASSNAME));
129
130       // Get path of directory for temporary file used for data exportation
131
dirPath = getServletContext().getRealPath(config.getInitParameter(SC_KEY_PATH));
132
133       // Get path for use modes file
134
useModePath = getServletContext().getRealPath(config.getInitParameter(SC_KEY_USEMODE));
135
136       // Get path for countries file
137
countriesPath = getServletContext().getRealPath(config.getInitParameter(SC_KEY_COUNTRY));
138
139       Tools.toConsole("AddressBookServlet: init", "end");
140     }
141
142
143
144     /**
145      * Method loadProperties
146      * Load properties from an external properties file
147      *
148      * @param file the full path of the properties file
149      * @return true if no error
150      */

151     private boolean loadProperties(String JavaDoc file) {
152
153       Properties Props = new Properties();
154       try {
155         FileInputStream fis = new FileInputStream(file);
156         Props.load(fis);
157         fis.close();
158
159         String JavaDoc m_ContextRootRealPath = getServletContext().getRealPath(File.separator);
160         //String propDBURL = Props.getProperty( PROP_DB_URL );
161
//int contextRootMarkerPos = propDBURL.indexOf(CONTEXT_ROOT_REAL_PATH);
162
// if (contextRootMarkerPos != -1) {
163
// String before = propDBURL.substring(0, contextRootMarkerPos);
164
// String after = propDBURL.substring(contextRootMarkerPos + CONTEXT_ROOT_REAL_PATH.length());
165
// m_DB_URL = before + getServletContext().getRealPath(after);
166
// } else {
167
// m_DB_URL = propDBURL;
168
// }
169
// m_DB_URL = Tools.replacePattern(Props.getProperty( PROP_DB_URL ), CONTEXT_ROOT_REAL_PATH, m_ContextRootRealPath);
170

171         // m_DB_DRIVER = Props.getProperty( PROP_DB_DRIVER );
172
// m_DB_USERNAME = Props.getProperty( PROP_DB_USERNAME );
173
//m_DB_PASSWORD = Props.getProperty( PROP_DB_PASSWORD );
174

175         //Integer iVal = new Integer( Props.getProperty( PROP_DB_MAXCONNECTIONS ) );
176
//m_DB_MAXCONNECTIONS = iVal.intValue();
177

178        // iVal = new Integer( Props.getProperty( PROP_DB_INITIALCONNECTIONS ) );
179
// m_DB_INITIALCONNECTIONS = iVal.intValue();
180

181             LIST_SIZE = Props.getProperty("listsize" );
182
183             //Tools.toConsole("AddressBookServlet: loadProperties", "driver="+m_DB_DRIVER+", url="+m_DB_URL+", username="+m_DB_USERNAME+", max connections="+ m_DB_MAXCONNECTIONS);
184

185         } catch (java.io.IOException JavaDoc ex) {
186             ex.printStackTrace();
187             return false;
188         }
189         return true;
190     }
191
192     /**
193      * Do servlet clean-up.
194      */

195     public void destroy() {
196
197       broker.close();
198
199     }
200
201     /**
202      * Method to handle Post method of form
203      * Simply redirect to Get method
204      *
205      * @param request the http request send to this servlet
206      * @param response the html response this servlet generates
207      */

208     public void doPost(HttpServletRequest request, HttpServletResponse response)
209         throws IOException, ServletException {
210         doGet(request, response);
211     }
212
213
214     /**
215      * Method to handle Get method of form
216      *
217      * @param request the http request send to this servlet
218      * @param response the html response this servlet generates
219      */

220     public void doGet(HttpServletRequest request, HttpServletResponse response)
221         throws IOException, ServletException {
222
223       Tools.toConsole("AddressBookServlet: doGet","begin");
224       HttpSession session = request.getSession(true);
225       String JavaDoc contextId = (String JavaDoc)request.getAttribute("org.portletapi.contextid");
226
227       session.setAttribute("servlet", request.getRequestURI());
228       String JavaDoc currentAction = request.getParameter("current_action");
229
230       // check if mode is given in request
231
String JavaDoc useMode = request.getParameter("useMode");
232       if (useMode != null) {
233         actionHandler.call(request.getParameter("current_action"),request);
234       }
235
236       if ( (session.getAttribute("useMode") == null) ) {
237
238         // first call to doGet method
239
// check if use mode has already been set in in-portal mode
240
if (contextId == null) {
241           // mode standalone: use mode = user
242
session.setAttribute("modeStandalone",new Boolean JavaDoc(true));
243           session.setAttribute("contextId","");
244           session.setAttribute("useMode","user");
245           initialize (request);
246
247         } else {
248
249           session.setAttribute("modeStandalone",new Boolean JavaDoc(false));
250           session.setAttribute("contextId",contextId);
251           // check in a flat file
252
if (!checkUseMode(request,response)) {
253                // first use of the application
254
Tools.toConsole("AddressBookServlet: doGet","First use of this application : must choose use mode");
255             try {
256
257               RequestDispatcher rd = getServletContext().getRequestDispatcher("/jsp/admin.jsp");
258               rd.forward(request, response);
259               return;
260             } catch (Exception JavaDoc e) {
261               Tools.toConsole("AddressBookServlet: doGet","Unable to forward to next page; cause : "+e.toString());
262               return;
263             }
264           } else {
265             Tools.toConsole("AddressBookServlet: doGet","Use mode already set : " + (String JavaDoc)session.getAttribute("useMode"));
266             initialize(request);
267           }
268         }
269       } else { // useMode has already been set
270
if (session.getAttribute("myBook") == null) {
271           Tools.toConsole("AddressBookServlet: doGet","Call to initialize");
272           initialize (request);
273         }
274       }
275       if (request.getAttribute("bottomPage") == null) {
276         request.setAttribute("bottomPage","empty_bottom.jsp");
277       }
278       Tools.toConsole("AddressBookServlet: doGet", "current action = " + currentAction);
279       if (currentAction == null) {
280         String JavaDoc nextPage = (String JavaDoc)request.getAttribute("nextPage");
281         if (nextPage == null) {
282           nextPage = "display.jsp";
283           request.setAttribute("nextPage", nextPage);
284         }
285         try {
286           String JavaDoc page = nextPage.equals("error.jsp") ? "error.jsp" : "template.jsp";
287           RequestDispatcher rd = getServletContext().getRequestDispatcher("/jsp/" + page);
288           Tools.toConsole("AddressBookServlet: doGet", "forward to " + nextPage);
289           rd.forward(request, response);
290         } catch (Exception JavaDoc e) {
291           Tools.toConsole("AddressBookServlet: doGet","Unable to forward to next page; cause : "+e.toString());
292           e.printStackTrace();
293         }
294
295       } else {
296         // call action handler to perform the current action
297
if (currentAction.equals("save")) {
298           // separated because it needs response and don't forward to a page
299
try {
300             String JavaDoc filePath = AddbookHandler.save(request);
301             Tools.toConsole("AddressbookServlet: doGet","File saved: path = " + filePath);
302             FileDownload fdwn = new FileDownload(request,response,"AddressBook.csv",filePath,"text/csv");
303             fdwn.writeFileContentToResponse();
304             // Delete temp file
305
try {
306               File f = new File(filePath);
307               f.delete();
308             } catch(SecurityException JavaDoc se) {
309               Tools.toConsole("AddbookHandler: save","Unable to delete file " + filePath+" :" + se.toString() );
310             }
311             return;
312           } catch(IOException ioe) {
313             Tools.toConsole("AddbookHandler: save","Unable to download file : " + ioe.toString());
314             request.setAttribute("nextPage","display.jsp");
315           }
316
317         } else {
318           // other action : execute then forward to specified page
319
try {
320             actionHandler.call(currentAction,request);
321           } catch (NullPointerException JavaDoc npe) {
322             Tools.toConsole("AddressBookServlet: doGet","Couldn't have performed action " + currentAction);
323             request.setAttribute("nextPage","display.jsp");
324           }
325           String JavaDoc nextPage = (String JavaDoc)request.getAttribute("nextPage");
326           Tools.toConsole("AddressBookServlet: doGet", "forward to " + nextPage);
327           try {
328             RequestDispatcher rd = getServletContext().getRequestDispatcher("/jsp/template.jsp");
329               // replace forward by include (Jahia5)
330
//rd.forward(request, response);
331
rd.include(request,response);
332           } catch (ServletException se) {
333             Tools.toConsole("AddressBookServlet: doGet","Unable to forward to next page; cause : "+se.toString());
334             se.printStackTrace();
335             if (se.getRootCause() != null) {
336               se.getRootCause().printStackTrace();
337             }
338           } catch (Exception JavaDoc e) {
339             Tools.toConsole("AddressBookServlet: doGet","Unable to forward to next page; cause : "+e.toString());
340             e.printStackTrace();
341           }
342         }
343       }
344     }
345
346
347     /**
348      * Method which checks if an use mode has already been defined for this instance of application
349      *
350      * @param request the http request send to this servlet
351      * @param response the html response this servlet generates
352      * @return true if the use mode has already been defined
353      */

354     private boolean checkUseMode (HttpServletRequest request, HttpServletResponse response) {
355
356       Tools.toConsole("AddressBookServlet: checkUseMode","begin");
357       HttpSession session = request.getSession();
358       boolean checked = false;
359       try {
360         Properties Prop_useMode = new Properties();
361         FileInputStream fis = new FileInputStream(useModePath);
362         Prop_useMode.load(fis);
363         fis.close();
364         String JavaDoc useMode = Prop_useMode.getProperty( "useMode" + (String JavaDoc)session.getAttribute("contextId") );
365         Tools.toConsole("AddressBookServlet: checkUseMode","useMode = " + useMode);
366         if (useMode == null) {
367           // use mode not found : call admin page to choose among misc modes
368
session.setAttribute("useModePath", useModePath);
369         } else {
370           session.setAttribute("useMode", useMode);
371           request.setAttribute("nextPage", "display.jsp");
372           checked = true;
373         }
374       } catch (java.io.IOException JavaDoc ioe) {
375         Tools.toConsole("AddressBookServlet: checkUseMode", ioe.toString());
376       }
377       return checked;
378     }
379
380
381     /**
382      * Method which initializes the address book
383      *
384      * @param request the http request send to this servlet
385      */

386     private void initialize (HttpServletRequest request) {
387
388       Tools.toConsole("AddressBookServlet: initialize","begin");
389       try {
390         HttpSession session = request.getSession();
391         String JavaDoc contextId = (String JavaDoc)session.getAttribute("contextId");
392         session.setAttribute("listSize",new Integer JavaDoc(LIST_SIZE));
393         session.setAttribute("dirPath",dirPath);
394         session.setAttribute("useModePath",useModePath);
395         String JavaDoc useMode = (String JavaDoc)session.getAttribute("useMode");
396         // check user
397
if (useMode.equals("user")) {
398           session.setAttribute("role","manager");
399           session.setAttribute("isManager",new Boolean JavaDoc(true));
400
401         } else { // usemode = shared, check for role
402
if (request.isUserInRole("manager")) {
403             session.setAttribute("role","manager");
404             session.setAttribute("isManager",new Boolean JavaDoc(true));
405           } else {
406             session.setAttribute("role","user");
407             session.setAttribute("isManager",new Boolean JavaDoc(false));
408           }
409         }
410         Tools.toConsole("AddressBookServlet: initialize","User role = " + (String JavaDoc)session.getAttribute("role"));
411         // check environment
412
if (contextId.equals("")) {
413           // mode standalone
414
session.setAttribute("modeStandalone",new Boolean JavaDoc(true));
415           session.setAttribute("contextId","");
416           AddbookHandler.init(request);
417         } else {
418           // mode inPortal
419
session.setAttribute("modeStandalone",new Boolean JavaDoc(false));
420           session.setAttribute("contextId",contextId);
421           AddbookHandler.init(request, contextId);
422         }
423         // load countries names from a flat file
424
session.setAttribute("countries",loadCountries());
425
426
427       } catch (IOException ioe) {
428         Tools.toConsole("AddressBookServlet: initialize",ioe.toString());
429         request.setAttribute("nextPage","error.jsp");
430
431       } catch (ServletException se) {
432         Tools.toConsole("AddressBookServlet: initialize",se.toString());
433         request.setAttribute("nextPage","error.jsp");
434       }
435       Tools.toConsole("AddressBookServlet: initialize","end");
436     }
437
438
439     /**
440      * Method which reads the countries name from a flat file
441      *
442      * @return a vector containing all these names
443      */

444     private Vector loadCountries() {
445
446         Vector countries = new Vector();
447         String JavaDoc thisLine;
448         try {
449             BufferedReader br = new BufferedReader(new FileReader(countriesPath));
450             while ((thisLine = br.readLine()) != null) {
451                 countries.addElement(thisLine);
452             }
453         } catch (IOException ioe) {
454             Tools.toConsole("AddressBookServlet: loadCountries()",ioe.toString());
455         }
456         return countries;
457     }
458
459 }
460
461
462
463
464
Popular Tags