KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > webapps > fichotheque > FichothequeServlet


1 package org.jahia.webapps.fichotheque;
2
3 import java.io.*;
4 import java.util.*;
5 import java.sql.*;
6 import javax.servlet.*;
7 import javax.servlet.http.*;
8
9 import org.jahia.tools.*;
10 import org.jahia.tools.db.*;
11 import org.jahia.webapps.util.*;
12
13 //import the OJB stuff
14
import org.apache.ojb.broker.PBFactoryException;
15 import org.apache.ojb.broker.PersistenceBroker;
16 import org.apache.ojb.broker.PersistenceBrokerFactory;
17 import org.apache.ojb.broker.util.ui.AsciiSplash;
18 import org.odmg.*;
19 import org.apache.ojb.odmg.*;
20
21 /**
22  * The actual controller of the web application
23  *
24  * @author Yann Gentil <a HREF="mailto:gentil@xo3.com">gentil@xo3.com</a>
25  * @version %I%, %G%
26  * @see com.myc.webapps.fichotheque
27  */

28 public class FichothequeServlet extends HttpServlet
29 {
30   private static org.apache.log4j.Logger logger =
31       org.apache.log4j.Logger.getLogger(FichothequeServlet.class);
32
33     //== database =========
34
/** The external properties file **/
35     //public final static String PROPERTIES_FILE = "WEB-INF/conf/fichotheque.properties";
36
/** the external properties file ServletConfig key **/
37     private final static String JavaDoc SC_KEY_PROPERTIES = "properties";
38     /** the file that describe action and method to call **/
39     private final static String JavaDoc SC_KEY_METHODS = "methods";
40     /** the file that contains the application's useMode **/
41     private final static String JavaDoc SC_KEY_USEMODE = "useMode";
42     /** the class handler **/
43     private final static String JavaDoc SC_KEY_CLASSNAME = "classname";
44     /** The component name (cardLibraryName) in the properties file **/
45     private final static String JavaDoc PROP_CARD_LIBRARY_NAME = "cardLibrary.name";
46     private final static String JavaDoc PROP_NB_CARD_BY_PAGE = "nbCardByPage";
47     /** The database driver attribute name in the properties file **/
48     private final static String JavaDoc PROP_DB_DRIVER = "database.driver";
49     /** The database url attribute name in the properties file **/
50     private final static String JavaDoc PROP_DB_URL = "database.url";
51     /** The database username attribute name in the properties file **/
52     private final static String JavaDoc PROP_DB_USERNAME = "database.username";
53     /** The database password attribute name in the properties file **/
54     private final static String JavaDoc PROP_DB_PASSWORD = "database.password";
55     /** The database initial connections number attribute name in the properties file **/
56     private final static String JavaDoc PROP_DB_INITIALCONNECTIONS = "database.initialConnections";
57     /** The database max connections attribute name in the properties file **/
58     private final static String JavaDoc PROP_DB_MAXCONNECTIONS = "database.maxConnections";
59     /** The token to replace by the context path **/
60     private final static String JavaDoc CONTEXT_ROOT_REAL_PATH = "$contextRootRealPath";
61     /** attribute to determine the type of license of the current jahia environment **/
62     private final static String JavaDoc JAHIA_LICENSE_TYPE = "com.xo3.jahia.license.licenseType";
63     /** license type for this application ('2' correspond to Jahia Pro Ed.) **/
64     private final static int LICENSE_TYPE = 2;
65     /** page to forward to in case of invalid license */
66     private final static String JavaDoc NO_LICENSE_PAGE = "/jsp/no_license.jsp";
67     /** The context path **/
68     private static String JavaDoc m_ContextRootRealPath = "";
69
70     /** The component name (cardLibraryName) **/
71     private String JavaDoc CARD_LIBRARY_NAME;
72     /** The fieldsNames of a card **/
73     private Card CARD_FIELDS_NAMES;
74     /** The number of card displayed in the list **/
75     private String JavaDoc NB_CARD_BY_PAGE;
76     /** The current action to execute **/
77     private String JavaDoc CURRENT_ACTION;
78     /** The current card id displyed **/
79     private int CURRENT_CARD_ID;
80     /** the name of the editor role **/
81     private String JavaDoc EDITOR_ROLE = "manager";
82     /** path for the file useMode **/
83     private String JavaDoc useModePath;
84
85
86     //== JDBC members =====
87
/** The database driver **/
88     private String JavaDoc m_DB_DRIVER;
89     /** The database url **/
90     private String JavaDoc m_DB_URL;
91     /** The database username **/
92     private String JavaDoc m_DB_USERNAME;
93     /** The database password **/
94     private String JavaDoc m_DB_PASSWORD;
95     /** The database max connections **/
96     private int m_DB_MAXCONNECTIONS;
97     /** The database initial connections **/
98     private int m_DB_INITIALCONNECTIONS;
99     /** The OBJ broker, will be instanciated by this class */
100     private PersistenceBroker broker = null;
101
102     /** The reference to the database pooling service **/
103
104     private DBServices m_DBServices;
105
106     private ActionHandler actionHandler;
107
108     private String JavaDoc next_page = "default.html";
109
110
111     public FichothequeServlet()
112     {
113     }
114
115
116     /**
117     * This method will load the default resources from a
118     * properties file and instanciate database pooling
119     *
120     * @param config typical Servlet initialization parameter.
121     * @exception ServletException a servlet exception.
122     */

123     public void init(ServletConfig config) throws ServletException
124     {
125         logger.debug("FichothequeServlet: init: begin");
126         super.init(config);
127
128         useModePath = getServletContext().getRealPath(config.getInitParameter(SC_KEY_USEMODE));
129
130         m_ContextRootRealPath = getServletContext().getRealPath(File.separator);
131
132         //String props = PROPERTIES_FILE;
133

134         String JavaDoc props = config.getInitParameter(SC_KEY_PROPERTIES);
135         if ( props != null )
136         {
137             String JavaDoc realPath = getServletContext().getRealPath(props);
138             if ( realPath != null )
139             {
140                 props = realPath;
141                 if (loadProperties(props))
142                 {
143
144            try {
145                     // init DBServices
146
// m_DBServices.getInstance( m_DB_DRIVER, m_DB_URL,
147
// m_DB_USERNAME, m_DB_PASSWORD,
148
// m_DB_INITIALCONNECTIONS,
149
// m_DB_MAXCONNECTIONS);
150

151                                          logger.debug("AbsenceRequest::init: stage 1");
152            if (broker != null) broker.close();
153            broker = PersistenceBrokerFactory.defaultPersistenceBroker();
154            AccessDB.init(broker);
155            logger.debug("AbsenceRequest::init: stage 2");
156
157
158          } catch (Throwable JavaDoc t)
159          {
160            logger.error("AbsenceRequestServlet::init: error initializing PersistenceBroker");
161            throw new ServletException("error initializing database via OJB", t);
162          }
163
164                 }
165                 else
166                 {
167                     logger.debug("FichothequeServlet: init: Error Loading Properties");
168                 }
169             }
170         }
171
172         //Load methods names
173
String JavaDoc methodsPath = getServletContext().getRealPath(config.getInitParameter(SC_KEY_METHODS));
174
175         if (methodsPath == null)
176         {
177             throw new ServletException("Methods file not specified in the servlet config - please specify init-param \""+SC_KEY_METHODS+"\"");
178         }
179         actionHandler = new ActionHandler(methodsPath, config.getInitParameter(SC_KEY_CLASSNAME));
180
181         // load fields names
182
loadFieldsNames();
183
184         logger.debug("FichothequeServlet: init: end");
185     }
186
187
188     /**
189     * Load the fields names of a card
190     * It is used to avoid to read in the database
191     * when the user want to add a card or search a card
192     */

193     protected void loadFieldsNames()
194     {
195
196         Card crd = new Card(0,CARD_LIBRARY_NAME);
197         CARD_FIELDS_NAMES = crd;
198     }
199
200
201     /**
202     * Load properties from an external properties file
203     *
204     * @param file the full path of the properties file
205     * @return true if no error
206     */

207     protected boolean loadProperties(String JavaDoc file)
208     {
209         Properties Props = new Properties();
210         try
211         {
212             FileInputStream fis = new FileInputStream(file);
213             Props.load(fis);
214             fis.close();
215
216             CARD_LIBRARY_NAME = Props.getProperty( PROP_CARD_LIBRARY_NAME );
217             NB_CARD_BY_PAGE = Props.getProperty( PROP_NB_CARD_BY_PAGE );
218             //m_DB_DRIVER = Props.getProperty( PROP_DB_DRIVER );
219
//m_DB_URL = replace(Props.getProperty( PROP_DB_URL ), CONTEXT_ROOT_REAL_PATH, m_ContextRootRealPath);
220
//m_DB_USERNAME = Props.getProperty( PROP_DB_USERNAME );
221
//m_DB_PASSWORD = Props.getProperty( PROP_DB_PASSWORD );
222

223             //Integer iVal = new Integer( Props.getProperty( PROP_DB_MAXCONNECTIONS ) );
224
//m_DB_MAXCONNECTIONS = iVal.intValue();
225

226             //iVal = new Integer( Props.getProperty( PROP_DB_INITIALCONNECTIONS ) );
227
//m_DB_INITIALCONNECTIONS = iVal.intValue();
228

229             //logger.debug("FichothequeServlet: loadProperties: driver="
230
// + m_DB_DRIVER + ", url=" + m_DB_URL + ", username="
231
// + m_DB_USERNAME + ", max connections=" + m_DB_MAXCONNECTIONS);
232

233         }
234         catch (java.io.IOException JavaDoc ex)
235         {
236             ex.printStackTrace();
237             return false;
238         }
239         return true;
240     }
241
242
243     /**
244     * Method to handle Get method of form
245     * Simply redirect to Post method
246     *
247     * @param request the http request send to this servlet
248     * @param response the html response this servlet generates
249     */

250     public void doGet(HttpServletRequest request, HttpServletResponse response)
251         throws IOException, ServletException
252     {
253         doPost(request, response);
254     }
255
256
257     /**
258     * Method to handle Post method of form
259     *
260     * @param request the http request send to this servlet
261     * @param response the html response this servlet generates
262     */

263     public void doPost(HttpServletRequest request, HttpServletResponse response)
264         throws IOException, ServletException
265     {
266         String JavaDoc inPortal = (String JavaDoc)request.getAttribute("org.portletapi.portal");
267         boolean run = true;
268
269         if ("true".equals(inPortal))
270         {
271             Integer JavaDoc licenseType = (Integer JavaDoc)request.getAttribute(JAHIA_LICENSE_TYPE);
272             if (licenseType != null && (licenseType.intValue() < LICENSE_TYPE) )
273             {
274                 logger.debug("AbsenceRequestServlet - doPost: Insufficient jahia version");
275                 run = false;
276             }
277         }
278
279         if (run)
280         {
281         // set the default and current parameters
282
setParameters(request);
283         logger.debug("FichothequeServlet: doPost: mode=*"+ request.getParameter("mode") + "*");
284         // call to external action handler
285
try
286         {
287           logger.debug("currentAction " + CURRENT_ACTION);
288           actionHandler.call(CURRENT_ACTION,request);
289         }
290         catch (NullPointerException JavaDoc npe)
291         {
292             logger.error("FichothequeServlet: doPost: Couldn't perform action " +
293                             CURRENT_ACTION);
294             request.setAttribute("next_page","display_list.jsp");
295             request.setAttribute("menu_page","menuList.jsp");
296             request.setAttribute("bottom_page","bottomList.jsp");
297         }
298         //FichApplication fich_app = new FichApplication();
299
//fich_app.handleAction(request, CURRENT_ACTION);
300
} // end if run
301

302         try
303         {
304             RequestDispatcher rd;
305             if (!run)
306             {
307                 rd = getServletContext().getRequestDispatcher(NO_LICENSE_PAGE);
308             }
309             else
310             {
311                 // forward to the next page
312
String JavaDoc next_page = (String JavaDoc)request.getAttribute("next_page");
313                 logger.debug("FichothequeServlet: doPost: forward to "+next_page);
314                 rd = getServletContext().getRequestDispatcher("/jsp/index.jsp");
315             }
316             rd.forward(request, response);
317         }
318         catch (Exception JavaDoc e)
319         {
320             logger.error("FichothequeServlet: doPost",e);
321         }
322
323             logger.debug("FichothequeServlet: doPost: end");
324     }
325
326
327     /**
328     * Set default and current parameters
329     *
330     * @param request the http request send to this servlet
331     */

332     protected void setParameters(HttpServletRequest request)
333     {
334         HttpSession session = request.getSession(true);
335         session.setMaxInactiveInterval(7200);
336         int t = session.getMaxInactiveInterval();
337         logger.debug("FichothequeServlet: setParameters: Session Max Inactive Time: "+ Integer.toString(t));
338         logger.debug("FichothequeServlet: setParameters: Context Id: "+ (String JavaDoc)request.getAttribute("org.portletapi.contextid"));
339
340         // set Jahia parameter if not in Jahia
341
if (request.getAttribute("org.portletapi.contextid") == null)
342         {
343             request.setAttribute("org.portletapi.contextid", "");
344         }
345         if (request.getAttribute("org.portletapi.portal") == null)
346         {
347             request.setAttribute("org.portletapi.portal", "");
348         }
349
350         // set current action
351
CURRENT_ACTION = request.getParameter("current_action");
352         if ((CURRENT_ACTION == null)||(CURRENT_ACTION == ""))
353         {
354             // First execution of the servlet
355
CURRENT_ACTION = "display_ListCards";
356         }
357
358         // set current card id
359
if (request.getParameter("card_id") != null)
360         {
361             CURRENT_CARD_ID = Integer.parseInt(request.getParameter("card_id"));
362         }
363         else
364         {
365             // First execution of the servlet
366
CURRENT_CARD_ID = 0;
367         }
368         request.setAttribute("card_id",Integer.toString(CURRENT_CARD_ID));
369
370
371         // set the sort parameter
372
String JavaDoc sortedBy = (String JavaDoc)request.getParameter("sort");
373         if (sortedBy == null)
374         {
375             sortedBy = "CARD_ID";
376         }
377         session.setAttribute(CARD_LIBRARY_NAME + "_sort", sortedBy);
378
379         // set the sortFlag parameter
380
String JavaDoc sortFlag = (String JavaDoc)request.getParameter("sortFlag");
381         if (sortFlag == null)
382         {
383             sortFlag = "ASC";
384         }
385         session.setAttribute(CARD_LIBRARY_NAME + "_sortFlag", sortFlag);
386
387
388         // set user name (to keep user name if login failed)
389
String JavaDoc userName = request.getParameter("username");
390         if (userName == null)
391         {
392             // First execution of the servlet
393
userName = "";
394         }
395         request.setAttribute("username",userName);
396
397         // initialise user right
398
String JavaDoc userRight = (String JavaDoc)session.getAttribute(CARD_LIBRARY_NAME
399                                                         + "_userRight");
400         if (userRight == null)
401         {
402             // First execution of the servlet
403
userRight = "";
404             session.setAttribute(CARD_LIBRARY_NAME + "_userRight",userRight );
405         }
406
407         //set the default useMode
408
String JavaDoc contextId = (String JavaDoc)request.getAttribute("org.portletapi.contextid");
409         logger.debug("FichothequeServlet: setParameters: useMode(session)=" + (String JavaDoc)session.getAttribute(CARD_LIBRARY_NAME + "_useMode"));
410         logger.debug("FichothequeServlet: setParameters: sessionId=" + (String JavaDoc)session.getId());
411         if (session.getAttribute(CARD_LIBRARY_NAME + "_useMode") == null)
412         {
413             try
414             {
415             Properties Prop_useMode = new Properties();
416             FileInputStream fis = new FileInputStream(useModePath);
417             Prop_useMode.load(fis);
418             fis.close();
419
420             String JavaDoc useMode = Prop_useMode.getProperty( "useMode"+ contextId );
421             logger.debug("FichothequeServlet: setParameters: useMode=*" + useMode + contextId +"*");
422
423             if (useMode == null || useMode.equals(""))
424             {
425                 logger.debug("FichothequeServlet: setParameters: action=useMode");
426                 //session.setAttribute(CARD_LIBRARY_NAME + "_useMode", "shared");
427
CURRENT_ACTION = "displayAdminMode";
428                 session.setAttribute(CARD_LIBRARY_NAME + "_useModePath", useModePath);
429                 session.setAttribute(CARD_LIBRARY_NAME + "_useMode", "");
430
431             }
432             else
433             {
434                 logger.debug("FichothequeServlet: setParameters: set useMode");
435                 session.setAttribute(CARD_LIBRARY_NAME + "_useMode", useMode);
436                 if (useMode.equals("user"))
437                 {
438                     session.setAttribute(CARD_LIBRARY_NAME + "_userRight", EDITOR_ROLE);
439                 }
440             }
441
442             }
443             catch (java.io.IOException JavaDoc ex)
444             {
445                 logger.error("FichothequeServlet: setParameters: Exception: " ,ex);
446                 ex.printStackTrace();
447             }
448         }
449         logger.debug("FichothequeServlet: setParameters: end useMode");
450
451
452         // initialise an empty inactive query
453
Query query = new Query();
454         if (session.getAttribute(CARD_LIBRARY_NAME + "_query") == null)
455         {
456             session.setAttribute(CARD_LIBRARY_NAME + "_query", query);
457         }
458
459         if ( !(((String JavaDoc)session.getAttribute(CARD_LIBRARY_NAME + "_useMode")).equals("")) )
460         {
461             // set the list
462

463             String JavaDoc oldContextId = (String JavaDoc)session.getAttribute(CARD_LIBRARY_NAME + "_oldContextId");
464
465             if ((session.getAttribute(CARD_LIBRARY_NAME + "_listCards") == null) || (!contextId.equals(oldContextId)) )
466             {
467                 String JavaDoc inPortal = (String JavaDoc)request.getAttribute("org.portletapi.portal");
468                 String JavaDoc useMode = (String JavaDoc)session.getAttribute(CARD_LIBRARY_NAME + "_useMode");
469                String JavaDoc remoteUser = (String JavaDoc)request.getRemoteUser();
470
471                ListCards currentList = new ListCards();
472               //currentList.loadList(CARD_LIBRARY_NAME, userRight, query, sortedBy, sortFlag, contextId, inPortal, useMode, remoteUser);
473
currentList.loadList(contextId, inPortal, useMode, remoteUser, userRight, sortFlag, sortedBy);
474               session.setAttribute(CARD_LIBRARY_NAME + "_listCards",currentList);
475               session.setAttribute(CARD_LIBRARY_NAME + "_oldContextId", contextId);
476             }
477         }
478
479         // set the fields names
480
request.setAttribute("card", CARD_FIELDS_NAMES);
481
482         // set the card library name
483
request.setAttribute("cardLibraryName", CARD_LIBRARY_NAME);
484
485         // set the number of card to display in the list
486
request.setAttribute("nbCardByPage", NB_CARD_BY_PAGE);
487
488         // set the editor role
489
session.setAttribute(CARD_LIBRARY_NAME + "_editorRole", EDITOR_ROLE);
490
491
492         // set servlet path for jsp
493
session.setAttribute(CARD_LIBRARY_NAME + "_servletURI", request.getRequestURI());
494
495
496
497
498         logger.debug("FichothequeServlet: setParameters: action= "
499             + CURRENT_ACTION + ", user= " + userName + ", userRight= "
500             + userRight + ", card_id = " + CURRENT_CARD_ID);
501
502     }
503
504
505     /**
506     * Replace a token in a string
507     *
508     * @param str string to be parsed
509     * @param token token to be found and replaced
510     * @param replaceValue the to insert where the token are found
511     */

512     protected String JavaDoc replace(String JavaDoc str, String JavaDoc token, String JavaDoc replaceValue)
513     {
514         String JavaDoc result = "";
515         int i = str.indexOf(token);
516         while (i != -1) {
517             result += str.substring(0,i) + replaceValue;
518             str = str.substring(i + token.length(), str.length());
519             i = str.indexOf(token);
520         }
521         return result + str;
522     }
523
524
525 }
526
527
528
529
Popular Tags