001: /*
002: * Enhydra Java Application Server Project
003: *
004: * The contents of this file are subject to the Enhydra Public License
005: * Version 1.1 (the "License"); you may not use this file except in
006: * compliance with the License. You may obtain a copy of the License on
007: * the Enhydra web site ( http://www.enhydra.org/ ).
008: *
009: * Software distributed under the License is distributed on an "AS IS"
010: * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
011: * the License for the specific terms governing rights and limitations
012: * under the License.
013: *
014: * The Initial Developer of the Enhydra Application Server is Lutris
015: * Technologies, Inc. The Enhydra Application Server and portions created
016: * by Lutris Technologies, Inc. are Copyright Lutris Technologies, Inc.
017: * All Rights Reserved.
018: *
019: * Contributor(s):
020: *
021: * $Id: Login.java,v 1.1 2006-09-11 12:30:36 sinisa Exp $
022: */
023:
024: package barracudaDiscRack.presentation.personMgmt;
025:
026: import barracudaDiscRack.business.person.*;
027: import barracudaDiscRack.presentation.BasePO;
028: import com.lutris.appserver.server.httpPresentation.*;
029: import com.lutris.appserver.server.session.*;
030: import com.lutris.util.*;
031: import org.enhydra.xml.xmlc.*;
032: import org.enhydra.xml.xmlc.html.*;
033: import org.w3c.dom.*;
034: import org.w3c.dom.html.*;
035: import org.enhydra.xml.xmlc.XMLObject;
036: import barracudaDiscRack.business.DiscRackBusinessException;
037: import barracudaDiscRack.presentation.DiscRackPresentationException;
038:
039: // import barracuda specifics
040: import org.barracudamvc.core.comp.*;
041: import org.barracudamvc.core.forms.*;
042: import org.barracudamvc.core.forms.validators.*;
043: import org.barracudamvc.plankton.data.*;
044: import org.barracudamvc.core.view.ViewCapabilities;
045: import org.barracudamvc.core.event.*;
046: import org.barracudamvc.core.comp.model.*;
047: import org.barracudamvc.plankton.data.CollectionsUtil;
048:
049: // import java specifics
050: import javax.servlet.http.*;
051: import javax.servlet.http.HttpServletRequest;
052: import javax.servlet.http.HttpServletResponse;
053: import java.io.*;
054: import java.util.List;
055: import java.util.Iterator;
056: import java.util.Collection;
057:
058: import org.apache.log4j.*;
059:
060: /**
061: * Login.java handles the login functionality of the DiscRack app.
062: *
063: * @author
064: * @version
065: */
066: public class Login extends BasePO {
067:
068: /**
069: * Constants
070: */
071: private static String SUBMIT_NAME = "submit";
072: private static String LOGIN_NAME = "login";
073: private static String PASSWORD_NAME = "password";
074: private static String ERROR_NAME = "ERROR_NAME";
075:
076: /**
077: * Superclass method override
078: */
079: public boolean loggedInUserRequired() {
080: return false;
081: }
082:
083: /**
084: * Default event. Just show the page.
085: */
086: public XMLObject handleDefault() throws HttpPresentationException {
087: return showPage(null);
088: }
089:
090: /**
091: * Process login data
092: *
093: * @return wml document
094: * @exception HttpPresentationException
095: */
096: public XMLObject handleLogin() throws HttpPresentationException {
097: String login = this .getComms().request.getParameter(LOGIN_NAME);
098: String password = this .getComms().request
099: .getParameter(PASSWORD_NAME);
100: Person user = null;
101: try {
102: user = PersonFactory.findPerson(login);
103: if (null == user || !user.getPassword().equals(password)) {
104: return showPage("Invalid username or password");
105: // Show error message that user not found (bad username/password)
106: } else {
107: this .setUser(user);
108: throw new ClientPageRedirectException(
109: getComms().request.getApplicationPath()
110: + DISC_CATALOG_PAGE);
111: }
112: } catch (DiscRackBusinessException ex) {
113: this .writeDebugMsg("System error finding user: "
114: + ex.getMessage());
115: throw new DiscRackPresentationException(
116: "System error finding user", ex);
117: }
118: }
119:
120: /**
121: * handle logout event
122: *
123: * @return html document
124: * @exception HttpPresentationException
125: */
126: public XMLObject handleLogout() throws HttpPresentationException {
127: this .removeUserFromSession();
128: return new ExitHTML();
129: }
130:
131: /**
132: * handle throw exception event.
133: *
134: * @return html document
135: * @exception Exception
136: */
137: public XMLObject handleThrowException() throws Exception {
138: throw new Exception(
139: "This is a test exception thrown from Login.java handleThrowException()");
140: }
141:
142: /**
143: * display page
144: *
145: * @param errorMsg, the error messages
146: * @return html document
147: */
148: public XMLObject showPage(String errorMsg) {
149:
150: LoginHTML page = (LoginHTML) myComms.xmlcFactory
151: .create(LoginHTML.class);
152:
153: if (null != errorMsg
154: || null != (errorMsg = this .getSessionData()
155: .getAndClearUserMessage())) {
156: page.setTextErrorText(errorMsg);
157: } else {
158: page.getElementErrorText().getParentNode().removeChild(
159: page.getElementErrorText());
160: }
161:
162: return page;
163: }
164:
165: //------------------------------------------------------------
166: // Use Barracuda Component Model
167: //------------------------------------------------------------
168:
169: /**
170: * handle special event to show page using Barracuda
171: */
172: public XMLObject handleShowUsingBarracuda()
173: throws HttpPresentationException {
174: return this .showPageUsingBarracuda(new DefaultStateMap());
175: }
176:
177: /**
178: * handle special event to login using Barracuda
179: */
180: public XMLObject handleLoginUsingBarracuda()
181: throws HttpPresentationException {
182:
183: //create the login form
184: ValidationException ve = null;
185: if (logger.isDebugEnabled())
186: logger.debug("Creating login form");
187: LoginForm lf = new LoginForm(getComms().session
188: .getHttpSession());
189: try {
190: //map/validate the form
191: if (logger.isDebugEnabled())
192: logger.debug("Mapping/Validating login form");
193: lf.map(this .getComms().request.getHttpServletRequest())
194: .validate(true);
195: } catch (ValidationException e) {
196: removeUserFromSession();
197: if (logger.isDebugEnabled())
198: logger.debug("Validation Exception: " + e);
199:
200: if (logger.isDebugEnabled()) {
201: CollectionsUtil.printStackTrace(e.getExceptionList(),
202: 0, logger, null);
203: }
204:
205: ve = e;
206: }
207:
208: //if no errors redirect to the catalog screen
209: if (ve == null) {
210: if (logger.isDebugEnabled())
211: logger.debug("Redirecting to "
212: + BasePO.DISC_CATALOG_PAGE);
213: throw new ClientPageRedirectException(getComms().request
214: .getApplicationPath()
215: + DISC_CATALOG_PAGE);
216: }
217:
218: if (logger.isDebugEnabled())
219: logger.debug("Displaying login page");
220:
221: // create a context for the rendering
222: StateMap context = new DefaultStateMap();
223:
224: //store a copy of the form and any errors in the context
225: if (logger.isDebugEnabled())
226: logger.debug("Saving form, errors");
227: context.putState(LOGIN_FORM, lf);
228: context.putState(LOGIN_ERR, ve);
229:
230: return this .showPageUsingBarracuda(context);
231: }
232:
233: /**
234: * display page using Barracuda
235: *
236: * @param context, the error messages
237: * @return html document
238: */
239: public XMLObject showPageUsingBarracuda(StateMap context) {
240:
241: LoginHTML page = (LoginHTML) myComms.xmlcFactory
242: .create(LoginHTML.class);
243:
244: //create a template component and render it
245: Node node = page.getDocument().getElementById("LoginForm");
246:
247: TemplateView tv = new DefaultTemplateView(node);
248: TemplateModel tm = new LoginModel(context);
249: BTemplate templateComp = new BTemplate(tm);
250: templateComp.setView(tv);
251:
252: try {
253: HttpServletRequest ireq = this .getComms().request
254: .getHttpServletRequest();
255: HttpServletResponse ires = this .getComms().response
256: .getHttpServletResponse();
257:
258: ViewContext vc = new DefaultViewContext(
259: new ViewCapabilities(), ireq, ires);
260: templateComp.render(vc);
261:
262: } catch (RenderException re) {
263: this .writeDebugMsg("Render err:" + re);
264: }
265:
266: return page;
267: }
268:
269: //=================================================================
270: // NOTE - the following are duplicated from LoginEventGateway.java
271: // (with modifications to remove any event model dependencies)
272: // purely for illustration of the standalone use of the
273: // Barracuda component/form models.
274: //=================================================================
275:
276: // setup a logger for the class
277: protected static Logger logger = Logger.getLogger(Login.class
278: .getName());
279:
280: //private constants
281: private static final String LOGIN_FORM = LoginEventGateway.class
282: .getName()
283: + ".LoginForm"; //LoginForm
284: private static final String LOGIN_ERR = LoginEventGateway.class
285: .getName()
286: + ".LoginErr"; //ValidationException
287:
288: //------------------------------------------------------------
289: // Template Models
290: //------------------------------------------------------------
291: /**
292: * LoginModel
293: */
294: class LoginModel extends AbstractTemplateModel {
295:
296: LoginForm fm = null;
297: ValidationException ve = null;
298:
299: //constructor (extract form, exception from context)
300: public LoginModel(StateMap context) {
301: fm = (LoginForm) context.getState(LOGIN_FORM);
302: ve = (ValidationException) context.getState(LOGIN_ERR);
303: }
304:
305: //register the model by name
306: public String getName() {
307: return "Login";
308: }
309:
310: public Object getItem(String key) {
311: ViewContext vc = getViewContext();
312: if (key.equals("Username")) {
313: String username = null;
314: try {
315: username = fm.getVal(LoginForm.USER, "").toString();
316: } catch (Exception ex) {
317: }
318: return (username != null ? username : "");
319: } else if (key.equals("Password")) {
320: String pass = null;
321: try {
322: pass = fm.getVal(LoginForm.PASSWORD, "").toString();
323: } catch (Exception ex) {
324: }
325: return (pass != null ? pass : "");
326: } else if (key.equals("Errors")) {
327: if (ve == null)
328: return "";
329: List errlist = ve.getExceptionList();
330: StringBuffer sb = new StringBuffer(
331: errlist.size() > 1 ? "There were several errors:"
332: : "");
333: Iterator it = errlist.iterator();
334: while (it.hasNext()) {
335: sb.append(" "
336: + ((ValidationException) it.next())
337: .getMessage());
338: }
339: return sb.toString();
340: } else {
341: return super .getItem(key);
342: }
343:
344: }
345: }
346:
347: //------------------------------------------------------------
348: // HTML Form Mappings, Validators
349: //------------------------------------------------------------
350:
351: /**
352: * Login form - define the login form
353: */
354: class LoginForm extends DefaultFormMap {
355: //login form constants (these values correspond to the HTML param names)
356: static final String USER = "login";
357: static final String PASSWORD = "password";
358:
359: HttpSession session = null;
360:
361: public LoginForm(HttpSession isession) {
362: session = isession;
363:
364: //define the elements
365: if (logger.isDebugEnabled())
366: logger.debug("Defining Login form elements");
367: this .defineElement(new DefaultFormElement(USER,
368: FormType.STRING, null, new NotNullValidator(
369: "You must enter a Login.")));
370: this .defineElement(new DefaultFormElement(PASSWORD,
371: FormType.STRING, null, new NotNullValidator(
372: "You must enter a Password.")));
373:
374: //define a form validator
375: if (logger.isDebugEnabled())
376: logger.debug("Defining Registration form validator");
377: this .defineValidator(new LoginValidator(session));
378: }
379:
380: /**
381: * we override this method because instead of using the default validation
382: * process (validate elements, then form), we don't want to validate at all
383: * if they are already logged in...we just assume they're valid and return.
384: */
385: public FormMap validate(boolean deferExceptions)
386: throws ValidationException {
387: //see if they are already logged in. If so, just consider them valid
388: if (logger.isDebugEnabled())
389: logger
390: .debug("Checking to see if already logged in (prevalidated)");
391: Person p = getUser();
392: if (null != p) {
393: try {
394: String fuser = this .getVal(LoginForm.USER, "")
395: .toString();
396: String fpassword = this .getVal(LoginForm.PASSWORD,
397: "").toString();
398: if (fuser == null && fpassword == null)
399: return this ; //if user/pwd = null, just use the current settings
400: if (p.getLogin().equals(fuser)
401: && p.getPassword().equals(fpassword))
402: return this ; //if they're != null, make sure they match, otherwise, we'll want to force a complete revalidate
403: } catch (DiscRackBusinessException e) {
404: }
405: }
406:
407: //if not, go ahead and validate
408: return super .validate(deferExceptions);
409: }
410: }
411:
412: /**
413: * Login validator - define a custom form validator
414: */
415: class LoginValidator extends DefaultFormValidator {
416:
417: HttpSession session = null;
418:
419: public LoginValidator(HttpSession isession) {
420: session = isession;
421: }
422:
423: public void validateForm(FormMap imap, boolean deferExceptions)
424: throws ValidationException {
425: if (logger.isDebugEnabled())
426: logger.debug("Validating login form");
427:
428: //validate the login information
429: if (logger.isDebugEnabled())
430: logger.debug("Validate the user/pwd info");
431: LoginForm map = (LoginForm) imap;
432: String user = map.getVal(LoginForm.USER, "").toString();
433: String password = map.getVal(LoginForm.PASSWORD, "")
434: .toString();
435: String errMsg = "Invalid username or password from LoginValidator. Please check your information and try again.";
436: try {
437: //make sure the login exists and the passwords match
438: Person person = PersonFactory.findPerson(user);
439: if (person == null)
440: throw new ValidationException(map
441: .getElement(LoginForm.USER), errMsg);
442: if (!person.getPassword().equals(password))
443: throw new ValidationException(map
444: .getElement(LoginForm.PASSWORD), errMsg);
445:
446: //log them in
447: setUser(person);
448: } catch (DiscRackBusinessException e) {
449: removeUserFromSession(); //just to be sure we don't get stuck in a loop
450: throw new ValidationException(
451: map.getElement(LoginForm.USER),
452: "System error finding user: "
453: + e.getMessage()
454: + ". Please try again. If the problem persists, contact your system administrator.",
455: e);
456: } catch (DiscRackPresentationException e) {
457: throw new ValidationException(
458: map.getElement(LoginForm.USER),
459: "System error setting user: "
460: + e.getMessage()
461: + ". Please try again. If the problem persists, contact your system administrator.",
462: e);
463: }
464: }
465: }
466: }
|