You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@struts.apache.org by dw...@apache.org on 2002/01/15 04:48:06 UTC
cvs commit: jakarta-struts/contrib/validator/src/share/org/apache/struts/validator/util StrutsValidator.java StrutsValidatorUtil.java
dwinterfeldt 02/01/14 19:48:06
Added: contrib/validator/src/example/org/apache/struts/validator/example
ApplicationResources.properties
ApplicationResources_fr.properties
CityStateZip.java MultiRegistrationAction.java
RegistrationAction.java RegistrationForm.java
TypeAction.java TypeForm.java
contrib/validator/src/share/org/apache/struts/validator/action
ValidatorActionForm.java ValidatorForm.java
ValidatorServlet.java
contrib/validator/src/share/org/apache/struts/validator/taglib/html
JavascriptValidatorTag.java
contrib/validator/src/share/org/apache/struts/validator/util
StrutsValidator.java StrutsValidatorUtil.java
Log:
Checking in classes under new packages with dependencies on the Commons Validator.
Revision Changes Path
1.1 jakarta-struts/contrib/validator/src/example/org/apache/struts/validator/example/ApplicationResources.properties
Index: ApplicationResources.properties
===================================================================
button.cancel=Cancel
button.confirm=Confirm
button.reset=Reset
button.save=Save
# Errors
errors.footer=
errors.header=<h3><font color="red">Validation Error</font></h3>You must correct the following error(s) before proceeding:
errors.ioException=I/O exception rendering error messages: {0}
error.database.missing=<li>User database is missing, cannot validate logon credentials</li>
errors.required={0} is required.
errors.minlength={0} can not be less than {1} characters.
errors.maxlength={0} can not be greater than {1} characters.
errors.invalid={0} is invalid.
errors.byte={0} must be an byte.
errors.short={0} must be an short.
errors.integer={0} must be an integer.
errors.long={0} must be an long.
errors.float={0} must be an float.
errors.double={0} must be an double.
errors.date={0} is not a date.
errors.range={0} is not in the range {1} through {2}.
errors.creditcard={0} is not a valid credit card number.
errors.email={0} is an invalid e-mail address.
# Registration Form
registrationForm.title=Registration
registrationForm.title.create=Register
registrationForm.title.edit=Edit User Information
registrationForm.firstname.displayname=First Name
registrationForm.lastname.displayname=Last Name
registrationForm.addr.displayname=Address
registrationForm.city.displayname=City
registrationForm.stateprov.displayname=State
registrationForm.zippostal.displayname=Zip
registrationForm.phone.displayname=Phone
registrationForm.email.displayname=E-mail
registrationForm.lastname.maskmsg=Last Name can only be letters and numbers, no spaces.
# Type form
typeForm.title=Type Form
typeForm.title.create=Type Form
typeForm.byte.displayname=Byte Field
typeForm.short.displayname=Short Field
typeForm.integer.displayname=Integer Field
typeForm.long.displayname=Long Field
typeForm.float.displayname=Float Field
typeForm.double.displayname=Double Field
typeForm.date.displayname=Date Field
typeForm.creditCard.displayname=Credit Card
1.1 jakarta-struts/contrib/validator/src/example/org/apache/struts/validator/example/ApplicationResources_fr.properties
Index: ApplicationResources_fr.properties
===================================================================
button.cancel=Annulent
button.confirm=Confirment
button.reset=Remettent
button.save=�conomiser
# Errors
errors.footer=
errors.header=<h3><font color="red">Erreur De Validation</font></h3>Vous devez corriger l'error(s) suivant avant proc�dant:
errors.ioException=Exception de E/S rendant des messages d'erreur: {0}
error.database.missing=<li>La base de données d'utilisateur est manquante, ne peut pas valider des qualifications de procédure de connexion </li>
errors.required={0} est exig�.
errors.minlength=Le {0} ne peut pas �tre moins de {1} caract�res.
errors.maxlength=Le {0} ne peut pas �tre les caract�res {1} plus grands que.
errors.invalid={0} est incorrect.
errors.byte=Le {0} doit �tre un nombre byte.
errors.short=Le {0} doit �tre un nombre short.
errors.integer=Le {0} doit �tre un nombre integer.
errors.long=Le {0} doit �tre un nombre long.
errors.float=Le {0} doit �tre un nombre float.
errors.double=Le {0} doit �tre un nombre double.
errors.date=Le {0} n'est pas une date.
errors.range=Le {0} n'est pas dans l'intervalle {1} � {2}.
errors.creditcard=Le {0} n'est pas un nombre valide de carte de cr�dit.
errors.email=Le {0} est une adresse incorrecte de e-mail.
# Registration Form
registrationForm.title=Enregistrement
registrationForm.title.create=Registre
registrationForm.title.edit=�ditez L'Information D'Utilisateur
registrationForm.firstname.displayname=Pr�nom
registrationForm.lastname.displayname=Dernier Nom
registrationForm.addr.displayname=Adresse
registrationForm.city.displayname=Ville
registrationForm.stateprov.displayname=�tat/Province
registrationForm.zippostal.displayname=Code postal
registrationForm.phone.displayname=T�l�phone
registrationForm.email.displayname=E-mail
registrationForm.lastname.maskmsg=Le dernier nom peut seulement être des lettres et des nombres, aucuns espaces.
# Type form
typeForm.title=Tapez La Forme
typeForm.title.create=Tapez La Forme
typeForm.byte.displayname=Zone D'Octet
typeForm.short.displayname=Courte Zone
typeForm.integer.displayname=Zone De Nombre entier
typeForm.long.displayname=Longue Zone
typeForm.float.displayname=Gisement De Flotteur
typeForm.double.displayname=Double Zone
typeForm.date.displayname=Zone De Date
typeForm.creditCard.displayname=Carte de cr�dit
1.1 jakarta-struts/contrib/validator/src/example/org/apache/struts/validator/example/CityStateZip.java
Index: CityStateZip.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Struts", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.struts.validator.example;
/**
* Just used to provide an indexed properties example.
*
* @author David Wintefeldt
*/
public class CityStateZip implements java.io.Serializable {
private String sCity = null;
private String sStateProv = null;
private String[] sZipPostal = new String[3];
public String getCity() {
return sCity;
}
public void setCity(String sCity) {
this.sCity = sCity;
}
public String getStateProv() {
return sStateProv;
}
public void setStateProv(String sStateProv) {
this.sStateProv = sStateProv;
}
public String getZipPostal(int index) {
return sZipPostal[index];
}
public void setZipPostal(int index, String value) {
this.sZipPostal[index] = value;
}
}
1.1 jakarta-struts/contrib/validator/src/example/org/apache/struts/validator/example/MultiRegistrationAction.java
Index: MultiRegistrationAction.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Struts", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.struts.validator.example;
import java.io.IOException;
import java.util.Locale;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;
/**
* Implementation of <strong>Action</strong> that validates a multi-page
* registration form.
*
* @author David Wintefeldt
*/
public final class MultiRegistrationAction extends Action {
/**
* Process the specified HTTP request, and create the corresponding HTTP
* response (or forward to another web component that will create it).
* Return an <code>ActionForward</code> instance describing where and how
* control should be forwarded, or <code>null</code> if the response has
* already been completed.
*
* @param mapping The ActionMapping used to select this instance
* @param actionForm The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet exception occurs
*/
public ActionForward perform(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
// Extract attributes we will need
HttpSession session = request.getSession();
Locale locale = getLocale(request);
MessageResources messages = getResources();
RegistrationForm info = (RegistrationForm)form;
String action = request.getParameter("action");
// Was this transaction cancelled?
if (isCancelled(request)) {
log(" " + mapping.getAttribute() + " - Registration transaction was cancelled");
removeFormBean(mapping, request);
return (mapping.findForward("success"));
}
ActionErrors errors = info.validate(mapping, request);
if (errors != null && errors.empty()) {
if (info.getPage() == 1)
return mapping.findForward("input2");
if (info.getPage() == 2)
return mapping.findForward("success");
} else {
saveErrors(request, errors);
if (info.getPage() == 1)
return mapping.findForward("input" + info.getPage());
if (info.getPage() == 2)
return mapping.findForward("input" + info.getPage());
}
return mapping.findForward("input1");
}
/**
* Convenience method that call the comparable servlet log method and writes
* an explanatory message and a stack trace for a given Throwable exception to the
* servlet log file.
*
* @param message String that describes the error or exception
*/
protected void log(String message) {
if (servlet.getDebug() >= 1)
servlet.log(message);
}
/**
* Convenience method that call the comparable servlet log method and writes
* an explanatory message and a stack trace for a given Throwable exception to the
* servlet log file.
*
* @param message String that describes the error or exception
* @param throwable Throwable error or exception
*/
protected void log(String message, Throwable throwable) {
if (servlet.getDebug() >= 1)
servlet.log(message, throwable);
}
/**
* Convenience method for removing the obsolete form bean.
*
* @param mapping The ActionMapping used to select this instance
* @param request The HTTP request we are processing
*/
protected void removeFormBean(ActionMapping mapping, HttpServletRequest request) {
// Remove the obsolete form bean
if (mapping.getAttribute() != null) {
if ("request".equals(mapping.getScope())) {
request.removeAttribute(mapping.getAttribute());
} else {
HttpSession session = request.getSession();
session.removeAttribute(mapping.getAttribute());
}
}
}
}
1.1 jakarta-struts/contrib/validator/src/example/org/apache/struts/validator/example/RegistrationAction.java
Index: RegistrationAction.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Struts", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.struts.validator.example;
import java.io.IOException;
import java.util.Locale;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;
/**
* Implementation of <strong>Action</strong> that validates a registration form.
*
* @author David Wintefeldt
*/
public final class RegistrationAction extends Action {
/**
* Process the specified HTTP request, and create the corresponding HTTP
* response (or forward to another web component that will create it).
* Return an <code>ActionForward</code> instance describing where and how
* control should be forwarded, or <code>null</code> if the response has
* already been completed.
*
* @param mapping The ActionMapping used to select this instance
* @param actionForm The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet exception occurs
*/
public ActionForward perform(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
// Extract attributes we will need
HttpSession session = request.getSession();
Locale locale = getLocale(request);
MessageResources messages = getResources();
RegistrationForm info = (RegistrationForm)form;
String action = request.getParameter("action");
// Was this transaction cancelled?
if (isCancelled(request)) {
log(" " + mapping.getAttribute() + " - Registration transaction was cancelled");
removeFormBean(mapping, request);
return (mapping.findForward("success"));
}
return mapping.findForward("success");
}
/**
* Convenience method that call the comparable servlet log method and writes
* an explanatory message and a stack trace for a given Throwable exception to the
* servlet log file.
*
* @param message String that describes the error or exception
*/
protected void log(String message) {
if (servlet.getDebug() >= 1)
servlet.log(message);
}
/**
* Convenience method that call the comparable servlet log method and writes
* an explanatory message and a stack trace for a given Throwable exception to the
* servlet log file.
*
* @param message String that describes the error or exception
* @param throwable Throwable error or exception
*/
protected void log(String message, Throwable throwable) {
if (servlet.getDebug() >= 1)
servlet.log(message, throwable);
}
/**
* Convenience method for removing the obsolete form bean.
*
* @param mapping The ActionMapping used to select this instance
* @param request The HTTP request we are processing
*/
protected void removeFormBean(ActionMapping mapping, HttpServletRequest request) {
// Remove the obsolete form bean
if (mapping.getAttribute() != null) {
if ("request".equals(mapping.getScope())) {
request.removeAttribute(mapping.getAttribute());
} else {
HttpSession session = request.getSession();
session.removeAttribute(mapping.getAttribute());
}
}
}
}
1.1 jakarta-struts/contrib/validator/src/example/org/apache/struts/validator/example/RegistrationForm.java
Index: RegistrationForm.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Struts", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.struts.validator.example;
import java.io.Serializable;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.validator.action.ValidatorForm;
/**
* Form bean for the user registration page.
*
* @author David Wintefeldt
*/
public final class RegistrationForm extends ValidatorForm implements Serializable {
private String action = null;
private String sFirstName = null;
private String sLastName = null;
private String sAddr = null;
private CityStateZip csz = new CityStateZip();
private String sPhone = null;
private String sEmail = null;
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public String getFirstName() {
return sFirstName;
}
public void setFirstName(String sFirstName) {
this.sFirstName = sFirstName;
}
public String getLastName() {
return sLastName;
}
public void setLastName(String sLastName) {
this.sLastName = sLastName;
}
public String getAddr() {
return sAddr;
}
public void setAddr(String sAddr) {
this.sAddr = sAddr;
}
public CityStateZip getCityStateZip() {
return csz;
}
public void setCityStateZip(CityStateZip csz) {
this.csz = csz;
}
public String getPhone() {
return sPhone;
}
public void setPhone(String sPhone) {
this.sPhone = sPhone;
}
public String getEmail() {
return sEmail;
}
public void setEmail(String sEmail) {
this.sEmail = sEmail;
}
/**
* Reset all properties to their default values.
*
* @param mapping The mapping used to select this instance
* @param request The servlet request we are processing
*/
public void reset(ActionMapping mapping, HttpServletRequest request) {
action = null;
sFirstName = null;
sLastName = null;
sAddr = null;
csz = new CityStateZip();
sPhone = null;
sEmail = null;
}
}
1.1 jakarta-struts/contrib/validator/src/example/org/apache/struts/validator/example/TypeAction.java
Index: TypeAction.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Struts", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.struts.validator.example;
import java.io.IOException;
import java.util.Locale;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;
/**
* Implementation of <strong>Action</strong> that validates a different 'types'.
*
* @author David Wintefeldt
*/
public final class TypeAction extends Action {
/**
* Process the specified HTTP request, and create the corresponding HTTP
* response (or forward to another web component that will create it).
* Return an <code>ActionForward</code> instance describing where and how
* control should be forwarded, or <code>null</code> if the response has
* already been completed.
*
* @param mapping The ActionMapping used to select this instance
* @param actionForm The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet exception occurs
*/
public ActionForward perform(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
// Extract attributes we will need
HttpSession session = request.getSession();
Locale locale = getLocale(request);
MessageResources messages = getResources();
TypeForm info = (TypeForm)form;
String action = request.getParameter("action");
// Was this transaction cancelled?
if (isCancelled(request)) {
log(" " + mapping.getAttribute() + " - Type transaction was cancelled");
removeFormBean(mapping, request);
return (mapping.findForward("success"));
}
return mapping.findForward("success");
}
/**
* Convenience method that call the comparable servlet log method and writes
* an explanatory message and a stack trace for a given Throwable exception to the
* servlet log file.
*
* @param message String that describes the error or exception
*/
protected void log(String message) {
if (servlet.getDebug() >= 1)
servlet.log(message);
}
/**
* Convenience method that call the comparable servlet log method and writes
* an explanatory message and a stack trace for a given Throwable exception to the
* servlet log file.
*
* @param message String that describes the error or exception
* @param throwable Throwable error or exception
*/
protected void log(String message, Throwable throwable) {
if (servlet.getDebug() >= 1)
servlet.log(message, throwable);
}
/**
* Convenience method for removing the obsolete form bean.
*
* @param mapping The ActionMapping used to select this instance
* @param request The HTTP request we are processing
*/
protected void removeFormBean(ActionMapping mapping, HttpServletRequest request) {
// Remove the obsolete form bean
if (mapping.getAttribute() != null) {
if ("request".equals(mapping.getScope())) {
request.removeAttribute(mapping.getAttribute());
} else {
HttpSession session = request.getSession();
session.removeAttribute(mapping.getAttribute());
}
}
}
}
1.1 jakarta-struts/contrib/validator/src/example/org/apache/struts/validator/example/TypeForm.java
Index: TypeForm.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Struts", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.struts.validator.example;
import java.io.Serializable;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.validator.action.ValidatorForm;
/**
* Form bean for the user type page.
*
* @author David Wintefeldt
*/
public final class TypeForm extends ValidatorForm implements Serializable {
private String action = null;
private String sByte = null;
private String sShort = null;
private String sInteger = null;
private String sLong = null;
private String sFloat = null;
private String sDouble = null;
private String sDate = null;
private String sCreditCard = null;
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public String getByte() {
return sByte;
}
public void setByte(String sByte) {
this.sByte = sByte;
}
public String getShort() {
return sShort;
}
public void setShort(String sShort) {
this.sShort = sShort;
}
public String getInteger() {
return sInteger;
}
public void setInteger(String sInteger) {
this.sInteger = sInteger;
}
public String getLong() {
return sLong;
}
public void setLong(String sLong) {
this.sLong = sLong;
}
public String getFloat() {
return sFloat;
}
public void setFloat(String sFloat) {
this.sFloat = sFloat;
}
public String getDouble() {
return sDouble;
}
public void setDouble(String sDouble) {
this.sDouble = sDouble;
}
public String getDate() {
return sDate;
}
public void setDate(String sDate) {
this.sDate = sDate;
}
public String getCreditCard() {
return sCreditCard;
}
public void setCreditCard(String sCreditCard) {
this.sCreditCard = sCreditCard;
}
/**
* Reset all properties to their default values.
*
* @param mapping The mapping used to select this instance
* @param request The servlet request we are processing
*/
public void reset(ActionMapping mapping, HttpServletRequest request) {
action = null;
sByte = null;
sShort = null;
sInteger = null;
sLong = null;
sFloat = null;
sDouble = null;
sDate = null;
sCreditCard = null;
}
}
1.1 jakarta-struts/contrib/validator/src/share/org/apache/struts/validator/action/ValidatorActionForm.java
Index: ValidatorActionForm.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Struts", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.struts.validator.action;
import java.io.Serializable;
import java.util.Locale;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.commons.validator.Validator;
import org.apache.commons.validator.ValidatorException;
import org.apache.commons.validator.ValidatorResources;
/**
* <p>This class extends <strong>ValidatorForm</strong> and provides
* basic field validation based on an XML file. The key passed into the
* validator is the action element's 'path' attribute from the
* struts-config.xml which should match the form element's name attribute
* in the validation.xml.</p>
*
* <ul><li>See /WEB-INF/validation.xml for validation rules.</li></ul>
*
* @author David Winterfeldt
*/
public class ValidatorActionForm extends ValidatorForm implements Serializable {
/**
* Validate the properties that have been set from this HTTP request,
* and return an <code>ActionErrors</code> object that encapsulates any
* validation errors that have been found. If no errors are found, return
* <code>null</code> or an <code>ActionErrors</code> object with no
* recorded error messages.
*
* @param mapping The mapping used to select this instance
* @param request The servlet request we are processing
*/
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
Validator validator = initValidator(mapping.getPath(), request, errors);
try {
validator.validate();
} catch (ValidatorException e) {
log("ValidatorActionForm::validate() - " + e.getMessage(), e);
}
return errors;
}
}
1.1 jakarta-struts/contrib/validator/src/share/org/apache/struts/validator/action/ValidatorForm.java
Index: ValidatorForm.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Struts", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.struts.validator.action;
import java.io.Serializable;
import java.util.Locale;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.commons.validator.Validator;
import org.apache.commons.validator.ValidatorException;
import org.apache.commons.validator.ValidatorResources;
import org.apache.struts.validator.util.StrutsValidatorUtil;
/**
* <p>This class extends <strong>ActionForm</strong> and provides
* basic field validation based on an XML file. The key passed into the
* validator is the action element's 'name' attribute from the
* struts-config.xml which should match the form element's name attribute
* in the validation.xml.</p>
*
* <ul><li>See /WEB-INF/validation.xml for validation rules.</li></ul>
*
* @author David Winterfeldt
* @see org.apache.struts.action.ActionForm
*/
public class ValidatorForm extends ActionForm implements Serializable {
/**
* Used to indicate the current page of a multi-page form.
*/
protected int page = 0;
/**
* Gets page.
*/
public int getPage() {
return page;
}
/**
* Sets page.
*/
public void setPage(int page) {
this.page = page;
}
/**
* Validate the properties that have been set from this HTTP request,
* and return an <code>ActionErrors</code> object that encapsulates any
* validation errors that have been found. If no errors are found, return
* <code>null</code> or an <code>ActionErrors</code> object with no
* recorded error messages.
*
* @param mapping The mapping used to select this instance
* @param request The servlet request we are processing
*/
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
Validator validator = initValidator(mapping.getAttribute(), request, errors);
try {
validator.validate();
} catch (ValidatorException e) {
log("ValidatorForm::validate() - " + e.getMessage(), e);
}
return errors;
}
/**
* Initialize the <code>Validator</code> to perform validation.
*
* @param key The key that the validation rules are under
* (the form elements name attribute).
* @param request The current request object.
* @param errors The object any errors will be stored in.
*/
protected Validator initValidator(String key, HttpServletRequest request, ActionErrors errors) {
ServletContext application = getServlet().getServletContext();
ValidatorResources resources = StrutsValidatorUtil.getValidatorResources(application);
Locale locale = StrutsValidatorUtil.getLocale(request);
Validator validator = new Validator(resources, key);
//validator.setDebug(getServlet().getDebug());
validator.setPage(getPage());
validator.addResource(Validator.SERVLET_CONTEXT_KEY, application);
validator.addResource(Validator.HTTP_SERVLET_REQUEST_KEY, request);
validator.addResource(Validator.LOCALE_KEY, locale);
validator.addResource(Validator.ACTION_ERRORS_KEY, errors);
validator.addResource(Validator.BEAN_KEY, this);
return validator;
}
/**
* Convenience method that call the comparable servlet log method and writes
* an explanatory message and a stack trace for a given Throwable exception to the
* servlet log file.
*
* @param message String that describes the error or exception
*/
protected void log(String message) {
if (getServlet().getDebug() >= 1)
getServlet().log(message);
}
/**
* Convenience method that call the comparable servlet log method and writes
* an explanatory message and a stack trace for a given Throwable exception to the
* servlet log file.
*
* @param message String that describes the error or exception
* @param throwable Throwable error or exception
*/
protected void log(String message, Throwable throwable) {
if (getServlet().getDebug() >= 1)
getServlet().log(message, throwable);
}
/**
* Reset all properties to their default values.
*
* @param mapping The mapping used to select this instance
* @param request The servlet request we are processing
*/
public void reset(ActionMapping mapping, HttpServletRequest request) {
super.reset(mapping, request);
page = 0;
}
}
1.1 jakarta-struts/contrib/validator/src/share/org/apache/struts/validator/action/ValidatorServlet.java
Index: ValidatorServlet.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Struts", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.struts.validator.action;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.validator.ValidatorResources;
import org.apache.commons.validator.ValidatorResourcesInitializer;
/**
* <p><strong>ValidatorServlet</strong> loads validation values into application scope.</p>
*
* @author David Winterfeldt
*/
public class ValidatorServlet extends HttpServlet {
public final static String VALIDATOR_KEY = "org.apache.struts.validator.action.VALIDATOR";
/**
* The set of Form instances that have been created and initialized,
* keyed by the struts form name.
*/
protected ValidatorResources resources = null;
/**
* The context-relative path to our configuration resource.
*/
protected String config = "WEB-INF/validation.xml";
/**
* The debugging detail level for this servlet.
*/
protected int debug = 0;
// ---------------------------------------------------- HttpServlet Methods
/**
* Gracefully shut down this controller servlet, releasing any resources
* that were allocated at initialization.
*/
public void destroy() {
if (debug >= 1)
log("Destroying ValidatorServlet");
destroyMapping();
}
/**
* Initialize this servlet. Most of the processing has been factored into
* support methods so that you can override particular functionality at a
* fairly granular level.
*
* @exception ServletException if we cannot configure ourselves correctly
*/
public void init() throws ServletException {
try {
initDebug();
initMapping();
} catch (IOException e) {
throw new UnavailableException
("Failure to initMapping in ValidatorServlet.");
}
getServletContext().setAttribute(VALIDATOR_KEY, resources);
}
/**
* Process an HTTP "GET" request.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet exception occurs
*/
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
// if action=reload, reload
//process(request, response);
}
/**
* Process an HTTP "POST" request.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet exception occurs
*/
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
// if action=reload, reload
//process(request, response);
}
// --------------------------------------------------------- Public Methods
/**
* Reload the configuration of this controller servlet from our
* underlying configuration files.
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet exception occurs
*/
public void reload() throws IOException, ServletException {
if (debug >= 1)
log("Reloading ValidatorServlet");
// Restart from our confirmation files
initMapping();
}
// ------------------------------------------------------ Protected Methods
protected void destroyMapping() {
resources = null;
}
/**
* Initialize the mapping information for this application.
*
* @exception IOException if an input/output error is encountered
* @exception ServletException if we cannot initialize these resources
*/
protected void initMapping() throws IOException, ServletException {
// Acquire an input stream to our database file
// Initialize the context-relative path to our configuration resources
String value = null;
value = getServletConfig().getInitParameter("config");
if (value != null)
config = value;
if (debug >= 1)
log("Loading validation file from '" + config + "'");
InputStream input = null;
input = getServletContext().getResourceAsStream(config);
if (input == null)
throw new UnavailableException("Can't load Validator XML file.");
BufferedInputStream bis = new BufferedInputStream(input);
try {
resources = ValidatorResourcesInitializer.initialize(bis, debug);
// new HttpValidatorLog(getServletContext()), bis, debug);
} catch (Exception e) {
log("ValidatorServlet::initMapping - " + e.getMessage(), debug);
}
}
/**
* Initialize the debugging detail level for this application's validator.
*
* @exception ServletException if we cannot initialize these resources
*/
protected void initDebug() throws ServletException {
String value = getServletConfig().getInitParameter("debug");
try {
debug = Integer.parseInt(value);
} catch (Throwable t) {
debug = 0;
}
}
/**
* Return the debugging detail level for this servlet.
*/
public int getDebug() {
return (this.debug);
}
/**
* Log the specified message if the current debugging detail level for
* this servlet has been set to an equal or higher value. Otherwise,
* ignore this message.
*
* @param message Message to be logged
* @param level Debugging detail level of this message
*/
public void log(String message, int level) {
if (debug >= level)
log(message);
}
}
1.1 jakarta-struts/contrib/validator/src/share/org/apache/struts/validator/taglib/html/JavascriptValidatorTag.java
Index: JavascriptValidatorTag.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Struts", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.struts.validator.taglib.html;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyTagSupport;
import org.apache.struts.action.Action;
import org.apache.struts.util.MessageResources;
import org.apache.struts.validator.action.ValidatorServlet;
import org.apache.commons.validator.Field;
import org.apache.commons.validator.Form;
import org.apache.commons.validator.ValidatorAction;
import org.apache.commons.validator.ValidatorResources;
import org.apache.commons.validator.ValidatorUtil;
import org.apache.commons.validator.Var;
import org.apache.struts.validator.util.StrutsValidatorUtil;
/**
* Custom tag that generates Javascript for client side validation based
* on the validation.xml file.
*
* @author David Winterfeldt
*/
public class JavascriptValidatorTag extends BodyTagSupport {
// ----------------------------------------------------------- Properties
/**
* The servlet context attribute key for our resources.
*/
protected String bundle = Action.MESSAGES_KEY;
/**
* The default locale on our server.
*/
protected static Locale defaultLocale = Locale.getDefault();
/**
* The name of the form that corresponds with the action name
* in struts-config.xml. This won't be needed if this is incorporated
* as an option in the html:form tag (ex: javascript="true").
*/
protected String formName = null;
/**
* The page number we are on in a multi-part form. This won't be needed
* if this is incorporated as an option in the html:form tag (should be able to be set
* or retrieved from scope).
*/
protected int page = 0;
/**
* This will be used as is for the Javascript validation method name if it has a value. This is
* the method name of the main Javascript method that the form calls to perform validations.
*/
protected String methodName = null;
/**
* The static JavaScript methods will only be printed if this is set to "true".
*/
protected String staticJavascript = "true";
/**
* The dynamic JavaScript objects will only be generated if this is set to "true".
*/
protected String dynamicJavascript = "true";
/**
* The src attribute for html script element (used to include an external script resource).
*/
protected String src = null;
public String getFormName() {
return formName;
}
public void setFormName(String formName) {
this.formName = formName;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public String getMethod() {
return methodName;
}
public void setMethod(String methodName) {
this.methodName = methodName;
}
public String getStaticJavascript() {
return staticJavascript;
}
public void setStaticJavascript(String staticJavascript) {
this.staticJavascript = staticJavascript;
}
public String getDynamicJavascript() {
return dynamicJavascript;
}
public void setDynamicJavascript(String dynamicJavascript) {
this.dynamicJavascript = dynamicJavascript;
}
public String getSrc() {
return src;
}
public void setSrc(String src) {
this.src = src;
}
/**
* Render the JavaScript for to perform validations based on the form name.
*
* @exception JspException if a JSP exception has occurred
*/
public int doStartTag() throws JspException {
StringBuffer results = new StringBuffer();
ValidatorResources resources = (ValidatorResources)
pageContext.getAttribute(ValidatorServlet.VALIDATOR_KEY, PageContext.APPLICATION_SCOPE);
Locale locale = null;
try {
locale = (Locale) pageContext.getAttribute(Action.LOCALE_KEY, PageContext.SESSION_SCOPE);
} catch (IllegalStateException e) { // Invalidated session
locale = null;
}
if (locale == null)
locale = defaultLocale;
Form form = null;
if ((form = resources.get(locale, formName)) != null && "true".equals(dynamicJavascript)) {
MessageResources messages = (MessageResources)
pageContext.getAttribute(bundle, PageContext.APPLICATION_SCOPE);
List lActions = new ArrayList();
List lActionMethods = new ArrayList();
// Get List of actions for this Form
for (Iterator i = form.getFields().iterator(); i.hasNext(); ) {
Field field = (Field)i.next();
for (Iterator x = field.getDependencies().iterator(); x.hasNext(); ) {
Object o = x.next();
if (o != null && !lActionMethods.contains(o))
lActionMethods.add(o);
}
}
// Create list of ValidatorActions based on lActionMethods
for (Iterator i = lActionMethods.iterator(); i.hasNext(); ) {
ValidatorAction va = resources.getValidatorAction((String)i.next());
String javascript = va.getJavascript();
if (javascript != null && javascript.length() > 0)
lActions.add(va);
else
i.remove();
}
Collections.sort(lActions, new Comparator() {
public int compare(Object o1, Object o2) {
ValidatorAction va1 = (ValidatorAction)o1;
ValidatorAction va2 = (ValidatorAction)o2;
if ((va1.getDepends() == null || va1.getDepends().length() == 0) &&
(va2.getDepends() == null || va2.getDepends().length() == 0)) {
return 0;
} else if ((va1.getDepends() != null && va1.getDepends().length() > 0) &&
(va2.getDepends() == null || va2.getDepends().length() == 0)) {
return 1;
} else if ((va1.getDepends() == null || va1.getDepends().length() == 0) &&
(va2.getDepends() != null && va2.getDepends().length() > 0)) {
return -1;
} else {
return va1.getDependencies().size() - va2.getDependencies().size();
}
}
});
String methods = null;
for (Iterator i = lActions.iterator(); i.hasNext(); ) {
ValidatorAction va = (ValidatorAction)i.next();
if (methods == null)
methods = va.getMethod() + "(form)";
else
methods += " && " + va.getMethod() + "(form)";
}
results.append(getJavascriptBegin(methods));
for (Iterator i = lActions.iterator(); i.hasNext(); ) {
ValidatorAction va = (ValidatorAction)i.next();
String jscriptVar = null;
String functionName = null;
if (va.getJsFunctionName() != null && va.getJsFunctionName().length() > 0)
functionName = va.getJsFunctionName();
else
functionName = va.getName();
results.append(" function " + functionName + " () { \n");
for (Iterator x = form.getFields().iterator(); x.hasNext(); ) {
Field field = (Field)x.next();
// Skip indexed fields for now until there is
// a good way to handle error messages (and the length of the list (could retrieve from scope?))
if (!field.isIndexed() && field.getPage() == page && field.isDependency(va.getName())) {
String message = StrutsValidatorUtil.getMessage(messages, locale, va, field);
message = (message != null ? message : "");
jscriptVar = getNextVar(jscriptVar);
results.append(" this." + jscriptVar + " = new Array(\"" + field.getKey() + "\", \"" + message + "\", ");
results.append("new Function (\"varName\", \"");
Map hVars = field.getVars();
// Loop through the field's variables.
for (Iterator iVars = hVars.keySet().iterator(); iVars.hasNext(); ) {
String varKey = (String)iVars.next();
Var var = (Var)hVars.get(varKey);
String varValue = var.getValue();
String jsType = var.getJsType();
if (Var.JSTYPE_INT.equalsIgnoreCase(jsType))
results.append("this." + varKey + "=" + ValidatorUtil.replace(varValue, "\\", "\\\\") + "; ");
else if (Var.JSTYPE_REGEXP.equalsIgnoreCase(jsType))
results.append("this." + varKey + "=/" + ValidatorUtil.replace(varValue, "\\", "\\\\") + "/; ");
else if (Var.JSTYPE_STRING.equalsIgnoreCase(jsType))
results.append("this." + varKey + "='" + ValidatorUtil.replace(varValue, "\\", "\\\\") + "'; ");
// So everyone using the latest format doesn't need to change their xml files immediately.
else if ("mask".equalsIgnoreCase(varKey))
results.append("this." + varKey + "=/" + ValidatorUtil.replace(varValue, "\\", "\\\\") + "/; ");
else
results.append("this." + varKey + "='" + ValidatorUtil.replace(varValue, "\\", "\\\\") + "'; ");
}
results.append(" return this[varName];\"));\n");
}
}
results.append(" } \n\n");
}
}
if ("true".equals(staticJavascript))
results.append(getJavascriptStaticMethods(resources));
if ("true".equals(dynamicJavascript))
results.append(getJavascriptEnd());
// Print this field to our output writer
JspWriter writer = pageContext.getOut();
try {
writer.print(results.toString());
} catch (IOException e) {
throw new JspException(e.getMessage());
//throw new JspException(messages.getMessage("common.io", e.toString()));
}
// Continue processing this page
return (EVAL_BODY_TAG);
}
/**
* Release any acquired resources.
*/
public void release() {
super.release();
bundle = Action.MESSAGES_KEY;
formName = null;
page = 0;
methodName = null;
staticJavascript = "true";
dynamicJavascript = "true";
src = null;
}
protected String getJavascriptBegin(String methods) {
StringBuffer sb = new StringBuffer();
String name = formName.substring(0, 1).toUpperCase() + formName.substring(1, formName.length());
if (src != null)
sb.append("<SCRIPT LANGUAGE=\"Javascript1.1\" src=\"" + src + "\"> \n");
else
sb.append("<SCRIPT LANGUAGE=\"Javascript1.1\"> \n");
sb.append("<!-- Begin \n");
sb.append("\n var bCancel = false; \n\n");
if (methodName == null || methodName.length() == 0)
sb.append(" function validate" + name + "(form) { \n");
else
sb.append(" function " + methodName + "(form) { \n");
sb.append(" if (bCancel) \n");
sb.append(" return true; \n");
sb.append(" else \n");
// Always return true if there aren't any Javascript validation methods
if (methods == null || methods.length() == 0)
sb.append(" return true; \n");
else
sb.append(" return " + methods + "; \n");
sb.append(" } \n\n");
return sb.toString();
}
protected String getJavascriptStaticMethods(ValidatorResources resources) {
StringBuffer sb = new StringBuffer();
sb.append("\n\n");
for (Iterator i = resources.getValidatorActions().values().iterator(); i.hasNext(); ) {
ValidatorAction va = (ValidatorAction)i.next();
if (va != null) {
String javascript = va.getJavascript();
if (javascript != null && javascript.length() > 0)
sb.append(javascript + "\n");
}
}
return sb.toString();
}
protected String getJavascriptEnd() {
StringBuffer sb = new StringBuffer();
sb.append("\n");
sb.append("// End -->\n");
sb.append("</SCRIPT>\n\n");
return sb.toString();
}
/**
* The value <code>null</code> will be returned at the end of the sequence.
* ex: "zz" will return <code>null</code>
*/
private String getNextVar(String input) {
if (input == null)
return "aa";
input = input.toLowerCase();
for (int i = input.length(); i > 0; i--) {
int pos = i - 1;
char c = input.charAt(pos);
c++;
if (c <= 'z') {
if (i == 0)
return c + input.substring(pos, input.length());
else if (i == input.length())
return input.substring(0, pos) + c;
else
return input.substring(0, pos) + c + input.substring(pos, input.length() - 1);
} else {
input = replaceChar(input, pos, 'a');
}
}
return null;
}
/**
* Replaces a single character in a <code>String</code>
*/
private String replaceChar(String input, int pos, char c) {
if (pos == 0)
return c + input.substring(pos, input.length());
else if (pos == input.length())
return input.substring(0, pos) + c;
else
return input.substring(0, pos) + c + input.substring(pos, input.length() - 1);
}
}
1.1 jakarta-struts/contrib/validator/src/share/org/apache/struts/validator/util/StrutsValidator.java
Index: StrutsValidator.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Struts", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.struts.validator.util;
import java.io.Serializable;
import java.util.Locale;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.regexp.RESyntaxException;
import org.apache.commons.validator.Field;
import org.apache.commons.validator.GenericValidator;
import org.apache.commons.validator.ValidatorAction;
import org.apache.commons.validator.ValidatorUtil;
/**
* <p>This class performs validations. The methods are can be configured to be
* used in the framework in the validation.xml file. (See example webapp)</p>
*
* @author David Winterfeldt
*/
public class StrutsValidator implements Serializable {
/**
* <p>Checks if the field isn't null and length of the field is greater than zero not
* including whitespace.</p>
*
* @param bean The bean validation is being performed on.
* @param va The <code>ValidatorAction</code> that is currently being performed.
* @param field The <code>Field</code> object associated with the current field
* being validated.
* @param errors The <code>ActionErrors</code> object to add errors to if any
* validation errors occur.
* @param request Current request object.
* @param application The application's <code>ServletContext</code>.
*/
public static boolean validateRequired(Object bean,
ValidatorAction va, Field field,
ActionErrors errors,
HttpServletRequest request, ServletContext application) {
String value = null;
if (field.getProperty() != null && field.getProperty().length() > 0)
value = ValidatorUtil.getValueAsString(bean, field.getProperty());
if (GenericValidator.isBlankOrNull(value)) {
errors.add(field.getKey(), StrutsValidatorUtil.getActionError(application, request, va, field));
return false;
} else {
return true;
}
}
/**
* <p>Checks if the field matches the regular expression in the field's mask attribute.</p>
*
* @param bean The bean validation is being performed on.
* @param va The <code>ValidatorAction</code> that is currently being performed.
* @param field The <code>Field</code> object associated with the current field
* being validated.
* @param errors The <code>ActionErrors</code> object to add errors to if any
* validation errors occur.
* @param request Current request object.
* @param application The application's <code>ServletContext</code>.
*/
public static boolean validateMask(Object bean,
ValidatorAction va, Field field,
ActionErrors errors,
HttpServletRequest request, ServletContext application) {
String mask = field.getVarValue("mask");
if (field.getProperty() != null && field.getProperty().length() > 0) {
String value = ValidatorUtil.getValueAsString(bean, field.getProperty());
try {
if (!GenericValidator.isBlankOrNull(value) && !GenericValidator.matchRegexp(value, mask)) {
errors.add(field.getKey(), StrutsValidatorUtil.getActionError(application, request, va, field));
return false;
} else {
return true;
}
} catch (RESyntaxException e) {
StrutsValidatorUtil.log(application, "Validator::validateMask() - " + e.getMessage(), e);
} catch (Exception e) {
StrutsValidatorUtil.log(application, "Validator::validateMask() - " + e.getMessage(), e);
}
}
return true;
}
/**
* <p>Checks if the field can safely be converted to a byte primitive.</p>
*
* @param bean The bean validation is being performed on.
* @param va The <code>ValidatorAction</code> that is currently being performed.
* @param field The <code>Field</code> object associated with the current field
* being validated.
* @param errors The <code>ActionErrors</code> object to add errors to if any
* validation errors occur.
* @param request Current request object.
* @param application The application's <code>ServletContext</code>.
*/
public static boolean validateByte(Object bean,
ValidatorAction va, Field field,
ActionErrors errors,
HttpServletRequest request, ServletContext application) {
String value = ValidatorUtil.getValueAsString(bean, field.getProperty());
if (!GenericValidator.isBlankOrNull(value) && !GenericValidator.isByte(value)) {
errors.add(field.getKey(), StrutsValidatorUtil.getActionError(application, request, va, field));
return false;
} else {
return true;
}
}
/**
* <p>Checks if the field can safely be converted to a short primitive.</p>
*
* @param bean The bean validation is being performed on.
* @param va The <code>ValidatorAction</code> that is currently being performed.
* @param field The <code>Field</code> object associated with the current field
* being validated.
* @param errors The <code>ActionErrors</code> object to add errors to if any
* validation errors occur.
* @param request Current request object.
* @param application The application's <code>ServletContext</code>.
*/
public static boolean validateShort(Object bean,
ValidatorAction va, Field field,
ActionErrors errors,
HttpServletRequest request, ServletContext application) {
String value = ValidatorUtil.getValueAsString(bean, field.getProperty());
if (!GenericValidator.isBlankOrNull(value) && !GenericValidator.isShort(value)) {
errors.add(field.getKey(), StrutsValidatorUtil.getActionError(application, request, va, field));
return false;
} else {
return true;
}
}
/**
* <p>Checks if the field can safely be converted to an int primitive.</p>
*
* @param bean The bean validation is being performed on.
* @param va The <code>ValidatorAction</code> that is currently being performed.
* @param field The <code>Field</code> object associated with the current field
* being validated.
* @param errors The <code>ActionErrors</code> object to add errors to if any
* validation errors occur.
* @param request Current request object.
* @param application The application's <code>ServletContext</code>.
*/
public static boolean validateInteger(Object bean,
ValidatorAction va, Field field,
ActionErrors errors,
HttpServletRequest request, ServletContext application) {
String value = ValidatorUtil.getValueAsString(bean, field.getProperty());
if (!GenericValidator.isBlankOrNull(value) && !GenericValidator.isInt(value)) {
errors.add(field.getKey(), StrutsValidatorUtil.getActionError(application, request, va, field));
return false;
} else {
return true;
}
}
/**
* <p>Checks if the field can safely be converted to a long primitive.</p>
*
* @param bean The bean validation is being performed on.
* @param va The <code>ValidatorAction</code> that is currently being performed.
* @param field The <code>Field</code> object associated with the current field
* being validated.
* @param errors The <code>ActionErrors</code> object to add errors to if any
* validation errors occur.
* @param request Current request object.
* @param application The application's <code>ServletContext</code>.
*/
public static boolean validateLong(Object bean,
ValidatorAction va, Field field,
ActionErrors errors,
HttpServletRequest request, ServletContext application) {
String value = ValidatorUtil.getValueAsString(bean, field.getProperty());
if (!GenericValidator.isBlankOrNull(value) && !GenericValidator.isLong(value)) {
errors.add(field.getKey(), StrutsValidatorUtil.getActionError(application, request, va, field));
return false;
} else {
return true;
}
}
/**
* <p>Checks if the field can safely be converted to a float primitive.</p>
*
* @param bean The bean validation is being performed on.
* @param va The <code>ValidatorAction</code> that is currently being performed.
* @param field The <code>Field</code> object associated with the current field
* being validated.
* @param errors The <code>ActionErrors</code> object to add errors to if any
* validation errors occur.
* @param request Current request object.
* @param application The application's <code>ServletContext</code>.
*/
public static boolean validateFloat(Object bean,
ValidatorAction va, Field field,
ActionErrors errors,
HttpServletRequest request, ServletContext application) {
String value = ValidatorUtil.getValueAsString(bean, field.getProperty());
if (!GenericValidator.isBlankOrNull(value) && !GenericValidator.isFloat(value)) {
errors.add(field.getKey(), StrutsValidatorUtil.getActionError(application, request, va, field));
return false;
} else {
return true;
}
}
/**
* <p>Checks if the field can safely be converted to a double primitive.</p>
*
* @param bean The bean validation is being performed on.
* @param va The <code>ValidatorAction</code> that is currently being performed.
* @param field The <code>Field</code> object associated with the current field
* being validated.
* @param errors The <code>ActionErrors</code> object to add errors to if any
* validation errors occur.
* @param request Current request object.
* @param application The application's <code>ServletContext</code>.
*/
public static boolean validateDouble(Object bean,
ValidatorAction va, Field field,
ActionErrors errors,
HttpServletRequest request, ServletContext application) {
String value = ValidatorUtil.getValueAsString(bean, field.getProperty());
if (!GenericValidator.isBlankOrNull(value) && !GenericValidator.isDouble(value)) {
errors.add(field.getKey(), StrutsValidatorUtil.getActionError(application, request, va, field));
return false;
} else {
return true;
}
}
/**
* <p>Checks if the field is a valid date. If the field has a datePattern variable,
* that will be used to format <code>java.text.SimpleDateFormat</code>. If the field
* has a datePatternStrict variable, that will be used to format
* <code>java.text.SimpleDateFormat</code> and the length will be checked so '2/12/1999'
* will not pass validation with the format 'MM/dd/yyyy' because the month isn't two digits.
* If no datePattern variable is specified, then the field gets the DateFormat.SHORT
* format for the locale. The setLenient method is set to <code>false</code> for all
* variations.</p>
*
* @param bean The bean validation is being performed on.
* @param va The <code>ValidatorAction</code> that is currently being performed.
* @param field The <code>Field</code> object associated with the current field
* being validated.
* @param errors The <code>ActionErrors</code> object to add errors to if any
* validation errors occur.
* @param request Current request object.
* @param application The application's <code>ServletContext</code>.
*/
public static boolean validateDate(Object bean,
ValidatorAction va, Field field,
ActionErrors errors,
HttpServletRequest request, ServletContext application) {
boolean bValid = true;
String value = ValidatorUtil.getValueAsString(bean, field.getProperty());
String datePattern = field.getVarValue("datePattern");
String datePatternStrict = field.getVarValue("datePatternStrict");
Locale locale = StrutsValidatorUtil.getLocale(request);
if (!GenericValidator.isBlankOrNull(value)) {
try {
if (datePattern != null && datePattern.length() > 0) {
bValid = GenericValidator.isDate(value, datePattern, false);
} else if (datePatternStrict != null && datePatternStrict.length() > 0) {
bValid = GenericValidator.isDate(value, datePatternStrict, true);
} else {
bValid = GenericValidator.isDate(value, locale);
}
} catch (Exception e) {
bValid = false;
}
}
if (!bValid)
errors.add(field.getKey(), StrutsValidatorUtil.getActionError(application, request, va, field));
return bValid;
}
/**
* <p>Checks if a fields value is within a range (min & max specified
* in the vars attribute).</p>
*
* @param bean The bean validation is being performed on.
* @param va The <code>ValidatorAction</code> that is currently being performed.
* @param field The <code>Field</code> object associated with the current field
* being validated.
* @param errors The <code>ActionErrors</code> object to add errors to if any
* validation errors occur.
* @param request Current request object.
* @param application The application's <code>ServletContext</code>.
*/
public static boolean validateRange(Object bean,
ValidatorAction va, Field field,
ActionErrors errors,
HttpServletRequest request, ServletContext application) {
String value = ValidatorUtil.getValueAsString(bean, field.getProperty());
String sMin = field.getVarValue("min");
String sMax = field.getVarValue("max");
if (!GenericValidator.isBlankOrNull(value)) {
try {
int iValue = Integer.parseInt(value);
int min = Integer.parseInt(sMin);
int max = Integer.parseInt(sMax);
if (!GenericValidator.isInRange(iValue, min, max)) {
errors.add(field.getKey(), StrutsValidatorUtil.getActionError(application, request, va, field));
return false;
}
} catch (Exception e) {
errors.add(field.getKey(), StrutsValidatorUtil.getActionError(application, request, va, field));
return false;
}
}
return true;
}
/**
* <p>Checks if the field is a valid credit card number.</p>
* <p>Translated to Java by Ted Husted (<a href="mailto:husted@apache.org">husted@apache.org</a>).<br>
* Reference Sean M. Burke's script at http://www.ling.nwu.edu/~sburke/pub/luhn_lib.pl</p>
*
* @param bean The bean validation is being performed on.
* @param va The <code>ValidatorAction</code> that is currently being performed.
* @param field The <code>Field</code> object associated with the current field
* being validated.
* @param errors The <code>ActionErrors</code> object to add errors to if any
* validation errors occur.
* @param request Current request object.
* @param application The application's <code>ServletContext</code>.
*/
public static boolean validateCreditCard(Object bean,
ValidatorAction va, Field field,
ActionErrors errors,
HttpServletRequest request, ServletContext application) {
if (field.getProperty() != null && field.getProperty().length() > 0) {
String value = ValidatorUtil.getValueAsString(bean, field.getProperty());
if (!GenericValidator.isBlankOrNull(value) && !GenericValidator.isCreditCard(value)) {
errors.add(field.getKey(), StrutsValidatorUtil.getActionError(application, request, va, field));
return false;
} else {
return true;
}
} else {
return true;
}
}
/**
* <p>Checks if a field has a valid e-mail address.</p>
* <p>Based on a script by Sandeep V. Tamhankar (stamhankar@hotmail.com),
* http://javascript.internet.com</p>
*
* @param bean The bean validation is being performed on.
* @param va The <code>ValidatorAction</code> that is currently being performed.
* @param field The <code>Field</code> object associated with the current field
* being validated.
* @param errors The <code>ActionErrors</code> object to add errors to if any
* validation errors occur.
* @param request Current request object.
* @param application The application's <code>ServletContext</code>.
*/
public static boolean validateEmail(Object bean,
ValidatorAction va, Field field,
ActionErrors errors,
HttpServletRequest request, ServletContext application) {
String value = ValidatorUtil.getValueAsString(bean, field.getProperty());
if (!GenericValidator.isBlankOrNull(value) && !GenericValidator.isEmail(value)) {
errors.add(field.getKey(), StrutsValidatorUtil.getActionError(application, request, va, field));
return false;
} else {
return true;
}
}
/**
* <p>Checks if the field's length is less than or equal to the maximum value. A <code>Null</code>
* will be considered an error.</p>
*
* @param bean The bean validation is being performed on.
* @param va The <code>ValidatorAction</code> that is currently being performed.
* @param field The <code>Field</code> object associated with the current field
* being validated.
* @param errors The <code>ActionErrors</code> object to add errors to if any
* validation errors occur.
* @param request Current request object.
* @param application The application's <code>ServletContext</code>.
*/
public static boolean validateMaxLength(Object bean,
ValidatorAction va, Field field,
ActionErrors errors,
HttpServletRequest request, ServletContext application) {
String value = ValidatorUtil.getValueAsString(bean, field.getProperty());
String sMaxLength = field.getVarValue("maxlength");
if (value != null) {
try {
int max = Integer.parseInt(sMaxLength);
if (!GenericValidator.maxLength(value, max)) {
errors.add(field.getKey(), StrutsValidatorUtil.getActionError(application, request, va, field));
return false;
}
} catch (Exception e) {
errors.add(field.getKey(), StrutsValidatorUtil.getActionError(application, request, va, field));
return false;
}
}
return true;
}
/**
* <p>Checks if the field's length is greater than or equal to the minimum value.
* A <code>Null</code> will be considered an error.</p>
*
* @param bean The bean validation is being performed on.
* @param va The <code>ValidatorAction</code> that is currently being performed.
* @param field The <code>Field</code> object associated with the current field
* being validated.
* @param errors The <code>ActionErrors</code> object to add errors to if any
* validation errors occur.
* @param request Current request object.
* @param application The application's <code>ServletContext</code>.
*/
public static boolean validateMinLength(Object bean,
ValidatorAction va, Field field,
ActionErrors errors,
HttpServletRequest request, ServletContext application) {
String value = ValidatorUtil.getValueAsString(bean, field.getProperty());
String sMinLength = field.getVarValue("minlength");
if (value != null) {
try {
int min = Integer.parseInt(sMinLength);
if (!GenericValidator.minLength(value, min)) {
errors.add(field.getKey(), StrutsValidatorUtil.getActionError(application, request, va, field));
return false;
}
} catch (Exception e) {
errors.add(field.getKey(), StrutsValidatorUtil.getActionError(application, request, va, field));
return false;
}
}
return true;
}
}
1.1 jakarta-struts/contrib/validator/src/share/org/apache/struts/validator/util/StrutsValidatorUtil.java
Index: StrutsValidatorUtil.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Struts", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.struts.validator.util;
import java.util.Locale;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.util.MessageResources;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.validator.Arg;
import org.apache.commons.validator.Field;
import org.apache.commons.validator.ValidatorAction;
import org.apache.commons.validator.ValidatorResources;
import org.apache.commons.validator.ValidatorUtil;
import org.apache.struts.validator.action.ValidatorServlet;
/**
* <p>This class helps provides some useful methods for retrieving objects
* from different scopes of the application.</p>
*
* @author David Winterfeldt
*/
public class StrutsValidatorUtil {
private static Locale defaultLocale = Locale.getDefault();
/**
* Retrieve <code>ValidatorResources</code> for the application.
*/
public static ValidatorResources getValidatorResources(ServletContext application) {
return (ValidatorResources)application.getAttribute(ValidatorServlet.VALIDATOR_KEY);
}
/**
* Retrieve <code>MessageResources</code> for the application.
*/
public static MessageResources getMessageResources(ServletContext application) {
return (MessageResources)application.getAttribute(Action.MESSAGES_KEY);
}
/**
* Get the <code>Locale</code> of the current user.
*/
public static Locale getLocale(HttpServletRequest request) {
Locale locale = null;
try {
locale = (Locale) request.getSession().getAttribute(Action.LOCALE_KEY);
} catch (IllegalStateException e) { // Invalidated session
locale = null;
}
if (locale == null)
locale = defaultLocale;
return locale;
}
/**
* Gets the <code>Locale</code> sensitive value based on the key passed in.
*/
public static String getMessage(MessageResources messages, Locale locale, String key) {
String message = null;
if (messages != null)
message = messages.getMessage(locale, key);
if (message == null)
message = "";
return message;
}
/**
* Gets the <code>Locale</code> sensitive value based on the key passed in.
*/
public static String getMessage(ServletContext application, HttpServletRequest request, String key) {
MessageResources messages = getMessageResources(application);
return getMessage(messages, getLocale(request), key);
}
/**
* Gets the locale sensitive message based on the <code>ValidatorAction</code> message and the
* <code>Field</code>'s arg objects.
*/
public static String getMessage(MessageResources messages, Locale locale,
ValidatorAction va, Field field) {
String arg[] = getArgs(va.getName(), messages, locale, field);
String msg = (field.getMsg(va.getName()) != null ? field.getMsg(va.getName()) : va.getMsg());
return messages.getMessage(locale, msg, arg[0], arg[1], arg[2], arg[3]);
}
/**
* Gets the <code>ActionError</code> based on the <code>ValidatorAction</code> message and the
* <code>Field</code>'s arg objects.
*/
public static ActionError getActionError(ServletContext application, HttpServletRequest request,
ValidatorAction va, Field field) {
String arg[] = getArgs(va.getName(), getMessageResources(application), getLocale(request), field);
String msg = (field.getMsg(va.getName()) != null ? field.getMsg(va.getName()) : va.getMsg());
return new ActionError(msg, arg[0], arg[1], arg[2], arg[3]);
}
/**
* Gets the message arguments based on the current <code>ValidatorAction</code>
* and <code>Field</code>.
*/
public static String[] getArgs(String actionName, MessageResources messages,
Locale locale, Field field) {
Arg arg0 = field.getArg0(actionName);
Arg arg1 = field.getArg1(actionName);
Arg arg2 = field.getArg2(actionName);
Arg arg3 = field.getArg3(actionName);
String sArg0 = null;
String sArg1 = null;
String sArg2 = null;
String sArg3 = null;
if (arg0 != null) {
if ("true".equals(arg0.getResource()))
sArg0 = getMessage(messages, locale, arg0.getKey());
else
sArg0 = arg0.getKey();
}
if (arg1 != null) {
if ("true".equals(arg1.getResource()))
sArg1 = getMessage(messages, locale, arg1.getKey());
else
sArg1 = arg1.getKey();
}
if (arg2 != null) {
if ("true".equals(arg2.getResource()))
sArg2 = getMessage(messages, locale, arg2.getKey());
else
sArg2 = arg2.getKey();
}
if (arg3 != null) {
if ("true".equals(arg3.getResource()))
sArg3 = getMessage(messages, locale, arg3.getKey());
else
sArg3 = arg3.getKey();
}
return new String[] { sArg0, sArg1, sArg2, sArg3 };
}
/**
* Writes a message based on the <code>Writer</code> defined in <code>MessageResources</code>.
*/
public static void log(ServletContext application, String message) {
MessageResources messages = getMessageResources(application);
if (messages != null)
messages.log(message);
}
/**
* Writes a message based on the <code>Writer</code> defined in <code>MessageResources</code>.
*/
public static void log(ServletContext application, String message, Throwable t) {
MessageResources messages = getMessageResources(application);
if (messages != null)
messages.log(message, t);
}
}
--
To unsubscribe, e-mail: <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>