KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > golfShop > GolfShop


1 /*
2  * Enhydra Java Application Server
3  * The Initial Developer of the Original Code is Lutris Technologies Inc.
4  * Portions created by Lutris are Copyright (C) 1997-2000 Lutris Technologies
5  * Inc.
6  * All Rights Reserved.
7  *
8  * The contents of this file are subject to the Enhydra Public License Version
9  * 1.0 (the "License"); you may not use this file except in compliance with the
10  * License. You may obtain a copy of the License at
11  * http://www.enhydra.org/software/license/epl.html
12  *
13  * Software distributed under the License is distributed on an "AS IS" basis,
14  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
15  * License for the specific language governing rights and limitations under the
16  * License.
17  *
18  *
19  */

20
21 package golfShop;
22
23 import java.io.*;
24 import java.math.BigDecimal JavaDoc;
25 import java.util.Enumeration JavaDoc;
26 import com.lutris.util.*;
27 import com.lutris.logging.Logger;
28 import com.lutris.logging.LogChannel;
29 import com.lutris.appserver.server.session.*;
30 import com.lutris.appserver.server.user.*;
31 import com.lutris.appserver.server.*;
32 import com.lutris.appserver.server.httpPresentation.*;
33 import golfShop.spec.user.*;
34
35 import golfShop.spec.cart.*;
36 import golfShop.spec.*;
37 /**
38  * Application class for this specific application. This implements
39  * standard startup and shutdown methods and well as application specific
40  * ones.
41  */

42 public class GolfShop extends StandardApplication {
43     /*
44      * This is the global Config object that is shared by the
45      * whole application. If there was an error reading the file, this
46      * will be null.
47      *
48      * @see Config
49      */

50     public static Config config = null;
51
52     /**
53      * User manager for this application.
54      */

55     private GolfShopUserManager userManager = null;
56
57     /**
58      * Return the UserManager for this server.
59      */

60     public GolfShopUserManager getUserManager() {
61         return userManager;
62     }
63     
64     private final String JavaDoc DEFAULT_FILENAME = "user_store";
65     private final String JavaDoc DEFAULT_DIRECTORY =
66                    "golfShop/presentation/xmlc/contents/itemdb";
67     private final String JavaDoc DEFAULT_OPTION ="File";
68     
69     
70     /**
71      * Start the application.
72      *
73      * @param appConfig Configuration object.
74      * @exception HarmonyAppException If an error occurs starting the
75      * application.
76      */

77     public void startup(Config appConfig) throws ApplicationException {
78         /*
79          * This will create the config and sessionManager objects.
80          */

81         super.startup(appConfig);
82         if (logChannel != null) {
83             logChannel.write(Logger.INFO,
84                              "Welcome to the Lutris GolfShop application!");
85         }
86         config = appConfig;
87          
88               
89         try {
90         
91           userManager = GolfShopUserManagerFactory.getGolfShopUserManager("golfShop.business.user.GolfShopUserManagerImpl");
92                    
93           //Set the default values to parameters that we need to initialize storages
94
String JavaDoc userStoreOption = DEFAULT_OPTION;
95           String JavaDoc storeOption = DEFAULT_OPTION;
96           String JavaDoc fileName = DEFAULT_FILENAME;
97           String JavaDoc dir = DEFAULT_DIRECTORY;
98          try{
99          
100           //Take the values from configuration file
101
userStoreOption = config.getString("GolfShop.UserStoreOption");
102           storeOption = config.getString("GolfShop.ItemStore.Option");
103          } catch (ConfigException e) {
104             
105          }
106          
107          File tempFile = null;
108          String JavaDoc tempString = null;
109          
110          // GolfShop.ItemStore.Directory parameter initialization
111

112          try{
113           dir = config.getString("GolfShop.ItemStore.Directory");
114           tempFile = new File(dir);
115           if (!tempFile.exists()||!tempFile.isDirectory()){
116             // in case a relative path is given (relative from configuration file)
117
tempString = config.getConfigFile().getFile().getParent();
118             dir = tempString+File.separator+dir;
119             tempFile = new File(dir);
120             
121             if (!tempFile.exists()||!tempFile.isDirectory()){
122                 tempString = this.getClass().getClassLoader().getResource(DEFAULT_DIRECTORY).getPath();
123                     dir = tempString;
124                     tempFile = new File(dir);
125             }
126           }
127          } catch (ConfigException e) {
128              tempString = this.getClass().getClassLoader().getResource(DEFAULT_DIRECTORY).getPath();
129              dir = tempString;
130              tempFile = new File(dir);
131          }
132          
133          if (!tempFile.exists()||!tempFile.isDirectory()){
134              dir = DEFAULT_DIRECTORY;
135              if (logChannel != null) {
136                 logChannel.write(Logger.INFO,
137                                  "GolfShop.ItemStore.Directory application parameter not initialized properly!");
138              }
139            }
140            
141            // GolfShop.UserStoreFilename parameter initialization
142

143          try{
144           fileName = config.getString("GolfShop.UserStoreFilename");
145           tempFile = new File(fileName);
146           if (!tempFile.exists()){
147             // in case a relative path is given (relative from configuration file)
148
tempString = config.getConfigFile().getFile().getParent();
149             fileName = tempString+File.separator+fileName;
150             tempFile = new File(fileName);
151             
152             if (!tempFile.exists()){
153                 tempString = this.getClass().getClassLoader().getResource(DEFAULT_FILENAME).getPath();
154                     fileName = tempString;
155                     tempFile = new File(fileName);
156             }
157           }
158          } catch (ConfigException e) {
159              tempString = this.getClass().getClassLoader().getResource(DEFAULT_FILENAME).getPath();
160              fileName = tempString;
161              tempFile = new File(fileName);
162          }
163          
164          if (!tempFile.exists()){
165              fileName = DEFAULT_FILENAME;
166              if (logChannel != null) {
167                 logChannel.write(Logger.INFO,
168                                  "GolfShop.UserStoreFilename application parameter not initialized properly!");
169              }
170            }
171          
172          //This will initialize all storages with given parameters
173
Initialize initialize = InitializeFactory.getInitialize("golfShop.business.InitializeImpl");
174          initialize.storages(userStoreOption,fileName,storeOption,dir);
175         
176 /*
177  * Catch null pointer exception ( we canot make a instances of classes from business layer when we run GolfShop_pres )
178  * We need to allow GolfShop_pres to be functional
179  */

180          }catch(NullPointerException JavaDoc e){
181          } catch (Exception JavaDoc e) {
182             // N.B. If shutdown methods are available for session and user
183
// manager, call them.
184
userManager = null;
185
186             // This application isn't designed to be restarted.
187
state = DEAD;
188             if (e instanceof ApplicationException) {
189                 throw (ApplicationException)e;
190             } else {
191                 throw new ApplicationException("failure to initialize GolfShop", e);
192             }
193         }
194     }
195
196     /**
197      * Shutdown the application.
198      */

199     public void shutdown() {
200         userManager = null;
201         super.shutdown();
202     }
203
204
205     public boolean requestPreprocessor(HttpPresentationComms comms)
206         throws Exception JavaDoc {
207         
208         if (logChannel != null) {
209             logChannel.write(Logger.DEBUG,
210                              "URI=\"" + comms.request.getRequestURI() + "\"");
211         }
212         
213         super.requestPreprocessor(comms);
214         if (comms.session == null) {
215             // Session not setup; so its not a presentation object.
216
return false;
217         }
218
219         String JavaDoc pp = comms.request.getApplicationPath();
220         if (!pp.endsWith("/"))
221             pp += "/";
222         String JavaDoc loginDir = pp + "login/";
223         String JavaDoc mediaDir = pp + "media/";
224         String JavaDoc page = comms.request.getRequestURI();
225         if (page.startsWith(loginDir) || page.startsWith(mediaDir)) {
226             /*
227              * Let them go to the login and logout areas whether or not
228              * they are logged in.
229              */

230             return false;
231         } else {
232                 //We need to allow poker_pres to be dynamic , so if the requested url is GolfShop_pres user dont need to be logged
233
String JavaDoc uri = comms.request.getRequestURI();
234          boolean is= uri.startsWith("/GolfShop_pres");
235           
236          if(is)
237          
238           return false;
239         
240           else{
241             if (comms.session.getUser() != null)
242                 // It's ok, they are logged in already.
243
return false;
244             else {
245                 // They are not logged in! Redirect to login page.
246
String JavaDoc url = pp + "login/Login.po";
247                 throw new ClientPageRedirectException(url);
248             }
249           }
250         }
251     }
252
253     /*
254      * Generate an HTML table of sessions.
255      */

256     private String JavaDoc makeSessionTable(Enumeration JavaDoc allSessions) {
257         StringBuffer JavaDoc results = new StringBuffer JavaDoc();
258
259         results.append("<TABLE><TR><TD ALIGN=CENTER><B>Username</B></TD>" +
260                        "<TD ALIGN=CENTER><B>Current total</B></TD></TR>\n");
261         while (allSessions.hasMoreElements()) {
262             String JavaDoc sessionKey = (String JavaDoc)allSessions.nextElement();
263             Session session;
264             try {
265                 session = sessionManager.getSession(sessionKey);
266             } catch (SessionException except) {
267                 // Skip session that may have just become invalid
268
continue;
269             }
270             Cart cart = null;
271             String JavaDoc username = null;
272             String JavaDoc totalStr = null;
273             
274             User user = session.getUser();
275             if (user != null) {
276                 username = user.getName();
277             } else {
278                 username = "<I>Not logged in yet</I>";
279             }
280
281             SessionData sd = session.getSessionData();
282             try {
283                 cart = (Cart)sd.get("cart");
284             } catch (KeywordValueException kve) {
285             }
286             if (cart != null) {
287                 double total = cart.getTotal();
288                 BigDecimal JavaDoc total2 = new BigDecimal JavaDoc(total);
289                 total2 = total2.setScale(2, BigDecimal.ROUND_HALF_UP);
290                 totalStr = "$" + total2;
291             } else {
292                 totalStr = "<I>No cart</I>";
293             }
294             results.append("<TR><TD ALIGN=CENTER>");
295             results.append(username);
296             results.append("</TD><TD ALIGN=RIGHT>");
297             results.append("</TD></TR>\n");
298         }
299         results.append("</TABLE>\n");
300         return results.toString();
301     }
302
303     /*
304      * The MultiServer's admin app will notice that this function exists
305      * and will call it when showing the state of this application.
306      * This is my chance to display info specific to this application.
307      */

308     public String JavaDoc toHtml() {
309         Enumeration JavaDoc allSessions;
310         try {
311             allSessions = sessionManager.getSessionKeys();
312         } catch (SessionException except) {
313             // Return error as HTML.
314
return except.getClass().getName() + " " + except.getMessage();
315         }
316         if (!allSessions.hasMoreElements()) {
317             return "There are no current sessions.";
318         } else {
319             return makeSessionTable(allSessions);
320         }
321     }
322 }
323
Popular Tags